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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2934922086d8ceb37e325d6d0d5d5408d238fd8e | C++ | gamecheung/framework | /Qt/XTextLengthEditor.h | UTF-8 | 1,814 | 2.859375 | 3 | [] | no_license | #ifndef _X_TEXT_LENGTH_EDITOR_H
#define _X_TEXT_LENGTH_EDITOR_H
#include <QComboBox>
#include <QSpinBox>
#include <QTextLength>
#include <Qt/XComboBoxHelper.h>
class XTextLengthEditor : public QObject
{
Q_OBJECT
signals:
void valueChanged(const QTextLength& value);
public:
XTextLengthEditor(QComboBox* combo,QSpinBox* spin)
:QObject(combo),m_combo(combo),m_spin(spin)
{
m_combo->addItem(tr("Variable"), QTextLength::VariableLength);
m_combo->addItem(tr("Fixed"), QTextLength::FixedLength);
m_combo->addItem(tr("Percent"), QTextLength::PercentageLength);
connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(updateSpinBox()));
connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(trigger()));
connect(m_spin, SIGNAL(valueChanged(int)), this, SLOT(trigger()));
}
QTextLength::Type type()const{ return (QTextLength::Type)m_combo->currentData().toInt(); }
public slots:
void setValue(const QTextLength& value)
{
if (value != this->value())
{
QSignalBlocker blocker(this);
XCOMBO_BOX_HELPER(m_combo)->setCurrentData(value.type());
m_spin->setValue(value.rawValue());
trigger();
}
}
QTextLength value()const
{
return QTextLength ((QTextLength::Type)m_combo->currentData().toInt(), m_spin->value());
}
void trigger()
{
emit valueChanged(value());
}
private slots:
void updateSpinBox()
{
switch (type())
{
case QTextLength::VariableLength:
m_spin->setEnabled(false);
break;
case QTextLength::FixedLength:
m_spin->setEnabled(true);
m_spin->setRange(1,99999);
m_spin->setSuffix("");
break;
case QTextLength::PercentageLength:
m_spin->setEnabled(true);
m_spin->setRange(1, 100);
m_spin->setSuffix("%");
break;
}
}
private:
QComboBox* m_combo;
QSpinBox* m_spin;
};
#endif //_X_TEXT_LENGTH_EDITOR_H
| true |
c2d0b72289a80bc1756827da0672d8aba34ce0bc | C++ | Zumisha/FPTL | /Testing/Arrays/ArrayGetErrors.cpp | UTF-8 | 5,071 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "../Shared.h"
namespace UnitTests
{
namespace Arrays
{
TEST(ArrayGetErrors, PositiveOOR)
{
const std::string innerCode = R"(@ = ((3 * 0).arrayCreate * 3).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 43, FPTL::Runtime::ArrayValue::badIndexMsg(3, 3));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, NegativeOOR)
{
const std::string innerCode = R"(@ = ((3 * 0).arrayCreate * -1).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 44, FPTL::Runtime::ArrayValue::badIndexMsg(3, -1));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, IntInsteadArray)
{
const std::string innerCode = R"(@ = (0 * 0).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 25, invalidOperation("int", "toArray"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, DoubleInsteadArray)
{
const std::string innerCode = R"(@ = (1.0 * 0).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 27, invalidOperation("double", "toArray"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, BoolInsteadArray)
{
const std::string innerCode = R"(@ = (true * 0).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 28, invalidOperation("boolean", "toArray"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, StringInsteadArray)
{
const std::string innerCode = R"(@ = ("Array[int]" * 0).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 36, invalidOperation("string", "toArray"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, ADTInsteadArray)
{
std::string innerCode = "@ = ((2*c_nil).c_cons * 0).arrayGet.print;";
innerCode = ListDefinition + MakeTestProgram(innerCode);
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 94, invalidOperation("List['t['t]]", "toArray"));
GeneralizedTest(standardInput, expected.str(), innerCode, 1);
}
TEST(ArrayGetErrors, DoubleIndex)
{
const std::string innerCode = R"(@ = ((3 * 0).arrayCreate * 0.0).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 45, invalidOperation("double", "toInt"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, BoolIndex)
{
const std::string innerCode = R"(@ = ((3 * 0).arrayCreate * true).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 46, invalidOperation("boolean", "toInt"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, StringIndex)
{
const std::string innerCode = R"(@ = ((3 * 0).arrayCreate * "1").arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 45, invalidOperation("string", "toInt"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, ArrayIndex)
{
const std::string innerCode = R"(@ = ((3 * 0).arrayCreate * (3 * 0).arrayCreate).arrayGet.print;)";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 61, invalidOperation("array[int]", "toInt"));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, ADTIndex)
{
std::string innerCode = "@ = ((3 * 0).arrayCreate * (2*c_nil).c_cons).arrayGet.print;";
innerCode = ListDefinition + MakeTestProgram(innerCode);
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 112, invalidOperation("List['t['t]]", "toInt"));
GeneralizedTest(standardInput, expected.str(), innerCode, 1);
}
TEST(ArrayGetErrors, OneArityInput)
{
const std::string innerCode = "@ = ((3 * 0).arrayCreate).arrayGet.print;";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 39, FPTL::Runtime::SExecutionContext::outOfRange(2, 1));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
TEST(ArrayGetErrors, ZeroArityInput)
{
const std::string innerCode = "@ = arrayGet.print;";
std::stringstream expected;
FPTL::Parser::Support::printPositionalMessage(expected, 1, 17, FPTL::Runtime::SExecutionContext::outOfRange(1, 0));
GeneralizedTest(standardInput, expected.str(), MakeTestProgram(innerCode), 1);
}
}
} | true |
9624fa34de2c53f4e5aa8de04520f9837dda1dd4 | C++ | AykanAkdag/rwth_infoprak1 | /Versuch05Teil2/ListElem.cpp | UTF-8 | 1,367 | 3.8125 | 4 | [] | no_license | /**
* @file ListElem.cpp
*
* @brief ListElem Class methods
*/
#include "ListElem.h"
ListElem::ListElem(const Student &s, ListElem* const nextPointer, ListElem* const prevPointer):
data(s), next(nextPointer), prev(prevPointer)
{
}
/**
* @brief Setter method for the 'data' variable of the ListElem class
*
* @param data_in Student Information
*/
void ListElem::setData(const Student &data_in)
{
data = data_in;
}
/**
* @brief Setter method for the 'next' pointer of the ListElem class
*
* @param cursor Next pointer specified by the cursor
*/
void ListElem::setNext(ListElem* const cursor)
{
next = cursor;
}
/**
* @brief Setter method for the 'prev' pointer of the ListElem class
*
* @param cursor Prev pointer specified by the cursor
*/
void ListElem::setPrev(ListElem* const cursor)
{
prev = cursor;
}
/**
* @brief Getter method for the 'data' variable of the ListElem class
*
* @return data Student information
*/
Student ListElem::getData() const
{
return data;
}
/**
* @brief Getter method for the 'next' pointer of the ListElem class
*
* @return next Next Element pointer
*/
ListElem* ListElem::getNext() const
{
return next;
}
/**
* @brief Getter method for the 'prev' pointer of the ListElem class
*
* @return prev Previous Element pointer
*/
ListElem* ListElem::getPrev() const
{
return prev;
}
| true |
030590bd6293eb172d1fbb03f7d3f2446d0a08e5 | C++ | yushroom/pat-basic | /1005.cpp | UTF-8 | 1,168 | 3.03125 | 3 | [] | no_license | // PAT 1005
//
// cpp by yunkang yu
#include <iostream>
using namespace std;
int num[100+5];
bool covered[100+5]; // is covered
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num[i];
covered[i] = false;
}
// bubble sort
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (num[i] < num[j]) {
int temp = num[j];
num[j] = num[i];
num[i] = temp;
}
}
}
for (int i = 0; i < n; i++) {
if (covered[i])
continue;
int a = num[i];
while (a != 1) {
if (a % 2 == 0)
a /= 2;
else a = (3*a + 1) / 2;
for (int j = 0; j < n; j++) {
if (i != j && a == num[j])
covered[j] = true;
}
}
}
bool first = true;
for (int i = 0; i < n; i++) {
if (!covered[i]) {
if (first) {
cout << num[i];
first = false;
}
else
cout << ' ' << num[i];
}
}
return 0;
}
| true |
deb3ff1360d6b7770009239a176c66e762e89c10 | C++ | bohaoist/OxSocket | /examples/mini_udp_client.cpp | UTF-8 | 334 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <OxSocket.h>
int main() {
char buf[255];
int bsize = 0;
std::string msg = "Hello World";
OxSocket::UDPClientSocket sock("127.0.0.1", 1234);
sock.send(msg.data(), msg.size());
bsize = sock.recv(buf, sizeof(buf));
std::cout << std::string(buf, bsize) << std::endl;
return 0;
}
| true |
3b44ddd1d840921ac7c996c9cd4a7487df4af59f | C++ | sotigr/CppGrades | /src/CsvReader.cpp | UTF-8 | 685 | 2.75 | 3 | [] | no_license | #include "CsvReader.h"
CsvReader::CsvReader(const char *filePath)
{
path = new char[strlen(filePath)];
strcpy(path, filePath);
}
CsvReader::~CsvReader()
{
delete [] path;
}
CSV_RESULT * CsvReader::read(const bool skipFirstLine)
{
CSV_RESULT * rows = new CSV_RESULT();
ifstream infile(path);
int bufferSize = 1024;
char line[bufferSize];
int cn = 0;
while( infile.getline( line, bufferSize ) )
{
if (!(skipFirstLine && cn == 0)) {
CString * str = new CString(line);
vector<CString*>* data = str->split(";");
rows->push_back(data);
}
cn++;
}
return rows;
}
| true |
d02e8d9bee0a823fd9bd6115da230bb60ef5f968 | C++ | LeptusHe/raytracer | /src/textures/imgtexture.cc | UTF-8 | 730 | 2.65625 | 3 | [] | no_license | #include "textures/imgtexture.h"
#include <fstream>
namespace leptus {
ImageTexture::ImageTexture(const std::string& image_path, const MappingPtr& mapper)
: image_(std::make_shared<Image>(image_path)), mapper_(mapper)
{ }
ImageTexture::ImageTexture(const ImagePtr& image, const MappingPtr& mapper)
: image_(image), mapper_(mapper)
{ }
Color ImageTexture::GetColor(const HitRecord& hit_rec) const
{
if (!mapper_) {
std::cout << "No mapper" << std::endl;
return Color(1.0f, 0.0f, 0.0f);
}
const Point3f& local_p_hit = hit_rec.local_p_hit_;
const Point2f& texture_coords = mapper_->GetTextureCoordinates(local_p_hit);
return image_->GetColor(texture_coords.x_, texture_coords.y_);
}
} // namespace leptus | true |
96be89a7774aaea934587746d18d53bf44112148 | C++ | POD153/C- | /li0102.cpp | UTF-8 | 202 | 3.21875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int sum(int x,int y)
{
int z;
z=x+y;
return z;
}
int main(void)
{
int a,b,c;
a=3;b=5;
c=sum(a,b);
cout<<c<<'\n';
return 0;
}
| true |
281f372b1235a878729b8659d63f1816f3dc5bca | C++ | izzyreal/vmpc-unreal-plugin | /VmpcPlugin/Source/ThirdParty/include/mpc/src/lcdgui/TwoDots.cpp | UTF-8 | 2,724 | 2.5625 | 3 | [] | no_license | #include <lcdgui/TwoDots.hpp>
#include <gui/Bressenham.hpp>
#include <Util.hpp>
using namespace mpc::lcdgui;
using namespace moduru::gui;
using namespace std;
TwoDots::TwoDots()
{
selected = vector<bool>(4);
visible = vector<bool>(4);
// for (int i = 0; i < 4; i++)
//visible[i] = true;
//SetDirty();
rect = MRECT(0, 0, 247, 50);
}
void TwoDots::setInverted(bool b)
{
inverted = b;
SetDirty();
}
void TwoDots::setSelected(int i, bool b)
{
selected[i] = b;
SetDirty();
}
void TwoDots::setVisible(int i, bool b)
{
visible[i] = b;
SetDirty();
}
void TwoDots::Draw(std::vector<std::vector<bool> >* pixels)
{
vector<vector<vector<int>>> lines;
vector<bool> colors;
for (int i = 0; i < 4; i++) {
if (selected[i]) {
color = inverted ? true : false;
} else {
color = inverted ? false : true;
}
if (i == 0 && visible[i]) {
if (inverted) {
color = true;
colors.push_back(color);
lines.push_back(Bressenham::Line(25, 19, 73, 19));
color = false;
}
colors.push_back(color);
lines.push_back(Bressenham::Line(37, 19, 37, 19));
colors.push_back(color);
lines.push_back(Bressenham::Line(55, 19, 55, 19));
}
else if (i == 1 && visible[i]) {
if (inverted) {
color = true;
colors.push_back(color);
lines.push_back(Bressenham::Line(96 + 25, 19, 114 + 55, 19));
color = false;
}
colors.push_back(color);
lines.push_back(Bressenham::Line(96 + 37, 19, 96 + 37, 19));
colors.push_back(color);
lines.push_back(Bressenham::Line(114 + 37, 19, 114 + 37, 19));
}
else if (i == 2 && visible[i]) {
if (inverted) {
color = true;
colors.push_back(color);
lines.push_back(Bressenham::Line(155 + 25, 21, 173 + 57, 21));
color = false;
}
colors.push_back(color);
lines.push_back(Bressenham::Line(155 + 37, 21, 155 + 37, 21));
colors.push_back(color);
lines.push_back(Bressenham::Line(173 + 37, 21, 173 + 37, 21));
}
else if (i == 3 && visible[i]) {
if (inverted) {
color = true;
colors.push_back(color);
lines.push_back(Bressenham::Line(155 + 25, 30, 173 + 57, 30));
color = false;
}
colors.push_back(color);
lines.push_back(Bressenham::Line(155 + 37, 30, 155 + 37, 30));
colors.push_back(color);
lines.push_back(Bressenham::Line(173 + 37, 30, 173 + 37, 30));
}
}
int xoff = 0;
int yoff = 0;
vector<int> offsetxy{ xoff, yoff };
mpc::Util::drawLines(pixels, &lines, colors);
dirty = false;
}
TwoDots::~TwoDots() {
}
| true |
38934395828c506e30527130091a462dc2cb7f8e | C++ | lucast98/Redes | /Trab 2 - Redes/Aplicacao.cpp | UTF-8 | 5,529 | 2.96875 | 3 | [] | no_license | /*
10345251 - Higor Tessari
10295180 - Lucas Tavares dos Santos
10716612 - Renan Peres Martins
10373663 - Renata Oliveira Brito
*/
/** Importamos as bibliotecas iostream pra realizar o fluxo de entrada e saída de dados*/
#include <iostream>
/** A biblioteca bits/stdc++ possui uma enorme quantidade de funções padroes, e por causa dela reduzimos o numero de importações*/
#include <bits/stdc++.h>
/** As bibliotecas util, EnlaceTransmissao e EnlaceRecepcao foram criadas por nos e utilizadas nesta etapa*/
#include "util.h"
#include "EnlaceTransmissao.h"
#include "EnlaceRecepcao.h"
using namespace std;
/** Função que converte os bits para uma string novamente, exibindo uma mensagem e a string recebida */
void AplicacaoReceptora(int quadro[], int tam){
int valorAscii, i;
//exibe mensagem
cout << "A mensagem recebida foi: ";
//converte binario para decimal
for (i = 0; i < tam; i++){
valorAscii = 0;
for (int j = 0; j < 8; j++)
valorAscii += pow(2, 7-j)*quadro[j+(8*i)]; //mais significativo a esquerda
cout << (char)valorAscii; //obtem caracetere
}
cout << endl;
}
/** Função que representa o meio de comunicação entre a aplicação transmissora e a receptora. Possui uma porcentagem de erro que deve
* ser alterada para testes.
*/
void MeioDeComunicacao (int fluxoBrutoDeBits[]){
//trabalhar com bits
int i = 0;
int porcentagemDeErros;
int fluxoBrutoDeBitsPontoA[tamBitMsg + CRC], fluxoBrutoDeBitsPontoB[tamBitMsg + CRC];
porcentagemDeErros = 0; //alterar valor
/** Fluxo no ponto a recebe o fluxo original */
for (i = 0; i < tamBitMsg + CRC; i++)
fluxoBrutoDeBitsPontoA[i] = fluxoBrutoDeBits[i]; //salva o fluxo original de bits em um vetor auxiliar
fill(fluxoBrutoDeBitsPontoB, fluxoBrutoDeBitsPontoB+tamBitMsg+CRC, 0); //zera o vetor para limpar lixo de memoria
for (i = 0; i < tamBitMsg + CRC; i++){
if (rand()%100 >= porcentagemDeErros) //numero aleatorio deve ser maior ou igual a porcentagem de erros
fluxoBrutoDeBitsPontoB[i] += fluxoBrutoDeBitsPontoA[i];
else{ //caso contrario, verifica se o bit do fluxo ponto b é 0.
//Caso seja, passará 1 para o fluxo do ponto A. Caso não seja, passará 0 para o fluxo do ponto B.
fluxoBrutoDeBitsPontoB[i] == 0 ?
fluxoBrutoDeBitsPontoA[i] = ++fluxoBrutoDeBitsPontoB[i]:
fluxoBrutoDeBitsPontoA[i] = --fluxoBrutoDeBitsPontoB[i];
}
}
//fluxo original recebe recebe o fluxo com possiveis erros
for (i = 0; i < tamBitMsg + CRC; i++)
fluxoBrutoDeBits[i] = fluxoBrutoDeBitsPontoA[i];
}//fim do metodo MeioDeComunicacao
/** Função que representa a camada fisica transmissora. Responsavel por realizar a comunicacao com o meio de comunicacao */
void CamadaFisicaTransmissora(int quadro[]){
MeioDeComunicacao(quadro); //chama o meio de comunicacao
}//fim do metodo CamadaFisicaTransmissora
/** Função responsavel por transformar os caracteres da string em binarios (bits) */
void CamadaDeAplicacaoTransmissora(string *mensagem, int quadro[]){
int aux[8];
int valorAscii = 0, k = 0;
//trabalhar com bits
for (int i = 0; i < (*mensagem).length(); i++){
valorAscii = (int)(*mensagem)[i]; //valor ascii do caractere
/** Aqui convertemo o numero decimal para binario */
for (int j = 7; j > 0; j--){
aux[j] = valorAscii % 2;
valorAscii = valorAscii / 2;
}
aux[0] = valorAscii;
cout << (*mensagem)[i] << ": "; //exibe o caractere
for (int j = 0; j < 8; j++){ //exibe o valor do bit do caractere
quadro[k] = aux[j];
cout << quadro[k];
k++;
}
cout << endl;
}
}//fim do metodo CamadaDeAplicacaoTransmissora
/** Função que representa a camada de enlace de dados transmissora */
void CamadaEnlaceDadosTransmissora (int quadro[], int tipoDeControleDeErro){
CamadaEnlaceDadosTransmissoraControleDeErro(quadro, tipoDeControleDeErro); //chama a função de controle de erros
}//fim do metodo CamadaEnlaceDadosTransmissora
/** Função que representa a aplicacao transmissora. Exibe uma mensagem e chama a camada de aplicacao transmissora. */
void AplicacaoTransmissora(string *mensagem, int quadro[]){
cout << "Digite uma mensagem: " << endl;
cin >> *mensagem;
CamadaDeAplicacaoTransmissora(mensagem, quadro); //chama a proxima camada
}//fim do metodo AplicacaoTransmissora
int main (void){
string mensagem;
int tipoDeControleDeErro = 2; /* determina o tipo de controle de erro a ser utilizado pela aplicacao de transmissao e recepcao.
0 = controle por bit de paridade par; 1 = controle por bit de paridade impar; 2 = controle por CRC */
int erro; //determina
int mensagemBit[tamBitMsg + CRC]; //representa os bits da mensagem
fill(mensagemBit, mensagemBit+tamBitMsg+CRC, 0); //preenche a variavel mensagemBit com 0 para evitar lixos de memoria
/** Aplicacao Transmissora */
AplicacaoTransmissora(&mensagem, mensagemBit);
CamadaEnlaceDadosTransmissora(mensagemBit, tipoDeControleDeErro);
/** Camada Fisica Transmissora */
CamadaFisicaTransmissora(mensagemBit);
/** Camada Fisica Receptora */
//CamadaFisicaReceptora(mensagemBit);
/** Aplicacao Receptora */
erro = CamadaEnlaceDadosReceptora(mensagemBit, tipoDeControleDeErro);
if (!erro) //se nao tiver erro
AplicacaoReceptora(mensagemBit, mensagem.length());
return 0;
}//fim da aplicação
| true |
db7d8dba756daa2599eeb819c8bb0f0fd32ae68c | C++ | Carlos-Santos-Altamirano/Trabajo_algoritmo | /partidos.cpp | UTF-8 | 2,064 | 3.171875 | 3 | [] | no_license | #include <iostream>
int matriz [5][4];
using namespace std;
void llenar();
void mostrar();
int multiplicar();
int suma();
int main(){
llenar();
mostrar();
multiplicar();
suma();
resultado(res);
}
int suma()
{
int i,c,res;
for (i=1;i<=5;i++)
{
for (c=1;c<=4;c++)
{
if(c=2)
{
res=res+matriz[i][c];
}
if(c=3)
}
}
}
int multiplicar()
{
int i,c;
for (i=1;i<=5;i++)
{
for (c=1;c<=4;c++)
{
if(c=2)
{
res=res+matriz[i][c];
}
}
}
cout<<"BARCELONA=1"<<endl;
cout<<"ATLETIC=2"<<endl;
cout<<"REAL MADRID=3"<<endl;
cout<<"GETAFE=4"<<endl;
cout<<"ALAVES=5"<<endl;
}
void mostrar()
{
int i,c;
for (i=1;i<=5;i++)
{
for (c=1;c<=4;c++)
{
}
}
}
void llenar()
{
int i,c,jugadas,ganadas,perdidas,empatadas;
for (i=0;i<5;i++)
{
switch (i)
{
case 1:
cout<<"BARCELONA"<<endl;
break;
case 2:
cout<<"ATLETICO"<<endl;
break;
case 3:
cout<<"REAL MADRID"<<endl;
break;
case 4:
cout<<"GETAFE"<<endl;
break;
case 5:
cout<<"ALAVES"<<endl;
break;
}
for(c=1;c<=4;c++)
{
switch (c)
{
case 1:
cout<<"Partidos jugados: ";
cin>>jugadas;
if(jugadas<1)
{
cout<<"No puedes ingresar numeros negativos: "<<endl;
}
else
{
matriz [i][c]=jugadas;
}
break;
case 2:
cout<<"Partidos ganados: ";
cin>>ganadas;
if(ganadas<1)
{
cout<<"No puedes ingresar numeros negativos: "<<endl;
}
else
{
matriz [i][c]=ganadas;
}
break;
case 3:
cout<<"Partidos perdidos: ";
cin>>perdidas;
if(perdidas<1)
{
cout<<"No puedes ingresar numeros negativos: "<<endl;
}
else
{
matriz [i][c]=perdidas;
}
case 4:
cout<<"Partidos empatados: ";
cin>>empatadas;
if(empatadas<1)
{
cout<<"no puedes ingresar numeros negativos: "<<endl;
}
else
{
matriz [i][c]=empatadas;
}
}
}
cout<<"\n";
}
}
| true |
df10e2fc5c5ed9b0741397acde8db0641c56a148 | C++ | shawwwn/YDWE | /Development/Editor/Core/ydbase/base/lua/make_range.h | UTF-8 | 1,556 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <base/config.h>
#include <base/lua/state.h>
namespace base { namespace lua {
template <class T>
int convert_to_lua(state* ls, const T& v);
template <class F, class S>
int convert_to_lua(state* ls, const std::pair<F, S>& v)
{
int nresult = 0;
nresult += convert_to_lua(ls, v.first);
nresult += convert_to_lua(ls, v.second);
return nresult;
}
template <class Iterator>
struct iterator
{
static int next(state* ls)
{
iterator* self = static_cast<iterator*>(ls->touserdata(lua_upvalueindex(1)));
if (self->first_ != self->last_)
{
int nreslut = convert_to_lua(ls, *self->first_);
++(self->first_);
return nreslut;
}
else
{
ls->pushnil();
return 1;
}
}
static int destroy(state* ls)
{
static_cast<iterator*>(ls->touserdata(1))->~iterator();
return 0;
}
iterator(const Iterator& first, const Iterator& last)
: first_(first)
, last_(last)
{ }
Iterator first_;
Iterator last_;
};
template <class Iterator>
int make_range(state* ls, const Iterator& first, const Iterator& last)
{
void* storage = ls->newuserdata(sizeof(iterator<Iterator>));
ls->newtable();
ls->pushcclosure(iterator<Iterator>::destroy, 0);
ls->setfield(-2, "__gc");
ls->setmetatable(-2);
ls->pushcclosure(iterator<Iterator>::next, 1);
new (storage) iterator<Iterator>(first, last);
return 1;
}
template <class Container>
int make_range(state* ls, const Container& container)
{
return make_range(ls, std::begin(container), std::end(container));
}
}}
| true |
0bf7ccb767050f2ac62d117f670085d215e69658 | C++ | nitsiey4u/CodeExercise | /LinearDS/shift_sort_arrays.cpp | UTF-8 | 4,870 | 3.96875 | 4 | [] | no_license | /***********************************************/
/***** Basic Array Related Problems **********/
/***********************************************/
#include <cstdio>
#include <cstdlib>
#include <algorithm>
// Class for array of shifting elements
class ShiftArray {
protected:
int* arr;
int size;
int usage;
public:
// Check if array reached max limit
bool isArrayFull(void) {
return (usage == size);
}
// Display elements of array - O(N)
void DisplayArray() {
fflush(stdout);
printf("\nValue:");
for(int index = 0; index < usage; index++) {
printf("\t%d", arr[index]);
}
printf("\nIndex:");
for(int index = 0; index < usage; index++) {
printf("\t%d", index);
}
}
// Insert element at specific index - O(N)
// Shift elements right --> (if already position occupied)
bool InsertElement(const int position, const int value) {
bool retval = false;
if(isArrayFull()) {
printf("\nArray is full cannot insert %d", value);
} else {
if((position < 0)||(position > usage)) {
printf("\nInvalid index %d cannot insert %d", position, value);
} else {
// Traverse reverse from Usage to Position <--
for(int index = usage; index > position; index--) {
// Copy left element to current index
arr[index] = arr[index - 1];
}
arr[position] = value;
printf("\nInserted element at %d: %d", position, value);
usage++;
retval = true;
}
}
return retval;
}
// Delete element at specific index - O(N)
// Shift elements left <-- (to reoccupy deleted element position)
bool DeleteElement(const int position) {
int maxsize = usage - 1;
bool retval = false;
if((position < 0) || (position > maxsize)) {
printf("\nInvalid index %d cannot delete", position);
} else {
const int value = arr[position];
if(position != maxsize) {
// Traverse forward from 0 to Position -->
for(int index = position; index < usage; index++) {
// Copy right element to current index
arr[index] = arr[index + 1];
}
}
printf("\nDeleted element at %d: %d", position, value);
usage --;
retval = true;
}
return retval;
}
// Constructor for allocating array
ShiftArray(int count) {
size = count;
usage = 0;
arr = (int*) malloc(sizeof(int) * size);
}
// Destructor for de-allocating array
~ShiftArray() {
printf("\nFreeup");
free(arr);
arr = NULL;
}
};
// Class for array of sorted elements (derived from ShiftArray)
class SortArray : public ShiftArray {
int maxlimit;
public:
// Find closest (smaller) neighbour for element - O(LogN)
int ClosestNeighbour(int low, int high, int target) {
int retval = -1;
if(low <= high) {
int mid = low + (high - low) / 2;
if(arr[mid] == target) {
return mid;
} else if (target < arr[mid]) {
retval = ClosestNeighbour(low, (mid - 1), target);
} else {
retval = ClosestNeighbour((mid + 1), high, target);
}
// No neighbour found, check current < target
if((retval == -1) && (arr[mid] < target)) {
return mid;
}
} // End of if block
return retval;
}
// Insert element into sorted array - O(LogN + N)
bool AddElement(const int value) {
// Find correct index for inserting new value - O(LogN)
int index = ClosestNeighbour(0, (usage - 1), value);
if(index == -1) {
// Array empty or lowest index available
index = 0;
} else if(index == 0) {
// To insert first, compare with existing element
index = (value < arr[0]) ? 0 : 1;
} else if(index == (usage - 1)) {
// To insert last, compare with existing element
index = (value < arr[usage - 1]) ? usage - 1 : usage;
} else {
// Lower index found, so insert at next index
index = index + 1;
}
// Insert value at found index - O(N)
return InsertElement(index, value);
}
// Delete element from sorted array - O(LogN + N)
bool RemoveElement(const int value) {
// Find exact index of element - O(LogN)
int index = ClosestNeighbour(0, (usage - 1), value);
// If element not found or closest neighbour found
if((index == -1)||(arr[index] != value)) {
printf("\nElement %d not found", value);
return false;
}
// Delete element at found index - O(N)
return DeleteElement(index);
}
// Constructor for SortArray and ShiftArray
SortArray(const int count) : ShiftArray(count) {
maxlimit = count;
}
};
int main () {
SortArray array(10);
int arr[] = {8, 10, 2, 4, 12, 9};
for(int index = 0; index < 6; index++) {
array.AddElement(arr[index]);
}
array.DisplayArray();
array.RemoveElement(12);
array.DisplayArray();
return 0;
}
| true |
2a9a87022ccc7001cb03ceadcff51357a699b55f | C++ | alecches/raytracer | /src/light/PointLight.h | UTF-8 | 563 | 3.046875 | 3 | [] | no_license | #pragma once
#include "../light/Light.h"
class PointLight : public Light
{
private:
Tuple position_;
Color intensity_;
public:
PointLight(Tuple p, Color c) :position_{ p }, intensity_{ c } {}
PointLight(const PointLight& pl) : position_{ pl.position() }, intensity_{ pl.intensity() } {}
Color intensity() const { return intensity_; }
Tuple position() const { return position_; }
bool operator==(const Light& l) const { return (position_ == l.position() && intensity_ == l.intensity()); }
Light* heapLight() const { return new PointLight(*this); }
};
| true |
061d8fc748c5d1819217151948cd89a29ec1d133 | C++ | arcsridhar/Programming-Practicum | /Stack/Stack.cpp | UTF-8 | 878 | 3.453125 | 3 | [] | no_license | // File Name: StackDriver.cpp
//
// Author: Jill Seaman
// Date: 4/14/2019
// Assignment Number: 6
// CS 2308.255 and CS 5301 Spring 2019
// Instructor: Jill Seaman
//
// A demo driver for Stack.
//
#include <iostream>
#include <cassert>
#include "Stack.h"
Stack :: Stack ()
{
head = NULL;
}
void Stack :: push(string x)
{
Node *newNode;
newNode = new Node;
newNode->value = x;
if(!isEmpty())
{
head = newNode;
newNode->next = NULL;
}
else
{
newNode->next = head;
head = newNode;
}
}
string Stack :: pop()
{
string result;
if(!isEmpty())
{
result = head->value;
Node *temp = head;
head = head->next;
delete temp;
}
return result;
}
bool Stack :: isEmpty()
{
if (head == NULL)
{
return true;
}
else
{
return false;
}
}
| true |
fcf740625cae23d85ba86805d9a5936387350bbb | C++ | MinorCollaboration/LINAL | /Framework/SDLFramework/SDLFramework/Linal/graphical3D/3dpoint.cpp | UTF-8 | 916 | 2.84375 | 3 | [] | no_license | #include "./3dpoint.h"
#include "../constants.h"
Linal::G3D::Point::Point() : xAxis(1), yAxis(1), zAxis(1)
{
}
Linal::G3D::Point::Point(double xAxis, double yAxis, double zAxis) : xAxis(xAxis), yAxis(yAxis), zAxis(zAxis)
{
}
Linal::G3D::Point::~Point()
{
}
Linal::G3D::Vector Linal::G3D::Point::ToVector()
{
return Linal::G3D::Vector(xAxis, yAxis, zAxis);
}
void Linal::G3D::Point::Draw(FWApplication *& application, int offsetX, int offsetY)
{
double sqrtZ = (zAxis < 0) ? -sqrt(+zAxis) * 2 : sqrt(zAxis) * 2;
double finalXAxis = xAxis + (sqrtZ - zAxis);
double finalYAxis = yAxis + (sqrtZ - zAxis);
application->DrawCircle(offsetX + (finalXAxis * Linal::FIELDWIDTH), offsetY - (finalYAxis * Linal::FIELDHEIGHT), Linal::POINTSIZE, true);
}
Linal::G3D::Vector operator*(const int & lhs, const Linal::G3D::Point & rhs)
{
return Linal::G3D::Vector(lhs * rhs.xAxis, lhs * rhs.yAxis, lhs * rhs.zAxis);
}
| true |
24aff28c94ed00bd0c1dc42ecaee8c24b240d559 | C++ | TerryBryant/MyLeetCode | /towards_offer/62_find_last_remain.cpp | UTF-8 | 1,299 | 3.9375 | 4 | [] | no_license | // 问题:将0,1,...n-1这n个数字排成一个圆圈,从数字0开始,每次从圆圈中删除第m个数字,求最后剩的那个数字
// 思路:该圆圈可以看成一个环形链表,于是问题就变成了环形链表中删节点的问题了
// 书上介绍的另一种方法,推了大半天,得到了一个递推公式,真的服了。。
int LastRemaining(unsigned int n, unsigned int m) {
if (n < 1 || m < 1) return -1;
unsigned int i = 0;
std::list<int> numbers;
for (int i = 0; i < n; ++i)
numbers.push_back(i);
auto current = numbers.begin();
while (numbers.size() > 1){
for (int i = 1; i < m; ++i) {
current++; // 移动到m处
if (current == numbers.end())
current = numbers.begin(); // 到了尾部就指向头部,这样就成了环形链表
}
auto next = ++current; // 先把下一个保存下来,免得current删掉之后找不到了
if (next == numbers.end())
next = numbers.begin();
--current;
numbers.erase(current);
current = next;
}
return *(current);
}
// 虽然推导了半天,但代码又简洁又高效,算法的力量!
int LastRemainning_2(unsigned int n, unsigned int m) {
if (n < 1 || m < 1) return -1;
int last = 0;
for (int i = 2; i <= n; ++i)
last = (last + m) % i;
return last;
}
| true |
0b757993c6f9a7fa40dba6b177cea0387a77afc0 | C++ | Thomas-WebDev/CSS503Project2 | /New/Shop.h | UTF-8 | 1,718 | 2.984375 | 3 | [] | no_license | #ifndef _SHOP_H_
#define _SHOP_H_
#include <pthread.h>
#include <queue>
using namespace std;
#define DEFAULT_CHAIRS 3
#define DEFAULT_BARBERS 1
class Shop {
public:
/*
Note that this is only a "starter" template provided for your convenience: Among other things,
you will need to add some private variables such as pthread_mutex_t and pthread_cond_t, etc. to
implement this Shop class as a monitor. Also, since there can be multiple barbers working on
multiple customers at the same time, you may consider using arrays or vectors of condition
variables, e.g., to ensure that a barber correctly signals the right customer when the haircut is
finished.
*/
Shop(int nBarbers, int nChairs); // initialize a Shop object with nBarbers and nChairs
Shop(); // initialize a Shop object with 1 barber and 3 chairs
int visitShop(int id); // return non-negative number (barber ID) only when a customer got service
void leaveShop(int customerId, int barberId);
void helloCustomer(int id);
void byeCustomer(int id);
int nDropsOff; // the number of customers dropped off
private:
const int max; // the max number of threads that can wait
int service_chair; // indicate the current customer thread id
bool in_service;
bool money_paid;
queue<int> waiting_chairs; // includes the ids of all waiting threads
pthread_mutex_t mutex;
pthread_cond_t cond_customers_waiting;
pthread_cond_t cond_customer_served;
pthread_cond_t cond_barber_paid;
pthread_cond_t cond_barber_sleeping;
static const int barber = 0; // the id of the barber thread
void init();
string int2string(int i);
void print(int person, string message);
};
#endif
| true |
3d7ce2c78d41d282511e8d8c4eb83ecac3ae2f89 | C++ | miguelmc/Online-Judge-Problems | /sepap/railroad.cpp | UTF-8 | 1,950 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n1, n2, *arr1, *arr2, *result, *temp1, *temp2;
cin >> n1 >> n2;
while(n1 || n2)
{
arr1 = new int[n1+1];
arr2 = new int[n2+1];
result = new int[n1+n2];
for(int i=0; i<n1; i++)
cin >> arr1[i];
for(int i=0; i<n2; i++)
cin >> arr2[i];
arr1[n1] = arr2[n2] = -1;
for(int i=0; i<n1+n2; i++)
cin >> result[i];
while(*arr1 != -1 || *arr2 != -1)
{
if(*arr1 == *result && *arr2 != *result)
{
++arr1;
++result;
}
else if(*arr2 == *result && *arr1 != *result)
{
++arr2;
++result;
}
else if(*arr1 == *result && *arr2 == *result)
{
temp1 = arr1;
temp2 = arr2;
while(*temp1 == *result && *temp2 == *result)
{
++temp1;
++temp2;
++result;
}
if(*temp1 == *result)
{
arr1 = temp1;
}
else if(*temp2 == *result)
{
arr2 = temp2;
}
else if(*temp1 == -1 && *temp2 == -1)
arr1 = temp1;
else if(*temp1 != -1 && *temp2 != -1)
{
arr1 = temp1;
arr2 = temp2;
}
else if(*temp1 == -1)
arr1 = temp1;
else
arr2 = temp2;
}
else
break;
}
if(*arr1 == -1 && *arr2 == -1)
cout << "possible" << endl;
else
cout << "not possible" << endl;
cin >> n1 >> n2;
}
return 0;
}
| true |
543b1a6fd01f3752c2d899cf1e2b869e828cb62f | C++ | impirios/CODE | /parabola.cpp | UTF-8 | 380 | 2.671875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char pa[6][100];
for(int i=0;i<6;i++)
{
for(int j=0;j<100;j++)
pa[i][j] = ':';
}
for(int i=0;(4*i*i)<=100;i++)
{
int j = 4*i*i;
if(i!=0){j--;}
pa[i][j] = '*';
}
for(int i=0;i<6;i++)
{
for(int j=0;j<100;j++)
cout<</*"["<<i<<"]["<<j<<"]"<<"="<<*/pa[i][j];
cout<<endl;
}
}
| true |
9827d7577150c29ba1c1d3e2ad79bb83bb339421 | C++ | team-charls/charls | /src/color_transform.h | UTF-8 | 4,587 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) Team CharLS.
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include "util.h"
namespace charls {
// This file defines simple classes that define (lossless) color transforms.
// They are invoked in process_line.h to convert between decoded values and the internal line buffers.
// Color transforms work best for computer generated images, but are outside the official JPEG-LS specifications.
template<typename T>
struct transform_none_impl
{
static_assert(std::is_integral_v<T>, "Integral required.");
using size_type = T;
FORCE_INLINE triplet<T> operator()(const int v1, const int v2, const int v3) const noexcept
{
return {v1, v2, v3};
}
FORCE_INLINE quad<T> operator()(const int v1, const int v2, const int v3, const int v4) const noexcept
{
return {v1, v2, v3, v4};
}
};
template<typename T>
struct transform_none final : transform_none_impl<T>
{
static_assert(std::is_integral_v<T>, "Integral required.");
using inverse = transform_none_impl<T>;
};
template<typename T>
struct transform_hp1 final
{
static_assert(std::is_integral_v<T>, "Integral required.");
using size_type = T;
struct inverse final
{
explicit inverse(const transform_hp1& /*template_selector*/) noexcept
{
}
FORCE_INLINE triplet<T> operator()(const int v1, const int v2, const int v3) const noexcept
{
return {static_cast<T>(v1 + v2 - range_ / 2), v2, static_cast<T>(v3 + v2 - range_ / 2)};
}
quad<T> operator()(int, int, int, int) const noexcept
{
ASSERT(false);
return {};
}
};
FORCE_INLINE triplet<T> operator()(const int red, const int green, const int blue) const noexcept
{
return {static_cast<T>(red - green + range_ / 2), static_cast<T>(green), static_cast<T>(blue - green + range_ / 2)};
}
quad<T> operator()(int, int, int, int) const noexcept
{
ASSERT(false);
return {};
}
private:
static constexpr size_t range_{1 << (sizeof(T) * 8)};
};
template<typename T>
struct transform_hp2 final
{
static_assert(std::is_integral_v<T>, "Integral required.");
using size_type = T;
struct inverse final
{
explicit inverse(const transform_hp2& /*template_selector*/) noexcept
{
}
FORCE_INLINE triplet<T> operator()(const int v1, const int v2, const int v3) const noexcept
{
const auto r{static_cast<T>(v1 + v2 - range_ / 2)};
return {r, static_cast<T>(v2), static_cast<T>(v3 + ((r + static_cast<T>(v2)) >> 1) - range_ / 2)};
}
quad<T> operator()(int, int, int, int) const noexcept
{
ASSERT(false);
return {};
}
};
FORCE_INLINE triplet<T> operator()(const int red, const int green, const int blue) const noexcept
{
return {static_cast<T>(red - green + range_ / 2), green, static_cast<T>(blue - ((red + green) >> 1) - range_ / 2)};
}
quad<T> operator()(int, int, int, int) const noexcept
{
ASSERT(false);
return {};
}
private:
static constexpr size_t range_{1 << (sizeof(T) * 8)};
};
template<typename T>
struct transform_hp3 final
{
static_assert(std::is_integral_v<T>, "Integral required.");
using size_type = T;
struct inverse final
{
explicit inverse(const transform_hp3& /*template_selector*/) noexcept
{
}
FORCE_INLINE triplet<T> operator()(const int v1, const int v2, const int v3) const noexcept
{
const auto g{static_cast<int>(v1 - ((v3 + v2) >> 2) + range_ / 4)};
return {static_cast<T>(v3 + g - range_ / 2), static_cast<T>(g), static_cast<T>(v2 + g - range_ / 2)};
}
quad<T> operator()(int, int, int, int) const noexcept
{
ASSERT(false);
return {};
}
};
FORCE_INLINE triplet<T> operator()(const int red, const int green, const int blue) const noexcept
{
const auto v2{static_cast<T>(blue - green + range_ / 2)};
const auto v3{static_cast<T>(red - green + range_ / 2)};
return {static_cast<T>(green + ((v2 + v3) >> 2) - range_ / 4), static_cast<T>(blue - green + range_ / 2),
static_cast<T>(red - green + range_ / 2)};
}
quad<T> operator()(int, int, int, int) const noexcept
{
ASSERT(false);
return {};
}
private:
static constexpr size_t range_{1 << (sizeof(T) * 8)};
};
} // namespace charls
| true |
93a3cc4b3648e7e292a7e69f5602e1d9625c6956 | C++ | wowns9270/code_up | /백준/다이나믹 프로그래밍/1520_내리막길.cpp | UTF-8 | 664 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int n, m;
int arr[501][501];
int dp[501][501];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
int gogo(int x, int y) {
if (x == n && y == m) return 1;
int& ret = dp[x][y];
if (ret != -1) return ret;
ret = 0;
for (int i = 0; i < 4; i++) {
int ux = x + dx[i];
int uy = y + dy[i];
if (ux < 1 || uy < 1 || ux > n || uy > m) continue;
if (arr[x][y] > arr[ux][uy]) {
ret += gogo(ux, uy);
}
}
return ret;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> arr[i][j];
}
}
memset(dp, -1, sizeof(dp));
cout << gogo(1, 1);
return 0;
} | true |
47765be8b8f94155abf9be6074fee51e9aace2b9 | C++ | pvdk276/Game_Rockman | /Game_Rockman/Game_Rockman/GameStateManager.cpp | UTF-8 | 1,282 | 2.515625 | 3 | [] | no_license | /*+===================================================================
File: GameStateManager.cpp
Summary: Định nghĩa các phương thức của CGameStateManager.
===================================================================+*/
#include "GameStateManager.h"
//#include "PlayState.h"
CGameStateManager* CGameStateManager::s_instance = nullptr;
CGameStateManager::CGameStateManager()
{
}
CGameStateManager::~CGameStateManager()
{
if (m_pCurrentState)
delete m_pCurrentState;
if (m_pNextState)
delete m_pNextState;
if (m_pResourceManager)
delete m_pResourceManager;
}
int CGameStateManager::Init(CBaseGameState* state)
{
m_pResourceManager = CResourcesManager::GetInstance();
m_pCurrentState = state;
return 1;
}
CBaseGameState* CGameStateManager::GetCurrentState()
{
if (m_pCurrentState->m_bFinished)
m_pCurrentState = m_aGameState[0];
return m_pCurrentState;
}
CGameStateManager* CGameStateManager::GetInstance()
{
if (s_instance == nullptr)
{
s_instance = new CGameStateManager();
}
return s_instance;
}
void CGameStateManager::ChangeState(CBaseGameState* state)
{
this->m_pNextState = state;
if (!m_aGameState.empty())
{
m_aGameState.pop_back();
}
m_aGameState.push_back(state);
CTimer::GetInstance()->StartCount();
}
| true |
6024cbfd62dec86da3912c0916e34982b11203ff | C++ | xaderil/Computer_Vision | /Ball.cpp | UTF-8 | 1,521 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "Ball.hpp"
int Ball::f = 940;
int Ball::H_MIN = 0;
int Ball::H_MAX = 256;
int Ball::S_MIN = 0;
int Ball::S_MAX = 256;
int Ball::V_MIN = 0;
int Ball::V_MAX = 256;
Ball::Ball(string Color) {
try {
JSON_Worker::readHSV();
} catch (exception err) {
JSON_Worker::writeHSVFile();
}
};
int Ball::getXPos() {
return this->xPos;
}
void Ball::setXPos(int x) {
this->xPos = x;
}
void Ball::setXRealPos(int x) {
this->XRealPos = x;
};
int Ball::getYPos() {
return this->yPos;
}
void Ball::setYPos(int y) {
this->yPos = y;
};
void Ball::setYRealPos(int y) {
this->YRealPos = y;
};
int Ball::getZDiameter() {
return this->zDiameter;
};
void Ball::setZDiameter(int z) {
this->zDiameter = z;
};
void Ball::setZRealPos(int z) {
this->ZRealPos = z;
};
/// Нахождение реального X объекта
void Ball::calculateXRealPos(int Frame_Width, int Frame_Height) {
float Cu = Frame_Width/2;
this->XRealPos = ((xPos-Cu)/f)*ZRealPos;
};
/// Нахождение реального Y объекта
void Ball::calculateYRealPos(int Frame_Width, int Frame_Height) {
float Cv = Frame_Height/2;
this->YRealPos = ((yPos-Cv)/f)*ZRealPos;
};
/// Нахождение реального Z объекта
void Ball::calculateZRealPos() {
float Z = (1/(this->zDiameter))*(this->f)*(this->d);
this->ZRealPos = Z;
};
float Ball::getXRealPos() {
return this->XRealPos;
};
float Ball::getYRealPos() {
return this->YRealPos;
};
float Ball::getZRealPos() {
return this->ZRealPos;
}; | true |
9d70f162b71ecfaf32cb4ffc508847a4b6bd7c0e | C++ | burkell530/Repository321 | /labs/Lab5/dl_node.cpp | UTF-8 | 520 | 2.8125 | 3 | [] | no_license | #include "dl_node.h"
DLNode::DLNode() {
mp_previous = NULL;
mp_next = NULL;
m_contents = 0;
}
DLNode::~DLNode() {
}
void DLNode::SetContents(int in_contents) {
m_contents = in_contents;
}
void DLNode::SetNext(DLNode* in_next) {
mp_next = in_next;
}
void DLNode::SetPrevious(DLNode* in_previous) {
mp_previous = in_previous;
}
int DLNode::GetContents() const {
return m_contents;
}
DLNode* DLNode::GetNext() const {
return mp_next;
}
DLNode* DLNode::GetPrevious() const {
return mp_previous;
}
| true |
761ed7e037e9575ce9f8979ba19d1ac3af59c118 | C++ | ParedesNahuel/Proyecto-POO | /tparchivos_lab2.cpp | UTF-8 | 1,223 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <ctime>
using namespace std;
#include "tipos.h"
#include "prototipos.h"
#include "funcionesmusicos.h"
int main ()
{
int op=1;
while (op!=0)
{
cout<< "MENU PRINCIPAL:"<<endl;
cout<< "=====================" <<endl;
cout << "1) MUSICOS:" <<endl;
cout<< "2) SESIONES: "<<endl;
cout<< "3) INSCRIPCION A SESIONES:" <<endl;
// cout<< "4) REPORTES: "<<endl;
cout<< "5) CONFIGURACION: " <<endl;
cout<< "0) FIN DEL PROGRAMA"<<endl;
cout<< "---------------------"<<endl;
cout<< "Seleccione una opcion: "<<endl;
cin>> op;
system("cls");
switch (op)
{
case 1:
menu_musicos();
break;
case 2:
menu_sesiones();
break;
case 3:
menu_inscripcion ();
break;
case 4:
break;
case 5:
menu_configuracion();
break;
case 0:
return 0;
break;
}
}
}
| true |
1293c0f44aa3cf2a5273977c1330dac825b56a12 | C++ | Viz108/Personal-Projects | /C++ Practice/ArrayDemo/main.cpp | UTF-8 | 1,724 | 3.6875 | 4 | [] | no_license | //
// ArrayDemo - demonstrate the use of an array
// to accumulate a sequence of numbers
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
// displayArray - displays the contents of the array
// of values of length nCount
void displayArray(int nValues[100], int nCount)
{
for(int i = 0; i <nCount; i++)
{
cout.width(3);p+
cout << i+1 << " - " << nValues[i] << endl;
}
}
// averageArray - averages the contents of an array
// of values of length nCount
int averageArray(int nValues[100], int nCount)
{
int nSum = 0;
for(int i = 0; i < nCount; i++)
{
nSum += nValues [i];
}
return nSum / nCount;
}
int main(int nNumberofArgs, char* pszArgs[])
{
int nScores[100];
int nCount;
// prompt the user for input
cout << "This program averages a set of scores\n"
<< "Enter scores to average\n"
<< "(enter a negative value to terminate input"
<< endl;
for(nCount = 0; nCount < 100; nCount++)
{
cout << "Next: ";
cin >> nScores[nCount];
if (nScores[nCount] < 0)
{
break;
}
}
// now output the results
cout << "Input terminated." << endl;
cout << "Input data:" << endl;
displayArray(nScores, nCount);
cout << "The average is "
<< averageArray(nScores, nCount)
<< endl;
// wait until the user is ready before terminating the program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
| true |
21a2e44143d2c4375a9147018b9b8aea5dcfab9a | C++ | arturobp3/DataStructures_And_Algorithms | /Ejercicios/63/63/Source.cpp | UTF-8 | 728 | 2.859375 | 3 | [] | no_license | // NOMBRE Y APELLIDOS
#include <iostream>
#include "bintree_ext.h"
#include <fstream>
using namespace std;
bool resuelveCaso() {
//Lee los datos
bintree_ext<int> arbol = leerArbol_ext(-1);
//Calcula el resultado
bool binario = arbol.esBinario();
if (binario){
cout << "SI" << endl;
}
else{
cout << "NO" << endl;
}
return true;
}
int main() {
// ajuste para que cin extraiga directamente de un fichero
#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif
int numCasos;
cin >> numCasos;
for (int i = 0; i < numCasos; ++i) {
resuelveCaso();
}
// restablecimiento de cin
#ifndef DOMJUDGE
std::cin.rdbuf(cinbuf);
system("pause");
#endif
return 0;
} | true |
b64da9828bf13f2624c0575195473588830f1293 | C++ | Andree6/LP1 | /Punteros/Laboratorio1.cpp | ISO-8859-10 | 441 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main (){
cout << "el tamao de char es " << sizeof(char) <<' '<<sizeof('a')<<'\n';
cout << "el tamao de int es " << sizeof(int) <<' '<<sizeof(2+2)<<'\n';
int* p=0;
cout << "el tamao de int* es " << sizeof(int*) <<' '<<sizeof(p)<<'\n';
vector<int> v(1000);
cout << "el tamao de vector<int>(1000) es " << sizeof(vector<int>) <<' '<<sizeof(v)<<'\n';
}
| true |
b99186dd8a9a5a07410ed31d84a9d81a6ff2fac7 | C++ | bhuman/BHumanCodeRelease | /Src/Modules/MotionControl/WalkingEngine/WalkGenerators/WalkAtSpeedEngine.cpp | UTF-8 | 3,586 | 2.828125 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* @file WalkAtSpeedEngine.cpp
*
* This file implements a module that provides walk generators.
*
* @author Arne Hasselbring
*/
#include "WalkAtSpeedEngine.h"
#include "Representations/MotionControl/MotionRequest.h"
MAKE_MODULE(WalkAtSpeedEngine, motionControl);
void WalkAtSpeedEngine::update(WalkAtAbsoluteSpeedGenerator& walkAtAbsoluteSpeedGenerator)
{
walkAtAbsoluteSpeedGenerator.createPhase = [this](const MotionRequest& motionRequest, const MotionPhase& lastPhase)
{
const Pose2f requestSpeed = motionRequest.walkSpeed;
const Vector2f useMaxSpeed(motionRequest.walkSpeed.translation.x() >= 0.f ? theWalkingEngineOutput.maxSpeed.translation.x() : std::abs(theWalkingEngineOutput.maxSpeedBackwards),
theWalkingEngineOutput.maxSpeed.translation.y());
const Pose2f speedScaling(std::abs(requestSpeed.rotation) / theWalkingEngineOutput.maxSpeed.rotation, motionRequest.walkSpeed.translation.array() / useMaxSpeed.array());
return createPhase(motionRequest.walkSpeed, speedScaling, lastPhase);
};
}
void WalkAtSpeedEngine::update(WalkAtRelativeSpeedGenerator& walkAtRelativeSpeedGenerator)
{
walkAtRelativeSpeedGenerator.createPhase = [this](const MotionRequest& motionRequest, const MotionPhase& lastPhase)
{
return createPhase(Pose2f(theWalkingEngineOutput.maxSpeed.rotation,
motionRequest.walkSpeed.translation.x() > 0.f ? theWalkingEngineOutput.maxSpeed.translation.x() : std::abs(theWalkingEngineOutput.maxSpeedBackwards), theWalkingEngineOutput.maxSpeed.translation.y()),
motionRequest.walkSpeed, lastPhase);
};
}
std::unique_ptr<MotionPhase> WalkAtSpeedEngine::createPhase(const Pose2f& walkTarget, const Pose2f& walkSpeed, const MotionPhase& lastPhase) const
{
Pose2f walkSpeedScaled = walkSpeed;
const float factor = std::abs(walkSpeedScaled.translation.x()) > 1.f || std::abs(walkSpeedScaled.translation.y()) > 1.f || std::abs(walkSpeedScaled.rotation) > 1.f ?
std::max(std::abs(walkSpeedScaled.rotation), std::max(std::abs(walkSpeedScaled.translation.x()), std::abs(walkSpeedScaled.translation.y()))) :
1.f;
walkSpeedScaled.rotation /= factor;
walkSpeedScaled.translation /= factor;
const bool isLeftPhase = theWalkGenerator.isNextLeftPhase(walkTarget.translation.y() != 0.f ? (walkTarget.translation.y() > 0.f) : (walkTarget.rotation > 0.f), lastPhase);
Pose2f stepTarget = walkTarget;
stepTarget.rotation = theWalkGenerator.getRotationRange(isLeftPhase, walkSpeedScaled).clamped(walkTarget.rotation * walkSpeedScaled.rotation);
std::vector<Vector2f> translationPolygon;
std::vector<Vector2f> translationPolygonNoCenter;
theWalkGenerator.getTranslationPolygon(isLeftPhase, stepTarget.rotation, lastPhase, walkSpeedScaled, translationPolygon, translationPolygonNoCenter, false);
Vector2f backRight(0.f, 0.f);
Vector2f frontLeft(0.f, 0.f);
for(const Vector2f& edge : translationPolygon)
{
backRight.x() = std::min(backRight.x(), edge.x());
backRight.y() = std::min(backRight.y(), edge.y());
frontLeft.x() = std::max(frontLeft.x(), edge.x());
frontLeft.y() = std::max(frontLeft.y(), edge.y());
}
stepTarget.translation.x() = walkSpeedScaled.translation.x() >= 0.f ? frontLeft.x() : backRight.x();
stepTarget.translation.y() = walkSpeedScaled.translation.y() >= 0.f ? frontLeft.y() : backRight.y();
if(isLeftPhase == (stepTarget.translation.y() < 0.f))
stepTarget.translation.y() = 0.f;
return theWalkGenerator.createPhase(stepTarget, lastPhase);
}
| true |
63c65a801101aba96a9fd3684627735019ffc72c | C++ | uicus/sbg2gdl | /src/gdl_constants.hpp | UTF-8 | 3,572 | 2.828125 | 3 | [] | no_license | #ifndef GDL_CONSTANTS
#define GDL_CONSTANTS
#include<string>
#include"types.hpp"
const std::string separator = ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n";
std::string player_name(bool uppercase);
std::string piece_name(char symbol, bool uppercase);
inline std::string player_name(bool uppercase){
return uppercase ? "uppercasePlayer" : "lowercasePlayer";
}
inline std::string piece_name(char symbol, bool uppercase){
return uppercase ? std::string("u")+char(toupper(symbol)) : std::string("l")+char(tolower(symbol));
}
inline std::string subsection(const std::string& title){
std::string result;
result += '\n' + separator;
result += ";; "+title+"\n";
result += separator+'\n';
return result;
}
inline uint length_of(uint v){
uint i;
for(i=0;v>>=1;++i);
return i+1;
}
inline std::string exist_at_least(uint quantity){
std::string result;
result += "(<= (existAtLeast"+std::to_string(quantity)+" ?piece)";
result += "\n\t(pieceType ?piece)";
result += "\n\t(true (cell ?x1 ?y1 ?piece))";
for(uint i=2;i<=quantity;++i){
result += "\n\t(true (cell ?x"+std::to_string(i)+" ?y"+std::to_string(i)+" ?piece))";
result += "\n\t(less ?x"+std::to_string(i)+" ?y"+std::to_string(i)+" ?x"+std::to_string(i-1)+" ?y"+std::to_string(i-1)+")";
}
result += ")\n";
return result;
}
const std::string digit = "(digit 0)\n(digit 1)\n";
/*inline std::string zero(uint max_number){
uint length = length_of(max_number);
std::string result = "(zero (number";
for(uint i=0;i<length;++i)result+=" 0";
result+="))\n";
return result;
}*/
inline std::string succ(const std::string& name, uint max_number, bool logarithmic){
std::string result;
if(logarithmic){
uint length = length_of(max_number);
for(uint i=0;i<length;++i){
if(i<length-1)
result+="(<= ";
result+="("+name;
for(uint j=length-1;j>i;--j)
result+=" ?x"+std::to_string(j);
result+=" 0";
for(uint j=i;j>0;--j)
result+=" 1";
//result+=") (number";
for(uint j=length-1;j>i;--j)
result+=" ?x"+std::to_string(j);
result+=" 1";
for(uint j=i;j>0;--j)
result+=" 0";
result+=")";
for(uint j=length-1;j>i;--j)
result+="\n\t(digit ?x"+std::to_string(j)+')';
if(i<length-1)
result+=')';
result+='\n';
}
}
else
for(uint i=1;i<=max_number;++i){
result += "("+name+' '+std::to_string(i)+' '+std::to_string(i+1)+")\n";
if(i%2==0)
result+= "("+name+"Even "+std::to_string(i)+")\n";
}
return result;
}
inline std::string number(uint n, uint max_number, bool logarithmic){
std::string result;
if(logarithmic){
uint length = length_of(max_number);
uint window = 1<<(length-1);
for(uint i=0;i<length;window>>=1,++i)
result+=((window&n) ? " 1" : " 0");
}
else
result += " "+std::to_string(n);
return result;
}
inline std::string variable(const std::string& base_name, uint max_number, bool logarithmic){
std::string result;
if(logarithmic){
uint length = length_of(max_number);
for(uint i=0;i<length;++i)
result += " ?"+base_name+std::to_string(i);
}
else
result += " ?"+base_name;
return result;
}
#endif
| true |
d62287a52d4033b3a3a2d122ce8e58e9b5c9688a | C++ | Wizmann/ACM-ICPC | /Codeforces/Codeforces Round #275 (Div. 2)/D.cc | UTF-8 | 3,978 | 3 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
#define input(x) cin >> x
#define print(x) cout << x << endl
class SegmentTree {
public:
SegmentTree(const vector<int>& ns): n(ns.size()) {
init(0, n - 1, ns);
}
int query(int l, int r) {
return do_query(0, l, r);
}
void add(int l, int r, int v) {
return do_add(0, l, r, v);
}
private:
struct SegmentTreeNode {
int l, r;
int lp, rp;
int lazy, update;
};
int init(int l, int r, const vector<int>& ns) {
tree.push_back(SegmentTreeNode());
int cur = tree.size() - 1;
tree[cur].l = l;
tree[cur].r = r;
tree[cur].lp = 0;
tree[cur].rp = 0;
tree[cur].update = 0;
if (l == r) {
tree[cur].lazy = ns[l];
tree[cur].lp = -1;
tree[cur].rp = -1;
} else {
int m = (l + r) >> 1;
int t1 = init(l, m, ns);
tree[cur].lp = t1;
int t2 = init(m + 1, r, ns);
tree[cur].rp = t2;
tree[cur].lazy = tree[tree[cur].lp].lazy & tree[tree[cur].rp].lazy;
}
assert(tree[cur].lp != 0 && tree[cur].rp != 0);
return cur;
}
void push_down(int cur) {
if (tree[cur].update) {
tree[tree[cur].lp].update |= tree[cur].update;
tree[tree[cur].lp].lazy |= tree[cur].update;
tree[tree[cur].rp].update |= tree[cur].update;
tree[tree[cur].rp].lazy |= tree[cur].update;
tree[cur].update = 0;
}
}
void push_up(int cur) {
tree[cur].lazy = tree[tree[cur].lp].lazy & tree[tree[cur].rp].lazy;
assert(tree[cur].update == 0);
}
int do_query(int cur, int l, int r) {
assert(tree[cur].l <= l && l <= r && r <= tree[cur].r);
if (l == tree[cur].l && r == tree[cur].r) {
return tree[cur].lazy;
}
push_down(cur);
int m = (tree[cur].l + tree[cur].r) >> 1;
int res = -999;
if (r <= m) {
res = do_query(tree[cur].lp, l, r);
} else if (l >= m + 1) {
res = do_query(tree[cur].rp, l, r);
} else {
res = do_query(tree[cur].lp, l, m) & do_query(tree[cur].rp, m + 1, r);
}
push_up(cur);
return res;
}
void do_add(int cur, int l, int r, int v) {
assert(tree[cur].l <= l && l <= r && r <= tree[cur].r);
if (l == tree[cur].l && r == tree[cur].r) {
tree[cur].update |= v;
tree[cur].lazy |= v;
return;
}
push_down(cur);
int m = (tree[cur].l + tree[cur].r) >> 1;
if (r <= m) {
do_add(tree[cur].lp, l, r, v);
} else if (l >= m + 1) {
do_add(tree[cur].rp, l, r, v);
} else {
do_add(tree[cur].lp, l, m, v);
do_add(tree[cur].rp, m + 1, r, v);
}
push_up(cur);
}
private:
int n;
vector<SegmentTreeNode> tree;
};
struct Query {
int l, r, v;
};
int main() {
int n, q;
input(n >> q);
vector<int> ns(n, 0);
auto tree = SegmentTree(ns);
vector<Query> qs;
int a, b, c;
for (int i = 0; i < q; i++) {
scanf("%d%d%d", &a, &b, &c);
a--;
b--;
qs.push_back({a, b, c});
tree.add(a, b, c);
}
bool flag = true;
for (int i = 0; i < q; i++) {
auto q = qs[i];
int u = tree.query(q.l, q.r);
if (u != q.v) {
flag = false;
break;
}
}
if (flag == false) {
puts("NO");
} else {
puts("YES");
for (int i = 0; i < n; i++) {
ns[i] = tree.query(i, i);
}
for (int i = 0; i < n; i++) {
printf("%d ", ns[i]);
}
puts("");
}
return 0;
}
| true |
c4d01d8effa6e256baaa99d604e4fe6d5daa1cbf | C++ | ladinu/CSClasses | /cs260/lab1/list.cpp | UTF-8 | 8,221 | 3.171875 | 3 | [] | no_license | #include "list.h"
list::node::node(const winery &awinery)
{
nextByName = NULL;
nextByRating = NULL;
item = winery();
item.copy(awinery);
}
list::list()
{
headByName = NULL;
headByRating = NULL;
}
list::~list()
{
node * current = NULL;
node * next = NULL;
current = headByName;
next = current -> nextByName;
while (next)
{
delete current;
current = next;
next = next -> nextByName;
}
if (current)
{
delete current;
}
current = NULL;
next = NULL;
headByName = NULL;
headByRating = NULL;
}
void list::displayByName(ostream& out) const
{
node * current = NULL;
current = headByName;
if (current)
{
current -> item.displayHeadings(out);
while (current)
{
out << &(current-> item) << endl;
current = current-> nextByName;
}
}
else
{
//out << "No items in lis";
}
return;
}
void list::displayByRating(ostream& out) const
{
node * current = NULL;
current = headByRating;
if (current)
{
current-> item.displayHeadings(out);
while (current)
{
out << &(current-> item) << endl;
current = current-> nextByRating;
}
}
else
{
//out << "No items in list";
}
return;
}
void list::insert(const winery& awinery)
{
node * tmpNode = new node(awinery);
if ( headByName && headByRating)
{
insertByRating (tmpNode);
insertByName (tmpNode);
}
else
{
headByName = tmpNode;
headByRating = tmpNode;
}
tmpNode = NULL;
return;
}
void list::insertByRating(node *&aNode)
{
node * current = NULL;
node * next = NULL;
int aNodeRating, currentRating, nextRating;
aNodeRating = aNode -> item.getRating();
current = headByRating;
next = current -> nextByRating;
// When only head is in list we only need one comparison
if ( (current == headByRating) && (!next) )
{
currentRating = headByRating -> item.getRating();
if (currentRating > aNodeRating)
{
headByRating -> nextByRating = aNode;
}
else if (currentRating < aNodeRating)
{
aNode -> nextByRating = headByRating;
headByRating = aNode;
}
// When they both have the same rating
else
{
int aNodeAcres = aNode -> item.getAcres();
int headAcres = headByName -> item.getAcres();
if (aNodeAcres < headAcres)
{
headByRating -> nextByRating = aNode;
}
else
{
aNode -> nextByRating = headByRating;
headByRating = aNode;
}
}
current = NULL;
}
while (current)
{
if (!next)
{
currentRating = headByRating -> item.getRating();
if (currentRating < aNodeRating)
{
aNode -> nextByRating = headByRating;
headByRating = aNode;
}
else
{
current -> nextByRating = aNode;
}
current = NULL;
}
else
{
currentRating = current -> item.getRating();
nextRating = next -> item.getRating();
//#TODO: What about when they are ==
if ( (aNodeRating < currentRating) && (aNodeRating > nextRating) )
{
current -> nextByRating = aNode;
aNode -> nextByRating = next;
current = NULL;
}
else
{
current = next;
next = current -> nextByRating;
}
}
}
return;
}
void list::insertByName(node *&aNode)
{
node * current = NULL;
node * next = NULL;
bool nameCmp;
const char * name = aNode-> item.getName();
const char * currName;
const char * nextName;
current = headByName;
next = current -> nextByName;
while (current)
{
// When there is only one node in list, you only
// need one comparison to figure out the order
if ( (current == headByName) && (!next) )
{
const char * headName = current -> item.getName();
if ( strcmp(name, headName) <= 0 )
{
aNode -> nextByName = current;
headByName = aNode;
}
else
{
current -> nextByName = aNode;
aNode -> nextByName = NULL;
}
// Because only one node was in list
current = NULL;
}
// When two or more nodes in list
else
{
if (next)
{
currName = current -> item.getName();
nextName = next -> item.getName();
nameCmp = ((strcmp(name, currName) >= 0) &&
(strcmp(name, nextName) <= 0));
if (nameCmp)
{
// Insert into list
aNode -> nextByName = next;
current -> nextByName = aNode;
// Wjen aNode is inseted break from loop
current = NULL;
}
else
{
current = next;
next = current -> nextByName;
}
}
else
{
const char * headName = headByName -> item.getName();
if (strcmp(name, headName) <= 0)
{
aNode -> nextByName = headByName;
headByName = aNode;
}
else
{
current -> nextByName = aNode;
}
current = NULL;
}
}
}
next = NULL;
return;
}
winery * const list::find(const char * const name) const
{
node * current = NULL;
winery * retVal = NULL;
current = headByName;
while (current)
{
if ( strcmp(current-> item.getName(), name) == 0 )
{
retVal = &(current-> item);
current = NULL;
}
else
{
current = current-> nextByName;
}
}
return retVal;
}
void list::getPrevNode(node *&prev, node *&query, node *&startPoint,int n)
{
node * current = startPoint;
prev = NULL;
while (current)
{
if (current == query)
{
current = NULL;
}
else
{
prev = current;
if (n == 1)
{
current = current -> nextByName;
}
else
{
current = current -> nextByRating;
}
}
}
return;
}
bool list::remove (const char * const name)
{
bool retVal = false;
node * nodeToDel = NULL;
node * current = headByName;
// Find the node to delete
while (current)
{
if (strcmp(current -> item.getName(), name) == 0)
{
nodeToDel = current;
current = NULL;
}
else
{
current = current -> nextByName;
}
}
// If the node is found delete it
if (nodeToDel)
{
node * prevByName = NULL;
node * prevByRate = NULL;
getPrevNode(prevByName, nodeToDel, headByName, 1);
getPrevNode(prevByRate, nodeToDel, headByRating, 0);
if (prevByName)
prevByName -> nextByName = nodeToDel -> nextByName;
else
headByName = headByName -> nextByName;
if (prevByRate)
prevByRate -> nextByRating = nodeToDel -> nextByRating;
else
headByRating = headByRating -> nextByRating;
delete nodeToDel;
nodeToDel = NULL;
}
return retVal;
}
| true |
e659dbf644eb7845c21c575502072caa43a50078 | C++ | okmonn/DirectX12_3D | /DirectX12_3D/DirectX12_3D/Texture.cpp | SHIFT_JIS | 27,409 | 2.515625 | 3 | [] | no_license | #include "Texture.h"
#include "WICTextureLoader12.h"
#include <sstream>
#include <tchar.h>
#pragma comment (lib,"d3d12.lib")
// RXgN^
Texture::Texture(std::weak_ptr<Device>dev) : dev(dev)
{
//WIC̏
CoInitialize(nullptr);
//Qƌ
result = S_OK;
//N
origin.clear();
//BMPf[^
bmp.clear();
//WICf[^
wic.clear();
//G[o͂ɕ\
#ifdef _DEBUG
ID3D12Debug *debug = nullptr;
result = D3D12GetDebugInterface(IID_PPV_ARGS(&debug));
if (FAILED(result))
int i = 0;
debug->EnableDebugLayer();
debug->Release();
debug = nullptr;
#endif
}
// fXgN^
Texture::~Texture()
{
for (auto itr = bmp.begin(); itr != bmp.end(); ++itr)
{
RELEASE(itr->second.vertex.resource);
RELEASE(itr->second.resource);
RELEASE(itr->second.heap);
}
for (auto itr = origin.begin(); itr != origin.end(); ++itr)
{
RELEASE(itr->second.resource);
RELEASE(itr->second.heap);
}
for (auto itr = wic.begin(); itr != wic.end(); ++itr)
{
itr->second.decode.release();
RELEASE(itr->second.vertex.resource);
RELEASE(itr->second.resource);
RELEASE(itr->second.heap);
}
}
// jR[hϊ
std::wstring Texture::ChangeUnicode(const CHAR * str)
{
//̎擾
auto byteSize = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED | MB_ERR_INVALID_CHARS, str, -1, nullptr, 0);
std::wstring wstr;
wstr.resize(byteSize);
//ϊ
byteSize = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED | MB_ERR_INVALID_CHARS, str, -1, &wstr[0], byteSize);
return wstr;
}
// ǂݍ
HRESULT Texture::LoadBMP(USHORT* index, std::string fileName)
{
for (auto itr = origin.begin(); itr != origin.end(); ++itr)
{
if (itr->first == fileName)
{
bmp[index] = itr->second;
return result;
break;
}
}
//BMPwb_[\
BITMAPINFOHEADER header = {};
//BMPt@Cwb_[
BITMAPFILEHEADER fileheader = {};
//t@C
FILE* file;
//t@CJ炭
if ((fopen_s(&file, fileName.c_str(), "rb")) != 0)
{
//G[io[mF
auto a = (fopen_s(&file, fileName.c_str(), "rb"));
std::stringstream s;
s << a;
OutputDebugString(_T("\nt@CJ܂łFs\n"));
OutputDebugStringA(s.str().c_str());
return S_FALSE;
}
//BMPt@Cwb_[ǂݍ
fread(&fileheader, sizeof(fileheader), 1, file);
//BMPwb_[ǂݍ
fread(&header, sizeof(header), 1, file);
//摜̕ƍ̕ۑ
origin[fileName].size = { header.biWidth, header.biHeight };
if (header.biBitCount == 24)
{
//f[^TCỸm(rbg̐[24bit̏ꍇ)
origin[fileName].data.resize(header.biWidth * header.biHeight * 4);
for (int line = header.biHeight - 1; line >= 0; --line)
{
for (int count = 0; count < header.biWidth * 4; count += 4)
{
//ԍ̔zԍ
UINT address = line * header.biWidth * 4;
origin[fileName].data[address + count] = 0;
fread(&origin[fileName].data[address + count + 1], sizeof(UCHAR), 3, file);
}
}
}
else if (header.biBitCount == 32)
{
//f[^TCỸm(rbg̐[32bit̏ꍇ)
origin[fileName].data.resize(header.biSizeImage);
for (int line = header.biHeight - 1; line >= 0; --line)
{
for (int count = 0; count < header.biWidth * 4; count += 4)
{
//ԍ̔zԍ
UINT address = line * header.biWidth * 4;
fread(&origin[fileName].data[address + count], sizeof(UCHAR), 4, file);
}
}
}
//t@C
fclose(file);
result = CreateShaderResourceView(index, fileName);
result = CreateVertex(index);
bmp[index] = origin[fileName];
return result;
}
// WICǂݍ
HRESULT Texture::LoadWIC(USHORT* index, std::wstring fileName)
{
result = DirectX::LoadWICTextureFromFile(dev.lock()->GetDevice(), fileName.c_str(), &wic[index].resource, wic[index].decode, wic[index].sub);
if (FAILED(result))
{
OutputDebugString(_T("\nWICeNX`̓ǂݍ݁Fs\n"));
return result;
}
result = CreateShaderResourceViewWIC(index);
result = CreateVertexWIC(index);
return result;
}
// fBXNv^[̃Zbg
void Texture::SetDescriptorBMP(USHORT * index)
{
//q[v̐擪nh擾
D3D12_GPU_DESCRIPTOR_HANDLE handle = bmp[index].heap->GetGPUDescriptorHandleForHeapStart();
//q[ṽZbg
dev.lock()->GetComList()->SetDescriptorHeaps(1, &bmp[index].heap);
//fBXNv^[e[ũZbg
dev.lock()->GetComList()->SetGraphicsRootDescriptorTable(1, handle);
}
// fBXNv^[̃Zbg
void Texture::SetDescriptorWIC(USHORT* index)
{
//q[v̐擪nh擾
D3D12_GPU_DESCRIPTOR_HANDLE handle = wic[index].heap->GetGPUDescriptorHandleForHeapStart();
//q[ṽZbg
dev.lock()->GetComList()->SetDescriptorHeaps(1, &wic[index].heap);
//fBXNv^[e[ũZbg
dev.lock()->GetComList()->SetGraphicsRootDescriptorTable(1, handle);
}
// 萔obt@p̃q[v̐
HRESULT Texture::CreateConstantHeap(USHORT* index, std::string fileName)
{
//q[vݒp\̂̐ݒ
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
desc.NodeMask = 0;
desc.NumDescriptors = 2;
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
//q[v
result = dev.lock()->GetDevice()->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&origin[fileName].heap));
if (FAILED(result))
{
OutputDebugString(_T("\neNX`̒萔obt@pq[v̐Fs\n"));
return result;
}
return result;
}
// 萔obt@̐
HRESULT Texture::CreateConstant(USHORT* index, std::string fileName)
{
result = CreateConstantHeap(index, fileName);
if (FAILED(result))
{
return result;
}
//q[vXe[gݒp\̂̐ݒ
D3D12_HEAP_PROPERTIES prop = {};
prop.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY::D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
prop.CreationNodeMask = 1;
prop.MemoryPoolPreference = D3D12_MEMORY_POOL::D3D12_MEMORY_POOL_L0;
prop.Type = D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_CUSTOM;
prop.VisibleNodeMask = 1;
//\[Xݒp\̂̐ݒ
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D;
desc.Width = origin[fileName].size.width;
desc.Height = origin[fileName].size.height;
desc.DepthOrArraySize = 1;
desc.Format = DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Flags = D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_NONE;
desc.Layout = D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_UNKNOWN;
//\[X
{
result = dev.lock()->GetDevice()->CreateCommittedResource(&prop, D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&origin[fileName].resource));
if (FAILED(result))
{
OutputDebugString(_T("\neNX`̒萔obt@p\[X̐Fs\n"));
return result;
}
}
return result;
}
// VF[_\[Xr[̐
HRESULT Texture::CreateShaderResourceView(USHORT* index, std::string fileName)
{
result = CreateConstant(index, fileName);
if (FAILED(result))
{
return result;
}
//VF[_\[Xr[ݒp\̂̐ݒ
D3D12_SHADER_RESOURCE_VIEW_DESC desc = {};
desc.Format = DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM;
desc.ViewDimension = D3D12_SRV_DIMENSION::D3D12_SRV_DIMENSION_TEXTURE2D;
desc.Texture2D.MipLevels = 1;
desc.Texture2D.MostDetailedMip = 0;
desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
//q[v̐擪nh擾
D3D12_CPU_DESCRIPTOR_HANDLE handle = origin[fileName].heap->GetCPUDescriptorHandleForHeapStart();
//VF[_[\[Xr[̐
dev.lock()->GetDevice()->CreateShaderResourceView(origin[fileName].resource, &desc, handle);
return S_OK;
}
// 萔obt@pq[v̐
HRESULT Texture::CreateConstantHeapWIC(USHORT* index)
{
//q[vݒp\̂̐ݒ
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
desc.NodeMask = 0;
desc.NumDescriptors = 2;
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
//q[v
{
result = dev.lock()->GetDevice()->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&wic[index].heap));
if (FAILED(result))
{
OutputDebugString(_T("\nWICeNX`̒萔obt@pq[v̐Fs\n"));
return result;
}
}
return result;
}
// VF[_\[Xr[̐
HRESULT Texture::CreateShaderResourceViewWIC(USHORT* index)
{
result = CreateConstantHeapWIC(index);
if (FAILED(result))
{
return result;
}
//VF[_\[Xr[ݒp\̂̐ݒ
D3D12_SHADER_RESOURCE_VIEW_DESC desc = {};
desc.Format = wic[index].resource->GetDesc().Format;
desc.ViewDimension = D3D12_SRV_DIMENSION::D3D12_SRV_DIMENSION_TEXTURE2D;
desc.Texture2D.MipLevels = 1;
desc.Texture2D.MostDetailedMip = 0;
desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
//q[v̐擪nh擾
D3D12_CPU_DESCRIPTOR_HANDLE handle = wic[index].heap->GetCPUDescriptorHandleForHeapStart();
//VF[_[\[Xr[̐
dev.lock()->GetDevice()->CreateShaderResourceView(wic[index].resource, &desc, handle);
return S_OK;
}
// _\[X̐
HRESULT Texture::CreateVertex(USHORT* index)
{
//q[vݒp\̂̐ݒ
D3D12_HEAP_PROPERTIES prop = {};
prop.Type = D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_UPLOAD;
prop.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY::D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
prop.MemoryPoolPreference = D3D12_MEMORY_POOL::D3D12_MEMORY_POOL_UNKNOWN;
prop.CreationNodeMask = 1;
prop.VisibleNodeMask = 1;
//\[Xݒp\̂̐ݒ
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = (sizeof(bmp[index].vertex.vertex));//((sizeof(v[index].vertex) + 0xff) &~0xff);
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = DXGI_FORMAT::DXGI_FORMAT_UNKNOWN;
desc.SampleDesc.Count = 1;
desc.Flags = D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_NONE;
desc.Layout = D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
//\[X
{
result = dev.lock()->GetDevice()->CreateCommittedResource(&prop, D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&bmp[index].vertex.resource));
if (FAILED(result))
{
OutputDebugString(_T("\neNX`̒_obt@p\[X̐Fs\n"));
return result;
}
}
//M͈
D3D12_RANGE range = { 0,0 };
//}bsO
{
result = bmp[index].vertex.resource->Map(0, &range, reinterpret_cast<void**>(&bmp[index].vertex.data));
if (FAILED(result))
{
OutputDebugString(_T("\n_p\[X̃}bsOFs\n"));
return result;
}
//_f[^̃Rs[
memcpy(bmp[index].vertex.data, &bmp[index].vertex.vertex, sizeof(bmp[index].vertex.vertex));
}
//_obt@ݒp\̂̐ݒ
bmp[index].vertex.view.BufferLocation = bmp[index].vertex.resource->GetGPUVirtualAddress();
bmp[index].vertex.view.SizeInBytes = sizeof(bmp[index].vertex.vertex);
bmp[index].vertex.view.StrideInBytes = sizeof(Vertex);
return result;
}
// _\[X̐
HRESULT Texture::CreateVertexWIC(USHORT* index)
{
//q[vݒp\̂̐ݒ
D3D12_HEAP_PROPERTIES prop = {};
prop.Type = D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_UPLOAD;
prop.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY::D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
prop.MemoryPoolPreference = D3D12_MEMORY_POOL::D3D12_MEMORY_POOL_UNKNOWN;
prop.CreationNodeMask = 1;
prop.VisibleNodeMask = 1;
//\[Xݒp\̂̐ݒ
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = sizeof(wic[index].vertex.vertex);//((sizeof(v[index].vertex) + 0xff) &~0xff);
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = DXGI_FORMAT::DXGI_FORMAT_UNKNOWN;
desc.SampleDesc.Count = 1;
desc.Flags = D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_NONE;
desc.Layout = D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
//\[X
{
result = dev.lock()->GetDevice()->CreateCommittedResource(&prop, D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&wic[index].vertex.resource));
if (FAILED(result))
{
OutputDebugString(_T("\neNX`̒_obt@p\[X̐Fs\n"));
return result;
}
}
//M͈
D3D12_RANGE range = { 0,0 };
//}bsO
{
result = wic[index].vertex.resource->Map(0, &range, reinterpret_cast<void**>(&wic[index].vertex.data));
if (FAILED(result))
{
OutputDebugString(_T("\nWIC_p\[X̃}bsOFs\n"));
return result;
}
}
//_f[^̃Rs[
memcpy(wic[index].vertex.data, &wic[index].vertex.vertex, sizeof(wic[index].vertex.vertex));
//_obt@ݒp\̂̐ݒ
wic[index].vertex.view.BufferLocation = wic[index].vertex.resource->GetGPUVirtualAddress();
wic[index].vertex.view.SizeInBytes = sizeof(wic[index].vertex.vertex);
wic[index].vertex.view.StrideInBytes = sizeof(Vertex);
return result;
}
// `揀
void Texture::SetDrawBMP(USHORT* index)
{
//{bNXݒp\̂̐ݒ
D3D12_BOX box = {};
box.back = 1;
box.bottom = bmp[index].size.height;
box.front = 0;
box.left = 0;
box.right = bmp[index].size.width;
box.top = 0;
//Tu\[Xɏ
{
result = bmp[index].resource->WriteToSubresource(0, &box, &bmp[index].data[0], (box.right * 4), (box.bottom * 4));
if (FAILED(result))
{
OutputDebugString(_T("\neNX`̃Tu\[Xւ̏݁Fs\n"));
return;
}
}
//q[ṽZbg
{
SetDescriptorBMP(index);
}
}
// `揀
void Texture::SetDrawWIC(USHORT* index)
{
//\[Xݒp\
D3D12_RESOURCE_DESC desc = {};
desc = wic[index].resource->GetDesc();
//{bNXݒp\̂̐ݒ
D3D12_BOX box = {};
box.back = 1;
box.bottom = desc.Height;
box.front = 0;
box.left = 0;
box.right = (UINT)desc.Width;
box.top = 0;
//Tu\[Xɏ
{
result = wic[index].resource->WriteToSubresource(0, &box, wic[index].decode.get(), wic[index].sub.RowPitch, wic[index].sub.SlicePitch);
if (FAILED(result))
{
OutputDebugString(_T("WICTu\[Xւ̏݁Fs\n"));
return;
}
}
//q[ṽZbg
{
SetDescriptorWIC(index);
}
}
// `
void Texture::DrawBMP(USHORT* index, Vector2<FLOAT>pos, Vector2<FLOAT>size)
{
bmp[index].vertex.vertex[0] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f}, {0.0f, 0.0f} };//
bmp[index].vertex.vertex[1] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f}, {1.0f, 0.0f} };//E
bmp[index].vertex.vertex[2] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f}, {1.0f, 1.0f} };//E
bmp[index].vertex.vertex[3] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f}, {1.0f, 1.0f} };//E
bmp[index].vertex.vertex[4] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f}, {0.0f, 1.0f} };//
bmp[index].vertex.vertex[5] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f}, {0.0f, 0.0f} };//
//_f[^̃Rs[
memcpy(bmp[index].vertex.data, &bmp[index].vertex.vertex, (sizeof(bmp[index].vertex.vertex)));
//_obt@ݒp\̂̐ݒ
bmp[index].vertex.view.BufferLocation = bmp[index].vertex.resource->GetGPUVirtualAddress();
bmp[index].vertex.view.SizeInBytes = sizeof(bmp[index].vertex.vertex);
bmp[index].vertex.view.StrideInBytes = sizeof(Vertex);
//_obt@r[̃Zbg
dev.lock()->GetComList()->IASetVertexBuffers(0, 1, &bmp[index].vertex.view);
//g|W[ݒ
dev.lock()->GetComList()->IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
SetDrawBMP(index);
//`
dev.lock()->GetComList()->DrawInstanced(6, 1, 0, 0);
}
// `
void Texture::DrawWIC(USHORT* index, Vector2<FLOAT> pos, Vector2<FLOAT> size)
{
wic[index].vertex.vertex[0] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ 0.0f, 0.0f } };//
wic[index].vertex.vertex[1] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ 1.0f, 0.0f } };//E
wic[index].vertex.vertex[2] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ 1.0f, 1.0f } };//E
wic[index].vertex.vertex[3] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ 1.0f, 1.0f } };//E
wic[index].vertex.vertex[4] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ 0.0f, 1.0f } };//
wic[index].vertex.vertex[5] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ 0.0f, 0.0f } };//
//_f[^̃Rs[
memcpy(wic[index].vertex.data, &wic[index].vertex.vertex, (sizeof(wic[index].vertex.vertex)));
//_obt@ݒp\̂̐ݒ
wic[index].vertex.view.BufferLocation = wic[index].vertex.resource->GetGPUVirtualAddress();
wic[index].vertex.view.SizeInBytes = sizeof(wic[index].vertex.vertex);
wic[index].vertex.view.StrideInBytes = sizeof(Vertex);
//_obt@r[̃Zbg
dev.lock()->GetComList()->IASetVertexBuffers(0, 1, &wic[index].vertex.view);
//g|W[ݒ
dev.lock()->GetComList()->IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
SetDrawWIC(index);
//`
dev.lock()->GetComList()->DrawInstanced(6, 1, 0, 0);
}
// `
void Texture::DrawRect(USHORT* index, Vector2<FLOAT> pos, Vector2<FLOAT> size, Vector2<FLOAT> rect, Vector2<FLOAT> rSize, bool turn)
{
if (turn == false)
{
bmp[index].vertex.vertex[0] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)bmp[index].size.width, rect.y / (FLOAT)bmp[index].size.height } };//
bmp[index].vertex.vertex[1] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)bmp[index].size.width, rect.y / (FLOAT)bmp[index].size.height } };//E
bmp[index].vertex.vertex[2] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)bmp[index].size.width, (rect.y + (FLOAT)rSize.y) / bmp[index].size.height } };//E
bmp[index].vertex.vertex[3] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)bmp[index].size.width, (rect.y + (FLOAT)rSize.y) / bmp[index].size.height } };//E
bmp[index].vertex.vertex[4] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)bmp[index].size.width, (rect.y + rSize.y) / (FLOAT)bmp[index].size.height } };//
bmp[index].vertex.vertex[5] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)bmp[index].size.width, rect.y / (FLOAT)bmp[index].size.height } };//
}
else
{
bmp[index].vertex.vertex[0] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)bmp[index].size.width, rect.y / (FLOAT)bmp[index].size.height } };//
bmp[index].vertex.vertex[1] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)bmp[index].size.width, rect.y / (FLOAT)bmp[index].size.height } };//E
bmp[index].vertex.vertex[2] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)bmp[index].size.width, (rect.y + rSize.y) / (FLOAT)bmp[index].size.height } };//E
bmp[index].vertex.vertex[3] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)bmp[index].size.width, (rect.y + rSize.y) / (FLOAT)bmp[index].size.height } };//E
bmp[index].vertex.vertex[4] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)bmp[index].size.width, (rect.y + (FLOAT)rSize.y) / bmp[index].size.height } };//
bmp[index].vertex.vertex[5] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)bmp[index].size.width, rect.y / (FLOAT)bmp[index].size.height } };//
}
//_f[^̃Rs[
memcpy(bmp[index].vertex.data, &bmp[index].vertex.vertex, (sizeof(bmp[index].vertex.vertex)));
//_obt@ݒp\̂̐ݒ
bmp[index].vertex.view.BufferLocation = bmp[index].vertex.resource->GetGPUVirtualAddress();
bmp[index].vertex.view.SizeInBytes = sizeof(bmp[index].vertex.vertex);
bmp[index].vertex.view.StrideInBytes = sizeof(Vertex);
//_obt@r[̃Zbg
dev.lock()->GetComList()->IASetVertexBuffers(0, 1, &bmp[index].vertex.view);
//g|W[ݒ
dev.lock()->GetComList()->IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
SetDrawBMP(index);
//`
dev.lock()->GetComList()->DrawInstanced(6, 1, 0, 0);
}
// `
void Texture::DrawRectWIC(USHORT* index, Vector2<FLOAT> pos, Vector2<FLOAT> size, Vector2<FLOAT> rect, Vector2<FLOAT> rSize, bool turn)
{
if (turn == false)
{
wic[index].vertex.vertex[0] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)(wic[index].resource->GetDesc().Width), rect.y / (FLOAT)(wic[index].resource->GetDesc().Height) } };//
wic[index].vertex.vertex[1] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)(wic[index].resource->GetDesc().Width), rect.y / (FLOAT)(wic[index].resource->GetDesc().Height) } };//E
wic[index].vertex.vertex[2] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)(wic[index].resource->GetDesc().Width), (rect.y + rSize.y) / (FLOAT)(wic[index].resource->GetDesc().Height) } };//E
wic[index].vertex.vertex[3] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)(wic[index].resource->GetDesc().Width), (rect.y + rSize.y) / (FLOAT)(wic[index].resource->GetDesc().Height) } };//E
wic[index].vertex.vertex[4] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)(wic[index].resource->GetDesc().Width), (rect.y + rSize.y) / (FLOAT)(wic[index].resource->GetDesc().Height) } };//
wic[index].vertex.vertex[5] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)(wic[index].resource->GetDesc().Width), rect.y / (FLOAT)(wic[index].resource->GetDesc().Height) } };//
}
else
{
wic[index].vertex.vertex[0] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)(wic[index].resource->GetDesc().Width), rect.y / (FLOAT)(wic[index].resource->GetDesc().Height) } };//
wic[index].vertex.vertex[1] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)(wic[index].resource->GetDesc().Width), rect.y / (FLOAT)(wic[index].resource->GetDesc().Height) } };//E
wic[index].vertex.vertex[2] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)(wic[index].resource->GetDesc().Width), (rect.y + rSize.y) / (FLOAT)(wic[index].resource->GetDesc().Height) } };//E
wic[index].vertex.vertex[3] = { { ((pos.x + size.x) / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ rect.x / (FLOAT)(wic[index].resource->GetDesc().Width), (rect.y + rSize.y) / (FLOAT)(wic[index].resource->GetDesc().Height) } };//E
wic[index].vertex.vertex[4] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - ((pos.y + size.y) / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)(wic[index].resource->GetDesc().Width), (rect.y + rSize.y) / (FLOAT)(wic[index].resource->GetDesc().Height) } };//
wic[index].vertex.vertex[5] = { { (pos.x / (FLOAT)(WINDOW_X / 2)) - 1.0f, 1.0f - (pos.y / (FLOAT)(WINDOW_Y / 2)), 0.0f },{ (rect.x + rSize.x) / (FLOAT)(wic[index].resource->GetDesc().Width), rect.y / (FLOAT)(wic[index].resource->GetDesc().Height) } };//
}
//_f[^̃Rs[
memcpy(wic[index].vertex.data, &wic[index].vertex.vertex, (sizeof(wic[index].vertex.vertex)));
//_obt@ݒp\̂̐ݒ
wic[index].vertex.view.BufferLocation = wic[index].vertex.resource->GetGPUVirtualAddress();
wic[index].vertex.view.SizeInBytes = sizeof(wic[index].vertex.vertex);
wic[index].vertex.view.StrideInBytes = sizeof(Vertex);
//_obt@r[̃Zbg
dev.lock()->GetComList()->IASetVertexBuffers(0, 1, &wic[index].vertex.view);
//g|W[ݒ
dev.lock()->GetComList()->IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
SetDrawWIC(index);
//`
dev.lock()->GetComList()->DrawInstanced(6, 1, 0, 0);
} | true |
2f1d80c9a1dfa910d5befeb922af8b99671eb45a | C++ | hrmay/project-euler | /pe10.cpp | UTF-8 | 570 | 3.734375 | 4 | [] | no_license | /**
Project Euler Problem 10: Summation of Primes
pe10.cpp
@author Evan May
*/
#include <cstdlib>
#include <iostream>
#include <vector>
#include "factor.cpp"
using namespace std;
int main() {
long long int sum = 0;
for (int i=2; i<2000000; i++) {
if (i%10000 == 0)
cout<<"Progress: "<<i<<" out of 2000000.\n";
if (i%2 == 1) {
vector<int> factors = factor(i);
if (factors.size() == 1)
sum += i;
}
}
sum += 2; //the loop ignores all even numbers even though 2's a prime, so add it now
cout<<"Sum of primes: "<<sum<<endl;
return sum;
}
| true |
bbacdd3633ba76a3e4739a82440620e907438126 | C++ | playbar/kaleido3d | /Source/Core/Os.h | UTF-8 | 6,875 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef __Os_h__
#define __Os_h__
#include <Interface/IIODevice.h>
#include <Config/OSHeaders.h>
#include <functional>
#include <map>
/**
* This module provides facilities on OS like:
* File,Directory,Socket,Threading
*/
namespace Os
{
class K3D_API File : public ::IIODevice
{
public:
File();
explicit File(const char *fileName);
~File();
bool Open(IOFlag flag);
bool Open(const char* fileName, IOFlag flag);
#if K3DPLATFORM_OS_WIN
bool Open(const WCHAR *fileName, IOFlag flag);
#endif
int64 GetSize();
bool IsEOF();
size_t Read(char *ptr, size_t len);
size_t Write(const void *ptr, size_t len);
bool Seek(size_t offset);
bool Skip(size_t offset);
void Flush();
void Close();
uint64 LastModified() const;
static File * CreateIOInterface();
private:
#ifdef K3DPLATFORM_OS_WIN
HANDLE m_hFile;
#else
int m_fd;
#endif
bool m_EOF;
int64 m_CurOffset;
const char *m_pFileName;
};
class K3D_API MemMapFile : public ::IIODevice
{
public:
MemMapFile();
~MemMapFile();
int64 GetSize();
//---------------------------------------------------------
bool Open(const char* fileName, IOFlag mode);
#if K3DPLATFORM_OS_WIN
bool Open(const WCHAR *fileName, IOFlag flag);
#endif
size_t Read(char * data_ptr, size_t len);
size_t Write(const void *, size_t);
bool Seek(size_t offset);
bool Skip(size_t offset);
bool IsEOF();
void Flush();
void Close();
//---------------------------------------------------------
//---------------------------------------------------------
/// FileData
/// \brief FileData
/// \return data const pointer
kByte* FileData() { return m_pData; }
template <class T>
/// Convert FileBlocks To Class
/// \brief ConvertToClass
/// \param address_of_file
/// \param object_offset
/// \return Object Pointer
static T* ConvertToClass(kByte * &address_of_file, uint32 object_offset)
{
kByte *objectptr = address_of_file + object_offset;
address_of_file += sizeof(T) + object_offset;
return reinterpret_cast<T*>(objectptr);
}
//---------------------------------------------------------
/// General Interface For GetIODevice
/// \brief CreateIOInterface
/// \return An IIODevice Pointer
static MemMapFile* CreateIOInterface();
private:
#ifdef K3DPLATFORM_OS_WIN
HANDLE m_FileHandle;
HANDLE m_FileMappingHandle;
#else
int m_Fd;
#endif
size_t m_szFile;
kByte * m_pData;
kByte * m_pCur;
};
extern K3D_API int Exec(const ::k3d::kchar * cmd, ::k3d::kchar *const *argv);
extern K3D_API bool MakeDir(const ::k3d::kchar * name);
extern K3D_API bool Exists(const ::k3d::kchar * name);
extern K3D_API void Sleep(uint32 ms);
extern K3D_API bool Copy(const ::k3d::kchar * src, const ::k3d::kchar * target);
extern K3D_API bool Remove(const ::k3d::kchar * name);
typedef void(*PFN_FileProcessRoutine)(const ::k3d::kchar * path, bool isDir);
extern K3D_API bool ListFiles(const ::k3d::kchar * srcPath, PFN_FileProcessRoutine);
extern K3D_API uint32 GetCpuCoreNum();
extern K3D_API float* GetCpuUsage();
enum class ThreadPriority
{
Low,
Normal,
High,
RealTime
};
enum class ThreadStatus
{
Ready,
Running,
Finish
};
struct MutexPrivate;
class K3D_API Mutex
{
public:
Mutex();
~Mutex();
void Lock();
void UnLock();
friend class ConditionVariable;
struct AutoLock
{
AutoLock()
{
m_Mutex = new Mutex;
m_Mutex->Lock();
}
explicit AutoLock(Mutex * mutex, bool lostOwnerShip = false)
: m_OnwerShipGot(lostOwnerShip)
, m_Mutex(mutex)
{
}
~AutoLock()
{
m_Mutex->UnLock();
if (m_OnwerShipGot)
{
delete m_Mutex;
m_Mutex = nullptr;
}
}
private:
bool m_OnwerShipGot;
Mutex *m_Mutex;
};
private:
MutexPrivate * m_Impl;
};
struct ConditionVariablePrivate;
class K3D_API ConditionVariable {
public:
ConditionVariable();
~ConditionVariable();
void Wait(Mutex * mutex);
void Wait(Mutex * mutex, uint32 milliseconds);
void Notify();
void NotifyAll();
ConditionVariable(const ConditionVariable &) = delete;
ConditionVariable(const ConditionVariable &&) = delete;
protected:
ConditionVariablePrivate * m_Impl;
};
class K3D_API Thread {
public:
// static functions
static void SleepForMilliSeconds(uint32_t millisecond);
//static void Yield();
static uint32_t GetId();
public:
typedef void * Handle;
typedef std::function<void()> Call;
Thread();
explicit Thread(std::string const & name, ThreadPriority priority = ThreadPriority::Normal);
explicit Thread(Call && callback, std::string const & name, ThreadPriority priority = ThreadPriority::Normal);
virtual ~Thread();
void SetPriority(ThreadPriority prio);
void Start();
void Join();
void Terminate();
ThreadStatus GetThreadStatus();
std::string GetName();
public:
static std::string GetCurrentThreadName();
static void SetCurrentThreadName(std::string const& name);
private:
Call m_ThreadCallBack;
std::string m_ThreadName;
ThreadPriority m_ThreadPriority;
uint32_t m_StackSize;
ThreadStatus m_ThreadStatus;
Handle m_ThreadHandle;
private:
static void* STD_CALL Run(void*);
static std::map<uint32, Thread*> s_ThreadMap;
};
class SockImpl;
class K3D_API IPv4Address
{
public:
explicit IPv4Address(const char* ip);
void SetIpPort(uint32 port);
IPv4Address * Clone() const;
private:
friend class Socket;
sockaddr_in m_Addr;
};
#if K3DPLATFORM_OS_WIN
typedef UINT_PTR SocketHandle;
#else
typedef int SocketHandle;
#endif
enum class SockStatus
{
Connected,
DisConnected,
Error
};
enum class SockType
{
TCP,
UDP,
RAW
};
enum class SoToOpt : uint32
{
Receive = 0,
Send = 1,
/*Connect = 2*/
};
class K3D_API Socket
{
public:
explicit Socket(SockType const & type);
virtual ~Socket();
bool IsValid();
void SetTimeOutOpt(SoToOpt opt, uint32 milleseconds);
void SetBlocking(bool block);
protected:
void Create();
void Bind(IPv4Address const & ipAddr);
void Listen(int maxConn);
virtual void Connect(IPv4Address const & ipAddr);
virtual void Close();
virtual SocketHandle Accept(IPv4Address & ipAddr);
virtual uint64 Receive(SocketHandle reomte, void * pData, uint32 recvLen);
virtual uint64 Send(SocketHandle remote, const char * pData, uint32 sendLen);
virtual uint64 Send(SocketHandle remote, std::string const & buffer);
SocketHandle GetHandle() { return m_SockFd; }
private:
SocketHandle m_SockFd;
SockType m_SockType;
#if K3DPLATFORM_OS_WIN
bool m_IsBlocking;
#endif
};
}
KTYPE_ISTYPE_TEMPLATE(Os::File, IIODevice);
KTYPE_ISTYPE_TEMPLATE(Os::MemMapFile, IIODevice);
#endif
| true |
ae051a59298f810a7c6a1183a41d144c0677220a | C++ | zzcym/NEUQ-ACM-Solution | /week1/王劲松/7-5.cpp | UTF-8 | 619 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
typedef struct {
int cx;
char a[1000];
}jgou;
int main(){
int n,m,i,cnt;
scanf("%d%d",&n,&m);
jgou xx[n];
for(i=0;i<n;i++){
scanf("%d%s",&xx[i].cx ,&xx[i].a );
}
for(cnt=1;m>0;m--){
int j,k;
scanf("%d%d",&j,&k);
if(xx[cnt-1].cx==0){
if(j==0){
cnt-=k;
}
else if(j==1){
cnt+=k;
}
for(;cnt>n;){
cnt-=n;
}
for(;cnt<1;){
cnt+=n;
}
}
else if(xx[cnt-1].cx ==1){
if(j==0){
cnt+=k;
}
else if(j==1){
cnt-=k;
}
for(;cnt>n;){
cnt-=n;
}
for(;cnt<1;){
cnt+=n;
}
}
}
printf("%s",xx[cnt-1].a);
return 0;
}
| true |
c9dad635ab1b3ba48b2b6f927b5843dda6136a0d | C++ | kevharvell/CompSci_I | /week5/Taxicab.cpp | UTF-8 | 1,582 | 3.796875 | 4 | [] | no_license | /*********************************************************************
** Author: Kevin Harvell
** Date: 2/3/2018
** Description:
** Taxicab class has three int data members to store
its current x- and y-coordinates and the total distance it has
driven so far(actual distance).
** Taxicab has a constructor that takes two parameters and uses them
to initialize the coordinates, and also initializes the distance
traveld to zero.
** Constructors will directly assign values to the data members instead
of calling set methods.
** Taxicab has a get method for each data member.
** Taxicab has a method moveX that takes an int parameter and tells
how far the Taxicab should shift left of right. moveY takes an int
parameter and tells how far the Taxicab should shift up or down.
*********************************************************************/
#include "Taxicab.hpp"
#include <cmath>
using std::abs;
// Default Taxicab constructor sets xPos, yPos, and totalDistance to zero
Taxicab::Taxicab()
{
xPos = 0;
yPos = 0;
totalDistance = 0;
}
// Constructor takes in 2 ints and passes them to xPos & yPos.
// Also initializes totalDistance to 0
Taxicab::Taxicab(int xPosIn, int yPosIn)
{
xPos = xPosIn;
yPos = yPosIn;
totalDistance = 0;
}
int Taxicab::getXCoord()
{
return xPos;
}
int Taxicab::getYCoord()
{
return yPos;
}
int Taxicab::getDistanceTraveled()
{
return totalDistance;
}
void Taxicab::moveX(int deltaX)
{
xPos += deltaX;
totalDistance += abs(deltaX);
}
void Taxicab::moveY(int deltaY)
{
yPos += deltaY;
totalDistance += abs(deltaY);
}
| true |
565db4945ea3c6780e42965b37a10f12b0f1d7ef | C++ | martinberlin/ESP32-S2 | /tests/protocols/http-client/main.cpp | UTF-8 | 2,419 | 2.921875 | 3 | [] | no_license |
#include "Arduino.h"
#include <WiFi.h>
#include <HTTPClient.h>
HTTPClient http;
// A very simple one liner PHP that just returns the time for this TZ
String url = "http://fs.fasani.de/time.php?tz=Europe/Berlin";
#define LED_GPIO 17 // Not important
int lostConnectionCount = 0;
#ifdef S2
void lostCon(arduino_event_id_t event) {
++lostConnectionCount;
Serial.printf("WiFi lost connection try %d to connect again\n", lostConnectionCount);
WiFi.begin(WIFI_SSID, WIFI_PASS);
if (lostConnectionCount==4) {
Serial.println("Cannot connect to the internet. Check your WiFI credentials");
delay(2000);
ESP.restart();
}
}
void online(){
digitalWrite(LED_GPIO, 1);
Serial.println("Online. Local IP address:");
Serial.println(WiFi.localIP().toString());
http.begin(url);
int httpCode = http.GET(); //Make the request
Serial.printf("http status:%d\n", httpCode);
if (httpCode == 200) {
String response = http.getString();
Serial.printf("The time now is: %s\n", response);
} else {
Serial.printf("We could not read the time.\nPlease check in the browser that the given url: %s is correct and replies with an HTTP 200 OK status", url);
}
}
void gotIP(arduino_event_id_t event) {
online();
}
#else // Then this is an ESP32
void gotIP() {
online();
}
#endif
void setup() {
Serial.begin(115200);
Serial.println("setup() started let's connect to WiFI");
Serial.printf("WiFi name: %s\nWiFi pass: %s\n", WIFI_SSID, WIFI_PASS);
// Start our connection attempt
WiFi.begin(WIFI_SSID, WIFI_PASS);
// Event driven WiFi callbacks for ESP32S2
// Let's use the event ID's so it works on both SoCs
// ARDUINO_EVENT_WIFI_STA_GOT_IP=7
// ARDUINO_EVENT_WIFI_STA_DISCONNECTED=5
// Sorry for the ugly cast, at the end is of course cleaner to use the constants that have the right type
#ifdef S2
WiFi.onEvent(gotIP, (arduino_event_id_t)7);
WiFi.onEvent(lostCon, (arduino_event_id_t)5);
#else
// No idea why trying to use the onEvent's w/ESP32 didn't work, was not being called, let's do it old way ;)
Serial.print("Connecting.");
uint8_t counter=0;
while (!WiFi.isConnected()) {
Serial.print(".");
delay(200);
++counter;
// Note at least with my router many times it stays in the loop and does not connect, restarting solves the issue
if (counter>20) {
ESP.restart();
}
}
gotIP();
#endif
}
void loop() {} | true |
2fd6b9eaf6903daf9bce9c7c87143546a7e3f211 | C++ | kotwani2883/Dsa-Daily-Practice | /Array/TripletWithGivenSum.cpp | UTF-8 | 718 | 2.6875 | 3 | [] | no_license | //Tripet with the given sum
/*Author-:Palak*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll t;
cin>>t;
while(t--)
{
ll n{},sum{};
cin>>n>>sum;
ll a[n];
for(ll i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
ll flag{0};
for(ll i=0;i<n-2;i++)
{
int low=i+1,high=n-1;
while(low<high)
{
if(a[i]+a[low]+a[high]==sum)
{
cout<<1<<endl;
flag=1;
break;
}
else if(a[i]+a[low]+a[high]<sum)
low++;
else
high--;
}
if(flag==1)
break;
}
if(flag!=1)
cout<<0<<endl;
}
return 0;
}
| true |
0db5193e6764b0ef2e373e908b5fb56dc43e5c49 | C++ | zeroplusone/AlgorithmPractice | /Leetcode/663. Equal Tree Partition.cpp | UTF-8 | 972 | 3.53125 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool checkEqualTree(TreeNode* root) {
int sum=presum(root);
return traverse(root->left, sum) || traverse(root->right, sum);
}
int presum(TreeNode* root) {
if(root==nullptr) {
return 0;
}
root->val=root->val+presum(root->left)+presum(root->right);
return root->val;
}
bool traverse(TreeNode* root, int& sum) {
if(root==nullptr) {
return false;
}
return root->val==sum-root->val || traverse(root->right, sum) || traverse(root->left, sum);
}
};
| true |
3c70335685a4c2d882f1151a2a37a2dca29e35a1 | C++ | siqiliu/FirstWebApp | /nearestWordGeneratorEnc.cpp | UTF-8 | 3,522 | 2.6875 | 3 | [] | no_license | #include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include <limits.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <chrono>
using namespace std;
int distT(string X, int m, string Y, int n)
{
int T[m+1][n+1] = { 0 };
for (int i = 1; i <=m ; i++)
{
T[i][0] = i;
}
for (int j = 1; j <= n; j++)
{
T[0][j] = j;
}
int cost;
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (tolower(X[i-1]) == tolower(Y[j-1]))
cost = 0;
else
cost = 1;
T[i][j] = min(min(T[i-1][j] + 1, T[i][j-1] + 1), T[i-1][j-1] + cost);
}
}
return T[m][n];
}
inline bool exists_test3 (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
int main(int argc, char **argv)
{
chrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now();
if (argc != 4)
{
cout << "input message wrong." << endl;
}
else
{
string inWord = argv[1];
string inDelta = argv[2];
string inNumber = argv[3];
int delta = stoi(inDelta);
int number = stoi(inNumber);
/*
#ifdef __linux__
string homeDir = getenv("HOME");
string downloadDir = homeDir + "/Downloads";
string wordsFile = downloadDir + "/words.txt";
#endif
#ifdef _WIN32
string homeDir = getenv("USERPROFILE");
string downloadDir = homeDir + "\\Downloads";
string wordsFile = downloadDir + "\\words.txt";
#endif
*/
ofstream outfile;
outfile.open("parseResultEnc.txt");
int count = 0;
string wordsFile = "words.txt";
if (exists_test3(wordsFile))
{
ifstream infile (wordsFile);
string line;
//vector<string> wordVec;
if (infile.is_open())
{
while (getline(infile,line))
{
//wordVec.push_back(line);
if (count == number)
{
break;
}
int len = line.length();
int inWordLen = inWord.length();
if (abs(len - inWordLen) <= delta)
{
if (distT(inWord, inWordLen, line, len) == delta)
{
cout << "\"" << line << "\"" << endl;
outfile << line;
outfile << "\n";
count++;
}
}
}
infile.close();
}
//string test = "Acarina";
//cout << distR(test, test.length(), inWord, inWord.length()) << endl;
//cout << distT(test, test.length(), inWord, inWord.length()) << endl;
outfile.close();
}
else
{
cout << "Please first download dictonary. " << endl;
}
}
chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>( t2 - t1 ).count();
cout << duration/1000 << " millisecond" << endl;
return 0;
}
| true |
ac80aae3bfcb025e0fb4fa2a87d6fb8f0ef080d9 | C++ | WPISmartmouse/Smartmouse_2017 | /test/Test.cpp | UTF-8 | 7,238 | 2.875 | 3 | [] | no_license | #include <common/AbstractMaze.h>
#include <common/Direction.h>
#include <console/ConsoleMaze.h>
#include <console/ConsoleMouse.h>
#include <common/Mouse.h>
#include <fstream>
#include <common/WallFollow.h>
#include <common/Flood.h>
#include <common/Node.h>
#include "gtest/gtest.h"
const char *FLOOD_SLN = "ESSSEESSWSSSEENNENESSEES";
const char *WALL_FOLLOW_SLN = "EEEEEEEEEWSNWSSNNWSSSEENENSWSESSEEENWWEENNNWSSWNSENNWNSENSENEEESSSSSSSSSSNNNNNWSSWWWSWWNNWWNNSSENNSSESSENNEEENSWWWSSENEEENNNWENWENWNSESSSENNNNNWSNWWSSSSSWWWNNWWWSNNNNWSSNWSWWWSEESENESNWSWSEWSSNNWSSSEENNENESSEES";
TEST(NodeTest, OutOfBoundsGetNode) {
AbstractMaze maze;
Node *n;
int status = maze.get_node(&n, -1, -1);
EXPECT_EQ(status, Node::OUT_OF_BOUNDS);
status = maze.get_node(&n, AbstractMaze::MAZE_SIZE, AbstractMaze::MAZE_SIZE);
EXPECT_EQ(status, Node::OUT_OF_BOUNDS);
}
TEST(NodeTest, InBoundsGetNode) {
AbstractMaze maze;
Node *n;
int status = maze.get_node(&n, 0, 0);
EXPECT_EQ(status, 0);
}
TEST(NeighborTest, NeighborTest) {
AbstractMaze maze;
Node *n;
int status = maze.get_node(&n, 0, 0);
EXPECT_EQ(status, 0);
Node *nSouth;
status = maze.get_node(&nSouth, 1, 0);
EXPECT_EQ(status, 0);
Node *neighbor = n->neighbor(Direction::S);
EXPECT_NE(nSouth, neighbor);
maze.connect_neighbor(0, 0, Direction::S);
neighbor = n->neighbor(Direction::S);
EXPECT_EQ(nSouth, neighbor);
}
TEST(NeighborTest, NeighborOfNeighborIsMyself) {
AbstractMaze maze;
maze.connect_all_neighbors(0, 0);
Node *myself;
Node *neighbor;
Node *neighborOfNeighbor;
int status = maze.get_node(&myself, 0, 0);
EXPECT_EQ(status, 0);
maze.connect_neighbor(0, 0, Direction::S);
neighbor = myself->neighbor(Direction::S);
ASSERT_NE(neighbor, (Node *)NULL);
neighborOfNeighbor = neighbor->neighbor(Direction::N);
EXPECT_EQ(myself, neighborOfNeighbor);
}
TEST(ConnectMazeTest, ConnectAllNeighbors) {
AbstractMaze maze;
maze.connect_all_neighbors_in_maze();
for (unsigned int i=0;i<AbstractMaze::MAZE_SIZE;i++){
for (unsigned int j=0;j<AbstractMaze::MAZE_SIZE;j++){
Node *n;
int status = maze.get_node(&n, i, j);
ASSERT_EQ(status, 0);
ASSERT_NE(n, (Node *)NULL);
if (i == 0) {
EXPECT_EQ(n->neighbor(Direction::N), (Node *)NULL);
if (j == 0) {
EXPECT_EQ(n->neighbor(Direction::W), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::E), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::S), (Node *)NULL);
}
else if (j == AbstractMaze::MAZE_SIZE - 1) {
EXPECT_EQ(n->neighbor(Direction::E), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::W), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::S), (Node *)NULL);
}
}
else if (i == AbstractMaze::MAZE_SIZE - 1) {
EXPECT_EQ(n->neighbor(Direction::S), (Node *)NULL);
if (j == 0) {
EXPECT_EQ(n->neighbor(Direction::W), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::E), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::N), (Node *)NULL);
}
else if (j == AbstractMaze::MAZE_SIZE - 1) {
EXPECT_EQ(n->neighbor(Direction::E), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::W), (Node *)NULL);
EXPECT_NE(n->neighbor(Direction::N), (Node *)NULL);
}
}
}
}
}
TEST(ConnectMazeTest, RemoveNeighbors) {
AbstractMaze maze;
maze.connect_all_neighbors_in_maze();
Node *n;
int status = maze.get_node(&n, 0, 0);
ASSERT_EQ(status, 0);
ASSERT_NE(n, (Node *)NULL);
Node *nSouth;
status = maze.get_node_in_direction(&nSouth, 0, 0, Direction::S);
ASSERT_EQ(status, 0);
ASSERT_NE(n, (Node *)NULL);
maze.remove_neighbor(0,0,Direction::S);
ASSERT_EQ(n->neighbor(Direction::S), (Node *)NULL);
ASSERT_EQ(nSouth->neighbor(Direction::N), (Node *)NULL);
}
TEST(FloodFillTest, EmptyMaze){
std::string maze_file = "../mazes/empty.mz";
std::fstream fs;
fs.open(maze_file, std::fstream::in);
ASSERT_TRUE(fs.good());
ConsoleMaze maze(fs);
Node *origin;
Node *center;
int status = maze.get_node(&origin, 0, 0);
ASSERT_EQ(status, 0);
status = maze.get_node(¢er,
AbstractMaze::MAZE_SIZE/2,
AbstractMaze::MAZE_SIZE/2);
ASSERT_EQ(status, 0);
bool success = false;
origin->assign_weights_to_neighbors(center, 0, &success);
for (unsigned int i=0;i<AbstractMaze::MAZE_SIZE;i++){
for (unsigned int j=0;j<AbstractMaze::MAZE_SIZE;j++){
Node *n;
status = maze.get_node(&n, i, j);
ASSERT_EQ(status, 0);
ASSERT_NE(n, (Node *)NULL);
EXPECT_EQ((signed int)(i+j), n->weight);
}
}
}
TEST(FloodFillTest, StripedMaze){
std::string maze_file = "../mazes/stripes.mz";
std::fstream fs;
fs.open(maze_file, std::fstream::in);
ASSERT_TRUE(fs.good());
ConsoleMaze maze(fs);
Node *origin;
Node *center;
int status = maze.get_node(&origin, 0, 0);
ASSERT_EQ(status, 0);
status = maze.get_node(¢er,
AbstractMaze::MAZE_SIZE/2,
AbstractMaze::MAZE_SIZE/2);
ASSERT_EQ(status, 0);
bool success = false;
origin->assign_weights_to_neighbors(center, 0, &success);
for (unsigned int i=0;i<AbstractMaze::MAZE_SIZE;i++){
for (unsigned int j=0;j<AbstractMaze::MAZE_SIZE;j++){
Node *n;
status = maze.get_node(&n, i, j);
ASSERT_EQ(status, 0);
ASSERT_NE(n, (Node *)NULL);
EXPECT_EQ((signed int)(i+j), n->weight);
}
}
}
TEST(SolveMazeTest, WallFollowSolve) {
std::string maze_file = "../mazes/16x16.mz";
std::fstream fs;
fs.open(maze_file, std::fstream::in);
ASSERT_TRUE(fs.good());
ConsoleMaze maze(fs);
ConsoleMouse::inst()->seedMaze(&maze);
WallFollow solver(ConsoleMouse::inst());
solver.setup();
char *solution = solver.solve();
solver.teardown();
ASSERT_NE(solution, (char *)NULL);
EXPECT_STREQ(WALL_FOLLOW_SLN, solution);
fs.close();
}
TEST(SolveMazeTest, FloodSolve) {
std::string maze_file = "../mazes/16x16.mz";
std::fstream fs;
fs.open(maze_file, std::fstream::in);
ASSERT_TRUE(fs.good());
ConsoleMaze maze(fs);
ConsoleMouse::inst()->seedMaze(&maze);
Flood solver(ConsoleMouse::inst());
solver.setup();
char *solution = solver.solve();
solver.teardown();
ASSERT_NE(solution, (char *)NULL);
EXPECT_STREQ(FLOOD_SLN, solution);
fs.close();
}
TEST(SolveMazeTest, RandSolve) {
for (int i=0; i < 100; i++) {
AbstractMaze maze = AbstractMaze::gen_random_legal_maze();
ConsoleMouse::inst()->seedMaze(&maze);
Flood solver(ConsoleMouse::inst());
solver.setup();
solver.solve();
solver.teardown();
ASSERT_TRUE(solver.isSolvable());
}
}
TEST(DirectionTest, DirectionLogic) {
EXPECT_TRUE(Direction::W > Direction::S);
EXPECT_TRUE(Direction::W > Direction::E);
EXPECT_TRUE(Direction::W > Direction::N);
EXPECT_TRUE(Direction::S > Direction::E);
EXPECT_TRUE(Direction::S > Direction::N);
EXPECT_TRUE(Direction::S < Direction::W);
EXPECT_TRUE(Direction::E > Direction::N);
EXPECT_TRUE(Direction::E < Direction::W);
EXPECT_TRUE(Direction::E < Direction::S);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
1342deaca36f2f27a007e7605daf2bb3c7b52999 | C++ | Sartech-B/Competitive-Programming | /CodeChef/p44.cpp | UTF-8 | 435 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string a;
cin>>a;
bool s = 0, f = 1;
for(int i=0; i<n; i++)
{
if(a[i]=='H')
{
if(s)
{
f = 0;
break;
}
s = 1;
}
if(a[i]=='T')
{
if(!s)
{
f = 0;
break;
}
s = 0;
}
}
if(s) f = 0;
if(f) cout<<"Valid"<<endl;
else cout<<"Invalid"<<endl;
}
} | true |
a939578db8af0cabf3a8a3bd83e3f9da8d9ec39f | C++ | Kanazawanaoaki/software-memo | /soft2/lec07/cpp/client.cpp | UTF-8 | 6,814 | 2.5625 | 3 | [] | no_license | #include "Quiz.hh"
#include <iostream>
/** Name is defined in the server */
#define SERVER_NAME "Quiz"
Quiz::QuizServer_ptr service_server;
using namespace std;
void insert_question(const char* sentence, int numAnswers, Quiz::Answer** answers, int numCorrectAnswers, CORBA::Char* correctAnswers);
void create_questions();
int main(int argc, char ** argv)
{
try {
//------------------------------------------------------------------------
// Initialize ORB object.
//------------------------------------------------------------------------
CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv);
//------------------------------------------------------------------------
// Resolve service
//------------------------------------------------------------------------
service_server = 0;
try {
//------------------------------------------------------------------------
// Bind ORB object to name service object.
// (Reference to Name service root context.)
//------------------------------------------------------------------------
CORBA::Object_var ns_obj = orb->resolve_initial_references("NameService");
if (!CORBA::is_nil(ns_obj)) {
//------------------------------------------------------------------------
// Bind ORB object to name service object.
// (Reference to Name service root context.)
//------------------------------------------------------------------------
CosNaming::NamingContext_ptr nc = CosNaming::NamingContext::_narrow(ns_obj);
//------------------------------------------------------------------------
// The "name text" put forth by CORBA server in name service.
// This same name ("MyServerName") is used by the CORBA server when
// binding to the name server (CosNaming::Name).
//------------------------------------------------------------------------
CosNaming::Name name;
name.length(1);
name[0].id = CORBA::string_dup(SERVER_NAME);
name[0].kind = CORBA::string_dup("");
//------------------------------------------------------------------------
// Resolve "name text" identifier to an object reference.
//------------------------------------------------------------------------
CORBA::Object_ptr obj = nc->resolve(name);
if (!CORBA::is_nil(obj)) {
service_server = Quiz::QuizServer::_narrow(obj);
}
}
} catch (CosNaming::NamingContext::NotFound &) {
cerr << "Caught corba not found" << endl;
} catch (CosNaming::NamingContext::InvalidName &) {
cerr << "Caught corba invalid name" << endl;
} catch (CosNaming::NamingContext::CannotProceed &) {
cerr << "Caught corba cannot proceed" << endl;
}
//------------------------------------------------------------------------
// Do stuff
//------------------------------------------------------------------------
if (!CORBA::is_nil(service_server)) {
cout << "QuizClient client is running ..." << endl;
orb->register_value_factory("IDL:Quiz/Answer:1.0", new Quiz::Answer_init());
create_questions();
//
// get random question
//
orb->register_value_factory("IDL:Quiz/Question:1.0", new Quiz::Question_init());
Quiz::Question* received_question = new OBV_Quiz::Question();
service_server->getQuestion(received_question);
const char* received_question_sentence = received_question->sentence();
CORBA::Long received_question_id = received_question->id();
Quiz::Question::AnswerSeq received_question_answers = received_question->answers();
int numAnswers = received_question_answers.length();
cout << "Received Question: id=" << received_question_id << ", sentence=" << received_question_sentence << endl;
for(int i = 0; i < numAnswers; i++) {
if(received_question_answers[i]) {
cout << "\t" << received_question_answers[i]->id() << ": " << received_question_answers[i]->sentence() << endl;
}
}
}
//------------------------------------------------------------------------
// Destroy OBR
//------------------------------------------------------------------------
orb->destroy();
} catch (CORBA::UNKNOWN) {
cerr << "Caught CORBA exception: unknown exception" << endl;
}
}
void insert_question(const char* sentence, int numAnswers, Quiz::Answer** answers, int numCorrectAnswers, CORBA::Char* correctAnswers)
{
Quiz::Question::AnswerSeq* answersSeq = new OBV_Quiz::Question::AnswerSeq(numAnswers, numAnswers, answers, 1);
Quiz::CompleteQuestion::CharSeq* correctAnswersSeq = new OBV_Quiz::CompleteQuestion::CharSeq(numCorrectAnswers, numCorrectAnswers, correctAnswers, 1);
Quiz::CompleteQuestion* new_question = new OBV_Quiz::CompleteQuestion(0, sentence, *answersSeq, *correctAnswersSeq);
CORBA::Long question_received_id = service_server->insertQuestion(new_question);
cout << "send question and received id " << question_received_id << endl;
}
void create_questions()
{
// create first question
const char* question_sentence = "It applies to a software layer that provides a programming abstraction as well as masking the heterogeneity of the underlying networks, hardware, operating systems and programming languages. What is it?";
Quiz::Answer** question0_answers = new Quiz::Answer*[3];
question0_answers[0] = new OBV_Quiz::Answer('a', "Hetereogenity");
question0_answers[1] = new OBV_Quiz::Answer('b', "Middleware");
question0_answers[2] = new OBV_Quiz::Answer('c', "Opennes");
CORBA::Char question0_correctAnswers[] = {'b'};
insert_question(question_sentence, 3, question0_answers, 1, question0_correctAnswers);
// create second question
question_sentence = "It refers to a running program (a process) on a networked computer that accepts requests from programs running on other computers to perform a service and responds appropriately.";
Quiz::Answer** question1_answers = new Quiz::Answer*[3];
question1_answers[0] = new OBV_Quiz::Answer('a', "Server");
question1_answers[1] = new OBV_Quiz::Answer('b', "Middleware");
question1_answers[2] = new OBV_Quiz::Answer('c', "Client");
CORBA::Char question1_correctAnswers[] = {'a'};
insert_question(question_sentence, 3, question1_answers, 1, question1_correctAnswers);
}
| true |
719dc83d78c13ba5bfa82e17055db5d51bee3e8b | C++ | TraurigeNarr/SupportSDK | /Sources/WorldInterfacing/PollingTask.h | UTF-8 | 1,233 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef __POLLING_TASK__
#define __POLLING_TASK__
#include "TypeDefines.h"
#include <functional>
namespace SDK
{
typedef std::function<ulong()> GetTickNumber;
template <typename PollingType>
struct MetaPollingTask
{
public:
typedef PollingType PollingType;
private:
uint m_task_code;
ulong m_last_updated;
GetTickNumber get_tick_number;
PollingType m_value;
private:
virtual void UpdateImpl() = 0;
public:
explicit MetaPollingTask(uint i_task_code)
: m_task_code(i_task_code)
, m_last_updated(0)
, m_value(0)
, get_tick_number(nullptr)
{}
virtual ~MetaPollingTask() {}
PollingType GetValue() const
{
if (IsStale()) const_cast<MetaPollingTask&>(*this).Update();
return m_value;
}
void SetValue(const PollingType& i_value) { m_value = i_value; }
void SetTickGetter(GetTickNumber i_getter) { get_tick_number = i_getter; }
bool IsStale() const
{ return get_tick_number == nullptr || m_last_updated < get_tick_number(); }
uint GetTaskCode() const { return m_task_code; }
void Update()
{
UpdateImpl();
if (get_tick_number)
m_last_updated = get_tick_number();
}
};
} //SDK
#endif | true |
70496a6ac95c28c8c7ee4b135bacdc8c72a1823b | C++ | abpprkonsalting/Salva_Red_VisualStudio_Cpp | /SyncFolder/Folder.cpp | WINDOWS-1250 | 57,328 | 3.109375 | 3 | [] | no_license | #include "stdafx.h"
#include "Common.h"
Folder::Folder(){
Files_hashed = FALSE;
hashing_algorithm = 0;
// Initialize the Folder object arrays.
Files.count = 0;
Files.items = NULL;
Subfolders.count = 0;
Subfolders.items = NULL;
Path = NULL;
Full_name = NULL;
Full_name_long = NULL;
return;
}
Folder::Folder(Folder* _Parent, class m_error** p_error) {
class m_error** p_error_t = p_error;
Path = NULL;
Full_name = NULL;
Full_name_long = NULL;
Files_hashed = FALSE;
hashing_algorithm = 0;
if (_Parent != NULL) {
Parent = _Parent;
class m_error* merror = NULL;
Parent->insert_SubFolder(this, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
// Initialize the Folder object arrays.
Files.count = 0;
Files.items = NULL;
Subfolders.count = 0;
Subfolders.items = NULL;
return;
}
Folder::Folder(LPTSTR Origen, Folder* _Parent, bool hashit, unsigned int algorithm, class m_error** p_error){
// This is one of the parametric constructors of the Folder class. The variables it accept are the following:
//
// Origen: Input. This is a string with the full name and path of the real folder in the file system that is intended be represented by the "Folder object".
// THIS CONSTRUCTOR DOES NOT VALIDATE THE EXISTENCE OF THE TERMINATING NULL CHARACTER, SO THE CALLING FUNCTION MUST PASS A NULL TERMINATED STRING.
// Parent: Input A pointer to a Folder class that contains this one (if exists).
// hashit: Input. Calculate the hash of the files contained inside the Folder and it's subfolders.
// algorithm: Input. The hash algorithm selected to do the hashing.
// p_error: Output. A pointer to a location where a linked list of "m_errors" can be placed. The way the calling function has to request errors report
// functionallity is to place in this variable a location where a m_error structure could be placed. This means the address of a variable
// of type m_error* in this way:
//
// class m_error* i = NULL;
//
// Folder* g = new Folder(a,b,c, &i);
//
// The constructor will create then an linked list of error structs and return it in the variable i.
// IT'S MANDATORY THAT, IF THIS FUNCTIONALLITY IS NOT GOING TO BE REQUESTED, THIS PARAMETER MUST BE NULL.
/*********************** Variables definitions ************************************/
HANDLE hFind = INVALID_HANDLE_VALUE;
class m_error** p_error_t = p_error;
DWORD internal_error;
/*********************** Body of the function *************************************/
//LPTSTR messages[3] = { L"Instanciando la clase Folder para la carpeta: \"\0",Origen,L"\".\0" };
////SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 3, messages)
//SET_PRINT_DELETE_SINGLE_MERROR_ARRAY(MESSAGE_LOG, MESSAGE, 3, messages, hLogFile)
// Initialize the Folder object arrays. These initializations must be here because in the destructor these fields need to have those values.
Path = NULL;
Full_name = NULL;
Full_name_long = NULL;
Files.count = 0;
Files.items = NULL;
Subfolders.count = 0;
Subfolders.items = NULL;
if (wcsncmp(Origen, L"\\\\?\\", 4) == 0) { Origen = Origen + 4; }
set_Path(Origen);
LPTSTR p_tmp = wcsrchr(Path, '\\'); // Search for the last \ in the string
if (p_tmp == NULL) { // There were not '\' characters in the string, so the Origen parameter was wrong.
//SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, INVALID_FUNCTION_PARAM, Origen)
SET_MERROR(p_error_t, FOLDER_ERRORS, INVALID_FUNCTION_PARAM, Origen)
return;
}
wmemset(p_tmp + 1, '\0', 1); // If the "Origen" variable is a NULL terminated string this will not fail because, in the worth case that there is not a valid
// character after the last '\', there will always be the original \0 character which will be overwritten.
set_Full_Name(Origen);
// Find the data of the real folder
hFind = FindFirstFile(Full_name_long, &FileData);
if (hFind == INVALID_HANDLE_VALUE)
{
internal_error = GetLastError();
// This error is recovable.
//SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, internal_error, Full_name)
SET_MERROR(p_error_t, FOLDER_ERRORS, internal_error, Full_name)
return; // If it's not possible to extract the data of the real folder it has not sense to continue on.
}
FindClose(hFind);
if (_Parent != NULL) {
Parent = _Parent;
class m_error* merror = NULL;
Parent->insert_SubFolder(this, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
Files_hashed = hashit;
hashing_algorithm = algorithm;
status = 0;
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 119, TEXT("SyncFolder.exe"), TEXT("FileData.cFileName: %S\r\n"), FileData.cFileName);
//#endif
// Prepare string for use with FindFile functions. First, copy the string to a buffer, then append '\*' to the directory name.
size_t szDir_size = wcslen(Full_name_long) + 3;
wchar_t* szDir = (wchar_t*)calloc(szDir_size, sizeof(wchar_t));
StringCchCopy(szDir, szDir_size, Full_name_long);
StringCchCat(szDir, szDir_size, TEXT("\\*"));
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
hFind = INVALID_HANDLE_VALUE;
BOOL continuar;
hFind = FindFirstFile(szDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE){
internal_error = GetLastError();
// ERROR_FILE_NOT_FOUND is not really an error in this context because it just means that inside the folder there were not files.
// Any other error is reported if that funcionallity has been requested.
if (internal_error != ERROR_FILE_NOT_FOUND) {
// Here the error is reported with Full_name as a parameter (instead of szDir) because the folder couldn't be listed at all, so it has not sense to instantiate
// the folder class. In the function that called this one must be checked the errors reported, and if this is one on them, the Folder class should be deleted and
// tried it's instantiation again, if proceed.
// This error is recovable.
//SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, internal_error, Origen)
SET_MERROR(p_error_t, FOLDER_ERRORS, internal_error, Full_name)
}
free(szDir);
return;
}
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // This is a subdirectory, so we create a Folder class that represent it.
if ((lstrcmp(ffd.cFileName, TEXT(".")) != 0) && (lstrcmp(ffd.cFileName, TEXT("..")) != 0)) { // If this subfolder is not . or ..
class m_error* merror = NULL;
Folder* Subfolder_temp = new Folder(&ffd, this, hashit, algorithm, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
else { // The file is a regular file, so what is created in this case is a File class
class m_error* merror = NULL;
File* file_temp = new File(&ffd, this, hashit, algorithm, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
continuar = FindNextFile(hFind, &ffd);
internal_error = GetLastError();
} while (continuar);
// This point is only reached if FindNextFile if equal to 0, and this set the last error variable, so there is not posibility that the "last error" has been set
// by a function different that FindNextFile
// ERROR_NO_MORE_FILES is not really an error in this context, it just means that the directory listing process has finish.
if (internal_error != ERROR_NO_MORE_FILES) {
// Here the error is reported with szDir as message because at least one file was listed in the Origen folder, and that make this error not fatal.
SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, internal_error, szDir)
}
FindClose(hFind);
free(szDir);
/*LPTSTR messages3[5] = { L"Instanciada la clase Folder: \"\0",Full_name,L", con Path: ",Path,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages3)
wchar_t* cantidad_archivos = (wchar_t*)calloc(20, sizeof(wchar_t));
_ultow_s(Files.count, cantidad_archivos, 20, 10);
LPTSTR messages1[5] = { L"Cantidad de archivos en la carpeta: \"\0",Origen,L": ",cantidad_archivos,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages1)
free(cantidad_archivos);
wchar_t* cantidad_folders = (wchar_t*)calloc(20, sizeof(wchar_t));
_ultow_s(Subfolders.count, cantidad_folders, 20, 10);
LPTSTR messages2[5] = { L"Cantidad de subcarpetas en la carpeta: \"\0",Origen,L": ",cantidad_folders,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages2)
free(cantidad_folders);*/
return;
}
Folder::Folder(WIN32_FIND_DATA* Origin_FileData, Folder* _Parent, bool hashit, unsigned int algorithm, class m_error** p_error){
// This is one of the parametric constructors of the Folder class. The variables it accept are the following:
//
// Origin_FileData: Input. The Folder class is been constructed recursivelly from an upper level Folder, so the information of the real folder in the
// file system is passed to this constructor as a WIN32_FIND_DATA struct.
// Parent: Input A pointer to a Folder class that contains this one (if exists).
// hashit: Input. Calculate the hash of the files contained inside the Folder and it's subfolders.
// algorithm: Input. The hash algorithm selected to do the hashing.
// p_error: Output. A pointer to a location where a linked list of "m_errors" can be placed. The way the calling function has to request errors report
// functionallity is to place in this variable a location where a m_error structure could be placed. This means the address of a variable
// of type m_error* in this way:
//
// class m_error* i = NULL;
//
// Folder* g = new Folder(a,b,c, &i);
//
// The constructor will create then an linked list of error structs and return it in the variable i.
// IT'S MANDATORY THAT, IF THIS FUNCTIONALLITY IS NOT GOING TO BE REQUESTED, THIS PARAMETER MUST BE NULL.
/*********************** Variables definitions ************************************/
//WIN32_FIND_DATA ffd;
//HANDLE hFind = INVALID_HANDLE_VALUE;
//size_t length_of_arg;
class m_error** p_error_t = p_error;
DWORD internal_error;
/*********************** Body of the function *************************************/
Path = NULL;
Full_name = NULL;
Full_name_long = NULL;
Files_hashed = hashit; // Carefull with this because we are stating that the files on the folder has been hashed when they has not been yet.
hashing_algorithm = algorithm;
// Initialize the Folder object arrays.
Files.count = 0;
Files.items = NULL;
Subfolders.count = 0;
Subfolders.items = NULL;
wchar_t* tempo = NULL;
_Parent->get_full_name(&tempo);
size_t Path_size = wcslen(tempo) + 2;
Path = (wchar_t*)calloc(Path_size, sizeof(wchar_t));
wcscpy_s(Path, Path_size, tempo);
free(tempo);
tempo = NULL;
wcscat_s(Path, Path_size, L"\\");
get_path(&tempo);
size_t Full_name_size = wcslen(tempo) + wcslen(Origin_FileData->cFileName) + 1;
Full_name = (wchar_t*)calloc(Full_name_size, sizeof(wchar_t));
wcscpy_s(Full_name, Full_name_size, tempo);
free(tempo);
tempo = NULL;
wcscat_s(Full_name, Full_name_size, Origin_FileData->cFileName);
set_Full_Name_long();
memcpy(&FileData, Origin_FileData, sizeof(WIN32_FIND_DATA));
status = 0;
if (_Parent != NULL) {
Parent = _Parent;
class m_error* merror = NULL;
Parent->insert_SubFolder(this, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
//LPTSTR messages[3] = { L"Instanciada la carpeta: \"\0",Full_name,L"\".\0" };
//SET_PRINT_DELETE_SINGLE_MERROR_ARRAY(MESSAGE_LOG, MESSAGE, 3, messages)
// Prepare string for use with FindFile functions. First, copy the string to a buffer, then append '\*' to the directory name.
size_t szDir_size = wcslen(Full_name_long) + 3;
wchar_t* szDir = (wchar_t*)calloc(szDir_size, sizeof(wchar_t));
StringCchCopy(szDir, szDir_size, Full_name_long);
StringCchCat(szDir, szDir_size, TEXT("\\*"));
// Find the first file in the directory.
WIN32_FIND_DATA ffd;
HANDLE hFind;
BOOL continuar;
hFind = FindFirstFile(szDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE){
internal_error = GetLastError();
// ERROR_FILE_NOT_FOUND is not really an error in this context because it just means that inside the folder there were not files.
// Any other error is reported if that funcionallity has been requested.
if (internal_error != ERROR_FILE_NOT_FOUND){
SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, internal_error, Full_name)
}
free(szDir);
return;
}
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // This is a subdirectory, so we create a Folder class that represent it.
if ((lstrcmp(ffd.cFileName, TEXT(".")) != 0) && (lstrcmp(ffd.cFileName, TEXT("..")) != 0)) { // If this subfolder is not . or ..
class m_error* merror = NULL;
Folder* Subfolder_temp = new Folder(&ffd, this, hashit, algorithm, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
else { // The file is a regular file, so what is created in this case is a File class
class m_error* merror = NULL;
File* file_temp = new File(&ffd, this, hashit, algorithm, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
continuar = FindNextFile(hFind, &ffd);
internal_error = GetLastError();
} while (continuar);
internal_error = GetLastError();
// ERROR_NO_MORE_FILES is not really an error in this context, it just means that the directory listing process has finish.
if (internal_error != ERROR_NO_MORE_FILES) {
SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, internal_error, szDir)
}
FindClose(hFind);
free(szDir);
/*LPTSTR messages3[5] = { L"Instanciada la clase Folder: \"\0",Full_name,L", con Path: ",Path,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages3)
wchar_t* cantidad_archivos = (wchar_t*)calloc(20, sizeof(wchar_t));
_ultow_s(Files.count, cantidad_archivos, 20, 10);
LPTSTR messages1[5] = { L"Cantidad de archivos en la carpeta: \"\0",Full_name,L": ",cantidad_archivos,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages1)
free(cantidad_archivos);
wchar_t* cantidad_folders = (wchar_t*)calloc(20, sizeof(wchar_t));
_ultow_s(Subfolders.count, cantidad_folders, 20, 10);
LPTSTR messages2[5] = { L"Cantidad de subcarpetas en la carpeta: \"\0",Full_name,L": ",cantidad_folders,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages2)
free(cantidad_folders);*/
return;
}
BOOL Folder::insert_SubFolder(Folder* Subfolder, class m_error** p_error){
class m_error** p_error_t = p_error;
/*TCHAR* Inserted_Folder_Full_name;
errno_t err = 0;
err = Subfolder->get_full_name(&Inserted_Folder_Full_name);
if (err != 0) {
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, (ERRNO_CODE_MASK | err), TEXT("Error obteniendo el nombre del archivo a insertar."))
return FALSE;
}
else {
LPTSTR messages[5] = { L"Insertando la carpeta: \"\0",Inserted_Folder_Full_name,L"\" en la carpeta: \"\0",Full_name,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE,5, messages)
}*/
Subfolders.count++;
Folder** temp = new Folder*[Subfolders.count];
if (Subfolders.count > 1){
memcpy(temp, Subfolders.items, sizeof(Folder*) * (Subfolders.count - 1));
delete[] Subfolders.items;
}
Subfolders.items = temp;
Subfolders.items[Subfolders.count - 1] = Subfolder;
Subfolder->set_parent(this);
return TRUE;
}
BOOL Folder::insert_file(File* file, class m_error** p_error){ //0x0004
class m_error** p_error_t = p_error; //0x0004
//0x0004
//DWORD internal_error;
wchar_t* InsertedFile_Full_name = NULL;
//TCHAR Remote_New_File[MAX_PATH];
errno_t err = 0;
err = file->get_full_name(&InsertedFile_Full_name);
if (err != 0) {
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, (ERRNO_CODE_MASK | err), TEXT("Error obteniendo el nombre del archivo a insertar."))
if (InsertedFile_Full_name != NULL) free(InsertedFile_Full_name);
return FALSE;
}
/*else {
LPTSTR messages[5] = { L"Insertando el archivo: \"\0",InsertedFile_Full_name,L"\" en la carpeta: \"\0",Full_name,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE,5, messages)
}*/
Files.count++; //count = 1 count = 2
File** temp = new File*[Files.count]; //temp [] temp [][]
if (Files.count > 1){
memcpy(temp, Files.items, sizeof(File*) * (Files.count - 1)); //temp [][] <= Files.items[0] * 1 = [0][]
delete[] Files.items;
}
Files.items = temp; //items = temp [] items = temp [0][]
Files.items[Files.count - 1] = file; //items[0] = file items[0][file]
file->set_parent(this);
if (InsertedFile_Full_name != NULL) free(InsertedFile_Full_name);
return TRUE;
}
/*File* Folder::search_file(LPTSTR file){
unsigned int i;
LPTSTR file_name;
for (i = 0; i < Files.count; i++){
file_name = (Files.items[i])->name();
if (lstrcmpi(file_name, file) == 0) return Files.items[i];
}
return NULL;
}*/
Folder::~Folder(){
/*
Files.count = 3; class File** Files.items = [(File*)0x000A{file1}] [(File*)0x000B{file2}] [(File*)0x000C{file3}]
*/
while (Files.count > 0){ //count = 3 > 0
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 79, TEXT("SyncFolder.exe"), TEXT("deleting file class: %S, index: %d from folder class: %S\r\n"),
// (Files.items[Files.count - 1]->get_FileData()).cFileName,Files.count - 1,Full_name);
//#endif
delete (Files.items[Files.count - 1]); // Files.items[2] = 0x000C
Files.count--;
}
delete[] Files.items;
while (Subfolders.count > 0){
delete (Subfolders.items[Subfolders.count - 1]);
Subfolders.count--;
}
delete[] Subfolders.items;
if (Path != NULL) free(Path);
if (Full_name != NULL) free(Full_name);
if (Full_name_long != NULL) free(Full_name_long);
}
errno_t Folder::get_name(TCHAR** Receiving_Name) {
size_t totalsize = wcslen(FileData.cFileName) + 1;
*Receiving_Name = (TCHAR*)calloc(totalsize, sizeof(wchar_t));
return (wcscpy_s(*Receiving_Name, totalsize, FileData.cFileName));
}
errno_t Folder::get_path(wchar_t** Receiving_Path) {
if (*Receiving_Path != NULL) free(*Receiving_Path);
size_t totalsize = wcslen(Path) + 1;
*Receiving_Path = (TCHAR*)calloc(totalsize, sizeof(wchar_t));
return (wcscpy_s(*Receiving_Path, totalsize, Path));
}
Folder* Folder::compare_content(Folder* ToFolder, COMPARE_LEVELS files_levels, class m_error** p_error) {
class m_error** p_error_t = p_error;
class m_error* merror = NULL;
Folder* return_value = new Folder(NULL, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
return_value->FileData = ToFolder->get_FileData();
wchar_t* tempo = NULL;
ToFolder->get_path(&tempo);
return_value->set_Path(tempo);
delete tempo;
tempo = NULL;
ToFolder->get_full_name(&tempo);
return_value->set_Full_Name(tempo);
delete tempo;
tempo = NULL;
// return_value->set_Full_Name calls internally set_Full_Name_long(), so there is not need to call it here.
// Mark the status of all the members of the folder as ghosts.
for (UINT i = 0; i < Subfolders.count; i++) {
Subfolders.items[i]->set_status(2);
}
for (UINT i = 0; i < Files.count; i++) {
Files.items[i]->set_status(2);
}
BOOL folder_founded;
for (UINT ToFolder_Subfolders_index = 0; ToFolder_Subfolders_index < ToFolder->get_subfolders_count(); ToFolder_Subfolders_index++) {
folder_founded = FALSE;
for (UINT i = 0; i < Subfolders.count; i++) {
if (Subfolders.items[i]->get_status() == 2) {
if (wcscmp((Subfolders.items[i]->get_FileData()).cFileName, ((ToFolder->get_subfolder(ToFolder_Subfolders_index))->get_FileData()).cFileName) == 0) {
folder_founded = TRUE;
class m_error* merror = NULL;
Folder* Folder_tmp = Subfolders.items[i]->compare_content(ToFolder->get_subfolder(ToFolder_Subfolders_index), files_levels, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
if (Folder_tmp != NULL) { // This means that there were differences between the two subfolders.
Subfolders.items[i]->set_status(1); // The folder is dirty.
class m_error* merror = NULL;
return_value->insert_SubFolder(Folder_tmp, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
else Subfolders.items[i]->set_status(0); // The folder is sync.
}
}
if (folder_founded) break;
}
if (!folder_founded) { // If the folder was not founded in the remote.
class m_error* merror = NULL;
LPTSTR tm = NULL;
LPTSTR tm_long = NULL;
(ToFolder->get_subfolder(ToFolder_Subfolders_index))->get_full_name(&tm);
size_t totalsize = wcslen(tm) + 5;
tm_long = (wchar_t*)calloc(totalsize, sizeof(wchar_t));
wcscpy_s(tm_long, totalsize, L"\\\\?\\");
wcscat_s(tm_long, totalsize, tm);
Folder* Folder_tmp1 = new Folder(tm_long, return_value, FALSE, 0, &merror);
Folder_tmp1->set_status(1);
delete tm;
delete tm_long;
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
BOOL file_founded;
for (UINT ToFolder_Files_index = 0; ToFolder_Files_index < ToFolder->get_files_count(); ToFolder_Files_index++) {
file_founded = FALSE;
for (UINT i = 0; i < Files.count; i++) {
if (Files.items[i]->get_status() == 2) {
if (wcscmp((Files.items[i]->get_FileData()).cFileName, ((ToFolder->get_file(ToFolder_Files_index))->get_FileData()).cFileName) == 0) {
file_founded = TRUE;
class m_error* merror = NULL;
INT16 sal = Files.items[i]->compare(ToFolder->get_file(ToFolder_Files_index), (~CONTENT & files_levels), 0, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
if ((sal & (~CONTENT & files_levels)) == (~CONTENT & files_levels)) { // if the files are equals, the status of the file is set to 0 (sync).
Files.items[i]->set_status(0);
}
else {
Files.items[i]->set_status(1); // The file is dirty
class m_error* merror = NULL;
File* file_tmp = new File(ToFolder->get_file(ToFolder_Files_index));
return_value->insert_file(file_tmp, &merror);
file_tmp->set_status(1);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
}
if (file_founded) break;
}
if (!file_founded) {
class m_error* merror = NULL;
//LPTSTR tm = NULL;
//(ToFolder->get_file(ToFolder_Files_index))->get_full_name(&tm);
File* file_tmp = new File(ToFolder->get_file(ToFolder_Files_index));
return_value->insert_file(file_tmp, &merror);
file_tmp->set_status(1);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
//File* File_tmp1 = new File(tm, return_value, FALSE, 0, &merror);
//File_tmp1->set_status(1);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("status added: %d\r\n"),File_tmp1->get_status());
//#endif
// delete tm;
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("subfolders: %d, files: %d\r\n"), return_value->get_subfolders_count(),
// return_value->get_files_count());
//#endif
if ((return_value->get_subfolders_count() == 0) && (return_value->get_files_count() == 0)) {
delete return_value;
return_value = NULL;
}
else return_value->set_status(1);
return return_value;
}
BOOLEAN Folder::synchronize(Folder* ToSyncFolder, class m_error** p_error) {
class m_error** p_error_t = p_error;
DWORD internal_error;
for (UINT TSF_files_index = 0; TSF_files_index < ToSyncFolder->get_files_count(); TSF_files_index++) {
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("status: %d\r\n"), (ToSyncFolder->get_file(TSF_files_index))->get_status());
//#endif
size_t Remote_New_File_size = (wcslen(Full_name) + 2 + wcslen(((ToSyncFolder->get_file(TSF_files_index))->get_FileData()).cFileName));
wchar_t* Remote_New_File = (wchar_t*)calloc(Remote_New_File_size,sizeof(wchar_t));
wcscpy_s(Remote_New_File, Remote_New_File_size, Full_name);
wcscat_s(Remote_New_File, Remote_New_File_size, L"\\");
wcscat_s(Remote_New_File, Remote_New_File_size, ((ToSyncFolder->get_file(TSF_files_index))->get_FileData()).cFileName);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("remote file: %S\r\n"), Remote_New_File);
//#endif
LPTSTR LocalNewFile = NULL;
(ToSyncFolder->get_file(TSF_files_index))->get_full_name(&LocalNewFile);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("local file: %S\r\n"), LocalNewFile);
//#endif
if (!CopyFile(LocalNewFile, Remote_New_File, FALSE)) {
internal_error = GetLastError();
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, internal_error, LocalNewFile)
}
else {
LPTSTR messages[5] = { L"Salvado el archivo: \"\0",LocalNewFile,L"\" al archivo: \"\0",Remote_New_File,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages)
UINT nuevo = TRUE;
for (UINT i = 0; i < Files.count; i++) {
//if (Files.items[i]->get_status() == 1) {
if (wcscmp((Files.items[i]->get_FileData()).cFileName, ((ToSyncFolder->get_file(TSF_files_index))->get_FileData()).cFileName) == 0) {
Files.items[i]->set_status(0);
WIN32_FIND_DATA FindDataTemp = (ToSyncFolder->get_file(TSF_files_index))->get_FileData();
Files.items[i]->set_FileData(FindDataTemp);
nuevo = FALSE;
break;
}
//}
}
if (nuevo) {
class m_error* merror = NULL;
File* ff = new File(Remote_New_File, this, Files_hashed, hashing_algorithm, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
ff->set_status(0);
}
}
free(LocalNewFile);
free(Remote_New_File);
}
/* for (UINT i = 0; i < Files.count; i++) {
if (Files.items[i]->get_status() == 1) {
for (UINT TSF_files_index = 0; TSF_files_index < ToSyncFolder->get_files_count(); TSF_files_index++) {
if ((ToSyncFolder->get_file(TSF_files_index))->get_status() == 1) {
if (wcscmp((Files.items[i]->get_FileData()).cFileName, ((ToSyncFolder->get_file(TSF_files_index))->get_FileData()).cFileName) == 0) {
Files.items[i]->set_status(0);
(ToSyncFolder->get_file(TSF_files_index))->set_status(0);
class m_error* merror = NULL;
Files.items[i]->synchronize(ToSyncFolder->get_file(TSF_files_index), &merror);
if (merror != NULL) ADD_MERROR(p_error, merror)
break;
}
}
}
}
}*/
/*for (UINT i = 0; i < Subfolders.count; i++) {
if (Subfolders.items[i]->get_status() == 1) { // La subcarpeta est sucia.
for (UINT TSF_Subfolder_index = 0; TSF_Subfolder_index < ToSyncFolder->get_subfolders_count(); TSF_Subfolder_index++) {
if ((ToSyncFolder->get_subfolder(TSF_Subfolder_index))->get_status() == 1) {
if (wcscmp((Subfolders.items[i]->get_FileData()).cFileName, ((ToSyncFolder->get_subfolder(TSF_Subfolder_index))->get_FileData()).cFileName) == 0) {
Subfolders.items[i]->set_status(0);
(ToSyncFolder->get_subfolder(TSF_Subfolder_index))->set_status(0);
class m_error* merror = NULL;
BOOL ba = Subfolders.items[i]->synchronize(ToSyncFolder->get_subfolder(TSF_Subfolder_index), &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
break;
}
}
}
}
}*/
for (UINT TSF_Subfolder_index = 0; TSF_Subfolder_index < ToSyncFolder->get_subfolders_count(); TSF_Subfolder_index++) {
BOOLEAN founded = FALSE;
for (UINT i = 0; i < Subfolders.count; i++) {
if (wcscmp(((ToSyncFolder->get_subfolder(TSF_Subfolder_index))->get_FileData()).cFileName, (Subfolders.items[i]->get_FileData()).cFileName) == 0) {
Subfolders.items[i]->set_status(0);
(ToSyncFolder->get_subfolder(TSF_Subfolder_index))->set_status(0);
class m_error* merror = NULL;
BOOL ba = Subfolders.items[i]->synchronize(ToSyncFolder->get_subfolder(TSF_Subfolder_index), &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
founded = TRUE;
break;
}
}
if (!founded) {
class m_error* merror = NULL;
copy_folder(ToSyncFolder->get_subfolder(TSF_Subfolder_index),this, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
return TRUE;
}
Folder* Folder::copy_folder(Folder* Origen, Folder* _Parent, class m_error** p_error) {
class m_error** p_error_t = p_error;
DWORD internal_error;
size_t size_path = wcslen(Full_name) + 2;
LPTSTR new_folder_path = (wchar_t*)calloc(size_path, sizeof(wchar_t));
wcscpy_s(new_folder_path, size_path,Full_name);
wcscat_s(new_folder_path,size_path, L"\\");
size_t name_size = (size_path - 1) + wcslen((Origen->get_FileData()).cFileName) + 1;
LPTSTR new_folder_name = (wchar_t*)calloc(name_size, sizeof(wchar_t));
wcscpy_s(new_folder_name,name_size, new_folder_path);
wcscat_s(new_folder_name,name_size, (Origen->get_FileData()).cFileName);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("receiver folder name: %S\r\n"), Full_name);
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("emiter folder name: %S\r\n"), Origen->Full_name);
//#endif
Folder* ff = NULL;
if (CreateDirectory(new_folder_name, NULL)) {
LPTSTR messages[3] = { L"Creado el directorio: \"\0",new_folder_name,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 3, messages)
class m_error* merror = NULL;
ff = new Folder(_Parent, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
ff->set_FileData(Origen->get_FileData());
ff->set_Path(new_folder_path);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("New Folder Path: %S\r\n"), ff->Path);
//#endif
ff->set_Full_Name(new_folder_name);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("New Folder Name: %S\r\n"), ff->Full_name);
//#endif
ff->set_Files_hashed(Origen->get_files_hashed());
ff->set_hashing_algorithm(Origen->get_hashing_algorithm());
ff->set_status(0);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("Origen->files_count: %d\r\n"), Origen->get_files_count());
//#endif
for (UINT i = 0; i < Origen->get_files_count(); i++) {
size_t new_file_path_size = name_size + 1;
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("new_file_path_size: %d\r\n"), new_file_path_size);
//#endif
LPTSTR new_file_path = (wchar_t*)calloc(new_file_path_size, sizeof(wchar_t));
wcscpy_s(new_file_path,new_file_path_size, new_folder_name);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("New File Path: %S\r\n"), new_file_path);
//#endif
wcscat_s(new_file_path, new_file_path_size, L"\\");
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("New File Path: %S\r\n"), new_file_path);
//#endif
size_t file_size = name_size + wcslen(((Origen->get_file(i))->get_FileData()).cFileName) + 1;
LPTSTR NewFile = (wchar_t*)calloc(file_size, sizeof(wchar_t));
wcscpy_s(NewFile, file_size, new_file_path);
wcscat_s(NewFile, file_size, ((Origen->get_file(i))->get_FileData()).cFileName);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("New File Name: %S\r\n"), NewFile);
//#endif
LPTSTR Existing_File = NULL;
(Origen->get_file(i))->get_full_name(&Existing_File);
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 552, TEXT("SyncFolder.exe"), TEXT("Existing_File: %S\r\n"), Existing_File);
//#endif
if (CopyFile(Existing_File,NewFile, FALSE)) {
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("file: %S\r\n"), NewFile);
//#endif
LPTSTR messages[5] = { L"Salvado el archivo: \"\0",Existing_File,L"\" al archivo: \"\0",NewFile,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages)
File* new_ff = new File(Origen->get_file(i));
new_ff->set_Path(new_file_path);
new_ff->set_Full_name(NewFile);
class m_error* merror = NULL;
ff->insert_file(new_ff, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
else {
internal_error = GetLastError();
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, internal_error, NewFile)
}
free(NewFile);
free(new_file_path);
}
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 681, TEXT("SyncFolder.exe"), TEXT("subfolders count: %d\r\n"), Origen->get_subfolders_count());
//#endif
for (UINT i = 0; i < Origen->get_subfolders_count(); i++) {
class m_error* merror = NULL;
ff->copy_folder((Origen->get_subfolder(i)), ff, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
}
}
else {
internal_error = GetLastError();
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, internal_error, new_folder_name)
}
free(new_folder_name);
free(new_folder_path);
return ff;
}
//INT16 Folder::compare(LPTSTR ToFolder, COMPARE_LEVELS Level, COMPARE_LEVELS sync, COMPARE_LEVELS files_levels, COMPARE_LEVELS files_sync, class m_error** p_error) {
//
// /* This function return two possible values:
//
// -1 - There was an error that made imposible to do the comparison.
// or a bit mask composed of the COMPARE_LEVELS that match both folders.
//
// Example: If the compare levels dictated that the comparison was on SIZE (10000), WTIME (01000) and NAME (01) and the result
// was that the folders was equals in NAME and WTIME but not in SIZE the return value will be: 01001
//
// sync determines on wich compare level matches the folder autosynchronize.
// */
//
// /*************** Variables *************************/
//
// class m_error** p_error_t = p_error; //0x0001[NULL]
// //0x0001[NULL]
// DWORD internal_error;
// INT16 return_value = 0;
// BOOL real_sync = FALSE;
//
//
// //WIN32_FILE_ATTRIBUTE_DATA ToFolder_Attributes;
// WIN32_FIND_DATA ffd;
// TCHAR szDir[MAX_PATH];
// HANDLE hFind = INVALID_HANDLE_VALUE;
//
//
//
// /************** Body of the function **************/
//
// // Check that ToFolder input variable does not exceed MAX_PATH - 3;
//
// if FAILED(StringCchLength(ToFolder, (MAX_PATH - 3), NULL)) {
//
// SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, FILENAME_TOO_LONG, ToFolder)
//
// return -1;
// }
//
// LPTSTR p_tmp = wcsrchr(ToFolder, '\\'); // Search for the last \ in the string
//
// if (p_tmp == NULL) { // There were not '\' characters in the string, so the ToFolder parameter was wrong.
//
// SET_PRINT_DELETE_SINGLE_MERROR( FOLDER_ERRORS, INVALID_FUNCTION_PARAM, ToFolder)
// return -1;
// }
// p_tmp++; // Move the pointer to the caracter more to the right of the last \ (i.e: the begining of the name of the folder without it path).
//
// // Compare the names of the folders, if that was requested
//
// if ((Level & NAME) == NAME) { // If there was requested name comparison.
//
// //LPTSTR messages[5] = { L"Comparando el nombre de la carpeta: \"\0",FileData.cFileName,L"\" contra el de la carpeta: \"\0",p_tmp, L"\".\0" };
// //SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages)
//
// if (wcscmp(FileData.cFileName, p_tmp) == 0) {
//
// //SET_PRINT_DELETE_SINGLE_MERROR( MESSAGE_LOG, MESSAGE, L"Nombres coincidentes\0")
// return_value = (return_value | NAME); // Both folder has the same name.
// }
// else {
//
// //SET_PRINT_DELETE_SINGLE_MERROR( MESSAGE_LOG, MESSAGE, L"Nombres no coincidentes\0")
// if ((sync & NAME) == NAME) real_sync = TRUE;
// }
// }
//
// if ((Level & CONTENT) == CONTENT) {
//
// // Compare the contents of the two folders.
//
// //LPTSTR messages[5] = { L"Comparando el contenido de la carpeta: \"\0",FileData.cFileName,L"\" contra el de la carpeta: \"\0",p_tmp,L"\".\0" };
// //SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages)
//
// // Mark the status of all the members of the folder as ghosts.
//
// for (UINT i = 0; i < Subfolders.count; i++) {
//
// Subfolders.items[i]->set_status(2);
// }
// for (UINT i = 0; i < Files.count; i++) {
//
// Files.items[i]->set_status(2);
// }
//
// // Prepare string for use with FindFile functions. First, copy the
// // string to a buffer, then append '\*' to the directory name.
//
// StringCchCopy(szDir, MAX_PATH, ToFolder);
// StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 594, TEXT("SyncFolder.exe"), TEXT("%S\r\n"), szDir);
////#endif
// // Find the first file in the directory.
//
// hFind = FindFirstFile(szDir, &ffd);
//
// if (hFind == INVALID_HANDLE_VALUE) {
//
// internal_error = GetLastError();
//
// // ERROR_FILE_NOT_FOUND is not really an error in this context because it just means that inside the folder there were not files.
// // Any other error is reported if that funcionallity has been requested.
//
// if (internal_error != ERROR_FILE_NOT_FOUND) {
//
// SET_PRINT_DELETE_SINGLE_MERROR( UNDETERMINED_ERROR_DOMAIN, internal_error, szDir)
//
// return -1; // There was an error listing the "ToFolder" folder, so it's not possible to compare it with this class.
// }
// }
// else { // The search returned a handle, so there is content in the Folder
//
// do {
//
// // Compose the full name of the file/subfolder to compare.
//
// size_t total_size;
// total_size = wcslen(ToFolder) + wcslen(ffd.cFileName) + 2;
// LPTSTR FullName = (wchar_t*)calloc(total_size, sizeof(wchar_t));
// wcscat_s(FullName, total_size, ToFolder);
// wcscat_s(FullName, total_size, L"\\");
// wcscat_s(FullName, total_size, ffd.cFileName);
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 629, TEXT("SyncFolder.exe"), TEXT("Elemento listado: %S\r\n"), FullName);
////#endif
//
// if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // This is a subfolder
//
// if ((lstrcmp(ffd.cFileName, TEXT(".")) != 0) && (lstrcmp(ffd.cFileName, TEXT("..")) != 0)) { // If this subfolder is not . or ..
//
// /*class m_error* merror = NULL;
// class Folder* temp_folder = new Folder(FullName, NULL, Files_hashed, (UINT)0, &merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)*/
//
// BOOL folder_founded = FALSE;
// for (UINT i = 0; i < Subfolders.count; i++) {
//
// if (Subfolders.items[i]->get_status() == 2) {
//
// class m_error* merror = NULL;
// // Compare only by name of the folder.
// INT16 sal = Subfolders.items[i]->compare(FullName, NAME, 0, 0, 0,&merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
//
// if ((sal != -1) && (sal & NAME) == NAME) { // If there was not error and both folders have the same name
//
// folder_founded = TRUE;
//
// class m_error* merror = NULL;
// //
// INT16 sal = Subfolders.items[i]->compare(FullName,CONTENT, sync, files_levels,files_sync, &merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
//
// if (sal != -1) {
//
// if ((sal & (~CONTENT & files_levels)) == (~CONTENT & files_levels)) { // if the files are the same (because they were or
// // because they were synchred) the status of the
// // file is set to 0 (sync).
// Files.items[i]->set_status(0);
// }
// }
// else Files.items[i]->set_status(1);
// break;
// }
// }
// }
// }
// }
// else { // The file is a regular file.
//
// class m_error* merror = NULL;
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 622, TEXT("SyncFolder.exe"), TEXT("merror before new File: %p[%p]\r\n"), &merror, merror);
////#endif
//
// class File* tmp_file = new File(FullName, NULL, Files_hashed, (UINT)0, &merror);
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 622, TEXT("SyncFolder.exe"), TEXT("merror after new File: %p[%p]\r\n"), &merror,merror);
////#endif
//
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
//
//
////#ifdef _DEBUG
//// TCHAR created_file[MAX_PATH];
//// tmp_file->get_full_name(created_file);
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 642, TEXT("SyncFolder.exe"), TEXT("Full name de la clase tmp_file creada: %S\r\n"), created_file);
////#endif
//
// BOOL file_founded = FALSE;
// // Check if the tmp_file was correctly created (from the error returned), if not clean and do not make the comparison.
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 682, TEXT("SyncFolder.exe"),
//// TEXT("cantidad de archivos en el arreglo: %d\r\n"), Files.count);
////#endif
//
// for (UINT i = 0; i < Files.count; i++) {
//
////#ifdef _DEBUG
//// TCHAR file_compared[MAX_PATH];
//// Files.items[i]->get_full_name(file_compared);
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"),
//// TEXT("status del archivo \"%S\" antes de la comparacin: %d\r\n"), file_compared, Files.items[i]->get_status());
////#endif
//
// if (Files.items[i]->get_status() == 2) { // If the file is still marked as a ghost.
//
// // Compare the files on the NAME Level
// class m_error* merror = NULL;
// INT16 sal = Files.items[i]->compare(tmp_file, NAME, 0, &merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
//
// if ((sal != -1) && (sal & NAME) == NAME) { // If there was not error and both files have the same name, it's supposed that the comparison
// // at NAME level without sync will not yield an error because all the parameters involved are
// // validated.
//
// file_founded = TRUE;
//
// // Make the comparison/sync at levels requested, but without the CONTENT level because that's
// // not implemented yet.
// class m_error* merror = NULL;
// INT16 sal = Files.items[i]->compare(tmp_file, (~CONTENT & files_levels), (~CONTENT & files_sync),&merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
//
// if (sal != -1) {
//
// if ((sal & (~CONTENT & files_levels)) == (~CONTENT & files_levels)) { // if the files are the same (because they were, or
// // because they were synchred) the status of the
// // file is set to 0 (sync).
// Files.items[i]->set_status(0);
// }
// else Files.items[i]->set_status(1); // If the files were different then
// }
// else Files.items[i]->set_status(1);
// break;
// }
// }
// }
// if (!file_founded) { // If the file was not found in the Folder class is a new file, so it must be insert it.
//
// if ((sync & CONTENT) == CONTENT) { // if it was requested CONTENT synchronization
//
// LPTSTR messages[5] = { L"Copiando el archivo: \"\0",FullName,L"\" en la carpeta: \"\0",Full_name,L"\".\0" };
// SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages)
//
// TCHAR Remote_New_File[MAX_PATH];
//
// wcscpy_s(Remote_New_File, MAX_PATH, Full_name);
// wcscat_s(Remote_New_File, MAX_PATH, L"\\");
// wcscat_s(Remote_New_File, MAX_PATH, ffd.cFileName);
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 629, TEXT("SyncFolder.exe"), TEXT("Remote_New_File: %S\r\n"), Remote_New_File);
////#endif
// if (!CopyFile(FullName, Remote_New_File, FALSE)) {
//
// internal_error = GetLastError();
// SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, internal_error, FullName)
// //
// // return_value = -1; // ESto est por verse.
// }
// else { // The file was copied, now it must be inserted in the Folder class.
//
// LPTSTR messages[5] = { L"Archivo: \"\0",FullName,L"\" copiado en la carpeta: \"\0",Full_name,L"\".\0" };
// SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 5, messages)
//
// class m_error* merror = NULL;
// File* ff = new File(Remote_New_File, this, Files_hashed, hashing_algorithm, &merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
// }
// }
// }
// delete tmp_file;
// }
// } while (FindNextFile(hFind, &ffd) != 0);
//
// internal_error = GetLastError();
//
// // ERROR_NO_MORE_FILES is not really an error in this context, it just means that the directory listing process has finish.
//
// if (internal_error != ERROR_NO_MORE_FILES) {
//
// SET_PRINT_DELETE_SINGLE_MERROR( UNDETERMINED_ERROR_DOMAIN, internal_error, ToFolder)
// }
//
// FindClose(hFind);
// }
//
// // At this point all the files/subfolders contained in the "ToFolder" folder that match by name a file/subfolder in the Folder class has been
// // compared an syncronized (if this action was requested), so the files/subfolders that remains in status == 2 (ghosts) does not exist in the
// // "ToFolder" folder, so they should be removed.
//
// if ((sync & CONTENT) == CONTENT) {
//
// for (UINT i = 0; i < Subfolders.count; i++) {
//
// if (Subfolders.items[i]->get_status() == 2) {
//
// class m_error* merror = NULL;
// remove_SubFolder(Subfolders.items[i], TRUE,&merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
// }
// }
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"),
//// TEXT("Cantidad de archivos en el arreglo Files.items antes de la limpieza: %d\r\n"), Files.count);
////#endif
//
///*
// for (UINT i = 0; i < Files.count; i++) {
//
//#ifdef _DEBUG
// TCHAR file_compared1[MAX_PATH];
// Files.items[i]->get_full_name(file_compared1);
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"),
// TEXT("status del archivo \"%S\" antes de ser removido: %d\r\n"), file_compared1, Files.items[i]->get_status());
//#endif
//
// if (Files.items[i]->get_status() == 2) {
//
// //p_a_eliminar[i] = i;
// remove_File(Files.items[i], TRUE, temp_error, &temp_error);
// }
// }
// //remove_File_group(p_a_eliminar, TRUE, temp_error, &temp_error);
//*/
//
// // [0] [2] [0] count = 3;
// UINT a = 0;
// while (a < Files.count) { // a = 0 < 3; a = 1 < 3; a = 1 < 2
//
////#ifdef _DEBUG
//// //TCHAR file_compared1[MAX_PATH];
//// //Files.items[a]->get_full_name(file_compared1);
//// //_CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"),
//// // TEXT("status del archivo \"%S\" antes de ser removido: %d\r\n"), file_compared1, Files.items[a]->get_status());
////
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"),TEXT("antes a: %d -- Files.count: %d\r\n"),a,Files.count);
////#endif
// if (Files.items[a]->get_status() == 2) { // 0 != 2 ; 2 == 2 ; 0 != 2
//
////#ifdef _DEBUG
////
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"), TEXT("%d\r\n"), 25);
////#endif
//
// class m_error* merror = NULL;
// BOOL band = remove_File(a, TRUE,&merror);
// if (merror != NULL) ADD_MERROR(p_error_t, merror)
//
// if (!band) a++; // rem a = 1 -> [0][0] Files.count = 2
// //else a--;
// }
// else a++; // a++ = 1; // a++ = 2
//
////#ifdef _DEBUG
//// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"), TEXT("despues a: %d -- Files.count: %d\r\n"), a, Files.count);
////#endif
// }
//
// /*int a = 0;
// for (UINT i = 0; i < Files.count; i++) {
//
// if (Files.items[i]->get_status() == 2) {
//
// if (Files.items[i]->delete_from_system(temp_error, &temp_error)) {
//
// delete Files.items[i];
// Files.items[i] = NULL;
// a++;
// }
// }
// }
// if ((Files.count - a) > 0) {
//
// UINT c = 0;
// File** tmp = new File*[Files.count - a];
// for (UINT b = 0; b < Files.count; b++) {
//
// if (Files.items[b] != NULL) {
//
// tmp[c] = Files.items[b];
// c++;
// }
// }
// delete Files.items;
// Files.items = tmp;
// Files.count = Files.count - a;
// }
// else {
// Files.count = 0;
// Files.items = NULL;
// }*/
// }
// }
//
// return return_value;
//}
UINT Folder::get_status(void) {
return status;
}
void Folder::set_status(UINT _status) {
status = _status;
return;
}
errno_t Folder::get_full_name(wchar_t** Receiving_FullName) {
if (*Receiving_FullName != NULL) free(*Receiving_FullName);
size_t totalsize = wcslen(Full_name) + 1;
*Receiving_FullName = (TCHAR*)calloc(totalsize, sizeof(wchar_t));
return (wcscpy_s(*Receiving_FullName, totalsize, Full_name));
}
BOOL Folder::delete_from_system(class m_error** p_error) {
class m_error** p_error_t = p_error;
BOOL content_deleted = TRUE;
DWORD internal_error;
for (UINT i = 0; i < Files.count; i++) {
//if (!(remove_File(Files.items[i], TRUE, temp_error, &temp_error))) content_deleted = FALSE;
}
for (UINT i = 0; i < Subfolders.count; i++) {
class m_error* merror = NULL;
BOOL band = remove_SubFolder(Subfolders.items[i], TRUE, &merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
if (!band) content_deleted = FALSE;
}
if (content_deleted) {
if (!(RemoveDirectory(Full_name))) {
internal_error = GetLastError();
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, internal_error, Full_name)
return FALSE;
}
else {
LPTSTR messages[3] = { L"Eliminado el directorio: \"\0",Full_name,L"\" del sistema.\0"};
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 3, messages)
}
return TRUE;
}
return FALSE;
}
BOOL Folder::remove_SubFolder(Folder* Subfolder, BOOL from_system, class m_error** p_error) {
class m_error** p_error_t = p_error;
BOOL remove = TRUE;
TCHAR* SubFolder_Full_name;
errno_t err = 0;
err = Subfolder->get_full_name(&SubFolder_Full_name);
if (err != 0) {
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, (ERRNO_CODE_MASK | err), L"Error obteniendo el nombre de la carpeta a eliminar.\0")
return FALSE;
}
else {
LPTSTR messages[3] = { L"Eliminando la carpeta: \"\0",SubFolder_Full_name,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 3, messages)
}
// Remove the files inside the subfolder
if (from_system) {
class m_error* merror = NULL;
BOOL band = Subfolder->delete_from_system(p_error_t);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
if (!band) remove = FALSE;
}
if (remove && (Subfolders.count > 0)) {
Folder** temp = new Folder*[Subfolders.count - 1];
for (UINT i = 0; i < Subfolders.count; i++) {
if (Subfolders.items[i] != Subfolder) temp[i] = Subfolders.items[i];
}
delete Subfolder;
Subfolders.count--;
delete Subfolders.items;
Subfolders.items = temp;
}
return TRUE;
}
BOOL Folder::remove_File(UINT file_index, BOOL from_system, class m_error** p_error) { // a = 1
/* The primary objective of this function is to remove the file from the Folder class, and if the parameter "from_system" is true, previously to that
action it remove the file from the system.
If "from_system" is true and the file could not be removed from the system, the file class is not removed from the folder class and the return is FALSE.
This is so because the Folder class must be a mirrow of the real folder in the file system, and if in it there is file it representation must be
in the folder class.
If "from_system" is false this function remove the file class from the folder and return the result of this action.
*/
class m_error** p_error_t = p_error;
BOOL remove = FALSE;
wchar_t* File_Full_name = NULL;
errno_t err = 0;
err = Files.items[file_index]->get_full_name(&File_Full_name);
if (err != 0) {
SET_PRINT_DELETE_SINGLE_MERROR( FILE_ERRORS, (ERRNO_CODE_MASK | err), L"Error obteniendo el nombre del archivo a eliminar.\0")
if (File_Full_name != NULL) free(File_Full_name);
return FALSE;
}
else {
LPTSTR messages[3] = { L"Eliminando el archivo: \"\0",File_Full_name,L"\".\0" };
SET_PRINT_DELETE_SINGLE_MERROR_ARRAY( MESSAGE_LOG, MESSAGE, 3, messages)
}
/*if (from_system) {
if (!(file->delete_from_system(temp_error, &temp_error))) remove = FALSE; // If the file could not be removed from the file system cancel the remove action
// from the folder class
//file->delete_from_system(temp_error, &temp_error);
}
if (remove && (Files.count > 0)) { //Files.count = 3
File** temp = new File*[Files.count - 1]; //temp = [][]
for (UINT i = 0; i < Files.count; i++) { // i = 0 i<3 ; i = 1 i < 3 ; i = 2 i < 3 ; i = 3 i == 3
if (Files.items[i] != file) temp[i] = Files.items[i]; // 0 != 1 -> [0]; 1 = 1 -> [0] ; 2 != 1 -> [0][0]
}
delete file; // delete 1
Files.count--; // Files.count = 2
delete Files.items;
Files.items = temp;
return TRUE;
}*/
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"), TEXT("Entrando a remove_File Files.count: %d\r\n"),Files.count);
//#endif
class m_error* merror = NULL;
BOOL band = Files.items[file_index]->delete_from_system(&merror);
if (merror != NULL) ADD_MERROR(p_error_t, merror)
if (band) {
delete Files.items[file_index];
Files.items[file_index] = NULL;
remove = TRUE;
}
if (remove) {
//#ifdef _DEBUG
// _CrtDbgReportW(_CRT_WARN, TEXT("Folder.cpp"), 653, TEXT("SyncFolder.exe"), TEXT("Entrando a remove Files.count: %d\r\n"), Files.count);
//#endif
if (Files.count > 1) {
UINT c = 0;
File** tmp = new File*[Files.count - 1];
for (UINT b = 0; b < Files.count; b++) {
if (Files.items[b] != NULL) {
tmp[c] = Files.items[b];
c++;
}
}
delete Files.items;
Files.items = tmp;
Files.count--;
}
else {
delete Files.items;
Files.count = 0;
Files.items = NULL;
}
if (File_Full_name != NULL) free(File_Full_name);
return TRUE;
}
if (File_Full_name != NULL) free(File_Full_name);
return FALSE;
}
UINT Folder::get_files_count() {
return Files.count;
}
UINT Folder::get_subfolders_count() {
return Subfolders.count;
}
Folder* Folder::get_subfolder(UINT index) {
return Subfolders.items[index];
}
File* Folder::get_file(UINT index) {
return Files.items[index];
}
WIN32_FIND_DATA Folder::get_FileData(void) {
return FileData;
}
void Folder::set_parent(Folder* _Parent) {
Parent = _Parent;
}
void Folder::set_FileData(WIN32_FIND_DATA _FileData) {
memcpy(&FileData, &_FileData,sizeof(WIN32_FIND_DATA));
return;
}
void Folder::set_Path(wchar_t* _Path) {
if (Path != NULL) free(Path);
size_t totalsize = wcslen(_Path) + 1;
Path = (wchar_t*)calloc(totalsize, sizeof(wchar_t));
wcscpy_s(Path, totalsize, _Path);
}
void Folder::set_Full_Name(wchar_t* _Full_Name) {
if (Full_name != NULL) free(Full_name);
size_t totalsize = wcslen(_Full_Name) + 1;
Full_name = (wchar_t*)calloc(totalsize, sizeof(wchar_t));
wcscpy_s(Full_name, totalsize, _Full_Name);
set_Full_Name_long();
return;
}
void Folder::set_Full_Name_long() {
size_t totalsize = wcslen(Full_name) + 5;
Full_name_long = (wchar_t*)calloc(totalsize, sizeof(wchar_t));
wcscpy_s(Full_name_long, totalsize, L"\\\\?\\");
wcscat_s(Full_name_long, totalsize, Full_name);
return;
}
void Folder::set_Files_hashed(BOOLEAN _Files_hashed) {
Files_hashed = _Files_hashed;
return;
}
void Folder::set_hashing_algorithm(UINT _hashing_algorithm) {
hashing_algorithm = _hashing_algorithm;
}
Folder* Folder::get_Parent() {
return Parent;
}
BOOL Folder::get_files_hashed() {
return Files_hashed;
}
BOOL Folder::get_hashing_algorithm() {
return hashing_algorithm;
} | true |
a8975514062421d827d563f89ee530ffd620cf3a | C++ | 7xxxx/CryptographicAlgorithms | /src/Public-Key/RabinAttack.cpp | UTF-8 | 710 | 2.59375 | 3 | [] | no_license | /*
* RabinAttack.cpp
*/
#include "PublicKeyAlgorithmBox.h"
#include "RabinDecryptor.h"
#include "RabinAttack.h"
using namespace std;
RabinAttack::RabinAttack() {
}
RabinAttack::~RabinAttack() {
}
int RabinAttack::factorize(const Integer& n, Integer& f, int max_tries,
RabinDecryptor& rabin_dec) {
PublicKeyAlgorithmBox pk_box;
Integer p, q, r, x;
for(int i=0; i < max_tries; i++){
r = pk_box.randomInteger(1, n-1);
rabin_dec.compute((r * r) % n, x);
if(x % n == r % n || x % n == -r % n)
continue;
else {
p = Integer::Gcd(x - r, n);
q = n / p;
f = q;
return i;
}
}
return -1;
}
| true |
a22c1ba59384a89453d49803bdc6d7a0276d0153 | C++ | PracticallyNothing/SWAN-Game-Engine | /SWAN/Utility/Group.hpp | UTF-8 | 370 | 2.640625 | 3 | [] | no_license | #ifndef SWAN_UTILITY_GROUP_HPP
#define SWAN_UTILITY_GROUP_HPP
#include <array>
namespace SWAN
{
namespace Util
{
template <typename T, typename Iter>
inline constexpr bool IsOneOf(T t, Iter begin, Iter end)
{
while(begin != end) {
if(t == *begin)
return true;
begin++;
}
return false;
}
} // namespace Util
} // namespace SWAN
#endif
| true |
4e17dfc778cc3335c0661cad8b242a08e9abae52 | C++ | laquythi/laquythi.github.io | /C++/66-HocToanTuConTro/main.cpp | UTF-8 | 1,295 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int count=100;
int *m=&count;//hoac int *m;dong tiep theo m=&count;
cout<<"dia chi cua bien count="<<&count<<endl;
cout<<"gia tri cua bien count="<<count<<endl;
cout<<"dia chi cua con tro m="<<m<<endl;
cout<<"gia tri ma con tro m dang tro toi="<<*m<<endl;
int p=*m;//p la bien thong thuong,co gia tri bang gia tri ma con tro m dang tro toi;
cout<<"gia tri cua p="<<p<<endl;
int *x=m;
cout<<"dia chi cua con tro x="<<x<<endl;
cout<<"gia tri cua con tro x="<<*x<<endl;
*x=15;
cout<<"gia tri ma con tro m dang tro toi="<<*m<<endl;
cout<<"gia tri cua bien count="<<count<<endl;
return 0;
}
// int count=100;
// int *m=&count;
// cout<<"dia chi cua bien count="<<&count<<endl;
// cout<<"gia tri cua bien count="<<count<<endl;
// cout<<"dia chi cua con tro m="<<m<<endl;
// cout<<"gia tri ma con tro m dang tro toi="<<*m;
//
// int p=*m;
// cout<<"\ngia tri cua p="<<p;
// int *x=m;
// cout<<"\ndia chi cua con tro x="<<x<<endl;
// cout<<"gia tri ma con tro x tro toi la "<<*x<<endl;
// *x=15;
// cout<<"gia tri ma con tro m dang tro toi la "<<*x<<endl;
// cout<<"gia tri cua bien count="<<count<<endl;
| true |
3be39fa57b2ff99f6bfc2316b4ddcef17e803cc1 | C++ | dc-maggic/978-7-121-15535-2 | /chapter6/practise6_33/practise6_33/practise6_33.cpp | UTF-8 | 407 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
void factorial(vector<string>::const_iterator beg, vector<string>::const_iterator end)
{
if (beg != end)
{
cout << *beg << endl;
return factorial(++beg, end);
}
}
int main()
{
const vector<string> str{ "sasd","sadasf","but","koh" };
auto s = str.begin();
factorial(str.begin(), str.end());
system("pause");
return 0;
} | true |
2299363f2025aa900a31145496191769c960a622 | C++ | bazindes/algo | /src/ds/BinaryTree.h | UTF-8 | 591 | 2.53125 | 3 | [] | no_license | /*
BinaryTree.h
Created by: baz
Date: 2019-04-09 17:13
*/
#if !defined(BINARY_TREE_H)
#define BINARY_TREE_H
namespace BinaryTree {
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode();
TreeNode(int x);
~TreeNode();
};
TreeNode* buildBT(int nums[], int n, int i);
TreeNode* buildBT(int **nums, int n, int i);
void inOrderTraversal(TreeNode *root, void (*func)(TreeNode *));
void preOrderTraversal(TreeNode *root, void (*func)(TreeNode *));
void postOrderTraversal(TreeNode *root, void (*func)(TreeNode *));
} // namespace BT
#endif // BINARY_TREE_H
| true |
5b9ea3ff642a3fba8d97ea1d8f0484c9ba09826e | C++ | vonKleve/Targets | /12-17/ptAbstract_Factory/Abstract_Factory(try1)/Abstract_Factory.cpp | UTF-8 | 781 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "Abstract_Factory.h"
English* DistributorA::EnglishSubs()
{
return new English("DistributorA");
}
French* DistributorA::FrenchSubs()
{
return new French("DistributorA");
}
English* DistributorB::EnglishSubs()
{
return new English("DistributorB");
}
French* DistributorB::FrenchSubs()
{
return new French("DistributorB");
}
English::English(std::string input)
{
content = "Happy timespending!" + input + " wishes you good luck! ";
}
std::string English::get_subs(std::string filmTitle)
{
return (content + filmTitle);
}
French::French(std::string input)
{
content = "Sans espoir, j'espere." + input + " dires vous: \"Profite de votre temps!\" ";
}
std::string French::get_subs(std::string filmTitle)
{
return (content + filmTitle);
}
| true |
0de9937cdbc25ed72a6dad364ab11387123b21e5 | C++ | mayankvanjani/OOP | /Lab/LinkedListFunc/rec11.cpp | UTF-8 | 4,516 | 3.65625 | 4 | [] | no_license | /*
Rec11: Linked Lists
Mayank Vanjani
11/17/17
CS2114
NYU Tandon School of Engineering
*/
#include <string>
#include <iostream>
using namespace std;
struct Node {
Node(int data=0, Node* next=nullptr) : data(data), next(next) {}
int data;
Node* next;
};
void listInsertHead(Node*& headPtr, int data) {
headPtr = new Node(data, headPtr);
}
void display( Node* hp ) {
if ( !hp ) { cout << "Empty"; }
Node* p = hp;
while ( p ) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//Part One Splice
void spliceInto( Node* insertAfter, Node* splice ) {
if ( !insertAfter->next ) { insertAfter->next = splice; }
else if ( splice ) {
Node* rightAfter = insertAfter->next;
while ( splice->next ) {
insertAfter->next = splice;
insertAfter = insertAfter->next;
splice = splice->next;
}
splice->next = rightAfter;
}
}
//Part Two Sublist
Node* sublist( Node* hp, Node* check ) {
Node* answer = hp;
Node* answerMover = answer;
Node* checkMover = check;
while ( answerMover && checkMover ) {
if ( answerMover->data == checkMover->data ) {
if (!checkMover->next) {
return answer;
}
if (!answerMover->next) {
cout << "Failed to Match" << endl;
return nullptr;
}
answerMover = answerMover->next;
checkMover = checkMover->next;
}
else {
answer = answer->next;
answerMover = answer;
checkMover = check;
}
}
cout << "Failed to Match" << endl;
return nullptr;
}
int main() {
cout << "Part One:" << endl << endl;
Node* L1 = new Node(5);
L1->next = new Node(7);
L1->next->next = new Node(9);
L1->next->next->next = new Node(1);
cout << "L1: ";
display(L1);
Node* L2 = new Node(6);
L2->next = new Node(3);
L2->next->next = new Node(2);
cout << "L2: ";
display(L2);
Node* target = L1->next;
cout << "Target: ";
display(target);
cout << "Splicing L2 into target 7 in L1" << endl;
spliceInto( target, L2 );
cout << "L1: ";
display(L1);
cout << "L2: ";
display(L2);
cout << endl;
/*
Node* edge = new Node(0);
Node* oneTarget = new Node(1);
display( edge );
display( oneTarget );
spliceInto( edge, oneTarget );
cout << "Splicing" << endl;
display( edge );
display( oneTarget );
Node* noSplice = nullptr;
cout << "Splicing" << endl;
spliceInto( edge, noSplice );
cout << "Splicing" << endl;
display( edge );
display( noSplice );
*/
cout << "==========" << endl << endl;
cout << "Part 2:" << endl;
Node* target2 = new Node(1);
target2->next = new Node(2);
target2->next->next = new Node(3);
target2->next->next->next = new Node(2);
target2->next->next->next->next = new Node(3);
target2->next->next->next->next->next = new Node(2);
target2->next->next->next->next->next->next = new Node(4);
target2->next->next->next->next->next->next->next = new Node(5);
target2->next->next->next->next->next->next->next->next = new Node(6);
cout << endl << "Target: ";
display( target2 );
cout << endl;
Node* match1 = new Node(1);
Node* match2 = new Node(3);
match2->next = new Node(9);
Node* match3 = new Node(2);
match3->next = new Node(3);
Node* match4 = new Node(2);
match4->next = new Node(4);
match4->next->next = new Node(5);
match4->next->next->next = new Node(6);
Node* match5 = new Node(2);
match5->next = new Node(3);
match5->next->next = new Node(2);
match5->next->next->next = new Node(4);
Node* match6 = new Node(5);
match6->next = new Node(6);
match6->next->next = new Node(7);
cout << "Attempt match: ";
display(match1);
display( sublist( target2, match1 ) );
cout << endl;
cout << "Attempt match: ";
display(match2);
display( sublist( target2, match2 ) );
cout << endl;
cout << "Attempt match: ";
display(match3);
display( sublist( target2, match3 ) );
cout << endl;
cout << "Attempt match: ";
display(match4);
display( sublist( target2, match4 ) );
cout << endl;
cout << "Attempt match: ";
display(match5);
display( sublist( target2, match5 ) );
cout << endl;
cout << "Attempt match: ";
display(match6);
display( sublist( target2, match6 ) );
cout << endl;
// nullptr match
cout << "Attempt match: ";
display( nullptr );
display( sublist( target2, nullptr ) );
cout << endl;
// nullptr match and target
cout << "Attempt match: ";
display( nullptr );
display( sublist( nullptr, nullptr ) );
cout << endl;
}
| true |
4803c48dc4306611a262e1373843f576e8980d13 | C++ | NicoG60/OpenOrganigram | /src/Vue/Scene.h | UTF-8 | 1,567 | 2.53125 | 3 | [] | no_license | // Scene.h 1.0 21/02/14 N.Jarnoux
#ifndef SCENE_H
#define SCENE_H
class Scene ;
//===== Headers standards =====
#include <QGraphicsScene>
#include <QGraphicsSceneDragDropEvent>
//===== Headers Peros =====
#include "Item.h"
#include "Fleche.h"
#include "MarqueurDrop.h"
class Scene : public QGraphicsScene
{
Q_OBJECT
public:
explicit Scene(QObject * pParent = 0); //Constructeur
~Scene() ;
Item * getItem(unsigned int nIdInst) ; //Renvois l'item à l'Id correspondant
void AjouterItem(Item * ItemAAjouter) ;
void AjouterFleche(Fleche * FlecheAAjouter) ;
void RAZ() ;
protected:
void dragEnterEvent(QGraphicsSceneDragDropEvent * pEvent);//Evenement d'entrée de drag
void dragLeaveEvent(QGraphicsSceneDragDropEvent * pEvent);//Evenement de sortie de drag
void dragMoveEvent(QGraphicsSceneDragDropEvent * pEvent); //Evenement de déplacement de drag
void dropEvent(QGraphicsSceneDragDropEvent * pEvent); //Evenemetn de drop
private:
QList<Item *> ListeItems ; //Liste des items
QList<Fleche *> ListeFleches ; //Liste des fleche
MarqueurDrop * pMarqueur ; //Marqueur de drop
Fleche * pFlecheMarqueur ; //Fleche que le marqueur pointe
void CalculerEmplacementMarqueur(QPointF Position) ; //Calcul l'emplacement du marqueur
};
#endif // SCENE_H
| true |
869228e6c66e7f82da6dbf8aee18470236b6f87d | C++ | Developer-Rajeev/code | /return_unit_digit_after_power.cpp | UTF-8 | 436 | 3.328125 | 3 | [] | no_license | /*
**This question was asked in Nagarro 2020**
return unit digit
input:
x=4
y=4
output:
6
logic:
y=0;
while(i<y)
box=(box*x)
return box%10;
*/
#include<stdio.h>
int main()
{
int x,y,box=1,res,i;
printf("enter first number\n");
scanf("%d",&x);
printf("enter power value\n");
scanf("%d",&y);
for(i=0;i<y;i++)
{
box=(box*x);
}
res=box%10;
printf("unit digit is %d",res);
}
| true |
477cfb18f2db8616ee17a793fede26879e0c3ecd | C++ | tomzig16/AoC20 | /src/13/day13_main.cpp | UTF-8 | 4,646 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include "../HelperFunctions.h"
typedef unsigned long long t_ULL;
int FirstPart(int minTime, std::vector<int> knownBusses) {
std::vector<std::pair<int, int>> earliestAvailable;
for (int busID : knownBusses) {
int remainder = minTime % busID;
earliestAvailable.push_back(std::pair<int, int>(busID, (busID - remainder) + minTime));
}
std::sort(earliestAvailable.begin(), earliestAvailable.end(),
[](std::pair<int, int> ls, std::pair<int, int> rs) {
return ls.second < rs.second;
});
return earliestAvailable[0].first * (earliestAvailable[0].second - minTime);
}
// 640856202464541 is correct answer.
// Very ineficcient way of finding
t_ULL SecondPart(std::string inputWithAllBusses) {
// First number is offset from first bus
// Second number is actual bus ID
std::vector<std::pair<int, int>> allBusses;
int busSequenceNumber = 0;
while (inputWithAllBusses.size() > 0) {
size_t nextComma = inputWithAllBusses.find(",");
if (nextComma == inputWithAllBusses.npos) nextComma = inputWithAllBusses.size();
std::string busID = inputWithAllBusses.substr(0, nextComma);
inputWithAllBusses.erase(0, nextComma + 1);
if (busID == "x") {
busSequenceNumber++;
continue;
}
allBusses.push_back(std::pair<int, int>(busSequenceNumber++, StringToInt(busID)));
}
// first number is index of first paired entry from allBusses
// second number is index of second paired entry from allBusses
std::vector<std::pair<int, int>> pairs; // numbers that contain pairs (second number contains pair with another number)
for (int i = 0; i < allBusses.size(); i++) {
for (int j = i+1; j < allBusses.size(); j++) {
if (allBusses[i].second == allBusses[j].first) {
pairs.push_back(std::pair<int, int>(i, j));
}
// If performance of the loop is bad, add check if modulus of two numbers is 0
// those could be used as pairs too
}
}
auto largestNumberIT = std::max_element(allBusses.begin(), allBusses.end(),
[](std::pair<int, int> ls, std::pair<int, int> rs) {
return ls.second < rs.second;
});
t_ULL largestNumberOffset = 41;
t_ULL largestNumber = 911;
// Buggest jumps would add biggest numbers in busses array,
// however real result is hiding in 't' value, which is offset
// of the very first entry
t_ULL realResult;
t_ULL start = 640856202400000 + (largestNumber - (640856202400000 % largestNumber));
for (t_ULL currentT = start; 1; currentT += largestNumber) {
if ((currentT - largestNumberOffset) % (t_ULL)allBusses[0].second != 0) {
continue;
}
else {
realResult = currentT - largestNumberOffset;
}
bool skipFurtherChecks = false;
for (auto pair : pairs) {
if (((realResult + (t_ULL)allBusses[pair.first].first) % // add offset
(t_ULL)allBusses[pair.first].second != 0) ||
((realResult + (t_ULL)allBusses[pair.second].first) % // add offset
(t_ULL)allBusses[pair.second].second != 0)) {
skipFurtherChecks = true;
break;
}
}
if (skipFurtherChecks) { continue; }
// we already checked id 0 as the first thing
for (int i = 1; i < allBusses.size(); i++) {
if ((realResult + (t_ULL)allBusses[i].first) % (t_ULL)allBusses[i].second != 0) {
skipFurtherChecks = true;
break;
}
}
if (skipFurtherChecks) {
continue;
}
else {
break;
} // result was found
}
return realResult;
}
std::vector<int> RemoveUnknownBusses(std::string allBusses) {
std::vector<int> inputs;
while (allBusses.size() > 0) {
size_t nextComma = allBusses.find(",");
if (nextComma == allBusses.npos) nextComma = allBusses.size();
std::string busID = allBusses.substr(0, nextComma);
allBusses.erase(0, nextComma + 1);
if (busID == "x") {
continue;
}
inputs.push_back(StringToInt(busID));
}
return inputs;
}
int main() {
std::vector<std::string> inputs = ReadStrings("input.txt");
int earliestTime = StringToInt(inputs[0]);
std::vector<int> knownBusses = RemoveUnknownBusses(inputs[1]);
PRINT(1, FirstPart(earliestTime, knownBusses));
PRINT(2, SecondPart(inputs[1]));
return 0;
} | true |
0d5ac36cac38b4b95e40b714d9598f842665cc02 | C++ | neelkanjariya1996/Algorithms | /Searching_and_Sorting/pigeonhole_sort.cpp | UTF-8 | 1,276 | 3.921875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
void
pigeonhole_sort (int arr[], int n)
{
int index = 0;
int range = 0;
int min = 0;
int max = 0;
int i = 0;
min = arr[0];
max = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
range = max - min + 1;
vector <int> holes[range];
for (i = 0; i < n; i++) {
holes[arr[i] - min].push_back (arr[i]);
}
for (i = 0; i < range; i++) {
vector <int> :: iterator it;
for (it = holes[i].begin(); it != holes[i].end(); it++) {
arr[index] = *it;
index++;
}
}
}
void
print_array (int arr[], int n)
{
int i = 0;
for (i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int
main ()
{
int arr[] = {3, 4, 21, 0, 2, 6, 2, 6, 9, 3, 19, 23, 3, 19};
int n = 0;
n = sizeof (arr) / sizeof (int);
cout << "Array before Sorting: ";
print_array (arr, n);
pigeonhole_sort (arr, n);
cout << "Array after Sorting: ";
print_array (arr, n);
return 0;
}
| true |
1553aab404f15be91d81a7712f03e5d0efa0d12e | C++ | AIREL46/SCAO | /C++/premier.cc | UTF-8 | 692 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n(1);
int D(0);
do {
cout << "Entrer un entier plus grand que 0" << endl;
cin >> n;
if (n<=0) { cout <<"Le nombre doit etre strictement positif"<<endl;}
else {cout <<"OK"<<endl;}
}
while (n<=0);
if (fmod(n,2)==0 and n!=2) {cout <<n<<" ce nombre est pair: "<<endl;}
else {cout <<"ce nombre n'est pas pair sauf s'il est egal a 2"<<endl;}
for (int i(2);i<=sqrt(n);++i) {
if (fmod(n,i)==0) {
D=i;}
else {
}
}
if (D!=0) {cout <<"Ce nombre n'est pas premier car il es divisible par :" <<D<<endl;}
else {cout <<"Ce nombre est premier"<<endl;}
return 0;
}
| true |
bb4b0593f4110ad9a6a3f370e7fbc0ac639d39fa | C++ | tisi1988/Super-Hang-On | /ModuleSceneMap.cpp | UTF-8 | 4,168 | 2.515625 | 3 | [] | no_license | #include "Globals.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleAudio.h"
#include "ModuleInput.h"
#include "ModuleRender.h"
#include "ModuleFadeToBlack.h"
#include "ModuleSceneMap.h"
ModuleSceneMap::ModuleSceneMap(bool active) : Module(active)
{
// Backdrop
backdrop.x = 0;
backdrop.y = 0;
backdrop.w = SCREEN_WIDTH * 3;
backdrop.h = SCREEN_HEIGHT * 3;
// World map
worldMap.x = 1;
worldMap.y = 41;
worldMap.w = 280;
worldMap.h = 165;
// "Choose your class" message
chooseClass.x = 3;
chooseClass.y = 3;
chooseClass.w = 136;
chooseClass.h = 8;
// Africa
africa.frames.push_back({ 294, 2, 52, 56 });
africa.frames.push_back({ 0, 0, 0, 0 });
africa.speed = 0.05f;
// Asia
asia.frames.push_back({ 420, 52, 116, 137 });
asia.frames.push_back({ 0, 0, 0, 0 });
asia.speed = 0.05f;
// America
america.frames.push_back({ 283, 61, 97, 128 });
america.frames.push_back({ 0, 0, 0, 0 });
america.speed = 0.05f;
// Europe
europe.frames.push_back({ 349, 4, 56, 48 });
europe.frames.push_back({ 0, 0, 0, 0 });
europe.speed = 0.05f;
// Africa text
courseAfrica.x = 142;
courseAfrica.y = 3;
courseAfrica.w = 71;
courseAfrica.h = 16;
// Asia text
courseAsia.x = 142;
courseAsia.y = 21;
courseAsia.w = 71;
courseAsia.h = 16;
// America text
courseAmerica.x = 215;
courseAmerica.y = 3;
courseAmerica.w = 71;
courseAmerica.h = 16;
// Europe text
courseEurope.x = 215;
courseEurope.y = 21;
courseEurope.w = 71;
courseEurope.h = 16;
// "Press button" animation
pressButton.frames.push_back({ 3, 14, 136, 8 });
pressButton.frames.push_back({ 0, 0, 0, 0 });
pressButton.speed = 0.03f;
}
ModuleSceneMap::~ModuleSceneMap()
{
}
bool ModuleSceneMap::Start()
{
LOG("Loading race intro");
graphics = App->textures->Load("bikes.png", 255, 0, 204);
App->audio->PlayMusic("opening.ogg", 1.0f);
if (fx == 0)
fx = App->audio->LoadFx("rtype/starting.wav");
App->renderer->camera.x = App->renderer->camera.y = 0;
return true;
}
// UnLoad assets
bool ModuleSceneMap::CleanUp()
{
LOG("Unloading scene");
App->textures->Unload(graphics);
if (fx == 0)
fx = App->audio->LoadFx("rtype/starting.wav");
return true;
}
// Update: draw background
update_status ModuleSceneMap::Update()
{
App->renderer->DrawQuad(backdrop, 160, 192, 224, 255, false);
App->renderer->Blit(graphics, SCREEN_WIDTH / 2 - 78, 30, &chooseClass);
App->renderer->Blit(graphics, SCREEN_WIDTH / 2 - 140, SCREEN_HEIGHT / 2 - 82, &worldMap);
switch (courseSelect)
{
case AFRICA:
App->renderer->Blit(graphics, 174, 111, &(africa.GetCurrentFrame()));
break;
case ASIA:
App->renderer->Blit(graphics, 210, 46, &(asia.GetCurrentFrame()));
break;
case AMERICA:
App->renderer->Blit(graphics, 62, 63, &(america.GetCurrentFrame()));
break;
case EUROPE:
App->renderer->Blit(graphics, 170, 63, &(europe.GetCurrentFrame()));
break;
}
App->renderer->Blit(graphics, 170, 127, &courseAfrica);
App->renderer->Blit(graphics, 235, 63, &courseAsia);
App->renderer->Blit(graphics, 83, 95, &courseAmerica);
App->renderer->Blit(graphics, 171, 79, &courseEurope);
App->renderer->Blit(graphics, SCREEN_WIDTH / 2 - 78, 200, &(pressButton.GetCurrentFrame()));
if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN && App->fade->isFading() == false)
{
switch (courseSelect)
{
case AFRICA:
App->fade->FadeToBlack((Module*)App->scene_music, this);
break;
case ASIA:
App->audio->PlayFx(fx);
break;
case AMERICA:
App->audio->PlayFx(fx);
break;
case EUROPE:
App->audio->PlayFx(fx);
break;
}
}
if (App->input->GetKey(SDL_SCANCODE_S) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
{
africa.Reset();
asia.Reset();
america.Reset();
europe.Reset();
if (courseSelect != AFRICA)
{
courseSelect--;
}
else
{
courseSelect = EUROPE;
}
}
else if (App->input->GetKey(SDL_SCANCODE_W) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_D) == KEY_DOWN)
{
africa.Reset();
asia.Reset();
america.Reset();
europe.Reset();
if (courseSelect != EUROPE)
{
courseSelect++;
}
else
{
courseSelect = AFRICA;
}
}
return UPDATE_CONTINUE;
}
| true |
8a41104aef46d08dbb995c37de8c3375f5ca3c25 | C++ | csteuer/ParallelBottomUpBalancedOctreeBuilder | /octreebuilder/octree.cpp | UTF-8 | 1,403 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "octree.h"
#include <ostream>
namespace octreebuilder {
::std::ostream& operator<<(::std::ostream& s, const OctreeNode& n) {
s << "{ llf: " << n.getLLF() << ", level: " << n.getLevel() << ", size: " << n.getSize() << ", morton_llf: " << n.getMortonEncodedLLF() << " }";
s << ::std::endl;
return s;
}
::std::ostream& operator<<(::std::ostream& s, const Octree& tree) {
s << "{ depth: " << tree.getDepth() << ", maxLevel: " << tree.getMaxLevel() << ", maxXYZ: " << tree.getMaxXYZ() << ", numNodes: " << tree.getNumNodes()
<< " }";
return s;
}
::std::ostream& operator<<(::std::ostream& s, const ::std::unique_ptr<Octree>& tree) {
if (tree != nullptr) {
s << *tree;
} else {
s << "NULL";
}
return s;
}
Octree::~Octree() {
}
::std::ostream& operator<<(::std::ostream& s, const Octree::OctreeState& octreeState) {
switch (octreeState) {
case Octree::OctreeState::INCOMPLETE:
s << "INCOMPLETE";
break;
case Octree::OctreeState::OVERLAPPING:
s << "OVERLAPPING";
break;
case Octree::OctreeState::UNBALANCED:
s << "UNBALANCED";
break;
case Octree::OctreeState::UNSORTED:
s << "UNSORTED";
break;
case Octree::OctreeState::VALID:
s << "VALID";
break;
}
return s;
}
}
| true |
f11d389163447a01358fbad05abb9cde9efb0689 | C++ | stuart-ashley/bijouengine | /src/render/sphericalHarmonics.h | UTF-8 | 685 | 2.5625 | 3 | [] | no_license | #pragma once
#include "renderTask.h"
#include <array>
#include <memory>
namespace render {
class SphericalHarmonics final: public RenderTask {
public:
/**
*
* @param name
* @param texture
* @param floats
*/
SphericalHarmonics(const std::string & name,
const std::shared_ptr<Texture> & texture,
const std::array<float, 27> & floats);
/**
* default destructor
*/
inline virtual ~SphericalHarmonics() = default;
/**
*
*/
void execute(Canvas & canvas) override;
/**
*
* @return
*/
bool hasExecuted() const override;
/**
*
*/
static void init();
private:
struct impl;
std::shared_ptr<impl> pimpl;
};
}
| true |
1fb8928088ebc9f65d843352df5cd50708e84afb | C++ | lorenmh/learn_c | /blackjack/deck.cpp | UTF-8 | 582 | 3.125 | 3 | [] | no_license | #include "deck.h"
#include "card.h"
#include "randomf.h"
const int DECKSIZE = 52;
Deck::Deck() {
index = 0;
for (int i = 0; i < DECKSIZE; i++) {
cards[ i ].setIndex( i );
}
}
void Deck::shuffle() {
index = 0;
for (int i = 0; i < DECKSIZE; i++) {
// swapIndex is a random int between i and len
int swapIndex = ((int)(randomf() * (DECKSIZE - i))) + i;
Card swap = cards[ i ];
cards[ i ] = cards[ swapIndex ];
cards[ swapIndex ] = swap;
}
}
Card* Deck::nextCard() {
if ( index >= DECKSIZE ) { return nullptr; }
return &cards[ index++ ];
}
| true |
476c7447654a50f53c9b5c32938b3d8dbb63a19c | C++ | menarus/C-Course | /Solutions/Ch7/Serendipity/bookinfo.cpp | UTF-8 | 924 | 2.9375 | 3 | [
"MIT"
] | permissive | /*
Project : bookinfo
Author : Mohammad Al-Husseini
Description : Displays the book information menu for the Serendipity Project.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <iostream> // cout object for command line output
using namespace std;
int bookinfo(char isbn[14], char title[51], char author[31], char publisher[31], char date[11], int qty, double wholeSale, double retail)
{
cout << " Serendipity Booksellers" << endl;
cout << " Book Information" << endl << endl;
cout << " ISBN: " << isbn << endl;
cout << " Title: " << title << endl;
cout << " Author: " << author << endl;
cout << " Publisher: " << publisher << endl;
cout << " Date Added: " << date << endl;
cout << " Quantity-On-Hand: " << qty << endl;
cout << " Wholesale Cost: $" << wholeSale << endl;
cout << " Retail Price: $" << retail;
return 0;
} | true |
1c1f7d8504cb86188684c95e736ab2ecf3be39db | C++ | iamsidv/sdl-samples | /sdl-tutorial/sdltutorial/surfaceexample.cpp | UTF-8 | 1,419 | 2.765625 | 3 | [] | no_license | //
// surfaceexample.cpp
// sdltutorial
//
// Created by Siddharth on 04/06/19.
// Copyright © 2019 Siddharth. All rights reserved.
//
//#include "SDLHeader.h"
//#include <stdio.h>
//
//const int WINDOW_WIDTH = 640;
//const int WINDOW_HEIGHT = 480;
//const char* win_name = "SDL Tutorial Test";
//
//int main(int argc, char * argv[]){
// printf("Entering the application");
// SDL_Window* s_window = NULL;
// SDL_Renderer* s_renderer = NULL;
//
// if(SDL_Init(SDL_INIT_VIDEO)<0){
// printf("Error while initialising SDL: %s \n", SDL_GetError());
// }else{
// //Create a SDL window
// s_window = SDL_CreateWindow(win_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
// if(s_window == NULL){
// printf("Error creating a window in SDL: %s \n", SDL_GetError());
// }else{
// //Create a renderer
// s_renderer = SDL_CreateRenderer(s_window, -1, 0);
// //Draw the color
// SDL_SetRenderDrawColor(s_renderer, 0xCD, 0xAA, 0xAB, 0xff);
// //Clear the screen
// SDL_RenderClear(s_renderer);
// //Render it
// SDL_RenderPresent(s_renderer);
// //Delay for 6 seconds
// SDL_Delay(6000);
// }
// }
// //QUIT SDL
// SDL_Quit();
// printf("Quitting the application");
// return 0;
//}
| true |
86e337d73996eacbf9b74374b26989ff4b512ee2 | C++ | frodal/Visualizer | /Visualizer/src/tests/Test.h | UTF-8 | 1,101 | 2.921875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "PreCompiledHeader.h"
#include "Window.h"
namespace Test {
class Test
{
public:
Test() : testName("Unknown") {}
Test(std::string& name) : testName(name) {};
Test(const char* name) : testName(name) {};
virtual ~Test() {}
virtual void OnUpdate(float deltaTime) {}
virtual void OnRender() {}
virtual void OnImGuiRender() {}
virtual void SetWindow(Window* window) { this->window = window; }
virtual std::string GetTestName() { return "Test: " + testName; }
protected:
std::string testName;
Window* window = nullptr;
};
class TestMenu : public Test
{
public:
TestMenu(Test*& currentTestPointer, Window* window);
virtual void OnImGuiRender() override;
virtual std::string GetTestName() override;
template<typename T>
void RegisterTest(const std::string& name)
{
std::cout << "Registering test " << name << std::endl;
tests.push_back(std::make_pair(name, [](std::string& _name) {return new T(_name); }));
}
private:
Test*& currentTest;
std::vector<std::pair<std::string, std::function<Test* (std::string&)>>> tests;
};
} | true |
b4a43dd90c6cfe6505981d3cc5933dbf409b6c74 | C++ | AppleTater/CS100-Labs | /lab-04-strategy-pattern-sigsegv-noises/SelectionSort.hpp | UTF-8 | 550 | 2.984375 | 3 | [] | no_license | #ifndef _SELECTION_SORT_HPP_
#define _SELECTION_SORT_HPP_
#include "container.hpp"
#include "sort.hpp"
#include <vector>
using namespace std;
class SelectionSort : public Sort {
public:
SelectionSort() {};
virtual void sort(Container* container) {
int min, i, j;
int size = container->size();
for(i = 0; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) {
if (container->at(j)->evaluate() < container->at(min)->evaluate()) {
min = j; }
}
container->swap(min, i);
}
}
};
#endif
| true |
727ecafdd3c95bc47f640311190d70e43f4ac2e9 | C++ | Starwolf-001/Real-Time_Image_Stitching | /Blending/main.cpp | UTF-8 | 4,156 | 2.875 | 3 | [] | no_license | #include "opencv2/opencv.hpp"
using namespace cv;
int value = 2;
// Taken from http://www.morethantechnical.com/2011/11/13/just-a-simple-laplacian-pyramid-blender-using-opencv-wcode/
class LaplacianBlending {
private:
int levels;
Mat currentImg;
Mat _down;
Mat down;
Mat up;
Mat_<Vec3f> left;
Mat_<Vec3f> right;
Mat_<float> blendMask;
vector<Mat_<Vec3f>> leftLapPyr,rightLapPyr,resultLapPyr;
Mat leftSmallestLevel, rightSmallestLevel, resultSmallestLevel;
//masks are 3-channels for easier multiplication with RGB
vector<Mat_<Vec3f>> maskGaussianPyramid;
void buildPyramids() {
buildLaplacianPyramid(left, leftLapPyr, leftSmallestLevel);
buildLaplacianPyramid(right, rightLapPyr, rightSmallestLevel);
buildGaussianPyramid();
}
void buildGaussianPyramid() {
assert(leftLapPyr.size() > 0);
maskGaussianPyramid.clear();
cvtColor(blendMask, currentImg, CV_GRAY2BGR);
// For the highest level
maskGaussianPyramid.push_back(currentImg);
currentImg = blendMask;
for (int l = 1; l < levels + 1; l++) {
if (leftLapPyr.size() > l) {
pyrDown(currentImg, _down, leftLapPyr[l].size());
} else {
// For the smallest level
pyrDown(currentImg, _down, leftSmallestLevel.size());
}
cvtColor(_down, down, CV_GRAY2BGR);
maskGaussianPyramid.push_back(down);
currentImg = _down;
}
}
void buildLaplacianPyramid(const Mat& img, vector<Mat_<Vec3f> >& lapPyr, Mat& smallestLevel) {
lapPyr.clear();
Mat currentImg = img;
for (int l = 0; l < levels; l++) {
pyrDown(currentImg, down);
pyrUp(down, up, currentImg.size());
Mat lap = currentImg - up;
lapPyr.push_back(lap);
currentImg = down;
}
currentImg.copyTo(smallestLevel);
}
Mat_<Vec3f> reconstructImgFromLapPyramid() {
Mat currentImg = resultSmallestLevel;
for (int l = levels - 1; l >= 0; l--) {
pyrUp(currentImg, up, resultLapPyr[l].size());
currentImg = up + resultLapPyr[l];
}
return currentImg;
}
void blendLapPyrs() {
resultSmallestLevel = leftSmallestLevel.mul(maskGaussianPyramid.back()) +
rightSmallestLevel.mul(Scalar(1.0, 1.0, 1.0) - maskGaussianPyramid.back());
for (int l = 0; l < levels; l++) {
Mat A = leftLapPyr[l].mul(maskGaussianPyramid[l]);
Mat antiMask = Scalar(1.0, 1.0, 1.0) - maskGaussianPyramid[l];
Mat B = rightLapPyr[l].mul(antiMask);
Mat_<Vec3f> blendedLevel = A + B;
resultLapPyr.push_back(blendedLevel);
}
}
public:
LaplacianBlending(const Mat_<Vec3f>& _left, const Mat_<Vec3f>& _right, const Mat_<float>& _blendMask, int _levels):
left(_left),right(_right),blendMask(_blendMask),levels(_levels)
{
assert(_left.size() == _right.size());
assert(_left.size() == _blendMask.size());
buildPyramids();
blendLapPyrs();
};
Mat_<Vec3f> blend() {
return reconstructImgFromLapPyramid();
}
};
Mat_<Vec3f> LaplacianBlend(const Mat_<Vec3f>& l, const Mat_<Vec3f>& r, const Mat_<float>& m) {
LaplacianBlending lb(l, r, m, 4);
return lb.blend();
}
int main(int argc, char** argv) {
// Input two images
Mat image_1 = imread("birdseye_blend_1.jpg");
Mat image_2 = imread("birdseye_blend_2.jpg");
// Convert to 32 float
Mat_<Vec3f> leftImage;
image_1.convertTo (leftImage, CV_32F, 1.0/255.0);
Mat_<Vec3f> rightImage;
image_2.convertTo(rightImage, CV_32F, 1.0/255.0);
Mat_<float> matrix (leftImage.rows, leftImage.cols, 0.0);
// Take value of each of the input images
// Default 2 means half of each image_1 and image_2
matrix (Range::all(), Range (0, matrix.cols / value)) = 1.0;
Mat_<Vec3f> blend = LaplacianBlend (leftImage, rightImage, matrix);
// Write image
imshow("Blended Image", blend);
waitKey();
}
| true |
1daa331b564e1b5edc4765251db7ee8de667f12f | C++ | MSergiev/EGT-course | /Tetris/Button.cpp | UTF-8 | 1,461 | 3.1875 | 3 | [] | no_license | #include "Button.h"
Button::Button() : TextTexture()
{
button.x = 0;
button.y = 0;
button.w = 0;
button.h = 0;
pressed = false;
}
Button::~Button()
{
}
int Button::getWidth()
{
return button.w;
}
int Button::getHeight()
{
return button.h;
}
void Button::render( SDL_Renderer*& renderer, int x, int y )
{
// Set draw color to gray
SDL_SetRenderDrawColor( renderer, 0x69, 0x69, 0x69, 0xFF );
// Set render coordinates
button.x = x;
button.y = y;
// Draw button outline
SDL_RenderDrawRect( renderer, &button );
// Render button text
if( pressed )
TextTexture::render( renderer, x + ( BUTTON_PADDING / 2 ) + ( BUTTON_PADDING / 4 ),
y + ( BUTTON_PADDING / 2 ) + ( BUTTON_PADDING / 4 ) );
else
TextTexture::render( renderer, x + ( BUTTON_PADDING / 2 ),
y + ( BUTTON_PADDING / 2 ) );
}
void Button::remake( SDL_Renderer*& renderer, const char* text, TTF_Font*& font )
{
// Remake the texture
TextTexture::remake( renderer, text, font );
// Set button to be 10px bigger
button.w = TextTexture::getWidth() + BUTTON_PADDING;
button.h = TextTexture::getHeight() + BUTTON_PADDING;
}
bool Button::isIn( int x, int y )
{
if( x < button.x || x > ( button.x + button.w ) )
return false;
else if( y < button.y || y > ( button.y + button.h ) )
return false;
return true;
}
void Button::press()
{
pressed = true;
}
void Button::release()
{
pressed = false;
}
bool Button::isPressed()
{
return pressed;
}
| true |
a3bbebab5a88bfc937bccfd3940806057c9bb25c | C++ | MadPidgeon/Order-versus-Chaos | /sat/visual.cc | UTF-8 | 728 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <string>
const int dx[4] = { -1, 0, 1, 1 };
const int dy[4] = { 1, 1, 1, 0 };
const std::string arrow[] = { "↗", "→", "↘", "↓" , "↙", "←", "↖", "↑" };
int main() {
int G[8][8];
std::string S;
while( std::cin >> S ) {
if( S[0] == 's' or S[0] == 'S' or S[0] == 'v' or S[0] == '0' )
continue;
int num = stoi( S );
if( num > 0 ) {
num--;
int d = num/64;
int x = (num%64) / 8;
int y = (num%64) % 8;
int nx = (x + dx[d] + 8) % 8;
int ny = (y + dy[d] + 8) % 8;
G[x][y] = d;
G[nx][ny] = d+4;
}
}
for( int i = 0; i < 8; ++i ) {
for( int j = 0; j < 8; ++j )
std::cout << arrow[G[i][j]] << " ";
std::cout << std::endl;
}
return 0;
}
| true |
79fe936b02930bb7c268882adc26cc78d89b9648 | C++ | MashaIvanova5/Calculator | /Functii.cpp | UTF-8 | 7,764 | 3.078125 | 3 | [] | no_license |
#include "Functii.h"
bool error(std::string s)//неверно написаны знаки возле скобок
{
if (std::count(s.begin(), s.end(), '(') != std::count(s.begin(), s.end(), ')'))
{
return true;
}
else
if (s.find("*)") != std::string::npos || s.find("/)") != std::string::npos || s.find("-)") != std::string::npos || s.find("+)") != std::string::npos || s.find("^)") != std::string::npos)
{
return true;
}
else
if (s.find("--") != std::string::npos || s.find("-+") != std::string::npos || s.find("+-") != std::string::npos || s.find("++") != std::string::npos || s.find("*-") != std::string::npos || s.find("*+") != std::string::npos || s.find("*/") != std::string::npos || s.find("**") != std::string::npos || s.find("-*") != std::string::npos || s.find("+*") != std::string::npos || s.find("/*") != std::string::npos || s.find("/-") != std::string::npos || s.find("/+") != std::string::npos || s.find("//") != std::string::npos || s.find("+/") != std::string::npos || s.find("-/") != std::string::npos || s.find("^*") != std::string::npos || s.find("^-") != std::string::npos || s.find("^+") != std::string::npos || s.find("^/") != std::string::npos || s.find("^^") != std::string::npos || s.find("-^") != std::string::npos || s.find("+^") != std::string::npos || s.find("*^") != std::string::npos || s.find("/*") != std::string::npos)
{
return true;
}
else return false;
}
bool isSeparator(char s)//это разделитель
{
std::string seps = " ";
if (seps.find(s) == std::string::npos)//если не встречен пробел, то...
{
return false; //вернуть false
}
else
return true;//иначе вернуть true
}
int priority(char s)//приоритетность: + и - это 1, * и / это 2, ^ это 3
{
switch (s)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
}
return 0;
}
bool isOperator(char s)//это опрератор...
{
std::string seps = "-+/*^()";
if (seps.find(s) == std::string::npos)//если не встречен оператор, то...
{
return false;//вернуть false
}
else
return true;//иначе вернуть true
}
float doIt(char s, float a, float b)//считаем в зависимости от встреченного оператора
{
switch (s)
{
case '+':
return a + b;//сложение
case '-':
return a - b;//вычитание
case '*':
return a * b;//умножение
case '/':
return a / b;//деление
case '^':
return std::pow(a, b);//степень
}
return 0;
}
std::string trigonometry(std::string input, int buf)//для излечения из скобок у тригоном и экспоненты, где buf-позиция начала выражения
{
int open = 1;
int close = 0;
int i = buf + 4;
while (close != open)
{
if (input[i] == '(')
{
open += 1;
}
else if (input[i] == ')')
{
close += 1;
}
i += 1;
}
std::string sub = input.substr(buf + 3, i - buf - 3);//присваиваем подстроку вида (...)
return sub;
}
std::string trigonometryforsqrt(std::string input, int buf)//для излечения из скобок у корня, где buf-позиция начала выражения
{
int open = 1;
int close = 0;
int i = buf + 5;
while (close != open)
{
if (input[i] == '(')
{
open += 1;
}
else if (input[i] == ')')
{
close += 1;
}
i += 1;
}
std::string sub = input.substr(buf + 3, i - buf - 3);
return sub;
}
float counter(std::string input)
{
std::map<std::string, float> constants{ {"pi", M_PI},{"e", exp(1)} };
std::stack<float> numbers;
std::stack<char> operations;
bool unMinus = true;
for (int i = 0; i < static_cast<int>(input.length()); i++)
{
if (isSeparator(input[i]))
{
continue;
}
if (isOperator(input[i]))
{
if (operations.empty())
{
if ((numbers.empty()) && (unMinus))
{
numbers.push(0);
}
operations.push(input[i]);
unMinus = false;
}
else
if (input[i] == '(')
{
operations.push(input[i]);
unMinus = true;
}
else
if (input[i] == ')')
{
while (operations.top() != '(')
{
float second = numbers.top();
numbers.pop();
float first = numbers.top();
numbers.pop();
float result = doIt(operations.top(), first, second);
if (std::isinf(result))
{
std::cout << "Деление на ноль\n";
return 0;
}
numbers.push(result);
operations.pop();
}
operations.pop();
}
else
if (operations.top() == '(' && unMinus)
{
numbers.push(0);
operations.push(input[i]);
}
else
if ((priority(input[i]) > priority(operations.top())) || (operations.top() == '('))
{
operations.push(input[i]);
}
else
{
float second = numbers.top();
numbers.pop();
float first = numbers.top();
numbers.pop();
float result = doIt(operations.top(), first, second);
if (std::isinf(result))
{
std::cout << "Деление на ноль\n";
return 0;
}
numbers.push(result);
operations.pop();
operations.push(input[i]);
}
continue;
}
if (isdigit(input[i]))
{
unMinus = false;
std::string longNumber;
while (!isSeparator(input[i]) && !isOperator(input[i]) && i < static_cast<int>(input.length()))
{
longNumber += input[i];
i++;
}
i--;
numbers.push(std::stof(longNumber));
}
else
{
unMinus = false;
std::string cons;//прога догадывается, что встречена константа
while (!isSeparator(input[i]) && !isOperator(input[i]) && i < static_cast<int>(input.length()))
{
cons += input[i];
i++;
}
i--;
numbers.push(constants[cons]);
}
}
while (!operations.empty())
{
float second = numbers.top();
numbers.pop();
float first = numbers.top();
numbers.pop();
float result = doIt(operations.top(), first, second);
if (std::isinf(result))
{
std::cout << "Деление на ноль/n";
return 0;
}
numbers.push(result);
operations.pop();
}
return numbers.top();
}
| true |
8d80472891437da26517ad4e020e223ea22cf05e | C++ | adanil/CompetitiveProgramming | /ACMP113/main.cpp | UTF-8 | 1,364 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
long long n;
cin >> n;
vector<vector<char>> table(n,vector<char>(n,0));
for (long long i = 0;i < n;i++){
for (long long j = 0;j < n;j++)
cin >> table[i][j];
}
vector<vector<long long>> dp(n,vector<long long>(n,0));
for(long long i = 0;i < n;i++) {
for (long long j = n - 1; j >= 0; j--) {
if (table[i][j] != '0'){
dp[i][j] = 1;
}
else{
dp[i][j] = 0;
}
}
}
long long ans = 0;
if (n > 1){
for (long long i = 1;i < n;i++){
for (long long j = 1;j < n;j++){
if (dp[i][j] == 0)
continue;
vector<long long> thr;
thr.push_back(dp[i-1][j]);
thr.push_back(dp[i][j-1]);
thr.push_back(dp[i-1][j-1]);
dp[i][j] = *min_element(thr.begin(),thr.end()) + 1;
}
}
for (long long i = 0;i < n;i++){
for (long long j = 0;j < n;j++){
if (dp[i][j] > ans)
ans = dp[i][j];
}
}
}
else{
if (dp[0][0] == 1)
ans = 1;
}
cout << ans*ans << endl;
return 0;
} | true |
ee3089e5e279d41b5233b1eca06e0a586a5af1a7 | C++ | lemospring/brynet | /tests/test_stack.cpp | UTF-8 | 1,412 | 2.921875 | 3 | [
"ICU",
"MIT"
] | permissive | #define CATCH_CONFIG_MAIN// This tells Catch to provide a main() - only do this in one cpp file
#include <brynet/base/Stack.hpp>
#include "catch.hpp"
TEST_CASE("Stack are computed", "[Stack]")
{
using namespace brynet::base;
const size_t StackNum = 10;
auto stack = stack_new(StackNum, sizeof(size_t));
REQUIRE(stack_num(stack) == 0);
REQUIRE(stack_size(stack) == StackNum);
REQUIRE(!stack_isfull(stack));
REQUIRE(stack_popback(stack) == nullptr);
REQUIRE(stack_popfront(stack) == nullptr);
for (size_t i = 0; i < StackNum; i++)
{
REQUIRE(stack_push(stack, &i));
}
REQUIRE(stack_num(stack) == StackNum);
REQUIRE(stack_isfull(stack));
for (size_t i = 0; i < StackNum; i++)
{
REQUIRE(*(size_t*) stack_popfront(stack) == i);
}
REQUIRE(stack_popback(stack) == nullptr);
REQUIRE(stack_popfront(stack) == nullptr);
stack_init(stack);
REQUIRE(!stack_isfull(stack));
REQUIRE(stack_popback(stack) == nullptr);
REQUIRE(stack_popfront(stack) == nullptr);
for (size_t i = 0; i < StackNum; i++)
{
REQUIRE(stack_push(stack, &i));
}
for (int i = StackNum - 1; i >= 0; i--)
{
REQUIRE(*(size_t*) stack_popback(stack) == (size_t) i);
}
REQUIRE(stack_popback(stack) == nullptr);
REQUIRE(stack_popfront(stack) == nullptr);
stack_delete(stack);
stack = nullptr;
}
| true |
1c7737d12ac1bde579531352c497111afea28118 | C++ | ghyess2/haodifang | /1086.cpp | UTF-8 | 278 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int main(){
long int a;
cin>>a;
do{
if(a%2!=0) {
cout<<a<<"*3+1="<<a*3+1<<endl;
a=a*3+1;
}
else {
cout<<a<<"/2="<<a/2<<endl;
a/=2;
}
}
while(a!=1);
cout<<"End"<<endl;
return 0;
}
| true |
e2666c9e661947a6eeb38a01b11d1f39a325c0d5 | C++ | krishankant10/C-language | /ch7_1.cpp | UTF-8 | 611 | 3.203125 | 3 | [] | no_license | 1. Solution: The error, could not find a match for space::space (int) in function space operator :: ++(), occurs. The statement, return Space(mCount) creates a temporary object. It calls a constructor with one int variable and it is not available in this program. The constructor to be included in the program is
Space(int i)
{
}
The correct program is:
#include <iostream.h>
class Space
{
int mCount;
public:
Space()
{
mCount = 0;
}
Space(int i)
{
}
Space operator ++()
{
mCount++;
return Space(mCount);
}
};
void main()
{
Space objSpace;
objSpace++;
} | true |
c1300a8d13a21374f118723b45d8b217f7f065d2 | C++ | ccdxc/logSurvey | /data/crawl/squid/hunk_129.cpp | UTF-8 | 871 | 2.625 | 3 | [] | no_license | fprintf( stderr, "%c requires a regex pattern argument!\n", option );
exit(1);
}
- if ( head == 0 )
- tail = head = new REList( optarg, option=='E' );
- else {
- tail->next = new REList( optarg, option=='E' );
- tail = tail->next;
+ try { // std::regex constructor throws on pattern errors
+ if (!head)
+ tail = head = new REList( optarg, option=='E' );
+ else {
+ tail->next = new REList( optarg, option=='E' );
+ tail = tail->next;
+ }
+ } catch (std::regex_error &e) {
+ fprintf(stderr, "%c contains invalid regular expression: %s\n", option, optarg);
+ exit(1);
}
break;
| true |
3727e51cff8c9c4d43de9039727be05fdaf1d6dc | C++ | maggieelli/ghost-racer | /StudentWorld.cpp | UTF-8 | 15,009 | 3.015625 | 3 | [] | no_license | #include "StudentWorld.h"
#include "Actor.h"
#include "GameConstants.h"
#include <string>
#include <sstream>
using namespace std;
GameWorld* createStudentWorld(string assetPath)
{
return new StudentWorld(assetPath);
}
// Students: Add code to this file, StudentWorld.h, Actor.h, and Actor.cpp
StudentWorld::StudentWorld(string assetPath)
: GameWorld(assetPath)
{
m_gr = nullptr;
m_last_white_border_y = 0;
m_nSouls = getLevel() * 2 + 5;
m_soulsSaved = 0;
m_bonus = START_BONUS;
}
// calls cleanUp method
StudentWorld::~StudentWorld() {
cleanUp();
}
// dynamically adds Ghost Racer and border lines
int StudentWorld::init()
{
m_nSouls = getLevel() * 2 + 5;
m_soulsSaved = 0;
m_bonus = START_BONUS;
// adds Ghost Racer
m_gr = new GhostRacer(this);
actorList.push_back(m_gr);
// adds border lines
insertBorderLines();
return GWSTATUS_CONTINUE_GAME;
}
int StudentWorld::move()
{
// This code is here merely to allow the game to build, run, and terminate after you hit enter.
// Notice that the return value GWSTATUS_PLAYER_DIED will cause our framework to end the current level.
list<Actor*>::iterator it;
it = actorList.begin();
// for every alive actor
while (it != actorList.end() && (*it)->isAlive()) {
// call the doSomething function
(*it)->doSomething();
// if Ghost Racer is dead now, decrement lives
if (!m_gr->isAlive()) {
decLives();
return GWSTATUS_PLAYER_DIED;
}
// if correct number of souls to save has been fulfilled
if (m_nSouls - m_soulsSaved <= 0) {
// increment score by bonus
increaseScore(m_bonus);
playSound(SOUND_FINISHED_LEVEL);
return GWSTATUS_FINISHED_LEVEL;
}
it++;
}
it = actorList.begin();
// delete all dead actors
while (it != actorList.end()) {
if (!(*it)->isAlive()) {
delete *it;
it = actorList.erase(it);
it--;
}
it++;
}
// adjust last white border's y-position
m_last_white_border_y += (-4 - m_gr->getVertSpeed());
// add actors if necessary
addNewBorderLines();
addNewHumanPed();
addNewZombiePed();
addNewZombieCabs();
addNewOilSlick();
addNewHolyWaterGoodie();
addNewLostSoulGoodie();
// decrement bonus each tick
if (m_bonus > 0) {
m_bonus--;
}
// update status text
updateStatusText();
return GWSTATUS_CONTINUE_GAME;
}
void StudentWorld::cleanUp()
{
// delete every actor in list
list<Actor*>::iterator it;
it = actorList.begin();
while (!actorList.empty()) {
delete *it;
it = actorList.erase(it);
}
}
GhostRacer* StudentWorld::getGR() {
return m_gr;
}
// adds new oil slick at specified location where zombie cab is destroyed
void StudentWorld::addNewOilSlick(double posX, double posY) {
actorList.push_back(new OilSlick(this, posX, posY, randInt(2, 5)));
}
// adds new healing goodie at specified location where zombie pedestrian is destroyed
void StudentWorld::addNewHealingGoodie(double posX, double posY) {
actorList.push_back(new HealingGoodie(this, posX, posY));
}
// adds new holy water projectile at specified location with specified direction
void StudentWorld::addNewHolyWaterProjectile() {
double posX;
double posY;
m_gr->getPositionInThisDirection(m_gr->getDirection(), SPRITE_HEIGHT, posX, posY);
actorList.push_back(new HolyWaterProjectile(this, posX, posY, m_gr->getDirection()));
}
// returns true if the two actors are overlapping, false if not
bool StudentWorld::overlapping(Actor* ac1, Actor* ac2) {
double delta_x = abs(ac1->getX() - ac2->getX());
double delta_y = abs(ac1->getY() - ac2->getY());
double radius_sum = ac1->getRadius() + ac2->getRadius();
if (delta_x < (radius_sum * 0.25) && delta_y < (radius_sum * 0.6)) {
return true;
}
return false;
}
// will spray a holy water affected actor if it is overlapping the holy water projectile and return true, false if there is no actor to be sprayed
bool StudentWorld::sprayOverlappingHolyWaterAffectedActor(HolyWaterProjectile* hw) {
list<Actor*>::iterator it;
it = actorList.begin();
// for every actor
while (it != actorList.end()) {
// if it is alive and is overlapping the holy water projectile
if ((*it)->isAlive() && overlapping((*it), hw)) {
// return true if it is sprayed
if ((*it)->sprayIfAppropriate()) {
return true;
}
}
it++;
}
// otherwise return false if nothing is sprayed
return false;
}
// returns the closest collision avoidance worthy actor in front or behind the zombie cab
Actor* StudentWorld::closestCollisionAvoidanceWorthyActor(ZombieCab* zc, string front_or_back) {
list<Actor*>::iterator it;
it = actorList.begin();
Actor* closestFront = nullptr;
Actor* closestBack = nullptr;
// for every actor
while (it != actorList.end()) {
// if it is not the zombie cab we are looking at and it is collision avoidance worthy
if ((*it) != zc && (*it)->isCollisionAvoidanceWorthy()) {
// if it is in the same lane as the zombie cab
if (abs((*it)->getX() - zc->getX()) < ROAD_WIDTH/6) {
// if we are looking at the front
if (front_or_back == "front") {
// if the actor is in front of the zombie cab and is the closest one, set closestFront to that actor
if ((*it)->getY() - zc->getY() > 0) {
if (closestFront == nullptr) {
closestFront = (*it);
}
else {
if ((*it)->getY() < closestFront->getY()) {
closestFront = (*it);
}
}
}
}
// else if we are looking at the back
else if (front_or_back == "back") {
// if the actor is behind the zombie cab and is the closest one, set closestBack to that actor
if ((*it)->getY() - zc->getY() < 0) {
if (closestBack == nullptr) {
closestBack = (*it);
}
else {
if ((*it)->getY() > closestBack->getY()) {
closestBack = (*it);
}
}
}
}
}
}
it++;
}
// return the closest collision avoidance worthy actor in the front or back depending on which we are looking for, return nullptr if there isn't one
if (front_or_back == "front") {
return closestFront;
}
return closestBack;
}
// increment number of souls saved
void StudentWorld::saveSoul() {
m_soulsSaved++;
}
// insert border lines called fron init(), fill screen with border lines
void StudentWorld::insertBorderLines() {
// add yellow border lines
for (int i = 0; i < VIEW_HEIGHT/SPRITE_HEIGHT; i++) {
actorList.push_back(new BorderLine(this, IID_YELLOW_BORDER_LINE, LEFT_EDGE, i * SPRITE_HEIGHT));
actorList.push_back(new BorderLine(this, IID_YELLOW_BORDER_LINE, RIGHT_EDGE, i * SPRITE_HEIGHT));
}
double last_y = 0;
for (int i = 0; i < (VIEW_HEIGHT / (4 * SPRITE_HEIGHT)); i++) {
actorList.push_back(new BorderLine(this, IID_WHITE_BORDER_LINE, LEFT_WHITE_BORDER_LINE, i * (4 * SPRITE_HEIGHT)));
actorList.push_back(new BorderLine(this, IID_WHITE_BORDER_LINE, RIGHT_WHITE_BORDER_LINE, i * (4 * SPRITE_HEIGHT)));
// keep track of y position of last white border line added
last_y = i * (4 * SPRITE_HEIGHT);
}
// keep y position of last white border line added in member variable
m_last_white_border_y = last_y;
}
// checks if new border lines need to be added, then adds if necessary
void StudentWorld::addNewBorderLines() {
int new_border_y = VIEW_HEIGHT - SPRITE_HEIGHT;
int delta_y = new_border_y - m_last_white_border_y;
// if yellow border lines should be added, add them
if (delta_y >= SPRITE_HEIGHT) {
actorList.push_back(new BorderLine(this, IID_YELLOW_BORDER_LINE, LEFT_EDGE, new_border_y));
actorList.push_back(new BorderLine(this, IID_YELLOW_BORDER_LINE, RIGHT_EDGE, new_border_y));
}
// if white border lines should be added, add them
if (delta_y >= (4 * SPRITE_HEIGHT)) {
actorList.push_back(new BorderLine(this, IID_WHITE_BORDER_LINE, LEFT_WHITE_BORDER_LINE, new_border_y));
actorList.push_back(new BorderLine(this, IID_WHITE_BORDER_LINE, RIGHT_WHITE_BORDER_LINE, new_border_y));
// keep y position of last white border line added in member variable
m_last_white_border_y = new_border_y;
}
}
// randomly adds new human pedestrian
void StudentWorld::addNewHumanPed() {
int chance = max(200 - getLevel() * 10, 30);
int rand = randInt(0, chance - 1);
if (rand == 0) {
int rand_x = randInt(0, VIEW_WIDTH);
actorList.push_back(new HumanPed(this, rand_x, VIEW_HEIGHT));
}
}
// randomly adds new zombie pedestrian
void StudentWorld::addNewZombiePed() {
int chance = max(100 - getLevel() * 10, 20);
int rand = randInt(0, chance - 1);
if (rand == 0) {
int rand_x = randInt(0, VIEW_WIDTH);
actorList.push_back(new ZombiePed(this, rand_x, VIEW_HEIGHT));
}
}
// randomly adds new zombie cabs
void StudentWorld::addNewZombieCabs() {
int chance = max(100 - getLevel() * 10, 20);
int rand = randInt(0, chance - 1);
if (rand == 0) {
// pick random lane (0 is left, 1 is middle, 2 is right)
int cur_lane = randInt(0, 2);
// for each lane
for (int i = 0; i < 3; i++) {
// find the closest collision avoidance worthy actor to the bottom of the screen
Actor* ac_bottom = closestCollisionAvoidanceWorthyActor("bottom", LEFT_EDGE + (ROAD_WIDTH/3 * cur_lane), LEFT_EDGE + (ROAD_WIDTH/3 * (1 + cur_lane)));
// if there is none or if it is towards the top of the screen, add a zombie cab at specified location at bottom of the lane, break
if (ac_bottom == nullptr || ac_bottom->getY() > (VIEW_HEIGHT / 3)) {
actorList.push_back(new ZombieCab(this, m_gr->getVertSpeed() + randInt(2, 4), FIRST_LANE_CENTER + (ROAD_WIDTH/3 * cur_lane), SPRITE_HEIGHT/2));
break;
}
// if there is a collision avoidance worthy actor at the bottom of the lane, find the closest collision avoidance worthy actor to the top of the screen
Actor* ac_top = closestCollisionAvoidanceWorthyActor("top", LEFT_EDGE + (ROAD_WIDTH/3 * cur_lane), LEFT_EDGE + (ROAD_WIDTH/3 * (1 + cur_lane)));
// if there is none or if it is towards the bottom of the screen, add a zombie cab at specified location at top of the lane, break
if (ac_top == nullptr || ac_top->getY() < (VIEW_HEIGHT * 2 / 3)) {
actorList.push_back(new ZombieCab(this, m_gr->getVertSpeed() - randInt(2, 4), FIRST_LANE_CENTER + (ROAD_WIDTH/3 * cur_lane), VIEW_HEIGHT - SPRITE_HEIGHT/2));
break;
}
// otherwise try another lane
if (cur_lane < 2) {
cur_lane++;
}
else {
cur_lane = 0;
}
}
}
}
// randomly adds new oil slick
void StudentWorld::addNewOilSlick() {
int chance = max(150 - getLevel() * 10, 40);
int rand = randInt(0, chance - 1);
if (rand == 0) {
int rand_x = randInt(LEFT_EDGE, RIGHT_EDGE);
actorList.push_back(new OilSlick(this, rand_x, VIEW_HEIGHT, randInt(2, 5)));
}
}
// randomly adds new holy water goodie
void StudentWorld::addNewHolyWaterGoodie() {
int chance = 100 + 10 * getLevel();
int rand = randInt(0, chance - 1);
if (rand == 0) {
int rand_x = randInt(LEFT_EDGE, RIGHT_EDGE);
actorList.push_back(new HolyWaterGoodie(this, rand_x, VIEW_HEIGHT));
}
}
// randomly adds new lost soul goodie
void StudentWorld::addNewLostSoulGoodie() {
int chance = 100;
int rand = randInt(0, chance - 1);
if (rand == 0) {
int rand_x = randInt(LEFT_EDGE, RIGHT_EDGE);
actorList.push_back(new SoulGoodie(this, rand_x, VIEW_HEIGHT));
}
}
Actor* StudentWorld::closestCollisionAvoidanceWorthyActor(string top_or_bottom, double left_boundary, double right_boundary) {
list<Actor*>::iterator it;
it = actorList.begin();
Actor* closestTop = nullptr;
Actor* closestBottom = nullptr;
// for every actor
while (it != actorList.end()) {
// if it is collision avoidance worthy
if ((*it)->isCollisionAvoidanceWorthy()) {
// if it is within the x bounds that are specified (lane bounds)
if ((*it)->getX() > left_boundary && (*it)->getX() < right_boundary) {
// if we are looking at the top of the screen
if (top_or_bottom == "top") {
// if the actor is the closest to the top, set closestTop to that actor
if (closestTop == nullptr) {
closestTop = (*it);
}
else {
if ((*it)->getY() > closestTop->getY()) {
closestTop = (*it);
}
}
}
// else if we are looking at the bottom of the screen
else if (top_or_bottom == "bottom") {
// if the actor is the closest to the bottom, set closestTop to that actor
if (closestBottom == nullptr) {
closestBottom = (*it);
}
else {
if ((*it)->getY() < closestBottom->getY()) {
closestBottom = (*it);
}
}
}
}
}
it++;
}
// return the closest collision avoidance worthy actor to the top or bottom depending on which we are looking for, return nullptr if there isn't one
if (top_or_bottom == "top") {
return closestTop;
}
return closestBottom;
}
// update status text
void StudentWorld::updateStatusText() {
ostringstream status;
status << "Score: " << getScore() << " ";
status << "Lvl: " << getLevel() << " ";
status << "Souls2Save: " << m_nSouls - m_soulsSaved << " ";
status << "Lives: " << getLives() << " ";
status << "Health: " << m_gr->getHealth() << " ";
status << "Sprays: " << m_gr->getHolyWater() << " ";
status << "Bonus: " << m_bonus;
setGameStatText(status.str());
}
| true |
dccd2f28b8516fd9b1ff00111c16846447577fbb | C++ | Phantomape/paxos | /src/comm/event.cc | UTF-8 | 1,257 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "event.h"
#include "event_loop.h"
namespace paxos {
Event::Event(EventLoop * event_loop) : event_(0), event_loop(event_loop) {
is_destroried_ = false;
}
Event::~Event() {}
int Event::OnRead() {
return -1;
}
int Event::OnWrite() {
return -1;
}
void Event::OnTimeout(const uint32_t timer_id, const int type) {}
void Event::JumpoutEpollWait() {
event_loop->JumpoutEpollWait();
}
void Event :: AddEvent(const int event) {
int previous_event = event;
event_ |= event;
if (event_ == previous_event) {
return;
}
event_loop->ModEvent(this, event_);
}
void Event::RemoveEvent(const int event) {
int previous_event = event;
event_ &= (~event);
if (event_ == previous_event) {
return;
}
if (event_ == 0) {
event_loop->RemoveEvent(this);
}
else {
event_loop->ModEvent(this, event);
}
}
void Event::AddTimer(const int timeout_ms, const int type, uint32_t& timer_id) {
event_loop->AddTimer(this, timeout_ms, type, timer_id);
}
void Event::RemoveTimer(const uint32_t timer_id) {
event_loop->RemoveTimer(timer_id);
}
void Event::Destroy() {
is_destroried_ = true;
}
const bool Event :: IsDestroy() const {
return is_destroried_;
}
} | true |
9abd45cbe9a27a81563709bbdcdbdfacb85eacf6 | C++ | Sarthakshah30/TopCoder-Solutions | /MostProfitable.cpp | UTF-8 | 4,863 | 2.625 | 3 | [] | no_license | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class MostProfitable {
public:
string bestItem(vector <int> costs, vector <int> prices, vector <int> sales, vector <string> items) {
int result = 0;
int index = -1;
for(int i = 0 ; i < costs.size() ; i++){
if(costs[i]>=prices[i])
continue;
int temp = (prices[i]-costs[i])*sales[i];
if(temp>result)
{
result = temp;
index=i;
}
}
if(index==-1)
return "";
else
return items[index];
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, vector <int> p0, vector <int> p1, vector <int> p2, vector <string> p3, bool hasAnswer, string p4) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p0[i];
}
cout << "}" << "," << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p1[i];
}
cout << "}" << "," << "{";
for (int i = 0; int(p2.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p2[i];
}
cout << "}" << "," << "{";
for (int i = 0; int(p3.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p3[i] << "\"";
}
cout << "}";
cout << "]" << endl;
MostProfitable *obj;
string answer;
obj = new MostProfitable();
clock_t startTime = clock();
answer = obj->bestItem(p0, p1, p2, p3);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "\"" << p4 << "\"" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "\"" << answer << "\"" << endl;
if (hasAnswer) {
res = answer == p4;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
vector <int> p0;
vector <int> p1;
vector <int> p2;
vector <string> p3;
string p4;
{
// ----- test 0 -----
int t0[] = {100,120,150,1000};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {110,110,200,2000};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {20,100,50,3};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
string t3[] = {"Video Card","256M Mem","CPU/Mobo combo","Complete machine"};
p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0]));
p4 = "Complete machine";
all_right = KawigiEdit_RunTest(0, p0, p1, p2, p3, true, p4) && all_right;
// ------------------
}
{
// ----- test 1 -----
int t0[] = {100};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {100};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {134};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
string t3[] = {"Service, at cost"};
p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0]));
p4 = "";
all_right = KawigiEdit_RunTest(1, p0, p1, p2, p3, true, p4) && all_right;
// ------------------
}
{
// ----- test 2 -----
int t0[] = {38,24};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {37,23};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {1000,643};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
string t3[] = {"Letter","Postcard"};
p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0]));
p4 = "";
all_right = KawigiEdit_RunTest(2, p0, p1, p2, p3, true, p4) && all_right;
// ------------------
}
{
// ----- test 3 -----
int t0[] = {10,10};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {11,12};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {2,1};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
string t3[] = {"A","B"};
p3.assign(t3, t3 + sizeof(t3) / sizeof(t3[0]));
p4 = "A";
all_right = KawigiEdit_RunTest(3, p0, p1, p2, p3, true, p4) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| true |
fa29aea8156d9aa6ec5856e93d776e412d3f3090 | C++ | Arekushi/Finite-State-Machine-Arduino | /src/Dictionary.h | UTF-8 | 875 | 3.21875 | 3 | [] | no_license | #ifndef Dictionary_h
#define Dictionary_h
#include <Arduino.h>
#include <ArrayList.h>
template<class K, class V>
class Dictionary {
private:
ArrayList<K> *m_keys;
ArrayList<V> *m_values;
public:
Dictionary() {
m_keys = new ArrayList<K>();
m_values = new ArrayList<V>();
}
void add(K *key, V *value) {
m_keys->add(key);
m_values->add(value);
}
V *get(K *key) {
for(byte i = 0; i < m_values->length(); i++) {
if(strcmp(m_keys->data()[i], key) == 0) {
return m_values->data()[i];
}
}
return nullptr;
}
K **getKeys() {
return m_keys.data();
}
V **getValues() {
return m_values.data();
}
};
#endif
| true |
c03c3df0b13f8a6e9c58927af962da312bcadfb7 | C++ | Devforlife07/Algorithms | /DivideAndConcquer/binSearchInRotatedArray.cpp | UTF-8 | 723 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int getResult(int a[], int n, int key, int s, int e)
{
if (s > e)
return -1;
int mid = (s + e) / 2;
if (a[mid] == key)
return mid;
if (a[s] <= a[mid])
{
if (key >= a[s] and key <= a[mid])
return getResult(a, n, key, s, mid - 1);
return getResult(a, n, key, mid + 1, e);
}
if (key >= a[mid] and key <= a[e])
return getResult(a, n, key, mid + 1, e);
return getResult(a, n, s, mid - 1, key);
}
int main()
{
int a[] = {3, 4, 5, 6, 7, 8, 9, 1, 2};
int n = sizeof(a) / sizeof(a[0]);
int key = 5;
int ans = getResult(a, n, key, 0, n - 1);
cout << ans << '\n';
return 0;
} | true |
a609556520aeef0e7c47df107c89f9925de9acdd | C++ | Angeld55/Object-oriented_programming_FMI | /Week 06/GpsPath/GpsPath.h | UTF-8 | 734 | 2.859375 | 3 | [] | no_license | #pragma once
#include <cmath>
class GPSPath
{
struct Point
{
int x;
int y;
double getDist(const Point& other) const
{
int dx = x - other.x;
int dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
};
Point* data;
size_t capacity;
size_t count;
double currentPathLength;
void resize(size_t newCapacity);
void copyFrom(const GPSPath& other);
void free();
public:
GPSPath();
GPSPath(const GPSPath&);
GPSPath& operator=(const GPSPath& other);
~GPSPath();
void addPoint(int x, int y);
double getDist() const;
void setPoint(int x, int y, unsigned ind);
}; | true |
10c4865cb395620b7567a2829bea75de620fbaa0 | C++ | btbaggin/Yaffe | /Logger.cpp | UTF-8 | 898 | 2.609375 | 3 | [] | no_license | #define DEBUG_LEVEL_None 0
#define DEBUG_LEVEL_Error 1
#define DEBUG_LEVEL_All 2
//Modify this define to control the level of logging
#define DEBUG_LEVEL DEBUG_LEVEL_All
#if DEBUG_LEVEL > DEBUG_LEVEL_Error
#define YaffeLogInfo Log
#else
#define LogInfo(message, ...)
#endif
#if DEBUG_LEVEL != DEBUG_LEVEL_None
#include <stdarg.h>
#define YaffeLogError Log
#define InitializeLogger() log_handle = fopen("log.txt", "w")
#define CloseLogger() fclose(log_handle)
#else
#define LogError(message, ...)
#define InitializeLogger()
#define CloseLogger()
#endif
FILE* log_handle = nullptr;
static void Log(const char* pMessage, ...)
{
va_list args;
va_start(args, pMessage);
char buffer[4000];
vsprintf(buffer, pMessage, args);
char time[100];
GetTime(time, 100, "{%x %X} ");
fputs(time, log_handle);
fputs(buffer, log_handle);
fputc('\n', log_handle);
fflush(log_handle);
va_end(args);
} | true |
7523b11b832b50e04ee4ba9f7bf696064ba51285 | C++ | odilon-matos/LP1 | /Roteiro 8 - Questão 2/main.cpp | UTF-8 | 3,069 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include "Imovel.h"
#include "Terreno.h"
#include "Casa.h"
#include "Apartamento.h"
int main()
{
double a, adt, ac, vdc;
int ndp, qdq, ndvng;
std::string p;
Casa casa0, casa1;
Terreno terreno0, terreno1;
Apartamento apartamento0;
casa0.setEndereco();
std::cout << "Casa 0 - Pavimentos: ";
std::cin >> ndp;
casa0.setNumeroDePavimentos(ndp);
std::cout << "Casa 0 - Quartos: ";
std::cin >> qdq;
casa0.setQuantidadeDeQuartos(qdq);
std::cout << "Casa 0 - Area do Terreno: ";
std::cin >> adt;
casa0.setAreaDoTerreno(adt);
std::cout << "Casa 0 - Area Construida: ";
std::cin >> ac;
casa0.setAreaConstruida(ac);
casa1.setEndereco();
std::cout << "Casa 1 - Pavimentos: ";
std::cin >> ndp;
casa1.setNumeroDePavimentos(ndp);
std::cout << "Casa 1 - Quartos: ";
std::cin >> qdq;
casa1.setQuantidadeDeQuartos(qdq);
std::cout << "Casa 1 - Area do Terreno: ";
std::cin >> adt;
casa1.setAreaDoTerreno(adt);
std::cout << "Casa 1 - Area Construida: ";
std::cin >> ac;
casa1.setAreaConstruida(ac);
terreno0.setEndereco();
std::cout << "Terreno 0 - Area: ";
std::cin >> a;
terreno0.setArea(a);
terreno1.setEndereco();
std::cout << "Terreno 1 - Area: ";
std::cin >> a;
terreno1.setArea(a);
apartamento0.setEndereco();
std::cout << "Apartamento 0 - Posicao: ";
std::cin >> p;
apartamento0.setPosicao(p);
std::cout << "Apartamento 0 - Condominio: R$";
std::cin >> vdc;
apartamento0.setValorDoCondominio(vdc);
std::cout << "Apartamento 0 - Vagas na Garagem: ";
std::cin >> ndvng;
apartamento0.setNumeroDeVagasNaGaragem(ndvng);
Imovel * imoveis[5];
imoveis[0] = &casa0;
imoveis[1] = &casa1;
imoveis[2] = &terreno0;
imoveis[3] = &terreno1;
imoveis[4] = &apartamento0;
for(int i = 0;i < 5;i++){
std::cout << "Descricao: " << imoveis[i]->getDescricao() << std::endl;
std::cout << "Endereco: ";
imoveis[i]->getEndereco();
const char * d = imoveis[i]->getDescricao().c_str();
if(strcmp(d,"Terreno")==0){
std::cout << "Area: " << imoveis[i]->getArea() << std::endl;
}
if(strcmp(d,"Casa")==0){
std::cout << "Numero de Pavimentos: " << imoveis[i]->getNumeroDePavimentos() << std::endl;
std::cout << "Quantidade de Quartos: " << imoveis[i]->getQuantidadeDeQuartos() << std::endl;
std::cout << "Area do Terreno: " << imoveis[i]->getAreaDoTerreno() << std::endl;
std::cout << "Area Construida: " << imoveis[i]->getAreaConstruida() << std::endl;
}
if(strcmp(d,"Apartamento")==0){
std::cout << "Posicao: " << imoveis[i]->getPosicao() << std::endl;
std::cout << "Valor do Condominio: R$" << imoveis[i]->getValorDoCondominio() << std::endl;
std::cout << "Numero de Vagas na Garagem: " << imoveis[i]->getNumeroDeVagasNaGaragem() << std::endl;
}
}
return 0;
}
| true |
35d222907e4a266ce2764aa43b6660c69e70dd11 | C++ | memoa/it-obuke | /Niz brojeva.cpp | UTF-8 | 585 | 3.1875 | 3 | [] | no_license | /*
Domaci Zadatak
verzija 1
Napisati program koji unosi brojeve u niz.
Kada zbir elemenata bude 1000, prekinuti unos brojeva.
Autor: Dejan Cvijetinovic, Web Aplikacije, grupa 1
Datum: 15.10.2018
*/
#include <iostream>
using namespace std;
int main() {
int a[1000];
int n;
printf("Unesite velicinu niza: ");
scanf("%d", &n);
for (int i=0; i<n; i++) {
printf("Unesite element na poziciju %d u nizu: ", i);
scanf("%d", &a[i]);
}
printf("Uneti niz je: ");
for (int i=0; i<n; i++)
printf("%d ", a[i]);
return 0;
} | true |
429cd305a0d4f701d37f7842e289239fdc397f60 | C++ | przemykomo/cppexp | /include/Vector.hpp | UTF-8 | 1,871 | 3.84375 | 4 | [] | no_license | #pragma once
#include <initializer_list>
#include <cstring>
template<class T>
class Vector {
public:
Vector() : Vector(0) {}
Vector(int initialSize) : m_size(initialSize), m_capacity(initialSize) {
dataPtr = new T[m_size];
}
Vector(std::initializer_list<T> list) : Vector(list.size()) {
std::memcpy(dataPtr, list.begin(), sizeof(T) * m_size);
}
~Vector() {
delete [] dataPtr;
}
inline int size() {
return m_size;
}
inline int capacity() {
return m_capacity;
}
void shrinkToFit() {
if (m_size < m_capacity) {
m_capacity = m_size;
T* tmpPtr = new T[m_size];
std::memcpy(tmpPtr, dataPtr, sizeof(T) * m_size);
delete [] dataPtr;
dataPtr = tmpPtr;
}
}
void pushBack(const T& value) {
m_size++;
if (m_size > m_capacity) {
m_capacity = m_size;
T* tmpPtr = new T[m_size];
std::memcpy(tmpPtr, dataPtr, sizeof(T) * (m_size - 1));
delete [] dataPtr;
dataPtr = tmpPtr;
}
dataPtr[m_size - 1] = value;
}
void popBack() {
m_size--;
}
void pushFront(const T& value) {
m_size++;
m_capacity = m_size;
T* tmpPtr = new T[m_size];
tmpPtr[0] = value;
std::memcpy(tmpPtr + 1, dataPtr, sizeof(T) * (m_size - 1));
delete [] dataPtr;
dataPtr = tmpPtr;
}
void popFront() {
m_size--;
m_capacity = m_size;
T* tmpPtr = new T[m_size];
std::memcpy(tmpPtr, dataPtr + 1, sizeof(T) * (m_size - 1));
delete [] dataPtr;
dataPtr = tmpPtr;
}
inline T& operator[](int index) {
return dataPtr[index];
}
private:
int m_size;
int m_capacity;
T* dataPtr;
};
| true |
176995e511ef0894d63c4df5d70eede26d5c398d | C++ | alexandramoraitaki/Progintro | /askisi15.cpp | UTF-8 | 1,140 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #include "pzhelp"
#include <iostream>
#include <cstring>
using namespace std;
void justify(char array[],int k, int d, int s) {
int a=s/d;
int b=d-(s%d);
int dwritten=0;
for(int i=0; i<k; i++) {
WRITE(array[i]);
if(array[i]==' ') {
dwritten++;
for(int j=0; j<a; j++) {
WRITE(" ");
}
if(dwritten>b)
WRITE(" ");
}
}
WRITELN();
}
int main() {
int k, diakena, spaces;
char line[61],word[21];
int lwc=0;
int c;
int i=0;
int j=-1;
c=getchar();
while(c!=EOF) {
if(c!=' ' && c!='\n') {
word[i++]=c;
}
else if(i!=0) {
if(j+i<60) {
for(k=0; k<i; k++)
line[++j]=word[k];
line[++j]=' ';
lwc++;
}
else{
diakena=lwc-1;
spaces=60-j;
justify(line, j, diakena, spaces);
j=-1;
lwc=1;
k=0;
while(k<1)
line[++j]=word[k++];
line[++j]=' ';
}
i=0;
}
c=getchar();
}
for(k=0; k<j; k++)
WRITE(line[k]);
WRITELN();
}
| true |
9e27a3ceec3cd285924b96378043f9d23350f895 | C++ | roshid2500/PingingServer | /client.cpp | UTF-8 | 1,830 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <chrono>
#define PORT 12551
using namespace std;
int main() {
int sockfd, n, send;
socklen_t len;
char buffer[1024] = "hello";
struct sockaddr_in servaddr;
struct timeval t;
//set timeout val to 1
t.tv_sec = 1;
t.tv_usec = 0;
// Create a UDP socket
// Notice the use of SOCK_DGRAM for UDP packets
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
// Fill server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY; // localhost
servaddr.sin_port = htons(PORT); // port number
len = sizeof(servaddr);
//Set the timeout for the socket to 1sec
if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&t,sizeof(struct timeval)) < 0){
cout << "Error setting timeout" << endl;
}
//Loop to send 10 packets
for(unsigned i = 0; i < 10; i++){
//track time before sending the packet to server
auto t1 = chrono::high_resolution_clock::now();
int send = sendto(sockfd, (const char *)buffer, strlen(buffer),
MSG_CONFIRM, (const struct sockaddr *) &servaddr, len);
//receive packet
n = recvfrom(sockfd, (char *)buffer, sizeof(buffer),
MSG_WAITALL, ( struct sockaddr *) &servaddr, &len);
buffer[n] = '\0';
//time after receiving
auto t2 = chrono::high_resolution_clock::now();
auto t3 = (t2 - t1).count();
//output either success or timeout
if(n >= 0)
cout << "Received in " << t3 << " (nanoseconds)" << endl;
else
cout << "Packet not received; timeout" << endl;
}
return 0;
}
| true |
2013ca75665018c34945797257267ed9d1c59e21 | C++ | XinweiChai/ALGPR | /TP5/fourmi.cpp | UTF-8 | 7,224 | 2.796875 | 3 | [] | no_license | /*************************************************************
Fonctions de déplacement des fourmis
------------------------------------------------------
Auteurs : équipe pédagogique ALGPR
Date : 01/10/2009
Modifié : 10/04/2013, 04/11/2013 (Vincent Tourre)
Fichier: fourmi.cpp
*************************************************************/
#include "constantes.h"
#include "fourmi.h"
#include "math.h"
#include "proba.h"
// constantes
const int tdx[8] = {+1,+1, 0,-1,-1,-1, 0,+1}; // déplacement 5 6 7
const int tdy[8] = { 0,+1,+1,+1, 0,-1,-1,-1}; // 4 0
// 3 2 1
const int ponderation_recherche[8] = {12,2,1,1,0,1,1,2};
const int ponderation_fourmiliere[8] = {200,32,8,2,1,2,8,32};
// Vérifie si la position est possible pour une fourmi
int PositionPossible (int x, int y, t_monde environnement)
{
int resultat = 1;
// fourmi en dehors du monde ?
if ( (x<0) || (y<0) || (x>=environnement.L) || (y>=environnement.H) ) {
resultat = 0;
} else {
// fourmi sur un obstacle ?
if (environnement.mat[x][y]==OBSTACLE)
resultat = 0;
}
return resultat;
}
// indique la direction de la fourmiliere (entre 0 et 7)
int DirFourmiliere( int x, int y,int Fx, int Fy)
{
int i;
int result = -1;
int dx = Fx - x;
int dy = Fy - y;
float norme = sqrt( (float) (dx*dx + dy*dy) );
dx = (int)round(dx / norme);
dy = (int)round(dy / norme);
for (i = 0; i < 8; i++)
{
if(dx == tdx[i] && dy == tdy[i]) result = i;
}
return result;
}
// ramène x dans la fourchette [0;7]
// (meme pour x négatif)
int modulo8(int x)
{
return ( x + 8) % 8; // car x est compris entre -7 et +7
// et donc x+8 entre 1 et 15
}
// déplace une fourmi
void DeplaceFourmi( t_fourmi& fourmi, t_monde& environnement, t_matrice pheromones)
{
/*
1er mode de recherche
1) choisir la nouvelle direction
- mode recherche :
direction = ( direction + rotation ) modulo 8
avec rotation pris dans [0;7] avec des ponderation 24, 2, 1, 1, 0, 1, 1, 2
(la ponderation devient nulle si le deplacement n'est pas possible (obstacle ou bord))
- mode retour_fourmiliere
direction = ( direction_fourmiliere + rotation ) modulo 8
avec rotation pris dans [-4;4] avec des ponderation 1024, 32, 8, 2 ,1, 2, 8, 32
(la ponderation devient nulle si le deplacement n'est pas possible (obstacle ou bord))
2) avancer dans cette direction
3) - mode recherche :
si on a atteint la nourriture :
- passer en mode retour_fourmiliere
- mode retour_fourmiliere
si on a atteint la fourmiliere
- faire demi-tour
- passer en mode recherche
*/
// calcul des ponderations
/* t_poids ponderation;
int dir;
// 1) on privilégie tjs de suivre la meme direction qu'avant
for(int i=0;i<8;i++)
{
dir = modulo8( i - fourmi->direction );
ponderation[i] = ponderation_recherche[dir];
}
*/
/*
// 2) pondération avec la phéromone.
if (fourmi->recherche)
{
for(int i=0;i<8;i++)
{
int delta_dir = modulo8(i + DirFourmiliere(fourmi->x+tdx[i],fourmi->y+tdy[i],Fx,Fy) );
delta_dir = ((delta_dir+12) % 8) -4; //pour avoir delta_dir entre -4 et 3
ponderation[i] = ponderation[i] + pheromones[fourmi->x+tdx[i]][fourmi->y+tdy[i]]*(abs(delta_dir)+1);
}
}
//si on est en mode retour à la fourmillière, on ajoute la pondération
//fourmillère
if(!fourmi->recherche)
{
for(int i=0;i<8;i++)
{
int base_dir = DirFourmiliere( fourmi->x, fourmi->y, Fx, Fy);
dir = (base_dir + i) % 8;
ponderation[i] += ponderation_recherche[dir];
}
}
// si on trouve de la nourriture et qu'on en recherche
// ou si on trouve la fourmiliere, et qu'on la recherche
// alors ponderation= max
for(int i=0;i<8;i++)
{
if ( (fourmi->recherche) && (environnement[fourmi->x+tdx[i]][fourmi->y+tdy[i]]>0) )
ponderation[i]=100000;
if ( (!fourmi->recherche) && (environnement[fourmi->x+tdx[i]][fourmi->y+tdy[i]])==FOURMILLIERE)
ponderation[i]=100000;
}
*/
//on met la pondération 0 sur les obstacles.
/* for(int i=0;i<8;i++)
{
if ( !PositionPossible( fourmi->x+tdx[i], fourmi->y+tdy[i], L, H, environnement) )
ponderation[i] = 0;
}
fourmi->direction = nalea_pondere(ponderation);
*/
// 1) choix d'une direction
int ponderation[8];
int dir;
int dir_a_suivre;
int i;
// choix de la direction à suivre (vers la fourmiliere, ou la meme direction qu'avant)
if (fourmi.recherche)
dir_a_suivre = fourmi.direction;
else
dir_a_suivre = DirFourmiliere( fourmi.x, fourmi.y,environnement.Fx, environnement.Fy);
// on examine une a une les direction possibles
for(i=0;i<8;i++)
{
// nouvelle direction empruntee
dir = (dir_a_suivre + i) % 8;
// on regarde si le déplacement dans cette direction est possible
if ( PositionPossible( fourmi.x+tdx[dir], fourmi.y+tdy[dir], environnement) )
{
// si oui, on affecte la ponderation correspondant au mode de la fourmi
if (fourmi.recherche) ponderation[i] = ponderation_recherche[i];
else ponderation[i] = ponderation_fourmiliere[i];
// pondere les endroits o˘ il y a le plus de pheromones, en mode recherche
// et qui sont le plus éloignés
if (fourmi.recherche)
{
int delta_dir = DirFourmiliere(fourmi.x+tdx[dir],fourmi.y+tdy[dir],environnement.Fx,environnement.Fy) - dir;
delta_dir = ((delta_dir+12) % 8) -4; //pour avoir delta_dir entre -4 et 3
ponderation[i] = ponderation[i] + pheromones[fourmi.x+tdx[dir]][fourmi.y+tdy[dir]]*((int)fabs((float)delta_dir)+1);
}
// mais si on trouve de la nourriture, ponderation= max
if ( (fourmi.recherche) && (environnement.mat[fourmi.x+tdx[dir]][fourmi.y+tdy[dir]]>0)
&& !(fourmi.x+tdx[dir]==environnement.Fx && fourmi.y+tdy[dir]==environnement.Fy))
ponderation[i]=100000;
}
else
{
// sinon, la ponderation est nulle
ponderation[i] = 0;
}
}
// on tire une nouvelle direction, avec un random pondéré
fourmi.direction = ( dir_a_suivre + nalea_pondere(ponderation) ) % 8;
// 2) on avance dans cette direction
fourmi.x = fourmi.x + tdx[fourmi.direction];
fourmi.y = fourmi.y + tdy[fourmi.direction];
// 3) action après déplacement
if (fourmi.recherche)
{
if (environnement.mat[fourmi.x][fourmi.y]>0 && !((fourmi.x==environnement.Fx) && (fourmi.y==environnement.Fy)))
{
//printf("fourmi sur de la nourriture\n");
fourmi.recherche=0;
environnement.mat[fourmi.x][fourmi.y]--; // on enleve de la nourriture
}
}
else
{
if ( (fourmi.x==environnement.Fx) && (fourmi.y==environnement.Fy) )
{
//printf("fourmi sur la fourmillière\n");
environnement.mat[fourmi.x][fourmi.y] ++;
fourmi.recherche=1;
fourmi.direction = (fourmi.direction+4) % 8;
}
else
{
// depose pheromone là o˘ il est et sur les cases environnantes
pheromones[fourmi.x][fourmi.y]+=10;
if(pheromones[fourmi.x][fourmi.y] > PHEROMONES_MAX)
pheromones[fourmi.x][fourmi.y]=PHEROMONES_MAX;
for(i = 0; i < 8; i++)
{
if(PositionPossible(fourmi.x+tdx[i], fourmi.y+tdy[i], environnement))
{
pheromones[fourmi.x+tdx[i]][fourmi.y+tdy[i]]+=5;
if(pheromones[fourmi.x+tdx[i]][fourmi.y+tdy[i]] > PHEROMONES_MAX)
pheromones[fourmi.x+tdx[i]][fourmi.y+tdy[i]]=PHEROMONES_MAX;
}
}
}
}
}
| true |
0ec74c711941dcc6ae1037572c8ede7841b79f4b | C++ | cupcake08/LinkedList-1 | /palindromeLinkedList.cpp | UTF-8 | 1,240 | 3.125 | 3 | [] | no_license | //coding ninjas platform
/*First Approach********/
Node* reverse(Node *head)
{
if(head->next==NULL)
{
return head;
}
Node *tail=head->next;
Node *newHead=reverse(head->next);
tail->next=head;
head->next=NULL;
return newHead;
}
bool isPalindrome(Node *head)
{
Node *slow=head;
Node *fast=head;
if(head==NULL||head->next==NULL)
{
return true;
}
while(fast->next!=NULL && fast->next->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
Node *head1=slow->next;
Node *head2=head;
head1=reverse(head1);
while(head1!=NULL && head2!=NULL)
{
if(head1->data!=head2->data)
{
return false;
}
head1=head1->next;
head2=head2->next;
}
return true;
}
/**************Another Approach*******/
#include <vector>
bool isPalindrome(Node *head){
if(head==NULL) return true;
Node *temp=head;
// int l=len(head);
vector<int> v;
v.push_back(temp->data);
while(temp->next!=nullptr){
temp=temp->next;
v.push_back(temp->data);
}
int i=0,j=v.size()-1;
while(i<j){
if(v[i] != v[j]){
return false;
}
i++;
j--;
}
return true;
}
| true |
58ccf9d62fb6957c8a0b8af9fce18919a9fa14d8 | C++ | luliyucoordinate/Leetcode | /src/0996-Number-of-Squareful-Arrays/0996.cpp | UTF-8 | 744 | 2.953125 | 3 | [] | no_license | static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
int numSquarefulPerms(vector<int>& A)
{
sort(A.begin(), A.end());
int res = 0;
permute(A, 0, res);
return res;
}
private:
void permute(vector<int> A, int i, int& res)
{
if (i == A.size())
{
++res; return;
}
for (int j = i; j < A.size(); ++j)
{
if (j > i && A[i] == A[j]) continue;
swap(A[j], A[i]);
if ((i == 0) or pow((int)sqrt(A[i] + A[i-1]), 2) == A[i] + A[i-1])
{
permute(A, i + 1, res);
}
}
}
}; | true |
6d4940ad2fac90122b7fb47d6e109aad910eb1e1 | C++ | mcclown1991/RavelEngine | /Ravel Engine/Source/Systems/Scene Management/SceneManager.cpp | UTF-8 | 1,387 | 2.65625 | 3 | [] | no_license | #include "SceneManager.h"
#include "RavelEngine.h"
SceneManager * SceneManagement()
{
static SceneManager s;
return (&s);
}
SceneManager::SceneManager()
{
}
void SceneManager::Init()
{
m_currentScene = m_NextScene = std::make_pair<unsigned int, Scene*>(-1, nullptr);
}
void SceneManager::Update()
{
if (m_currentScene.first != m_NextScene.first)
LoadScene();
}
void SceneManager::LoadScene() {
//Unload current scene
if (m_currentScene.second != nullptr) {
m_currentScene.second->Free();
}
if (_scenelist.size() == 0) return;
m_currentScene.first = m_NextScene.first;
m_currentScene.second = m_NextScene.second;
m_currentScene.second->Init();
m_currentScene.second->Load();
m_currentScene.second->Start();
}
void SceneManager::LoadScene(unsigned int sceneIndex)
{
m_NextScene.first = sceneIndex;
m_NextScene.second = _scenelist[sceneIndex];
}
void SceneManager::AddScene(Scene* scene)
{
_scenelist[_scenelist.size()] = scene;
}
void SceneManager::OnExit()
{
for (auto& iter : _scenelist) {
iter.second->~Scene();
}
}
void SceneManager::Restart()
{
m_currentScene.second->Reset();
RavelEngine::GetRavelEngine()->ResetScene();
}
std::vector<size_t> SceneManager::GetSceneObjects()
{
std::vector<size_t> objectsids = m_currentScene.second->GetSceneObjects();
return objectsids;
}
| true |
6d17dfdd6ff74df1533eef9cc9cea113efcb84ad | C++ | MrDetectiv/fb-labs-2020 | /cp_4/chudo_fb-83_tushchenko_fb-83_cp4/main.cpp | UTF-8 | 3,237 | 3.09375 | 3 | [] | no_license | #include "func.h"
int main()
{
size_t gen_sz;
cout << "Enter generator size: " << endl;
cin >> gen_sz;
cout << endl << endl;
Pers Chris(gen_sz);
cout << "***************************************************************************" << endl;
cout << endl << "Chris" << endl;
Chris.printpublickey();
cout << "---------------" << endl;
Chris.printprivatekey();
cout << "***************************************************************************" << endl;
cout << endl << endl;
pair <cpp_int, cpp_int> chris_key = Chris.getpublickey();
Pers Den(gen_sz);
cout << "***************************************************************************" << endl;
cout << endl << "Den" << endl;
Den.printpublickey();
cout << "---------------" << endl;
Den.printprivatekey();
cout << "***************************************************************************" << endl;
cout << endl << endl;
pair <cpp_int, cpp_int> den_key = Den.getpublickey();
cpp_int message = 0x123456;
pair<cpp_int, cpp_int> chrissign = Chris.sign_message(message);
cout << "Chris signes a message" << endl;
cout << "(" << message << ", " << chrissign.second << ")" << endl;
cout << "Den verifies Chris` signature" << endl;
Den.check_signature(chrissign.first, chrissign.second, chris_key);
cout << endl << endl;
cout << "Chris encodes a message for Den" << endl;
cpp_int d_enc = Chris.encrypt(message, den_key);
cout << "Encoded message: " << d_enc << endl;
cout << "Den decodes message" << endl;
cpp_int d_dec = Den.decrypt(d_enc);
cout << "Decoded message: " << d_dec << endl << endl;
cpp_int k = 0x21122019;
cout << "Chris sends key "<< k << " to Den" << endl;
pair<cpp_int, cpp_int> sentkey = Chris.RSA_sender(Den, k);
cout << "Chris` message: (" << sentkey.first << ", " << sentkey.second << ")" << endl;
cout << "Den receives key" << endl;
cpp_int rec_k = Den.RSA_reciever(Chris, sentkey.first, sentkey.second);
cout << "Den received key " << rec_k << endl << endl;
//pair<cpp_int, cpp_int> servk = Server.getpublickey();
//pair<cpp_int, cpp_int> chrisk = Chris.getpublickey();
/* //decrypt
cout << endl << "Encryption" << endl;
cpp_int mes = 0x12345;
cout << "Message: " << mes << endl;
cpp_int encr = Server.encrypt(mes, chrisk);
cout <<"Encrypted by Server: " << encr << endl;
cout << "Decryption by Chris" << endl;
cpp_int decr = Chris.decrypt(encr);
cout << "Message: " << decr << endl;
//encrypt
cout << endl << "Encryption for Server" << endl;
cout << "Message: " << mes << endl;
cpp_int serv_encr = Chris.encrypt(mes, servk);
cout << "Encrypted by Chris: " << hex << serv_encr << endl;
//server ReceiveKey
cout << endl << "Sending key for server:" << endl;
cout << "Original key: " << mes << endl;
pair< cpp_int, cpp_int> sentkey = Chris.RSA_sender(Server, mes);
cout << "Sent key:" << sentkey.first << endl;
cout << "Sent key signature: " << sentkey.second << endl;
//server SendKey
/* cout << endl << "Receiving key from Server" << endl;
cpp_int k, S;
cout << "Enter key: ";
cin >> hex >> k;
cout << endl << "Enter signature: ";
cin >> hex >> S;
cpp_int key = Chris.RSA_reciever(Server, k, S);
cout << endl << "Received key: " << key << endl;*/
return 0;
} | true |
56a9c3cbf246f394fd54e983b0985e2579b053e7 | C++ | timchenggu123/darepo | /052ECE/Project1/P1-src/Dynamic_range_stack.h | UTF-8 | 5,218 | 3.25 | 3 | [] | no_license | /*****************************************
* Instructions
* - Replace 'uwuserid' with your uWaterloo User ID
* - Select the current calendar term and enter the year
* - List students with whom you had discussions and who helped you
*
* uWaterloo User ID: uwuserid @uwaterloo.ca
* Submitted for ECE 250
* Department of Electrical and Computer Engineering
* University of Waterloo
* Calender Term of Submission: (Winter|Spring|Fall) 201N
*
* By submitting this file, I affirm that
* I am the author of all modifications to
* the provided code.
*
* The following is a list of uWaterloo User IDs of those students
* I had discussions with in preparing this project:
* -
*
* The following is a list of uWaterloo User IDs of those students
* who helped me with this project (describe their help; e.g., debugging):
* -
*****************************************/
#ifndef DYNAMIC_STACK_AS_ARRAY_H
#define DYNAMIC_STACK_AS_ARRAY_H
#ifndef nullptr
#define nullptr 0
#endif
#include <algorithm>
#include "Exception.h"
class Dynamic_range_stack {
private:
int entry_count;
int max_count;
int min_count;
int initial_capacity;
int current_capacity;
int *stack_array;
int *maximum_array;
int *minimum_array;
// You may wish to include a number of helper functions
// in order to abstract out some operations
public:
Dynamic_range_stack( int = 10 );
~Dynamic_range_stack();
int top() const;
int size() const;
bool empty() const;
int capacity() const;
int maximum() const;
int minimum() const;
void push( int const & );
int pop();
void clear();
// Friends
friend std::ostream &operator<<( std::ostream &, Dynamic_range_stack const & );
};
Dynamic_range_stack::Dynamic_range_stack( int n ):
entry_count( 0 ),
min_count( 0 ),
max_count( 0 ),
initial_capacity( std::max( 1, n ) ),
current_capacity( initial_capacity ),
stack_array( new int[current_capacity] ),
maximum_array( new int[current_capacity] ),
minimum_array( new int[current_capacity] ) {
// empty constructor
}
Dynamic_range_stack::~Dynamic_range_stack() {
// Enter your implementation here.
delete[] maximum_array;
delete[] minimum_array;
delete[] stack_array;
}
int Dynamic_range_stack::top() const {
// Enter your implementation here.
if (empty() == 1){
throw underflow();
return 0;
}
int t = stack_array[entry_count-1];
return t ;
}
int Dynamic_range_stack::maximum() const {
// Enter your implementation here.
if (empty() == 1){
throw underflow();
return 0;
}
int max = maximum_array[max_count-1];
return max;
}
int Dynamic_range_stack::minimum() const {
// Enter your implementation here.
if (empty() == 1){
throw underflow();
return 0;
}
int min = minimum_array[min_count-1];
return min;
}
int Dynamic_range_stack::size() const {
// Enter your implementation here.
return entry_count;
}
bool Dynamic_range_stack::empty() const {
// Enter your implementation here.
if (entry_count == 0){
return 1;
}else
{
return 0;
}
}
int Dynamic_range_stack::capacity() const {
// Enter your implementation here.
return current_capacity;
}
void Dynamic_range_stack::push( int const &obj ) {
// Enter your implementation here.]
//check if the current stack is full
if (entry_count == current_capacity){
int *new_array = new int[2*current_capacity];
int *new_max_array = new int[2*current_capacity];
int *new_min_array = new int[2*current_capacity];
for (int i = 0; i < current_capacity; i++){
new_array[i] = stack_array[i];
new_max_array[i] = maximum_array[i];
new_min_array[i] = minimum_array[i];
}
delete[] stack_array;
delete[] maximum_array;
delete[] minimum_array;
stack_array = new_array;
maximum_array = new_max_array;
minimum_array = new_min_array;
current_capacity = 2*current_capacity;
}
stack_array[entry_count] = obj;
entry_count ++;
//push to max stack
int y = 0;
if (max_count > 0){
y = maximum_array[max_count-1];
}else{
y = obj;
}
if (obj >= y){
maximum_array[max_count] = obj;
}else{
maximum_array[max_count] = y;
}
max_count ++;
if (min_count > 0){
y = minimum_array[min_count -1];
}else{
y = obj;
}
if (obj <= y){
minimum_array[min_count] = obj;
} else{
minimum_array[min_count] = y;
}
min_count ++;
return;
}
int Dynamic_range_stack::pop() {
// Enter your implementation here.
int t = top();
entry_count --;
max_count --;
min_count --;
return t;
}
void Dynamic_range_stack::clear() {
// Enter your implementation here.
if (initial_capacity != current_capacity){
int *new_array = new int[initial_capacity];
int *new_max_array = new int[initial_capacity];
int *new_min_array = new int[initial_capacity];
delete[] stack_array;
delete[] maximum_array;
delete[] minimum_array;
stack_array = new_array;
maximum_array = new_max_array;
minimum_array = new_min_array;
current_capacity = initial_capacity;
}
}
// You can modify this function however you want: it will not be tested
std::ostream &operator<<( std::ostream &out, Dynamic_range_stack const &stack ) {
// Print out your stacks
return out;
}
// Is an error showing up in ece250.h or elsewhere?
// Did you forget a closing '}' ?
#endif
| true |
fcee197d43b5aba505a09637b147c57397a90384 | C++ | lhju4e/TIL | /algo/7453.cpp | UTF-8 | 1,653 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int a[4000];
int b[4000];
int c[4000];
int d[4000];
int main()
{
vector<int> ab;
vector<int> cd;
int n;
long long cnt=0;
cin >> n;
for(int i=0; i<n; i++)
{
cin >> a[i];
cin >> b[i];
cin >> c[i];
cin >> d[i];
}
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
ab.push_back(a[i] + b[j]);
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cd.push_back(c[i] + d[j]);
sort(ab.begin(), ab.end());
sort(cd.begin(), cd.end());
// for(int i=0; i<ab.size(); i++)
// cout << ab[i]<<" ";
// cout<<endl;
// for(int i=0; i<cd.size(); i++)
// cout << cd[i]<<" ";
// cout << endl;
int i=0,j=cd.size()-1;
//ab그룹이 음수고, cd그룹이 양수인 경우
while(j>=0 && i<ab.size())
{
if(ab[i] + cd[j] == 0)
{
// cout <<"i " <<i<< " ab[i] " << ab[i] << " j "<< j << " cd[j] " << cd[j] << endl;
int c1 = 1;
int c2 = 1;
while(i<ab.size()-1 && ab[i] == ab[i+1])
{
c1++;
i++;
// cout << "i " << i << endl;
}
while(j>0 && cd[j] == cd[j-1])
{
c2++;
j--;
// cout << "j " << j << endl;
}
i++;j--;
cnt += (long long)c1* c2;
}
else if(ab[i] + cd[j] > 0)
j--;
else if(ab[i] + cd[j] < 0)
i++;
}
cout << cnt;
return 0;
} | true |
40f50d47781ada0d88048597fb5792a7f956ef94 | C++ | Jeffrey-P-McAteer/ros_object_recognition | /src/object_detection_2d_vis/src/visualizer_main.cpp | UTF-8 | 1,569 | 2.921875 | 3 | [
"MIT"
] | permissive | /** \file
* \brief main function for running the Visualizer.
*/
// std.
#include <iostream>
#include <exception>
// Qt.
#include <QApplication>
// ROS.
#include <ros/ros.h>
// object_detection_*.
#include <object_detection_2d_vis/visualizer.h>
using object_detection_2d_vis::Visualizer;
using namespace std;
/** \brief Representation of the visualizer-application. */
class Application {
public:
/** \brief Default constructor.
*
* Initializes the QApplication and Visualizer members.
*/
Application(int argc, char** argv)
: q_app_ {argc, argv} {}
/** \brief Processes events until the node is shut down. */
void run()
{
ros::Rate r {10};
while (ros::ok()) {
processEvents();
r.sleep();
}
}
/** \brief Destructor.
*
* Closes the gui if necessary.
*/
~Application()
{
q_app_.quit();
}
private:
/** \brief Processes ROS and Qt events. */
void processEvents()
{
ros::spinOnce();
q_app_.processEvents();
// Shutdown ros when gui is closed.
if (!vis_.isVisible())
ros::shutdown();
}
// Data members.
QApplication q_app_;
Visualizer vis_;
};
/** \brief main function.
*
* Creates an Application object and lets it run.
*/
int main(int argc, char** argv)
try {
ros::init(argc, argv, "visualizer");
Application app {argc, argv};
app.run();
return 0;
}
catch (const std::exception& e) {
cerr << "std::exception: " << e.what() << '\n';
return 1;
}
catch (...) {
cerr << "Unknown exception caught. Terminating program.\n";
return 1;
}
| true |
e88a4cf0601c08177ee5dc7d16925109c547cdf3 | C++ | Atsuiai/ATAC | /DataStructureFunctionsATAC.cpp | UTF-8 | 112,380 | 2.890625 | 3 | [] | no_license |
#include "DataStructureFunctionsATAC.h"
// Builds a list of Neighbors.
imat DataStructureFunctionsATAC::buildNeigh(mat pos) {
int posn_rows = pos.n_rows;
int maxNumberOfNeighbors = 4;
imat neigh(posn_rows, maxNumberOfNeighbors);
/* row is atom number on original position list, columns are 4
nearist neighbors. Negative -1 indicates no neighbor, i.e. an edge atom
-2 indicates the proper values have not been assigned yet.*/
neigh.fill(-2);
//keeping this variable here in case of more generalization later.
//initialize with junk value
// imat bondedAtoms;
//bondedAtoms << -1 << endr;
for (int i = 0; i < posn_rows; ++i) // Iterates position atom.
{
// mat dist;
// dist << 0 << -1 << endr;
//first row is closest, etc. intialize with junk values.
// mat sortedDist;
//first column is distance, second column is neighbor number.
mat dist(maxNumberOfNeighbors, 2);
dist << 0 << -1 << endr
<< 0 << -1 << endr
<< 0 << -1 << endr
<< 0 << -1 << endr;
int numberOfAcceptedNeighbors = 0;
if (i % 100 == 0) {
cout << "Finding neighbors for atoms: " << i << "-" << i + 99 << endl;
}
//cout << "Finding neighbors for atom " << i << endl;
for (int j = i + 1; j < posn_rows; ++j) {
// Iterates atom to check distance wrt.
//The reason that j is always greater than i, is that we will find and force all neighbors for i as we go along
//i.e., even if the jth atom has neighbors that are a better fit than i, too bad.
//essentially a greedy algorithm that can be improved upon.
// j - (i + 1) = zero indexed number of atoms we have tested for j so far.
// if(j%100 == 0){
// cout << "and atoms " << j << "-" << j+99 << endl;
// }
double distance;
shortestLineDeterminer(pos, i, j, distance, periodicityNum, xLatticeParameter, yLatticeParameter, zLatticeParameter, latticeVec1Norm, latticeVec1, latticeVec2Norm, latticeVec2, latticeVec3Norm, latticeVec3);
//cout << "AFTER FINDING DIST " << endl;
//accept as neighbor if distance is between the ranges given, and we have not already bonded this atom before.
if (distance < bondDistanceToleranceMax && distance > bondDistanceToleranceMin /*&& contains(bondedAtoms,j) == 0*/) {
// cout << "before dist setting " << endl;
dist(numberOfAcceptedNeighbors, 0) = distance;
dist(numberOfAcceptedNeighbors, 1) = j;
// cout << "after setting " << endl;
//iterate accepted Neighbors, and add atom to bonded atom list.
imat toBeAdded;
toBeAdded << j;
// bondedAtoms = join_cols(bondedAtoms,toBeAdded);
numberOfAcceptedNeighbors++;
//If we have enough satisfactory neighbors, we can move onto the next atom.
if (numberOfAcceptedNeighbors == maxNumberOfNeighbors) {
break;
}
}
//fill out our distance matrix with the first initial guesses.
// if (j < maxNumberOfNeighbors){
// dist((j-i-1), 0) = distance;
// dist((j-i-1), 1) = j;
// continue;
// }
//we can sort our list of guesses now.
// if (j == maxNumberOfNeighbors){
// sortedDist = betterSortRows(dist, 0);
// }
}
/*
//loop through satisfying atoms.
for (int s = 0; s < maxNumberOfNeighbors; s++) {
//loop over neighbor atoms for atom i
for (int n = 0; n < neigh.n_cols; n++) {
//dist(k,1) is a satisfing atom.
//
imat neighRow = neigh.row(i);
if (contains(neighRow,dist(s, 1))) {
continue
neigh(i, s) = dist(s, 1);
}
if (neigh(dist(s, 1), maxNumberOfNeighbors - 1 - s) == -2) {
neigh(dist(s, 1), maxNumberOfNeighbors - 1 - s) = i;
}
}
}
*/
///*
//now add our found neighbors to the neighbor list.
//since -1 means no neighbor, we don't need to worry about clearing junk values from dist, as it would only have junk values
//if there weren't enough atoms to satisfying all the possible neighbors.
// k +1 should equal maxNumberOfNeighbors equals dist.n_rows.
//loop through satisfying atoms.
bool foundAllNeighs = false;
int satifying = 0;
//loop over neighbor atoms for atom i
for (int n = 0; n < maxNumberOfNeighbors; n++) {
//break if we have found the max number of neighbors, or if the satifying atom does not exist.
if (foundAllNeighs == true || dist(satifying, 1) == -1) {
break;
}
//need to make sure we aren't overwriting a pre-existing bond/
if (neigh(i, n) == -2) {
//now to make sure that the satisfying atom can accept atom i
for (int n2 = 0; n2 < maxNumberOfNeighbors; n2++) {
if (neigh(dist(satifying, 1), n2) == -2) {
//dist(k,1) is a satisfing atom.
neigh(i, n) = dist(satifying, 1);
neigh(dist(satifying, 1), n2) = i;
//cout <<"YESS HAAA i, n, and dist(satifying, 1), n2: " << i << " " << n << " " << dist(satifying, 1) << " " << n2 << endl;
//cout << neigh << endl;
//system("read -p \"sdklfjdk \" key");
satifying++;
if (satifying == maxNumberOfNeighbors) {
foundAllNeighs = true;
}
break;
}
}
}
}
// */
}
//need to turn all undetermined values into -1 now.
for (int i = 0; i < posn_rows; i++) {
for (int j = 0; j < maxNumberOfNeighbors; j++) {
if (neigh(i, j) == -2) {
neigh(i, j) = -1;
}
}
}
return (neigh); // first column has closest atom, second has second, etc.
}
//these prototype functions are for debugging; They allow for an intermediate view of the structure,esp after adding a dimer.
//void writeTopFile(mat positions, imat bondList, string masterBatchName);
//void writePgnFile(mat positions, string masterBatchName);
//void writePdbPsfFiles(string masterBatchName);
//declaring prototype function for mutation for mutationBody, so C++ can compile.
//void DataStructureFunctionsATAC::mutation(int mutationNum, imat& neighList, imat& bonds, mat& positions, imat& remainingBonds, string masterBatchName, int& inBeam);
//mutationBody contains the actual sp2 topological manipulation algorithms for our mutation alphabet.
void DataStructureFunctionsATAC::mutationBody(int mutationNum, imat& neighList, imat& bonds, mat& positions, int& chosen, int& neighbor, int& NN1, int& NN2, int& NNN1, int& NNN2, imat& remainingBonds, int currentRemainingBond, string masterBatchName, int& inBeam) {
imat toBeAppended;
int atomAddedToNNRingAfterRotation;
int atomAddedToNNNRingAfterRotation;
int NNnotFound = -1;
int NNNFound = -1;
int NNNnotFound = -1;
int NNFound = -1;
int beforeEnd;
int afterEnd;
int prospectiveNeighbor;
int randomAdvancement = 0;
//mutation for rotate
if (mutationNum == 1) {
cout << "ENTERING MUTATION BODY ROTATE " << endl;
//Immediately, we must check if the chosen and neighbor can be in a double bond. if no double bond, call the mutation again.
if (isDoubleBond(neighList, chosen, neighbor) == false) {
remainingBonds.shed_row(currentRemainingBond);
if (remainingBonds.is_empty()) {
cout << "NO MUTATION POSSIBLE, FAILED AT TRYING TO FIND DOUBLE BOND FOR ROTATION " << endl;
return;
}
mutation(mutationNum, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
return;
}
//FOLLOWING CODE USES RINGS TO FIND NEIGHBORS. AT THE MOMENT, COMPUTATIONALLY EXPENSIVE.
//first tries to find a ring with the chosen and neighbor atoms as one side.
//if this fails, finds atoms to switch by checking the positions.
/*
//initilize our stub of a ring, which is the chosen atom and neighbor
imat ring;
ring << chosen << neighbor << endr;
imat winningRing;
bool victory = false;
int ringSizeMax = atoi(variableReader("ringSizeMax").c_str());
// must start depth at 0, as 1 is added at the beginning.
findSmallestRingForAtom(neighbor, ring, winningRing, neighList, 0, victory, ringSizeMax);
//if a ring is found, find the found and not found atoms
if (winningRing.is_empty() == false) {
//now we must determine which ring is the Found Ring.
uvec NN1Index = find(winningRing == NN1);
uvec NN2Index = find(winningRing == NN2);
uvec NNN1Index = find(winningRing == NNN1);
uvec NNN2Index = find(winningRing == NNN2);
if (NN1Index.is_empty() == 0) {
NNnotFound = NN2;
NNFound = NN1;
} else {
NNnotFound = NN1;
NNFound = NN2;
}
if (NNN1Index.is_empty() == 0) {
NNNFound = NNN1;
NNNnotFound = NNN2;
} else {
NNNFound = NNN2;
NNNnotFound = NNN1;
}
} else */
{//if a ring is not found, we must use spatial coordinates.
//The distance between NNFound and NNNFound in a normal graphene sheet is about 3.07 A...
//The distance between NNFound and NNNnotFound in a normal graphene sheet is about 3.77 A...
double distance1;
shortestLineDeterminer(positions, NN1, NNN1, distance1, periodicityNum, xLatticeParameter, yLatticeParameter, zLatticeParameter, latticeVec1Norm, latticeVec1, latticeVec2Norm, latticeVec2, latticeVec3Norm, latticeVec3);
double distance2;
shortestLineDeterminer(positions, NN1, NNN2, distance2, periodicityNum, xLatticeParameter, yLatticeParameter, zLatticeParameter, latticeVec1Norm, latticeVec1, latticeVec2Norm, latticeVec2, latticeVec3Norm, latticeVec3);
//if the distance from NN1 to NNN1 is shortest, then NNN1 would be considered a part of the (imaginary) found ring.
// likewise for NN1 and NNN2
if (distance1 <= distance2) {
NNFound = NN1;
NNnotFound = NN2;
NNNFound = NNN1;
NNNnotFound = NNN2;
} else {
NNFound = NN1;
NNnotFound = NN2;
NNNFound = NNN2;
NNNnotFound = NNN1;
}
}
//first index is row in bonds, second is column in bonds.
vec NNnotFoundIndex(2);
vec NNNFoundIndex(2);
vec NNFoundIndex(2);
vec NNNnotFoundIndex(2);
//loops over rows in bonds to find indexes of those to be switched.
for (int j = 0; j < bonds.n_rows; ++j) {
if ((bonds(j, 0) == NNFound) && (bonds(j, 1) == chosen)) {
NNFoundIndex(0) = j;
NNFoundIndex(1) = 0;
}
if ((bonds(j, 1) == NNFound) && (bonds(j, 0) == chosen)) {
NNFoundIndex(0) = j;
NNFoundIndex(1) = 1;
}
if ((bonds(j, 0) == NNnotFound) && (bonds(j, 1) == chosen)) {
NNnotFoundIndex(0) = j;
NNnotFoundIndex(1) = 0;
}
if ((bonds(j, 1) == NNnotFound) && (bonds(j, 0) == chosen)) {
NNnotFoundIndex(0) = j;
NNnotFoundIndex(1) = 1;
}
if ((bonds(j, 1) == NNNFound) && (bonds(j, 0) == neighbor)) {
NNNFoundIndex(0) = j;
NNNFoundIndex(1) = 1;
}
if ((bonds(j, 0) == NNNFound) && (bonds(j, 1) == neighbor)) {
NNNFoundIndex(0) = j;
NNNFoundIndex(1) = 0;
}
if ((bonds(j, 1) == NNNnotFound) && (bonds(j, 0) == neighbor)) {
NNNnotFoundIndex(0) = j;
NNNnotFoundIndex(1) = 1;
}
if ((bonds(j, 0) == NNNnotFound) && (bonds(j, 1) == neighbor)) {
NNNnotFoundIndex(0) = j;
NNNnotFoundIndex(1) = 0;
}
}
//imat bondsBefore = bonds;
//switches bonds. Randomly determines which to switch (randomizes rotation direction)
int randomDirection = rand() % 2;
//NOT RANDOM, CHANGE LATER
randomDirection = 1;
if (randomDirection == 0) {
bonds(NNnotFoundIndex(0), NNnotFoundIndex(1)) = NNNFound;
bonds(NNNFoundIndex(0), NNNFoundIndex(1)) = NNnotFound;
} else {
bonds(NNNnotFoundIndex(0), NNNnotFoundIndex(1)) = NNFound;
bonds(NNFoundIndex(0), NNFoundIndex(1)) = NNNnotFound;
}
// These values might not be nessesarily used. The renaming is arbitrary
//SHOULD BE RANDOM BETWEEN NEIGHBOR AND CHOSEN, IS NOT, CHANGE LATER
atomAddedToNNRingAfterRotation = neighbor;
atomAddedToNNNRingAfterRotation = chosen;
//expensive routene, replace if speed benefits are really needed.
buildNeighFromBonds(bonds, neighList);
//does not need to rebuild bonds
}
//mutation for remove dimer
if (mutationNum == 2) {
for (int i = 0; i < bonds.n_rows; i++) {
for (int j = i; j < bonds.n_rows; j++) {
if (j != i) {
if ((bonds(i, 0) == bonds(j, 0) && bonds(i, 1) == bonds(j, 1))
|| (bonds(i, 0) == bonds(j, 1) && bonds(i, 1) == bonds(j, 0))) {
cout << "OFFENDING BONDS: THE FIRST " << bonds.row(i) << "THE SECOND " << bonds.row(j) << endl;
cout << "OFFENDING ROW NUM: " << i << " " << j << endl;
system("read -p \"paused, same bond counted twice BEFORE REMOVAL.\" key");
}
}
}
}
//Immediately, we must check if the chosen and neighbor can be in a double bond. if no double bond, call the mutation again.
if (isDoubleBond(neighList, chosen, neighbor) == false) {
remainingBonds.shed_row(currentRemainingBond);
if (remainingBonds.is_empty()) {
cout << "NO MUTATION POSSIBLE, FAILED AT TRYING TO FIND DOUBLE BOND FOR REMOVE DIMER (GRAPH THEORY) " << endl;
return;
}
mutation(mutationNum, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
return;
}
//adjusts neighbor indexes to account for a shorter neighbor matrix
int greaterIndex;
int lesserIndex;
if (chosen > neighbor) {
greaterIndex = chosen;
lesserIndex = neighbor;
} else {
greaterIndex = neighbor;
lesserIndex = chosen;
}
//handy code
/*
writeTopFile(positions, bonds, batchName);
writePgnFile(positions, batchName);
writePdbPsfFiles(batchName);
//Handy debugging code colors the ring in question; this pdb file is kept seperate, in batchnameModified.pdb
system(("rm " + batchName + "Modified.pdb").c_str());
string line;
ifstream original((batchName + ".pdb").c_str());
ofstream modified((batchName + "Modified.pdb").c_str());
int lineNumber = 0;
while (getline(original, line)) {
//does not modify the first or last line.
//looks for only atoms in the winning ring.
if ((lineNumber > 0) && (line.size() > 4) && (chosen == lineNumber - 1 || neighbor == lineNumber - 1)) {
line.erase(77, 79);
line = line + "N";
}
modified << line << "\n";
++lineNumber;
}
modified.close();
original.close();
/// */
//links NNs to each other, and also the NNNs
for (int i = 0; i < neighList.n_cols; ++i) {
if (neighList(NN1, i) == chosen) {
neighList(NN1, i) = NN2;
}
if (neighList(NN2, i) == chosen) {
neighList(NN2, i) = NN1;
}
if (neighList(NNN1, i) == neighbor) {
neighList(NNN1, i) = NNN2;
}
if (neighList(NNN2, i) == neighbor) {
neighList(NNN2, i) = NNN1;
}
}
//loops over neighbor list, adjusting for the soon to be missing rows
for (int j = 0; j < neighList.n_rows; ++j) {
for (int i = 0; i < neighList.n_cols; ++i) {
if (neighList(j, i) > greaterIndex) {
neighList(j, i) = neighList(j, i) - 2;
continue;
}
if ((neighList(j, i) > lesserIndex) && (neighList(j, i) < greaterIndex)) {
neighList(j, i) = neighList(j, i) - 1;
continue;
}
}
}
//loops over neighbor list, adjusting indexes
// sheds the rows corrosponding to the divacancy atoms. Need to shed rows from larger to smaller, or indexes will be off (falling stack of boxes or sand analogy);
positions.shed_row(greaterIndex);
positions.shed_row(lesserIndex);
//sheds atoms in neighbor list.
neighList.shed_row(greaterIndex);
neighList.shed_row(lesserIndex);
/*
//following block of code should work. replace the build bonds line
* on. possible speed benefits.
//update bonds
int bondsRowMax = bonds.n_rows;
cout << "chosend neighb" << chosen << " " << neighbor << endl;
for(int i = 0; i < bondsRowMax; ++i){
// delete all bonds containing the removed atoms
if ((bonds(i,0)== chosen)||(bonds(i,0)== neighbor)||
(bonds(i,1)== chosen)||(bonds(i,1)== neighbor)){
bonds.shed_row(i);
--bondsRowMax;
--i;
}
}
//add two new chasm-crossing bonds
imat toBeAdded;
toBeAdded << NN1 << NN2 << endr << NNN1 << NNN2 << endr;
bonds = join_cols(bonds,toBeAdded);
//loops over bond list, adjusting for the missing rows
for (int j = 0; j < bonds.n_rows; ++j) {
for (int i = 0; i < 2; ++i) {
if (bonds(j, i) > greaterIndex) {
bonds(j, i) = bonds(j, i) - 2;
}
if ((bonds(j, i) > lesserIndex) && (bonds(j, i) < greaterIndex)) {
bonds(j, i) = bonds(j, i) - 1;
}
}
}
*/
//if bonds are adjusted directly with previous bit of code, might result
//in speed benefits.
bonds = buildBond(neighList);
for (int i = 0; i < bonds.n_rows; i++) {
for (int j = i; j < bonds.n_rows; j++) {
if (j != i) {
if ((bonds(i, 0) == bonds(j, 0) && bonds(i, 1) == bonds(j, 1))
|| (bonds(i, 0) == bonds(j, 1) && bonds(i, 1) == bonds(j, 0))) {
cout << "OFFENDING BONDS: THE FIRST " << bonds.row(i) << "THE SECOND " << bonds.row(j) << endl;
cout << "OFFENDING ROW NUM: " << i << " " << j << endl;
system("read -p \"paused, same bond counted twice AFTER REMOVAL.\" key");
}
}
}
}
}
//This mutation for add dimer. The two bonds that the dimer intersects must NOT be double bonds.
if (mutationNum == 3) {
//initilize our stub of a ring, which is the chosen atom and neighbor
//imat ring;
//ring << chosen << neighbor << endr;
imat winningRing;
vector<pair<imat, int> > ringsOfSizes = findUniqueRingsForDimer(neighList, chosen, neighbor, ringSizeMin, ringSizeMax);
//dimer might not have any rings.
if (ringsOfSizes.empty()) {
remainingBonds.shed_row(currentRemainingBond);
mutation(mutationNum, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
return;
}
// ADD CHECK THAT AT LEAST ONE RING EXISTS; ELSE THIS PROGRAM WILL RUN INFINITELY
//This algoritm DOES require at least one ring to be found. if it is not found, recursively call mutation
if (ringsOfSizes.empty() == 1) {
//cout << "DIDN'T FIND RING, FAILED" << endl;
//calls mutation again to attempt another chosen and neighbor
remainingBonds.shed_row(currentRemainingBond);
if (remainingBonds.is_empty()) {
cout << "NO MUTATION POSSIBLE, FAILED AT TRYING TO FIND RING FOR ADD DIMER " << endl;
return;
}
mutation(mutationNum, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
return;
}
// cout << "FLAG " << endl;
//we must choose a winning ring out of ringsOfSizes. We first must find total number of rings.
int totalNumberOfRings = 0;
for (int i = 0; i < ringsOfSizes.size(); ++i) {
// cout << "Size of rings: " << ringsOfSizes[i].second << ". Number of rings: " << ringsOfSizes[i].first.n_rows << endl << "endl" << endl;
// if (ringsOfSizes[i].first.n_rows != 0) {
// cout << ringsOfSizes[i].first;
// }
//no not count empty rings and rings of 3.
if (ringsOfSizes[i].first.n_rows != 0 && ringsOfSizes[i].first.n_cols != 3) {
//cout << "TOTAL NUMBER OF RINGS " << totalNumberOfRings << endl;
totalNumberOfRings = totalNumberOfRings + ringsOfSizes[i].first.n_rows;
}
}
//cout << "TOTAL NUM OF RINGS " << totalNumberOfRings << endl;
for (int i = 0; i < ringsOfSizes.size(); i++) {
for (int j = 0; j < ringsOfSizes[i].first.n_rows; j++) {
// cout << "RINGS FOR DIMER: " << ringsOfSizes[i].first.row(j) << endl;
}
}
//choose a random, acceptable ring to be the winner.
int randomRing = rand() % totalNumberOfRings;
// keep track of how many rings you've seen.
int runningTotal = 0;
bool victory = false;
//advance through rings until you reach the random ring.
//advance through ring sizes first
for (int i = 0; i < ringsOfSizes.size(); ++i) {
//then advance through rings in that size.
//cout << "RINGS SIZE SIZE " << ringsOfSizes.size() << "num of rings in this size " << ringsOfSizes[i].first.n_rows << endl;
//cout << "Running total and random ring " << runningTotal << " " << randomRing << endl;
//we will not consider addind dimers to triangular formations
if (ringsOfSizes[i].second != 3) {
//cout << ringsOfSizes[i].second << "RING SIZE THE SECOND " << endl;
for (int j = 0; j < ringsOfSizes[i].first.n_rows; ++j) {
// cout << "I J " << i << " " << j << endl;
// cout << "Running total and random ring " << runningTotal << " " << randomRing << endl;
if (runningTotal == randomRing) {
winningRing = ringsOfSizes[i].first.row(j);
// cout << "Victory" << endl;
victory = true;
break;
} else {
++runningTotal;
}
}
//victory should always eventually be true, do to check that
//ringsOfSizes was not empty earlier on.
if (victory == true) {
break;
}
} else {
// cout << "RING OF SIZE THREE CHOSEN " << endl;
}
}
// cout << "FLAGyes " << endl;
//advance around the ring by a random amount. Must eliminate the possibility of advancing 0.
// 3 rings forbidden...
int numOfRandomAdvancements = winningRing.n_cols - 3;
imat advancementList;
//initilize junk value
advancementList << -1 << endr;
// cout << "numOfRandomAdvancements " << numOfRandomAdvancements << endl;
// cout << "winning ring " << winningRing << endl;
for (int i = 0; i < numOfRandomAdvancements; ++i) {
imat toBeAdded;
toBeAdded << i + 2 << endr;
advancementList = join_cols(advancementList, toBeAdded);
}
//shed junk value
advancementList.shed_row(0);
// cout << "FLAGmider " << endl;
//randomAdvancement = (rand() % (winner.n_cols - 3)) + 2;
int addDimerSuccess = 0;
do {
//randomly pick an advancement left on the list.
int advancementListRandIndex = rand() % (advancementList.n_rows);
int randomAdvancement = advancementList(advancementListRandIndex);
//path variable actually not used; for debugging and possible use elsewhere.
imat path;
//initialize with starting dimer
path << chosen << neighbor << endr;
// cout << "FLAGmid " << endl;
beforeEnd = chosen;
afterEnd = neighbor;
// starting at one end of a ring, travels to the opposite end (for the two adatoms).
for (int i = 0; i < randomAdvancement; ++i) {
//loops over neighbors
for (int j = 0; j < neighList.n_cols; ++j) {
// condition for advancing is the neighbor is not the previous atom,
//that the neighbor is on the ring, and ,
//and the neighbor exists
if ((neighList(afterEnd, j) != beforeEnd) &&
(contains(winningRing, neighList(afterEnd, j))) &&
(neighList(afterEnd, j) != -1)) {
beforeEnd = afterEnd;
afterEnd = neighList(afterEnd, j);
imat toBeAdded;
toBeAdded << afterEnd << endr;
path = join_rows(path, toBeAdded);
break;
}
}
}
//destroy junk value
path.shed_col(0);
// cout << "FLAGno " << endl;
//We must check if the beforeEnd and afterEnd are NOT in a double bond. if condtion fails, call the mutation again.
if (isNotDoubleBond(neighList, chosen, neighbor, NN1, NN2, NNN1, NNN2, beforeEnd, afterEnd) == 1) {
addDimerSuccess = 1;
} else {
//shed failed end,
advancementList.shed_row(advancementListRandIndex);
//if advancementList is empty, shed the picked bond and try again.
if (advancementList.is_empty() == true) {
remainingBonds.shed_row(currentRemainingBond);
if (remainingBonds.is_empty()) {
cout << "NO MUTATION POSSIBLE, FAILED AT TRYING TO FIND SINGLE BOND FOR ADD DIMER " << endl;
return;
}
mutation(mutationNum, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
return;
}
}
// loop continues as long as the advancement list is NOT empty
} while (addDimerSuccess == 0);
// cout << "FLAG " << endl;
// note, originally this coded created a new atom, with a position that is the average of the first chosen and neighbor atoms.
//However, NAMD cannot handle atoms that are too close to one another;
//thus this new code generates a circle of a given radius whose plane is perpendicular to the chosen-neighbor vector through the midpoint,
//and creates a new atom that is on a random angle on this circle.
//repeats with the end atoms.
double addDimerCircleRadius = 0.4;
double randomAngle = (rand() % 359) * 3.14159265 / 180;
vec xVec;
xVec << 1 << 0 << 0 << endr;
rowvec yVec;
yVec << 0 << 1 << 0 << endr;
vec u;
vec v;
vec circleCenter;
vec circleNormal;
double parallelCrossingTolerance = 0.1;
//Formula for a plane is A(x - x0) + B(y - y0) + C(z - z0) = 0,
//where A,B,and C are the slopes
//(derived from the chosen and neighbor coordinates), and the x0, y0, and z0 values are
//the midpoint positions.
//Parametric formula for a circle is R(t)=Center + r*cos(t)u + r*sin(t)v,
//where Center is the coordinates of the center, r is radius, and u and v are orthogonal unit vectors in the circle.
circleCenter << (positions(chosen, 0) + positions(neighbor, 0)) / 2 << (positions(chosen, 1) + positions(neighbor, 1)) / 2 << (positions(chosen, 2) + positions(neighbor, 2)) / 2 << endr;
circleNormal << positions(chosen, 0) - positions(neighbor, 0) << positions(chosen, 1) - positions(neighbor, 1) << positions(chosen, 2) - positions(neighbor, 2) << endr;
// we must now find two orthogonal directions to the normal vector.
//we can do this by crossing the normal with an arbitrary vector, and crossing this result with the norm again, normalizing as we go along.
//We will arbitrarily choose [1 0 0], however if this is coincidentally parallel to the normal, then we will choose [0 1 0]
u = cross(circleNormal, xVec);
mat absu = abs(u);
vec vecConvertedFromMat = absu;
if (sum(vecConvertedFromMat) < parallelCrossingTolerance) {
//the vectors are too close to parallel, choose a new arbitrary.
u = cross(circleNormal, yVec);
// cout << "TOO CLOSE THE FIRST TIME" << endl;
}
//normalize
u = u / norm(u, "inf");
//second vector.
v = cross(circleNormal, u);
v = v / norm(v, "inf");
mat newAtom1Positions;
//now use the paramentric formula discussed from before.
newAtom1Positions << circleCenter(0) + addDimerCircleRadius * (cos(randomAngle) * u(0) + sin(randomAngle) * v(0))
<< circleCenter(1) + addDimerCircleRadius * (cos(randomAngle) * u(1) + sin(randomAngle) * v(1))
<< circleCenter(2) + addDimerCircleRadius * (cos(randomAngle) * u(2) + sin(randomAngle) * v(2))
<< endr;
//repeat for second atom to be added
circleCenter.clear();
circleCenter << (positions(beforeEnd, 0) + positions(afterEnd, 0)) / 2 << (positions(beforeEnd, 1) + positions(afterEnd, 1)) / 2 << (positions(beforeEnd, 2) + positions(afterEnd, 2)) / 2 << endr;
circleNormal.clear();
circleNormal << positions(beforeEnd, 0) - positions(afterEnd, 0) << positions(beforeEnd, 1) - positions(afterEnd, 1) << positions(beforeEnd, 2) - positions(afterEnd, 2) << endr;
// we must now find two orthogonal directions to the normal vector.
//we can do this by crossing the normal with an arbitrary vector, and crossing this result with the norm again, normalizing as we go along.
//We will arbitrarily choose [1 0 0], however if this is coincidentally parallel to the normal, then we will choose [0 1 0]
u.clear();
u = cross(circleNormal, xVec);
absu = abs(u);
vecConvertedFromMat = absu;
if (sum(vecConvertedFromMat) < parallelCrossingTolerance) {
//the vectors are too close to parallel, choose a new arbitrary.
u = cross(circleNormal, yVec);
}
//normalize
u = u / norm(u, "inf");
//second vector.
v.clear();
v = cross(circleNormal, u);
v = v / norm(v, "inf");
mat newAtom2Positions;
//now use the paramentric formula discussed from before.
newAtom2Positions << circleCenter(0) + addDimerCircleRadius * (cos(randomAngle) * u(0) + sin(randomAngle) * v(0))
<< circleCenter(1) + addDimerCircleRadius * (cos(randomAngle) * u(1) + sin(randomAngle) * v(1))
<< circleCenter(2) + addDimerCircleRadius * (cos(randomAngle) * u(2) + sin(randomAngle) * v(2))
<< endr;
//handy code
/*
writeTopFile(positions, bonds, batchName);
writePgnFile(positions, batchName);
writePdbPsfFiles(batchName);
//Handy debugging code colors the ring in question; this pdb file is kept seperate, in batchnameModified.pdb
system(("rm " + batchName + "Modified.pdb").c_str());
string line;
ifstream original((batchName + ".pdb").c_str());
ofstream modified((batchName + "Modified.pdb").c_str());
int lineNumber = 0;
while (getline(original, line)) {
//does not modify the first or last line.
//looks for only atoms in the winning ring.
if ((lineNumber > 0) && (line.size() > 4) && contains(winningRing, lineNumber - 1)) {
line.erase(77, 79);
line = line + "N";
}
modified << line << "\n";
++lineNumber;
}
modified.close();
original.close();
*/
//adds atoms
positions = join_cols(positions, newAtom1Positions);
positions = join_cols(positions, newAtom2Positions);
//updates neighbor list by finding references to chosen atom pairs, and replacing them with the indexes
//of the inserted atoms (which will be appended to the end of the neighbor list)
for (int j = 0; j < neighList.n_cols; ++j) {
if (neighList(chosen, j) == neighbor) {
neighList(chosen, j) = (neighList.n_rows);
break;
}
}
for (int j = 0; j < neighList.n_cols; ++j) {
if (neighList(neighbor, j) == chosen) {
neighList(neighbor, j) = (neighList.n_rows);
break;
}
}
for (int j = 0; j < neighList.n_cols; ++j) {
if (neighList(beforeEnd, j) == afterEnd) {
neighList(beforeEnd, j) = (neighList.n_rows + 1);
break;
}
}
for (int j = 0; j < neighList.n_cols; ++j) {
if (neighList(afterEnd, j) == beforeEnd) {
neighList(afterEnd, j) = (neighList.n_rows + 1);
break;
}
}
//new atom1 has new atom2 as a neighbor, and vice versa
imat newAtom1Neighbors;
newAtom1Neighbors << chosen << neighbor << neighList.n_rows + 1 << -1 << endr;
imat newAtom2Neighbors;
newAtom2Neighbors << beforeEnd << afterEnd << neighList.n_rows << -1 << endr;
/*
for (int i = 0; i < bonds.n_rows; i++) {
for (int j = i; j < bonds.n_rows; j++) {
if (j != i) {
if ((bonds(i, 0) == bonds(j, 0) && bonds(i, 1) == bonds(j, 1))
|| (bonds(i, 0) == bonds(j, 1) && bonds(i, 1) == bonds(j, 0))) {
cout << "OFFENDING BONDS: THE FIRST " << bonds.row(i) << "THE SECOND " << bonds.row(j) << endl;
cout << "OFFENDING ROW NUM: " << i << " " << j << endl;
system("read -p \"paused, same bond counted twice BEFORE ADDITION.\" key");
}
}
}
}
*/
neighList = join_cols(neighList, newAtom1Neighbors);
neighList = join_cols(neighList, newAtom2Neighbors);
bonds = buildBond(neighList);
}
}
//the main point of this subroutine is find a dimer and its neighbors around which feed to
//mutationBody.
//Either rotates a bond, creates a divacancy, or adds a dimer, depending on
//the mutation number given (1,2,and 3 respectively
//The mutations all have the same set-up: choose an atom, find it's Nearist Neighbors NN, and it's
//Next Nearest Neighbors NNN. Modify the rings, delete the outdated versions, and then add the new ones.
//remainingBonds starts off as a full bond list. As the bonds fail various conditions and this subfunction is recursively called again, this list is chopped down.
//This ensures the code will not run forever if a specific mutation is impossible, and will improve run times.
void DataStructureFunctionsATAC::mutation(int mutationNum, imat& neighList, imat& bonds, mat& positions, imat& remainingBonds, string masterBatchName, int& inBeam) {
int chosen;
int neighbor;
int NN1;
int NN2;
int NNN1;
int NNN2;
int randomBond;
uvec NNIndexes;
uvec NNNIndexes;
uvec chosenUnbonded;
uvec neighborUnbonded;
bool dimerFound = false;
do {
//check that we still have bonds to Test...
if (remainingBonds.is_empty()) {
// cout << "BEAM RADIUS " << beamRadius << endl;
cout << "NO MUTATION POSSIBLE, FAILED TRYING TO FIND APPROPRIATE DIMER " << endl;
return;
}
randomBond = rand() % remainingBonds.n_rows;
// cout << "RANDOM BOND" << endl;
chosen = remainingBonds(randomBond, 0);
// cout << " CHO " << chosen << endl;
neighbor = remainingBonds(randomBond, 1);
// cout << "NEIGH " << neighbor << endl;
NNIndexes = find(neighList.row(chosen) != neighbor);
// cout <<"NNIndexes " << NNIndexes << endl;
NN1 = neighList(chosen, NNIndexes[0]);
// cout <<"NN1 " << NN1 << endl;
NN2 = neighList(chosen, NNIndexes[1]);
// cout <<"NN2 " << NN2<< endl;
NNNIndexes = find(neighList.row(neighbor) != chosen);
// cout <<"NNNIndexes " << NNNIndexes << endl;
NNN1 = neighList(neighbor, NNNIndexes[0]); //
// cout <<"NNN1 " << NNN1 << endl;
NNN2 = neighList(neighbor, NNNIndexes[1]);
// cout <<"NNN2 " << NNN2 << endl;
chosenUnbonded = find(neighList.row(chosen) == -1);
neighborUnbonded = find(neighList.row(neighbor) == -1);
bool isElectrode = false;
//if this system has electrodes, no atoms may participate in the mutation.
if (numberOfElectrodes != 0) {
//NOTE: TO UPDATE ELECTRODES AT EVERY INSTANCE, UNCOMMENT FOLLOWING LINE. DO NOT DELETE-ISH.
//electrodeDeterminer(positions, xp1Electrodes, xn1Electrodes, yp1Electrodes, yn1Electrodes, xp2Electrodes, xn2Electrodes, yp2Electrodes, yn2Electrodes);
//since ordering is not important, we can just stack the electrodes into one matrix.
imat electrodes;
if (numberOfElectrodes == 2) {
imat xpElectrodes = join_cols(xp1Electrodes, xp2Electrodes);
imat xnElectrodes = join_cols(xn1Electrodes, xn2Electrodes);
electrodes = join_cols(xpElectrodes, xnElectrodes);
}
if (numberOfElectrodes == 4) {
imat xpElectrodes = join_cols(xp1Electrodes, xp2Electrodes);
imat xnElectrodes = join_cols(xn1Electrodes, xn2Electrodes);
imat intermediate1;
intermediate1 = join_cols(xpElectrodes, xnElectrodes);
imat ypElectrodes = join_cols(yp1Electrodes, yp2Electrodes);
imat ynElectrodes = join_cols(yn1Electrodes, yn2Electrodes);
imat intermediate2;
intermediate2 = join_cols(ypElectrodes, ynElectrodes);
electrodes = join_cols(intermediate1, intermediate2);
}
//loop through our electrode atoms.
for (int i = 0; i < electrodes.n_rows; i++) {
//if the electrode atom is any of the atoms we are currently looking at,
//disreguard this dimer.
if ((electrodes(i) == chosen) || (electrodes(i) == neighbor)
|| (electrodes(i) == NN1) || (electrodes(i) == NN2)
|| (electrodes(i) == NNN1) || (electrodes(i) == NNN2)) {
isElectrode = true;
}
}
}
//test makes sure the atoms we chose are within the beam (if the beam is exclusionary like that).
//assume the system passes the bool, until proven wrong.
bool passBeamTest = true;
//We check if the system has a irradation beam.
if (haveBeam == 1) {
//find axis intercept dimentions (0, 1, 2, for x, y, z).
int intercept1, intercept2;
if (beamAxis == 1) {
intercept1 = 1;
intercept2 = 2;
} else if (beamAxis == 2) {
intercept1 = 0;
intercept2 = 2;
} else if (beamAxis == 3) {
intercept1 = 0;
intercept2 = 1;
}
//check beam type.
if (beamType == 1) {
//This is a stationary beam that does not allow mutations outside the beam.
//the only way we can fail this test is if either neighbor or chosen are outside the beam.
//check that both chosen and neighbor atoms are in the beam.
if (pow(positions(chosen, intercept1) - beamAxisIntercept1, 2) + pow(positions(chosen, intercept2) - beamAxisIntercept2, 2) <= pow(beamRadius, 2) &&
pow(positions(neighbor, intercept1) - beamAxisIntercept1, 2) + pow(positions(neighbor, intercept2) - beamAxisIntercept2, 2) <= pow(beamRadius, 2)) {
//passed
inBeam == 1;
} else {
//failed
passBeamTest = false;
inBeam == 0;
}
}
if (beamType == 2) {
//This is a stationary beam that DOES allow mutations outside the beam.
//always passes test technically, as mutaitons are allowed everywhere.
//check that both chosen and neighbor atoms are in the beam.
if (pow(positions(chosen, intercept1) - beamAxisIntercept1, 2) + pow(positions(chosen, intercept2) - beamAxisIntercept2, 2) <= pow(beamRadius, 2) &&
pow(positions(neighbor, intercept1) - beamAxisIntercept1, 2) + pow(positions(neighbor, intercept2) - beamAxisIntercept2, 2) <= pow(beamRadius, 2)) {
//passed
inBeam == 1;
} else {
//failed
inBeam == 0;
}
}
}
// if neighbor or the NNs or the NNNs don't exist,
// or if the NN and NNN have the same values (a three-ring triangle situation)
// or if the chosen or neighbor are sp3,
// or if the NN's or NNN's are neighbors of each other (triangle at end of dimer situation),
// or if any of the atoms are electrodes,
// delete failed bond and continue loop.
if ((neighbor < 0) || (NN1 < 0) || (NN2 < 0) || (NNN1 < 0) || (NNN2 < 0)
|| (NN1 == NN2) || (NN1 == NNN1) || (NN1 == NNN2) || (NN2 == NNN1) || (NN2 == NNN2) || (NNN1 == NNN2)
|| (chosenUnbonded.is_empty() == true) || (neighborUnbonded.is_empty() == true)
|| contains(neighList.row(NN1), NN2) || contains(neighList.row(NN2), NN1)
|| contains(neighList.row(NNN1), NNN2) || contains(neighList.row(NNN2), NNN1)
|| (isElectrode == true)
|| (passBeamTest == false)) {
// cout << "BOND FAILED " << endl;
remainingBonds.shed_row(randomBond);
} else {
//cout << "chosen neighbor NN1 NN2 NNN1 NNN2 " << chosen <<" " << neighbor << " " << NN1 << " " << NN2 << " " << " " << NNN1 << " " << NNN2 << endl;
dimerFound = true;
}
} while (dimerFound == false);
//cout << " TRUE BONDS AFTER" << bonds << endl;
mutationBody(mutationNum, neighList, bonds, positions, chosen, neighbor, NN1, NN2, NNN1, NNN2, remainingBonds, randomBond, masterBatchName, inBeam);
}
//INCLUDE DOUBLE BOND CHECK
//checks if atoms i and j can go through an sp2 to sp3 condition to bond with
//each other.
bool DataStructureFunctionsATAC::sp2Tosp3Conditions(int i, int j, mat positions, imat& neighbors) {
bool pass = false;
//check that i and j exist...
if ((i < 0) || (j < 0)) {
return pass;
}
uvec jNeighborOfiIndex = find(neighbors.row(i) == j);
uvec emptySpotsi = find(neighbors.row(i) == -1);
uvec emptySpotsj = find(neighbors.row(j) == -1);
// fails if i and j are the same atom, or
// are neighbors
// or are not sp2 (i.e. bonded to three atoms, so one possible neighbor is missing...)
if ((j == i)
|| (jNeighborOfiIndex.is_empty() == false)
|| (emptySpotsi.n_elem != 1)
|| (emptySpotsj.n_elem != 1)) {
return pass;
}
double distance;
/*
int periodicityNumBackup;
if (periodicOnlyOnNonInteracting == true) {
//IMPORTANT: CURRENTLY THE DYNAMIC PERIODIC CONDITION WILL NOT LOOK AT THE NORMAL ATOMS, ONLY THE NON-INTERACTING ONES.
periodicityNumBackup = periodicityNum;
periodicityNum = 0;
}*/
shortestLineDeterminer(positions, i, j, distance, periodicityNum, xLatticeParameter, yLatticeParameter, zLatticeParameter, latticeVec1Norm, latticeVec1, latticeVec2Norm, latticeVec2, latticeVec3Norm, latticeVec3);
/*
if (periodicOnlyOnNonInteracting == true) {
periodicityNum = periodicityNumBackup;
}*/
//atoms must be within a certain distance of each other.
if (distance > sp2tosp3Tolerance) {
//cout << "ATOMS TOO FAR FOR SP2 TO SP3" << endl;
return false;
}
//"spDenialPathSize"
//the next set of lines will not allow the sp2 to sp3 transition to occur
//if a path of a given length can be found between the dimers in question.
//essentially it is to prevent the sp2 to sp3 transition to occur within
//the same structure, for instance, imploding a bucky ball. This is more
//likely to occur for large sp2tosp3Tolerance values.
bool victory = false;
imat path;
path << -1 << endr;
imat winner;
int layersDeep = 0 - 1;
//ring size must be four, as we are looking for a 4 ring.
int pathSizeMax = spDenialPathSize + 1; //a value of 4+1 will effectively not allow for sp2 to sp3 to be undone.
findPathForAtoms(i, j, path, winner, neighbors, layersDeep, victory, pathSizeMax);
// if a path can be found between the two atoms, then they are part of the immediate
// surrounding structure, not seperate ones.
if (victory) {
return false;
}
//congrats, if the code as made it this far, it has passed all tests.
pass = true;
/*
//now must see if the atoms are a part of two six rings, each!
//CHANGE TO DOUBLE BOND FINDING ALGORITM!!!
for (int k = 0; k < rings.size(); ++k) {
if ((rings[k].second == 6) && (rings[k].first.n_rows != 0)) {
uvec iInSixIndexes = find(i == rings[k].first);
uvec jInSixIndexes = find(j == rings[k].first);
if ((iInSixIndexes.n_elem >= 2) && (jInSixIndexes.n_elem >= 2)) {
//congrats, all conditions have been passed for the chosen pair.
pass = true;
return pass;
}else{
return pass;
}
}else{return pass;}
}
return pass;
}else{return pass;}
}*/
return pass;
}
// the sp3 to sp2 transition occurs via two even-numbered rings (including size 2) that are connected face to face.
// same could be said for 2 to 3, but in reverse.
// Only rings of size 2 are considered, as the 3 to 2 barrier is significantly lower in such a case.
void DataStructureFunctionsATAC::sp3Tosp2(imat& neighbors, imat& bonds, mat& positions) {
//SP3 to SP2: break the bonds between chosen and chosen's neighbor, other and other's neighbor
//simply creates a list numbered 0 through # of atoms
imat atomsLeftToBeTested(neighbors.n_rows, 1);
for (
int i = 0; i < neighbors.n_rows; ++i) {
atomsLeftToBeTested(i) = i;
}
//must find a four ring in sp3...
//make a neighlist of just sp3
imat sp3Neighbors = neighbors;
///first we loop over neighbors, and eliminate all sp2 carbon atoms.
for (int i = 0; i < sp3Neighbors.n_rows; ++i) {
uvec negIndex = find(sp3Neighbors.row(i) == -1);
if (negIndex.is_empty() != true) {
//at least one negative index, thus less than 4 neighbor atoms, thus sp2, thus must be eliminated.
sp3Neighbors(i, 0) = -1;
sp3Neighbors(i, 1) = -1;
sp3Neighbors(i, 2) = -1;
sp3Neighbors(i, 3) = -1;
atomsLeftToBeTested(i) = -1;
}
}
int iterLimit = atomsLeftToBeTested.n_rows;
for (int i = 0; i < iterLimit; ++i) {
if (atomsLeftToBeTested(i) == -1) {
atomsLeftToBeTested.shed_row(i);
--i;
--iterLimit;
}
}
if (atomsLeftToBeTested.is_empty()) {
cout << " NOT ENOUGH SP3 TO CONVERT TO SP2 " << endl;
return;
}
//inefficient, change later.
imat sp3Bonds = buildBond(sp3Neighbors);
buildNeighFromBonds(sp3Bonds, sp3Neighbors);
imat winningRing;
int chosen;
bool victory = false;
do {
//cout << "ATOMS LEFT" << atomsLeftToBeTested.n_rows << endl;
int randomIndex = rand() % atomsLeftToBeTested.n_rows;
chosen = atomsLeftToBeTested(randomIndex);
//ring size must be 4, in this transition.
int ringSizeMax = 4;
imat ring;
for (int i = 0; i < neighbors.n_cols; ++i) {
ring << chosen << neighbors(chosen, i) << endr;
// must start depth at 0, as 1 is added at the beginning.
findSmallestRingForAtom(neighbors(chosen, i), ring, winningRing, neighbors, 0, victory, ringSizeMax);
if (victory == true) {
break;
}
}
if (victory == false) {
atomsLeftToBeTested.shed_row(randomIndex);
if (atomsLeftToBeTested.is_empty()) {
cout << " COULDN'T FIND 4 RING " << endl;
return;
}
}
} while (victory == false);
//only working with 4 rings currently. So, these atoms were chosen, chosenNeighbor,
//other, and otherNeighbor, from the sp2 to sp3 transition.
//We must randomize which atom in the ring is chosen, etc.
int chosenNeighbor;
int otherNeighbor;
int other;
int randNum = rand() % 4;
if (superfluousSp3Sp2 == false) {
//Disallows superfluous sp3 to sp2 transitions, i.e. ones that reverse the effects of the previous sp2 to sp3 reaction.
randNum = 2;
}
chosen = winningRing(randNum);
randNum++;
if (randNum >= 4) {
randNum = randNum - 4;
}
chosenNeighbor = winningRing(randNum);
randNum++;
if (randNum >= 4) {
randNum = randNum - 4;
}
otherNeighbor = winningRing(randNum);
randNum++;
if (randNum >= 4) {
randNum = randNum - 4;
}
other = winningRing(randNum);
//loops over rows in bonds to find indexes of those to be deleted.
int iterMax = bonds.n_rows;
for (int i = 0; i < iterMax; ++i) {
if ((bonds(i, 0) == chosen) && (bonds(i, 1) == chosenNeighbor)) {
bonds.shed_row(i);
--i;
--iterMax;
}
if ((bonds(i, 0) == chosenNeighbor) && (bonds(i, 1) == chosen)) {
bonds.shed_row(i);
--i;
--iterMax;
}
if ((bonds(i, 0) == other) && (bonds(i, 1) == otherNeighbor)) {
bonds.shed_row(i);
--i;
--iterMax;
}
if ((bonds(i, 0) == otherNeighbor) && (bonds(i, 1) == other)) {
bonds.shed_row(i);
--i;
--iterMax;
}
}
//do the same for neighbors
uvec chosenNeighborIndex1 = find(neighbors.row(chosen) == chosenNeighbor);
neighbors(chosen, chosenNeighborIndex1(0)) = -1;
uvec chosenIndex1 = find(neighbors.row(chosenNeighbor) == chosen);
neighbors(chosenNeighbor, chosenIndex1(0)) = -1;
uvec otherNeighborIndex1 = find(neighbors.row(other) == otherNeighbor);
neighbors(other, otherNeighborIndex1(0)) = -1;
uvec otherIndex1 = find(neighbors.row(otherNeighbor) == other);
neighbors(otherNeighbor, otherIndex1(0)) = -1;
//we now rotate the neighbor other and neighbor neighbor bonds.
//but first, must find the NN and NNN of each respectively.
int chosenNN1;
int chosenNN2;
uvec chosenNNIndexes = find(neighbors.row(chosen) != other);
uvec chosenNNPosIndexes = find(neighbors.row(chosen) != -1);
int countNN = 0;
for (int i = 0; i < chosenNNIndexes.n_elem; ++i) {
for (int j = 0; j < chosenNNPosIndexes.n_elem; ++j) {
if (chosenNNIndexes(i) == chosenNNPosIndexes(j) && (countNN == 0)) {
chosenNN1 = neighbors(chosen, chosenNNIndexes(i));
++countNN;
continue;
}
if (chosenNNIndexes(i) == chosenNNPosIndexes(j) && (countNN == 1)) {
chosenNN2 = neighbors(chosen, chosenNNIndexes(i));
++countNN;
continue;
}
}
}
int otherNN1;
int otherNN2;
uvec otherNNIndexes = find(neighbors.row(other) != chosen);
uvec otherNNPosIndexes = find(neighbors.row(other) != -1);
int countNNN = 0;
for (int i = 0; i < otherNNIndexes.n_elem; ++i) {
for (int j = 0; j < otherNNPosIndexes.n_elem; ++j) {
if (otherNNIndexes(i) == otherNNPosIndexes(j) && (countNNN == 0)) {
otherNN1 = neighbors(other, otherNNIndexes(i));
++countNNN;
continue;
}
if (otherNNIndexes(i) == otherNNPosIndexes(j) && (countNNN == 1)) {
otherNN2 = neighbors(other, otherNNIndexes(i));
++countNNN;
continue;
}
}
}
//these are just dummy values, and should never be called in mutation body...
imat remainingBonds;
int currentBond;
int chosenNeighborNN1;
int chosenNeighborNN2;
uvec chosenNeighborNNIndexes = find(neighbors.row(chosenNeighbor) != otherNeighbor);
uvec chosenNeighborNNPosIndexes = find(neighbors.row(chosenNeighbor) != -1);
int countNeighborNN = 0;
for (int i = 0; i < chosenNeighborNNIndexes.n_elem; ++i) {
for (int j = 0; j < chosenNeighborNNPosIndexes.n_elem; ++j) {
if (chosenNeighborNNIndexes(i) == chosenNeighborNNPosIndexes(j) && (countNeighborNN == 0)) {
chosenNeighborNN1 = neighbors(chosenNeighbor, chosenNeighborNNIndexes(i));
++countNeighborNN;
continue;
}
if (chosenNeighborNNIndexes(i) == chosenNeighborNNPosIndexes(j) && (countNeighborNN == 1)) {
chosenNeighborNN2 = neighbors(chosenNeighbor, chosenNeighborNNIndexes(i));
++countNN;
continue;
}
}
}
int otherNeighborNN1;
int otherNeighborNN2;
uvec otherNeighborNNIndexes = find(neighbors.row(otherNeighbor) != chosenNeighbor);
uvec otherNeighborNNPosIndexes = find(neighbors.row(otherNeighbor) != -1);
int countNeighborNNN = 0;
for (int i = 0; i < otherNeighborNNIndexes.n_elem; ++i) {
for (int j = 0; j < otherNeighborNNPosIndexes.n_elem; ++j) {
if (otherNeighborNNIndexes(i) == otherNeighborNNPosIndexes(j) && (countNeighborNNN == 0)) {
otherNeighborNN1 = neighbors(otherNeighbor, otherNeighborNNIndexes(i));
++countNeighborNNN;
continue;
}
if (otherNeighborNNIndexes(i) == otherNeighborNNPosIndexes(j) && (countNeighborNNN == 1)) {
otherNeighborNN2 = neighbors(otherNeighbor, otherNeighborNNIndexes(i));
++countNeighborNNN;
continue;
}
}
}
}
//This algorithm converts sp2 bonds to sp3 bonds, via the mechanism of
//forcing two double bonded pairs of atoms within close vicinity of each other.
//First, looks for two atoms that are within 2 angstroms, and not otherwise bonded.
//if these atoms are a part of mutually exclusive six rings,
//then look for neighbors that also fulfill the previous conditions.
//if so, bond atoms to atoms and neighbors to neighbors
//Might later modify slightly so it can bond edge atoms as well.
void DataStructureFunctionsATAC::sp2Tosp3(mat positions, imat& neighbors, imat& bonds, int& spPossibility) {
spPossibility = 0; //reset the spPossibility number, as we have performed the operations needed.
bool chosenPairMeetConditions = false;
bool neighborPairMeetConditions = false;
int chosen;
int other;
int randomIndex1;
int randomIndex2;
//simply creates a list numbered 0 through # of atoms
ivec atomsLeftToBeTested(positions.n_rows);
for (
int i = 0; i < positions.n_rows; ++i) {
atomsLeftToBeTested(i) = i;
}
//we will randomly choose atoms to find a sp2 to sp3 candidate,
//until all possibilities have been exhausted.
// we keep testing until we succeed or have nothing left to test
do {
randomIndex1 = rand() % atomsLeftToBeTested.n_rows;
chosen = atomsLeftToBeTested(randomIndex1);
//simply creates a list numbered 0 through # of atoms
ivec atomsToCheckAgainst(positions.n_rows);
for (int i = 0; i < positions.n_rows; ++i) {
atomsToCheckAgainst(i) = i;
}
do {
randomIndex2 = rand() % atomsToCheckAgainst.n_rows;
//other is the atom we are comparing chosen to
other = atomsToCheckAgainst(randomIndex2);
// and we check the conditions...
// DataStructureFunctionsATAC molecule; //DANGER DANGER DANGER
chosenPairMeetConditions = sp2Tosp3Conditions(chosen, other, positions, neighbors);
//If the chosen pair meets the conditions, then sees if there are neighbors that do the same
if (chosenPairMeetConditions == true) {
//chosenNeighbor is the chosen neighbor atom we are currently looking at
for (int chosenNeighborIter = 0; chosenNeighborIter < neighbors.n_cols; ++chosenNeighborIter) {
//otherNeighbor is the other neighbor atom we are comparing chosenNeighbor to
for (int otherNeighborIter = 0; otherNeighborIter < neighbors.n_cols; ++otherNeighborIter) {
int chosenNeighbor = neighbors(chosen, chosenNeighborIter);
int otherNeighbor = neighbors(other, otherNeighborIter);
// must also check that the neighbors we are picking out are not one of the already chosen atoms
if ((chosen != otherNeighbor) && (other != chosenNeighbor)) {
//we must find neighbors of our chosen pair, that also fufil the condition.
neighborPairMeetConditions = sp2Tosp3Conditions(chosenNeighbor, otherNeighbor, positions, neighbors);
//now see if we can execute the mutation... all sp2 conditions must be fufilled, and the double bonds confirmed.
if ((chosenPairMeetConditions == true) && (neighborPairMeetConditions == true) && isDoubleBond(neighbors, chosen, chosenNeighbor) && isDoubleBond(neighbors, other, otherNeighbor)) {
//success
//set the chosen pair to each other...
uvec emptySpoti = find(-1 == neighbors.row(chosen));
uvec emptySpotj = find(-1 == neighbors.row(other));
neighbors(chosen, emptySpoti(0)) = other;
neighbors(other, emptySpotj(0)) = chosen;
//and the neighbor pair
uvec emptySpotl = find(-1 == neighbors.row(chosenNeighbor));
uvec emptySpotm = find(-1 == neighbors.row(otherNeighbor));
neighbors(chosenNeighbor, emptySpotl(0)) = otherNeighbor;
neighbors(otherNeighbor, emptySpotm(0)) = chosenNeighbor;
//add to bonds
imat toBeAppended;
toBeAppended
<< chosen << other << endr
<< chosenNeighbor << otherNeighbor << endr;
bonds = join_cols(bonds, toBeAppended);
spPossibility = 1;
cout << "SP2 TO SP3 TRANSITION OK" << endl;
return;
}
}
}
}
}
//if the code ever reaches this far, then it failed to fufil all the conditions
// chosen and other failed, get new other atom
atomsToCheckAgainst.shed_row(randomIndex2);
} while (atomsToCheckAgainst.n_elem > 0);
// chosen failed, get new chosen atom
atomsLeftToBeTested.shed_row(randomIndex1);
} while (atomsLeftToBeTested.n_elem > 0);
cout << "SP2 TO SP3 TRANSITION CURRENTLY IMPOSSIBLE" << endl;
spPossibility = -1;
}
//adds non-interacting atoms to our position and bond lists.
void DataStructureFunctionsATAC::nonInteractingAppender(mat& positions, imat& bondList, imat& neighborList) {
// for appending the bonds and the neighbors, we must keep in mind that the non-interacting
// indexes have to be shifted over
// by the number of normal interacing atoms. Also, -1 must stay -1.
imat bondsToBeAppended = nonInteractingBonds + positions.n_rows;
bondList = join_cols(bondList, bondsToBeAppended);
// Also, -1 must stay -1. We can find what values used to be -1, buy seeing which values equal added amount (positions.n_rows)-1.
imat neighborsToBeAppended = nonInteractingNeighbors + positions.n_rows;
for (int i = 0; i < neighborsToBeAppended.n_rows; ++i) {
for (int j = 0; j < neighborsToBeAppended.n_cols; ++j) {
//if the neighbor to be appended used to not exist (be -1)....
if (neighborsToBeAppended(i, j) == positions.n_rows - 1) {
neighborsToBeAppended(i, j) = -1;
}
}
}
neighborList = join_cols(neighborList, neighborsToBeAppended);
//for positions we can simply append the non interacting on the back end of the normal atoms
positions = join_cols(positions, nonInteracting);
}
//removes the non-interacting atoms from our position and bond lists,
//while updating the non-interacting component
//the non interacting bond list never changes.
void DataStructureFunctionsATAC::nonInteractingDeAppender(mat& positions, imat& bondList, imat& neighList) {
//non interacting particles are appended at the end.
nonInteracting = positions.rows(positions.n_rows - numOfNonInteracting, positions.n_rows - 1);
positions = positions.rows(0, positions.n_rows - 1 - numOfNonInteracting);
bondList = bondList.rows(0, bondList.n_rows - 1 - numOfNonInteractingBonds);
neighList = neighList.rows(0, neighList.n_rows - 1 - numOfNonInteractingNeighbors);
}
//finds chirality based on diameter. Assumes nanotube is x aligned.
void DataStructureFunctionsATAC::findChiralityBasedOnDiameter(mat positions, imat bonds, imat neighList, bool haveNonInteracting) {
if (haveNonInteracting == true) {
nonInteractingDeAppender(positions, bonds, neighList);
}
//assume diamter is an average of the x and y max and min differences.
vec zCol = positions.col(2);
vec yCol = positions.col(1);
double zDiff = abs(zCol.max() - zCol.min());
double yDiff = abs(yCol.max() - yCol.min());
double diameter = (yDiff + zDiff) / 2;
//now we must generate a set of known diameter values to compare against.
double a = 2.46;
//double pi = 3.14159265;
mat diameterDifferences;
diameterDifferences << -1 << -1 << -1 << endr;
for (int n = minChiralIndex; n <= maxChiralIndex; ++n) {
for (int m = minChiralIndex - 1; m <= n; m++) {
mat toBeAppended;
toBeAppended << abs(diameter - a / 3.14159265 * sqrt(n * n + n * m + m * m)) << n << m << endr;
diameterDifferences = join_cols(diameterDifferences, toBeAppended);
// cout << "N, M, and Diameter, sqrt " <<n<< " " << m<<" " << sqrt(n*n + n * m + m*m)*a/3.14159265 << " " << sqrt(n*n + n * m + m*m)*a/3.14159265 << endl;
}
}
diameterDifferences.shed_row(0);
//sort allong the diameter differences, min to max.
mat sorted = betterSortRows(diameterDifferences, 0);
//save
// cout << "SORTED " << sorted << endl;
// cout << "POS " << positions << endl;
// cout << "z max min " <<zCol.max()<<" " <<zCol.min() << endl;
// cout << "y max min " <<yCol.max()<<" " <<yCol.min() << endl;
//cout << "DIAMTER " << diameter << endl;
for (int i = 0; i < diameterDifferences.n_rows; i++) {
string xS;
stringstream ssX;
ssX << sorted(i, 0) << " " << sorted(i, 1) << " " << sorted(i, 2);
xS = ssX.str();
system(("echo '" + xS + "' >> 0ApproximateDiameterIndexes.txt").c_str());
// system(("echo '" + sorted(i,0) + " " + sorted(i,1) + " "+sorted(i,2) + "' >> ApproximateDiameterIndexes.txt").c_str());
}
//sorted.save("ApproximateDiameterIndexes.txt", arma_ascii);
//add non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingAppender(positions, bonds, neighList);
}
}
//void DataStructureFunctionsATAC::NAMDrun(int mutationGo, double& oldEnergy, double& temperature, mat& positions, imat& bondList, imat& neighborList, double& ratioRotate, double& ratioDimerDisplacement, double& ratioSp2ToSp3, int& spPossibility, string masterBatchName);
//void movieMaker(mat positions, string batchname);
//the flux refers to mass. Only needs the rotate ratio, as the DV and add dimer operations occur on a 1:1 ratio.
void DataStructureFunctionsATAC::noFluxMutation(int& spPossibility, double rotateRatio, double ratioDimerDisplacement, double ratioSp2ToSp3, imat& neighList, imat& bonds, mat& positions, double& randomPercent, double& oldEnergy, double& temperature, imat& neighborList, string masterBatchName, int& inBeam) {
//remove non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingDeAppender(positions, bonds, neighList);
}
imat remainingBonds = bonds;
if (randomPercent < rotateRatio) {
for (int i = 0; i < rotationsPerRun; i++) {
cout << "ROTATE" << endl;
mutation(1, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
cout << "ROTATED" << endl;
}
} else if ((randomPercent > rotateRatio) && (randomPercent < rotateRatio + ratioDimerDisplacement)) {
//dimer displacement.
cout << "REMOVE DIMER" << endl;
mutation(2, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
cout << "REMOVED DIMER" << endl;
int inBeamDummy = -1;
cout << "ADD DIMER" << endl;
imat remainingBonds = bonds; //must refresh the remaining bonds.
mutation(3, neighList, bonds, positions, remainingBonds, masterBatchName, inBeamDummy);
//note, if we have a beam, and a dimer was removed from the beam, we are considering the add dimer reaction to always have the energy
// of the beam, reguardless if the dimer is added in the beam or not. Reason being: the displaced
// dimer would carry the energy from the beam to where ever it goes.
// This is also why we need to make a dummy inBeam varible, as mutation() expects a pointer to an int (int&),
// not an int value.
cout << "ADDED DIMER" << endl;
} else {
//As a reminder, spPossibility -1 means a sp2 to sp3 transition is impossible,
//0 means that we are not considering that transition, and
//1 means that the transition was taken.
//int spPossibility = 0;
cout << "SP2 to SP3 START" << endl;
sp2Tosp3(positions, neighList, bonds, spPossibility);
cout << "SP2 to SP3 END" << endl;
if (relaxAfterSp2Sp3Failure == true || spPossibility == 1) {
cout << "RELAXING STRUCTURE AFTER SP2 TO SP3" << endl;
//add non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingAppender(positions, bonds, neighList);
}
NAMDrun(0, oldEnergy, temperature, positions, bonds, neighborList, rotateRatio, ratioDimerDisplacement, ratioSp2ToSp3, spPossibility, masterBatchName);
//removenon-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingDeAppender(positions, bonds, neighList);
}
}
//if the transition was taken, then we can also take the sp3 to sp2 transition.
//cout << "SP POSSIBILITY " << spPossibility << endl;
if (spPossibility == 1) {
// take sp3 to sp2 reaction.
cout << "SP3 to SP2 START" << endl;
sp3Tosp2(neighList, bonds, positions);
cout << "SP3 to SP2 END" << endl;
}
//spPossibility = 0; //reset the spPossibility number, as we have performed the operations needed.
}
//cout << "Before adding noninteracting atoms" << endl;
//add non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingAppender(positions, bonds, neighList);
}
//cout << "After adding noninteracting atoms" << endl;
}
//This simulates chemical vapor depostion, which at the time is simply add dimer.
void DataStructureFunctionsATAC::CVD(imat& neighList, imat& bonds, mat& positions, double& oldEnergy, double& temperature, imat& neighborList, string masterBatchName, int& inBeam) {
//remove non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingDeAppender(positions, bonds, neighList);
}
cout << "ADD DIMER" << endl;
imat remainingBonds = bonds; //must refresh the remaining bonds.
mutation(3, neighList, bonds, positions, remainingBonds, masterBatchName, inBeam);
cout << "ADDED DIMER" << endl;
//add non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingAppender(positions, bonds, neighList);
}
}
double DataStructureFunctionsATAC::ratioShift(double& ratioRotate, double& ratioDimerDisplacment, double& ratioSp2ToSp3) {
//if noFluxRatioShift type is 1, increase rotation at the expense of sp2 to sp3.
if (noFluxRatioShift == 1) {
//if we go beyond the bounds of the ratios we have set, take the cap values and disable ratio shifting.
if (ratioRotate + ratioShiftRate > ratioRotateFinal || ratioSp2ToSp3 - ratioShiftRate < ratioSp2ToSp3Final) {
//cout << "RATIOooooooooooos " << ratioRotate << " " << ratioRotateFinal << " " << ratioSp2ToSp3 << " " << ratioSp2ToSp3Final << " " << ratioShiftRate << endl;
ratioRotate = ratioRotateFinal;
ratioSp2ToSp3 = ratioSp2ToSp3Final;
noFluxRatioShift = 0;
} else {
ratioRotate += ratioShiftRate;
ratioSp2ToSp3 -= ratioShiftRate;
}
}
}
//bit of code that will run namd, and will always accept configuration (if NAMD doesn't fail)
void DataStructureFunctionsATAC::NAMDrun(int mutationGo, double& oldEnergy, double& temperature, mat& positions, imat& bondList, imat& neighborList, double& ratioRotate, double& ratioDimerDisplacement, double& ratioSp2ToSp3, int& spPossibility, string batchName) {
cout << "NAMD RUN NUMBER: " << namdRunNum << endl;
cout << batchName << endl;
//We need to back up the current information, in case the introduced defect is reduced.
mat positionsBackup = positions; //do I really need this line?
imat neighborListBackup = neighborList;
imat bondListBackup = bondList;
// mat nonInteractingPositionsBackup = nonInteracting;
// imat nonInteractingBondListBackup = nonInteractingBonds;
int inBeam = -1;
//inBeam tells us if the current mutation occured inside or outside the irradiation beam, if it is present.
//0 means the mutation is outside, 1 means the mutation is inside, and -1 means that it is unknown, or unimportant.
double randomPercent;
//pure relaxation.
if (mutationGo == 0) {
cout << "RELAXING WITH NO MUTATION" << endl;
} else
//no flux mutation
if (mutationGo == 1) {
// cout << "MUT GO INSIDE" << mutationGo << endl;
spPossibility = 0;
randomPercent = (double) rand() / (double) (RAND_MAX);
noFluxMutation(spPossibility, ratioRotate, ratioDimerDisplacement, ratioSp2ToSp3, neighborList, bondList, positions, randomPercent, oldEnergy, temperature, neighborList, batchName, inBeam);
} else
//Chemical Vapor Deposition
if (mutationGo == 2) {
CVD(neighborList, bondList, positions, oldEnergy, temperature, neighborList, batchName, inBeam);
}
// the only case we can ignore the following code is if we tried an sp2 to sp3 run that failed.
// and we don't want to record a mutationless frame.
//BAD CODING AHEAD
//need to hide these variables if namd is selected, but still keep them in scope if namd is not selected...
// min_input_t input;
// min_output_t output;
if (spPossibility != -1 || relaxAfterSp2Sp3Failure == true) {
if (forceNum == 1) {
mat xValues = positions.col(0);
double minWallPos = xValues.min() + atof(variableReader("minWallPosModifier").c_str());
double maxWallPos = xValues.max() + atof(variableReader("maxWallPosModifier").c_str());
double wallForce = atof(variableReader("wallForce").c_str());
double tubeRadius = atof(variableReader("tubeRadius").c_str());
double tubeForce = pow(atof(variableReader("tubeForceBase").c_str()), atof(variableReader("tubeForceExponent").c_str())); //force in kcal/mol*A. Should be 7^12.
//tubeForce = 138412;
mat forceMatrix;
forceMatrix.copy_size(positions);
//fills with zeros, as we are initilizing.
forceMatrix.zeros();
forceParallelWalls(positions, forceMatrix, minWallPos, maxWallPos, wallForce, 1);
forceTube(positions, forceMatrix, tubeForce, tubeRadius);
writeForcePDB(positions, forceMatrix);
} else if (forceNum == 2) {
double minViceWall = atof(variableReader("minViceWall").c_str());
double maxViceWall = atof(variableReader("maxViceWall").c_str());
double viceForce = atof(variableReader("viceForce").c_str());
mat forceMatrix;
forceMatrix.copy_size(positions);
//fills with zeros, as we are initilizing.
forceMatrix.zeros();
forceVice(positions, forceMatrix, minViceWall, maxViceWall, viceForce);
writeForcePDB(positions, forceMatrix);
}
cout << "Writing Files...." << endl;
writeTopFile(positions, bondList, batchName);
writePgnFile(positions, batchName);
writePdbPsfFiles(batchName);
cout << "Writing Files Done " << endl;
// cout << "POSITON " << positions << endl << "NEIGH " << neighborList << endl << "BONDs " << bondList << endl;
//remove old log file, as we are about to make a new one.
system(("rm " + batchName + ".log").c_str());
cout << "RUNNING NAMD" << endl;
if (relaxationMethod == 1) {
//NAMD selected
system(("namd2 +p" + numProcessors + " " + batchName + ".conf >> " + batchName + ".log ").c_str());
} else {
//TB selected
// minimization method (enumeration in header file)
// input.method = CT_OPT;
// inputs
// input.bondList = bondList;
// input.positions = positions;
// exit conditions, set either to 0 to disable
// input.interation_limit = 250;
// input.max_force_cutoff = 1e-3;
// periodicity options, 0 to disable
// input.x_period = xLatticeParameter;
// input.y_period = yLatticeParameter;
// input.z_period = zLatticeParameter;
// pass to the minimize function and get an output structure
// output = minimize(input);
}
}
//if we have a beam, and the mutation takes place in the beam region, we must use the beam temperature and not the ambient one.
double ambientTempBackUp = temperature;
if (haveBeam == true && inBeam == true) {
temperature = beamTemperature;
}
//cout << "SP FSFDFS " << spPossibility << endl;
if (energyCheck(oldEnergy, temperature, spPossibility, randomPercent, ratioRotate, ratioDimerDisplacement, batchName, namdRunNum, relaxAfterSp2Sp3Failure, boltzmann, energyFailureTolerance, acceptAnyMutation, relaxationMethod)) {
// cout << "ENERGY WIN " << endl;
//if energy check is passes, updates positions to be used for the next round
//of defects, and adds the frame to the xyz movie.
//copy over sucessful log file to movies directory.
system(("cp " + batchName + ".log movies").c_str());
//place "if coor not found" error check here.
if (relaxationMethod == 1) {
//Get positions from Namd Run
coorStripper(positions, batchName);
} else {
//Get positions from TB
// positions = output.positions;
}
movieMaker(positions, batchName, numberOfElectrodes, xp1Electrodes, xp2Electrodes, xn1Electrodes, xn2Electrodes, yp1Electrodes, yp2Electrodes, yn1Electrodes, yn2Electrodes);
++acceptedRunNum;
++namdRunNum;
string runNumS;
stringstream ssRun;
ssRun << namdRunNum;
runNumS = ssRun.str();
string successfulRunNumS;
stringstream ssSRun;
ssSRun << acceptedRunNum;
successfulRunNumS = ssSRun.str();
string oldEnergyS;
stringstream ssEner;
ssEner << oldEnergy;
oldEnergyS = ssEner.str();
//record energy
chdir("energies");
system(("echo '" + runNumS + " " + oldEnergyS + "' >> energyHist" + batchName + ".dat").c_str());
system(("echo '" + successfulRunNumS + " " + oldEnergyS + "' >> energyHistMovie" + batchName + ".dat").c_str());
chdir("..");
//record chirality
if (findChiralAngles == true) {
//remove non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingDeAppender(positions, bondList, neighborList);
}
//generate rings.
vector<pair<imat, int> > rings;
rings = findRings(neighborList, ringSizeMin, ringSizeMax);
//using this just to generate the angle.dat files, not for the final chiral to index conversion.
recordChirality(rings, positions, false);
//record ring sizes
if (findRingSizes == true) {
recordRingSizes(rings, globalRingSizeRunNum, generateRingHistogramImages);
}
//add non-interactig atoms back.
if (haveNonInteracting == true) {
nonInteractingAppender(positions, bondList, neighborList);
}
}
//record ring sizes, if haven't done so already in the chiral angle finder.
if ((findRingSizes == true) && (findChiralAngles != true)) {
//remove non-interacting atoms to our system
if (haveNonInteracting == true) {
nonInteractingDeAppender(positions, bondList, neighborList);
}
//generate rings.
vector<pair<imat, int> > rings;
rings = findRings(neighborList, ringSizeMin, ringSizeMax);
recordRingSizes(rings, globalRingSizeRunNum, generateRingHistogramImages);
//add non-interactig atoms back.
if (haveNonInteracting == true) {
nonInteractingAppender(positions, bondList, neighborList);
}
}
//adjust beam radius.
beamRadius += beamRadiusGrowthRate;
//restore ambient temperature
if (haveBeam == true && inBeam == true) {
temperature = ambientTempBackUp;
}
if (coolMethod != 0) {
//adjust temperature
if (coolMethod == 1) {
temperature = linearCooling(tempS, tempF, acceptedRunNum, coolR);
} else if (coolMethod == 2) {
temperature = newtonianCooling(tempS, tempF, acceptedRunNum, coolR);
}
//string with updated energy
stringstream ssTemp;
ssTemp << temperature;
string tempStr = ssTemp.str();
system(("sed -i 's/set temperature.*/set temperature " + tempStr + "/' " + batchName + ".conf").c_str()); //" + batchName + ".conf"
}
if (noFluxRatioShift != 0) {
ratioShift(ratioRotate, ratioDimerDisplacement, ratioSp2ToSp3);
//cout << "rrrrrrrrrrrrrrratioSP2ToSp3 " << ratioSp2ToSp3 << endl;
}
if (periodicStretching != 0) {
//adjust periodicity
//see if we are updating in an orthogonal or arbitrary periodicity scheme.
if (periodicityNum < 4) {
if (periodicStretching == 1) {
// cout << "X LAT PARAM IS " << xLatticeParameter << endl;
// system("read -p \"paused\" key");
xLatticeParameter += periodicStretchRate;
stringstream ssX;
ssX << setprecision(15) << xLatticeParameter;
string XS = ssX.str();
//assumes that system is periodic in at least x
system(("sed -i 's/cellBasisVector1.*/cellBasisVector1 " + XS + " 0 0/' " + batchName + ".conf").c_str());
}
//assumes system is at least perodic in x and y directions.
if (periodicStretching == 2) {
xLatticeParameter += periodicStretchRate;
//cout << "Y LAT PARAM before" << yLatticeParameter << " rate stretch "<< periodicStretchRate <<endl;
yLatticeParameter = yLatticeParameter + periodicStretchRate;
//cout << "Y LAT PARAM after" << yLatticeParameter << endl;
stringstream ssX;
ssX << setprecision(15) << xLatticeParameter;
string XS = ssX.str();
stringstream ssY;
ssY << setprecision(15) << yLatticeParameter;
string YS = ssY.str();
//cout <<"STRING " << YS << endl;
system(("sed -i 's/cellBasisVector1.*/cellBasisVector1 " + XS + " 0 0/' " + batchName + ".conf").c_str());
system(("sed -i 's/cellBasisVector2.*/cellBasisVector2 0 " + YS + " 0/' " + batchName + ".conf").c_str());
}
if (periodicStretching == 3) {
xLatticeParameter += periodicStretchRate;
//cout << "Y LAT PARAM before" << yLatticeParameter << " rate stretch "<< periodicStretchRate <<endl;
yLatticeParameter = yLatticeParameter + periodicStretchRate;
//cout << "Y LAT PARAM after" << yLatticeParameter << endl;
zLatticeParameter = yLatticeParameter + periodicStretchRate;
stringstream ssX;
ssX << setprecision(15) << xLatticeParameter;
string XS = ssX.str();
stringstream ssY;
ssY << setprecision(15) << yLatticeParameter;
string YS = ssY.str();
stringstream ssZ;
ssZ << setprecision(15) << zLatticeParameter;
string ZS = ssZ.str();
//cout <<"STRING " << YS << endl;
system(("sed -i 's/cellBasisVector1.*/cellBasisVector1 " + XS + " 0 0/' " + batchName + ".conf").c_str());
system(("sed -i 's/cellBasisVector2.*/cellBasisVector2 0 " + YS + " 0/' " + batchName + ".conf").c_str());
system(("sed -i 's/cellBasisVector3.*/cellBasisVector3 0 " + ZS + " 0/' " + batchName + ".conf").c_str());
}
}
if (periodicityNum == 4) {
if (periodicStretching == 1) {
latticeVec1(0) += periodicStretchRate; //lattice vector 1, dimension 1.
//cout << "LATTICE VEC 1 " << latticeVec1(0) << endl;
//find the normalized values.
double normalizationFactor;
normalizationFactor = abs(latticeVec1(0)) + abs(latticeVec1(1)) + abs(latticeVec1(2));
for (int i = 0; i < 3; i++) {
latticeVec1Norm(i) = latticeVec1(i) / normalizationFactor;
}
stringstream commandSS;
commandSS << setprecision(15) << "sed -i 's/cellBasisVector1.*/cellBasisVector1 " << latticeVec1(0) << " " << latticeVec1(1) << " " << latticeVec1(2) << "/' " << batchName << ".conf";
string Command;
Command.append(commandSS.str());
system(Command.c_str());
// system(("sed -i 's/cellBasisVector1.*/cellBasisVector1 " + latticeVec1(0) + " " + latticeVec1(1) + " " + latticeVec1(2) + "/' " + batchName + ".conf").c_str());
}
if (periodicStretching == 2) {
latticeVec1(0) += periodicStretchRate; //lattice vector 1, dimension 1.
latticeVec2(1) += periodicStretchRate;
//find the normalized values.
double normalizationFactor;
normalizationFactor = abs(latticeVec1(0)) + abs(latticeVec1(1)) + abs(latticeVec1(2));
for (int i = 0; i < 3; i++) {
latticeVec1Norm(i) = latticeVec1(i) / normalizationFactor;
}
normalizationFactor = latticeVec2(0) + latticeVec2(1) + latticeVec2(2);
for (int i = 0; i < 3; i++) {
latticeVec2Norm(i) = latticeVec2(i) / normalizationFactor;
}
stringstream command1SS;
command1SS << setprecision(15) << "sed -i 's/cellBasisVector1.*/cellBasisVector1 " << latticeVec1(0) << " " << latticeVec1(1) << " " << latticeVec1(2) << "/' " << batchName << ".conf";
string Command1;
Command1.append(command1SS.str());
system(Command1.c_str());
stringstream command2SS;
command2SS << setprecision(15) << "sed -i 's/cellBasisVector2.*/cellBasisVector2 " << latticeVec2(0) << " " << latticeVec2(1) << " " << latticeVec2(2) << "/' " << batchName << ".conf";
string Command2;
Command2.append(command2SS.str());
system(Command2.c_str());
}
if (periodicStretching == 3) {
latticeVec1(0) += periodicStretchRate; //lattice vector 1, dimension 1.
latticeVec2(1) += periodicStretchRate;
latticeVec3(2) += periodicStretchRate;
//find the normalized values.
double normalizationFactor;
normalizationFactor = abs(latticeVec1(0)) + abs(latticeVec1(1)) + abs(latticeVec1(2));
for (int i = 0; i < 3; i++) {
latticeVec1Norm(i) = latticeVec1(i) / normalizationFactor;
}
normalizationFactor = latticeVec2(0) + latticeVec2(1) + latticeVec2(2);
for (int i = 0; i < 3; i++) {
latticeVec2Norm(i) = latticeVec2(i) / normalizationFactor;
}
normalizationFactor = latticeVec3(0) + latticeVec3(1) + latticeVec3(2);
for (int i = 0; i < 3; i++) {
latticeVec3Norm(i) = latticeVec3(i) / normalizationFactor;
}
stringstream command1SS;
command1SS << setprecision(15) << "sed -i 's/cellBasisVector1.*/cellBasisVector1 " << latticeVec1(0) << " " << latticeVec1(1) << " " << latticeVec1(2) << "/' " << batchName << ".conf";
string Command1;
Command1.append(command1SS.str());
system(Command1.c_str());
stringstream command2SS;
command2SS << setprecision(15) << "sed -i 's/cellBasisVector2.*/cellBasisVector2 " << latticeVec2(0) << " " << latticeVec2(1) << " " << latticeVec2(2) << "/' " << batchName << ".conf";
string Command2;
Command2.append(command2SS.str());
system(Command2.c_str());
stringstream command3SS;
command3SS << setprecision(15) << "sed -i 's/cellBasisVector3.*/cellBasisVector3 " << latticeVec3(0) << " " << latticeVec3(1) << " " << latticeVec3(2) << "/' " << batchName << ".conf";
string Command3;
Command3.append(command3SS.str());
system(Command3.c_str());
}
}
}
} else {
//if energy check is not tripped, restores values
++namdRunNum;
string runNumS;
stringstream ssRun;
ssRun << namdRunNum;
runNumS = ssRun.str();
string successfulRunNumS;
stringstream ssSRun;
ssSRun << acceptedRunNum;
successfulRunNumS = ssSRun.str();
string oldEnergyS;
stringstream ssEner;
ssEner << oldEnergy;
oldEnergyS = ssEner.str();
//record energy
chdir("energies");
system(("echo '" + runNumS + " " + oldEnergyS + "' >> energyHist" + batchName + ".dat").c_str());
system(("echo '" + successfulRunNumS + " " + oldEnergyS + "' >> energyHistMovie" + batchName + ".dat").c_str());
chdir("..");
neighborList = neighborListBackup;
bondList = bondListBackup;
positions = positionsBackup;
}
//restore ambient temperature
if (haveBeam == true && inBeam == true) {
temperature = ambientTempBackUp;
}
cout << "---------------------------------------------------------" << endl;
}
//This subfunction writes generates a datafile to be used in final movie
//showing the evolution of the chiral angles for all 6 rings.
//assumes tube axis is in x direction.
void DataStructureFunctionsATAC::recordChirality(vector<pair<imat, int> > rings, mat pos, bool findIndexes) {
//find if rings of six exist
for (int i = 0; i < rings.size(); ++i) {
if (rings[i].second == 6) {
chdir("chiralAngles");
imat sixRings = rings[i].first;
//start file with chiral angle points.
ofstream writeFile;
string globalRunNumS;
stringstream ssglobalRunNum;
ssglobalRunNum << globalChiralAngleRunNum;
globalRunNumS = ssglobalRunNum.str();
string globalRunNum1S;
stringstream ssglobalRunNum1;
ssglobalRunNum1 << globalChiralAngleRunNum + 1;
globalRunNum1S = ssglobalRunNum1.str();
mat chiralList;
chiralList << -1 << endr;
writeFile.open((globalRunNum1S + ".dat").c_str());
// loop through each ring...
for (int j = 0; j < sixRings.n_rows /*&& j==0*/; ++j) {
mat NNVec;
//junk initilization value
NNVec << -1 << -1 << -1 << endr;
//loop through each atom in the ring...
for (int k = 0; k < sixRings.n_cols; ++k) {
//loop through each atom again
for (int l = k; l < sixRings.n_cols; ++l) {
if (k != l) {
double distance;
//compare the two atoms, and see if they are within NNN distance of each other.
shortestLineDeterminer(pos, sixRings(j, k), sixRings(j, l), distance, periodicityNum, xLatticeParameter, yLatticeParameter, zLatticeParameter, latticeVec1Norm, latticeVec1, latticeVec2Norm, latticeVec2, latticeVec3Norm, latticeVec3);
if ((lowerNNLimit < distance) && (distance < higherNNLimit)) {
//generate "zig zag" direction vector
mat vectorToBeAppended;
vectorToBeAppended << pos(sixRings(j, k), 0) - pos(sixRings(j, l), 0) << pos(sixRings(j, k), 1) - pos(sixRings(j, l), 1) << pos(sixRings(j, k), 2) - pos(sixRings(j, l), 2) << endr;
NNVec = join_cols(NNVec, vectorToBeAppended);
// cout << "KAY EL " << k << " " << l << " "<< endl;
// cout <<pos(sixRings(j, k), 0) << " "<<pos(sixRings(j, k), 1) << " "<< pos(sixRings(j, k), 2)<<" "<< endl;
//cout <<pos(sixRings(j, l), 0) << " "<<pos(sixRings(j, l), 1) << " "<< pos(sixRings(j, l), 2)<<" "<< endl;
//cout << pos(sixRings(j, k), 0) - pos(sixRings(j, l), 0) <<" "<< pos(sixRings(j, k), 1) - pos(sixRings(j, l), 1) <<" "<< pos(sixRings(j, k), 2) - pos(sixRings(j, l), 2) << endl;
}
}
}
}
//shed junk initilization value
NNVec.shed_row(0);
//check we got at least one vector. This warning message should never trigger, since
//we are looking at a list of rings. should be 3 vectors.
if (NNVec.is_empty()) {
cout << "CANNOT FIND ANY NEXT NEARIST NEIGHBORS, THUS FINDING CHIRAL ANGLES IMPOSSIBLE" << endl;
exit;
}
mat NNVecAveraged;
int useAveragedVectors = atoi(variableReader("useAveragedVectors").c_str());
if (useAveragedVectors == 0) {
NNVecAveraged = NNVec;
} else {
//we have 6 vectors, one for each zig-zag edge of the hexagon.
//However, it's really 3 pairs of parrallel vectors.
//But these vectors are not parrallel in most real cases, due to
//warping of the hexagon. So, we take an average of the pairs that
//are closest. This also makes our results more accurate, as
//often the warping can be canceled by such averaging.
NNVecAveraged << -1 << -1 << -1 << endr;
//iter over vector 1...
for (int vecIter1 = 0; vecIter1 < NNVec.n_rows; vecIter1++) {
mat averagedVector;
//first index is normalized dot product, or similarity. Second and third are the vec Iters.
//last 3 are the averaged vector.
averagedVector << -1 << -1 << -1 << -1 << -1 << -1 << endr;
//iter over vector 2...
for (int vecIter2 = vecIter1; vecIter2 < NNVec.n_rows; vecIter2++) {
// cout << "Vect Iter 1, 2, and num rows " << vecIter1 << " " << vecIter2 << " " << NNVec.n_rows << endl;
if (vecIter1 != vecIter2) {
double similarity;
similarity = abs(dot(NNVec.row(vecIter1) /
sqrt(NNVec(vecIter1, 0) * NNVec(vecIter1, 0) + NNVec(vecIter1, 1) * NNVec(vecIter1, 1) + NNVec(vecIter1, 2) * NNVec(vecIter1, 2)),
NNVec.row(vecIter2) /
sqrt(NNVec(vecIter2, 0) * NNVec(vecIter2, 0) + NNVec(vecIter2, 1) * NNVec(vecIter2, 1) + NNVec(vecIter2, 2) * NNVec(vecIter2, 2))
));
// cout << "SIMILARITY " << similarity << endl << endl;
//we record the vector with the greatest similiarity
if (similarity > averagedVector(0)) {
//before we take the average, keep in mind that one of the vectors might be the
// negative of the other
//If the two vector components multiplied against each other are negative,
//and are above a threshhold size (because of rounding errors near zero), then muliply one vector by -1
if (((NNVec(vecIter1, 0) * NNVec(vecIter2, 0) < 0) && abs(NNVec(vecIter1, 0)) >= vecRoundingErrorCutOff && abs(NNVec(vecIter2, 0)) >= vecRoundingErrorCutOff) ||
((NNVec(vecIter1, 1) * NNVec(vecIter2, 1) < 0) && abs(NNVec(vecIter1, 1)) >= vecRoundingErrorCutOff && abs(NNVec(vecIter2, 1)) >= vecRoundingErrorCutOff) ||
((NNVec(vecIter1, 2) * NNVec(vecIter2, 2) < 0) && abs(NNVec(vecIter1, 2)) >= vecRoundingErrorCutOff && abs(NNVec(vecIter2, 2)) >= vecRoundingErrorCutOff)) {
//vectors are antiparallel
averagedVector << similarity << vecIter1 << vecIter2
<< (-1 * NNVec(vecIter1, 0) + NNVec(vecIter2, 0)) / 2
<< (-1 * NNVec(vecIter1, 1) + NNVec(vecIter2, 1)) / 2
<< (-1 * NNVec(vecIter1, 2) + NNVec(vecIter2, 2)) / 2 << endr;
} else {
//vectors are parallel.
averagedVector << similarity << vecIter1 << vecIter2
<< (NNVec(vecIter1, 0) + NNVec(vecIter2, 0)) / 2
<< (NNVec(vecIter1, 1) + NNVec(vecIter2, 1)) / 2
<< (NNVec(vecIter1, 2) + NNVec(vecIter2, 2)) / 2 << endr;
cout << "VEC 1 " << NNVec.row(vecIter1) << endl << "VEC 2 " << NNVec.row(vecIter2) << endl;
}
}
}
}
// cout << "AVERAGED VECTOR " << averagedVector << endl;
NNVec.shed_row(averagedVector(2));
NNVec.shed_row(averagedVector(1));
vecIter1--;
NNVecAveraged = join_cols(NNVecAveraged, averagedVector.cols(3, 5));
}
NNVecAveraged.shed_row(0);
//cout << "AVERAGED " << NNVecAveraged << endl;
}
//*/
//assume tube is x aligned:
rowvec tubeAxis;
tubeAxis << 1 << 0 << 0 << endr;
//find smallest chiral angle (largest angle possible should be 30 deg,
// so start with the assumption that it's 90 deg, and we'll update it
//with with smaller values as we find them).
double chiralAngle = 3.14159265 / 2;
// cout << "NN VEC " << NNVecAveraged << endl;
for (int vecIter = 0; vecIter < NNVecAveraged.n_rows; vecIter++) {
//phi is angle between the NNN vector and the tube axis
double phi;
rowvec NNVecRow = NNVecAveraged.row(vecIter);
//phi is angle between the NNN vector and the tube axis
phi = acos(dot(tubeAxis, NNVecRow) / (1 * sqrt(NNVecRow(0) * NNVecRow(0) + NNVecRow(1) * NNVecRow(1) + NNVecRow(2) * NNVecRow(2))));
//we need the smallest angle of the intersection of these two vectors,
//so find the acute complimentary of phi if it is oblique.
// if (phi < 3.14259265 / 2) {
// phi = 3.14259265 - phi;
// }
// cout <<"PHI "<< abs(phi)*180/3.141 << endl;
//theta is the chiral angle. We must remember that the
//chiral angle is that between the zig-zag direction (NNN vector)
//and the tube diameter (the plane normal to the tube axis).
//to convert phi into theta, do the simple conversion:
double theta;
if (phi < 3.14159265 / 2) {
theta = 3.14159265 / 2 - phi;
} else {
theta = phi - 3.14159265 / 2;
}
// cout <<"THATA "<< abs(theta)*180/3.141 << endl;
//find smallest chiral angle out of all zig-zag directions.
if (abs(theta) < chiralAngle) {
//theta should always be positive, but due to rounding, small angles could be negative.
chiralAngle = abs(theta);
}
}
mat toBeAppended;
toBeAppended << chiralAngle * 180 / 3.1412 << endr;
chiralList = join_cols(chiralList, toBeAppended);
writeFile << chiralAngle * 180 / 3.14159265 << endl;
}
writeFile.close();
chiralList.shed_row(0);
// cout << "CHIRAL LIST " << chiralList << endl;
if (findIndexes == true) {
double a = 2.46; //in angstroms.
//double pi = 3.14159265;
mat anglesAndIndexes;
anglesAndIndexes << -1 << -1 << -1 << -1 << endr;
//creat a matrix recording how many rings of a given n and m are seen.
mat counts;
counts << -1 << -1 << -1 << endr;
for (int n = minChiralIndex; n <= maxChiralIndex; ++n) {
for (int m = minChiralIndex - 1; m <= n; m++) {
mat toBeAppended;
toBeAppended << 0 << n << m << endr;
counts = join_cols(counts, toBeAppended);
}
}
counts.shed_row(0);
// for each angle...
for (int angleIter = 0; angleIter < chiralList.n_rows; angleIter++) {
mat angleDifferences;
angleDifferences << -1 << -1 << -1 << -1 << endr;
for (int n = minChiralIndex; n <= maxChiralIndex; ++n) {
for (int m = minChiralIndex - 1; m <= n; m++) {
//must remember that N must always be greater than M in the nanotube indexed scheme.
if (n >= m) {
mat toBeAppended;
toBeAppended << abs(chiralList(angleIter) - atan(sqrt(3) * m / (2 * n + m))*180 / 3.14159265) << chiralList(angleIter) << n << m << endr;
angleDifferences = join_cols(angleDifferences, toBeAppended);
//cout << "N, M, ANGLE " << n << " " << m << " " << atan(sqrt(3) * m / (2 * n + m))*180 / 3.14159265 << " "<< endl;
}
}
}
angleDifferences.shed_row(0);
//sort to find the best match of a given angle to the index list.
mat sortedForAnAngle = betterSortRows(angleDifferences, 0);
// cout <<"SORTEDFORANANGLE " << sortedForAnAngle << endl;
bool findChiralSpread = atoi(variableReader("findChiralSpread").c_str());
if (findChiralSpread == 0) {
//best chiral fit found. will have the least difference
//add to our final list of indexes
mat toBeAppendedIndexes;
toBeAppendedIndexes << sortedForAnAngle(0, 0) << sortedForAnAngle(0, 1) << sortedForAnAngle(0, 2) << sortedForAnAngle(0, 3) << endr;
anglesAndIndexes = join_cols(anglesAndIndexes, toBeAppendedIndexes);
//have to find matching indexes on count, then add to it.
for (int i = 0; i < counts.n_rows; i++) {
if (counts(i, 1) == sortedForAnAngle(0, 2) && counts(i, 2) == sortedForAnAngle(0, 3)) {
counts(i, 0) = counts(i, 0) + 1;
break;
}
}
} else {
//same as immediatly above, except we record multiple possible theoretical indexes for the experimental angle.
double maxChiralAngleDifference = atof(variableReader("maxChiralAngleDifference").c_str());
for (int sortedIter = 0; sortedIter < sortedForAnAngle.n_rows; sortedIter++) {
if (sortedForAnAngle(sortedIter, 0) < maxChiralAngleDifference) {
mat toBeAppendedIndexes;
toBeAppendedIndexes << sortedForAnAngle(sortedIter, 0) << sortedForAnAngle(sortedIter, 1) << sortedForAnAngle(sortedIter, 2) << sortedForAnAngle(sortedIter, 3) << endr;
anglesAndIndexes = join_cols(anglesAndIndexes, toBeAppendedIndexes);
//have to find matching indexes on count, then add to it.
for (int i = 0; i < counts.n_rows; i++) {
if (counts(i, 1) == sortedForAnAngle(sortedIter, 2) && counts(i, 2) == sortedForAnAngle(sortedIter, 3)) {
counts(i, 0) = counts(i, 0) + 1;
break;
}
}
}
}
}
}
anglesAndIndexes.shed_row(0);
//cout << "ANGLDS " << anglesAndIndexes << "FIN " << endl;
// counts.shed_row(0);
mat sortedForCount = betterSortRows(counts, 0);
//save count
//reverse iter for count.
for (int i = sortedForCount.n_rows - 1; i >= 0; i--) {
string xS;
stringstream ssX;
ssX << sortedForCount(i, 0) << " " << sortedForCount(i, 1) << " " << sortedForCount(i, 2);
xS = ssX.str();
system(("echo '" + xS + "' >> 0IndexCountAngleBased.txt").c_str());
// system(("echo '" + sorted(i,0) + " " + sorted(i,1) + " "+sorted(i,2) + "' >> ApproximateDiameterIndexes.txt").c_str());
}
string xS1;
stringstream ssX1;
ssX1 << "Median Difference From Ideal: " << median(anglesAndIndexes.col(0)) << " Median Angle: " << median(anglesAndIndexes.col(1)) << " Average Difference From Ideal: " << mean(anglesAndIndexes.col(0)) << " Average Angle: " << mean(anglesAndIndexes.col(1));
xS1 = ssX1.str();
system(("echo '" + xS1 + "' >> 0EachRingsAnglesAndIndexes.txt").c_str());
//save angles and indexes.
for (int i = 0; i < anglesAndIndexes.n_rows; i++) {
string xS;
stringstream ssX;
ssX << anglesAndIndexes(i, 0) << " " << anglesAndIndexes(i, 1) << " " << anglesAndIndexes(i, 2) << " " << anglesAndIndexes(i, 3);
xS = ssX.str();
system(("echo '" + xS + "' >> 0EachRingsAnglesAndIndexes.txt").c_str());
// system(("echo '" + sorted(i,0) + " " + sorted(i,1) + " "+sorted(i,2) + "' >> ApproximateDiameterIndexes.txt").c_str());
}
}
//we must label the jpegs of the plots in an appropriate manner to be
//converted into an mpeg later.
string label;
stringstream number;
if ((globalChiralAngleRunNum + 1) < 10) {
label = "0000";
} else if ((globalChiralAngleRunNum + 1) < 100) {
label = "000" + number.str();
} else if ((globalChiralAngleRunNum + 1) < 1000) {
label = "00" + number.str();
} else if ((globalChiralAngleRunNum + 1) < 10000) {
label = "0" + number.str();
} else if ((globalChiralAngleRunNum + 1) < 100000) {
label = "" + number.str();
} else {
cerr << "MORE THAN 99,999 frames" << endl;
}
number << (globalChiralAngleRunNum + 1);
label.append(number.str());
if (generateRingHistogramImages == 1) {
//updates the histogram script with the current run data, executes it, and generates a jpeg.
system(("sed \"s/0.dat/" + globalRunNum1S + ".dat/g\" histogramScript.plt | gnuplot > pic" + label + ".jpg").c_str());
}
globalChiralAngleRunNum++;
chdir("..");
}
}
}
| true |
d692f843a45080fc6e09de7267e9e8672ff0c82c | C++ | Nickqiaoo/TinySTL | /Alloc.h | UTF-8 | 2,087 | 3.109375 | 3 | [] | no_license | #ifndef ALLOC_H__
#define ALLOC_H__
#include <cstddef>
#include <cstdlib>
namespace TinySTL {
//包装接口,使用传入的Alloc分配内存,Alloc默认第二级
template <class T, class Alloc>
class simple_alloc {
public:
static T* allocate(size_t n) {
return n == 0 ? 0:
(T*)Alloc::allocate(n * sizeof(T));
}
static T* allocate(void) { return (T*)Alloc::allocate(sizeof(T)); }
static void deallocate(T* p, size_t n) {
if (0 != n) Alloc::deallocate(p, n * sizeof(T));
}
static void deallocate(T* p) { Alloc::deallocate(p, sizeof(T)); }
};
//申请内存较大时直接使用malloc
class malloc_alloc {
public:
static void* allocate(size_t n) { return malloc(n); }
static void* deallocate(void* p, size_t) { free(p); }
static void* reallocate(void* p, size_t, size_t new_sz) {
return realloc(p, new_sz);
}
};
//第二级配置器
class default_alloc {
private:
enum { ALIGN = 8 }; //区块大小是8的倍数
enum { MAX_BYTES = 128 }; //区块最大大小
enum { NFREELISTS = MAX_BYTES / ALIGN }; //自由区块链表个数
union obj {
union obj* free_list_link;
char client_data[1];
};
static obj* free_list[NFREELISTS];
static char* start_free;
static char* end_free;
static size_t heap_size;
static size_t ROUND_UP(size_t bytes) { //调整为8的倍数
return ((bytes + ALIGN - 1) & ~(ALIGN - 1));
}
static size_t FREELIST_INDEX(size_t bytes) { //根据区块大小访问对应链表
return (((bytes) + ALIGN - 1) / ALIGN - 1);
}
static void* refill(size_t n); //返回一个大小为n的对象并填充新的区块
static char* chunk_alloc(size_t size,
int& nobjs); //配置 nobjs * size 大小的空间
public:
static void* allocate(size_t n);
static void deallocate(void* p, size_t);
static void* reallocate(void* p, size_t, size_t new_sz);
};
typedef default_alloc alloc;
} // namespace TinySTL
#endif
| true |
c8ee91bb4ec95162ecf1934ec2af7dad5cb55946 | C++ | hiromk6/socket-study | /002_basic/2-11_copy.cpp | UTF-8 | 829 | 3.765625 | 4 | [] | no_license | //remove_copy, replace_copy
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
char str[] = "Algorithms operate on containers through iterators.";
vector<char> v, v2(100);
vector<char>::iterator p;
int i;
for(i=0; str[i]; i++) v.push_back(str[i]);
cout << "Input sequence:\n";
for(i=0; i<v.size(); i++) cout << v[i];
cout << endl;
p = remove_copy(v.begin(), v.end(), v2.begin(), ' ');
cout << "Result after removing spaces:\n";
for(i=0; i<p-v2.begin(); i++) cout << v2[i];
cout << "\n\n";
cout << "Input sequence:\n";
for(i=0; i<v.size(); i++) cout << v[i];
cout << endl;
p = replace_copy(v.begin(), v.end(), v2.begin(), ' ', '+');
cout << "Result after replacing spaces with +'s:\n";
for(i=0; i<p-v2.begin(); i++) cout << v2[i];
cout << "\n\n";
return 0;
}
| true |
d4940394fec9f65bc86ab81b54aaafd0edec835e | C++ | demaisj/ZiaModuleAPISpec | /include/Zia/API/Module.hpp | UTF-8 | 1,964 | 2.90625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2019
** ZiaModuleAPISpec
** File description:
** Module spec
*/
#pragma once
#include <string>
#include "ServerConfig.hpp"
#include "RequestHandler.hpp"
namespace Zia {
namespace API {
/*
* BASE MODULE
*
* This class is the main module interface. It describes the module meta-data,
* and contains server-level hooks for this module.
*
* Use exceptions for critial errors in the module code. Those can be catched
* by the server in order to shut down the module and prevent a crash.
*/
class Module {
public:
/*
* TYPES:
*
* pointer:
* pointer type for the Module class
* factory:
* prototype for the module factory function
* recycler:
* prototype for the module recycler function
*/
using pointer = Module*;
using factory = Module::pointer (*)();
using recycler = void (*)(Module::pointer);
/*
* INSTANTIATION:
*
* constructor:
* used to allocated needed resources for said module
* destructor:
* used to deallocate those same resources
*/
virtual ~Module() {};
/*
* METADATA:
*
* getName:
* name of the module
*/
virtual const std::string& getName() const = 0;
/*
* ACTIVATION HOOKS:
*
* onActivate:
* called when the module is activated by the server
* server configuration is passed as an argument
* onDeactivate:
* called when the module is deactivated
* onConfigChange:
* called when the server configuration is updated
*/
virtual void onActivate(const ServerConfig& /* cfg */) { }
virtual void onDeactivate() { }
virtual void onConfigChange(const ServerConfig& /* cfg */) { }
/*
* REQUEST HANDLER:
*
* newRequestHandler:
* creates a new instance of a Request Handler.
*/
virtual RequestHandler::pointer newRequestHandler() = 0;
};
}
}
| true |