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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c342a89276358d720896daab9845ab7903f0d4a0 | C++ | ehan69rus/FlightAssign | /FlightAssignCoreLib/src/FlightAssignBaseItem.h | UTF-8 | 508 | 2.765625 | 3 | [] | no_license | #ifndef FLIGHTASSIGNBASEITEM_H
#define FLIGHTASSIGNBASEITEM_H
//! Базовый класс
class FlightAssignBaseItem {
public:
//! Конструктор.
FlightAssignBaseItem(long long _id);
//! Возвращает идентификатор аэродрома.
long long id() const;
//! Задает идентификатор аэродрома.
void setId(long long _id);
private:
//! Идентификатор.
long long m_id;
};
#endif // FLIGHTASSIGNBASEITEM_H
| true |
c02151e236ce784d7e01472bf605288a139855bd | C++ | PonchoCeniceros/Arduino-Matlab-legacy-projects | /projects/PID-Controller-for-Arduino/testing/Printer.h | UTF-8 | 197 | 2.859375 | 3 | [
"MIT"
] | permissive | /**
* @file Printer.h
* @date Abr 22, 2019
*/
#define endl "\n"
#define tab "\t"
template<class T> inline Print &operator <<(Print &obj, T arg)
{
obj.print(arg); return obj;
}
/* EOF */
| true |
0801d071ddc7eb6ec2807ce32ecf414185e3cddd | C++ | rofernan42/Modules_CPP | /CPP04/ex03/MateriaSource.cpp | UTF-8 | 1,519 | 3.21875 | 3 | [] | no_license | #include "MateriaSource.hpp"
MateriaSource::MateriaSource():
_nbmat(0)
{
for (int i = 0; i < 4; i++)
_materia[i] = NULL;
}
MateriaSource::MateriaSource(const MateriaSource ©):
_nbmat(copy._nbmat)
{
for (int i = 0; i < 4; i++)
{
if (copy._materia[i])
this->_materia[i] = copy._materia[i]->clone();
else
this->_materia[i] = NULL;
}
}
MateriaSource::~MateriaSource()
{
for (int i = 0; i < 4; i++)
delete _materia[i];
}
MateriaSource &MateriaSource::operator=(const MateriaSource &b)
{
this->_nbmat = b._nbmat;
for (int i = 0; i < 4; i++)
{
if (b._materia[i])
this->_materia[i] = b._materia[i]->clone();
else
this->_materia[i] = NULL;
}
return (*this);
}
void MateriaSource::learnMateria(AMateria *m)
{
if (_nbmat < 4 && m)
{
for (int i = 0; i < _nbmat; i++)
{
if (_materia[i] == m)
return ;
}
_materia[_nbmat] = m;
_nbmat++;
}
}
AMateria *MateriaSource::createMateria(std::string const &type)
{
for (int i = 0; i < 4; i++)
{
if (_materia[i] && _materia[i]->getType() == type)
{
AMateria *ret = _materia[i]->clone();
return (ret);
}
}
return (NULL);
}
//test fct
void MateriaSource::display() const
{
std::cout << "*************" << std::endl;
std::cout << "nb mat: " << _nbmat << std::endl;
for (int i = 0; i < 4; i++)
{
if (_materia[i])
std::cout << "source[" << i << "]: " << _materia[i]->getType() << std::endl;
else
std::cout << "source[" << i << "]: null" << std::endl;
}
std::cout << "*************" << std::endl;
}
| true |
3ebedb44c9afe77cfc6685fe871fa3a44fb8fbe5 | C++ | qiubit/lattec | /src/IdEnvEntry.h | UTF-8 | 1,251 | 2.859375 | 3 | [] | no_license | //
// Created by Pawel Golinski on 20.01.2018.
//
#ifndef TESTLLVM_ENVENTRY_H
#define TESTLLVM_ENVENTRY_H
#include <string>
#include "types/Type.h"
class IdEnvEntry {
private:
std::string entryId;
Type *entryType;
llvm::Value *entryAlloca = nullptr;
llvm::Function *entryFunction = nullptr;
llvm::Value *entryValue = nullptr;
public:
IdEnvEntry(std::string entryId, Type *entryType) : entryId(std::move(entryId)), entryType(entryType) { }
const std::string &getEntryId() const { return entryId; }
Type *getEntryType() const { return entryType; }
llvm::Value *getEntryAlloca() const { return entryAlloca; }
llvm::Function *getEntryFunction() const { return entryFunction; }
llvm::Value *getEntryValue() const { return entryValue; }
void setEntryAlloca(llvm::Value *val) { entryAlloca = val; }
void setEntryFunction(llvm::Function *val) { entryFunction = val; }
void setEntryValue(llvm::Value *val) { entryValue = val; }
};
namespace std {
template<> struct hash<IdEnvEntry>
{
using result_type = std::size_t;
result_type operator()(const IdEnvEntry &e)
{
return std::hash<std::string>{}(e.getEntryId());
}
};
}
#endif //TESTLLVM_ENVENTRY_H
| true |
8b590fd4f4cddacca05fe687359d61049b9889f0 | C++ | Kullsno2/C-Cpp-Programs | /CartesianTree.cpp | UTF-8 | 1,274 | 3.28125 | 3 | [] | no_license | #include<utility>
#include<windows.h>
#include<map>
#include<vector>
#include<iostream>
#include<limits.h>
using namespace std ;
struct node{
int val ;
struct node * left ;
struct node * right ;
node(int x) : val(x) , left(NULL) , right(NULL) {}
};
int findMax(vector<int> v,int st,int ed,int &m)
{
int maxi = INT_MIN ;
for(int i= st ; i<=ed ; i++)
{
if(v[i] > maxi)
{
m = i;
maxi = v[i] ;
}
}
return maxi ;
}
struct node * build(struct node * root,vector<int> v,int st,int end)
{
if(st > end)
return NULL ;
if(st==end)
{
root = new node(v[st]) ;
return root ;
}
int maxi ,maxi_index ;
maxi = findMax(v,st,end,maxi_index) ;
root = new node(maxi) ;
root -> left = build(root->left,v,st,maxi_index-1) ;
root -> right = build(root->right,v,maxi_index+1,end) ;
return root ;
}
void inorder(struct node * root)
{
if(root)
{
inorder(root->left) ;
cout<<root->val<<" ";
inorder(root->right) ;
}
}
struct node * buildTree(vector<int> v)
{
struct node * root = NULL ;
return build(root,v,0,v.size()-1) ;
}
int main()
{
vector<int> v;
v.push_back(4) ;
v.push_back(3) ;
v.push_back(6) ;
v.push_back(7) ;
v.push_back(2) ;
v.push_back(1) ;
v.push_back(5) ;
node * root = buildTree(v) ;
inorder(root) ;
}
| true |
10b98a1ca52e21d3b5508d0ace815004cb6253e0 | C++ | gabrielhpr/symbol-table-comparator | /estruturas.hpp | UTF-8 | 1,392 | 2.625 | 3 | [] | no_license | #ifndef ESTRUTURAS_H
#define ESTRUTURAS_H
#include <string>
using namespace std;
typedef string Chave;
typedef int Item;
class Celula {
public:
Chave chave;
Item valor;
Celula* prox;
};
class NoABB {
public:
Chave chave;
Item valor;
int quantNosSubArvEsq;
int quantNosSubArvDir;
NoABB* esq;
NoABB* dir;
};
class NoTreap {
public:
Chave chave;
Item valor;
int prioridade;
int quantNosSubArvEsq;
int quantNosSubArvDir;
NoTreap* esq;
NoTreap* dir;
};
class NoRN {
public:
Chave chave;
Item valor;
char cor;
int quantNosSubArvEsq;
int quantNosSubArvDir;
bool ehDuploPreto;
NoRN* esq;
NoRN* dir;
NoRN* pai;
};
class No23 {
public:
Chave chave1, chave2;
Item valor1, valor2;
int quantNosSubArvEsq = 0;
int quantNosSubArvDir = 0;
No23 *ap1;
No23 *ap2;
No23 *ap3;
No23 *pai;
bool doisNo;
bool ehFolha();
};
bool No23 :: ehFolha() {
//Retorna se o Nó é uma folha ou não
return (ap1 == nullptr && ap2 == nullptr && ap3 == nullptr);
}
class CelulasHash {
public:
Chave chave;
Item valor;
CelulasHash* ant;
CelulasHash* prox;
};
#endif | true |
81dd5656abebf5bbc43cd3c5ec16e7582c9b9a55 | C++ | alvarosg/JetProcessing | /SourceCode/headers/imagesequencecontroller.h | ISO-8859-1 | 7,030 | 2.6875 | 3 | [] | no_license | /**
* @file imagesequencecontroller.h
* @author lvaro Snchez Gonzlez <alvarosg@usal.es>
* @date Mon Jul 23 2012
*
* Copyright (c) 2012 lvaro Snchez Gonzlez
*
* @brief Fichero que define la clase que controla y gestiona la lista de imagenes de la fase guardadas en el programa.
*
*/
#ifndef IMAGESEQUENCECONTROLLER_H
#define IMAGESEQUENCECONTROLLER_H
#include <QList>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QTextStream>
#include <QDomElement>
#include <stdio.h>
#include <stdlib.h>
#include "imageelement.h"
#include "abstractimagefactory.h"
/*! \class ImageSequenceController imagesequencecontroller.h "imagesequencecontroller.h"
* \brief Clase que controla y conoce una lista de imgenes de la fase.
*
* Se encargar de comprobar la integridad de los nombres de las imgenes asi como de devolver una imagen que se le solicite.
*
*/
class ImageSequenceController : public QList <ImageElement>
{
public:
ImageSequenceController();
/**< Constructor.*/
void AppendImageElement(PhaseImage * source_in=NULL,QString label = "",float pixelsMmX_in=1,float pixelsMmY_in=1,float pixelsFromOriginX_in=0,float pixelsFromOriginY_in=0);
/**< Aade una imagen al final de la lista.
@param source_in Imagen de la fase antes de aplicar algoritmos. El objeto creado toma la responsabilidad de este puntero.
@param label Etiqueta para la imagen.
@param pixelsMmX_in Valor para iniciar el atributo pixelsMmX.
@param pixelsMmY_in Valor para iniciar el atributo pixelsMmY.
@param pixelsFromOriginX_in Valor para iniciar el atributo pixelsFromOriginX.
@param pixelsFromOriginY_in Valor para iniciar el atributo pixelsFromOriginY.*/
QString GetLabelIndex(int index);
/**< Devuelve la etiqueta de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Etiqueta de la imagen.*/
PhaseImage * GetPhaseImageSourceIndex(int index);
/**< Devuelve el puntero a la imagen de origen de la imagen en la posicin indicada. Debe usarse slo para lectura.
@param index ndice de la imagen.
@return Puntero a la imagen de origen. Puede devolver NULL.*/
PhaseImage * GetPhaseImageIndex(int index);
/**< Devuelve el puntero a la imagen procesada de la imagen en la posicin indicada. Debe usarse slo para lectura.
@param index ndice de la imagen.
@return Puntero a la imagen procesada. Puede devolver NULL.*/
PhaseLine * GetPhaseLineIndex(int index);
/**< Devuelve el puntero a la lnea procesada de la imagen en la posicin indicada. Debe usarse slo para lectura.
@param index ndice de la imagen.
@return Puntero a la lnea procesada. Puede devolver NULL.*/
Data2D * GetData2DIndex(int index);
/**< Devuelve el puntero a los datos 2d de la imagen procesada de la imagen en la posicin indicada. Debe usarse slo para lectura.
@param index ndice de la imagen.
@return Puntero a los datos 2d de la imagen procesada. Puede devolver NULL.*/
Data1D * GetData1DIndex(int index);
/**< Devuelve el puntero a los datos 1d de la lnea procesada de la imagen en la posicin indicada. Debe usarse slo para lectura.
@param index ndice de la imagen.
@return Puntero a los datos 1d lnea procesada. Puede devolver NULL.*/
QImage GetPreviewIndex(int index);
/**< Devuelve, generndola si es necesario, la vista previa de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Vista previa.*/
bool GetUpdatedIndex(int index);
/**< Devuelve el valor del atributo updated de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Atributo updated.*/
float GetPixelsMmXIndex(int index);
/**< Devuelve el valor del atributo pixelsMmX de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Atributo pixelsMmX.*/
float GetPixelsMmYIndex(int index);
/**< Devuelve el valor del atributo pixelsMmY de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Atributo pixelsMmY.*/
int GetPixelsFromOriginXIndex(int index);
/**< Devuelve el valor del atributo pixelsFromOriginX de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Atributo pixelsFromOriginX.*/
int GetPixelsFromOriginYIndex(int index);
/**< Devuelve el valor del atributo pixelsFromOriginY de la imagen en la posicin indicada.
@param index ndice de la imagen.
@return Atributo pixelsFromOriginY.*/
void SetLabelIndex(int index,QString value);
/**< Establece la etiqueta de la imagen en la posicin indicada.
@param index ndice de la imagen.
@param value Etiqueta a establecer.*/
void SetPhaseImageIndex(int index,PhaseImage * value);
/**< Establece la imagen de la fase procesada en la posicin indicada. El cliente pierde la propiedad del puntero. Automticamente actualiza data2d.
@param index ndice de la imagen.
@param value Imagen a establecer.*/
void SetPhaseLineIndex(int index,PhaseLine * value);
/**< Establece la imagen de la lnea procesada en la posicin indicada. El cliente pierde la propiedad del puntero. Automticamente actualiza data1d.
@param index ndice de la imagen.
@param value Lnea a establecer.*/
void SetPreviewIndex(int index,QImage value);
/**< Establece una vista previa personalizada por el usuario en la posicin indicada.
@param index ndice de la imagen.
@param value Imagen de la vista previa.*/
void SetUpdatedIndex(int index,bool value);
/**< Establece el estado de actualizacin de la imagen en la posicin indicada.
@param index ndice de la imagen.
@param value Nuevo estado de actualizacin.*/
void FreePointersIndex(int index);
/**< Libera los diferentes objetos a los que apuntan los atributos de la imagen en la posicin indicada.
@param index ndice de la imagen.*/
void CheckLabels();
/**< Comprueba las etiquetas de la lista de imgenes, modificndolas para que nunca haya dos iguales.*/
bool LoadImageList(QString filePath, AbstractImageFactory * imageFactory);
/**< Carga un fichero .dat con la secuencia de imgenes de la ruta indicada, eliminando la lista anterior.
@param filePath Ruta y nombre del fichero para cargar.
@param imageFactory Puntero a la factora que se deba usar para cargar las imgenes.
@return Verdadero si se carg correctamente.*/
bool SaveImageList(QString filePath);
/**< Guarda un fichero .dat con la secuencia de imgenes de la ruta indicada, eliminando la lista anterior.
@param filePath Ruta y nombre del fichero para guardar.
@return Verdadero si se guard correctamente.*/
};
#endif // IMAGESEQUENCECONTROLLER_H
| true |
d3e0452e7aff250c966fb5c220e5899a9592c7e7 | C++ | k2font/atcoder | /test/kyokasyo.cpp | UTF-8 | 192 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int a = 12345;
int b = 98765;
cout << a + b << endl;
cout << a - b << endl;
cout << numeric_limits<int>::max() << endl;
} | true |
17fd7a499610a84844ff08812e0fa356616618d1 | C++ | Akapulk/KURS_GRAF | /Source.cpp | WINDOWS-1251 | 4,233 | 2.609375 | 3 | [] | no_license | #include <conio.h>
#include <iostream>
#include "pyramid_4.h"
#include "pyramid.h"
using namespace::std;
void cur();
void mainmu();
int q = 1,p=0;
int main() {
setlocale(0, "Russian");
mainmu();
if (p == 1) {
cur();
}
return 0;
}
void mainmu() {
int c, tr = 1;
while (tr)
{
cout << "\t\t\t\t\t\t_20" << endl;
cout << "1)New Game" << endl;
cout << "2)Help" << endl;
cout << "3)Exid" << endl;
c = _getch();
switch (c) {
case 49:
system("cls");
p = 1; tr = 0;
break;
case 50:
system("cls");
cout << ":" << endl;
cout << "(+-)- Z" << endl;
cout << "( /)- Y" << endl;
cout << "( /)- X" << endl;
cout << "( 1/2)- " << endl;
cout << "- " << endl;
cout << "X,Y,Z- " << endl;
cout << "(crtl+ )- -" << endl;
cout << "(crtl+ )- +" << endl;
_getch();
system("cls");
break;
case 51:
system("cls");
cout << " " << endl;
_getch();
tr = 0;
break;
}
}
}
void cur() {
SetConsoleDisplayMode(GetStdHandle(STD_OUTPUT_HANDLE), CONSOLE_FULLSCREEN_MODE, nullptr);
int c;
char flag = '+';
BitMap bmp1(
(int)DIM_BMP_ONE::width,
(int)DIM_BMP_ONE::height,
(int)DIM_BMP_ONE::left_margin,
(int)DIM_BMP_ONE::top_margin,
(COLORREF)COL_BMP::clear
);
BitMap bmp2(
(int)DIM_BMP_TWO::width,
(int)DIM_BMP_TWO::height,
(int)DIM_BMP_TWO::left_margin,
(int)DIM_BMP_TWO::top_margin,
(COLORREF)COL_BMP::clear
);
pyramid_4 b1(
&bmp1,
(size_t)NUM_VER::pyr_4,
(size_t)NUM_FACE::pyr_4
);
pyramid b2(
&bmp2,
(size_t)NUM_VER::pyr,
(size_t)NUM_FACE::pyr
);
figure *ptr = &b1;
bmp1.DrawBitmap();
bmp2.DrawBitmap();
while (q) {
c = _getch();
switch (c) {
case 43://+
ptr->move('z', '+');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 45://-
ptr->move('z', '-');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 72://
ptr->move('y', '-');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 77://
ptr->move('x', '+');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 80://
ptr->move('y', '+');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 75://
ptr->move('x', '-');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 49://1
ptr = &b1;
break;
case 50://2
ptr = &b2;
break;
case 32:
(flag == '+') ? flag = '-' : flag = '+';
break;
case 120://x
ptr->rotate('x', flag);
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 121://y
ptr->rotate('y', flag);
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 122://z
ptr->rotate('z', flag);
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 115://cntrl+
ptr->zoom('-');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 116://cntrl+
ptr->zoom('+');
b1.SetBitMap();
b2.SetBitMap();
bmp1.DrawBitmap();
bmp2.DrawBitmap();
break;
case 27://esc
q = 0;
break;
}
}
} | true |
37b51653d263ab362ea136bf1968d42fb56007f6 | C++ | Odenysyuk/Learning | /WinApi/2016.04.03/Project1/Project1/Source.cpp | UTF-8 | 3,727 | 2.640625 | 3 | [] | no_license | #include <Windows.h>
//#include <tchar.h>
#include <wchar.h>
#include <vector>
#include <iostream>
#include "resource.h"
#include <stdio.h>
float GetDer(std::vector<char*> algoritm) {
float res= 0;
for (int i = 0; i < algoritm.size(); i++)
{
if (algoritm[i] == "+")
{
res = +atoi(algoritm[++i]);
}
else if (algoritm[i] == "-")
{
res = -atoi(algoritm[++i]);
}
else if (algoritm[i] == "*")
{
res = res * atoi(algoritm[++i]);
}
else if (algoritm[i] == "/")
{
res = res / atoi(algoritm[++i]);
}
else
{
return 0;
}
}
return res;
};
BOOL CALLBACK DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static wchar_t temp[255];
static std::vector<char*> algoritm;
static float res = 0, temp_number=0;
switch (uMsg)
{
case WM_INITDIALOG:
return 1;
case WM_LBUTTONDOWN:
{
HWND hCalc = FindWindow(L"CalcFrame",L"Calculator");
SetWindowText(hCalc, L"Copyright");
SendMessage(hCalc, WM_CLOSE, 0, 0);
}
break;
case WM_MOVE:
break;
case WM_COMMAND:
{
switch (wParam)
{
case IDC_ONE:
res = res * 10 + 1;
wcscat_s(temp, L"1");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_TWO:
res = res * 10 + 2;
wcscat_s(temp, L"2");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_THREE:
res = res * 10 + 3;
wcscat_s(temp, L"3");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_FOUR:
res = res * 10 + 4;
wcscat_s(temp, L"4");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_FIVE:
res = res * 10 + 5;
wcscat_s(temp, L"5");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_SIX:
res = res * 10 + 6;
wcscat_s(temp, L"6");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_SEVEN:
res = res * 10 + 7;
wcscat_s(temp, L"7");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_EIGHT:
res = res * 10 + 8;
wcscat_s(temp, L"8");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_NINE:
res = res * 10 + 9;
wcscat_s(temp, L"9");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_ZERO:
if (res != 0)
{
res = res * 10;
wcscat_s(temp, L"0");
SetDlgItemText(hWnd, IDC_RESULT, temp);
}
break;
case IDC_DIVISION:
{
char buff[25];
_itoa_s(res, buff, 10);
algoritm.push_back(buff);
algoritm.push_back("/");
}
res = 0;
wcscat_s(temp, L"/");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_MULTIPLICATION:
{
char buff[25];
_itoa_s(res, buff, 10);
algoritm.push_back(buff);
algoritm.push_back("*");
}
res = 0;
wcscat_s(temp, L"*");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_MINUS:
{
char buff[25];
_itoa_s(res, buff, 10);
algoritm.push_back(buff);
algoritm.push_back("-");
}
res = 0;
wcscat_s(temp, L"-");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_PLUS:
{
char buff[25];
_itoa_s(res, buff, 10);
algoritm.push_back(buff);
algoritm.push_back("+");
}
res = 0;
wcscat_s(temp, L"+");
SetDlgItemText(hWnd, IDC_RESULT, temp);
break;
case IDC_EQUAL:
{
res = GetDer(algoritm);
char buff[25];
_itoa_s(res, buff, 10);
wcscpy_s(temp, (wchar_t *)buff);
SetDlgItemText(hWnd, IDC_RESULT, temp);
}
break;
case IDC_ESC:
res = 0;
wcscpy_s(temp, L"");
SetDlgItemText(hWnd, IDC_RESULT, L"0");
break;
return 1;
}
}
break;
case WM_CLOSE:
EndDialog(hWnd, 0);
return 1;
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR nCmd, int nCmdShow)
{
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc);
return 0;
} | true |
0ac1795314b4f049e6666a6db2517d636e18cc5b | C++ | yinyinyin123/LintCode | /0497-Shape Factory/0497-Shape Factory.cpp | UTF-8 | 1,318 | 3.734375 | 4 | [
"MIT"
] | permissive | /**
* Your object will be instantiated and called as such:
* ShapeFactory* sf = new ShapeFactory();
* Shape* shape = sf->getShape(shapeType);
* shape->draw();
*/
class Shape {
public:
virtual void draw() const=0;
};
class Rectangle: public Shape {
// Write your code here
public:
void draw() const {
cout << " ----" << endl;
cout << "| |" << endl;
cout << " ----" << endl;
}
};
class Square: public Shape {
// Write your code here
public:
void draw() const {
cout << " ----" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << " ----" << endl;
}
};
class Triangle: public Shape {
// Write your code here
public:
void draw() const {
cout << " /\\" << endl;
cout << " / \\" << endl;
cout << "/____\\" << endl;
}
};
class ShapeFactory {
public:
/**
* @param shapeType a string
* @return Get object of type Shape
*/
Shape* getShape(string& shapeType) {
// Write your code here
if (shapeType == "Square")
{
return new Square();
}
else if (shapeType == "Triangle")
{
return new Triangle();
}
else
{
return new Rectangle();
}
}
};
| true |
eff2824839e72b3977d99e8eb9f32cee7aeef598 | C++ | josh-windsor/DirectX-VR-Instanced-Renderer | /Framework/VertexFormats.h | UTF-8 | 3,869 | 2.78125 | 3 | [] | no_license | #pragma once
//////////////////////////////////////////////////////////////////////
// Vertex Formats.
//////////////////////////////////////////////////////////////////////
using VertexColour = u32;
//////////////////////////////////////////////////////////////////////////
// vertex descriptors are described using type traits.
// redefine the following for each vertex type.
// see examples for further info.
//////////////////////////////////////////////////////////////////////////
template <typename T> struct VertexFormatTraits {};
//////////////////////////////////////////////////////////////////////////
// Position and Colour
//////////////////////////////////////////////////////////////////////////
struct Vertex_Pos3fColour4ub
{
DirectX::XMFLOAT3 pos;
VertexColour colour;
Vertex_Pos3fColour4ub();
Vertex_Pos3fColour4ub(const DirectX::XMFLOAT3 &pos, VertexColour colour);
};
template <> struct VertexFormatTraits<Vertex_Pos3fColour4ub> {
static const D3D11_INPUT_ELEMENT_DESC desc[];
static const u32 size = 2;
};
//////////////////////////////////////////////////////////////////////////
// Position, Colour and Texture Coordinate
//////////////////////////////////////////////////////////////////////////
struct Vertex_Pos3fTex2fColour4ub
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 tex;
VertexColour colour;
Vertex_Pos3fTex2fColour4ub();
Vertex_Pos3fTex2fColour4ub(const DirectX::XMFLOAT3 &pos, const DirectX::XMFLOAT2 &tex, VertexColour colour);
};
template <> struct VertexFormatTraits<Vertex_Pos3fTex2fColour4ub> {
static const D3D11_INPUT_ELEMENT_DESC desc[];
static const u32 size = 3;
};
//////////////////////////////////////////////////////////////////////////
// Position, Colour and Normal
//////////////////////////////////////////////////////////////////////////
struct Vertex_Pos3fColour4ubNormal3f
{
DirectX::XMFLOAT3 pos;
VertexColour colour;
DirectX::XMFLOAT3 normal;
Vertex_Pos3fColour4ubNormal3f();
Vertex_Pos3fColour4ubNormal3f(const DirectX::XMFLOAT3 &pos, VertexColour colour, const DirectX::XMFLOAT3 &normal);
};
template <> struct VertexFormatTraits<Vertex_Pos3fColour4ubNormal3f> {
static const D3D11_INPUT_ELEMENT_DESC desc[];
static const u32 size = 3;
};
//////////////////////////////////////////////////////////////////////////
// Position, Colour, Normal and Texture
//////////////////////////////////////////////////////////////////////////
struct Vertex_Pos3fColour4ubNormal3fTex2f
{
DirectX::XMFLOAT3 pos;
VertexColour colour;
DirectX::XMFLOAT3 normal;
DirectX::XMFLOAT2 tex;
Vertex_Pos3fColour4ubNormal3fTex2f();
Vertex_Pos3fColour4ubNormal3fTex2f(const DirectX::XMFLOAT3 &pos, VertexColour colour, const DirectX::XMFLOAT3 &normal, const DirectX::XMFLOAT2 &tex);
};
template <> struct VertexFormatTraits<Vertex_Pos3fColour4ubNormal3fTex2f> {
static const D3D11_INPUT_ELEMENT_DESC desc[];
static const u32 size = 4;
};
//////////////////////////////////////////////////////////////////////////
// Position, Colour, Normal, Tangent (+sign) and Texture
//////////////////////////////////////////////////////////////////////////
struct Vertex_Pos3fColour4ubNormal3fTangent3fTex2f
{
DirectX::XMFLOAT3 pos;
VertexColour colour;
DirectX::XMFLOAT3 normal;
DirectX::XMFLOAT4 tangent;
DirectX::XMFLOAT2 tex;
Vertex_Pos3fColour4ubNormal3fTangent3fTex2f();
Vertex_Pos3fColour4ubNormal3fTangent3fTex2f(const DirectX::XMFLOAT3 &pos, VertexColour colour, const DirectX::XMFLOAT3 &normal, const DirectX::XMFLOAT2 &tex);
Vertex_Pos3fColour4ubNormal3fTangent3fTex2f(const DirectX::XMFLOAT3 &pos, VertexColour colour, const DirectX::XMFLOAT3 &normal, const DirectX::XMFLOAT4 &tangent, const DirectX::XMFLOAT2 &tex);
};
template <> struct VertexFormatTraits<Vertex_Pos3fColour4ubNormal3fTangent3fTex2f> {
static const D3D11_INPUT_ELEMENT_DESC desc[];
static const u32 size = 5;
}; | true |
7dd63734e6f963ef06bc6c57eb2bf9f49f86df40 | C++ | Fol4/algo-semester1-2020-master | /task_2/section_2/2_3/2_3.cpp | UTF-8 | 1,619 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <vector>
void quickSort(std::vector<std::pair<int, int>>& array, int low, int high){
int i = low;
int j = high;
int pivot = array[(i + j) / 2].first;
int temp;
while (i <= j){
while (array[i].first < pivot)
i++;
while (array[j].first > pivot)
j--;
if (i <= j){
std::swap(array[i], array[j]);
i++;
j--;
}
}
if (j > low)
quickSort(array, low, j);
if (i < high)
quickSort(array, i, high);
}
std::vector<std::pair<int, int>> merge(std::vector<std::pair<int, int>>& array) {
int i = 0;
std::vector<std::pair<int, int>> newArray;
while (i < array.size()) {
int count = 0;
int maxEnd = i;
for (int j = i; j < array.size() - 1 and (array[maxEnd].second >= array[j + 1].first); ++j) {
count++;
if (array[j+1].second > array[maxEnd].second) {
maxEnd = j+1;
}
}
newArray.push_back({ array[i].first, array[maxEnd].second });
i += count + 1;
}
return newArray;
}
int count(std::vector<std::pair<int, int>>& array) {
int c = 0;
for (int i = 0; i < array.size(); ++i) {
c += array[i].second - array[i].first;
}
return c;
}
int main() {
int n;
std::cin >> n;
std::vector<std::pair<int, int>> section(n);
for (int i = 0; i < n; ++i) {
std::cin >> section[i].first >> section[i].second;
}
quickSort(section, 0, n - 1);
section = merge(section);
std::cout << count(section) << std::endl;
} | true |
75f044a27e342c16bc38810c8aaff4afd0074da3 | C++ | xznxzy/Data_Structure | /Stack/MyStack.hpp | UTF-8 | 936 | 3.328125 | 3 | [] | no_license | //
// MyStack.hpp
// Stack
//
// Created by zhangying on 10/2/17.
// Copyright © 2017 zhangying. All rights reserved.
//
#ifndef MyStack_hpp
#define MyStack_hpp
#include <stdio.h>
#include <iostream>
using namespace std;
template <typename T>
class MyStack{
public:
//分配内存初始化栈空间,设定栈容量,栈顶
MyStack(int size);
//回收栈空间内存
~MyStack();
//判定栈是否为空,为空返回true,非空返回false
bool stackEmpty();
//判断栈是否已满,为满返回true,不满返回false
bool stackFull();
//清空栈
void clearStack();
//已有元素的个数
int stackLength();
//元素入栈,栈顶上升
bool push(T elem);
//元素出栈,栈顶下降
bool pop(T &elem);
//遍历栈中所有元素
void stackTraverse();
private:
T * m_pBuffer; //栈空间指针
int m_iSize; //栈容量
int m_iTop; //栈顶,栈中元素个数
};
#endif /* MyStack_hpp */
| true |
94030027a81347bc9f378967ae62cb647cb18b29 | C++ | wonder-alt/- | /2020-11-29/2020-11-29/源.cpp | GB18030 | 1,964 | 3.9375 | 4 | [] | no_license | //ָ018ַ
//Ӽnn<100ַ(ÿַȲ19)ַеĻַ
//жһַǷΪַúʵַ֣ܹ±ַָʽʵ֡
//νĴָ˳͵һһַ硱levelabccbaǻĴ
//ʽһΪnΪnַ
//#include<iostream>
//using namespace std;
//int main()
//{
// char s[20];
// int n;
// int count = 0;
// cin >> n;
// int i = 0;
// int j = 0;
// int k = 0;
// int len = 0;
// for (k = 0; k < n; k++)
// {
// cin >> s;
// i = 0;
// while (s[i] != '\0')
// {
// i++;
// len++;
// }
// for (i = 0, j = len - 1; i < len / 2; i++, j--)
// {
// if (s[i] != s[j])
// break;
// else
// count++;
// }
// if (count == len /2)
// cout << s<<" ";
// }
// return 0;
//}
//Ӽnn<100ַ(ÿַȲ19)ַеĻַ
//жһַǷΪַúʵַ֣ܹ±ַָʽʵ֡
//νĴָ˳͵һһַ硱levelabccbaǻĴ
//ʽһΪnΪnַ
//#include<iostream>
//using namespace std;
//int main()
//{
// int n;
// cin >> n;
// int i = 0;
// char s[19];
// int x = 123;
// int *a = &x;
// cout << a << endl;
// cout << *a << endl;
//
// for (i = 0; i < n; i++)
// {
//
//
// cin >> s;
// char *p = s;
// cout << &p << endl;
// cout << *(p+2)<<" "<<s[2]<<" "<<p[2] << endl;
// for (p = s; *p != '\0'; p++)
// {
// cout << *p << " ";
// cout << (float * )&p << endl;
// }
// }
//
// return 0;
//}
#include<iostream>
using namespace std;
int main()
{
int s[100];
cin >> s;
return 0;
} | true |
4ae95d743dda3b18fe775454fc63c190f2f68a5b | C++ | Fernand0D/Calculadora | /Proyecto calculadora.cpp | UTF-8 | 2,244 | 4.125 | 4 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
int main() {
int pos, num1, num2, resultado;
cout << "Ingrese la opcion deseada :3" << endl;
cout << "1-. Suma" << endl;
cout << "2-. Resta" << endl;
cout << "3.- Multiplicacoin" << endl;
cout << "4.- Division" << endl;
cout << "5.- Raiz" << endl;
cout << "6.- Potencia" << endl;
cin >> pos;
system("cls");
switch (pos) {
case 1:
cout << "\n Suma. " << endl;
cout << "Ingrese los numeros para a sumar " << endl;
cout << "Dame El Primer numero:";
cin >> num1;
cout << "Dame EL Segundo numero:";
cin >> num2;
resultado = num1 + num2;
cout << "\n Resultado:" << resultado << endl;
break;
case 2:
cout << "\n Resta. " << endl;
cout << "Ingrese los numeros para restar " << endl;
cout << "Dame el Primer numero:";
cin >> num1;
cout << "Dame el Segundo numero:";
cin >> num2;
resultado = num1 - num2;
cout << "\n Resultado:" << resultado << endl;
break;
case 3:
cout << "\n Multiplicacion. " << endl;
cout << "Ingrese los numeros para multiplcar " << endl;
cout << "Dame el Primer numero:";
cin >> num1;
cout << "Dame el Segundo numero:";
cin >> num2;
resultado = num1 * num2;
cout << "\n Resultado:" << resultado << endl;
break;
case 4:
cout << "\n Division. " << endl;
cout << "Ingrese los numeros para dividir " << endl;
cout << "Dame el Primer numero:";
cin >> num1;
cout << "Dame el Segundo numero:";
cin >> num2;
resultado = num1 / num2;
cout << "\n Resultado:" << resultado << endl;
break;
case 5:
cout << "\n Riaz. " << endl;
cout << "Ingrese los numeros a sumar " << endl;
cout << "Dame el Primer numero:";
cin >> num1;
cout << "Dame el Segundo numero:";
cin >> num2;
resultado = (sqrt(num1));
cout << "\n Resultado:" << resultado << endl;
break;
case 6:
cout << "\n Potencia. " << endl;
cout << "Dame elIngrese los numeros a sumar " << endl;
cout << "Primer numero:";
cin >> num1;
cout << "Dme el Segundo numero:";
cin >> num2;
resultado = (pow(num1, num2));
cout << "\n Resultado:" << resultado << endl;
break;
default:
cout << "\n Opcion no valida";
break;
}
return 0;
}
| true |
af2dcd2683b825a86d0758fbcf69bd82cb3c2a76 | C++ | mopack/OnlineJudgeCode | /OnlineJudgeCode/LC328. Odd Even Linked List.cpp | UTF-8 | 1,965 | 2.5625 | 3 | [] | no_license | //#include <iostream>
//#include <cstdlib>
//#include <vector>
//#include <string>
//#include <algorithm>
//#define max(a,b) (((a) > (b)) ? (a) : (b))
//using namespace std;
////Sol: Coding: min. Present: AC: Lines/ms/PR
////Sol: . Present: AC: Lines/ms/PR
//struct ListNode {
// int val;
// ListNode *next;
// ListNode(int x) : val(x), next(NULL) {}
//};
//static int fast = []() {ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }();
//class Solution {
//public:
// ListNode* oddEvenList(ListNode* t) {
// if (!t || !t->next) return t;
// ListNode *o = t, *e = t->next, *eSt = e, *oSt = o;
//
// while (t->next && t->next->next ) {
// t = t->next->next;
// o->next = t, o = t;
// e->next = t->next, e = t->next;
// }
// if(t) o->next = t, o = t;
// o->next = eSt;
//
// return oSt;
// }
//};
//
////8ms/PR100
//#define Next(x, y) (x->next = y, x = x->next)
//static int fast = []() {ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }();
//class Solution {
//public:
// ListNode* oddEvenList(ListNode* t) {
// if (!t || !t->next) return t;
// ListNode *o = t, *e = t->next, *eSt = e, *oSt = o;
//
// while (t->next && t->next->next) {
// t = t->next->next;
// Next(o, t);
// Next(e, t->next);
// }
// if (t) Next(o, t);
// o->next = eSt;
//
// return oSt;
// }
//};
//
//#define Next(x, y) (x->next = y, x = x->next)
//static int fast = []() {ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }();
//class Solution {
//public:
// ListNode* oddEvenList(ListNode* H) {
// if (!H || !H->next) return H;
// ListNode *t = H, *o = t, *e = t->next, *eSt = e;
//
// while (t->next && t->next->next) {
// t = t->next->next;
// Next(o, t);
// Next(e, t->next);
// }
// if (t) Next(o, t);
// o->next = eSt;
//
// return H;
// }
//};
//
//int main() {
// //freopen("in.txt", "rt", stdin); freopen("outwjio.txt", "wt", stdout);
// class Solution az;
// system("pause");
// return 0;
//} | true |
92147f82ec3ffcd7f47add4c75db7aee795cfa81 | C++ | Saborit/Competitive-Programming | /SNIPPET ZONE/IMP. AJENAS/2-Algorithms Implementations/Fibonacci Sequence.cpp | ISO-8859-1 | 474 | 3 | 3 | [] | no_license | /*
Luis Enrique Bernal Fuentes
Algorithm: Fibomacci Sequence
Description: Halla el nmero de la Secuencia Fibonaci que cae en tal posicin.
*/
#include <cstdio>
#include <algorithm>
using namespace std;
int n;
long long a = 0, b = 1, fib;
int main() {
scanf ("%d", &n);
if (n <= 2)
printf ("1\n");
else {
for (int i = 3; i <= n; i++) {
fib = a + b;
a = b;
b = fib;
}
printf ("%I64d\n", fib);
}
system ("pause > nul");
return 0;
}
| true |
13fa8f1e696d4768446d68fe343eba5017ce9f30 | C++ | Deepanshu2017/boost.python_practise | /cpp_revision/advance C++/rvalue_lvalue.cpp | UTF-8 | 1,053 | 3.40625 | 3 | [] | no_license | //lvalue is something that has address and modifiable and we can
//store some data in that memory
//int i = 5;
// ^--------->i is lvalue
// ^----->5 is rvalue
//because we can get address of i but we cannot get the address of 5
//
//int i = 5;
//int var = i;
// ^---> i is lvalue but in the above context i is implicity
// transformed into rvalue
//so lavlue can be implicitly transformed into rvalue but otherway
//around is not possible. To transform rvalue into lavlue we have to
//do it explicitly
//int v[10];
//*(v + 2) = 5;
// ^^^^^---------> v + 2 is rvalue but *(v + 2) is lvalue
//Every C++ expression uses either rvalue or lvalue
//If the expression has an identifiable memory address, it's lvalue
//other wise it is rvalue
//C defination of lvalue-->"value suitable for left hand side ofassignment"
//^above defination is no longer true in C++
#include <iostream>
using namespace std;
int myglobal = 0;
int &foo() {
return myglobal;
}
int main(void) {
foo() = 50;
cout << myglobal << endl;
return 0;
}
| true |
cd0ac1fdcdea1a4e1fe98130b0795d69209ba970 | C++ | derbess/PP1-assist | /quiz3/bonapity.cpp | UTF-8 | 1,401 | 3.09375 | 3 | [] | no_license | #include<iostream>
using namespace std;
bool ponapity(string s1, string s2){
int cnt = 0;
if(s1.size()==s2.size())
{
for(int i=0;i<s1.size();i++)
{
s1[i] = tolower(s1[i]);
s2[i] = tolower(s2[i]);
if(s1[i]==s2[i])
{
cnt++;
}
else if((s1[i]=='B'&&s2[i]=='p')||(s1[i]=='b'&&s2[i]=='P')||(s1[i]=='P'&&s2[i]=='b')||(s1[i]=='p'&&s2[i]=='B')||(s1[i]=='B'&&s2[i]=='P')||(s1[i]=='b'&&s2[i]=='p')||(s1[i]=='P'&&s2[i]=='B')||(s1[i]=='p'&&s2[i]=='b'))
{
cnt++;
}
else if((s1[i]=='E'&&s2[i]=='i')||(s1[i]=='e'&&s2[i]=='I')||(s1[i]=='I'&&s2[i]=='e')||(s1[i]=='i'&&s2[i]=='E')||(s1[i]=='E'&&s2[i]=='I')||(s1[i]=='e'&&s2[i]=='i')||(s1[i]=='I'&&s2[i]=='E')||(s1[i]=='i'&&s2[i]=='e'))
{
cnt++;
}
}
if(cnt==s1.size()) return true;
else return false;
}
else return false;
}
bool bonapity(string s1, string s2)
{
if(s1.size() == s2.size())
{
for(int i=0;i<s1.size();i++)
{
s1[i] = tolower(s1[i]);
s2[i] = tolower(s2[i]);
if(s1[i] == 'p') s1[i] = 'b';
else if(s1[i] == 'e') s1[i] = 'i';
if(s2[i] == 'p') s2[i] = 'b';
else if(s2[i] == 'e') s2[i] = 'i';
}
if(s1==s2) return true;
else return false;
}
else return false;
}
int main()
{
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
string s1,s2;
cin>>s1>>s2;
if(bonapity(s1,s2)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
ponabity bonabety
bonabity bonabity | true |
27dfe63f78c2f56ee7e723fb54931dd459c82e47 | C++ | walekkk/search_system | /search_client/common/log.h | UTF-8 | 835 | 2.796875 | 3 | [] | no_license | #ifndef LOG_H
#define LOG_H
#include <iostream>
#include <string>
#include <sys/time.h>
#include "./common.h"
#define INFO 0
#define ERROR 1
#define DEBUG 2
int64_t GetTimeStamp() {
struct timeval mTime;
gettimeofday(&mTime, NULL);
return mTime.tv_sec;
}
std::string GetLogLevel(int32_t level) {
switch(level) {
case 0:
return "INFO";
case 1:
return "ERROR";
case 2:
return "DEBUG";
default:
return "UNKNOW";
}
}
void LOG(int level, std::string massage,
std::string file, int line) {
std::cout << "【 " << GetTimeStamp() << ", "
<< GetLogLevel(level) << ", " << file << " : "
<< line << " 】" << massage << std::endl;
}
#define LOG(level, massage) LOG(level, massage, __FILE__, __LINE__)
#endif
| true |
ea2e6bb3f314ed9ba95b6851d4cb816ed9e126d2 | C++ | flameshimmer/leet2019.io | /Leet2019/MaximumDistanceinArrays.cpp | UTF-8 | 2,166 | 3.53125 | 4 | [] | no_license | #include "stdafx.h"
//Given m arrays, and each array is sorted in ascending order.
//Now you can pick up two integers from two different arrays
//(each array picks one) and calculate the distance. We define
//the distance between two integers a and b to be their absolute
//difference |a-b|. Your task is to find the maximum distance.
//
//Example 1:
//Input:
//[[1,2,3],
// [4,5],
// [1,2,3]]
//Output: 4
//Explanation:
//One way to reach the maximum distance 4 is to pick 1 in the
//first or third array and pick 5 in the second array.
//Note:
//Each given array will have at least 1 number. There will be at least two non-empty arrays.
//The total number of the integers in all the m arrays will be in the range of [2, 10000].
//The integers in the m arrays will be in the range of [-10000, 10000].
namespace Solution2019
{
namespace MaximumDistanceinArrays
{
int maxDistance(vector<vector<int>>& arrays) {
int left = arrays[0].front();
int right = arrays[0].back();
int result = 0;
for (int i = 1; i < arrays.size(); i++) {
vector<int> a = arrays[i];
result = max(result, max(right - a.front(), a.back() - left));
left = min(left, a.front());
right = max(right, a.back());
}
return result;
}
int maxDistanceAnother(vector<vector<int>>& arrays) {
int min1 = INT_MAX;
int min2 = INT_MAX;
int max1 = INT_MIN;
int max2 = INT_MIN;
int imin1 = -1;
int imin2 = -1;
int imax1 = -1;
int imax2 = -1;
for (int i = 0; i < arrays.size(); i++) {
int vmin = arrays[i][0];
if (vmin < min1) {
min2 = min1;
imin2 = imin1;
min1 = vmin;
imin1 = i;
}
else if (vmin < min2) {
min2 = vmin;
imin2 = i;
}
int vmax = arrays[i][arrays[i].size() - 1];
if (vmax > max1) {
max2 = max1;
imax2 = imax1;
max1 = vmax;
imax1 = i;
}
else if (vmax > max2) {
max2 = vmax;
imax2 = i;
}
}
int result = 0;
if (imin1 != imax1) { result = max1 - min1; }
else {
result = max(max1 - min2, max2 - min1);
}
return result;
}
void Main() {
string test = "tst test test";
print(test);
}
}
}
| true |
ab10fcdff4f958653db45f04509927b3c65ac151 | C++ | lvirgili/programming_challenges | /uri/uri1393.cpp | UTF-8 | 273 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
long long fib[41];
fib[0] = fib[1] = 1;
fib[2] = 2;
for (int i = 3; i < 41; ++i) fib[i] = fib[i-1] + fib[i-2];
int n;
while (cin >> n, n) {
cout << fib[n] << endl;
}
return 0;
}
| true |
457b70795b52718ee36550cd7137345882cf6d52 | C++ | shoaibrayeen/Programmers-Community | /Basic/Reverse A Given Number/solutionByPooja.cpp | UTF-8 | 461 | 4.28125 | 4 | [
"MIT"
] | permissive | /*
A Number is given and You need to reverse it.
Input :
An Integer ( Positive )
*/
#include <iostream>
using namespace std;
int reverse(int num)
{
int rev = 0;
for (int i = 1; num > 0; i++) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
int main()
{
int num;
cout << "Enter a number ";
cin >> num;
if (num >= 0)
cout << "\nReverse of " << num << " is " << reverse(num);
}
| true |
7024e8c932bdc10e0df746258f6031a7ff31f701 | C++ | 3DPIT/algorithmTest | /Algorithm(2020.05.06)/SWTEST/SWTEST/17143 낚시왕(프린트).cpp | UHC | 2,473 | 2.671875 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
#define NS 101
#define MS 101
int N, M, K;
int ret;
struct Data {
int y, x, s, d, z;
};
vector<Data>v;
void init() {
N = M = K = ret = 0;
v.clear();
scanf("%d %d %d", &N, &M, &K);
for (int i = 0; i < K; i++) {
Data c;
scanf("%d %d %d %d %d", &c.y, &c.x, &c.s, &c.d, &c.z);
v.push_back(c);
}
}
bool cmp(Data a, Data b) {
if (a.y == b.y) {
return a.x < b.x;
}
return a.y < b.y;
}
bool cmp1(Data a, Data b) {
if (a.y == b.x&&a.y <= b.x) return a.z > b.z;
}
void P(string name, int idx) {
cout << name << endl;
if (idx == 0) {
for (int i = 0; i < v.size(); i++) {
printf("%d %d %d", v[i].y, v[i].x, v[i].z);
cout << endl;
}
}
}
int dy[] = { 0,-1,1,0,0 };
int dx[] = { 0, 0,0,1,-1 };
bool safe(int y, int x) {
return 1 <= y && y <= N && 1 <= x && x <= M;
}
void eat(int x) {
for (int k = 0; k < v.size(); k++) {
if (v[k].x == x) {
ret += v[k].z;
v.erase(v.begin() + k);
break;
}
}
}
void equlPosEat() {
for (int k = 0; k < v.size() - 1; k++) {
if (v.size() == 0)break;
if (v[k].y == v[k + 1].y&&v[k].x == v[k + 1].x) {
if (v[k].z < v[k + 1].z) {
v[k] = v[k + 1];
v.erase(v.begin() + k + 1);
k--;
}
else {
v.erase(v.begin() + k + 1);
k--;
}
}
}
}
void fishing() {
for (int i = 1; i <= M; i++) {
if (v.size() == 0) break;
sort(v.begin(), v.end(), cmp);
eat(i);
//cout << ret << endl;
for (int k = 0; k < v.size(); k++) {
Data n;
n.y = v[k].y;
n.x = v[k].x;
n.d = v[k].d;
if (v[k].d == 1 || v[k].d == 2) {
n.s = v[k].s % ((N * 2) - 2);
}
else {
n.s = v[k].s % ((M * 2) - 2);
}
for (int t = 0; t < n.s; t++) {
n.y += dy[n.d]; n.x += dx[n.d];
if (!safe(n.y, n.x)) {
n.y -= dy[n.d];
n.x -= dx[n.d];
if (n.d == 1) {
n.d = 2;
}
else if (n.d == 2) {
n.d = 1;
}
else if (n.d == 3) {
n.d = 4;
}
else if (n.d == 4) {
n.d = 3;
}
n.y += dy[n.d];
n.x += dx[n.d];
}
}
v[k].y = n.y;
v[k].x = n.x;
v[k].d = n.d;
}
//cout << i << endl;
sort(v.begin(), v.end(), cmp);
//P("Ȯ", 0);
equlPosEat();
//P(" ", 0);
}
}
int main(void) {
int T = 1;
for (int t = 1; t <= T; t++) {
init();
fishing();
printf("#%d %d\n", t, ret);
printf("%d\n", ret);
}
return 0;
} | true |
19918ae9b76cc4ddb651a118f16aa6da3b5db250 | C++ | darkoppressor/escape-from-the-masters-lair | /grammar.cpp | UTF-8 | 804 | 2.625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /* Copyright (c) 2011 Kevin Wells */
/* Escape from the Master's Lair may be freely redistributed. See license for details. */
#include "grammar.h"
#include "world.h"
using namespace std;
string a_vs_an(Item* item){
string a_or_an="";
//If the item is a corpse or skeleton.
if(item->is_corpse || item->is_skeleton){
a_or_an=templates.template_races[item->race].prefix_article;
}
//If the item is anything else.
else{
a_or_an=item->prefix_article;
}
return a_or_an;
}
string a_vs_an(Creature* creature){
string a_or_an="";
a_or_an=templates.template_races[creature->race].prefix_article;
return a_or_an;
}
string a_vs_an(short race){
string a_or_an="";
a_or_an=templates.template_races[race].prefix_article;
return a_or_an;
}
| true |
455ab46a0ca9376bea18ab25bdc9cde1d5202291 | C++ | jgcazares/Badlands | /explosion.h | UTF-8 | 1,267 | 2.609375 | 3 | [] | no_license | //needed includes for cross platform developement
#if defined (_WIN32) || (WIN64)
#include "SDL.h"
#include "SDL_image.h"
#endif
#if defined (__APPLE__)
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#include <SDL2_mixer/SDL_mixer.h>
#endif
#if defined (__linux__)
#include SDL2/SDL2.h
#include SDL2/SDL_image.h
#endif
#include <string>
#include <iostream>
using namespace std;
class Explode {
public:
//boolean for the state of the explosion
bool active;
//explosion rectangle for positions
SDL_Texture *texture;
//explosion rectanglefor position
SDL_Rect posRect;
//explosion rectangle for position
SDL_Rect drawRect;
//width ad height of each frame plus width and height of entire image
int frameWidth, frameHeight, textureWidth, textureHeight;
//float values to track time until next frame of aniamtion
float frameCounter;
//explode creation method, requires the renderer a path to the needed image and x position and y position
Explode(SDL_Renderer *renderer, string filePath, float x, float y);
//explode update requires delta time
void Update(float deltaTime);
//explode draw requires renderer to be passed
void Draw(SDL_Renderer *renderer);
//explode reset
void Reset();
//explode destruction
~Explode();
};
| true |
600ace444fd2161aea896f93fbdb9296fd2b9e72 | C++ | lucifercr07/GFG | /HE/HE/prateekndquery.cpp | UTF-8 | 617 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> vec(n);
for(int i=0;i<n;i++)
cin>>vec[i];
sort(vec.begin(),vec.end());
//for(int i=0;i<n;i++)
// cout<<vec[i]<<" ";
//cout<<endl;
int q;
cin>>q;
while(q--)
{
int a,b;
cin>>a>>b;
vector<int>::iterator low,up,it;
low=lower_bound(vec.begin(),vec.end(),a);
up=upper_bound(vec.begin(),vec.end(),b);
int count=0;
if(*low==0&&*up==0)
{
}
else if(*low!=0&&*up==0)
{
for(it=low;it!=vec.end();++it)
count++;
}
else
{
for(it=low;it<up;++it)
count++;
}
cout<<count<<endl;
}
} | true |
1c6eba39a7ad3472be068732214e08bae2a14fb0 | C++ | mom4ilakis/DSA-Homework-task-4 | /TripleTree/TripleTree.cpp | UTF-8 | 3,105 | 3.28125 | 3 | [] | no_license | #include "TripleTree.h"
//TripleTree::TripleTree()
//{
//}
TripleTree::TripleTree(const std::string & filename):root(nullptr)
{
loadFromFile(filename);
}
TripleTree::~TripleTree()
{
clear(root);
}
void TripleTree::loadFromFile(const std::string & Filename)
{
std::ifstream inputFile;
inputFile.open(Filename);
if (inputFile.is_open())
{
clear(root);
std::cout << "Loading from... " << Filename << '\n';
char symbol;
eatFiller(inputFile);
symbol = inputFile.get();
if (symbol != '*')
{
node * left = createNode(inputFile, 'l');
node * center = createNode(inputFile, 'c');
node * right = createNode(inputFile, 'r');
root = new node(symbol, left, center, right);
}
}
else
std::cout << "Failed to load from: " << Filename << '\n';
inputFile.close();
}
void TripleTree::NormalPrint() const
{
printRRL(root);
}
void TripleTree::PrintByLevels() const
{
WeirdPrint();
}
void TripleTree::WeirdPrint() const
{
unsigned cur_level = 0;
std::unordered_map<int, std::vector<node>> levels;
preorder(root, 1, levels);
std::unordered_map<int, std::vector<node>>::iterator it = levels.begin(), end = levels.end();
while (it != end)
{
for (const node& n : it->second)
std::cout << n.data;
std::cout << '\n';
++it;
}
//MyPrint(root);
}
void TripleTree::preorder(const node * ptr, unsigned level, std::unordered_map<int, std::vector<node>>& lev) const
{
if (ptr == nullptr)
return;
lev[level].push_back(*ptr);
preorder(ptr->left_chl, level + 1, lev);
preorder(ptr->center_cld, level + 1, lev);
preorder(ptr->right_chl, level + 1, lev);
}
void TripleTree::MyPrint(const node * tmp, unsigned level) const
{
if (tmp == nullptr)
return;
level++;
std::cout << tmp->data;
MyPrint(tmp->left_chl);
MyPrint(tmp->center_cld);
MyPrint(tmp->right_chl);
}
void TripleTree::printRRL(const node* tmp) const
{
if (tmp == nullptr)
return;
std::cout << tmp->data;
printRRL(tmp->left_chl);
printRRL(tmp->center_cld);
printRRL(tmp->right_chl);
}
TripleTree::node * TripleTree::createNode(std::ifstream & is, char cld)
{
unsigned number_stars = 0;
char symbol;
node* tmp = nullptr, *left = nullptr, *center = nullptr, *right = nullptr;
eatFiller(is);
symbol = is.get();
if (symbol != '*')
{
left = createNode(is, 'l');
center = createNode(is, 'c');
right = createNode(is, 'r');
tmp = new node(symbol, left, center, right);
}
return tmp;
}
void TripleTree::eatFiller(std::ifstream & is)
{
while(is.good() && (is.peek() == '(' || is.peek() == ')' || is.peek() == ' '))
is.get();
}
void TripleTree::clear(node * tmp)
{
if (tmp != nullptr)
{
clear(tmp->left_chl);
clear(tmp->right_chl);
clear(tmp->center_cld);
delete tmp;
}
}
TripleTree::node::node(char data, node * left_c, node * center_c, node * right_c) :data(data), left_chl(left_c), right_chl(right_c), center_cld(center_c)
{
;
}
| true |
f528f35d73946d7cd69651211a904bcf45ef9ad3 | C++ | karan109/Traffic-Density-Estimation | /Code/method2.cpp | UTF-8 | 2,418 | 2.96875 | 3 | [] | no_license | #include "helpers.hpp"
string file_name = "trafficvideo.mp4";
int X;
int Y;
int original_X;
int original_Y;
string output_file;
vector<vector<double>> result;
void method2();
int main(int argc, char* argv[]){
if (argc >= 2) file_name = argv[1];
VideoCapture getres;
getres.open("../Data/Videos/"+file_name);
if (getres.isOpened() == false){
cout << "Cannot open the video file. Please provide a valid name (refer to README.md)." << endl;
exit(3);
}
Mat temp;
getres.read(temp);
original_Y = temp.rows;
original_X = temp.cols;
X = original_X;
Y = original_Y;
getres.release();
if (argc >= 3) {
if(!isint(argv[2]) || stoi(argv[2]) <= 0 ) {
cout << "X resolution is not a positive integer." << endl;
return 0;
}
X = stoi(argv[2]);
}
if (argc == 4) {
if(!isint(argv[3]) || stoi(argv[3]) <= 0 ) {
cout << "Y resolution is not a positive integer." << endl;
return 0;
}
Y = stoi(argv[3]);
}
method2();
}
void method2 () {
VideoCapture cap;
cap.open("../Data/Videos/"+file_name); // Capture video
// if not success, exit program
if (cap.isOpened() == false) {
cout << "Cannot open the video file. Please provide a valid name (refer to README.md)." << endl;
exit(3);
}
auto start = high_resolution_clock::now(); // Start clock to get run-time
// Extract frame data
// result = getDensityDataResolutionEasy(cap, X, Y);
result = getDensityDataResolution(cap, X, Y, original_X, original_Y);
cap.release(); // Close the VideoCapture
auto stop = high_resolution_clock :: now(); // Stop clock
auto duration = duration_cast<microseconds> (stop - start); // Get duration
// Output file
output_file = "../Analysis/Outputs/Method2/"+to_string(X)+ "x" + to_string(Y) + "_test.txt";
fstream f(output_file, ios::out);
f << "Frame_Num,Queue_Density,Dynamic_Density" << endl;
for(int i = 1 ; i < result.size() ; i++) {
f << result[i][0] << "," << result[i][1] << "," << result[i][2] << endl;
}
// Append the time taken for analysis
f << duration.count();
cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
cout << "Output saved to " << output_file << endl;
f.close();
}
| true |
a407739513f2323768e7c03a68bde88220bb182b | C++ | mcwall/skylark | /src/loader.cpp | UTF-8 | 774 | 2.96875 | 3 | [] | no_license | #include "loader.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <stdexcept>
using namespace std;
RomLoader::RomLoader()
{
}
RomLoader::~RomLoader()
{
}
void RomLoader::load_rom(string fileName, Memory *memory, uint16_t offset)
{
// TODO: Protect against buffer overflow, odd filesize, etc.
// TODO: Optimize for buffering
// Read ROM file as byte stream and write to memory
basic_ifstream<char> file(fileName, ios::binary);
vector<char> fileBytes = vector<char>(istreambuf_iterator<char>(file), istreambuf_iterator<char>());
if (fileBytes.empty())
throw runtime_error("Invalid ROM");
for (uint16_t addr = 0; addr < fileBytes.size(); addr++)
{
memory->write(addr + offset, fileBytes[addr]);
}
} | true |
79c640ef1a226e2758e1fff6d2e598ba7b32fe76 | C++ | leejaeseung/Algorithm | /CodeForce/C++/1360C_Similar Pairs.cpp | UTF-8 | 3,062 | 2.96875 | 3 | [] | no_license | /*
C. Similar Pairs
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x−y|=1. For example, in each of the pairs (2,6), (4,3), (11,7), the numbers are similar to each other, and in the pairs (1,4), (3,12), they are not.
You are given an array a of n (n is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.
For example, for the array a=[11,14,16,12], there is a partition into pairs (11,12) and (14,16). The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.
Input
The first line contains a single integer t (1≤t≤1000) — the number of test cases. Then t test cases follow.
Each test case consists of two lines.
The first line contains an even positive integer n (2≤n≤50) — length of array a.
The second line contains n positive integers a1,a2,…,an (1≤ai≤100).
Output
For each test case print:
YES if the such a partition exists,
NO otherwise.
The letters in the words YES and NO can be displayed in any case.
풀이:
홀수의 개수가 짝수 개, 짝수의 개수가 짝수 개이면 무조건 YES입니다.
마찬가지로 짝수 개, 홀수 개(홀수 개, 짝수 개)이면 절대 만들 수 없으므로 NO입니다.
홀수 개, 홀수 개일 때 인접한 수의 개수를 고려해야 합니다.
1차이가 나는 수의 개수를 먼저 세줍니다.(sim)
1차이가 나는 수가 하나라도 있으면 홀수, 짝수를 각각 하나씩 줄여줄 수 있으므로 무조건 YES가 됩니다.
*/
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
using namespace std;
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define pii pair<int, int>
#define pdd pair<double, double>
#define pic pair<int, char>
#define ll long long
#define vi vector<int>
#define vl vector<long long>
#define vii vector<pii>
#define IMAX 2000000001
#define LMAX 1000000000000000000
#define DMAX 0xFFFFFFFFFFFFF
int mv1[4] = { 0, 1, 0, -1 };
int mv2[4] = { 1, 0, -1, 0 };
int t, n;
int c[101];
int main(void) {
FIO;
cin >> t;
while (t--) {
cin >> n;
vi vt;
for (int i = 0; i < 101; i++)
{
c[i] = 0;
}
int cntE = 0;
int cntO = 0;
for (int i = 0; i < n; i++)
{
int v;
cin >> v;
vt.push_back(v);
if (v % 2 == 0)
cntE++;
else
cntO++;
}
sort(vt.begin(), vt.end());
int sim = 0;
for (int i = 0; i < vt.size() - 1; i++)
{
if (abs(vt[i] - vt[i + 1]) == 1) {
sim++;
i++;
}
}
if (cntE % 2 == 0 && cntO % 2 == 0)
cout << "YES\n";
else if(cntE % 2 != 0 && cntO % 2 != 0){
if (sim > 0) {
cout << "YES\n";
}
else
cout << "NO\n";
}
else {
cout << "NO\n";
}
}
} | true |
762f5f89ab4f4bce83780dd37d1a861e7e173040 | C++ | ahnyeji/C_Algorithm | /BOJ/DFS_BFS/7562.cpp | UTF-8 | 1,394 | 3.125 | 3 | [] | no_license | /* BOJ - 7562 : 나이트의 이동
28.February.2021
(28.February.2021 Live Problem Solving)
*/
/* [BFS]
# 8방 탐색
# visit[i][j] : 해당 위치에 오기까지 이동한 횟수
# 목표 지점 좌표가 최초 등장할 경우가 최소 이동 횟수 (BFS)
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int I, dest_x, dest_y;
int dir[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
vector<vector<int> > chess;
int bfs(int y, int x){
int yy, xx;
queue<pair<int, int> > q;
q.push({y, x});
while(!q.empty()){
y = q.front().first;
x = q.front().second;
q.pop();
if(y == dest_y && x == dest_x){
return chess[y][x];
}
for(int i = 0; i < 8; i++){
yy = y + dir[i][0];
xx = x + dir[i][1];
if((yy > -1 && yy < I) && (xx > -1 && xx < I) && chess[yy][xx] == 0){
chess[yy][xx] = chess[y][x] + 1;
q.push({yy, xx});
}
}
}
}
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int t, curr_x, curr_y;
cin >> t;
while(t--){
cin >> I;
cin >> curr_y >> curr_x;
cin >> dest_y >> dest_x;
chess.assign(I, vector<int>(I));
cout << bfs(curr_y, curr_x) << "\n";
}
} | true |
8c17940e1391d5327843e71eed7115b8d22292fa | C++ | leo2105/Algoritmos-Paralelos | /MPI/Section7/MonteCarlo_PI.cpp | UTF-8 | 1,598 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
static long MULTIPLIER = 1366;
static long ADDEND = 150889;
static long PMOD = 714025;
double random_low,random_hi;
long random_last;
double drandom()
{
long random_next;
double ret_val;
// compute an integer number from zero to mod
random_next = (MULTIPLIER * random_last + ADDEND) % PMOD;
random_last = random_next;
//shift into preset range
ret_val = ((double)random_next/(double)PMOD) * (random_hi - random_low) + random_low;
return ret_val;
}
void seed(double low_in,double hi_in)
{
if(low_in < hi_in)
{
random_low = low_in;
random_hi = hi_in;
}
else
{
random_low = hi_in;
random_hi = low_in;
}
random_last = PMOD/ADDEND;
}
int main()
{
long i; long Ncirc = 0;
double pi,x,y,test,pi1;
double r = 1.0; // radio del circulo. Lado del cuadrado es 2*r
time_t t;
seed(0.0,1.0);
//srand(time(&t));
long num_trials=100000000;
for(i=0;i<num_trials;i++)
{
//x = (double)rand() / RAND_MAX;
//y = (double)rand / RAND_MAX;
//cout<<x<<endl;
//cout<<y<<endl;
x = drandom();
y = drandom();
if(x*x + y*y <= r*r)
Ncirc++;
}
pi = 4.0 * ((double)Ncirc/(double)num_trials);
Ncirc = 0;
for(i=0;i<num_trials;i++)
{
x = (double)rand() / RAND_MAX;
y = (double)rand() / RAND_MAX;
//cout<<x<<endl;
//cout<<y<<endl;
//x = drandom();
//y = drandom();
if(x*x + y*y <= r*r)
Ncirc++;
}
pi1 = 4.0 * ((double)Ncirc/(double)num_trials);
cout<<endl<<num_trials<<" trials, pi is "<<pi<<endl;
cout<<endl<<num_trials<<" trials, pi1 is "<<pi1<<endl;
return 0;
} | true |
4f42e511d0eb49bad3070c7d8de466a85f3bd59b | C++ | rcherrera/ProyRoboticaBasica | /SkEvasorObst01.ino | UTF-8 | 2,866 | 2.78125 | 3 | [] | no_license | //Roberto Herrera
#include <Servo.h>
#include <AFMotor.h> //libreria para motores
#define trigPin 8 // definir pin 8 para Trigger
#define echoPin 13 //definir pin 13 para Echo
AF_DCMotor motor1(3,MOTOR12_64KHZ); // setear motores.
AF_DCMotor motor2(4, MOTOR12_8KHZ);
Servo myservo; // create servo object to control a servo
//int pos=0;
void setup() {
Serial.begin(9600); // comienza comunicacion serial
Serial.println("Probando motores!");
pinMode(trigPin, OUTPUT);// configurar el Trigger al pin (Enviar sound waves)
pinMode(echoPin, INPUT);// Configurar el pin Echo (para recibir ondas de sonido)
motor1.setSpeed(155); //configurar velocidad de los motores 0-255
motor2.setSpeed (155);
//myservo.attach(9); // Eso es para configurar el servo (si tienen servo para que gire el HCSR04
}
void loop() {
long duration, distance; // comenzar el scaneo
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // Delay necesario tras la configuracion del sensor.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); //DELAY EN MICROSEGUNDOS
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;// CONVIERTE DISTANCIA A CENTIMETROS.
if (distance < 25)// si la distancia es menor a 20 cms probar evadir PRIMER INTENTO
{
Serial.print ("Distance From Robot is " );
Serial.print ( distance);
Serial.print ( " CM!");// print out the distance in centimeters.
Serial.println (" Turning !");
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(500);
motor2.setSpeed(250);
motor1.setSpeed(150);
motor2.run(BACKWARD);
motor1.run (FORWARD);
delay(500);
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(1000);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//segundo intento de evasion
if(distance <25){
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(500);
motor2.setSpeed(250);
motor1.setSpeed(150);
motor2.run(BACKWARD);
motor1.run (FORWARD);
delay(500);
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(500);
}
// si son mas de dos intentos... probar invertir el giro
if(distance <25){
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(500);
motor2.setSpeed(150);
motor1.setSpeed(250);
motor2.run(FORWARD);
motor1.run (BACKWARD);
delay(500);
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(500);
}
}
else {
Serial.println ("No hay obstaculos: ir al frente");
delay (15);
motor1.run(BACKWARD); //Si no hay obstaculos ir al frente
motor2.run(BACKWARD);
}
}
| true |
11481cc146cfd7dcdca1bd5690aad3f12b7a73e4 | C++ | edrixon/net-relay | /netvars.cpp | UTF-8 | 1,142 | 2.875 | 3 | [] | no_license | #include "types.h"
#include "globals.h"
void readNetVars()
{
int eepromAddr;
byte *bPtr;
eepromAddr = 0;
bPtr = (byte *)&netVars;
while (eepromAddr < sizeof(netVars_t))
{
*bPtr = EEPROM.read(eepromAddr);
bPtr++;
eepromAddr++;
}
}
// Save network variables in EEPROM
void saveNetVars()
{
int eepromAddr;
byte *bPtr;
eepromAddr = 0;
bPtr = (byte *)&netVars;
while (eepromAddr < sizeof(netVars_t))
{
EEPROM.write(eepromAddr, *bPtr);
bPtr++;
eepromAddr++;
}
}
void dumpEeprom()
{
int eepromAddr;
int c;
char strBuff[8];
eepromAddr = 0;
while(eepromAddr < 256)
{
sprintf(strBuff, "%04x ", eepromAddr);
Serial.write(strBuff);
for(c = 0; c < 8; c++)
{
sprintf(strBuff, "%02x ", EEPROM.read(eepromAddr + c));
Serial.write(strBuff);
}
Serial.write("- ");
for(c = 8; c < 16; c++)
{
sprintf(strBuff, "%02x ", EEPROM.read(eepromAddr + c));
Serial.write(strBuff);
}
Serial.write("\r\n");
eepromAddr = eepromAddr + 16;
}
}
| true |
94d33eabb6bef532a19576bea7b565da022ebd53 | C++ | TeoPaius/Projects | /c++/Diverse problems and algorithms/Problems/bile/main.cpp | UTF-8 | 1,978 | 2.5625 | 3 | [] | no_license | #include <fstream>
using namespace std;
ifstream is ("bile.in");
ofstream os ("bile.out");
int t[64000];
int a[251][251];
int sol[64000];
struct Bila{
int col;
int lin;
};
Bila b[64000];
int n;
int H;
int h[64000];
int hmax;
int cnt = 1;
int Find(int x);
int main()
{
is >> n;
for(int i = 1; i <= n * n; ++i)
{
is >> b[n*n - i + 1].lin;
is >> b[n*n - i + 1].col;
}
for(int i = 1; i <= n * n; ++i)
{
a[b[i].lin][b[i].col] = i;
if( a[b[i].lin - 1][b[i].col] == 0 && a[b[i].lin][b[i].col + 1] == 0 && a[b[i].lin + 1][b[i].col] == 0 && a[b[i].lin][b[i].col - 1] == 0)
{
t[i] = i;
h[i] = 1;
}
else
{
H = 1;
int rad;
if(a[b[i].lin - 1][b[i].col] != 0)
{
rad = Find(a[b[i].lin-1][b[i].col]);
H += h[rad];
t[rad] = i;
t[i] = i;
}
if(a[b[i].lin][b[i].col + 1] != 0)
{
rad = Find(a[b[i].lin][b[i].col + 1]);
H += h[rad];
t[rad] = i;
t[i] = i;
}
if(a[b[i].lin + 1][b[i].col] != 0)
{
rad = Find(a[b[i].lin + 1][b[i].col]);
H += h[rad];
t[rad] = i;
t[i] = i;
}
if(a[b[i].lin][b[i].col - 1] != 0)
{
rad = Find(a[b[i].lin][b[i].col - 1]);
H += h[rad];
t[rad] = i;
t[i] = i;
}
h[i] = H;
}
if(h[i] > hmax)
{
hmax = h[i];
}
sol[cnt] = hmax;
cnt++;
}
for(int i = n * n - 1; i >= 0; --i)
os << sol[i] << '\n';
is.close();
os.close();
return 0;
}
int Find(int x)
{
if (x == t[x])
return x;
return t[x] = Find(t[x]);
}
| true |
88a776701dd132a7ab173497a5e42cebf8e2e6d6 | C++ | ajaakman/cpp-audio-library | /src/Components/MasterMixer.cpp | UTF-8 | 1,716 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "./MasterMixer.h"
#include "../Utilities.h"
#include "../API.h"
namespace audio
{
MasterMixer::MasterMixer(const double& time)
: Component(*this), m_globalTime(time), m_amp_target(0.0f), m_amplitude(0.0f), m_channel_clip{ 0 }, m_clip_timer{ 0 }
{
}
void MasterMixer::writeSamples(std::array<float, CHANNELS<size_t>>& samples)
{
for (size_t i = 0; i < samples.size(); ++i)
{
// Lerp the master amplitude before applying it to the final ouput to prevent audio clicks.
samples[i] *= Utilities::lerp(m_amplitude, m_amp_target, (20.0f / SAMPLE_RATE<float>), 0.0f, 1.0f);
setChannelClip(i, samples[i] > 1.0f ? true : false);
}
}
void MasterMixer::setChannelClip(size_t channel, bool value)
{
if (value)
{
m_clip_timer[channel] = SAMPLE_RATE<unsigned>;
if (!m_channel_clip[channel])
{
m_channel_clip[channel] = value;
clipCallback(channel, true);
}
}
else
{
if (m_clip_timer[channel])
{
--m_clip_timer[channel];
}
else
{
if (m_channel_clip[channel])
{
m_channel_clip[channel] = value;
clipCallback(channel, false);
}
}
}
}
const bool MasterMixer::setOutput(Component* const new_output)
{
return false;
}
const Component* const MasterMixer::getOutput() const
{
return nullptr;
}
const std::array<float, CHANNELS<size_t>>& MasterMixer::getMasterOutput()
{
return finalOutput();
}
const std::array<std::atomic<bool>, CHANNELS<size_t>>& MasterMixer::isOutClipping()
{
return m_channel_clip;
}
void MasterMixer::setAmplitude(const float new_amplitude)
{
m_amp_target = std::clamp(new_amplitude, 0.0f, 1.0f);
}
const float MasterMixer::getAmplitude()
{
return m_amp_target;
}
} | true |
fe839821ec7a8becb0d6cec9f57c65d70e67d7f7 | C++ | diepdao1708/CPP | /T1.cpp | UTF-8 | 798 | 2.6875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
vector<int> res;
vector<int> a;
bool check(){
for(int i = 1; i < res.size(); i++)
{
if (res[i] < res[i-1]) return 0;
}
return 1;
}
void sinhth (int n, int k, int spt){
if (res.size() == k) {
if (check())
{
for(int i = 0; i < res.size(); i++) cout << res[i]<<' ';
cout <<endl;
}
return;
}
if (spt == n) return;
for(int i = spt; i < n; i++)
{
res.push_back(a[i]);
sinhth(n, k, i+1);
res.pop_back();
}
}
void solve(){
int n, k;
cin >> n >> k;
a.clear();
a.resize(n);
for(int i = 0;i < n; i++) cin >> a[i];
sinhth(n, k, 0);
}
int main(){
int t;
cin >> t;
while(t--) solve();
return 0;
} | true |
cf4be9b1176f1b62960fc6c813faf5c71d3d8bd9 | C++ | djyt/cannonball | /src/main/romloader.cpp | UTF-8 | 7,050 | 3.015625 | 3 | [] | no_license | /***************************************************************************
Binary File Loader.
Handles loading an individual binary file to memory.
Supports reading bytes, words and longs from this area of memory.
Copyright Chris White.
See license.txt for more details.
***************************************************************************/
#include <iostream>
#include <fstream>
#include <cstddef> // for std::size_t
#include <boost/crc.hpp> // CRC Checking via Boost library.
#include <unordered_map>
#include "stdint.hpp"
#include "romloader.hpp"
#include "frontend/config.hpp"
// In order to get a cross-platform directory listing I'm using a Visual Studio
// version of Linux's Dirent from here: https://github.com/tronkko/dirent
//
// This appears to be the most lightweight solution available without resorting
// to enormous boost libraries or switching to C++17.
#ifdef _MSC_VER
#include "windirent.h"
#else
#include <dirent.h>
#endif
// Unordered Map to store contents of directory by CRC 32 value. Similar to Hashmap.
static std::unordered_map<int, std::string> map;
static bool map_created;
RomLoader::RomLoader()
{
rom = NULL;
map_created = false;
loaded = false;
}
RomLoader::~RomLoader()
{
if (rom != NULL)
delete[] rom;
}
void RomLoader::init(const uint32_t length)
{
// Setup pointer to function we want to use (either load_crc32 or load_rom)
load = config.data.crc32 ? &RomLoader::load_crc32 : &RomLoader::load_rom;
this->length = length;
rom = new uint8_t[length];
}
void RomLoader::unload(void)
{
delete[] rom;
rom = NULL;
}
// ------------------------------------------------------------------------------------------------
// Filename based ROM loader
// Advantage: Simpler. Does not require <dirent.h>
// ------------------------------------------------------------------------------------------------
int RomLoader::load_rom(const char* filename, const int offset, const int length, const int expected_crc, const uint8_t interleave, const bool verbose)
{
std::string path = config.data.rom_path;
path += std::string(filename);
// Open rom file
std::ifstream src(path.c_str(), std::ios::in | std::ios::binary);
if (!src)
{
if (verbose) std::cout << "cannot open rom: " << path << std::endl;
loaded = false;
return 1; // fail
}
// Read file
char* buffer = new char[length];
src.read(buffer, length);
// Check CRC on file
boost::crc_32_type result;
result.process_bytes(buffer, (size_t) src.gcount());
if (expected_crc != result.checksum())
{
if (verbose)
std::cout << std::hex <<
filename << " has incorrect checksum.\nExpected: " << expected_crc << " Found: " << result.checksum() << std::endl;
return 1;
}
// Interleave file as necessary
for (int i = 0; i < length; i++)
{
rom[(i * interleave) + offset] = buffer[i];
}
// Clean Up
delete[] buffer;
src.close();
loaded = true;
return 0; // success
}
// --------------------------------------------------------------------------------------------
// Create Unordered Map of files in ROM directory by CRC32 value
// This should be faster than brute force searching every file in the directory every time.
// --------------------------------------------------------------------------------------------
int RomLoader::create_map()
{
map_created = true;
std::string path = config.data.rom_path;
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) == NULL)
{
std::cout << "Warning: Could not open ROM directory - " << path << std::endl;
return 1; // Failure (Could not open directory)
}
// Iterate all files in directory
while ((ent = readdir(dir)) != NULL)
{
std::string file = path + ent->d_name;
std::ifstream src(file, std::ios::in | std::ios::binary);
if (!src) continue;
// Read file
char* buffer = new char[length];
src.read(buffer, length);
// Check CRC on file
boost::crc_32_type result;
result.process_bytes(buffer, (size_t)src.gcount());
// Insert file into MAP between CRC and filename
map.insert({ result.checksum(), file });
delete[] buffer;
src.close();
}
if (map.empty())
std::cout << "Warning: Could not create CRC32 Map. Did you copy the ROM files into the directory? " << std::endl;
closedir(dir);
return 0; //success
}
// ------------------------------------------------------------------------------------------------
// Search and load ROM by CRC32 value as opposed to filename.
// Advantage: More resilient to renamed romsets.
// ------------------------------------------------------------------------------------------------
int RomLoader::load_crc32(const char* debug, const int offset, const int length, const int expected_crc, const uint8_t interleave, const bool verbose)
{
if (!map_created)
create_map();
if (map.empty())
return 1;
auto search = map.find(expected_crc);
// Cannot find file by CRC value in map
if (search == map.end())
{
if (verbose) std::cout << "Unable to locate rom in path: " << config.data.rom_path << " possible name: " << debug << " crc32: 0x" << std::hex << expected_crc << std::endl;
loaded = false;
return 1;
}
// Correct ROM found
std::string file = search->second;
std::ifstream src(file, std::ios::in | std::ios::binary);
if (!src)
{
if (verbose) std::cout << "cannot open rom: " << file << std::endl;
loaded = false;
return 1; // fail
}
// Read file
char* buffer = new char[length];
src.read(buffer, length);
// Interleave file as necessary
for (int i = 0; i < length; i++)
rom[(i * interleave) + offset] = buffer[i];
// Clean Up
delete[] buffer;
src.close();
loaded = true;
return 0; // success
}
// --------------------------------------------------------------------------------------------
// Load Binary File (LayOut Levels, Tilemap Data etc.)
// --------------------------------------------------------------------------------------------
int RomLoader::load_binary(const char* filename)
{
std::ifstream src(filename, std::ios::in | std::ios::binary);
if (!src)
{
std::cout << "cannot open file: " << filename << std::endl;
loaded = false;
return 1; // fail
}
length = filesize(filename);
// Read file
char* buffer = new char[length];
src.read(buffer, length);
rom = (uint8_t*) buffer;
// Clean Up
src.close();
loaded = true;
return 0; // success
}
int RomLoader::filesize(const char* filename)
{
std::ifstream in(filename, std::ifstream::in | std::ifstream::binary);
in.seekg(0, std::ifstream::end);
int size = (int) in.tellg();
in.close();
return size;
} | true |
fe286a67d9fadfb3e2eee1fc92b9d6b0511bacd4 | C++ | Taeyeong201/RnD | /Network_Test/Security/FileEncrypt/FileCrypto.cpp | UHC | 6,114 | 2.578125 | 3 | [] | no_license | #include "FileCrypto.h"
//#include <Windows.h>
int fs_decrypt_aes(char *in_file, char *out_file)
{
const unsigned char key32[32] =
{
0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,
0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,
0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,
0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,0x56
};
AES_KEY aes_ks3;
unsigned char iv[IV_SIZE];
unsigned char buf[FREAD_COUNT + BLOCK_SIZE];
int len = 0;
int total_size = 0;
int save_len = 0;
int w_len = 0;
FILE *fp = fopen(in_file, "rb");
if (fp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, in_file);
return FAIL;
}
FILE *wfp = fopen(out_file, "wb");
if (wfp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, out_file);
return FAIL;
}
memset(iv, 0, sizeof(iv)); // the same iv
AES_set_decrypt_key(key32, KEY_BIT, &aes_ks3);
fseek(fp, 0, SEEK_END);
total_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("total_size %d\n", total_size);
while (len = fread(buf, RW_SIZE, FREAD_COUNT, fp)) {
if (FREAD_COUNT == 0) {
break;
}
save_len += len;
w_len = len;
AES_cbc_encrypt(buf, buf, len, &aes_ks3, iv, AES_DECRYPT);
if (save_len == total_size) { // check last block
w_len = len - buf[len - 1];
printf("dec padding size %d\n", buf[len - 1]);
}
fwrite(buf, RW_SIZE, w_len, wfp);
}
fclose(wfp);
fclose(fp);
return SUCC;
}
int fs_encrypt_aes(char *in_file, char *out_file)
{
const unsigned char key32[32] =
{
0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,
0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,
0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,
0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,0x56
};
AES_KEY aes_ks3;
unsigned char iv[IV_SIZE];
int i = 0;
int len = 0;
int padding_len = 0;
unsigned char buf[FREAD_COUNT + BLOCK_SIZE];
FILE *fp = fopen(in_file, "rb");
if (fp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, in_file);
return FAIL;
}
FILE *wfp = fopen(out_file, "wb");
if (wfp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, out_file);
return FAIL;
}
memset(iv, 0, sizeof(iv)); // init iv
AES_set_encrypt_key(key32, KEY_BIT, &aes_ks3);
while (len = fread(buf, RW_SIZE, FREAD_COUNT, fp)) {
if (FREAD_COUNT != len) {
break;
}
AES_cbc_encrypt(buf, buf, len, &aes_ks3, iv, AES_ENCRYPT);
fwrite(buf, RW_SIZE, len, wfp);
}
// padding : pkcs5? pkcs7?? http://wiki.dgoon.net/doku.php?id=ssl:pkcs_5
padding_len = BLOCK_SIZE - len % BLOCK_SIZE;
printf("enc padding len:%d\n", padding_len);
memset(buf + len, padding_len, padding_len);
/**
for(i=len; i < len+padding_len ;i++){
buf[i]=padding_len;
}
**/
AES_cbc_encrypt(buf, buf, len + padding_len, &aes_ks3, iv, AES_ENCRYPT);
fwrite(buf, RW_SIZE, len + padding_len, wfp);
fclose(wfp);
fclose(fp);
return SUCC;
}
int fs_encrypt_seed(char* in_file, char* out_file)
{
const unsigned char key16[16] =
{
0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,
0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12
};
SEED_KEY_SCHEDULE cbc_ks;
unsigned char iv[IV_SIZE];
int i = 0;
int len = 0;
int padding_len = 0;
unsigned char buf[FREAD_COUNT + BLOCK_SIZE];
FILE* fp = fopen(in_file, "rb");
if (fp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, in_file);
return FAIL;
}
FILE* wfp = fopen(out_file, "wb");
if (wfp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, out_file);
return FAIL;
}
memset(iv, 0, sizeof(iv)); // init iv
SEED_set_key(key16, &cbc_ks);
while (len = fread(buf, RW_SIZE, FREAD_COUNT, fp)) {
if (FREAD_COUNT != len) {
break;
}
SEED_cbc_encrypt(buf, buf, len, &cbc_ks, iv, SEED_ENCRYPT);
fwrite(buf, RW_SIZE, len, wfp);
}
// padding : pkcs5? pkcs7?? http://wiki.dgoon.net/doku.php?id=ssl:pkcs_5
padding_len = BLOCK_SIZE - len % BLOCK_SIZE;
printf("enc padding len:%d\n", padding_len);
memset(buf + len, padding_len, padding_len);
/**
for(i=len; i < len+padding_len ;i++){
buf[i]=padding_len;
}
**/
SEED_cbc_encrypt(buf, buf, len + padding_len, &cbc_ks, iv, SEED_ENCRYPT);
fwrite(buf, RW_SIZE, len + padding_len, wfp);
fclose(wfp);
fclose(fp);
return SUCC;
}
int fs_decrypt_seed(char* in_file, char* out_file)
{
const unsigned char key16[16] =
{
0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,
0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12
};
SEED_KEY_SCHEDULE cbc_ks;
unsigned char iv[IV_SIZE];
unsigned char buf[FREAD_COUNT + BLOCK_SIZE];
int i = 0;
int len = 0;
int total_size = 0;
int save_len = 0;
int w_len = 0;
FILE* fp = fopen(in_file, "rb");
if (fp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, in_file);
return FAIL;
}
FILE* wfp = fopen(out_file, "wb");
if (wfp == NULL) {
fprintf(stderr, "[ERROR] %d can not fopen('%s')\n", __LINE__, out_file);
return FAIL;
}
memset(iv, 0, sizeof(iv)); // the same iv
SEED_set_key(key16, &cbc_ks);
fseek(fp, 0, SEEK_END);
total_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("total_size %d\n", total_size);
while (len = fread(buf, RW_SIZE, FREAD_COUNT, fp)) {
if (FREAD_COUNT == 0) {
break;
}
save_len += len;
w_len = len;
SEED_cbc_encrypt(buf, buf, len, &cbc_ks, iv, SEED_DECRYPT);
if (save_len == total_size) { // check last block
w_len = len - buf[len - 1];
printf("dec padding size %d\n", buf[len - 1]);
}
fwrite(buf, RW_SIZE, w_len, wfp);
}
fclose(wfp);
fclose(fp);
return SUCC;
}
/*
wchar to char
char to wchar
*/
char * ConvertWCtoC(wchar_t* str)
{
//ȯ char*
char* pStr;
//Է¹ wchar_t ̸
int strSize = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
//char* Ҵ
pStr = new char[strSize];
// ȯ
WideCharToMultiByte(CP_ACP, 0, str, -1, pStr, strSize, 0, 0);
return pStr;
}
wchar_t* ConverCtoWC(char* str)
{
//wchar_t
wchar_t* pStr;
//Ƽ Ʈ ũ ȯ
int strSize = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, NULL);
//wchar_t Ҵ
pStr = new WCHAR[strSize];
// ȯ
MultiByteToWideChar(CP_ACP, 0, str, strlen(str) + 1, pStr, strSize);
return pStr;
}
| true |
c12aa5694c15f49c2534a66caee455775e31ef62 | C++ | lelong03/esp8266-host-client | /8266_host.cpp | UTF-8 | 1,685 | 2.78125 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
// Assign output variables to GPIO pins
const int output5 = 5;
// Wifi ssid and password
const char *ssid = "wifi_name";
const char *password = "wifi_password";
ESP8266WebServer server(80);
IPAddress localIP(192, 168, 1, 184);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
void handleOn() {
if (server.hasArg("pin")) {
int pin = server.arg("pin").toInt();
digitalWrite(pin, HIGH);
server.send(200, "text/html", "Turned On");
}
}
void handleOff() {
if (server.hasArg("pin")) {
int pin = server.arg("pin").toInt();
digitalWrite(pin, LOW);
server.send(200, "text/html", "Turn Off");
}
}
void setup() {
delay(1000);
Serial.begin(115200);
pinMode(output5, OUTPUT);
digitalWrite(output5, LOW);
// Configures static IP address
if (!WiFi.config(localIP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
// Setup access point
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(myIP);
// when the server receives a request with /turn_on/ in the string then run the handleOn function
server.on("/turn_on/", HTTP_GET, handleOn);
// when the server receives a request with /turn_off/ in the string then run the handleOff function
server.on("/turn_off/", HTTP_GET, handleOff);
server.begin();
}
void loop() {
server.handleClient();
}
| true |
dcf84bb6160627c3aef36d299369f19441de756f | C++ | Balraaj/Windows-Programming | /Visual C++/FileHandling/FileOUT.cpp | UTF-8 | 573 | 3.65625 | 4 | [] | no_license | #include<iostream>
#include<fstream>
using namespace std;
class student
{
public:
char name[20];
int roll;
student() = default;
student(char *n, int r)
{
strcpy(name, n);
roll = r;
}
void show()
{
cout << "\nName is : " << name;
cout << "\nRoll is : " << roll;
}
};
void main()
{
student arr[5];
ofstream out("myfile");
for (int i = 0;i < 5;i++)
{
cout << "Enter details of student " << i + 1;
cout << "\nEnter name : ";
cin >> arr[i].name;
cout << "\nEnter Roll : ";
cin >> arr[i].roll;
out.write((char*)&arr[i], sizeof(student));
}
} | true |
8b81d1c91bde3026a776486f460da85363472699 | C++ | Jothapunkt/gdv-praktikum | /Menu.cpp | MacCentralEurope | 7,011 | 2.765625 | 3 | [] | no_license | /* ----------------------------------------------------------- */
/* OpenGL-Testprogramm (quick and dirty) */
/* ----------------------------------------------------------- */
/* Datei: Menu.cpp */
/* zusaetzlich benoetigt: Wuerfel_mit_Normalen.cpp und h */
/* */
/* Autor: W. Kestner, W.-D. Groch */
/* letzte Aenderung: Groch 03.05.2011 */
/* ----------------------------------------------------------- */
/* */
/* Rechte Maustaste um Menu zu oeffnen */
/* */
/* ----------------------------------------------------------- */
/* Menu Management
GLUT supports simple cascading pop-up menus. They are designed to
let a user select various modes within a program. The functionality
is simple and minimalistic and is meant to be that way. Do not
mistake GLUTs pop-up menu facility with an attempt to create a
full-featured user interface. It is illegal to create or destroy
menus, or change, add, or remove menu items while a menu (and any
cascaded sub-menus) are in use (that is, popped up).
glutCreateMenu creates a new pop-up menu.
Usage
int glutCreateMenu(void (*func)(int value));
func The callback function for the menu that is called when a menu
entry from the menu is selected. The value passed to the callback
is determined by the value for the selected menu entry.
Description
glutCreateMenu creates a new pop-up menu and returns a unique small
integer identifier. The range of allocated identifiers starts at one.
The menu identifier range is separate from the window identifier
range. Implicitly, the current menu is set to the newly created menu.
This menu identifier can be used when calling glutSetMenu.
When the menu callback is called because a menu entry is selected
for the menu, the current menu will be implicitly set to the menu
with the selected entry before the callback is made.
glutAddMenuEntry adds a menu entry to the bottom of the current menu.
Usage
void glutAddMenuEntry(char *name, int value);
name: ASCII character string to display in the menu entry.
value: Value to return to the menus callback function if the menu
entry is selected.
Description
glutAddMenuEntry adds a menu entry to the bottom of the current
menu. The string name will be displayed for the newly added menu
entry. If the menu entry is selected by the user, the menus
callback will be called passing value as the callbacks parameter.
glutAddSubMenu adds a sub-menu trigger to the bottom of the current menu.
Usage
void glutAddSubMenu(char *name, int menu);
name: ASCII character string to display in the menu item from which
to cascade the sub-menu.
menu: Identifier of the menu to cascade from this sub-menu menu item.
Description
glutAddSubMenu adds a sub-menu trigger to the bottom of the current menu.
The string name will be displayed for the newly added sub-menu trigger.
If the sub-menu trigger is entered, the sub-menu numbered menu
will be cascaded, allowing sub-menu menu items to be selected.
*/
#include <windows.h>
#include <GL/freeglut.h> //laedt alles fuer OpenGL
#include <iostream>
#include <math.h>
#include "Wuerfel_mit_Normalen.h"
GLfloat extent = 1.0f;// Mass fuer die Ausdehnung des Modells
void mainMenu(int item)
{
switch(item)
{
case 1 :
std::cout <<"Exit"<<std::endl;
exit(0);
}
}
void backGroundColor (int item)
{
switch(item)
{
case 1 :
{
glClearColor(1.0f,1.0f,1.0f,1.0f); // Hintergrundfarbe weiss definieren
// RenderScene aufrufen.
glutPostRedisplay();
break;
}
case 2 :
{
glClearColor(1.0f,0.0f,0.0f,1.0f); // Hintergrundfarbe rot definieren
// RenderScene aufrufen.
glutPostRedisplay();
break;
}
case 3 :
{
glClearColor(0.33f,0.225f,0.0f,1.0f);// Hintergrundfarbe gold definieren
// RenderScene aufrufen.
glutPostRedisplay();
break;
}
}
}
void Init()
{
// Hier finden jene Aktionen statt, die zum Programmstart einmalig
// durchgefuehrt werden muessen
glClearColor ( 0.33f, 0.225f, 0.0f, 1.0f); //Hintergrundfarbe definieren
glEnable(GL_DEPTH_TEST);
glClearDepth(1.0);
// Unter-Menu
int submenu1;
submenu1 = glutCreateMenu(backGroundColor);
glutAddMenuEntry("BackgroundColor WHITE", 1);
glutAddMenuEntry("BackgroundColor RED", 2);
glutAddMenuEntry("BackgroundColor GOLD", 3);
// Haupt-Menu
glutCreateMenu(mainMenu);
glutAddSubMenu("Background color", submenu1);
glutAddMenuEntry("Exit", 1);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void RenderScene(void)
{
// Hier befindet sich der Code der in jedem frame ausgefuehrt werden muss
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Puffer loeschen
glLoadIdentity();
Wuerfel_mit_Normalen(extent);
glutSwapBuffers();
glFlush();
}
void Reshape(int width,int height)
{
// Hier finden die Reaktionen auf eine Veraenderung der Groesse des
// Graphikfensters statt
glMatrixMode(GL_PROJECTION); //Matrix fuer Transf. Frustum->viewport
glLoadIdentity();
glViewport(0,0,width,height);
glOrtho(-extent*2.0,+extent*2.0,-extent*2.0,+extent*2.0,-extent*2.0,+extent*2.0); //Frustum
glMatrixMode(GL_MODELVIEW); //Modellierungs/Viewing-Matrix
}
void Animate (int value)
{
// Hier werden Berechnungen durchgefuehrt, die zu einer Animation der Szene
// erforderlich sind. Dieser Prozess laeuft im Hintergrund und wird alle
// wait_msec Milli-Sekunden aufgerufen. Der Parameter "value" wird einfach
// nur um eins inkrementiert und dem Callback wieder uebergeben.
std::cout << "value=" << value << std::endl;
// RenderScene aufrufen.
glutPostRedisplay();
// Timer wieder registrieren; Animate also nach wait_msec Milli-Sekunden wieder aufrufen
int wait_msec = 1000;
glutTimerFunc(wait_msec, Animate, ++value);
}
int main(int argc, char **argv)
{
std::cout<<"Grundlegende Interaktionen:"<<std::endl;
std::cout<<"Rechte Maustaste (ueber dem Graphik-Fenster)"<<std::endl;
std::cout<<"zum Oeffnen des Menus verwenden"<<std::endl<<std::endl;
std::cout<<"Beenden: Graphik-Fenster schliessen oder per Menu!"<<std::endl<<std::endl;
glutInit ( &argc, argv );
glutInitDisplayMode ( GLUT_DOUBLE|GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH );
glutInitWindowSize ( 600,600 );
glutCreateWindow ("*** Menu-Management ***");
glutDisplayFunc ( RenderScene );
glutReshapeFunc ( Reshape );
// TimerCallback registrieren; wird nach 10 msec aufgerufen mit Parameter 0
glutTimerFunc(10,Animate,0);
Init();
glutMainLoop ();
return 0;
}
| true |
73db4f353be0ae9ff50adcac07cd46beb869a132 | C++ | JiangSir857/C-Plus-Plus-1 | /Object Oriented Programming(C++)/模仿练习参考代码/chapter10/ex4.cpp | GB18030 | 816 | 3.1875 | 3 | [] | no_license | /*
1. Fibonacciе30дļȻʾеÿʾ5
*/
#include "fstream.h"
#define N 18
void main()
{
int iData[N]={0},i,n;
iData[0]=iData[1] = 1;
for(i=2;i<N;i++)
iData[i]=iData[i-1]+iData[i-2];
ofstream outputfile("d:\\a9.dat"); //ù캯ļ
if(!outputfile)
{
cout<<"ļʧܣ"<<endl;
return;
}
outputfile.write ((char *)iData,sizeof(int)*N);//д
outputfile.close (); //رļ
ifstream inputfile("d:\\a9.dat");
if(!inputfile)
{
cout<<"ļʧܣ"<<endl;
return;
}
for(i=0;i<N;i+=2)
{
inputfile.read ((char *)&n,sizeof(int));
cout<<n<<" ";
inputfile.seekg((long)sizeof(int),ios::cur);
}
cout<<"\n";
inputfile.close ();
}
| true |
ab14ef57baadc5fc36a9cc62a430038db4d674db | C++ | omarhosny206/Data-Structures-and-Algorithms-Specialization | /1- Algorithmic Toolbox/Week 1/Programming Assignments/1- Sum of Two Digits/Sum of Two Digits.cpp | UTF-8 | 153 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int Number1, Number2;
cin >> Number1 >> Number2;
cout << Number1 + Number2 << endl;
}
| true |
688c66742d3c009030c134939b5beb1299f3efa9 | C++ | cerminar/UserCode | /Tools/MyAnalysisTools/test/root_lib/LumiNormalization.h | UTF-8 | 3,754 | 2.625 | 3 | [] | no_license | #ifndef LumiNormalization_H
#define LumiNormalization_H
/** \class LumiNormalization
* Class to get the normalization of each sample.
* The relative normalization is get from MC xsections while the overall normalization
* can be derived from the number of events under the Z peak.
* The samples used in this luminosity normalization must be added explicitly throught the add method.
* Look to the XSection.txt and Luminosity.txt files for naming conventions.
*
* $Date: 2011/03/14 18:05:53 $
* $Revision: 1.1 $
* \author G. Cerminara - NEU Boston & INFN Torino
*/
#include "TString.h"
#include "Number.h"
#include <vector>
#include <set>
class XSecReader;
class SampleGroup;
class LumiNormalization {
public:
/// Constructor
// Create a tool for normalization. You need to specify the XSection file and the lumi file
// and the elements to look for the right lumi in the map.
// also the inputDir for the histo to be used for data/MC normalization in required (che be a null string)
LumiNormalization(const TString& xsecFileName, const TString& lumiFileName,
const TString& epoch, const TString& finalState, bool dqApplied,
const TString& inputDir);
/// Destructor
virtual ~LumiNormalization();
// Operations
// Add data to the count of events to be used for data/MC normalization
// the histo used to get the count is zmass_restricted_1
// the default file for this histo is: histos_zzanalysis_data_FINALSTATE.root
void addData();
// Add data to the count of events to be used for data/MC normalization
// the histo used to get the count is zmass_restricted_1
// This method allows to specify the name of the file which contains this histo
void addData(const TString& filename);
// Add MC sample to the count of events to be used for data/MC normalization
// the histo used to get the count is zmass_restricted_1
// the default file for this histo is: theInputDir+"/histos_zzanalysis_mc_"+sampleName+"_"+theFinalState+".root"
void addMC(const TString& sampleName);
// Add MC sample to the count of events to be used for data/MC normalization
// the histo used to get the count is zmass_restricted_1
// This method allows to specify the name of the file which contains this histo
void addMC(const TString& sampleName, const TString& filename);
// Add MC samples to the count of events to be used for data/MC normalization
// the histo used to get the count is zmass_restricted_1
// the default file for this histo is: theInputDir+"/histos_zzanalysis_mc_"+sampleName+"_"+theFinalState+".root"
void addMC(const std::vector<TString>& sampleNames);
// Get the relative normalization of MC/data under the Z peak
double getNormalizationFactor() const;
// Get the overall scale factor (relative normalization of MC/data under the Z peak + theo. xsec)
double getScaleFactor(const TString& sampleName) const;
// add an additional scale facto
void setAdditionalScale(double scale);
// switch off the normalization of MC/data under the Z peak
void normalizeToZPeak(bool doNormalize);
// set the name of the file histo to be used for the normalization of MC/data under the Z peak
void setNormalizHistoName(const TString& histoname);
// Get initial # of events (as in XSection.txt scaled for lumi e xsec)
Number getInitialNEv(const TString& sampleName) const;
double getLuminosity() const;
void addDataGroup(const SampleGroup& group);
protected:
private:
double nData;
double nMC;
TString theInputDir;
TString theEpoch;
TString theFinalState;
TString theNormHistoName;
bool isDqApplied;
double additionalScale;
bool normalizeToZ;
XSecReader *xsecRead;
std::set<TString> dataSamples;
};
#endif
| true |
56ccaa0bf156b57eb68ef33bddc21b24ec217e22 | C++ | eunxeong/BOJ | /Floyd/1507_궁금한민호.cpp | WINDOWS-1256 | 789 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
// 1507 ñ ȣ
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int N; cin >> N;
int arr[21][21];
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++){
cin >> arr[i][j];
}
}
bool ans[21][21] = { false, };
int Answer;
for(int k = 1; k <= N; k++){
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++){
if (i == k || k == j || i == j) continue;
if (arr[i][k] + arr[k][j] < arr[i][j]) Answer = -1;
if (arr[i][k] + arr[k][j] == arr[i][j]){
ans[i][j] = true;
}
}
}
}
if (Answer != -1){
Answer = 0;
for(int i = 1; i < N; i++){
for(int j = i + 1; j <= N; j++){
if (!ans[i][j]) Answer += arr[i][j];
}
}
}
cout << Answer;
return 0;
}
| true |
d72ebaa19a2d2c6b92572fbdea544fc73615fc91 | C++ | AplusB/ACEveryDay | /ybai62868/CodeForces/div_2/Round-354/B.cpp | UTF-8 | 358 | 2.546875 | 3 | [] | no_license | #include <iostream>
using namespace std;
double dp[10][10];
int main(void)
{
int n,t,ans = 0;
cin >> n >> t;
dp[0][0] = t;
for( int i = 0; i < n; i++)
{
for( int j = 0; j <= i; j++ )
{
if( dp[i][j] >= 1 )
{
dp[i + 1][j] += (dp[i][j] - 1) * 0.5;
dp[i + 1][j + 1] += (dp[i][j] - 1) * 0.5;
ans++;
}
}
}
cout << ans << endl;
}
| true |
7edf686d1020f49d9bc743737675b5dbc0783056 | C++ | randoruf/cpp | /acm/template/stack.cpp | UTF-8 | 2,205 | 3.5 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
void func(vector<char>kind,int count[],int n)
{
if(count[0]>=1)
{
kind.push_back('(');
count[0]--;
func(kind,count,n);
count[0]++;
kind.pop_back();
}
if((count[1]>=1) && (count[1]>count[0]))
{
kind.push_back(')');
count[1]--;
func(kind,count,n);
count[1]++;
kind.pop_back();
}
if(kind.size()==2*n)
{
vector<char>::iterator iter;
for(iter=kind.begin();iter!=kind.end();iter++)
{
cout<<(*iter)<<" ";
}
cout<<endl;
}
}
int main()
{
int n;
cout << "please input the number of ():" << endl;
cin>>n;
int count[2]={n-1,n};
vector<char>kind;
kind.push_back('(');
func(kind,count,n);
return 0;
}/*
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int number=0;
void func(vector<int>kind,int count[],int n,int A[])
{
if(count[0]>=1)
{
kind.push_back(1);
count[0]--;
func(kind,count,n,A);
count[0]++;
kind.pop_back();
}
if((count[1]>=1) && (count[1]>count[0]))
{
kind.push_back(0);
count[1]--;
func(kind,count,n,A);
count[1]++;
kind.pop_back();
}
if(kind.size()==2*n)
{
vector<int>::iterator iter;
stack<int>stk;
int j=0;
for(iter=kind.begin();iter!=kind.end();iter++)
{
//cout<<(*iter)<<" ";
if(1==(*iter))
{
stk.push(A[j]);
j++;
}
else
{
cout<<stk.top()<<" ";
stk.pop();
}
}
number++;
cout<<endl;
}
}
int main()
{
int n,i;
cout << "please input the number:" << endl;
cin>>n;
int A[n];
cout << "please input the push sequence:" << endl;
for(i=0;i<n;i++)
{
cin>>A[i];
}
int count[2]={n-1,n};
vector<int>kind;
kind.push_back(1);
cout<<"the result is:"<<endl;
func(kind,count,n,A);
cout<<"total:"<<number<<endl;
return 0;
}
*/
| true |
c18bc3539d830b8183c31fcd2a25c3d9145115af | C++ | thiagocferr/remote-checkers-raw-protocol | /client/include/Tictactoe.hpp | UTF-8 | 989 | 3.5 | 4 | [] | no_license | #ifndef TICTACTOE_HPP
#define TICTACTOE_HPP
#include <string>
enum class GamePiece {
Empty,
X,
O,
};
enum class GameStatus {
In_Progress,
X_Winner,
O_Winner,
Draw
};
class Tictactoe {
private:
GamePiece game[3][3];
public:
Tictactoe();
// Stringfy board (empty spaces are represented by "_", spaces occupied by X is represented by "x"
// and spaces occupied by O, "o")
std::string getStateMessage();
// Check if it's possible to place a piece at the specified position (i.e. there's no player
// piece there yet)
bool canSetPlay(int row, int col);
// Put a piece on the board at specific row and col and return if it was performed or not
bool setPlay(int row, int col, GamePiece piece);
// Get printable board
std::string getBoard();
// 0: no winner yet; 1: player X won; 2: player O won; 3: draw
GameStatus checkWin();
};
#endif | true |
1534475afc13dec755cf830ae78521b1bf2cc8f5 | C++ | hankel343/Lab-2 | /Lab 2/Lab2.cpp | UTF-8 | 4,153 | 4.03125 | 4 | [] | no_license | /*
Hankel Haldin
Lab 2 Exploring Output
Due: 9/14/2020
Printing class schedule and star pattern to console
*/
#include <iostream> //For cout and endl keywords
#include <string> //Allows use of strings
#include <iomanip> //Used for setprecision for this program to control spacing between output
//Eliminates the need to use scope resolution operator (::) on standard library keywords
using namespace std;
/******************
Function Prototypes
******************/
//Prototypes for schedules by day
void Monday_Schedule();
void Tuesday_Schedule();
void Wednesday_Schedule();
void Thursday_Schedule();
void Friday_Schedule();
//Prototype for star pattern
void Star_Pattern();
/**********************
Identifier declarations
***********************/
//Identifier declarations for days of the week M-F.
const string M = "Monday";
const string T = "Tuesday";
const string W = "Wednesday";
const string TH = "Thursday";
const string F = "Friday";
//Identifier declarations for classes. Includes meeting times.
const string ALGEBRA = "8:00 - 9:30am College Algebra";
const string RELIGION = "12:00 - 1:30pm Intro to Religion";
const string C_LECTURE = "1:30 - 2:30pm C++ Lecture";
const string MICRO_ECON = "8:00 - 9:30am Microeconomics";
const string C_LAB = "1:00 - 3:00pm C++ Lab";
const string COLLEGE_EXP = "8:00 - 9:30am College Experience";
//Identifier declarations for star pattern.
const string PATTERN1 = " * * * *";
const string PATTERN2 = "* * * * ";
int main()
{
//Banner message for class schedule
cout << "********\n";
cout << "Class Schedule Fall 2020" << endl;
cout << "********\n";
//Calls to schedule functions defined below.
Monday_Schedule();
Tuesday_Schedule();
Wednesday_Schedule();
Thursday_Schedule();
Friday_Schedule();
//Banner message for star pattern
cout << "********\n";
cout << "Star Pattern" << endl;
cout << "********\n";
//Calls star pattern function
Star_Pattern();
return 0;
}
/************************
Definitions for functions
*************************/
void Monday_Schedule()
{
//Outputs Monday with classes and their times.
cout << M << setw(int(ALGEBRA.length()) + int(8)) << ALGEBRA << endl;
cout << M << setw(int(RELIGION.length()) + int(8)) << RELIGION << endl;
cout << M << setw(int(C_LECTURE.length()) + int(8)) << C_LECTURE << endl;
cout << " " << endl; //Space before next block of output.
}
void Tuesday_Schedule()
{
//Outputs Tuesday with classes and their times.
cout << T << setw(int(MICRO_ECON.length()) + int(7)) << MICRO_ECON << endl;
cout << T << setw(int(C_LAB.length()) + int(7)) << C_LAB << endl;
cout << " " << endl; //Space before next block of output.
}
void Wednesday_Schedule()
{
//Outputs Wednesday with classes and their times.
cout << W << setw(int(ALGEBRA.length()) + int(5)) << ALGEBRA << endl;
cout << W << setw(int(RELIGION.length()) + int(5)) << RELIGION << endl;
cout << " " << endl; //Space before next block of output.
}
void Thursday_Schedule()
{
//Outputs Thursday with classes and their times
cout << TH << setw(int(MICRO_ECON.length()) + int(6)) << MICRO_ECON << endl;
cout << " " << endl; //Space before next block of output
}
void Friday_Schedule()
{
//Outputs Friday with classes and their times.
cout << F << setw(int(COLLEGE_EXP.length()) + int(8)) << COLLEGE_EXP << endl;
cout << " " << endl; //Space before next block of output
}
//Definition of the Star_Pattern function.
void Star_Pattern()
{
/************************************************************************************************************************
*This function is composed of 2 patterns that repeat four times each.
*Instead of having to count out the pattern each time, the function allows you call it and reproduce the following block.
*************************************************************************************************************************/
cout << PATTERN1 << endl;
cout << PATTERN2 << endl;
cout << PATTERN1 << endl;
cout << PATTERN2 << endl;
cout << PATTERN1 << endl;
cout << PATTERN2 << endl;
cout << PATTERN1 << endl;
cout << PATTERN2 << endl;
} | true |
fed103fd23ccfe5b889d557354d8abce8dca5bf4 | C++ | lbenc135/Cpp_codes | /Tables/main.cpp | UTF-8 | 346 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,k,s,result=0,boxes=0;
cin >> n >> k >> s;
int box[n];
for(int i=0;i<n;i++)
{
cin >> box[i];
}
sort(box,box+n);
for(int i=n-1;result<k*s;i--)
{
result+=box[i];
boxes++;
}
cout << boxes << endl;
}
| true |
f571b3de56b2b697780c21b34a8cf37521636850 | C++ | MarcoNadalin/Azul_BoardGame_Terminal_Based | /Menu.h | UTF-8 | 961 | 3.09375 | 3 | [] | no_license | #ifndef COSC_ASS_TWO_MENU
#define COSC_ASS_TWO_MENU
#include <iostream>
#include <string>
#include "Game.h"
class Menu {
public:
/*
* the menu constructor which instantiates the game.
*/
Menu();
~Menu();
/*
* Prints out the main menu and handles all user input. If the user inputs "1", the startGame method is called.
* is called.
* @param seed The seed the user has selected from the command line arguments.
*/
void run(unsigned int seed);
/*
* Prints out the menu
*/
void printMenu();
/*
* Prints out the credits.
*/
void printCredits();
/*
* calls the startGame method on the Game object.
* @param seed The seed the user has selected from the command line arguments.
*/
void startGame(unsigned int seed);
/*
*
*/
void loadGame(std::string filename);
private:
Game* game;
};
#endif | true |
9cfa69a900e6575dd8261dcbca48f83dbcfd56ab | C++ | yanglin526000/Wu-Algorithm | /公司真题/滴滴17秋招_餐馆.cc | UTF-8 | 1,961 | 3.671875 | 4 | [] | no_license | /*
某餐馆有n张桌子,每张桌子有一个参数:a 可容纳的最大人数; 有m批客人,每批客人有两个参数:b人数,c预计消费金额。 在不允许拼桌的情况下,请实现一个算法选择其中一部分客人,使得总预计消费金额最大
输入描述:
输入包括m+2行。
第一行两个整数n(1 <= n <= 50000),m(1 <= m <= 50000)
第二行为n个参数a,即每个桌子可容纳的最大人数,以空格分隔,范围均在32位int范围内。
接下来m行,每行两个参数b,c。分别表示第i批客人的人数和预计消费金额,以空格分隔,范围均在32位int范围内。
输出描述:
输出一个整数,表示最大的总预计消费金额
输入例子:
3 5
2 4 2
1 3
3 5
3 7
5 9
1 10
输出例子:
20
*/
#include <iostream>
#include <utility>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
//思路:把餐桌椅子个数从小到大排,把顾客数从小到大排,然后从第一个餐桌开始,能放进去的顾客数中找到消费量最大的塞进餐桌
//或者说,我是把餐桌椅子个数从小到大排,把顾客的金额从小到大排,先满足最大金额的,保证最大金额的使用的椅子数桌子是最少的,然后依次走下去。
int main(){
int n, m;
vector<int> a;
for(int i=0; i<n; i++){
cin>>a[i];
}
vector<pair<int, int> > v;
for(int i=0; i<m; i++){
cin>>v[i].first>>v[i].second;
}
sort(a.begin(), a.end());
list<int> l(a.begin(), a.end());
sort(v.begin(), v.end(),[](pair<int,int> x, pair<int, int> y){
return x.second>y.second;
});
int count=0;
for(int i=0; i<m; i++){
//从最小的容量桌子开始
for(auto it=l.begin(); it!=l.end(); it++){
if(*it>v[i].first){
l.erase(it);
count+=v[i].second;
break;
}
}
}
cout<<count<<endl;
} | true |
de830b158480cb3e6a4b0ef7ff02aec13a6e34fd | C++ | Analking228/cpp_piscine | /Module_04/ex03/Character.cpp | UTF-8 | 1,135 | 3.09375 | 3 | [] | no_license | #include "Character.hpp"
Character::Character(const std::string& name) : _Name(name) {}
Character::Character(const Character& other) : _Name(other._Name) {
for(int i = 0; i < 4; i++)
if(other._Inv[i] != nullptr)
_Inv[i] = other._Inv[i]->clone();
}
const std::string& Character::getName() const{
return _Name;
}
void Character::equip(AMateria* m) {
for (int i = 0; i < 4; i++)
if (_Inv[i] == nullptr) {
_Inv[i] = m->clone();
return ;
}
}
void Character::unequip(int idx) {
if (idx >= 0 && idx <= 3)
_Inv[idx] = nullptr;
}
void Character::use(int idx, ICharacter& target) {
if (idx >= 0 && idx <= 3 && _Inv[idx])
_Inv[idx]->use(target);
}
Character& Character::operator=(const Character& other) {
for(int i = 0; i < 4; i++)
if(other._Inv[i] == nullptr) {
if (_Inv[i])
delete _Inv[i];
_Inv[i] = nullptr;
}
else {
if (_Inv[i])
delete _Inv[i];
_Inv[i] = other._Inv[i]->clone();
}
return *this;
}
Character::~Character() {
for(int i = 0; i < 4; i++)
if(_Inv[i] != nullptr)
delete _Inv[i];
} | true |
bb9b47d079dfe6297bb97267df26294ac5f1d174 | C++ | hatlonely/leetcode | /cpp/leetcode/leetcode/120_triangle.cpp | UTF-8 | 1,779 | 3.71875 | 4 | [] | no_license | //
// 120_triangle.cpp
// leetcode
//
// Created by hatlonely on 16/1/25.
// Copyright © 2016年 hatlonely. All rights reserved.
//
// Given a triangle, find the minimum path sum from top to bottom.
// Each step you may move to adjacent numbers on the row below.
//
// For example, given the following triangle
// [
// [2],
// [3,4],
// [6,5,7],
// [4,1,8,3]
// ]
// The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
//
// Note:
// Bonus point if you are able to do this using only O(n) extra space,
// where n is the total number of rows in the triangle.
//
#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>
namespace triangle {
class Solution {
public:
int minimumTotal(std::vector<std::vector<int>> &triangle) {
if (triangle.empty()) {
return 0;
}
int n = (int)triangle.size();
std::vector<int> sums(n, 0);
sums[0] = triangle[0][0];
for (int i = 1; i < n; i++) {
sums[i] = sums[i - 1];
for (int j = i - 1; j >= 1; j--) {
sums[j] = std::min(sums[j - 1], sums[j]);
}
for (int j = 0; j <= i; j++) {
sums[j] += triangle[i][j];
}
}
return *std::min_element(sums.begin(), sums.end());
}
};
int main(int argc, const char *argv[]) {
auto test = [](std::vector<std::vector<int>> vvi, int expected) {
Solution solution;
std::vector<std::vector<int>> triangle(vvi);
int result = solution.minimumTotal(triangle);
std::cout << result << std::endl;
return result == expected;
};
assert(test({{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}, 11));
return 0;
}
}
| true |
3371556e8aec54d34d044c091a6f05776f4efc66 | C++ | liuxuanhai/C-code | /The C++ Standard Library/The C++ Standard Library/P123 二元判断式.cpp | WINDOWS-1252 | 1,006 | 3.5 | 4 | [] | no_license | // : 2014-08-22 09:56:39
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
using namespace std;
class Person
{
private:
string f;
string l;
public:
Person(const string & ff, const string & ll): f(ff), l(ll) {}
string firstname() const { return f; }
string lastname() const { return l; }
};
// binary function predicate:
// - return whether a person is less than another person
bool personSortCriterion(const Person & p1, const Person & p2)
{
return p1.firstname() < p2.firstname();
}
int main()
{
deque<Person> coll;
char tmp[100];
for (int i = 0; i < 10; i++)
coll.push_back(Person(itoa(rand() % 100, tmp, 10), itoa(rand() % 100, tmp, 10)));
for (auto pos = coll.begin(); pos != coll.end(); ++pos)
cout << pos->firstname() << " - " << pos->lastname() << endl;
cout << endl;
sort(coll.begin(), coll.end(), personSortCriterion);
for (auto pos = coll.begin(); pos != coll.end(); ++pos)
cout << pos->firstname() << " - " << pos->lastname() << endl;
} | true |
9bdc9b0cbf4a549b6278cdaba2a67b01de1b9eb9 | C++ | chiragramani/SystemMonitor | /src/process.cpp | UTF-8 | 1,126 | 2.875 | 3 | [
"MIT"
] | permissive | #include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include "process.h"
#include "linux_parser.h"
using std::string;
using std::to_string;
using std::vector;
// Constructor
Process::Process(int pid) : _pid(pid), _user(LinuxParser::User(pid)), _command(LinuxParser::Command(pid)) {};
// Pid
int Process::Pid() const { return _pid; }
// Cpu Utilization
float Process::CpuUtilization() const {
LinuxParser::ProcessCPUInfo info = LinuxParser::CpuUtilization(_pid);
const float totalTime = info.uTime + info.sTime + info.cutime + info.cstime;
const float seconds = LinuxParser::UpTime() - info.startTime;
const float utilization = (totalTime / seconds);
return utilization;
}
// Command
string Process::Command() const { return _command; }
// RAM
string Process::Ram() { return LinuxParser::Ram(_pid); }
// User
string Process::User() const { return _user; }
// Uptime
long int Process::UpTime() const { return LinuxParser::UpTime(_pid); }
// > operator overloading
bool Process::operator>(Process const& a) const {
return (CpuUtilization() > a.CpuUtilization());
} | true |
4f633db82dfc64a312203bf5873739df158e16d8 | C++ | StephaneB1/POO2_Labo4_Buffy | /Action/Action.h | UTF-8 | 616 | 2.515625 | 3 | [] | no_license | /*
-----------------------------------------------------------------------------------
Laboratoire : 04
Fichier : Action.h
Auteur(s) : Stéphane Bottin & Chau Ying Kot
Date : 14.05.2020
-----------------------------------------------------------------------------------
*/
#ifndef POO2_LABO4_BUFFY_ACTION_H
#define POO2_LABO4_BUFFY_ACTION_H
#include "../Humanoid/Humanoid.h"
class Field;
class Action {
public:
Action() {};
virtual ~Action();
/**
* Execute the corresponding action
* @param field
*/
virtual void execute(Field* field) = 0;
};
#endif //POO2_LABO4_BUFFY_ACTION_H
| true |
069ec37724318a6942c31c3e48d83ee5fab47b89 | C++ | DhruvKumar/MDP-Power-Manager | /matrix_calc.cc | UTF-8 | 12,997 | 2.578125 | 3 | [] | no_license | /*
This program calculates the Transition Probability matrices for the MDP formulation.
Copyright (C) 2008 Dhruv Kumar dhruv21@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <float.h>
#define MAXLINE 8192
//#define DEBUG
char STAT_FILE_PATH[]="/home/dhruv/thesis/programs/stats/2sec_sampling/past_pering_newstats_report";
using namespace std;
/* reverse: reverse string s in place */
void reverse(char s[])
{
int c, i, j;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
int divide_states(double maxval, double minval, int numstates, double * statearray)
{
#ifdef DEBUG
printf("\nOn entering divide_state values are : %lf %lf %d\n", maxval, minval, numstates);
#endif
int i=0;
double current_val = minval;
double final_val = maxval;
double step = (maxval - minval)/(double)numstates;
while (current_val <= final_val )
{
*(statearray + i) = current_val;
current_val += step;
i++;
}
if(statearray[numstates] != maxval)
statearray[numstates] = maxval;
if(statearray[0] != minval)
statearray[0] = minval;
return 0;
}
int state_transition_encode(double statearray[], int numstates, double inival, double finval, char * transitionstring)
{
#ifdef DEBUG
puts("\nEntering state_transition_decode function\n");
puts("Initial transition string: ");
puts(transitionstring);
#endif
int i, transition, ini_state_number, fin_state_number;
char ini_state[100], fin_state[100], statestring[200];
for (i=0; i<numstates; i++)
{
if (inival >= statearray[i] && inival <= statearray[i+1])
ini_state_number = i;
if (finval >= statearray[i] && finval <= statearray[i+1])
fin_state_number = i;
}
#ifdef DEBUG
puts("\nInteger value of initial state= ");
printf("%d", ini_state_number);
#endif
itoa(ini_state_number, ini_state);
#ifdef DEBUG
puts("\nInitial state as identified: ");
puts(ini_state);
#endif
itoa(fin_state_number, fin_state);
#ifdef DEBUG
puts("\nFinal state as identified: ");
puts(fin_state);
puts("\nAdding space at the end of the Initial state string: ");
#endif
strcat(ini_state," ");
#ifdef DEBUG
puts(ini_state);
puts("\nConcatenating initial state string with final state string and copying into statestring object: ");
#endif
strcpy(statestring,strcat(ini_state,fin_state));
#ifdef DEBUG
puts(statestring);
cout<<endl;
puts("\nCopying statestring to final transitionstring: ");
#endif
strcpy(transitionstring, statestring);
#ifdef DEBUG
puts(transitionstring);
cout<< endl;
#endif
return 0;
}
int action_encode(long inifreq, long finfreq)
{
#ifdef DEBUG
puts("\nEntering the action encode function");
printf("\nThe inifreq and finfreq values received are %ld, %ld", inifreq, finfreq);
#endif
int action;
if(inifreq == 1000000 && finfreq == 1000000)
action = 0;
else if (inifreq == 1000000 && finfreq == 1333000)
action = 1;
else if (inifreq == 1000000 && finfreq == 1667000)
action =2;
else if (inifreq == 1000000 && finfreq == 2000000)
action = 3;
else if (inifreq == 1333000 && finfreq == 1000000)
action =0;
else if (inifreq == 1333000 && finfreq == 1333000)
action = 1;
else if (inifreq == 1333000 && finfreq == 1667000)
action =2;
else if (inifreq == 1333000 && finfreq == 2000000)
action = 3;
else if (inifreq == 1667000 && finfreq == 1000000)
action = 0;
else if (inifreq == 1667000 && finfreq == 1333000)
action = 1;
else if (inifreq == 1667000 && finfreq == 1667000)
action = 2;
else if (inifreq == 1667000 && finfreq == 2000000)
action = 3;
else if (inifreq == 2000000 && finfreq == 1000000)
action = 0;
else if (inifreq == 2000000 && finfreq == 1333000)
action = 1;
else if (inifreq == 2000000 && finfreq == 1667000)
action = 2;
else if (inifreq == 2000000 && finfreq == 2000000)
action = 3;
else action = -1;
#ifdef DEBUG
printf("\nThe action identified with this transition is %d\n", action);
#endif
return action;
}
int main(int argc, char **argv)
{
int TOTALSTATES = 10;
int TOTALACTIONS = 4;
double statevector[TOTALSTATES];
double initial_val = 0.0, final_val = 0.0;
double transitionProbMatrix[TOTALACTIONS][TOTALSTATES][TOTALSTATES];
char transition_string[200];
//end test
double initialprob = 1.0/(double)(TOTALSTATES);
double incrementprob = 1.0/((double)(TOTALACTIONS*TOTALSTATES*TOTALSTATES));
double decrementprob = incrementprob/(TOTALSTATES-1);
printf("\nIncrement Prob = %lf Decrement Prob = %lf\n", incrementprob, decrementprob);
int j,k,l;
for (j=0; j <TOTALACTIONS ; j++)
{
for (k=0 ; k<TOTALSTATES; k++)
{
for (l=0; l <= TOTALSTATES; l++)
transitionProbMatrix[j][k][l] = initialprob;
}
}
char line_stat_file[MAXLINE];
FILE *fp;
char * pch;
fp = fopen(STAT_FILE_PATH, "r");
double linecount = 0.0;
int inifreqindex, changefreq, finfreqindex, core0temp, core1temp ;
long rate, busytime, totaltime, FREQ;
double cpi, volt, avgvolt, avgcurrent, AVGCURRENTCPI,BDCPI, AVGRATECPI, totcyc, totinst, dcyc, dinst, cap, dcap, maxBDCPI=0, maxAVGRATECPI=0, maxAVGCURRENTCPI=0, minAVGCURRENTCPI=DBL_MAX, minBDCPI=DBL_MAX, minAVGRATECPI=DBL_MAX, util, avgrate, dschrg;
if(fp != NULL)
{
while(fgets(line_stat_file, MAXLINE, fp)!=NULL)
{
linecount ++;
cout << endl;
int match=0;
pch = strtok(line_stat_file," ");
while(pch != NULL)
{
match++;
switch(match)
{
case 1: cpi = atof(pch); break;
case 2: totcyc = atof(pch); break;
case 3: totinst = atof(pch); break;
case 4: dcyc = atof(pch); break;
case 5: dinst = atof(pch); break;
case 6: rate = atol(pch); break;
case 7: avgrate = atof(pch); break;
case 8: cap = atof(pch); break;
case 9: dcap = atof(pch); break;
case 10: dschrg = atof(pch); break;
case 11: volt = atof(pch); break;
case 12: avgvolt = atof(pch); break;
case 13: avgcurrent = atof(pch); break;
case 14: AVGCURRENTCPI = atof(pch); break;
case 15: BDCPI = atof(pch); break;
case 16: AVGRATECPI = atof(pch); break;
case 17: busytime = atol(pch); break;
case 18: totaltime = atol(pch); break;
case 19: util = atof(pch); break;
case 20: FREQ = atol(pch); break;
case 21: inifreqindex = atoi(pch); break;
case 22: changefreq = atoi(pch); break;
case 23: finfreqindex = atoi(pch); break;
case 24: core0temp = atoi(pch); break;
case 25: core1temp = atoi(pch); break;
default: break;
}
pch = strtok(NULL," ");
}
if(BDCPI > maxBDCPI)
maxBDCPI=BDCPI;
if(AVGRATECPI > maxAVGRATECPI)
maxAVGRATECPI = AVGRATECPI;
if(AVGCURRENTCPI > maxAVGCURRENTCPI)
maxAVGCURRENTCPI = AVGCURRENTCPI;
if(BDCPI < minBDCPI)
minBDCPI = BDCPI;
if(AVGRATECPI < minAVGRATECPI)
minAVGRATECPI = AVGRATECPI;
if(AVGCURRENTCPI < minAVGCURRENTCPI)
minAVGCURRENTCPI = AVGCURRENTCPI;
}
}
//printf("\n\n MAX_BDCPI = %lf MIN_BDCPI = %lf MAX_AVGRATECPI = %lf MIN_AVGRATECPI = %lf\n\n", maxBDCPI, minBDCPI, maxAVGRATECPI, minAVGRATECPI);
//divide_states(maxBDCPI, minBDCPI, TOTALSTATES, statevector);
// For AVGCURRENTCPI
divide_states(maxAVGCURRENTCPI, minAVGCURRENTCPI, TOTALSTATES, statevector);
#ifdef DEBUG
for(int i=0; i <= TOTALSTATES; i++)
printf("%lf\n", statevector[i]);
state_transition_encode(statevector, TOTALSTATES, initial_val, final_val, transition_string);
puts("\nFinal transition string in the main function: ");
puts(transition_string);
cout<<endl<<endl;
#endif
fclose(fp);
fp = fopen(STAT_FILE_PATH, "r");
linecount=0.0;
double prev_AVGRATECPI, prev_BDCPI, prev_FREQ=FREQ, prev_AVGCURRENTCPI;
int flag = 0, action;
while(fgets(line_stat_file, MAXLINE, fp)!=NULL)
{
linecount ++;
cout << endl;
int match=0;
pch = strtok(line_stat_file," ");
while(pch != NULL)
{
match++;
switch(match)
{
case 1: cpi = atof(pch); break;
case 2: totcyc = atof(pch); break;
case 3: totinst = atof(pch); break;
case 4: dcyc = atof(pch); break;
case 5: dinst = atof(pch); break;
case 6: rate = atol(pch); break;
case 7: avgrate = atof(pch); break;
case 8: cap = atof(pch); break;
case 9: dcap = atof(pch); break;
case 10: dschrg = atof(pch); break;
case 11: volt = atof(pch); break;
case 12: avgvolt = atof(pch); break;
case 13: avgcurrent = atof(pch); break;
case 14: AVGCURRENTCPI = atof(pch); break;
case 15: BDCPI = atof(pch); break;
case 16: AVGRATECPI = atof(pch); break;
case 17: busytime = atol(pch); break;
case 18: totaltime = atol(pch); break;
case 19: util = atof(pch); break;
case 20: FREQ = atol(pch); break;
case 21: inifreqindex = atoi(pch); break;
case 22: changefreq = atoi(pch); break;
case 23: finfreqindex = atoi(pch); break;
case 24: core0temp = atoi(pch); break;
case 25: core1temp = atoi(pch); break;
default: break;
}
pch = strtok(NULL," ");
}
if(flag!=0 && action !=-1)
{
state_transition_encode(statevector, TOTALSTATES, prev_AVGCURRENTCPI, AVGCURRENTCPI, transition_string);
action = action_encode(prev_FREQ, FREQ) ;
int INISTATE=0, FINSTATE=0;
sscanf(transition_string,"%d %d", &INISTATE, &FINSTATE);
printf("\nInitial State = %d Final State = %d Action = %d\n", INISTATE, FINSTATE, action);
transitionProbMatrix[action][INISTATE][FINSTATE] += incrementprob;
k=INISTATE;
l=0;
while(l<TOTALSTATES)
{
if(transitionProbMatrix[action][k][l]>0 && l != FINSTATE)
{
transitionProbMatrix[action][k][l] -= decrementprob;
printf("\nDecrementing %d %d %d\n",action,k,l);
}
l++;
}
}
prev_AVGCURRENTCPI = AVGCURRENTCPI;
prev_AVGRATECPI = AVGRATECPI;
prev_BDCPI = BDCPI;
prev_FREQ = FREQ;
flag +=1;
}
fclose(fp);
double observationprobability = 1.0/(double)linecount;
int statenumber = 0;
for (j=0; j <= 3 ; j++)
{
printf("\n\n\n------Matrix for action %d------\n\n", j);
for (k=0 ; k<= TOTALSTATES-1; k++)
{
for (l=0; l <= TOTALSTATES-1; l++)
{
printf("%lf", transitionProbMatrix[j][k][l]);
printf(" ");
}
printf(";\n");
}
}
int reward_distribution = (TOTALSTATES/2);
for(j=0; j< 4; j++)
{
printf("\n\n------Reward Matrix for action %d------\n\n", j);
for(k=0; k<TOTALSTATES; k++)
{
for(l=0; l<TOTALSTATES; l++)
{
printf("%d", reward_distribution);
printf(" ");
reward_distribution--;
}
printf(";\n");
reward_distribution = (TOTALSTATES/2);
}
}
printf("\n\nState Vector\n");
for(k=0; k<=TOTALSTATES;k++)
{
printf("\n%lf",statevector[k]);
}
printf("\n\nmaxAVGCURRENTCPI= %lf minAVGCURRENTCPI=%lf", maxAVGCURRENTCPI, minAVGCURRENTCPI);
cout<<endl<<endl<<endl;
return 0;
}
| true |
ddfb9e6f81452569158cbc4cefd574b09ad41dc2 | C++ | F0RTYS3V3N/Metin2-Advanced-Duel-Exchange- | /1.Svn/Server/game/src/pvp.h | UTF-8 | 1,660 | 2.65625 | 3 | [] | no_license | //Find
~CPVP();
///Change
#if defined(__BL_ADVANCED_DUEL__)
virtual ~CPVP();
#else
~CPVP();
#endif
//Find
void Win(DWORD dwPID);
///Change
#if defined(__BL_ADVANCED_DUEL__)
virtual void Win(DWORD dwPID);
#else
void Win(DWORD dwPID);
#endif
///Add after CPVP class
#if defined(__BL_ADVANCED_DUEL__)
class CAdvancedPVP : public CPVP
{
public:
enum class EFLAG : std::uint8_t
{
AdvancedDuel = 1 << 0,
Potion = 1 << 1,
Equip_Change = 1 << 2,
Mount = 1 << 3,
};
class SPlayerStuff
{
public:
SPlayerStuff(LPCHARACTER m_ch, std::vector<LPITEM>&& m_DuelItems, long m_Gold, bool bMountRestrict);
~SPlayerStuff() = default;
void Win(LPCHARACTER ch) const;
void GiveMyStuffBack() const;
private:
LPCHARACTER ch; // Owner
std::vector<LPITEM> vDuelItems;
long lGold;
};
CAdvancedPVP(CPVP& v, LPCHARACTER ch_1, LPCHARACTER ch_2);
~CAdvancedPVP() = default;
void Win(DWORD dwPID) override;
static constexpr bool IsForbidden(EFLAG e, std::uint8_t m_Flag)
{
return m_Flag & static_cast<std::uint8_t>(e);
}
constexpr bool IsForbidden(EFLAG e) const
{
return IsForbidden(e, uFlag);
}
private:
std::array<std::unique_ptr< SPlayerStuff >, 2> arrPlayerStuff;
std::uint8_t uFlag; // EFLAG
};
#endif
//Find
virtual ~CPVPManager();
///Add
#if defined(__BL_ADVANCED_DUEL__)
CAdvancedPVP* GetAdvancedPVP(const LPCHARACTER pkChr) const;
#endif
//Find
void Insert(LPCHARACTER pkChr, LPCHARACTER pkVictim);
///Change
#if defined(__BL_ADVANCED_DUEL__)
void Insert(LPCHARACTER pkChr, LPCHARACTER pkVictim, bool bIsAdvanced = false);
#else
void Insert(LPCHARACTER pkChr, LPCHARACTER pkVictim);
#endif | true |
3d66e61e53c280363dbc5919dbe0f524f0641b4f | C++ | huseyinoztrk/DataStructures | /Week5/CircularLinkedList/include/CircularLinkedList.hpp | UTF-8 | 3,276 | 3.765625 | 4 | [] | no_license | #ifndef CIRCULARLINKEDLIST_HPP
#define CIRCULARLINKEDLIST_HPP
#include "Iterator.hpp"
#include "NoSuchElement.hpp"
template <typename Object>
class CircularLinkedList{
private:
Node<Object> *head;
int size;
Iterator<Object> FindPrevByPosition(int position){
if(position < 0 || position > size) throw NoSuchElement("No Such Element");
int index=0;
Iterator<Object> iterator(head);
while(position != index){
iterator.next();
index++;
}
return iterator;
}
void updateLastNode(){
Node<Object> *lastNode = FindPrevByPosition(size).current;
lastNode->next = head->next;
}
public:
CircularLinkedList(){
head = new Node<Object>();
size=0;
}
bool isEmpty()const{
return head->next == NULL;
}
int Count()const{
return size;
}
void add(const Object& item){
insert(size,item);
}
void insert(int index,const Object& item){
Iterator<Object> iterator = FindPrevByPosition(index);
iterator.current->next = new Node<Object>(item,iterator.current->next);
size++;
if(index == 0) updateLastNode();
}
const Object& first()const throw(NoSuchElement){
if(isEmpty()) throw NoSuchElement("No Such Element");
return head->next->item;
}
const Object& last()throw(NoSuchElement){
if(isEmpty()) throw NoSuchElement("No Such Element");
return FindPrevByPosition(size).getCurrent();
}
int indexOf(const Object& item)throw(NoSuchElement){
int index=0;
for(Iterator<Object> iterator(head->next);index<size;iterator.next()){
if(iterator.getCurrent() == item) return index;
index++;
}
throw NoSuchElement("No Such Element");
}
const Object& elementAt(int index)throw(NoSuchElement){
if(index < 0 || index >= size) throw NoSuchElement("No Such Element");
Iterator<Object> iterator = FindPrevByPosition(index);
return iterator.current->next->item;
}
bool find(const Object& item)const{
for(Iterator<Object> iterator(head->next);iterator.hasNext();iterator.next()){
if(iterator.getCurrent() == item) return true;
}
return false;
}
void remove(const Object& item){
int index = indexOf(item);
removeAt(index);
}
void removeAt(int index)throw(NoSuchElement){
if(index < 0 || index >= size) throw NoSuchElement("No Such Element");
Iterator<Object> iterator = FindPrevByPosition(index);
Node<Object> *del = iterator.current->next;
iterator.current->next = iterator.current->next->next;
delete del;
size--;
if(size != 0 && index == 0) updateLastNode();
}
friend ostream& operator<<(ostream& screen,CircularLinkedList<Object> &right)
{
int index=0;
for(Iterator<Object> iterator(right.head->next);index<right.size;iterator.next()){
screen<<iterator.getCurrent()<<" -> ";
index++;
}
screen<<"NULL"<<endl;
return screen;
}
void printAllFromPosition(int index)throw(NoSuchElement){
if(index < 0 || index >= size) throw NoSuchElement("No Such Element");
Iterator<Object> iterator = FindPrevByPosition(index);
int ind=0;
for(iterator.next();ind<size;iterator.next(),ind++){
cout<<iterator.getCurrent()<<" -> ";
}
cout<<endl;
}
void clear(){
while(!isEmpty())
removeAt(0);
}
~CircularLinkedList(){
clear();
delete head;
}
};
#endif
| true |
7439b152fe039abd6e04032a9c902faa997b4c5e | C++ | ferserc1/bg2e-cpp | /src/base/Image.cpp | UTF-8 | 2,070 | 3.0625 | 3 | [
"MIT"
] | permissive |
#include <bg2e/base/Image.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <iostream>
namespace bg2e {
namespace base {
std::unordered_map<std::string, std::shared_ptr<Image>> Image::g_imageCache;
void Image::ClearCache()
{
g_imageCache.clear();
}
void Image::ClearCacheFile(const std::string& file)
{
auto it = g_imageCache.find(file);
if (it != g_imageCache.end())
{
g_imageCache.erase(it);
}
}
std::shared_ptr<Image> Image::LoadFromFile(const std::string& fileName)
{
if (g_imageCache.find(fileName) != g_imageCache.end())
{
std::cout << "Image found in cache: '" << fileName << "'. Skip load" << std::endl;
return g_imageCache[fileName];
}
else
{
std::cout << "Image not found in cache: '" << fileName << "'. Loading from file" << std::endl;
int w, h, c;
stbi_uc* data = stbi_load(fileName.c_str(), &w, &h, &c, STBI_rgb_alpha);
if (!data)
{
throw std::runtime_error("Could not load image from file '" + fileName + "'");
}
std::shared_ptr<Image> result = std::make_shared<Image>();
result->_imageData = static_cast<Byte*>(data);
result->_size = Size{ static_cast<uint32_t>(w), static_cast<uint32_t>(h) };
if (c == 3)
{
result->_format = ImageComponentFormat::RGB;
}
else if (c == 4)
{
result->_format = ImageComponentFormat::RGBA;
}
result->_imageSource = ImageSource::LoadFromFile;
g_imageCache[fileName] = result;
return result;
}
}
Image::Image()
{
}
Image::~Image()
{
destroy();
}
void Image::destroy()
{
std::cout << "Destroy image" << std::endl;
if (_imageSource == ImageSource::Setter)
{
delete [] _imageData;
}
else if (_imageSource == ImageSource::LoadFromFile)
{
stbi_image_free(_imageData);
}
_imageData = nullptr;
_size = Size{ 0, 0 };
_format = ImageComponentFormat::RGB;
}
}
}
| true |
00ae4bacdbda2e0bf02ea4c10b751035daf6d065 | C++ | mwthinker/CppSdl2 | /src/sdl/shaderprogram.h | UTF-8 | 2,468 | 2.90625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef CPPSDL2_SDL_SHADERPROGRAM_H
#define CPPSDL2_SDL_SHADERPROGRAM_H
#include "opengl.h"
#include <string>
#include <map>
namespace sdl {
class ShaderProgram {
public:
// Create an empty non linked shader.
ShaderProgram() = default;
ShaderProgram(const ShaderProgram&) = delete;
ShaderProgram& operator=(const ShaderProgram&) = delete;
ShaderProgram(ShaderProgram&& other) noexcept;
ShaderProgram& operator=(ShaderProgram&& other) noexcept;
~ShaderProgram();
// Bind the attribute to the shader.
// Must be called before linking the shader in order for the attribute to
// be available. I.e. before calling loadAndLinkShadersFromFile(...).
void bindAttribute(const std::string& attribute);
// Return the gl memory location for the attribute.
// Return -1 on error.
int getAttributeLocation(const std::string& attribute) const;
// Return the gl memory location for the uniform.
// Return -1 on error.
int getUniformLocation(const std::string& uniform) const;
// Load shaders from files. Is safe to call multiple times but only the
// first successful is "used. Load and link the vertex shader and the
// fragment shader in the created program. Return true if the creation
// is successful else false.
[[nodiscard]] bool loadAndLinkFromFile(const std::string& vShaderFile, const std::string& fShaderFile);
[[nodiscard]] bool loadAndLinkFromFile(const std::string& vShaderFile, const std::string& gShaderFile, const std::string& fShaderFile);
// Load shaders string parameters "vShader" and "fShader". Is safe to
// call multiple times but only the first successful is "used. Load and
// link the vertex shader and the fragment shader in the created program.
// Return true if the creation is successful else false.
[[nodiscard]] bool loadAndLink(const std::string& vShader, const std::string& fShader);
[[nodiscard]] bool loadAndLink(const std::string& vShader, const std::string& gShader, const std::string& fShader);
// Uses the current gl program. I.e. a call to glUseProgram.
// Does nothing if the program is not loaded.
void useProgram();
// Return if the shader program is linked.
bool isLinked() const noexcept {
return programObjectId_ != 0;
}
private:
bool linkProgram();
void bindAllAttributes();
std::map<std::string, gl::GLuint> attributes_;
mutable std::map<std::string, gl::GLuint> uniforms_;
gl::GLuint programObjectId_ = 0;
};
}
#endif
| true |
8df343b50a9e9a20b10129813c3dbafcd15650f0 | C++ | mattsan/divideInto | /cpp/divideInto.h | UTF-8 | 531 | 3.1875 | 3 | [] | no_license | #ifndef DVIDEINTO_H
#define DVIDEINTO_H
#include <vector>
#include <iterator>
template<typename Iterator>
std::vector<Iterator> divideInto(int n, Iterator begin, Iterator end)
{
std::vector<Iterator> result;
const int length = std::distance(begin, end);
const int partial_length = (length + n - 1) / n;
for(Iterator i = begin; i < end; std::advance(i, partial_length))
{
result.push_back(i);
}
result.push_back(end);
return result;
}
#endif//DVIDEINTO_H
| true |
f78345c463894f19a062c3825661c6dbe56ff69b | C++ | Jojendersie/glhelper | /glhelper/samplerobject.hpp | UTF-8 | 3,647 | 2.84375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "gl.hpp"
#include "texture.hpp"
#include <unordered_map>
namespace gl
{
/// \brief Easy to use OpenGL Sampler Object
///
/// Will store all runtime create sampler objects in a intern static list. List will be cleared on program shutdown or on explicit call.
/// Also binds sampler only if not already bound.
class SamplerObject
{
public:
enum class Filter
{
NEAREST,
LINEAR
};
enum class Border
{
REPEAT = GL_REPEAT,
MIRROR = GL_MIRRORED_REPEAT,
CLAMP = GL_CLAMP_TO_EDGE,
BORDER = GL_CLAMP_TO_BORDER
};
enum class CompareMode
{
NONE,
LESS_EQUAL = GL_LEQUAL,
GREATER_EQUAL = GL_GEQUAL,
LESS = GL_LESS,
GREATER = GL_GREATER,
EQUAL = GL_EQUAL,
NOTEQUAL = GL_NOTEQUAL,
ALWAYS = GL_ALWAYS,
NEVER = GL_NEVER,
};
struct Desc
{
/// Constructs a descriptor with the same border handling for all dimensions.
Desc(Filter minFilter, Filter magFilter, Filter mipFilter, Border borderHandling,
unsigned int maxAnisotropy = 1, const gl::Vec4& borderColor = gl::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
CompareMode compareMode = CompareMode::NONE, float minLod = -1000.0f, float maxLod = 1000.0f);
/// Constructs a descriptor with the different border handling for each dimension.
Desc(Filter minFilter, Filter magFilter, Filter mipFilter, Border borderHandlingU, Border borderHandlingV, Border m_borderHandlingW,
unsigned int maxAnisotropy = 1, const gl::Vec4& borderColor = gl::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
CompareMode compareMode = CompareMode::NONE, float minLod = -1000.0f, float maxLod = 1000.0f);
bool operator == (const Desc& other) const { return memcmp(this, &other, sizeof(Desc)) == 0; }
Filter minFilter;
Filter magFilter;
Filter mipFilter;
Border borderHandlingU;
Border borderHandlingV;
Border borderHandlingW;
unsigned int maxAnisotropy;
gl::Vec4 borderColor;
CompareMode compareMode;
float minLod;
float maxLod;
struct GetHash
{
size_t operator()(const gl::SamplerObject::Desc& desc) const
{
// Super simple sdbm hash function.
size_t hash = 0;
int c;
const unsigned char* str = reinterpret_cast<const unsigned char*>(this);
for (int i = 0; i < sizeof(*this), c = *str++; ++i)
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
};
};
/// Will create or return a existing SamplerObject.
static const SamplerObject& GetSamplerObject(const Desc& desc);
/// Binds sampler to given texture stage if not already bound.
///
/// \attention Deleting a bound resource may cause unexpected errors.
/// The user is responsible for manual unbinding it (or overwriting the previous binding) before deleting.
void BindSampler(GLuint _textureStage) const;
/// Resets sampler binding for the given texture stage to zero.
static void ResetBinding(GLuint _textureStage);
/// Removes all existing sampler objects.
void DestroyAllCachedSamplerObjects() { s_existingSamplerObjects.clear(); }
/// Returns intern OpenGL sampler handle.
SamplerId GetInternHandle() const { return m_samplerId; }
/// Move constructor. Needed for intern hashmap.
///
/// A single redundant bind may happen if the sampler _cpy was bound to a slot, since this pointer will not replaced with the new sampler.
SamplerObject(SamplerObject&& _cpy);
~SamplerObject();
private:
SamplerObject(const Desc& samplerDesc);
static const SamplerObject* s_samplerBindings[Texture::s_numTextureBindings];
static std::unordered_map<Desc, SamplerObject, Desc::GetHash> s_existingSamplerObjects;
SamplerId m_samplerId;
};
};
| true |
2f51e13b75760159d203459eec175d4b6d1ae576 | C++ | Ama-10669107/bubble-sort-and-selection-sort | /bubble sort.cpp | UTF-8 | 367 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
void main()
int i,int arr[],int j,int temp,int c;
cout<<"Enter array size:";
cin>>c;
for (i=0;i<c;i++)
{
cin>>arr[i]
}
for (i=0;i<c;i++)
{
for(j=0;j<(c-i-1);j++)
{if arr[j]>arr[j+1])
{temp=arr[j];
arr[j]= arr[j+1];
arr[j+1]=temp;}}}
cout<<"Elements successfully sorted in ascending order:\n";
for(i=0;i<c;i++)
{cout<<arr[i]<<"";} | true |
7f5a41c117ca0d838d6b38ae5365eb66bca75ce6 | C++ | iamjhpark/BOJ | /2251.cpp | UTF-8 | 6,144 | 3 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<int> answer;
void BFS(int A, int B, int C, vector<vector<bool>> &check) {
int sum = C;
queue<pair<int, int>> q;
q.push(make_pair(0, 0));
check[0][0] = false;
vector<int> from = { 0, 0, 1, 1, 2, 2 };
vector<int> to = { 1, 2, 0, 2, 0, 1 };
while (!q.empty()) {
pair<int, int> current = q.front();
int currentA = current.first;
int currentB = current.second;
int currentC = sum - (currentA + currentB);
q.pop();
if (currentA == 0) { answer.push_back(currentC); }
for (int i = 0; i < 6; i++) {
if (from[i] == 0 && to[i] == 1) {
if (currentA == 0) { continue; }
else if (currentA + currentB > B) {
int nextA = currentA - (B - currentB);
int nextB = B;
int nextC = sum - (nextA + nextB);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
} else {
int nextA = 0;
int nextB = currentA + currentB;
int nextC = sum - (nextA + nextB);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
}
} else if (from[i] == 0 && to[i] == 2) {
if (currentA == 0) { continue; }
else if (currentA + currentC > C) {
int nextA = currentA - (C - currentC);
int nextC = C;
int nextB = sum - (nextA + nextC);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
} else {
int nextA = 0;
int nextC = currentA + currentC;
int nextB = sum - (nextA + nextC);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
}
} else if (from[i] == 1 && to[i] == 0) {
if (currentB == 0) { continue; }
else if (currentB + currentA > A) {
int nextB = currentB - (A - currentA);
int nextA = A;
int nextC = sum - (nextB + nextA);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
} else {
int nextB = 0;
int nextA = currentB + currentA;
int nextC = sum - (nextB + nextA);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
}
} else if (from[i] == 1 && to[i] == 2) {
if (currentB == 0) { continue; }
else if (currentB + currentC > C) {
int nextB = currentB - (C - currentC);
int nextC = C;
int nextA = sum - (nextB + nextC);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
} else {
int nextB = 0;
int nextC = currentB + currentC;
int nextA = sum - (nextB + nextC);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
}
} else if (from[i] == 2 && to[i] == 0) {
if (currentC == 0) { continue; }
else if (currentC + currentA > A) {
int nextC = currentC - (A - currentA);
int nextA = A;
int nextB = sum - (nextC + nextA);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
} else {
int nextC = 0;
int nextA = currentC + currentA;
int nextB = sum - (nextC + nextA);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
}
} else if (from[i] == 2 && to[i] == 1) {
if (currentC == 0) { continue; }
else if (currentC + currentB > B) {
int nextC = currentC - (B - currentB);
int nextB = B;
int nextA = sum - (nextC + nextB);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
} else {
int nextC = 0;
int nextB = currentC + currentB;
int nextA = sum - (nextC + nextB);
if (check[nextA][nextB]) {
check[nextA][nextB] = false;
q.push(make_pair(nextA, nextB));
}
}
}
}
}
}
int main(void) {
int A;
scanf("%d", &A);
int B;
scanf("%d", &B);
int C;
scanf("%d", &C);
vector<vector<bool>> check(201, vector<bool>(201, true));
BFS(A, B, C, check);
sort(answer.begin(), answer.end());
for (auto i = 0; i < answer.size(); i++) {
printf("%d ", answer[i]);
}
return 0;
} | true |
08e8250c6492bda21c4cea762753e1612376ee12 | C++ | sankarmanoj/thrust2D | /opencv/omp/sobel_filter.cpp | UTF-8 | 3,651 | 2.578125 | 3 | [] | no_license | #define THRUST_DEVICE_SYSTEM 2
#include <opencv2/opencv.hpp>
#include <thrust/window_2d.h>
#define PI 3.14159
#define ITER 25
using namespace cv;
class transFunctor
{
public:
__host__ uchar operator() (const uchar a,const uchar b) const
{
return (uchar) sqrt((float) a*a + b*b);
}
};
class convolutionFunctor //:public thrust::shared_unary_window_transform_functor<uchar>
{
public:
int dim;
thrust::block_2d<float> * kernel;
convolutionFunctor( thrust::block_2d<float> * kernel,int dim)
{
this->dim =dim;
this->kernel = kernel;
}
__host__ uchar operator() (const thrust::window_2d<uchar> & input_window,const thrust::window_2d<uchar> & output_window) const
{
uchar temp = 0;
for(int i = 0; i< dim; i++)
{
for(int j = 0; j<dim; j++)
{
temp+=input_window[i][j]*(*kernel)[i][j];
}
}
output_window[1][1]=temp;
return 0;
}
};
int main(int argc, char const *argv[]) {
Mat image;
image = cv::imread( "car.jpg", CV_LOAD_IMAGE_GRAYSCALE );
int dim = 512;
if(argc ==2)
{
dim = atoi(argv[1]);
}
cv::resize(image,image,cv::Size(dim,dim));
thrust::host_block_2d<float> kernelx(3,3);
thrust::host_block_2d<float> kernely(3,3);
thrust::block_2d<float> dkernelx(3,3);
thrust::block_2d<float> dkernely(3,3);
//Sobel Filter
kernelx[0][0]=-1;
kernelx[0][1]=0;
kernelx[0][2]=+1;
kernelx[1][0]=-2;
kernelx[1][1]=0;
kernelx[1][2]=+2;
kernelx[2][0]=-1;
kernelx[2][1]=0;
kernelx[2][2]=+1;
kernely[0][0]=-1;
kernely[0][1]=-2;
kernely[0][2]=-1;
kernely[1][0]=0;
kernely[1][1]=0;
kernely[1][2]=0;
kernely[2][0]=+1;
kernely[2][1]=+2;
kernely[2][2]=+1;
dkernelx=kernelx;
dkernely=kernely;
thrust::block_2d<uchar> uchar_image_block (image.cols,image.rows);
thrust::block_2d<uchar> convolve1_block (image.cols,image.rows);
thrust::block_2d<uchar> convolve2_block (image.cols,image.rows);
thrust::block_2d<uchar> outBlock (image.cols,image.rows);
thrust::block_2d<uchar> zero_image_block (image.cols,image.rows);
uchar * img = (uchar * )malloc(sizeof(uchar)*(uchar_image_block.end()-uchar_image_block.begin()));
for(int i = 0; i<image.cols*image.rows;i++)
{
img[i]=(uchar)image.ptr()[i];
}
uchar_image_block.upload(img);
convolve1_block.upload(img);
convolve2_block.upload(img);
thrust::window_vector<uchar> input_wv(&uchar_image_block,3,3,1,1);
thrust::window_vector<uchar> output_wv_x(&convolve1_block,3,3,1,1);
thrust::window_vector<uchar> output_wv_y(&convolve2_block,3,3,1,1);
double start, end;
start = omp_get_wtime();
for(int i = 0; i< ITER;i++)
{
thrust::transform(input_wv.begin(),input_wv.end(),output_wv_x.begin(),zero_image_block.begin(),convolutionFunctor(dkernelx.device_pointer,3));
thrust::transform(input_wv.begin(),input_wv.end(),output_wv_y.begin(),zero_image_block.begin(),convolutionFunctor(dkernely.device_pointer,3));
thrust::transform(convolve1_block.begin(),convolve1_block.end(),convolve2_block.begin(),outBlock.begin(),transFunctor());
}
end = omp_get_wtime();
unsigned char * outputFloatImageData = (unsigned char *)malloc(sizeof(unsigned char)*(uchar_image_block.end()-uchar_image_block.begin()));
outBlock.download(&img);
printf("%f\n",(end-start)/ITER);
for(int i = 0; i<image.cols*image.rows;i++)
{
outputFloatImageData[i]=(unsigned char)img[i];
}
Mat output (Size(image.cols,image.rows),CV_8UC1,outputFloatImageData);
#ifdef OWRITE
imwrite("input.png",image);
imwrite("output.png",output);
#endif
#ifdef SHOW
imshow("input.png",image);
imshow("output.png",output);
waitKey(0);
#endif
return 0;
}
| true |
50606909457929d8d8f77b58a187ea6d4136b86e | C++ | JumpeiTerashita/PunyoPunyo | /PunyoPunyo/Program/Liblary/BitController.cpp | UTF-8 | 392 | 3 | 3 | [] | no_license | #include "BitController.h"
void BitAddition(unsigned char* _lookat, const unsigned char _plus)
{
*_lookat |= _plus;
}
void BitTakeaway(unsigned char* _lookat, const unsigned char _negative)
{
unsigned int mask = ~_negative;
*_lookat &= mask;
}
bool BitChecker(const unsigned char _lookat, const unsigned char _check)
{
if ((_lookat&_check) == _check) return true;
else return false;
} | true |
23a37a9f11cb316a2d85ae0f4674a0b01004e725 | C++ | moevm/oop | /8304/Butko_Artem/lab6/SOURCE/Game/Objects/Object.cpp | UTF-8 | 635 | 2.859375 | 3 | [] | no_license | //
// Created by Artem Butko on 08/05/2020.
//
#include "Object.h"
void Object::death()
{
this->notice();
}
void Object::getInformation()
{
std::cout << "------- OBJECT INFO ---------" << std::endl;
std::cout << "Name of object : " << this->id << std::endl;
std::cout << "Health : " << this->health.get() << std::endl;
std::cout << "Mana : " << this->mana.get() << std::endl;
std::cout << "Damage : " << this->damage.getDamage() << std::endl;
std::cout << "Damage radius : " << this->damage.getRange() << std::endl;
std::cout << "_____________________________" << std::endl;
}
| true |
924d97f78e84f6c6bcea195f79c36d3305e45141 | C++ | Rhoban/gp | /include/rhoban_gp/core/gaussian_process.h | UTF-8 | 5,521 | 2.671875 | 3 | [] | no_license | #pragma once
#include "rhoban_gp/core/covariance_function.h"
#include "rhoban_gp/gradient_ascent/randomized_rprop.h"
#include <Eigen/Core>
#include <functional>
#include <memory>
#include <random>
namespace rhoban_gp
{
class GaussianProcess
{
public:
GaussianProcess();
GaussianProcess(const Eigen::MatrixXd& inputs, const Eigen::VectorXd& observations,
std::unique_ptr<CovarianceFunction> covar_func);
// Enabling copy of GaussianProcess
GaussianProcess(const GaussianProcess& other);
// Allowing left affectation
GaussianProcess& operator=(const GaussianProcess& other);
/// Set the parameters for measurement noise and covariance function
/// Order is as follows: [measurement_noise, covar_parameters]
void setParameters(const Eigen::VectorXd& parameters);
/// Return current values for the parameters
Eigen::VectorXd getParameters() const;
/// Return default guess for parameters
Eigen::VectorXd getParametersGuess() const;
/// Return initial step for rProp
Eigen::VectorXd getParametersStep() const;
/// Return the limits for the parameters
Eigen::MatrixXd getParametersLimits() const;
/// Since modifying the CovarianceFunction requires to set the flags to dirty,
/// access is const only.
const CovarianceFunction& getCovarFunc() const;
/// Update the covariance function
void setCovarFunc(std::unique_ptr<CovarianceFunction> f);
/// Update the measurement noise
void setMeasurementNoise(double noise_stddev);
/// Return a prediction of the value at the given point
double getPrediction(const Eigen::VectorXd& point);
/// Throw an error if some parameters are dirty
double getPrediction(const Eigen::VectorXd& point) const;
/// Return an estimation of the variance at the given point
double getVariance(const Eigen::VectorXd& point);
/// Throw an error if some parameters are dirty
double getVariance(const Eigen::VectorXd& point) const;
/// Return the predicted gradient at the given point
Eigen::VectorXd getGradient(const Eigen::VectorXd& point);
/// Throw an error if some parameters are dirty
Eigen::VectorXd getGradient(const Eigen::VectorXd& point) const;
/// Compute the parameters of the distribution at the given point and
/// update the 'mean' and 'var' values accordingly
void getDistribParameters(const Eigen::VectorXd& point, double& mean, double& var);
/// Throw an error if some parameters are dirty
void getDistribParameters(const Eigen::VectorXd& point, double& mean, double& var) const;
/// Compute the parameters of the multivariate distribution for the given points
void getDistribParameters(const Eigen::MatrixXd& points, Eigen::VectorXd& mu, Eigen::MatrixXd& sigma);
/// Generate the outputs of a random function using the requested inputs
/// While in the requested Inputs, each column is a different input,
/// In the result, each row is a different output
/// If add measurement noise is chosen, then an independent measurement noise
/// with the provided standard deviation is applied on each measurement
Eigen::VectorXd generateValues(const Eigen::MatrixXd& requested_inputs, std::default_random_engine& engine,
bool add_measurement_noise = false);
/// Compute the log likelihood of the current distribution
/// i.e. p(observations|inputs,theta) with theta the parameters of the covariance function
double getLogMarginalLikelihood();
/// Return the partial derivatives of the marginal likelihood with respect to the
/// parameters of the covariance function
Eigen::VectorXd getMarginalLikelihoodGradient();
/// Solve all internal computations
void updateInternal();
/// Search the best parameters for fitting using randomized RProp with the
/// provided configuration
void autoTune(const RandomizedRProp::Config& conf);
/// Return the number of bytes written in the stream
int write(std::ostream& out) const;
/// Return the number of bytes read from the stream
int read(std::istream& in);
private:
/// Update the covariance matrix if required
void updateCov();
/// Update the inverse covariance matrix if required
void updateInverse();
/// Update the cholesky matrix if required
void updateCholesky();
/// Update the alpha matrix if required
void updateAlpha();
/// Signal that internal data have changed and that it is required to update internal data
void setDirty();
/// The covariance function used. By using unique_ptr, we make 'sure' that the function
/// cannot be modified from outside
std::unique_ptr<CovarianceFunction> covar_func;
/// The standard deviation of the measurements
double measurement_noise;
/// Known inputs of the gaussian process (row is dimension, col is sample no)
Eigen::MatrixXd inputs;
/// Measured outputs (row is sample no)
Eigen::VectorXd observations;
/// Covariance matrix of the inputs
Eigen::MatrixXd cov;
/// Inverse covariance matrix of the inputs
Eigen::MatrixXd inv_cov;
/// The L matrix of the cholesky decomposition of the covariance Matrix (LLT)
Eigen::MatrixXd cholesky;
/// The alpha matrix: alpha = L^T \ (L \ y)
Eigen::VectorXd alpha;
/// Is it necessary to update inverse of the covariance matrix
bool dirty_cov;
/// Is it necessary to update inverse of the covariance matrix
bool dirty_inv;
/// Is it necessary to update the cholesky matrix
bool dirty_cholesky;
/// Is it necessary to update the alpha matrix
bool dirty_alpha;
};
} // namespace rhoban_gp
| true |
66fb8ddbf737a4ed5d94f177776731e4ae1e4790 | C++ | lucamono/NavigationPlanner_Robocup-atWork | /spqr_splines_navigation/voronoi_action/include/topological_nav_utils/astar.h | UTF-8 | 678 | 2.71875 | 3 | [] | no_license | #ifndef ASTAR_H
#define ASTAR_H
#include <iostream>
#include <vector>
#include <list>
#include "graph.h"
using namespace std;
struct node {
graphNode g_node;
node* parent;
double f, g, h;
node(){};
node(graphNode& n){
g_node = n;
f=0;
g=0;
h=0;
}
};
class Astar {
private:
pGraph _graph;
list<node> _open_list;
vector<int> _closed_list;
vector<int> _path;
private:
vector<node> getSuccessors(node n);
double getDistance(node& p1, node& p2);
void addToOpenList(node n);
bool alreadyVisited(int id);
public:
Astar(pGraph graph_);
std::vector<int> compute(int start, int goal);
};
#endif
| true |
fb352e521acf9c2bb22c0f3ea35f348f02976662 | C++ | Lvnszn/flink_ai | /package/whl_dependencies/proxima-tianchi-master-668a0a87cb2a4aa1c68443b1ab05ee5a80008cb4/plugin/deps/aitheta2/index_container.h | UTF-8 | 2,500 | 2.703125 | 3 | [] | no_license | /**
* Copyright (C) The Software Authors. All rights reserved.
* \file index_container.h
* \author Alibaba-tianchi
* \date July 2020
* \version 2.0.0
* \brief Interface of AiTheta Index Container
*/
#ifndef __AITHETA2_INDEX_CONTAINER_H__
#define __AITHETA2_INDEX_CONTAINER_H__
#include "index_module.h"
namespace aitheta2 {
/*! Index Container
*/
class IndexContainer : public IndexModule
{
public:
//! Index Container Pointer
typedef std::shared_ptr<IndexContainer> Pointer;
/*! Index Container Segment Data
*/
struct SegmentData
{
//! Constructor
SegmentData(void) : offset(0u), length(0u), data(nullptr) {}
//! Constructor
SegmentData(size_t off, size_t len)
: offset(off), length(len), data(nullptr)
{
}
//! Members
size_t offset;
size_t length;
const void *data;
};
/*! Index Container Segment
*/
struct Segment
{
//! Index Container Pointer
typedef std::shared_ptr<Segment> Pointer;
//! Destructor
virtual ~Segment(void) {}
//! Retrieve size of data
virtual size_t data_size(void) const = 0;
//! Retrieve crc of data
virtual uint32_t data_crc(void) const = 0;
//! Retrieve size of padding
virtual size_t padding_size(void) const = 0;
//! Read data from segment
virtual size_t read(size_t offset, const void **data, size_t len) = 0;
//! Read data from segment
virtual bool read(SegmentData *iovec, size_t count) = 0;
//! Clone the segment
virtual Pointer clone(void) = 0;
};
//! Destructor
virtual ~IndexContainer(void) {}
//! Initialize container
virtual int init(const IndexParams ¶ms) = 0;
//! Cleanup container
virtual int cleanup(void) = 0;
//! Load a index file into container
virtual int load(const std::string &path) = 0;
//! Unload all indexes
virtual int unload(void) = 0;
//! Retrieve a segment by id
virtual Segment::Pointer get(const std::string &id) const = 0;
//! Retrieve all segments
virtual std::map<std::string, Segment::Pointer> get_all(void) const = 0;
//! Retrieve Index Meta
virtual const IndexMeta &meta(void) const = 0;
//! Retrieve magic number of index
virtual uint32_t magic(void) const = 0;
};
} // namespace aitheta2
#endif // __AITHETA2_INDEX_CONTAINER_H__
| true |
95a22a5a5d9957bcdcd7e81bc4a5e86a28ff5e63 | C++ | billpugh/Pyramid-of-Possibilities | /Arduino/Pachinko/StripLighting.cpp | UTF-8 | 1,439 | 2.921875 | 3 | [] | no_license | //
// StripLighting.cpp
//
// Created by Bill on 5/19/15.
//
//
#include "StripLighting.h"
#include "PachinkoMain.h"
#include <stdlib.h>
StripLighting::StripLighting(OctoWS2811 & lights, int firstPixel, int numPixels) : lights(lights), firstPixel(firstPixel), numPixels(numPixels) {};
bool changeColors() {
if (currentAmbientMode == AmbientPattern)
return true;
return (random() & 0x3) == 0;
}
void StripLighting::setColor(int rgb) {
for (int i = 0; i < numPixels; i++) {
lights.setPixel(firstPixel + i, rgb);
}
}
void StripLighting::fill() {
if (currentAmbientMode == AmbientPattern && currentAmbientPatternChoice == AmbientComets) {
for (int i = 0; i < numPixels; i++)
lights.setPixel(firstPixel + i, 0);
return;
}
int rgb = randomColor(0);
for (int i = 0; i < numPixels; i++) {
lights.setPixel(firstPixel + i, rgb);
if (changeColors())
rgb = randomColor(i+1);
}
}
void StripLighting::update() {
if (currentAmbientMode == AmbientPattern && currentAmbientPatternChoice == AmbientSparkles) {
for (int i = 0; i < numPixels - 1; i++)
lights.setPixel(firstPixel + i, randomColor(i));
return;
}
for (int i = 0; i < numPixels - 1; i++)
lights.setPixel(firstPixel + i, lights.getPixel(firstPixel + i + 1));
if (changeColors())
lights.setPixel(firstPixel + numPixels - 1, randomColor(numPixels - 1));
}
| true |
6c4fe4ec79fa34da1bbf4e191a40cd1176b243b3 | C++ | stephenmathieson/sophia.cc | /test.cc | UTF-8 | 8,541 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
#include "sophia-cc.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
using namespace sophia;
#define SUITE(title) \
printf("\n \e[36m%s\e[0m\n", title)
#define TEST(suite, name) \
static void Test##suite##name(void)
#define RUN_TEST(suite, test) \
Test##suite##test(); \
printf(" \e[92m✓ \e[90m"#suite "::" #test "\e[0m\n");
#define SOPHIA_ASSERT(rc) \
if (SOPHIA_SUCCESS != rc) { \
fprintf( \
stderr \
, "Error: %s (%d / %s at line %d)\n" \
, sp->Error(rc) \
, rc \
, __PRETTY_FUNCTION__ \
, __LINE__ \
); \
exit(1); \
}
/**
* Sophia tests.
*/
TEST(Sophia, Set) {
Sophia *sp = new Sophia("testdb");
// shouldn't segfault
assert(SOPHIA_DATABASE_NOT_OPEN_ERROR == sp->Set("foo", "bar"));
SOPHIA_ASSERT(sp->Open());
for (int i = 0; i < 100; i++) {
char key[100];
char value[100];
sprintf(key, "key%03d", i);
sprintf(value, "value%03d", i);
SOPHIA_ASSERT(sp->Set(key, value));
}
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Sophia, Get) {
Sophia *sp = new Sophia("testdb");
// shouldn't segfault
assert(!sp->Get("foo"));
SOPHIA_ASSERT(sp->Open());
for (int i = 0; i < 100; i++) {
char key[100];
char value[100];
sprintf(key, "key%03d", i);
sprintf(value, "value%03d", i);
char *_actual = sp->Get(key);
assert(0 == strcmp(value, _actual));
free(_actual);
}
assert(NULL == sp->Get("asdf"));
assert(NULL == sp->Get("lkjh"));
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Sophia, Delete) {
Sophia *sp = new Sophia("testdb");
// shouldn't segfault
assert(SOPHIA_DATABASE_NOT_OPEN_ERROR == sp->Delete("foo"));
SOPHIA_ASSERT(sp->Open());
for (int i = 0; i < 100; i += 2) {
char key[100];
sprintf(key, "key%03d", i);
SOPHIA_ASSERT(sp->Delete(key));
assert(NULL == sp->Get(key));
}
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Sophia, Error) {
Sophia *sp = new Sophia("/1/2/3");
assert(0 == strcmp(
"Unknown environment error"
, sp->Error(SOPHIA_ENV_ERROR)
));
assert(0 == strcmp(
"Unknown database error"
, sp->Error(SOPHIA_DB_ERROR)
));
delete sp;
}
TEST(Sophia, IsOpen) {
Sophia *sp = new Sophia("testdb");
SOPHIA_ASSERT(sp->Open());
assert(true == sp->IsOpen());
SOPHIA_ASSERT(sp->Close());
assert(false == sp->IsOpen());
delete sp;
}
TEST(Sophia, Clear) {
Sophia *sp = new Sophia("testdb");
// shouldn't segfault
assert(SOPHIA_DATABASE_NOT_OPEN_ERROR == sp->Clear());
SOPHIA_ASSERT(sp->Open());
SOPHIA_ASSERT(sp->Clear());
for (int i = 0; i < 100; i++) {
char key[100];
sprintf(key, "key%03d", i);
assert(NULL == sp->Get(key));
}
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Sophia, Count) {
Sophia *sp = new Sophia("testdb");
size_t count;
// shouldn't segfault
assert(SOPHIA_DATABASE_NOT_OPEN_ERROR == sp->Count(&count));
SOPHIA_ASSERT(sp->Open());
for (int i = 0; i < 5000; i++) {
char key[100];
char value[100];
sprintf(key, "key%05d", i);
sprintf(value, "value%05d", i);
SOPHIA_ASSERT(sp->Set(key, value));
}
SOPHIA_ASSERT(sp->Count(&count));
assert(5000 == count);
SOPHIA_ASSERT(sp->Close());
delete sp;
}
/**
* Iterator tests.
*/
TEST(Iterator, Begin) {
Sophia *sp = new Sophia("testdb");
Iterator *it = NULL;
IteratorResult *res = NULL;
it = new Iterator(sp);
assert(SOPHIA_DATABASE_NOT_OPEN_ERROR == it->Begin());
delete it;
SOPHIA_ASSERT(sp->Open());
// test reverse
it = new Iterator(sp, SPLT);
SOPHIA_ASSERT(it->Begin());
res = it->Next();
assert(0 == strcmp("key04999", res->key));
assert(0 == strcmp("value04999", res->value));
delete res;
SOPHIA_ASSERT(it->End());
delete it;
// test start
it = new Iterator(sp, SPGT, "key03999");
SOPHIA_ASSERT(it->Begin());
res = it->Next();
assert(0 == strcmp("key04000", res->key));
assert(0 == strcmp("value04000", res->value));
delete res;
SOPHIA_ASSERT(it->End());
delete it;
// test start/end
it = new Iterator(sp, SPGT, "key03999", "key04001");
SOPHIA_ASSERT(it->Begin());
res = it->Next();
assert(0 == strcmp("key04000", res->key));
assert(0 == strcmp("value04000", res->value));
delete res;
assert(NULL == it->Next());
SOPHIA_ASSERT(it->End());
delete it;
// test end
it = new Iterator(sp, SPGT, NULL, "key00002");
SOPHIA_ASSERT(it->Begin());
res = it->Next();
assert(0 == strcmp("key00000", res->key));
assert(0 == strcmp("value00000", res->value));
delete res;
res = it->Next();
assert(0 == strcmp("key00001", res->key));
assert(0 == strcmp("value00001", res->value));
delete res;
assert(NULL == it->Next());
SOPHIA_ASSERT(it->End());
delete it;
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Iterator, Next) {
Sophia *sp = new Sophia("testdb");
Iterator *it = NULL;
Iterator *it2 = NULL;
IteratorResult *res = NULL;
int i = 0;
SOPHIA_ASSERT(sp->Open());
it = new Iterator(sp, SPGT, "key00100", "key00500");
assert(0 == it->Begin());
i = 100;
while ((res = it->Next())) {
i++;
char key[100];
char value[100];
sprintf(key, "key%05d", i);
sprintf(value, "value%05d", i);
assert(0 == strcmp(key, res->key));
assert(0 == strcmp(value, res->value));
delete res;
}
assert(499 == i);
SOPHIA_ASSERT(it->End());
delete it;
// multiple iterators
it = new Iterator(sp, SPGT, "key00000", "key00100");
it2 = new Iterator(sp, SPLT, "key00100", "key00000");
SOPHIA_ASSERT(it->Begin());
SOPHIA_ASSERT(it2->Begin());
res = it->Next();
assert(0 == strcmp("key00001", res->key));
assert(0 == strcmp("value00001", res->value));
delete res;
res = it2->Next();
assert(0 == strcmp("key00099", res->key));
assert(0 == strcmp("value00099", res->value));
delete res;
SOPHIA_ASSERT(it->End());
SOPHIA_ASSERT(it2->End());
SOPHIA_ASSERT(sp->Close());
delete sp;
}
/**
* Transaction tests.
*/
TEST(Transaction, Begin) {
Sophia *sp = new Sophia("testdb");
Transaction *t = new Transaction(sp);
assert(SOPHIA_DATABASE_NOT_OPEN_ERROR == t->Begin());
SOPHIA_ASSERT(sp->Open());
SOPHIA_ASSERT(sp->Clear());
SOPHIA_ASSERT(t->Begin());
SOPHIA_ASSERT(t->Rollback());
delete t;
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Transaction, Set) {
Sophia *sp = new Sophia("testdb");
Transaction *t = new Transaction(sp);
SOPHIA_ASSERT(sp->Open());
SOPHIA_ASSERT(t->Begin());
for (int i = 0; i < 5000; i++) {
char key[100];
char value[100];
sprintf(key, "key%05d", i);
sprintf(value, "value%05d", i);
SOPHIA_ASSERT(t->Set(key, value));
}
SOPHIA_ASSERT(t->Commit());
delete t;
size_t count;
SOPHIA_ASSERT(sp->Count(&count));
assert(5000 == count);
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Transaction, Delete) {
Sophia *sp = new Sophia("testdb");
Transaction *t = new Transaction(sp);
SOPHIA_ASSERT(sp->Open());
SOPHIA_ASSERT(t->Begin());
for (int i = 0; i < 5000; i += 2) {
char key[100];
sprintf(key, "key%05d", i);
SOPHIA_ASSERT(t->Delete(key));
}
SOPHIA_ASSERT(t->Commit());
delete t;
size_t count;
SOPHIA_ASSERT(sp->Count(&count));
assert(2500 == count);
SOPHIA_ASSERT(sp->Close());
delete sp;
}
TEST(Transaction, Commit) {
Sophia *sp = new Sophia("testdb");
Transaction *t = new Transaction(sp);
SOPHIA_ASSERT(sp->Open());
SOPHIA_ASSERT(sp->Clear());
SOPHIA_ASSERT(t->Begin());
size_t sets = 0;
size_t dels = 0;
for (int i = 0; i < 10000; i++) {
char key[100];
char value[100];
sprintf(key, "key%05d", i);
sprintf(value, "value%05d", i);
int n = (rand() % 3) + 1;
if (2 == n) {
SOPHIA_ASSERT(t->Delete(key));
dels++;
} else {
SOPHIA_ASSERT(t->Set(key, value));
sets++;
}
}
SOPHIA_ASSERT(t->Commit());
size_t count;
SOPHIA_ASSERT(sp->Count(&count));
assert(sets == count);
SOPHIA_ASSERT(sp->Close());
delete sp;
}
int
main(void) {
srand(time(0));
SUITE("Sophia");
RUN_TEST(Sophia, Set);
RUN_TEST(Sophia, Get);
RUN_TEST(Sophia, Delete);
RUN_TEST(Sophia, Error);
RUN_TEST(Sophia, IsOpen);
RUN_TEST(Sophia, Clear);
RUN_TEST(Sophia, Count);
SUITE("Iterator");
RUN_TEST(Iterator, Begin);
RUN_TEST(Iterator, Next);
SUITE("Transaction");
RUN_TEST(Transaction, Begin);
RUN_TEST(Transaction, Set);
RUN_TEST(Transaction, Delete);
RUN_TEST(Transaction, Commit);
printf("\n");
}
| true |
168407f523197ebc15df172f304fcd435291938e | C++ | maurosch/Competitive-Programming | /CODEFORCES/Round #493/C/main.cpp | UTF-8 | 928 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
#define forn(i,n) for(int i = 0; i < int(n); i++)
#define forsn(i,s,n) for(int i = int(s); i < int(n); i++)
#define rforn(i,n) for(int i = int(n)-1; i >= 0; i--)
int main()
{
int n;
long long reverse, change;
cin >> n >> reverse >> change;
char anterior;
int cantCeros = 0;
string auxString;
cin >> auxString;
if(auxString[0] == '0') cantCeros++;
anterior = auxString[0];
forsn(i, 1, n)
{
if(auxString[i] != anterior)
{
anterior = auxString[i];
if(auxString[i] == '0') cantCeros++;
}
}
if(cantCeros == 0)
{
cout << 0 << endl;
return 0;
}
if(reverse < change)
{
cout << ((long long)cantCeros-1) * reverse + change << endl;
}
else
{
cout << (long long)cantCeros *change << endl;
}
return 0;
} | true |
ff7a87c34e746dd1d16b2d3027710169cff608da | C++ | pyomeca/biorbd | /include/Utils/Scalar.h | UTF-8 | 910 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef BIORBD_UTILS_SCALAR_H
#define BIORBD_UTILS_SCALAR_H
#include "biorbdConfig.h"
#include "rbdl/rbdl_math.h"
namespace BIORBD_NAMESPACE
{
namespace utils
{
#ifdef BIORBD_USE_CASADI_MATH
///
/// \brief Wrapper of scalar
///
#ifdef SWIG
class Scalar
{
#else
class Scalar : public RigidBodyDynamics::Math::Scalar
{
#endif
public:
///
/// \brief Constructor for a casadi::MX scalar
///
Scalar();
///
/// \brief Constructor for a casadi::MX scalar
/// \param val The value to copy
///
Scalar(
double val);
///
/// \brief Constructor for a casadi::MX scalar
/// \param val The value to copy. A test is performed to ensure val is 1x1
///
Scalar(
const casadi::MX& val);
};
#else
#ifdef SWIG
typedef double Scalar;
#else
typedef RigidBodyDynamics::Math::Scalar Scalar;
#endif
#endif
}
}
#endif // BIORBD_UTILS_SCALAR_H
| true |
3849f896a2ecdf64e82fa61230ba75216292b6b3 | C++ | ethz-asl/kalibr | /Schweizer-Messer/sm_common/include/sm/round.hpp | UTF-8 | 786 | 3.015625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef SM_ROUND_HPP
#define SM_ROUND_HPP
namespace sm {
inline double round (double number)
{
return (number < 0.0 ? ceil (number - 0.5) : floor (number + 0.5));
}
inline float round (float number)
{
return (number < 0.0f ? ceilf (number - 0.5f) : floorf (number + 0.5f));
}
inline int rint(double number)
{
return static_cast<int>( round(number) );
}
inline int rint(float number)
{
return static_cast<long int>( round(number) );
}
inline long int lrint(double number)
{
return static_cast<int>( round(number) );
}
inline long int lrint(float number)
{
return static_cast<long int>( round(number) );
}
} // namespace sm
#endif /* SM_ROUND_HPP */
| true |
a057f5dd4ed917cbb9ad0c58f8a862ace10d9bfe | C++ | bryanbl/Proyecto_Aviones | /Jugador.cpp | UTF-8 | 1,243 | 2.8125 | 3 | [] | no_license | #include "Jugador.h"
#include <QKeyEvent>
#include "Balas.h"
#include "Enemigo.h"
#include <QGraphicsScene>
Jugador::Jugador(QGraphicsItem *causa): QGraphicsRectItem(causa){
}
//Configuracion del movimiento
void Jugador::keyPressEvent(QKeyEvent *event)
{
//cada vez que presiono una tecla el programa lo reconoce
//qDebug() << "MiRecta conoce la tecla presionada";
//Mueve a la izquierda con el boton de la flecha a la izquierda
if(event->key()==Qt::Key_Left){
if(pos().x()>0)
setPos(x()-10,y());
}
//Mueve a la derecha con el boton de la flecha a la derecha
else if(event->key()==Qt::Key_Right){
if(pos().x()<800-rect().width())
setPos(x()+10,y());
}
/*else if(event->key()==Qt::Key_Up){
setPos(x(),y()-10);
}
else if(event->key()==Qt::Key_Down){
setPos(x(),y()+10);
}*/
else if(event->key() == Qt::Key_Space){
//Aqui estan las balas
Balas * balas = new Balas();
balas->setPos(x(),y());
//qDebug() << "Bala creada";
scene() -> addItem(balas);
}
}
void Jugador::creo_Enenemigo(){
//Creo mi enemigo
Enemigo *enemigo = new Enemigo();
scene() ->addItem(enemigo);
return;
}
| true |
397aac2ff3168f71db38f9015df520c5ec367797 | C++ | alexhein189/code-plagiarism-detector | /data/open-Yellow/sources/000829-open-2015-322-Yellow.cpp | UTF-8 | 1,182 | 2.5625 | 3 | [] | no_license | #include <fstream>
#include <vector>
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
//ifstream in("input.txt");
//ofstream out("output.txt");
int n, m;
cin >> n;
int a[n + 2];
int ans = 0;
a[0] = -1;
a[n + 1] = -2;
for (int i = 1; i <= n; i++){
cin >> a[i];
if (a[i] != a[i - 1])
ans++;
}
cin >> m;
int p, c;
for (int i = 0; i < m; i++){
cin >> p >> c;
if (c == a[p]){
cout << ans << endl;
continue;
}
if (c == a[p - 1] && c == a[p + 1])
ans -= 2;
else
if ((c == a[p - 1] || c == a[p + 1]) && !(a[p] == a[p - 1] || a[p] == a[p + 1]))
ans -= 1;
else
if (a[p] == a[p - 1] && a[p] == a[p + 1])
ans += 2;
else
if ((a[p] == a[p - 1] || a[p] == a[p + 1]) && !(c == a[p - 1] || c == a[p + 1]))
ans += 1;
cout << ans << endl;
a[p] = c;
}
return 0;
}
| true |
a02b392e11b530ac2b3be9457c758b65823ae07b | C++ | Alek96/TKOM-Interpreter | /tests/unitTest/ast/statement/WhileStatement_test.cpp | UTF-8 | 8,685 | 3.015625 | 3 | [] | no_license | #include <catch.hpp>
#include "modules/ast/statement/WhileStatement.hpp"
#include <memory>
#include "ast/Variable.hpp"
#include "ast/expression/BaseMathExpr.hpp"
#include "ast/Return.hpp"
#include "ast/statement/BlockStatement.hpp"
#include "ast/statement/AssignStatement.hpp"
#include "ast/statement/IfStatement.hpp"
#include "ast/statement/ReturnStatement.hpp"
#include "ast/expression/MathExpr.hpp"
#include "ast/expression/RelationalExpr.hpp"
#include "exception/Exception.hpp"
using namespace tkom::ast;
SCENARIO("Test for WhileStatement", "[ast][statement][WhileStatement]") {
GIVEN("WhileStatement object") {
/*
* while(exprVar < newExprVar) {
* exprVar = exprVar + 1;
* }
* */
Variable exprVar({1});
Variable oldExprVar(exprVar);
Variable newExprVar({10});
// expr < 10
auto whileExpr = std::make_unique<RelationalExpr>(std::make_unique<BaseMathExpr>(exprVar));
whileExpr->addLess(std::make_unique<BaseMathExpr>(newExprVar));
// {...}
auto whileBlock = std::make_unique<BlockStatement>();
// exprVar = exprVar + 1
auto addExpr = std::make_unique<MathExpr>(std::make_unique<BaseMathExpr>(exprVar));
addExpr->addPlus(std::make_unique<BaseMathExpr>(new Variable({1})));
whileBlock->addInstruction(std::make_unique<AssignStatement>(exprVar, std::move(addExpr)));
WhileStatement whileStatement(std::move(whileExpr), std::move(whileBlock));
WHEN("Method run is coled") {
Return ret;
REQUIRE_NOTHROW(ret = whileStatement.run());
THEN("exprVar is equal to newExprVar") {
REQUIRE(ret.type == Return::_none);
REQUIRE_FALSE(exprVar == oldExprVar);
REQUIRE(exprVar == newExprVar);
}
}
}
GIVEN("WhileStatement object 2") {
/*
* while(trueExprVar) {
* exprVar = exprVar + 1;
* if( exprVar == newExprVar )
* break;
* }
* */
Variable trueExprVar({1});
Variable exprVar({1});
Variable newExprVar({10});
// trueExprVar
auto whileExpr = std::make_unique<BaseMathExpr>(trueExprVar);
// {...}
auto whileBlock = std::make_unique<BlockStatement>();
// exprVar = exprVar + 1
auto addExpr = std::make_unique<MathExpr>(std::make_unique<BaseMathExpr>(exprVar));
addExpr->addPlus(std::make_unique<BaseMathExpr>(new Variable({1})));
whileBlock->addInstruction(std::make_unique<AssignStatement>(exprVar, std::move(addExpr)));
// if: exprVar == newExprVar
auto ifExpr = std::make_unique<RelationalExpr>(std::make_unique<BaseMathExpr>(exprVar));
ifExpr->addEquality(std::make_unique<BaseMathExpr>(newExprVar));
// if: { break; }
auto ifBlock = std::make_unique<BlockStatement>();
ifBlock->addInstruction(std::make_unique<ReturnStatement>(Return::_break));
// if
whileBlock->addInstruction(std::make_unique<IfStatement>(std::move(ifExpr), std::move(ifBlock)));
WhileStatement whileStatement(std::move(whileExpr), std::move(whileBlock));
WHEN("Method run is coled") {
Return ret;
REQUIRE_NOTHROW(ret = whileStatement.run());
THEN("exprVar is equal to newExprVar") {
REQUIRE(ret.type == Return::_none);
REQUIRE(exprVar == newExprVar);
}
}
}
GIVEN("WhileStatement object 3") {
/*
* while(trueExprVar) {
* exprVar = exprVar + 1;
* if( exprVar == newExprVar )
* return retVar;
* }
* */
Variable trueExprVar({1});
Variable exprVar({1});
Variable newExprVar({10});
Variable retVar({20});
// trueExprVar
auto whileExpr = std::make_unique<BaseMathExpr>(trueExprVar);
// {...}
auto whileBlock = std::make_unique<BlockStatement>();
// exprVar = exprVar + 1
auto addExpr = std::make_unique<MathExpr>(std::make_unique<BaseMathExpr>(exprVar));
addExpr->addPlus(std::make_unique<BaseMathExpr>(new Variable({1})));
whileBlock->addInstruction(std::make_unique<AssignStatement>(exprVar, std::move(addExpr)));
// if: exprVar == newExprVar
auto ifExpr = std::make_unique<RelationalExpr>(std::make_unique<BaseMathExpr>(exprVar));
ifExpr->addEquality(std::make_unique<BaseMathExpr>(newExprVar));
// if: { return retVar; }
auto ifBlock = std::make_unique<BlockStatement>();
ifBlock->addInstruction(std::make_unique<ReturnStatement>(std::make_unique<BaseMathExpr>(retVar)));
// if
whileBlock->addInstruction(std::make_unique<IfStatement>(std::move(ifExpr), std::move(ifBlock)));
WhileStatement whileStatement(std::move(whileExpr), std::move(whileBlock));
WHEN("Method run is coled") {
Return ret;
REQUIRE_NOTHROW(ret = whileStatement.run());
THEN("exprVar is equal to newExprVar") {
REQUIRE(ret.type == Return::_variable);
REQUIRE(ret.variable == retVar);
REQUIRE(exprVar == newExprVar);
}
}
}
GIVEN("WhileStatement object 4") {
/*
* while(trueExprVar) {
* exprVar = exprVar + 1;
* if( exprVar == newExprVar )
* continue;
*
* exprVar2 = exprVar2 + 1;
* if( exprVar == newNewExprVar )
* break;
* }
* */
Variable trueExprVar({1});
Variable exprVar({1});
Variable newExprVar({10});
Variable newNewExprVar({20});
Variable exprVar2(exprVar);
// trueExprVar
auto whileExpr = std::make_unique<BaseMathExpr>(trueExprVar);
// {...}
auto whileBlock = std::make_unique<BlockStatement>();
// exprVar = exprVar + 1
auto addExpr = std::make_unique<MathExpr>(std::make_unique<BaseMathExpr>(exprVar));
addExpr->addPlus(std::make_unique<BaseMathExpr>(new Variable({1})));
whileBlock->addInstruction(std::make_unique<AssignStatement>(exprVar, std::move(addExpr)));
// if: exprVar == newExprVar
auto ifExpr = std::make_unique<RelationalExpr>(std::make_unique<BaseMathExpr>(exprVar));
ifExpr->addEquality(std::make_unique<BaseMathExpr>(newExprVar));
// if: { continue; }
auto ifBlock = std::make_unique<BlockStatement>();
ifBlock->addInstruction(std::make_unique<ReturnStatement>(Return::_continue));
// if
whileBlock->addInstruction(std::make_unique<IfStatement>(std::move(ifExpr), std::move(ifBlock)));
// exprVar2 = exprVar2 + 1
auto addExpr2 = std::make_unique<MathExpr>(std::make_unique<BaseMathExpr>(exprVar2));
addExpr2->addPlus(std::make_unique<BaseMathExpr>(new Variable({1})));
whileBlock->addInstruction(std::make_unique<AssignStatement>(exprVar2, std::move(addExpr2)));
// if: exprVar == newNewExprVar
auto ifExpr2 = std::make_unique<RelationalExpr>(std::make_unique<BaseMathExpr>(exprVar));
ifExpr2->addEquality(std::make_unique<BaseMathExpr>(newNewExprVar));
// if: { break; }
auto ifBlock2 = std::make_unique<BlockStatement>();
ifBlock2->addInstruction(std::make_unique<ReturnStatement>(Return::_break));
// if
whileBlock->addInstruction(std::make_unique<IfStatement>(std::move(ifExpr2), std::move(ifBlock2)));
WhileStatement whileStatement(std::move(whileExpr), std::move(whileBlock));
WHEN("Method run is coled") {
Return ret;
REQUIRE_NOTHROW(ret = whileStatement.run());
THEN("exprVar is equal to newExprVar") {
REQUIRE(ret.type == Return::_none);
REQUIRE(exprVar == newNewExprVar);
REQUIRE(exprVar2 == newNewExprVar - Variable({1}));
}
}
}
/*GIVEN("WhileStatement object 5 that throw exception ") {
*//*
* while(trueExprVar) {}
* *//*
Variable trueExprVar({1});
// trueExprVar
auto whileExpr = std::make_unique<BaseMathExpr>(trueExprVar);
// {...}
auto whileBlock = std::make_unique<BlockStatement>();
// while
WhileStatement whileStatement(std::move(whileExpr), std::move(whileBlock));
WHEN("Method run is coled") {
THEN("Exception appears") {
REQUIRE_THROWS(whileStatement.run());
}
}
}*/
}
| true |
7072e817d990eb40de65d58244f290e84e5d548d | C++ | DanielaSol/taller2015 | /src/Pantalla/Pantalla.cpp | UTF-8 | 5,034 | 2.65625 | 3 | [] | no_license | /*
* Pantalla.cpp
*
* Created on: 25/10/2015
* Author: daniela
*/
#include "Pantalla.h"
#include "../GameObject.h"
#include "../TextureManager.h"
#include <map>
#include <sstream>
#include <string>
#include "../Vector2D.h"
#include "SDL/SDL_ttf.h"
#include "../Game.h"
#include "stdlib.h"
using namespace std;
Pantalla::Pantalla(int width, int height) {
this->width = width;
this->height = height;
//defino los sectores
SDL_Rect sector;
sector.x=0;
sector.y=0;
sector.w = this->width;
sector.h = 30;
sectores.insert( pair<string,SDL_Rect> ("barra",sector) );
//mapa
sector.x=0;
sector.y=30;
sector.w = this->width;
sector.h = this->height - 30 -150;
sectores.insert( pair<string,SDL_Rect> ("mapa",sector) );
//barra_bajo
sector.x=0;
sector.y=this->height -150 ;
sector.w = 2*(this->width/3);
sector.h = this->height - 30 ;
sectores.insert( pair<string,SDL_Rect> ("barra_bajo",sector) );
//minimapa
sector.x=2*(this->width/3);
sector.y=this->height -150 ;
sector.w = 1*(this->width/3);
sector.h = this->height - 30 ;
sectores.insert( pair<string,SDL_Rect> ("minimapa",sector) );
}
Pantalla::~Pantalla() {
clean();
}
void Pantalla::draw(SDL_Renderer* m_pRenderer, Map* m_pMap ,vector<GameObject*> entidades) {
SDL_Rect sector;
//////////////////////////////////////////////////////////////////
sector = sectores.at("barra");
TheTextureManager::Instance()->drawArea("barra",sector,m_pRenderer);
SDL_Color textColor = { 255, 255, 255 };
map<string, int>myMap = TheGame::Instance()->m_pBarra->getMapRecursos();
int acum =0;
for (const auto& recurso : myMap) {
ostringstream convert; // stream used for the conversion
convert << (recurso.second);
string text = recurso.first+ ": " + convert.str();
sector.x=5+acum;
sector.y=5;
acum+= 100;
TheTextureManager::Instance()->drawText(text,textColor,sector,m_pRenderer);
}
//////////////////////////////////////////////////////////////////
sector = sectores.at("barra_bajo");
TheTextureManager::Instance()->drawArea("barra_bajo",sector,m_pRenderer);
textColor = { 0, 0, 0 };
for (uint i=0;i<entidades.size();i++){
if (entidades[i]->m_isClicked){
string text = "NOMBRE: " + entidades[i]->name;
sector.x = 20;
sector.y= 30;
TheTextureManager::Instance()->drawText(text,textColor,sector,m_pRenderer);
text = "DESCRIPCION: " + entidades[i]->descripcion;
sector.x = 20;
sector.y += 30;
TheTextureManager::Instance()->drawText(text,textColor,sector,m_pRenderer);
}
}
//////////////////////////////////////////////////////////////////
sector = sectores.at("minimapa");
//TheTextureManager::Instance()->drawArea("minimapa",sector,m_pRenderer);
SDL_RenderSetViewport( m_pRenderer, §or );
for(int i = 0 ; i < m_pMap->getMapSize().getX(); i++) {
for(int j = 0 ; j < m_pMap->getMapSize().getY() ; j++) {
if (m_pMap->getVisionMapValue(i,j) == 1 || m_pMap->getVisionMapValue(i,j) == 2) {
Vector2D* vector = new Vector2D(0,0);
vector->setX(i); vector->setY(j); vector->toIsometric();
int tileValue1 = TheGame::Instance()->m_pMap->getValue(i,j);
if (tileValue1 == 3 ) {
TheTextureManager::Instance()->drawFrame("puntoRojo",vector->getX()+95,vector->getY()-5,180,150,50,50,1,0,m_pRenderer);
}
else if (tileValue1 == 0){
TheTextureManager::Instance()->drawFrame("puntoAmarillo",vector->getX()+95,vector->getY()-5,180,150,50,50,1,0,m_pRenderer);
}
else
TheTextureManager::Instance()->drawFrame("puntoVerde",vector->getX()+100,vector->getY(),180,150,50,50,1,0,m_pRenderer);
delete vector;
}
}
}
//////////////////////////////////////////////////////////////////
sector = sectores.at("mapa");
SDL_RenderSetViewport( m_pRenderer, §or );
m_pMap->draw();
//primero dibuja entidades, luego el personaje (siempre aparece por arriba de las cosas
for (uint i=0;i<entidades.size();i++){
if (entidades[i]->m_isClicked){
entidades[i]->drawSelected();
}
//SDL_RenderSetViewport( m_pRenderer, §or );
if (entidades[i] && (entidades[i]->m_atSight || entidades[i]->m_wasSeen))
entidades[i]->draw();
}
SDL_RenderPresent(m_pRenderer);
//////////////////////////////////////////////////////////////////
}
void Pantalla::init(SDL_Renderer* m_pRenderer) {
TheTextureManager::Instance()->load("assets/wood.jpg","barra", m_pRenderer);
TheTextureManager::Instance()->load("assets/paper.png","barra_bajo", m_pRenderer);
TheTextureManager::Instance()->load("assets/papiro.png","minimapa", m_pRenderer);
TheTextureManager::Instance()->load("assets/puntoVerde.png","puntoVerde", m_pRenderer);
TheTextureManager::Instance()->load("assets/puntoRojo.png","puntoRojo", m_pRenderer);
TheTextureManager::Instance()->load("assets/puntoAmarillo.png","puntoAmarillo", m_pRenderer);
TheTextureManager::Instance()->load("assets/Tiles/GrassSelected.png","sueloSeleccionado", m_pRenderer);
}
void Pantalla::clean() {
sectores.clear();
}
| true |
942380e5c86cc6fba217afaf8f2d3d2c00b3bd7b | C++ | asteine8/CISC-192_MESA_SPRING_2020 | /Testing/IOTest/filter_file_test.cpp | UTF-8 | 166 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int input;
cin >> input;
cout << "Your Input: " << input;
cerr << "I don't like you";
return 0;
}
| true |
9574474fd7ae0699e3c024ac93f1aca8ce4b809a | C++ | AndreyLatyshev/HelixAndFriends | /Ellipse.h | UTF-8 | 512 | 2.796875 | 3 | [] | no_license | #ifndef ELLIPSE_H
#define ELLIPSE_H
#include "Point.h"
#include "Curve.h"
class Ellipse : public Curve
{
public:
Ellipse();
Ellipse (Point thePoint, double theMajRad, double theMinRad);
double GetMajRad() const;
double GetMinRad() const;
Point GetPoint (double theParameter) const;
Vector GetDerivative (double theParameter) const;
void SetMajRad(double theMajRad);
void SetMinRad(double theMinRad);
private:
double myMajRad;
double myMinRad;
};
#endif //!ELLIPSE_H
| true |
77859b30ae132655c37432ee6b7c6ba9c72795c9 | C++ | 1993LETICIA/LINGUAGEM-DE-PROGRAMA-O | /EX21.cpp | IBM852 | 335 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include<locale.h>
int main()
{
setlocale(LC_ALL, "Portuguese");
char *c;
int a = 1, b = 1,n, i;
printf("Digite o N-simo termo: ");
scanf("%d", &n);
printf("\n");
for(i=0;i<n;i++)
if(i % 2 == 0)
{
printf("%d ", a);
a += b;
}
else
{
printf("%d ", b);
b += a;
}
}
| true |
6774efd01aa6c1336a7188f34f0abc74ddd1dd96 | C++ | btbd/DOOM_Trainer | /memory.cpp | UTF-8 | 18,086 | 3 | 3 | [
"Apache-2.0"
] | permissive | #include "stdafx.h"
ARRAY ArrayNew(unsigned char element_size) {
ARRAY array;
array.element_size = element_size;
array.allocated = 0xFF;
array.buffer = malloc(element_size * 0xFF);
array.length = 0;
return array;
}
void *ArrayGet(ARRAY *array, DWORD index) {
return (void *)((SINT)array->buffer + (index * array->element_size));
}
void *ArraySet(ARRAY *array, DWORD index, void *element) {
return memcpy((void *)((SINT)array->buffer + (index * array->element_size)), element, array->element_size);
}
void *ArrayPush(ARRAY *array, void *element) {
if (array->length >= array->allocated) {
array->allocated *= 2;
array->buffer = realloc(array->buffer, array->allocated * array->element_size);
}
return memcpy((void *)((SINT)array->buffer + (array->length++ * array->element_size)), element, array->element_size);
}
void ArrayPop(ARRAY *array, void *out) {
if (out) {
memcpy(out, ArrayGet(array, --array->length), array->element_size);
} else {
--array->length;
}
}
void ArrayMerge(ARRAY *dest, ARRAY *array) {
dest->allocated += array->allocated;
dest->buffer = realloc(dest->buffer, dest->allocated * array->element_size);
memcpy((void *)((SINT)dest->buffer + (dest->length * dest->element_size)), array->buffer, array->length * dest->element_size);
dest->length += array->length;
}
void ArrayFree(ARRAY *array) {
if (array->buffer) {
free(array->buffer);
array->buffer = 0;
}
}
char *WCharToChar(char *dest, wchar_t *src) {
sprintf(dest, "%ws", src);
return dest;
}
wchar_t *CharToWChar(wchar_t *dest, char *src) {
int length = (int)strlen(src);
dest[MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src, length, dest, length)] = 0;
return dest;
}
PROCESSENTRY32 GetProcessInfoById(DWORD pid) {
PROCESSENTRY32 entry = { 0 };
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry)) {
do {
if (entry.th32ProcessID == pid) {
CloseHandle(snapshot);
return entry;
}
} while (Process32Next(snapshot, &entry));
}
CloseHandle(snapshot);
return{ 0 };
}
PROCESSENTRY32 GetProcessInfoByName(wchar_t *exe_name) {
PROCESSENTRY32 entry = { 0 };
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry)) {
do {
if (_wcsicmp(entry.szExeFile, exe_name) == 0) {
CloseHandle(snapshot);
return entry;
}
} while (Process32Next(snapshot, &entry));
}
CloseHandle(snapshot);
return{ 0 };
}
MODULEENTRY32 GetModuleInfoByName(int process_id, wchar_t *module_name) {
MODULEENTRY32 entry = { 0 };
entry.dwSize = sizeof(MODULEENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, process_id);
if (Module32First(snapshot, &entry)) {
do {
if (_wcsicmp(entry.szModule, module_name) == 0) {
CloseHandle(snapshot);
return entry;
}
} while (Module32Next(snapshot, &entry));
}
CloseHandle(snapshot);
return{ 0 };
}
THREADENTRY32 GetThreadInfoById(int thread_id) {
THREADENTRY32 entry = { 0 };
entry.dwSize = sizeof(THREADENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, NULL);
if (Thread32First(snapshot, &entry)) {
do {
if (entry.th32ThreadID == thread_id) {
CloseHandle(snapshot);
return entry;
}
} while (Thread32Next(snapshot, &entry));
}
CloseHandle(snapshot);
return{ 0 };
}
void SuspendProcess(int process_id) {
THREADENTRY32 entry = { 0 };
entry.dwSize = sizeof(THREADENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, NULL);
if (Thread32First(snapshot, &entry)) {
do {
if (entry.th32OwnerProcessID == process_id) {
HANDLE thread = OpenThread(THREAD_ALL_ACCESS, 0, entry.th32ThreadID);
SuspendThread(thread);
CloseHandle(thread);
}
} while (Thread32Next(snapshot, &entry));
}
CloseHandle(snapshot);
}
void ResumeProcess(int process_id) {
THREADENTRY32 entry = { 0 };
entry.dwSize = sizeof(THREADENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, NULL);
if (Thread32First(snapshot, &entry)) {
do {
if (entry.th32OwnerProcessID == process_id) {
HANDLE thread = OpenThread(THREAD_ALL_ACCESS, 0, entry.th32ThreadID);
ResumeThread(thread);
CloseHandle(thread);
}
} while (Thread32Next(snapshot, &entry));
}
CloseHandle(snapshot);
}
ULARGE_INTEGER GetThreadCreationTime(HANDLE thread) {
FILETIME filetime, idle;
GetThreadTimes(thread, &filetime, &idle, &idle, &idle);
ULARGE_INTEGER time;
time.LowPart = filetime.dwLowDateTime;
time.HighPart = filetime.dwHighDateTime;
return time;
}
int _thread_compare(const void *a, const void *b) {
HANDLE thread_a = *(HANDLE *)a;
HANDLE thread_b = *(HANDLE *)b;
long long diff = GetThreadCreationTime(thread_a).QuadPart - GetThreadCreationTime(thread_b).QuadPart;
return diff == 0 ? 0 : diff < 0 ? -1 : 1;
}
THREADENTRY32 GetThreadInfoByNumber(int process_id, int number) {
ARRAY threads = ArrayNew(sizeof(HANDLE));
THREADENTRY32 entry = { 0 };
entry.dwSize = sizeof(THREADENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, process_id);
if (Thread32First(snapshot, &entry)) {
do {
if (entry.th32OwnerProcessID == process_id) {
HANDLE thread = OpenThread(THREAD_ALL_ACCESS, 0, entry.th32ThreadID);
ArrayPush(&threads, &thread);
}
} while (Thread32Next(snapshot, &entry));
}
CloseHandle(snapshot);
qsort(threads.buffer, threads.length, threads.element_size, _thread_compare);
THREADENTRY32 thread_info = GetThreadInfoById(GetThreadId(*(HANDLE *)ArrayGet(&threads, number)));
for (DWORD i = 0; i < threads.length; i++) {
CloseHandle(*(HANDLE *)ArrayGet(&threads, i));
}
ArrayFree(&threads);
return thread_info;
}
void *GetThreadStackTop(int thread_id) {
HANDLE thread = OpenThread(THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, 0, thread_id);
HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, GetThreadInfoById(thread_id).th32OwnerProcessID);
if (process && thread) {
SuspendThread(thread);
BOOL x32;
IsWow64Process(process, &x32);
if (x32) {
CONTEXT32 context = { 0 };
context.ContextFlags = CONTEXT_SEGMENTS;
if (GetThreadContext32(thread, &context)) {
LDT_ENTRY32 entry = { 0 };
if (GetThreadSelectorEntry32(thread, context.SegFs, &entry)) {
DWORD stack = entry.BaseLow + (entry.HighWord.Bytes.BaseMid << 16) + (entry.HighWord.Bytes.BaseHi << 24);
ReadProcessMemory(process, (void *)(stack + sizeof(stack)), &stack, sizeof(stack), NULL);
ResumeThread(thread);
CloseHandle(thread);
CloseHandle(process);
return (void *)((SINT)stack - sizeof(stack));
}
}
} else {
THREAD_BASIC_INFORMATION tbi = { 0 };
if (!NtQueryInformationThread(thread, (THREADINFOCLASS)0, &tbi, sizeof(tbi), 0)) {
SINT stack = 0;
if (ReadProcessMemory(process, (void *)((SINT)tbi.TebBaseAddress + 8), &stack, sizeof(stack), 0)) {
ResumeThread(thread);
CloseHandle(thread);
CloseHandle(process);
return (void *)(stack - sizeof(stack));
}
}
}
ResumeThread(thread);
}
CloseHandle(thread);
CloseHandle(process);
return NULL;
}
void *GetThreadStack(int thread_id) {
SINT top = (SINT)GetThreadStackTop(thread_id);
if (!top) {
return NULL;
}
DWORD process_id = GetThreadInfoById(thread_id).th32OwnerProcessID;
MODULEENTRY32 kernel32 = GetModuleInfoByName(process_id, L"kernel32.dll");
if (!(SINT)kernel32.hModule) {
return NULL;
}
SINT min = (SINT)kernel32.modBaseAddr;
SINT max = min + kernel32.modBaseSize;
HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, process_id);
if (process) {
BOOL x32 = true;
IsWow64Process(process, &x32);
if (x32) {
DWORD stack = 0;
for (;; top -= sizeof(stack), stack = 0) {
if (!ReadProcessMemory(process, (void *)top, &stack, sizeof(stack), NULL)) {
break;
}
if (stack >= min && stack < max) {
CloseHandle(process);
return (void *)top;
}
}
} else {
SINT stack = 0;
for (;; top -= sizeof(stack), stack = 0) {
if (!ReadProcessMemory(process, (void *)top, &stack, sizeof(stack), NULL)) {
break;
}
if (stack >= min && stack < max) {
CloseHandle(process);
return (void *)top;
}
}
}
}
CloseHandle(process);
return NULL;
}
DWORD GetProcessThreadCount(int process_id) {
THREADENTRY32 entry = { 0 };
entry.dwSize = sizeof(THREADENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, NULL);
DWORD count = 0;
if (Thread32First(snapshot, &entry)) {
do {
if (entry.th32OwnerProcessID == process_id) {
++count;
}
} while (Thread32Next(snapshot, &entry));
}
CloseHandle(snapshot);
return count;
}
void *GetPointer(HANDLE process, unsigned int offset_count, ...) {
BOOL x32 = false;
IsWow64Process(process, &x32);
if (x32) {
va_list offsets;
va_start(offsets, offset_count);
DWORD base = 0;
for (unsigned int i = 0; i < offset_count - 1; i++) {
ReadProcessMemory(process, (void *)((SINT)(base + va_arg(offsets, DWORD))), &base, sizeof(base), NULL);
}
base += va_arg(offsets, DWORD);
va_end(offsets);
return (void *)((SINT)base);
} else {
va_list offsets;
va_start(offsets, offset_count);
SINT base = 0;
for (unsigned int i = 0; i < offset_count - 1; i++) {
ReadProcessMemory(process, (void *)(base + va_arg(offsets, SINT)), &base, sizeof(base), NULL);
}
base += va_arg(offsets, SINT);
va_end(offsets);
return (void *)((SINT)base);
}
}
DWORD ReadBuffer(HANDLE process, void *address, void *buffer, DWORD size) {
ReadProcessMemory(process, address, buffer, size, (SIZE_T *)&size);
return size;
}
byte ReadByte(HANDLE process, void *address) {
byte b = 0;
ReadProcessMemory(process, address, &b, sizeof(b), 0);
return b;
}
short ReadShort(HANDLE process, void *address) {
short s = 0;
ReadProcessMemory(process, address, &s, sizeof(s), 0);
return s;
}
int ReadInt(HANDLE process, void *address) {
int i = 0;
ReadProcessMemory(process, address, &i, sizeof(i), 0);
return i;
}
long ReadLong(HANDLE process, void *address) {
long l = 0;
ReadProcessMemory(process, address, &l, sizeof(l), 0);
return l;
}
float ReadFloat(HANDLE process, void *address) {
float f = 0;
ReadProcessMemory(process, address, &f, sizeof(f), 0);
return f;
}
long long ReadLongLong(HANDLE process, void *address) {
long long l = 0;
ReadProcessMemory(process, address, &l, sizeof(l), 0);
return l;
}
double ReadDouble(HANDLE process, void *address) {
double d = 0;
ReadProcessMemory(process, address, &d, sizeof(d), 0);
return d;
}
VECTOR ReadVector(HANDLE process, void *address) {
VECTOR v = { 0 };
ReadProcessMemory(process, address, &v, sizeof(v), 0);
return v;
}
bool WriteBuffer(HANDLE process, void *address, void *buffer, DWORD size) {
return WriteProcessMemory(process, address, buffer, size, 0) != 0;
}
bool WriteByte(HANDLE process, void *address, byte value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteShort(HANDLE process, void *address, short value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteInt(HANDLE process, void *address, int value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteLong(HANDLE process, void *address, long value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteFloat(HANDLE process, void *address, float value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteLongLong(HANDLE process, void *address, long long value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteDouble(HANDLE process, void *address, double value) {
return WriteProcessMemory(process, address, &value, sizeof(value), 0) != 0;
}
bool WriteVector(HANDLE process, void *address, VECTOR *value) {
return WriteProcessMemory(process, address, value, sizeof(value), 0) != 0;
}
ARGUMENT ArgumentByte(byte value) {
ARGUMENT a = { 0 };
a.type = ARGUMENT_BYTE;
*(byte *)&a.value = value;
return a;
}
ARGUMENT ArgumentShort(short value) {
ARGUMENT a = { 0 };
a.type = ARGUMENT_SHORT;
*(short *)&a.value = value;
return a;
}
ARGUMENT ArgumentInt(int value) {
ARGUMENT a = { 0 };
a.type = ARGUMENT_INT;
*(short *)&a.value = value;
return a;
}
ARGUMENT ArgumentFloat(float value) {
ARGUMENT a = { 0 };
a.type = ARGUMENT_FLOAT;
*(float *)&a.value = value;
return a;
}
ARGUMENT ArgumentLongLong(long long value) {
ARGUMENT a = { 0 };
a.type = ARGUMENT_LONGLONG;
a.value = value;
return a;
}
ARGUMENT ArgumentDouble(double value) {
ARGUMENT a = { 0 };
a.type = ARGUMENT_DOUBLE;
*(double *)&a.value = value;
return a;
}
DWORD GetPushSize32(ARGUMENT *argument) {
switch (argument->type) {
case ARGUMENT_BYTE:
return 2;
case ARGUMENT_SHORT: case ARGUMENT_INT: case ARGUMENT_FLOAT:
return 5;
case ARGUMENT_LONGLONG: case ARGUMENT_DOUBLE:
return 10;
}
return 0;
}
bool CallCDECL(HANDLE process, void *function, DWORD argument_count, ...) {
BOOL x32;
IsWow64Process(process, &x32);
if (x32) {
byte bytes[10] = { 0 };
va_list va_args;
ARGUMENT *args;
LPVOID base;
DWORD size = 6 + argument_count;
SINT addr;
args = (ARGUMENT *)malloc(argument_count * sizeof(ARGUMENT));
va_start(va_args, argument_count);
for (DWORD i = 0; i < argument_count; ++i) {
args[i] = va_arg(va_args, ARGUMENT);
size += GetPushSize32(&args[i]);
if (args[i].type == ARGUMENT_LONGLONG || args[i].type == ARGUMENT_DOUBLE) {
++size;
}
}
va_end(va_args);
base = VirtualAllocEx(process, 0, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!base) {
free(args);
return false;
}
addr = (SINT)base;
for (int i = (int)argument_count - 1; i > -1; --i) {
DWORD push_size = GetPushSize32(&args[i]);
switch (args[i].type) {
case ARGUMENT_BYTE:
bytes[0] = 0x6A;
bytes[1] = *(byte *)&args[i].value;
break;
case ARGUMENT_SHORT:
bytes[0] = 0x68;
*(DWORD *)&bytes[1] = *(short *)&args[i].value;
break;
case ARGUMENT_INT: case ARGUMENT_FLOAT:
bytes[0] = 0x68;
*(DWORD *)&bytes[1] = *(DWORD *)&args[i].value;
break;
case ARGUMENT_LONGLONG: case ARGUMENT_DOUBLE:
bytes[0] = 0x68;
*(DWORD *)&bytes[1] = *(DWORD *)((SINT)&args[i].value + 4);
bytes[5] = 0x68;
*(DWORD *)&bytes[6] = *(DWORD *)&args[i].value;
++argument_count;
break;
}
WriteProcessMemory(process, (LPVOID)addr, bytes, push_size, 0);
addr += push_size;
}
bytes[0] = 0xE8;
*(int *)&bytes[1] = (int)((SINT)function - (SINT)addr - 5);
WriteProcessMemory(process, (LPVOID)addr, bytes, 5, 0);
addr += 5;
for (DWORD i = 0; i < argument_count; ++i) {
bytes[0] = 0x58;
WriteProcessMemory(process, (LPVOID)addr++, bytes, 1, 0);
}
bytes[0] = 0xC3;
WriteProcessMemory(process, (LPVOID)addr, bytes, 1, 0);
WaitForSingleObject(CreateRemoteThread(process, 0, 0, (LPTHREAD_START_ROUTINE)base, 0, 0, 0), INFINITE);
VirtualFreeEx(process, base, 0, MEM_RELEASE);
free(args);
return true;
}
return false;
}
bool CallSTDCALL(HANDLE process, void *function, DWORD argument_count, ...) {
BOOL x32;
IsWow64Process(process, &x32);
if (x32) {
byte bytes[10] = { 0 };
va_list va_args;
ARGUMENT *args;
LPVOID base;
DWORD size = 6;
SINT addr;
args = (ARGUMENT *)malloc(argument_count * sizeof(ARGUMENT));
va_start(va_args, argument_count);
for (DWORD i = 0; i < argument_count; ++i) {
args[i] = va_arg(va_args, ARGUMENT);
size += GetPushSize32(&args[i]);
}
va_end(va_args);
base = VirtualAllocEx(process, 0, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!base) {
free(args);
return false;
}
addr = (SINT)base;
for (int i = (int)argument_count - 1; i > -1; --i) {
DWORD push_size = GetPushSize32(&args[i]);
switch (args[i].type) {
case ARGUMENT_BYTE:
bytes[0] = 0x6A;
bytes[1] = *(byte *)&args[i].value;
break;
case ARGUMENT_SHORT:
bytes[0] = 0x68;
*(DWORD *)&bytes[1] = *(short *)&args[i].value;
break;
case ARGUMENT_INT: case ARGUMENT_FLOAT:
bytes[0] = 0x68;
*(DWORD *)&bytes[1] = *(DWORD *)&args[i].value;
break;
case ARGUMENT_LONGLONG: case ARGUMENT_DOUBLE:
bytes[0] = 0x68;
*(DWORD *)&bytes[1] = *(DWORD *)((SINT)&args[i].value + 4);
bytes[5] = 0x68;
*(DWORD *)&bytes[6] = *(DWORD *)&args[i].value;
++argument_count;
break;
}
WriteProcessMemory(process, (LPVOID)addr, bytes, push_size, 0);
addr += push_size;
}
bytes[0] = 0xE8;
*(int *)&bytes[1] = (int)((SINT)function - (SINT)addr - 5);
WriteProcessMemory(process, (LPVOID)addr, bytes, 5, 0);
addr += 5;
bytes[0] = 0xC3;
WriteProcessMemory(process, (LPVOID)addr, bytes, 1, 0);
WaitForSingleObject(CreateRemoteThread(process, 0, 0, (LPTHREAD_START_ROUTINE)base, 0, 0, 0), INFINITE);
VirtualFreeEx(process, base, 0, MEM_RELEASE);
free(args);
return true;
}
return false;
}
bool MaskCompare(char *s1, char *s2, char *mask) {
for (; *mask; ++mask, ++s1, ++s2) {
if (*mask == 'x' && *s1 != *s2) {
return false;
}
}
return true;
}
void *FindLocalPattern(void *base, unsigned int length, char *pattern, char *mask) {
for (SINT l = (SINT)base + length - strlen(mask) + 1; (SINT)base < l; base = (void *)((SINT)base + 1)) {
if (MaskCompare((char *)base, pattern, mask)) {
return base;
}
}
return 0;
}
void *FindPattern(HANDLE process, void *base, unsigned int length, char *pattern, char *mask) {
char *buffer = (char *)malloc(length);
if (!buffer) return 0;
SINT addr = 0;
if (ReadProcessMemory(process, base, buffer, length, 0)) {
addr = (SINT)FindLocalPattern(buffer, length, pattern, mask);
if (addr) {
addr += (SINT)base - (SINT)buffer;
}
}
free(buffer);
return (void *)addr;
} | true |
ac63c8c15dc3fbd0b673761a5f6a38cfad7aa332 | C++ | lucafanselau/ovk | /ovk/ui/concept.cpp | UTF-8 | 1,554 | 2.578125 | 3 | [] | no_license | // Ok so this is how i would image the library to look like
// very very wip
int main() {
/* Create OVK RenderContext (atm ovk::Device and ovk::SwapChain?)*/
ovk::ui::UIManager ui(device, swapchain);
/* Build up UI */
// ui::Panel is a window
// ui::Panel is an ui::Element which is constrainable and animatable
// adding a panel intruduces a "heavy" workload so it is adviced to do that at startup
// each ui::Panel may have children
using constraints = ovk::ui::constraints;
ovk::ui::Panel panel = ui.build_panel()
.add_constraint(/*x:*/ constraints::center, /*y:*/ constraints::pixel(50), /*width*/ constraints::rel(0.1f), /*height*/ constraints::aspect(1.0f))
.add_transition(ovk::ui::transition::alpha_fade(0.0f, 1.0f, /* timing: (seconds)*/ 0.5f))
// The advantage of a ui::Panel is that in the add_child() method the panel will figure out constraints on its own
// but u are free to add them urself?
.add_child("my_button", ui.create_button("Click me!", on_button))
.add_child("text", ui.create_text("This is some constant text"))
.add_child("dynamic_text", ui.create_dynamic_text("This text can change later!"))
.build();
// u can do some manipulation at run-time
panel.deactivate(); // will use the transition to deactivate the panel
// u can also get a child and call the run-time function of that child
panel["dynamic_text"].set_text("Yes now it will change!");
// U can also use free floating ui::Elements that are not docked within a panel
ovk::ui::Button brush_
}
| true |
7eb3c6fabe49559c795de30b1defe8fea1e5c6ca | C++ | k-swis/CS1337 | /lab28.cpp | UTF-8 | 894 | 2.953125 | 3 | [] | no_license | //Your Name
//CS 1337
//Lab 28
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <bitset>
#include <climits>
#include <bits.h>
extern const int N;
using namespace std;
void printHexadecimal(int word, ostream& os)
{
int i;
for ( i = (N - 1) / 4 * 4; i >= 0; i -= 4)
{
if(getBits(word, i, 4) < 10)
{
os << getBits(word, i, 4);
}
else if(getBits(word, i, 4) > 9 &&
getBits(word, i, 4) < 11)
{
os << 'A';
}
else if(getBits(word, i, 4) > 10 &&
getBits(word, i, 4) < 12)
{
os << 'B';
}
else if(getBits(word, i, 4) > 11 &&
getBits(word, i, 4) < 13)
{
os << 'C';
}
else if(getBits(word, i, 4) > 12 &&
getBits(word, i, 4) < 14)
{
os << 'D';
}
else if(getBits(word, i, 4) > 13 &&
getBits(word, i, 4) < 15)
{
os << 'E';
}
else if(getBits(word, i, 4) == 15)
{
os << 'F';
}
}
} | true |
02f5b4565daadef1ad1dacef0784cdc8a9f0bd50 | C++ | OSSGames/GAME-SPORTS-BillardGL | /Kamera.cpp | UTF-8 | 14,921 | 2.78125 | 3 | [] | no_license | /****************************************************************************
**
** Kamera.cpp Stefan Disch, Tobias Nopper, Martina Welte 2001
**
*****************************************************************************/
#include <math.h>
#include <stdio.h> //2CHANGE wieder raus wenn kein printf mehr drin
#include "Kugel.h"
#include "Kamera.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
GLfloat BewegFaktor=.3;
GLfloat DrehFaktor=.3;
GLfloat Positionen[12][6]; // Array zum Abspeichern der Kamerapositionen
/* --------- Konstruktor ---------- */
Kamera::Kamera() {
// Generieren der vordefinierten Kamerapositionen
Alpha=60.0;Beta=60.0;
Pos_x=-100.0;Pos_y=-50.0;Pos_z=50.0;
FOV=38.6;
speicherePosition(0);
Alpha=0;Beta=0;
Pos_x=0;Pos_y=0;Pos_z=400;
FOV=30.7;
speicherePosition(1);
Alpha=80;Beta=90;
Pos_x=-170;Pos_y=0;Pos_z=30;
FOV=38.6;
speicherePosition(2);
Alpha=80;Beta=-90;
Pos_x=170;Pos_y=0;Pos_z=30;
FOV=38.6;
speicherePosition(3);
Alpha=53;Beta=90;
Pos_x=-220;Pos_y=0;Pos_z=120;
FOV=38.6;
speicherePosition(4);
Alpha=53;Beta=-90;
Pos_x=220;Pos_y=0;Pos_z=120;
FOV=38.6;
speicherePosition(5);
Alpha=48;Beta=123.5;
Pos_x=-229;Pos_y=121;Pos_z=176;
FOV=38.6;
speicherePosition(7);
Alpha=48;Beta=56.5;
Pos_x=-229;Pos_y=-121;Pos_z=176;
FOV=38.6;
speicherePosition(6);
Soll_Pos_x=-60;
Soll_Pos_y=-30;
Rundflug(0);
Alpha=Soll_Alpha;
Beta=Soll_Beta;
Pos_x=Soll_Pos_x;
Pos_y=Soll_Pos_y;
Pos_z=Soll_Pos_z;
Aspekt=1.333333;
Verfolgung=-1;
Alpha=100;Beta=0;
Pos_x=0;Pos_y=-200;Pos_z=20;
FOV=38.6;
}
void Kamera::male() {
glMatrixMode(GL_PROJECTION); // Kameraparameter!
glLoadIdentity(); // zuruecksetzen
gluPerspective(FOV,Aspekt,Nah,Fern);
glMatrixMode(GL_MODELVIEW); // Blickpunkt!
glLoadIdentity(); // Kamera an den Ursprung setzen
glRotatef(Alpha,-1,0,0); // um Alpha nach oben und Beta nach Rechts drehen
glRotatef(Beta,0,0,1);
// an die gewuenschte Position setzen
glTranslatef(-Pos_x,-Pos_y,-Pos_z);
//glEnable(GL_LIGHTING);
}
//setzt die Kamera an eine neue Position
void Kamera::neuePosition(GLfloat Position[]) {
Soll_Pos_x = Position[0];
Soll_Pos_y = Position[1];
Soll_Pos_z = Position[2];
Soll_Alpha = Position[3];
Soll_Beta = Position[4];
Soll_FOV = Position[5];
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
//gibt die aktuelle Kameraposition zur"uck
//GLfloat* Kamera::Position() {
// GLfloat temp[] ={Soll_Pos_x,Soll_Pos_y,Soll_Pos_z,Soll_Alpha,Soll_Beta,Soll_FOV};
// return temp;
//}
GLfloat Kamera::Pos_xCM() {
return Pos_x;
}
GLfloat Kamera::Pos_yCM() {
return Pos_y;
}
GLfloat Kamera::Pos_zCM() {
return Pos_z;
}
//schreibt die aktuelle Kameraposition in die Tabelle ab
void Kamera::speicherePosition(GLint Platz) {
Positionen[Platz][0]=Pos_x;
Positionen[Platz][1]=Pos_y;
Positionen[Platz][2]=Pos_z;
Positionen[Platz][3]=Alpha;
Positionen[Platz][4]=Beta;
Positionen[Platz][5]=FOV;
//2DEL
//printf("%i: %f %f %f %f %f %f \n",Platz,Pos_x,Pos_y,Pos_z,Alpha,Beta,FOV);
}
// l"adt eine Kameraposition aus der Tabelle
void Kamera::ladePosition(GLint Platz) {
setzeSollPosition(Positionen[Platz]);
Verfolgung=-1;
}
// Bewegt die Kamera in Blickrichtung
void Kamera::Beweg_Rein(GLfloat Faktor) {
Soll_Pos_x+=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*sin(Soll_Beta/57.29578);
Soll_Pos_y+=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*cos(Soll_Beta/57.29578);
Soll_Pos_z-=2*BewegFaktor*Faktor*cos(Soll_Alpha/57.29578);
// if (Pos_z>400) {Pos_z=400;}
if (Soll_Pos_z<2.8) {Soll_Pos_z=2.9;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera gegen die Blickrichtung
void Kamera::Beweg_Raus(GLfloat Faktor) {
Soll_Pos_x-=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*sin(Soll_Beta/57.29578);
Soll_Pos_y-=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*cos(Soll_Beta/57.29578);
Soll_Pos_z+=2*BewegFaktor*Faktor*cos(Soll_Alpha/57.29578);
// if (Pos_z>400) {Pos_z=400;}
if (Soll_Pos_z<2.8) {Soll_Pos_z=2.8;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera in Blickrichtung, aber unter Beibehaltung der H"ohe
void Kamera::Beweg_Vor(GLfloat Faktor) {
Soll_Pos_x+=2*BewegFaktor*Faktor*sin(Soll_Beta/57.29578);
Soll_Pos_y+=2*BewegFaktor*Faktor*cos(Soll_Beta/57.29578);
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera gegen die Blickrichtung, aber unter Beibehaltung der H"ohe
void Kamera::Beweg_Zurueck(GLfloat Faktor) {
Soll_Pos_x-=2*BewegFaktor*Faktor*sin(Soll_Beta/57.29578);
Soll_Pos_y-=2*BewegFaktor*Faktor*cos(Soll_Beta/57.29578);
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera nach rechts
void Kamera::Beweg_Rechts(GLfloat Faktor) {
Soll_Pos_x+=BewegFaktor*Faktor*cos(Soll_Beta/57.29578);
Soll_Pos_y-=BewegFaktor*Faktor*sin(Soll_Beta/57.29578);
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera nach links
void Kamera::Beweg_Links(GLfloat Faktor) {
Soll_Pos_x-=BewegFaktor*Faktor*cos(Soll_Beta/57.29578);
Soll_Pos_y+=BewegFaktor*Faktor*sin(Soll_Beta/57.29578);
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera nach oben
void Kamera::Beweg_Hoch(GLfloat Faktor) {
Soll_Pos_z+=BewegFaktor*Faktor;
// if (Pos_z>400) {Pos_z=400;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Bewegt die Kamera nach unten
void Kamera::Beweg_Runter(GLfloat Faktor) {
Soll_Pos_z-=BewegFaktor*Faktor;
if (Soll_Pos_z<2.8) {Soll_Pos_z=2.8;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
// Vergr"o"sert den Zoom
void Kamera::Zoom_Rein(GLfloat Faktor) {
Soll_FOV-=BewegFaktor*Faktor;
if (Soll_FOV<1) {Soll_FOV=1;}
Verfolgung=-1;
}
// Verkleinert den Zoom
void Kamera::Zoom_Raus(GLfloat Faktor) {
Soll_FOV+=BewegFaktor*Faktor;
Verfolgung=-1;
}
// Vergr"o"sert den Vertigo
void Kamera::Vertigo_Rein(GLfloat Faktor) {
Soll_Pos_x-=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*sin(Soll_Beta/57.29578);
Soll_Pos_y-=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*cos(Soll_Beta/57.29578);
Soll_Pos_z+=2*BewegFaktor*Faktor*cos(Soll_Alpha/57.29578);
Soll_FOV=2077*cos(Soll_Alpha/57.29578)/Soll_Pos_z;
if (Soll_FOV<1) {Soll_FOV=1;}
Verfolgung=-1;
}
// Verkleinert den Vertigo
void Kamera::Vertigo_Raus(GLfloat Faktor) {
Soll_Pos_x+=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*sin(Soll_Beta/57.29578);
Soll_Pos_y+=2*BewegFaktor*Faktor*sin(Soll_Alpha/57.29578)*cos(Soll_Beta/57.29578);
Soll_Pos_z-=2*BewegFaktor*Faktor*cos(Soll_Alpha/57.29578);
Soll_FOV=2077*cos(Soll_Alpha/57.29578)/Soll_Pos_z;
Verfolgung=-1;
}
// Dreht die Kamera nach rechts
void Kamera::Dreh_Rechts(GLfloat Faktor) {
Soll_Beta+=Faktor*DrehFaktor;
Verfolgung=-1;
}
// Dreht die Kamera nach links
void Kamera::Dreh_Links(GLfloat Faktor) {
Soll_Beta-=Faktor*DrehFaktor;
Verfolgung=-1;
}
// Dreht die Kamera nach oben
void Kamera::Dreh_Hoch(GLfloat Faktor) {
Soll_Alpha+=Faktor*DrehFaktor;
if (Soll_Alpha>90) {Soll_Alpha=90;}
if (Soll_Alpha<0) {Soll_Alpha=0;}
Verfolgung=-1;
}
// Dreht die Kamera nach unten
void Kamera::Dreh_Runter(GLfloat Faktor) {
Soll_Alpha-=Faktor*DrehFaktor;
if (Soll_Alpha>90) {Soll_Alpha=90;}
if (Soll_Alpha<0) {Soll_Alpha=0;}
Verfolgung=-1;
}
void Kamera::Schwenk_Links(GLfloat Faktor, GLfloat Mitte_x, GLfloat Mitte_y) {
GLfloat Abstand=sqrt((Mitte_x-Soll_Pos_x)*(Mitte_x-Soll_Pos_x)+(Mitte_y-Soll_Pos_y)*(Mitte_y-Soll_Pos_y));
if (Abstand<5) Abstand=5;
Soll_Beta+=Faktor*DrehFaktor*7.338/sqrt(Abstand);
Soll_Pos_x=Mitte_x-Abstand*sin(Soll_Beta/57.29578);
Soll_Pos_y=Mitte_y-Abstand*cos(Soll_Beta/57.29578);
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
void Kamera::Schwenk_Rechts(GLfloat Faktor, GLfloat Mitte_x, GLfloat Mitte_y) {
GLfloat Abstand=sqrt((Mitte_x-Soll_Pos_x)*(Mitte_x-Soll_Pos_x)+(Mitte_y-Soll_Pos_y)*(Mitte_y-Soll_Pos_y));
if (Abstand<5) Abstand=5;
Soll_Beta-=Faktor*DrehFaktor*7.338/sqrt(Abstand);
Soll_Pos_x=Mitte_x-Abstand*sin(Soll_Beta/57.29578);
Soll_Pos_y=Mitte_y-Abstand*cos(Soll_Beta/57.29578);
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
void Kamera::Schwenk_Hoch(GLfloat Faktor, GLfloat Mitte_x, GLfloat Mitte_y) {
GLfloat Abstand=sqrt((Mitte_x-Soll_Pos_x)*(Mitte_x-Soll_Pos_x)+(Mitte_y-Soll_Pos_y)*(Mitte_y-Soll_Pos_y)+(Soll_Pos_z-2.8)*(Soll_Pos_z-2.8));
if (Abstand==0) {
Soll_Alpha=0;
} else {
Soll_Alpha+=Faktor*DrehFaktor*7.338/sqrt(Abstand);
if (Soll_Alpha<0) {Soll_Alpha=0;}
if (Soll_Alpha>90) {Soll_Alpha=90;}
}
Soll_Pos_x=Mitte_x-Abstand*sin(Soll_Beta/57.29578)*sin(Soll_Alpha/57.29578);
Soll_Pos_y=Mitte_y-Abstand*cos(Soll_Beta/57.29578)*sin(Soll_Alpha/57.29578);
Soll_Pos_z=2.8+Abstand*cos(Soll_Alpha/57.29578);
// if (Pos_z>400) {Pos_z=400;}
if (Soll_Pos_z<2.8) {Soll_Pos_z=2.8;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
void Kamera::Schwenk_Runter(GLfloat Faktor, GLfloat Mitte_x, GLfloat Mitte_y) {
GLfloat Abstand=sqrt((Mitte_x-Soll_Pos_x)*(Mitte_x-Soll_Pos_x)+(Mitte_y-Soll_Pos_y)*(Mitte_y-Soll_Pos_y)+(Soll_Pos_z-2.8)*(Soll_Pos_z-2.8));
if (Abstand==0) {
Soll_Alpha=0;
} else {
Soll_Alpha-=Faktor*DrehFaktor*7.338/sqrt(Abstand);
if (Soll_Alpha<0) {Soll_Alpha=0;}
if (Soll_Alpha>90) {Soll_Alpha=90;}
}
Soll_Pos_x=Mitte_x-Abstand*sin(Soll_Beta/57.29578)*sin(Soll_Alpha/57.29578);
Soll_Pos_y=Mitte_y-Abstand*cos(Soll_Beta/57.29578)*sin(Soll_Alpha/57.29578);
Soll_Pos_z=2.8+Abstand*cos(Soll_Alpha/57.29578);
// if (Pos_z>400) {Pos_z=400;}
if (Soll_Pos_z<2.8) {Soll_Pos_z=2.8;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
void Kamera::setzeSollPosition(GLfloat Soll_Pos[6]) {
Soll_Pos_x = Soll_Pos[0];
Soll_Pos_y = Soll_Pos[1];
Soll_Pos_z = Soll_Pos[2];
Soll_Alpha = Soll_Pos[3];
Soll_Beta = Soll_Pos[4];
Soll_FOV = Soll_Pos[5];
Beta=fmod(Beta,360);
Soll_Beta=fmod(Soll_Beta,360);
if (Soll_Beta>Beta+180) {Soll_Beta-=360;}
if (Soll_Beta<Beta-180) {Soll_Beta+=360;}
BlickTiefeNeuBestimmen();
Verfolgung=-1;
}
void Kamera::setzeSollPosition(GLfloat SollPosx,
GLfloat SollPosy,
GLfloat SollPosz,
GLfloat SollAlpha,
GLfloat SollBeta,
GLfloat SollFOV) {
Soll_Pos_x = SollPosx;
Soll_Pos_y = SollPosy;
Soll_Pos_z = SollPosz;
Soll_Alpha = SollAlpha;
Soll_Beta = SollBeta;
Soll_FOV = SollFOV;
Beta=fmod(Beta,360);
Soll_Beta=fmod(Soll_Beta,360);
if (Soll_Beta>Beta+180) {Soll_Beta-=360;}
if (Soll_Beta<Beta-180) {Soll_Beta+=360;}
Verfolgung=-1;
}
void Kamera::BlickeAuf(GLfloat Blickpunkt[2]) {
BlickeAuf(Blickpunkt[0],Blickpunkt[1]);
}
void Kamera::BlickeAuf(GLfloat Blickpunkt_x,GLfloat Blickpunkt_y) {
GLfloat SollPosx=50*(Pos_x-Blickpunkt_x)/
sqrt((Blickpunkt_x-Pos_x)*(Blickpunkt_x-Pos_x)+
(Blickpunkt_y-Pos_y)*(Blickpunkt_y-Pos_y))+
Blickpunkt_x;
GLfloat SollPosy=50*(Pos_y-Blickpunkt_y)/
sqrt((Blickpunkt_x-Pos_x)*(Blickpunkt_x-Pos_x)+
(Blickpunkt_y-Pos_y)*(Blickpunkt_y-Pos_y))+
Blickpunkt_y;
GLfloat SollPosz=20;
GLfloat SollAlpha=71.0167;
GLfloat SollBeta=atan((Blickpunkt_x-SollPosx)/(Blickpunkt_y-SollPosy))*180/M_PI;
if (SollPosy>Blickpunkt_y) {SollBeta-=180;}
GLfloat SollFOV=38.6;
setzeSollPosition(SollPosx,SollPosy,SollPosz,SollAlpha,SollBeta,SollFOV);
Verfolgung=-1;
}
void Kamera::BlickeAuf2(GLfloat Blickpunkt[2]) {
BlickeAuf2(Blickpunkt[0],Blickpunkt[1]);
}
void Kamera::BlickeAuf2(GLfloat Blickpunkt_x,GLfloat Blickpunkt_y) {
GLfloat SollPosx=80*(Pos_x-Blickpunkt_x)/
sqrt((Blickpunkt_x-Pos_x)*(Blickpunkt_x-Pos_x)+
(Blickpunkt_y-Pos_y)*(Blickpunkt_y-Pos_y))+
Blickpunkt_x;
GLfloat SollPosy=80*(Pos_y-Blickpunkt_y)/
sqrt((Blickpunkt_x-Pos_x)*(Blickpunkt_x-Pos_x)+
(Blickpunkt_y-Pos_y)*(Blickpunkt_y-Pos_y))+
Blickpunkt_y;
GLfloat SollPosz=50;
GLfloat SollAlpha=72;
GLfloat SollBeta=atan((Blickpunkt_x-SollPosx)/(Blickpunkt_y-SollPosy))*180/M_PI;
if (SollPosy>Blickpunkt_y) {SollBeta-=180;}
GLfloat SollFOV=38.6;
setzeSollPosition(SollPosx,SollPosy,SollPosz,SollAlpha,SollBeta,SollFOV);
Verfolgung=-1;
}
void Kamera::BlickeAuf3(GLfloat Blickpunkt[2]) {
BlickeAuf3(Blickpunkt[0],Blickpunkt[1]);
}
void Kamera::BlickeAuf3(GLfloat Blickpunkt_x,GLfloat Blickpunkt_y) {
GLfloat SollPosx=80*(Pos_x-Blickpunkt_x)/
sqrt((Blickpunkt_x-Pos_x)*(Blickpunkt_x-Pos_x)+
(Blickpunkt_y-Pos_y)*(Blickpunkt_y-Pos_y))+
Blickpunkt_x;
GLfloat SollPosy=80*(Pos_y-Blickpunkt_y)/
sqrt((Blickpunkt_x-Pos_x)*(Blickpunkt_x-Pos_x)+
(Blickpunkt_y-Pos_y)*(Blickpunkt_y-Pos_y))+
Blickpunkt_y;
GLfloat SollPosz=50;
GLfloat SollAlpha=58;
GLfloat SollBeta=atan((Blickpunkt_x-SollPosx)/(Blickpunkt_y-SollPosy))*180/M_PI;
if (SollPosy>Blickpunkt_y) {SollBeta-=180;}
GLfloat SollFOV=38.6;
setzeSollPosition(SollPosx,SollPosy,SollPosz,SollAlpha,SollBeta,SollFOV);
Verfolgung=-1;
}
void Kamera::Fahrt(GLfloat Faktor) {
if (Verfolgung!=-1) {
if (Kugel[Verfolgung].Pos_x()==3000.0) {
Verfolgung=-1;
} else {
GLint Verfolgung2=Verfolgung;
BlickeAuf3(Kugel[Verfolgung].Pos_xCM(),Kugel[Verfolgung].Pos_yCM());
Verfolgung=Verfolgung2;
}
}
for (int i=0;i<Faktor;i++) {
if (Soll_Beta-Beta<-180){Beta-=360;}
if (Soll_Beta-Beta> 180){Beta+=360;}
d_Pos_x = d_Pos_x * 0.9 + 0.003 * (Soll_Pos_x-Pos_x);
d_Pos_y = d_Pos_y * 0.9 + 0.003 * (Soll_Pos_y-Pos_y);
d_Pos_z = d_Pos_z * 0.9 + 0.003 * (Soll_Pos_z-Pos_z);
d_Alpha = d_Alpha * 0.9 + 0.003 * (Soll_Alpha-Alpha);
d_Beta = d_Beta * 0.9 + 0.003 * (Soll_Beta-Beta);
d_FOV = d_FOV * 0.9 + 0.003 * (Soll_FOV-FOV);
Pos_x += d_Pos_x;
Pos_y += d_Pos_y;
Pos_z += d_Pos_z;
Alpha += d_Alpha;
Beta += d_Beta;
FOV += d_FOV;
BlickTiefeNeuBestimmen();
}
}
void Kamera::Verfolge(GLint Kugel) {
Verfolgung=Kugel;
}
void Kamera::BlickTiefeNeuBestimmen() {
GLfloat ax=fabs(Pos_x),ay=fabs(Pos_y),az=Pos_z;
if (ax<150) {
if (ay<80) {
Nah=az-5;
} else {
Nah=sqrt((ay-80)*(ay-80)+(az-5)*(az-5));
}
} else {
if (ay<80) {
Nah=sqrt((ax-150)*(ax-150)+(az-5)*(az-5));
} else {
Nah=sqrt((ax-150)*(ax-150)+(ay-80)*(ay-80)+(az-5)*(az-5));
}
}
Nah*=.8;
if (Nah<1) {Nah=1;}
Fern=sqrt((ax+150)*(ax+150)+(ay+80)*(ay+80)+az*az);
// printf ("Nah: %f\nFern: %f\n\n",Nah,Fern); 2DEL
}
void Kamera::Rundflug(GLint Faktor){
if (Soll_Pos_y==0) {Soll_Pos_y=.00001;}
//Soll_Beta=Faktor*.1+atan(Soll_Pos_x/Soll_Pos_y)*180/M_PI;
//if (Soll_Pos_y>0) {Soll_Beta-=180;}
Soll_Beta+=.1*Faktor;
Soll_Pos_x=(-30*sin(Soll_Beta*M_PI/180)-280)*sin(Soll_Beta*M_PI/180);
Soll_Pos_y=(-30*sin(Soll_Beta*M_PI/180)-280)*cos(Soll_Beta*M_PI/180);
Soll_Pos_z=100-50*sin(Soll_Beta*M_PI/180);
Soll_FOV=36.8;
Soll_Alpha=atan(sqrt(Soll_Pos_x*Soll_Pos_x+
Soll_Pos_y*Soll_Pos_y)/
Soll_Pos_z)*180/M_PI;
}
| true |
07d07fc5d9bc94945cc5f1c4163cd55dbab967dd | C++ | ahawk66/priorityPrint | /simulation.h | UTF-8 | 3,416 | 3.046875 | 3 | [] | no_license | #include <fstream>
#include <string>
#include <queue>
using namespace std;
/////////////////////////////////////////
// PrintJob stores and/or modifies information about what needs to be printed, how much still needs to be printed, and what time it got to a printer,
/////////////////////////////////////////
class PrintJob
{
public:
PrintJob(int identifier =-1,int nPages = -1, int aTime= -1);
int getNumPages();
int getArrivalTime();
int getRemainingPages();
int getId();
void decrementPages(int pagesToPrint);
private:
int numPages;
int arrivalTime;
int remainingPages;
int id;
};
class PrintJobQueue: public queue<PrintJob>
{
public:
PrintJobQueue(int upperCutoff);
PrintJobQueue();
int getUpperCutoff();
int getTotalJobCount();
int getTotalPageCount();
void increaseTotalJobCount(int count);
void increaseTotalPageCount(int count);
private:
int upperCutoff;
int totalJobCount;
int totalPageCount;
};
/////////////////////////////////////////
// JobQueueManager will hold and manage the job queues
/////////////////////////////////////////
class JobQueueManager
{
public:
JobQueueManager(int); // Constructor will ] generate the queues
int addJob(int queueIndex,int jobIndex, int time); //newJob takes a printjob, sends it to a print queue, and returns queue id
PrintJob getJob();
bool hasJob();
int getNumJobs();
void stats();
void addQueue(int cutoff, int index);
int getCutoff(int index);
private:
PrintJobQueue *jobQueueArray;
int numOfQueues;
};
/////////////////////////////////////////
// Printer gets jobs, has a certain speed, and holds jobs.
/////////////////////////////////////////
class Printer
{
public:
Printer(int identifier = -1, int speed=-1, double cost=-1, int degradeRat=-1, double rechargeRate=-1, double failRate=-1);
void doJob(PrintJob newJob);
bool isOpen();
void decrementPages();
int getId();
int getPrinterSpeed();
PrintJob getCurrentPrintJob();
void setPagesTillDegrade(int pages);
int getPagesTillDegrade();
int getTimeTillRecharge();
void setTimeTillRecharge(int time);
double getTotalCost();
int getTotalTimeSpent();
int getTotalPages();
int getTotalJobs();
int getRechargeRate();
int getDegradeRate();
double getCost();
private:
int printerSpeed;
int id;
double cost;
int pagesPrinted;
int pagesTillDegrade;
int timeTillRecharge;
int rechargeRate;
double failRate;
PrintJob currentJob;
double totalCost;
int totalTimeSpent;
int totalPages;
int totalJobs;
int degradeRate;
};
/////////////////////////////////////////
// The printer list holds and generates all the printers and will tell you if they are open and how many we have.
// It also holds the key function to update the printers(fetch and process jobs)
/////////////////////////////////////////
class PrinterManager
{
public:
PrinterManager(int nPrinters);
int updatePrinters(int clock, JobQueueManager queueManager);
int getNumPrinters();
bool isPrinterOpen();
Printer getOpenPrinter();
void addPrinter(int id, int speed, double cost, int degradeRate, double failRate, int rechargeRate);
void printerSummary(int time);
double getTotalCost();
private:
int numPrinters;
Printer * printerArray;
// to allocate in constructor do printerArray= new printerType[];
};
| true |
20601349a63133f843fe538be340887875ae62e4 | C++ | whztt07/acm | /zoj/3338/Sov_09_17_2012.cpp | UTF-8 | 2,655 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdarg>
using namespace std;
const int MAX_L = 3;
struct Matrix {
int n, m;
double mat[MAX_L][MAX_L];
Matrix(){}
Matrix(int _n, int _m, ...) : n(_n), m(_m) {
va_list ap;
va_start(ap, _m);
for (int i = 0; i < _n; ++ i)
for (int j = 0; j < _m; ++ j)
mat[i][j] = va_arg(ap, double);
va_end(ap);
}
Matrix operator *(const Matrix &b) const {
Matrix r;
r.n = n; r.m = b.m;
memset(r.mat, 0, sizeof(r.mat));
for (int i = 0; i < r.n; ++ i)
for (int j = 0; j < r.m; ++ j)
for (int k = 0; k < m; ++ k)
r.mat[i][j] += mat[i][k] * b.mat[k][j];
return r;
}
};
struct Point {
double x, y;
Point(){}
Point(double _x, double _y) : x(_x), y(_y) {}
Point operator -(const Point &p) const {return Point(x-p.x, y-p.y);}
double len2() {return x*x + y*y;}
double len() {return sqrt(len2());}
double arg() {return atan2(y, x);}
void get() {cin >> x >> y;}
};
int main(int argc, char *argv[])
{
int t;
cin >> t;
while (t--)
{
Point p1[4], p2[4];
p1[2].get();
p1[0] = Point(0, 0);
p1[1] = Point(p1[2].x, 0);
p1[3] = Point(0, p1[2].y);
for (int i = 0; i < 4; ++ i) p2[i].get();
double sx = (p2[1] - p2[0]).len() / (p1[1] - p1[0]).len();
double sy = (p2[3] - p2[0]).len() / (p1[3] - p1[0]).len();
double th = (p2[1] - p2[0]).arg();
double tx = p2[0].x - p1[0].x;
double ty = p2[0].y - p1[0].y;
// 缩放变换
Matrix TrSca(3, 3
, sx, 0.0, 0.0
,0.0, sy, 0.0
,0.0, 0.0, 1.0);
// cout << sx << " " << sy << endl;
// TrSca.print();
// 旋转变换
Matrix TrRot(3, 3
,cos(th), -sin(th), 0.0
,sin(th), cos(th), 0.0
, 0.0, 0.0, 1.0);
// 平移变换
Matrix TrTra(3, 3
,1.0, 0.0, tx
,0.0, 1.0, ty
,0.0, 0.0, 1.0);
// 复合
Matrix Tr = TrTra*TrRot*TrSca;
double a, b, c, a1, b1, c1;
a = Tr.mat[0][0] - 1; b = Tr.mat[0][1]; c = Tr.mat[0][2];
a1 = Tr.mat[1][0]; b1 = Tr.mat[1][1] - 1; c1 = Tr.mat[1][2];
double x = (c1*b - c*b1) / (a*b1 - a1*b);
double y = (c1*a - c*a1) / (b*a1 - b1*a);
printf("%.2lf %.2lf\n", x, y);
}
return 0;
}
| true |
e95283a6996e3ee2c4ecdec1f4e744c952c12b0b | C++ | daniellba/SMatrix | /SMatrix.cpp | UTF-8 | 12,710 | 3.421875 | 3 | [] | no_license | /*Daniel Ben-Ami*/
#include "SMatrix.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>;
using namespace std;
// MNode constructor
MNode::MNode(double data, int i, int j)
{
_data = data;
_indexI = i;
_indexJ = j;
_nextRow = NULL;
_nextCol = NULL;
}
// SMatrix constructor
SMatrix::SMatrix(int rows, int cols, string type)
{
if (type != "Arrowhead" && type != "Toeplitz" && type != "any")
//checks if the type is legal
{
cout << "NA" << endl;
return;
}
if (rows < 0 || cols < 0)
{
cout << "NA" << endl;
return;
}
_rowSize = rows;
_colSize = cols;
_elemNum = 0;
_matType = type;
_rowHead = new MNode*[rows];
if (!_rowHead)
{
cout << "allocation error";
exit(1);
}
_colHead = new MNode*[cols];
if (!_colHead)
{
cout << "allocation error";
exit(1);
}
for (int i = 0; i < rows; i++)
{
_rowHead[i] = NULL;
}
for (int i = 0; i < cols; i++)
{
_colHead[i] = NULL;
}
}
// remove element with (i,j) index from row and column
// separate cases: first element in list or in the middle
void SMatrix::removeElement(int i, int j)
{
MNode *prev=NULL;
MNode *colPtr = _colHead[j]; // keep the column linked list
MNode *rowPtr = _rowHead[i]; // keep the row linked lst
if (_colHead[j]->_indexI == i) // if element is the first in column
_colHead[j] = _colHead[j]->_nextCol;
else // if element is not the first in column
{
while (colPtr->_indexI != i) // find prev element on the column
{
prev = colPtr;
colPtr = colPtr->_nextCol;
}
prev->_nextCol = colPtr->_nextCol; // connect the prev with the next
}
if (_rowHead[i]->_indexJ == j) // if element is the first in row
{
rowPtr = _rowHead[i];
_rowHead[i] = _rowHead[i]->_nextRow;
}
else // if element is not the first in row
{
while (rowPtr->_indexJ != j) // find prev element on the row
{
prev = rowPtr;
rowPtr = rowPtr->_nextRow;
}
prev->_nextRow = rowPtr->_nextRow; // connect the prev with the next
}
delete rowPtr; // delete the element only once
}
//add new node to both row and column
// separate cases: list is empty or not empty
void SMatrix::insertNode(MNode* n)
{
MNode* p = _rowHead[n->_indexI]; // the i row
if (p != NULL) // there are elements in i row
{
if (p->_indexJ > n->_indexJ) // need to insert n at start, before existing elements
{
n->_nextRow = p;
_rowHead[n->_indexI] = n;
}
else // need to inserst in the middle of the list or at end
{
while (p->_nextRow && p->_nextRow->_indexJ < n->_indexJ)
p = p->_nextRow;
n->_nextRow = p->_nextRow;
p->_nextRow = n;
}
}
else // row is empty
_rowHead[n->_indexI] = n;
p = _colHead[n->_indexJ]; // the j column
if (p != NULL) // there are elements in j col
{
if (p->_indexI > n->_indexI) // need to insert n at start, before existing elements
{
n->_nextCol = p;
_colHead[n->_indexJ] = n;
}
else // need to inserst in the middle of the list or at end
{
while (p->_nextCol && p->_nextCol->_indexI < n->_indexI)
p = p->_nextCol;
n->_nextCol = p->_nextCol;
p->_nextCol = n;
}
}
else // column is empty
_colHead[n->_indexJ] = n;
}
// set value to exist element (i,j)
void SMatrix::setValue(int i, int j, double data)
{
MNode *ptr = _rowHead[i];
while (ptr->_indexJ != j) // find the element on the row
ptr = ptr->_nextRow;
ptr->_data = data;
}
// check if element (i,j) exists
bool SMatrix::IsExist(int i, int j) const
{
MNode *ptr = _rowHead[i];
if (ptr == NULL)
return false;
while (ptr && ptr->_indexJ < j)
ptr = ptr->_nextRow;
if (ptr && ptr->_indexJ == j)
return true;
return false;
}
// set the (i,j) element to be 'data'
void SMatrix::setElement(int i, int j, double data)
{
if (i<0 || i >= _rowSize || j<0 || j >= _colSize) {
cout << "NA" << endl;
return;
}
double temp = getElement(i, j);
bool found = IsExist(i, j);
if (data == 0 && found == true)
{
_elemNum--;
removeElement(i, j);
if (isA(this->_matType) == false)
{
setValue(i, j, temp);
cout << "NA" << endl;
return;
}
}
if (data == 0 && found == false)
{
return;
}
if (data != 0 && found == true)
{
setValue(i, j, data);
if (isA(this->_matType) == false)
{
setValue(i, j, temp);
cout << "NA" << endl;
return;
}
}
if (data != 0 && found == false)
{
MNode *n = new MNode(data, i, j);
_elemNum++;
insertNode(n);
if (isA(this->_matType) == false)
{
setValue(i, j, temp);
cout << "NA" << endl;
return;
}
}
}
// destroy this matrix.
SMatrix::~SMatrix()
{
if (_elemNum != 0)
{
//delete all nodes inside linked lists
for (int i = 0; i < _rowSize; i++)
{
MNode* p = _rowHead[i], *p2;
while (p)
{
p2 = p;
p = p->_nextRow;
delete p2;
}
}
}
//delete array of linked lists
delete[] _colHead;
delete[] _rowHead;
}
// print zero value 'num' times
void printZero(int num)
{
for (int i = 0; i < num; i++)
cout << "0,";
}
// print operator for SMatrix class
ostream& operator<<(ostream& os, const SMatrix& mat)
{
for (int i = 0; i < mat._rowSize; i++)
{
for (int j = 0; j < mat._colSize; j++)
{
os << mat.getElement(i, j);
if (j + 1 != mat._colSize)
os << ",";
}
cout << endl;
}
return os;
}
//copy constractor
SMatrix::SMatrix(SMatrix &other)
{
this->_colSize = other._colSize;
this->_rowSize = other._rowSize;
this->_elemNum = 0;
this->_matType = other._matType;
_rowHead = new MNode *[_rowSize];
if (!_rowHead)
{
cout << "allocation error";
exit(1);
}
_colHead = new MNode*[_colSize];
if (!_colHead)
{
cout << "allocation error";
exit(1);
}
//inialize the matrix to nulls
for (int i = 0; i < _rowSize; i++)
{
_rowHead[i] = NULL;
}
for (int i = 0; i < _colSize; i++)
{
_colHead[i] = NULL;
}
double temp;
for (int i = 0; i < _rowSize; i++)
{
for (int j = 0; j < _colSize; j++)
{
temp = other.getElement(i, j);
this->setElement(i, j, temp);
}
}
}
//gets a specific element with 2 indexs
double SMatrix::getElement(int i, int j) const
{
MNode *ptr = _rowHead[i];
//in case the indexs out of bounds
if (i<0 || i >= _rowSize || j<0 || j >= _colSize) {
cout << "NA" << endl;
}
else
{
while (ptr != NULL && ptr->_indexJ < _colSize)
{
if (ptr->_indexJ==j)
{
return ptr->_data;
}
else
{
ptr = ptr->_nextRow;
}
}
return 0;
}
}
//switchs between rows
void SMatrix::rowShift(const int shiftSize)
{
int counter = shiftSize;
if (counter<0)//if it's negative
{
int temp;
temp = counter * (-1);
temp = counter % 10;
temp = _rowSize - 1 - temp;
counter = temp;
}
while (counter > 0)//the amount of the time I do the etartions
{
for (int i = 0; i < _rowSize; i++)
{
double ptrArr = getElement(i, 0); //holds cells data
double ptr2Arr; //holds the next cell data
for (int j = 1; j < _colSize; j++)
{
ptr2Arr = getElement(i,j); //switchs between the cells
setElement(i, j, ptrArr);
ptrArr = ptr2Arr;
}
setElement(i, 0, ptrArr); //inserts the data to the first cell
}
counter--;
}
if (isA(_matType) == false) //checks if the new matrix still stand the requiarments
{
int counter2 = _rowSize - shiftSize;
rowShift(counter2); //in case it doesn't it makes the matrix back to it's original
}
}
//switchs between cols
void SMatrix::colShift(const int shiftSize)
{
int counter = shiftSize;
if (counter<0)//if it's negative
{
int temp;
temp = counter * (-1);
temp = counter % 10;
temp = _colSize - 1 - temp;
counter = temp;
}
while (counter > 0)//the amount of the time I do the etartions
{
for (int j = 0; j < _colSize; j++)
{
double ptrArr = getElement(0, j); //holds cells data
double ptr2Arr; //holds the next cell data
for (int i = 1; i < _rowSize; i++)
{
ptr2Arr = getElement(i, j); //switchs between the cells
setElement(i, j, ptrArr);
ptrArr = ptr2Arr;
}
setElement(0, j, ptrArr); //inserts the data to the first cell
}
counter--;
}
if (isA(_matType) == false) //checks if the new matrix still stand the requiarments
{
int counter2 = _colSize - shiftSize;
rowShift(counter2); //in case it doesn't it makes the matrix back to it's original
}
}
//checks the type of the matrix
bool SMatrix::isA(string matType)
{
int i, j, k;
double cellData;
cout.setf(std::ios::boolalpha);
if (matType == "Toeplitz")
{
//basicly here i save the cell data and compare it to the other
//cells data in the rows/cols.
for (k = 0; k < _colSize; k++)
{
cellData = getElement(0, k);
for (i = 0, j = 0 + k; i < _rowSize && j < _colSize; i++, j++)
{
if (cellData != getElement(i, j))
{
return false;
}
}
}
for (k = 0; k < _rowSize; k++)
{
cellData = getElement(k, 0);
for (i = 0 + k, j = 0; i < _colSize && j < _rowSize; i++, j++)
{
if (cellData != getElement(i, j))
{
return false;
}
}
}
return true;
}
else if (matType == "Arrowhead")
{
if (_rowSize == _colSize) //checks if it's a square matrix
{
for (i = 1; i < _rowSize; i++)
{
for (j = 1; j < _colSize; j++)
{
if (getElement(i,j) != 0 && i != j)
{
return false;
}
}
}
return true;
}
return false;
}
else if (matType == "any")
{
return true;
}
else { return false; }
}
//calculate the "weight" of the matrix
void SMatrix::sizeInBytes()
{
int sum = (_colSize + _rowSize) * sizeof(MNode*);
double sumOfElement = _elemNum * sizeof(MNode);
cout << sum + sumOfElement + sizeof(SMatrix) << endl;
}
//prints by columns
void SMatrix::printColumnsIndexes()
{
for (int i = 0; i < _colSize; i++)
{
cout << i << ": ";
while (_colHead[i] != NULL && _colHead[i]->_indexI<_rowSize)
{
cout << "(" << _colHead[i]->_indexI << "," << _colHead[i]->_data << ")->";
_colHead[i] = _colHead[i]->_nextCol;
}
cout << endl;
}
}
//prints by rows
void SMatrix::printRowsIndexes()
{
for (int i = 0; i < _rowSize ; i++)
{
cout << i << ": ";
while (_rowHead[i] != NULL && _rowHead[i]->_indexJ<_colSize)
{
cout << "(" << _rowHead[i]->_indexJ << "," << _rowHead[i]->_data << ")->";
_rowHead[i] = _rowHead[i]->_nextRow;
}
cout << endl;
}
}
//ableing to add matrix with the operator "+"
SMatrix SMatrix:: operator+(SMatrix &other)
{
if (this->_colSize == other._colSize && this->_rowSize == other._rowSize &&
this->_matType == other._matType)
//checks if the matrixs are the same size (MxN)
{
double cellSum = 0;
SMatrix *result = new SMatrix (this->_rowSize, this->_colSize, this->_matType);
for (int i = 0; i < this->_rowSize; i++)
{
for (int j = 0; j < this->_colSize; j++)
{
cellSum = this->getElement(i,j) + other.getElement(i,j);
result->setElement(i, j, cellSum);
cellSum = 0;
}
}
return *result;
}
else { cout << "NA" << endl; exit(1); }
}
//ableing to place a matrix to other matrix and thanks to the method "+" you can
//also do matrix + matrix = matrix
SMatrix& SMatrix :: operator=(SMatrix& other)
{
if (this == &other) //if the matrix already same
return *this;
else
{
this->_colSize = other._colSize;
this->_rowSize = other._rowSize;
this->_elemNum = 0;
this->_matType = other._matType;
this->_rowHead = new MNode *[_rowSize];
if (!_rowHead)
{
cout << "allocation error";
exit(1);
}
this->_colHead = new MNode*[_colSize];
if (!_colHead)
{
cout << "allocation error";
exit(1);
}
for (int i = 0; i < _rowSize; i++)
{
_rowHead[i] = NULL;
}
for (int i = 0; i < _colSize; i++)
{
_colHead[i] = NULL;
}
double temp;
for (int i = 0; i < _rowSize; i++)
{
for (int j = 0; j < _colSize; j++)
{
temp = other.getElement(i, j);
this->setElement(i, j, temp);
}
}
}return *this;
}
| true |
55a20171ee0f30ca8d034468d54b2c35394a8529 | C++ | xiaoguosk/safeGeoRecommend | /util.h | GB18030 | 9,115 | 2.578125 | 3 | [] | no_license | #include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/legacy/legacy.hpp>
#include "opencv2/highgui/highgui.hpp"
#include<opencv2\opencv.hpp>
#include<iostream>
#include <stdio.h>
#include <gmp.h>
#include <windows.h>
using namespace std;
using namespace cv;
static float B[3][3] = { { 1, 2, 3 }, { 0, 1, 4 }, { 5, 6, 0 } };//Գɹ
static float B1[2][2] = { { 3, 4 }, { 4, 5 } };
/*pʽĵ*/
static void printHelper(double x, double y){
//cout << "(x,y): (" << x << "," << y << ")" << "\n";
}
CV_INLINE void printMat(CvMat* matrix){
for (int i = 0; i < matrix->rows; i++)//
{
for (int j = 0; j < matrix->cols; j++)
{
cout << (double)(cvGetReal2D(matrix, i, j)) << "\n";
}
}
}
static string mat2String(CvMat* matrix){
string res = "";
for (int i = 0; i < matrix->rows; i++)//
{
for (int j = 0; j < matrix->cols; j++)
{
res = res + to_string(cvGetReal2D(matrix, i, j));
}
}
return res;
}
//static string uchar2String(unsigned char* c){
// string res = "";
// for (int i = 0; i < 16; i++){
// res = res + c[i];
// }
// return res;
//}
/*gen random key*/
static string ase128_random_key(){
string res = "";
for (int i = 0; i < 16; i++){
int c = rand() % 128;
res = res + (char)c;
}
return res;
}
unsigned char* string2Uchar(string str){
unsigned char* res = new unsigned char[str.size()];
for (int i = 0; i < str.size(); i++){
char c = str[i];
unsigned int intC = c;
res[i] = intC;
}
return res;
}
static char* ltos(long l)
{
char c[32];
sprintf(c, "%ld", l);
return c;
}
static string or(string s1, string s2){
string res = "";
int s1Size = s1.size();
int s2Size = s2.size();
if (s1Size < s2Size){
s2 = s2.substr(0, s1Size);
}
if (s1.size() > s2.size()){
int overSize = s1Size - s2Size;
for (int i = 0; i < overSize; i++){
s2 = s2 + "0";
}
}
if (s1.size() == s2.size()){
for (int i = 0; i < s1.size(); i++){
char c = s1[i] ^ s2[i];
res = res + c;
}
}
if (res == ""){
cout << "fs";
}
return res;
}
static CvMat* CvPoint2CvMatS(CvPoint2D32f point){
CvMat* res = cvCreateMat(3, 1, CV_32FC1);
CV_MAT_ELEM(*res, double, 0, 0) = point.x * 3;
CV_MAT_ELEM(*res, double, 1, 0) = point.y * 3;
CV_MAT_ELEM(*res, double, 2, 0) = sqrt(point.x * point.x + point.y * point.y) * 3;
return res;
}
static CvMat* CvPoint2CvMatOfP(CvPoint2D32f point){
float p[3][1] = { 0 };
p[0][0] = point.x;
p[1][0] = point.y;
p[2][0] = -0.5 * (point.x * point.x + point.y * point.y);
CvMat M = cvMat(3, 3, CV_32FC1, B);
CvMat P = cvMat(3, 1, CV_32FC1, p);
//cvTranspose(&M, MT);
CvMat* res = cvCreateMat(3, 1, CV_32FC1);//ûݷ
cvGEMM(&M, &P, 1, &P, 0, res);//3 * 3 * 3 * 1
return res;
}
static CvMat* CvPoint2CvMatOfM(CvPoint2D32f point){
float p[3][1] = { 0 };
p[0][0] = point.x;
p[1][0] = point.y;
p[2][0] = 0;
CvMat M = cvMat(3, 3, CV_32FC1, B);
CvMat P = cvMat(3, 1, CV_32FC1, p);
CvMat* res = cvCreateMat(3, 1, CV_32FC1);
cvGEMM(&M, &P, 1, &M, 0, res, 1);
return res;
}
/*qʽĵ*/
static CvMat* CvPoint2CvMatOfQ(CvPoint2D32f point){
float q[3][1] = { 0 };
q[0][0] = 3 * point.x;
q[1][0] = 3 * point.y;
q[2][0] = 3 * 1;
CvMat M = cvMat(3, 3, CV_32FC1, B);
CvMat* MI = cvCreateMat(3, 3, CV_32FC1);
CvMat Q = cvMat(3, 1, CV_32FC1, q);
cvInvert(&M, MI);
CvMat* res = cvCreateMat(3, 1, CV_32FC1);//ûݷ
cvGEMM(MI, &Q, 1, MI, 0, res, 1);//3 * 3 * 3 * 1
return res;
}
static bool CvCompare(CvMat* src, CvMat* dst){
if (src->rows == dst->rows & src->cols == dst->cols){
for (int i = 0; i < src->rows; i++){
for (int j = 0; j < src->cols; j++){
if ((double)(cvGetReal2D(src, i, j)) != (double)(cvGetReal2D(dst, i, j))){
return false;
}
}
}
return true;
}
return false;
}
//õǰʱ-
static long getCurrentTime()
{
SYSTEMTIME sys;
GetLocalTime(&sys);
return sys.wMilliseconds;
}
static string int2str(const int &int_temp )
{
stringstream stream;
stream << int_temp;
return stream.str(); //˴Ҳ stream>>string_temp
}
static int str2int(const string &string_temp)
{
int int_temp;
stringstream stream(string_temp);
stream >> int_temp;
return int_temp;
}
static const char* double2Char(double d){
ostringstream os;
if (os << d){
string str = os.str();
return str.c_str();
}
return "invalid conversion";
}
static int check(CvMat* ab, CvMat* ac, CvMat* ap){
int scale = 10000000;
double a1 = cvGetReal2D(ab, 0, 0)*scale;
double a2 = cvGetReal2D(ab, 1, 0)*scale;
double a3 = cvGetReal2D(ab, 2, 0)*scale;
const char* a1s = double2Char(a1);
const char* a2s = double2Char(a2);
const char* a3s = double2Char(a3);
double b1 = cvGetReal2D(ac, 0, 0)*scale;
double b2 = cvGetReal2D(ac, 1, 0)*scale;
double b3 = cvGetReal2D(ac, 2, 0)*scale;
const char* b1s = double2Char(b1);
const char* b2s = double2Char(b2);
const char* b3s = double2Char(b3);
mpz_t f_a1, f_a2, f_a3;
//test
//char *char_rand = new char[2];
//char_rand[0] = '1';
//char_rand[1] = '0';
//char_rand[2] = '\0';
////char_rand[1] = "2";
//mpz_t mpzPrime;
//mpz_init(mpzPrime);
//mpz_set_str(mpzPrime, char_rand, 10);
//gmp_printf("p=%Zd\n", mpzPrime);
//mpz_t p;
//mpz_init(p);
//CreateBigPrime(p, 1024);
/*mpz_t f;
mpz_init_set_str(f, "1000.00", 10);
int n = 0;*/
//test
mpz_t zero;
mpz_init_set_d(zero, 0);
//mpz_init_set_str(f_a1, "1000000", 10);
//int j = mpz_cmp(f_a1, zero);
mpz_init_set_d(f_a1, a1);//ʼ
mpz_init_set_d(f_a2, a2);
mpz_init_set_d(f_a3, a3);
//mpz_mul(zero, f_a1, f_a1);
//gmp_printf("p=%fd\n", f_a1);
mpz_t f_b1, f_b2, f_b3;
mpz_init_set_d(f_b1, b1);
mpz_init_set_d(f_b2, b2);
mpz_init_set_d(f_b3, b3);
mpz_t f_c1_temp1, f_c1_temp2, f_c1_temp3, f_c1_temp4;
mpz_init(f_c1_temp1); mpz_init(f_c1_temp2); mpz_init(f_c1_temp3); mpz_init(f_c1_temp4);
mpz_mul(f_c1_temp1, f_a2, f_b3);
//gmp_printf("fixed point mpz %Zd\t%Zd = %Zd\n", f_a2, f_a3, f_c1_temp1);
//long double C1 = a2*b3;
//long double C2 = a3 * b2;
//long double c1 = a2 * b3 - a3 * b2;
//long double c2 = -(a1 * b3 - b1 * a3);
//long double c3 = a1 * b2 - a2 * b1;
//ab * ac
mpz_t f_c1, f_c2, f_c3;
mpz_init(f_c1); mpz_init(f_c2); mpz_init(f_c3);
mpz_mul(f_c1_temp1, f_a2, f_b3);
//gmp_printf("c1: %Zd\t%Zd = %Zd\n", f_a2, f_b3, f_c1_temp1);
mpz_mul(f_c1_temp2, f_a3, f_b2);
//gmp_printf("c1: %Zd\t%Zd = %Zd\n", f_a3, f_b2, f_c1_temp2);
mpz_sub(f_c1, f_c1_temp1, f_c1_temp2);
//gmp_printf("_c1: %Zd\t%Zd = %Zd\n", f_c1, f_c1_temp1, f_c1_temp2);
mpz_mul(f_c1_temp1, f_a1, f_b3);
//gmp_printf("_c2: %Zd\t%Zd = %Zd\n", f_a1, f_b3, f_c1_temp1);
mpz_mul(f_c1_temp2, f_b1, f_a3);
//gmp_printf("_c2: %Zd\t%Zd = %Zd\n", f_b1, f_a3, f_c1_temp2);
mpz_sub(f_c2, f_c1_temp2, f_c1_temp1);
//gmp_printf("_c2: %Zd\t%Zd = %Zd\n", f_c2, f_c1_temp2, f_c1_temp1);
mpz_mul(f_c1_temp1, f_a1, f_b2);
//gmp_printf("_c3: %Zd\t%Zd = %Zd\n", f_c1_temp1, f_a1, f_b2);
mpz_mul(f_c1_temp2, f_a2, f_b1);
//gmp_printf("_c3: %Zd\t%Zd = %Zd\n", f_c1_temp2, f_a2, f_b1);
mpz_sub(f_c3, f_c1_temp1, f_c1_temp2);
//gmp_printf("_c3: %Zd\t%Zd = %Zd\n", f_c3, f_c1_temp1, f_c1_temp2);
b1 = cvGetReal2D(ap, 0, 0)*scale;
b2 = cvGetReal2D(ap, 1, 0)*scale;
b3 = cvGetReal2D(ap, 2, 0)*scale;
b1s = double2Char(b1);
b2s = double2Char(b2);
b3s = double2Char(b3);
/*double _c1 = a2 * b3 - a3 * b2;
double _c2 = -(a1 * b3 - b1 * a3);
double _c3 = a1 * b2 - a2 * b1;*/
mpz_init_set_d(f_b1, b1);
mpz_init_set_d(f_b2, b2);
mpz_init_set_d(f_b3, b3);
mpz_t _f_c1, _f_c2, _f_c3;
mpz_init(_f_c1); mpz_init(_f_c2); mpz_init(_f_c3);
mpz_mul(f_c1_temp1, f_a2, f_b3);
// gmp_printf("_c1: %Zd\t%Zd = %Zd\n", f_a2, f_b3, f_c1_temp1);
mpz_mul(f_c1_temp2, f_a3, f_b2);
//gmp_printf("_c1: %Zd\t%Zd = %Zd\n", f_a3, f_b2, f_c1_temp2);
mpz_sub(_f_c1, f_c1_temp1, f_c1_temp2);
//gmp_printf("_c1: %Zd\t%Zd = %Zd\n", f_c1_temp1, f_c1_temp2, _f_c1);
mpz_mul(f_c1_temp1, f_a1, f_b3);
//gmp_printf("_c2: %Zd\t%Zd = %Zd\n", f_a1, f_b3, f_c1_temp1);
mpz_mul(f_c1_temp2, f_b1, f_a3);
//gmp_printf("_c2: %Zd\t%Zd = %Zd\n", f_b1, f_a3, f_c1_temp2);
mpz_sub(_f_c2, f_c1_temp2, f_c1_temp1);
//gmp_printf("_c2: %Zd\t%Zd = %Zd\n", f_c1_temp2, f_c1_temp1, _f_c2);
mpz_mul(f_c1_temp1, f_a1, f_b2);
//gmp_printf("_c3: %Zd\t%Zd = %Zd\n", f_c1_temp1, f_a1, f_b2);
mpz_mul(f_c1_temp2, f_a2, f_b1);
mpz_sub(_f_c3, f_c1_temp1, f_c1_temp2);
//gmp_printf("_c3: %Zd\t%Zd = %Zd\n", _f_c3, f_c1_temp1, f_c1_temp2);
mpz_t res;
mpz_init(res);
mpz_mul(f_c1_temp1, f_c1, _f_c1);
mpz_mul(f_c1_temp2, f_c2, _f_c2);
mpz_mul(f_c1_temp3, f_c3, _f_c3);
mpz_add(f_c1_temp4, f_c1_temp1, f_c1_temp2);
mpz_add(res, f_c1_temp4, f_c1_temp3);
int i = mpz_cmp(res, zero);
mpz_clear(f_a1);
mpz_clear(f_a2);
mpz_clear(f_a3);
mpz_clear(f_b1);
mpz_clear(f_b2);
mpz_clear(f_b3);
mpz_clear(f_c1);
mpz_clear(f_c2);
mpz_clear(f_c3);
mpz_clear(_f_c1);
mpz_clear(_f_c2);
mpz_clear(_f_c3);
mpz_clear(f_c1_temp1);
mpz_clear(f_c1_temp2);
mpz_clear(f_c1_temp3);
mpz_clear(f_c1_temp4);
mpz_clear(zero);
mpz_clear(res);
return i;
}
| true |
0e43b55644858550b5d6714add4aba83e408887d | C++ | michlord/kurs_c | /c4/zadanie1/test/testgenerator.cpp | UTF-8 | 1,872 | 2.734375 | 3 | [] | no_license | #include <fstream>
#include <set>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
template<class T>
std::string toString(const T& t){
std::ostringstream s;
s << t;
return s.str();
}
int main()
{
const int test_case_amt = 15;
int test_case_size[test_case_amt] = {1,5,5,7,8,10,15,20,100,150,500,800,999,999,465};
std::set<int> set1;
std::set<int> set2;
std::vector<int> set_union;
std::vector<int> set_intersection;
std::ofstream out_in;
std::ofstream out_out;
std::string out_in_name;
std::string out_out_name;
for(int i=0;i<test_case_amt;++i)
{
out_in_name=toString(i)+"in.txt";
out_out_name=toString(i)+"out.txt";
set1.clear();set2.clear();set_union.clear();set_intersection.clear();
int set1_size = test_case_size[i];
int set2_size = 1+rand()%test_case_size[i]+3*(rand()%2);
while(set1.size()<set1_size)
set1.insert(rand()%(test_case_size[i]+15));
while(set2.size()<set2_size)
set2.insert(rand()%(test_case_size[i]+15));
std::set_union(set1.begin(),set1.end(),set2.begin(),set2.end(),back_inserter(set_union));
std::set_intersection(set1.begin(),set1.end(),set2.begin(),set2.end(),back_inserter(set_intersection));
out_in.open(out_in_name.c_str());
if(out_in.is_open()==false)
return -1;
out_in << set1.size() << '\n';
for(std::set<int>::iterator it=set1.begin();it!=set1.end();++it)
out_in << *it << ' ';
out_in << '\n' << set2.size() << '\n';
for(std::set<int>::iterator it=set2.begin();it!=set2.end();++it)
out_in << *it << ' ';
out_in.close();
out_out.open(out_out_name.c_str());
if(out_out.is_open()==false)
return -1;
for(int i=0;i<set_union.size();++i)
out_out << set_union[i] << ' ';
out_out << '\n';
for(int i=0;i<set_intersection.size();++i)
out_out << set_intersection[i] << ' ';
out_out.close();
}
return 0;
} | true |
1d554c3a8d55613379506614e2a9ef81393ee974 | C++ | dykieu/Text-Based-Console-Game | /Game Objects/Character Objects/hunter.cpp | UTF-8 | 9,665 | 3.46875 | 3 | [] | no_license | /*************************************************************
* Programmer: Dylan Kieu
* Date: 11/25/19
* Purpose: Hunter class defines the player character 'Hunter'
* Introduces special skills and a level up system
* that improves character stats throughout the game.
***************************************************************/
#include "hunter.hpp"
/***************************************************************
* Function: Hunter()
* Purpose: initializes variables for the Hunter Character
****************************************************************/
Hunter::Hunter()
{
//Character Stats
attack = "1D6";
defense = "1D6";
rank = 'E';
armor = 0;
health = 100;
mana = 100;
hpMax = health;
exp = 0;
//Spell variables
spellMultiplier = 1;
spellName = "Deadly Strike<I>";
//Item bonuses
wepDmg = 0;
armDef = 0;
//Items
wepEq = "empty";
armEq = "empty";
misc = "empty";
//Achievements:
killedBaran = 0;
}
/***************************************************************
* Function: inflictDmg()
* Purpose: Deals TRUE dmg to the Hunter(Traps within game).
****************************************************************/
void Hunter::inflictDmg(int dmg)
{
//IF damage exceeds the amount of health, prevents health from going negative
if (dmg >= health)
{
health = health - health;
cout << " due to the impact you take " << dmg << " damage." << endl;
cout << " [HP]: " << health << endl;
}
else if (health > dmg)
{
health = health - dmg;
cout << " due to the impact you take " << dmg << " damage." << endl;
cout << " [HP]: " << health << endl;
}
}
/***************************************************************
* Function: attacking()
* Purpose: Function for when hunter attacks. Allows the
* hunter to choose to use a normal attack or spell.
* Rolls for a normal attack or use a spell which
* does a flat damage + multiplier
****************************************************************/
int Hunter::attacking()
{
int choice;
Menu attMenu;
choice = attMenu.AttOrSpell();
//If user chooses to use a spell
if (choice == 2)
{
//If user has enough mana for the spell
if (mana >= 10)
{
//Uses spell and returns the dmg inflicted by the spell
cout << " You use " << spellName << endl;
mana = mana - 10;
return (25 * 1) + wepDmg;
}
cout << " No enought mana!" << endl;
cout << " **You use normal attacks instead" << endl;
}
//Attack damage + wep bonus
return die.rollDie(attack) + wepDmg;
}
/***************************************************************
* Function: defend()
* Purpose: Basic defense function that takes into account of
* def dice roll, armor, and any other reductions
* It prints out updated stats.
****************************************************************/
int Hunter::defend(int dmg)
{
//Rolls a dice for the def roll
int defRoll = die.rollDie(defense);
//If enemy can't get past your defense
if (dmg <= (defRoll + armor + armDef))
{
cout << " You block the attack" << endl;
return health;
}
//Calculates the total damage dealt by the enemy
int totaldmg = dmg - (defRoll + armor + armDef);
cout << " You take " << totaldmg << " damage"<< endl;
//If dmg exceeds hp
if (totaldmg >= health)
{
health = health - health;
cout << " [HP]: " << health << endl;
cout << " **You have died..." << endl;
return health;
}
//If your hp can handle the dmg
health = health - totaldmg;
cout << " [HP]: " << health << endl;
//If attack was just enough to make your hp reach 0
if (health == 0)
{
cout << " **You have died..." << endl;
return health;
}
return health;
}
/***************************************************************
* Function: recovery()
* Purpose: Allows user to recover hp (This is for the blood
* room).
****************************************************************/
void Hunter::recovery(int restore)
{
//If health is restored max the max, set it to max
if ((health + restore) > hpMax)
{
health = hpMax;
}
else
{
health = health + restore;
}
return;
}
/***************************************************************
* Function: level()
* Purpose: Function that updates the hunter's experience
* points. If the hunter is a certain rank and meets
* a exp threshold, they will level up. The function
* is ran 5 times in the case that exp exceeds multiple
* level thresholds.
****************************************************************/
void Hunter::level(int experience)
{
//Prints out how much exp was gained
cout << " gained " << experience << " exp" << endl;
exp = exp + experience;
//Loops through 5 times to make sure that all level ups are accounted for
int i = 5;
while (i > 0)
{
switch (rank)
{
//Rank up to D
case 'E':
//User levels up to rank D
if (exp >= 50)
{
//Updates stats
rank = 'D';
attack = "1D12";
defense = "1D12";
cout << "Congrats, you have ranked up!" << endl;
cout << " Rank: " << rank << endl;
i--;
}
i--;
break;
//Rank up to C
case 'D':
//User levels up to rank C
if (exp >= 100)
{
//Update stats
rank = 'C';
attack = "2D6";
defense = "2D6";
cout << "Congrats, you have ranked up!" << endl;
cout << " Rank: " << rank << endl;
i--;
}
i--;
break;
//Rank up to B
case 'C':
//User levels up to rank B
if (exp >= 200)
{
//Update Stats
rank = 'B';
attack = "2D10";
defense = "2D10";
spellMultiplier = 2;
cout << "Congrats, you have ranked up!" << endl;
cout << " Rank: " << rank << endl;
cout << " " << spellName << " has evolved into Deadly Strike<II>" << endl;
cout << " It will now deal more damage." << endl;
//Upgrades spell
spellName = "Deadly Strike[II]";
i--;
}
i--;
break;
//Rank up to A
case 'B':
//User levels up to rank A
if (exp >= 250)
{
//Update Stats
rank = 'A';
attack = "2D12";
defense = "2D12";
cout << "Congrats, you have ranked up!" << endl;
cout << " Rank: " << rank << endl;
i--;
}
i--;
break;
//Rank up to S
case 'A':
//User levels up to rank S
if (exp >= 400)
{
//Update Stats
rank = 'S';
attack = "3D99";
cout << "Congrats, you have ranked up!" << endl;
cout << " Rank: " << rank << endl;
cout << " " << spellName << " has evolved into Deadly Strike<III>" << endl;
cout << " It will now deal more damage." << endl;
//Upgrades spell
spellMultiplier = 5;
spellName = "Deadly Strike<III>";
i--;
}
i--;
break;
default:
i--;
break;
}
}
return;
}
//Returns hunter rank
char Hunter::getRank()
{
return rank;
}
//Returns hunter def dice
string Hunter::getDef()
{
return defense;
}
//Returns hunter health
int Hunter::getHp()
{
return health;
}
//Returns hunter mana
int Hunter::getMp()
{
return mana;
}
//Returns hunter armor
int Hunter::getArmor()
{
return armor;
}
//Returns hunter name
string Hunter::getname()
{
return name;
}
//sets hunter name
void Hunter::setname(string n)
{
name = n;
}
//Sets hunter mp
void Hunter::setMp(int value)
{
mana = value;
}
//Allows hunter to equip certain items
void Hunter::setEquipment(string wep, string armor, string miscItem)
{
//Sets the items
wepEq = wep;
armEq = armor;
misc = miscItem;
return;
}
//returns what weapon hunter is wearing
string Hunter::getWepEQ()
{
return wepEq;
}
//returns what armor hunter is wearing
string Hunter::getArmEQ()
{
return armEq;
}
//Returns any misc items the hunter is holding
string Hunter::getMisc()
{
return misc;
}
//If a weapon is equiped, change the bonus to match it
void Hunter::changeWep(int value)
{
wepDmg = value;
}
//if a armor is equipped, change the bonus to match
void Hunter::changeArmor(int value)
{
armDef = value;
}
//Trophy if hunter kills the finall boss
int Hunter::getBaran()
{
return killedBaran;
}
//Sets variable that indicates that user has killed baran
void Hunter::setBaran(int value)
{
killedBaran = value;
} | true |
f3ddc70542b71b619a33abfb982a8af2046ba9ac | C++ | davezli/Coursework | /cs246/project/dragon.cc | UTF-8 | 488 | 2.703125 | 3 | [] | no_license | #include "dragon.h"
using namespace std;
void Dragon::print() {
cout << 'D';
}
DragonGold * Dragon:: getDragonGold()
{
return dg;
}
Dragon::Dragon(int a, int b) {
x = a;
y = b;
type = "dragon";
dg = NULL;
hp = 150;
atk = 20;
def = 20;
moved = false;
}
Dragon::Dragon(int a, int b, DragonGold * drg) {
x = a;
y = b;
type = "dragon";
dg = drg;
hp = 150;
atk = 20;
def = 20;
moved = false;
}
Dragon::~Dragon() {}
| true |
3dab9f7fc822c7eb0ac6f9600edb1a35bcf36344 | C++ | kballard08/ThermalSolver | /ScriptReader.h | UTF-8 | 2,333 | 2.96875 | 3 | [] | no_license | /*
* ScriptReader.h
*
* Created on: Feb 27, 2013
* Author: kballard
*/
#ifndef SCRIPTREADER_H_
#define SCRIPTREADER_H_
#include <deal.II/base/exceptions.h>
#include <iterator>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace FEASolverNS
{
using namespace dealii;
class ScriptReader
{
public:
ScriptReader() {};
ScriptReader(std::string filePath);
~ScriptReader();
void open(std::string filePath);
// Return file indicates if the read was valid,
// false will be returned if the eof was reached
bool get_next_line(std::vector<std::string> &tokens);
private:
std::ifstream scriptFile;
}; // ScriptReader
ScriptReader::ScriptReader(std::string filePath)
{
open(filePath);
}
ScriptReader::~ScriptReader()
{
scriptFile.close();
}
void ScriptReader::open(std::string filePath)
{
// Assumes file exists, later add check to see if it exists
scriptFile.open(filePath.c_str());
if (!scriptFile) {
Assert(false, ExcMessage("File path passed to ScriptReader does not exist."))
}
std::cout << "Successfully open script: " << filePath << std::endl;
}
bool ScriptReader::get_next_line(std::vector<std::string> &tokens)
{
if (!scriptFile) {
Assert(false, ExcMessage("ScriptReader has tried to read the stream before a file has been opened."))
}
bool foundTokens = false;
while (!foundTokens) {
// Copy the line from the file to a string
std::string line;
getline(scriptFile, line);
// Test if there was an error
if (scriptFile.bad()) {
Assert(false, ExcMessage("Error when reading stream."))
}
// Check end of file
if (scriptFile.eof())
return false;
// Convert the line into tokens
std::istringstream ss(line);
std::istream_iterator<std::string> current(ss), end;
tokens.clear();
// Insert tokens but watch for comments (indicated by //)
while (current != end) {
// Test if the token contains the comment characters "//"
if ((*current).find("//") != std::string::npos)
break;
// Push back the token
tokens.push_back(*current);
// Increment iterator
current++;
}
// If there are no tokens then the line was just "/n" so get the next one
if (tokens.size() > 0)
foundTokens = true;
}
// get_next_line succeeded
return true;
}
} // namespace
#endif /* SCRIPTREADER_H_ */
| true |
7bca9f3c5d0d6079fd1fa72b647c55357afa2c4d | C++ | mtszpater/Uniwersytet-Wroclawski | /Kurs C++/Zad2/prosta.h | UTF-8 | 832 | 2.546875 | 3 | [] | no_license | //
// Created by Mateusz Pater on 09.03.2016.
//
#ifndef ZADANIE2_PROSTA_H
#define ZADANIE2_PROSTA_H
#include "wektor.h"
#include "punkt.h"
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <stdexcept>
#define EPSILON 0.0000000000001
class prosta{
double A;
double B;
double C;
void normal();
public:
prosta(punkt p1, punkt p2);
prosta(double A1, double B1, double C1);
prosta(wektor w, prosta k);
prosta(wektor w);
punkt przeciecie(prosta k);
bool wektor_prostopadly(wektor w);
bool wektor_rownolegly(wektor w);
bool rownolegle(prosta B);
bool prostopadle(prosta B);
double lezy(punkt p);
double return_a ();
double return_b ();
double return_c ();
};
#endif //ZADANIE2_PROSTA_H
| true |