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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3221b1c33d92b8f77b8314f307499e86a53ad743 | C++ | coderodde/Circuitspp | /net/coderodde/circuits/components/AbstractDoubleInputPinCircuitComponent.hpp | UTF-8 | 1,828 | 2.625 | 3 | [] | no_license | #ifndef NET_CODERODDE_CIRCUITS_ABSTRACT_DOUBLE_INPUT_PIN_CIRCUIT_COMPONENT_HPP
#define NET_CODERODDE_CIRCUITS_ABSTRACT_DOUBLE_INPUT_PIN_CIRCUIT_COMPONENT_HPP
#include "AbstractCircuitComponent.hpp"
#include <string>
#include <utility>
namespace net {
namespace coderodde {
namespace circuits {
class AbstractDoubleInputPinCircuitComponent :
public AbstractCircuitComponent {
protected:
AbstractCircuitComponent* m_input1;
AbstractCircuitComponent* m_input2;
public:
AbstractDoubleInputPinCircuitComponent(const std::string& name) :
AbstractCircuitComponent{name},
m_input1{nullptr},
m_input2{nullptr} {}
AbstractCircuitComponent* getInputComponent1() { return m_input1; }
AbstractCircuitComponent* getInputComponent2() { return m_input2; }
void setInputComponent1(AbstractCircuitComponent* input) {
m_input1 = input;
}
void setInputComponent2(AbstractCircuitComponent* input) {
m_input2 = input;
}
std::vector<AbstractCircuitComponent*> getInputComponents() const {
std::vector<AbstractCircuitComponent*> input_components = {
m_input1, m_input2
};
return input_components;
}
std::vector<AbstractCircuitComponent*> getOutputComponents() const {
std::vector<AbstractCircuitComponent*> output_components = {
m_output
};
return output_components;
}
};
} // End of namespace net::coderodde::circuits.
} // End of namespace net::coderodde.
} // End of namespace net.
#endif // NET_CODERODDE_CIRCUITS_ABSTRACT_DOUBLE_INPUT_PIN_CIRCUIT_COMPONENT_HPP
| true |
bf7a6f245df0368bc6b616053b62eb71e1edcad3 | C++ | MiguelAngelGC/c | /CAPITULO 2-3/CODIGO 4.cpp | UTF-8 | 702 | 3.3125 | 3 | [] | no_license | #include<stdio.h>
int main (){
int a,b,c,suma,promedio,producto;
printf ("Introduzca 3 numeros enteros\n");
scanf ("%d,%d,%d",&a,&b,&c);
suma= a+b+c;
promedio=(a+b+c)/3;
producto= a*b*c;
printf ("\nla suma es %d\n",suma);
printf ("el promedio es %d\n",promedio);
printf ("el producto es %d\n",producto);
if (b,c<a)
printf ("el numero mas grande es %d\n",a );
else if (b,a<c) printf ("el numero mas grande es %d\n",c);
else if (a,c<b) printf ("el numero mas grande es %d\n",b);
if (a<b,c)
printf ("el numero mas chico es %d\n",a);
else if (b<a,c) printf ("el numero mas chico es %d\n",b);
else if (c<a,b) printf ("el numero mas chico es %d\n",c);
return 0;
}
| true |
2c13f7982c446937a649929927ae7f22c3e88932 | C++ | jiadaizhao/LeetCode | /0801-0900/0850-Rectangle Area II/0850-Rectangle Area II.cpp | UTF-8 | 2,092 | 2.765625 | 3 | [
"MIT"
] | permissive | int MOD = 1000000007;
class Node {
public:
int start, end;
Node *left, *right;
int count;
long long total;
Node(int start, int end) {
this->start = start;
this->end = end;
left = right = nullptr;
count = total = 0;
}
Node* getLeft() {
if (left == nullptr) {
left = new Node(start, (start + end) / 2);
}
return left;
}
Node* getRight() {
if (right == nullptr) {
right = new Node((start + end) / 2, end);
}
return right;
}
long long update(int i, int j, int val, vector<int>& X) {
if (i >= j) return 0;
if (start == i && end == j) {
count += val;
}
else {
int mid = (start + end) / 2;
getLeft()->update(i, min(mid, j), val, X);
getRight()->update(max(mid, i), j, val, X);
}
if (count > 0) {
total = X[end] - X[start];
}
else {
total = getLeft()->total + getRight()->total;
}
return total;
}
};
class Solution {
public:
int rectangleArea(vector<vector<int>>& rectangles) {
set<int> xs;
vector<vector<int>> edges;
for (auto rec : rectangles) {
xs.insert(rec[0]);
xs.insert(rec[2]);
edges.push_back({rec[1], 1, rec[0], rec[2]});
edges.push_back({rec[3], -1, rec[0], rec[2]});
}
sort(edges.begin(), edges.end());
vector<int> X(xs.begin(), xs.end());
unordered_map<int, int> table;
int index = 0;
for (int x : xs) {
table[x] = index++;
}
long long currY = edges[0][0], currXSum = 0, area = 0;
Node* root = new Node(0, X.size() - 1);
for (auto edge : edges) {
int y = edge[0], type = edge[1], x1 = edge[2], x2 = edge[3];
area += currXSum * (y - currY);
currXSum = root->update(table[x1], table[x2], type, X);
currY = y;
}
return area % MOD;
}
};
| true |
d88c925d4456d5815e34c93cc32ff1cc3f72fc56 | C++ | streamchenao/Protobuf----RPC | /test/testRpcServer.cpp | GB18030 | 2,248 | 2.984375 | 3 | [] | no_license | #include "rpcserver.h"
#include "service.pb.h"
//Dz࣬дĿܵ÷ʾ
class UserService :public UserServiceRpc
{
public:
//ΪLService麯,ڵǰд
void login(::google::protobuf::RpcController* controller,
const ::LoginRequest* request,
::LoginResponse* response,
::google::protobuf::Closure* done)
{
// Ҫloginдеñطķ
// ruquestRPCнͻ˴ݵIJ
// responseҪõġloginķֵдresponse
// doneRPCעĻص
string name = request->name();
string pwd = request->pwd();
string login_response = login(name, pwd);
response->set_isloginsuccess(login_response);// ҵloginķֵдresponse
done->Run(); // RPCעĻص(صRPCԷֵδ)
}
void reg(::google::protobuf::RpcController* controller,
const ::RegRequest* request,
::RegResponse* response,
::google::protobuf::Closure* done)
{
// ͬlogin
int id = request->id();
string name = request->name();
string pwd = request->pwd();
string regis_response = regist(id, name, pwd);
response->set_isregsuccess(regis_response);
done->Run();
}
private:
// ԭȱصķ Ҫ䷢rpcҪڿܵrpcserverעһ
string login(string name, string pwd)
{
string result = "Login sucess";
cout << "call UserService::login->";
cout << "name:" << name << " ";
cout << "pwd:" << pwd << endl;
return "Login success";
}
string regist(int id, string name, string pwd)
{
cout << "call UserService::reg->";
cout << "id:" << id << " ";
cout << "name:" << name << " ";
cout << "password:" << pwd << endl;
return "Register success";
}
};
int main()
{
RpcServer* rs_ptr = RpcServer::getInstance(); //ûʹʱȻȡһrpcserverʵrpcserverĴϸڲҪû֪
rs_ptr->registerService
(new UserService());
rs_ptr->run();//עrpcserverվ
return 0;
} | true |
965f717572923994862a4f51b9950c3d79ec00c5 | C++ | msk4862/DS-Algo | /Practice/DP/2_LCSProbs/4_cvtAtoB.cpp | UTF-8 | 1,214 | 3.296875 | 3 | [] | no_license | // https://www.geeksforgeeks.org/minimum-number-deletions-insertions-transform-one-string-another/
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define FASTIO \
ios_base::sync_with_stdio(false); \
cin.tie(nullptr); \
cout.tie(nullptr);
int lcs(string s1, string s2) {
int n1 = s1.size(), n2 = s2.size();
int dp[n1+1][n2+1];
for (int i = 0; i <= n1; ++i) {
for (int j = 0; j <= n2; ++j) {
if(i == 0 || j == 0) dp[i][j] = 0;
else if(s1[i-1] == s2[j-1]) dp[i][j] = dp[i-1][j-1]+1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[n1][n2];
}
int min_oprs(string initial, string target) {
int lcs_length = lcs(initial, target);
int min_oprs_required = 0;
// delete operaions required = initial string - common string subsequence part
min_oprs_required += initial.size() - lcs_length;
// insert operaions required = target string - common string subsequence part
min_oprs_required += target.size() - lcs_length;
return min_oprs_required;
}
int main() {
string initial, target;
cin>>initial>>target;
cout<<min_oprs(initial, target);
return 0;
} | true |
c32b971b8c4953f6856ebf50fa2a76d876caaa56 | C++ | feifeipan123/chessBY | /board.cpp | UTF-8 | 11,304 | 2.65625 | 3 | [] | no_license | #include "board.h"
#include <QPainter>
#include <QMouseEvent>
#include <QDebug>
#define GetRowCol(__row, __col, __id) \
int __row = _s[__id]._row;\
int __col = _s[__id]._col
Board::Board(QWidget *parent) : QWidget(parent),_selectid(-1)
{
this->_r = 20;
setMinimumSize(_r*18+20, _r*20+20);
init(true);
}
bool Board::isBottomSide(int id)
{
return _bSide == _s[id]._red;
}
int Board::getStoneCountAtLine(int row1, int col1, int row2, int col2)
{
int ret = 0;
if(row1 != row2 && col1 != col2)
return -1;
if(row1 == row2 && col1 == col2)
return -1;
if(row1 == row2)
{
int min = col1 < col2 ? col1 : col2;
int max = col1 < col2 ? col2 : col1;
for(int col = min+1; col<max; ++col)
{
if(getStoneId(row1, col) != -1) ++ret;
}
}
else
{
int min = row1 < row2 ? row1 : row2;
int max = row1 < row2 ? row2 : row1;
for(int row = min+1; row<max; ++row)
{
if(getStoneId(row, col1) != -1) ++ret;
}
}
return ret;
}
void Board::init(bool bRedSide)
{
for(int i=0; i<32; ++i)
{
_s[i].init(i);
}
if(bRedSide)
{
for(int i=0; i<32; ++i)
{
_s[i].rotate();
}
}
_selectid = -1;
_bRedTurn = true;
_bSide = bRedSide;
update();
}
void Board::paintEvent(QPaintEvent *){
QPainter painter(this);
int d=40;
_r = d/2;
//画10条横线
for(int i=1;i<=10;++i){
painter.drawLine(QPoint(d,i*d),QPoint(9*d,i*d));
}
//画9条竖线
for(int i=1;i<=9;++i){
if(i==1 || i==9)
painter.drawLine(QPoint(i*d,d),QPoint(i*d,10*d));
else{
painter.drawLine(QPoint(i*d,d),QPoint(i*d,5*d));
painter.drawLine(QPoint(i*d,6*d),QPoint(i*d,10*d));
}
}
//九宫格
painter.drawLine(QPoint(4*d,d),QPoint(6*d,3*d));
painter.drawLine(QPoint(4*d,3*d),QPoint(6*d,d));
painter.drawLine(QPoint(4*d,8*d),QPoint(6*d,10*d));
painter.drawLine(QPoint(4*d,10*d),QPoint(6*d,8*d));
//绘制32个棋子
for(int i=0;i<32;++i){
drawStone(painter,i);
}
}
QPoint Board::center(int row,int col){
QPoint ret;
ret.rx()=2*_r*(col+1);
ret.ry()=2*_r*(row+1);
return ret;
}
QPoint Board::center(int id){
return center(_s[id]._row,_s[id]._col);
}
bool Board::isDead(int id)
{
if(id == -1)return true;
return _s[id]._dead;
}
void Board::drawStone(QPainter& painter,int id){
if(isDead(id))return;
QPoint c = center(id);
QRect rect = QRect(c.x()-_r,c.y()-_r,_r*2,_r*2);
QColor color;
if(red(id))color=Qt::red;
else color=Qt::black;
painter.setPen(QPen(QBrush(color),2));
if(id==_selectid){
painter.setBrush(QBrush(Qt::gray));
}else{
painter.setBrush(QBrush(Qt::yellow));
}
painter.drawEllipse(c,_r,_r);
painter.setFont(QFont("system",_r*1.2,700));
painter.drawText(rect,_s[id].getText(),QTextOption(Qt::AlignCenter));
}
bool Board::getRowCol(QPoint pt,int &row,int &col){
for(row=0;row<=9;row++){
for(col=0;col<=8;col++){
QPoint c=center(row,col);
int dx=abs(c.x()-pt.x());
int dy=abs(c.y()-pt.y());
int dist = dx*dx+dy*dy;
if(dist<_r*_r){
return true;
}
}
}
return false;
}
//根据行列值获取棋子id
int Board::getStoneId(int row, int col)
{
for(int i=0; i<32; ++i)
{
if(_s[i]._row == row && _s[i]._col == col && !isDead(i))
return i;
}
return -1;
}
int Board::relation(int row1, int col1, int row, int col)
{
return qAbs(row1-row)*10+qAbs(col1-col);
}
//将的走棋规则
bool Board::canMoveJiang(int moveid,int row,int col,int){
/*
* 1.位置在九宫格之内
* 2.移动步长是一个格子
*/
GetRowCol(row1, col1, moveid);
int r = relation(row1, col1, row, col);
//只能走一格
if(r != 1 && r != 10){
return false;
}
//列不分红黑棋子
if(col < 3 || col > 5) return false;
//行分红黑
if(isBottomSide(moveid))
{
if(row < 7) return false;
}
else
{
if(row > 2) return false;
}
return true;
}
//士的走棋规则
bool Board::canMoveShi(int moveid,int row,int col,int killid){
/*
* 1.位置在九宫格之内
* 2.移动步长是一个格子
*/
GetRowCol(row1, col1, moveid);
int r = relation(row1, col1, row, col);
if(r != 11) return false;
if(col < 3 || col > 5) return false;
if(isBottomSide(moveid))
{
if(row < 7) return false;
}
else
{
if(row > 2) return false;
}
return true;
}
bool Board::canMoveXiang(int moveid,int row,int col,int killid){
GetRowCol(row1, col1, moveid);
int r = relation(row1, col1, row, col);
if(r != 22) return false;
int rEye = (row+row1)/2;
int cEye = (col+col1)/2;
if(getStoneId(rEye, cEye) != -1)//象眼位置不能有棋子
return false;
if(isBottomSide(moveid))
{
if(row < 4) return false;
}
else
{
if(row > 5) return false;
}
return true;
}
bool Board::canMoveMa(int moveid,int row,int col,int)
{
GetRowCol(row1, col1, moveid);
int r = relation(row1, col1, row, col);
if(r != 12 && r != 21)
return false;
if(r == 12)
{
if(getStoneId(row1, (col+col1)/2) != -1)
return false;
}
else
{
if(getStoneId((row+row1)/2, col1) != -1)
return false;
}
return true;
}
bool Board::canMoveBing(int moveid, int row, int col, int)
{
GetRowCol(row1, col1, moveid);
int r = relation(row1, col1, row, col);
if(r != 1 && r != 10) return false;
if(isBottomSide(moveid))
{
if(row > row1) return false;
if(row1 >= 5 && row == row1) return false;
}
else
{
if(row < row1) return false;
if(row1 <= 4 && row == row1) return false;
}
return true;
}
bool Board::canMoveChe(int moveid,int row, int col,int)
{
GetRowCol(row1, col1, moveid);
int ret = getStoneCountAtLine(row1, col1, row, col);
if(ret == 0)
return true;
return false;
}
bool Board::canMovePao(int moveid,int row, int col,int killid)
{
GetRowCol(row1, col1, moveid);
int ret = getStoneCountAtLine(row, col, row1, col1);
if(killid != -1)
{
if(ret == 1) return true;
}
else
{
if(ret == 0) return true;
}
return false;
}
bool Board::canMove(int moveid,int row,int col,int killid){
//moveid和killid颜色相同
if(_s[moveid]._red==_s[killid]._red){
//换选择
_selectid = killid;
update();
return false;
}
switch(_s[moveid]._type){
case Stone::JIANG:
return canMoveJiang(moveid,row,col,killid);
break;
case Stone::SHI:
return canMoveShi(moveid,row,col,killid);
break;
case Stone::XIANG:
return canMoveXiang(moveid,row,col,killid);
break;
case Stone::CHE:
return canMoveChe(moveid,row,col,killid);
break;
case Stone::MA:
return canMoveMa(moveid,row,col,killid);
break;
case Stone::PAO:
return canMovePao(moveid,row,col,killid);
break;
case Stone::BING:
return canMoveBing(moveid,row,col,killid);
break;
}
}
void Board::reliveStone(int id)
{
if(id==-1) return;
_s[id]._dead = false;
}
void Board::killStone(int id)
{
if(id==-1) return;
_s[id]._dead = true;
}
bool Board::canSelect(int id)
{
return _bRedTurn == _s[id]._red;
}
void Board::saveStep(int moveid, int killid, int row, int col, QVector<Step*>& steps){
GetRowCol(row1, col1, moveid);
Step* step = new Step;
step->_colFrom = col1;
step->_colTo = col;
step->_rowFrom = row1;
step->_rowTo = row;
step->_moveid = moveid;
step->_killid = killid;
steps.append(step);
}
void Board::moveStone(int moveid, int row, int col)
{
_s[moveid]._row = row;
_s[moveid]._col = col;
_bRedTurn = !_bRedTurn;
}
void Board::moveStone(int moveid, int row, int col,int killid)
{
saveStep(moveid, killid, row, col, _steps);//保存走棋步骤
killStone(killid);
moveStone(moveid, row, col);
}
void Board::trySelectStone(int id)
{
if(id == -1)
return;
if(!canSelect(id)) return;
_selectid = id;
update();
}
bool Board::red(int id)
{
return _s[id]._red;
}
bool Board::sameColor(int id1, int id2)
{
if(id1 == -1 || id2 == -1) return false;
return red(id1) == red(id2);
}
void Board::tryMoveStone(int killid, int row, int col)
{
if(killid != -1 && sameColor(killid, _selectid))
{
trySelectStone(killid);
return;
}
bool ret = canMove(_selectid, row, col,killid);
if(ret)
{
moveStone(_selectid, row, col,killid);
_selectid = -1;
update();
}
}
void Board::click(int id, int row, int col)
{
if(this->_selectid == -1)
{
trySelectStone(id);
}
else
{
tryMoveStone(id, row, col);
}
}
bool Board::getClickRowCol(QPoint pt, int &row, int &col)
{
for(row=0; row<=9; ++row)
{
for(col=0; col<=8; ++col)
{
QPoint distance = center(row, col) - pt;
if(distance.x() * distance.x() + distance.y() * distance.y() < _r* _r)
return true;
}
}
return false;
}
void Board::click(QPoint pt)
{
int row, col;
bool bClicked = getClickRowCol(pt, row, col);
if(!bClicked) return;
int id = getStoneId(row, col);
click(id, row, col);
}
void Board::mouseReleaseEvent(QMouseEvent *ev){
if(ev->button() != Qt::LeftButton)
{
return;
}
click(ev->pos());
// QPoint pt=ev->pos();
// int row,col;
// bool bRet = getRowCol(pt,row,col);
// if(bRet == false)
// return;
// int i,clickid=-1;
// for(i=0;i<32;++i){
// if(_s[i]._row==row&&_s[i]._col==col&&_s[i]._dead==false){
// break;
// }
// }
// if(i<32){
// clickid=i;
// }
// if(_selectid==-1){//可以选择棋子了
// if(clickid!=-1){//能选中棋子
// if(_bRedTurn==_s[clickid]._red){//是红棋走
// _selectid = clickid;
// update();
// }
// }
// }else{//走棋
// if(canMove(_selectid,row,col,clickid)){
// _s[_selectid]._row=row;
// _s[_selectid]._col=col;
// if(clickid!=-1){
// _s[clickid]._dead=true;
// }
// _selectid = -1;
// _bRedTurn = !_bRedTurn;
// update();
// }
// }
}
void Board::back(Step *step)
{
reliveStone(step->_killid);
moveStone(step->_moveid, step->_rowFrom, step->_colFrom);
}
void Board::backOne()
{
if(this->_steps.size() == 0) return;
Step* step = this->_steps.last();
_steps.removeLast();
back(step);
update();
delete step;
}
void Board::back()
{
backOne();
}
void Board::slotBack()
{
back();
}
| true |
e1d02211bb2e0e4e77ec4c34b61007201aa555d7 | C++ | josuefdz10/Tarea-Corta-1 | /src/lista.cpp | UTF-8 | 9,468 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <string.h>
#include "lista.h"
#include <math.h>
using namespace std;
lista::~lista()
{
pnodo aux;
while(primero) {
aux = primero;
primero = primero->siguiente;
delete aux;
}
actual = NULL;
}
int lista::largoLista(){
int cont=0;
pnodo aux;
aux = primero;
if(ListaVacia()){
return cont;
}else{
while(aux!=NULL){
aux=aux->siguiente;
cont++;
}
return cont;
}
}
void lista::InsertarInicio(string v)
{
if (ListaVacia())
primero = new nodo(v);
else
primero=new nodo (v,primero);
}
void lista::InsertarFinal(string v)
{
if (ListaVacia())
primero = new nodo(v);
else
{ pnodo aux = primero;
while ( aux->siguiente != NULL)
aux= aux->siguiente;
aux->siguiente=new nodo(v);
}
}
void lista::InsertarPos(string v,int pos)
{
if (ListaVacia())
primero = new nodo(v);
else{
if(pos <=1){
pnodo nuevo = new nodo(v);
nuevo->siguiente= primero;
primero= nuevo;
}
else{
pnodo aux= primero;
int i =2;
while((i != pos )&&(aux->siguiente!= NULL)){
i++;
aux=aux->siguiente;
}
pnodo nuevo= new nodo(v);
nuevo->siguiente=aux->siguiente;
aux->siguiente=nuevo;
}
}
}
void lista::BorrarFinal()
{
if (ListaVacia()){
cout << "No hay elementos en la lista:" << endl;
}else{
if (primero->siguiente == NULL) {
pnodo temp = primero;
primero= NULL;
delete temp;
} else {
pnodo aux = primero;
while (aux->siguiente->siguiente != NULL) {
aux = aux->siguiente;
}
pnodo temp = aux->siguiente;
aux->siguiente= NULL;
delete temp;
}
}
}
void lista::BorrarInicio()
{
if (ListaVacia()){
cout << "No hay elementos en la lista:" << endl;
}else{
if (primero->siguiente == NULL) {
primero= NULL;
} else {
pnodo aux = primero;
primero=primero->siguiente;
delete aux;
}
}
}
void lista:: borrarPosicion(int pos){
if(ListaVacia()){
cout << "Lista vacia" <<endl;
}else{
if((pos>largoLista())||(pos<0)){
cout << "Error en posicion" << endl;
}else{
if(pos==1){
primero=primero->siguiente;
}else{
int cont=2;
pnodo aux= primero;
while(cont<pos){
aux=aux->siguiente;
cont++;
}
aux->siguiente=aux->siguiente->siguiente;
}
}
}
}
void lista::Imprimir()
{
nodo *aux;
aux = primero;
while(aux) {
cout << aux->valor << "-> ";
aux = aux->siguiente;
//hola
}
cout << endl;
}
void lista::Siguiente()
{
if(actual) actual = actual->siguiente;
}
void lista::Primero()
{
actual = primero;
}
int lista::operadorBinario(string caracter){
std::string str1 (caracter);
bool valor;
if ((str1.compare("+") == 0) || (str1.compare("-") == 0) ||(str1.compare("/") == 0)||(str1.compare("*") == 0)||
(str1.compare("^") == 0)|| (str1.compare("(") == 0) || (str1.compare(")") == 0))
valor = true;
//else if (strcmp(caracter, "0") == 0)
//valor = true;
else
valor = false;
return valor;
}
int lista::validacion(char *caracter){
bool valor = false;
char *finalPtr;
if (operadorBinario(caracter))
valor = true;
else if (strtod(caracter, &finalPtr) != 0)
valor = true;
else
valor = false;
return valor;
}
int lista::valorDentroPila(string caracter){
int valor = 0;
std::string str1 (caracter);
if (str1.compare("(") == 0)
valor = 0;
else if ((str1.compare("+") == 0) || (str1.compare("-")) == 0)
valor = 1;
else if (((str1.compare("*")) == 0) || (str1.compare("/") == 0))
valor = 2;
else if (str1.compare("^")== 0)
valor = 3;
return valor;
}
string lista::Ultimo(){
string elemento;
pnodo aux = primero;
while (aux != NULL){
elemento = aux -> valor;
aux = aux -> siguiente;
}
return elemento;
}
int lista::valorFueraPila(string caracter){
int valor = 0;
std::string str1 (caracter);
if (str1.compare("(") == 0)
valor = 5;
else if ((str1.compare("+") == 0) || (str1.compare("-") == 0))
valor = 1;
else if ((str1.compare("*") == 0) || (str1.compare("/") == 0))
valor = 2;
else if (str1.compare("^")== 0)
valor = 4;
return valor;
}
void lista::Leer() {
char nombreArchivo[50];
char caracter[100];
ifstream Archivo;
cin.getline(nombreArchivo, 50);
Archivo.open(nombreArchivo);
if (Archivo.is_open()) {
while (!Archivo.eof()) {
Archivo >> caracter;
if (validacion(caracter)){
//cout<<endl;
//cout<<caracter;
InsertarFinal(caracter);
//cout << "->";
//cout << valorFueraPila(caracter)<<endl;
}
else{
cout << "Ingrese caracteres validos para el programa."<< endl;
break;
}
}
}
Archivo.close();
}
string lista::multiplicar(char *numero1, char *numero2){
char *num1;
char *num2;
double a;
double b;
string conversion;
a = strtod(numero1, &num1);
b = strtod(numero2, &num2);
float result = a * b;
std::ostringstream ostr;
ostr << result;
conversion = ostr.str();
return conversion;
}
string lista::aplicarOperando(string numero1, string numero2,string caracter){
std::string str1 (numero1);
std::string str2 (numero2);
std::string operador (caracter);
double a = atoi(str1.c_str());
double b = atoi(str2.c_str());
float result;
string conversion;
if (operador.compare("+") == 0)
result = a + b;
else if (operador.compare("-") == 0)
result = a - b;
else if (operador.compare("*") == 0)
result = a * b;
else if (operador.compare("^") == 0)
result = powf(a, b);
else {
if (b == 0)
return "La operacion esta indefinida.";
else
result = a / b;
}
std::ostringstream ostr;
ostr << result;
conversion = ostr.str();
return conversion;
}
void lista::procesar() {
lista Pila, ExpPostFijo, listaNumeros;
pnodo aux = primero;
string temporal;
int eliminado = 0;
string numero1;
string numero2;
int posicion = 0;
// Transformacion de la expresion algebraica a expresion postfijo
while (aux != NULL){
if (Pila.ListaVacia())
Pila.InsertarFinal(aux -> valor);
else {
std::string str1 (aux -> valor);
if ((operadorBinario(aux -> valor))&&(str1.compare(")") != 0)){
if (valorFueraPila(aux -> valor) > valorDentroPila(Pila.Ultimo()))
Pila.InsertarFinal(aux -> valor);
else {
temporal = Pila.Ultimo();
Pila.BorrarFinal();
Pila.InsertarFinal(aux -> valor);
ExpPostFijo.InsertarFinal(temporal);
}
}
else if ((operadorBinario(aux -> valor))&&(str1.compare(")") == 0)) {
std::string ultimoPila (Pila.Ultimo());
while (eliminado != 1){
ExpPostFijo.InsertarFinal(Pila.Ultimo());
Pila.BorrarFinal();
std::string parada(Pila.Ultimo());
if (parada.compare("(") == 0)
eliminado += 1;
}
Pila.BorrarFinal();
eliminado = 0;
}
else
ExpPostFijo.InsertarFinal(aux -> valor);
}
aux = aux -> siguiente;
if (aux == NULL)
ExpPostFijo.InsertarFinal(Pila.Ultimo());
}
Pila.BorrarFinal(); // Elimina el ultimo nodo sobrante en la pila.
Pila.Imprimir(); // Para saber como quedo la pila despues de la expresion postfijo.
ExpPostFijo.Imprimir(); //Verficar visualmente la expresion postfijo.
// Realizacion de la Expresion Postfijo
pnodo aux2 = ExpPostFijo.primero;
while (aux2 != NULL){
if (posicion <=1){
numero1 = aux2 -> valor;
numero2 = aux2 -> siguiente -> valor;
aux2 = aux2 -> siguiente -> siguiente;
listaNumeros.InsertarFinal(aplicarOperando(numero1, numero2, aux2 -> valor));
aux2 = aux2 -> siguiente;
posicion += 3;
}
else if (posicion % 2 == 0){
listaNumeros.BorrarFinal();
listaNumeros.InsertarFinal(aplicarOperando(numero1, numero2, aux2 -> valor));
aux2 = aux2 -> siguiente;
posicion ++;
}
else{
numero1 = listaNumeros.Ultimo();
numero2 = aux2 -> valor;
aux2 = aux2 -> siguiente;
posicion ++;
}
}
listaNumeros.Imprimir();
}
| true |
0eab55f21f18e154f4cee44d4a1b36104d5f5d5f | C++ | nsweb/bigball | /engine/src/core/name.cpp | UTF-8 | 957 | 2.6875 | 3 | [
"MIT"
] | permissive |
#include "../bigball.h"
#include "name.h"
namespace bigball
{
NameManager* NameManager::m_pStaticInstance = nullptr;
NameManager::NameManager()
{
m_pStaticInstance = this;
}
NameManager::~NameManager()
{
m_pStaticInstance = nullptr;
}
NameHandle NameManager::FindOrAddHandle( String const& str )
{
const NameMap::Pair* NameEntry = m_StringTable.Add( str, m_StringTable.m_NbActivePairs );
return NameEntry->Value;
}
const String& NameManager::GetString( NameHandle Handle )
{
if( Handle < m_StringTable.m_NbActivePairs )
{
return m_StringTable.m_Pairs[Handle].Key;
}
return m_StringTable.m_Pairs[0].Key;
}
void NameManager::Init()
{
HashData::InitHashData();
m_StringTable.reserve( 4096 );
FindOrAddHandle( "None" );
}
NameManager* NameManager::GetStaticInstance()
{
if( !m_pStaticInstance )
{
m_pStaticInstance = new NameManager();
m_pStaticInstance->Init();
}
return m_pStaticInstance;
}
} /* namespace bigball */
| true |
27b94cba5a068c1a6f16444f6c57bf4f8577d316 | C++ | Giantpizzahead/comp-programming | /AtCoder/ABC 284/Fold.cpp | UTF-8 | 2,399 | 2.59375 | 3 | [] | no_license | /*
bandana
input: banANADNABdana (T)
reversed: anadBANDANAnab (U)
Search for string U in T, recording longest matching prefix at each index.
Search for string T in U, recording longest matching prefix at each index.
Then, combine this recorded arrays (reversing the one for U).
Iterate through each index to find one where the sum of the longest matches equals N.
*/
// ============================== BEGIN TEMPLATE ==============================
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define sz(x) ((int) x.size())
#define all(x) x.begin(), x.end()
#ifdef LOCAL
#include "pprint.hpp"
#else
#define debug(...) 42
#define dumpVars(...) 42
#endif
void solve();
int runTests(bool multiple_tests) {
ios::sync_with_stdio(0);
cin.tie(0);
if (multiple_tests) {
int T; cin >> T;
rep(i, 0, T) solve();
} else solve();
return 0;
}
// =============================== END TEMPLATE ===============================
vector<int> getLCP(string& S) {
vector<int> lcp(sz(S));
int currLoc = 0;
lcp[0] = 0;
rep(i, 1, sz(S)) {
while (currLoc != 0 && S[i] != S[currLoc]) {
currLoc = lcp[currLoc];
}
if (S[i] == S[currLoc]) currLoc++;
lcp[i] = currLoc;
}
return lcp;
}
vector<int> getKMP(string& S, string& T) {
// T is the pattern to search for
vector<int> lcp = getLCP(T);
dumpVars(lcp, S, T);
vector<int> kmp(sz(S));
int currLoc = 0;
rep(i, 0, sz(S)) {
while (currLoc != 0 && (currLoc == sz(T) || S[i] != T[currLoc])) {
currLoc = lcp[currLoc-1];
}
if (S[i] == T[currLoc]) currLoc++;
kmp[i] = currLoc;
}
return kmp;
}
void solve() {
int N; cin >> N;
string T; cin >> T;
string revT = T;
reverse(all(revT));
vector<int> kmp1 = getKMP(T, revT);
vector<int> kmp2 = getKMP(revT, T);
reverse(all(kmp2));
dumpVars(T, revT);
dumpVars(kmp1);
dumpVars(kmp2);
rep(i, 0, 2*N) {
if (kmp1[2*N-1] + kmp2[i] >= N) {
int ans = kmp2[i];
cout << T.substr(0, ans) << T.substr(2*N-(N-ans)) << "\n";
cout << ans << "\n";
return;
}
}
cout << -1 << "\n";
}
int main() {
bool multipleTests = false;
return runTests(multipleTests);
}
| true |
03e713934647cec7c5c98cfa67080247d9ea0192 | C++ | lizr2004/Coding | /rqnoj/202.cpp | UTF-8 | 409 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
int dp[205][205];
int N,O,n;
int x,y,z;
int minW=0x3f3f3f3f;
int main()
{
memset(dp,0x3f,sizeof(dp));
dp[0][0]=0;
cin>>O>>N>>n;
while(n--)
{
cin>>x>>y>>z;
for(int i=O;i>=0;i--)
for(int j=N;j>=0;j--)
{
int a=min(i+x,O),b=min(j+y,N);
dp[a][b]=min(dp[a][b],dp[i][j]+z);
}
}
cout<<dp[O][N]<<endl;
} | true |
e4a29ec392159baa37ec4ce0b55335d0a73590a7 | C++ | root-project/roottest | /root/io/newClassDef/new/InheritMulti.h | UTF-8 | 1,221 | 2.796875 | 3 | [] | no_license | #ifndef InheritMulti_H
#define InheritMulti_H
#include "TObject.h"
#include <stdio.h>
// Test for multi-inheritance objects.
class MyTop {
public:
int t;
MyTop() {};
MyTop(int it) : t(it) {};
virtual ~MyTop() {};
ClassDef(MyTop,1)
};
class MyMulti : public TObject, public MyTop {
public:
float m;
MyMulti() {};
MyMulti(int it, float im) : TObject(),MyTop(it),m(im) {};
virtual ~MyMulti() {};
ClassDef(MyMulti,1)
};
class MyInverseMulti : public MyTop, public TObject {
public:
int i;
MyInverseMulti() {};
MyInverseMulti(int it, int ii) : MyTop(it),TObject(),i(ii) {};
virtual ~MyInverseMulti() {};
ClassDef(MyInverseMulti,1)
};
class A : public TObject {
public:
int a;
A() {};
A(int ia) : a(ia) {};
virtual ~A() {};
ClassDef(A,1)
};
class B {
public:
B() : b(0), a(0) {};
B(int ia, float ib) : b(ib) { a = new A(ia); }
virtual ~B() {};
float b;
A *a;
void Dump() {
fprintf(stderr,"Printing object of type \"B\" at %p\n",this);
fprintf(stderr,"\tb = %f\n",b);
fprintf(stderr,"\ta = 0x%p\n",a);
if (a) fprintf(stderr,"\t\ta = %d\n",a->a);
}
ClassDef(B,1)
};
bool InheritMulti_driver();
#endif
| true |
a17a9d7d8be9ff5602dfdc6b70a46fb150aa93c7 | C++ | TangLingxiao/learn | /mess/Util/FileHelper.cpp | UTF-8 | 10,293 | 2.875 | 3 | [] | no_license | #include "FileHelper.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <stdexcept>
#include <unistd.h>
#ifndef BUILD_ON_MINGW
#include <pwd.h>
#else
#include <shlwapi.h>
#endif
#include <sys/stat.h>
#include <dirent.h>
#ifndef BUILD_ON_MINGW
#include <sys/wait.h>
#endif
string UtilFile::getHomeDir()
{
#ifndef BUILD_ON_MINGW
struct passwd *pw = getpwuid(getuid());
if (pw != NULL)
{
return pw->pw_dir;
}
return "";
#else
return "~";
#endif
}
string UtilFile::getCurrentDir()
{
char buf[PATH_MAX];
if (getcwd(buf, sizeof(buf)))
{
return buf;
}
return "";
}
static void splitString(const string &str, const string &sep, bool bStrip, vector<string> &vResult)
{
string::size_type p = 0, q = 0;
while (true)
{
q = str.find_first_of(sep, p);
if (q == string::npos)
{
if (!bStrip || p < str.size())
{
vResult.push_back(str.substr(p));
}
break;
}
if (q == p)
{
if (!bStrip)
{
vResult.push_back("");
}
}
else
{
vResult.push_back(str.substr(p, q - p));
p = q;
}
++p;
}
}
string UtilFile::getSimplifiedPath(const string &sPath)
{
if (sPath.empty())
{
return sPath;
}
#ifndef BUILD_ON_MINGW
vector<string> v;
splitString(sPath, "/", true, v);
vector<string*> vp;
for (unsigned i = 0; i < v.size(); ++i)
{
if (v[i] == "..")
{
if (!vp.empty())
{
vp.resize(vp.size() - 1);
}
}
else if (v[i] != ".")
{
vp.push_back(&v[i]);
}
}
string r;
if (sPath[0] == '/')
{
r.push_back('/');
}
for (unsigned i = 0; i < vp.size(); ++i)
{
if (i != 0)
{
r.push_back('/');
}
r.append(*vp[i]);
}
return r;
#else
char buf[MAX_PATH];
if (PathCanonicalize(buf, sPath.c_str()))
{
return buf;
}
return sPath;
#endif
}
string UtilFile::getAbsolutePath(const string &sPath, const string &sBasePath)
{
#ifndef BUILD_ON_MINGW
// absolute
if (!sPath.empty() && sPath[0] == '/')
{
return getSimplifiedPath(sPath);
}
if (!sPath.empty() && sPath[0] == '~' && (sPath.size() == 1 || sPath[1] == '/'))
{
return getSimplifiedPath(getHomeDir() + "/" + sPath.substr(1));
}
// relative
if (sBasePath.empty())
{
return getSimplifiedPath(getCurrentDir() + "/" + sPath);
}
if (sBasePath[0] == '/')
{
return getSimplifiedPath(sBasePath + "/" + sPath);
}
if (sBasePath[0] == '~' && (sBasePath.size() == 1 || sBasePath[1] == '/'))
{
return getSimplifiedPath(getHomeDir() + "/" + sBasePath.substr(1) + "/" + sPath);
}
return getSimplifiedPath(getCurrentDir() + "/" + sBasePath + "/" + sPath);
#else
string sPathWin = UtilString::replace(sPath, "/", "\\");
string sBasePathWin = UtilString::replace(sBasePath, "/", "\\");
// absolute
if (!PathIsRelative(sPathWin.c_str()))
{
return getSimplifiedPath(sPathWin);
}
// relative
if (sBasePathWin.empty())
{
return getSimplifiedPath(getCurrentDir() + "\\" + sPathWin);
}
if (!PathIsRelative(sBasePathWin.c_str()))
{
return getSimplifiedPath(sBasePathWin + "\\" + sPathWin);
}
return getSimplifiedPath(getCurrentDir() + "\\" + sBasePathWin + "\\" + sPathWin);
#endif
}
string UtilFile::getCanonicalPath(const string &sPath)
{
#ifndef BUILD_ON_MINGW
char buf[PATH_MAX];
if (realpath(sPath.c_str(), buf))
{
return buf;
}
return "";
#else
return getAbsolutePath(sPath);
#endif
}
string UtilFile::getFileBasename(const string &sPath)
{
#ifndef BUILD_ON_MINGW
if (sPath.empty())
{
return "";
}
string::size_type pos = sPath.size();
while (pos > 0 && sPath[pos - 1] == '/') --pos;
if (pos == 0)
{
return "/";
}
string::size_type end = pos;
while (pos > 0 && sPath[pos - 1] != '/') --pos;
return sPath.substr(pos, end - pos);
#else
char buf[MAX_PATH];
int n = sizeof(buf) > sPath.size() ? sPath.size() : sizeof(buf) - 1;
strncpy(buf, sPath.c_str(), n);
buf[n] = 0;
for (char *p = buf; *p; ++p)
{
if (*p == '/')
*p = '\\';
}
PathStripPath(buf);
return buf;
#endif
}
string UtilFile::getFileDirname(const string &sPath)
{
#ifndef BUILD_ON_MINGW
if (sPath.empty())
{
return ".";
}
string::size_type pos = sPath.size();
while (pos > 0 && sPath[pos - 1] == '/') --pos;
if (pos == 0)
{
return "/";
}
while (pos > 0 && sPath[pos - 1] != '/') --pos;
if (pos == 0)
{
return ".";
}
while (pos > 0 && sPath[pos - 1] == '/') --pos;
if (pos == 0)
{
return "/";
}
return sPath.substr(0, pos);
#else
char buf[MAX_PATH];
int n = sizeof(buf) > sPath.size() ? sPath.size() : sizeof(buf) - 1;
strncpy(buf, sPath.c_str(), n);
buf[n] = 0;
for (char *p = buf; *p; ++p)
{
if (*p == '/')
*p = '\\';
}
PathRemoveFileSpec(buf);
return buf;
#endif
}
string UtilFile::getFileExt(const string &sPath, bool bWithDot)
{
string::size_type pos = sPath.rfind('.');
if (pos == string::npos)
{
return "";
}
#ifndef BUILD_ON_MINGW
string::size_type pos1 = sPath.rfind('/');
#else
string::size_type pos1 = sPath.rfind('\\');
#endif
if (pos < pos1)
{
return "";
}
return sPath.substr(bWithDot ? pos : pos + 1);
}
string UtilFile::replaceFileExt(const string &sPath, const string &sReplace, bool bWithDot)
{
string::size_type pos = sPath.rfind('.');
if (pos == string::npos)
{
return sPath;
}
#ifndef BUILD_ON_MINGW
string::size_type pos1 = sPath.rfind('/');
#else
string::size_type pos1 = sPath.rfind('\\');
#endif
if (pos1 != string::npos && pos < pos1)
{
return sPath;
}
return sPath.substr(0, bWithDot ? pos : pos + 1) + sReplace;
}
string UtilFile::loadFromFile(const string &sFileName)
{
ifstream ifs(sFileName.c_str(), ios_base::in | ios_base::binary);
return string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>());
}
void UtilFile::saveToFile(const string &sFileName, const string &sContent)
{
ofstream ofs(sFileName.c_str(), ios_base::out | ios_base::binary);
ofs.write(sContent.c_str(), sContent.size());
}
bool UtilFile::removeFile(const string &sPath)
{
return remove(sPath.c_str()) == 0 ? true : false;
}
bool UtilFile::moveFile(const string &sPathFrom, const string &sPathTo)
{
return rename(sPathFrom.c_str(), sPathTo.c_str()) == 0 ? true : false;
}
bool UtilFile::makeDirectory(const string &sPath)
{
#ifndef BUILD_ON_MINGW
int ret = mkdir(sPath.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
#else
if (sPath.empty() || sPath[sPath.size() - 1] == ':' || isDirectoryExists(sPath))
{
return true;
}
int ret = mkdir(sPath.c_str());
#endif
if (ret == 0)
{
return true;
}
if (errno == EEXIST && isDirectoryExists(sPath))
{
return true;
}
return false;
}
bool UtilFile::makeDirectoryRecursive(const string &sPath)
{
string sAbsPath = getAbsolutePath(sPath);
string::size_type pos = 0;
while (true)
{
#ifndef BUILD_ON_MINGW
pos = sAbsPath.find('/', pos);
#else
pos = sAbsPath.find('\\', pos);
#endif
if (pos == string::npos)
{
return makeDirectory(sAbsPath);
}
else if (pos != 0)
{
string sSub = sAbsPath.substr(0, pos);
if (!makeDirectory(sSub))
{
return false;
}
}
++pos;
}
return false;
}
bool UtilFile::isFileExists(const string &sPath)
{
struct stat buf;
if (stat(sPath.c_str(), &buf) == 0 && S_ISREG(buf.st_mode))
{
return true;
}
return false;
}
bool UtilFile::isDirectoryExists(const string &sPath)
{
struct stat buf;
if (stat(sPath.c_str(), &buf) == 0 && S_ISDIR(buf.st_mode))
{
return true;
}
return false;
}
static void scanOneDirectory(const string &sPath, vector<string> &vFiles, bool bWithDirectory)
{
#ifndef BUILD_ON_MINGW
struct dirent **namelist = NULL;
int n = scandir(sPath.c_str(), &namelist, NULL, alphasort);
if (n < 0)
{
throw std::runtime_error("list directory: scandir failed");
}
for (int i = 0; i < n; ++i)
{
if (strcmp(namelist[i]->d_name, ".") != 0 && strcmp(namelist[i]->d_name, "..") != 0)
{
if (bWithDirectory || namelist[i]->d_type != DT_DIR)
{
vFiles.push_back(namelist[i]->d_name);
}
}
free(namelist[i]);
}
free(namelist);
#else
DIR *dirp = opendir(sPath.c_str());
if (dirp == NULL)
{
return;
}
struct dirent *dir = NULL;
while ((dir = readdir(dirp)) != NULL)
{
if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0)
{
if (bWithDirectory || UtilFile::isDirectoryExists(sPath + "\\" + dir->d_name))
{
vFiles.push_back(dir->d_name);
}
}
}
closedir(dirp);
#endif
}
static void scanRecDirectory(const string &sPath, const string &sPrefix, vector<string> &vFiles, bool bWithDirectory)
{
vector<string> v;
scanOneDirectory(sPath, v, true);
for (unsigned i = 0; i < v.size(); ++i)
{
const string &sFile = v[i];
const string &sAbsFile = sPath + "/" + sFile;
bool bIsDir = UtilFile::isDirectoryExists(sAbsFile);
if (!bIsDir || bWithDirectory)
{
if (sPrefix.empty())
{
vFiles.push_back(sFile);
}
else
{
vFiles.push_back(sPrefix + sFile);
}
}
if (bIsDir)
{
scanRecDirectory(sAbsFile, sPrefix + sFile + "/", vFiles, bWithDirectory);
}
}
}
void UtilFile::listDirectory(const string &sPath, vector<string> &vFiles, bool bRecursive, bool bWithDirectory)
{
if (!isDirectoryExists(sPath))
{
throw std::runtime_error("list directory: no such directory");
}
if (!bRecursive)
{
scanOneDirectory(sPath, vFiles, bWithDirectory);
}
else
{
scanRecDirectory(sPath, "", vFiles, bWithDirectory);
}
}
int32_t UtilFile::doSystem(const char* pCommand)
{
#ifndef BUILD_ON_MINGW
pid_t pid;
int32_t status;
if (pCommand == NULL)
{
return (1);
}
if((pid = fork()) < 0)
{
status = -1;
}
else if(pid == 0)
{
/* close all descriptors in child sysconf(_SC_OPEN_MAX) */
for (int i = 3; i < ::sysconf(_SC_OPEN_MAX); i++)
{
close(i);
}
execl("/bin/sh", "sh", "-c", pCommand, (char *)0);
_exit(127);
}
else
{
/*当进程中SIGCHLD做SIG_IGN操作时,获取不到status返回值,XOS_System无法正常工作*/
while(::waitpid(pid, &status, 0) < 0)
{
if(errno != EINTR)
{
status = -1;
break;
}
}
}
return status;
#else
return ::system(pCommand);
#endif
}
int32_t UtilFile::doFile(const string &sFileName)
{
if (sFileName.empty())
{
return -3;
}
int32_t iRet = doSystem(sFileName.c_str());
if (iRet != 0)
{
throw std::runtime_error("system: " + string(strerror(errno)));
}
return 0;
}
| true |
dee9cfd7164433b1d409932d13b8afcbac784564 | C++ | exposedtalent/CodingBlocks | /Assignment-1/changeBase.cpp | UTF-8 | 982 | 2.640625 | 3 | [] | no_license | #include<iostream>
using namespace std;
// int main() {
// int sb, db, sn;
// cin >> sb >> db >> sn;
// int mul = 1;
// int ans = 0;
// while (sn > 0) {
// int rem = sn%10;
// ans += (rem*mul);
// sn = sn/10;
// mul = mul*sb;
// cout << " Hello";
// }
// int fv = 0;
// mul = 1;
// while (ans > 0) {
// int rem = ans%10;
// fv+= (rem*mul);
// mul = mul*10;
// ans = ans/db;
// cout << " Hello2";
// }
// cout << fv << endl;
// }
int main() {
int sb,db,sn;
/* int sb;
int db;
int sn; */
cin>>sb>>db>>sn;
int mul = 1;
int ans =0;
while(sn>0){
int rem = sn%10;
ans+=(rem*mul);
sn=sn/10;
mul = mul*sb;
}
// cout << ans << endl; ///decimal no for src base
int final_value=0;
mul =1;
while(ans>0){
int rem = ans%db;
final_value+=(rem*mul);
mul = mul*10;
ans = ans/db;
}
cout << final_value << endl;
return 0;
} | true |
8ee32cf2fdc7881cc420d7de6196f36a706a52e9 | C++ | ChaseGregoryCS/DataStructures-College | /practice/LinkedList.cpp | UTF-8 | 318 | 2.9375 | 3 | [] | no_license |
List::List(){
iterator = NULL;
begining = NULL;
last = NULL;
}
List::List(int id){
beginning = new Element(id);
last = begining;
}
~List::List(){
}
Element List::Pop(){
int n = Length();
Element rValue = *last;
*last = this[n].DeleteMe();
}
| true |
2aa38ad94608ffb2eb41aedfd58df7a4387f6b6d | C++ | FeiZhan/Algo-Collection | /answers/leetcode/3Sum Closest/3Sum Closest.cpp | UTF-8 | 2,500 | 3.0625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int closest_diff = INT_MAX;
std::multimap<int, size_t> num_map;
for (size_t i = 0; i < num.size(); ++ i) {
num_map.insert(std::make_pair(num[i], 1));
}
for (std::multimap<int, size_t>::iterator it = num_map.begin(); it != num_map.end(); ++ it) {
std::multimap<int, size_t>::iterator it1 = num_map.begin();
std::multimap<int, size_t>::iterator it2 = num_map.end();
if (it1 == it) {
++ it1;
}
-- it2;
if (it2 == it) {
-- it2;
}
while (it1 != num_map.end() && it2 != num_map.end() && it1 != it2) {
int diff = it->first + it1->first + it2->first - target;
//@note abs
closest_diff = std::abs(closest_diff) > std::abs(diff) ? diff : closest_diff;
if (diff > 0) {
-- it2;
if (it2 == it) {
-- it2;
}
} else {
++ it1;
if (it1 == it) {
++ it1;
}
}
}
}
return target + closest_diff;
}
};
// 2015-01-10
// two pointers
//@result 120 / 120 test cases passed. Status: Accepted Runtime: 28 ms Submitted: 0 minutes ago You are here! Your runtime beats 15.51% of cpp submissions.
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
std::sort(num.begin(), num.end());
int closest = INT_MAX;
int three_sum = 0;
if (num.size() < 3) {
return three_sum;
}
for (size_t i = 0; i < num.size(); ++i) {
size_t left = i + 1, right = num.size() - 1;
while (left < num.size() && right < num.size() && left < right) {
int sum = num[left] + num[right] + num[i];
if (std::abs(sum - target) < closest) {
closest = std::abs(sum - target);
three_sum = sum;
int temp1 = num[left];
}
if (sum > target) {
int temp = num[right];
while (--right < num.size() && num[right] == temp) {}
}
else if (sum < target) {
int temp1 = num[left];
while (++left < num.size() && num[left] == temp1) {}
}
else {
break;
}
}
while (i + 1 < num.size() && num[i] == num[i + 1]) {
++i;
}
}
return three_sum;
}
};
| true |
9ae89b936cd26f70f89f39696ec0b34c7e3413e9 | C++ | ohahlev/topautocamcpp | /controllers/gradecontroller.cpp | UTF-8 | 2,619 | 2.734375 | 3 | [] | no_license | #include "gradecontroller.h"
#include "grade.h"
#include "gradevalidator.h"
void GradeController::index()
{
auto gradeList = Grade::getAll();
texport(gradeList);
render("index", "backend");
}
void GradeController::getCreate()
{
render("create", "backend");
}
void GradeController::postCreate()
{
QString notice;
QString error;
auto grade = httpRequest().formItems("grade");
GradeValidator validator;
if (!validator.validate(grade))
{
exportValidationErrors(validator);
texport(grade);
render("create", "backend");
return;
}
auto model = Grade::create(grade);
if (model.isNull())
{
error = "Failed to create.";
texport(error);
texport(grade);
render("create", "backend");
return;
}
notice = "Created successfully.";
tflash(notice);
redirect(urla("index"));
}
void GradeController::getSave(const QString &id)
{
auto model = Grade::get(id.toInt());
if (model.isNull())
{
renderErrorResponse(Tf::NotFound);
return;
}
auto grade = model.toVariantMap();
texport(grade);
render("save", "backend");
}
void GradeController::postSave(const QString &id)
{
QString notice;
QString error;
auto model = Grade::get(id.toInt());
if (model.isNull())
{
notice = "Original data not found. It may have been updated/removed by another transaction.";
tflash(notice);
redirect(url("admin/grade", "save", id));
return;
}
auto grade = httpRequest().formItems("grade");
GradeValidator validator;
if (!validator.validate(grade))
{
exportValidationErrors(validator);
texport(grade);
render("save", "backend");
return;
}
model.setProperties(grade);
if (!model.save())
{
error = "Failed to update.";
texport(error);
texport(grade);
render("save", "backend");
return;
}
notice = "Updated successfully.";
tflash(notice);
redirect(url("admin/grade", "save", id));
}
void GradeController::postRemove(const QString &id)
{
if (httpRequest().method() != Tf::Post)
{
renderErrorResponse(Tf::NotFound);
return;
}
auto grade = Grade::get(id.toInt());
bool removed = grade.remove();
QString notice;
if (removed == true)
{
notice = "Removed successfully.";
}
else
{
notice = "Failed to remove.";
}
redirect(urla("index"));
}
// Don't remove below this line
T_DEFINE_CONTROLLER(GradeController)
| true |
a28638a44913308c04faeace2a7d3ec1ebc79695 | C++ | DustinAwesome/Programming-Principles-and-Practice-Using-Cpp | /Section_8/token.h | UTF-8 | 1,843 | 3.0625 | 3 | [
"MIT"
] | permissive | #ifndef TOKEN_H // begin header guard
#define TOKEN_H
#include <string>
namespace calculator
{
const char number = '8'; // t.kind == number Token.
const char print = ';'; // t.kind == print Token.
const char quit = 'q'; // t.kind == quit Token.
const std::string key_quit = "quit"; // quit keyword
const char help = 'h'; // t.kind == help Token.
const std::string key_help = "help"; // help keyword
const char name = 'a'; // t.kind = name of variable Token
const char let = 'L'; // t.kind = declaration token
const std::string declkey = "let"; // declaration keyword
const char constant = 'C'; // t.kind = constant declaration Token
const std::string declkey_const = "const";// constant declaration keyword
const char func = 'F'; // t.kind = function Token
//------------------------------------------------------------------------------
class Token
{
public:
char kind;
double value;
std::string name;
Token();
Token(char ch, double val = 0.0);
Token(char ch, std::string s);
~Token();
};
//------------------------------------------------------------------------------
class Token_Stream
{
public:
Token_Stream();
Token_Stream(std::istream& /*tsin*/); // Token_stream that reads from an istream
~Token_Stream();
Token get();
void putback(const Token t);
void ignore(const char c);
private:
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
};
}
#endif // close header guard | true |
abdd80c674bc3bf63ad1d1754b34307bdb027df7 | C++ | Tonio5978/ESP32-HUB75-MatrixPanel-I2S-DMA | /examples/ChainedPanels/ChainedPanels.ino | UTF-8 | 9,265 | 2.578125 | 3 | [
"MIT"
] | permissive | /******************************************************************************
-----------
Steps to use
-----------
1) In the sketch (i.e. this example):
- Set values for NUM_ROWS, NUM_COLS, PANEL_RES_X, PANEL_RES_Y, PANEL_CHAIN.
There are comments beside them explaining what they are in more detail.
- Other than where the matrix is defined and matrix.begin in the setup, you
should now be using the virtual display for everything (drawing pixels, writing text etc).
You can do a find and replace of all calls if it's an existing sketch
(just make sure you don't replace the definition and the matrix.begin)
- If the sketch makes use of MATRIX_HEIGHT or MATRIX_WIDTH, these will need to be
replaced with the width and height of your virtual screen.
Either make new defines and use that, or you can use virtualDisp.width() or .height()
Thanks to:
* Brian Lough for the original example as raised in this issue:
https://github.com/mrfaptastic/ESP32-HUB75-MatrixPanel-I2S-DMA/issues/26
YouTube: https://www.youtube.com/brianlough
Tindie: https://www.tindie.com/stores/brianlough/
Twitter: https://twitter.com/witnessmenow
* Galaxy-Man for the kind donation of panels make/test that this is possible:
https://github.com/Galaxy-Man
*****************************************************************************/
/******************************************************************************
* VIRTUAL DISPLAY / MATRIX PANEL CHAINING CONFIGURATION
*
* Note 1: If chaining from the top right to the left, and then S curving down
* then serpentine_chain = true and top_down_chain = true
* (these being the last two parameters of the virtualDisp(...) constructor.
*
* Note 2: If chaining starts from the bottom up, then top_down_chain = false.
*
* Note 3: By default, this library has serpentine_chain = true, that is, every
* second row has the panels 'upside down' (rotated 180), so the output
* pin of the row above is right above the input connector of the next
* row.
Example 1 panel chaining:
+-----------------+-----------------+-------------------+
| 64x32px PANEL 3 | 64x32px PANEL 2 | 64x32px PANEL 1 |
| ------------ <-------- | ------------xx |
| [OUT] | [IN] | [OUT] [IN] | [OUT] [ESP IN] |
+--------|--------+-----------------+-------------------+
| 64x32px|PANEL 4 | 64x32px PANEL 5 | 64x32px PANEL 6 |
| \|/ ----------> | -----> |
| [IN] [OUT] | [IN] [OUT] | [IN] [OUT] |
+-----------------+-----------------+-------------------+
Example 1 configuration:
#define PANEL_RES_X 64 // Number of pixels wide of each INDIVIDUAL panel module.
#define PANEL_RES_Y 32 // Number of pixels tall of each INDIVIDUAL panel module.
#define NUM_ROWS 2 // Number of rows of chained INDIVIDUAL PANELS
#define NUM_COLS 3 // Number of INDIVIDUAL PANELS per ROW
virtualDisp(dma_display, NUM_ROWS, NUM_COLS, PANEL_RES_X, PANEL_RES_Y, true, true);
= 192x64 px virtual display, with the top left of panel 3 being pixel co-ord (0,0)
==========================================================
Example 2 panel chaining:
+-------------------+
| 64x32px PANEL 1 |
| ----------------- |
| [OUT] [ESP IN] |
+-------------------+
| 64x32px PANEL 2 |
| |
| [IN] [OUT] |
+-------------------+
| 64x32px PANEL 3 |
| |
| [OUT] [IN] |
+-------------------+
| 64x32px PANEL 4 |
| |
| [IN] [OUT] |
+-------------------+
Example 2 configuration:
#define PANEL_RES_X 64 // Number of pixels wide of each INDIVIDUAL panel module.
#define PANEL_RES_Y 32 // Number of pixels tall of each INDIVIDUAL panel module.
#define NUM_ROWS 4 // Number of rows of chained INDIVIDUAL PANELS
#define NUM_COLS 1 // Number of INDIVIDUAL PANELS per ROW
virtualDisp(dma_display, NUM_ROWS, NUM_COLS, PANEL_RES_X, PANEL_RES_Y, true, true);
virtualDisp(dma_display, NUM_ROWS, NUM_COLS, PANEL_RES_X, PANEL_RES_Y, true, true);
= 128x64 px virtual display, with the top left of panel 1 being pixel co-ord (0,0)
==========================================================
Example 3 panel chaining (bottom up):
+-----------------+-----------------+
| 64x32px PANEL 4 | 64x32px PANEL 3 |
| <---------- |
| [OUT] [IN] | [OUT] [in] |
+-----------------+-----------------+
| 64x32px PANEL 1 | 64x32px PANEL 2 |
| ----------> |
| [ESP IN] [OUT] | [IN] [OUT] |
+-----------------+-----------------+
Example 1 configuration:
#define PANEL_RES_X 64 // Number of pixels wide of each INDIVIDUAL panel module.
#define PANEL_RES_Y 32 // Number of pixels tall of each INDIVIDUAL panel module.
#define NUM_ROWS 2 // Number of rows of chained INDIVIDUAL PANELS
#define NUM_COLS 2 // Number of INDIVIDUAL PANELS per ROW
virtualDisp(dma_display, NUM_ROWS, NUM_COLS, PANEL_RES_X, PANEL_RES_Y, true, false);
= 128x64 px virtual display, with the top left of panel 4 being pixel co-ord (0,0)
*/
#define PANEL_RES_X 64 // Number of pixels wide of each INDIVIDUAL panel module.
#define PANEL_RES_Y 32 // Number of pixels tall of each INDIVIDUAL panel module.
#define NUM_ROWS 2 // Number of rows of chained INDIVIDUAL PANELS
#define NUM_COLS 2 // Number of INDIVIDUAL PANELS per ROW
#define PANEL_CHAIN NUM_ROWS*NUM_COLS // total number of panels chained one to another
// library includes
#include <ESP32-VirtualMatrixPanel-I2S-DMA.h>
// placeholder for the matrix object
MatrixPanel_I2S_DMA *dma_display = nullptr;
// placeholder for the virtual display object
VirtualMatrixPanel *virtualDisp = nullptr;
/******************************************************************************
* Setup!
******************************************************************************/
void setup() {
delay(2000);
Serial.begin(115200);
Serial.println(""); Serial.println(""); Serial.println("");
Serial.println("*****************************************************");
Serial.println(" HELLO !");
Serial.println("*****************************************************");
/******************************************************************************
* Create physical DMA panel class AND virtual (chained) display class.
******************************************************************************/
/*
The configuration for MatrixPanel_I2S_DMA object is held in HUB75_I2S_CFG structure,
All options has it's predefined default values. So we can create a new structure and redefine only the options we need
Please refer to the '2_PatternPlasma.ino' example for detailed example of how to use the MatrixPanel_I2S_DMA configuration
*/
HUB75_I2S_CFG mxconfig(
PANEL_RES_X, // module width
PANEL_RES_Y, // module height
PANEL_CHAIN // chain length
);
//mxconfig.driver = HUB75_I2S_CFG::FM6126A; // in case that we use panels based on FM6126A chip, we can set it here before creating MatrixPanel_I2S_DMA object
// Sanity checks
if (NUM_ROWS <= 1) {
Serial.println(F("There is no reason to use the VirtualDisplay class for a single horizontal chain and row!"));
}
// OK, now we can create our matrix object
dma_display = new MatrixPanel_I2S_DMA(mxconfig);
// let's adjust default brightness to about 75%
dma_display->setBrightness8(192); // range is 0-255, 0 - 0%, 255 - 100%
// Allocate memory and start DMA display
if( not dma_display->begin() )
Serial.println("****** !KABOOM! I2S memory allocation failed ***********");
// create VirtualDisplay object based on our newly created dma_display object
virtualDisp = new VirtualMatrixPanel((*dma_display), NUM_ROWS, NUM_COLS, PANEL_RES_X, PANEL_RES_Y, true);
// So far so good, so continue
virtualDisp->fillScreen(virtualDisp->color444(0, 0, 0));
virtualDisp->drawDisplayTest(); // draw text numbering on each screen to check connectivity
delay(3000);
Serial.println("Chain of 64x32 panels for this example:");
Serial.println("+--------+---------+");
Serial.println("| 4 | 3 |");
Serial.println("| | |");
Serial.println("+--------+---------+");
Serial.println("| 1 | 2 |");
Serial.println("| (ESP) | |");
Serial.println("+--------+---------+");
virtualDisp->setFont(&FreeSansBold12pt7b);
virtualDisp->setTextColor(virtualDisp->color565(0, 0, 255));
virtualDisp->setTextSize(2);
virtualDisp->setCursor(10, virtualDisp->height()-20);
// Red text inside red rect (2 pix in from edge)
virtualDisp->print("1234");
virtualDisp->drawRect(1,1, virtualDisp->width()-2, virtualDisp->height()-2, virtualDisp->color565(255,0,0));
// White line from top left to bottom right
virtualDisp->drawLine(0,0, virtualDisp->width()-1, virtualDisp->height()-1, virtualDisp->color565(255,255,255));
}
void loop() {
} // end loop
| true |
e012823358967c999b20d82d40f769946467882a | C++ | steinbergerbernd/Lucky-Leprechauns | /LuckyLeprechauns/Framework/GraphicsBuffer.h | UTF-8 | 2,478 | 3.15625 | 3 | [] | no_license | #pragma once
#include <vector>
#include "Exception.h"
#include "Resource.h"
template <class T, class DESC>
class GraphicsBuffer : public Resource<T>
{
public:
virtual ~GraphicsBuffer() = 0;
DESC getDesc() const;
template <class TF>
void getData(TF* data) const;
template <class TF>
void setData(const std::vector<TF>& data, unsigned long flags = 0) const;
template <class TF, int N>
void setData(TF (&data) [N], unsigned long flags = 0) const;
template <class TF>
void setData(TF* data, int size, unsigned long flags = 0) const;
protected:
virtual const char* getLockFailedException() const = 0;
virtual const char* getUnlockFailedException() const = 0;
virtual const char* getGetDescFailedException() const = 0;
private:
void lock(VOID **ppbData, unsigned long flags = 0, unsigned offsetToLock = 0, unsigned sizeToLock = 0) const;
void unlock() const;
};
template <class T, class DESC>
GraphicsBuffer<T, DESC>::~GraphicsBuffer()
{
}
template <class T, class DESC>
DESC GraphicsBuffer<T, DESC>::getDesc() const
{
DESC desc;
if (!resource || resource->GetDesc(&desc) != D3D_OK)
throw Exception(getGetDescFailedException());
return desc;
}
template <class T, class DESC>
void GraphicsBuffer<T, DESC>::lock(VOID **ppbData, unsigned long flags = 0, unsigned offsetToLock = 0, unsigned sizeToLock = 0) const
{
if (!resource || resource->Lock(offsetToLock, sizeToLock, ppbData, flags) != D3D_OK)
throw Exception(getLockFailedException());
}
template <class T, class DESC>
void GraphicsBuffer<T, DESC>::unlock() const
{
if (!resource || resource->Unlock() != D3D_OK)
throw Exception(getUnlockFailedException());
}
template <class T, class DESC> template <class TF>
void GraphicsBuffer<T, DESC>::setData(const std::vector<TF>& data, unsigned long flags) const
{
setData(&data[0], data.size(), flags);
}
template <class T, class DESC> template <class TF, int N>
void GraphicsBuffer<T, DESC>::setData(TF (&data) [N], unsigned long flags) const
{
setData(data, N, flags);
}
template <class T, class DESC> template <class TF>
void GraphicsBuffer<T, DESC>::setData(TF* data, int size, unsigned long flags) const
{
void* p;
int totalSize = sizeof(TF) * size;
lock(&p, flags, 0, totalSize);
memcpy(p, data, totalSize);
unlock();
}
template <class T, class DESC> template <class TF>
void GraphicsBuffer<T, DESC>::getData(TF* data) const
{
void* p;
lock(&p, D3DLOCK_READONLY);
memcpy(data, p, getDesc().Size);
unlock();
}
| true |
8194276603d7a6902d8bcdd1ceaa86767c740625 | C++ | jakubriegel/cjr | /test/numbers/comparisonTest.cpp | UTF-8 | 4,200 | 3.015625 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "numbers/number.hpp"
class NumberComparisonTest : public ::testing::Test {
protected:
cjr::number<> a = 1234;
cjr::number<> b = 1234;
cjr::number<> c = 4321;
cjr::number<> d = -1234;
cjr::number<> e = -1234;
cjr::number<> f = -4321;
};
TEST_F(NumberComparisonTest, ChecksNumbersEquality) {
// by member function
EXPECT_TRUE(a.isEqual(a));
EXPECT_TRUE(a.isEqual(b));
EXPECT_FALSE(a.isEqual(c));
EXPECT_TRUE(d.isEqual(d));
EXPECT_TRUE(d.isEqual(e));
EXPECT_FALSE(d.isEqual(f));
EXPECT_FALSE(a.isEqual(d));
// by operator
EXPECT_TRUE(a == a);
EXPECT_TRUE(a == b);
EXPECT_FALSE(a == c);
EXPECT_TRUE(d == d);
EXPECT_TRUE(d == e);
EXPECT_FALSE(d == f);
EXPECT_FALSE(a == d);
// by googletest
EXPECT_EQ(a, a);
EXPECT_EQ(a, b);
EXPECT_NE(a, c);
EXPECT_EQ(d, d);
EXPECT_EQ(d, e);
EXPECT_NE(d, f);
EXPECT_NE(a, d);
}
TEST_F(NumberComparisonTest, ChecksIfNumberIsBiggerThanAnother) {
// by member function
EXPECT_TRUE(c.isBigger(a));
EXPECT_FALSE(a.isBigger(b));
EXPECT_FALSE(a.isBigger(c));
EXPECT_TRUE(a.isBigger(d));
EXPECT_TRUE(d.isBigger(f));
EXPECT_FALSE(f.isBigger(d));
// by operator
EXPECT_TRUE(c > a);
EXPECT_FALSE(a > b);
EXPECT_FALSE(a > c);
EXPECT_TRUE(a > d);
EXPECT_TRUE(d > f);
EXPECT_FALSE(f > d);
// by googletest
EXPECT_GT(c, a);
EXPECT_GT(a, d);
EXPECT_GT(d, f);
}
TEST_F(NumberComparisonTest, ChecksIfNumberIsBiggerOrEqualThanAnother) {
// by member function
EXPECT_TRUE(c.isBiggerOrEqual(a));
EXPECT_TRUE(a.isBiggerOrEqual(a));
EXPECT_TRUE(a.isBiggerOrEqual(b));
EXPECT_FALSE(a.isBiggerOrEqual(c));
EXPECT_TRUE(a.isBiggerOrEqual(d));
EXPECT_TRUE(d.isBiggerOrEqual(d));
EXPECT_TRUE(d.isBiggerOrEqual(f));
EXPECT_FALSE(f.isBiggerOrEqual(d));
// by operator
EXPECT_TRUE(c >= a);
EXPECT_TRUE(a >= a);
EXPECT_TRUE(a >= b);
EXPECT_FALSE(a >= c);
EXPECT_TRUE(a >= d);
EXPECT_TRUE(d >= d);
EXPECT_TRUE(d >= f);
EXPECT_FALSE(f >= d);
// by googletest
EXPECT_GE(c, a);
EXPECT_GE(a, a);
EXPECT_GE(a, b);
EXPECT_GE(a, d);
EXPECT_GE(d, d);
EXPECT_GE(d, f);
}
TEST_F(NumberComparisonTest, ChecksIfNumberIsSmallerThanAnother) {
// by member function
EXPECT_TRUE(a.isSmaller(c));
EXPECT_FALSE(a.isSmaller(b));
EXPECT_FALSE(c.isSmaller(a));
EXPECT_TRUE(d.isSmaller(a));
EXPECT_TRUE(f.isSmaller(d));
EXPECT_FALSE(a.isSmaller(f));
// by operator
EXPECT_TRUE(a < c);
EXPECT_FALSE(a < b);
EXPECT_FALSE(c < a);
EXPECT_TRUE(d < a);
EXPECT_TRUE(f < d);
EXPECT_FALSE(a < f);
// by googletest
EXPECT_LT(a, c);
EXPECT_LT(d, a);
EXPECT_LT(f, d);
}
TEST_F(NumberComparisonTest, ChecksIfNumberIsSmallerOrEqualThanAnother) {
// by member function
EXPECT_TRUE(a.isSmallerOrEqual(c));
EXPECT_TRUE(a.isSmallerOrEqual(a));
EXPECT_TRUE(a.isSmallerOrEqual(b));
EXPECT_FALSE(c.isSmallerOrEqual(a));
EXPECT_TRUE(d.isSmallerOrEqual(a));
EXPECT_TRUE(d.isSmallerOrEqual(d));
EXPECT_TRUE(f.isSmallerOrEqual(d));
EXPECT_FALSE(a.isSmallerOrEqual(f));
// by operator
EXPECT_TRUE(a <= c);
EXPECT_TRUE(a <= a);
EXPECT_TRUE(a <= b);
EXPECT_FALSE(c <= a);
EXPECT_TRUE(d <= a);
EXPECT_TRUE(d <= d);
EXPECT_TRUE(f <= d);
EXPECT_FALSE(a <= f);
// by googletest
EXPECT_LE(a, c);
EXPECT_LE(a, a);
EXPECT_LE(a, b);
EXPECT_LE(d, a);
EXPECT_LE(d, d);
EXPECT_LE(f, d);
}
TEST_F(NumberComparisonTest, ThrowsExceptionWhenComparingNumbersWithDifferentBases) {
cjr::number<> a7(1234, 7);
cjr::number<> b1231(1234, 1231);
EXPECT_THROW(a7.isEqual(b1231), cjr::exception::differentBaseException);
EXPECT_THROW(a7.isBigger(b1231), cjr::exception::differentBaseException);
EXPECT_THROW(a7.isBiggerOrEqual(b1231), cjr::exception::differentBaseException);
EXPECT_THROW(a7.isSmaller(b1231), cjr::exception::differentBaseException);
EXPECT_THROW(a7.isSmallerOrEqual(b1231), cjr::exception::differentBaseException);
} | true |
b02b36dd92717e6ac62c5f4aed4cc83165b00303 | C++ | 380676003925/Labb | /Source (2).cpp | UTF-8 | 958 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Vegatables {
private:
char *color;
int price;
public:
Vegatables() {
color = '\0';
price = 0;
}
Vegatables(char* color, int price) {
this->color = color;
this->price = price;
}
Vegatables(const Vegatables& other){
this->color = other.color;
this->price = other.price;
}
void SetColor(char* color) {
this->color = color;
}
char *GetColor() {
return color;
}
void SetPrice(int price) {
this->price = price;
}
int GetPrice() {
return price;
}
void Print() {
cout << "Vegatables \n Color : " << color << "\t Price : " << price;
}
void Input() {
cout << "Enter Color : "; cin >> color;
cout << "Enter Price : "; cin >> price;
}
};
int main() {
char temporary[10];
//temporary = new char[10];
cin >> temporary;
Vegatables broccoli(temporary, 80);
broccoli.Print();
cout << endl;
system("pause");
return 0;
} | true |
6a5d163a68919b7bf5be2f3607cc520945d7ffb7 | C++ | sysulby/Standard-Code-Library | /include/data_structure/splay.hpp | UTF-8 | 2,441 | 2.546875 | 3 | [] | no_license | const int maxn = 1000000 + 5;
int psz;
int key[maxn], tag[maxn];
int sz[maxn], fa[maxn], ch[maxn][2];
int node(int k) {
int u = ++psz;
key[u] = k, tag[u] = 0, sz[u] = 1, fa[u] = ch[u][0] = ch[u][1] = 0;
return u;
}
void maintain(int u) { sz[u] = sz[ch[u][0]] + sz[ch[u][1]] + 1; }
void pushdown(int u) {
if (tag[u]) {
// apply change
tag[u] = 0;
}
}
class Splay {
public:
Splay() : root(0) {}
bool empty() { return root == 0; }
int size() { return sz[root]; }
void clear() { root = 0; }
int find(int k) {
int u = root, p = 0;
while (u) {
pushdown(u);
if (k == key[u]) return splay(u);
p = u, u = ch[u][k > key[u]];
}
splay(p);
return 0;
}
int insert(int k) {
int u = root, p = 0;
while (u) {
pushdown(u);
p = u, u = ch[u][k > key[u]];
}
u = node(k), fa[u] = p;
if (p) ch[p][k > key[p]] = u;
return splay(u);
}
int erase(int k) {
int u = find(k);
if (!u) return 0;
if (!ch[u][0] || !ch[u][1]) {
root = ch[u][0] ^ ch[u][1];
} else {
int d = (sz[ch[u][0]] > sz[ch[u][1]]), v = ch[u][d ^ 1];
while (ch[v][d]) {
pushdown(v);
v = ch[v][d];
}
splay(v, u);
fa[ch[u][d]] = v, ch[v][d] = ch[u][d], maintain(v);
root = v;
}
fa[root] = 0;
return u;
}
int order_of_key(int k) {
int u = root, p = 0, ret = 0;
while (u) {
pushdown(u);
if (k > key[u]) ret += sz[ch[u][0]] + 1;
p = u, u = ch[u][k > key[u]];
}
splay(p);
return ret;
}
int find_by_order(int i) {
int u = root, p = 0;
while (u) {
pushdown(u);
int l = sz[ch[u][0]];
if (i == l) return splay(u);
u = ch[u][i > l];
if (i > l) i -= l + 1;
}
splay(p);
return 0;
}
private:
int root;
void rotate(int u) {
int p = fa[u], g = fa[p], d = (u == ch[p][1]);
fa[ch[u][d ^ 1]] = p, ch[p][d] = ch[u][d ^ 1], maintain(p);
fa[p] = u, ch[u][d ^ 1] = p, maintain(u);
fa[u] = g;
if (g) ch[g][p == ch[g][1]] = u, maintain(g);
}
int splay(int u, int top = 0) {
while (fa[u] != top) {
int p = fa[u], g = fa[p];
if (g != top) rotate((u == ch[p][1]) ^ (p == ch[g][1]) ? u : p);
rotate(u);
}
if (!top) root = u;
return u;
}
};
| true |
bb18cd20c399087263d2b0c826e336cee7e03db9 | C++ | Vort/VortOS | /DriverPack/String2.h | UTF-8 | 2,059 | 2.71875 | 3 | [] | no_license | // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// String2.h
//
// v 2.01 (2007.02.28)
// v 2.02 (2009.04.30)
//
#pragma once
#include "Defs.h"
#include "Array2.h"
// ----------------------------------------------------------------------------
//typedef unsigned short wchar_t;
// ----------------------------------------------------------------------------
template<bool U> class _chartype {public: typedef wchar_t char_t;};
template<> class _chartype<false> {public: typedef char char_t;};
// ----------------------------------------------------------------------------
template <bool U>
class CString
{
public:
typedef typename _chartype<U>::char_t char_t;
CString();
CString(const char_t* Src);
CString(const char_t* Src, dword SrcLen);
void Add(const CString& Str);
void Add(const char_t Char);
dword Len() const;
char_t GetCh(dword Index) const;
void SetCh(dword Index, const char_t& Char);
CString Left(dword Count) const;
CString MidRel(dword Start, dword Count) const;
CString MidAbs(dword Start, dword EndX) const;
CString RightRel(dword Count) const;
CString RightAbs(dword Start) const;
void Trim(const char_t* CharSet);
void TrimLeft(const char_t* CharSet);
void TrimRight(const char_t* CharSet);
const CString& ToLower();
/*
const CString& ToUpper();
int Find(char_t Char, dword Offset) const;
int Find(const char_t* Substring, dword Offset) const;
void Replace(const CString& What, const CString& ByWhat);
*/
bool operator==(const CString& Str) const;
bool operator<=(const CString& Str) const;
bool operator>=(const CString& Str) const;
bool operator!=(const CString& Str) const;
bool operator<(const CString& Str) const;
bool operator>(const CString& Str) const;
char_t* _ptr();
const char_t* _ptr() const;
private:
CArray<char_t> m_Data;
};
// ----------------------------------------------------------------------------
typedef CString<false> CStringA;
typedef CString<true> CStringW;
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | true |
c0a2f607bd26c9726f5abd4a9b6b27c0d4b26a37 | C++ | ckhajavi/VDMS_FOR_REAL_THO | /user.h | UTF-8 | 3,953 | 2.859375 | 3 | [] | no_license | #ifndef USER_H
#define USER_H
#include <QString>
#include <iostream>
#include <fstream>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QDebug>
#include<Qmap>
#include<QStringList>
#include<stocklist.h>
using namespace std;
enum enumGender { MALE, FEMALE };
class User
{
public:
friend class StockList;
//default constructor
//friend class NewUserSetup;
User();
~User();
StockList *userStockList; //list of stocks
void setStockFile(); //sets the path to the where the stock list is held
void setFileName(); //sets the path to where the user info is stored
void setFileName(const QString&); //overloaded the above function
bool setDirectory(); //sets the directory of the userInfo.
bool loadUser(); //reads the user info from a text file, puts it into a Map and sets member variables to their corresponding values in the map
bool loadStockList(); //reads the stockList from a text file, puts it into a Map and sets member variables to their corresponding values in the map
void saveUser(); //reads the user info, in the form of a map to a text file
bool saveStockList(); //reads the list of stocks, in the form of a map to a text file
QString getFileName() const;
//set functions
void setUserName(const QString&);
void setPassword(const QString&);
void setFName(const QString&);
void setMName(const QString&);
void setLName( const QString&);
void setCellPhone(const QString&);
void setHomePhone(const QString&);
void setWorkPhone(const QString&);
void setAge(const QString&);
void setDOB(const QString&);
void setSSN(const QString&);
void setAddr1(const QString&);
void setAddr2(const QString&);
void setCity(const QString&);
void setState(const QString&);
void setCountry(const QString&);
void setEmail(const QString&);
void setSecurityQuestion1( const QString&);
void setSecurityQuestion2(const QString&);
void setSecurityAnswer1(const QString&);
void setSecurityAnswer2(const QString&);
void setGender(const enumGender&);
void setUserFunds(double);
//get methods
QString getUserName() const;
QString getFName() const;
QString getMName() const;
QString getLName() const;
QString getCellPhone() const;
QString getHomePhone() const;
QString getWorkPhone() const;
QString getAge() const;
QString getDOB() const;
//string getBirthMonth() const;
//string getBirthYear() const;
// string getBirthDay() const;
QString getLastFourSSN() const;
QString getAddr1() const;
QString getAddr2() const;
QString getCity() const;
QString getState() const;
QString getCountry() const;
QString getEmail() const;
QString getSecurityQuestion1() const;
QString getSecurityAnswer1() const;
QString getSecurityQuestion2() const;
QString getSecurityAnswer2() const;
QString getPassword() const;
enumGender getGender() const;
double totalCostOfStocks(const StockList&);
double getUserFunds() const;
private:
QString userName;
QString plainTextPassword;
QString fName, mName, lName;
QString cellPhone, homePhone, workPhone;
QString age;
QString DOB;
//QString birthMonth, birthYear, birthDay;
QString plainTextSSN;
QString addr1;
QString addr2;
QString city;
QString state;
QString country;
QString email;
QString securityQuestion1;
QString securityAnswer1;
QString securityQuestion2;
QString securityAnswer2;
enumGender gender;
QMap<QString, QString> userMap; //holds the user information in a map, sorted by variable name. variable name is the key
QString fileName; //holds the path to the text file of where we are storing the user's info
QString stockFile; //holds the path to the text file of where we are storing the list of stocks
double userFunds;
};
#endif // USER_H
| true |
8ad5f1d278a4b1adaacc5db13b413a91b740553c | C++ | chenyu1927/hello-world | /NewC++11/FileUntil.cpp | UTF-8 | 2,797 | 2.703125 | 3 | [] | no_license | #include "FileUntil.h"
#include "Type.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string>
#include <assert.h>
#include <stdio.h>
fileUntil::ReadSmallFile::ReadSmallFile(StringArg filename)
: fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC)),
err_(0)
{
buf_[0] = '\0';
if (fd_ < 0)
err_ = errno;
}
fileUntil::ReadSmallFile::~ReadSmallFile()
{
if (fd_ >= 0)
::close(fd_);
}
int fileUntil::ReadSmallFile::readToBuffer(int* size)
{
int err = err_;
if (fd_ >= 0)
{
ssize_t n = ::pread(fd_, buf_, sizeof(buf_)-1, 0);
if (n >= 0)
{
if (n > 0)
*size = static_cast<int>(n);
buf_[n] = '\0';
}
else
err = errno;
}
return err;
}
template <typename String>
int fileUntil::ReadSmallFile::readToString(int maxSize, String* context,
int64_t* fileSize, int64_t* createTime, int64_t* modifyTime)
{
static_assert(sizeof (off_t) == 8, "system diff");
assert(context != nullptr);
int err = err_;
if (fd_ >= 0)
{
struct stat st_buf;
if (fstat(fd_, &st_buf) < 0)
err_ = errno;
else
{
context->clear();
if (fileSize)
{
if (S_ISREG(st_buf.st_mode)) //regular file ==> normal file
{
*fileSize = st_buf.st_size;
context->reserve(static_cast<int>(std::min(implicit_cast<int64_t>(maxSize), *fileSize)));
}
else if (S_ISDIR(st_buf.st_mode))
{
err = EISDIR;
}
if (createTime)
{
*createTime = st_buf.st_ctime;
}
if (modifyTime)
{
*modifyTime = st_buf.st_mtime;
}
}
}
while (context->size() < implicit_cast<size_t>(maxSize))
{
size_t toRead = static_cast<size_t>(std::min(implicit_cast<int64_t>(maxSize) - context->size()
, sizeof buf_));
ssize_t n = ::read(fd_, buf_, toRead);
if (n > 0)
{
context->append(buf_, n);
}
else
{
if (n < 0)
err = errno;
break;
}
}
}
return err;
}
template int fileUntil::readFile(StringArg filename, int maxSize, std::string*, int64_t*, int64_t*, int64_t* );
fileUntil::AppendFile::AppendFile(StringArg filename)
: fp_(::fopen(filename.c_str(), "a+")),
writtenBytes_(0)
{
assert(fp_);
::setbuffer(fp_, buffer_, sizeof buffer_);
}
fileUntil::AppendFile::~AppendFile()
{
::fclose(fp_);
}
void fileUntil::AppendFile::flush()
{
::fflush(fp_);
}
void fileUntil::AppendFile::Append(const char* log, const size_t len)
{
size_t n = write(log, len);
size_t remain = len - n;
while (remain > 0)
{
size_t x = write(log+n, remain);
if (x <= 0)
{
int err = ferror(fp_);
if (err)
fprintf(stderr, "AppendFile::Append() failed %s\n", strerror(err));
break;
}
n += x;
remain -= x;
}
writtenBytes_ += n;
}
size_t fileUntil::AppendFile::write(const char* log, const size_t len)
{
return ::fwrite_unlocked(log, 1, len, fp_);
}
| true |
6be27bcc770f688aacd483c73766e29da3f18416 | C++ | Nickalus/MovieDB | /MovieDB.cpp | UTF-8 | 3,599 | 3.109375 | 3 | [] | no_license | #include "MovieDB.hpp"
#include "Actor.hpp"
#include "Movie.hpp"
#include "Genre.hpp"
#include <algorithm>
#include <iostream>
#include <memory>
#include <sstream>
////////////////////////////////////////////////////////////////////////////////
// Description: Constructor, does nothing other than run mysql_init
// Inputs: none
// Output: none
// Example: Project2 p2;
////////////////////////////////////////////////////////////////////////////////
MovieDB::MovieDB()
: mConnector(mysql_init(NULL)),
mServer("mysql.cs.uky.edu")
{
if(mConnector == NULL)
{
std::cerr << mysql_error(mConnector);
exit(1);
}
else
{
std::cout << "Connected!" << std::endl;
}
}
////////////////////////////////////////////////////////////////////////////////
// Description: Establishes connection to the databse
// Inputs: none
// Output: true or false depending on if the connection was successful
// Example: Project2 p2;
// if(p2.Connect)
// {
// //Loop
// }
////////////////////////////////////////////////////////////////////////////////
bool MovieDB::Connect()
{
if(!mysql_real_connect(mConnector, mServer.c_str(), "ntyo222", "u0442840", "ntyo222", 0, NULL, 0))
{
std::cerr << mysql_error(mConnector);
return false;
}
return true;
}
void MovieDB::Run()
{
std::string command = "Not Exit!";
while(command.compare("exit") != 0)
{
std::cout << "Enter a command or type help: ";
std::getline(std::cin, command);
//Make all text lower case
std::transform(command.begin(), command.end(), command.begin(), ::tolower);
std::istringstream iss(command);
//Loop till end of string
while(iss)
{
iss >> command;
//Test the command string for the correct command
if(command.compare("add") == 0)
{
iss >> command;
MovieDB::Add(command);
}
else if(command.compare("update") == 0)
{
iss >> command;
MovieDB::Update(command);
}
else if(command.compare("help") == 0)
{
MovieDB::Help();
}
else if(command.compare("exit") == 0)
{
std::cout << "Exiting" << std::endl;
}
else
{
std::cout << "Invild input!" << std::endl;
}
}
}
}
void MovieDB::Help()
{
}
void MovieDB::Add(std::string s)
{
//Test the command string for the correct command
if(s.compare("actor") == 0)
{
//Smart pointer for memory management
std::unique_ptr<Actor> actor(new Actor(mConnector));
actor->Add();
return;
}
else if(s.compare("movie") == 0)
{
std::unique_ptr<Movie> movie(new Movie(mConnector));
movie->Add();
return;
}
else if(s.compare("genre") == 0)
{
std::unique_ptr<Genre> genre(new Genre(mConnector));
genre->Add();
return;
}
else if(s.compare("back") == 0)
{
return;
}
else
{
std::cout << "Invild input!" << std::endl;
}
}
void MovieDB::Update(std::string s)
{
//Test the command string for the correct command
if(s.compare("actor") == 0)
{
//Smart pointer for memory management
std::unique_ptr<Actor> actor(new Actor(mConnector));
actor->Update();
return;
}
else if(s.compare("movie") == 0)
{
std::unique_ptr<Movie> movie(new Movie(mConnector));
movie->Update();
return;
}
else if(s.compare("genre") == 0)
{
std::unique_ptr<Genre> genre(new Genre(mConnector));
genre->Update();
return;
}
else if(s.compare("back") == 0)
{
return;
}
else
{
std::cout << "Invild input!" << std::endl;
}
}
| true |
b6bff8ce92a5348825a72564174cc666f529620b | C++ | adi-075/C-HSC-Boards-2021 | /Board Paper Programs/CS Board Question Solved/point.cpp | UTF-8 | 432 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
class point
{
int x, y, z;
public:
point(){
x=0; y=0;
}
point (int a, int b)
{
a=x;b=y;c=z;
}
void display()
{
cout << "\nThe Cartesian Cordinates are: " << a << " " << b;
}
void add(point p1, point p2)
{
a = p1.a + p2.a;
b = p1.b+p2.b;
}
};
int main()
{
point p1, p2(1, 2);
point p3(p1);
p1.add(p2,p3);
p1.display();
}
| true |
8458265057adaa8485c045769dd55e340b570e8f | C++ | JensLangerak/thesis | /src/pumpkin/Utilities/directly_hashed_integer_to_integer_map.h | UTF-8 | 658 | 3.28125 | 3 | [] | no_license | #pragma once
#include <vector>
namespace Pumpkin
{
//todo description
class DirectlyHashedIntegerToIntegerMap
{
public:
DirectlyHashedIntegerToIntegerMap(int num_values); //values in the set must be within [0,.., num_values)
void Insert(int value);
void Grow();
void Resize(int new_size);
void Clear();
bool IsPresent(int value) const;
int GetNumPresentValues() const;
int GetCapacity() const;
void SortPresentValues();
typename std::vector<int>::const_iterator begin() const;
typename std::vector<int>::const_iterator end() const;
private:
std::vector<int> present_values_;
std::vector<bool> is_value_present_;
};
}//end namespace Pumpkin | true |
9fd93a92643ac90e014c68db79c0714876b7b7ba | C++ | lancercd/Learning-code | /test/test123.cpp | UTF-8 | 857 | 2.625 | 3 | [] | no_license | #include "iostream"
#include "algorithm"
#include "cstring"
using namespace std;
const int MAXN = 505;
int N, M;
typedef struct{int p,q,v;}Node;
Node arr[MAXN];
int dp[5005];
bool cmp(Node a, Node b){
return (b.q - b.p) > (a.q - a.p);
}
int main()
{
freopen("../data/in.txt", "r", stdin); freopen("../data/out.txt", "w", stdout);
while(scanf("%d %d", &N, &M) != EOF)
{
fill(dp, dp + M + 1, 0);
for(int i=1;i<=N;++i){scanf("%d %d %d",&arr[i].p, &arr[i].q, &arr[i].v);}
sort(arr + 1, arr + N + 1, cmp);
for(int i=1; i <= N; ++i)
{
for(int j=M; j >= arr[i].q; --j)
{
if(dp[j] < dp[j - arr[i].p] + arr[i].v){
dp[j] = dp[j - arr[i].p] + arr[i].v;
}
}
}
printf("%d\n",dp[M]);
}
return 0;
}
| true |
06fc21ecb656efc500a5c3e5db27ba5cc7503bc0 | C++ | CLEMENTINATOR/TeamWiigen | /BrowserDemo/Browser/source/business/FileSystemManager.h | UTF-8 | 1,058 | 2.5625 | 3 | [] | no_license | #ifndef _FILE_SYSTEM_MANAGER_H_
#define _FILE_SYSTEM_MANAGER_H_
#include <string>
#include <libutils/Object.h>
#include "FileSystemManagerEvents.h"
class FileSystemManager : public Object
{
private:
FileSystemManager();
bool cut;
std::string clipboard;
bool PasteFile(const std::string &sourceFile, const std::string &destDirectory);
bool PasteDirectory(const std::string &sourceDirectory, const std::string &destDirectory);
protected:
void OnCopiing(FileSystemManagerProcessControl *processControl);
public:
FileSystemManagerEvent BeforeCopiing;
static FileSystemManager& Current();
bool Cut(const std::string &path);
void Copy(const std::string &path);
bool Paste(const std::string &directory);
bool Delete(const std::string &path);
void InstallWad(const std::string &path);
void UninstallWad(const std::string &path);
bool CanCopy(const std::string &path);
bool CanDelete(const std::string &path);
bool CanCut(const std::string &path);
bool CanPaste(const std::string &directory);
};
#endif
| true |
c683cfbd4751c64884f18c4dd821d505d3606cf9 | C++ | xshi/CEPCSW | /Utilities/DataHelper/src/ClusterExtended.cc | UTF-8 | 4,884 | 2.953125 | 3 | [] | no_license | #include "DataHelper/CaloHitExtended.h"
#include "DataHelper/TrackExtended.h"
#include "DataHelper/ClusterExtended.h"
#include <math.h>
ClusterExtended::ClusterExtended() {
_hitVector.clear();
_trackVector.clear();
_direction[0] = 0.;
_direction[1] = 0.;
_direction[2] = 0.;
_startingPoint[0] = 0.;
_startingPoint[1] = 0.;
_startingPoint[2] = 0.;
}
ClusterExtended::ClusterExtended( Cluster * cluster ) {
_hitVector.clear();
_trackVector.clear();
_direction[0] = 0.;
_direction[1] = 0.;
_direction[2] = 0.;
_startingPoint[0] = 0.;
_startingPoint[1] = 0.;
_startingPoint[2] = 0.;
_cluster = cluster;
}
ClusterExtended::ClusterExtended(CaloHitExtended * calohit) {
_hitVector.clear();
_hitVector.push_back(calohit);
_trackVector.clear();
float rad(0);
_startingPoint[0] = calohit->getCalorimeterHit()->getPosition().x;
_startingPoint[1] = calohit->getCalorimeterHit()->getPosition().y;
_startingPoint[2] = calohit->getCalorimeterHit()->getPosition().z;
for (int i(0); i < 3; ++i) {
rad += _startingPoint[i]*_startingPoint[i];
}
rad = sqrt(rad);
_direction[0] = _startingPoint[0]/rad;
_direction[1] = _startingPoint[1]/rad;
_direction[2] = _startingPoint[2]/rad;
}
ClusterExtended::ClusterExtended(TrackExtended * track) {
_hitVector.clear();
_trackVector.clear();
_trackVector.push_back(track);
for (int i(0); i < 3; ++i) {
_startingPoint[i] = track->getSeedPosition()[i];
_direction[i] = track->getSeedDirection()[i];
}
}
ClusterExtended::~ClusterExtended() {
_hitVector.clear();
_trackVector.clear();
}
CaloHitExtendedVec& ClusterExtended::getCaloHitExtendedVec() {
return _hitVector;
}
TrackExtendedVec& ClusterExtended::getTrackExtendedVec() {
return _trackVector;
}
const float* ClusterExtended::getStartingPoint() {
return _startingPoint;
}
const float* ClusterExtended::getDirection() {
return _direction;
}
void ClusterExtended::setStartingPoint(float* sPoint) {
_startingPoint[0] = sPoint[0];
_startingPoint[1] = sPoint[1];
_startingPoint[2] = sPoint[2];
}
void ClusterExtended::setDirection(float* direct) {
_direction[0] = direct[0];
_direction[1] = direct[1];
_direction[2] = direct[2];
}
void ClusterExtended::addCaloHitExtended(CaloHitExtended* calohit) {
_hitVector.push_back(calohit);
}
void ClusterExtended::addTrackExtended(TrackExtended * track) {
_trackVector.push_back(track);
}
void ClusterExtended::Clear() {
_hitVector.clear();
_trackVector.clear();
}
void ClusterExtended::setType( int type ) {
_type = type;
}
int ClusterExtended::getType() {
return _type;
}
void ClusterExtended::setCluster(Cluster * cluster) {
_cluster = cluster;
}
Cluster * ClusterExtended::getCluster() {
return _cluster;
}
void ClusterExtended::setAxis(float * axis) {
_axis[0] = axis[0];
_axis[1] = axis[1];
_axis[2] = axis[2];
}
float * ClusterExtended::getAxis() {
return _axis;
}
void ClusterExtended::setEccentricity( float eccentricity) {
_eccentricity = eccentricity;
}
float ClusterExtended::getEccentricity() {
return _eccentricity;
}
void ClusterExtended::setHelix(HelixClass helix) {
_helix = helix;
int nHits = int(_hitVector.size());
float timeMax = -1.0e+20;
float timeMin = 1.0e+20;
for (int ihit=0;ihit<nHits;++ihit) {
float pos[3];
for (int i=0;i<3;++i)
pos[i]=_hitVector[ihit]->getCalorimeterHit()->getPosition()[i];
float distance[3];
float time = _helix.getDistanceToPoint(pos,distance);
if (time > timeMax) {
timeMax = time;
_upEdge[0] = pos[0];
_upEdge[1] = pos[1];
_upEdge[2] = pos[2];
}
if (time < timeMin) {
timeMin = time;
_lowEdge[0] = pos[0];
_lowEdge[1] = pos[1];
_lowEdge[2] = pos[2];
}
}
}
HelixClass & ClusterExtended::getHelix() {
return _helix;
}
void ClusterExtended::setHelixChi2R(float helixChi2) {
_helixChi2R = helixChi2;
}
float ClusterExtended::getHelixChi2R() {
return _helixChi2R;
}
void ClusterExtended::setHelixChi2Z(float helixChi2) {
_helixChi2Z = helixChi2;
}
float ClusterExtended::getHelixChi2Z() {
return _helixChi2Z;
}
void ClusterExtended::setPosition(float * position) {
_position[0] = position[0];
_position[1] = position[1];
_position[2] = position[2];
}
float * ClusterExtended::getPosition() {
return _position;
}
void ClusterExtended::setUpEdge(float * upEdge) {
_upEdge[0] = upEdge[0];
_upEdge[1] = upEdge[1];
_upEdge[2] = upEdge[2];
}
void ClusterExtended::setLowEdge(float * lowEdge) {
_lowEdge[0] = lowEdge[0];
_lowEdge[1] = lowEdge[1];
_lowEdge[2] = lowEdge[2];
}
float * ClusterExtended::getUpEdge() {
return _upEdge;
}
float * ClusterExtended::getLowEdge() {
return _lowEdge;
}
| true |
b3e824b76889a0b26071daeeb02f5f3b7c224b60 | C++ | KoalaGroup/KoalaSoft | /daq/ems/KoaEmsConfig.h | UTF-8 | 4,432 | 2.609375 | 3 | [] | no_license | #ifndef KOA_EMS_CONFIG_H
#define KOA_EMS_CONFIG_H
#include "TObject.h"
#include <cstdint>
#include <fstream>
#include <string>
#include <sstream>
#include <map>
/* Module type enumeration. The value comes from KoalaEms definition, which is not important in KoalaSoft. */
enum class MesytecType : std::uint64_t
{
MTDC32 = 0x23f10032UL,
MADC32 = 0x21f10032UL,
MQDC32 = 0x22f10032UL,
INVALID = 0x00000000UL
};
/* Module configuration table. Module id as key, Module info as value */
struct ModuleInfo
{
ModuleInfo() : type(MesytecType::INVALID), name("INVALID") {}
ModuleInfo(MesytecType& intype, std::string& inname) : type(intype), name(inname) {}
MesytecType type;
std::string name;
};
using ModuleId = std::uint32_t;
using ModuleTable = std::map<ModuleId, ModuleInfo>;
/* Types used in Module Channel mapping */
using ChannelInfo = std::pair<Int_t, Int_t>; // for DAQ, it's <ModuleId, ModuleCh>; for detector, it's <DetectorId, DetectorCh>
using ChannelMap = std::map<Int_t, ChannelInfo>; // from encoded detector channel id to DAQ channel info
using ChannelMapReverse = std::map<ChannelInfo, Int_t>; // from DAQ channel info to encoded detector channel id
using ChannelInfoMap = std::map<ChannelInfo, ChannelInfo>; // from channel info pair to channel info map
using ScalorMap = std::map<std::string, int>;
/* This class stores the EMS DAQ configuration information and the mapping table from
DAQ channel to Detector channel.
DAQ configuration information is:
1. Number of Modules used
2. Type ID of the module
3. ID of the module
4. Name of the module
The mapping table is:
1. 1-1 mapping from module channel to Koala detector readout channel
2. Each type of the module has a separate mapping table
These information is provide by the user as a text configuration file.
It's a singleton class and should be instantiated once and owned by the user himself.
After the usage, the user is in charge of the destruction of this singleton.
*/
class KoaEmsConfig : public TObject
{
public:
KoaEmsConfig();
~KoaEmsConfig();
static KoaEmsConfig* Instance() {
return fgInstance;
}
// Module configuration table
bool SetEmsConfigFile(const char* filename);
bool SetAmplitudeChannelMap(const char* filename);
bool SetTimeChannelMap(const char* filename);
bool SetScalorChannelMap(const char* filename);
//
void PrintModuleTable(const char* filename = nullptr);
void PrintAmplitudeChannelMap(const char* filename = nullptr);
void PrintTimeChannelMap(const char* filename = nullptr);
void PrintScalorChannelMap(const char* filename = nullptr);
//
ModuleTable GetModuleTable() { return fModuleTable; }
ChannelInfoMap GetAmplitudeChMapInfo() { return fChInfoMap_Amplitude; }
ChannelInfoMap GetTimeChMapInfo() { return fChInfoMap_Time; }
ChannelInfoMap GetAmplitudeChMapInfoReverse() { return fChInfoMapReverse_Amplitude; }
ChannelInfoMap GetTimeChMapInfoReverse() { return fChInfoMapReverse_Time; }
ChannelMap GetAmplitudeChMap() { return fChMap_Amplitude; }
ChannelMap GetTimeChMap() { return fChMap_Time; }
ChannelMapReverse GetAmplitudeChMapReverse() { return fChMapReverse_Amplitude; }
ChannelMapReverse GetTimeChMapReverse() { return fChMapReverse_Time; }
ScalorMap GetScalorChMap() { return fScalorChMap; }
private:
bool ReadEmsConfig(std::ifstream& infile);
bool ReadAmplitudeChannelMapConfig(std::ifstream& infile);
bool ReadTimeChannelMapConfig(std::ifstream& infile);
bool ReadScalorChannelMapConfig(std::ifstream& infile);
private:
std::string fFileEmsConfig;
std::string fFileAmplitudeMapConfig;
std::string fFileTimeMapConfig;
std::string fFileScalorMapConfig;
ModuleTable fModuleTable; // EMS configuration
ChannelInfoMap fChInfoMap_Amplitude; // from detector channel info pair to DAQ channel info pair
ChannelInfoMap fChInfoMap_Time;
ChannelInfoMap fChInfoMapReverse_Amplitude; // from DAQ channel info pair to detector channel info pair
ChannelInfoMap fChInfoMapReverse_Time;
ChannelMap fChMap_Amplitude; // from encoded detector channel id to DAQ channel info pair
ChannelMap fChMap_Time;
ChannelMapReverse fChMapReverse_Amplitude; // from DAQ channel info pair to encoded channel id
ChannelMapReverse fChMapReverse_Time;
ScalorMap fScalorChMap;
// static instance
static KoaEmsConfig* fgInstance;
ClassDef(KoaEmsConfig, 1)
};
#endif
| true |
3989d5132bb2ebb0642bca598e2e1f064fcce061 | C++ | josura/generic_programs | /prog2/Pile con le liste semplici.cpp | UTF-8 | 1,776 | 4.125 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*
Pile
Struttura LIFO, last in first out, ogni volta che inseriamo un elemento questo sarà il primo ad essere
cancellato. Operazione di inserimento push, di cancellazione pop.
Una pila può essere realizzata con un array o una lista semplice. Se la pila è vuota dobbiamo fare
in modo di non poter fare pop, viceversa se è piena. Indice per la cima della pila etc.
*/
class Nodo{
public:
Nodo(int x) {valore=x; succ=NULL;}
int get_valore(){return valore;}
void Assegna(int x){valore=x;}
Nodo* Successivo(){return succ;}
void AssegnaSuccessivo(Nodo* p){succ=p;}
private:
int valore;
Nodo* succ;
};
class Pila{
public:
Pila() {p=NULL;}
~Pila();
bool PilaVuota() {return !p;}
int PrimoElemento(){
if(p!=NULL) return p->get_valore();
else return -1;
}
void Push(int x);
int Pop();
void StampaPila();
private:
Nodo *p;
void CancellaNodo();
};
void Pila::StampaPila(){
Nodo* pnodo=p;
if(pnodo==NULL) cout << "Lista vuota! \n";
while (pnodo!=NULL){
cout << pnodo->get_valore() << endl;
pnodo=pnodo->Successivo();
}
}
void Pila::Push(int x){
Nodo* aux=new Nodo(x);
if (p) aux->AssegnaSuccessivo(p); //abbiamo esposto la testa, inserimento in testa
p=aux;
}
void Pila::CancellaNodo(){
Nodo* pnodo;
if (p) {
pnodo=p;
p=p->Successivo();
delete pnodo;
}
}
int Pila::Pop(){
int e;
e=PrimoElemento();
CancellaNodo();
return e;
}
Pila::~Pila(){
Nodo* pnodo;
while(p!=0){
pnodo=p;
p=p->Successivo();
delete pnodo;
}
}
int main(){
Pila p;
p.Push(4);
p.Push(5);
p.Push(12);
p.StampaPila();
while(!p.PilaVuota()){
cout << p.PrimoElemento() << "\t";
p.Pop();
}
cout << endl;
p.Push(34);
p.StampaPila();
p.~Pila();
p.StampaPila();
return 0;
} | true |
8808b531b05d981c63bcac70eaf04a6054f16901 | C++ | gomip/PL | /C/PL_test.cpp | UTF-8 | 2,838 | 3.09375 | 3 | [] | no_license | // PL_test.cpp: 콘솔 응용 프로그램의 진입점을 정의합니다.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void Generate(int* arr,const char* fileName);
void init_board();
int board[10] = { ' ',' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
int check_win(); //check game state 1 = win -1 = draw 0 = none
int main()
{
int value1[9];
int checkRepeat=0; //to avoid repeat in random variable
char p; //check player
int finish; // check game state
srand(time(NULL));
init_board();
int turn=rand()%2+1;
if (turn == 1) {
printf("A goes first\n");
p = 'O';
}
else {
printf("B goes first\n");
p = 'X';
}
printf("\n======= List ======\n");
for (int i = 0; i < 9; i++) {
value1[i] = rand() % 9 + 1;
for (int j = 0; j < i; j++) {
if (value1[i] == value1[j]) {
i--;
break;
}
}
}
for (int i = 0; i < 9; i++) {
printf("A [%d] = %d\n", i+1, value1[i]);
}
Generate(value1, "move.txt");
finish = check_win();
if (finish == -1) {
printf("draw\n");
}
else if (finish==1){
if (p == 'O') {
printf("A win\n");
}
else {
printf("B win\n");
}
}
else {
printf("\n");
}
return 0;
}
void Generate(int* arr,const char* fileName) {
FILE *fp;
fopen_s(&fp, fileName, "wt");
for (int i = 0; i < 9; i++) {
fprintf(fp, "[%d] = %d\n", i, arr[i]);
}
}
void init_board() {
printf("\n====Board====\n");
printf("-------------\n");
printf("| %c │ %c │ %c │\n",board[1],board[2] ,board[3] );
printf("-------------\n");
printf("| %c │ %c │ %c │\n", board[4], board[5], board[6]);
printf("-------------\n");
printf("| %c │ %c │ %c │\n", board[7], board[8], board[9]);
printf("-------------\n");
}
int check_win() {
int i;
//horizontal and vertical
if (board[1] == board[2] && board[2] == board[3] && board[1]!=' ') {
return 1;
}
else if (board[4] == board[5] && board[5] == board[6] && board[4] != ' ') {
return 1;
}
else if (board[7] == board[8] && board[8] == board[9] && board[7] != ' ') {
return 1;
}
else if (board[1] == board[4] && board[4] == board[7] && board[1] != ' ') {
return 1;
}
else if (board[2] == board[5] && board[5] == board[8] && board[2] != ' ') {
return 1;
}
else if (board[3] == board[6] && board[6] == board[9] && board[3] != ' ') {
return 1;
}
else if (board[1] == board[5] && board[5] == board[9] && board[1] != ' ') {
return 1;
}
else if (board[3] == board[5] && board[5] == board[7] && board[3] != ' ') {
return 1;
}
else if (board[1] != ' '&&board[2] != ' '&&board[3] != ' '&&board[4] != ' '&&board[5] != ' '&&board[6] != ' '&&board[7] != ' '&&board[8] != ' '&&board[9] != ' ') {
return -1;
}
else {
return 0;
}
}
| true |
bf8cce1fdad2042284e07881ec6390484a6ecb97 | C++ | yonasadiel/cp | /TLX/TLC/4_C_D_StringBerbeda.cpp | UTF-8 | 665 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int bedanya(string a, string b) {
// cout<<a<<" "<<b<<endl;
int hitung=0;
for (int i=0; i<a.length(); i++) {
if (a[i]!=b[i]) {
hitung++;
}
}
return hitung;
}
int main() {
int hasil=999999999;
string panjang,pendek;
cin>>panjang>>pendek;
if (panjang.length()<pendek.length()) {
string temp=pendek;
pendek=panjang;
panjang=temp;
}
int beda=panjang.length()-pendek.length();
for (int i=0; i<=beda; i++) {
// cout<<panjang<<" "<<pendek<<endl;
string baru="";
for (int j=0; j<pendek.length(); j++) {
baru+=panjang[j+i];
}
hasil=min(hasil,bedanya(baru,pendek));
}
cout<<hasil<<endl;
}
| true |
8b2c2167f2d14ea6d6cf19a4e857a16ea72e2f1d | C++ | trbahb252/traffic_signal_sim_cookbook | /2. Signalized Intersection Control/2.6 Advanced Control Simulation/2.6.5 VISSIM Signal APIs/2nd DLL (GUI) for defining sgs/SignalGroup.h | UTF-8 | 6,397 | 3.140625 | 3 | [] | no_license | #pragma once
#include <map>
#include <set>
#include <string>
#include <vector>
/*==========================================================================*/
/**
* @brief Contains all properties of a signal group.
*
* The signal group allows reverting changes, if the
* editing was canceled. If further properties are required
* for a signal group, add them in this class using the following
* pattern:
*
* @code
* template<typename T>
* T GetValue() {
* return value_;
* }
*
* template<typename T>
* T GetOrigValue() {
* return origValue_;
* }
*
* template<typename T>
* void SetValue(T value) {
* if (!editable_) {
* origValue_ = value;
* }
* value_ = value;
* }
* @endcode
*
* You should also add default values for the new properties. This
* requires updating the SetDefault method.
*/
class SignalGroup
{
public:
SignalGroup(long nr);
SignalGroup(long nr, bool editable);
long GetNr() {
return nr_;
}
long GetOrigNr() {
return origNr_;
}
std::string GetName(){
return name_;
}
unsigned int GetAmber() {
return amber_;
}
unsigned int GetRed() {
return red_;
}
unsigned int GetMinRed() {
return minRed_;
}
unsigned int GetGreen() {
return green_;
}
unsigned int GetMinGreen() {
return minGreen_;
}
void SetNr(long nr) {
if (!editable_) {
origNr_ = nr;
}
nr_ = nr;
}
void SetName(std::string & name) {
if (!editable_) {
origName_ = name;
}
name_ = name;
}
void SetAmber(unsigned int amber) {
if (!editable_) {
origAmber_ = amber;
}
amber_ = amber;
}
void SetRed(unsigned int red) {
if (!editable_) {
origRed_ = red;
}
red_ = red;
}
void SetMinRed(unsigned int minRed) {
if (!editable_) {
origMinRed_ = minRed;
}
minRed_ = minRed;
}
void SetGreen(unsigned int green) {
if (!editable_) {
origGreen_ = green;
}
green_ = green;
}
void SetMinGreen(unsigned int minGreen) {
if (!editable_) {
origMinGreen_ = minGreen;
}
minGreen_ = minGreen;
}
/**
* @brief Compares two signal groups using the signal group number.
*
* @param The signal group to compare with.
*
* @return <code>true</code>, if both object equal, otherwise <code>false</code>.
*/
bool operator== (SignalGroup* group) {
return nr_ == group->nr_;
}
/**
* @brief Sets, whether the signal group is edited or not.
*
* @param editable Whether the signal group is edited or not.
*/
void EditModus(bool editable);
/**
* @brief Undo all made changes.
*
* The function reverts all changes made on the signal group.
* Update this function, if you require additional properties.
*
*/
void Revert(void);
/**
* @brief Sets all values to the default.
*
* Update this function, if you require additional properties.
*/
void SetDefault(void);
private:
bool editable_;
long nr_;
long origNr_;
std::string name_;
std::string origName_;
unsigned int amber_;
unsigned int origAmber_;
unsigned int red_;
unsigned int origRed_;
unsigned int minRed_;
unsigned int origMinRed_;
unsigned int green_;
unsigned int origGreen_;
unsigned int minGreen_;
unsigned int origMinGreen_;
};
typedef std::map<long, SignalGroup*> SignalGroups;
/*==========================================================================*/
/**
* @brief Contains all properties of a signal control including the
* signal groups.
*
* Add here additional properties for the signal control using
* the pattern described in the SignalGroup class.
*/
class SignalControl
{
public:
SignalControl(long nr);
virtual ~SignalControl();
std::string GetFileName() {
return fileName_;
}
long GetNumber() {
return scNr_;
}
std::string & FileName() {
return fileName_;
}
SignalGroups & SignalGroups() {
return groups_;
}
std::vector<SignalGroup*> & NewGroups() {
return newGroups_;
}
/**
* @brief Sets, whether the signal group is edited or not.
*
* All signal groups are also marked as edited.
*
* @param editable Whether the signal group is edited or not.
*/
void EditModus(bool editable);
/**
* @brief Adds a new signal group with the given id.
*
* An existing signal group with the id is erased, before
* the new one is added.
*
* @param sgNo The signal group number.
*/
void AddSignalGroup(long sgNo);
/**
* @brief Removes an existing signal group with the given id.
*
* If the signal control is in the edit mode, the signal group
* is not really removed but marked as removed.
*
* @param sgNo The signal group number.
*/
void RemoveSignalGroup(long sgNo);
/**
* @brief Gets the signal group with the given id.
*
* @param sgNo The signal group number.
* @param includeDeleted Whether already deleted signal
* groups should be considered or not.
*/
SignalGroup* GetSignalGroup(long sgNo, bool includeDeleted = false);
/**
* @brief Changes the number of the given signal group.
*
* @param oldSgNo The old signal group number.
* @param newSgNo The new signal group number.
*
* @return <code>true</code> if the renaming succeeded, otherwise <code>false</code>.
*/
bool RenameSignalGroup(long oldSgNo, long newSgNo);
/**
* @brief Makes the changes permanent, if the signal group was in edit mode before.
*/
void ComputeUpdatedSignalGroups(void);
/**
* @brief Removes all signal groups.
*/
void ClearSignalGroups(void);
/**
* @brief Reverts all changed made on the signal groups.
*/
void RevertSignalGroups(void);
private:
bool editable_;
long scNr_;
std::string fileName_;
std::vector<SignalGroup*> newGroups_;
std::vector<SignalGroup*> changedGroups_;
std::vector<SignalGroup*> deletedGroups_;
std::map<long, SignalGroup*> groups_;
};
typedef std::map<long, SignalControl* > SignalControls;
/*==========================================================================*/ | true |
37d1a323da0507f0f4fc313e1aac6ba47bdb5829 | C++ | pbrusco/tps-algoritmos3 | /TP1/Ej_2/Otros/Con y sin mejoras/mejora 1/Ronda.h | UTF-8 | 709 | 2.5625 | 3 | [] | no_license | #ifndef __RONDA__
#define __RONDA__
#include <iostream>
#include <list>
#include <set>
using namespace std;
class chica{
private:
int nombre;
set<int>* amigas;
public:
chica();
~chica();
int dameNombre() const;
set<int>* dameAmigas() const;
chica(const chica&);
chica& operator=(const chica &c1);
void nombrar(int i);
void amigar(int i);
void borrarAmigas();
};
class Ronda{
public:
Ronda();
~Ronda();
void cargarAmistades(istream& is,int n);
bool resolver();
bool probarDistintasRondas(const chica &prim,const chica& ult);
private:
set<int>* enRonda;
list<chica>* gente;
// set<int>* amigasPrimera;
};
bool operator<(const chica &c1,const chica &c2);
#endif
| true |
d5f4636b0725308f675d45ba65f287b39502f6f3 | C++ | Alex-Chechulov/Meteo_Summary | /Meteo_Summary/Section_5.cpp | WINDOWS-1251 | 5,614 | 3.078125 | 3 | [] | no_license | #include "Section_5.h"
// 5
// 5
String^ Struct_555()
{
return "555 ";
}
//1EsnT'gT'g
//1
//
//snT'gT'g
//sn
//T'gT'g
String^ Struct_1EsnTgTg(String^ Ok_Temperature_of_soil, int Ok_Condition_of_soil_surfase)
{
String^ Summary;
int Temperature_of_soil = Convert::ToInt32(Ok_Temperature_of_soil);
String^ Sign = "0";
if (Temperature_of_soil < 0) {
Sign = "1";
Temperature_of_soil = -Temperature_of_soil;
}
Summary += "1";
if (Ok_Condition_of_soil_surfase < 10)Summary += Convert::ToString(Ok_Condition_of_soil_surfase);
else Summary += "/";
if (Temperature_of_soil < 10.0) Summary += Sign + "0" + Convert::ToString(Temperature_of_soil);
else Summary += Sign + Convert::ToString(Temperature_of_soil);
Summary += " ";
return Summary;
}
//5snT24T24T24
//5
//snT24T24T24 ,
//sn
//T24T24T24
String ^ Struct_5snT24T24T24(String^ Ok_Average_of_air_temperature)
{
String^ Summary;
double Average_of_air_temperature = Convert::ToDouble(Ok_Average_of_air_temperature);
String^ Sign = "0";
if (Average_of_air_temperature < 0) {
Sign = "1";
Average_of_air_temperature = -Average_of_air_temperature;
}
Summary += "5";
if (Average_of_air_temperature < 1.0) Summary += Sign + "0" + "0" + Convert::ToString(Average_of_air_temperature * 10.0);
else if (Average_of_air_temperature < 10.0) Summary += Sign + "0" + Convert::ToString(Average_of_air_temperature * 10.0);
else Summary += Sign + Convert::ToString(Average_of_air_temperature * 10.0);
Summary += " ";
return Summary;
}
//52snT2T2
//52
//snT2T2 2
//sn
//T2T2
String^ Struct_52snT2T2(String^ Ok_Min_air_temperature_for_night)
{
String^ Summary;
int Min_air_temperature_for_night = Convert::ToInt32(Ok_Min_air_temperature_for_night);
String^ Sign = "0";
if (Min_air_temperature_for_night < 0) {
Sign = "1";
Min_air_temperature_for_night = -Min_air_temperature_for_night;
}
Summary += "52";
if (Min_air_temperature_for_night < 10.0) Summary += Sign + "0" + Convert::ToString(Min_air_temperature_for_night);
else Summary += Sign + Convert::ToString(Min_air_temperature_for_night);
Summary += " ";
return Summary;
}
//530f12f12
//530
//f12f12 ,
String^ Struct_530f12f12(String^ Ok_Maximum_of_wind_speed)
{
String^ Summary;
int Maximum_of_wind_speed = Convert::ToInt32(Ok_Maximum_of_wind_speed);
Summary += "530";
if (Maximum_of_wind_speed < 10)
Summary += "0" + Convert::ToString(Maximum_of_wind_speed);
else Summary += Convert::ToString(Maximum_of_wind_speed);
Summary += " ";
return Summary;
}
//7R24R24R24/
//7
//R24R24R24 ,
// / ( , , )
double Rainfall_per_day1;
double Rainfall_per_day;
String^ Struct_7R24R24R24(String^ Ok_Rainfall_per_day)
{
String^ Summary;
Rainfall_per_day1 = Convert::ToDouble(Ok_Rainfall_per_day);
Rainfall_per_day = Rainfall_per_day1;
if (Rainfall_per_day < 1)Rainfall_per_day = Rainfall_per_day * 10 + 990;
else if (Rainfall_per_day <= 989)Rainfall_per_day = (int)Rainfall_per_day;
else if (Rainfall_per_day > 989)Rainfall_per_day = 989;
Summary += "7";
if (Rainfall_per_day < 10)Summary += "00" + Convert::ToString(Rainfall_per_day);
else if (Rainfall_per_day < 100)Summary += "0" + Convert::ToString(Rainfall_per_day);
else Summary += Convert::ToString(Rainfall_per_day);
Summary += "/ ";
return Summary;
}
//88R24R24R24
//88
//R24R24R24 , 30
String^ Struct_88R24R24R24()
{
String^ Summary;
if (Rainfall_per_day1 >= 30)
{
Summary += "88";
if (Rainfall_per_day < 100)Summary += "0" + Convert::ToString(Rainfall_per_day);
else Summary += Convert::ToString(Rainfall_per_day);
Summary += " ";
}
return Summary;
}
| true |
55370303024a2fbd89dad2d9eacc7f1f6b37309a | C++ | sujeewasandeepa/HackerRank-Project-Euler-Solutions | /Problem_#79_Passcode_derivation.cpp | UTF-8 | 1,290 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
#include <cassert>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <deque>
using namespace std;
typedef long long ll;
typedef pair<double, double> dd;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
const int M = 200;
vvi g(M);
vi deg(M, -1);
int main(){
int n; cin >> n;
int letters = 0;
for(int i=0;i<n;i++){
string s; cin >> s;
int a = s[0];
int b = s[1];
int c = s[2];
if(deg[a] == -1){
deg[a] = 0;
letters++;
}
if(deg[b] == -1){
deg[b] = 1;
letters++;
}else{
deg[b]++;
}
if(deg[c] == -1){
deg[c] = 1;
letters++;
}else{
deg[c]++;
}
g[a].push_back(b);
g[b].push_back(c);
}
// Topo sort + picking min. letter
set<int> q;
for(int i=0;i<M;i++){
if(deg[i] == 0){
q.insert(i);
}
}
string ans = "";
while(!q.empty()){
char c = *q.begin();
q.erase(q.begin());
ans += c;
for(int i=0;i<g[c].size();i++){
int to = g[c][i];
deg[to]--;
if(deg[to] == 0){
q.insert(to);
}
}
}
if(ans.size() != letters){
cout << "SMTH WRONG" <<endl;
}else{
cout << ans <<endl;
}
}
| true |
be343138675b54d36fd07692c1b2abed92b7c01e | C++ | troter/xyzzy | /src/alloc.h | SHIFT_JIS | 1,871 | 2.921875 | 3 | [
"MIT"
] | permissive | // -*-C++-*-
#ifndef _alloc_h_
# define _alloc_h_
# include "cdecl.h"
/* y[WPʂŃmۂBOSɑĂOS̃蓖ĒPʂ
vAĂяoɂ̓y[WTCỸ蓖ĂB
蓖Ăꂽ̃AhX́AOS̃蓖ĒPʂɐĂ
͂B郁蓖ĒPʓ̃y[WׂĊJꂽꍇ̓
OSɕԂB蓖ĒPʂɂy[W̌BITS_PER_INTȓ
łȂȂȂB*/
class alloc_page
{
protected:
/* gp̃y[W̃Xg */
struct alloc_page_rep *ap_rep;
/* OS̃y[WTCY */
static u_int ap_page_size;
/* OS̃蓖ĒP */
static u_int ap_block_size;
/* vꂽy[WTCY(OS̃y[WEɐグ) */
u_int ap_unit_size;
/* 蓖ĒPʂƂ̃y[W̌
0̏ꍇ̓y[WƂ̊ǗɊ蓖ĒPʂ̂܂ܕԂ */
u_int ap_units_per_block;
public:
alloc_page (u_int size);
~alloc_page () {}
void *alloc ();
void free (void *);
friend class fixed_heap;
};
/* alloc_pageɌŒ蒷TCYɃTuAP[VB
̓sATCY2ׂ̂łȂȂȂB蓖Ăꂽ
q[ṽAhX̓TCY̔{ɂȂĂ͂B*/
class fixed_heap
{
protected:
alloc_page fh_ap;
struct fixed_heap_rep *fh_heap;
u_int fh_heap_size;
u_int fh_heap_per_page;
public:
fixed_heap (u_int size);
~fixed_heap () {}
void *alloc ();
void free (void *);
u_int size () const {return fh_heap_size;}
};
#endif
| true |
f5914b9d63d76ad2d98407181816fe85f354583b | C++ | joabda/ASCELOPIOS | /pmanager.h | UTF-8 | 2,031 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef PMANAGER_H
#define PMANAGER_H
#include <sqlite3.h> /* Version: 3.9.2 */
#include <stdio.h>
#include <list>
#include <vector>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/stat.h>
#include <fstream>
#include <cstring>
#include <experimental/filesystem>
#include "model/event.h"
#include "model/category.h"
#define FOLDER_NAME "kalendar"
#define DEFAULT_DATABASE_NAME "default.sql"
using namespace std;
static string dbName_ = DEFAULT_DATABASE_NAME;
class PManager
{
public:
PManager(const string& database = DEFAULT_DATABASE_NAME);
void init_db(const string& db_name);
void set_db(const string& database);
string get_db_name() const;
string get_db_folder() const;
vector<string> get_db_list() const;
bool add_event (Event* e, Event* child = nullptr);
bool replace_event (Event* old_event, Event* new_event); //return true also if old_event doesn't exist
bool remove_event(Event* e);
bool remove_db();
list<Event*> get_events_of_month(const int month, const int year) const;
list<Event*> get_events(Category* c) const;
list<Event*> get_all_events() const;
bool add_category (Category* c);
/* Note: the id will not be changed (to avoid to change the events with a reference to the category */
bool replace_category(Category* old_category, Category* new_category);
bool remove_category(Category* c);
vector<Category*> get_categories() const;
Category* get_category(const unsigned int id) const;
bool remove_past_events(const time_t& timestamp);
int save_db(string path);
int export_db_iCal_format(list<Event *> events, string path);
int load_db(const string& path);
int import_db_iCal_format(const string& path,Category* category);
~PManager();
private:
sqlite3* db_ = nullptr;
string dbPath_;
string dbFolder_;
string filterSpecialChars(string str);
bool error(const string& customMessage, char* sqlMessage, bool closeDB = false);
};
#endif // PMANAGER_H
| true |
90b93d818e94c96405d0853408b88fe29830333f | C++ | cod4i3/MyAtcoder | /ABC100_199/ABC150/c.cpp | UTF-8 | 906 | 2.53125 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
int main() {
int N;
cin >> N;
vector<int> P;
vector<int> Q;
for (int i = 0; i < N; i++) {
int p;
cin >> p;
P.push_back(p);
}
for (int i = 0; i < N; i++) {
int q;
cin >> q;
Q.push_back(q);
}
vector<int> ans;
for (int i = 0; i < N; i++) ans.push_back(i + 1);
ll pcnt = 0, qcnt = 0;
bool pflag = false, qflag = false;
ll a = 1, b = 1;
ll cnt = 0;
do {
cnt++;
for (int i = 0; i < N; i++) {
if (ans[i] == P[i]) pcnt++;
if (ans[i] == Q[i]) qcnt++;
}
if (pcnt == N) {
pflag = true;
a = cnt;
}
if (qcnt == N) {
qflag = true;
b = cnt;
}
pcnt = 0, qcnt = 0;
if (pflag && qflag) break;
} while (next_permutation(ans.begin(), ans.end()));
cout << abs(a - b) << endl;
return 0;
} | true |
c2821ce0a9237f5d27418e38b3ff5aec38128765 | C++ | DCX776113582/cTEST1 | /C++/lianxi/student.h | UTF-8 | 1,044 | 2.90625 | 3 | [] | no_license | //
// student.h
// lianxi
//
// Created by mac on 18/2/26.
// Copyright (c) 2018年 duanchuanxin. All rights reserved.
//
#ifndef __lianxi__student__
#define __lianxi__student__
#include "person.h"
/*1. 写一个学生类Student,要求从person类继承(继承方式分别从private、protected、public形式进行验证练习),增加的属性为成绩 int score;和评语 char* label(字符串);。
*/
class Student:public Person{
private:
int score;
char * label;
public:
Student(const char* _name = "",int _age = 0,int _score = 0,const char * _label = "");
void print();
};
class Student1:protected Person{
private:
int score;
char * label;
public:
Student1(const char* _name = "",int _age = 0,int _score = 0,const char * _label = "");
void print();
};
class Student2:private Person{
private:
int score;
char * label;
public:
Student2(const char* _name = "",int _age = 0,int _score = 0,const char * _label = "");
void print();
};
#endif /* defined(__lianxi__student__) */
| true |
e811e5759857ae95f4a9b730dcee61538c74e015 | C++ | SeoWJ/CodingTest | /CodingTest/15663_'N과 M (9)'.cpp | UTF-8 | 1,206 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#define endl '\n'
using namespace std;
int N, M;
vector<vector<int>> answer;
void bruteForce(vector<pair<int, bool>> natural, vector<int> seq);
int main(int argc, char* argv[]) {
ios::sync_with_stdio(false);
cin.tie(NULL);
vector<pair<int, bool>> natural;
cin >> N >> M;
for (int i = 0; i < N; i++) {
int input; cin >> input;
natural.push_back({ input, false });
}
sort(natural.begin(), natural.end());
bruteForce(natural, {});
sort(answer.begin(), answer.end());
for (unsigned int i = 0; i < answer[0].size(); i++)
cout << answer[0][i] << " ";
cout << endl;
for (unsigned int i = 1; i < answer.size(); i++) {
if (answer[i] == answer[i - 1])
continue;
else {
for (auto e : answer[i])
cout << e << " ";
cout << endl;
}
}
}
void bruteForce(vector<pair<int, bool>> natural, vector<int> seq) {
if (seq.size() == M) {
answer.push_back(seq);
return;
}
for (unsigned int i = 0; i < natural.size(); i++) {
if (natural[i].second == false) {
natural[i].second = true;
seq.push_back(natural[i].first);
bruteForce(natural, seq);
seq.pop_back();
natural[i].second = false;
}
}
} | true |
f331da233a26a6e5a1459825a7c2c153796df6a0 | C++ | TenzinBraun/TP_CPP_IUT | /TaskManager/TaskManager/TaskManager.cpp | UTF-8 | 623 | 2.796875 | 3 | [] | no_license | // TaskManager.cpp : Définit le point d'entrée pour l'application console.
//
#include "stdafx.h"
#include "TaskWarrior.h"
int main()
{
TaskWarrior taskWarrior;
taskWarrior.addTask("Manger", Date("12", "02", "13"), LOW);
taskWarrior.addTask("Dormir", Date("12", "02", "13"), URGENT);
taskWarrior.addTask("Se Doucher", Date("12", "02", "13"), MEDIUM);
taskWarrior.addTask("Faire la vaisselle", Date("12", "02", "13"), URGENT);
taskWarrior.addTask("Regarder une serie", Date("12", "02", "13"), HIGH);
taskWarrior.addTask("Ranger", Date("12", "02", "13"), LOW);
taskWarrior.completeTaskMap();
return 0;
}
| true |
443a0e47f535018214761c01d95a0dd75c55d69e | C++ | bob-young/CPPDesignPattern | /iterator.h | UTF-8 | 755 | 3.15625 | 3 | [] | no_license | //
// Created by xidian on 18-6-18.
//
#ifndef DESIGNPATTERN_ITERATOR_H
#define DESIGNPATTERN_ITERATOR_H
#include <iostream>
#include <vector>
template<class T>
class iterator {
public:
virtual bool has_next()=0;
virtual T next()=0;
};
template<class T>
class Container :public iterator<T>{
private:
int myiter;
public:
Container(){};
std::vector<T> myvec;
void add(T t){
myvec.push_back(t);
};
bool has_next();
T next();
};
template <class T>
bool Container<T>::has_next() {
if(myiter>=myvec.size())
return false;
return true;
}
template <class T>
T Container<T>::next() {
if(myiter<myvec.size())
return myvec[myiter++];
return 0;
}
#endif //DESIGNPATTERN_ITERATOR_H
| true |
9b5989d9ab388c4605e1c562c11f903f62850636 | C++ | robertpi/caffe | /windows/caffe.flat/opencvwrapper.cpp | UTF-8 | 2,966 | 2.609375 | 3 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] | permissive | #include "stdafx.h"
#pragma warning(push, 0) // disable warnings from the following external headers
#include <caffe/caffe.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#pragma warning(push, 0)
using namespace caffe; // NOLINT(build/namespaces)
using std::string;
EXPORT void *opencv_imread(char *file, int i)
{
cv::Mat img = cv::imread(file, i);
return new cv::Mat(img);
}
EXPORT void opencv_imwrite(char *file, cv::Mat* img)
{
cv::imwrite(file, *img);
}
EXPORT void opencv_split_to_input_blob(cv::Mat *img, Blob<float>* input_blob)
{
// need to read these here because of net_size, hopefully we'd fix that when all is torn apart
int width = input_blob->width();
int height = input_blob->height();
// load from the blob into the input layer in a strange way
std::vector<cv::Mat> input_channels;
float* input_data = input_blob->mutable_cpu_data();
for (int i = 0; i < input_blob->channels(); ++i) {
cv::Mat channel(height, width, CV_32FC1, input_data);
input_channels.push_back(channel);
input_data += width * height;
}
cv::split(*img, input_channels);
}
EXPORT void *opencv_matrix_convertTo(cv::Mat* target, int rtype)
{
cv::Mat *m = new cv::Mat();
target->convertTo(*m, rtype);
return m;
}
EXPORT int opencv_matrix_height(cv::Mat* target)
{
return target->size().height;
}
EXPORT int opencv_matrix_width(cv::Mat* target)
{
return target->size().width;
}
EXPORT int opencv_matrix_type(cv::Mat* target)
{
return target->type();
}
EXPORT void *opencv_matrix_new_from_scalar(int rows, int cols, int type, cv::Scalar *init_value)
{
return new cv::Mat(rows, cols, type, *init_value);
}
EXPORT void *opencv_matrix_new_from_data(int rows, int cols, int type, void *data)
{
return new cv::Mat(rows, cols, type, data);
}
EXPORT void *opencv_resize(cv::Mat *m, int width, int height)
{
cv::Mat *target = new cv::Mat();
cv::Size target_size(width, height);
cv::resize(*m, *target, target_size);
return target;
}
EXPORT void *opencv_subtract(cv::Mat *mX, cv::Mat *mY)
{
cv::Mat *mZ = new cv::Mat();
cv::subtract(*mX, *mY, *mZ);
return mZ;
}
EXPORT void *opencv_add(cv::Mat *mX, cv::Mat *mY)
{
cv::Mat *mZ = new cv::Mat();
cv::add(*mX, *mY, *mZ);
return mZ;
}
EXPORT void *opencv_merge_float_array(float *data, int num_channels, int width, int height)
{
std::vector<cv::Mat> channels;
for (int i = 0; i < num_channels; ++i) {
/* Extract an individual channel. */
cv::Mat channel(height, width, CV_32FC1, data);
channels.push_back(channel);
data += height * width;
}
/* Merge the separate channels into a single image. */
cv::Mat *mean = new cv::Mat();
cv::merge(channels, *mean);
return mean;
}
EXPORT void *opencv_mean(cv::Mat *mean)
{
cv::Scalar channel_mean = cv::mean(*mean);
return new cv::Scalar(channel_mean);
}
| true |
3615d5ddc0f7288c1b09750e0e0d6e468ce98677 | C++ | kingFighter/project-euler | /C++/22/1.cpp | UTF-8 | 1,354 | 3.25 | 3 | [] | no_license | #include<fstream>
#include<algorithm>
#include<string>
#include<iostream>
#include<cstdlib>
#include<vector>
using std::ifstream;
using std::string;
using std::vector;
void split(int, int, vector<string> &, int &);
void quickSort(int, int, vector<string> &);
int main()
{
ifstream in("names.txt");
if(in.fail())
{
std::cerr << "Open failed.\n";
exit(1);
}
string s;
vector<string> v;
while(std::getline(in, s, ','))
v.push_back(s.substr(1, s.size() - 2));
std::sort(v.begin(),v.end());
// quickSort(0, v.size() - 1, v);
long long sum = 0;
for(int i = 0; i < v.size(); i++)
{
int sumT = 0;
s = v[i];
for(int j = 0; j < s.size(); j++)
sumT += s[j] - 'A' + 1;
sum += sumT * (i + 1);
}
std::cout << sum << std::endl;
return 0;
}
void split(int low, int high, vector<string> &v, int &w)
{
string x = v[low];
int j = low;
for(int i = low + 1; i <= high; i++)
{
if(v[i] < x)
{
if (++j != i)
{
string temp = v[i];
v[i] = v[j];
v[j] = temp;
}
}
}
string temp = v[j];
v[j] = v[low];
v[low] = temp;
w = j;
}
void quickSort(int low, int high, vector<string> &v)
{
if(low < high)
{
int w = -1;
split(low, high, v, w);
quickSort(low, w - 1, v);
quickSort(w + 1, high, v);
}
}
| true |
b6e58de9cbd29eed6c665b971b62d50e91f35acb | C++ | henrikhasell/shadow-mapping | /Shadow Mapping/texture.hpp | UTF-8 | 387 | 2.671875 | 3 | [] | no_license | #ifndef TEXTURE_HPP
#define TEXTURE_HPP
#include <GL/glew.h>
#include <SDL2/SDL.h>
class Texture
{
public:
Texture();
~Texture();
bool load(const char path[]);
bool load(SDL_Surface *surface);
void colour(GLfloat r, GLfloat g, GLfloat b);
void bind(GLenum texture = GL_TEXTURE0) const;
int getW();
int getH();
private:
GLuint texture;
int w;
int h;
};
#endif // TEXTURE_HPP | true |
fec1f3a265e84db5ceb17f0038504e7de1f8fbd6 | C++ | dlakwwkd/CommitAgain | /SkimaServer/SkimaServer/Missile.h | UTF-8 | 388 | 2.59375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Unit.h"
#include "ObjectPool.h"
class Missile : public Unit, public ObjectPool<Missile>
{
public:
Missile();
virtual ~Missile();
void SetRange(float range) { m_Range = range; }
void SetLivetime(float livetime) { m_Livetime = livetime; }
void MissileShoot();
void MissileExplosion();
private:
float m_Range = 0;
float m_Livetime = 0;
};
| true |
6f028fbe6e3b79e696552d7cc9cc73f1322a119d | C++ | AraiYuhki/GLProject | /GLFrameWork/MeshSphere.cpp | SHIFT_JIS | 3,729 | 2.71875 | 3 | [] | no_license | #include <math.h>
#include "MeshSphere.h"
#include "Texture.h"
#define SUM_INDEX(X,Z) ((X+1)*(Z-1)+((X+1)*(Z+1))+(Z-1)*2)
CMeshSphere::CMeshSphere(int priority):CObject(priority)
{
_Pos = VECTOR3(0,0,0);
_Rot = VECTOR3(0,0,0);
Vtx = nullptr;
Tex = nullptr;
Nor = nullptr;
}
CMeshSphere::~CMeshSphere()
{
SafeDeletes(Vtx);
SafeDeletes(Tex);
SafeDeletes(Nor);
SafeDeletes(Index);
}
CMeshSphere* CMeshSphere::Create(VECTOR3 pos,VECTOR2 PanelNum,float radius,VECTOR2 TexDivide)
{
CMeshSphere* Field = new CMeshSphere;
if(Field == nullptr)
{
return nullptr;
}
Field->_Pos = pos;
Field->PanelNum = PanelNum;
Field->Radius = radius;
Field->TexDiv = TexDivide;
Field->Init();
return Field;
}
void CMeshSphere::Init(void)
{
IndexNum = (int)(SUM_INDEX(PanelNum.x,PanelNum.y));
VertexNum = (int)((PanelNum.x+1)*(PanelNum.y+1));
PolygonNum = (int)(((PanelNum.x*2)*PanelNum.y)+((PanelNum.y-1)*4));
Vtx = new VECTOR3[VertexNum];
Tex = new VECTOR2[VertexNum];
Nor = new VECTOR3[VertexNum];
float angle = (360.0f/PanelNum.x)*(PI/180.0f);
float angleY = (90.0f/PanelNum.y)*(PI/180.0f);
for(int LoopZ=0,num=0;LoopZ<PanelNum.y+1;LoopZ++)
{
for(int LoopX=0;LoopX<PanelNum.x+1;LoopX++)
{
if (num < VertexNum)
{
Vtx[num] = VECTOR3(cosf(angle*LoopX)*(Radius*cosf(angleY*LoopZ)),sinf(angleY*LoopZ)*Radius,sinf(angle*LoopX)*(Radius*cosf(angleY*LoopZ)));
Tex[num] = VECTOR2((TexDiv.x / PanelNum.x)*LoopX,-(TexDiv.x / PanelNum.x)*LoopZ);
Nor[num] = VECTOR3(sinf(angle*LoopX),sinf(angleY*LoopZ),cosf(angle*LoopX));
Nor[num].Normalize();
_Color = COLOR(1.0f,1.0f,1.0f,1.0f);
}
num++;
}
}
int LoopX=0;
int VtxNo = 0;
Index = new int[IndexNum];
for (int cnt = 0;cnt < IndexNum;cnt++)
{
Index[cnt] = 0;
}
for(int LoopZ=0;LoopZ<PanelNum.y;LoopZ++)
{
if(LoopZ != 0 && VtxNo < IndexNum)
{
LoopX = 0;
Index[VtxNo] = (int)((LoopZ*(PanelNum.x+1))+(((LoopX+1)%2)*(PanelNum.x+1)+(LoopX/2)));
VtxNo++;
}
for(LoopX=0;LoopX<(PanelNum.x+1)*2;LoopX++)
{
if (VtxNo < IndexNum)
{
Index[VtxNo] = (int)((LoopZ*(PanelNum.x + 1)) + (((LoopX + 1) % 2)*(PanelNum.x + 1) + (LoopX / 2)));
}
VtxNo++;
}
if(LoopZ==PanelNum.y-1)
{
break;
}
if (VtxNo < IndexNum && VtxNo > 0)
{
Index[VtxNo] = Index[VtxNo - 1];
}
VtxNo++;
}
DrawList = glGenLists(1);
glNewList(DrawList,GL_COMPILE);
glBegin(GL_TRIANGLE_STRIP);
for (int cnt = 0;cnt<IndexNum;cnt++)
{
glColor4f(_Color.r,_Color.g,_Color.b,_Color.a);
glNormal3f(Nor[Index[cnt]].x,Nor[Index[cnt]].y,Nor[Index[cnt]].z);
glTexCoord2f(Tex[Index[cnt]].x,Tex[Index[cnt]].y);
glVertex3f(Vtx[Index[cnt]].x,Vtx[Index[cnt]].y,Vtx[Index[cnt]].z);
}
glEnd();
glEndList();
}
void CMeshSphere::Uninit(void)
{
glDeleteLists(DrawList,1);
delete this;
}
void CMeshSphere::Update(void)
{
//Rot.x++;
}
void CMeshSphere::Draw(void)
{
glDisable(GL_LIGHTING);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();//r[}gbNXޔ
//`ݒ
glTranslatef(_Pos.x,_Pos.y,_Pos.z);
glRotatef(_Rot.z,0,0,1.0f);
glRotatef(_Rot.y,0,1.0f,0);
glRotatef(_Rot.x,1.0f,0,0);
glScalef(1.0f,1.0f,1.0f);
glBindTexture(GL_TEXTURE_2D,Texture.TexID);
//glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,(float*)&Material.ambient);
//glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,(float*)&Material.diffuse);
//glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,(float*)&Material.specular);
//glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,(float*)&Material.emission);
//glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,Material.shininess);
//|S`
glCallList(DrawList);
glPopMatrix();//r[}gbNX߂
glBindTexture(GL_TEXTURE_2D,0);
glEnable(GL_LIGHTING);
} | true |
e52204b55d0f83a09e176a661aa396f6d189671b | C++ | guminjin/problem | /BOJ/1707_이분그래프.cpp | UHC | 1,617 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define endl '\n'
typedef long long ll;
const int MAX = 20000 + 1;
int n, m;
vector<int> v[MAX];
int color[MAX];
bool result;
// start Ȯ
void dfs(int start, int c)
{
color[start] = c;
for (int i = 0; i < v[start].size(); i++)
{
int next = v[start][i];
// ̹ ٸ Ǿ ִٸ
if (color[next])
{
// Ȯ
// ٸ ̺ ƴϴ.
if (color[next] == color[start])
{
result = false;
return;
}
continue;
}
// Ǿ ʴٸ ش ȸ
else
{
dfs(next, c *-1);
if (!result)
return;
}
}
}
// Է
void input()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
// Ʈ̽ Է
int tc;
cin >> tc;
for (int t = 0; t < tc; t++)
{
// v color, result ʱȭ
for (int i = 0; i < MAX; i++)
{
v[i].clear();
color[i] = 0;
}
result = true;
// Է
input();
// Ȯ
for (int i = 1; i <= n; i++)
{
// 0 ƴ϶ ̹
if (color[i])
continue;
// Ȯ
dfs(i, 1);
// result false, ̺б ƴ
if (!result)
break;
}
if (result)
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}
| true |
b2f3b8af98ad53be04a8fd5cae0efcaa35a93775 | C++ | Manchas2k4/multiprocessors | /examples/02-intro-cpp/example3.cpp | UTF-8 | 1,544 | 3.1875 | 3 | [] | no_license | }// =================================================================
//
// File: example3.cpp
// Author: Pedro Perez
// Description: This file contains the code to perform the numerical
// integration of a function within a defined interval.
// The time this implementation takes will be used as
// the basis to calculate the improvement obtained with
// parallel technologies.
//
// Copyright (c) 2020 by Tecnologico de Monterrey.
// All Rights Reserved. May be reproduced for any non-commercial
// purpose.
//
// =================================================================
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include "utils.h"
const double PI = 3.14159265;
const int RECTS = 100000000; //1e8
using namespace std;
class Integration {
private:
double start, dx, result;
double (*func) (double);
public:
Integration(double a, double b, double (*fn) (double))
: func(fn) {
start = min(a, b);
dx = (max(a, b) - min(a, b)) / RECTS;
}
double getResult() const {
return result;
}
void calculate() {
result = 0;
for (int i = 0; i < RECTS; i++) {
result += func(start + (i * dx));
}
result = result * dx;
}
};
int main(int argc, char* argv[]) {
double ms;
cout << "Starting..." << endl;
ms = 0;
Integration obj(0, PI, sin);
for (int i = 0; i < N; i++) {
start_timer();
obj.calculate();
ms += stop_timer();
}
cout << "result = " << setprecision(15) << obj.getResult() << endl;
cout << "avg time = " << setprecision(15) << (ms / N) << " ms" << endl;
return 0;
}
| true |
50211a9bc71a76e71bc3ad23f3023da2f219ef99 | C++ | marshalltaylorSFE/codeblocks_cpp_projects | /VoiceUnitTest/wavegen.cpp | UTF-8 | 1,649 | 2.90625 | 3 | [] | no_license | //--------------------------------------------------------------------------------------
// Generates a single sample of a 256 sample long waveform
//
// char shape is SINESHAPE, PULSESHAPE, RAMPSHAPE, or DCSHAPE
// float duty, float amp
// char sample is 0x00 to 0xFF
//
// Shapes are ~ +-127, scaled by amp/100, then output ranged 0 to 255 (but type int)
#include "math.h"
#include "wavegen.h"
WaveGenerator::WaveGenerator( void )
{
masterAmp = 0;
rampAmp = 0;
sineAmp = 0;
pulseAmp = 0;
pulseDuty = 0;
sampleNumber = 0;
}
void WaveGenerator::resetOffset( void )
{
sampleNumber = 0;
}
uint8_t WaveGenerator::getSample( void )
{
float tempRamp = 0;
int8_t tempSine = 0;
int8_t tempPulse = 0;
uint8_t retVal;
if(rampAmp)
{
tempRamp = ((((float)sampleNumber) - 128 ) * (float)rampAmp) / 255;
}
if( sineAmp )
{
tempSine = int8_t((int16_t)(127 * sin(((float)sampleNumber * 3.141592)/128)) * sineAmp / 255);
}
if( pulseAmp )
{
//Is sample beyond duty cycle?
if ( sampleNumber < pulseDuty )
{
tempPulse = int8_t( pulseAmp >> 1 );
}
else
{
tempPulse = int8_t(pulseAmp >> 1 ) * -1;
}
}
sampleNumber++;
//cast
retVal = (((((int16_t)tempRamp + (int16_t)tempSine + (int16_t)tempPulse) / 3) * masterAmp / 255 ));
return retVal;
}
void WaveGenerator::setParameters( uint8_t masterAmpVar, uint8_t rampAmpVar, uint8_t sineAmpVar, uint8_t pulseAmpVar, uint8_t pulseDutyVar )
{
masterAmp = masterAmpVar;
rampAmp = rampAmpVar;
sineAmp = sineAmpVar;
pulseAmp = pulseAmpVar;
pulseDuty = pulseDutyVar;
}
| true |
826a4240831b4b5aa3e53900f23e6ea1e2aa2634 | C++ | kokko1990/pyrfa | /common/Timer.h | UTF-8 | 1,761 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef __SESSION_LAYER_THREADED_EXAMPLE__TIMER__H__
#define __SESSION_LAYER_THREADED_EXAMPLE__TIMER__H__
#include <list>
#define Timer_MinimumInterval 10
// A timer class; SessionClient is a derived class of CTimer and implements
// the main loop for driving the timers
// Publisher, StatManager, and Terminator classes implement CTimerClient interface
//
class CTimerClient
{
public:
CTimerClient();
virtual ~CTimerClient();
virtual void processTimer(void* pClosure) = 0;
private:
// Declared, but not implemented to prevent default behavior generated by compiler
CTimerClient( const CTimerClient & );
CTimerClient & operator=( const CTimerClient & );
};
class CTimer
{
public:
CTimer();
~CTimer();
void addTimerClient( CTimerClient &timerClient, long millisec, bool repeating, void* pClosure = 0 );
void dropTimerClient( CTimerClient &timerClient );
long nextTimer() const;
void processExpiredTimers();
private:
#ifndef WIN32
public:
#endif
struct CTime
{
long _sec;
long _millisec;
void set( long millisec );
static CTime getCurrentTime();
bool operator <= ( const CTime &two );
long operator - ( const CTime &two );
private:
CTime & setCurrentTime();
};
struct CTimerCallback
{
CTimerClient *_pTimerClient;
CTime _expirationTime;
long _millisec;
bool _repeating;
void* _pClosure;
};
typedef std::list<CTimerCallback *> _TimerCallbacks;
_TimerCallbacks _timerCallbacks;
void addTimerCallback( CTimerCallback *pCTimerCallback );
private:
// Declared, but not implemented to prevent default behavior generated by compiler
CTimer( const CTimer & );
CTimer & operator=( const CTimer & );
};
#endif // __SESSION_LAYER_THREADED_EXAMPLE__TIMER__H__
| true |
3f4e012473e647e3ec53e08d520b56513e19abc2 | C++ | CXYhh121/Data-Structure | /Bloom5_19/Bloom5_19/BitMap.h | GB18030 | 946 | 3.609375 | 4 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
using namespace std;
class BitMap
{
public:
BitMap(size_t range)
{
//5λ൱ڳ321ΪС3232õ0
_bitTable.resize((range >> 5) + 1);
}
void SetBit(size_t x)
{
size_t index = x >> 5;//5λdz32
size_t num = x % 32;
_bitTable[index] |= (1 << num);
}
void RemoveBit(size_t x)
{
size_t index = x >> 5;
size_t num = x % 32;
//~(1 << num),ӦλΪ0λΪ1֮Ӧλ0λ
_bitTable[index] &= ~(1 << num);
}
bool TestBit(size_t x)
{
size_t index = x >> 5;
size_t num = x % 32;
//λΪ11֮1ڣλΪ010
return _bitTable[index] & (1 << num);
}
size_t Size()
{
}
private:
vector<int> _bitTable;//һintС4ֽڣ32λ
};
| true |
50f3a055d99a2c6212f80aec8b20c2789bfc2462 | C++ | FacuEt/MortalKombat-TallerDeProgramacion1-2015 | /Mortal Kombat/src/model/CapaPrincipal.cpp | UTF-8 | 4,868 | 2.5625 | 3 | [] | no_license | /*
* CapaPrincipal.cpp
*
* Created on: Mar 28, 2015
* Author: root
*/
#include "CapaPrincipal.h"
#include <list>
CapaPrincipal::CapaPrincipal(float alto, float ancho, int zIndex, float anchoDeFondo,float ancho_ventana, float velocidadPrincipal, Personaje* personajeUno, Personaje* personajeDos)
:Capa(alto,ancho,zIndex, anchoDeFondo,ancho_ventana,velocidadPrincipal) //call superclass constructorPersonaje* personajeUno
{
m_Personaje = personajeUno;
m_PersonajeDos = personajeDos;
personajeUno->setDimensionesMundo(alto,ancho);
personajeDos->setDimensionesMundo(alto,ancho);
rect->x = rect->x - ancho_ventana/2;//Inicia al medio
m_velocidad_derecha = m_Personaje->getVelocidadDerecha();
m_velocidad_izquierda = m_Personaje->getVelocidadIzquierda();
m_PersonajeQueScrollea = 0;
}
CapaPrincipal::CapaPrincipal(float alto, float ancho, int zIndex, float anchoDeFondo,float ancho_ventana, float velocidadPrincipal, vector<Personaje*> personajes)
:Capa(alto,ancho,zIndex, anchoDeFondo,ancho_ventana,velocidadPrincipal) //call superclass constructorPersonaje* personajeUno
{
m_Personaje = personajes[0];
m_PersonajeDos = personajes[1];
personajes[0]->setDimensionesMundo(alto,ancho);
personajes[1]->setDimensionesMundo(alto,ancho);
rect->x = rect->x - ancho_ventana/2;//Inicia al medio
m_velocidad_derecha = m_Personaje->getVelocidadDerecha();
m_velocidad_izquierda = m_Personaje->getVelocidadIzquierda();
m_PersonajeQueScrollea = 0;
}
void CapaPrincipal::_actualizarX(){
if (rect->x < 0) rect->x = 0;
if (rect->x > rect->w) rect->x = rect->w;
}
void CapaPrincipal::Update(int scroll){
if (scroll > 0)this->Mover(true);
else if (scroll < 0) this->Mover(false);
this->_actualizarX();
if(m_PersonajeQueScrollea==2){
if (m_Personaje->getX() >= (getX() + m_ancho_ventana*0.80f)) {
m_Personaje->Update(m_PersonajeDos->getVelocidadIzquierda());
}else if (m_Personaje->getX() <= (getX() + m_ancho_ventana*0.02f) ){
m_Personaje->Update(m_PersonajeDos->getVelocidadDerecha());
}
m_Personaje->Update(scroll>0? m_PersonajeDos->getVelocidadDerecha() : m_PersonajeDos->getVelocidadIzquierda());
}else
m_Personaje->Update(0);
if(m_PersonajeDos){
if(m_PersonajeQueScrollea==1){
if (m_PersonajeDos->getX() >= (getX() + m_ancho_ventana*0.80f)) {
m_PersonajeDos->Update(m_Personaje->getVelocidadIzquierda());
}else if (m_PersonajeDos->getX() <= (getX() + m_ancho_ventana*0.02f) ){
m_PersonajeDos->Update(m_Personaje->getVelocidadDerecha());
}
else
m_PersonajeDos->Update(0);
}else{
m_PersonajeDos->Update(0);
}
}
}
void CapaPrincipal::Renderizar()
{
m_Personaje->renderizar(getX(), m_PersonajeDos->getX());
if(m_PersonajeDos){
m_PersonajeDos->renderizar(getX(), m_Personaje->getX());
}
}
int CapaPrincipal::Scrollear(){
if(getX() == 0 and (m_Personaje->getSentidoDeMovimiento() < 0))return this->CheckSegundoJugador(0);
if(getX() == rect->w and (m_Personaje->getSentidoDeMovimiento() > 0)) return this->CheckSegundoJugador(0);
if ((m_Personaje->getX() <= (getX() + m_ancho_ventana*0.02f)) and (m_Personaje->getSentidoDeMovimiento() < 0)) return this->CheckSegundoJugador(-1);
if ((m_Personaje->getX() >= (getX() + m_ancho_ventana*0.80f)) and (m_Personaje->getSentidoDeMovimiento() > 0) ) return this->CheckSegundoJugador(1);
return this->CheckSegundoJugador(0);
}
int CapaPrincipal::CheckSegundoJugador(int estadoJugador1){
if(!m_PersonajeDos){
if(estadoJugador1 == 1)
m_PersonajeQueScrollea = 1;
return estadoJugador1;
}
switch (estadoJugador1) {
case 1: if ((m_PersonajeDos->getX() <= (getX() + m_ancho_ventana*0.02f)) and (m_PersonajeDos->getSentidoDeMovimiento() < 0)){
m_PersonajeQueScrollea = 2;
return -1;
}
m_PersonajeQueScrollea = 1;
return 1;
break;
case -1:
if ((m_PersonajeDos->getX() >= (getX() + m_ancho_ventana*0.80f)) and (m_PersonajeDos->getSentidoDeMovimiento() > 0) ){
m_PersonajeQueScrollea = 2;
return 1;
}
m_PersonajeQueScrollea = 1;
return -1;
break;
default:
if(getX() == 0 and (m_PersonajeDos->getSentidoDeMovimiento() < 0))return this->_NadieScrollea();
if(getX() == rect->w and (m_PersonajeDos->getSentidoDeMovimiento() > 0)) return this->_NadieScrollea();
if ((m_PersonajeDos->getX() <= (getX() + m_ancho_ventana*0.02f)) and (m_PersonajeDos->getSentidoDeMovimiento() < 0)){
m_PersonajeQueScrollea = 2;
return -1;
}
if ((m_PersonajeDos->getX() >= (getX() + m_ancho_ventana*0.80f)) and (m_PersonajeDos->getSentidoDeMovimiento() > 0) ){
m_PersonajeQueScrollea = 2;
return 1;
}
return this->_NadieScrollea();
break;
}
}
int CapaPrincipal::_NadieScrollea(){
m_PersonajeQueScrollea = 0;
return 0;
}
CapaPrincipal::~CapaPrincipal() {
m_velocidad_derecha = 0;
m_velocidad_izquierda = 0;
m_Personaje = NULL;
if(m_PersonajeDos)
m_PersonajeDos = NULL;
}
| true |
8975b21d8b043ddbfbd5e2e8176b3194797ed743 | C++ | Sanfield/Cplusplus | /string类数据结构.cpp | ISO-8859-9 | 387 | 3.1875 | 3 | [] | no_license | //ݽṹ
#include<iostream>
using namespace std;
class String
{ private:
char* _str;
public:
String(char* str="")
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
~String()
{
delete[] _str;
_str = NULL;
}
};
void TestString
{
String s1("Hello!");
String s2;
cout << s1 << endl;
cout << s2 << endl;
}
int main()
{
TestString();
return 0;
} | true |
e90e999e1c38ee93ff6e3129fbe3299f4120603f | C++ | ccharly/constregex | /src/state.hpp | UTF-8 | 384 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef STATE_HPP__
#define STATE_HPP__
template <size_t Tid, bool Tfinal = false>
struct State {
enum {
id = Tid,
is_final = Tfinal
};
typedef
State<Tid, true>
make_final;
};
template <size_t Tid>
struct id_is {
template <typename T>
struct functor {
enum {
value = Tid == T::id
};
};
};
#endif
| true |
83ee4a8c7d7746d77161291915dcd7a41bba65da | C++ | All8Up/cpf | /Cpf/Libraries/Platform/Math/Include/Math/Detail/Quaternion.inl | UTF-8 | 4,210 | 2.859375 | 3 | [
"MIT"
] | permissive | //////////////////////////////////////////////////////////////////////////
#pragma once
#include "Math/Vector3v.hpp"
namespace CPF
{
namespace Math
{
//////////////////////////////////////////////////////////////////////////
template <typename TYPE>
Quaternion<TYPE>::Quaternion()
{}
template <typename TYPE>
Quaternion<TYPE>::Quaternion(typename TYPE::LaneType value)
: mVector(value)
{}
template <typename TYPE>
Quaternion<TYPE>::Quaternion(TYPE value)
: mVector(value)
{}
template <typename TYPE>
Quaternion<TYPE>::Quaternion(Element v0, Element v1, Element v2, Element v3)
: mVector(v0, v1, v2, v3)
{}
template <typename TYPE>
template <int I0, int I1, int I2, int I3>
constexpr Quaternion<TYPE>::Quaternion(SIMD::LaneRef_4<TYPE, I0, I1, I2, I3>& ref)
: mVector(ref)
{}
template <typename TYPE>
Quaternion<TYPE>::Quaternion(typename TYPE::Lanes_3 v012, Element w)
: mVector(v012, w)
{}
//////////////////////////////////////////////////////////////////////////
template <typename TYPE>
SIMD::LaneIndex<TYPE> CPF_VECTORCALL Quaternion<TYPE>::operator [](int idx)
{
return SIMD::LaneIndex<TYPE>(mVector, idx);
}
template <typename TYPE>
CPF_FORCE_INLINE typename Quaternion<TYPE>::Element CPF_VECTORCALL Quaternion<TYPE>::operator [](int idx) const
{
switch (idx)
{
case 0: return mVector.GetLane<0>();
case 1: return mVector.GetLane<1>();
case 2: return mVector.GetLane<2>();
case 3: return mVector.GetLane<3>();
}
CPF_ASSERT_ALWAYS;
return 0;
}
//////////////////////////////////////////////////////////////////////////
template <typename TYPE>
CPF_FORCE_INLINE Quaternion<TYPE> CPF_VECTORCALL Conjugate(Quaternion<TYPE> value)
{
return Quaternion<TYPE>(-value.xyz, value.w);
}
//////////////////////////////////////////////////////////////////////////
template <typename TYPE>
Quaternion<TYPE> CPF_VECTORCALL operator * (const Quaternion<TYPE> lhs, const Quaternion<TYPE> rhs)
{
// TODO: This can be optimized.
return Quaternion<TYPE>(
+lhs[0] * rhs[3] + lhs[1] * rhs[2] - lhs[2] * rhs[1] + lhs[3] * rhs[0],
-lhs[0] * rhs[2] + lhs[1] * rhs[3] + lhs[2] * rhs[0] + lhs[3] * rhs[1],
+lhs[0] * rhs[1] - lhs[1] * rhs[0] + lhs[2] * rhs[3] + lhs[3] * rhs[2],
-lhs[0] * rhs[0] - lhs[1] * rhs[1] - lhs[2] * rhs[2] + lhs[3] * rhs[3]
);
}
template <typename TYPE>
Vector3v<typename TYPE::Lanes_3> CPF_VECTORCALL operator * (const Quaternion<TYPE>& lhs, const Vector3v<typename TYPE::Lanes_3> rhs)
{
Vector3v<typename TYPE::Lanes_3> u(lhs.xyz);
float s = lhs.w;
return Vector3v<typename TYPE::Lanes_3>(
2 * Dot(u, rhs) * u +
(s*s - Dot(u, u)) * rhs +
2 * s * Cross(u, rhs)
);
}
//////////////////////////////////////////////////////////////////////////
template <typename TYPE>
Quaternion<TYPE> CPF_VECTORCALL Quaternion<TYPE>::Zero()
{
return Quaternion<TYPE>(Element(0), Element(0), Element(0), Element(0));
}
template <typename TYPE>
Quaternion<TYPE> CPF_VECTORCALL Quaternion<TYPE>::Identity()
{
return Quaternion<TYPE>(Element(0), Element(0), Element(0), Element(1));
}
template <typename TYPE>
template<typename ATYPE>
Quaternion<TYPE> CPF_VECTORCALL Quaternion<TYPE>::AxisAngle(ATYPE axis, Element radians)
{
const float a = radians * Element(0.5);
const float s = std::sin(a);
return Quaternion<TYPE>(typename TYPE::Lanes_3(axis * s), std::cos(a));
}
template <typename TYPE>
typename Quaternion<TYPE>::Element Dot(Quaternion<TYPE> lhs, Quaternion<TYPE> rhs)
{
return Dot(lhs.mVector, rhs.mVector);
}
template <typename TYPE>
Quaternion<TYPE> CPF_VECTORCALL Normalize(const Quaternion<TYPE> value)
{
}
template <typename TYPE>
Quaternion<TYPE> CPF_VECTORCALL Inverse(const Quaternion<TYPE> value)
{
using Element = typename Quaternion<TYPE>::Element;
Element lengthSq = Dot(value, value);
if (lengthSq > Element(0))
{
Element invLength = Element(1) / lengthSq;
Quaternion<TYPE> result = Conjugate(value) * invLength;
return result;
}
return Quaternion<TYPE>(Element(0));
}
/*
Lerp
Slerp
*/
}
}
| true |
3ad39657b5a389932a2b62e86a33f676d7c53002 | C++ | xxx1766/data_structure | /第六周/广义表.cpp | GB18030 | 4,938 | 2.984375 | 3 | [] | no_license | //
//ͷβ/ͷβ洢ṹ
typedef enum {ATOM, LIST} ElemTag;
typedef struct GLNode {
ElemTag tag; // ATOM or LIST
union { //ԭӽͱϲ
AtomType atom;
struct {struct GLNode *hp, *tp;} ptr; //ptr.hp, ptr.tpָıͷβ
}
} *Glist;
//ӱ
typedef enum {ATOM, LIST} ElemTag;
typedef struct GLNode {
ElemTag tag; // ATOM or LIST
union { //ԭӽͱϲ
AtomType atom;
struct GLNode *hp;//ָӱָ
};
struct GLNode *tp;
//ָͬһһԪؽָ
} *Glist;
//mԪʽı
typedef struct MPNode {
ElemTag tag;
int exp; //ָ
union { //ԭӽͱϲ
float coef; //ϵ
struct MPNode *hp;
};
struct MPNode *tp;//൱next
} *Mplist;
//
InitGList(&L); //յĹ
CreateGList(&L, S); //ַ
DestroyGList(&L);
//롢ɾ
InsertFirst_GL(&L, e); //eLĵһԪ
DeleteFirst_GL(&L, &e);
CopyGList(&T, L);//LƵT
//״̬
GListLength(L); GListDepth(L);
GListEmpty(L); GetHead(L); GetTail(L);
//
Traverse_GL(L, Visit());
//ַ
void CreateGList(Glist &L, SString S) {
if (!strComp(S,())) L = NULL; // ձ
else {
// ɱ
if(!(L=(Glist)malloc(sizeof(GLNode)) )) exit(OVERFLOW)
if (StrLen(S)==1){//ԭӹ
L->tag=ATOM, L->atom = S; }
else {
L->tag=List; p=L
//subΪ ȥ S Ӵ
StrSubStr(sub, S,2,StrLen(S)-1); //subһӴ
//ΪsubnӴnӱ
do { //ظnӱ
//ӱhsub=?I
Sever(sub, hsub);
//ɴhsubĹp?ptr.hp
CreateGList(p->ptr.hp, hsub);
q=p;
if (!IsStrEmpty(sub) {
//µıΪ
if(!(p=(GLNode*)malloc(sizeof(GLNode)) )) exit(OVERFLOW);
//һӱı*(p->ptr.tp)
p->tag = LIST; q->ptr.tp=p;
}
} while (!IsStrEmpty(sub));
q->ptr.tp = NULL; // βΪձ
} // else
}//else
return OK;
}
Status Sever(SString &str, SString &hstr) {
//ǿմstrָΪ֣hstrΪһ֮ǰӴstrΪ֮Ӵ
n = StrLength(str);
i=0; k=0; //k:δԵŸ
do{
++i;
StrSubStr(ch, str, i, 1); //ȡһַ
if ( ch==( ) ++k;
else ( ch==) ) --k;
}while ( i<n && (ch!=, || k!=0) );
if (i<n){ //Ż
StrSubStr(hstr, str, 1, i-1);
StrSubStr(str, str, i+1, n-i);
}
else {
StrCopy(hstr, str); StrClear(str);
}
}
//
int GlistDepth(Glist L) { //ָLָĹ
if (!L) return 1;
if (L->tag == ATOM) return 0;
for (max=0, pp=L; pp;
pp=pp->ptr.tp) { //ppptr.hpΪͷָӱ
dep = GlistDepth(pp->ptr.hp);
if (dep > max) max = dep;
}
//ǿձǸԪȵֵ1
return max + 1;
}
//ƹ
Status CopyGList(Glist &T, Glist L) {
if (!L) T = NULL; // ƿձ
else {
//
if ( !(T =(GList)malloc(sizeof(GLNode))))
exit(OVERFLOW);
T->tag = L->tag;
if (L->tag == ATOM)
T->atom = L->atom; //Ƶԭ
else {
CopyGList (T->ptr.hp, L->ptr.hp);
//L->ptr.hpT->ptr.hp
CopyGList (T->ptr.tp, L->ptr.tp);
//L->ptr.tpT->ptr.tp
}
} // else
return OK;
}
//ɾֵΪxԪ
void delete(LinkedList &L, ElemType x) {
// ɾLΪͷָĴͷĵ
// ֵΪxԪ
if (L->next) {
if (L->next->data==x) {
p=L->next; L->next=p->next;
free(p); delete(L, x);
}
else delete(L->next, x);
}
}
/*
ݽṹĶ
(Chapter5)ִ洢ʽ
Ӧѡݽṹ
(Chapter2) ӦãҪIJ ұͷ㡢ұβPǰ㣬ʣĸݽṹȽϺã
ͷĵL
ͷѭ(ͷָ)L
βָRѭ
ͷ˫ѭL
ݽṹѡȨǣԺͿά(ά۵ĸߵ)
(Chapter5)ϡӵ˳rpos飻תõĸ num cpot
ݽṹͨ
(Chapter2)ͷ
ûͼ˼
*/
| true |
6d2ebfb0af28e769a83391e59c012fcfe7b295ab | C++ | viktorstrate/MiniPlatformer | /src/Test.cpp | UTF-8 | 2,415 | 2.9375 | 3 | [] | no_license | #include "includes.h"
#include "Entity.h"
#include "InputHandler.h"
#include "Player.h"
#include "Enemy.h"
vector<CEnemy> enemies;
void createEnemy(SDL_Renderer *renderer, CPlayer *player);
int main(int argc, char* argv[]) {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event mainEvent;
double lastTime = SDL_GetTicks();
double lastTime_EnemyCreate = SDL_GetTicks();
double ticksPerSec = 60;
if(SDL_Init(SDL_INIT_EVERYTHING) != 0){
std::cout << "SDL Init Error: " << SDL_GetError() << std::endl;
} else {
std::cout << "SDL Init Success" << std::endl;
}
window = SDL_CreateWindow("Test Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
if(window == NULL){
std::cout << "SDL Window Error: " << SDL_GetError() << std::endl;
} else {
std::cout << "SDL Window created successfully" << std::endl;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if(renderer == NULL){
std::cout << "SDL Renderer Error: " << SDL_GetError() << std::endl;
} else {
std::cout << "SDL Renderer created successfully" << std::endl;
}
CInputHandler inputHandler = CInputHandler();
CPlayer player = CPlayer(renderer);
createEnemy(renderer, &player);
bool isRunning = true;
while (isRunning){
while (SDL_PollEvent(&mainEvent) != 0){
if (mainEvent.type == SDL_QUIT){
isRunning = false;
}
inputHandler.inputUpdate(mainEvent);
}
// update
if (lastTime + (1000 / ticksPerSec) < SDL_GetTicks()){
lastTime = SDL_GetTicks();
player.update(&inputHandler);
for (int i = 0; i < enemies.size(); i++){
enemies[i].update();
}
}
SDL_RenderClear(renderer);
/*for (int i = 0; i < 10; i++){
if (enemies[i].isDead == false)
enemies[i].render();
}*/
for (int i = 0; i < enemies.size(); i++){
enemies[i].render();
}
player.render();
SDL_RenderPresent(renderer);
SDL_UpdateWindowSurface(window);
// Create Enemies
if (lastTime_EnemyCreate + 3000 < SDL_GetTicks()){
lastTime_EnemyCreate = SDL_GetTicks();
createEnemy(renderer, &player);
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
void createEnemy(SDL_Renderer *renderer, CPlayer *player){
CEnemy enm = CEnemy();
enm.setupEnemy(renderer, player, 700, 480-32);
enemies.push_back(enm);
enm = CEnemy();
enm.setupEnemy(renderer, player, -100, 480 - 32);
enemies.push_back(enm);
}
| true |
4e9f418d45da75bec223c3575d1d18591c1ec706 | C++ | davidkuehner/FieldDetection | /FieldDetection/FilesTools.cpp | UTF-8 | 1,918 | 2.9375 | 3 | [] | no_license | #include "stdafx.h"
#include "FilesTools.h"
string FilesTools::SOURCE_PATH = "..\\images\\sources";
string FilesTools::OUTPUT_PATH = "..\\images\\output";
string FilesTools::TITLE = "output";
FilesTools::FilesTools(void)
{
}
FilesTools::~FilesTools(void)
{
}
Mat FilesTools::getImage(string path)
{
return imread(path);
}
vector<Mat> FilesTools::getImages(string path)
{
// read images filenames
vector<string> filenames;
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(string2wchar_t(path + "\\*.jpg"), &fd);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
if ( !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
filenames.push_back(path + "\\" + wchar_t2string(fd.cFileName));
}
while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
// create Mat list
vector<Mat> images;
for(unsigned int i = 0; i < filenames.size(); i ++)
{
string filename = filenames[i];
images.push_back(getImage(filename));
}
return images;
}
void FilesTools::showImage(Mat image, string title)
{
imshow(title, image);
}
void FilesTools::showImages(vector<Mat> images, string title)
{
for (unsigned int i = 0; i < images.size(); i ++)
imshow(title + " " + to_string(i), images[i]);
}
void FilesTools::saveImage(Mat image, string path)
{
imwrite(path, image);
}
void FilesTools::saveImages(vector<Mat> images, string path)
{
for(unsigned int i = 0; i < images.size(); i ++)
saveImage(images[i], path + "\\" + to_string(i) + ".jpg");
}
string FilesTools::wchar_t2string(const wchar_t *wchar)
{
string str = "";
int index = 0;
while(wchar[index] != 0)
{
str += (char)wchar[index];
++index;
}
return str;
}
wchar_t* FilesTools::string2wchar_t(const string &str)
{
wchar_t wchar[260];
int index = 0;
while(index < str.size())
{
wchar[index] = (wchar_t)str[index];
++index;
}
wchar[index] = 0;
return wchar;
} | true |
a3ad71c7ca00c6275ce65f649a56a79de7e78286 | C++ | lesleyping/leetcode-together | /src/offer15.numberof1/numberof1.cpp | UTF-8 | 503 | 2.921875 | 3 | [] | no_license | class Solution1 {
public:
int NumberOf1(int n) {
int count = 0;
unsigned int flag = 1;
while(flag){
if(n & flag){
count++;
}
flag = flag << 1;
}
return count;
}
};
class Solution2 {
public:
int NumberOf1(int n) {
int count = 0;
while(n){
int nn = n - 1;
n = n & nn;
count++;
}
return count;
}
}; | true |
af334ed29de41fe8128fdf0d4c855a3136c46a3e | C++ | amapyon/tdd_lifegame_cpp_sample | /src/Board.cpp | UTF-8 | 1,755 | 3.296875 | 3 | [] | no_license | #include "Board.h"
using namespace std;
Board::Board(int size) : _size{size} {
int length = (_size + 2) * (_size + 2);
// cout << "_size=" << _size << "length=" << length << endl;
_cells = new int[length];
for (int i = 0; i < length; i++ ) {
*(_cells + i) = 0;
}
}
Board::~Board() {
delete _cells;
}
string Board::toString() {
string result = "";
result += "┌";
for (int x = 0; x < _size; x++) {
result += "─";
}
result += "┐\n";
for (int y = 0; y < _size; y++) {
result += "│";
for (int x = 0; x < _size; x++) {
int offset = (x + 1) + (y + 1) * (_size + 2);
if (*(_cells + offset) == 1) {
result += "■";
} else {
result += "□";
}
}
result += "│\n";
}
result += "└";
for (int x = 0; x < _size; x++) {
result += "─";
}
result += "┘";
return result;
}
string Board::toString_() {
string result = "";
for (int y = 0; y < _size + 2; y++) {
for (int x = 0; x < _size + 2; x++) {
int offset = x + y * (_size + 2);
result += to_string(*(_cells + offset));
result += ",";
}
result += "\n";
}
return result;
}
void Board::put(const int x, const int y) {
int offset = (x + 1) + (y + 1) * (_size + 2);
*(_cells + offset) = 1;
}
Board Board::next() {
Board boardNext{_size};
Cell cell{_size, _cells};
for (int y = 0; y < _size; y++) {
for (int x = 0; x < _size; x++) {
int count = cell.count(x, y);
// cout << "x=" << x << ",y=" << y << ",count=" << count << endl;
switch (count) {
case 0:
case 1:
break;
case 2:
if (cell.value(x, y) == 1) {
boardNext.put(x, y);
}
break;
case 3:
boardNext.put(x, y);
break;
case 4:
case 5:
case 6:
case 7:
case 8:
break;
}
}
}
return boardNext;
}
| true |
b84cebdba7cee6ceaaced81f55951f2a9ca5aa13 | C++ | YanceyZhangDL/Interview_Algorithm | /recursive_fib/recursive_fib.cpp | UTF-8 | 1,004 | 3.328125 | 3 | [] | no_license | /****************************************************************
Copyright (C) 2016 Yancey Zhang. All rights reserved.
> File Name: < recursive_fib.cpp >
> Author: < Yancey Zhang >
> Mail: < yanceyzhang2013@gmail.com >
> Created Time: < 2016/08/28 >
> Last Changed:
> Description:
****************************************************************/
#include <iostream>
using namespace std;
/****************************************************************
* 计算斐波那契数列
* f(n) = f(n-1) + f(n-2)
****************************************************************/
const int N = 10;
int fib(int n, int *a)
{
if(n == 0)
return 0;
if(n == 1)
return 1;
a[n - 1] = fib(n-1, a) + fib(n-2, a);
return a[n - 1]; // 数组存的时候是n-1, 这个要特别注意
}
int main()
{
int a[N];
memset(a, -1, sizeof(a)/sizeof(int));
cout << sizeof(a) / sizeof(int) << endl;
int num = fib(N, a);
cout << num << endl;
return 0;
}
| true |
466b3fcf0a6324bb86edce2bb6008d08afa7b103 | C++ | whuCanon/sh_render | /Renderer/graphics.cpp | UTF-8 | 16,147 | 2.625 | 3 | [] | no_license | #include <fstream>
#include <opencv2/opencv.hpp>
#include "framework.h"
using namespace shr;
using namespace std;
using namespace Eigen;
map<string, Texture> Model::loaded_mesh_;
GLuint shr::createProgram(string vertexfilename, string fragmentfilename)
{
std::vector<std::tuple<std::string, GLenum>> shaders;
shaders.push_back(std::tuple<std::string, GLenum>(vertexfilename, GL_VERTEX_SHADER));
shaders.push_back(std::tuple<std::string, GLenum>(fragmentfilename, GL_FRAGMENT_SHADER));
return createProgram(shaders);
}
GLuint shr::createProgram(vector<tuple<string, GLenum>> shadernames)
{
// create program
GLuint program = glCreateProgram();
vector<GLuint> shaders;
// setup shader deletion
auto delete_shaders = [](const vector<GLuint>& shaders){
for (auto s : shaders){
glDeleteShader(s);
}
};
// setup compile error checker
auto check_compile = [](GLint shader, std::string* info)->bool{
GLint success = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE){
// get info size
GLint logsize = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logsize);
// get info
GLchar* errinfo = new GLchar[logsize];
glGetShaderInfoLog(shader, logsize, &logsize, errinfo);
*info = std::string(errinfo, errinfo + logsize);
delete[] errinfo;
return false;
}
return true;
};
// read each shader
for (auto shaderinfo : shadernames)
{
string sname = get<0>(shaderinfo);
GLenum type = get<1>(shaderinfo);
// open file stream
std::ifstream sfile(sname);
if (!sfile)
throw runtime_error("read " + sname + " failed");
// read content
std::string content;
std::string line;
while (std::getline(sfile, line))
content += line + '\n';
// create shader
GLuint shader = glCreateShader(type);
shaders.push_back(shader);
const GLchar* str = content.c_str();
glShaderSource(shader, 1, &str, nullptr);
glCompileShader(shader);
// check compile result
std::string info;
if (!check_compile(shader, &info)){
delete_shaders(shaders);
glDeleteProgram(program);
throw runtime_error("A error ocurred when compile "
+ sname + ":\n" + info);
}
// attach to program
glAttachShader(program, shader);
}
// link
glLinkProgram(program);
// clean up
delete_shaders(shaders);
return program;
}
GLuint shr::loadTexture(string filename)
{
GLuint textureID;
glGenTextures(1, &textureID);
// load image
cv::Mat img = cv::imread(filename);
int w = img.cols;
int h = img.rows;
cv::flip(img, img, 0);
// Assign texture to ID
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_BGR, GL_UNSIGNED_BYTE, img.data);
glGenerateMipmap(GL_TEXTURE_2D);
// Parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
//FreeImage_Unload(imagen);
return textureID;
}
shared_ptr<Model> shr::loadModel(string filename)
{
shared_ptr<Model> model = std::make_shared<Model>(filename);
return model;
}
Mesh::Mesh(const vector<Vertex> &v, const vector<GLuint> &i, const vector<Texture> &t)
{
vertices = v;
indices = i;
textures = t;
//this->setupMesh();
}
void Mesh::draw(GLuint program)
{
// setup materials
GLuint diffuse_count = 1;
GLuint specular_count = 1;
for (GLuint i = 0; i < textures.size(); i++){
glActiveTexture(GL_TEXTURE0 + i);
stringstream ss;
string num;
string type = textures[i].type;
if (type == "texture_diffuse")
ss << diffuse_count++;
else if (type == "texture_specular")
ss << specular_count++;
num = ss.str();
string mattype = "material." + type + num;
GLint loc = glGetUniformLocation(program, mattype.c_str());
glUniform1i(loc, i);
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
glActiveTexture(GL_TEXTURE0);
// draw
glBindVertexArray(vao_);
//glDrawArrays(GL_TRIANGLES, 0, indices_.size());
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
bool Mesh::rayHitObject(const Ray &ray)
{
vector<Vector3f> triangle;
auto i = indices.begin();
while (i != indices.end())
{
triangle.push_back(vertices[*i++].position);
triangle.push_back(vertices[*i++].position);
triangle.push_back(vertices[*i++].position);
if (ray.isIntersectsTriangle(triangle)) return true;
vector<Vector3f>().swap(triangle);
}
return false;
}
void Mesh::setupMesh()
{
// Vertex buffer object setup
glGenBuffers(1, &vbo_);
glBindBuffer(GL_ARRAY_BUFFER, vbo_);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
// Vertex array object setup
glGenVertexArrays(1, &vao_);
glBindVertexArray(vao_);
// Elememt buffer object setup
glGenBuffers(1, &ebo_);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
// position
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0);
// normal
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal));
// texture coordination
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, texcoords));
// render coeffs
switch (L)
{
case 0:
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs)));
break;
case 1:
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs)));
glEnableVertexAttribArray(3+1);
glVertexAttribPointer(3+1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs) + sizeof(float)));
break;
case 2:
for (GLuint attrib = 0; attrib < 3; attrib++){
glEnableVertexAttribArray(3+attrib);
glVertexAttribPointer(3+attrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs) + 3*attrib*sizeof(float)));
}
break;
case 3:
for (GLuint attrib = 0; attrib < 4; attrib++){
glEnableVertexAttribArray(3+attrib);
glVertexAttribPointer(3+attrib, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs) + 4*attrib*sizeof(float)));
}
break;
case 4:
for (GLuint attrib = 0; attrib < 6; attrib++){
glEnableVertexAttribArray(3+attrib);
glVertexAttribPointer(3+attrib, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs) + 4*attrib*sizeof(float)));
}
glEnableVertexAttribArray(9);
glVertexAttribPointer(9, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), \
(GLvoid*)(offsetof(Vertex, render_coeffs) + 24*sizeof(float)));
}
// detach
glBindVertexArray(0);
}
void Model::draw(GLuint program)
{
for (auto& mesh : meshes_)
mesh.draw(program);
}
void Model::loadModel(string path)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){
throw runtime_error(string("Loading model error:") + importer.GetErrorString());
return ;
}
dir_ = path.substr(0, path.find_last_of('/'));
procNode(scene->mRootNode, scene);
createPlane();
generateRenderCoeffs();
for (auto m = meshes_.begin(); m != meshes_.end(); m++)
m->setupMesh();
}
void Model::procNode(aiNode* node, const aiScene* scene)
{
// process meshes
for (GLuint i = 0; i < node->mNumMeshes; i++){
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
meshes_.push_back(procMesh(mesh, scene));
}
//--- recursively walk on node ---
for (GLuint i = 0; i < node->mNumChildren; i++)
procNode(node->mChildren[i], scene);
}
Mesh Model::procMesh(aiMesh* mesh, const aiScene* scene)
{
vector<Vertex> vertices;
vector<GLuint> indices;
vector<Texture> textures;
// process vertices
for (GLuint i = 0; i < mesh->mNumVertices; i++)
{
Vertex v;
const auto& mv = mesh->mVertices[i];
if (!mesh->mNormals)
throw runtime_error("model missing normal");
const auto& mn = mesh->mNormals[i];
v.position = Vector3f(mv.x, mv.y, mv.z);
v.normal = Vector3f(mn.x, mn.y, mn.z);
if (mesh->HasTextureCoords(0)){
const auto& mtex = mesh->mTextureCoords[0][i];
v.texcoords = Vector2f(mtex.x, mtex.y);
}
else{
v.texcoords = Vector2f::Zero();
}
vertices.push_back(v);
bound_.updateBound(v.position);
}
// process indices
for (GLuint i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (GLuint j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
// process material
if (mesh->mMaterialIndex > 0)
{
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
vector<Texture> diffuseMaps = loadMaterialTextures(material,
aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
vector<Texture> specularMaps = loadMaterialTextures(material,
aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
}
return Mesh(vertices, indices, textures);
}
vector<Texture> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName)
{
vector<Texture> textures;
for (GLuint i = 0; i < mat->GetTextureCount(type); i++)
{
aiString str;
mat->GetTexture(type, i, &str);
// find in recoreds
string texfile = str.C_Str();
auto texiter = loaded_mesh_.find(texfile);
if (texiter != loaded_mesh_.end()){
// used loaded texture
textures.push_back(texiter->second);
}
else{
Texture texture;
texture.id = loadTexture(dir_ + '/' + str.C_Str());
texture.type = typeName;
texture.path = str;
textures.push_back(texture);
loaded_mesh_[texfile] = texture;
}
}
return textures;
}
void Model::createPlane()
{
float l = bound_.length();
float w = bound_.width();
float h = bound_.height();
float x = bound_.xmin() - SCALE*h;
float y = bound_.ymin() - 10*EPSILON;
float z = bound_.zmin() - SCALE*h;
int count = sqrt(PLANE_VNUM);
float dx = (2*SCALE*h + l) / static_cast<float>(count);
float dz = (2*SCALE*h + w) / static_cast<float>(count);
vector<Vertex> vertices;
vector<GLuint> indices;
vector<Texture> textures;
for (int i = 0; i < count; i++){
for (int j = 0; j < count; j++)
{
Vertex v;
v.position = Vector3f(x+i*dx, y, z+j*dz);
v.normal = Vector3f(0, 1, 0);
v.texcoords = Vector2f(0, 0);
vertices.push_back(v);
}
}
for (int i = 0; i < count-1; i++){
for (int j = 0; j < count-1; j++)
{
indices.push_back(static_cast<GLuint>( i *count + j ));
indices.push_back(static_cast<GLuint>( i *count + (j+1) ));
indices.push_back(static_cast<GLuint>( (i+1)*count + j ));
indices.push_back(static_cast<GLuint>( (i+1)*count + j ));
indices.push_back(static_cast<GLuint>( i *count + (j+1) ));
indices.push_back(static_cast<GLuint>( (i+1)*count + (j+1) ));
}
}
bound_.setYmin(y);
meshes_.push_back(Mesh(vertices, indices, textures));
}
void Model::generateRenderCoeffs()
{
bool regenerate = false;
ifstream infile("render_coeffs.dat", ios::in | ios::binary);
if (!infile.is_open()){
cout << "Unable to open render_coeffs.dat, need a few moment to regenerate coefficients...";
regenerate = true;
}
// if already generate, just read from file
if(!regenerate)
{
for (auto m = meshes_.begin(); m != meshes_.end(); m++)
for (auto v = m->vertices.begin(); v != m->vertices.end(); v++)
infile.read((char* )v->render_coeffs, SH_NUM*sizeof(float));
infile.close();
return;
}
// regenerate render coefficients of all vertices
srand(static_cast<unsigned>(time(nullptr)));
int sqrt_num = sqrt(static_cast<double>(SAMPLE_NUM));
for (auto m = meshes_.begin(); m != meshes_.end(); m++)
{
for (auto v = m->vertices.begin(); v != m->vertices.end(); v++)
{
int real_sampled = 0;
for (int i = 0; i < SAMPLE_NUM; i++)
{
// isometric (or random) uniform sampling on sphere
double phi = 2*PI * ((0.5+i/sqrt_num) / sqrt_num);
double theta = acos(1 - 2 * ((0.5+i%sqrt_num) / sqrt_num));
// double phi = 2*PI * (rand() / double(RAND_MAX));
// double theta = PI - acos(2*(rand()/double(RAND_MAX)) - 1);
Vector3f sample = sh::ToVector(phi, theta).cast<float>();
float dot = sample.dot(v->normal);
if (dot <= 0) continue; real_sampled++;
// fill in a Ray structure for this sample and determine whether be blocked
Ray ray(v->position + EPSILON*v->normal, sample);
bool ray_blocked = isRayBlocked(ray);
// add the contribution of this sample to the coefficients
if (!ray_blocked){
for (int l = 0; l <= L; l++){
for (int m = -l; m <= l; m++){
float contrib = static_cast<float>(sh::EvalSH(l, m, phi, theta));
v->render_coeffs[sh::GetIndex(l,m)] += contrib * dot;
}
}
}
}
// rescale coeffs
for (int i = 0; i < SH_NUM; i++)
v->render_coeffs[i] *= real_sampled;
}
}
// save the coefficients to a file
ofstream outfile("render_coeffs.dat", ios::out | ios::binary | ios::trunc);
for (auto m = meshes_.begin(); m != meshes_.end(); m++)
for (auto v = m->vertices.begin(); v != m->vertices.end(); v++)
outfile.write((const char* )v->render_coeffs, SH_NUM*sizeof(float));
outfile.close();
}
bool Model::isRayBlocked(const Ray &ray)
{
for (auto m = meshes_.begin(); m != meshes_.end(); m++)
if (m->rayHitObject(ray)) return true;
return false;
}
| true |
4430f3de5abd2edfa43cad56c5a479d5fcb53642 | C++ | mohita02/Data-Structures | /33link.cpp | UTF-8 | 747 | 2.828125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
using namespace std;
#define max 6
bool IsPopOrder(int pu[],int po[],int n)
{
int flag=0;
for(int i=0;i<n;i++)
{
for(int j=n-1;j>=0;j--)
{
if(pu[i]==po[j])
{
flag=1;
}
else{
flag=0;
}
}
}
if(flag==1)
{
return true;
}
else{
return false;
}
}
int main(int argc,char* argv[])
{
int nlength;
cin>>nlength;
int push[nlength];
for(int i=0;i<nlength;i++)
{
cin>>push[i];
}
int pop[nlength];
for(int i=0;i<nlength;i++)
{
cin>>pop[i];
}
bool x=IsPopOrder(push,pop,nlength);
cout<<x;
return 0;
} | true |
ec4eac6f219533e3f41ce6480c5e4e7ea82d9043 | C++ | hongiii/aha_algorithm_practice | /4.4再解炸弹人/main.cpp | UTF-8 | 2,629 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
struct note
{
int x;
int y;
};
const int N = 51;
int sum = 0;
char a[N][N];
note nt[N*N];
int n, m, startx, starty, head, tail, book[N][N];
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int p, q;
int getnum(int x, int y)
{
int sum = 0;
int tx = x, ty = y;
while(a[tx][ty] != '#')
{
if(a[tx][ty] == 'G')
{
sum++;
}
tx++;
}
tx = x, ty = y;
while(a[tx][ty] != '#')
{
if(a[tx][ty] == 'G')
{
sum++;
}
ty++;
}
tx = x, ty = y;
while(a[tx][ty] != '#')
{
if(a[tx][ty] == 'G')
{
sum++;
}
tx--;
}
tx = x, ty = y;
while(a[tx][ty] != '#')
{
if(a[tx][ty] == 'G')
{
sum++;
}
ty--;
}
return sum;
}
void bfs(int x, int y)
{
int tx, ty;
while(head < tail)
{
for(int i = 0; i < 4; i++)
{
tx = nt[head].x + next[i][0];
ty = nt[head].y + next[i][1];
if(tx < 1 || tx > n || ty < 1 || ty > m)
continue;
if(a[tx][ty] == '.' && book[tx][ty] == 0)
{
// printf("%d--%d\n", tx, ty);
nt[tail].x = tx;
nt[tail].y = ty;
tail++;
book[tx][ty] = 1;
int num = getnum(tx, ty);
if(sum < num)
{
sum = num;
// printf("--%d--\n", sum);
p = tx;
q = ty;
}
}
}
head++;
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &startx, &starty);
for(int i = 0; i < n; i++)
scanf("%s", a[i]);
memset(book, 0, sizeof(0));
// for(int i = 0; i < n; i++)
// {
// for(int j = 0; j < m; j++)
// printf("%c", a[i][j]);
// printf("\n");
// }
head = tail = 0;
p = nt[tail].x = startx;
q = nt[tail].y = starty;
tail++;
book[startx][starty] = 1;
sum = getnum(startx, starty);
bfs(startx, starty);
printf("%d %d %d\n", sum, p, q);
return 0;
}
/*
13 13 3 3
#############
#GG.GGG#GGG.#
###.#G#G#G#G#
#.......#..G#
#G#.###.#G#G#
#GG.GGG.#.GG#
#G#.#G#.#.#.#
##G...G.....#
#G#.#G###.#G#
#...G#GGG.GG#
#G#.#G#G#.#G#
#GG.GGG#G.GG#
#############
*/
| true |
d657d681c7e3fe1a3d728ef711ffe12c08efacad | C++ | NatiTew/graderHansaEditByNatiTew | /problems/sut/temp/sut-posnDAY1/buu02-sms.cpp | UTF-8 | 1,255 | 2.796875 | 3 | [
"MIT"
] | permissive | /*
TASK: SMS
LANG: C
AUTHOR: Napat Hataivichian
CENTER: BUU
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char dat[3][3][5],str[100];
int i,n,m,cou,num,r,c,h,v,len,ind;
dat[0][0][0] = '\0';
strcpy(dat[0][1],"ABC");
strcpy(dat[0][2],"DEF");
strcpy(dat[1][0],"GHI");
strcpy(dat[1][1],"JKL");
strcpy(dat[1][2],"MNO");
strcpy(dat[2][0],"PQRS");
strcpy(dat[2][1],"TUV");
strcpy(dat[2][2],"WXYZ");
str[0] = '\0';
scanf("%d",&n);
scanf("%d %d",&num,&cou);
switch(num){
case 1 : r=0;c=0;break;
case 2 : r=0;c=1;break;
case 3 : r=0;c=2;break;
case 4 : r=1;c=0;break;
case 5 : r=1;c=1;break;
case 6 : r=1;c=2;break;
case 7 : r=2;c=0;break;
case 8 : r=2;c=1;break;
case 9 : r=2;c=2;break;
}
len = strlen(dat[r][c]);
ind = 0;
if(len > 0){
str[0] = (dat[r][c][(cou-1)%len]);
ind++;
}
for(m=0;m<(n-1);m++){
scanf("%d %d %d",&h,&v,&cou);
r += v;
c += h;
len = strlen(dat[r][c]);
if(len > 0){
str[ind] = (dat[r][c][(cou-1)%len]);
ind++;
}else{
for(i=0;i<cou;i++){
if(ind > 0){
str[ind-1] = '\0';
ind--;
}else break;
}
}
}
str[ind] = '\0';
if(str[0] != '\0')
printf("%s\n",str);
else printf("null\n");
return 0;
}
| true |
9b354c5bfb51cc492a968fe3cdbb0c57b582152d | C++ | catch4/yisoo | /week_3/level2_[3차]n진수-게임.cpp | UTF-8 | 1,295 | 3.84375 | 4 | [] | no_license | #include <string>
#include <vector>
// 프로그래머스 level2_[3차]n진수-게임
using namespace std;
// 1. 구해야할 문자열 길이 : t*m
// 2. n진수를 구하여 문자열에 계속 추가. 만약 문자열 길이가 t*m보다 같거나 길어질 때까지 n진수 반복.
// 3. 2번에서 구한 문자열을 t*m에 맞게 자르기
// 4. 인덱스 p-1부터 문자열의 길이까지 m씩 증가하며 추가하기.
// 10이상이면 A~F
char giveAlpha(int num){
if(num>=10)
return num-10+'A';
return num+'0';
}
// n진수 구하기
string calNum(int n, int number){
string ret= "";
if(number==0)
return "0";
while(number>0){
int remain = number % n;
ret = giveAlpha(remain)+ret;
number /= n;
}
return ret;
}
// t*m에 해당하는 문자열 구하는 함수.
string giveString(int n, int size){
string ret ="";
int idx =0;
while(ret.length()<size){
ret += calNum(n, idx);
idx++;
}
ret = ret.substr(0,size); // 문자열 t*m만큼 자르기.
return ret;
}
string solution(int n, int t, int m, int p) {
string answer = "";
string temp = giveString(n, t*m);
for(int i =p-1;i<temp.length();i+=m){
answer += temp[i];
}
return answer;
} | true |
7917d3dc6f4e464aacb4320925d5c5e39319f576 | C++ | omerfarukabaci/Appointment-Simulation | /CivilRegistry.cpp | UTF-8 | 567 | 2.765625 | 3 | [] | no_license | #include "CivilRegistry.h"
#include <iostream>
CivilRegistry::CivilRegistry() {
//there's no need to do anything in here.
}
void CivilRegistry::insertCitizen(Citizen *givenCitizen) {
if (givenCitizen->getHasApp())
wApp.push_back(givenCitizen);
else
wOutApp.push_back(givenCitizen);
}
void CivilRegistry::removeCitizen(int listSel) {
if (listSel == 0) {
std::cout << wApp.front()->getName() << std::endl;
wApp.pop_front();
}
else if (listSel == 1) {
std::cout << wOutApp.front()->getName() << std::endl;
wOutApp.pop_front();
}
else
return;
} | true |
e47f3de3b125e82a759bf5f1bb599edd53057f82 | C++ | Beisenbek/kbtu-2018-fall-lecture-samples | /pp1/Wednesday/week11/2.cpp | UTF-8 | 459 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<map>
using namespace std;
int main(){
map<string, int> m;
pair<string, int> p2 = make_pair("orange", 6);
pair<string, int> p1 = make_pair("apple", 5);
m.insert(p1);
m.insert(p2);
m.insert(make_pair("potato", 6));
m["onion"] = 5;
map<string, int> :: iterator it;
for(it = m.begin(); it != m.end(); it++){
cout << (*it).first << " " << (*it).second << endl;
}
return 0;
}
| true |
465e90ca6ca5c0a61553bf64e780f7a9053749b0 | C++ | adenprince/azure-kinect-data-collection | /interface.cpp | UTF-8 | 15,329 | 2.578125 | 3 | [] | no_license | /* Aden Prince
* HiMER Lab at U. of Illinois, Chicago
* Azure Kinect Data Collection
*
* interface.cpp
* Contains functions for getting program settings and displaying program usage.
*
* Body tracking 3D viewer code obtained from: https://github.com/microsoft/Azure-Kinect-Samples/blob/master/body-tracking-samples/simple_3d_viewer/main.cpp
*/
#include <fstream>
#include <Window3dWrapper.h>
#include "imgui_dx11.h"
#include "imgui_internal.h"
#include "3DViewer.h"
// Print command-line argument usage to the command line
void PrintUsage() {
printf("\nUSAGE: AzureKinectDataCollection.exe SensorMode[NFOV_UNBINNED, WFOV_BINNED](optional) RuntimeMode[CPU](optional)\n");
printf(" - SensorMode: \n");
printf(" NFOV_UNBINNED (default) - Narrow Field of View Unbinned Mode [Resolution: 640x576; FOI: 75 degree x 65 degree]\n");
printf(" WFOV_BINNED - Wide Field of View Binned Mode [Resolution: 512x512; FOI: 120 degree x 120 degree]\n");
printf(" - RuntimeMode: \n");
printf(" CPU - Use the CPU only mode. It runs on machines without a GPU but it will be much slower\n");
printf(" OFFLINE - Play a specified file. Does not require Kinect device\n");
printf(" OUTPUT - Write angle information to a specified file in CSV format\n");
printf("e.g. AzureKinectDataCollection.exe WFOV_BINNED CPU\n");
printf("e.g. AzureKinectDataCollection.exe CPU\n");
printf("e.g. AzureKinectDataCollection.exe WFOV_BINNED\n");
printf("e.g. AzureKinectDataCollection.exe OFFLINE MyFile.mkv\n");
printf("e.g. AzureKinectDataCollection.exe OUTPUT output.csv\n");
}
// Print 3D viewer window controls to the command line
void PrintAppUsage() {
printf("\n");
printf(" Basic Navigation:\n\n");
printf(" Rotate: Rotate the camera by moving the mouse while holding mouse left button\n");
printf(" Pan: Translate the scene by holding Ctrl key and drag the scene with mouse left button\n");
printf(" Zoom in/out: Move closer/farther away from the scene center by scrolling the mouse scroll wheel\n");
printf(" Select Center: Center the scene based on a detected joint by right clicking the joint with mouse\n");
printf("\n");
printf(" Key Shortcuts\n\n");
printf(" ESC: quit\n");
printf(" h: help\n");
printf(" b: body visualization mode\n");
printf(" k: 3d window layout\n");
printf("\n");
}
// Check if a file exists with the passed filename
bool fileExists(std::string filename) {
std::ifstream inputFile;
inputFile.open(filename);
bool isOpen = inputFile.is_open();
inputFile.close();
return isOpen;
}
// Get the first unused indexed output filename
std::string getIndexedFilename() {
int fileIndex = 1;
std::string curFilename = "output1.csv";
// Run until an unused indexed output filename is found or the file index is too high
while(fileExists(curFilename) && fileIndex < INT_MAX) {
fileIndex++;
curFilename = "output" + std::to_string(fileIndex) + ".csv";
}
// Check if the maximum number of numbered output files has been reached
if(fileIndex == INT_MAX && fileExists(curFilename)) {
std::string errorText = "Maximum number of indexed output files used.";
printf("%s\n", errorText.c_str());
MessageBoxA(0, errorText.c_str(), NULL, MB_OK | MB_ICONHAND);
exit(1);
}
return curFilename;
}
// Create and handle startup GUI widgets
int startupGUIWidgets(InputSettings& inputSettings, std::string& errorText) {
// 0: Continue running startup GUI, 1: Start data collection, -1: Quit program
int startCollection = 0;
const char* depth_modes[] = {"NFOV_2X2BINNED", "NFOV_UNBINNED", "WFOV_2X2BINNED", "WFOV_UNBINNED"};
static int depth_mode_index = 1; // Default depth mode is NFOV_UNBINNED
const char* frame_rates[] = {"30", "15", "5"};
static int frame_rate_index = 0; // Default target frame rate is 30 FPS
static bool cpu_mode = false;
static bool offline_mode = false;
static bool run_for_time = false;
static bool empty_lines = false;
static float run_time = 0.0f;
static char input_filename[128] = "";
static char output_filename[128] = "";
// Disable depth mode and frame rate input if collecting data from file
if(offline_mode) {
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f);
}
ImGui::Combo("Depth camera mode", &depth_mode_index, depth_modes, IM_ARRAYSIZE(depth_modes));
ImGui::Combo("Target frame rate", &frame_rate_index, frame_rates, IM_ARRAYSIZE(frame_rates));
if(offline_mode) {
ImGui::PopItemFlag();
ImGui::PopStyleVar();
}
ImGui::Checkbox("CPU mode", &cpu_mode);
ImGui::Checkbox("Collect data from file", &offline_mode);
ImGui::Checkbox("Run for set time", &run_for_time);
ImGui::Checkbox("Record lines without body data", &empty_lines);
// Disable seconds to run text input if not running for a set time
if(!run_for_time) {
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f);
}
ImGui::InputFloat("Seconds to run", &run_time);
if(!run_for_time) {
ImGui::PopItemFlag();
ImGui::PopStyleVar();
}
// Disable input filename text input if not collecting data from file
if(!offline_mode) {
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f);
}
ImGui::InputText("Input filename (.mkv)", input_filename, IM_ARRAYSIZE(input_filename));
if(!offline_mode) {
ImGui::PopItemFlag();
ImGui::PopStyleVar();
}
// Check if the output filename in input settings and the text input do not match
if(strcmp(output_filename, inputSettings.OutputFileName.c_str()) != 0) {
// Copy the default output filename to the GUI once
strcpy_s(output_filename, inputSettings.OutputFileName.c_str());
}
ImGui::InputText("Output filename", output_filename, IM_ARRAYSIZE(output_filename));
// Update output filename in input settings
inputSettings.OutputFileName = output_filename;
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ImColor::HSV(0.4f, 0.6f, 0.6f)));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(ImColor::HSV(0.4f, 0.7f, 0.7f)));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(ImColor::HSV(0.4f, 0.8f, 0.8f)));
if(ImGui::Button("Start")) {
// Reset error text
errorText = "";
inputSettings.CpuOnlyMode = cpu_mode;
inputSettings.Offline = offline_mode;
inputSettings.InputFileName = input_filename;
inputSettings.EmptyLines = empty_lines;
if(run_for_time) {
inputSettings.RunTime = (int) (run_time * 1000.0f);
}
if(depth_mode_index == 0) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_NFOV_2X2BINNED;
}
// No check for index 1 because depth mode is NFOV_UNBINNED by default
else if(depth_mode_index == 2) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_WFOV_2X2BINNED;
}
else if(depth_mode_index == 3) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_WFOV_UNBINNED;
}
// No check for index 0 because target frame rate is 30 FPS by default
if(frame_rate_index == 1) {
inputSettings.FrameRate = K4A_FRAMES_PER_SECOND_15;
}
else if(frame_rate_index == 2) {
inputSettings.FrameRate = K4A_FRAMES_PER_SECOND_5;
}
// 1 is returned and data collection starts if there are no errors
startCollection = 1;
// Check for errors
if(inputSettings.DepthCameraMode == K4A_DEPTH_MODE_WFOV_UNBINNED &&
inputSettings.FrameRate == K4A_FRAMES_PER_SECOND_30) {
errorText += "ERROR: WFOV_UNBINNED depth mode requires a lower frame rate\n";
startCollection = 0;
}
if(run_for_time && inputSettings.RunTime < 0) {
errorText += "ERROR: Run time cannot be negative\n";
startCollection = 0;
}
if(offline_mode && !fileExists(inputSettings.InputFileName)) {
errorText += "ERROR: Input file \"" + inputSettings.InputFileName + "\" does not exist\n";
startCollection = 0;
}
// Check if there are no non-space characters in the output filename
if(inputSettings.OutputFileName.find_first_not_of(' ') == std::string::npos) {
errorText += "ERROR: Output filename is empty\n";
startCollection = 0;
}
if(fileExists(inputSettings.OutputFileName)) {
errorText += "ERROR: Output file \"" + inputSettings.OutputFileName + "\" already exists\n";
startCollection = 0;
}
}
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(ImColor::HSV(0.0f, 0.6f, 0.6f)));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(ImColor::HSV(0.0f, 0.7f, 0.7f)));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(ImColor::HSV(0.0f, 0.8f, 0.8f)));
if(ImGui::Button("Quit")) {
startCollection = -1; // Quit program
}
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.3f, 0.0f, 1.0f));
ImGui::TextWrapped(errorText.c_str());
// Remove style settings
ImGui::PopStyleColor(7);
// Return whether the program should continue running the GUI, start data collection, or quit
return startCollection;
}
// Set input settings from a GUI
bool runStartupGUI(InputSettings& inputSettings) {
// 0: Continue running startup GUI, 1: Start data collection, -1: Quit program
int startCollection = 0;
std::string errorText = "";
inputSettings.OutputFileName = getIndexedFilename();
// Correct font scaling
if(!glfwInit()) {
std::string errorText = "GLFW failed to initialize.";
printf("%s\n", errorText.c_str());
MessageBoxA(0, errorText.c_str(), NULL, MB_OK | MB_ICONHAND);
exit(EXIT_FAILURE);
}
// Create application window
WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("Program Settings"), NULL};
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Program Settings"), WS_OVERLAPPEDWINDOW, 100, 100, 720, 520, NULL, NULL, wc.hInstance, NULL);
initImGui(wc, hwnd);
// Get main configuration and I/O between application and ImGui
ImGuiIO& io = ImGui::GetIO(); (void) io;
// Our state
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
// Run until the window is closed or Quit is clicked
while(msg.message != WM_QUIT && startCollection == 0) {
// Poll and handle messages (inputs, window resize, etc.)
if(::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Make next ImGui window fill OS window
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(io.DisplaySize);
// Open startup GUI
ImGui::Begin("Settings", (bool*) 0, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize);
startCollection = startupGUIWidgets(inputSettings, errorText);
ImGui::End();
// Render
ImGui::Render();
g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*) &clear_color);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // Present with vsync
//g_pSwapChain->Present(0, 0); // Present without vsync
}
// Cleanup
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
// Stop program if the window was closed or Quit was clicked
if(msg.message == WM_QUIT || startCollection == -1) {
return false;
}
// Empty message queue
while(::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) != 0) {}
return true;
}
// Set input settings from command-line arguments
bool ParseInputSettingsFromArg(int argc, char** argv, InputSettings& inputSettings) {
for(int i = 1; i < argc; i++) {
std::string inputArg(argv[i]);
if(inputArg == std::string("NFOV_BINNED")) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_NFOV_2X2BINNED;
}
else if(inputArg == std::string("NFOV_UNBINNED")) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_NFOV_UNBINNED;
}
else if(inputArg == std::string("WFOV_BINNED")) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_WFOV_2X2BINNED;
}
else if(inputArg == std::string("WFOV_UNBINNED")) {
inputSettings.DepthCameraMode = K4A_DEPTH_MODE_WFOV_UNBINNED;
}
else if(inputArg == std::string("30_FPS")) {
inputSettings.FrameRate = K4A_FRAMES_PER_SECOND_30;
}
else if(inputArg == std::string("15_FPS")) {
inputSettings.FrameRate = K4A_FRAMES_PER_SECOND_15;
}
else if(inputArg == std::string("5_FPS")) {
inputSettings.FrameRate = K4A_FRAMES_PER_SECOND_5;
}
else if(inputArg.substr(0, 9) == std::string("RUN_TIME=")) {
float runTime = stof(inputArg.substr(9, inputArg.size() - 9));
inputSettings.RunTime = (int) (runTime * 1000.0f);
}
else if(inputArg == std::string("CPU")) {
inputSettings.CpuOnlyMode = true;
}
else if(inputArg == std::string("OFFLINE")) {
inputSettings.Offline = true;
if(i < argc - 1) {
// Take the next argument after OFFLINE as input file name
inputSettings.InputFileName = argv[i + 1];
i++;
}
else {
return false;
}
}
else if(inputArg == std::string("OUTPUT")) {
if(i < argc - 1) {
// Take the next argument after OUTPUT as output file name
inputSettings.OutputFileName = argv[i + 1];
i++;
}
else {
return false;
}
}
else {
printf("Error command not understood: %s\n", inputArg.c_str());
return false;
}
}
// Set output filename to default if not specified
if(inputSettings.OutputFileName == "") {
inputSettings.OutputFileName = getIndexedFilename();
}
// Check if output file already exists
else if(fileExists(inputSettings.OutputFileName)) {
printf("File %s already exists.\n", inputSettings.OutputFileName.c_str());
return false;
}
return true;
} | true |
c3a5d65e3d42e51c7cca23f1dacb65658af459e4 | C++ | naoyat/topcoder | /lib/making/21.cc | UTF-8 | 4,591 | 3.15625 | 3 | [] | no_license | //#include <stack>
#include <vector> // ベクタ、というか配列というか
#include <set> // 集合
#include <map> // ハッシュ
#include <iostream>
/*
typedef vector<int> vi;
typedef vector<vi> vvi;
#define sz(a) int((a).size())
typedef pair<int,int> ii;
#define pb push_back
#define all(c) c.begin(),c.end()
#define tr(container,it) \
for(typeof(container.begin()) it=container.begin(); it!=container.end(); it++)
*/
#include "dump.cc"
using namespace std;
/*
vector<int> emptyVector()
{
vector<int> v;
return v;
}
*/
void learn_vector()
{
vector<int> N;
vector< vector<int> > CorrectDefinition;
// vector<vector<int>> WrongDefinition;
vector<int> v1(10);
cout << v1.size() << endl;
for(int i=0; i<10; i++) v1[i] = (i+1) * (i+1);
for(int i=9; i>0; i--) v1[i] -= v1[i-1];
// vector<int> v2 = emptyVector();
// cout << "size() = " << v2.size() << ", empty() = " << v2.empty() << endl;
// non-empty は !v.empty() みたいに調べる。size()は必ずしもO(1)ではない
vector<int> v3[10]; // これは vector<int>[10] な型
// cout << v3.size() << endl;
vector<int> c(50,1); // [1,1,1,1,1,...,1]
// 次の2つは同じ
cout << c[5] << endl;
cout << c.at(5) << endl;
vector<int> a(10,1);
dump_vector(a); // [1,1,1,1,1,1,1,1,1,1]
a.push_back(2);
dump_vector(a); // [1,1,1,1,1,1,1,1,1,1,<2>]
a.resize(15);
dump_vector(a); // [1,1,1,1,1,1,1,1,1,1,2,0,0,0,0]
for (int i=0; i<7; i++) a.pop_back();
dump_vector(a); // [1,1,1,1,1,1,1,1]
cout << a.size() << endl; // must show 8
cout << a.back() << endl; // returns 1=a[7], but dont remove
cout << a.size() << endl; // must show 8
a.clear();
cout << a.size() << endl; // must show 0
dump_vector(a); // [ ]
vector<int> b(10,1); // [1,1,1,1,1,1,1,1,1,1]
b.push_back(2); // [1,1,1,1,1,1,1,1,1,1,<2>]
b.resize(15); // [1,1,1,1,1,1,1,1,1,1,2,0,0,0,0]
// cout << b.at(9) << "," << b.at(10) << "," << b.at(11) << endl; // 1,2,0
dump_vector(b);
// sort(&b[0], &b[15]);
sort(b.begin(), b.end());
// => [0,0,0,0,1,1,1,1,1,1,1,1,1,1,2]
//cout << b.at(9) << "," << b.at(10) << "," << b.at(11) << endl; // 1,1,1
dump_vector(b);
}
/*
// less_than operatorを定義する
bool operator<(const MyStruct &a, const MyStruct &b)
{
// return true if A<B; false if A>=B
}
*/
//#include <pair>
void learn_pair()
{
int N,x,y;
vector< pair<int,int> > a;
cin >> N;
for (int i=0; i<N; i++) {
cin >> x >> y;
a.push_back( make_pair(x,y) );
// a.push_back(pair<int,int>(x,y));
}
dump_vector_of_pair(a);
sort(a.begin(), a.end()); // first then second
dump_vector_of_pair(a);
}
void learn_set()
{
set<int> a;
a.insert(2);
a.insert(7);
a.insert(2);
a.insert(5);
a.insert(3);
dump_set(a); // [2,3,5,7]
a.erase(5); // remove integer 5 if exists
dump_set(a); // [2,3,7]
if (a.find(7) != a.end())
cout << "7 found." << endl; // Integer 7 exists in the set
else
cout << "7 not found." << endl; // Integer 7 does not exist in the set
set<int> b, un, in, di;
b.insert(1); b.insert(3); b.insert(5); b.insert(7); b.insert(9);
dump_set(a); // [ 2, 3, 7 ]
dump_set(b); // [ 1, 3, 5, 7, 9 ]
set_union( a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(un,un.begin()) );
dump_set(un); // [ 1, 2, 3, 5, 7, 9 ]
set_intersection( a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(in,in.begin()) );
dump_set(in); // [ 3, 7 ]
set_difference( a.begin(), a.end(), b.begin(), b.end(), insert_iterator<set<int> >(di,di.begin()) );
dump_set(di); // [ 2 ]
a.clear();
dump_set(a); // [ ]
cout << "Conversions:" << endl;
vector<int> v0(3);
v0[0] = 9; v0[1] = 4; v0[2] = 1; //= { 9, 4, 1 };
dump_vector(v0);
set<int> s0(v0.begin(), v0.end()); // vector --> set
dump_set(s0);
}
void doit(const int &t) { cout << t << endl; }
void learn_map()
{
map<string,int> a;
a["New York"] = 7;
a["Los Angeles"] = 8;
a["Boston"] = 10;
a["Los Angeles"] = 3;
dump_map(a);
cout << a["Los Angeles"] << endl; // prints 3
cout << a["San Francisco"] << endl; // prints 0
dump_map(a); // SFが追加されている
/*
set<int> u;
map<string,string> v;
for (set<int>::iterator i=u.begin(); i!=u.end(); i++) {
cout << *i << endl;
}
for (map<string,string>::iterator i=v.begin(); i!=v.end(); i++) {
cout << i->first << " => " << i->second << endl;
}
*/
set<int> b;
b.insert(3); b.insert(2); b.insert(2);
for_each(b.begin(), b.end(), doit);
}
int main()
{
// learn_vector();
// learn_pair();
// learn_set();
learn_map();
}
| true |
11ab1389bf174d08a2cce01b1c03c513f946f4c6 | C++ | zingkg/renamer-cpp | /Common/Common.cpp | UTF-8 | 330 | 2.625 | 3 | [
"MIT"
] | permissive | #include "Common.hpp"
#include <sstream>
std::string Common::toString(const std::size_t num) {
std::ostringstream sStream;
sStream << num;
return sStream.str();
}
std::int64_t Common::parseInt(const char* string) {
std::istringstream sStream(string);
std::int64_t num;
sStream >> num;
return num;
}
| true |
22840395e50605fad3feecdf52094397eb80500c | C++ | dradgun/firstweb | /homework/L5_9.cpp | UTF-8 | 601 | 3.875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int Min(int V1, int V2);
int Max(int V1, int V2);
int main()
{
int Value1, Value2;
cout << "Enter first number : ";
cin >> Value1;
cout << "Enter second number : ";
cin >> Value2;
cout << "Max value : " << Max(Value1,Value2) << endl;
cout << "Min value : " << Min(Value1,Value2) << endl;
return(0);
}
int Min(int V1, int V2)
{
if (V1 < V2) return(V1);
else return(V2);
}
int Max(int V1, int V2)
{
if (V1 > V2) return(V1);
else return(V2);
} | true |
18fceec2a384c685bf27db09a8aacf5a3cbf4cb6 | C++ | Gurkirand/lidar | /src/slam/types/Quaternion.cpp | UTF-8 | 1,269 | 3.0625 | 3 | [] | no_license | #include "../../../include/slam/types/Quaternion.h"
#include <cmath>
namespace slam
{
Quaternion::Quaternion() {}
Quaternion::Quaternion(float x, float y, float z, float w)
: x(x), y(y), z(z), w(w) {}
Quaternion make_quaternion_ypr(float yaw, float pitch, float roll)
{
float sinYaw = sin(yaw / 2);
float cosYaw = cos(yaw / 2);
float sinPitch = sin(pitch / 2);
float cosPitch = cos(pitch / 2);
float sinRoll = sin(roll / 2);
float cosRoll = cos(roll / 2);
return Quaternion(cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw,
cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw,
sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw,
cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw);
}
Quaternion make_quaternion_rpy(float roll, float pitch, float yaw)
{
float sinRoll = sin(roll / 2);
float cosRoll = cos(roll / 2);
float sinPitch = sin(pitch / 2);
float cosPitch = cos(pitch / 2);
float sinYaw = sin(yaw / 2);
float cosYaw = cos(yaw / 2);
return Quaternion(sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw,
cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw,
cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw,
cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw);
}
}
| true |
e97088123bcd61a71dd0d381f74533e8b4d549ff | C++ | enterstudio/sport-programming | /LightOJ/Contests/BdOI Training Contest 2/L.cpp | UTF-8 | 767 | 2.59375 | 3 | [] | no_license | // In the name of Allah, Most Gracious, Most Merciful
// Neighbor House (II)
// dp
// AC (402)
#include <cstdio>
#include <cstring>
#include <algorithm>
#define SET(c) memset(c, -1, sizeof(c))
using namespace std;
int H[1005];
int M[1005][2];
int ans(int n, int i, int x, int l) {
if(l >= n-1)
return 0;
int &r = M[i][x];
if(r == -1) {
r = 0;
if(x == 0)
r = max(r, ans(n, (i+1)%n, 1, l+1)+H[i%n]);
r = max(r, ans(n, (i+1)%n, 0, l+1));
}
return r;
}
int main() {
int T, no = 1;
scanf("%d", &T);
while(T--) {
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i)
scanf("%d", &H[i]);
int r = 0;
for(int i = 0; i < n; ++i) {
SET(M);
r = max(r, ans(n, (i+1)%n, 1, 1)+H[i]);
}
printf("Case %d: %d\n", no++, r);
}
return 0;
}
| true |
cfaec84e0c7724cf3c4b6f80279e90a2dd0a2392 | C++ | PYBPYB/OJ_ShuiTi | /c++语言文件/1206.cpp | UTF-8 | 328 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<iterator>
using namespace std;
int main()
{
for(int i = 50; i<100;i++)
{
int T = i*i;
int a,b,c,d;
a = T / 1000;
b = (T /100)%10;
c = (T / 10)%10;
d = T%10;
if(a == b && c == d)cout<<T<<endl;;
}
return 0;
}
| true |
079f9188f8d75b74eec612aa1159f57eb39afe23 | C++ | headhsu2568/codejam | /NCTUcourses/MP/lab10/main.cpp | UTF-8 | 4,379 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
struct position_t
{
int width;
int height;
int diff;
};
int frame_width = 1024;
int frame_height = 1024;
int body_width = 32;
int body_height = 32;
int* h_frame = NULL;
int* h_body = NULL;
int* h_diff = NULL;
position_t* h_position = NULL;
int* d_frame = NULL;
int* d_body = NULL;
int* d_diff = NULL;
position_t* d_position = NULL;
unsigned int seed = 0x1234567;
//timespec start_time;
//timespec end_time;
void body_track(int* frame, int frame_width, int frame_height,
int* body, int body_width, int body_height, int* diff, position_t* pos)
{
for(int i = 0; i < (frame_height-body_height+1); i++)
{
for(int j = 0; j < (frame_width-body_width+1); j++)
{
int* sub_frame = frame + i*frame_width + j;
int total_diff = 0;
for(int k = 0; k < body_height; k++)
{
for(int l = 0; l < body_width; l++)
{
int diff = sub_frame[k*frame_width+l] - body[k*body_width+l];
diff = diff < 0 ? diff * -1 : diff;
total_diff += diff;
}
}
diff[i*frame_width+j] = total_diff;
if(total_diff < pos->diff)
{
pos->diff = total_diff;
pos->height = i;
pos->width = j;
pos->diff = total_diff;
}
}
}
};
unsigned int myrand(unsigned int *seed, unsigned int input)
{
*seed ^= (*seed << 13) ^ (*seed >> 15) + input;
*seed += (*seed << 17) ^ (*seed >> 14) ^ input;
return *seed;
};
void sig_check()
{
unsigned int sig = 0x1234567;
for(int i = 0; i < frame_height; i++)
for(int j = 0; j < frame_width; j++)
myrand(&sig, h_diff[i*frame_width+j]);
//myrand(&sig, h_position->height);
//myrand(&sig, h_position->width);
printf("Computed check sum signature:0x%08x\n", sig);
if(sig == 0x17dd3971)
printf("Result check by signature successful!!\n");
else
printf("Result check by signature failed!!\n");
}
void show_array(int* array, int width, int height)
{
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
printf("%03d, ", array[i*width+j]);
printf("\n");
}
printf("\n");
}
int main (int argc, char *argv[])
{
// Allocate input vectors h_A and h_B in host memory
h_frame = (int*)malloc(frame_width*frame_height*sizeof(int));
h_body = (int*)malloc(body_width*body_height*sizeof(int));
h_diff = (int*)malloc(frame_width*frame_height*sizeof(int));
h_position = (position_t*)malloc(sizeof(position_t));
assert(h_frame);
assert(h_body);
assert(h_diff);
assert(h_position);
// initial frame, body, diff
for(int i = 0; i < frame_height; i++)
for(int j = 0; j < frame_width; j++)
{
h_frame[i*frame_width+j] = myrand(&seed, i*j) & 0xff;
h_diff[i*frame_width+j] = 0;
}
for(int i = 0; i < body_height; i++)
for(int j = 0; j < body_width; j++)
{
h_body[i*body_width+j] = myrand(&seed, i*j) & 0xff;
}
h_position->width = -1;
h_position->height = -1;
h_position->diff = 0x7fffffff;
//clock_gettime(CLOCK_REALTIME, &start_time);
body_track(h_frame, frame_width, frame_height, h_body, body_width, body_height, h_diff, h_position);
//clock_gettime(CLOCK_REALTIME, &end_time);
printf("position(%d,%d):%d\n", h_position->width, h_position->height, h_position->diff);
//printf("sizeof(start_time.tv_sec):%d, sizeof(start_time.tv_nsec):%d\n", sizeof(start_time.tv_sec), sizeof(start_time.tv_nsec));
//printf("s_time.tv_sec:%d, s_time.tv_nsec:%d\n", start_time.tv_sec, start_time.tv_nsec);
//printf("e_time.tv_sec:%d, e_time.tv_nsec:%d\n", end_time.tv_sec, end_time.tv_nsec);
//double execution_time = (double)end_time.tv_sec + (double)end_time.tv_nsec/1000000000.0
// - (double)start_time.tv_sec - (double)start_time.tv_nsec/1000000000.0;
//printf("diff_time:%.4f(s)\n", execution_time);
//show_array(h_frame, frame_width, frame_height);
//show_array(h_body, body_width, body_height);
//show_array(h_diff, frame_width, frame_height);
sig_check();
return 0;
}
| true |
66fa8eae908a64a5938ca651fef02aaa52413204 | C++ | cookyt/huffman-encoder | /util/util.cc | UTF-8 | 276 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <cstdlib>
#include "util/util.h"
FILE *sfopen(const char *path, const char *mode)
{
FILE *fil = fopen(path, mode);
if (fil == NULL)
{
fprintf(stderr, "Cannot open file '%s' with mode '%s'\n", path, mode);
exit(1);
}
return fil;
}
| true |
74e3c68030c4e49a2b370d9dde92d10e5265ed38 | C++ | robharris249/CSC8501-Maze | /CSC8501 Resit/CSC8501.cpp | UTF-8 | 1,726 | 3.03125 | 3 | [] | no_license | #include "Maze.h"
#include <iostream>
#include <Windows.h>
void move(Maze* m);
int main() {
Maze* m = new Maze();
bool exitReached = false;
m->loadMaze();
m->findNearestCoin();
bool keyPressFlag = true;
while (m->coins.size() > 0) {
if (GetKeyState(VK_SPACE) & 0x8000) {//if Spacebar has been pressed
if (keyPressFlag) {//this is to ensure code runs only once per sapce bar press
move(m);
std::cout << "Player Health = " << m->playerHealth << std::endl;
keyPressFlag = false;
}
} else {
keyPressFlag = true;
}
}
m->pathFinding();
while (!exitReached) {
if (GetKeyState(VK_SPACE) & 0x8000) {//if Spacebar has been pressed
if (keyPressFlag) {//this is to ensure code runs only once per sapce bar press
move(m);
std::cout << "Player Health = " << m->playerHealth << std::endl;
keyPressFlag = false;
}
} else {
keyPressFlag = true;
}
if (m->player == m->entrance) {
exitReached = true;
}
}
std::cout << "Player Health = " << m->playerHealth << std::endl;
return 0;
}
static void move(Maze* m) {
m->player.first = m->path[1]->x;
m->player.second = m->path[1]->y;
m->maze[m->path[1]->y][m->path[1]->x] = 'P';
m->maze[m->path[0]->y][m->path[0]->x] = ' ';
m->path.erase(m->path.begin());
m->printMaze();
m->playerHealth--;
if (m->coins.size() != 0) {
if (m->path.size() < 2) {
m->playerHealth += 11;
for (unsigned int i = 0; i < m->coins.size(); i++) {
if (m->coins[i].first == m->player.first && m->coins[i].second == m->player.second) {//remove taken coin from list
m->coins.erase(m->coins.begin() + i);
}
}
m->path.erase(m->path.begin());
if (m->coins.size() != 0) {
m->findNearestCoin();
}
}
}
} | true |
d802dd2fbbaed9151be7ffe5d1ccd09b827c0933 | C++ | kyuri09/boj-answer | /src/b9019.cpp | UTF-8 | 1,761 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int t;
char how[10001];
int from[10001];
int dist[10001];
bool visited[10001];
char cmd[] = { 'D','S','L','R' };
void print(int num1, int num2)
{
if (num1 == num2) return;
print(num1, from[num2]);
cout << how[num2];
}
int main(void)
{
cin >> t;
while (t--)
{
int n1, n2;
cin >> n1 >> n2;
for (int i = 0; i < 10001; i++)
{
visited[i] = false;
}
queue<int> q;
q.push(n1);
dist[n1] = 0;
visited[n1] = true;
while (!q.empty())
{
int now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
if (cmd[i] == 'D')
{
int next = (now * 2) % 10000;
if (visited[next] == false)
{
q.push(next);
visited[next] = true;
how[next] = cmd[i];
from[next] = now;
dist[next] = dist[now] + 1;
}
}
else if (cmd[i] == 'S')
{
int next = now - 1;
if (visited[next] == false)
{
if (now == 0) next = 9999;
q.push(next);
visited[next] = true;
how[next] = cmd[i];
from[next] = now;
dist[next] = dist[now] + 1;
}
}
else if (cmd[i] == 'L')
{
int next = ((now % 1000) * 10) + (now / 1000);
if (visited[next] == false)
{
q.push(next);
visited[next] = true;
how[next] = cmd[i];
from[next] = now;
dist[next] = dist[now] + 1;
}
}
else if (cmd[i] == 'R')
{
int next = (now / 10) + ((now % 10) * 1000);
if (visited[next] == false)
{
q.push(next);
visited[next] = true;
how[next] = cmd[i];
from[next] = now;
dist[next] = dist[now] + 1;
}
}
}
}
print(n1, n2);
cout << endl;
}
return 0;
} | true |
c2f95570f8d7fc4d1d9352b6a70e8f258efbbb55 | C++ | pengHappy/Peking-University-Online-Judgement | /BigMult(Same len).cpp | UTF-8 | 1,341 | 3.03125 | 3 | [] | no_license | #include <stdio.h>
#include <memory.h>
#define MAX_L 30
char a[MAX_L], b[MAX_L];
int c[MAX_L * 2];
int len;
void init() {
char a_holder[MAX_L], b_holder[MAX_L];
memset(a, '\0', sizeof(a));
memset(b, '\0', sizeof(b));
for(int i = 0; i < MAX_L * 2; i++)
c[i] = 0;
scanf("%s", a_holder);
scanf("%s", b_holder);
len = 0;
while(a_holder[len] != '\0')
len++;
for(int i = len - 1, k = 0; i >= 0; i--, k++) {
a[k] = a_holder[i];
b[k] = b_holder[i];
}
}
void calculate() {
int i, k, j;
for(k = 0; k < len; k++) {
for(i = 0; i < len; i++) {
int item1 = b[k] - '0';
int item2 = a[i] - '0';
c[i + k] += item1 * item2;
}
}
int fromPrev = c[0] / 10;
for(j = 1; j <= 2*len - 1; j++) {
int thisRes = c[j] % 10;
int toNext = c[j] / 10;
thisRes += fromPrev;
if(thisRes >= 10) {
thisRes %= 10;
toNext += 1;
}
c[j] = thisRes;
fromPrev = toNext;
}
c[0] = c[0] % 10;
}
int main()
{
init();
calculate();
for(int i = 2*len - 1; i >= 0; i--) {
if((c[i] == 0) && (i == 2*len - 1))
continue;
printf("%d", c[i]);
}
return 0;
}
| true |
7f8bb6449bc17abbe5664f3dd657d2cea7f3bd96 | C++ | HPunktOchs/RayTracer | /RayTracerV2/Glass.h | UTF-8 | 482 | 2.953125 | 3 | [] | no_license | #ifndef __GLASS_H__
#define __GLASS_H__
#include "Material.h"
class Glass : public Material {
private:
double refractiveIndex;
double shininess;
public:
Glass::Glass(double refrIndex, double shininess) {
this->refractiveIndex = refrIndex;
this->shininess = shininess;
}
Color Glass::getColor() {
return Color(0.0, 0.0, 0.0);
}
double Glass::getRefractiveIndex() {
return refractiveIndex;
}
double Glass::getShininess() {
return shininess;
}
};
#endif
| true |
43f49fbb289f6f6899aecad7d022fac2fdbb334c | C++ | dbowker/othello | /findBestMove.cpp | UTF-8 | 2,361 | 2.921875 | 3 | [] | no_license | /*
* File: findBestMove.cpp
* Author: dan bowker
* Project: othello
*
* Returns an array of possible moves for the color specified, The array is
* passed in as pVM (pointer_ValidMoves)
*
* Created on February 8, 2012, 5:10 PM
*/
#include "othello.h"
#include <sys/time.h>
int findBestMove(Communicator comm, char origB[BS], char color, int depth) {
int wallClockTime;
int processorTime;
int boardCount;
int possibleMoves[BS];
int scores[BS];
int totalWorkRequests = 0;
int i;
int resultScores[BS];
int resultCount[BS];
char logBuffer[200];
struct timeval startTime, endTime;
gettimeofday(&startTime, NULL);
WorkRequest* wReq;// = new WorkRequest();
validMoves(origB, color, possibleMoves, scores);
// seed the system - push all current valid moves onto the queue one at a time
cout << "Ready to process possible moves.\n";
wReq = new WorkRequest();
processorTime = 0;
boardCount = 0;
wallClockTime = 0;
for (int whichPossibleMove=0; possibleMoves[whichPossibleMove]; whichPossibleMove++) {
strncpy(wReq->b,origB,BS);
wReq->color = color;
wReq->depth = depth;
wReq->history[1] = 0;
resultScores[possibleMoves[whichPossibleMove]] = 0;
resultCount[possibleMoves[whichPossibleMove]] = 0;
wReq->history[0] = possibleMoves[whichPossibleMove];
processRequest(comm, wReq, totalWorkRequests, resultScores, resultCount);
cout << comm.rank << "\tDone processing " << possibleMoves[whichPossibleMove] << endl;
}
delete wReq;
gettimeofday(&endTime, NULL);
int elapsed = elapsedTime(&endTime, &startTime);
logIt(elapsed);
cout << "*********************************************" << endl;
cout << "*** all done processing possible moves **" << endl;
cout << "*********************************************" << endl;
cout << "requests sent: " << totalWorkRequests << endl;
double bestValue = -9.0e100;
int bestPosition = 0;
for (i=0; possibleMoves[i]; i++) {
int move = possibleMoves[i];
double finalScore = (double)resultScores[move] / (double)resultCount[move];
cout << "Position " << move << " final score: " << finalScore << " (" << resultScores[move] << "/" << resultCount[move] << ")" << endl;
if (bestValue < finalScore) {
bestValue = finalScore;
bestPosition = move;
}
}
cout << "best position appears to be " << bestPosition << endl;
return bestPosition;
}
| true |
64aa2e5baa9f1941f58442ef25b02844af92a93e | C++ | 2shaar2059/PurePursuitSim | /include/WayPoint.h | UTF-8 | 958 | 2.734375 | 3 | [] | no_license | #pragma once
#include "CoordinatePoint.h"
#include <string>
class WayPoint {
private: CoordinatePoint point;
double curvatureAtPoint;
double TargetVelocityAtPoint;
double DistanceAlongPathAtPoint;
public:
WayPoint(CoordinatePoint p1);
WayPoint(double x, double y);
CoordinatePoint getPoint();
double distanceTo(WayPoint wp);
void setPoint(CoordinatePoint point);
double getCurvatureAtPoint();
void setCurvatureAtPoint(double curvatureAtPoint);
double getTargetVelocityAtPoint();
void setTargetVelocityAtPoint(double targetVelocityAtPoint);
double getDistanceAlongPathAtPoint();
void setDistanceAlongPathAtPoint(double distanceAlongPathAtPoint);
bool operator==(WayPoint wayPoint);
bool operator!=(WayPoint wayPoint);
WayPoint operator/(double scale);
WayPoint operator*(double scale);
WayPoint operator+(WayPoint wayPoint);
WayPoint operator-(WayPoint wayPoint);
WayPoint getNormalized();
std::string toString();
}; | true |
67bbc3c56c92e83ee030c29477b6af8a651faa31 | C++ | Anonymous-inception/c- | /13-VolumeOfCube.cpp | UTF-8 | 296 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
int main(int argc, char const *argv[])
{
double edge, volume;
std::cout << "Enter the edge length of the cube : ";
std::cin >> edge;
volume = pow(edge, 3);
std::cout << "The volume of the cube = " << volume << std::endl;
return 0;
}
| true |
21364fcac7169c672e52fc905e1edb2d03d06296 | C++ | yzq986/cntt2016-hw1 | /TC-SRM-553-div1-250/yyt16384.cpp | UTF-8 | 1,356 | 3.546875 | 4 | [] | no_license | #include <stack>
#include <vector>
class Suminator {
public:
int findMissing(std::vector<int> program, int wantedResult);
private:
long long getResult(const std::vector<int> &a);
};
int Suminator::findMissing(std::vector<int> program, int wantedResult)
{
int pos = -1;
for (int i = 0; i < (int)program.size(); i++) {
if (program[i] == -1) {
pos = i;
break;
}
}
std::vector<int> c = program;
// Try changing it into 0
c[pos] = 0;
if (getResult(c) == wantedResult) {
return 0;
}
// Try changing it into 1
c[pos] = 1;
long long s1 = getResult(c);
if (s1 == wantedResult) {
return 1;
}
if (wantedResult < s1) {
// Cannot make the answer smaller
return -1;
}
c[pos] = 2;
long long s2 = getResult(c);
if (s1 == s2) {
// Answer is independent of x
return -1;
} else {
return wantedResult - s1 + 1;
}
}
long long Suminator::getResult(const std::vector<int> &a)
{
std::stack<long long> s;
for (auto x : a) {
if (x == 0) {
if (s.size() >= 2) {
long long w = s.top();
s.pop();
s.top() += w;
}
} else {
s.push(x);
}
}
return s.empty() ? 0 : s.top();
}
| true |
7039b178ce10ee36b0e61b696d4b6cb3b996c6fd | C++ | guidoreina/classes | /util/red_black_tree.h | UTF-8 | 20,366 | 3.109375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef UTIL_RED_BLACK_TREE_H
#define UTIL_RED_BLACK_TREE_H
// Implementation of the Red-Black-Tree algorithm of the book:
// "Introduction to Algorithms", by Cormen, Leiserson, Rivest and Stein.
#include <stdlib.h>
#include <stdint.h>
#include <memory>
#include "util/minus.h"
namespace util {
template<typename _Key,
typename _Value,
typename _Compare = util::minus<_Key> >
class red_black_tree {
private:
typedef uint8_t color_t;
struct node {
_Key key;
_Value value;
color_t color;
node* left;
node* right;
node* p;
// Constructor.
node();
node(const _Key& k, const _Value& v);
};
public:
class iterator {
friend class red_black_tree;
public:
_Key* first;
_Value* second;
private:
node* _M_node;
};
class const_iterator {
friend class red_black_tree;
public:
const _Key* first;
const _Value* second;
private:
const node* _M_node;
};
// Constructor.
red_black_tree();
red_black_tree(const _Compare& comp);
red_black_tree(red_black_tree&& other);
// Destructor.
~red_black_tree();
// Clear.
void clear();
// Get number of elements.
size_t count() const;
// Insert.
bool insert(const _Key& key, const _Value& value);
// Erase.
bool erase(iterator& it);
bool erase(const _Key& key);
// Find.
bool find(const _Key& key, iterator& it);
bool find(const _Key& key, const_iterator& it) const;
// Begin.
bool begin(iterator& it);
bool begin(const_iterator& it) const;
// End.
bool end(iterator& it);
bool end(const_iterator& it) const;
// Previous.
bool prev(iterator& it);
bool prev(const_iterator& it) const;
// Next.
bool next(iterator& it);
bool next(const_iterator& it) const;
private:
enum {
kRed = 0,
kBlack = 1
};
static node _M_nil;
node* _M_root;
#if HAVE_FREE_LIST
node* _M_free;
#endif // HAVE_FREE_LIST
size_t _M_count;
_Compare _M_comp;
// Search.
node* search(const _Key& key);
const node* search(const _Key& key) const;
// Minimum.
node* minimum(node* x);
const node* minimum(const node* x) const;
// Maximum.
node* maximum(node* x);
const node* maximum(const node* x) const;
// Predecessor.
node* predecessor(node* x);
const node* predecessor(const node* x) const;
// Successor.
node* successor(node* x);
const node* successor(const node* x) const;
// Left rotate.
void left_rotate(node* x);
// Right rotate.
void right_rotate(node* x);
// Insert fixup.
void insert_fixup(node* z);
// Transplant.
void transplant(node* u, node* v);
// Delete fixup.
void delete_fixup(node* x);
// Create node.
node* create(const _Key& key, const _Value& value);
#if HAVE_FREE_LIST
// Add node to free list.
void add_free_list(node* node);
#endif // HAVE_FREE_LIST
// Erase subtree.
void erase_subtree(node* node);
// Get nil.
static node* nil();
// Disable copy constructor and assignment operator.
red_black_tree(const red_black_tree&) = delete;
red_black_tree& operator=(const red_black_tree&) = delete;
};
template<typename _Key, typename _Value, typename _Compare>
typename red_black_tree<_Key, _Value, _Compare>::node
red_black_tree<_Key, _Value, _Compare>::_M_nil;
template<typename _Key, typename _Value, typename _Compare>
inline red_black_tree<_Key, _Value, _Compare>::node::node()
: color(kBlack)
{
}
template<typename _Key, typename _Value, typename _Compare>
inline red_black_tree<_Key, _Value, _Compare>::node::node(const _Key& k,
const _Value& v)
: key(k),
value(v)
{
}
template<typename _Key, typename _Value, typename _Compare>
inline
red_black_tree<_Key, _Value, _Compare>::red_black_tree()
: _M_root(nil()),
#if HAVE_FREE_LIST
_M_free(NULL),
#endif // HAVE_FREE_LIST
_M_count(0),
_M_comp()
{
}
template<typename _Key, typename _Value, typename _Compare>
inline
red_black_tree<_Key, _Value, _Compare>::red_black_tree(const _Compare& comp)
: _M_root(nil()),
#if HAVE_FREE_LIST
_M_free(NULL),
#endif // HAVE_FREE_LIST
_M_count(0),
_M_comp(comp)
{
}
template<typename _Key, typename _Value, typename _Compare>
inline
red_black_tree<_Key, _Value, _Compare>::red_black_tree(red_black_tree&& other)
{
_M_root = other._M_root;
#if HAVE_FREE_LIST
_M_free = other._M_free;
#endif // HAVE_FREE_LIST
_M_count = other._M_count;
_M_comp = other._M_comp;
other._M_root = nil();
other._M_free = NULL;
}
template<typename _Key, typename _Value, typename _Compare>
inline red_black_tree<_Key, _Value, _Compare>::~red_black_tree()
{
clear();
}
template<typename _Key, typename _Value, typename _Compare>
void red_black_tree<_Key, _Value, _Compare>::clear()
{
if (_M_root != nil()) {
erase_subtree(_M_root);
_M_root = nil();
}
#if HAVE_FREE_LIST
while (_M_free) {
node* next = _M_free->left;
delete _M_free;
_M_free = next;
}
#endif // HAVE_FREE_LIST
_M_count = 0;
}
template<typename _Key, typename _Value, typename _Compare>
inline size_t red_black_tree<_Key, _Value, _Compare>::count() const
{
return _M_count;
}
template<typename _Key, typename _Value, typename _Compare>
bool red_black_tree<_Key, _Value, _Compare>::insert(const _Key& key,
const _Value& value)
{
node* z;
if ((z = create(key, value)) == NULL) {
return false;
}
node* y = nil();
node* x = _M_root;
while (x != nil()) {
y = x;
if (_M_comp(z->key, x->key) < 0) {
x = x->left;
} else {
x = x->right;
}
}
z->p = y;
if (y == nil()) {
_M_root = z;
} else if (_M_comp(z->key, y->key) < 0) {
y->left = z;
} else {
y->right = z;
}
z->left = nil();
z->right = nil();
z->color = kRed;
insert_fixup(z);
_M_count++;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
bool red_black_tree<_Key, _Value, _Compare>::erase(iterator& it)
{
node* z = it._M_node;
it._M_node = successor(z);
node* x;
node* y = z;
color_t ycolor = y->color;
if (z->left == nil()) {
x = z->right;
transplant(z, z->right);
} else if (z->right == nil()) {
x = z->left;
transplant(z, z->left);
} else {
y = minimum(z->right);
ycolor = y->color;
x = y->right;
if (y->p == z) {
x->p = y;
} else {
transplant(y, y->right);
y->right = z->right;
y->right->p = y;
}
transplant(z, y);
y->left = z->left;
y->left->p = y;
y->color = z->color;
}
if (ycolor == kBlack) {
delete_fixup(x);
}
_M_count--;
#if HAVE_FREE_LIST
// Call destructor.
z->~node();
add_free_list(z);
#else
delete z;
#endif
if (it._M_node == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool red_black_tree<_Key, _Value, _Compare>::erase(const _Key& key)
{
iterator it;
if ((it._M_node = search(key)) == nil()) {
return false;
}
erase(it);
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool red_black_tree<_Key, _Value, _Compare>::find(const _Key& key,
iterator& it)
{
if ((it._M_node = search(key)) == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool
red_black_tree<_Key, _Value, _Compare>::find(const _Key& key,
const_iterator& it) const
{
if ((it._M_node = search(key)) == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool red_black_tree<_Key, _Value, _Compare>::begin(iterator& it)
{
if (_M_root == nil()) {
return false;
}
it._M_node = minimum(_M_root);
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool
red_black_tree<_Key, _Value, _Compare>::begin(const_iterator& it) const
{
if (_M_root == nil()) {
return false;
}
it._M_node = minimum(_M_root);
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool red_black_tree<_Key, _Value, _Compare>::end(iterator& it)
{
if (_M_root == nil()) {
return false;
}
it._M_node = maximum(_M_root);
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool
red_black_tree<_Key, _Value, _Compare>::end(const_iterator& it) const
{
if (_M_root == nil()) {
return false;
}
it._M_node = maximum(_M_root);
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool red_black_tree<_Key, _Value, _Compare>::prev(iterator& it)
{
if ((it._M_node = predecessor(it._M_node)) == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool
red_black_tree<_Key, _Value, _Compare>::prev(const_iterator& it) const
{
if ((it._M_node = predecessor(it._M_node)) == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool red_black_tree<_Key, _Value, _Compare>::next(iterator& it)
{
if ((it._M_node = successor(it._M_node)) == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline bool
red_black_tree<_Key, _Value, _Compare>::next(const_iterator& it) const
{
if ((it._M_node = successor(it._M_node)) == nil()) {
return false;
}
it.first = &it._M_node->key;
it.second = &it._M_node->value;
return true;
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::search(const _Key& key)
{
return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>(
const_cast<const red_black_tree<_Key, _Value, _Compare>&>(
*this
).search(key)
);
}
template<typename _Key, typename _Value, typename _Compare>
const typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::search(const _Key& key) const
{
const node* x = _M_root;
while (x != nil()) {
int ret;
if ((ret = _M_comp(key, x->key)) < 0) {
x = x->left;
} else if (ret == 0) {
return x;
} else {
x = x->right;
}
}
return nil();
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::minimum(node* x)
{
return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>(
const_cast<const red_black_tree<_Key, _Value, _Compare>&>(
*this
).minimum(x)
);
}
template<typename _Key, typename _Value, typename _Compare>
inline const typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::minimum(const node* x) const
{
while (x->left != nil()) {
x = x->left;
}
return x;
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::maximum(node* x)
{
return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>(
const_cast<const red_black_tree<_Key, _Value, _Compare>&>(
*this
).maximum(x)
);
}
template<typename _Key, typename _Value, typename _Compare>
inline const typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::maximum(const node* x) const
{
while (x->right != nil()) {
x = x->right;
}
return x;
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::predecessor(node* x)
{
return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>(
const_cast<const red_black_tree<_Key, _Value, _Compare>&>(
*this
).predecessor(x)
);
}
template<typename _Key, typename _Value, typename _Compare>
const typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::predecessor(const node* x) const
{
if (x->left != nil()) {
return maximum(x->left);
}
const node* y = x->p;
while ((y != nil()) && (x == y->left)) {
x = y;
y = y->p;
}
return y;
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::successor(node* x)
{
return const_cast<red_black_tree<_Key, _Value, _Compare>::node*>(
const_cast<const red_black_tree<_Key, _Value, _Compare>&>(
*this
).successor(x)
);
}
template<typename _Key, typename _Value, typename _Compare>
const typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::successor(const node* x) const
{
if (x->right != nil()) {
return minimum(x->right);
}
const node* y = x->p;
while ((y != nil()) && (x == y->right)) {
x = y;
y = y->p;
}
return y;
}
template<typename _Key, typename _Value, typename _Compare>
void red_black_tree<_Key, _Value, _Compare>::left_rotate(node* x)
{
node* y = x->right;
x->right = y->left;
if (y->left != nil()) {
y->left->p = x;
}
y->p = x->p;
if (x->p == nil()) {
_M_root = y;
} else if (x == x->p->left) {
x->p->left = y;
} else {
x->p->right = y;
}
y->left = x;
x->p = y;
}
template<typename _Key, typename _Value, typename _Compare>
void red_black_tree<_Key, _Value, _Compare>::right_rotate(node* x)
{
node* y = x->left;
x->left = y->right;
if (y->right != nil()) {
y->right->p = x;
}
y->p = x->p;
if (x->p == nil()) {
_M_root = y;
} else if (x == x->p->right) {
x->p->right = y;
} else {
x->p->left = y;
}
y->right = x;
x->p = y;
}
template<typename _Key, typename _Value, typename _Compare>
void red_black_tree<_Key, _Value, _Compare>::insert_fixup(node* z)
{
while (z->p->color == kRed) {
if (z->p == z->p->p->left) {
node* y = z->p->p->right;
if (y->color == kRed) {
z->p->color = kBlack;
y->color = kBlack;
z->p->p->color = kRed;
z = z->p->p;
} else {
if (z == z->p->right) {
z = z->p;
left_rotate(z);
}
z->p->color = kBlack;
z->p->p->color = kRed;
right_rotate(z->p->p);
}
} else {
node* y = z->p->p->left;
if (y->color == kRed) {
z->p->color = kBlack;
y->color = kBlack;
z->p->p->color = kRed;
z = z->p->p;
} else {
if (z == z->p->left) {
z = z->p;
right_rotate(z);
}
z->p->color = kBlack;
z->p->p->color = kRed;
left_rotate(z->p->p);
}
}
}
_M_root->color = kBlack;
}
template<typename _Key, typename _Value, typename _Compare>
inline void red_black_tree<_Key, _Value, _Compare>::transplant(node* u,
node* v)
{
if (u->p == nil()) {
_M_root = v;
} else if (u == u->p->left) {
u->p->left = v;
} else {
u->p->right = v;
}
v->p = u->p;
}
template<typename _Key, typename _Value, typename _Compare>
void red_black_tree<_Key, _Value, _Compare>::delete_fixup(node* x)
{
while ((x != _M_root) && (x->color == kBlack)) {
if (x == x->p->left) {
node* w = x->p->right;
if (w->color == kRed) {
w->color = kBlack;
x->p->color = kRed;
left_rotate(x->p);
w = x->p->right;
}
if ((w->left->color == kBlack) && (w->right->color == kBlack)) {
w->color = kRed;
x = x->p;
} else {
if (w->right->color == kBlack) {
w->left->color = kBlack;
w->color = kRed;
right_rotate(w);
w = x->p->right;
}
w->color = x->p->color;
x->p->color = kBlack;
w->right->color = kBlack;
left_rotate(x->p);
x = _M_root;
}
} else {
node* w = x->p->left;
if (w->color == kRed) {
w->color = kBlack;
x->p->color = kRed;
right_rotate(x->p);
w = x->p->left;
}
if ((w->right->color == kBlack) && (w->left->color == kBlack)) {
w->color = kRed;
x = x->p;
} else {
if (w->left->color == kBlack) {
w->right->color = kBlack;
w->color = kRed;
left_rotate(w);
w = x->p->left;
}
w->color = x->p->color;
x->p->color = kBlack;
w->left->color = kBlack;
right_rotate(x->p);
x = _M_root;
}
}
}
x->color = kBlack;
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::create(const _Key& key,
const _Value& value)
{
#if HAVE_FREE_LIST
if (!_M_free) {
return new (std::nothrow) node(key, value);
}
node* n = _M_free;
_M_free = _M_free->left;
return new (n) node(key, value);
#else
return new (std::nothrow) node(key, value);
#endif
}
#if HAVE_FREE_LIST
template<typename _Key, typename _Value, typename _Compare>
inline void red_black_tree<_Key, _Value, _Compare>::add_free_list(node* node)
{
node->left = _M_free;
_M_free = node;
}
#endif // HAVE_FREE_LIST
template<typename _Key, typename _Value, typename _Compare>
void red_black_tree<_Key, _Value, _Compare>::erase_subtree(node* node)
{
if (node->left != nil()) {
erase_subtree(node->left);
}
if (node->right != nil()) {
erase_subtree(node->right);
}
delete node;
}
template<typename _Key, typename _Value, typename _Compare>
inline typename red_black_tree<_Key, _Value, _Compare>::node*
red_black_tree<_Key, _Value, _Compare>::nil()
{
return &_M_nil;
}
}
#endif // UTIL_RED_BLACK_TREE_H
| true |
542370bdc1e225c1fb018eee31967544ea6880c4 | C++ | Penergy/CPPLearn | /chapt2-4/exercise2.12/Rectangle.cpp | UTF-8 | 499 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle(double width, double height )
{
init(width, height);
}
double Rectangle::getArea()
{
if(!_isAreaCalculated)
{
_area = _width *_height;
}
return _area;
}
double Rectangle::getGirth()
{
if(!_isGirthCalculated)
{
_girth = (_height + _width) * 2;
}
return _girth;
}
void Rectangle::init(double width, double height )
{
_width = width;
_height = height;
} | true |
23bd16d189b75bfd06948c3590d775d030e1619f | C++ | mikebrownie/OSRS-Script-Dump | /osrsClicker/main.cpp | UTF-8 | 567 | 3.078125 | 3 | [] | no_license | #include <windows.h>
#include <iostream>
void LeftClick ( )
{
INPUT Input={0};
// left down
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
::SendInput(1,&Input,sizeof(INPUT));
// left up
::ZeroMemory(&Input,sizeof(INPUT));
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
::SendInput(1,&Input,sizeof(INPUT));
}
int main()
{
std::cout<<"Running... Press shift to auto-click";
while(1){
Sleep(15);
if(GetKeyState(VK_SHIFT) < 0)
LeftClick();
}
std::cout<<"Done";
return 0;
}
| true |
dfab34779fd6c2d9dfacb559162542fa5b3ca986 | C++ | pyxploiter/Mission-Plan-Specialist-Program | /LocationData.cpp | UTF-8 | 2,909 | 3.03125 | 3 | [] | no_license | #include "LocationData.h"
#include <string>
#include <string.h>
//Constructor Without parameters
LocationData::LocationData(){
sunType = "";
noOfEarthLikePlanets = 0;
noOfEarthLikeMoons = 0;
aveParticulateDensity = 0.0;
avePlasmaDensity = 0.0;
}
//constructor with parameters
LocationData::LocationData(string sType, int noOfELP, int noOfELM, float aveParDen, float avePlaDen){
sunType = sType;
noOfEarthLikePlanets = noOfELP;
noOfEarthLikeMoons = noOfELM;
aveParticulateDensity = aveParDen;
avePlasmaDensity = avePlaDen;
}
//getter for sunType
string LocationData::getSunType(){
return sunType;
}
//getter for noOfEarthLikePlanets
int LocationData::getNoOfEarthLikePlanets(){
return noOfEarthLikePlanets;
}
//getter for noOfEarthLikeMoons
int LocationData::getNoOfEarthLikeMoons(){
return noOfEarthLikeMoons;
}
//getter for aveParticulateDensity
float LocationData::getAveParticulateDensity(){
return aveParticulateDensity;
}
//getter for avePlasmaDensity
float LocationData::getAvePlasmaDensity(){
return avePlasmaDensity;
}
//setter for sunType
void LocationData::setSunType(string sType){
sunType = sType;
}
//setter for noOfEarthLikePlanets
void LocationData::setNoOfEarthLikePlanets(int noOfELP){
noOfEarthLikePlanets = noOfELP;
}
//setter for noOfEarthLikeMoons
void LocationData::setNoOfEarthLikeMoons(int noOfELM){
noOfEarthLikeMoons = noOfELM;
}
//setter for aveParticulateDensity
void LocationData::setAveParticulateDensity(float aveParDen){
aveParticulateDensity = aveParDen;
}
//setter for avePlasmaDensity
void LocationData::setAvePlasmaDensity(float avePlaDen){
avePlasmaDensity = avePlaDen;
}
//returns a String, containing the name of each attribute and its value respectively
string LocationData::toString(){
return "sunType: "+sunType+",\nnoOfEarthLikePlanets: "+to_string(noOfEarthLikePlanets)+",\nnoOfEarthLikeMoons: "+to_string(noOfEarthLikeMoons)+",\naveParticulateDensity: "+to_string(aveParticulateDensity)+",\navePlasmaDensity: "+to_string(avePlasmaDensity);
}
//static function for computing civilization index
float LocationData::computeCivIndex(string sType, int noOfELP, int noOfELM, float aveParDen, float avePlaDen){
int sunTypePercent = 0;
if (strcmp(sType.c_str(), "Type O") == 0){
sunTypePercent = 30;
} else if(strcmp(sType.c_str(), "Type B") == 0){
sunTypePercent = 45;
} else if(strcmp(sType.c_str(), "Type A") == 0){
sunTypePercent = 60;
} else if(strcmp(sType.c_str(), "Type F") == 0){
sunTypePercent = 75;
} else if(strcmp(sType.c_str(), "Type G") == 0){
sunTypePercent = 90;
} else if(strcmp(sType.c_str(), "Type K") == 0){
sunTypePercent = 80;
} else if(strcmp(sType.c_str(), "Type M") == 0){
sunTypePercent = 70;
} else{
cout << "[Error] SunType unknown." << endl;
}
//formula for civ.Index
float civIndex = ((sunTypePercent/100.0)-((aveParDen+avePlaDen)/200.0))*(noOfELP+noOfELM);
return civIndex;
} | true |
2fb766d51df3a0cfed5af5cfacf3ec455f4ed4dc | C++ | zhenchen/cors-overlayrouting | /CORS/src/test/simpleclient.cpp | UTF-8 | 2,602 | 2.5625 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <sys/socket.h>
#include <vector>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <../client/corssocket.h>
using namespace std;
void usage()
{
cout << "usage: simpleclient config_file" << endl;
}
int load_config(string file_name,
Requirement &req,
sockaddr_in &local,
sockaddr_in &remote)
{
ifstream ifs(file_name.c_str());
if (!ifs) {
cerr << "Unable to open config file: " << file_name << endl;
return -1;
}
string line;
// load local port
getline(ifs, line);
istringstream iss1(line);
in_port_t local_port;
iss1 >> local_port;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(local_port);
// load remote ip and port
getline(ifs, line);
istringstream iss2(line);
in_port_t remote_port;
in_addr_t remote_ip;
string ip_str;
iss2 >> ip_str >> remote_port;
memset(&remote, 0, sizeof(remote));
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = inet_addr(ip_str.c_str());
remote.sin_port = htons(remote_port);
// load requirement
getline(ifs, line);
istringstream iss3(line);
iss3 >> req.delay >> req.bandwidth >> req.lossrate >> req.qospara >> req.seculevel >> req.relaynum;
return 0;
}
int init_sock(const sockaddr_in &local)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (bind(sock, (sockaddr *)&local, sizeof(local)) < 0) {
cerr << "socket error" << endl;
close(sock);
return -1;
}
return sock;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
usage();
return -1;
}
string conf_file = argv[1];
Requirement req;
sockaddr_in local, remote;
load_config(conf_file, req, local, remote);
int sock = init_sock(local);
if (sock < 0)
return -1;
vector<string> rsparams, mmparams;
rsparams.push_back("SimpleRlysltr");
rsparams.push_back("rsltr.conf");
rsparams.push_back("1");
rsparams.push_back("300");
mmparams.push_back("SimpleMpathManager");
cout << "pass" << endl;
CorsSocket cors_socket(sock, rsparams, mmparams);
cors_socket.init(req, remote.sin_addr.s_addr, remote.sin_port);
int count = 0;
Feature feature;
feature.delay = 300;
feature.significance = 0;
feature.seculevel = 0;
feature.channelnum = 3;
while (count < 5) {
stringstream ss;
ss << "string: " << count << flush;
cors_socket.sendto((char *)ss.str().c_str(), ss.str().length(), remote.sin_addr.s_addr, remote.sin_port, feature);
cout << "Send " << ss.str() << endl;
usleep(2000000);
count++;
}
cors_socket.close();
}
| true |
35a255fcd46b57c52256eabfd962eabd11406df9 | C++ | inbei/cortono | /http/example/file_server/file_server.cc | UTF-8 | 5,046 | 2.6875 | 3 | [] | no_license | #include <boost/program_options.hpp>
#include <cortono/http/app.hpp>
#include </usr/local/include/inja.hpp>
namespace fs = std::experimental::filesystem;
std::string render_view(const std::string& filepath, const std::unordered_map<std::string, inja::json>& m) {
inja::Environment env = inja::Environment("./www/");
env.set_element_notation(inja::ElementNotation::Dot);
inja::Template tmpl = env.parse_template(filepath);
inja::json tmpl_json_data;
for(auto& [key, value] : m) {
tmpl_json_data[key] = value;
}
for(auto& [key, data] : m) {
if(data.is_object()) {
for(auto it = data.begin(); it != data.end(); ++it) {
tmpl_json_data[it.key()] = it.value();
}
}
}
return env.render_template(tmpl, tmpl_json_data);
}
std::string parse_file_name(const std::string& filepath) {
auto pos = filepath.find_last_of('/');
std::string filename;
if(pos != std::string::npos)
filename = filepath.substr(pos + 1);
else
filename = filepath;
log_info(filename);
return filename;
}
cortono::http::Response handle_directory(const std::string& directory, const std::string& host, unsigned short port) {
log_info(host, port);
inja::json files;
for(auto& p : fs::directory_iterator(directory)) {
inja::json file;
std::stringstream oss;
oss << p;
std::string filepath = oss.str().substr(1, oss.str().size() - 2);
file["path"] = filepath;
file["name"] = parse_file_name(filepath);
if(fs::is_directory(p)) {
file["icon"] = "img/dir.png";
}
else {
file["icon"] = "img/file.png";
}
file["host"] = host;
file["port"] = port;
files.push_back(file);
}
std::unordered_map<std::string, inja::json> m;
m["files"] = files;
std::string s = render_view("template.html", m);
log_info(s);
return cortono::http::Response(std::move(s));
}
int main()
{
namespace po = boost::program_options;
po::options_description parser("param parser");
parser.add_options()
("host", po::value<std::string>(), "set host")
("port", po::value<unsigned short>(), "set port")
("https", po::value<bool>(), "enable https")
("directory", po::value<std::string>(), "set file directory")
;
po::variables_map vm;
try {
std::ifstream fin{ "server.conf" };
po::store(po::parse_config_file(fin, parser), vm);
po::notify(vm);
fin.close();
if(!vm.count("host"))
log_fatal("config error: no host");
if(!vm.count("port"))
log_fatal("config error: no port");
if(!vm.count("directory"))
log_fatal("config error: no directory");
std::string ip = vm["host"].as<std::string>();
unsigned short port = vm["port"].as<unsigned short>();
std::string directory = vm["directory"].as<std::string>();
log_info(ip, port, directory);
using namespace cortono;
http::SimpleApp app;
app.register_rule("/" + directory)([&](const http::Request& , http::Response& res) {
res = handle_directory(directory, ip, port);
});
app.register_rule("/" + directory + "<path>")([&](const http::Request&, http::Response& res, std::string filename) {
log_info(filename);
std::string filepath = directory + filename;
if(fs::is_directory(filepath)) {
res = handle_directory(filepath, ip, port);
}
else {
res.send_file(filepath);
auto pos = filepath.find_last_of('/');
if(pos != std::string::npos)
filename = filepath.substr(pos + 1);
res.set_header("Content-Disposition", "attachment;filename="+filename);
}
});
app.register_rule("/img/<path>")([&](const http::Request& , http::Response& res, std::string filename) {
log_info(filename);
res.send_file("img/" + filename);
return;
});
app.register_rule("/" + directory + "upload").methods(http::HttpMethod::POST)([&](const http::Request& req) {
if(req.upload_files.empty())
return "error";
std::string upload_path = directory + "upload/";
if(!fs::exists(upload_path))
fs::create_directory(upload_path);
for(auto& upload_file : req.upload_files) {
log_info("start write file:", upload_path, upload_file.filename);
std::ofstream fout{ upload_path + upload_file.filename, std::ios_base::out };
fout.write(upload_file.content.data(), upload_file.content.length());
fout.close();
}
return "ok";
});
app.bindaddr(ip).port(port).multithread().run();
}
catch(...) {
std::cout << "error" << std::endl;
}
return 0;
}
| true |
e27bffa58043e4e78fda7065f646d41be18c7d5e | C++ | jeremiahkramer/creature-battle-game | /centaur.cpp | UTF-8 | 926 | 3.015625 | 3 | [] | no_license | /******************************************************
** Program: centaur.cpp
** Author: Jeremiah Kamer
** Date: 05/13/2017
** Description: function definitions for centaur.cpp
** Input: none
** Output: none
*****************************************************/
#include "creature.h"
#include "centaur.h"
using namespace std;
Centaur::Centaur() {
set_type(4);
set_strength(45);
set_hitpoints(40);
set_payoff(15);
set_cost(50);
}
/*****************************
** Function: get_damage
** Description: returns damage, specific to centaurs
** Parameters: none
** Pre- Conditions: battle
** Post- Conditions: damage int
** Return: int
****************************/
int Centaur::get_damage() {
int damage = getDamage();
srand(time(NULL));
if ((rand() % 100) < 10) { //10% chance at special attack
damage = damage + 25;
cout << "Centaur hind kick inflicts 25 additional points!" << endl;
}
return damage;
}
| true |
5285048d71d90d4ebb489b81e3f9f9725d882659 | C++ | PoulpePalpitant/Wall-in | /FONCTIONS/spawns/valid_spwn_intervals.cpp | ISO-8859-1 | 10,967 | 2.765625 | 3 | [] | no_license |
#include "../UI/direction.h"
#include "valid_spwn_intervals.h"
/* Variables static */
int ValidSpwnIntervals::maxVer;
int ValidSpwnIntervals::maxHor;
IntervalList ValidSpwnIntervals::primary;
IntervalList ValidSpwnIntervals::scndary;
Interval* ValidSpwnIntervals::prev;
int ValidSpwnIntervals::bannedSpwn[4];
bool ValidSpwnIntervals::borderIsFull[4];
bool ValidSpwnIntervals::allPrimeEmpty = true;
bool ValidSpwnIntervals::isPriority;
/* OUECH*/
bool ValidSpwnIntervals::Is_Secondary_List_Full(int border)
{
if (border == LEFT || border == RIGHT)
return bannedSpwn[border] == maxVer;
else
return bannedSpwn[border] == maxHor;
}
bool ValidSpwnIntervals::Is_Border_Full(int border)
{
if (Is_Secondary_List_Full(border))
if (primary.start[border] == NULL)
{
borderIsFull[border] = true;
return true;
}
return false;
}
bool ValidSpwnIntervals::Is_Secondary_List_Empty(int border)
{
return (scndary.start[border] == NULL && bannedSpwn[border] == 0);
}
void ValidSpwnIntervals::Modify_Min(Interval* intval, int newMin)
{
intval->min = newMin;
}
void ValidSpwnIntervals::Modify_Max(Interval* intval, int newMax)
{
intval->max = newMax;
}
bool ValidSpwnIntervals::Are_Primary_Lists_Empty()
{
int arethey = 0; // they are!
for (int border = 0; border < 4; border++)
{
if (primary.numIntervals[border] == 0)
arethey++;
}
if (arethey == 4)
return true;
else
return false;
}
// Delete un intervalle quand il est vide
// --------------------------------------
void ValidSpwnIntervals::Destroy_Empty_Interval(IntervalList& list, Interval* intval, int border)
{
list.numIntervals[border]--;
if (intval == list.start[border] && intval == list.end[border])
{
delete intval;
intval = list.start[border] = list.end[border] = NULL;
if (isPriority) // POURRAIT TRE POTENTIELLEMENT RRON
allPrimeEmpty = Are_Primary_Lists_Empty();
}
else
{
if (intval == list.start[border])
{
list.start[border] = list.start[border]->nxt;
}
else
if (intval == list.end[border])
{
list.end[border] = prev;
prev->nxt = NULL;
}
else
if (prev)
prev->nxt = intval->nxt;
delete intval;
}
}
Interval* ValidSpwnIntervals::Find_Interval(int border, int spwNum, IntervalList* &theList)
{
static Interval* it; it = NULL;
static IntervalList *list;
static bool found; found = false;
prev = NULL; // chaque fois qu'on cherche un nouvel item, on va reset le previous* ptr
for (size_t i = 0; i < 2; i++) // Faut vrifier les deux listes malheureusement. Puisque primary limine des lments de secondary
{
if (i % 2 == 0)
list = &scndary; // Vrifie la liste secondaire en premier
else
list = &primary; // ensuite la primaire
it = list->start[border];
while (it)
{
if (it->min <= spwNum)
if (it->max > spwNum)
{
found = true;
break; // La crd est dans cet interval intrv >= min intrv < max
}
prev = it;
it = it->nxt;
}
if (found)
break;
}
if (it)
theList = list; // Faut rapporter la bonne liste aprs :( mais pas la modifier si on a rien trouv. i know its dumbo
return it; // Pourrait tre NULL si liste vide, --=-=ou si valeure trop grande ou errone!!!!-=-=-
}
void ValidSpwnIntervals::Initialize_Valid_Spawn_List() // DOIT TRE FAIT CHAQUE DBUT DE NIVEAU!
{
for (int border = 0; border < 4; border++)
{
Reset_Secondary_List();
}
}
Interval* ValidSpwnIntervals::Set_First_Interval(int border)
{
if (Is_Secondary_List_Empty(border))
{
scndary.start[border] = scndary.end[border] = new Interval;
scndary.start[border]->min = 0;
if (border == LEFT || border == RIGHT)
scndary.start[border]->max = maxVer;
else
scndary.start[border]->max = maxHor;
scndary.numIntervals[border] = 1;
scndary.end[border]->nxt = NULL;
return scndary.start[border];
}
else
return NULL; // Y'an avait dj 1 ici. Il faut vider D'abord!!
}
Interval* ValidSpwnIntervals::Create_New_Interval(IntervalList& list, int border, int min, int max)
{
static Interval* newIntval; newIntval = NULL; // Fais des static cuz i dont know if it really helps
newIntval = new Interval;
newIntval->min = min;
newIntval->max = max;
newIntval->nxt = NULL;
if (prev)
{
prev = prev->nxt = newIntval;
}
list.numIntervals[border]++;
return newIntval;
}
bool ValidSpwnIntervals::Add_Primary_Interval(int border, int min, int max) // SIDENOTE: Pour chaque Bordure, 1 seule intervalle pourra tre fournis lors d'un cycle de spawn
{ // cette intervalle pourra tre divis au fur et mesure, mais il sera interdit de l'agrandir
if (primary.start[border] != NULL)
return false; // Il est Interdit d'ajouter un Nouvel Intervalle!!!!!
primary.start[border] = primary.end[border] = Create_New_Interval(primary, border, min, max); // Derp
Exclude_Primary_Interval(border, min, max);
allPrimeEmpty = false;
return true;
}
bool ValidSpwnIntervals::Exclude_Primary_Interval(int border, int min, int max)
{
int scndaryMax = scndary.start[border]->max;
int scndaryMin = scndary.start[border]->min;
if (min == scndaryMin && scndaryMax == max)
Destroy_Empty_Interval(scndary, scndary.start[border], border);
else
{
if (min == scndaryMin)
scndary.start[border]->min = max + 1;
else
if (max == scndaryMax)
scndary.start[border]->max = min;
else
{
scndary.start[border]->max = min;
prev = scndary.start[border];
Create_New_Interval(scndary, border, max, scndaryMax);
if(scndary.end[border] == scndary.start[border])
scndary.end[border] = scndary.start[border]->nxt;
prev = scndary.end[border]->nxt = NULL; // tout brisait cause d'un pointeur gloabl dnomme prev. Un pointeur static de class est une vritable ide tron-esque
}
}
return true;
}
void ValidSpwnIntervals::Remove_Spawn_From_List(IntervalList &list, Interval* intval, int border, int bannedCrd)
{
int max = intval->max;
int min = intval->min;
if (max - min == 1)
{
if (min == bannedCrd || bannedCrd == max)
Destroy_Empty_Interval(list, intval, border);
}
else
{
if (min == bannedCrd)
Modify_Min(intval, bannedCrd + 1);
else
if (bannedCrd == max - 1)
Modify_Max(intval, bannedCrd);
else
Split_Interval_In_Two(list, border, intval, bannedCrd);
}
}
void ValidSpwnIntervals::Split_Interval_In_Two(IntervalList &list, int border, Interval* &intval, int bannedCrd)
{
static Interval* interval_1; interval_1 = NULL; // Fais des static cuz i dont know if it really helps
interval_1 = Create_New_Interval(list, border, intval->min, bannedCrd);
if (intval == list.start[border])
list.start[border] = interval_1;
interval_1->nxt = intval; // Re-Pointeursiation
Modify_Min(intval, bannedCrd + 1); // Rduit l'intervalle originale
}
void ValidSpwnIntervals::Reset_Secondary_List()
{
static Interval* it; it = NULL;
for (int i = 0; i < 4; i++) // 4 = nombre de borders
{
if (!Is_Secondary_List_Full(i))
{
it = scndary.start[i];
while (it)
{
prev = it;
it = it->nxt;
delete prev; // Vide la liste : Si tu Crash ici, c'est que ta essayer de faire spawner un bot sur une coord plus grande que le nombre de spawn possible
} // Genre en crivant linkGrid.Get_Rows() au lieu de Get_Num_Spawns(). Faudrait Vraiment que Je criss un safety l-dedans....
scndary.start[i] = NULL;
prev = it = NULL;
}
bannedSpwn[i] = 0; // !in this order pls!
borderIsFull[i] = false; // ahhhhh
Set_First_Interval(i);
}
}
void ValidSpwnIntervals::Empty_Primary_List()
{
static Interval* it; it = NULL;
for (int i = 0; i < 4; i++)
{
while (it = primary.start[i])
{
primary.start[i] = it->nxt;
delete it;
}
primary.numIntervals[i] = 0;
primary.end[i] = {};
}
allPrimeEmpty = true;
}
Interval* ValidSpwnIntervals::Pick_Random_Interval(const IntervalList& list, int border)
{
static Interval* it; it = NULL;
int rdmIntervalle;
rdmIntervalle = rand() % list.numIntervals[border];
it = list.start[border];
if (list.numIntervals[border] != 1) // % 1 donne toujours 1. % > 1 peut donner 0 (par dfinition, un intervalle de zro n'existe pas)
for (int i = 0; i < rdmIntervalle; i++)
{
prev = it;
it = it->nxt;
}
return it;
}
int ValidSpwnIntervals::Pick_Rdm_Spwn_From_Interval(Interval* intval)
{
int rdmSpwn, numSpwns;
if (intval->min == 1)
rdmSpwn = intval->min;
else
{
numSpwns = intval->max - intval->min;
rdmSpwn = rand() % numSpwns + intval->min;
}
return rdmSpwn;
}
int ValidSpwnIntervals::Pick_Primary_Border()
{
if (allPrimeEmpty == true)
return -1;
else
for (int border = 0; border < 4; border++)
{
if (primary.start[border] != NULL)
return border;
}
return -1;
}
int ValidSpwnIntervals::Pick_Valid_Spawn(int border, bool random, int spwNum)
{
static Interval* it; prev = it = NULL; // J'ai block longtemps parce que prev n'avait pas t r-initialis NULL
static IntervalList *list;
static int spawn; // BONNE PRATIQUE BONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUE
// BONNE PRATIQUE BONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUE
// Trouve la bonne liste si le spawn qu'on choisit est random // BONNE PRATIQUE BONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUE
if (primary.start[border] != NULL) // On va prendre une coord l dedans mah dude // BONNE PRATIQUE BONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUE
{ // BONNE PRATIQUE BONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUEBONNE PRATIQUE
list = &primary;
isPriority = true;
}
else
{
if (Is_Secondary_List_Full(border)) // Safety
return -1; // La bordure slectionn ne contient aucun spawn de disponible durant ce cycle
else
Set_First_Interval(border); // La liste avait-elle t initialis?
list = &scndary;
}
if (!random) // Trouvons le spawn!
{
spawn = spwNum;
it = Find_Interval(border, spwNum, list); // Trouve l'intervalle contenant le spawn.
if (!it) // Si le spawn n'est pas dans un intervalle
random = true; // On va spawner quelque chose de random sur la mme bordure la place
}
if (random) // Trouvons un spawn disponible, un peu randomly :)
{
it = Pick_Random_Interval(*list, border); // Prend 1 intervalle random parmis cette liste!!!
spawn = Pick_Rdm_Spwn_From_Interval(it); // Prend un spawn Random parmis cette intervalle
}
Remove_Spawn_From_List(*list, it, border, spawn); // Modifie l'intervalle pour exclure le spawn slectionn par les DieuX
bannedSpwn[border]++;
return spawn;
}
// bingo bango
| true |
c594c491cd61480b39ff62b82dcfddcfe6dffe49 | C++ | thedewangan/spoj | /abcpath.cpp | UTF-8 | 2,039 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#define ll long long
using namespace std;
vector < pair<int, int> > getNeighbours(int i, int j, int h, int c, vector< vector<char> > &mat){
vector< pair <int,int> > neighbours;
for(int x=-1; x <=1; x++) {
for(int y =-1; y<=1; y++) {
int u = i+x;
int v = j+y;
if((u!=i || v!=j) && u >= 0 && u < h && v>=0 && v < c) {
if (mat[u][v] == mat[i][j] + 1){
//cout<<u<<" "<<v<<endl;
neighbours.push_back(make_pair(u, v));
}
}
}
}
//cout<<"Neighbour size "<<neighbours.size()<<endl;
return neighbours;
}
int dfs(int i, int j, int h, int c, vector < vector<int > > &dp, vector< vector<char> > &mat) {
if(dp[i][j]) return dp[i][j];
//cout<<"In dfs\t"<<i<<" "<<j<<endl;
vector < pair<int, int> > v;
v = getNeighbours(i, j, h, c, mat);
//cout<<v.size()<<endl;
int max = 1;
for(int x = 0; x < v.size(); x++) {
int p = 1 + dfs(v[x].first, v[x].second, h, c, dp, mat);
if (p > max) max = p;
}
dp[i][j] = max;
return max;
}
int main()
{
int h, c;
// width is c
int ctr = 0;
while(1) {
cin>>h>>c;
if(!h && !c) break;
vector < vector<int > >dp;
vector< vector<char> > mat;
mat.resize(h);
dp.resize(h);
for(int i = 0; i < h; i++) {
mat[i].resize(c);
dp[i].resize(c, 0);
for(int j = 0; j < c; j++) {
cin>>mat[i][j];
}
}
int max = 0;
for(int i = 0; i < h; i++) {
for(int j = 0; j < c; j++) {
if(mat[i][j] == 'A') {
int t = dfs(i, j, h, c, dp, mat);
if (t > max) max = t;
}
}
}
// for(int i = 0; i < h; i++) {
// for(int j = 0; j < c; j++)
// cout<<mat[i][j]<<" ";
// cout<<endl;
// }
// dfs(0, 0, h, c, dp, mat);
// for(int i = 0; i < h; i++) {
// for(int j = 0; j < c; j++)
// cout<<dp[i][j]<<" ";
// cout<<endl;
// }
ctr ++;
cout<<"Case "<<ctr<<": "<<max<<endl;
}
return 0;
} | true |
20d699fbf78537593bd17ba5b4e3698f2bb3719a | C++ | jts/nanopolish | /src/common/logger.hpp | UTF-8 | 12,824 | 2.890625 | 3 | [
"MPL-1.1",
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | /// Part of: https://github.com/mateidavid/hpptools
/// Commit: 5a6f39c
/// @author Matei David, Ontario Institute for Cancer Research
/// @version 1.0
/// @date 2013-2017
/// @copyright MIT Public License
///
/// Logger mechanism.
///
/// Properties:
/// - thread-safe, non-garbled output (uses c++11's thread_local)
/// - customizable ostream sink. by default, uses std::clog
///
/// Exports:
/// - macro: LOG (takes 1, 2, or 3 arguments, see below)
/// - macros: LOG_EXIT_, LOG_ABORT, LOG_EXIT, LOG_THROW_, and LOG_THROW
/// - namespace logger
/// - enum logger::level
/// - class logger::Logger
///
/// To use:
/// - In source code, use:
///
/// LOG(info) << "hello" << endl;
/// // or
/// LOG("main", info) << "hello" << endl;
/// // or
/// LOG("main", info, sink_os) << "hello" << endl;
///
/// Here, "main" is the facility (a string) and info is the message level.
/// Note that "logger" is a macro which knows how to look up the name info
/// inside logger namespace. The macro introduces C++ code equivalent to:
///
/// if (...message should be ignored...) then; else sink_os
///
/// NOTE: As with assert(), the code in the output stream following the
/// LOG() macro will ***not be executed*** if the log level of the
/// facility is higher than the level of the message.
///
/// - To set the default log level (for unspecified facilities):
///
/// logger::Logger::set_default_level(logger::Logger::level_from_string(s));
///
/// - To set the log level for the "main" facility:
///
/// logger::Logger::set_facility_level("main", logger::Logger::level_from_string(s));
///
/// - To parse a log facility level setting in the form "[<facility>:]<level>":
///
/// logger::Logger::set_level_from_option("alt:debug1", &cerr);
///
/// - By using these functions, one can set log levels using command-line
/// parameters and achieve dynamic log level settings without recompiling.
///
/// - The macros LOG_EXIT_, LOG_ABORT, LOG_EXIT, LOG_THROW_, and LOG_THROW
/// provide a way to specify what to do after logging the message.
///
/// LOG_EXIT_(exit_code) << "print this message to std::cerr, call std::exit(exit_code)";
/// LOG_ABORT << "print this message to std::cerr, call std::abort()";
/// LOG_EXIT << "print this message to std::cerr, call std::exit(EXIT_FAILURE)";
/// LOG_THROW_(Exception) << "throw Exception with this message";
/// LOG_THROW << "throw std::runtime_error with this message";
#ifndef __LOGGER_HPP
#define __LOGGER_HPP
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <functional>
namespace logger
{
// log levels
enum level
{
error = 0,
warning,
info,
debug,
debug1,
debug2
};
class Logger
{
public:
// Constructor: initialize buffer.
Logger(std::string const & facility, level msg_level,
std::string const & file_name, unsigned line_num, std::string const & func_name,
std::ostream & os = std::clog)
: _os_p(&os)
{
_oss << "= " << facility << "." << int(msg_level)
<< " " << file_name << ":" << line_num << " " << func_name << " ";
_on_destruct = [&] () {
_os_p->write(_oss.str().c_str(), _oss.str().size());
};
}
// Constructor for exiting
Logger(int exit_code,
std::string const & file_name, unsigned line_num, std::string const & func_name,
std::ostream & os = std::cerr)
: _os_p(&os), _exit_code(exit_code)
{
_oss << file_name << ":" << line_num << " " << func_name << " ";
_on_destruct = [&] () {
_os_p->write(_oss.str().c_str(), _oss.str().size());
if (_exit_code < 0)
{
std::abort();
}
else
{
std::exit(_exit_code);
}
};
}
// Constructor for throwing exceptions
// first argument is only used to deduce the template argument type
template <typename Exception>
Logger(Exception const &,
std::string const & file_name, unsigned line_num, std::string const & func_name,
typename std::enable_if<std::is_base_of<std::exception, Exception>::value>::type * = 0)
{
_oss << file_name << ":" << line_num << " " << func_name << " ";
_on_destruct = [&] () {
throw Exception(_oss.str());
};
}
// Destructor: dump buffer to output.
~Logger() noexcept(false)
{
_on_destruct();
}
// Produce l-value for output chaining.
std::ostream & l_value() { return _oss; }
// static methods for setting and getting facility log levels.
static level get_default_level()
{
return default_level();
}
static void set_default_level(level l)
{
static std::mutex m;
std::lock_guard<std::mutex> lg(m);
default_level() = l;
}
static void set_default_level(int l)
{
set_default_level(get_level(l));
}
static void set_default_level(std::string const & s)
{
set_default_level(get_level(s));
}
static level get_facility_level(std::string const & facility)
{
return (facility_level_map().count(facility) > 0?
facility_level_map().at(facility) : get_default_level());
}
static void set_facility_level(std::string const & facility, level l)
{
static std::mutex m;
std::lock_guard<std::mutex> lg(m);
facility_level_map()[facility] = l;
}
static void set_facility_level(std::string const & facility, int l)
{
set_facility_level(facility, get_level(l));
}
static void set_facility_level(std::string const & facility, std::string const & s)
{
set_facility_level(facility, get_level(s));
}
// static methods for setting log levels from command-line options
static void set_level_from_option(std::string const & l, std::ostream * os_p = nullptr)
{
size_t i = l.find(':');
if (i == std::string::npos)
{
set_default_level(l);
if (os_p)
{
(*os_p) << "set default log level to: "
<< static_cast<int>(Logger::get_default_level()) << std::endl;
}
}
else
{
set_facility_level(l.substr(0, i), l.substr(i + 1));
if (os_p)
{
(*os_p) << "set log level of '" << l.substr(0, i) << "' to: "
<< static_cast<int>(Logger::get_facility_level(l.substr(0, i))) << std::endl;
}
}
}
static void set_levels_from_options(std::vector<std::string> const & v, std::ostream * os_p = nullptr)
{
for (auto const & l : v)
{
set_level_from_option(l, os_p);
}
}
// public static utility functions (used by LOG macro)
static level get_level(level l) { return l; }
static level get_level(int i) { return static_cast<level>(i); }
static level get_level(std::string const & s) { return level_from_string(s); }
// public static member (used by LOG macro)
static level& thread_local_last_level()
{
static thread_local level _last_level = error;
return _last_level;
}
private:
std::ostringstream _oss;
std::function<void()> _on_destruct;
std::ostream * _os_p;
int _exit_code;
// private static data members
static level & default_level()
{
static level _default_level = error;
return _default_level;
}
static std::map<std::string, level> & facility_level_map()
{
static std::map<std::string, level> _facility_level_map;
return _facility_level_map;
}
// private static utility functions
static level level_from_string(std::string const & s)
{
std::istringstream iss(s + "\n");
int tmp_int = -1;
iss >> tmp_int;
if (iss.good())
{
return level(tmp_int);
}
else
{
if (s == "error") return logger::error;
else if (s == "warning") return logger::warning;
else if (s == "info") return logger::info;
else if (s == "debug") return logger::debug;
else if (s == "debug1") return logger::debug1;
else if (s == "debug2") return logger::debug2;
else
{
std::ostringstream oss;
oss << "could not parse log level: " << s;
throw std::invalid_argument(oss.str());
}
}
}
}; // class Logger
} //namespace logger
#define __FILENAME__ (std::string(__FILE__).find('/') != std::string::npos? std::string(__FILE__).substr(std::string(__FILE__).rfind('/') + 1) : std::string(__FILE__))
/**
* LOG macro
*
* Synopsis:
* LOG(facility, level_spec, sink) << message
* LOG(facility, level_spec) << message
* LOG(level_spec) << message
*
* `facility` : string
* `level_spec` : integer, string, or logger level
* `sink` : sink ostream
*
* Log to `facility` at logger level `level_spec` and dump output to `sink`.
* If sink is omitted, it defaults to std::clog.
* If `facility` is omitted (logger has single argument), the macro LOG_FACILITY
* is used instead, defaulting to "main".
*/
#define __LOG_3(facility, level_spec, sink) \
{ using namespace logger; logger::Logger::thread_local_last_level() = logger::Logger::get_level(level_spec); } \
if (logger::Logger::thread_local_last_level() > logger::Logger::get_facility_level(facility)) ; \
else logger::Logger(facility, logger::Logger::thread_local_last_level(), __FILENAME__, __LINE__, __func__, sink).l_value()
#define __LOG_2(facility, level_spec) \
{ using namespace logger; logger::Logger::thread_local_last_level() = logger::Logger::get_level(level_spec); } \
if (logger::Logger::thread_local_last_level() > logger::Logger::get_facility_level(facility)) ; \
else logger::Logger(facility, logger::Logger::thread_local_last_level(), __FILENAME__, __LINE__, __func__).l_value()
#define __LOG_1(level_spec) \
__LOG_2(LOG_FACILITY, level_spec)
// we need 2-level indirection in order to trigger expansion after token pasting
// http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-with-positioning-macr
// http://stackoverflow.com/a/11763196/717706
#ifdef WIN32
#define __EXPAND(...) __VA_ARGS__
#define __LOG_aux2(N, ...) __EXPAND(__LOG_ ## N (__VA_ARGS__))
#else
#define __LOG_aux2(N, ...) __LOG_ ## N (__VA_ARGS__)
#endif
#define __LOG_aux1(N, ...) __LOG_aux2(N, __VA_ARGS__)
#define __NARGS_AUX(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) _9
#ifdef WIN32
#define __NARGS(...) __EXPAND(__NARGS_AUX(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0))
#else
#define __NARGS(...) __NARGS_AUX(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0)
#endif
#ifndef LOG_FACILITY
#define LOG_FACILITY "main"
#endif
#define LOG(...) __LOG_aux1(__NARGS(__VA_ARGS__), __VA_ARGS__)
#define LOG_EXIT_(exit_code) logger::Logger((exit_code), __FILENAME__, __LINE__, __func__).l_value()
#define LOG_ABORT LOG_EXIT_(-1)
#define LOG_EXIT LOG_EXIT_(EXIT_FAILURE)
#define LOG_THROW_(Exception) logger::Logger(Exception(""), __FILENAME__, __LINE__, __func__).l_value()
#define LOG_THROW LOG_THROW_(std::runtime_error)
#endif
#ifdef SAMPLE_LOGGER
/*
Compile:
g++ -std=c++11 -D SAMPLE_LOGGER -x c++ logger.hpp -o sample-logger
Run:
./sample-logger info
./sample-logger info alt:debug1
*/
using namespace std;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cerr << "Use: " << argv[0] << " <log_level_setting> ..." << endl
<< "The program sends 5 log messages with decreasing priority (0=highest, 4=lowest)" << endl
<< "to 2 facilities \"main\" and \"alt\". Command-line arguments are interpreted as" << endl
<< "log facility level settings in the form [<facility>:]<level>." << endl;
return EXIT_FAILURE;
}
for (int i = 1; i < argc; ++i)
{
cerr << "processing argument [" << argv[i] << "]" << endl;
logger::Logger::set_level_from_option(argv[i], &cerr);
}
vector<string> const level_name{ "error", "warning", "info", "debug", "debug1", "debug2" };
for (int l = 0; l < 5; ++l)
{
LOG(level_name[l]) << "message at level " << l << " (" << level_name[l]
<< ") for facility main" << endl;
LOG("alt", l) << "message at level " << l << " (" << level_name[l]
<< ") for facility alt" << endl;
}
}
#endif
| true |