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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22955b6653299276fc0dc9e280a715a061b20006 | C++ | SerenityOS/serenity | /Userland/Utilities/pkg/InstalledPort.h | UTF-8 | 1,238 | 2.78125 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* Copyright (c) 2023, Liav A. <liavalb@hotmail.co.il>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/HashMap.h>
#include <AK/String.h>
#include <AK/StringView.h>
#include <AK/Types.h>
class InstalledPort {
public:
enum class Type {
Auto,
Dependency,
Manual,
};
static ErrorOr<HashMap<String, InstalledPort>> read_ports_database();
static ErrorOr<void> for_each_by_type(HashMap<String, InstalledPort>&, Type type, Function<ErrorOr<void>(InstalledPort const&)> callback);
InstalledPort(String name, Type type, String version)
: m_name(name)
, m_type(type)
, m_version(move(version))
{
}
Type type() const { return m_type; }
StringView type_as_string_view() const
{
if (m_type == Type::Auto)
return "Automatic"sv;
if (m_type == Type::Dependency)
return "Dependency"sv;
if (m_type == Type::Manual)
return "Manual"sv;
VERIFY_NOT_REACHED();
}
StringView name() const { return m_name.bytes_as_string_view(); }
StringView version() const { return m_version.bytes_as_string_view(); }
private:
String m_name;
Type m_type;
String m_version;
};
| true |
463ed6ac0eb946cf171516e59909e97507c6f77a | C++ | marcuscraske/project-euler | /PE_CPP/PE_CPP/Solution035.cpp | UTF-8 | 1,900 | 3.46875 | 3 | [
"WTFPL"
] | permissive | #pragma once
#include "Solution035.h"
#include "SolutionIncludes.h"
#include "SievePrimes.h"
#include <vector>
#include <algorithm>
int Solution035::problemNumber()
{
return 35;
}
string Solution035::title()
{
return "Number of circular primes below one million.";
}
void Solution035::execute()
{
int limit = 1000000;
SievePrimes sp(limit * 10, true);
long cPrimes = 0;
long* digits;
long num;
long endElement;
bool nonPrimeFound;
// We will cache pre-existing circulars to speed-up the process
vector<long> circulars;
vector<long> iterations;
// Begin iterating up to the limit for primes and check if each prime is circular
for(int i = 2; i < limit; i++)
{
if(sp.isPrime(i) && find(circulars.begin(), circulars.end(), i) == circulars.end())
{
if(i < 10) cPrimes++;
else
{
// We need to get the digits and make every permutation of the number
// and check if it's a prime
digits = Utils::getDigits(i);
// Check if the digits have been moved around; if so, we need to check it's prime
nonPrimeFound = false;
iterations.clear();
do
{
// Shift the elements to the right by one
endElement = digits[digits[0]];
for(int i = digits[0] - 1; i > 0; i--)
digits[i + 1] = digits[i];
digits[1] = endElement;
// Sum the digits
num = 0;
for(int i = 1; i <= digits[0]; i++)
num = (num * 10) + digits[i];
// Add the iteration to the list
iterations.push_back(num);
// Check the number is prime
if(!sp.isPrime(num))
break;
}
while(num != i);
if(num == i)
{
// Add all the iterations found (since they too are circular)
cPrimes += iterations.size();
// Add the iterations to the circular cache
circulars.insert(circulars.end(), iterations.begin(), iterations.end());
}
delete[] digits;
}
}
}
cout << "Answer: " << cPrimes << endl;
} | true |
0033ae5d616714884d4f8bdce77460c4adc0463e | C++ | Haozhu3/Comp_Arch | /Lab12/simplecache.cpp | UTF-8 | 706 | 2.875 | 3 | [] | no_license | #include "simplecache.h"
int SimpleCache::find(int index, int tag, int block_offset) {
// read handout for implementation details
auto & vec = _cache[index];
for (size_t i = 0; i < vec.size(); i++) {
if (vec[i].valid() == 1 && vec[i].tag() == tag) {
return vec[i].get_byte(block_offset);
}
}
return 0xdeadbeef;
}
void SimpleCache::insert(int index, int tag, char data[]) {
// read handout for implementation details
// keep in mind what happens when you assign in in C++ (hint: Rule of Three)
auto & vec = _cache[index];
size_t i;
for (i = 0; i < vec.size(); i++) {
if (vec[i].valid() == 0) break;
}
i = i == vec.size() ? 0 : i;
vec[i].replace(tag, data);
}
| true |
5822f1cdc9d8cfcf660e2ed2b8d9938d431d6dab | C++ | Exoil/DirectedOrderNumber | /CpuSourceCode/DirectedEquation.cpp | UTF-8 | 22,103 | 3.09375 | 3 | [] | no_license | #include "./DirectedOrderNumber.cpp"
#include <vector>
#include <string>
#include <algorithm>
#include <time.h>
#include <filesystem>
#if defined(_MSC_VER)
#include <direct.h>
#define getcwd _getcwd
#elif defined(__GNUC__)
#include <unistd.h>
#endif
#include <iomanip>
#include <sstream>
#include <fstream>
#include <sys/stat.h>
#include <string>
#include <stdlib.h>
#include <iostream>
class DirectedOrderNumberArithmetic
{
public:
void AddDirectedOrderNumber(DirectedOrderNumber* firstValue, DirectedOrderNumber* secondValue, DirectedOrderNumber* result)
{
result->SetValues(firstValue->infimum+ secondValue->infimum, firstValue->supremum + secondValue->supremum);
}
void SubstractDirectedOrderNumber(DirectedOrderNumber* firstValue, DirectedOrderNumber* secondValue, DirectedOrderNumber* result)
{
result->SetValues(firstValue->infimum - secondValue->infimum, firstValue->supremum - secondValue->supremum);
}
void MultipleDirectedOrderNumber(DirectedOrderNumber* firstNumber, DirectedOrderNumber* secondNumber, DirectedOrderNumber* result) {
double* multipleResult;
multipleResult = new double[4];
multipleResult[0] = (firstNumber->infimum * secondNumber->infimum);
multipleResult[1] = (firstNumber->infimum * secondNumber->supremum);
multipleResult[2] = (firstNumber->supremum * secondNumber->supremum);
multipleResult[3] = (firstNumber->supremum * secondNumber->infimum);
std::sort(multipleResult, multipleResult + 4);
result->infimum = multipleResult[0];
result->supremum = multipleResult[3];
delete[](multipleResult);
}
void DivideDirectedOrderNumber(DirectedOrderNumber* firstNumber, DirectedOrderNumber* secondNumber, DirectedOrderNumber* result) {
if (firstNumber->GetDivideType() == GreaterThanZero && secondNumber->GetDivideType() == GreaterThanZero)
{
result->infimum = firstNumber->infimum / secondNumber->infimum;
result->supremum = firstNumber->supremum / secondNumber->supremum;
}
else if (firstNumber->GetDivideType() == LesserThanZero && secondNumber->GetDivideType() == LesserThanZero)
{
result->supremum = firstNumber->infimum / secondNumber->infimum;
result->infimum = firstNumber->supremum / secondNumber->supremum;
}
else if (firstNumber->GetDivideType() == GreaterThanZero && secondNumber->GetDivideType() == LesserThanZero)
{
result->infimum = firstNumber->supremum / secondNumber->infimum;
result->supremum = firstNumber->infimum / secondNumber->supremum;
}
else if (firstNumber->GetDivideType() == LesserThanZero && secondNumber->GetDivideType() == GreaterThanZero)
{
result->infimum = firstNumber->infimum / secondNumber->supremum;
result->supremum = firstNumber->supremum / secondNumber->infimum;
}
else if (firstNumber->GetDivideType() == HaveZero && secondNumber->GetDivideType() == GreaterThanZero)
{
result->infimum = firstNumber->infimum / secondNumber->supremum;
result->supremum = firstNumber->supremum / secondNumber->supremum;
}
else if (firstNumber->GetDivideType() == HaveZero && secondNumber->GetDivideType() == LesserThanZero)
{
result->infimum = firstNumber->supremum / secondNumber->infimum;
result->supremum = firstNumber->infimum / secondNumber->infimum;
}
else if (secondNumber->GetDivideType() == HaveZero)
{
secondNumber->infimum = (1.0);
secondNumber->supremum = (1.0);
DivideDirectedOrderNumber(firstNumber, secondNumber, result);
}
}
};
class DirectedOrderNumberGenerator
{
private:
double GenerateNumber()
{
int floor = (int)lowerRange;
int roof = (int)upperRange;
double result = (double)(rand() % roof + 1.0);
return result;
}
double CreateSampleInfimum()
{
return (GenerateNumber() - precision);
}
double CreateSampleSupremum()
{
return (GenerateNumber() + precision);
}
DirectedOrderNumber GenerateDirectedOrderNumber()
{
double generatedNumber = GenerateNumber();
if (rand() % 100 + 1 % 2 != 0) {
generatedNumber *= -1.0;
}
double halfNumber = generatedNumber / 2.0;
DirectedOrderNumber result;
if (rand() % 100 + 1 % 2 == 0)
result.SetValues(halfNumber - precision, halfNumber + precision);
else
result.SetValues(halfNumber + precision, halfNumber - precision);
return result;
}
public:
double precision;
int lowerRange;
int upperRange;
DirectedOrderNumberGenerator(int low, int up, double prec)
{
srand((unsigned)time(0));
lowerRange = low;
upperRange = up;
precision = prec;
}
DirectedOrderNumber* GenerateSampleVector(int rows)
{
DirectedOrderNumber* resultVector;
resultVector = new DirectedOrderNumber[rows];
for (int i = 0; i < rows; i++)
{
resultVector[i] = GenerateDirectedOrderNumber();
}
return resultVector;
}
DirectedOrderNumber** GenerateEquationwithoutFreeValues(int rows)
{
DirectedOrderNumber** equation;
equation = new DirectedOrderNumber * [rows];
for (int i = 0; i < rows; i++)
equation[i] = new DirectedOrderNumber[rows + 1];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows + 1; j++)
equation[i][j] = GenerateDirectedOrderNumber();
equation[i][rows].SetValues(0.0, 0.0);
}
return equation;
}
DirectedOrderNumber* GenereteFreeVaule(DirectedOrderNumber** equation, DirectedOrderNumber* resultVector, int rows)
{
DirectedOrderNumberArithmetic operations;
DirectedOrderNumber* freeVector;
freeVector = new DirectedOrderNumber[rows];
DirectedOrderNumber tmp(0.0, 0.0);
for (int i = 0; i < rows; i++)
{
tmp = GenerateDirectedOrderNumber();
freeVector[i].SetValues(tmp.infimum, tmp.supremum);
}
return freeVector;
}
void FillEquationWithFreeValues(DirectedOrderNumber** equation, DirectedOrderNumber* resultVector, int rows)
{
DirectedOrderNumber tmp(0.0, 0.0);
DirectedOrderNumberArithmetic operations;
for (int i = 0; i < rows; i++)
{
tmp = GenerateDirectedOrderNumber();
equation[i][rows].SetValues(tmp.infimum, tmp.supremum);
}
}
DirectedOrderNumber** SimpleSampleEquationTest()
{
DirectedOrderNumber** sample;
sample = new DirectedOrderNumber * [2];
for (int i = 0; i < 2; i++)
sample[i] = new DirectedOrderNumber[3];
sample[0][0].SetValues(1.99999999, 2.00000001);
sample[0][1].SetValues(2.99999999, 3.00000001);
sample[0][2].SetValues(6.99999999, 7.00000001);
sample[1][0].SetValues(-1.00000001, -0.99999999);
sample[1][1].SetValues(3.99999999, 4.00000001);
sample[1][2].SetValues(1.99999999, 2.00000001);
return sample;
}
DirectedOrderNumber** SimpleSampleEquationFourRowsTest()
{
DirectedOrderNumber** sample;
sample = new DirectedOrderNumber * [4];
for (int i = 0; i < 4; i++)
sample[i] = new DirectedOrderNumber[5];
sample[0][0].SetValues(2.01,5.99);
sample[0][1].SetValues(-3.01, -0.99);
sample[0][2].SetValues(1.99, 4.01);
sample[0][3].SetValues(-0.99, -3.01);
sample[0][4].SetValues(4.01, 7.99);
sample[1][0].SetValues(1.99, 4.01);
sample[1][1].SetValues(0.99, 1.01);
sample[1][2].SetValues(2.99, 3.01);
sample[1][3].SetValues(0.99, 3.01);
sample[1][4].SetValues(4.01, 9.99);
sample[2][0].SetValues(1.01, 2.99);
sample[2][1].SetValues(2.01, 3.99);
sample[2][2].SetValues(1.99, 2.01);
sample[2][3].SetValues(0.99, 1.01);
sample[2][4].SetValues(7.99, 12.01);
sample[3][0].SetValues(1.99, 2.01);
sample[3][1].SetValues(-2.01, -1.99);
sample[3][2].SetValues(2.99, 3.01);
sample[3][3].SetValues(1.99, 2.01);
sample[3][4].SetValues(2.01, 1.99);
return sample;
}
DirectedOrderNumber** SimpleSampleForPivotEquationTest()
{
DirectedOrderNumber** sample;
sample = new DirectedOrderNumber * [2];
for (int i = 0; i < 2; i++)
sample[i] = new DirectedOrderNumber[3];
sample[1][0].SetValues(1.99999999, 2.00000001);
sample[1][1].SetValues(2.99999999, 3.00000001);
sample[1][2].SetValues(6.99999999, 7.00000001);
sample[0][0].SetValues(-1.00000001, -0.99999999);
sample[0][1].SetValues(3.99999999, 4.00000001);
sample[0][2].SetValues(1.99999999, 2.00000001);
return sample;
}
DirectedOrderNumber** PivotSimpleSampleEquationTest()
{
DirectedOrderNumber** sample;
sample = new DirectedOrderNumber * [2];
for (int i = 0; i < 2; i++)
sample[i] = new DirectedOrderNumber[3];
sample[0][0].SetValues(1.99999999, 2.00000001);
sample[0][1].SetValues(2.99999999, 3.00000001);
sample[0][2].SetValues(6.99999999, 7.00000001);
sample[1][0].SetValues(1.00000001, 6.99999999);
sample[1][1].SetValues(3.99999999, 4.00000001);
sample[1][2].SetValues(1.99999999, 2.00000001);
return sample;
}
DirectedOrderNumber** SimpleSampleEquationTestSecond()
{
DirectedOrderNumber** sample;
sample = new DirectedOrderNumber * [3];
for (int i = 0; i < 3; i++)
sample[i] = new DirectedOrderNumber[3 + 1];
sample[0][0].SetValues(4.99999999, 5.00000001);
sample[0][1].SetValues(-4.00000001, -2.99999999);
sample[0][2].SetValues(1.99999999, 3.00000001);
sample[0][3].SetValues(4.00000001, 4.99999999);
sample[1][0].SetValues(0.99999999, 2.00000001);
sample[1][1].SetValues(2.99999999, 3.00000000001);
sample[1][2].SetValues(2.99999999, 2.00000001);
sample[1][3].SetValues(-6.00000001, -2.99999999);
sample[2][0].SetValues(2.99999999, 6.00000001);
sample[2][1].SetValues(1.99999999, 1.00000001);
sample[2][2].SetValues(-1.00000001, -0.99999999);
sample[2][3].SetValues(-4.99999999, 2.99999999);
return sample;
}
};
class DirectedEquationMethod {
public:
DirectedOrderNumberArithmetic* operation;
double precison;
DirectedEquationMethod(double precison)
{
operation = new DirectedOrderNumberArithmetic();
this->precison = precison;
}
~DirectedEquationMethod()
{
delete operation;
}
void SetElimantedZeroToken(DirectedOrderNumber** equation, int rows, int i)
{
for (int l = 0; l < rows; l++)
{
if (l != i)
equation[l][i].zeroFlag = true;
}
}
void EleminatePart(DirectedOrderNumber** equation, int rows)
{
int i, j;
DirectedOrderNumber *mnoznik;
DirectedOrderNumber *minus;
DirectedOrderNumber* tmp;
mnoznik = new DirectedOrderNumber();
minus = new DirectedOrderNumber(-1.0, -1.0);
tmp = new DirectedOrderNumber(0.0, 0.0);
for (i = 0; i < rows - 1; i++)
{
for (j = i + 1; j < rows; j++)
{
operation->MultipleDirectedOrderNumber(minus, &equation[j][i],minus);
operation->DivideDirectedOrderNumber(minus, &equation[i][i], mnoznik);
for (int k = i; k <= rows; k++)
{
operation->MultipleDirectedOrderNumber(mnoznik, &equation[i][k], tmp);
operation->AddDirectedOrderNumber(&equation[j][k], tmp, &equation[j][k]);
}
// std::cout << std::setprecision(8) << "inf " << equation[i][j].infimum << " sup " << equation[i][j].supremum;
}
std::cout <<"Krok: " <<i<< std::endl;
//
SetElimantedZeroToken(equation, rows, i);
tmp->SetValues(0.0, 0.0);
minus->SetValues(-1.0, -1.0);
mnoznik->SetValues(0.0, 0.0);
}
delete tmp;
delete minus;
delete mnoznik;
}
DirectedOrderNumber* VectorResult(DirectedOrderNumber** equation, int rows)
{
int i, j;
DirectedOrderNumber *sum,*tmp;
DirectedOrderNumber* vectorResult;
vectorResult = new DirectedOrderNumber[rows];
sum = new DirectedOrderNumber(0.0, 0.0);
tmp = new DirectedOrderNumber(0.0, 0.0);
for (int k = 0; k < rows; k++)
{
vectorResult[k].SetValues(1.0, 1.0);
}
for (i = rows - 1; i >= 0; i--)
{
sum->SetValues(equation[i][rows].infimum, equation[i][rows].supremum);
for (j = rows - 1; j >= i + 1; j--)
{
operation->MultipleDirectedOrderNumber(&equation[i][j], &vectorResult[j], tmp);
operation->SubstractDirectedOrderNumber(sum, tmp, sum);
}
operation->DivideDirectedOrderNumber(sum, &equation[i][i],&vectorResult[i]);
}
return vectorResult;
}
DirectedOrderNumber* GaussElemination(DirectedOrderNumber** equation, int rows)
{
DirectedOrderNumber* resultVector;
EleminatePart(equation, rows);
resultVector = VectorResult(equation, rows);
return resultVector;
}
int FindMaxInColumn(DirectedOrderNumber** equation, int column, int row, int rows)
{
int indexWithMaxValue = row;
for (int i = row + 1; i < rows; i++)
{
if (equation[indexWithMaxValue][column].GetAbsoulteRealNumber() < equation[i][column].GetAbsoulteRealNumber()) {
indexWithMaxValue = i;
}
}
return indexWithMaxValue;
}
void PartialPivot(DirectedOrderNumber** equation, int rows, int firstIndexToSwap, int secondIndexToSwap)
{
DirectedOrderNumber *rowTmp;
rowTmp = NULL;
for (int i = 0; i < rows + 1; i++)
{
rowTmp = new DirectedOrderNumber(equation[firstIndexToSwap][i].infimum, equation[firstIndexToSwap][i].supremum);
equation[firstIndexToSwap][i].SetValues(equation[secondIndexToSwap][i].infimum, equation[secondIndexToSwap][i].supremum);
equation[secondIndexToSwap][i].SetValues(rowTmp->infimum, rowTmp->supremum);
int x = 5;
}
delete rowTmp;
}
void EleminatePartWithPivot(DirectedOrderNumber** equation, int rows)
{ //iteratory
int i, j;
int indexPivot = -1;
int indexToswap = -1;
DirectedOrderNumber* mnoznik;
DirectedOrderNumber* minus;
DirectedOrderNumber* tmp;
mnoznik = new DirectedOrderNumber();
minus = new DirectedOrderNumber(-1.0, -1.0);
tmp = new DirectedOrderNumber(0.0, 0.0);
for (i = 0; i < rows - 1; i++)
{
indexPivot = i;
indexToswap = FindMaxInColumn(equation, i, i, rows);
if (indexPivot != indexToswap)
PartialPivot(equation, rows, indexPivot, indexToswap);
for (j = i + 1; j < rows; j++)
{
operation->MultipleDirectedOrderNumber(minus, &equation[j][i], minus);
operation->DivideDirectedOrderNumber(minus, &equation[i][i], mnoznik);
for (int k = i; k <= rows; k++)
{
operation->MultipleDirectedOrderNumber(mnoznik, &equation[i][k], tmp);
operation->AddDirectedOrderNumber(&equation[j][k], tmp, &equation[j][k]);
}
}
SetElimantedZeroToken(equation, rows, i);
}
}
DirectedOrderNumber* GaussEleminationWithPivot(DirectedOrderNumber** equation, int rows)
{
DirectedOrderNumber* resultVector;
resultVector = new DirectedOrderNumber[rows];
EleminatePartWithPivot(equation, rows);
resultVector = VectorResult(equation, rows);
return resultVector;
}
void ElemintPartJordan(DirectedOrderNumber** equation, int rows)
{
DirectedOrderNumber *tmp;
DirectedOrderNumber *tmp2;
DirectedOrderNumber *minus;
DirectedOrderNumberArithmetic* operations;
tmp = new DirectedOrderNumber(0.0, 0.0);
tmp2 = new DirectedOrderNumber(0.0, 0.0);
minus = new DirectedOrderNumber(-1.0, -1.0);
operations = new DirectedOrderNumberArithmetic();
for (int i = 0; i < rows; i++)
{ for (int j = 0; j < rows; j++)
{ if (j != i)
{ operations->DivideDirectedOrderNumber(&equation[j][i], &equation[j][j], tmp);
operations->MultipleDirectedOrderNumber(minus,tmp,minus);
for (int k = 0; k < rows + 1; k++)
{
if (equation[i][k].zeroFlag != true)
{
operations->MultipleDirectedOrderNumber(tmp, &equation[i][k],tmp2);
operations->AddDirectedOrderNumber(&equation[j][k], tmp2, &equation[j][k]);
}
}
}
minus->SetValues(-1.0, -1.0);
}
std::cout << "Krok: " << i << std::endl;
SetElimantedZeroToken(equation, rows, i);
}
delete tmp;
delete tmp2;
delete minus;
delete(operations);
}
DirectedOrderNumber* JordanVector(DirectedOrderNumber** equation, int rows)
{
DirectedOrderNumber* resultVector;
DirectedOrderNumberArithmetic operation;
DirectedOrderNumber *tmp;
tmp = new DirectedOrderNumber(0.0, 0.0);
resultVector = new DirectedOrderNumber[rows];
for (int i = 0; i < rows; i++)
{
operation.DivideDirectedOrderNumber(&equation[i][rows], &equation[i][i], tmp);
resultVector[i].SetValues(tmp->infimum, tmp->supremum);
}
return resultVector;
}
DirectedOrderNumber* GaussJordanElemination(DirectedOrderNumber** equation, int rows)
{
DirectedOrderNumber* resultVector;
ElemintPartJordan(equation, rows);
resultVector = JordanVector(equation, rows);
return resultVector;
}
};
class FileHelper
{
public:
double precsiosn;
FileHelper()
{
precsiosn = 0.00000001;
}
FileHelper(int prec)
{
precsiosn = prec;
}
std::string GetPathToSampleFolder()
{
char* buffer;
if ((buffer = getcwd(NULL, 0)) == NULL) {
perror("failed to get current directory\n");
}
else {
std::string pathToCurrentDirectory(buffer);
pathToCurrentDirectory += "\\Sample";
free(buffer);
return pathToCurrentDirectory;
}
return "";
}
bool CheckDirectoryExist()
{
std::string path = GetPathToSampleFolder();
std::ifstream file(path.c_str());
bool isTrue = file.good();
return isTrue;
}
int CreateSampleFolder()
{
std::string pathToFolder = "md " + GetPathToSampleFolder();
int x = system(pathToFolder.c_str());
return x;
}
bool ChcekEquationFolderExisst(std::string folderName)
{
std::string path = GetPathToSampleFolder() + "\\" + folderName;
std::ifstream file(path.c_str());
bool isTrue = file.good();
return isTrue;
}
int CreateEquationFolder(std::string folderName)
{
if (ChcekEquationFolderExisst(folderName))
return 0;
std::string pathToFolder = "md " + GetPathToSampleFolder() + "\\" + folderName;
int x = system(pathToFolder.c_str());
return x;
}
void SaveEquation(DirectedOrderNumber** equation, int rows, std::string fileName, std::string folderName)
{
std::string pathToFile = GetPathToSampleFolder();
std::ofstream myfile;
try {
myfile.open(pathToFile + "\\" + folderName + "\\" + fileName + ".txt");
myfile << rows << "\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows + 1; j++)
{
myfile << "(" << std::fixed << std::setprecision(precsiosn) << (double)equation[i][j].infimum << "," << std::fixed << std::setprecision(precsiosn) << (double)equation[i][j].supremum << ")";
myfile << ";";
}
myfile << "\n";
}
myfile.close();
}
catch (std::ifstream::failure e)
{
printf("Exception");
}
}
void SaveVectorToFile(DirectedOrderNumber* frevaluesVector, std::string fileName, std::string folderName, int rows)
{
std::string pathToFile = GetPathToSampleFolder() + "\\" + folderName + "\\" + fileName + ".txt";
std::ofstream myfile;
try {
myfile.open(pathToFile);
for (int i = 0; i < rows; i++)
{
myfile << "(" << std::fixed << std::setprecision(precsiosn) << frevaluesVector[i].infimum << "," << std::fixed << std::setprecision(precsiosn) << frevaluesVector[i].supremum << ")";
myfile << "\n";
}
myfile.close();
}
catch (std::ifstream::failure e)
{
printf("Exception");
}
}
DirectedOrderNumber* ReadVectorFromFile(std::string fileName, std::string folderName, int rows)
{
std::string pathToFile = GetPathToSampleFolder() + "\\" + folderName + "\\" + fileName + ".txt";
std::ifstream file;
DirectedOrderNumber* vector;
file.open(pathToFile.c_str());
if (!file) {
printf("Cannot read file");
return NULL;
}
else
{
int counter = 0;
std::string line;
vector = new DirectedOrderNumber[rows];
while (std::getline(file, line, '\n'))
{
vector[counter] = GetDirectedOrderNumberFromString(line);
counter++;
}
return vector;
}
return NULL;
}
bool FileExist(std::string filename, std::string folderName)
{
std::string pathToFile = GetPathToSampleFolder() + "\\" + folderName + "\\" + filename + ".txt";
std::ifstream file(pathToFile.c_str());
bool isTrue = file.good();
return isTrue;
}
DirectedOrderNumber** ReadEquation(std::string filename, std::string folderName, int* rowstoSave)
{
std::string pathToFile = GetPathToSampleFolder() + "\\" + folderName + "\\" + filename + ".txt";
std::ifstream file;
DirectedOrderNumber** equation;
file.open(pathToFile.c_str());
if (!file) {
printf("Cannot read file");
equation = CreateMatrix(1);
}
else
{
std::string line;
std::getline(file, line);
equation = CreateMatrix(*rowstoSave);
line = "";
int count = 0;
std::vector<std::string>* splittedStrings;
while (std::getline(file, line, '\n'))
{
splittedStrings = StringRowToVector(line);
SetNumberRowFromText(splittedStrings, equation, *rowstoSave, count);
delete(splittedStrings);
count++;
}
int x = 5;
}
file.close();
return equation;
}
std::vector<std::string>* StringRowToVector(std::string row)
{
std::stringstream ss(row);
std::string item;
std::vector<std::string>* splittedStrings;
splittedStrings = new std::vector<std::string>();
while (std::getline(ss, item, ';'))
{
splittedStrings->push_back(item);
}
return splittedStrings;
}
void SetNumberRowFromText(std::vector<std::string>* row, DirectedOrderNumber** equation, int rows, int counter)
{
DirectedOrderNumber* number;
number = NULL;
std::string numberString;
for (int i = 0; i < rows + 1; i++)
{
number = GetDirectedOrderNumberFromString(row->at(i));
equation[counter][i].infimum = number->infimum;
equation[counter][i].supremum = number->supremum;
}
delete(number);
}
DirectedOrderNumber* GetDirectedOrderNumberFromString(std::string numberInString)
{
DirectedOrderNumber* number;
number = new DirectedOrderNumber(0.0, 0.0);
numberInString.erase(std::remove(numberInString.begin(), numberInString.end(), '('), numberInString.end());
numberInString.erase(std::remove(numberInString.begin(), numberInString.end(), ')'), numberInString.end());
std::stringstream ss(numberInString);
std::string line;
std::vector<std::string>* splittedStrings;
splittedStrings = new std::vector<std::string>();
while (std::getline(ss, line, ','))
{
splittedStrings->push_back(line);
}
number->SetValues(std::stod(splittedStrings->at(0), NULL), std::stod(splittedStrings->at(1), NULL));
return number;
}
DirectedOrderNumber** CreateMatrix(int rows)
{
DirectedOrderNumber** equation;
equation = new DirectedOrderNumber * [rows];
for (int i = 0; i < rows; i++)
{
equation[i] = new DirectedOrderNumber[rows + 1];
}
return equation;
}
};
| true |
c0954fe0dfc374346ba7698b99832a46932cf545 | C++ | VinInn/ctest | /vectorize/extNotAlign.cc | UTF-8 | 1,906 | 2.78125 | 3 | [] | no_license | typedef float __attribute__( ( vector_size( 16 ) ) ) float32x4_t;
typedef float __attribute__( ( vector_size( 16 ) , aligned(4) ) ) float32x4a4_t;
typedef int __attribute__( ( vector_size( 16 ) ) ) int32x4_t;
float32x4_t load(float32x4a4_t x) {
return x;
}
// float v[3*1024];
float32x4_t load(float const * x) {
return *(float32x4a4_t const *)(x);
}
void store(float * x, float32x4_t v) {
*(float32x4a4_t*)(x) = v;
}
void add(float * x, float32x4_t v) {
*(float32x4a4_t*)(x) += v;
}
float32x4_t load3(float const * x) {
return *(float32x4a4_t const *)(x);
}
void store3(float * x, float32x4_t v) {
int32x4_t mask = {0,1,2,7};
decltype(auto) res = *(float32x4a4_t*)(x);
res = __builtin_shuffle(v,res,mask);
}
void add3(float * x, float32x4_t v) {
int32x4_t mask = {0,1,2,7};
decltype(auto) res = *(float32x4a4_t*)(x);
res = __builtin_shuffle(v+res,res,mask);
}
void add11(float * x, float * y, float32x4_t v) {
auto & k1 = *(float32x4a4_t*)(x);
auto & k2 = *(float32x4a4_t*)(y);
k1 +=v;
k2 += k1+v;
}
void add14(float * x, float * y, float32x4_t v) {
decltype(auto) k1 = *(float32x4a4_t*)(x);
decltype(auto) k2 = *(float32x4a4_t*)(y);
k1 +=v;
k2 += k1+v;
}
void add98(float * x, float * y, float32x4_t v) {
float32x4a4_t & k1 = *(float32x4a4_t*)(x);
float32x4a4_t & k2 = *(float32x4a4_t*)(y);
k1 +=v;
k2 += k1+v;
}
int doit() {
float v[3*1025]{1};
float32x4_t v1{1,2,3,4};
float32x4_t v2 = load(v+3);
for (int i=0;i<1024; i+=3)
store(v+i,v1);
for (int i=0;i<1024; i+=3)
add(v+i,v1);
return v[124]+v2[2];
};
int doit3() {
float v[3*1025]{1};
float32x4_t v1{1,2,3,4};
float32x4_t v2 = load3(v+3);
for (int i=0;i<1024; i+=3)
store3(v+i,v1);
for (int i=0;i<1024; i+=3)
add3(v+i,v1);
return v[124]+v2[2];
};
int main() {
return doit()+doit3();
}
| true |
c9765cc034fc8e17845c71b173a9b21ff4ae2f72 | C++ | mbfilho/icpc | /UNICAMP summer school/18.01/key.cpp | UTF-8 | 3,654 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;
#define N 500000
#define M 500000
int resp[ M ], c;
struct No{
int x, y;
int val;
int cont;
int esq, dir;
No(){
x = 8; y = 0; val = -1; cont = -1; esq = 0; dir = 0;
}
void set( int ind ){
val = 0;
cont = 0;
x = ind;
y = rand();
esq = dir = -1;
}
}nos[M];
int n, m;
void ajeitar( int t ){
if( t == -1 ) return;
nos[t].x = 1;
if( nos[t].val == 0 ) nos[t].cont = 1;
else nos[t].cont = 0;
if( nos[t].esq != -1 ){
nos[t].x += nos[ nos[t].esq ].x;
nos[t].cont += nos[ nos[t].esq ].cont;
}
if( nos[t].dir != -1 ){
nos[t].x += nos[ nos[t].dir ].x;
nos[t].cont += nos[ nos[t].dir ].cont;
}
}
void split( int t, int x, int& l, int& r ){
if( t == -1 ){
l = r = -1;
return;
}
int qtd = 1;
if( nos[t].esq != -1 ) qtd += nos[ nos[t].esq ].x;
if( x == qtd ){
l = t;
r = nos[t].dir;
nos[t].dir = -1;
}else if( x < qtd ){
split( nos[t].esq, x, l, nos[t].esq );
r = t;
}else{
split( nos[t].dir, x - qtd, nos[t].dir, r );
l = t;
}
ajeitar(t);
}
int merge( int& l, int& r ){
if( l == -1 ) return r;
if( r == -1 ) return l;
if( nos[l].y > nos[r].y ){
nos[r].esq = merge( l, nos[r].esq );
ajeitar(r);
return r;
}else{
nos[l].dir = merge( nos[l].dir, r );
ajeitar(l);
return l;
}
}
int add( int t, int nw ){
if( t == -1 || nos[t].y > nos[nw].y ){
split( t, nos[nw].x, nos[nw].esq, nos[nw].dir );
ajeitar(nw);
return nw;
}
int qtd = 1;
if( nos[t].esq != -1 ) qtd += nos[ nos[t].esq ].x;
if( nos[nw].x < qtd ){
nos[t].esq = add( nos[t].esq, nw );
}else{
nos[nw].x -= qtd;
nos[t].dir = add( nos[t].dir, nw );
}
ajeitar(t);
return t;
}
bool insert( int t, int x, int val ){
if( t == -1 ) return false;
int qtd = 1;
if( nos[t].esq != -1 ) qtd = 1 + nos[ nos[t].esq ].x;
if( x == qtd ){
if( !nos[t].val ){
--nos[t].cont;
nos[t].val = val;
return true;
}else return false;
}else if( x < qtd ){
if( insert( nos[t].esq, x, val ) ){
ajeitar(t);
return true;
}else return false;
}else{
if( insert( nos[t].dir, x - qtd, val ) ){
ajeitar(t);
return true;
}else return false;
}
}
int remove( int t ){
if( t == -1 ) return t;
int esq = 0, dir = 0;
if( nos[t].esq != -1 ) esq = nos[ nos[t].esq ].cont;
if( nos[t].dir != -1 ) dir = nos[ nos[t].dir ].cont;
if( esq ){
nos[t].esq = remove( nos[t].esq );
}else if( !nos[t].val ){
int tmp = merge( nos[t].esq, nos[t].dir );
ajeitar( tmp );
return tmp;
}else if( dir ){
nos[t].dir = remove( nos[t].dir );
}
ajeitar(t);
return t;
}
void print( int t, bool b = false ){
if( t == -1 ) return;
print( nos[t].esq, b );
resp[c++] = t;
print( nos[t].dir, b );
}
int main(){
srand( time(0) );
#ifndef X
freopen( "key.in", "r", stdin );
freopen( "key.out", "w", stdout );
#endif
scanf( "%d %d", &n, &m );
int root = -1;
int prt = 0;
c = 0;
for( int i = 1; i <= m + n + 7; ++i ){
nos[prt].set(i);
root = add( root, prt );
prt++;
}
for( int i = 1; i <= n; ++i ){
int tmp;
scanf( "%d", &tmp );
if( !insert( root, tmp, i ) ){
int p1 = -1, p2 = -1, p3 = -1;
split( root, tmp, p1, p2 );
split( p1, tmp - 1, p1, p3 );
p2 = remove( p2 );
nos[prt].set(1);
nos[prt].val = i;
root = merge( p1, prt );
p3 = merge( p3, p2 );
root = merge( root, p3 );
++prt;
}
}
print( root );
--c;
while( c >= 0 && nos[ resp[c] ].val == 0 ){
--c;
}
printf( "%d\n", c + 1 );
for( int i = 0; i <= c; ++i ){
printf( "%d ", nos[ resp[i] ].val );
}
printf( "\n" );
}
| true |
b56268ab0e5d7befca6a3eb990b2abf0aa64f386 | C++ | iliayar/ITMO | /Term2/algo/labs/lab1/taskE.cpp | UTF-8 | 2,549 | 2.640625 | 3 | [] | no_license |
// Generated at 2020-02-24 04:17:28.330777
// By iliayar
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <cstdio>
using namespace std;
//##################CODE BEGIN#############
class Matrix {
public:
int a[2][2];
Matrix(int, int, int, int);
Matrix operator*(Matrix m);
};
Matrix::Matrix(int a11, int a12, int a21, int a22) {
this->a[0][0] = a11;
this->a[0][1] = a12;
this->a[1][0] = a21;
this->a[1][1] = a22;
}
int MOD;
Matrix Matrix::operator* (Matrix m) {
Matrix res(0,0,0,0);
res.a[0][0] = (this->a[0][0]*m.a[0][0]%MOD + this->a[0][1]*m.a[1][0]%MOD) % MOD;
res.a[1][0] = (this->a[1][0]*m.a[0][0]%MOD + this->a[1][1]*m.a[1][0]%MOD) % MOD;
res.a[0][1] = (this->a[0][0]*m.a[0][1]%MOD + this->a[0][1]*m.a[1][1]%MOD) % MOD;
res.a[1][1] = (this->a[1][0]*m.a[0][1]%MOD + this->a[1][1]*m.a[1][1]%MOD) % MOD;
return res;
}
Matrix I(1,0,0,1);
vector<Matrix> tree;
void set(int i, Matrix x, int v, int lx, int rx) {
if(rx - lx == 1) {
tree[v] = x;
return;
}
int m = (lx + rx)/2;
if(i < m)
set(i,x,v*2+1, lx, m);
else
set(i,x, v*2 + 2, m, rx);
tree[v] = tree[v*2 + 1]*tree[v*2 + 2];
}
Matrix mult(int l, int r, int v, int lx, int rx) {
if(r <= l) {
return I;
}
if(l == lx && rx == r) {
return tree[v];
}
int m = (lx + rx)/2;
return mult(l,min(r,m),v*2+1, lx,m)*
mult(max(l,m),r,v*2 + 2,m, rx);
}
//entry
void sol() {
FILE* finp = fopen("crypto.in", "r");
FILE* fout = fopen("crypto.out", "w");
int n, m;
// cin >> MOD >> n >> m;
fscanf(finp, "%Ld %Ld %Ld\n", &MOD, &n, &m);
// fprintf(fout, "%d %d %d\n", MOD, n, m);
tree.resize(n*4,I);
for(int i = 0; i < n; ++i) {
int a11, a12, a21, a22;
// cin >> a11 >> a12 >> a21 >> a22;
fscanf(finp ,"%Ld %Ld\n", &a11, &a12);
fscanf(finp ,"%Ld %Ld\n\n", &a21, &a22);
// fprintf(fout, "%d", MOD);
set(i, Matrix(a11,a12, a21, a22), 0, 0, n);
}
for(int i = 0; i < m; ++i) {
int l ,r;
// cin >> l >> r; l--;
fscanf(finp, "%Ld %Ld", &l, &r); l--;
Matrix t = mult(l,r,0,0,n);
// cout << t.a[0][0] << " " << t.a[0][1] << endl;
// cout << t.a[1][0] << " " << t.a[1][1] << endl << endl;
fprintf(fout, "%d %d\n", t.a[0][0], t.a[0][1]);
fprintf(fout, "%d %d\n\n", t.a[1][0], t.a[1][1]);
}
}
//##################CODE END###############
signed main() {
sol();
}
| true |
ab984d50e357abc9511009a1d246923f172301d5 | C++ | DougGregor/swift | /unittests/Basic/TreeScopedHashTableTests.cpp | UTF-8 | 3,180 | 2.828125 | 3 | [
"Apache-2.0",
"Swift-exception"
] | permissive | #include "swift/Basic/TreeScopedHashTable.h"
#include "gtest/gtest.h"
using namespace swift;
TEST(TreeScopedHashTableTest, T1) {
using HashtableTy = TreeScopedHashTable<unsigned, unsigned>;
using ScopeTy = HashtableTy::ScopeTy;
HashtableTy HT;
auto S1 = new ScopeTy(HT, 0);
HT.insertIntoScope(*S1, 1, 1001);
HT.insertIntoScope(*S1, 2, 1002);
auto S2 = new ScopeTy(HT, S1);
HT.insertIntoScope(*S2, 3, 2003);
HT.insertIntoScope(*S2, 4, 2004);
EXPECT_EQ(1001U, HT.lookup(*S1, 1));
EXPECT_EQ(1002U, HT.lookup(*S1, 2));
EXPECT_EQ(0U, HT.lookup(*S1, 3));
EXPECT_EQ(0U, HT.lookup(*S1, 4));
EXPECT_EQ(1001U, HT.lookup(*S2, 1));
EXPECT_EQ(1002U, HT.lookup(*S2, 2));
EXPECT_EQ(2003U, HT.lookup(*S2, 3));
EXPECT_EQ(2004U, HT.lookup(*S2, 4));
delete S2;
delete S1;
}
TEST(TreeScopedHashTableTest, T2) {
using HashtableTy = TreeScopedHashTable<unsigned, unsigned>;
using ScopeTy = HashtableTy::ScopeTy;
HashtableTy HT;
auto S1 = new ScopeTy(HT, 0);
HT.insertIntoScope(*S1, 1, 1001);
HT.insertIntoScope(*S1, 2, 1002);
auto S2 = new ScopeTy(HT, S1);
HT.insertIntoScope(*S2, 3, 2003);
HT.insertIntoScope(*S2, 4, 2004);
auto S3 = new ScopeTy(HT, S1);
HT.insertIntoScope(*S3, 1, 3001);
HT.insertIntoScope(*S3, 4, 3004);
EXPECT_EQ(1001U, HT.lookup(*S1, 1));
EXPECT_EQ(1002U, HT.lookup(*S1, 2));
EXPECT_EQ(0U, HT.lookup(*S1, 3));
EXPECT_EQ(0U, HT.lookup(*S1, 4));
EXPECT_EQ(1001U, HT.lookup(*S2, 1));
EXPECT_EQ(1002U, HT.lookup(*S2, 2));
EXPECT_EQ(2003U, HT.lookup(*S2, 3));
EXPECT_EQ(2004U, HT.lookup(*S2, 4));
EXPECT_EQ(3001U, HT.lookup(*S3, 1));
EXPECT_EQ(1002U, HT.lookup(*S3, 2));
EXPECT_EQ(0U, HT.lookup(*S3, 3));
EXPECT_EQ(3004U, HT.lookup(*S3, 4));
EXPECT_EQ(true, HT.count(*S3, 1));
EXPECT_EQ(true, HT.count(*S3, 2));
EXPECT_EQ(false, HT.count(*S3, 3));
EXPECT_EQ(true, HT.count(*S3, 4));
delete S2;
EXPECT_EQ(1001U, HT.lookup(*S1, 1));
EXPECT_EQ(1002U, HT.lookup(*S1, 2));
EXPECT_EQ(0U, HT.lookup(*S1, 3));
EXPECT_EQ(0U, HT.lookup(*S1, 4));
EXPECT_EQ(3001U, HT.lookup(*S3, 1));
EXPECT_EQ(1002U, HT.lookup(*S3, 2));
EXPECT_EQ(0U, HT.lookup(*S3, 3));
EXPECT_EQ(3004U, HT.lookup(*S3, 4));
delete S3;
EXPECT_EQ(1001U, HT.lookup(*S1, 1));
EXPECT_EQ(1002U, HT.lookup(*S1, 2));
EXPECT_EQ(0U, HT.lookup(*S1, 3));
EXPECT_EQ(0U, HT.lookup(*S1, 4));
delete S1;
}
TEST(TreeScopedHashTableTest, IteratorTest) {
using HashtableTy = TreeScopedHashTable<unsigned, int>;
using ScopeTy = HashtableTy::ScopeTy;
HashtableTy HT;
auto S1 = new ScopeTy(HT, 0);
HT.insertIntoScope(*S1, 1, 1001);
HT.insertIntoScope(*S1, 2, 1002);
auto S2 = new ScopeTy(HT, S1);
HT.insertIntoScope(*S2, 1, 2001);
HT.insertIntoScope(*S2, 4, 2004);
auto S3 = new ScopeTy(HT, S1);
HT.insertIntoScope(*S3, 1, 3001);
HT.insertIntoScope(*S3, 4, 3004);
{
auto I = HT.begin(*S1, 1);
EXPECT_EQ(1001, *I);
I++;
EXPECT_EQ(HT.end(), I);
}
{
auto I = HT.begin(*S3, 1);
EXPECT_EQ(3001, *I);
I++;
EXPECT_EQ(1001, *I);
I++;
EXPECT_EQ(HT.end(), I);
}
delete S3;
delete S2;
delete S1;
}
| true |
4317ad0fd1c485ec2c416aa54c24d3ac5ddb8084 | C++ | Vladyslav13/Qt | /modules/NoteBookGui/src/AdditionalContactInfo.cpp | UTF-8 | 2,835 | 2.734375 | 3 | [] | no_license | #include "pch.h"
#include "AdditionalContactInfo.h"
namespace notebook
{
//
// Definition of the AdditionalContactInfo class.
//
AdditionalContactInfo::AdditionalContactInfo(QWidget *parent)
: QGroupBox{ parent }
, address_{ new QTextEdit }
, birthday_{ new QDateEdit }
, cancelButton_{ new QPushButton{ tr("Cancel") } }
, okButton_{ new QPushButton{ tr("Ok") } }
{
ConfigureView();
connect(okButton_, &QPushButton::clicked, [this]()
{
emit OkButtonClicked();
});
connect(cancelButton_, &QPushButton::clicked, [this]()
{
emit CancelButtonClicked();
});
connect(address_, &QTextEdit::textChanged, this,
&AdditionalContactInfo::OnChangeAddressSlot);
}
void AdditionalContactInfo::OnChangeAddressSlot()
{
QFontMetrics fm{ address_->font() };
if(fm.width(address_->toPlainText()) >= address_->width())
{
address_->setFixedSize(200, fm.height() + 10 +
address_->horizontalScrollBar()->height());
}
else
{
address_->setFixedSize(200, fm.height() + 10);
}
}
void AdditionalContactInfo::ConfigureView()
{
// configuration of text box with address of person.
QLabel* birthdayLbl = new QLabel{ tr("&Birthday.") };
birthdayLbl->setBuddy(birthday_);
birthday_->setFixedSize(200, 25);
birthday_->setLocale(QLocale::English);
birthday_->setDisplayFormat(tr("dd-MMM-yyyy"));
birthday_->setInputMethodHints(Qt::ImhDate);
// configuration of text box with birthday of person.
QLabel* addressLbl = new QLabel{ tr("&Address.") };
addressLbl->setBuddy(address_);
address_->setFixedSize(200, 25);
address_->setLineWrapMode(QTextEdit::NoWrap);
// configuration of button layout.
QHBoxLayout* buttnLay = new QHBoxLayout;
buttnLay->addWidget(okButton_, 0, Qt::AlignRight);
buttnLay->addWidget(cancelButton_, 0, Qt::AlignRight);
// Configuration main layout of widget.
QVBoxLayout* vLay = new QVBoxLayout;
vLay->addStretch(1);
vLay->addWidget(addressLbl, 0, Qt::AlignLeft);
vLay->addWidget(address_);
vLay->addWidget(birthdayLbl, 0, Qt::AlignLeft);
vLay->addWidget(birthday_);
vLay->addLayout(buttnLay);
vLay->setSpacing(10);
// Configuration of widget.
setTitle(tr("Extra information"));
setLayout(vLay);
setAlignment(Qt::AlignCenter | Qt::AlignBottom);
setFixedSize(220, 200);
setEnabled(false);
}
QString AdditionalContactInfo::GetAddress() const
{
return address_->toPlainText();
}
QString AdditionalContactInfo::GetBirthday(const QString& format) const
{
return birthday_->date().toString(format);
}
void AdditionalContactInfo::SetAddress(const QVariant& adr)
{
address_->setText(adr.toString());
}
void AdditionalContactInfo::SetBirthday(const QVariant& brthd)
{
birthday_->setDate(brthd.toDate());
}
void AdditionalContactInfo::SetEnabled(bool flag)
{
setEnabled(flag);
if (!flag)
{
address_->clear();
birthday_->clear();
}
}
} // namespace notebook
| true |
24cf0de7463eb9e3432b8f39903bf90cf12fa6c2 | C++ | mangesh-kurambhatti/CPP | /Cpp-Programms/Date Class/Date.h | UTF-8 | 413 | 3.046875 | 3 | [] | no_license | #ifndef DATE_H
#define DATE_H
class SpecialDate
{
int dd;
int mm;
public:
SpecialDate(int dd,int mm);
};
class Date
{
int dd,mm,yy;
public:
Date();
Date(int dd);
Date(int dd,int mm,int yy);
void SetDD(const int dd);
void SetMM(const int mm);
void SetYY(const int yy);
int GetDD() const;
int GetMM() const;
int GetYY() const;
operator int();
operator SpecialDate();
};
#endif
| true |
9aed3c8af42dc9dc07516b040adb0fa5fa9ef2f7 | C++ | jsdjayanga/mcp | /MatrixMultiplication/MatrixMultiplication.cpp | UTF-8 | 8,649 | 3.046875 | 3 | [] | no_license | /*
* File: MatrixMultiplication.cpp
* Author: jayangad
*
* Created on July 15, 2013, 1:57 PM
*/
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <CommandLineParser.h>
#include <Utils.h>
#include <set>
#include <vector>
#include <sstream>
using namespace std;
double** source_matrix_1 = NULL;
double** source_matrix_2 = NULL;
double** destination_matrix = NULL;
set<double> execution_times;
void InitMatrices(int32_t count)
{
srand(time(NULL));
source_matrix_1 = new double*[count];
source_matrix_2 = new double*[count];
destination_matrix = new double*[count];
for (int32_t j = 0; j < count; j++)
{
destination_matrix[j] = new double[count];
source_matrix_1[j] = new double[count];
source_matrix_2[j] = new double[count];
for (int32_t k = 0; k < count; k++)
{
destination_matrix[j][k] = 0;
source_matrix_1[j][k] = (rand() % 2) + 1;
source_matrix_2[j][k] = (rand() % 2) + 1;
}
}
}
void MultiplyMatrices(int32_t starting_row, int32_t ending_row, int32_t length_of_side)
{
for (int32_t i = starting_row; i < ending_row; i++)
{
for (int32_t j = 0; j < length_of_side; j++)
{
for (int32_t k = 0; k < length_of_side; k++)
{
destination_matrix[i][j] = destination_matrix[i][j] + (source_matrix_1[i][k] * source_matrix_2[k][j]);
}
}
}
}
void Print(double** matrix, int32_t count)
{
for (int32_t row = 0; row < count; row++)
{
for (int32_t column = 0; column < count; column++)
{
cout << matrix[row][column] << " ";
}
cout << endl;
}
}
void MatrixMultiplicationSequential(int32_t count)
{
struct timespec t0, t1;
long sec, nsec;
Utils::GetTime(t0);
MultiplyMatrices(0, count, count);
Utils::GetTime(t1);
double compute_time = Utils::elapsed_time_msec(&t0, &t1, &sec, &nsec);
cout << "Sequential Compute Time=" << compute_time << endl;
execution_times.insert(compute_time);
//Print(source_matrix_1, count);
//Print(source_matrix_2, count);
//Print(destination_matrix, count);
}
struct PositionDetails
{
int32_t _start_row;
int32_t _end_row;
int32_t _count;
PositionDetails() :
_start_row(0),
_end_row(0),
_count(0)
{
}
};
void *MatrixMultiplicationParallel(void* value)
{
PositionDetails* pd = (PositionDetails*) value;
MultiplyMatrices(pd->_start_row, pd->_end_row, pd->_count);
}
void MatrixMultiplicationParallel(int32_t count)
{
int32_t threads = atoi(CommandLineParser::GetInstance().GetParameterValue("--threads").c_str());
PositionDetails* pds = new PositionDetails[threads];
int32_t thread_working_set_size = count / threads;
int32_t excess_count = count % threads;
int32_t row = 0;
for (int32_t index = 0; index < threads; index++)
{
pds[index]._start_row = row;
pds[index]._count = count;
if (index == 0 && excess_count > 0)
{
pds[index]._end_row = row + thread_working_set_size + excess_count;
row = row + thread_working_set_size + excess_count;
}
else
{
pds[index]._end_row = row + thread_working_set_size;
row = row + thread_working_set_size;
}
}
struct timespec t0, t1;
long sec, nsec;
pthread_t* threads_ids = new pthread_t[threads];
Utils::GetTime(t0);
for (int32_t index = 0; index < threads; index++)
{
int32_t ret_val = pthread_create(&threads_ids[index], NULL, MatrixMultiplicationParallel, (void *)(&pds[index]));
if (ret_val != 0)
{
cout << "Error creating thread. [ThreadID=" << index + 1 << "]" << endl;
}
}
for (int32_t index = 0; index < threads; index++)
{
pthread_join(threads_ids[index], NULL);
}
Utils::GetTime(t1);
double compute_time = Utils::elapsed_time_msec(&t0, &t1, &sec, &nsec);
cout << "Parallel Compute Time=" << compute_time << endl;
execution_times.insert(compute_time);
//Print(source_matrix_1, count);
//Print(source_matrix_2, count);
//Print(destination_matrix, count);
}
void Validate(int32_t count)
{
double** temp = new double*[count];
MatrixMultiplicationSequential(count);
for (int row = 0; row < count; row++)
{
temp[row] = new double[count];
for (int column = 0; column < count; column++)
{
temp[row][column] = destination_matrix[row][column];
destination_matrix[row][column] = 0;
}
}
MatrixMultiplicationParallel(count);
for (int row = 0; row < count; row++)
{
for (int column = 0; column < count; column++)
{
if (Utils::Compare(destination_matrix[row][column], temp[row][column]) == false )
{
cout << "Mismatch @ Row :" << row << ", Column=" << column
<< " [Expected=" << temp[row][column]
<< ", Received=" << destination_matrix[row][column] << "]" << endl;
return;
}
}
}
cout << "Validation complete." << endl;
Print(temp, count);
Print(destination_matrix, count);
}
void AnalyzePerformance(int32_t count)
{
vector<int32_t> counts;
counts.push_back(600);
counts.push_back(1200);
counts.push_back(1800);
vector<int32_t> thread_counts;
thread_counts.push_back(1);
thread_counts.push_back(2);
thread_counts.push_back(4);
thread_counts.push_back(8);
thread_counts.push_back(16);
thread_counts.push_back(32);
for (vector<int32_t>::iterator ite = counts.begin(); ite != counts.end(); ite++)
{
int32_t count = *ite;
execution_times.clear();
int32_t iterations = atoi(CommandLineParser::GetInstance().GetParameterValue("--iterations").c_str());
for (int iteration = 0; iteration < iterations; iteration++)
{
MatrixMultiplicationSequential(count);
}
double sequntial_time = Utils::AverageValues(execution_times);
vector<double> parallel_times;
parallel_times.clear();
for (vector<int32_t>::iterator th_ite = thread_counts.begin(); th_ite != thread_counts.end(); th_ite++)
{
int32_t thread_count = *th_ite;
stringstream ss;
ss << thread_count;
CommandLineParser::GetInstance().SetParameterValue("--threads", ss.str());
execution_times.clear();
for (int iteration = 0; iteration < iterations; iteration++)
{
MatrixMultiplicationParallel(count);
}
parallel_times.push_back(Utils::AverageValues(execution_times));
}
execution_times.clear();
cout << "=====================================================" << endl;
cout << "MatrixMultiplication" << endl;
cout << "Count : " << count << endl;
cout << "Sequential Average Time: " << sequntial_time << endl;
for (int32_t index = 0; index < parallel_times.size(); index++)
{
cout << "Parallel Average Time ("<< thread_counts[index] << ") : " << parallel_times[index] << endl;
}
cout << "=====================================================" << endl;
}
}
/*
*
*/
int main(int argc, char** argv)
{
CommandLineParser::GetInstance().Initialize(argc, argv);
string mode = CommandLineParser::GetInstance().GetParameterValue("--mode");
int32_t count = atoi(CommandLineParser::GetInstance().GetParameterValue("--count").c_str());
execution_times.clear();
struct timespec t0, t1;
long sec, nsec;
Utils::GetTime(t0);
InitMatrices(count);
Utils::GetTime(t1);
double init_time = Utils::elapsed_time_msec(&t0, &t1, &sec, &nsec);
cout << "InitTime=" << init_time << endl;
if (mode == "s")
{
MatrixMultiplicationSequential(count);
}
else if (mode == "p")
{
MatrixMultiplicationParallel(count);
}
else if (mode == "v")
{
Validate(count);
}
else if (mode == "a")
{
AnalyzePerformance(count);
}
else
{
cout << "Unknown mode [Mode=" << mode << "]" << endl;
return -1;
}
return 0;
}
| true |
74f61aeafa8d328d20b114a243b920bccbf2ef90 | C++ | shreya1901/Cpp_Program | /smallest_divisible.cpp | UTF-8 | 606 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
//Function returns the lcm of first n numbers
long long lcm(long long n)
{
long long ans = 1;
for (long long i = 1; i <= n; i++)
ans = (ans * i)/(__gcd(ans, i));
return ans;
}
//Driver program to test the above function
int main()
{
int ch;
do
{
long long n = 0;
cout<<"Enter max number up to which any number should be divisible equally : ";
cin>>n;
cout << lcm(n);
cout<<"\n\nEnter 1 to continue and 0 to exit\nEnter your choice :";
cin>>ch;
}
while(ch==1);
return 0;
}
| true |
4216b532c016a981bbb16a7a4cd973990b702cf6 | C++ | zpervan/NeuralNetworks | /Libraries/Base/neural_network_data.h | UTF-8 | 720 | 2.578125 | 3 | [] | no_license | #ifndef NEURALNETWORK_NEURAL_NETWORK_ARCHITECTURE_DATA_H
#define NEURALNETWORK_NEURAL_NETWORK_ARCHITECTURE_DATA_H
#include "../activation_functions.h"
#include <cstdint>
using Id = std::uint64_t;
using Value = double;
using Weight = double;
/// @TODO: Add multiple levels of hidden layer
struct NeuralNetworkArchitecture {
std::size_t input_layer_size;
std::size_t single_hidden_layer_size;
std::size_t output_layer_layer_size;
ActivationFunctionType activation_function_type;
};
/// @brief Defines one neuron in the network
struct Neuron {
const Id id{0};
Value value{0.0};
Value activation_func_result{0.0};
Value output_target{0.0};
};
#endif // NEURALNETWORK_NEURAL_NETWORK_ARCHITECTURE_DATA_H
| true |
5b7ea7b28153bdf343970af7c6edba2c42c1ef8f | C++ | GayathriSuresh69999/CS141-LAB5.5 | /lab5.5_q8.cpp | UTF-8 | 292 | 3.40625 | 3 | [] | no_license | // First include the libraray and the main function
#include<iostream>
using namespace std;
int main()
{
int i=1,j;
// Do the following five times
while(i<=5)
{
// Print stars in the increasing order
for (j=0;j<i;j++)
{
cout << "*";
}
// Go to the next line
cout << endl;
i++;
}
return 3;
}
| true |
a31a8c4caa2a98f567e882c56fc9ab2c13020b0d | C++ | ismailvohra/raytracer | /raytracer/samplers/RegularBox.cpp | UTF-8 | 1,425 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "RegularBox.hpp"
#include "../cameras/Camera.hpp"
#include "../utilities/Ray.hpp"
#include "../world/ViewPlane.hpp"
RegularBox::RegularBox(Camera* c_ptr, ViewPlane* v_ptr, size_t degree)
: Sampler(c_ptr, v_ptr), degree{degree}, weight{1.0 / degree / degree} {}
RegularBox* RegularBox::clone() const
{
return new RegularBox(*this);
}
Ray* RegularBox::get_rays(size_t px, size_t py) const
{
/*
Gives the rays out of the given pixel coordinates whose weights add up to 1
@param [size_t] px : Horizontal pixel coordinate
@param [size_t] py : Vertical pixel coordinate
@return [Ray*] : Pointer to the array of rays
*/
Ray* rays = new Ray[this->num_rays()];
for (int y = 0; y < static_cast<int>(this->degree); ++y)
{
for (int x = 0; x < static_cast<int>(this->degree); ++x)
{
double xPrime = (-static_cast<int>(this->degree) + 2 * x + 1) * this->weight;
double yPrime = (-static_cast<int>(this->degree) + 2 * y + 1) * this->weight;
Point3D origin = this->viewplane_ptr->getPixelPoint(px + xPrime, py + yPrime);
rays[y * this->degree + x] = Ray(origin, this->camera_ptr->get_direction(origin), weight);
}
}
return rays;
}
size_t RegularBox::num_rays() const
{
/*
Gives the number of rays per pixel
@return [size_t] : this->degree^2
*/
return this->degree * this->degree;
} | true |
c2b2a6194b14a6b728a5c026c5d953411a89908a | C++ | 100sarthak100/DataStructures-Algorithms | /Code/Trees/BSTtreefromPreOrder.cpp | UTF-8 | 1,063 | 3.390625 | 3 | [] | no_license | // Input: [8,5,1,7,10,12]
// Output: [8,5,10,1,7,null,12] ->inorder return
class Solution {
public:
TreeNode* newNode(int data)
{
TreeNode* newnode = new TreeNode;
newnode->val = data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
stack<TreeNode*> s;
TreeNode* head = newNode(preorder[0]);
s.push(head);
TreeNode* temp;
for(int i = 1;i<preorder.size();i++)
{
temp = NULL;
while(!s.empty() && preorder[i] > s.top()->val)
{
temp = s.top();
s.pop();
}
if(temp != NULL)
{
temp->right = newNode(preorder[i]);
s.push(temp->right);
}
else
{
temp = s.top();
temp->left = newNode(preorder[i]);
s.push(temp->left);
}
}
return head;
}
}; | true |
4f417499dd03b09a51707e1d5b9479e14f6ccf24 | C++ | George-Tech/cpp_stl | /c_map.cpp | GB18030 | 3,905 | 3.84375 | 4 | [] | no_license | #include "cpp_base_head.h"
/*
map ǹһ֡ڹУλȡںļֵ
ǻ(int string ...)Ҳ͡
*/
//------
/*
map 4 ֣ÿһֶģ嶨ġ
͵ map ĶǼֵ͵Ԫء
map Ԫ pair<const KT> ͵Ķֶװһ T ͵Ķһ K ͵ļ
pair Ԫеļ constΪļԪص˳
ÿ map ģ嶼вͬԣ
1.map<KT> pair<const KT> ͵Ԫء
pair<const K,T> װһԼ K T
ÿΨһģԲظļԱظĶֻҪǵļͬ
map еԪضģԪڵ˳ͨȽϼȷġ
Ĭʹ less<K> Ƚϡ
2.multimap<KT> map<KT> ƣҲԪ
ļǿɱȽϵģԪص˳ͨȽϼȷġ
map<KT> ͬǣmultimap<KT> ʹظļ
ˣһ multimap Աֵͬ <const K,T> Ԫء
3.unordered_map<KT> pair< const KT>Ԫص˳ֱɼֵȷģɼֵĹϣֵġ
ϣֵһϣĹɵºһ㡣unordered_map<KT>ظļ
4.unordered_multimap<K,T> ҲֵͨɵĹϣֵȷλãظļ
*/
static void map_print(map<int,string> readlog)
{
for (auto iter = readlog.begin(); iter != readlog.end(); iter++) {
cout << "(" << iter->first << ", " << iter->second << ") ";
}
cout << endl;
}
void init_c_map()
{
map<int, string> nickname0;//int Ǽͣ stringǶ
//map <K,T>УÿԪضͬ·װ˶pair<const K, T>
map<int, string> nickname1{ { 5, "five" }, { 2, "two" }, { 1, "one" } };
map<int, string> nickname2{ make_pair(4, "four"), make_pair(0, "zero") };
map<int, string> nickname3{ nickname2 };
map<int, string> nickname4{ ++nickname3.begin(), nickname3.end() };
cout << "nickname0 :" << endl;
map_print(nickname0);
cout << "nickname1 :" << endl;
map_print(nickname1);
cout << "nickname2 :" << endl;
map_print(nickname2);
cout << "nickname3 :" << endl;
map_print(nickname3);
cout << "nickname4 :" << endl;
map_print(nickname4);
}
void insert_c_map()
{
map<int, string> nickname{ { 5, "five" }, { 2, "two" }, { 1, "one" } };
pair<int, string> tmp = make_pair(3, "three");
pair<map<int, string>::iterator, bool> ret = nickname.insert(tmp);//һͲż pair
//д auto = nickname.insert(make_pair(3, "three")); Ҳok
cout << "insert pair : " << ret.first->first << ", " << ret.first->second << endl;
cout << "insert success : " << ret.second << endl;
//ļ Ӧ 洢ֵ
ret.first->second = "threeee";
cout << "nickname :" << endl;
map_print(nickname);
}
void visit_c_map()
{
//iter static void map_print(map<int,string> readlog)
//.at() []
map<int, string> nickname{ { 5, "five" }, { 2, "two" }, { 1, "one" } };
cout << ".at(5) = " << nickname.at(5) << endl;
cout << "[5] = " << nickname[5] << endl;
auto itr = nickname.find(5);
cout << ".find(5).second = " << itr->second << endl;
nickname.erase(2);
map_print(nickname);
}
void opt_c_pair()
{
pair<int, string> my_pair{1,"one"};
auto your_pair = make_pair(2, "two");
cout << my_pair.first << ", " << my_pair.second << endl;
cout << your_pair.first << ", " << your_pair.second << endl;
} | true |
772778bce5ecd52cf05824844bd63d632c565cd2 | C++ | iGNSS/ALT-F4 | /software/src/reference/frame.cpp | UTF-8 | 19,516 | 3.046875 | 3 | [] | no_license | #include <opencv2/core.hpp>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <stack>
#include "global.hpp"
#include "frame.hpp"
#include "blob.hpp"
/**********************************************************************************/
/**** Constructors ****/
/**********************************************************************************/
Frame::Frame()
{
init(std::vector< unsigned char >(), 0, 0, 0, 0);
}
Frame::Frame(std::vector< unsigned char > values, unsigned int width, unsigned int height,
unsigned int channels)
{
init(values, width, height, channels, 1);
}
/**********************************************************************************/
/**** Methods ****/
/**********************************************************************************/
void Frame::init(std::vector< unsigned char > values, unsigned int width, unsigned int height,
unsigned int channels, unsigned char initialized)
{
this->values = values;
this->width = width;
this->height = height;
this->cols = width;
this->rows = height;
this->channels = channels;
this->initialized = initialized; // Verify that we are indeed initialized
if (this->initialized)
convertValues();
}
void Frame::convertValues()
{
this->pixels.resize(this->rows);
for (unsigned int row = 0; row < this->rows; row++)
{
this->pixels[row].resize(this->cols);
for (unsigned int col = 0; col < this->cols; col++)
{
unsigned char b = this->values[(channels * cols) * row + (col * channels) + 0];
unsigned char g = this->values[(channels * cols) * row + (col * channels) + 1];
unsigned char r = this->values[(channels * cols) * row + (col * channels) + 2];
this->pixels[row][col] = Pixel(row, col, b, g, r);
}
}
}
void Frame::inRange(unsigned char b_l, unsigned char b_h, // low / high blue
unsigned char g_l, unsigned char g_h, // low / high green
unsigned char r_l, unsigned char r_h, // low / high red
unsigned char type = 0)
{
// NOTE: If this is bottleneck, combine it with the 'convertValues()' function.
// this is separated for readability
std::vector< std::vector< unsigned char > > *matrix;
switch (type)
{
case 0: matrix = &binary_matrix_red;
break;
case 1: matrix = &binary_matrix_green;
break;
default: break;
}
(*matrix).resize(this->rows);
for (int row = 0; row < this->rows; row++)
{
(*matrix)[row].resize(this->cols);
for (int col = 0; col < this->cols; col++)
{
unsigned char b = this->values[(channels * cols) * row + (col * channels) + 0];
unsigned char g = this->values[(channels * cols) * row + (col * channels) + 1];
unsigned char r = this->values[(channels * cols) * row + (col * channels) + 2];
(*matrix)[row][col] = 0; // Start out as 0
if (this->initialized) // If this frame is initialized
{
if ((b < b_l) || (b > b_h)) // If out of bounds of blue
continue; // Skip
if ((g < g_l) || (g > g_h)) // If out of bounds of green
continue; // Skip
if ((r < r_l) || (r > r_h)) // If out of bounds of red
continue; // Skip
(*matrix)[row][col] = 1; // Otherwise success!
}
else
{
(*matrix)[row][col] = 0;
}
}
}
}
void Frame::findBlobs(unsigned char type = 0)
{
// "type":
// 0 -> binary_matrix_red
// 1 -> binary_matrix_green
// "edited_matrix":
// 0 -> nothing (skip it)
// 1 -> juicy_pixel (blob it)
// 2 -> eaten_pixel (dont blob it)
std::vector< std::vector< unsigned char > > *matrix;
std::vector< Blob > *blobs;
switch (type)
{
case 0: matrix = &binary_matrix_red;
blobs = &blobs_red;
break;
case 1: matrix = &binary_matrix_green;
blobs = &blobs_green;
break;
default: break;
}
std::vector< std::vector < unsigned char > > edited_matrix( (*matrix) );
std::stack < Pixel > blob_stack;
unsigned int blob_count = 0;
for (int row = 0; row < this->rows; row++)
{
for (int col = 0; col < this->cols; col++)
{
if (edited_matrix[row][col] == 1)
{
std::vector< Pixel > blob_pixels;
std::vector< Pixel > edge_pixels;
std::vector< Pixel > core_pixels;
// BLOB IT!
blob_stack.push(this->pixels[row][col]); // start the blob stack
blob_pixels.push_back(this->pixels[row][col]); // keep track of pixels in blob
edited_matrix[row][col] = 2; // eat the pixel
unsigned int blob_min_row = row; // keep track of boundaries of blob
unsigned int blob_min_col = col; // keep track of boundaries of blob
unsigned int blob_max_row = row; // keep track of boundaries of blob
unsigned int blob_max_col = col; // keep track of boundaries of blob
while (!blob_stack.empty()) // while there's still pixels to eat...
{
// Grab next pixel
Pixel next_pixel = blob_stack.top();
int p_row = next_pixel.getRow();
int p_col = next_pixel.getCol();
blob_stack.pop(); // swallow pixel
// Check all 8 neighbors
unsigned int neighbor_count = 0;
for (int ro = -MAX_MINESWEEP_OFFSET; ro <= MAX_MINESWEEP_OFFSET; ro++) // row offset
{
for (int co = -MAX_MINESWEEP_OFFSET; co <= MAX_MINESWEEP_OFFSET; co++) // col offset
{
if ( !( ro == 0 && co == 0 ) && // if not in center
( p_row + ro < MAX_ROW ) &&
( p_row + ro >= MIN_ROW ) &&
( p_col + co < MAX_COL ) &&
( p_col + co >= MIN_COL ) )
{
if (edited_matrix[p_row + ro][p_col + co] == 1)
{
blob_stack.push(this->pixels[p_row + ro][p_col + co]);
blob_pixels.push_back(this->pixels[p_row + ro][p_col + co]);
edited_matrix[p_row + ro][p_col + co] = 2;
if ( p_row + ro > blob_max_row )
blob_max_row = p_row + ro;
if ( p_row + ro < blob_min_row )
blob_min_row = p_row + ro;
if ( p_col + co > blob_max_col )
blob_max_col = p_col + co;
if ( p_col + co < blob_min_col )
blob_min_col = p_col + co;
}
if (edited_matrix[p_row + ro][p_col + co] != 0)
{
if ((std::abs(ro) <= 1) && (std::abs(co) <= 1)) // make sure they're IMMEDIATE neighbors (Max of 8)
{
neighbor_count++;
}
}
}
}
}
if ( neighbor_count < NEIGHBOR_COUNT )
{
edge_pixels.push_back(this->pixels[p_row][p_col]); // start the blob stack
}
}
// Get core pixels (all pixels in blob but not in edges)
for (int i = 0; i < blob_pixels.size(); i++)
{
// If pixel is in blob, but NOT in edges then ...
if (std::find(edge_pixels.begin(), edge_pixels.end(), blob_pixels[i]) == edge_pixels.end())
{
core_pixels.push_back(blob_pixels[i]);
}
}
Blob new_blob = Blob(blob_pixels, edge_pixels, core_pixels, blob_min_row, blob_min_col, blob_max_row, blob_max_col);
(*blobs).push_back(new_blob);
blob_count++;
}
}
}
}
Blob Frame::bestBlob(const unsigned int filters,
const unsigned char bgr_blob[3], const unsigned char bgr_edge[3], const unsigned char bgr_core[3],
unsigned char type = 0)
{
/* filters:
* bit 0 = Blob Blue: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 1 = Blob Green: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 2 = Blob Red: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 3 = Edge Blue: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 4 = Edge Green: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 5 = Edge Red: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 6 = Core Blue: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 7 = Core Green: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 8 = Core Red: Score based on closest bgr value of ONLY edge pixels (targetted at 'laser iris effect')
* bit 9 = Size: Score based on amount of pixels
*/
std::vector< Blob > *blobs;
switch (type)
{
case 0: blobs = &blobs_red;
break;
case 1: blobs = &blobs_green;
break;
default: break;
}
if ((*blobs).size() == 0)
{
std::cout << "*** Warning: No blobs at all. Returning empty blob (frame.cpp -> bestBlob())\n";
return Blob();
}
// Filter extraction
bool blob_filter_blue = filters & (1 << 0);
bool blob_filter_green = filters & (1 << 1);
bool blob_filter_red = filters & (1 << 2);
bool edge_filter_blue = filters & (1 << 3);
bool edge_filter_green = filters & (1 << 4);
bool edge_filter_red = filters & (1 << 5);
bool core_filter_blue = filters & (1 << 6);
bool core_filter_green = filters & (1 << 7);
bool core_filter_red = filters & (1 << 8);
bool size_filter = filters & (1 << 9);
std::vector< int > scores((*blobs).size(), 0);
for (int i = 0; i < (*blobs).size(); i++)
{
std::vector< Pixel > blob_pixels = (*blobs)[i].getBlobPixels();
std::vector< Pixel > edge_pixels = (*blobs)[i].getEdgePixels();
std::vector< Pixel > core_pixels = (*blobs)[i].getCorePixels();
cv::Scalar bgr_blob_avg = {0, 0, 0};
cv::Scalar bgr_edge_avg = {0, 0, 0};
cv::Scalar bgr_core_avg = {0, 0, 0};
cv::Scalar bgr_blob_diffs = {0, 0, 0};
cv::Scalar bgr_edge_diffs = {0, 0, 0};
cv::Scalar bgr_core_diffs = {0, 0, 0};
if ((blob_filter_blue || blob_filter_green || blob_filter_red) && blob_pixels.size() > 0)
{
unsigned int bgr_blob_sums[3] = {0, 0, 0};
for (int pi = 0; pi < blob_pixels.size(); pi++) // pixel index
{
for (int ch = 0; ch < this->channels; ch++)
{
bgr_blob_sums[ch] += blob_pixels[pi][ch];
}
}
for (int ch = 0; ch < this->channels; ch++)
{
bgr_blob_avg[ch] = bgr_blob_sums[ch] / blob_pixels.size();
bgr_blob_diffs[ch] = std::abs((int)(bgr_blob_avg[ch]) - (int)(bgr_blob[ch]));
}
(*blobs)[i].setAverageBGR(bgr_blob_avg, 0);
if (blob_filter_blue)
{
scores[i] += (255 - bgr_blob_diffs[0]) * BLOB_BLUE_WEIGHT;
}
if (blob_filter_green)
{
scores[i] += (255 - bgr_blob_diffs[1]) * BLOB_GREEN_WEIGHT;
}
if (blob_filter_red)
{
scores[i] += (255 - bgr_blob_diffs[2]) * BLOB_RED_WEIGHT;
}
}
if ((edge_filter_blue || edge_filter_green || edge_filter_red) && edge_pixels.size() > 0)
{
unsigned int bgr_edge_sums[3] = {0, 0, 0};
for (int pi = 0; pi < edge_pixels.size(); pi++) // pixel index
{
for (int ch = 0; ch < this->channels; ch++)
{
bgr_edge_sums[ch] += edge_pixels[pi][ch];
}
}
for (int ch = 0; ch < this->channels; ch++)
{
bgr_edge_avg[ch] = bgr_edge_sums[ch] / edge_pixels.size();
bgr_edge_diffs[ch] = std::abs((int)(bgr_edge_avg[ch]) - (int)(bgr_edge[ch]));
}
(*blobs)[i].setAverageBGR(bgr_edge_avg, 1);
if (edge_filter_blue)
{
scores[i] += (255 - bgr_edge_diffs[0]) * EDGE_BLUE_WEIGHT;
}
if (edge_filter_green)
{
scores[i] += (255 - bgr_edge_diffs[1]) * EDGE_GREEN_WEIGHT;
}
if (edge_filter_red)
{
scores[i] += (255 - bgr_edge_diffs[2]) * EDGE_RED_WEIGHT;
}
}
if ((core_filter_blue || core_filter_green || core_filter_red) && core_pixels.size() > 0)
{
unsigned int bgr_core_sums[3] = {0, 0, 0};
for (int pi = 0; pi < core_pixels.size(); pi++) // pixel index
{
for (int ch = 0; ch < this->channels; ch++)
{
bgr_core_sums[ch] += core_pixels[pi][ch];
}
}
for (int ch = 0; ch < this->channels; ch++)
{
bgr_core_avg[ch] = bgr_core_sums[ch] / core_pixels.size();
bgr_core_diffs[ch] = std::abs((int)(bgr_core_avg[ch]) - (int)(bgr_core[ch]));
}
(*blobs)[i].setAverageBGR(bgr_core_avg, 2);
if (core_filter_blue)
{
scores[i] += (255 - bgr_core_diffs[0]) * CORE_BLUE_WEIGHT;
}
if (core_filter_green)
{
scores[i] += (255 - bgr_core_diffs[1]) * CORE_GREEN_WEIGHT;
}
if (core_filter_red)
{
scores[i] += (255 - bgr_core_diffs[2]) * CORE_RED_WEIGHT;
}
}
if (size_filter)
{
scores[i] += (SIZE_IDEAL - blob_pixels.size()) * -SIZE_WEIGHT;
}
}
int best_score = 0;
Blob best_blob;
for (int i = 0; i < (*blobs).size(); i++)
{
(*blobs)[i].setScore(scores[i]);
if (scores[i] > best_score && scores[i] >= SCORE_CUTOFF)
{
best_score = scores[i];
best_blob = (*blobs)[i];
}
}
// if (best_blob.isInitialized())
// std::cout << "Best score: " << best_score << "\n";
return best_blob;
}
std::vector< unsigned char >& Frame::getValues()
{
// Don't return garbage if not initialized
if (this->initialized == 0)
{
std::cout << "*** Warning: trying to return uninitialized 'values' 1D array (frame.cpp -> getValues())\n";
}
return values;
}
std::vector< std::vector< Pixel > >& Frame::getPixels()
{
// Don't return garbage if not initialized
if (this->initialized == 0)
std::cout << "*** Warning: trying to return uninitialized 'pixels' 2D array (frame.cpp -> getPixels())\n";
return pixels;
}
cv::Mat& Frame::getMat(int channels = 3, int type = 0)
{
/*! TODO: Generalize this (clean up)
* \todo Generalize this (clean up)
*/
// Channels: However many channels you want
// Type: 0 = this->pixels
// Type: 1 = this->binary_matrix
// Don't return garbage if not initialized
if (this->initialized == 0)
std::cout << "*** Warning: trying to return an image of uninitialized frame (frame.cpp -> getMat())\n";
else if (this->rows * this->cols * this->channels != MAX_COL * MAX_ROW * this->channels)
std::cout << "*** Warning: Camera has Aspect Ratio " << this->cols << "x" << this-rows << " (expecting " << MAX_COL << "x" << MAX_ROW << ") (Frame -> getMat())\n";
if (type == 0)
{
for (int row = 0; row < this->rows; row++)
{
for (int col = 0; col < this->cols; col++)
{
for (int ch = 0; ch < this->channels; ch++)
{
unsigned long index = (this->channels * this->cols) * row + (col * this->channels) + ch;
if (this->initialized)
pixels1D[index] = this->pixels[row][col][ch];
else
pixels1D[index] = 0;
}
}
}
output_frame = cv::Mat(MAX_ROW, MAX_COL, CV_8UC3, pixels1D);
}
else if (type == 1 || type == 2)
{
for (int row = 0; row < this->rows; row++)
{
for (int col = 0; col < this->cols; col++)
{
unsigned long index = this->cols * row + col;
if (this->initialized)
{
if (type == 1)
binary1D[index] = this->binary_matrix_red[row][col]*255;
if (type == 2)
binary1D[index] = this->binary_matrix_green[row][col]*255;
}
else
{
binary1D[index] = 0;
}
}
}
output_frame = cv::Mat(MAX_ROW, MAX_COL, CV_8UC1, binary1D);
}
else
{
std::cout << "*** Warning: Invalid type (frame.cpp -> getMat())\n";
}
return output_frame;
}
unsigned char Frame::isInitialized()
{
return this->initialized;
}
std::vector< Blob > Frame::getBlobs(unsigned char type = 0)
{
switch (type)
{
case 0: return (this->blobs_red);
case 1: return (this->blobs_green);
default: std::cout << "*** Warning: invalid type! (frame.cpp -> getBlobs(type))\n";
return (std::vector< Blob >());
}
}
bool Frame::hasBlobs(unsigned char type = 0)
{
switch (type)
{
case 0: return (this->blobs_red.size() > 0);
case 1: return (this->blobs_green.size() > 0);
default: std::cout << "*** Warning: invalid type! (frame.cpp -> hasBlobs(type))\n";
return (false);
}
}
| true |
92bb606ffdae91f26460726080be1cbb270b562d | C++ | aautushka/measure | /tests/metric_trie_tests.cpp | UTF-8 | 5,923 | 2.734375 | 3 | [
"Unlicense"
] | permissive | /*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#include <gtest/gtest.h>
#include "metric.h"
struct metric_trie_test : ::testing::Test
{
using trie_t = metric::trie<int, int>;
trie_t trie;
trie_t lhs;
trie_t rhs;
};
TEST_F(metric_trie_test, adds_node)
{
trie.down(11) = 123;
EXPECT_EQ(123, trie.get());
}
TEST_F(metric_trie_test, adds_second_node)
{
trie.down(11) = 123;
trie.down(11) = 456;
EXPECT_EQ(456, trie.get());
}
TEST_F(metric_trie_test, goes_one_node_up)
{
trie.down(11) = 123;
trie.down(22) = 456;
EXPECT_EQ(456, trie.up());
EXPECT_EQ(123, trie.get());
}
TEST_F(metric_trie_test, builds_stack)
{
trie.down(1) = 1;
trie.down(2) = 2;
trie.down(3) = 3;
EXPECT_EQ(1, trie.at({1}));
EXPECT_EQ(2, trie.at({1, 2}));
EXPECT_EQ(3, trie.at({1, 2, 3}));
}
TEST_F(metric_trie_test, never_clears_data)
{
trie.down(1) = 1;
trie.down(2) = 2;
trie.down(3) = 3;
trie.up();
trie.up();
trie.up();
EXPECT_EQ(1, trie.at({1}));
EXPECT_EQ(2, trie.at({1, 2}));
EXPECT_EQ(3, trie.at({1, 2, 3}));
}
TEST_F(metric_trie_test, adds_sibling_node)
{
trie.down(1) = 1;
trie.down(2) = 2;
trie.up();
trie.down(3) = 3;
trie.up();
trie.down(4) = 4;
trie.up();
EXPECT_EQ(2, trie.at({1, 2}));
EXPECT_EQ(3, trie.at({1, 3}));
EXPECT_EQ(4, trie.at({1, 4}));
}
TEST_F(metric_trie_test, drills_down_the_stack)
{
trie.create({1, 2, 3, 4}) = 4;
EXPECT_EQ(4, trie.at({1, 2, 3, 4}));
}
TEST_F(metric_trie_test, check_node_existence)
{
EXPECT_FALSE(trie.has({1}));
EXPECT_FALSE(trie.has({1, 2}));
trie.down(1);
EXPECT_TRUE(trie.has({1}));
EXPECT_FALSE(trie.has({1, 2}));
trie.down(2);
EXPECT_TRUE(trie.has({1, 2}));
trie.up();
EXPECT_TRUE(trie.has({1}));
EXPECT_TRUE(trie.has({1, 2}));
trie.down(3);
EXPECT_TRUE(trie.has({1}));
EXPECT_TRUE(trie.has({1, 2}));
EXPECT_TRUE(trie.has({1, 3}));
}
TEST_F(metric_trie_test, timer_integration_test)
{
metric::trie<int, metric::timer> trie;
trie.down(1).start();
trie.down(2).start();
trie.up();
trie.up();
EXPECT_TRUE(trie.has({1}));
EXPECT_TRUE(trie.has({1, 2}));
}
TEST_F(metric_trie_test, preserves_top_node)
{
trie.down(11) = 123;
trie.up();
EXPECT_EQ(123, trie.down(11));
}
TEST_F(metric_trie_test, initially_has_zero_depth)
{
EXPECT_EQ(0u, trie.depth());
}
TEST_F(metric_trie_test, grows_in_depth)
{
trie.down(1);
EXPECT_EQ(1u, trie.depth());
trie.down(2);
EXPECT_EQ(2u, trie.depth());
trie.down(3);
EXPECT_EQ(3u, trie.depth());
}
TEST_F(metric_trie_test, reduces_depth)
{
trie.down(1);
trie.down(2);
trie.down(3);
trie.up();
EXPECT_EQ(2u, trie.depth());
trie.up();
EXPECT_EQ(1u, trie.depth());
trie.up();
EXPECT_EQ(0u, trie.depth());
}
TEST_F(metric_trie_test, reduces_depth_in_labmda_api)
{
auto up = [this]{this->trie.up([](auto){return 1;});};
trie.down(1);
trie.down(2);
trie.down(3);
up();
EXPECT_EQ(2u, trie.depth());
up();
EXPECT_EQ(1u, trie.depth());
up();
EXPECT_EQ(0u, trie.depth());
}
TEST_F(metric_trie_test, have_no_common_root)
{
trie.down(1) = 1;
trie.up();
trie.down(2) = 2;
trie.up();
EXPECT_TRUE(trie.has({1}));
EXPECT_EQ(1, trie.at({1}));
EXPECT_TRUE(trie.has({2}));
EXPECT_EQ(2, trie.at({2}));
}
TEST_F(metric_trie_test, clones_one_element_trie)
{
trie.down(11) = 123;
auto clone = trie.clone();
EXPECT_EQ(123, clone.at({11}));
}
TEST_F(metric_trie_test, clones_one_element_trie_with_no_cursor)
{
trie.down(11) = 123;
trie.up();
auto clone = trie.clone();
EXPECT_EQ(123, clone.at({11}));
}
TEST_F(metric_trie_test, clones_deep_trie)
{
trie.down(11) = 123;
trie.down(22) = 456;
trie.down(33) = 789;
auto clone = trie.clone();
EXPECT_EQ(123, clone.at({11}));
EXPECT_EQ(456, clone.at({11, 22}));
EXPECT_EQ(789, clone.at({11, 22, 33}));
}
TEST_F(metric_trie_test, clones_wide_trie)
{
trie.down(11) = 123;
trie.up();
trie.down(22) = 456;
trie.up();
trie.down(33) = 789;
trie.up();
auto clone = trie.clone();
EXPECT_EQ(123, clone.at({11}));
EXPECT_EQ(456, clone.at({22}));
EXPECT_EQ(789, clone.at({33}));
}
TEST_F(metric_trie_test, combines_tries)
{
rhs.down(1) = 11;
lhs.down(2) = 22;
auto combine = rhs.combine(lhs);
EXPECT_EQ(11, combine.at({1}));
EXPECT_EQ(22, combine.at({2}));
}
TEST_F(metric_trie_test, aggregates_tries)
{
rhs.down(1) = 11;
lhs.down(1) = 22;
auto combine = rhs.combine(lhs);
EXPECT_EQ(33, combine.at({1}));
}
| true |
4bf3e0718bb7a2f8363f3d385996d3777ddf6795 | C++ | dkarm/cannon-ball | /Cannonball/Powerbar.cpp | UTF-8 | 1,107 | 2.953125 | 3 | [] | no_license | //
// Powerbar.cpp
// Cannonball
//
// Created by Dipti Karmarkar on 8/17/16.
// Copyright © 2016 Dipti Karmarkar. All rights reserved.
//
#include "Powerbar.hpp"
Powerbar::Powerbar(sf::RenderWindow &window): window(window)
{
//initialize the outside rectangle
outside.setPosition(5,5);
pos.x = 100;
pos.y = 20;
outside.setSize(pos);
outside.setFillColor(sf::Color::Black);
outside.setOutlineColor(sf::Color::White);
outside.setOutlineThickness(2.0);
//initialize the inside rectangle
inside.setPosition(5,5);
//initialize number
charge = 100;
pos.x = charge;
inside.setSize(pos);
inside.setFillColor(sf::Color::Cyan);
}
void Powerbar::draw()
{
window.draw(outside);
window.draw(inside);
}
void Powerbar::startbar()
{
if (activated==0)
{
charge -= speed;
if (charge==0)
{
speed= -speed;
}
if (charge ==100)
{
speed = -speed;
}
pos.x = charge;
inside.setSize(pos);
}
}
int Powerbar::getstrength()
{
return charge;
}
void Powerbar::stopbar()
{
activated = 1;
}
| true |
2aaf557b40a0a6e1972510b5f25c9887f6d3b760 | C++ | RocketSkates/SchoolNew | /Semester 2/Exercise4/Exercise4/Avengers.h | UTF-8 | 571 | 2.546875 | 3 | [] | no_license |
#ifndef AVENGERS__H_
#define AVENGERS__H_
#include "CaptainSpider.h"
#include "SuperHero.h"
#include "Spiderman.h"
#include "AnimalBasedSuperHero.h"
#include "ProfessionBasedSuperHero.h"
#include "CaptainAmerica.h"
class Avengers
{
public:
Avengers();
~Avengers();
void saveType(ofstream& out, const SuperHero* hero) const;
void save(ofstream& out) const;
void load(ifstream& in);
void setSuperHeros(SuperHero** superHeros, int size);
SuperHero** getSuperHeros() const { return _superHeros; }
private:
SuperHero** _superHeros;
int _numSuperHeros;
};
#endif | true |
a4280051c499d20ad2355c301539a90ced7b2f25 | C++ | jaschulz/JobifyAS | /AppServer/src/db/dbController.cpp | UTF-8 | 1,078 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <string>
#include "dbController.h"
#include "leveldb/db.h"
using namespace std;
int dbController::connect(string dataBase) {
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, dataBase.c_str(), &db);
/*
if (false == status.ok())
{
cerr << "Unable to open/create test database './"+dataBase+"'" << endl;
cerr << status.ToString() << endl;
return -1;
}*/
return status.ok();
}
void dbController::CloseDB() {
// Close the database
delete db;
}
/*
string dbController::printDB(){
// Iterate over each item in the database and print them
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next())
{
cout << it->key().ToString() << " : " << it->value().ToString() << endl;
}
string error ="";
if (false == it->status().ok())
{
cerr << "An error was found during the scan" << endl;
cerr << it->status().ToString() << endl;
error = "Failed: " + it->status().ToString();
}
delete it;
return error;
}
*/
| true |
4bc3e7c1cb9127a89ac4f23b27759e6ce5737648 | C++ | flagship20030/Modified-Operant-Cage | /Arduino/Testing/operant_room_testing_2_27/operant_room_testing_2_27.ino | UTF-8 | 8,321 | 2.8125 | 3 | [] | no_license | /* Final Testing in Operant Room (3 solenoids / 3 IRs / 3 LEDs + 1 Button)
* 2/27/19
* JHL
*
* Head Pokes trigger solenoid reward in each port respectively (for a given amount of time ex: 200ms)
* for ex) if port 8 detects head poke, delivers reward for 200ms and records it
*
* remove the LED blinking part
* retain the button functionality so that we can test solenoids working or not
*
* Future To-Dos: Refactor Code into functions with emphasis on modularity!
*
*/
// coding schemes:
// On : 100
// Off: 001
// "component pin" + "on"
// i.e) IR at port 8 was poked in --> 8100 // poked out --> 8001
byte button_Pin = 2;
byte old_button_State = HIGH;
unsigned long debounceTime = 10; // 10 milliseconds
unsigned long button_PressTime; // when the button_ last changed state
// Solenoids
byte port_solenoid_3 = 3;
byte port_solenoid_4 = 4;
byte port_solenoid_5 = 5;
// LED constants
byte ledPin_6 = 6;// the number of the LED pin
byte ledPin_7 = 7;// the number of the LED pin
byte ledPin_9 = 9;// the number of the LED pin
// IRs
byte port_IR_8 = 8;
byte port_IR_10 = 10;
byte port_IR_11 = 11;
// LED variable states:
byte ledState_6 = LOW; // ledState used to set the LED
byte ledState_7 = LOW;
byte ledState_9 = LOW;
//**Solenoid Variables States:
byte sol_State_3 = LOW;
byte sol_State_4 = LOW;
byte sol_State_5 = LOW;
// IR States
boolean IR_previous_state_8;
boolean IR_previous_state_10;
boolean IR_previous_state_11;
// boolean to see if IR was broken:
boolean poke_in_8 = false;
boolean poke_in_10 = false;
boolean poke_in_11 = false;
// constants won't change:
const long sol_interval = 20; // LED + solenoid interval
// * * * * * * * * * * * S E T U P * * * * * * * * * * * * * * *
void setup() {
pinMode (button_Pin, INPUT);
// looks like the test program worked without solenoids set as OUTPUT
// but will include them just to make sure (and to see if code breaks)
pinMode(port_solenoid_3, OUTPUT);
pinMode(port_solenoid_4, OUTPUT);
pinMode(port_solenoid_5, OUTPUT);
pinMode(ledPin_6, OUTPUT);
pinMode(ledPin_7, OUTPUT);
pinMode(ledPin_9, OUTPUT);
pinMode(port_IR_8, INPUT);
pinMode(port_IR_10, INPUT);
pinMode(port_IR_11, INPUT);
Serial.begin(9600);
// delay(2000);
Serial.println("Start Test Program");
}
// * * * * * * * * * * * S E T U P * * * * * * * * * * * * * * *
// * * * * * * * * * * * L O O P * * * * * * * * * * * * * * *
void loop() {
// blink_led();
record_IR();
solenoid_on();
button_push();
}
// * * * * * * * * * * * L O O P * * * * * * * * * * * * * * *
void record_IR() {
static unsigned long Poke_On_Time_8 = 0;
static unsigned long Poke_Off_Time_8 = 0;
static unsigned long Poke_On_Time_10 = 0;
static unsigned long Poke_Off_Time_10 = 0;
static unsigned long Poke_On_Time_11 = 0;
static unsigned long Poke_Off_Time_11 = 0;
byte read_gate_8 = digitalRead(port_IR_8);
byte read_gate_10 = digitalRead(port_IR_10);
byte read_gate_11 = digitalRead(port_IR_11);
if (read_gate_8 != IR_previous_state_8) {
// low means IR has been broken
if (read_gate_8 == LOW) {
Poke_On_Time_8 = millis();
Serial.print("8100: ");
// Serial.print("Poke On at IR_8: ");
Serial.println(Poke_On_Time_8);
poke_in_8 = true;
}
if (read_gate_8 == HIGH){
Poke_Off_Time_8 = millis();
Serial.print("8001: ");
// Serial.print("Poke Off at IR_8: ");
Serial.println(Poke_Off_Time_8);
}
}
IR_previous_state_8 = read_gate_8;
if (read_gate_10 != IR_previous_state_10) {
if (read_gate_10 == LOW) {
Poke_On_Time_10 = millis();
Serial.print("10100: ");
// Serial.print("Poke On at IR_10: ");
Serial.println(Poke_On_Time_10);
poke_in_10 = true;
}
if (read_gate_10 == HIGH){
Poke_Off_Time_10 = millis();
Serial.print("10001: ");
// Serial.print("Poke Off at IR_10: ");
Serial.println(Poke_Off_Time_10);
}
}
IR_previous_state_10 = read_gate_10;
if (read_gate_11 != IR_previous_state_11) {
if (read_gate_11 == LOW) {
Poke_On_Time_11 = millis();
Serial.print("11100: ");
// Serial.print("Poke On at IR_11: ");
Serial.println(Poke_On_Time_11);
poke_in_11 = true;
}
if (read_gate_11 == HIGH){
Poke_Off_Time_11 = millis();
Serial.print("11001: ");
// Serial.print("Poke Off at IR_11: ");
Serial.println(Poke_Off_Time_11);
}
}
IR_previous_state_11 = read_gate_11;
}
void solenoid_on() {
unsigned long currentMillis = millis();
static unsigned long sol_on_3 = 0;
static unsigned long sol_off_3 = 0;
static unsigned long sol_on_4 = 0;
static unsigned long sol_off_4 = 0;
static unsigned long sol_on_5 = 0;
static unsigned long sol_off_5 = 0;
if (poke_in_8) {
poke_in_8 = false;
sol_State_3 = HIGH;
digitalWrite(port_solenoid_3, sol_State_3);
sol_on_3 = millis();
// Serial.print("3100: ");
Serial.print("solenoid On at 3: ");
Serial.println(sol_on_3);
// theoretically, currentMillis output and sol_on_3 output time should be the same!
}
// can't come in to this loop in the first place bc its nested in the if() above!!
if (sol_State_3 == HIGH && currentMillis - sol_on_3 >= sol_interval) { //poke_in_8 = false &&
sol_State_3 = LOW;
digitalWrite(port_solenoid_3, sol_State_3);
sol_off_3 = millis();
// Serial.print("3001: ");
Serial.print("solenoid Off at 3: ");
Serial.println(sol_off_3);
// theoretically currentMillis should be sol_off_3 + sol_interval value
}
if (poke_in_10) {
poke_in_10 = false;
sol_State_4 = HIGH;
digitalWrite(port_solenoid_4, sol_State_4);
sol_on_4 = millis();
// Serial.print("4100: ");
Serial.print("solenoid On at 4: ");
Serial.println(sol_on_4);
// theoretically, currentMillis output and sol_on_4 output time should be the same!
}
// breaking out of above loop is crucial!!!
// can't come in to this loop in the first place bc its nested in the if() above!!
if (sol_State_4 == HIGH && currentMillis - sol_on_4 >= sol_interval) { //poke_in_8 = false &&
sol_State_4 = LOW;
digitalWrite(port_solenoid_4, sol_State_4);
sol_off_4 = millis();
// Serial.print("4001: ");
Serial.print("solenoid Off at 4: ");
Serial.println(sol_off_4);
// theoretically currentMillis should be sol_off_3 + sol_interval value
}
if (poke_in_11) {
poke_in_11 = false;
sol_State_5 = HIGH;
digitalWrite(port_solenoid_5, sol_State_5);
sol_on_5 = millis();
// Serial.print("5100: ");
Serial.print("solenoid On at 5: ");
Serial.println(sol_on_5);
// can't come in to this loop in the first place bc its nested in the if() above!!
}
if (sol_State_5 == HIGH && currentMillis - sol_on_5 >= sol_interval) { //poke_in_8 = false &&
sol_State_5 = LOW;
digitalWrite(port_solenoid_5, sol_State_5);
sol_off_5 = millis();
// Serial.print("5001: ");
Serial.print("solenoid Off at 5: ");
Serial.println(sol_off_5);
// theoretically currentMillis should be sol_off_3 + sol_interval value
}
}
void button_push() {
// see if button_is open or closed
byte button_State = digitalRead (button_Pin);
// has it changed since last time?
if (button_State != old_button_State) {
// debounce
if (millis () - button_PressTime >= debounceTime) {
button_PressTime = millis (); // time when we close the button
old_button_State = button_State; // remember for next time
if (button_State == LOW) {
Serial.println ("button_closed.");
digitalWrite(port_solenoid_3, HIGH);
digitalWrite(port_solenoid_4, HIGH);
digitalWrite(port_solenoid_5, HIGH);
} // end if button_State is LOW
else {
Serial.println ("button_opened.");
digitalWrite(port_solenoid_3, LOW);
digitalWrite(port_solenoid_4, LOW);
digitalWrite(port_solenoid_5, LOW);
} // end if button_State is HIGH
} // end if debounce time up
} // end of state change
}
| true |
640e17bb98bd825475cba1030fb92dde2a2546d0 | C++ | henrychoi/realtime | /control/estimator.cpp | UTF-8 | 3,549 | 2.640625 | 3 | [] | no_license | #include "platform/all.h"//Must be the first include!!!!!
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <algorithm>
#include "log/log.h"
#include "control/estimator.h"
using namespace std; // for min()
bool ScalarLowpass::reset(float initial, float hz, float pd
, unsigned outlierThreshold) {
bool ok = true;
char msg[100];
estimator::reset();
mean = 0, sigma = 0;
outliers = 0;
k = 0;
cutoffhz = hz;
period = pd;
outlier_sigma = outlierThreshold;
// Sanity check
if(order >= window) {
snprintf(msg, sizeof(msg), "Filter order %d >= window %d"
, order, window);
log_fatal(NULL, msg);
ok = false;
}
if(order) {
if(cutoffhz > 1/period) {/* Cut-off frequency should be at most
1/10th sampling rate */
snprintf(msg, sizeof(msg)
, "Cutoff freq %f > 10%% * sampling rate %f\n" , cutoffhz, 1/period);
log_fatal(NULL, msg);
ok = false;
} else if(cutoffhz < 0.001f/period) {
// Likewise, cut-off frequency should be at least 1/1000th
// the sampling frequency or else we'll get into numerical problems,
// especially with higher order filters.
snprintf(msg, sizeof(msg)
, "Cutoff freq %f < 0.1%% * sampling rate %f\n", cutoffhz, 1/period);
log_fatal(NULL, msg);
ok = false;
}
}
// Compute coeff
float alpha = (float)exp(-2.0f * M_PI * cutoffhz * period);
dwindow = max((size_t)(.2f/(cutoffhz * period)), 1U);
dwindow = min(dwindow, window-1);
switch(order) {
case 0: a[0] = 1.0f; b[0] = 1.0f; break;
case 1:
a[0] = 1; b[0] = 1 - alpha;
a[1] = alpha; b[1] = 0;
break;
case 2://2nd-order is simply implemented as convolution of 2 1st-order
a[0] = 1; b[0] = pow((1-alpha),2);
a[1] = 2*alpha; b[1] = 0;
a[2] = -alpha*alpha; b[2] = 0;
break;
case 3://Similarly, a 3rd-order is convolution of 3 1st-order filters
a[0] = 1; b[0] = pow((1 - alpha),3);
a[1] = 3*alpha; b[1] = 0;
a[2] = -3*alpha*alpha; b[2] = 0;
a[3] = pow(alpha, 3); b[3] = 0;
break;
default:
snprintf(msg, sizeof(msg)
, "Estimator order %d unimplemented\n", order);
log_fatal(NULL, msg);
ok = false;
}
if(isnan(initial)) {
log_fatal(NULL, "initial is NAN\n");
}
update(initial);
return ok;
}
bool ScalarLowpass::update(float input) {
if(isnan(input)
|| (k > window
&& (sigma
&& fabs(input - mean) > (outlier_sigma * sigma)))) {
if(++outliers > window/2) {
//reset(hz, period);
return false;//bad!
}
z[k] = y[k-1]; //just use the history or initial in outlier case
} else { //back to normal
outliers = 0;
z[k] = input;
}
x[k] = z[k];//latest measurement
if(k < (window-1)) {//If insufficient sample, do not apply the filter
y[k] = x[k];
} else {
size_t j;
// take the average over a window up to window size
for(j = k - window + 1, mean = 0; j <= k; ++j) {
mean += x[j];
} mean /= window;
float var = 0;
for(j = k - window + 1, var = 0; j <= k; ++j) {
var += (x[j] - mean) * (x[j] - mean);
} var /= window, sigma = pow(var, 0.5f);
/* Update the estimator output, i.e.,
y[k] = a[1]y[k-1] + ... + a[n]y[k-n] + b[0]z[k] + ... + b[n]*z[k-n]
*/
for(y[k] = b[0] * z[k], j = 1; j <= order; ++j) {
y[k] += a[j] * y[k-j] + b[j] * z[k-j];
}
xdote = (y[k] - y[k - dwindow]) / (dwindow * period);
}
xe = y[k];
++k;
return true;
}
| true |
72e1458c3921d9220e273e27314466ce0385c5e7 | C++ | JLtea/Data_Structures | /mp_intro/intro.cpp | UTF-8 | 13,378 | 3.078125 | 3 | [] | no_license | #include "cs225/PNG.h"
#include "cs225/HSLAPixel.h"
#include <string>
#include <cmath>
#include <iostream>
void rotate(std::string inputFile, std::string outputFile) {
// TODO: Part 2
cs225::PNG png;
png.readFromFile(inputFile);
cs225::PNG* result = new cs225::PNG(png.width(), png.height());
for(unsigned int x = 0; x < png.width(); x++){
for(unsigned int y = 0; y < png.height(); y++) {
cs225::HSLAPixel & pixel = png.getPixel(x,y);
cs225::HSLAPixel & toCopy = result->getPixel(png.width() - x - 1,png.height() - y - 1);
toCopy.h = pixel.h;
toCopy.s = pixel.s;
toCopy.l = pixel.l;
toCopy.a = pixel.a;
}
}
result->writeToFile(outputFile);
}
cs225::PNG myArt(unsigned int width, unsigned int height) {
cs225::PNG png(width, height);
unsigned int centerX = width/2;
unsigned int centerY = height/2;
// TODO: Part 3
for(unsigned int x = 0; x < png.width(); x++){
for(unsigned int y = 0; y < png.height(); y++) {
cs225::HSLAPixel & pixel = png.getPixel(x,y);
double dist = sqrt((x-centerX)*(x-centerX) + (y-centerY)*(y-centerY));
pixel.h = 270;
pixel.s = 1;
pixel.l = 1;
pixel.l = (0.0015*dist)*pixel.l;
}
}
unsigned int x = 0;
unsigned int y = 0;
unsigned int t;
int angle = 7;
int hue = 180;
for(; y < png.height(); y+=angle) {
x += 1;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 1;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+2,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+2,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 1;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-2).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-2).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 1;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y+3).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y+3).h == hue){
break;
}
}
angle = 3;
for(; y < png.height(); y+=angle) {
x += 1;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t+1).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t+1).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 1;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+2,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+2,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 1;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-2).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-2).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 1;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y+3).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y+3).h == hue){
break;
}
}
angle = 2;
for(; y < png.height(); y+=angle) {
x += 1;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t+1).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t+1).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 1;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+2,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+2,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 1;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-2).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-2).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 1;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y+3).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y+3).h == hue){
break;
}
}
angle = 3;
for(; y < png.height(); y+=angle) {
x += 2;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t+1).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t+1).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 2;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+2,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+2,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 2;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-2).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-2).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 2;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y+3).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y+3).h == hue){
break;
}
}
angle = 1;
for(; y < png.height(); y+=angle) {
x += 1;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t+1).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t+1).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 1;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+2,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+2,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 1;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-2).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-2).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 1;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y+3).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y+3).h == hue){
break;
}
}
angle = 3;
for(; y < png.height(); y+=angle) {
x += 4;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t+1).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t+1).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 4;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+1,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+1,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 4;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-1).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-1).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 4;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y+1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y+1).h == hue){
break;
}
}
angle = 1;
for(; y < png.height(); y+=angle) {
x += 2;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t+1).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t+1).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 2;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t,y-1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t,y-1).h == hue){
break;
}
}
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 2;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-1).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-1,t).h = hue;
}
}
if(png.getPixel(x-1,t-1).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 2;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t-1,y).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t-1,y).h == hue){
break;
}
}
angle = 1;
for(; y < png.height(); y+=angle) {
x += 3;
for(t = y; t<(y+angle) && t<png.height();t+=1){
if(png.getPixel(x+1,t).h == hue){
break;
}
if(0<t<png.height()){
png.getPixel(x,t).h = hue;
if(x < png.width() - 1){
png.getPixel(x+1,t).h = hue;
}
}
}
if(png.getPixel(x+1,t).h == hue){
break;
}
}
y = t;
for(; x < png.width(); x+=angle) {
if (y >= 0) {
y -= 3;
}
for(t = x; t<(x+angle) && t<png.width() -3;t+=1){
if(png.getPixel(t+1,y-2).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y>= 1){
png.getPixel(t,y-1).h = hue;
}
}
if(png.getPixel(t+1,y-2).h == hue){
break;
}
}
y--;
x = t;
for(; y > 0 && y < png.height(); y-=angle) {
x -= 3;
for(t = y; t>(y-angle) && t > 0 ;t--){
if(png.getPixel(x-1,t-1).h == hue){
break;
}
if(t>0){
png.getPixel(x,t).h = hue;
png.getPixel(x-2,t).h = hue;
}
}
if(png.getPixel(x-2,t-1).h == hue){
break;
}
}
y = t;
for(; x > 0 && x < png.width(); x-=angle) {
if (y < png.height()) {
y+= 3;
}
for(t = x; t>(x-angle) && t>0;t--){
if(png.getPixel(t,y+1).h == hue){
break;
}
png.getPixel(t,y).h = hue;
if(y<png.height()){
png.getPixel(t,y+1).h = hue;
}
}
if(png.getPixel(t,y+1).h == hue){
break;
}
}
return png;
}
| true |
a13ea68c39ae7fcd9f09eada9c3aef723f723f52 | C++ | victorazzam/Cpp98-Course-Material | /Pointer Arithmetic/src/Pointer Arithmetic.cpp | UTF-8 | 1,260 | 4.15625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main() {
const int NSTRINGS = 5; // Const variables cannot be changed
string texts[NSTRINGS] = {"one", "two", "three", "four", "five"};
cout << "&texts: " << &texts << endl; // Location of array in memory, i.e. where it starts
cout << "texts: " << texts << endl; // Represented as its location in memory
// Hence `&array` and `array` are the same thing.
cout << endl;
string *p_texts = texts; // Pointer to (first element of) array
p_texts += 3; // Increase pointer position by 3
cout << "Increased pointer by 3: " << *p_texts << endl;
p_texts -= 2; // Decrease pointer position by 2
cout << "Decreased pointer by 2: " << *p_texts << endl << endl;
string *p_end = &texts[NSTRINGS]; // Pointer to just after end of array
p_texts = &texts[0]; // Pointer to start of array
while (p_texts < p_end) {
cout << *p_texts << endl;
p_texts++;
}
p_texts = &texts[0]; // Pointer to start of array
int elements = p_end - p_texts; // Subtract pointer values
cout << endl << "Difference between pointers: " << elements << endl;
p_texts = &texts[0]; // Pointer to start of array
p_texts += NSTRINGS / 2; // Pointer to middle of array
cout << "Middle of array: " << *p_texts << endl;
return 0;
}
| true |
74e6d0554be7ff87a14853a81e698a587a3d25cd | C++ | rajani-ku/COMP202-Labs | /Lab1/src/LinkedList.cpp | UTF-8 | 1,056 | 4 | 4 | [] | no_license | #include <iostream>
#include "LinkedList.h"
LinkedList::LinkedList()
{
HEAD = nullptr;
TAIL = nullptr;
}
bool LinkedList::isEmpty()
{
return HEAD == nullptr && TAIL == nullptr;
}
void LinkedList::addToHead(int element)
{
Node *newNode = new Node(element, HEAD);
HEAD = newNode;
if (TAIL == nullptr)
{
TAIL = HEAD;
}
}
int LinkedList::removeFromHead()
{
if (!this->isEmpty())
{
Node *nodeToDelete = HEAD;
int data = nodeToDelete->info;
this->HEAD = nodeToDelete->next;
if (HEAD == nullptr)
{
TAIL = nullptr;
}
delete nodeToDelete;
return data;
}
else
{
// TBD
}
}
void LinkedList::traverse(char separator)
{
if (isEmpty())
{
std::cout << "List is empty!!\n";
}
else
{
Node *temp = HEAD;
while (temp != nullptr)
{
std::cout << temp->info << separator;
temp = temp->next;
}
std::cout << std::endl;
}
} | true |
f27279df6716e41efabc0237f4ed51df8af2fe62 | C++ | aceiii/cpp-test | /singleton.cpp | UTF-8 | 1,081 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <memory>
class Singleton {
public:
static Singleton& getInstance() {
std::cout << "Singleton::getInstance()" << std::endl;
return *_instance;
}
void foo() {
std::cout << "Singleton::foo()" << std::endl;
}
private:
Singleton() {
std::cout << "Singleton::Singleton()" << std::endl;
}
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton(const Singleton&&) = delete;
Singleton& operator= (Singleton) = delete;
Singleton& operator= (Singleton&) = delete;
Singleton& operator= (const Singleton&) = delete;
Singleton&& operator= (Singleton&&) = delete;
Singleton&& operator= (const Singleton&&) = delete;
static std::unique_ptr<Singleton> _instance;
};
std::unique_ptr<Singleton> Singleton::_instance = std::unique_ptr<Singleton>{ new Singleton() };
auto main() -> int {
Singleton& singleton = Singleton::getInstance();
singleton.foo();
//Singleton singleton;
return 0;
}
| true |
1fa1f03dde95310a4a478f81ed3fbf60f763f879 | C++ | pedris11s/coj-solutions | /lmm-p1303-Accepted-s353849.cpp | UTF-8 | 3,483 | 2.75 | 3 | [] | no_license | //by pter
/*
3 6
D...*.
.X.X..
....S.
*/
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstdlib>
using namespace std;
#define x first
#define y second
#define MKP(a, b) make_pair((a), (b))
typedef pair <int, int> pii;
const int oo = 9999;
int f, c;
char M[60][60];
int costo_aster[60][60];
int costo_slikar[60][60];
bool mkA[60][60];
bool mkS[60][60];
queue < pii > cA;
queue < pii > cS;
pii s_ini;
pii dest;
vector <pii> ast_ini;
int DX[4] = {-1, 0, 1, 0};
int DY[4] = {0, 1, 0, -1};
bool Valido(pii A)
{
if(A.x <= f && A.y <= c && A.x >= 0 && A.y >= 0 && M[A.x][A.y] == '.')
return true;
return false;
}
void BFS_Aster()
{
while( !cA.empty() )
{
pii actual = cA.front();
cA.pop();
for(int i = 0; i < 4; i++)
{
pii ast = MKP(actual.x + DX[i], actual.y + DY[i]);
if(Valido(ast) && !mkA[ast.x][ast.y] )
{
mkA[ast.x][ast.y] = true;
cA.push(ast);
//M[ast.x][ast.y] = '*';
costo_aster[ast.x][ast.y] = costo_aster[actual.x][actual.y] + 1;
}
}
}
}
int BFS_Slikar()
{
while( !cS.empty() )
{
pii actual = cS.front();
cS.pop();
if(actual == dest)
return costo_slikar[actual.x][actual.y];
for(int i = 0; i < 4; i++)
{
pii slk = MKP(actual.x + DX[i], actual.y + DY[i]);
if( Valido(slk) && !mkS[slk.x][slk.y] )
{
costo_slikar[slk.x][slk.y] = costo_slikar[actual.x][actual.y] + 1;
if(costo_slikar[slk.x][slk.y] < costo_aster[slk.x][slk.y])
{
//cout << "entro" <<endl;
mkS[slk.x][slk.y] = true;
cS.push(slk);
}
}
}
}
return -1;
}
int main()
{
//freopen("slikar.in", "r", stdin);
//freopen("slikar.out", "w", stdout);
cin >> f >> c;
for(int i = 0; i < f; i++)
scanf("%s", M[i]);
//inicializando costo_aster;
for(int i = 0; i < f; i++)
for(int j = 0; j < c; j++)
costo_aster[i][j] = oo;
for(int i = 0; i < f; i++)
for(int j = 0; j < c; j++)
{
if(M[i][j] == '*')
{
//ast_ini.push_back(MKP(i, j));
cA.push(MKP(i,j));
mkA[i][j] = true;
costo_aster[i][j] = 0;
//cout << i << ' ' << j << endl;
}
else if(M[i][j] == 'S')
{
//s_ini = MKP(i,j);
cS.push( MKP( i, j ) );
mkS[i][j] = true;
}
else if(M[i][j] == 'D')
{
dest = MKP(i,j);
M[i][j] = '.';
mkA[i][j] = true;
costo_aster[i][j] = oo;
}
}
BFS_Aster();
/*for(int i = 0; i < f; i++)
{
for(int j = 0; j < c; j++)
cout << costo_aster[i][j];
cout << endl;
}
cout << endl;*/
int sol = BFS_Slikar();
/*for(int i = 0; i < f; i++)
{
for(int j = 0; j < c; j++)
cout << costo_slikar[i][j];
cout << endl;
}*/
if(sol >= 0)
cout << sol << endl;
else
cout << "KAKTUS\n";
//fclose(stdin);
//fclose(stdout);
//system("pause");
return 0;
}
| true |
a4edec644df6ae41380f8c82de0ea1945538ba85 | C++ | Kennylixinran/cs225 | /POTD/BernsteinHash45/main.cpp | UTF-8 | 756 | 3.734375 | 4 | [] | no_license | #include <string>
#include <iostream>
#include <algorithm>
using namespace std;
unsigned long bernstein(string str, int M)
{
unsigned long b_hash = 5381;
//Your code here
for(unsigned long i = 0; i < str.length(); i++){
//b_hash = b_hash * 33 + char;
//33 is the magic number for no reason;
b_hash = b_hash*33 + (int)str[i];
}
return b_hash % M;
}
string reverse(string str)
{
reverse(str.begin(), str.end());
//Your code here
return str;
}
int main()
{
string s = "POTS";
int M = 13;
cout<<"Bernstein hash of "<<s<<" with range "<<M<<" is: "<<bernstein(s, M)<<'\n';
cout<<"Bernstein hash of the reverse of "<<s<<" - " <<reverse(s)<<" - with range "<<M<<", is: "<<bernstein(reverse(s), M)<<'\n';
}
| true |
6d44ee5fdf077383ef1438c3388b52ce5ee0c306 | C++ | alongj/cppPrimer | /leetcode/leetcode141.cpp | UTF-8 | 4,823 | 2.9375 | 3 | [] | no_license | //
// Created by 邵军 on 2019/3/25.
//
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
bool hasCycle(ListNode *head) {
if (head == nullptr)
return false;
ListNode *oneStep = head;
ListNode *twoStep = head->next;
while (true) {
if (oneStep == nullptr && twoStep == nullptr)
return false;
if (oneStep == twoStep)
return true;
if (oneStep != nullptr)
oneStep = oneStep->next;
if (twoStep != nullptr && twoStep->next != nullptr)
twoStep = twoStep->next->next;
}
}
int numRookCaptures(vector<vector<char>> &board) {
int x = 0, y = 0;
int px = 0, py = 0;
for (vector<vector<char>>::iterator i = board.begin(); i != board.end(); ++i) {
y = 0;
for (vector<char>::iterator j = (*i).begin(); j < (*i).end(); ++j) {
if (*j == 'R') {
px = x;
py = y;
}
++y;
}
++x;
}
int count = 0;
char tmp;
for (int i = px; i >= 0; --i) {
tmp = board[i][py];
if (tmp == 'p') {
count++;
break;
}
if (tmp == 'B')
break;
}
for (int i = px; i < 8; ++i) {
tmp = board[i][py];
if (tmp == 'p') {
count++;
break;
}
if (tmp == 'B')
break;
}
for (int j = py; j >= 0; --j) {
tmp = board[px][j];
if (tmp == 'p') {
count++;
break;
}
if (tmp == 'B')
break;
}
for (int j = py; j < 8; ++j) {
tmp = board[px][j];
if (tmp == 'p') {
count++;
break;
}
if (tmp == 'B')
break;
}
return count;
}
vector<pair<int, int>> kSmallestPairs(vector<int> &nums1, vector<int> &nums2, int k) {
vector<pair<int, int>> vec;
if (nums1.size() == 0 || nums2.size() == 0)
return vec;
int i = 0, i1 = 0, j1 = i1 + 1, j2 = 0, i2 = j2 + 1;
int v, v1, v2;
while (vec.size() < k) {
if (i >= nums1.size() || i >= nums2.size()) {
v = INT_MAX;
} else {
v = nums1[i] + nums2[i];
}
if (i1 >= nums1.size()) {
v1 = INT_MAX;
} else if (j1 >= nums2.size()) {
i1++;
if (i1 >= nums1.size() || i1 + 1 >= nums2.size()) {
v1 = INT_MAX;
} else {
j1 = i1 + 1;
v1 = nums1[i1] + nums2[j1];
}
} else {
v1 = nums1[i1] + nums2[j1];
}
if (j2 >= nums2.size()) {
v2 = INT_MAX;
} else if (i2 >= nums1.size()) {
j2++;
if (j2 >= nums2.size() || j2 + 1 >= nums1.size()) {
v2 = INT_MAX;
} else {
i2 = j2 + 1;
v2 = nums1[i2] + nums2[j2];
}
} else {
v2 = nums1[i2] + nums2[j2];
}
if (v == INT_MAX && v1 == INT_MAX && v2 == INT_MAX)
break;
if (v <= v1 && v <= v2) {
vec.push_back(pair<int, int>(nums1[i], nums2[i]));
i++;
}
if (v1 < v && v1 <= v2) {
vec.push_back(pair<int, int>(nums1[i1], nums2[j1]));
j1++;
}
if (v2 < v && v2 < v1) {
vec.push_back(pair<int, int>(nums1[i2], nums2[j2]));
i2++;
}
}
return vec;
}
int main(int argc, char **argv) {
// vector<vector<char>> vec;
// char data[8][8] = {{'.', '.', '.', '.', '.', '.', '.', '.'},
// {'.', '.', '.', 'p', '.', '.', '.', '.'},
// {'.', '.', '.', 'R', '.', '.', '.', 'p'},
// {'.', '.', '.', '.', '.', '.', '.', '.'},
// {'.', '.', '.', '.', '.', '.', '.', '.'},
// {'.', '.', '.', 'p', '.', '.', '.', '.'},
// {'.', '.', '.', '.', '.', '.', '.', '.'},
// {'.', '.', '.', '.', '.', '.', '.', '.'}};
//
//
// for (int i = 0; i < 8; ++i) {
// vector<char> v;
// for (int j = 0; j < 8; ++j) {
// v.push_back(data[i][j]);
// }
// vec.push_back(v);
// }
//
// cout << vec[1][1] << endl;
// cout << numRookCaptures(vec) << endl;
vector<int> nums1 = {-10, -4, 0, 0, 6};
vector<int> nums2 = {3, 5, 6, 7, 8, 100};
vector<pair<int, int>> nums = kSmallestPairs(nums1, nums2, 10);
cout << "nums.size()=" << nums.size() << endl;
for (int i = 0; i < nums.size(); i++) {
cout << "[" << nums[i].first << "," << nums[i].second << "]" << endl;
}
} | true |
d2c1260897ba137386a23b780e7cb55d1dfea783 | C++ | milwilczynski/BomberChamp | /Headers/Player.h | UTF-8 | 989 | 3 | 3 | [] | no_license | #pragma once
#include "Main.h"
#include "Definitions.h"
class GameClass;
class Player
{
public:
inline Player()
: apk_rotation(0),
apk_destroyed(false)
{
}
inline virtual ~Player() {}
inline virtual void SetLocation(const grim::Vector2 &loc)
{
apk_location = loc;
}
inline virtual void SetRotation(const float &rot)
{
apk_rotation = rot;
}
inline virtual void Move(const grim::Vector2 &move)
{
this->SetLocation(apk_location + move);
}
inline virtual void Rotate(const float &move)
{
this->SetRotation(apk_rotation + move);
}
inline void Destroy()
{
apk_destroyed = true;
}
inline virtual void Update(const float &time)
{
}
virtual void Draw() = 0;
inline grim::Vector2 GetLocation() const
{
return apk_location;
}
inline float GetRotation() const
{
return apk_rotation;
}
inline bool IsDestroyed() const
{
return apk_destroyed;
}
protected:
grim::Vector2 apk_location;
float apk_rotation;
bool apk_destroyed;
}; | true |
3313237d4567fc08bb7dc011d99bdf2dfa09957b | C++ | rosekc/acm | /cf/832/B.cpp | UTF-8 | 1,818 | 2.703125 | 3 | [] | no_license | //2017-07-24-23.01
//B
#include <bits/stdc++.h>
using namespace std;
int n;
int pos;
string in, pat;
bool good['a' + 26];
bool check1() {
for (int i = 0; i < pos; i++) {
//cout << pat[i] << " " << in[i] << endl;
if (pat[i] == '?' && !good[in[i]]) return 0;
else if (pat[i] != '?' && in[i] != pat[i]) {
//puts("???");
return 0;
}
}
return true;
}
bool check2() {
for (int i = in.length(), j = pat.length(); j != pos; i--, j--) {
if (pat[j] == '?' && !good[in[i]]) return false;
else if (pat[j] != '?' && in[i] != pat[j]) return 0;
}
return 1;
}
bool check3() {
//cout << (int)in.length() - ((int)pat.length() - pos) << endl;
for (int i = pos; i <= (int)in.length() - ((int)pat.length() - pos); i++) {
if (good[in[i]]) return 0;
}
return 1;
}
int main() {
cin >> in >> pat >> n;
memset(good, 0, sizeof good);
for (int i = 0; i < in.length(); i++) {
good[in[i]] = 1;
}
pos = -1;
bool found = 1;
for (int i = 0; i < pat.length(); i++) {
if (pat[i] == '*') {
pos = i;
break;
}
}
if (pos == -1) {
found = 0;
}
while (n--) {
cin >> in;
if (!found) {
pos = in.length();
if (in.length() == pat.length() && check1()) puts("YES");
else puts("NO");
continue;
}
if (in.length() < (int)pat.length() - 1) {
puts("NO");
continue;
}
// cout << check1() << endl;
// cout << check2() << endl;
// cout << check3() << endl;
if (check1() && check2() && check3()) {
puts("YES");
} else {
puts("NO");
}
}
}
| true |
42c3f174985f022156d76e19758db27b4f20c5e7 | C++ | giordi91/machine-learning | /tests/src/logistic_regression.cpp | UTF-8 | 1,722 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "test_utils.h"
#include <mg_ml/cpu/matrix_functions.h>
#include <mg_ml/cpu/models/logistic_regression.h>
TEST(logistic_regression, sigmoid) {
std::vector<float> sig_data{0.0f, 2.0f};
std::vector<float> sig_data_out{0.0f, 0.0f};
core::Matrixf inm{sig_data.data(), 1, 2};
core::Matrixf outm{sig_data_out.data(), 1, 2};
models::cpu::sigmoid<float>(inm, outm);
ASSERT_NEAR(outm.data[0], 0.5f, 0.0000001);
ASSERT_NEAR(outm.data[1], 0.88079708f, 0.00001);
}
TEST(logistic_regression, simple_eval) {
// w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]),
// np.array([[1,0]])
std::vector<float> w_data{2.0f, 1.0f, 2.0f};
std::vector<float> x_data{1.0f, 1.0f, 3.0f, 1.0f, 2.0f, 4.0f};
std::vector<float> y_data{1.0f, 0.0f};
std::vector<float> out_data{0.0f, 0.0f};
std::vector<float> grad_data{0.0f, 0.0f};
core::Matrixf wm{w_data.data(), 1, 3};
core::Matrixf xm{x_data.data(), 2, 3};
// keeping Y transposed for easyness of computing, avoids a transpose
core::Matrixf ym{y_data.data(), 1, 2};
core::Matrixf outm{out_data.data(), 2, 1};
core::Matrixf gradm{grad_data.data(), 1, 3};
models::cpu::simple_logistic_forward<float>(xm, wm, outm);
ASSERT_NEAR(outm.data[0], 0.99987661, 0.00001);
ASSERT_NEAR(outm.data[1], 0.99999386, 0.00001);
float cost = models::cpu::logistic_cost<float>(outm, ym);
ASSERT_NEAR(cost, 6.000064773192205f, 0.01);
// lets chack backward prop
models::cpu::simple_logistic_backwards(xm, outm, ym, gradm);
ASSERT_NEAR(gradm.data[0], 0.499935230625, 0.00001);
ASSERT_NEAR(gradm.data[1], 0.99993216, 0.00001);
ASSERT_NEAR(gradm.data[2], 1.99980262, 0.00001);
models::cpu::simple_logistic_apply_grad(wm, gradm, 0.01);
}
| true |
47cfc6b7364222a7ec7960b7a9f3073c645fad16 | C++ | MostafaOmar98/competitive-programming | /Algorithms/graph/MaximumMatchingN^2PseudoCode.cpp | UTF-8 | 2,574 | 2.75 | 3 | [] | no_license | int husband[N];
int vis[N], vid; // vid for maximum matching increment
bool foundMatch(int MID)
{
vis[MID] = vid;
for (auto to : adj[MID])
{
if (husband[to] == -1)
{
husband[to] = MID;
return 1;
}
else if (vis[husband[to]] != vid && foundMatch(husband[to]))
{
husband[to] = MID;
return 1;
}
}
return 0;
}
int maxMatch()
{
int ans = 0;
for (int i = 0; i < Males; ++i)
{
++vid;
ans += foundMatch(i);
}
return ans;
}
// EXAMPLE -- FAST NOW
int nMales, nFemales;
const int MAX_N = 1e5 + 5;
vector<int> adj[MAX_N]; // adj[male] -> female
int husband[MAX_N]; // husband[female] -> male
int vis[MAX_N], vid; // vis[male] -> vid;
int wife[MAX_N]; // wife[male] -> female
int foundMatch(int male)
{
if (vis[male] == vid)
return 0;
vis[male] = vid;
for (int v : adj[male])
{
if (husband[v] == -1)
{
husband[v] = male;
wife[male] = v;
return 1;
}
}
for (int v : adj[male])
{
if (foundMatch(husband[v]))
{
husband[v] = male;
wife[male] = v;
return 1;
}
}
return 0;
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int maximumMatching()
{
memset(husband, -1, nFemales * sizeof(husband[0]));
memset(wife, -1, nMales * sizeof(wife[0]));
vector<int> maleIDs(nMales);
iota(maleIDs.begin(), maleIDs.end(), 0);
shuffle(maleIDs.begin(), maleIDs.end(), rng);
for (int male : maleIDs)
shuffle(adj[male].begin(), adj[male].end(), rng);
int ok = 1;
while(ok--)
{
++vid;
for (int male : maleIDs)
if (wife[male] == -1)
ok |= foundMatch(male);
}
int ans = 0;
for (int male : maleIDs)
ans += wife[male] != -1;
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#else
// freopen("grand.in", "r", stdin);
// freopen("grand.out", "w", stdout);
#endif
cin >> nMales >> nFemales;
int m;
cin >> m;
while(m--)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v); // edge from male to female
}
cout << maximumMatching() << '\n';
for (int female = 0; female < nFemales; ++female)
{
if (husband[female] != -1)
cout << husband[female] << " " << female << '\n';
}
} | true |
4a7922c6b24e5d286f43ba9db4dfe1c7a4e7c173 | C++ | xiaoyiqingz/DesignPattern | /DesignPattern/Mediator.cpp | UTF-8 | 1,815 | 2.9375 | 3 | [] | no_license | #include "Mediator.h"
#include <iostream>
namespace dp {
Colleage::Colleage()
{
}
Colleage::Colleage(Mediator* md)
{
md_ = md;
}
Colleage::~Colleage()
{
}
ConcreteColleageA::ConcreteColleageA()
{
}
ConcreteColleageA::ConcreteColleageA(Mediator* mt)
: Colleage(mt)
{
}
ConcreteColleageA::~ConcreteColleageA()
{
}
void ConcreteColleageA::DoAction()
{
md_->DoActionFromAToB();
std::cout << GetState() << "..." << std::endl;
}
void ConcreteColleageA::SetState(const std::string& st)
{
st_ = st;
}
std::string ConcreteColleageA::GetState()
{
return st_;
}
ConcreteColleageB::ConcreteColleageB()
{
}
ConcreteColleageB::ConcreteColleageB(Mediator* mt)
: Colleage(mt)
{
}
ConcreteColleageB::~ConcreteColleageB()
{
}
void ConcreteColleageB::DoAction()
{
md_->DoActionFromBToA();
std::cout << GetState() << "..." << std::endl;
}
void ConcreteColleageB::SetState(const std::string& st)
{
st_ = st;
}
std::string ConcreteColleageB::GetState()
{
return st_;
}
Mediator::Mediator()
{
}
Mediator::~Mediator()
{
}
ConcreteMediator::ConcreteMediator()
{
}
ConcreteMediator::ConcreteMediator(Colleage* clgA, Colleage* clgB)
: clgA_(clgA), clgB_(clgB)
{
}
ConcreteMediator::~ConcreteMediator()
{
}
void ConcreteMediator::DoActionFromAToB()
{
clgB_->SetState(clgA_->GetState());
}
void ConcreteMediator::DoActionFromBToA()
{
clgA_->SetState(clgB_->GetState());
}
void ConcreteMediator::SetConcreteColleageA(Colleage* clgA)
{
clgA_ = clgA;
}
void ConcreteMediator::SetConcreteColleageB(Colleage* clgB)
{
clgB_ = clgB;
}
Colleage* ConcreteMediator::GetConcreteColleageA()
{
return clgA_;
}
Colleage* ConcreteMediator::GetConcreteColleageB()
{
return clgB_;
}
void ConcreteMediator::IntroColleage(Colleage* clgA, Colleage* clgB)
{
clgA_ = clgA;
clgB_ = clgB;
}
} // namespace dp
| true |
4f93894cf67bc8e23215b7cbf17c7aa690fba922 | C++ | riteshkumar99/coding-for-placement | /leetcode/problemset-algorithms/sum-of-nodes-with-even-valued-grandparent.cpp | UTF-8 | 972 | 3.34375 | 3 | [
"MIT"
] | permissive | /**
* 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:
int solve(TreeNode *node, bool isGrandParentEven, bool isParentEven) {
int sum = 0;
if(isGrandParentEven) {
sum += node->val;
}
if(node->left != NULL) {
sum += solve(node->left, isParentEven, (node->val % 2 == 0));
}
if(node->right != NULL) {
sum += solve(node->right, isParentEven, (node->val % 2 == 0));
}
return sum;
}
int sumEvenGrandparent(TreeNode* root) {
if(root == NULL) {
return 0;
}
return solve(root, false, false);
}
};
| true |
bc1fb3c16d158a74ad82b5eb5eca8fdf3cd717e9 | C++ | DaniielaRodas/PropuestaSimposio | /main.cpp | UTF-8 | 843 | 3.390625 | 3 | [
"MIT"
] | permissive | #include <iostream>
int main()
{
std::cout << "Propuesta de programa para el simposio de Ingenieria 2021\n";
// Daniela Rodas - 1652421
#include <iostream>
using namespace std;
int main () {
int C1, C2, C3;
cout << "Ingrese la cantidad de asistentes para Ingenieria en sistemas:";
cin >> C1;
cout << "Ingrese la cantidad de asistentes para Ingenieria Industrial:";
cin >> C2;
cout << "Ingrese la cantidad de asistentes para Ingenieria Civil:";
cin >> C3;
if (C1 > C2 && C1 > C3) {
cout << "A la carrera de Ingenieria en sistemas se le asignara el salon mayor";
}
else if (C2 > C1 && C2 > C3) {
cout << "A la carrera de Ingenieria Industrial se le asignara el salon mayor";
}
else if (C3 > C1 && C3 > C2) {
cout << "A la carrera de Ingenieria Civil se le asignara el salon mayor ";
}
}
std::cin.ignore();
return 0;
}
| true |
9f41d16aa8839238ceb3f624659b8c3385de9485 | C++ | SaulRuizS/C-and-CPP-exercises | /Cpp/POO_excercises/Headers/MyExampleClass.hpp | UTF-8 | 303 | 2.53125 | 3 | [] | no_license | #ifndef MYEXAMPLECLASS_HPP
#define MYEXAMPLECLASS_HPP
class MyExampleClass
{
private:
int regVariable;
const int constVariable;
public:
MyExampleClass(); //Default constructor
MyExampleClass(int a, int b); //Parameterizied constructor
~MyExampleClass();
};
#endif | true |
026e06832b79ef56532aba8a7f5e95fd059d8882 | C++ | tylercchase/cs202 | /labs/lab03/Student.cpp | UTF-8 | 550 | 3.375 | 3 | [] | no_license | #include "Student.hpp"
#include <iostream>
using std::cout;
Student::Student(const Student &orig)
{
_age = orig._age;
_gpa = orig._gpa;
std::cout << "Make a copy" << std::endl;
}
Student::Student(){
_age = 0;
_gpa = 0;
std::cout << "Construct with default params" << std::endl;
}
Student::Student(int age, double gpa){
_age = age;
_gpa = gpa;
std::cout << "Construct with parameter" << std::endl;
}
Student::~Student(){
std::cout << "Deconstruct woo" << std::endl;
}
int Student::getAge(){
return _age;
} | true |
4bce238c4752b7d47d42f70cbdc0038cf010ec20 | C++ | takashato/GameUIT | /GameProject/GameComponents/Animation.cpp | UTF-8 | 2,273 | 2.71875 | 3 | [] | no_license | #include "Animation.h"
Animation::Animation()
{
}
Animation::Animation(const char* filePath, int totalFrame, int rows, int columns, float timePerFrame, D3DCOLOR colorKey)
{
InitWithAnimation(filePath, totalFrame, rows, columns, timePerFrame, colorKey);
}
void Animation::InitWithAnimation(const char* filePath, int totalFrame, int rows, int columns, float timePerFrame, D3DCOLOR colorKey)
{
//GAMELOG("animation: frame: %d, row: %d, column: %d, time: %f", totalFrame, rows, columns, timePerFrame);
this->InitWithSprite(filePath);
mCurrentColumn = 0;
mCurrentRow = 0;
mTimePerFrame = timePerFrame;
mTotalFrame = totalFrame;
mRows = rows;
mColumns = columns;
//width - height luc nay la cua spritesheet
mFrameWidth = GetWidth() / mColumns;
mFrameHeight = GetHeight() / mRows;
SetWidth(mFrameWidth);
SetHeight(mFrameHeight);
mRect.top = 0;
mRect.left = 0;
mRect.right = mFrameWidth;
mRect.bottom = mFrameHeight;
SetSourceRect(mRect);
}
Animation::~Animation()
{
}
void Animation::Update(float dt)
{
if (mTotalFrame <= 1)
return;
if (mCurrentTotalTime >= mTimePerFrame)
{
mCurrentTotalTime = 0;
mCurrentIndex++;
mCurrentColumn++;
if (mCurrentIndex >= mTotalFrame)
{
mCurrentIndex = 0;
mCurrentColumn = 0;
mCurrentRow = 0;
}
if (mCurrentColumn >= mColumns)
{
mCurrentColumn = 0;
mCurrentRow++;
if (mCurrentRow >= mRows)
mCurrentRow = 0;
}
mRect.left = mCurrentColumn * mFrameWidth;
mRect.right = mRect.left + mFrameWidth;
mRect.top = mCurrentRow * mFrameHeight;
mRect.bottom = mRect.top + mFrameHeight;
SetSourceRect(mRect);
}
else
{
mCurrentTotalTime += dt;
}
}
void Animation::Draw(D3DXVECTOR3 position, RECT sourceRect, D3DXVECTOR2 scale,
D3DXVECTOR2 transform, float angle, D3DXVECTOR2 rotationCenter, D3DXCOLOR colorKey)
{
Sprite::Draw(position, sourceRect, scale, transform, angle, rotationCenter, colorKey);
}
void Animation::Draw(D3DXVECTOR2 translate)
{
Sprite::Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), translate);
} | true |
5e41ac6a9b1e2f6d97e538084a307c1f0c1406e1 | C++ | ZPGuiGroupWhu/ClusteringDirectionCentrality | /Toolkit/Synthetic Data Analysis/UMAP/epp/cpp/boundary.h | UTF-8 | 32,457 | 3.390625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef _EPP_BOUNDARY_H
#define _EPP_BOUNDARY_H 1
#include <vector>
#include <algorithm>
#include <memory>
#include <cassert>
namespace EPP
{
/*
* Utilities for Colored Maps
*
* The map is composed of directed edges that are color labeled on each side.
* Primary design goal is speed of the lookup function. Secondary but still
* important, speed of pulling out a point list of the graph edges. Includes
* support for weighing the various graph edges for EPP
*/
// four orientations of the edge within a grid square
// order is important in colorAt() and initializing index and edge_color
enum ColoredSlope
{
ColoredHorizontal,
ColoredRight,
ColoredLeft,
ColoredVertical
};
// points are given a raster order so we can search them quickly
template <typename coordinate>
class ColoredPoint
{
public:
coordinate i;
coordinate j;
inline bool operator<(const ColoredPoint<coordinate> &cp) const noexcept
{
if (i < cp.i)
return true;
if (i > cp.i)
return false;
return j < cp.j;
};
inline bool operator>(const ColoredPoint<coordinate> &cp) const noexcept
{
if (i > cp.i)
return true;
if (i < cp.i)
return false;
return j > cp.j;
};
inline bool operator==(const ColoredPoint<coordinate> &cp) const noexcept
{
return i == cp.i && j == cp.j;
};
inline bool adjacent(const ColoredPoint<coordinate> cp) const noexcept
{
return abs(i - cp.i) <= 1 && abs(j - cp.j) <= 1;
};
inline ColoredPoint<coordinate>(
coordinate i,
coordinate j) noexcept
: i(i), j(j){};
inline ColoredPoint<coordinate>() = default;
};
/**
* a segment is a directed edge with the two sides labeled by color.
* each segment represents one grid square. for efficiency of lookup
* always stored by the lower left coordinate of the square.
*/
template <typename coordinate, typename color>
class ColoredSegment
{
public:
float weight;
coordinate i;
coordinate j;
color clockwise;
color widdershins;
ColoredSlope slope;
// to save space, compute the head and tail
inline ColoredPoint<coordinate> tail() const noexcept
{
switch (slope)
{
case ColoredLeft:
return ColoredPoint<coordinate>(i + 1, j);
case ColoredRight:
return ColoredPoint<coordinate>(i, j);
case ColoredHorizontal:
return ColoredPoint<coordinate>(i, j);
case ColoredVertical:
return ColoredPoint<coordinate>(i, j);
}
assert(("shouldn't happen", false));
return ColoredPoint<coordinate>(0, 0);
}
inline ColoredPoint<coordinate> head() const noexcept
{
switch (slope)
{
case ColoredLeft:
return ColoredPoint<coordinate>(i, j + 1);
case ColoredRight:
return ColoredPoint<coordinate>(i + 1, j + 1);
case ColoredHorizontal:
return ColoredPoint<coordinate>(i + 1, j);
case ColoredVertical:
return ColoredPoint<coordinate>(i, j + 1);
}
assert(("shouldn't happen", false));
return ColoredPoint<coordinate>(0, 0);
}
// the head of one edge connects to the tail of the other
bool adjacent(ColoredSegment<coordinate, color> ce) const noexcept
{
return head() == ce.head() || head() == ce.tail() || tail() == ce.tail() || tail() == ce.head();
};
// the point is the head or tail of the edge
bool adjacent(ColoredPoint<coordinate> cp) const noexcept
{
return head() == cp || tail() == cp;
};
// segments are sorted for fast access
inline bool operator<(const ColoredSegment &cs) const noexcept
{
if (i < cs.i)
return true;
if (i > cs.i)
return false;
if (j < cs.j)
return true;
if (j > cs.j)
return false;
return slope < cs.slope;
};
inline bool operator>(const ColoredSegment &cs) const noexcept
{
if (i > cs.i)
return true;
if (i < cs.i)
return false;
if (j > cs.j)
return true;
if (j < cs.j)
return false;
return slope > cs.slope;
};
ColoredSegment<coordinate, color>(
ColoredSlope slope,
coordinate i,
coordinate j,
color clockwise,
color widdershins,
float weight) noexcept
: slope(slope), i(i), j(j), clockwise(clockwise), widdershins(widdershins),
weight(weight > 0 ? weight : std::numeric_limits<float>::min()){};
ColoredSegment<coordinate, color>(
ColoredSlope slope,
coordinate i,
coordinate j,
color clockwise,
color widdershins) noexcept
: slope(slope), i(i), j(j), clockwise(clockwise), widdershins(widdershins),
weight(std::numeric_limits<float>::min()){};
ColoredSegment<coordinate, color>() = default;
};
// an ordered list of pointers to adjacent segments
template <typename coordinate, typename color>
class ColoredChain : public std::vector<ColoredSegment<coordinate, color> *>
{
public:
// figure out the head and tail of the chain
ColoredPoint<coordinate> tail() const noexcept
{
if (this->size() == 1)
return this->front()->tail();
ColoredSegment<coordinate, color> *first = this->at(0);
ColoredSegment<coordinate, color> *second = this->at(1);
if (first->head() == second->tail() || first->head() == second->head())
return first->tail();
else
return first->head();
};
ColoredPoint<coordinate> head() const noexcept
{
if (this->size() == 1)
return this->back()->head();
ColoredSegment<coordinate, color> *ultimate = this->at(this->size() - 1);
ColoredSegment<coordinate, color> *penultimate = this->at(this->size() - 2);
if (penultimate->tail() == ultimate->tail() || penultimate->head() == ultimate->tail())
return ultimate->head();
else
return ultimate->tail();
};
};
/**
* A directed and labeled edge longer than one grid square
* always equivalent to a segment chain though
*/
template <typename coordinate, typename color>
class ColoredEdge
{
public:
std::vector<ColoredPoint<coordinate>> points;
float weight;
color clockwise;
color widdershins;
ColoredEdge(
std::vector<ColoredPoint<coordinate>> points,
color clockwise,
color widdershins,
double weight) noexcept
: points(points), clockwise(clockwise), widdershins(widdershins), weight((float)weight){};
ColoredEdge(
std::vector<ColoredPoint<coordinate>> points,
color clockwise,
color widdershins) noexcept
: points(points), clockwise(clockwise), widdershins(widdershins), weight(0){};
ColoredEdge(const ColoredEdge &that) noexcept
{
this->points = that.points;
this->clockwise = that.clockwise;
this->widdershins = that.widdershins;
this->weight = that.weight;
}
ColoredEdge() = default;
;
~ColoredEdge() = default;
;
ColoredEdge &operator=(const ColoredEdge &that) noexcept
{
this->points = that.points;
this->clockwise = that.clockwise;
this->widdershins = that.widdershins;
this->weight = that.weight;
return *this;
}
ColoredEdge &operator=(ColoredEdge &&that) noexcept
{
if (this != that)
{
this->points = that.points;
this->clockwise = that.clockwise;
this->widdershins = that.widdershins;
this->weight = that.weight;
}
return *this;
}
};
// utility class for rapid lookup of color by map position
template <typename coordinate, typename color>
class ColoredMap
{
int segments;
ColoredSegment<coordinate, color> *boundary;
ColoredSegment<coordinate, color> *index[N];
color edge_color[N];
public:
// this is the money shot, the innermost loop
// everything is designed to make this fast
inline color colorAt(
const double x,
const double y) const noexcept
{
int i = (int)(x * N);
int j = (int)(y * N);
double dx = x * N - i;
double dy = y * N - j;
// jump to the first element for this i
ColoredSegment<coordinate, color> *segment = index[i];
color result = edge_color[i];
for (; segment < boundary + segments; segment++)
{
if (segment->i > i)
break; // definitely not here
if (segment->j < j)
// the point is somewhere above this segment
switch (segment->slope)
{
case ColoredLeft:
result = segment->clockwise;
break;
case ColoredRight:
case ColoredHorizontal:
result = segment->widdershins;
break;
case ColoredVertical:
break;
}
else if (segment->j == j)
switch (segment->slope)
// we've found it so dispatch
{
case ColoredLeft:
if (dy > 1 - dx)
result = segment->clockwise;
else
result = segment->widdershins;
return result;
case ColoredRight:
if (dy <= dx)
result = segment->clockwise;
else
result = segment->widdershins;
return result;
case ColoredHorizontal:
result = segment->widdershins;
return result;
case ColoredVertical:
return result;
}
else
break; // definitely not here
// might be another one so go around again
}
return result;
}
explicit ColoredMap(std::vector<ColoredSegment<coordinate, color>> bounds) noexcept
{
segments = bounds.size();
boundary = new ColoredSegment<coordinate, color>[segments];
std::copy(bounds.begin(), bounds.end(), boundary);
ColoredSegment<coordinate, color> *segment = boundary;
color outside;
if (segment->j == 0) // figure out the color < Point(0,0);
{
if (segment->slope == ColoredHorizontal)
outside = segment->clockwise;
else
outside = segment->widdershins;
}
else
{
if (segment->slope == ColoredLeft)
outside = segment->widdershins;
else
outside = segment->clockwise;
}
for (int i = 0; i < N; ++i) // for each i value find the color < Point(i,0)
{ // and the first segment with that coordinate if any
if (segment < boundary + segments && segment->i == i)
{
if (segment->j == 0)
{
outside = segment->clockwise; // boundary from here on is clockwise
}
else
{
if (segment->slope == ColoredLeft)
outside = segment->widdershins;
else
outside = segment->clockwise;
}
index[i] = segment++; // remember the first segment that applies to this i for later
}
else
index[i] = boundary + segments; // if there are no segments for this i point to the boundary end
edge_color[i] = outside;
for (; segment < boundary + segments; segment++) // skip to next i
if (segment->i != i)
break;
}
};
~ColoredMap()
{
delete[] boundary;
}
};
/*
The dual graph exchanges vertices and faces while inverting the meaning of edges. The initial dual points
are the original clusters. Not clear the dual graph is planar or what the dual faces mean. Each original point
is connected to some others by an edge. We can simplify the graph by removing one edge and merging two clusters.
Lather rinse repeat. Eventually we get to a simple case of two populations and one edge. There's some gotcha's
if things get multiply connected but basically all of these operations can be efficiently implemented as
boolean vectors of appropriate size.
*/
template <typename booleans>
class ColoredGraph
{
public:
struct DualEdge
{
public: // bits are
booleans left; // clusters in the left set
booleans right; // clusters in the right set
booleans edge; // edges in the boundary between
DualEdge(
booleans left,
booleans right,
booleans edge) noexcept
{
// order is well defined although meaningless
// except that it makes comparisons faster
// since the edges are not directed
if (left < right)
{
this->left = left;
this->right = right;
}
else
{
this->left = right;
this->right = left;
}
this->edge = edge;
};
inline bool same_as(const DualEdge &de) const noexcept
{
return left == de.left && right == de.right;
}
DualEdge() = default;
};
std::vector<booleans> nodes;
std::vector<DualEdge> duals;
booleans removed;
ColoredGraph() = default;
// implement move semantics
ColoredGraph(std::vector<booleans> &nodes,
std::vector<DualEdge> &duals,
booleans removed) noexcept
: nodes(nodes), duals(duals), removed(removed){};
ColoredGraph(ColoredGraph &&other) noexcept
: nodes(other.nodes), duals(other.duals), removed(other.removed){};
ColoredGraph &operator=(ColoredGraph &&other) noexcept
{
if (this != other)
{
this->nodes = other.nodes;
this->duals = other.duals;
this->removed = other.removed;
}
return *this;
}
// copy constructor
ColoredGraph(const ColoredGraph &other) noexcept
: nodes(other.nodes), duals(other.duals), removed(other.removed){};
inline bool isSimple() const noexcept
{
return duals.size() == 1;
}
inline booleans left() const noexcept
{
return duals[0].left;
}
inline booleans right() const noexcept
{
return duals[0].right;
}
inline booleans edge() const noexcept
{
return duals[0].edge;
}
std::vector<ColoredGraph> simplify() const noexcept
{
std::vector<booleans> nodes;
nodes.reserve(this->nodes.size() - 1);
std::vector<DualEdge> duals;
duals.reserve(this->duals.size() - 1);
std::vector<ColoredGraph> graphs;
graphs.reserve(this->duals.size());
for (unsigned int i = 0; i < this->duals.size(); i++)
{
DualEdge remove = this->duals[i];
// we don't care in what order the edges are removed as long as
// some order is tried for every instance. This will not eliminate
// all duplicates because the details of the graph may only allow a
// partial ordering but it drastically reduces the combinitoric explosion
if (remove.edge < this->removed)
continue; // someone else will handle this
nodes.clear();
duals.clear();
// construct a simpler graph by removing the indicated edge
// since left and right are disjoint this is pretty easy for the nodes
booleans new_node = remove.left | remove.right; // the merged result
for (auto np : this->nodes)
if (!(np & new_node)) // skip the two we're merging
nodes.push_back(np);
nodes.push_back(new_node); // add the merged node
// for the edges we have to see if two or more edges collapsed into one
for (unsigned int j = 0; j < this->duals.size(); j++)
{
// skip the one we're removing
if (i == j)
continue;
DualEdge de = this->duals[j];
unsigned int k;
// this is a rapid test for the interesting cases. because of the disjunction of the
// nodes this is equivalent to (de.left == remove.left || de.left == remove.right)
if (de.left & new_node)
{ // look to see if this edge already exists
if (!(de.right & new_node))
{
DualEdge nde{de.right, new_node, de.edge};
for (k = 0; k < duals.size(); ++k)
if (nde.same_as(duals[k]))
{
duals[k].edge |= nde.edge; // found it OR it in
break;
}
if (k == duals.size())
duals.push_back(nde); // new edge
}
}
else if (de.right & new_node) // same for the right
{
DualEdge nde{de.left, new_node, de.edge};
for (k = 0; k < duals.size(); ++k)
if (nde.same_as(duals[k]))
{
duals[k].edge |= nde.edge;
break;
}
if (k == duals.size())
duals.push_back(nde);
}
else
{ // nothing to see here copy it forward
duals.push_back(de);
}
}
graphs.push_back(ColoredGraph(nodes, duals, this->removed | remove.edge));
}
return graphs;
};
};
template <typename coordinate, typename color, typename booleans>
class ColoredBoundary
{
std::vector<ColoredSegment<coordinate, color>> boundary;
std::vector<ColoredEdge<coordinate, color>> edges;
std::vector<ColoredPoint<coordinate>> vertices;
friend class ColoredMap<coordinate, color>;
color colorful;
public:
void setColorful(const int colors) noexcept
{
this->colorful = colors;
std::sort(vertices.begin(), vertices.end());
std::sort(boundary.begin(), boundary.end());
}
color getColorful() const noexcept
{
return colorful;
};
inline void addSegment(ColoredSegment<coordinate, color> segment)
{
boundary.push_back(segment);
};
void addSegment(
ColoredSlope slope,
int i,
int j,
color clockwise,
color widdershins,
double weight) noexcept
{
addSegment(ColoredSegment<coordinate, color>(slope, (coordinate)i, (coordinate)j, clockwise, widdershins, (float)weight));
}
void addSegment(
ColoredSlope slope,
int i,
int j,
color clockwise,
color widdershins) noexcept
{
addSegment(ColoredSegment<coordinate, color>(slope, (coordinate)i, (coordinate)j, clockwise, widdershins, 0));
}
void addSegment(
ColoredPoint<coordinate> tail,
ColoredPoint<coordinate> head,
color clockwise,
color widdershins,
float weight) noexcept
{
assert(head.adjacent(tail));
if (head < tail)
{
std::swap(tail, head);
std::swap(clockwise, widdershins);
}
if (tail.i == head.i)
{
addSegment(ColoredSegment<coordinate, color>(ColoredVertical, tail.i, tail.j, clockwise, widdershins, weight));
return;
}
switch (head.j - tail.j)
{
case 1:
addSegment(ColoredSegment<coordinate, color>(ColoredRight, tail.i, tail.j, clockwise, widdershins, weight));
return;
case 0:
addSegment(ColoredSegment<coordinate, color>(ColoredHorizontal, tail.i, tail.j, clockwise, widdershins, weight));
return;
case -1:
addSegment(ColoredSegment<coordinate, color>(ColoredLeft, tail.i, head.j, widdershins, clockwise, weight));
return;
}
};
void addSegment(
ColoredPoint<coordinate> tail,
ColoredPoint<coordinate> head,
color clockwise,
color widdershins,
double weight) noexcept
{
addSegment(tail, head, clockwise, widdershins, (float)weight);
};
void addSegment(
ColoredPoint<coordinate> tail,
ColoredPoint<coordinate> head,
color clockwise,
color widdershins) noexcept
{
addSegment(tail, head, clockwise, widdershins, 0);
};
void addVertex(ColoredPoint<coordinate> vertex) noexcept
{
vertices.push_back(vertex);
};
std::vector<ColoredPoint<coordinate>> &getVertices() const noexcept
{
return vertices;
}
bool isVertex(ColoredPoint<coordinate> vertex) const noexcept
{
return std::binary_search(vertices.begin(), vertices.end(), vertex);
};
void addEdge(ColoredEdge<coordinate, color> &edge) noexcept
{
assert(edge.points.size() > 1);
auto point = edge.points.begin();
ColoredPoint<coordinate> head, tail = *point++;
double weight = edge.weight / (edge.points.size() - 1);
while (point < edge.points.end())
{
head = *point++;
addSegment(tail, head, edge.clockwise, edge.widdershins, weight);
tail = head;
}
edges.push_back(edge);
};
void addEdge(std::vector<ColoredPoint<coordinate>> points, color clockwise, color widdershins, double weight) noexcept
{
ColoredEdge<coordinate, color> nce(points, clockwise, widdershins, weight);
addEdge(nce);
};
void addEdge(std::vector<ColoredPoint<coordinate>> points, color clockwise, color widdershins) noexcept
{
addEdge(points, clockwise, widdershins, 0.0);
};
void addEdge(ColoredChain<coordinate, color> &chain) noexcept
{
std::vector<ColoredPoint<coordinate>> points;
points.reserve(chain.size() + 1);
ColoredSegment<coordinate, color> *segment = chain.front();
color clockwise = segment->clockwise;
color widdershins = segment->widdershins;
double weight = 0;
ColoredPoint<coordinate> point = chain.tail();
if (segment->head() == point)
std::swap(clockwise, widdershins);
points.push_back(point);
for (auto csp = chain.begin(); csp < chain.end(); ++csp)
{
segment = *csp;
if (point == segment->tail())
{
assert(clockwise == segment->clockwise && widdershins == segment->widdershins);
point = segment->head();
}
else
{
assert(clockwise == segment->widdershins && widdershins == segment->clockwise);
point = segment->tail();
}
weight += segment->weight;
points.push_back(point);
}
ColoredEdge<coordinate, color> edge(points, clockwise, widdershins, weight);
edges.push_back(edge);
};
std::vector<bool> *done;
// find next segment adjacent to a point
ColoredSegment<coordinate, color> *find_next_segment(
ColoredPoint<coordinate> point) noexcept
{
// we know the next adjacent segment can't be far away
ColoredSegment<coordinate, color> low, high;
low.i = point.i - 1;
low.j = point.j - 1;
low.slope = ColoredHorizontal;
high.i = point.i + 1;
high.j = point.j + 2; // strict upper bound
high.slope = ColoredHorizontal;
// so it's contained in a small interval
// that we can find quickly since they are sorted
auto lower = std::lower_bound(boundary.begin(), boundary.end(), low);
auto upper = std::upper_bound(lower, boundary.end(), high);
// and then we use brute force
for (auto cp = lower; cp != upper; ++cp)
{
ColoredSegment<coordinate, color> *peek = &(*cp);
if (!(*done)[cp - boundary.begin()])
{
ColoredSegment<coordinate, color> *candidate = &(*cp);
if (!candidate->adjacent(point))
continue;
(*done)[cp - boundary.begin()] = true;
return candidate;
}
}
return nullptr;
}
// find any segment we haven't considered yet
ColoredSegment<coordinate, color> *find_next_segment() noexcept
{
for (auto csp = boundary.begin(); csp != boundary.end(); ++csp)
if (!(*done)[csp - boundary.begin()])
{
ColoredSegment<coordinate, color> *candidate = &(*csp);
(*done)[csp - boundary.begin()] = true;
return candidate;
}
return nullptr;
}
// this is the other hard problem but uses
// much less total time than the lookup
std::vector<ColoredEdge<coordinate, color>> &getEdges() noexcept
{
done = new std::vector<bool>(boundary.size(), false);
edges.clear();
ColoredChain<coordinate, color> chain;
ColoredSegment<coordinate, color> *segment;
// look for open edges starting and ending at a vertex
for (auto vp = vertices.begin(); vp < vertices.end();)
{
ColoredPoint<coordinate> vertex = *vp;
ColoredSegment<coordinate, color> *segment = find_next_segment(vertex);
if (!segment)
{
vp++;
continue;
}
chain.clear();
chain.push_back(segment);
ColoredPoint<coordinate> point;
if (segment->tail() == vertex)
point = segment->head();
else
point = segment->tail();
while (!isVertex(point))
{
segment = find_next_segment(point);
if (segment == nullptr)
segment = find_next_segment(point);
if (segment == nullptr)
break;
chain.push_back(segment);
if (segment->tail() == point)
point = segment->head();
else
point = segment->tail();
}
addEdge(chain);
}
// now look for closed edges
while ((segment = find_next_segment()))
{
chain.clear();
chain.push_back(segment);
ColoredPoint<coordinate> tail = segment->tail();
ColoredPoint<coordinate> head = segment->head();
while ((segment = find_next_segment(head)))
{
chain.push_back(segment);
head = chain.head();
if (head == tail)
break;
}
assert(head == tail);
addEdge(chain);
}
delete done;
return edges;
}
std::unique_ptr<ColoredMap<coordinate, color>> getMap() noexcept
{
return std::unique_ptr<ColoredMap<coordinate, color>>(new ColoredMap<coordinate, color>(boundary));
}
std::unique_ptr<ColoredGraph<booleans>> getDualGraph() noexcept
{
std::vector<booleans> nodes(colorful - 1);
std::vector<typename ColoredGraph<booleans>::DualEdge> duals;
duals.reserve(edges.size());
for (int i = 1; i < colorful; i++)
{
nodes[i - 1] = 1 << (i - 1);
}
for (unsigned int i = 0; i < edges.size(); i++)
{
typename ColoredGraph<booleans>::DualEdge dual(1 << (edges[i].widdershins - 1), 1 << (edges[i].clockwise - 1), 1 << i);
unsigned int k;
for (k = 0; k < duals.size(); ++k)
if (dual.same_as(duals[k]))
{
duals[k].edge |= dual.edge; // found it OR it in
break;
}
if (k == duals.size())
duals.push_back(dual); // new edge
}
ColoredGraph<booleans> *graph = new ColoredGraph<booleans>(nodes, duals, 0);
return std::unique_ptr<ColoredGraph<booleans>>(graph);
}
void clear() noexcept
{
boundary.clear();
edges.clear();
vertices.clear();
colorful = (color)0;
};
ColoredBoundary() = default;
~ColoredBoundary() = default;
};
}
#endif /* _EPP_BOUNDARY_H */ | true |
619f2ede46b9fe1dab147765c53dd9b8812666ff | C++ | WalkerDongGithub/undergraduate_projects | /面向对象程序设计基础/template/typetraits.cpp | UTF-8 | 1,874 | 3.25 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
template <typename Iter>
void destruct(Iter where)
{
typedef typename std::iterator_traits<Iter>::value_type value_type;
//std::cout << typeid(value_type).name() << '\n';
//std::cout << typeid(Iter).name();
where->~value_type();
}
struct SimpleIterator
{
typedef std::random_access_iterator_tag iterator_category;
typedef int value_type;
typedef ptrdiff_t difference_type;
typedef int *pointer;
typedef int &reference;
int *pos;
int &operator*() { return *pos; }
int *operator->() { return &(operator*()); }
};
class ClassName
{
public:
int foo(int) { return 42; }
};
template <typename K,size_t N>
struct Array //注意,合成的拷贝构造函数是默认复制数组元素的
{
K arr[N];
};
struct Data
{
Array<char, 20> arr;
int x;
double d;
};
struct TestFunc
{
void foo(){}
//void bar(){}
};
template <typename K>
void test(K k)
{
using Foo = decltype(k.foo());
//using Bar = decltype(k.bar()); //CE
}
int main()
{
TestFunc tf;
test(tf);
/*cout << boolalpha;
cout << is_nothrow_copy_assignable<string>::value << endl;
cout << is_nothrow_copy_assignable<vector<int>>::value << endl;
cout << is_nothrow_copy_assignable<int>::value << endl;
cout << is_nothrow_copy_assignable<int[10]>::value << endl; //false
cout << is_nothrow_copy_assignable<Array<int,10>>::value << endl; //true
cout << is_nothrow_copy_assignable<Data>::value << endl; //true
*/
/*int a = 0;
int *p = &a;
using Int = int;
p->~Int(); //看来只是不能用int这个词而已
//destruct(p);
//typedef void func(SimpleIterator *);
int (ClassName::*pmf)(int) = &ClassName::foo;
auto pderef = &SimpleIterator::operator*;*/
}
| true |
8394b2339f6232713a1dfb66aaa2ba9d8c4f8479 | C++ | 15831944/bastionlandscape | /LuaPlus/Samples/UnitTest++/src/tests/TestTestRunner.cpp | UTF-8 | 3,838 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "../UnitTest++.h"
#include "RecordingReporter.h"
#include "../ReportAssert.h"
#include "../TestList.h"
#include "../TimeHelpers.h"
using namespace UnitTest;
namespace
{
struct MockTest : public Test
{
MockTest(char const* testName, bool const success_, bool const assert_)
: Test(testName)
, success(success_)
, asserted(assert_)
{
}
virtual void RunImpl(TestResults& testResults_) const
{
if (asserted)
ReportAssert("desc", "file", 0);
else if (!success)
testResults_.OnTestFailure("filename", 0, "", "message");
}
bool success;
bool asserted;
};
struct TestRunnerFixture
{
RecordingReporter reporter;
TestList list;
};
TEST_FIXTURE(TestRunnerFixture, TestStartIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
RunAllTests(reporter, list);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestFinishIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
RunAllTests(reporter, list);
CHECK_EQUAL(1, reporter.testFinishedCount);
CHECK_EQUAL("goodtest", reporter.lastFinishedTest);
}
class SlowTest : public Test
{
public:
SlowTest() : Test("slow", "filename", 123) {}
virtual void RunImpl(TestResults&) const
{
TimeHelpers::SleepMs(20);
}
};
TEST_FIXTURE(TestRunnerFixture, TestFinishIsCalledWithCorrectTime)
{
SlowTest test;
list.Add(&test);
RunAllTests(reporter, list);
CHECK (reporter.lastFinishedTestTime >= 0.005f && reporter.lastFinishedTestTime <= 0.050f);
}
TEST_FIXTURE(TestRunnerFixture, FailureCountIsZeroWhenNoTestsAreRun)
{
CHECK_EQUAL(0, RunAllTests(reporter, list));
CHECK_EQUAL(0, reporter.testRunCount);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, CallsReportFailureOncePerFailingTest)
{
MockTest test1("test", false, false);
list.Add(&test1);
MockTest test2("test", true, false);
list.Add(&test2);
MockTest test3("test", false, false);
list.Add(&test3);
CHECK_EQUAL(2, RunAllTests(reporter, list));
CHECK_EQUAL(2, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, TestsThatAssertAreReportedAsFailing)
{
MockTest test("test", true, true);
list.Add(&test);
RunAllTests(reporter, list);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, FinishedTestsReportDone)
{
MockTest test1("test", true, false);
MockTest test2("test", false, false);
list.Add(&test1);
list.Add(&test2);
RunAllTests(reporter, list);
CHECK_EQUAL(2, reporter.summaryTestCount);
CHECK_EQUAL(1, reporter.summaryFailureCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestPassesForHighTimeThreshold)
{
SlowTest test;
list.Add(&test);
RunAllTests(reporter, list);
CHECK_EQUAL (0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestFailsForLowTimeThreshold)
{
SlowTest test;
list.Add(&test);
RunAllTests(reporter, list, 3);
CHECK_EQUAL (1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestHasCorrectFailureInformation)
{
SlowTest test;
list.Add(&test);
RunAllTests(reporter, list, 3);
CHECK_EQUAL (test.m_testName, reporter.lastFailedTest);
CHECK (std::strstr(test.m_filename, reporter.lastFailedFile));
CHECK_EQUAL (test.m_lineNumber, reporter.lastFailedLine);
CHECK (std::strstr(reporter.lastFailedMessage, "Global time constraint failed"));
CHECK (std::strstr(reporter.lastFailedMessage, "3ms"));
}
}
| true |
75ad0801e72c90d83d4abcc6fc035b0e25dbb93e | C++ | abasak24/SAGA-Bench | /src/dynamic/dyn_sssp.h | UTF-8 | 8,355 | 2.625 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef DYN_SSSP_H_
#define DYN_SSSP_H_
#include <limits>
#include <vector>
#include <algorithm>
#include "traversal.h"
#include "sliding_queue_dynamic.h"
#include "../common/timer.h"
#include "../common/pvector.h"
/* Algorithm: Incremental SSSP and SSSP from scratch */
template<typename T>
void SSSPIter0(T* ds, SlidingQueue<NodeID>& queue){
pvector<bool> visited(ds->num_nodes, false);
#pragma omp parallel
{
QueueBuffer<NodeID> lqueue(queue);
#pragma omp for schedule(dynamic, 64)
for(NodeID n=0; n < ds->num_nodes; n++){
if(ds->affected[n]){
float old_path = ds->property[n];
float new_path = kDistInf;
neighborhood<T> neigh = in_neigh(n, ds);
// pull new depth from incoming neighbors
for(neighborhood_iter<T> it = neigh.begin(); it != neigh.end(); it++){
new_path = std::min(new_path, ds->property[*it] + it.extractWeight());
}
bool trigger = (((new_path < old_path) && (new_path != kDistInf)));
if(trigger){
ds->property[n] = new_path;
//put the out-neighbors into active list
for(auto v: out_neigh(n, ds)){
bool curr_val = visited[v];
if(!curr_val){
if(compare_and_swap(visited[v], curr_val, true))
lqueue.push_back(v);
}
}
}
}
}
lqueue.flush();
}
}
template<typename T>
void dynSSSPAlg(T* ds, NodeID source){
std::cout << "Running dynamic SSSP" << std::endl;
Timer t;
t.Start();
SlidingQueue<NodeID> queue(ds->num_nodes);
// set all new vertices' rank to inf, otherwise reuse old values
#pragma omp parallel for schedule(dynamic, 64)
for(NodeID n = 0; n < ds->num_nodes; n++){
if(ds->property[n] == -1){
if(n == source) ds->property[n] = 0;
else ds->property[n] = kDistInf;
}
}
SSSPIter0(ds, queue);
queue.slide_window();
while(!queue.empty()){
//std::cout << "Not empty queue, Queue Size:" << queue.size() << std::endl;
pvector<bool> visited(ds->num_nodes, false);
#pragma omp parallel
{
QueueBuffer<NodeID> lqueue(queue);
#pragma omp for schedule(dynamic, 64)
for (auto q_iter = queue.begin(); q_iter < queue.end(); q_iter++){
NodeID n = *q_iter;
float old_path = ds->property[n];
float new_path = kDistInf;
neighborhood<T> neigh = in_neigh(n, ds);
// pull new depth from incoming neighbors
for(neighborhood_iter<T> it = neigh.begin(); it != neigh.end(); it++){
new_path = std::min(new_path, ds->property[*it] + it.extractWeight());
}
// valid depth + lower than before = trigger
bool trigger = (((new_path < old_path) && (new_path != kDistInf)));
if(trigger){
ds->property[n] = new_path;
for(auto v: out_neigh(n, ds)){
bool curr_val = visited[v];
if(!curr_val){
if(compare_and_swap(visited[v], curr_val, true))
lqueue.push_back(v);
}
}
}
}
lqueue.flush();
}
queue.slide_window();
}
// clear affected array to get ready for the next update round
#pragma omp parallel for schedule(dynamic, 64)
for(NodeID i = 0; i < ds->num_nodes; i++){
ds->affected[i] = false;
}
t.Stop();
ofstream out("Alg.csv", std::ios_base::app);
out << t.Seconds() << std::endl;
out.close();
}
template<typename T>
void SSSPStartFromScratch(T* ds, NodeID source, float delta){
std::cout <<"Running SSSP from scratch" << std::endl;
Timer t;
t.Start();
int num_edges_directed = ds->directed ? ds->num_edges : 2*ds->num_edges;
#pragma omp parallel for
for(NodeID n = 0; n < ds->num_nodes; n++)
ds->property[n] = kDistInf;
ds->property[source] = 0;
pvector<NodeID> frontier(num_edges_directed);
// two element arrays for double buffering curr=iter&1, next=(iter+1)&1
size_t shared_indexes[2] = {0, kMaxBin};
size_t frontier_tails[2] = {1, 0};
frontier[0] = source;
#pragma omp parallel
{
std::vector<std::vector<NodeID> > local_bins(0);
size_t iter = 0;
while (shared_indexes[iter&1] != kMaxBin) {
size_t &curr_bin_index = shared_indexes[iter&1];
size_t &next_bin_index = shared_indexes[(iter+1)&1];
size_t &curr_frontier_tail = frontier_tails[iter&1];
size_t &next_frontier_tail = frontier_tails[(iter+1)&1];
#pragma omp for nowait schedule(dynamic, 64)
for (size_t i=0; i < curr_frontier_tail; i++) {
NodeID u = frontier[i];
if (ds->property[u] >= delta * static_cast<float>(curr_bin_index)) {
neighborhood<T> neigh = out_neigh(u, ds);
for(neighborhood_iter<T> it = neigh.begin(); it != neigh.end(); it++){
float old_dist = ds->property[*it];
float new_dist = ds->property[u] + it.extractWeight();
if (new_dist < old_dist) {
bool changed_dist = true;
while (!compare_and_swap(ds->property[*it], old_dist, new_dist)){
old_dist = ds->property[*it];
if (old_dist <= new_dist) {
changed_dist = false;
break;
}
}
if (changed_dist) {
size_t dest_bin = new_dist/delta;
if (dest_bin >= local_bins.size()) {
local_bins.resize(dest_bin+1);
}
local_bins[dest_bin].push_back(*it);
}
}
}
}
}
for (size_t i=curr_bin_index; i < local_bins.size(); i++) {
if (!local_bins[i].empty()) {
#pragma omp critical
next_bin_index = std::min(next_bin_index, i);
break;
}
}
#pragma omp barrier
#pragma omp single nowait
{
//t.Stop();
//PrintStep(curr_bin_index, t.Millisecs(), curr_frontier_tail);
//t.Start();
curr_bin_index = kMaxBin;
curr_frontier_tail = 0;
}
if (next_bin_index < local_bins.size()) {
size_t copy_start = fetch_and_add(next_frontier_tail,
local_bins[next_bin_index].size());
std::copy(local_bins[next_bin_index].begin(),
local_bins[next_bin_index].end(), frontier.data() + copy_start);
local_bins[next_bin_index].resize(0);
}
iter++;
#pragma omp barrier
}
//#pragma omp single
//std::cout << "took " << iter << " iterations" << std::endl;
}
t.Stop();
ofstream out("Alg.csv", std::ios_base::app);
out << t.Seconds() << std::endl;
out.close();
}
#endif // DYN_SSSP_H_ | true |
3f0285e32cc2fac5d2a38ebaca69c2a40b9c7e16 | C++ | alexandraback/datacollection | /solutions_5639104758808576_0/C++/zentropy/cpptest.cpp | UTF-8 | 549 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int main()
{
static const unsigned int maxsize = 1000;
char buff[maxsize+1] = { 0 };
unsigned int nCases = 0;scanf("%d",&nCases);
for(unsigned int iCases = 1;iCases <= nCases;++iCases)
{
unsigned int smax = 0;scanf("%d%s",&smax,buff);
unsigned int count = 0,ans = 0,p = 0;
for(size_t len = strlen(buff);p < len;++p)
{
unsigned int v = buff[p] - '0';
if(p > count) { ans += p - count;count = p; }
count += v;
}
printf("Case #%u: %u\n",iCases,ans);
}
return 0;
} | true |
5f239bb66b3502700998d8733bb0e72e61fa301a | C++ | henrybear327/Sandbox | /Codeforces/Educational/1/C/main_old_but_workig_code.cpp | UTF-8 | 1,394 | 2.921875 | 3 | [] | no_license | /*
AC if you use long double
WTF
*/
#include <bits/stdc++.h>
// LLONG_MIN LLONG_MAX INT_MIN INT_MAX
#define PI (atan(1) * 4)
#define double long double
using namespace std;
#define INF 1e9
inline double atan2_process(double x, double y)
{
double ans = atan2(y, x);
if (ans < 0.0)
ans += 2 * PI;
return ans;
}
inline double get_small_angle(double x)
{
return x > PI ? 2 * PI - x : x;
}
typedef struct data {
int x, y;
double s;
int idx;
} Data;
bool cmp(Data a, Data b)
{
return a.s < b.s;
}
int main()
{
int n;
scanf("%d", &n);
Data inp[n];
for (int i = 0; i < n; i++) {
scanf("%d %d", &inp[i].x, &inp[i].y);
inp[i].s = atan2_process(inp[i].x, inp[i].y);
inp[i].idx = i + 1;
}
sort(inp, inp + n, cmp);
/*
for (int i = 0; i < n; i++)
printf("%d %d %f %d\n", inp[i].x, inp[i].y, inp[i].s, inp[i].idx);
*/
double ans = INF;
int ans1 = -1, ans2 = -1;
for (int i = 1; i < n; i++) {
if (get_small_angle(inp[i].s - inp[i - 1].s) < ans) {
ans = get_small_angle(inp[i].s - inp[i - 1].s);
ans1 = inp[i - 1].idx;
ans2 = inp[i].idx;
}
}
if (get_small_angle(inp[n - 1].s - inp[0].s) < ans)
printf("%d %d\n", inp[n - 1].idx, inp[0].idx);
else
printf("%d %d\n", ans1, ans2);
return 0;
}
| true |
cb43396375842d93191131dd93e767792377b6f9 | C++ | MRYoungITO/Class | /项目13_项目练习1/项目13_项目练习1/Monster.cpp | GB18030 | 1,184 | 3.390625 | 3 | [] | no_license | #include "Monster.h"
#include "SpriteStone.h"
#define MONSTER_LEVEL_FACTOR 1000
Monster::Monster(int level, const string& category)
{
this->level = level;
this->category = category;
}
/*
1ޣֵ 100 ʯ
2ޣֵ 200 ʯ
3ޣֵ 500 ʯ
4ޣֵ 1000 ʯ
5ޣֵ 2000 ʯ
6ޣֵ 5000 ʯ
7ޣֵ 10000 ʯ
8ޣֵ 20000 ʯ
9ޣֵ 100000 ʯ
*/
SpriteStone Monster::getValue() const
{
int stoneCount[] = { 100,200,500,1000,2000,5000,10000,20000,100000 };
int count = stoneCount[level - 1];
return SpriteStone(count, SpriteStoneLevel::PRIMARY_LEVEL);
}
int Monster::getPower() const
{
int ret = level * MONSTER_LEVEL_FACTOR;
return ret;
}
ostream& operator<<(ostream& os, const Monster& monster)
{
os << monster.level << "" << monster.category << "";
return os;
}
bool operator==(const Monster& one, const Monster& other)
{
if (one.category == other.category &&
one.level == other.level) {
return true;
}
else {
return false;
}
}
| true |
4b1804debadd700fc863267f30ee6d71b34326cb | C++ | ZenasAlex/MiniRPG | /Player.cpp | UTF-8 | 3,359 | 2.703125 | 3 | [] | no_license | #include "Player.h"
#include "ofGraphics.h"
#include "ofAppRunner.h"
void Player::start(float x, float y, float width, float height){
this->x = x;
this->y = y;
this->w = width;
this->h = height;
center.set(x + w / 2, y + h / 2);
//initPos.set(x, y);
swordRadius = 15;
cooldown = 2;
currentTime = ofGetElapsedTimeMillis();
speedX = 4;
speedY = 4;
up = false;
down = false;
left = false;
right = false;
imgRight.load("PersonajeRight.png");
imgLeft.load("PersonajeLeft.png");
imgUp.load("PersonajeUp.png");
imgDown.load("PersonajeDown.png");
imgRight.resize(width, height);
imgLeft.resize(width, height);
imgDown.resize(width, height);
imgUp.resize(width, height);
emptyHeart.load("heart vacio.png");
emptyHeart.resize(width, height);
fullHeart.load("heart.png");
fullHeart.resize(width, height);
emptyMN.load("mana vacio.png");
emptyMN.resize(width, height);
fullMN.load("mana.png");
fullMN.resize(width, height);
HPMeter_x = 700;
HPMeter_y = 1;
MNMeter_x = 700;
MNMeter_y = 61;
maxHP = 5;
maxMP = 5;
HP = 5;
MP = 5;
}
void Player::update(){
float deltaTime = ofGetElapsedTimeMillis() - currentTime;
acumulator += deltaTime;
currentTime = ofGetElapsedTimeMillis();
if (acumulator > timer) {
cooldown = true;
}
if (up) {
y -= speedY;
direction = UP;
}
else if (down) {
y += speedY;
direction = DOWN;
}
if (right) {
x += speedX;
direction = LEFT;
}
else if (left) {
x -= speedX;
direction = RIGTH;
}
center.set(x + w / 2, y + h / 2);
}
void Player::draw(){
ofSetColor(255);
if (imgDown.isAllocated()) {
imgDown.draw(x, y);
}
for (int i = 0; i < maxHP; i++) {
emptyHeart.draw(HPMeter_x + i *(32 + 10), HPMeter_y);
}
for (int i = 0; i < HP; i++) {
fullHeart.draw(HPMeter_x + i *(32 + 10), HPMeter_y);
}
for (int i = 0; i < maxMP; i++) {
emptyMN.draw(MNMeter_x + i *(32 + 10), MNMeter_y);
}
for (int i = 0; i < MP; i++) {
fullMN.draw(MNMeter_x + i *(32 + 10), MNMeter_y);
}
ofNoFill;
if (!cooldown) {
switch (direction) {
case UP:
ofDrawCircle(center.x, center.y - h / 2 - swordRadius, swordRadius);
break;
case DOWN:
ofDrawCircle(center.x, center.y + h / 2 + swordRadius, swordRadius);
break;
case LEFT:
ofDrawCircle(center.x-w / 2 - swordRadius, center.y, swordRadius);
break;
case RIGTH:
ofDrawCircle(center.x+w / 2 + swordRadius, center.y, swordRadius);
break;
}
}
}
void Player::attack()
{
if (cooldown == true) {
acumulator = 0;
cooldown = false;
}
if (MP > 0) {
MP--;
}
}
void Player::stop(){
up = false;
down = false;
left = false;
right = false;
}
void Player::moveUp(){
up = true;
}
void Player::moveDown(){
down = true;
}
void Player::moveLeft(){
left = true;
}
void Player::moveRight(){
right = true;
}
void Player::stopUp(){
up = false;
}
void Player::stopDown(){
down = false;
}
void Player::stopRight(){
right = false;
}
void Player::stopLeft(){
left = false;
}
void Player::hit()
{
if (HP > 0) {
HP--;
}
}
void Player::HPUp()
{
if (HP < maxHP) {
HP++;
}
}
void Player::MPUp()
{
if (MP < maxMP) {
MP = 5;
}
}
/*void Player::dead()
{
if (HP <= 0) {
initPos.set(50, 150);
}
}*/
| true |
2136f03e2194dc17fada16822632d171f41e5d7e | C++ | hydrodog/C-2016S | /session02/s03_arrays.cc | UTF-8 | 463 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int a[100]; // 100 int = 100 * sizeof(int) = 400 bytes
int b[500000000]; // too big for windows
int n = 500000000; // windows hack , should work
int b[n]; // dynamiccally allocated on heap
int c[2*5*3]; // will calculate at compile time = 30
cout << 365 * 24 * 60 * 60; // constant expressions
int n;
cin >> n;
int d[n]; // int* p = new int[n];
// delete [] p;
}
| true |
0a7e107e8c6018b823a71a20e33c5bcf74745d50 | C++ | Ancaor/IG | /Practica4/esqueleto_qt/o3dr.cpp | UTF-8 | 5,662 | 2.828125 | 3 | [] | no_license | #include "o3dr.h"
O3DR::O3DR()
{
tapa_inferior = 0;
tapa_superior = 0;
}
/*********************************************************************************
Funcion que ajusta a size la variable PUNTOS_PERFIL
*********************************************************************************/
void O3DR::setPuntosPerfil(int size){
PUNTOS_PERFIL=size;
}
/*********************************************************************************
Funcion que realiza la revolucion por barrido respecto al eje y.
*********************************************************************************/
void O3DR::revolucion_por_barrido_y(float angulo)
{
int i,j;
float alpha;
int tamanio = vertices.size();
for(i=1;i < SECCIONES ; i++){
alpha = (i*angulo)/SECCIONES; // 2.0*M_PI
for(j=0;j<tamanio;j++){
float x_rotado= ((vertices[j].x) * cos(alpha) + (vertices[j].z) * sin(alpha));
float z_rotado= (-(vertices[j].x)*sin(alpha) + (vertices[j].z)*cos(alpha) );
_vertex3f rotado = _vertex3f(x_rotado,vertices[j].y,z_rotado);
vertices.push_back(rotado);
}
}
}
/*********************************************************************************
Funcion que realiza la revolucion por barrido respecto aal eje z. Util para generar
la esfera .
*********************************************************************************/
void O3DR::revolucion_por_barrido_z(float angulo)
{
int i,j;
float x_rotado;
float y_rotado;
float alpha;
int tamanio = vertices.size();
for(i = 1;i <= SECCIONES; i++){
alpha = (i*angulo)/SECCIONES;
for(j=0;j<tamanio;j++){
x_rotado= ((vertices[j].x) * cos(alpha) - (vertices[j].y) * sin(alpha));
y_rotado= ((vertices[j].x)*sin(alpha) + (vertices[j].y)*cos(alpha) );
_vertex3f rotado = _vertex3f(x_rotado,y_rotado,vertices[j].z);
vertices.push_back(rotado);
}
}
}
/*********************************************************************************
Funcion que genera las caras del cuerpo del objeto, es decir, sin las tapas
*********************************************************************************/
void O3DR::generar_caras()
{
int i,j;
int PUNTOS = vertices.size();
for(i = 0; i < PUNTOS_PERFIL-1 ; i++){
for(j=0; j < SECCIONES ; j++){
//Triangulo Par
triangles.push_back(_vertex3i( ((j*PUNTOS_PERFIL)+(i+1))%PUNTOS ,((j*PUNTOS_PERFIL)+i)%PUNTOS , (((j+1)*PUNTOS_PERFIL)+i )%PUNTOS) );
//Triangulo Impar
triangles.push_back(_vertex3i( (((j+1)*PUNTOS_PERFIL)+i)%PUNTOS ,(((j+1)*PUNTOS_PERFIL)+(i+1))%PUNTOS , ((j*PUNTOS_PERFIL)+(i+1))%PUNTOS ) );
}
}
}
/*********************************************************************************
Funcion que genera las caras de la tapa superior
*********************************************************************************/
void O3DR::generar_tapa_superior(int indice_centro)
{
int j;
int PUNTOS = vertices.size()-1;
for(j = 0; j<SECCIONES-1;j++){
triangles.push_back(_vertex3i( indice_centro,((j*PUNTOS_PERFIL)+(PUNTOS_PERFIL-1))%PUNTOS , (((j+1)*PUNTOS_PERFIL)+(PUNTOS_PERFIL-1) )%PUNTOS) );
}
triangles.push_back(_vertex3i(indice_centro,(((j*PUNTOS_PERFIL)+(PUNTOS_PERFIL-1))%PUNTOS),PUNTOS_PERFIL-1));
}
/*********************************************************************************
Funcion que genera las caras de la tapa inferior
*********************************************************************************/
void O3DR::generar_tapa_inferior(int indice_centro)
{
int j;
int PUNTOS = vertices.size()-1;
for(j = 0; j<SECCIONES;j++){
triangles.push_back(_vertex3i( ((j*PUNTOS_PERFIL))%PUNTOS ,indice_centro, (((j+1)*PUNTOS_PERFIL) )%PUNTOS) );
}
}
/*********************************************************************************
Funcion que busca en el perfil dado si tiene tapas.
*********************************************************************************/
void O3DR::encontrar_tapas()
{
for(auto it = vertices.begin();it < vertices.end();it++){
if((it->x == 0.0) && (it->z == 0.0) ){
if(!tapa_inferior && (it->y)<0.0){
posicion_tapa_inferior = *it;
tapa_inferior=true;
it = vertices.erase(it);
PUNTOS_PERFIL--;
}
if(!tapa_superior && (it->y)>0.0){
posicion_tapa_superior = *it;
tapa_superior = true;
it = vertices.erase(it);
PUNTOS_PERFIL--;
}
}
}
}
/*********************************************************************************
Funcion que genera el objeto por revolucion:
1- primero encuentra las tapas
2- despues quita las tapas si tiene y realiza la revolucion por barrido al
cuerpo del objeto
3- si el cuerpo tiene mas de 2 puntos puede generar sus caras
4- en funcion del numero de tapas qe tuviera las genera.
*********************************************************************************/
void O3DR::generar_objeto_de_revolucion(int angulo)
{
SECCIONES--;
encontrar_tapas();
float angulo_radianes = angulo*(M_PI/180.0);
revolucion_por_barrido_y(angulo_radianes);
if(PUNTOS_PERFIL>1)
generar_caras();
if(tapa_inferior){
vertices.push_back(posicion_tapa_inferior);
generar_tapa_inferior(vertices.size()-1);
}
if(tapa_superior){
vertices.push_back(posicion_tapa_superior);
generar_tapa_superior(vertices.size()-1);
}
}
| true |
1769e3c07a5415d3c4c47c3b1f137da7d8132159 | C++ | changjunpyo/algorithmPS | /leetcode/1363_largest_multiple_of_three_HD.cpp | UTF-8 | 2,532 | 3.1875 | 3 | [] | no_license | class Solution {
public:
string largestMultipleOfThree(vector<int>& digits) {
vector<int> three_one;
vector<int> three_two;
vector<int> three_three;
for (int i=0; i<digits.size(); i++){
if (digits[i]%3 ==0)
three_three.push_back(digits[i]);
else if (digits[i]%3 ==1)
three_one.push_back(digits[i]);
else
three_two.push_back(digits[i]);
}
sort(three_one.begin(), three_one.end(), greater<int>());
sort(three_two.begin(), three_two.end(), greater<int>());
sort(three_three.begin(), three_three.end(), greater<int>());
int x = (three_one.size()/3)*3;
int y = (three_two.size()/3)*3;
bool oneIsBigger= three_one.size() < three_two.size() ? false : true;
int sz = three_one.size() < three_two.size() ? three_one.size() : three_two.size();
if (x+y >= sz*2){
for (int i=0; i<x; i++){
three_three.push_back(three_one[i]);
}
for (int i=0; i<y; i++){
three_three.push_back(three_two[i]);
}
for (int i=0; i<3; i++){
if (x == three_one.size() || y==three_two.size())
break;
three_three.push_back(three_one[x++]);
three_three.push_back(three_two[y++]);
}
}
else {
for (int i=0; i<sz; i++){
three_three.push_back(three_one[i]);
three_three.push_back(three_two[i]);
int new_x = ((three_one.size()-i-1)/3)*3;
int new_y = ((three_two.size()-i-1)/3)*3;
if (new_x+new_y > (sz-i-1)*2){
for (int j=i+1;j<i+new_x+1; j++){
three_three.push_back(three_one[j]);
}
for (int j=i+1; j<i+new_y+1; j++){
three_three.push_back(three_two[j]);
}
break;
}
}
}
sort(three_three.begin(), three_three.end(), greater<int>());
if (three_three.size() == 0)
return "";
else if (three_three[0] == 0)
return "0";
else{
string ans;
for (int i=0; i<three_three.size(); i++){
ans.push_back(three_three[i]+'0');
}
return ans;
}
}
}; | true |
bc0b0c1ee8eb147e980dbfe0bce7f3a145659fde | C++ | vrunge/listChallenge | /src/SinglyLinkedList5.h | UTF-8 | 496 | 2.65625 | 3 | [] | no_license | #ifndef LINKED_LIST2_H
#define LINKED_LIST2_H
#include "Point.h"
#include <vector>
class SinglyLinkedList5
{
private:
Point * head;
Point * currentPosition;
Point * lastActivePosition;
Point * tail;
unsigned int lengthList;
public:
SinglyLinkedList5();
~SinglyLinkedList5();
void move();
void addPoint(unsigned int a, unsigned int b);
void deleteNxtPointAndMove();
void initializeCurrentPosition();
unsigned int getLength();
};
#endif
| true |
a42d58fae2daecf2e8450355d0d803f11abbb069 | C++ | robotology/idyntree | /examples/cxx/InverseKinematics/iDynTreeExampleInverseKinematics.cpp | UTF-8 | 8,462 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | // SPDX-FileCopyrightText: Fondazione Istituto Italiano di Tecnologia (IIT)
// SPDX-License-Identifier: BSD-3-Clause
/**
* @ingroup idyntree_tutorials
*
* A tutorial on how to use the InverseKinematics class in iDynTree
*
*/
// C headers
#include <cmath>
#include <cstdlib>
// C++ headers
#include <string>
#include <vector>
// iDynTree headers
#include <iDynTree/KinDynComputations.h>
#include <iDynTree/ModelIO/ModelLoader.h>
#include <iDynTree/InverseKinematics.h>
int main(int argc, char *argv[])
{
// Assume that the model is found in the current working directory
// In production code, the model is tipical found using some strategy
std::string modelFile = "kr16_2.urdf";
// To make sure that the serialization of the joint is exactly the one that we need,
// it is a good practice to explicitly specify the desired joint/degrees of freedom
// serialization. Note that in production code this can be loaded from some parameter
std::vector<std::string> consideredJoints
= {"joint_a1", "joint_a2", "joint_a3", "joint_a4", "joint_a5", "joint_a6"};
// Helper class to load the model from an external format
// Note: the loadReducedModelFromFile method permits to specify also a subset of the
// joint of the robot, hence the name "reduced". As we are specifying all the joints
// of the robot (we are just specifying them to make sure that the joint serialization
// is the one that we desire) we are actually loading a "full" model
iDynTree::ModelLoader mdlLoader;
bool ok = mdlLoader.loadReducedModelFromFile(modelFile, consideredJoints);
if (!ok) {
std::cerr << "iDynTreeExampleInverseKinematics: impossible to load the following model in a KinDynComputations class:" << std::endl
<< mdlLoader.model().toString() << std::endl;
}
// Create iDynTree::KinDynComputations, that can be used to compute the Forward Kinematics of robot
// We compute the Forward kinematics position initially to get a reasonable starting point for a cartesian position,
// and then to verify that the obtained Inverse Kinematics solution is actually closed to the desired one
iDynTree::KinDynComputations kinDynMeas;
ok = kinDynMeas.loadRobotModel(mdlLoader.model());
if (!ok) {
std::cerr << "iDynTreeExampleInverseKinematics: impossible to load model from " << modelFile << std::endl;
return EXIT_FAILURE;
}
// As different frames are available on the robot, we need to explicitly specify the frames used as base
// and as end-effector frames
std::string baseFrame = "base_link";
std::string endEffectorFrame = "tool0";
// All units in iDynTree are the one of the International System of Units (SI)
// Always pay attention to units, because other robotics software systems (such as YARP or KUKA)
// actually use degrees for representing angles
iDynTree::VectorDynSize jointPosInitialInRadians(mdlLoader.model().getNrOfPosCoords());
// Let's start from the classical KUKA KR** home position
double deg2rad = M_PI/180.0;
jointPosInitialInRadians(0) = 0.0*deg2rad;
jointPosInitialInRadians(1) = -90.0*deg2rad;
jointPosInitialInRadians(2) = 90.0*deg2rad;
jointPosInitialInRadians(3) = 0.0*deg2rad;
jointPosInitialInRadians(4) = 90.0*deg2rad;
jointPosInitialInRadians(5) = 0.0*deg2rad;
// The iDynTree::KinDynComputations actually supports also setting the base position
// and the base and joint velocity, but in this case we just use it for computing
// the forward kinematics between two frames in the model, so we just need to
kinDynMeas.setJointPos(jointPosInitialInRadians);
// Let's read the initial cartesian position
iDynTree::Transform base_H_ee_initial = kinDynMeas.getRelativeTransform(baseFrame, endEffectorFrame);
// Print the initial joint and cartesian position
std::cerr << "Initial cartesian linear position: " << std::endl << "\t" << base_H_ee_initial.getPosition().toString() << std::endl;
std::cerr << "Initial joint position (radians): " << std::endl << "\t" << jointPosInitialInRadians.toString() << std::endl;
// Let's define a new desired cartesian position, by decreasing the z-position of initial cartesian pose by 10 centimeters (0.1 meters):
// We keep the same rotation
iDynTree::Rotation initial_rot_pose = base_H_ee_initial.getRotation();
// But we change the liner position
iDynTree::Position initial_linear_pose = base_H_ee_initial.getPosition();
initial_linear_pose(2) = initial_linear_pose(2) - 0.1;
iDynTree::Transform base_H_ee_desired = iDynTree::Transform(initial_rot_pose, initial_linear_pose);
// Let's print the desired position
std::cerr << "Desired cartesian linear position: " << std::endl << "\t" << base_H_ee_desired.getPosition().toString() << std::endl;
// Create a InverseKinematics class using the loaded model
iDynTree::InverseKinematics ik;
ok = ik.setModel(mdlLoader.model());
if (!ok) {
std::cerr << "iDynTreeExampleInverseKinematics: impossible to load the following model in a InverseKinematics class:" << std::endl
<< mdlLoader.model().toString() << std::endl;
return EXIT_FAILURE;
}
// Setup Inverse Kinematics problem
// Set IK tolerances
ik.setCostTolerance(0.0001);
ik.setConstraintsTolerance(0.00001);
// Always consider targets as costs, as opposed to a
ik.setDefaultTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone);
// Use roll pitch yaw parametrization for the rotational part of the inverse kinematics
ik.setRotationParametrization(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw);
// Note: the InverseKinematics class actually implements a floating base inverse kinematics,
// meaning that both the joint position and the robot base are optimized to reach the desired cartesian position
// As in this example we are considering instead the fixed-base case, we impose that the desired position of the base
// is the identity
iDynTree::Transform world_H_base = iDynTree::Transform::Identity();
ok = ik.setFloatingBaseOnFrameNamed(baseFrame);
if (!ok) {
std::cerr << "iDynTreeExampleInverseKinematics: impossible to set floating base on " << baseFrame << std::endl;
return EXIT_FAILURE;
}
ik.addFrameConstraint(baseFrame, world_H_base);
// Add the desired task: the cartesian pose of the endEffectorFrame w.r.t to the baseFrame
// Note that all the target are defined implicitly w.r.t. to the world frame of the ik, but
// as we imposed that the transform between the baseFrame and the world is the identity,
// asking for a desired world_H_ee pose is equivalent to asking for a desired base_H_ee pose
ok = ik.addTarget(endEffectorFrame, base_H_ee_desired);
if (!ok) {
std::cerr << "iDynTreeExampleInverseKinematics: impossible to add target on " << endEffectorFrame << std::endl;
return EXIT_FAILURE;
}
// As the IK optimization problem is a non-linear iterative optimization, the optimization needs
// an initial starting point, we use the initial position of the robot but note that this choice
// can influence the actual convergence of the algorithm
ik.setFullJointsInitialCondition(&world_H_base, &(jointPosInitialInRadians));
// Actually run the inverse kinematics optimization problem
ok = ik.solve();
if (!ok) {
std::cerr << "iDynTreeExampleInverseKinematics: impossible to solve inverse kinematics problem." << std::endl;
return EXIT_FAILURE;
}
// Read the solution
iDynTree::Transform basePoseOptimized;
iDynTree::VectorDynSize jointPosOptimizedInRadians(mdlLoader.model().getNrOfPosCoords());
ik.getFullJointsSolution(basePoseOptimized, jointPosOptimizedInRadians);
// Compute the actual transform associated with the optimized values
kinDynMeas.setJointPos(jointPosOptimizedInRadians);
iDynTree::Transform base_H_ee_optimized = kinDynMeas.getRelativeTransform(baseFrame, endEffectorFrame);
std::cerr << "Optimized cartesian position: " << std::endl << "\t" << base_H_ee_optimized.getPosition().toString() << std::endl;
std::cerr << "Optimized joint position (radians): " << std::endl << "\t" << jointPosOptimizedInRadians.toString() << std::endl;
return EXIT_SUCCESS;
}
| true |
0d67980814ae72f9354671c48f2c0b186ccdbd2b | C++ | yucongxing/PAT_practice | /basic_pat_practice/1021.cpp | UTF-8 | 268 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int main(int argc, char const *argv[])
{
int a[10]={0};
char t;
while(scanf("%c",&t)!=EOF){
a[t-'0']++;
}
for(int i=0;i<10;i++){
if(a[i]!=0) printf("%d:%d\n",i,a[i]);
}
return 0;
}
| true |
22ebdfddaab3294f5c2adc2f43e7bf459a3474f0 | C++ | priory/arduino-project | /lib/AnalogIO/src/AnalogInput.h | UTF-8 | 1,678 | 3.28125 | 3 | [] | no_license | #ifndef ANALOGINPUT_H
#define ANALOGINPUT_H
#include <Arduino.h>
class AnalogInput {
public:
/**
* Constructor.
*
* @param pin: pin used for the analog input
* @param min: minimum value of the input
* @param max: maximum value of the input.
* @param threshold: limit to when input change can trigger onChange
* @param stability: how many consecutive times threshold must be exceeded
* @param pollingRate: polling time interval
*/
explicit AnalogInput(
uint8_t pin,
unsigned int min = 26,
unsigned int max = 1022,
uint8_t threshold = 5,
uint8_t stability = 1,
unsigned long int pollingRate = 1000
);
/**
* Sets on input change event handler function.
*
* @param onChange
*/
void setOnChange(void (*onChange)());
/**
* Invokes on input change event.
*/
void triggerOnChange();
/**
* The loop function used to check for analog input.
*
* @param micro
*/
void loop(unsigned long int µ);
/**
* Reads the literal value from the analog sensor.
*
* @return
*/
unsigned int read() const;
/**
* Reads the decimal value between 0 and 1.
*
* @return
*/
float value() const;
private:
const uint8_t _pin;
const unsigned int _min;
const unsigned int _max;
const uint8_t _threshold;
const uint8_t _stability;
const unsigned long int _pollingRate;
unsigned long int _counter = 0;
uint8_t _setOffs = 0;
unsigned int _previous;
void (*_onChange)() = [] {};
};
#endif //ANALOGINPUT_H
| true |
4f25123a4da46162c7a084a8115ea7313ac6c85a | C++ | kbs781025/Sparky | /Sparky Core/src/maths/vec4.cpp | UTF-8 | 1,303 | 3.5625 | 4 | [] | no_license | #include "vec4.h"
namespace sparky {
namespace maths {
vec4::vec4(const float x, const float y, const float z, const float w)
{
this->x = x;
this->y = y;
this->z = z;
this->w = w;
}
vec4 & vec4::operator+=(const vec4 & other)
{
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
vec4 & vec4::operator-=(const vec4 & other)
{
x -= other.x;
y -= other.y;
z -= other.z;
w -= other.w;
return *this;
}
vec4 & vec4::operator*=(const vec4 & other)
{
x *= other.x;
y *= other.y;
z *= other.z;
w *= other.w;
return *this;
}
vec4 & vec4::operator/=(const vec4 & other)
{
x /= other.x;
y /= other.y;
z /= other.z;
w /= other.w;
return *this;
}
std::ostream & operator<<(std::ostream & os, const vec4 & vec)
{
os << "vec4 : <" << vec.x << ", " << vec.y << ", " << vec.z << ", " << vec.w << ">";
return os;
}
vec4 operator+(const vec4 & lhs, const vec4 & rhs)
{
return vec4(lhs) += rhs;
}
vec4 operator-(const vec4 & lhs, const vec4 & rhs)
{
return vec4(lhs) -= rhs;
}
vec4 operator*(const vec4 & lhs, const vec4 & rhs)
{
return vec4(lhs) *= rhs;
}
vec4 operator/(const vec4 & lhs, const vec4 & rhs)
{
return vec4(lhs) /= rhs;
}
}
} | true |
a402fa8d3bfca491fefb19035a5b2beb6f7fdf70 | C++ | BraderLh/AED | /ListaEnlazada_Gerarquía_Clases(Iterator,Tipos y Uso-VideoType)/linkedList.h | UTF-8 | 6,315 | 3.625 | 4 | [] | no_license | #ifndef LISTTYPE_H_INCLUDED
#define LISTTYPE_H_INCLUDED
#include <iostream>
#include <vector>
#include "orderedLinkedList.h"
#include "unorderedLinkedList.h"
#include <assert.h>
using namespace std;
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class linkedListIterator
{
protected:
int count;
nodeType<Type> *first;
nodeType<Type> *last;
public:
//friend class linkedListType<Type>;
//friend struct nodeType<Type>;
linkedListIterator();
linkedListIterator(nodeType<Type> *ptr);
Type operator*();
linkedListIterator<Type> operator++();
bool operator==(const linkedListIterator<Type>& right) const;
bool operator!=(const linkedListIterator<Type>& right) const;
private:
nodeType<Type> *current;
};
template <class Type>
class linkedListType
{
public:
//template <class Ty>
friend class linkedListIterator<Type>;
friend struct nodeType<Type>;
const linkedListType<Type>& operator= (const linkedListType<Type>&);
void initializeList();
bool isEmptyList() const;
void print() const;
int length() const;
void destroyList();
Type front() const;
Type back() const;
virtual bool search(const Type& searchItem) const = 0;
virtual void insertFirst(const Type& newItem) = 0;
virtual void insertLast(const Type& newItem) = 0;
virtual void deleteNode(const Type& deleteItem) = 0;
linkedListIterator<Type> begin();
linkedListIterator<Type> end();
linkedListType();
linkedListType(const linkedListType<Type>& otherList);
~linkedListType();
protected:
int count;
nodeType<Type> *first;
nodeType<Type> *last;
private:
void copyList(const linkedListType<Type>& otherList);
};
//CONSTRUCTOR POR DEFECTO
template <class Type>
linkedListType<Type>::linkedListType()
{
first = NULL;
last = NULL;
count = 0;
}
//CONSTRUCTOR COPIA
template <class Type>
linkedListType<Type>::linkedListType(const linkedListType<Type>& otherList)
{
first = NULL;
copyList(otherList);
}//end copy constructor
//FUNCION PARA VER SI LA LISTA ESTA VACIA
template <class Type>
bool linkedListType<Type>::isEmptyList() const
{
return (first == NULL);
}
//DESTRUYE LA LISTA
template <class Type>
void linkedListType<Type>::destroyList()
{
nodeType<Type> *temp; //pointer to deallocate the memory
//occupied by the node
while (first != NULL) //while there are nodes in the list
{
temp = first; //set temp to the current node
first = first->link; //advance first to the next node
delete temp; //deallocate the memory occupied by temp
}
last = NULL; //initialize last to NULL; first has already
//been set to NULL by the while loop
count = 0;
}
//INCIALIZADOR DE LA LISTA
template <class Type>
void linkedListType<Type>::initializeList()
{
destroyList(); //if the list has any nodes, delete them
}
//IMPRIMIR LISTA
template <class Type>
void linkedListType<Type>::print() const
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current point to the first node
while (current != NULL) //while more data to print
{
cout << current->info << " ";
current = current->link;
}
}//end print
//TAMANO DE UNA LISTA
template <class Type>
int linkedListType<Type>::length() const
{
return count;
}
//RETORNA EL PRIMER ELEMNTO DE LA LISTA
template <class Type>
Type linkedListType<Type>::front() const
{
assert(first != NULL);
return first->info; //return the info of the first node
}//end front
//RETORNA EL ULTIMO ELEMENTO DE LA LINKED LIST
template <class Type>
Type linkedListType<Type>::back() const
{
assert(last != NULL);
return last->info; //return the info of the last node
}//end back
//RETORNA UN ITERADOR DEL PRIMER NODO DE LINKED LIST
template <class Type>
linkedListIterator<Type> linkedListType<Type>::begin()
{
linkedListIterator<Type> temp(first);
return temp;
}
//RETORNA UN ITERADOR DEL ULTIMO NODO DE LA LINKED LIST
template <class Type>
linkedListIterator<Type> linkedListType<Type>::end()
{
linkedListIterator<Type> temp(NULL);
return temp;
}
//COPIAR LOS DATOS QUE CONTIENDE LA LISTA A OTRA LISTA
template <class Type>
void linkedListType<Type>::copyList(const linkedListType<Type>& otherList)
{
nodeType<Type> *newNode; //pointer to create a node
nodeType<Type> *current; //pointer to traverse the list
if (first != NULL) //if the list is nonempty, make it empty
destroyList();
if (otherList.first == NULL) //otherList is empty
{
first = NULL;
last = NULL;
count = 0;
}
else
{
current = otherList.first; //current points to the
//list to be copied
count = otherList.count;
//copy the first node
first = new nodeType<Type>; //create the node
first->info = current->info; //copy the info
first->link = NULL; //set the link field of the node to NULL
last = first; //make last point to the first node
current = current->link; //make current point to the next
// node
//copy the remaining list
while (current != NULL)
{
newNode = new nodeType<Type>; //create a node
newNode->info = current->info; //copy the info
newNode->link = NULL; //set the link of newNode to NULL
last->link = newNode; //attach newNode after last
last = newNode; //make last point to the actual last
//node
current = current->link; //make current point to the
//next node
}//end while
}//end else
}//end copyList
template <class Type>
const linkedListType<Type>& linkedListType<Type>::operator= (const linkedListType<Type>& otherList)
{
if (this != &otherList) //avoid self-copy
{
copyList(otherList);
}//end else
return *this;
}
template <class Type>
linkedListType<Type>::~linkedListType() //destructor
{
destroyList();
}
#endif // LISTTYPE_H_INCLUDED
| true |
175b7048a97c2eeee060bfa57ec1d3ed77ce9a15 | C++ | DFXLuna/ANN | /Perceptron.h | UTF-8 | 5,618 | 3.03125 | 3 | [] | no_license | // Perceptron.h
// Matt Grant(teamuba@gmail.com)
#include<cstdlib>
#include<algorithm>
using std::find;
#include<list>
using std::list;
#include<utility>
using std::pair;
#include<map>
using std::map;
#include<functional>
using std::function;
#include<vector>
using std::vector;
#include<cmath>
using std::abs;
#include<iostream>
using std::cout;
using std::endl;
// TODO
// Literally a fucking perceptron in perceptrons
// Rules about linking nodes?
// Implements a sigmoid neuron by default
class Node{
public:
// can specify activation function or NULL for fast sigmoid approx
Node(function<float( vector<float> )> activation);
auto activate(vector<float> weightedInput);
private:
// Activation function
function<float( vector<float> )> _activation;
};
// Node functions
Node::Node(function<float( vector<float> )> activation){
if(activation){
_activation = activation;
}
else{
_activation = [](vector<float> x ) -> float{
// z = sum of weighted inputs
float z = 0;
for(auto i : x){ z += i; }
return (z / (1 + abs(z)));
};
}
}
auto Node::activate(vector<float> weightedInput){
return(_activation(weightedInput));
}
class BinNode : public Node{
public:
BinNode(int bias);
private:
const int _bias = 0;
};
//BinNode functions
BinNode::BinNode(int bias) : Node(
[bias](vector<float> x) -> float{
// z = sum of weighted inputs
float z = 0;
for(auto i : x){ z += i; }
if(z > bias){ return 1; }
return 0;
}),
_bias(bias){
}
class Perceptron{
public:
// returns an integer id to reference the node
int createBNode(int bias);
int createSNode();
int createNode(function<float (vector<float>)> activation);
void linkNode(int from, int to, float weight);
void linkInput(int to);
map<int, float> run(vector<float> input);
void printLinks();
private:
map<int, float> run();
void sendInput(vector<float> input);
Node* get(int id);
int getid(Node* n);
int _id = 0;
vector< pair<int, Node> > _nodes;
// Maps node* to all forward edges and weights
map< Node*, vector< pair<Node*, int> >> _links;
vector<Node*> _inputLinks;
vector<float> _input;
};
// Perceptron functions
int Perceptron::createBNode(int bias){
Node b = BinNode(bias);
_nodes.push_back(pair<int, Node>(_id, b));
return _id++;
}
int Perceptron::createSNode(){
Node n = Node(NULL);
_nodes.push_back( pair<int, Node>(_id, n) );
return _id++;
}
int Perceptron::createNode(function<float ( vector<float> )> activation){
Node n = Node(activation);
_nodes.push_back( pair<int, Node>(_id,n) );
return _id++;
}
void Perceptron::linkNode(int to, int from, float weight){
pair<Node*, float> p;
p.first = get(from);
p.second = weight;
_links[get(to)].push_back(p);
}
void Perceptron::linkInput(int to){
_inputLinks.push_back(get(to));
}
void Perceptron::sendInput(vector<float> input){
_input = input;
}
void Perceptron::printLinks(){
int idx = 0;
int idy = 0;
float weight = 0;
cout << "---- Links ----" << endl;
for(auto const& x : _links){
idx = getid(x.first);
cout << "Node " << idx << endl;
for(auto const& y : x.second){
idy = getid(y.first);
weight = y.second;
cout << idx << " -" << weight <<"-> " << idy << endl;
}
}
cout << "---- Links----" << endl << endl;
}
map<int, float> Perceptron::run(vector<float> input){
sendInput(input);
return run();
}
map<int, float> Perceptron::run(){
// Queue of nodes to be evaluated. Enforces layer by layer evaluation
list<Node*> q;
// Keeps track of total weighted input to be sent to a node
map< Node*, vector<float> > inputs;
map<int, float> outputs;
// Initial setup
for(auto i : _inputLinks){
q.push_back(i);
inputs[i].insert(inputs[i].end(), _input.begin(), _input.end());
}
Node* curr = NULL;
float val = 0;
while(!q.empty()){
curr = q.front();
q.pop_front();
// Activate node and capture value
val = curr->activate(inputs[curr]);
// If node is not an output node, register its output for connected nodes
if(!_links[curr].empty()){
for(auto i : _links[curr]){
Node* n = i.first;
float weight = i.second;
inputs[n].push_back(val * weight);
if(find(q.begin(), q.end(), n) == q.end()){
q.push_back(n);
}
}
}
// output node, capture value
else{
outputs[getid(curr)] = val;
}
}
return outputs;
}
// As long as id is valid than this shouldn't ever fail
Node* Perceptron::get(int id){
if(id > _id){ return NULL; }
Node* ret = NULL;
bool found = false;
int i = 0;
while(found == false && i < _id){
if(_nodes[i].first == id){
found = true;
ret = &(_nodes[i].second);
}
i++;
}
return ret;
}
int Perceptron::getid(Node* n){
int ret = -1;
bool found = false;
size_t i = 0;
while(found == false && i < _nodes.size()){
if(&(_nodes[i].second) == n){
found = true;
ret = (_nodes[i].first);
}
i++;
}
return ret;
} | true |
d3dbccd7475d3c0ed903de56542de22c82068cfb | C++ | skapin/TestProtocol | /uart.h | UTF-8 | 1,577 | 2.953125 | 3 | [] | no_license | #ifndef UART_H
#define UART_H
/**
* @brief The Uart class
*
*
* @url http://stackoverflow.com/questions/6947413/how-to-open-read-and-write-from-serial-port-in-c
*
*
* The values for speed are B115200, B230400, B9600, B19200, B38400, B57600, B1200, B2400, B4800, etc.
* The values for parity are 0 (meaning no parity), PARENB|PARODD (enable parity and use odd), PARENB
* (enable parity and use even), PARENB|PARODD|CMSPAR (mark parity), and PARENB|CMSPAR (space parity).
* "Blocking" sets whether a read() on the port waits for the specified number of characters to arrive.
* Setting no blocking means that a read() returns however many characters are available without waiting
* for more, up to the buffer limit.
*/
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include <stdio.h>
#include <fcntl.h>
using namespace std;
class Uart
{
public:
enum baud_rate {
BR57600, BR115200, BR230400, BR460800, BR500000, BR576000, BR921600, BR1000000,
BR1152000, BR1500000, BR2000000, BR2500000, BR3000000, BR3500000, BR4000000
};
Uart( string portName );
~Uart();
int openDevice();
void closeDevice();
bool isDeviceOpen();
int setInterfaceAttrib (Uart::baud_rate speed, int parity );
void setBlocking ( int should_block );
int uartBaudRate2int( Uart::baud_rate baudrate);
void send( string data );
void send(int data);
string readData( );
private:
string _portName;
int _device;
baud_rate _currentBaudRate;
};
#endif // UART_H
| true |
3d29a4f4308affa1d2a46623bd46dcb4de6f5b5c | C++ | ajimenezh/Programing-Contests | /Topcoder/HamiltonPath.cpp | UTF-8 | 4,344 | 2.890625 | 3 | [] | no_license | #include <vector>
#include <list>
#include <map>
#include <set>
#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 HamiltonPath {
public:
int countPaths(vector <string>);
};
vector<string> r;
vector<int> vis;
int n;
bool dfs(int a,int pre) {
bool res=true;
vis[a]=1;
for (int i=0; i<n; i++) {
if (r[a][i]=='Y' && vis[i]==-1 && i!=pre) res=res&dfs(i,a);
else if (r[a][i]=='Y' && vis[i]!=-1 && i!=pre) return false;
}
return res;
}
int HamiltonPath::countPaths(vector <string> roads) {
n=roads.size();
vector<int> v(n,-1);
vis=v;
int is=0;
r=roads;
for (int i=0; i<n; i++) {
int count=0;
for (int j=0; j<n; j++) {
if (r[i][j]=='Y') count++;
}
if (count>2) return 0;
if (count==0) is++;
}
int tot=0;
for (int i=0; i<n; i++) {
if (vis[i]==-1) {
if (!dfs(i,i)) return 0;
tot++;
}
}
int c=tot-is;
long long res=1;
long long mod=1000000007;
for (int i=1; i<=tot; i++) {
res = (res*i)%mod;
}
for (int i=1; i<=c; i++) {
res=(res*2)%mod;
}
return res;
}
double test0() {
string t0[] = {"NYN",
"YNN",
"NNN"};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
HamiltonPath * obj = new HamiltonPath();
clock_t start = clock();
int my_answer = obj->countPaths(p0);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p1 = 4;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p1 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p1 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test1() {
string t0[] = {"NYYY",
"YNNN",
"YNNN",
"YNNN"};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
HamiltonPath * obj = new HamiltonPath();
clock_t start = clock();
int my_answer = obj->countPaths(p0);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p1 = 0;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p1 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p1 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test2() {
string t0[] = {"NYY",
"YNY",
"YYN"};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
HamiltonPath * obj = new HamiltonPath();
clock_t start = clock();
int my_answer = obj->countPaths(p0);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p1 = 0;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p1 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p1 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test3() {
string t0[] = {"NNNNNY",
"NNNNYN",
"NNNNYN",
"NNNNNN",
"NYYNNN",
"YNNNNN"};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
HamiltonPath * obj = new HamiltonPath();
clock_t start = clock();
int my_answer = obj->countPaths(p0);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p1 = 24;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p1 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p1 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
int main() {
int time;
bool errors = false;
time = test0();
if (time < 0)
errors = true;
time = test1();
if (time < 0)
errors = true;
time = test2();
if (time < 0)
errors = true;
time = test3();
if (time < 0)
errors = true;
if (!errors)
cout <<"You're a stud (at least on the example cases)!" <<endl;
else
cout <<"Some of the test cases had errors." <<endl;
}
//Powered by [KawigiEdit] 2.0!
| true |
480066bcb704e36fbe5db88ab963ac56f5787ab2 | C++ | npjtwy/DS_CPP | /list/List_search.h | GB18030 | 454 | 3.125 | 3 | [] | no_license | #pragma once
/*
* زֹλ
* ListNodePosi(T) search(T const& e, int n, ListNodePosi(T) p) const; //
*/
template <typename T>
ListNodePosi(T) List<T>::search(T const& e, int n, ListNodePosi(T) p) const
{
// 0 <= n <= rank(p) < _size
while (n-- >= 0) //עֹ
{
if ((p = p->pred)->data <= e) //עֹ < eڽв
{
return p;
}
}
return p;
} | true |
0c5b5060fa37624f20e5e6bd6ef1c131ef543211 | C++ | mtekman/MembranousScripts | /preciseChi/main.cpp | UTF-8 | 3,033 | 3.125 | 3 | [] | no_license | #include <boost/tokenizer.hpp>
#include <fstream>
#include <string>
#include "ChiSquare.h"
using namespace boost;
//inline expands the code inside the scope of where it is called. Almost a macro function
inline double convertToDouble(std::string const& s){
std::istringstream i(s); double x;
if (!(i >> x)){
cerr << "Could not convert to double: " << s << endl;
exit(-1);
}
return x;
}
inline int convertToInt(std::string const& s){
std::istringstream i(s); int x;
if (!(i >> x)){
cerr << "Could not convert to int: " << s << endl;
exit(-1);
}
return x;
}
void checkArg(char * arg, string valid_arg_start){
string setarg = string(arg).substr(0,valid_arg_start.size());
if (setarg!=valid_arg_start){
cerr << "Please give " << valid_arg_start << "N argument!" << endl;
exit(-1);
}
}
int main(int argc, char ** argv)
{
//Args
string setnum_id("--#sets=");
string valset_id("--#valsper=");
string sigfig_id("--#sf=");
if (argc<4) {
cerr << endl;
cerr << "Takes in a text file where each row contains several different sets and calculates the chi-squared and p-value across all sets for that row.";
cerr << endl;
cerr << "\nEach row of the text file is delimited by spaces in the format:";
cerr << "\n\trow1:\tA11 A12 B11 B12 C11 C12 D11 D12 ... etc";
cerr << "\n\trow2:\tA21 A22 B21 B22 C21 C22 D21 D22 ... etc" << endl;
cerr << "\tetc..\n";
cerr << endl;
cerr << "Set number MUST be specified to indicate how many values there are per set (in the above example there are 2).\n" << endl;
cerr << " usage: " << argv[0] << " <text.input> "<< setnum_id << "N " << valset_id << "N [" << sigfig_id << "N]" << endl;
cerr << endl;
exit(-1);
}
//File arg
ifstream file(argv[1]);
//////////Flags
//Reqs
checkArg(argv[2],setnum_id);
checkArg(argv[3],valset_id);
int setnum = convertToInt(string(argv[2]).substr(setnum_id.size()));
int valset = convertToInt(string(argv[3]).substr(valset_id.size()));
//Opts
int sigfig=3; //default
if (argc==5){
checkArg(argv[4],sigfig_id);
sigfig = convertToInt(string(argv[4]).substr(sigfig_id.size()));
}
/////////Begin
chi_squared_distribution<long double> dist(setnum-1); // Make chisq once
//Read in file, process lines
typedef tokenizer<char_separator<char> > tokenizer;
string line;
while(getline(file, line))
{
vector<vector<int> > row_data;
tokenizer tok(line);
for (tokenizer::iterator beg=tok.begin(); beg!=tok.end(); false) {
vector<int> val_in_set;
for (int r=0; r < valset; r++){
int val = convertToInt(*beg);
val_in_set.push_back(val);
if ((++beg).at_end())break;
}
row_data.push_back( val_in_set );
}
ChiSquare(row_data, dist, valset, sigfig);
}
return 0;
}
| true |
62e8a25a52a75b6dd73cb568ac889bb1dcf78548 | C++ | willemjan92/Cpp_rougelike | /Eindopdracht/Trap.cpp | UTF-8 | 1,193 | 2.734375 | 3 | [] | no_license | #include "Trap.h"
Trap::Trap(Level * lvl, int x, int y, Vijand * vijand) : Kamer(lvl, x, y, "trap", vijand)
{
}
Trap::Trap()
{
}
string Trap::GetMapIcon() {
return "S";
}
Kamer* Trap::GetBuurKamer(Richting richting)
{
switch (richting)
{
case Richting::Noord:
return Noord;
break;
case Richting::Oost:
return Oost;
break;
case Richting::Zuid:
return Zuid;
break;
case Richting::West:
return West;
break;
case Richting::Omhoog:
return Omhoog;
break;
case Richting::Omlaag:
return Omlaag;
break;
default:
break;
}
}
void Trap::ZetBuurKamer(Kamer* kamer, Richting richting) {
if (kamer) {
switch (richting)
{
case Richting::Noord:
Noord = kamer;
kamer->Zuid = this;
uitgang[0] = true;
break;
case Richting::Oost:
Oost = kamer;
kamer->West = this;
uitgang[1] = true;
break;
case Richting::Zuid:
Zuid = kamer;
kamer->Noord = this;
uitgang[2] = true;
break;
case Richting::West:
West = kamer;
kamer->Oost = this;
uitgang[3] = true;
break;
case Richting::Omhoog:
Omhoog = kamer;
break;
case Richting::Omlaag:
Omlaag = kamer;
break;
default:
break;
}
}
}
Trap::~Trap()
{
} | true |
8721e4b8131c42752ad1fa090fa56cac2b5e2051 | C++ | mrSerega/matmod | /ConsoleApplication3/ConsoleApplication3/cAbstractMethod.h | UTF-8 | 321 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
#ifndef AF_H
#define AF_H
class cAbstractMethod
{
public:
cAbstractMethod();
cAbstractMethod(cAbstractMethod* rhs);
~cAbstractMethod();
double operator[](int index);
size_t size();
protected:
vector<double> arr;
};
#endif // !AF_H
| true |
90819c4834b7808489d87177f214b532f6fea019 | C++ | benardp/Radium-Engine | /src/Core/Geometry/PolyLine.inl | UTF-8 | 1,396 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <Core/Geometry/PolyLine.hpp>
#include <Core/Math/LinearAlgebra.hpp> // cotan, saturate (from Math.hpp)
namespace Ra {
namespace Core {
namespace Geometry {
const Vector3Array& PolyLine::getPoints() const {
return m_pts;
}
Scalar PolyLine::length() const {
return m_lengths.back();
}
Aabb PolyLine::aabb() const {
Aabb aabb;
for ( const auto& v : m_pts )
{
aabb.extend( v );
}
return aabb;
}
Scalar PolyLine::getLineParameter( uint segment, Scalar tSegment ) const {
CORE_ASSERT( segment < m_ptsDiff.size(), "invalid segment index" );
const Scalar lprev = segment > 0 ? m_lengths[segment - 1] : 0;
const Scalar lSegment = m_lengths[segment] - lprev;
return ( ( lSegment * tSegment ) + lprev ) / length();
}
void PolyLine::getSegment( uint segment, Vector3& aOut, Vector3& abOut ) const {
CORE_ASSERT( segment < m_ptsDiff.size(), "Invalid segment index." );
aOut = m_pts[segment];
abOut = m_ptsDiff[segment];
}
const Vector3Array& PolyLine::getSegmentVectors() const {
return m_ptsDiff;
}
uint PolyLine::getSegmentIndex( Scalar t ) const {
// This could be optimized by dichotomy
Scalar param = length() * Math::saturate( t );
uint i = 0;
while ( m_lengths[i] < param )
{
++i;
}
return i;
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
| true |
363cdfcd0898924a08f3712fc9c3a63c0b1466d5 | C++ | green-fox-academy/pengegyuri | /week-04/day-3/modeldevices/printer.cpp | UTF-8 | 281 | 2.84375 | 3 | [] | no_license | //
// Created by gyuri on 2019.02.06..
//
#include "printer.h"
#include <iostream>
Printer::Printer(int sizeX, int sizeY)
{
_sizeX = sizeX;
_sizeY = sizeY;
}
void Printer::print()
{
std::cout << "I'm printing something that's " << getSize() << " cm."<< std::endl;
}
| true |
7a101e7e984908c22eaf1f95b9c34e2be9dbb627 | C++ | asfopoo/bankCPP | /Bank.cpp | UTF-8 | 588 | 2.859375 | 3 | [] | no_license | #include "Bank.h"
#include "structures.h"
Bank::Bank() {
balance = 0;
}
Bank::~Bank() {
}
void Bank::deposit(double x, struct Transaction *t, int *d, int *tt) {
balance += x;
*d += 1;
*tt += 1;
t->date = *d;
t->amount = x;
t->transactionType = dep;
t->balance = balanceTotal();
}
void Bank::withdraw(double x, struct Transaction *t, int *d, int *tt) {
balance -= x;
*d += 1;
*tt += 1;
t->date = *d;
t->amount = x;
t->transactionType = with;
t->balance = balanceTotal();
}
double Bank::balanceTotal() {
return balance;
}
| true |
392fc01684e24bdcb5c853a4d8610e4bc2711f2c | C++ | walkccc/LeetCode | /solutions/1117. Building H2O/1117.cpp | UTF-8 | 891 | 3.078125 | 3 | [
"MIT"
] | permissive | // LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore
// or binary_semaphore.
#include <semaphore.h>
class H2O {
public:
H2O() {
sem_init(&hSemaphore, /*pshared=*/0, /*value=*/1);
sem_init(&oSemaphore, /*pshared=*/0, /*value=*/0);
}
~H2O() {
sem_destroy(&hSemaphore);
sem_destroy(&oSemaphore);
}
void hydrogen(function<void()> releaseHydrogen) {
sem_wait(&hSemaphore);
++h;
// releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen();
if (h % 2 == 0)
sem_post(&oSemaphore);
else
sem_post(&hSemaphore);
}
void oxygen(function<void()> releaseOxygen) {
sem_wait(&oSemaphore);
// releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen();
sem_post(&hSemaphore);
}
private:
sem_t hSemaphore;
sem_t oSemaphore;
int h = 0;
};
| true |
b23ca400863feebad922073c52602232af726d74 | C++ | 15831944/airengine | /AirClient/Tool/CppScript/Debug/1.cpp | WINDOWS-1252 | 754 | 2.84375 | 3 | [] | no_license | /*
Function
*/
char* str="HELLO WORLD!";
__declspec(dllimport) void Print(const char* str);
__declspec(dllimport) int strlen(char* p);
__declspec(dllimport) int CopyFileA(char* lpExistingFileName,char* lpNewFileName,int bFailIfExists);
namespace Air{
//int strlen(char* p){
// if(p==0){
// return 0;
// }
// for(int i=0;;i++){
// if(p[i]==0){
// return i;
// }
// }
// return 0;
//}
void ToLower(char* str){
int iLen=strlen(str);
for(int i=0;i<iLen;i++){
if((str[i]>='A') && (str[i]<=90)){
str[i]+=32;
}
}
}
}
//ע
__declspec(dllexport) int main(int count,int param){
//CopyFileA("1.cpp","1.cpp.bak",0);
Print(str);
Air::ToLower(str);
Print(str);
return -1;
}
| true |
5e9fb3f869de75d13591bb69cae30a83e7c2c58b | C++ | nikita-nazarov/Renderer | /camera.cpp | UTF-8 | 1,126 | 3.078125 | 3 | [] | no_license | /* START OF 'camera.cpp' FILE */
#include "camera.h"
CAMERA::CAMERA (void) :
viewDirection(0.0f, 0.0f, -1.0f), up(0.0f, 1.0f, 0.0f), position(0.0f, 0.0f, -10.0f)
{
}
CAMERA::CAMERA (const CAMERA & newCamera) :
viewDirection(newCamera.viewDirection),
position(newCamera.position),
up(newCamera.up)
{
}
CAMERA::~CAMERA (void)
{
}
CAMERA & CAMERA::operator= (const CAMERA & newCamera)
{
viewDirection = newCamera.viewDirection;
position = newCamera.position;
up = newCamera.up;
return *this;
}
void CAMERA::MouseUpdate (const POINT & mouseDelta, const float rotationSpeed)
{
float angleX = mouseDelta.x * rotationSpeed;
float angleY = mouseDelta.y * rotationSpeed;
// Horizontal rotation
viewDirection = glm::mat3(glm::rotate(angleX, up)) * viewDirection;
// Vertical rotation
glm::vec3 rotateAround = glm::cross(viewDirection, up);
viewDirection = glm::mat3(glm::rotate(angleY, rotateAround)) * viewDirection;
}
glm::mat4 CAMERA::GetWorldToViewMatrix (void) const
{
return glm::lookAt(position, position + viewDirection, up);
}
/* END OF 'camera.cpp' FILE */
| true |
b9efd8fef6b52c90a19a2d24bd2906b03e4dbf6a | C++ | smn06/Code | /extra/mid/5.cpp | UTF-8 | 1,231 | 3.15625 | 3 | [] | no_license | //5
#include<iostream>
#include<algorithm>
using namespace std;
#define M 10
int calc(double a[][M], int n)
{
int i,j,k=0,c,check=0,m=0;
for(i=0;i<n;i++)
{
if(a[i][i]==0)
{
c=1;
while((i + c)<n && a[i+c][i]==0)
c++;
if((i+c)==n) {
check=1;
break;
}
for(j=i,k =0;k<=n;k++)
swap(a[j][k],a[j+c][k]);
}
for(j=0;j<n;j++) {
if(i!=j) {
double pro=a[j][i]/a[i][i];
for(k=0;k<=n;k++)
a[j][k]=a[j][k]-(a[i][k])*pro;
}
}
}
return check;
}
void print(double a[][M], int n, int check)
{
cout<<"Solution is : ";
if(check==2)
cout<<"Infinite Solutions"<<endl;
else if(check==3)
cout<<"No Solution"<<endl;
else {
for(int i=0;i<n;i++)
cout<<a[i][n]/a[i][i]<<" ";
}
}
int consist(double a[][M],int n,int check)
{
int i,j;
double sum;
check=3;
for (i=0;i<n;i++)
{
sum=0;
for(j=0;j<n;j++)
sum=sum+a[i][j];
if(sum==a[i][j])
check=2;
}
return check;
}
int main()
{
double a[M][M]={{ 1, 2, 1, 8 },
{ 2, 3, 4, 20 },
{ 4, 3, 2, 16}};
int n=3,check=0;
check=calc(a,n);
if(check==1)
check=consist(a,n,check);
cout<<endl;
print(a,n,check);
}
| true |
95f24a303ceeb2dba145887a691479ec17223b48 | C++ | oceanofthelost/Project-Euler | /PE003/C++/PE003.cpp | UTF-8 | 684 | 3.859375 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i=0; //variables that i need for loops
long q=600851475143;
while(q!=1) //loop that increments the amound of times you want to reduce the number
{
for(i=2;i<q;i++) //finds a number that we will use to divide q.
{
if(q%i==0) //if i can divide evenly into q then we execute the if statments
{
break; //gets us out of the loop
}
}
q=q/i; //divides q by i and stores theresult in q.
cout<<"your number was divided "<<i<<" now it is "<<q<<endl;
}
}
| true |
85b86226691fbaf184bcbd2871abcc123a92e1cd | C++ | palacaze/sigslot | /example/lambdas.cpp | UTF-8 | 723 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <sigslot/signal.hpp>
#include <cstdio>
/*
* This example is meant to test compilation time as well as object size when a
* lot of unique callables get connected to a signal.
* This example motivated the introduction of a SOCUTE_REDUCE_COMPILE_TIME cmake option.
*/
#define LAMBDA4() sig.connect([](int) { puts("lambda\n"); });
#define LAMBDA3() LAMBDA4() LAMBDA4() LAMBDA4() LAMBDA4() LAMBDA4()
#define LAMBDA2() LAMBDA3() LAMBDA3() LAMBDA3() LAMBDA3() LAMBDA3()
#define LAMBDA1() LAMBDA2() LAMBDA2() LAMBDA2() LAMBDA2() LAMBDA2()
#define LAMBDAS() LAMBDA1() LAMBDA1() LAMBDA1() LAMBDA1() LAMBDA1()
int main() {
sigslot::signal<int> sig;
// connect a bunch of lambdas
LAMBDAS()
return 0;
}
| true |
d56fe12dff6607c9a3360f7546bc0963215f4a75 | C++ | Abhinav95/tv-ad-classification | /utility-scripts/split.cpp | UTF-8 | 583 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]){
if(argc < 2){
cout << "Usage: ./split <filename> <every how many lines> <train/test>" << endl;
return 0;
}
ifstream myfile;
string line;
myfile.open(argv[1]);
int cur = 1;
int max = atoi(argv[2]);
if(myfile.is_open()){
while(getline(myfile,line)){
if(cur<max-1&&!strcmp(argv[3],"train")){
cout << line << endl;
}
else if(cur==max-1&&!strcmp(argv[3],"test")){
cout << line << endl;
}
cur++;
if(cur >= max){
cur = 1;
}
}
myfile.close();
}
return 0;
} | true |
d7043b0411b7d8d21e756d0025c77876788274a0 | C++ | Bingyy/LeetCode | /C++/106_Construct_Binary_Tree_from_Preorder_and_InOrder_Traversal_Medium.cpp | UTF-8 | 1,564 | 3.296875 | 3 | [] | no_license | #include "lib.h"
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// 根据中序和后序遍历序列构建二叉树
// 可以唯一构建一棵二叉树
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return helper(inorder, 0, inorder.size(), postorder, 0, postorder.size()); // 左闭右
}
// i,j是中序遍历序列的[i,j),j可以看成是中序序列的元素个数
// 传递的是引用变量,所以需要用下标跟踪
TreeNode* helper(vector<int>& inorder, int inL, int inR, vector<int>& postorder, int pL, int pR) {
if(inL >= inR || pL >= pR) {
return NULL;
}
int root = postorder[pR-1];
TreeNode* rootNode = new TreeNode(root);
int k; // 根元素在中序序列的位置
for (int i = inL;i < inR; i++) {
if (inorder[i] == root) {
k = i;
break;
}
}
int leftTreeSize = k - inL; // 不含k下标
// 划分左右子树
rootNode->left = helper(inorder, inL, inL + leftTreeSize, postorder, pL, pL + leftTreeSize);
rootNode->right = helper(inorder, inL + leftTreeSize + 1, inR, postorder, pL + leftTreeSize, pR - 1);
return rootNode;
}
};
| true |
566ff340a1d0c13930dfb5511b2679ed884a08be | C++ | JuliaSamartseva/Binary-search-tree | /Visualisation/Visualisation.cpp | UTF-8 | 2,666 | 3.109375 | 3 | [] | no_license | #include "Visualisation.h"
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <sstream>
#include <string>
#include <windows.h>
#include <sstream>
#include <conio.h>
namespace visualisation {
void bst_print_dot_null(Node *key, int nullcount, FILE* stream)
{
fprintf(stream, " null%d [shape=point];\n", nullcount);
fprintf(stream, " %s -> null%d;\n", key->english.c_str(), nullcount);
}
void bst_print_dot_aux(Node* node, FILE* stream)
{
static int nullcount = 0;
static int dotcount = 0;
if (node->left)
{
fprintf(stream, " %s -> %s;\n", node->english.c_str(), node->left->english.c_str());
bst_print_dot_aux(node->left, stream);
}
else
bst_print_dot_null(node, nullcount++, stream);
if (node->right)
{
fprintf(stream, " %s -> %s;\n", node->english.c_str(), node->right->english.c_str());
bst_print_dot_aux(node->right, stream);
}
else
bst_print_dot_null(node, nullcount++, stream);
}
void bst_print_dot(Node* tree, FILE* stream)
{
fprintf(stream, "digraph BST {\n");
fprintf(stream, " node [fontname=\"Arial\"];\n");
if (!tree)
fprintf(stream, "\n");
else if (!tree->right && !tree->left) {
fprintf(stream, " %s;\n", tree->english.c_str());
//fprintf(stream, " \"%s\";\n", tree->info.c_str());
}
else
bst_print_dot_aux(tree, stream);
fprintf(stream, "}\n");
}
void gotoxy(int x, int y)
{
COORD ord;
ord.X = x;
ord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), ord);
}
int DisplayMainMenu() {
::system("cls");
gotoxy(5, 4);
std::cout << "___________________________________________";
gotoxy(5, 6);
std::cout << "1. Add words";
gotoxy(5, 7);
std::cout << "2. Tree appearance";
gotoxy(5, 8);
std::cout << "3. Search words";
gotoxy(5, 9);
std::cout << "4. Rebuild tree";
gotoxy(5, 10);
std::cout << "5. Exit";
gotoxy(5, 11);
std::cout << "___________________________________________";
gotoxy(5, 13);
std::cout << "Your choice: ";
int m = -1;
std::cin >> m;
return m;
}
int DisplayMainMenu2() {
::system("cls");
gotoxy(5, 4);
std::cout << "___________________________________________";
gotoxy(5, 6);
std::cout << "1. Sort by Alphabetic Order";
gotoxy(5, 7);
std::cout << "2. Sort by Frequency";
gotoxy(5, 8);
std::cout << "3. Sort by Character Number";
gotoxy(5, 9);
std::cout << "4. Tree appearance";
gotoxy(5, 10);
std::cout << "5. Exit";
gotoxy(5, 11);
std::cout << "___________________________________________";
gotoxy(5, 13);
std::cout << "Your choice: ";
int m = -1;
std::cin >> m;
return m;
}
} | true |
96a086770d6a9a8cabb9100c97c3261703ca6b4b | C++ | a173/CPP_modules | /cpp04/ex03/MateriaSource.hpp | UTF-8 | 558 | 2.59375 | 3 | [] | no_license | //
// Created by Allegra Caryn on 4/24/21.
//
#ifndef EX03_MATERIASOURCE_HPP
#define EX03_MATERIASOURCE_HPP
#include "IMateriaSource.hpp"
#include "AMateria.hpp"
class MateriaSource : public IMateriaSource {
public:
MateriaSource();
MateriaSource(const MateriaSource &);
virtual ~MateriaSource();
MateriaSource & operator=(const MateriaSource &);
virtual void learnMateria(AMateria*);
virtual AMateria* createMateria(std::string const & type);
private:
void my_del();
AMateria** _materia;
int _count;
};
#endif //EX03_MATERIASOURCE_HPP
| true |
99e1a1068d28636d2de39be79a6f45ab95723b4a | C++ | yctseng1227/CPE | /CPE_1_Star_Problems/UVa10209 - Is This Integration?.cpp | UTF-8 | 1,175 | 2.875 | 3 | [] | no_license | /*=======================================
UVa10209 - Is This Integration?
=========================================
Completion Date: 105/04/26
=======================================*/
#include <iostream>
#include <iomanip>
#define PI 2.0*acos(0.0) // 題目給予
using namespace std;
int main()
{
double dLength; // 輸入之正方形邊長
double dStripedRegion; // 題目中斜線的面積
double dDottedRegion; // 題目中點點的面積
double dRestRegion; // 題目中方格的面積
double dSquare; // 整塊正方形面積
double dCircle; // 以正方形邊長作為半徑之圓面積
double dSeed; // 某塊為方便計算需求得的面積
while (cin >> dLength)
{
dSquare = dLength*dLength;
dCircle = dLength*dLength*PI;
dSeed = ( dCircle/6 - ( (sqrt(3)/4) * dLength*dLength ) );
dRestRegion = 4 * ( ( dSquare-dCircle/4 ) - ( dCircle/4 - dCircle/6 - dSeed) );
dDottedRegion = 4 * ( dSquare - dCircle/4 - dRestRegion/2 );
dStripedRegion = dSquare - dRestRegion - dDottedRegion;
cout << fixed << setprecision(3) << dStripedRegion << " "
<< dDottedRegion << " " << dRestRegion << endl;
}
return 0;
}
| true |
cc4befacc244eba3e48dd89c1439f2364decf7ec | C++ | zackkk/leetcode | /Trapping Rain Water.cpp | UTF-8 | 775 | 3.1875 | 3 | [] | no_license | class Solution {
public:
// water volumn depends on left max height and right max height
int trap(int A[], int n) {
if(n == 0) return 0;
vector<int> left(n, 0); // highest bar on its left;
vector<int> right(n, 0);
int left_max = 0;
for(int i = 0; i < n; ++i){
left[i] = left_max;
left_max = max(A[i], left_max);
}
int right_max = 0;
for(int i = n-1; i >= 0; --i){
right[i] = right_max;
right_max = max(A[i], right_max);
}
int water = 0;
for(int i = 1; i < n-1; ++i){
int tmp = min(left[i], right[i]) - A[i];
if(tmp > 0) water += tmp;
}
return water;
}
}; | true |
0ac563f5e1d618f9c285b3db9fb7a4f7542dff40 | C++ | fzylx/std-make | /include/experimental/fundamental/v3/strong/strict_bool.hpp | UTF-8 | 4,994 | 2.9375 | 3 | [
"BSL-1.0"
] | permissive | // Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Copyright (C) 2017 Vicente J. Botet Escriba
#ifndef JASEL_FUNDAMENTAL_V3_STRONG_STRICT_BOOL_HPP
#define JASEL_FUNDAMENTAL_V3_STRONG_STRICT_BOOL_HPP
#include <experimental/fundamental/v3/strong/strong_type.hpp>
#include <experimental/fundamental/v3/strong/mixins/comparable.hpp>
#include <experimental/fundamental/v3/strong/mixins/logical.hpp>
#include <experimental/fundamental/v3/strong/mixins/hashable.hpp>
#include <experimental/fundamental/v3/strong/mixins/streamable.hpp>
#include <experimental/fundamental/v3/strong/mixins/ordinal.hpp>
#include <type_traits>
#include <functional>
namespace std
{
namespace experimental
{
inline namespace fundamental_v3
{
/**
`strict_bool` is a strongly type that wraps a bool and behaves like an `bool`
The main goal is to be able to define strong booleans that don't mix between them.
The single conversion is the explicit conversion to bool type.
This is a safe bool, in the sense that it doesn't allows conversions from integral, floating point and pointer types.
In addition it forbids conversions between different strong booleans types.
As any tagged type, it makes the parameter more explicit.
Example
<code>
using X = strict_bool<XTag>;
using Y = strict_bool<YTag>;
void f(X, Y);
f(X(true), Y(false));
</code>
*/
// Do we need a Bool parameter? Which type will be a good candidate?
// bool takes 4 bytes in some machines. Sometimes we want to use just 1 byte
template <class Tag, class Bool = bool>
struct strict_bool final
: strong_type<strict_bool<Tag, Bool>, Bool>
, mixin::comparable<strict_bool<Tag, Bool>>
, mixin::explicit_convertible_to<strong_bool<Tag, Bool>, bool>
, mixin::logical<strict_bool<Tag, Bool>>
, mixin::hashable<strict_bool<Tag, Bool>>
, mixin::streamable<strict_bool<Tag, Bool>>
, mixin::ordinal<strict_bool<Tag, Bool>>
{
using base_type = strong_type<strict_bool<Tag, Bool>, Bool>;
using base_type::base_type;
// copy constructor/assignment default
constexpr strict_bool() noexcept = default;
// If Bool is not bool, we want an explicit conversion from bool but not Bool.
constexpr explicit strict_bool (Bool) = delete;
constexpr explicit strict_bool (bool b) : base_type(b) {}
// unwanted conversions
constexpr explicit strict_bool (int) = delete;
constexpr explicit strict_bool (double) = delete;
constexpr explicit strict_bool (void*) = delete;
template <class R, class ... Args>
constexpr explicit strict_bool (R(*)(Args...)) = delete;
template <class C, class R, class ... Args>
constexpr explicit strict_bool (R(C::*)(Args...)) = delete;
// boolean operators
// fixme do we need these && and || operators?
// strict_bool is explicit convertible to bool and so && and || operator will force the conversion to bool
// If we don't define them we need to be explicit to convert to strict_bool
// If we define them, we need to be explicit to convert to bool.
// todo do we need mixed boolean operators?
// If yes, which would be the result. IMO, it should be bool.
// If not, there will be a conversion to bool and the result is bool
};
template <class Tag>
struct strict_bool<Tag, bool> final
: strong_type<strict_bool<Tag, bool>, bool>
, mixins<strict_bool<Tag, bool>,
meta_mixin::comparable<>
, meta_mixin::explicit_convertible_to<bool>
, meta_mixin::logical<>
, meta_mixin::hashable<>
, meta_mixin::streamable<>
, meta_mixin::ordinal<>
>
{
using base_type = strong_type<strict_bool<Tag, bool>, bool>;
using base_type::base_type;
// copy constructor/assignment default
constexpr strict_bool() noexcept = default;
// unwanted conversions
constexpr explicit strict_bool (int) = delete;
constexpr explicit strict_bool (double) = delete;
constexpr explicit strict_bool (void*) = delete;
template <class R, class ... Args>
constexpr explicit strict_bool (R(*)(Args...)) = delete;
template <class C, class R, class ... Args>
constexpr explicit strict_bool (R(C::*)(Args...)) = delete;
};
#if __cplusplus <= 201402L || (! defined __clang__ && defined __GNUC__ && __GNUC__ <= 6)
static_assert(std::is_pod<strict_bool<bool>>::value, "");
static_assert(std::is_trivially_default_constructible<strict_bool<bool>>::value, "");
static_assert(std::is_trivially_copyable<strict_bool<bool>>::value, "");
static_assert(std::is_standard_layout<strict_bool<bool>>::value, "");
static_assert(std::is_trivial<strict_bool<bool>>::value, "");
#endif
}
}
template <class Tag, class UT>
struct hash<experimental::strict_bool<Tag,UT>> :
experimental::wrapping_hash<experimental::strict_bool<Tag,UT>> {};
}
#endif // header
| true |
e191d8610e4096e79d0ffad0ea3c7f7b92c309d0 | C++ | martinv/pdekit | /src/linear_system/TrilinosCrsMatrix.hpp | UTF-8 | 2,272 | 2.53125 | 3 | [] | no_license | #ifndef PDEKIT_Trilinos_Sparse_Matrix_hpp
#define PDEKIT_Trilinos_Sparse_Matrix_hpp
#include "PDEKit_Config.hpp"
#if PDEKIT_HAVE_TRILINOS
#include <iostream>
#include <memory>
#include <vector>
#include "Epetra_CrsMatrix.h"
#include "Epetra_MpiComm.h"
#include "Teuchos_RCP.hpp"
#include "common/PDEKit.hpp"
namespace pdekit
{
namespace ls
{
class TrilinosCrsMatrix
{
public:
/// Default constructor
TrilinosCrsMatrix(const Uint global_nb_rows);
/// Destructor
~TrilinosCrsMatrix();
/// Get the number of global elements in the matrix
Uint nb_global_elem() const;
/// Lock the structure of the matrix
void lock_structure();
/// Insert values in one row
void insert_values_in_row(const Uint row_idx, const std::vector<Real> &values,
const std::vector<Int> &indices);
/// Accumulate values in one row
void add_values_to_row(const Uint row_idx, const std::vector<Real> &values,
const std::vector<Int> &indices);
/// Get the underlying map
const std::shared_ptr<Epetra_Map> map() const;
/// Get the domain map of this matrix
/// @note This should be used to construct the vectors
/// for linear systems involving this matrix!
const Epetra_Map &domain_map() const;
/// Assign the same scalar value to all entries in the sparse matrix
void fill(const Real value);
/// Print the structure of the matrix to file
void print_structure_to_file(const std::string &filename) const;
/// Print info
void print_info() const
{
#if PDEKIT_HAVE_TRILINOS
std::cout << "LSS with trilinos support" << std::endl;
#else
std::cout << "LSS without trilinos support" << std::endl;
#endif
}
/// Print the values of the matrix
friend std::ostream &operator<<(std::ostream &os, const TrilinosCrsMatrix &tril_crs_mat);
private:
friend class LSTrilinos;
/// Trilinos communicator object
/// Takes MPI communicator in constructor
Epetra_MpiComm m_comm;
/// Map - needed to create the matrix
std::shared_ptr<Epetra_Map> m_map;
/// Sparse distributed matrix from Trilinos
Teuchos::RCP<Epetra_CrsMatrix> m_epetra_matrix;
};
} // namespace ls
} // namespace pdekit
#endif // PDEKIT_HAVE_TRILINOS
#endif // PDEKIT_Trilinos_Sparse_Matrix_hpp
| true |
176517fc85f99d50aa9d8bce7ac62f31262c8452 | C++ | Dardariel/fantasies | /Server/world.h | UTF-8 | 1,147 | 2.53125 | 3 | [] | no_license | #ifndef WORLD_H
#define WORLD_H
#include <QObject>
#include <QList>
#include <QTimer>
#include "objects.h"
#include <QJsonObject>
enum OperationsObject
{
DELETE,
REMAP
};
class World : public QObject
{
Q_OBJECT
public:
World(unsigned int x, unsigned int y, QObject *parent = nullptr);
bool enterNewObjectCircle(unsigned int x, unsigned int y, unsigned int radius, TypesObject type=TypesObject::CIRCLE);
bool entrance(Circle *object);
void sendState();
signals:
void sendStateWorld(QByteArray);
public slots:
void setAreaWorld(unsigned int x, unsigned int y);
void setTypeOperation(OperationsObject type);
void startWorld();
void pauseWorld();
private slots:
void slotTimer();
private:
unsigned int LenghtX;
unsigned int LenghtY;
unsigned int LastId;
OperationsObject TypeOperation;
QList<Circle *> ObjectsLists;
QTimer *timer;
void entranceAllObjects();
void clearJsonObject(QJsonObject *obj)
{
for(int i=obj->keys().count()-1; i>=0; i--)
{
obj->remove(obj->keys().at(i));
}
}
};
#endif // WORLD_H
| true |
8f1197609508acd6f711756765c4e265ecc5cadc | C++ | wangyongliang/nova | /poj/2325/POJ_2325_2735057_AC_78MS_80K.cpp | UTF-8 | 864 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
char s[1100];
int a[1100];
char ans[1100];
int div(int n)
{
int k;
int i=0,j=0;
k=0;
while(s[i])
{
k=k*10+s[i]-'0';
ans[j]=k/n+'0';
k%=n;
i++;
j++;
}
if(!k)
{
ans[j]='\0';
for(i=0;ans[i];i++)
{
if(ans[i]!='0') break;
}
strcpy(s,ans+i);
return 1;
}
else return 0;
}
int main()
{
int i;
int j;
while(scanf("%s",s)!=EOF)
{
j=0;
if(s[0]=='-') break;
if(strlen(s)==1)
{
printf("1%s\n",s);
continue;
}
for(i=9;i>1;i--)
{
if(strlen(s)==1)
{
if(s[0]!='1') a[j++]=s[0]-'0';
s[0]='\0';
break;
}
while(div(i))
{
a[j++]=i;
}
}
if(strlen(s)==0)
{
for(j--;j>=0;j--) printf("%d",a[j]);
printf("\n");
}
else printf("There is no such number.\n");
}
return 0;
}
| true |
4bfbe0cf07c38406952f5010478471564f5d1463 | C++ | juniorxsound/Ray-Tracer | /src/Object3D.h | UTF-8 | 854 | 2.71875 | 3 | [] | no_license | #ifndef _OBJECT3D_H_
#define _OBJECT3D_H_
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <tuple>
//Base class for everything that lives in the 3D space
class Object3D {
public:
Object3D();
~Object3D();
//Origin only construction
Object3D(Eigen::Vector3d);
//Origin and direction
Object3D(Eigen::Vector3d, Eigen::Vector3d);
/**************
* Class methods
**************/
Eigen::Vector3d& getOrigin();
Eigen::Vector3d getDirection();
void translate(Eigen::Vector3d);
void scale(Eigen::Vector3d);
void rotate(Eigen::Vector3d rotation);
void setX(double displace);
void setY(double displace);
void setZ(double displace);
static Eigen::Vector3d ScreenToWorld(Eigen::Vector3d);
protected:
Eigen::Vector3d o;
Eigen::Vector3d d;
};
#endif | true |
837c8c3a2bcbfea9fd5aac5889655796793cd42a | C++ | MORTAL2000/OpenGLEngine | /JuMenu/JuMenuResourceManager.h | UTF-8 | 2,554 | 2.671875 | 3 | [
"MIT"
] | permissive | #ifndef JUMENURESMANTEST_H
#define JUMENURESMANTEST_H
#include <string>
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
#include <vector>
#include <unordered_map>
#include "resources/imageresource.h"
#include "resources/writerresource.h"
#include "JuMenuDeps.h"
namespace JuMenu {
/* --------------------------------
Aliases
---------------------------------- */
typedef std::unordered_map< std::string,std::shared_ptr<MenuResourceBase> > resource_umap;
/* ------------------------------------
Menu Resource Manager
Allows for dependency injection into the
primary Menu Class.
-------------------------------------- */
class MenuResourceManager {
/* Audio Engine Pointer */
ISoundEngine* audioengine;
/* Properties Pointer */
Properties* props;
/* Maps and Stacks */
resource_umap umap;
std::vector<std::string> add_resourcestack;
std::vector<std::string> rmv_resourcestack;
static void thr_loader(std::shared_ptr<MenuResourceBase> p,std::string filename) {
// shared use_count is incremented
//static std::mutex load_mutex;
//std::lock_guard<std::mutex> lk(load_mutex);
p.get()->Init(filename);
};
public:
/* Constructor */
MenuResourceManager () {};
/* Destructor */
~MenuResourceManager () {};
void Init(Properties* props,ISoundEngine* audioengine) {
this->props = props;
this->audioengine = audioengine;
}
/*------------------------------------
Function for Requesting Resources
-------------------------------------*/
std::shared_ptr<MenuResourceBase> requestResource( std::string ident );
/* ----------------------------------------------
This function loads all resources in the stack
------------------------------------------------*/
void manageResources( void );
/*------------------------------------
Print Loaded Stuff
-------------------------------------*/
void printLoad() {
for (auto&& i : umap) {
if (i.second.get()->is_loaded()) {
std::cout << i.first << " LOADED!" << std::endl;
} else {
std::cout << i.first << " WAITING!" << std::endl;
};
}
std::cout << "nresources: " << umap.size() << std::endl;
};
/* Class Access */
const Properties* getProps() {
return props;
};
ISoundEngine* getAudEng() {
return audioengine;
};
};
};
#endif
| true |
36ea8fe5b3023133602b99f19b5686a60ac2d2b7 | C++ | luk036/lineda | /recti/geo_iter.hpp | UTF-8 | 2,490 | 3.40625 | 3 | [] | no_license | #ifndef RECTI_GEO_ITERATOR
#define RECTI_GEO_ITERATOR
namespace recti {
template <class Iterator>
/** Iterator with x() and y() member functions */
class geo_iterator {
typedef geo_iterator<Iterator> _Self;
public:
typedef typename Iterator::value_type::value_type value_type;
/** Create an iterator from base class */
geo_iterator(Iterator &it) : _it(it) {}
/** @return the x value */
value_type x() const { return _it->x(); }
/** @return the y value */
value_type y() const { return _it->y(); }
/** @return the next iterator */
_Self next() const {
Iterator it = _it.next();
return _Self(it);
}
/** Prefix increment: advance one node */
_Self &operator++() {
++_it;
return *this;
}
/** Postfix increment: advance one node */
_Self operator++(int) {
_Self old(*this);
++*this;
return old;
}
/** Prefix decrement: advance backward one node */
_Self &operator--() {
--_it;
return *this;
}
/** Postfix decrement: advance backward one node */
_Self operator--(int) {
_Self old(*this);
--*this;
return old;
}
/** Equal */
bool operator==(const _Self &x) const { return _it == x._it; }
/** Not equal */
bool operator!=(const _Self &x) const { return _it != x._it; }
private:
Iterator _it;
};
/** Dual iterator of geo_iterator, i.e. x() and y() are interchange */
template <class Iterator> class geo_dual_iterator {
typedef geo_dual_iterator<Iterator> _Self;
public:
typedef typename Iterator::value_type::value_type value_type;
/** Create an iterator from base class */
geo_dual_iterator(Iterator &it) : _it(it) {}
value_type x() const { return _it->y(); }
value_type y() const { return _it->x(); }
_Self next() const {
Iterator it = _it.next();
return _Self(it);
}
/** Prefix increment: advance one node */
_Self &operator++() {
++_it;
return *this;
}
/** Postfix increment: advance one node */
_Self operator++(int) {
_Self old(*this);
++*this;
return old;
}
/** Prefix decrement: advance backward one node */
_Self &operator--() {
--_it;
return *this;
}
/** Postfix decrement: advance backward one node */
_Self operator--(int) {
_Self old(*this);
--*this;
return old;
}
/** Equal */
bool operator==(const _Self &x) const { return _it == x._it; }
/** Not equal */
bool operator!=(const _Self &x) const { return _it != x._it; }
private:
Iterator _it;
};
}
#endif
| true |
fc706f41c6b3f1db1e03a4d4ee8f8fa10fef8dbe | C++ | Kwongy/Online_Judge | /PAT/DataStruct(chinese)/7-23.cpp | UTF-8 | 589 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
int n;
string preorder;
string inorder;
int Max = 0;
void dfs(int pre_l, int pre_r, int in_l, int in_r, int level){
if(pre_l > pre_r || in_l > in_r) return;
if(level > Max) Max = level;
char index = preorder[pre_l], i = in_l;
while(inorder[i] != index) i++;
cout << index << endl;
dfs(pre_l + 1, pre_l + i - in_l, in_l, i - 1, level + 1);
dfs(pre_l + i - in_l + 1, pre_r, i + 1, in_r, level + 1);
}
int main(){
freopen("aa.txt","r",stdin);
cin >> n;
cin >> preorder >> inorder;
dfs(0, n-1, 0, n-1, 1);
cout << Max << endl;
return 0;
}
| true |
6e8ac771e31d9158c3aa5337ad6774a5d089ab53 | C++ | smusman/CSE-102_Computer-Programming | /Programs/FinalsPractice/practice (6).cpp | UTF-8 | 236 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main ()
{
string s;
cout<<"Write Something to the file> ";
ofstream outfile("new.txt");
outfile<<s;
return 0;
}
| true |
f8b031db175183aaef2071d246b1d99f6bd81225 | C++ | macpd/experimental | /cpp_primer/chapter7/array_range.cc | UTF-8 | 769 | 4.03125 | 4 | [] | no_license | #include <iostream>
const int SIZE = 10;
/* assignes n to all elements of array a, starting at start and upto (but not
* including) end*/
void assignArrayRange(int* a, int* end, int val);
int main() {
using std::cout;
using std::endl;
int array[SIZE];
cout << "assigning 4 to elements 0-4" << endl;
assignArrayRange(array, &array[5], 4);
cout << "assigning 10 to elements 5-9" << endl;
assignArrayRange(&array[5], &array[SIZE], 10);
cout << "final array values:" << endl;
for(int i = 0; i < SIZE; i++) {
cout << "array[" << i << "]: " << array[i] << endl;
}
return 0;
}
void assignArrayRange(int* a, int* end, int val) {
for(int i = 0; a+i != end; i++) {
std::cerr << "a+" << i << std::endl;
*(a+i) = val;
}
return;
}
| true |
3a732d2167a24916c7b5254b3e96fc47404518c5 | C++ | MichaelEBurton/PPP_Cpp | /Chapter11/Exercises/exercise13.cpp | UTF-8 | 1,901 | 3.734375 | 4 | [] | no_license | /*
Exercise 13: Reverse the order of words (defined as whitespace-separated strings) in a file. For example, Norwegian
Blue parrot becomes parrot Blue Norwegian. You are allowed to assume that all the strings from the
file will fit into memory at once.
Notes: Could improve by fixing how punctuation is handled.
*/
#include "../../../std_lib_facilities.h"
//===================================================================================================================================
vector<string> get_words(ifstream& is)
{
vector<string> words;
while(!is.eof())
{
string s;
is>>s;
words.push_back(s);
}
return words;
}
void print_words(ofstream& os, vector<string> words)
{
for(int i = words.size() - 1; i >= 0; --i)
{
os<<words[i]<<' ';
}
}
//===================================================================================================================================
// File names
string get_input_file()
{
string iname;
cout<<"What is the name of the file you wish to read: ";
cin>>iname;
return iname;
}
string get_output_file()
{
string oname;
cout<<"\nWhat is the name of the file you wish to write: ";
cin>>oname;
return oname;
}
//===================================================================================================================================
int main()
try{
string iname = get_input_file();
ifstream ist{iname};
if(!ist) error("Cannot open file ", iname);
string oname = get_output_file();
ofstream ost{oname};
if(!ost) error("Cannot open file ", oname);
vector<string> words = get_words(ist);
print_words(ost, words);
return 0;
}
catch(exception& e){
cerr<<"Error: "<<e.what()<<'\n';
return 1;
}
catch(...) {
cerr<<"Oops, unknown error!\n";
return 2;
} | true |
f311d09823702b866fb45d63f8b7aab10839eb02 | C++ | metaphaseaudio/metaphase_core | /inc/meta/util/math.h | UTF-8 | 5,279 | 2.90625 | 3 | [
"MIT"
] | permissive | //
// Created by Matt Zapp on 4/28/2018.
//
#pragma once
#include <cmath>
#include <type_traits>
#include <limits>
#include <array>
#include <cmath>
#include <iostream>
#include "NumericConstants.h"
namespace meta
{
template <typename Type, Type Value>
struct static_negate { static constexpr Type value = -Value; };
template <typename NumericType>
NumericType wrap(NumericType x, NumericType lower, NumericType upper)
{
auto range = upper - lower + 1;
if (x < lower)
{ x += range * ((lower - x) / range + 1); }
return lower + fmodf(x - lower, range);
}
template <typename NumericType>
constexpr NumericType limit(NumericType low, NumericType high, NumericType value)
{ return value < low ? low : (high < value ? high : value); }
template <typename T> constexpr T abs(T i){ return i < 0 ? -1 * i : i; }
template <typename T> constexpr T fabs(T i) { return std::fabs(i); }
template <typename NumericType>
struct Interpolate
{
static constexpr NumericType linear(NumericType a, NumericType b, NumericType weight)
{ return (a * (1 - weight)) + (b * weight); }
static constexpr NumericType parabolic
(NumericType a, NumericType b, NumericType weight, NumericType exponent=2)
{
if (fabs(exponent) < 0.001) { return linear(a, b, weight); }
const auto ratio = (1 - exp(exponent * weight)) / (1 - exp(exponent));
return a + (b - a) * ratio;
}
};
template <typename NumericType>
constexpr NumericType power(NumericType base, size_t exponent)
{ return exponent == 0 ? 1 : base * power(base, exponent - 1);}
template <size_t base, size_t exponent>
struct static_power {
static constexpr size_t value = base * static_power<base, exponent - 1>::value;
};
template <size_t base> struct static_power<base, 0> { static constexpr size_t value = 1; };
template <typename NumericType, NumericType in>
struct static_abs {
static constexpr NumericType value = (in >= 0) ? in : - in;
};
template<std::size_t... Is> struct seq{};
template<std::size_t N, std::size_t... Is>
struct gen_seq: gen_seq<N-1, N, Is...> {};
template<std::size_t... Is>
struct gen_seq<0, Is...> : seq<Is...>{};
template<class T,class dcy = std::decay_t<T>>
constexpr inline std::enable_if_t<std::is_floating_point<T>::value,dcy> inverse(T value){
return (value == 0) ? 0.0 : 1.0 / value;
}
constexpr inline long double factorial(std::intmax_t const& n){
if(n==0){return 1;}
long double result = n;
for(std::intmax_t i=n-1;i>0;--i){
result *=i;
}
return result;
}
constexpr inline std::size_t max_factorial(){
std::size_t i=0;
long double d=0;
while ((d= factorial(i))<std::numeric_limits<long double>::max()){++i;}
return i;
}
template<class base,std::size_t N>
class trig_coeffs {
using T = typename base::value_type;
using array_type = std::array<T,N>;
template<std::size_t ... NS>
constexpr static inline array_type _coeffs(seq<NS ...>){
return {{base::coeff(NS) ...}};
}
public:
constexpr static array_type coeffs=_coeffs(gen_seq<N>{});
};
template<class base,std::size_t N>
constexpr typename trig_coeffs<base,N>::array_type trig_coeffs<base,N>::coeffs;
template<class base,std::size_t N, class dcy = std::decay_t<typename base::value_type>>
constexpr std::enable_if_t<std::is_floating_point<dcy>::value,dcy>
_sincos(typename base::value_type x) noexcept{
using c = trig_coeffs<base,N>;
dcy result = 0.0;//result accumulator
//do input range mapping
dcy _x =base::range_reduce(x);
//taylor series
{
const dcy x_2 = _x*_x; //store x^2
dcy pow = base::initial_condition(_x);
for(auto&& cf: c::coeffs){
result += cf * pow;
pow*=x_2;
}
}
return result;
}
namespace detail{
template<class T>
struct _sin{
using value_type = T;
constexpr static inline T coeff(std::size_t n)noexcept {
return (n % 2 ? 1 : -1) * inverse(factorial((2 * n)-1));
}
constexpr static inline T range_reduce(T x)noexcept{
T _x = x;
_x += NumericConstants<T>::PI;
_x -= static_cast<std::size_t>(_x / NumericConstants<T>::TWO_PI) * NumericConstants<T>::TWO_PI;
_x -= NumericConstants<T>::PI;
return _x;
}
constexpr static inline T initial_condition(T x)noexcept{
return x;
}
constexpr static inline std::size_t default_N()noexcept{
return 16;
}
};
}
template<class T,std::size_t N = detail::_sin<T>::default_N()>
constexpr inline std::decay_t<T> sin(T x) noexcept {
return _sincos<detail::_sin<T>,N>(x);
}
template<class T>
constexpr inline std::decay_t<T> cos(T x) noexcept { return sin(x - meta::NumericConstants<T>::PI);}
}
| true |
f70133247dc9999dbc76aa34dd19dd71cae96c72 | C++ | Pchemelil/UsingIfStatements | /UsingIfStatements.cpp | UTF-8 | 238 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int age;
cout<<"Please enter their age:\n";
cin>> age;
if (age>=4){
cout<< "admit child to school.";
} else
cout<<"do not admit child";
return 0;
}
| true |
e9cf611c9f3036b0bdd342519ff12101eaf6e46e | C++ | soumyadeep-khandual/assignment-1 | /assignment 2/tsk207.cpp | UTF-8 | 333 | 3.359375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main ()
{
float a, b, c, d;
cout<<"enter 1st angle in degrees\n";
cin>>a;
cout<<"enter 2nd angle in degrees\n";
cin>>b;
d=a+b;
c=180-d;
if(d<180){
cout<<"the 3rd angle in degrees = "<<c<<"\n";}
else {cout<< "error; sum of 2 angles of a triangle cannot be greater than 180\n";}
return 0;
}
| true |
a4ff9c2e80c6e10304879b82ffab9831fb7bb9c2 | C++ | dbielawski/Nachos | /nachos/code/userprog/exception.cc | UTF-8 | 8,144 | 2.828125 | 3 | [
"MIT-Modern-Variant"
] | permissive | // exception.cc
// Entry point into the Nachos kernel from user programs.
// There are two kinds of things that can cause control to
// transfer back to here from user code:
//
// syscall -- The user code explicitly requests to call a procedure
// in the Nachos kernel. Right now, the only function we support is
// "Halt".
//
// exceptions -- The user code does something that the CPU can't handle.
// For instance, accessing memory that doesn't exist, arithmetic errors,
// etc.
//
// Interrupts (which can also cause control to transfer from user
// code into the Nachos kernel) are handled elsewhere.
//
// For now, this only handles the Halt() system call.
// Everything else core dumps.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "system.h"
#include "syscall.h"
#ifdef CHANGED
#include "synchconsole.h"
#include "userthread.h"
#endif // end CAHANGED
//----------------------------------------------------------------------
// UpdatePC : Increments the Program Counter register in order to resume
// the user program immediately after the "syscall" instruction.
//----------------------------------------------------------------------
static void
UpdatePC ()
{
int pc = machine->ReadRegister (PCReg);
machine->WriteRegister (PrevPCReg, pc);
pc = machine->ReadRegister (NextPCReg);
machine->WriteRegister (PCReg, pc);
pc += 4;
machine->WriteRegister (NextPCReg, pc);
}
//----------------------------------------------------------------------
// ExceptionHandler
// Entry point into the Nachos kernel. Called when a user program
// is executing, and either does a syscall, or generates an addressing
// or arithmetic exception.
//
// For system calls, the following is the calling convention:
//
// system call code -- r2
// arg1 -- r4
// arg2 -- r5
// arg3 -- r6
// arg4 -- r7
//
// The result of the system call, if any, must be put back into r2.
//
// And don't forget to increment the pc before returning. (Or else you'll
// loop making the same system call forever!
//
// "which" is the kind of exception. The list of possible exceptions
// are in machine.h.
//----------------------------------------------------------------------
void
ExceptionHandler (ExceptionType which)
{
int type = machine->ReadRegister (2);
if (MAX_STRING_SIZE < 2)
{
printf ("La taille du buffer doit etre superieure a 1\n");
ASSERT(FALSE);
}
switch (which)
{
case SyscallException:
{
switch (type)
{
case SC_Halt:
{
DEBUG ('s', "Shutdown, initiated by user program.\n");
interrupt->Halt ();
break;
}
#ifdef CHANGED
case SC_Exit:
{
DEBUG ('s', "Exit, initiated by user program.\n");
// On recupere l'aguement dans le registre 4
// int code = machine->ReadRegister(4);
// printf("Le programme s'est terminé avec le code de retour: %i\n", code);
// interrupt->Halt();
do_Exit();
break;
}
case SC_PutChar:
{
DEBUG ('s', "PutChar, initiated by user program.\n");
int c = machine->ReadRegister (4);
synchconsole->SynchPutChar(c);
break;
}
case SC_PutString:
{
DEBUG ('s', "PutString, initiated by user program.\n");
if (MAX_STRING_SIZE < 2)
{
printf("PutString, le taille du tampon doit etre superieure a 1 !");
ASSERT(FALSE);
}
char* buffer = (char*)malloc(MAX_STRING_SIZE * sizeof(char));
int c = machine->ReadRegister (4);
int nbCharCopie = 0;
int i = 0;
do
{
nbCharCopie = copyStringFromMachine(i * MAX_STRING_SIZE + c, buffer, MAX_STRING_SIZE);
synchconsole->SynchPutString(buffer);
++i;
} while (nbCharCopie == MAX_STRING_SIZE);
free(buffer);
break;
}
case SC_GetChar:
{
DEBUG ('s', "GetChar, initiated by user program.\n");
int c = synchconsole->SynchGetChar();
machine->WriteRegister(2, c);
break;
}
case SC_GetString:
{
DEBUG ('s', "GetString, initiated by user program.\n");
int s = machine->ReadRegister(4);
int taille = machine->ReadRegister(5);
char* buffer = (char*)malloc(sizeof(char) * MAX_STRING_SIZE);
synchconsole->SynchGetString(buffer, taille);
int nbCharCopie = copyStringToMachine(buffer, s, taille);
free(buffer);
break;
}
case SC_PutInt:
{
DEBUG ('s', "PutInt, initiated by user program.\n");
int entier = machine->ReadRegister(4);
synchconsole->SynchPutInt(entier);
break;
}
case SC_GetInt:
{
DEBUG ('s', "GetInt, initiated by user program.\n");
int n;
synchconsole->SynchGetInt(&n);
int s = machine->ReadRegister(4);
machine->WriteMem(s, sizeof(int), n);
break;
}
case SC_ThreadCreate:
{
DEBUG ('s', "ThreadCreate, initiated by user program.\n");
int f = machine->ReadRegister(4);
int arg = machine->ReadRegister(5);
if (do_CreateThread(f, arg) < 0)
{
printf("Erreur lors de la creation du thread\n");
//ASSERT(FALSE);
}
break;
}
case SC_ThreadExit:
{
DEBUG ('s', "ThreadExit, initiated by user program.\n");
do_ThreadExit();
break;
}
case SC_ForkExec:
{
DEBUG ('s', "SC_ForkExec, initiated by user program.\n");
if (MAX_STRING_SIZE < 2)
{
printf("ForkExec, le taille du tampon doit etre superieure a 1 !\n");
ASSERT(FALSE);
}
int c = machine->ReadRegister (4);
// Tres moche...
char filename[100];
copyStringFromMachine(c, filename, 100);
ForkExec(filename);
break;
}
#endif // end CHANGED
default:
{
printf("Unimplemented system call %d\n", type);
ASSERT(FALSE);
}
}
// Do not forget to increment the pc before returning!
UpdatePC ();
break;
}
case PageFaultException:
if (!type) {
printf("NULL dereference at PC %x!\n", machine->registers[PCReg]);
ASSERT (FALSE);
} else {
printf ("Page Fault at address %x at PC %x\n", type, machine->registers[PCReg]);
ASSERT (FALSE); // For now
}
default:
printf ("Unexpected user mode exception %d %d at PC %x\n", which, type, machine->registers[PCReg]);
ASSERT (FALSE);
}
}
#ifdef CHANGED
// Copie une chaine du mode user vers un tampon dans lespace kernel.
// from : adresse de lespace user
// to : buffer dans lespace kernel
// size : taille du buffer du mode kernel
// return le nombre delements reelement copie dans to
int copyStringFromMachine(int from, char* to, unsigned size)
{
if (!to || size < 2)
return 0;
else
{
int v;
unsigned i = 0;
// Tant que nous ne sommes pas en fin de chaine et que nous n'avons pas
// ecris plus que la taille limite du buffer, size,
// ecrire dans le buffer du kernel
do
{
if (machine->ReadMem(from + i, sizeof(char), &v))
to[i] = v;
++i;
} while (v != '\0' && i < size);
to[i] = '\0';
return i;
}
}
// Copie une chaine du mode kernel dans un tampon du mode user
// s: la chaine a copier
// to: pointeur sur adresse (mode user)
// size: taille du tampon
int copyStringToMachine(char* s, int to, unsigned size)
{
// Traite les cas non valides (pointeur null, buffer trop petit)
if (!to || size < 2)
return 0;
else
{
// Compteur du nombre de caracteres copies
unsigned i = 0;
// Copie les caracteres dans to
for (i = 0; i < size && s[i]; ++i)
{
machine->WriteMem(to, sizeof(char), s[i]);
++to;
}
// On s'assure que to fini par un retour a la ligne
// pour ne pas que les caracteres tapes soient concatenes
machine->WriteMem(to, sizeof(char), '\n');
return i;
}
}
#endif // end CHAGNED | true |
b641a5836e29599e2ec470cd27ad46c4232a5625 | C++ | zruslan2/Kontroln | /KontrRab/Function.cpp | WINDOWS-1251 | 2,995 | 3.546875 | 4 | [] | no_license | #include <stdint.h>
#include <iostream>
using namespace std;
/*17. , ,
- .*/
void sum(int *arr, int r, int &s, int &p)
{
s = 0;
p = 1;
for (int i = 0;i < r;i++)
{
s += arr[i];
p*= arr[i];
}
}
/*18. 17 ( 2 :
1. ; 2 - )
a. int
b. double
c. Shor int*/
void sum(int(*arr)[3],int r, int &s, int &p)
{
s = 0;
p = 1;
for (int i = 0;i < r;i++)
{
for (int j = 0;j < 3;j++)
{
s += arr[i][j];
p *= arr[i][j];
}
}
}
void sum(short(*arr)[3], int r, short &s, short &p)
{
s = 0;
p = 1;
for (int i = 0;i < r;i++)
{
for (int j = 0;j < 3;j++)
{
s += arr[i][j];
p *= arr[i][j];
}
}
}
void sum(double(*arr)[3], int r, double &s, double &p)
{
s = 0;
p = 1;
for (int i = 0;i < r;i++)
{
for (int j = 0;j < 3;j++)
{
s += arr[i][j];
p *= arr[i][j];
}
}
}
/*19. , , .*/
void printArr(int *arr, int r)
{
for (int i = 0;i < r;i++)
{
cout << arr[i]<<"\t";
}
}
void printMatrix(int(*arr)[3], int r)
{
for (int i = 0;i < r;i++)
{
for (int j = 0;j < 3;j++)
{
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
/*20. , ( ,
), ,
, .
enum. (enum ,
)*/
int f (int*arr, int*arrP, int (*func)(int*, int*))
{
int c;
c=func(arr, arrP);
return c;
}
int otr(int*arr, int*arrP)
{
int count = 0;
while (*arr != *arrP)
{
if (*arr < 0)count++;
arr++;
}
return count;
}
int pol(int*arr, int*arrP)
{
int count = 0;
while (*arr != *arrP)
{
if (*arr > 0)count++;
arr++;
}
return count;
}
int zero (int*arr, int*arrP)
{
int count = 0;
while (*arr != *arrP)
{
if (*arr == 0)count++;
arr++;
}
return count;
} | true |
0f5b91a27e98409e61c9a720b31ad0ddee7c5df2 | C++ | jjungkang2/2018-2020.Waddle-Corp | /2018.11-braille/braille/WordToBraille.cpp | UTF-8 | 1,298 | 3.234375 | 3 | [] | no_license | #include "BrailleToWord.h"
#include "WordToBraille.h"
Word::Word(){}
void Word::Init(char *in_word){
word = in_word, wordlen = 0;
while(word[wordlen] != '\0'){
wordlen++;
}
}
Braille Word::WordToBraille(){
int *bin = (int*)malloc(sizeof(int) * 500), langmode = 0;
binlen = 0;
for(int i = 0; i < wordlen; i++){
if(word[i] >= 'a' && word[i] <= 'z'){
if(langmode == 1){
bin[binlen++] = AsciiToBin(';');
langmode = 0;
}
bin[binlen++] = AsciiToBin(word[i]);
}
else if(word[i] >= '0' && word[i] <= '9'){
if(langmode == 0){
bin[binlen++] = AsciiToBin('#');
langmode = 1;
}
if(word[i] == '0'){
bin[binlen++] = AsciiToBin('j');
}
else{
bin[binlen++] = AsciiToBin(word[i] - '1' + 'a');
}
}
else if(word[i] == '.'){
bin[binlen++] = AsciiToBin('4');
}
else if(word[i] == '!'){
langmode = 0;
bin[binlen++] = AsciiToBin('6');
}
else if(word[i] == '?'){
langmode = 0;
bin[binlen++] = AsciiToBin('8');
}
else if(word[i] == ' '){
langmode = 0;
bin[binlen++] = AsciiToBin(' ');
}
}
Braille return_bin;
return_bin.Init(bin, binlen);
return return_bin;
}
int Word::WordLen(){
return wordlen;
}
char Word::get(int index){
return word[index];
}
void Word::FreeWord(){
free(word);
return;
}
| true |
d719214c62c0101ed78d8d2a521b57d20e363f87 | C++ | nawal1775/DNAString- | /DNAStrings.cpp | UTF-8 | 12,420 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <fstream> //for file access
#include <random>
using namespace std;
int main(int argc, char** argv)
{
if (argc > 1)
{
cout << "argv[1] = " << argv[1] << endl;
}
else
{
cout << "No file name entered. Exiting...";
return -1;
}
ifstream infile(argv[1]); //open the file
ofstream outputFile; // copy to a file
outputFile.open("Nawal.out");
if (infile.is_open() && infile.good())
{
cout << "File is now open:\n" << endl;
string line = "";
int count = 0;
int sum = 0;
int mean;
int addingsquaredlines = 0;
// for probability
int occurrences_A;
double probability_A;
int occurrences_T;
double probability_T;
int occurrences_G;
double probability_G;
int occurrences_C;
double probability_C;
int occurrences_AA;
double probability_AA;
int occurrences_AT;
double probability_AT;
int occurrences_AG;
double probability_AG;
int occurrences_AC;
double probability_AC;
int occurrences_TA;
double probability_TA;
int occurrences_TG;
double probability_TG;
int occurrences_TC;
double probability_TC;
int occurrences_TT;
double probability_TT;
int occurrences_CC;
double probability_CC;
int occurrences_CG;
double probability_CG;
int occurrences_CA;
double probability_CA;
int occurrences_CT;
double probability_CT;
int occurrences_GG;
double probability_GG;
int occurrences_GC;
double probability_GC;
int occurrences_GA;
double probability_GA;
int occurrences_GT;
double probability_GT;
char c;
char d;
int countA = 0;
int countT = 0;
int countG = 0;
int countC = 0;
int countAA = 0;
int countAT = 0;
int countAG = 0;
int countAC = 0;
int countCA = 0;
int countCT = 0;
int countCG = 0;
int countCC = 0;
int countGA = 0;
int countGT = 0;
int countGG = 0;
int countGC = 0;
int countTA = 0;
int countTT = 0;
int countTG = 0;
int countTC = 0;
while (getline(infile, line))
{
// cout << line << endl;
// cout << line.size()-1 << endl;
// to find the length of DNA strings and adding it up (sum of DNA strings)
sum += line.size()-1;
// to find the number of lines
count++;
// squaring number of strings in each line and adding them up for variance calculation
addingsquaredlines += pow(line.size()-1,2);
// cout << addingsquaredlines << endl;
// for loop to iterate through list of strings and find the occurrences of each nucleotide and nucleotide biagram
for (int i =0; i<sum; ++i)
{
c = line[i];
d = line[i-1];
if(c == 'A')
{
countA++;
if (d == 'A')
{
countAA++;
}
if (d == 'T')
{
countAT++;
}
if (d == 'G')
{
countAG++;
}
if (d == 'C')
{
countAC++;
}
}
else if (c == 'T')
{
countT++;
if (d == 'A')
{
countTA++;
}
if (d == 'G')
{
countTG++;
}
if (d == 'C')
{
countTC++;
}
if (d == 'T')
{
countTT++;
}
}
else if (c == 'G')
{
countG++;
if (d == 'A')
{
countGA++;
}
if (d == 'G')
{
countGG++;
}
if (d == 'C')
{
countGC++;
}
if (d == 'T')
{
countGT++;
}
}
else if (c == 'C')
{
countC++;
if (d == 'A')
{
countCA++;
}
if (d == 'G')
{
countCG++;
}
if (d == 'C')
{
countCC++;
}
if (d == 'T')
{
countCT++;
}
}
}
}
// printing out the number of lines, mean, variance and std.
outputFile << "The number of lines in the file is: " << count <<endl;
outputFile << "The sum of DNA strings' length is: " << sum <<endl;
// cout << "each line of the DNA squared indivisually and added equals: " << addingsquaredlines <<endl;
mean = sum/count;
outputFile << "Mean equals: " << mean << endl;
// calculating variance w/o using arrays
float sum_square = pow((sum),2);
float devide_by_linesnum = sum_square/count;
float substract = addingsquaredlines - devide_by_linesnum;
float substract_one = count - 1;
float variance = substract/substract_one;
outputFile << "Variance equals: " << variance << endl;
// calculating Standard deviation
float square_root = pow(variance,0.5);
outputFile << "Standard deviation equals: " << square_root << endl;
//counting the probability for each nucleotide and nucleotide biagram
occurrences_A = countA;
probability_A = (double) occurrences_A / sum;
occurrences_T = countT;
probability_T = (double) occurrences_T / sum;
occurrences_G = countG;
probability_G = (double) occurrences_G / sum;
occurrences_C = countC;
probability_C = (double) occurrences_C / sum;
outputFile << "The probability of A in the sequence equals: " <<probability_A << ", " << probability_A*100 <<"% "<< occurrences_A << " A's" << endl;
outputFile << "The probability of T in the sequence equals: " <<probability_T << ", " << probability_T*100 <<"% "<< occurrences_T << " T's" << endl;
outputFile << "The probability of G in the sequence equals: " <<probability_G << ", " << probability_G*100 <<"% "<< occurrences_G << " G's" << endl;
outputFile << "The probability of C in the sequence equals: " <<probability_C << ", " << probability_C*100 <<"% "<< occurrences_C << " C's \n" << endl;
occurrences_AA = countAA;
probability_AA = (double) occurrences_AA / sum;
outputFile << "The probability of AA in the sequence equals: " <<probability_AA << ", " << probability_AA*100 <<"% "<< occurrences_AA << " AA's" << endl;
occurrences_AT = countAT;
probability_AT = (double) occurrences_AT / sum;
outputFile << "The probability of AT in the sequence equals: " <<probability_AT << ", " << probability_AT*100 <<"% "<< occurrences_AT << " AT's" << endl;
occurrences_AG = countAG;
probability_AG = (double) occurrences_AG / sum;
outputFile << "The probability of AG in the sequence equals: " <<probability_AG << ", " << probability_AG*100 <<"% "<< occurrences_AG << " AG's" << endl;
occurrences_AC = countAC;
probability_AC = (double) occurrences_AC / sum;
outputFile << "The probability of AC in the sequence equals: " <<probability_AC << ", " << probability_AC*100 <<"% "<< occurrences_AC << " AC's\n" << endl;
occurrences_TA = countTA;
probability_TA = (double) occurrences_TA / sum;
outputFile << "The probability of TA in the sequence equals: " <<probability_TA << ", " << probability_TA*100 <<"% "<< occurrences_TA << " TA's" << endl;
occurrences_TC = countTC;
probability_TC = (double) occurrences_TC / sum;
outputFile << "The probability of TC in the sequence equals: " <<probability_TC << ", " << probability_TC*100 <<"% "<< occurrences_TC << " TC's" << endl;
occurrences_TT = countTT;
probability_TT = (double) occurrences_TT / sum;
outputFile << "The probability of TT in the sequence equals: " <<probability_TT << ", " << probability_TT*100 <<"% "<< occurrences_TT << " TT's" << endl;
occurrences_TG = countTG;
probability_TG = (double) occurrences_TG / sum;
outputFile << "The probability of TG in the sequence equals: " <<probability_TG << ", " << probability_TG*100 <<"% "<< occurrences_TG << " TG's\n" << endl;
occurrences_GA = countGA;
probability_GA = (double) occurrences_GA / sum;
outputFile << "The probability of GA in the sequence equals: " <<probability_GA << ", " << probability_GA*100 <<"% "<< occurrences_GA << " GA's" << endl;
occurrences_GC = countGC;
probability_GC = (double) occurrences_GC / sum;
outputFile << "The probability of GC in the sequence equals: " <<probability_GC << ", " << probability_GC*100 <<"% "<< occurrences_GC << " GC's" << endl;
occurrences_GT = countGT;
probability_GT = (double) occurrences_GT / sum;
outputFile << "The probability of GT in the sequence equals: " <<probability_GT << ", " << probability_GT*100 <<"% "<< occurrences_GT << " GT's" << endl;
occurrences_GG = countGG;
probability_GG = (double) occurrences_GG / sum;
outputFile << "The probability of GG in the sequence equals: " <<probability_GG << ", " << probability_GG*100 <<"% "<< occurrences_GG << " GG's\n" << endl;
occurrences_CA = countCA;
probability_CA = (double) occurrences_CA / sum;
outputFile << "The probability of CA in the sequence equals: " <<probability_CA << ", " << probability_CA*100 <<"% "<< occurrences_CA << " CA's" << endl;
occurrences_CT = countCT;
probability_CT = (double) occurrences_CT / sum;
outputFile << "The probability of CT in the sequence equals: " <<probability_CT << ", " << probability_CT*100 <<"% "<< occurrences_CT << " CT's" << endl;
occurrences_CG = countCG;
probability_CG = (double) occurrences_CG / sum;
outputFile << "The probability of CG in the sequence equals: " <<probability_CG << ", " << probability_CG*100 <<"% "<< occurrences_CG << " CG's" << endl;
occurrences_CC = countCC;
probability_CC = (double) occurrences_CC / sum;
outputFile << "The probability of CC in the sequence equals: " <<probability_CC << ", " << probability_CC*100 <<"% "<< occurrences_CC << " CC's\n" << endl;
//generating 1000 DNA strings
int x;
int y;
char n;
int mean1 = 6;
float variance1 = 0.214286;
float sDeviation = 0.46291;
string random = "ACGT";
// to calculate the length of strings based with known mean variance and std.
y = sqrt( -2*log( rand() ) ) * cos(6.2831853*rand() );
for (int i = 0; i < 1000; ++i)
{
// x is the length of the strings generated
x = 6 + 0.46291*y;
return x;
// to generate stings with a specific length
for (int j = 0; j < x; ++j)
{
n = random[rand() % x];
return n;
}
}
// appends a new list of strings.
outputFile << n << endl;
// askes if the user wants to process another lest.
char command;
cin >> command;
cout << "Do you want to process another list(y/n) ?" << endl;
// if the answer is no the program will exist
if(command == 'n' || command == 'N')
{
return 1;
}
// close the files!
infile.close();
outputFile.close();
cout << "Done!\n"<<endl;
}
else
{
cout << "Failed to open file.." << endl;
}
return 0;
}
| true |
08d8c1e86b996cdaef8a9e44418637f0f1fe8dff | C++ | mposypkin/BNB-solver | /problems/nlp/testproblems/mixedinteger/boxcon/sqsum/misqsumfact.hpp | UTF-8 | 2,482 | 2.890625 | 3 | [] | no_license | /*
* File: misqsum.hpp
* Author: medved
*
* Created on May 5, 2015, 8:57 AM
*/
#ifndef MISQSUMFACT_HPP
#define MISQSUMFACT_HPP
#include <math.h>
#include <string>
#include <iostream>
#include <sstream>
#include <problems/nlp/common/nlpproblem.hpp>
#include <util/poly/polynom.hpp>
#include <util/poly/polynomtxt.hpp>
#include <util/poly/polyutil.hpp>
#include <problems/optlib/polyobjective.hpp>
/**
* Generates an instance of scaled mixed integer sum of square problems
* x1^2 - x2^2 + x3^2 - ...
* -d <= xi <= d, i =1,...,n
*/
class MISqSumFactory {
public:
/**
* Constructor
* @param n number of dimensions
* @param d box size
*/
MISqSumFactory(int n, int d) {
mN = n;
mD = d;
mPobj = createPobj();
mProb = createProb();
}
/**
* Retrieve NLP problem (lazy style)
* @return nlp problem
*/
NlpProblem<double>* getProb() {
return mProb;
}
private:
NlpProblem<double>* createProb() {
NlpProblem<double>* prob = new NlpProblem<double>();
/** Initilizing bounding box **/
Box<double> box(mN);
initBox(box);
prob->mBox = box;
prob->mVariables.resize(mN);
/** Initilizing variables **/
for (int i = 0; i < mN; i++)
prob->mVariables[i] = NlpProblem<double>::VariableTypes::INTEGRAL;
/** Setup objective */
prob->mObj = mPobj;
return prob;
}
void initBox(Box<double> &box) {
for (int i = 0; i < mN; i++) {
box.mA[i] = -mD;
box.mB[i] = mD;
}
}
PolyObjective<double>* createPobj() {
std::map < std::string, int> idents;
Polynom<double> *poly = new Polynom<double>();
PolyUtil::fromString(getPolyString().c_str(), idents, *poly);
PolynomTxt fmt;
std::string ss = PolyUtil::toString(fmt, *poly);
std::cout << "Polynom: " << ss << "\n";
PolyObjective<double>* pobj = new PolyObjective<double>(poly);
return pobj;
}
std::string getPolyString() {
std::ostringstream os;
for (int i = 0; i < mN; i++) {
if(i != 0) {
os << ((i % 2) ? " - " : "+");
}
os << " x" << i << "^2";
}
return os.str();
}
int mN;
double mD;
NlpProblem<double>* mProb;
PolyObjective<double>* mPobj;
};
#endif /* MISQSUMFACT_HPP */
| true |
8abae84ca6f078049d4712a66c688d1cf119c88c | C++ | glucu/JoshLospinoso-CPlusPlusAFPI | /Part 1/Chapter 8/src/8-1.cpp | UTF-8 | 292 | 2.609375 | 3 | [] | no_license | #include "PrimeNumberRange.h"
#include "FibonacciIterator.h"
#include "FibonacciRange.h"
#include <cstdio>
int main() {
FibonacciRange range{ 5000 };
const auto end = range.end();
for (auto x = range.begin(); x != end; ++x) {
const auto i = *x;
printf("%d ", i);
}
return 0;
} | true |