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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f6ca27ef8b3ff77d093f7997406a910e26fb98f8 | C++ | huudinh1401/ProjectATM_Nhom2_Sang4_git | /Main.cpp | UTF-8 | 888 | 2.5625 | 3 | [] | no_license | #include "iostream"
#include "fstream"
#include "string"
#include "UserTransaction.h"
#include "FileUtility.h"
#include "windows.h"
using namespace std;
void main()
{
UserTransaction User;
User.Doc();
int nChon;
User.Nhap();
do
{
system("cls");
cout << "\n\t\t* * * * * * * * * * * * * * * * *";
cout << "\n\n\t\t* \t MENU \t *";
cout << "\n\n\t\t* * * * * * * * * * * * * * * * *";
cout << "\n\n\t\t1.Rut Tien";
cout << "\n\t\t2.Chuyen Tien";
cout << "\n\t\t3.Thoat";
cout << "\n\t\tMoi Ban Chon: ";
cin >> nChon;
switch (nChon)
{
case 1:
User.Rut();
break;
case 2:
User.Chuyen();
break;
case 3:
system("cls");
cout << "\t\tHan Hanh Phuc Vu Quy Khach!";
cout << "\n\t\tMoi Quy Khach Nhan Lai The!";
Sleep(1500);
exit(1);
}
} while (nChon > 0 && nChon < 3);
cout << endl << endl;
system ("pause");
} | true |
ed2ef7377d52784ee0680ae4df2c6c0f14d6678c | C++ | jacklee032016/pbx | /800/VPBX_Support/include/util/behavior/EventSubject.hxx | UTF-8 | 1,169 | 2.640625 | 3 | [] | no_license | #if !defined(ASSIST_EVENT_SUBJECT_HXX)
#define ASSIST_EVENT_SUBJECT_HXX
/*
* $Id: EventSubject.hxx,v 1.1.1.1 2006/11/30 16:27:09 lizhijie Exp $
*/
#include "global.h"
#include "Subject.hxx"
/** Infrastructure common to ASSIST.
*/
namespace Assist
{
/** Infrastructure in ASSIST related to "algorithms and the assignment of
* responsibilities between objects".<br><br>
*
* See Design Patterns, ISBN 0-201-63361-2, Chapter 5.
*/
namespace Behavioral
{
/** Specialized subject to handle events.<br><br>
*
* @see Assist::Behavioral::Subject
* @see Assist::Behavioral::EventObserver
*/
template <class Event>
class EventSubject : public Assist::Behavioral::Subject
{
public:
/** Default constructor
*/
EventSubject();
/** Virtual destructor
*/
virtual ~EventSubject();
/** Causes all EventObservers to be notified of the given Event.
*/
void setEvent(Event);
/** Event accessor.
*/
Event getEvent();
private:
Event myEvent;
};
#include "EventSubject.cc"
} // namespace Behavioral
} // namespace Assist
#endif // !defined(ASSIST_EVENT_SUBJECT_HXX)
| true |
778ef847215a2a541fcc806ad393082b41573552 | C++ | elielouis/Symbolic-Differentiation | /main.cpp | UTF-8 | 358 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include "derivative.h"
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> function;
function.push_back("1");
function.push_back("x");
function.push_back("+");
function.push_back("x");
function.push_back("*");
differentiate(function, "x");
return 0;
}
| true |
2c11cfdced856f3dad2ff938f45fb89b404eb78a | C++ | sushma-nagaraj/Master-Thesis | /Code/f-DRIT/src/BatchMeansByEuclideanDistance/BatchMeansByEuclideanDistance.cpp | UTF-8 | 946 | 2.65625 | 3 | [] | no_license | /*
* BatchMeansByEuclideanDistance.cpp
*
* Created on: 16.10.2015
* Author: sushma_n
*/
# include <cmath>
# include <iostream>
# include <string>
# include <vector>
# include <list>
# include "BatchMeansByEuclideanDistance.h"
using namespace std;
//to be configurable
int n_Obs = 10;
double normalizingFactor = 0.0;
list<double> l_Obs;
long EuclideanDistanceTransientDetector(list<double> Obs)
{
// int i = 0;
l_Obs = Obs;
// int index = 0;
// int count = 0;
// list<double> ObsSet = collectData(index);
//
// if(EuclideanCriteriaSatisfied(ObsSet))
// {
// index = index+1;
// }
// else
// {
// count = 0;
// }
}
bool EuclideanCriteriaSatisfied(list<double> ObsSet)
{
return false;
}
list<double> collectData(int index)
{
list<double> ObsSet;
for(int i = index; i < index + n_Obs; i++)
{
// int iter = l_Obs.begin();
// std::advance(iter, i);
// double val = *iter;
// ObsSet.push_back(val);
}
return ObsSet;
}
| true |
22c180cfeddc1e4cbffe894a6f04316a2a44336d | C++ | yalekseev/lcs | /lcs.h | UTF-8 | 853 | 3.15625 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <iterator>
#include <vector>
namespace util {
/* O(mn) */
template <typename Iterator1, typename Iterator2>
int longest_common_subsequence(Iterator1 begin1, Iterator1 end1, Iterator2 begin2, Iterator2 end2) {
auto size1 = std::distance(begin1, end1);
auto size2 = std::distance(begin2, end2);
std::vector<std::vector<int>> t(size1 + 1);
for (auto &r : t) {
r.resize(size2 + 1, 0);
}
auto i = 1;
for (auto it1 = begin1; it1 != end1; ++it1, ++i) {
auto j = 1;
for (auto it2 = begin2; it2 != end2; ++it2, ++j) {
if (*it1 == *it2) {
t[i][j] = t[i - 1][j - 1] + 1;
} else {
t[i][j] = std::max(t[i - 1][j], t[i][j - 1]);
}
}
}
return t[size1][size2];
}
} // namespace util
| true |
cd596cd045ec23894ff21eaeeb5507ecb33b8e91 | C++ | qianfeng0/CodePractice | /LeetCode/7_ReverseInteger.cpp | UTF-8 | 750 | 3.9375 | 4 | [] | no_license | /**
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
*/
#include <stdio.h>
#include <stdint.h>
class Solution {
public:
int reverse(int x) {
long result = 0;
while(x != 0){
result = result * 10 + x % 10;
x /= 10;
}
if( result < INT32_MIN || result > INT32_MAX)
return 0;
else
return result;
}
};
int main(){
Solution solution;
int input = 0;
while(scanf("%d", &input)){
printf("%d\n", solution.reverse(input));
}
return 0;
} | true |
b42ca93e02608e9e7c5a57b1c95a2c9b621aa1f4 | C++ | Cristhian-Sierra/POO-C- | /Ejemplos_Clases/Tipos_Funciones2.cpp | UTF-8 | 465 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include<stdlib.h>
#include<locale.h>
using namespace std;
class uno{
public:
void Entrada(char frase[]);
void Salida(char cad[]);
};
void uno::Entrada(char frase[]){
cout<<" Digite una frase " <<endl;
gets(frase);
}
void uno::Salida(char cad[]){
cout<<"\nLa cadena es "<<endl;
for(int i=0;cad[i];i++){
cout<<cad[i]<< " ";
}
}
int main(){
uno u;
char arreglo [10];
u.Entrada(arreglo);
u.Salida(arreglo);
}
| true |
091ea6be821b786a7aeb2e91dbfc5e91c5c322e1 | C++ | Wembie/Fabian-s-World | /PROYECTO 2/Controller.h | UTF-8 | 1,646 | 2.609375 | 3 | [] | no_license | #ifndef CONTROLLER_H
#include <iostream>
#include <list>
#include <map>
#include<cstdlib>
#include<ctime>
#include "arma.h"
#include "item.h"
#include "pocion.h"
#include "personaje.h"
#include "jugador.h"
#include "enemigo.h"
using std::cin;
using std::cout;
using std::endl;
using std::list;
using std::string;
/*
Se crea la clase Controller, donde de atributos esta un atributo de tipo Jugador, Enemigo y Personaje, con sus respetivos metodos
*/
class Controller{
private:
Jugador jugador;
Enemigo enemigo; //Estos son los enemigos que se ponene en el mapa, no con los que pelea
Personaje personaje;
public:
Controller();
Jugador getJugador( );
Enemigo getEnemigo();
list<int> encontrarLimites( int matrizNivel[10][14] );
void verificarFase(int * x, int * y, int * faseActual);
list<int> encontrarPosicionesEnemigos( int matrizNivel[10][14] );
Personaje getPersonaje();
void verificarFaseBatalla(int * x, int * y, int * faseActualBatalla);
void mostrarNumero(int , BITMAP * , int , int , BITMAP *);
void mostrarNumeroPequenio(int , BITMAP * , int , int , BITMAP *);
void mostrarDatosPersonaje(BITMAP *, BITMAP *);
void mostrarDatosEnemigo(BITMAP *, BITMAP *, Enemigo);
void cambiarVidaJugador(Enemigo);
void reiniciarVida();
void darItemAleatorio();
void mostrarInventario( BITMAP * buffer, BITMAP * numeritos );
void vaciarInventario();
void cambiarMana( int );
void usarInventario( Enemigo * enemigoBatalla );
};
#endif
| true |
25216bfa80cdb00db0d699a8740fc025f4334acd | C++ | FeiZhao0531/BasicAlgorithm | /Sort/bubbleSort/main.cpp | UTF-8 | 754 | 3.453125 | 3 | [
"MIT"
] | permissive | /// bubble sort
/// author: Fei Zhao
/// creating time: May-2-2019
#include <iostream>
#include <cassert>
#include <vector>
using namespace std;
void bubbleSort( vector<int>& arr, int len) {
for( int i=0; i<len; ++i) {
for( int j=0; j<len-i-1; ++j) {
if( arr[j] > arr[j+1])
swap( arr[j], arr[j+1]);
/*
int tmp = arr[j+1];
a[j+1] = arr[j];
a[j] = tmp;
*/
}
}
return;
}
int main()
{
int nums[] = { 5,3,9,4,1,7,9,6};
int len = sizeof(nums)/sizeof(int);
vector<int> arr( nums, nums+len);
bubbleSort( arr, len);
for( int i=0; i<len; ++i)
cout<<arr[i]<<", ";
cout<<endl;
return 0;
}
| true |
563dce44f58ac8f5cc698acdb34c99f4437a1c67 | C++ | Shaniamoro/Countdown | /Set_Of_Six/New_Rules_/main.cpp | UTF-8 | 21,458 | 3.921875 | 4 | [] | no_license |
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
class Countdown {
int T = 0; // target number
int a;
int b;
int c;
int d;
int e;
int f;
public:
Countdown();
Countdown(int, int, int, int, int, int, int);
double Addition(int, int);
double Multiplication(int, int);
double Division(int, int); // Only integers allowed
double Subtraction(int, int);// Only Positive Subtraction allowed
double Exponentiation1(int, int);// First number raised to the second
double Exponentiation2(int, int);//Second number raised to the first
bool Compare(int, int, int);
bool Compare(int, int, int, int);
bool Compare(int, int, int, int, int);
bool Compare(int, int, int, int, int, int);
bool Compare(int, int, int, int, int, int, int);
};
Countdown::Countdown() {
// T = 10;
// a = 5;
// b = 2;
// c= 1;
}
// Instead of a and b maybe use an array
Countdown::Countdown(int Target, int first, int second, int third, int fourth, int fifth, int sixth) {
T = Target;
a = first;
b = second;
c = third;
d = fourth;
e = fifth;
f = sixth;
}
double Countdown::Addition(int a, int b) {
int sum = a + b;
return sum;
}
double Countdown::Multiplication(int a, int b) {
int mult = a * b;
return mult;
}
double Countdown::Division(int a, int b) {
int div = 0;
if (a >= b) {
if (b != 0 && a % b == 0) {
div = a / b;
}
else {
div = a / 1;
}
}
else if (a < b) {
if (a != 0 && b% a == 0) {
div = b / a;
}
else {
div = b / 1;
}
}
return div;
}
double Countdown::Subtraction(int a, int b) {
int sub = 0;
if (a > b) {
sub = a - b;
}
else if (b > a) {
sub = b - a;
}
return sub;
}
double Countdown::Exponentiation1(int a, int b) {
if (a == 1) {
return a;
}
else if (a < 1000 && b < 1000) {
return pow(a, b);
}
else {
return a;
}
}
double Countdown::Exponentiation2(int a, int b) {
if (b == 1) {
return b;
}
else if (a < 1000 && b < 1000) {
return pow(b, a);
}
else {
return b;
}
}
bool Countdown::Compare(int T, int a, int b) {
if (Addition(a, b) == T) {
return true;
}
else if (Multiplication(a, b) == T) {
return true;
}
else if (Division(a, b) == T) {
return true;
}
else if (Subtraction(a, b) == T) {
return true;
}
else if (Exponentiation1(a, b) == T) {
return true;
}
else if (Exponentiation2(a, b) == T) {
return true;
}
else {
return false;
}
}
bool Countdown::Compare(int T, int a, int b, int c) {
//Check if pairs of two can solve first
if (Compare(T, a, b) == true) {
return true;
}
else if (Compare(T, b, c) == true) {
return true;
}
else if (Compare(T, a, c) == true) {
return true;
}
else if (Compare(T, Addition(a, b), c) == true) {
return true;
}
else if (Compare(T, Addition(b, c), a) == true) {
return true;
}
else if (Compare(T, Addition(a, c), b) == true) {
return true;
}
else if (Compare(T, Multiplication(a, b), c) == true) {
return true;
}
else if (Compare(T, Multiplication(b, c), a) == true) {
return true;
}
else if (Compare(T, Multiplication(a, c), b) == true) {
return true;
}
else if (Compare(T, Division(a, b), c) == true) {
return true;
}
else if (Compare(T, Division(b, c), a) == true) {
return true;
}
else if (Compare(T, Division(a, c), b) == true) {
return true;
}
else if (Compare(T, Subtraction(a, b), c) == true) {
return true;
}
else if (Compare(T, Subtraction(b, c), a) == true) {
return true;
}
else if (Compare(T, Subtraction(a, c), b) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, b), c) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, c), a) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, c), b) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, b), c) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, c), a) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, c), b) == true) {
return true;
}
else {
return false;
}
}
bool Countdown::Compare(int T, int a, int b, int c, int d) {
//Check if pairs of two can solve first
if (Compare(T, a, b, c) == true) {
return true;
}
if (Compare(T, a, b, d) == true) {
return true;
}
else if (Compare(T, a, c, d) == true) {
return true;
}
else if (Compare(T, b, c, d) == true) {
return true;
}
else if (Compare(T, Addition(a, b), c, d) == true) {
return true;
}
else if (Compare(T, Addition(a, c), b, d) == true) {
return true;
}
else if (Compare(T, Addition(a, d), b, c) == true) {
return true;
}
else if (Compare(T, Addition(b, c), a, d) == true) {
return true;
}
else if (Compare(T, Addition(b, d), a, c) == true) {
return true;
}
else if (Compare(T, Addition(c, d), a, b) == true) {
return true;
}
else if (Compare(T, Multiplication(a, b), c, d) == true) {
return true;
}
else if (Compare(T, Multiplication(a, c), b, d) == true) {
return true;
}
else if (Compare(T, Multiplication(a, d), b, c) == true) {
return true;
}
else if (Compare(T, Multiplication(b, c), a, d) == true) {
return true;
}
else if (Compare(T, Multiplication(b, d), a, c) == true) {
return true;
}
else if (Compare(T, Multiplication(c, d), a, b) == true) {
return true;
}
else if (Compare(T, Division(a, b), c, d) == true) {
return true;
}
else if (Compare(T, Division(a, c), b, d) == true) {
return true;
}
else if (Compare(T, Division(a, d), b, c) == true) {
return true;
}
else if (Compare(T, Division(b, c), a, d) == true) {
return true;
}
else if (Compare(T, Division(b, d), a, c) == true) {
return true;
}
else if (Compare(T, Division(c, d), a, b) == true) {
return true;
}
else if (Compare(T, Subtraction(a, b), c, d) == true) {
return true;
}
else if (Compare(T, Subtraction(a, c), b, d) == true) {
return true;
}
else if (Compare(T, Subtraction(a, d), b, c) == true) {
return true;
}
else if (Compare(T, Subtraction(b, c), a, d) == true) {
return true;
}
else if (Compare(T, Subtraction(b, d), a, c) == true) {
return true;
}
else if (Compare(T, Subtraction(c, d), a, b) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, b), c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, c), b, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, d), b, c) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, c), a, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, d), a, c) == true) {
return true;
}
else if (Compare(T, Exponentiation1(c, d), a, b) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, b), c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, c), b, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, d), b, c) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, c), a, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, d), a, c) == true) {
return true;
}
else if (Compare(T, Exponentiation2(c, d), a, b) == true) {
return true;
}
else {
return false;
}
}
bool Countdown::Compare(int T, int a, int b, int c, int d, int e) {
//Check if pairs of two can solve first
if (Compare(T, a, b, c, d) == true) {
return true;
}
if (Compare(T, a, b, c, e) == true) {
return true;
}
if (Compare(T, a, b, d, e) == true) {
return true;
}
if (Compare(T, a, c, d, e) == true) {
return true;
}
else if (Compare(T, b, c, d, e) == true) {
return true;
}
else if (Compare(T, Addition(a, b), c, d, e) == true) {
return true;
}
else if (Compare(T, Addition(a, c), b, d, e) == true) {
return true;
}
else if (Compare(T, Addition(a, d), b, c, e) == true) {
return true;
}
else if (Compare(T, Addition(a, e), b, c, d) == true) {
return true;
}
else if (Compare(T, Addition(b, c), a, d, e) == true) {
return true;
}
else if (Compare(T, Addition(b, d), a, c, e) == true) {
return true;
}
else if (Compare(T, Addition(b, e), a, c, d) == true) {
return true;
}
else if (Compare(T, Addition(c, d), a, b, e) == true) {
return true;
}
else if (Compare(T, Addition(c, e), a, b, d) == true) {
return true;
}
else if (Compare(T, Addition(d, e), a, b, c) == true) {
return true;
}
else if (Compare(T, Multiplication(a, b), c, d, e) == true) {
return true;
}
else if (Compare(T, Multiplication(a, c), b, d, e) == true) {
return true;
}
else if (Compare(T, Multiplication(a, d), b, c, e) == true) {
return true;
}
else if (Compare(T, Multiplication(a, e), b, c, d) == true) {
return true;
}
else if (Compare(T, Multiplication(b, c), a, d, e) == true) {
return true;
}
else if (Compare(T, Multiplication(b, d), a, c, e) == true) {
return true;
}
else if (Compare(T, Multiplication(b, e), a, c, d) == true) {
return true;
}
else if (Compare(T, Multiplication(c, d), a, b, e) == true) {
return true;
}
else if (Compare(T, Multiplication(c, e), a, b, d) == true) {
return true;
}
else if (Compare(T, Multiplication(d, e), a, b, c) == true) {
return true;
}
else if (Compare(T, Division(a, b), c, d, e) == true) {
return true;
}
else if (Compare(T, Division(a, c), b, d, e) == true) {
return true;
}
else if (Compare(T, Division(a, d), b, c, e) == true) {
return true;
}
else if (Compare(T, Division(a, e), b, c, d) == true) {
return true;
}
else if (Compare(T, Division(b, c), a, d, e) == true) {
return true;
}
else if (Compare(T, Division(b, d), a, c, e) == true) {
return true;
}
else if (Compare(T, Division(b, e), a, c, d) == true) {
return true;
}
else if (Compare(T, Division(c, d), a, b, e) == true) {
return true;
}
else if (Compare(T, Division(c, e), a, b, d) == true) {
return true;
}
else if (Compare(T, Division(d, e), a, b, c) == true) {
return true;
}
else if (Compare(T, Subtraction(a, b), c, d, e) == true) {
return true;
}
else if (Compare(T, Subtraction(a, c), b, d, e) == true) {
return true;
}
else if (Compare(T, Subtraction(a, d), b, c, e) == true) {
return true;
}
else if (Compare(T, Subtraction(a, e), b, c, d) == true) {
return true;
}
else if (Compare(T, Subtraction(b, c), a, d, e) == true) {
return true;
}
else if (Compare(T, Subtraction(b, d), a, c, e) == true) {
return true;
}
else if (Compare(T, Subtraction(b, e), a, c, d) == true) {
return true;
}
else if (Compare(T, Subtraction(c, d), a, b, e) == true) {
return true;
}
else if (Compare(T, Subtraction(c, e), a, b, d) == true) {
return true;
}
else if (Compare(T, Subtraction(d, e), a, b, c) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, b), c, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, c), b, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, d), b, c, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, e), b, c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, c), a, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, d), a, c, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, e), a, c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(c, d), a, b, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(c, e), a, b, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(d, e), a, b, c) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, b), c, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, c), b, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, d), b, c, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, e), b, c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, c), a, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, d), a, c, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, e), a, c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(c, d), a, b, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(c, e), a, b, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(d, e), a, b, c) == true) {
return true;
}
else {
return false;
}
}
bool Countdown::Compare(int T, int a, int b, int c, int d, int e, int f) {
//Check if pairs of two can solve first
if (Compare(T, a, b, c, d, e) == true) {
return true;
}
if (Compare(T, a, b, c, d, f) == true) {
return true;
}
if (Compare(T, a, b, c, e, f) == true) {
return true;
}
if (Compare(T, a, b, d, e, f) == true) {
return true;
}
else if (Compare(T, a, c, d, e, f) == true) {
return true;
}
else if (Compare(T, b, c, d, e, f) == true) {
return true;
}
else if (Compare(T, Addition(a, b), c, d, e, f) == true) {
return true;
}
else if (Compare(T, Addition(a, c), b, d, e, f) == true) {
return true;
}
else if (Compare(T, Addition(a, d), b, c, e, f) == true) {
return true;
}
else if (Compare(T, Addition(a, e), b, c, d, f) == true) {
return true;
}
else if (Compare(T, Addition(a, f), b, c, d, e) == true) {
return true;
}
else if (Compare(T, Addition(b, c), a, d, e, f) == true) {
return true;
}
else if (Compare(T, Addition(b, d), a, c, e, f) == true) {
return true;
}
else if (Compare(T, Addition(b, e), a, c, d, f) == true) {
return true;
}
else if (Compare(T, Addition(b, f), a, c, d, e) == true) {
return true;
}
else if (Compare(T, Addition(c, d), a, b, e, f) == true) {
return true;
}
else if (Compare(T, Addition(c, e), a, b, d, f) == true) {
return true;
}
else if (Compare(T, Addition(c, f), a, b, d, e) == true) {
return true;
}
else if (Compare(T, Addition(d, e), a, b, c, f) == true) {
return true;
}
else if (Compare(T, Addition(d, f), a, b, c, e) == true) {
return true;
}
else if (Compare(T, Addition(e, f), a, b, c, d) == true) {
return true;
}
else if (Compare(T, Multiplication(a, b), c, d, e, f) == true) {
return true;
}
else if (Compare(T, Multiplication(a, c), b, d, e, f) == true) {
return true;
}
else if (Compare(T, Multiplication(a, d), b, c, e, f) == true) {
return true;
}
else if (Compare(T, Multiplication(a, e), b, c, d, f) == true) {
return true;
}
else if (Compare(T, Multiplication(a, f), b, c, d, e) == true) {
return true;
}
else if (Compare(T, Multiplication(b, c), a, d, e, f) == true) {
return true;
}
else if (Compare(T, Multiplication(b, d), a, c, e, f) == true) {
return true;
}
else if (Compare(T, Multiplication(b, e), a, c, d, f) == true) {
return true;
}
else if (Compare(T, Multiplication(b, f), a, c, d, e) == true) {
return true;
}
else if (Compare(T, Multiplication(c, d), a, b, e, f) == true) {
return true;
}
else if (Compare(T, Multiplication(c, e), a, b, d, f) == true) {
return true;
}
else if (Compare(T, Multiplication(c, f), a, b, d, e) == true) {
return true;
}
else if (Compare(T, Multiplication(d, e), a, b, c, f) == true) {
return true;
}
else if (Compare(T, Multiplication(d, f), a, b, c, e) == true) {
return true;
}
else if (Compare(T, Multiplication(e, f), a, b, c, d) == true) {
return true;
}
else if (Compare(T, Division(a, b), c, d, e, f) == true) {
return true;
}
else if (Compare(T, Division(a, c), b, d, e, f) == true) {
return true;
}
else if (Compare(T, Division(a, d), b, c, e, f) == true) {
return true;
}
else if (Compare(T, Division(a, e), b, c, d, f) == true) {
return true;
}
else if (Compare(T, Division(a, f), b, c, d, e) == true) {
return true;
}
else if (Compare(T, Division(b, c), a, d, e, f) == true) {
return true;
}
else if (Compare(T, Division(b, d), a, c, e, f) == true) {
return true;
}
else if (Compare(T, Division(b, e), a, c, d, f) == true) {
return true;
}
else if (Compare(T, Division(b, f), a, c, d, e) == true) {
return true;
}
else if (Compare(T, Division(c, d), a, b, e, f) == true) {
return true;
}
else if (Compare(T, Division(c, e), a, b, d, f) == true) {
return true;
}
else if (Compare(T, Division(c, f), a, b, d, e) == true) {
return true;
}
else if (Compare(T, Division(d, e), a, b, c, f) == true) {
return true;
}
else if (Compare(T, Division(d, f), a, b, c, e) == true) {
return true;
}
else if (Compare(T, Division(e, f), a, b, c, d) == true) {
return true;
}
else if (Compare(T, Subtraction(a, b), c, d, e, f) == true) {
return true;
}
else if (Compare(T, Subtraction(a, c), b, d, e, f) == true) {
return true;
}
else if (Compare(T, Subtraction(a, d), b, c, e, f) == true) {
return true;
}
else if (Compare(T, Subtraction(a, e), b, c, d, f) == true) {
return true;
}
else if (Compare(T, Subtraction(a, f), b, c, d, e) == true) {
return true;
}
else if (Compare(T, Subtraction(b, c), a, d, e, f) == true) {
return true;
}
else if (Compare(T, Subtraction(b, d), a, c, e, f) == true) {
return true;
}
else if (Compare(T, Subtraction(b, e), a, c, d, f) == true) {
return true;
}
else if (Compare(T, Subtraction(b, f), a, c, d, e) == true) {
return true;
}
else if (Compare(T, Subtraction(c, d), a, b, e, f) == true) {
return true;
}
else if (Compare(T, Subtraction(c, e), a, b, d, f) == true) {
return true;
}
else if (Compare(T, Subtraction(c, f), a, b, d, e) == true) {
return true;
}
else if (Compare(T, Subtraction(d, e), a, b, c, f) == true) {
return true;
}
else if (Compare(T, Subtraction(d, f), a, b, c, e) == true) {
return true;
}
else if (Compare(T, Subtraction(e, f), a, b, c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, b), c, d, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, c), b, d, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, d), b, c, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, e), b, c, d, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(a, f), b, c, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, c), a, d, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, d), a, c, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, e), a, c, d, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(b, f), a, c, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(c, d), a, b, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(c, e), a, b, d, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(c, f), a, b, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(d, e), a, b, c, f) == true) {
return true;
}
else if (Compare(T, Exponentiation1(d, f), a, b, c, e) == true) {
return true;
}
else if (Compare(T, Exponentiation1(e, f), a, b, c, d) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, b), c, d, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, c), b, d, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, d), b, c, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, e), b, c, d, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(a, f), b, c, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, c), a, d, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, d), a, c, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, e), a, c, d, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(b, f), a, c, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(c, d), a, b, e, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(c, e), a, b, d, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(c, f), a, b, d, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(d, e), a, b, c, f) == true) {
return true;
}
else if (Compare(T, Exponentiation2(d, f), a, b, c, e) == true) {
return true;
}
else if (Compare(T, Exponentiation2(e, f), a, b, c, d) == true) {
return true;
}
else {
return false;
}
}
int main() {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int max = 0;
int min = 899;
// Creates a file with the generators
ofstream output;
output.open("../generators.txt");
// Output file with the details
ofstream outfile;
outfile.open("../output.txt");
// Output file with the number solved
ofstream out;
out.open("../out.txt");
Countdown C;
ifstream infile;
infile.open("../input.txt");
if (!infile) {
exit(1);
}
else {
while (infile >> a >> b >> c >> d >> e >> f) {
int count = 0;
outfile << "{ " << a << " , " << b << " , " << c << ", " << d << " , " << e << " , " << f << " }" << endl;
out << "{ " << a << " , " << b << " , " << c << ", " << d << " , " << e << " , " << f << " }" << endl;
for (int x = 101; x <= 999; x++) {
if (C.Compare(x, a, b, c, d, e, f) == true) {
count++;
outfile << " This solves " << x << endl;
}
}
out << "Number solved :" << count << endl;
if (count == 899) {
output << "{ " << a << " , " << b << " , " << c << ", " << d << " , " << e << " , " << f << " }" << endl;
}
if (count >= max) {
max = count;
}
if (count <= min) {
min = count;
}
}
}
out << " The most targets solved is : " << max << endl;
out << " The least targets solved is : " << min << endl;
}
| true |
0b826defa34d9cf5b3b765149ed7b207b4211ff0 | C++ | dqtweb/aixue2 | / aixue2/WeiWeiClient/thirdparty/Theron/UnitTests/TestFramework/ITestSuite.h | UTF-8 | 1,956 | 2.796875 | 3 | [
"MIT"
] | permissive | // Copyright (C) by Ashton Mason. See LICENSE.txt for licensing information.
#ifndef TESTFRAMEWORK_ITESTSUITE_H
#define TESTFRAMEWORK_ITESTSUITE_H
#ifdef _MSC_VER
#pragma warning(push,0)
#pragma warning (disable:4530) // C++ exception handler used, but unwind semantics are not enabled
#endif //_MSC_VER
#include <vector>
#include <string>
#ifdef _MSC_VER
#pragma warning(pop)
#endif //_MSC_VER
namespace TestFramework
{
/// Interface describing a suite of unit tests.
class ITestSuite
{
public:
/// Defines a test suite name.
typedef std::string TestSuiteName;
/// Defines a test name.
typedef std::string TestName;
/// Defines a static test method.
/// Static member functions count as static functions and can be used as tests.
typedef void (*Test)();
/// Defines a list of tests in a test suite.
typedef std::vector<Test> TestList;
/// Defines a list of test names.
typedef std::vector<TestName> TestNameList;
/// Defines a test error message.
typedef std::string Error;
/// Defines a list of test error messages.
typedef std::vector<Error> ErrorList;
/// Default constructor
inline ITestSuite()
{
}
/// Virtual destructor
inline virtual ~ITestSuite()
{
}
/// Runs all tests in the suite.
/// \return True, if all the tests in the suite passed.
virtual bool RunTests() = 0;
/// Gets the errors returned by the failed tests in the suite.
/// \return A list of errors.
virtual const ErrorList &GetErrors() = 0;
private:
/// Disallowed copy constructor. TestSuite objects can't be copied.
ITestSuite(const ITestSuite &other);
/// Disallowed assignment operator. ITestSuite objects can't be assigned.
ITestSuite &operator=(const ITestSuite &other);
};
} // namespace TestFramework
#endif // TESTFRAMEWORK_ITESTSUITE_H
| true |
1bac121707a5b621999d259760759ff76ee837c1 | C++ | HadarAmira/Hadar | /Documents/Reversi/src/client/Board.h | UTF-8 | 1,214 | 3.40625 | 3 | [] | no_license | /*
* Board.h
*
* Created on: Nov 24, 2017
* Author: zvi
*/
#include "PlayerSign.h"
#include "Point.h"
#ifndef BOARD_H_
#define BOARD_H_
class Board {
public:
/**
* creates the game board.
* size - the wanted size of the board
* sign1 - a sign that represents player1
* sign2 - a sign that represents player2
*/
Board(int size, PlayerSign sign1, PlayerSign sign2);
/**
* copy constructor
* origin - a board to copy
*/
Board(Board* origin);
/**
* arrange the board to its starting shape
*/
void initialize();
/**
* returns the size of the board
*/
int getSize() const;
/**
* returns the char at the wanted point
*/
PlayerSign getCharAt(int row, int col) const;
/**
* returns the char at the wanted point
*/
PlayerSign getCharAt(Point& p) const;
/**
* move - a point to change
* player - the sign to change to
*/
void setTile(Point& move, PlayerSign player);
/**
* row - the row of the point to change
* col - the col of the point to change
* player - the sign to change to
*/
void setTile(int row, int col, PlayerSign player);
virtual ~Board();
private:
PlayerSign** board;
int size;
PlayerSign sign1, sign2;
};
#endif /* BOARD_H_ */
| true |
5d2dae1944363fd6fb62ac3770c06514ba70b93f | C++ | jakeadicoff/Handwritten-Digit-Compression | /NN.h | UTF-8 | 1,238 | 2.59375 | 3 | [] | no_license | #ifndef __NN_h
#define __NN_h
#include <vector>
#include <random>
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
struct output {
vector<double> weights;
};
struct Problem {
vector<vector<int>> inputs;
vector<int> targets;
int num_inputs;
int map_size;
};
class NN {
public:
NN(double learningRate, Problem train_prob, Problem test_prob,
int numOutputs, int maxEpochs, int numSymbols);
double test();
void train();
vector<int> compression_vector;
private:
int num_train_inputs;
int num_test_inputs;
int num_symbols;
int num_outputs;
int map_size;
int max_epochs;
double learning_rate;
vector<vector<int>> train_inputs;
vector<vector<int>> test_inputs;
vector<vector<int>> compressed_train_inputs;
vector<vector<int>> compressed_test_inputs;
vector<int> train_targets;
vector<int> test_targets;
vector<output> outputs;
void initialize_weights();
void reset();
void compress_maps();
void update_weights(int output_index, int input_index, double g, double g_prime, double target);
double activation_function(double x);
double ddx_activation_function(double x);
};
#endif
| true |
02f0fd20bf56f5767de191cb02a82b4d17a993bd | C++ | catadascalu/Real_Estate_Agency | /RealEstateAgency/Dwelling.cpp | UTF-8 | 526 | 2.84375 | 3 | [] | no_license | #include "Dwelling.h"
double Dwelling::normalBankRate()
{
double rate;
rate = this->price / 1000;
return rate;
}
double Dwelling::largeBankRate()
{
double rate;
rate = this->price / 100;
return rate;
}
std::string Dwelling::toString()
{
std::string status;
if (this->isProfitable == false)
status = "not profitable";
else
status = "profitable";
std::string str;
str = "Building type: " + this->type + " Price: " + std::to_string(this->price) + " Status: " + status;
return str;
}
| true |
b9395754b335e75ee6ef4f928d25189eb5cd10a2 | C++ | lukaszwalocha/GalaxyShooter | /Asteroids.cpp | UTF-8 | 7,639 | 2.78125 | 3 | [] | no_license | #include "Asteroids.h"
Asteroids::Asteroids()
{
asteroidTexture.loadFromFile("asteroid1.png");
sf::Texture *texturePtr = &asteroidTexture;
asteroidSprite.setTexture(*texturePtr);
asteroidSprite.setTextureRect(sf::IntRect(64 * 0, 64 * 0, 64, 64));
velocity = 5;
}
Asteroids::~Asteroids()
{
}
void Asteroids::drawAsteroids(sf::RenderWindow &window, std::vector<Asteroids> &asteroidVect)
{
for (int i = 0; i < asteroidVect.size(); i++)
{
window.draw(asteroidVect[i].asteroidSprite);
}
}
void Asteroids::addAsteroid(std::vector<Asteroids> &asteroidsVect, Asteroids &asteroidObj)
{
for (int i = 0; i < 5; i++) // SETTING ASTEROIDS AMOUNT AND PUSHING THEM INTO THE VECTOR
{
asteroidsVect.push_back(asteroidObj);
}
}
void Asteroids::positionProtection(std::vector<Asteroids> &asteroidsVector, sf::RenderWindow &window)
{
//ASTEROID 0
if (asteroidsVector[0].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[1].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[0].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[0].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[2].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[0].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[0].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[3].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[0].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[0].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[4].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[0].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
//ASTEROID 1
if (asteroidsVector[1].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[0].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[1].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[1].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[2].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[1].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[1].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[3].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[1].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[1].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[4].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[1].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
//ASTEROID 2
if (asteroidsVector[2].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[0].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[2].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[2].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[1].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[2].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[2].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[3].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[2].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[2].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[4].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[2].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
//ASTEROID 3
if (asteroidsVector[3].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[1].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[3].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[3].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[2].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[3].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[3].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[4].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[3].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[3].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[0].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[4].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
//ASTEROID 4
if (asteroidsVector[4].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[0].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[4].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[4].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[1].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[4].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[4].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[2].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[4].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
else if (asteroidsVector[4].asteroidSprite.getGlobalBounds().intersects(asteroidsVector[3].asteroidSprite.getGlobalBounds()))
{
asteroidsVector[4].asteroidSprite.setPosition(rand() % unsigned int(window.getSize().x - 0.95*window.getSize().x + 1), -(rand() % int(250) + 1));
}
}
void Asteroids::asteroidMovement(sf::RenderWindow &window, std::vector<Asteroids> &asteroidVect, bool &playerAlive, bool &MenuAktywne, bool &menuBack)
{
for (int i = 0; i < asteroidVect.size(); i++)
{
if (!MenuAktywne)
{
if (velocity < 30 && playerAlive)
{
velocity += 0.00025;
}
else
{
velocity = 5;
}
asteroidVect[i].asteroidSprite.move(0, velocity);
}
if (asteroidVect[i].asteroidSprite.getPosition().y > 800 && playerAlive)
{
asteroidVect[i].asteroidSprite.setPosition(rand() % int(window.getSize().x - 0.15*window.getSize().x) + 1, -(rand() % int(250) + 1));
}
else if (MenuAktywne)
asteroidVect[i].asteroidSprite.setPosition(rand() % int(window.getSize().x - 0.15*window.getSize().x) + 1, -(rand() % int(250) + 1));
}
}
void Asteroids::setAsteroidPosition(std::vector<Asteroids> &asteroidsVect, sf::RenderWindow &window)
{
for (int i = 0; i < asteroidsVect.size(); i++){
asteroidsVect[i].asteroidSprite.setPosition(rand() % int(800) + 1, -(rand() % int(250) + 1));
}
} | true |
86af0af3084cc069c7cac3e50ff880ca90a8b0f3 | C++ | elfion/nanoengineer | /cad/plugins/NanoVision-1/src/Utility/NXPointTest.cpp | UTF-8 | 8,030 | 2.71875 | 3 | [] | no_license | // Copyright 2008 Nanorex, Inc. See LICENSE file for details.
#include "NXPointTest.h"
CPPUNIT_TEST_SUITE_REGISTRATION(NXPointTest);
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(NXPointTest,
"NXPointTestSuite");
// ---------------------------------------------------------------------
/* Helper comparison functions */
template<typename T, int N>
void cppunit_assert_points_equal(NXPointRef<T,N> const& pRef,
T answer[N],
T const& delta = 1.0e-8)
{
for(int n=0; n<N; ++n) {
CPPUNIT_ASSERT_DOUBLES_EQUAL(double(pRef[n]),
double(answer[n]),
double(delta));
}
}
template<typename T, int N>
void cppunit_assert_points_unequal(NXPointRef<T,N> const& pRef,
T answer[N],
T const& delta = 1.0e-8)
{
for(int n=0; n<N; ++n) {
CPPUNIT_ASSERT(fabs(double(pRef[n])-double(answer[n])) > double(delta));
}
}
template<typename T, int N>
void cppunit_assert_points_equal(NXPointRef<T,N> const& p1Ref,
NXPointRef<T,N> const& p2Ref,
T const& delta = 1.0e-8)
{
for(int n=0; n<N; ++n) {
CPPUNIT_ASSERT_DOUBLES_EQUAL(double(p1Ref[n]),
double(p2Ref[n]),
double(delta));
}
}
// ---------------------------------------------------------------------
/* Test-suite */
void NXPointTest::accessTest(void)
{
NXPoint4d p;
double answer[4] = { 0.0, 1.0, 2.0, 3.0 };
p[0] = answer[0]; p[1] = answer[1]; p[2] = answer[2]; p[3] = answer[3];
double const *const ptr = p.data();
CPPUNIT_ASSERT(ptr[0] == 0.0);
CPPUNIT_ASSERT(ptr[1] == 1.0);
CPPUNIT_ASSERT(ptr[2] == 2.0);
CPPUNIT_ASSERT(ptr[3] == 3.0);
cppunit_assert_points_equal(p, answer, 0.0);
}
void NXPointTest::dataTest(void)
{
NXPoint4d p;
NXPointRef4d pRef = p;
CPPUNIT_ASSERT(p.data() == pRef.data());
// test copy constructor for deep-copy semantics
double init[4] = { 2.0, 3.0, -1.0, 6.0 };
NXPointRef4d initRef(init);
NXPoint4d initCopy(initRef);
CPPUNIT_ASSERT(initRef.data() != initCopy.data());
cppunit_assert_points_equal(initRef, initCopy);
// test copy assignment for deep-copy
initCopy.zero();
initCopy = initRef;
CPPUNIT_ASSERT(initRef.data() != initCopy.data());
cppunit_assert_points_equal(initRef, initCopy);
}
void NXPointTest::sizeTest(void)
{
NXPoint4d p;
CPPUNIT_ASSERT(p.size() == 4);
NXPointRef3f pRef;
CPPUNIT_ASSERT(pRef.size() == 3);
}
void NXPointTest::zeroTest(void)
{
NXPoint4d p;
p.zero();
CPPUNIT_ASSERT(p[0] == 0.0);
CPPUNIT_ASSERT(p[1] == 0.0);
CPPUNIT_ASSERT(p[2] == 0.0);
CPPUNIT_ASSERT(p[3] == 0.0);
NXPoint<char,2> cp;
cp.zero();
CPPUNIT_ASSERT(cp[0] == '\0');
CPPUNIT_ASSERT(cp[1] == '\0');
}
void NXPointTest::incrementTest(void)
{
NXPoint4d p;
double init[4] = { 0.0, 1.0, 2.0, 3.0 };
p[0] = init[0]; p[1] = init[1]; p[2] = init[2]; p[3] = init[3];
NXPoint4d p2;
p2.zero();
p2 += p;
cppunit_assert_points_equal(p2, init);
double twice[4] = { 0.0, 2.0, 4.0, 6.0 };
p2 += p2;
cppunit_assert_points_equal(p2, twice, 0.0);
}
void NXPointTest::decrementTest(void)
{
double zeros[4] = { 0.0, 0.0, 0.0, 0.0 };
NXPoint4d p1;
p1.zero();
NXPoint4d p2;
p2.zero();
p1 -= p2;
cppunit_assert_points_equal(p1, zeros, 0.0);
double init[4] = { 1.0, -2.0, 13.0, -27.0 };
double answer[4] = { -1.0, 2.0, -13.0, 27.0 };
NXPointRef4d initRef(init);
NXPoint4d initCopy = initRef;
cppunit_assert_points_equal(initRef, initCopy);
initCopy -= initRef;
cppunit_assert_points_equal(initCopy, zeros, 0.0);
initCopy -= initRef;
cppunit_assert_points_equal(initCopy, answer, 0.0);
}
void NXPointTest::scalingTest(void)
{
double init[4] = { 5.0, 8.0, -2.0, 3.0 };
double const factor = -2.0;
double answer[4] = { -10.0, -16.0, 4.0, -6.0 };
NXPointRef4d p(init);
p *= factor;
cppunit_assert_points_equal(p, answer, 0.0);
// check to see if the reference updated the actual array
for(int n=0; n<4; ++n)
CPPUNIT_ASSERT(init[n] == answer[n]);
}
void NXPointTest::invScalingTest(void)
{
double init[4] = { -10.0, -16.0, 4.0, -6.0 };
double answer[4] = { 5.0, 8.0, -2.0, 3.0 };
double const factor = -2.0;
NXPointRef4d p(init);
p /= factor;
cppunit_assert_points_equal(p, answer, 0.0);
// check to see if the reference updated the actual array
for(int n=0; n<4; ++n)
CPPUNIT_ASSERT(init[n] == answer[n]);
}
void NXPointTest::dotTest(void)
{
double p1Data[4] = { 5.0, 6.0, 7.0, 8.0 };
double p2Data[4] = { 8.0, 7.0, 6.0, 5.0 };
NXPointRef4d p1(p1Data);
NXPointRef4d p2(p2Data);
double const p1_dot_p2 = dot(p1, p2);
double const answer = (p1Data[0] * p2Data[0] +
p1Data[1] * p2Data[1] +
p1Data[2] * p2Data[2] +
p1Data[3] * p2Data[3]);
CPPUNIT_ASSERT(p1_dot_p2 == answer);
}
void NXPointTest::squared_normTest(void)
{
double pData[4] = { 5.0, 6.0, 7.0, 8.0 };
NXPointRef4d p(pData);
double const pSquaredNorm = squared_norm(p);
double const answer = (pData[0] * pData[0] +
pData[1] * pData[1] +
pData[2] * pData[2] +
pData[3] * pData[3]);
CPPUNIT_ASSERT(pSquaredNorm == answer);
}
void NXPointTest::normTest(void)
{
double pData[5] = { 3.0, 4.0, 5.0, 5.0, 5.0 };
NXPointRef<double,5> p(pData);
double const pNorm = norm(p);
double const answer = 10.0;
CPPUNIT_ASSERT_DOUBLES_EQUAL(pNorm, answer, 1.0e-8);
}
void NXPointTest::normalizeSelfTest(void)
{
double init[4] = { 1.0, 1.0, 1.0, 1.0 };
NXPoint4d initCopy(init);
initCopy.normalizeSelf();
double answer[4] = { 0.5, 0.5, 0.5, 0.5 };
cppunit_assert_points_equal(initCopy, answer, 1.0e-8);
NXPoint<float,2> pythagoreanPair;
pythagoreanPair[0] = 3.0f;
pythagoreanPair[1] = 4.0f;
pythagoreanPair.normalizeSelf();
float pythagoreanPairNormalizedValues[2] = { 0.6f, 0.8f };
NXPointRef2f pythagoreanPairNormalized(pythagoreanPairNormalizedValues);
cppunit_assert_points_equal(pythagoreanPair,
pythagoreanPairNormalized,
1.0e-8f);
}
void NXPointTest::normalizedTest(void)
{
double init[4] = { 1.0, 1.0, 1.0, 1.0 };
NXPoint4d initCopy(init);
NXPoint4d initNormalized = initCopy.normalized();
double answer[4] = { 0.5, 0.5, 0.5, 0.5 };
cppunit_assert_points_equal(initNormalized, answer, 1.0e-8);
cppunit_assert_points_unequal(initNormalized, init, 1.0e-8);
}
void NXPointTest::crossTest(void)
{
double iData[3] = { 1.0, 0.0, 0.0 };
double jData[3] = { 0.0, 1.0, 0.0 };
double kData[3] = { 0.0, 0.0, 1.0 };
NXPointRef3d iUnit(iData), jUnit(jData), kUnit(kData);
NXPoint3d iCross = cross(jUnit, kUnit);
cppunit_assert_points_equal(iCross, iUnit);
NXPoint3d jCross = cross(kUnit, iUnit);
cppunit_assert_points_equal(jCross, jUnit);
NXPoint3d kCross = cross(iUnit, jUnit);
cppunit_assert_points_equal(kCross, kUnit);
double pData[3] = { 2.0, 1.0, -1.0 };
double qData[3] = { -3.0, 4.0, 1.0 };
double pcrossqData [3] = { 5.0, 1.0, 11.0 };
NXPointRef3d p(pData), q(qData);
NXPoint3d r = cross(p,q);
cppunit_assert_points_equal(NXPointRef3d(pcrossqData), r.data());
int lData[3] = { 0, 1, 1 };
int mData[3] = { 1, -1, 3 };
int minus_lcrossm_data[3] = { -4, -1, 1 };
NXPointRef<int,3> l(lData), m(mData);
NXPoint<int,3> n = cross(m,l);
cppunit_assert_points_equal(n, minus_lcrossm_data, 0);
}
| true |
faafd18936ba16b97e32d0e247d5cf70356ff8a3 | C++ | matheushjs/projeto_bd | /src/data_structures/show.h | UTF-8 | 590 | 2.921875 | 3 | [] | no_license | #ifndef SHOW_H
#define SHOW_H
#include "data_structures/band.h"
//Tratar que só pode ter um show por dia
//Tratar que a data do show deve estar entre a data inicio da festa e data de fim da festa
class Show
{
public:
Show(QString partyIMO, QString partyDate, QString showDate, QString contract);
Show();
void setBand(Band band);
void setPreviusEnd(QString previousEnd);
void setInitialHour(QString initialHour);
private:
QString m_partyIMO;
QString m_partyDate;
Band m_band;
QString m_showDate;
QString m_previousEnd;
QString m_initialHour;
QString m_contract;
};
#endif | true |
a42a96b9d63141b0830dda7cc5ef3a689e59be43 | C++ | kornel13/zaawansowaneCPP | /itemattributesdialog.cpp | UTF-8 | 1,900 | 2.625 | 3 | [] | no_license | #include "itemattributesdialog.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
#include <QPalette>
#include <QLineEdit>
ItemAttributesDialog::ItemAttributesDialog(ItemConfig defaultConfig, QWidget *parent)
: QDialog(parent), defaultConfig(defaultConfig)
{
setWindowTitle(defaultConfig.getClassName());
QVBoxLayout* layout = new QVBoxLayout();
addAttributes(layout);
QPushButton* createButton = new QPushButton("CREATE",this);
layout->addWidget(createButton);
setLayout(layout);
connect(createButton, SIGNAL(clicked(bool)),
this, SLOT(buttonClicked()));
}
void ItemAttributesDialog::buttonClicked()
{
if(validate()) accept();
}
void ItemAttributesDialog::addAttributes(QVBoxLayout* layout)
{
QString key;
foreach(key, defaultConfig.getKeys())
{
QLabel *label = new QLabel(key, this);
QLineEdit *lineEdit = new QLineEdit(this);
label->setBuddy(lineEdit);
lineEdit->setText(defaultConfig.getValue(key));
inputMap[key] = lineEdit;
layout->addWidget(label);
layout->addWidget(lineEdit);
}
}
ItemConfig ItemAttributesDialog::getDefaultConfig()
{
return defaultConfig;
}
ItemConfig ItemAttributesDialog::getConfig()
{
ItemConfig config = defaultConfig;
QString key;
foreach(key, defaultConfig.getKeys())
{
config.setValue(key, inputMap[key]->text());
}
return config;
}
bool ItemAttributesDialog::validate()
{
bool result = true;
QString key;
foreach(key, defaultConfig.getKeys())
{
auto text = inputMap[key]->text();
if( ! defaultConfig.validate(key,text) )
{
QPalette palette;
palette.setColor(QPalette::Base,Qt::red);
inputMap[key]->setPalette(palette);
result = false;
break;
}
}
return result;
}
| true |
2db74eddb9340af6f2e86264489e17bc1f4cb946 | C++ | citxx/osfi-2 | /src/Spectrum.cpp | UTF-8 | 8,387 | 3.015625 | 3 | [
"MIT"
] | permissive | /*#include <algorithm>*/
//#include <cmath>
//#include <fstream>
//#include <iostream>
//#include <numeric>
//#include <string>
//#include <utility>
//#include "Spectrum.hpp"
//#include "utils.hpp"
//const double Spectrum::EPS = 1e-6;
//Spectrum::Spectrum(
//const std::vector<double> &values,
//const std::vector<double> &frequencies): values_(values), freqs_(frequencies) {
//if (freqs_.empty()) {
//for (int i = 0; i < static_cast<int>(values_.size()); ++i) {
//freqs_.push_back(static_cast<double>(i));
//}
//}
//}
//Spectrum Spectrum::fromCsvFile(const std::string &path) {
//std::ifstream file(path);
//std::vector<double> frequency, value;
//std::string line;
//while (file >> line) {
//if (!line.empty()) {
//std::vector<std::string> fields = utils::split(line, ",");
//if (fields.size() != 2) {
//throw "Invalid spectrum file format near '" + line + "'";
//}
//frequency.push_back(std::stod(fields[0]));
//value.push_back(std::stod(fields[1]));
//}
//}
//file.close();
//// TODO: check if sorted
//return Spectrum(value, frequency);
//}
//std::vector<Spectrum> Spectrum::manyFromCsvFile(const std::string &path) {
//std::ifstream file(path);
//std::vector<double> frequency;
//std::vector<std::vector<double>> values;
//std::string line;
//while (file >> line) {
//if (!line.empty()) {
//std::vector<std::string> fields = utils::split(line, ",");
//if (!values.empty() && values.size() + 1 != fields.size()) {
//throw "Invalid spectrum file format near '" + line + "'";
//}
//frequency.push_back(std::stod(fields[0]));
//if (values.empty()) {
//values.resize(static_cast<int>(fields.size()) - 1);
//}
//for (int i = 1; i < static_cast<int>(fields.size()); ++i) {
//values[i - 1].push_back(std::stod(fields[i]));
//}
//}
//}
//file.close();
//std::vector<Spectrum> result;
//for (auto value : values) {
//result.push_back(Spectrum(value, frequency));
//}
//return result;
//}
//int Spectrum::size() const {
//return values_.size();
//}
//double Spectrum::sum() const {
//return std::accumulate(values_.begin(), values_.end(), 0.0);
//}
//Spectrum Spectrum::normalized() const {
//return *this / sum();
//}
//Spectrum Spectrum::operator -() const {
//std::vector<double> v(values_.size());
//std::transform(values_.begin(), values_.end(), v.begin(), [](double x) { return -x; });
//return Spectrum(v, freqs_);
//}
//Spectrum Spectrum::operator +() const {
//return *this;
//}
//double Spectrum::operator [](int i) const {
//return values_[i];
//}
//double Spectrum::interpolate(double frequency) const {
//// Binary search for first element greater than 'frequency'
//int left = -1, right = freqs_.size();
//while (left + 1 < right) {
//int middle = (left + right) / 2.0;
//if (freqs_[middle] <= frequency) {
//left = middle;
//} else {
//right = middle;
//}
//}
//int upper_i = right;
//if (upper_i == 0) {
//return 0.0;
//} else if (fabs(freqs_[upper_i - 1] - frequency) < EPS) {
//return values_[upper_i - 1];
//} else if (right == freqs_.size()) {
//return 0.0;
//} else {
//double lf = freqs_[upper_i - 1], rf = freqs_[upper_i];
//double alpha = (frequency - lf) / (rf - lf);
//return (1 - alpha) * values_[upper_i - 1] + alpha * values_[upper_i];
//}
//}
//bool operator ==(const Spectrum &a, const Spectrum &b) {
//// Check for hashes
//// The next only if hashes are equal
//if (a.values_.size() != b.values_.size() ||
//a.freqs_.size() != b.freqs_.size()) {
//return false;
//}
//for (int i = 0; i < static_cast<int>(a.values_.size()); ++i) {
//if (abs(a.freqs_[i] - b.freqs_[i]) > EPS) {
//return false;
//}
//if (abs(a.values_[i] - b.values_[i]) > EPS) {
//return false;
//}
//}
//return true;
//}
//bool operator !=(const Spectrum &a, const Spectrum &b) {
//return !(a == b);
//}
//Spectrum operator +(const Spectrum &a, const Spectrum &b) {
//std::vector<double> v(a.values_);
//// If hashes are equal then
//for (int i = 0; i < static_cast<int>(v.size()); ++i) {
//v[i] += b.values_[i];
//}
//// else
//for (int i = 0; i < static_cast<int>(v.size()); ++i) {
//v[i] += b.interpolate(a.freqs_[i]);
//}
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//Spectrum operator +(double a, const Spectrum &b) {
//std::vector<double> v(b.values_.size());
//std::transform(b.values_.begin(), b.values_.end(), v.begin(), [a](double x) { return a + x; });
//return Spectrum(b.first_freq_, b.step_freq_, v);
//}
//Spectrum operator +(const Spectrum &a, double b) {
//std::vector<double> v(a.values_.size());
//std::transform(a.values_.begin(), a.values_.end(), v.begin(), [b](double x) { return x + b; });
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//// TODO: replace with copy of operator +
//Spectrum operator -(const Spectrum &a, const Spectrum &b) {
//std::vector<double> v(a.values_);
//for (int i = 0; i < static_cast<int>(v.size()); ++i) {
//v[i] -= b.values_[i];
//}
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//Spectrum operator -(double a, const Spectrum &b) {
//std::vector<double> v(b.values_.size());
//std::transform(b.values_.begin(), b.values_.end(), v.begin(), [a](double x) { return a - x; });
//return Spectrum(b.first_freq_, b.step_freq_, v);
//}
//Spectrum operator -(const Spectrum &a, double b) {
//std::vector<double> v(a.values_.size());
//std::transform(a.values_.begin(), a.values_.end(), v.begin(), [b](double x) { return x - b; });
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//// TODO: replace with copy of operator +
//Spectrum operator *(const Spectrum &a, const Spectrum &b) {
//std::vector<double> v(a.values_);
//for (int i = 0; i < static_cast<int>(v.size()); ++i) {
//v[i] *= b.values_[i];
//}
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//Spectrum operator *(double a, const Spectrum &b) {
//std::vector<double> v(b.values_.size());
//std::transform(b.values_.begin(), b.values_.end(), v.begin(), [a](double x) { return a * x; });
//return Spectrum(b.first_freq_, b.step_freq_, v);
//}
//Spectrum operator *(const Spectrum &a, double b) {
//std::vector<double> v(a.values_.size());
//std::transform(a.values_.begin(), a.values_.end(), v.begin(), [b](double x) { return x * b; });
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//// TODO: replace with copy of operator +
//Spectrum operator /(const Spectrum &a, const Spectrum &b) {
//std::vector<double> v(a.values_);
//for (int i = 0; i < static_cast<int>(v.size()); ++i) {
//v[i] /= b.values_[i];
//}
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//Spectrum operator /(const Spectrum &a, double b) {
//std::vector<double> v(a.values_.size());
//std::transform(a.values_.begin(), a.values_.end(), v.begin(), [b](double x) { return x / b; });
//return Spectrum(a.first_freq_, a.step_freq_, v);
//}
//Spectrum operator /(double a, const Spectrum &b) {
//std::vector<double> v(b.values_.size());
//std::transform(b.values_.begin(), b.values_.end(), v.begin(), [a](double x) { return a / x; });
//return Spectrum(b.first_freq_, b.step_freq_, v);
//}
//std::ostream & operator <<(std::ostream &stream, const Spectrum &t) {
//const int MAX_HEIGHT = 10;
//double mx = 0;
//for (int i = 0; i < t.size(); ++i) {
//mx = std::max(mx, t[i]);
//mx = std::max(mx, -t[i]);
//}
//int lower = 0, upper = 0;
//std::vector<int> height(t.size());
//for (int i = 0; i < t.size(); ++i) {
//height[i] = round(t[i] / mx * MAX_HEIGHT);
//lower = std::min(lower, height[i]);
//upper = std::max(upper, height[i]);
//}
//stream << "Specter: from " << t.freqs_[0]
//<< " to " << t.freqs_.back() << std::endl;
//for (int i = upper; i > 0; --i) {
//for (auto h : height) {
//stream << ((h >= i) ? "#" : " ");
//}
//stream << std::endl;
//}
//for (auto h : height) {
//stream << "-";
//}
//stream << std::endl;
//for (int i = -1; i >= lower; --i) {
//for (auto h : height) {
//stream << ((h >= i) ? "#" : " ");
//}
//stream << std::endl;
//}
//return stream;
/*}*/
| true |
10d4fa0125f47bea32d0a32b2abc6bbb19ebfdd3 | C++ | syedareehaquasar/Coding-Interview-Preparation | /Day 13 - Stacks and Queues/8. checkBalBrackets.cpp | UTF-8 | 1,365 | 3.4375 | 3 | [] | no_license | /** Check Balanced Parentheses **/
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define mod 1e9 + 7
#define MAX 100000
using namespace std;
bool isValid(string s) {
stack<char> S;
bool flag = true;
for(int i = 0; i < s.size(); i++){
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
S.push(s[i]);
} else {
if(s[i] == ')'){
if(S.empty() || S.top() != '('){
flag = false;
break;
} else {
S.pop();
}
} else if(s[i] == '}'){
if(S.empty() || S.top() != '{'){
flag = false;
break;
} else {
S.pop();
}
} else if(s[i] == ']'){
if(S.empty() || S.top() != '['){
flag = false;
break;
} else {
S.pop();
}
}
}
}
if(S.empty())
return flag;
else
return false;
}
int main() {
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
string s;
cin >> s;
bool flag = isValid(s);
if(flag) cout << "Brackets are balanced!\n";
else cout << "Brackets aren't balanced!\n";
return 0;
}
| true |
89926886d32c428d2dee2a010eaa1c0cd328fead | C++ | mattheiler/nupic.core | /nupic.core/src/engine/Output.cpp | UTF-8 | 331 | 2.59375 | 3 | [] | no_license | #include "nupic/engine/Output.hpp"
using namespace nupic::engine;
struct Output::Impl
{
Region* region;
explicit Impl(Region* region) :
region(region)
{
}
};
Output::Output(Region* region) :
impl_(make_unique<Impl>(region))
{
}
Output::~Output() = default;
Region* Output::getRegion() const
{
return impl_->region;
}
| true |
0564d4fb03ac39c83991d327c90c3e4411fe1001 | C++ | Khaos-Labs/khaos-wallet-core | /src/Cardano/AddressV3.cpp | UTF-8 | 7,673 | 2.53125 | 3 | [
"MIT"
] | permissive | // Copyright © 2017-2020 Khaos Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "AddressV3.h"
#include "AddressV2.h"
#include <KhaosWalletCore/TWCoinType.h>
#include "../Data.h"
#include "../Bech32.h"
#include "../Base32.h"
#include "../Crc.h"
#include "../HexCoding.h"
#include "../Hash.h"
#include <array>
using namespace TW;
using namespace TW::Cardano;
using namespace std;
bool AddressV3::parseAndCheckV3(const std::string& addr, Discrimination& discrimination, Kind& kind, Data& key1, Data& key2) {
try {
auto bech = Bech32::decode(addr);
if (bech.second.size() == 0) {
// empty Bech data
return false;
}
// Bech bits conversion
Data conv;
auto success = Bech32::convertBits<5, 8, false>(conv, bech.second);
if (!success) {
return false;
}
if (conv.size() != 33 && conv.size() != 65) {
return false;
}
discrimination = (Discrimination)((conv[0] & 0b10000000) >> 7);
kind = (Kind)(conv[0] & 0b01111111);
if (kind <= Kind_Sentinel_Low || kind >= Kind_Sentinel_High) {
return false;
}
if ((kind == Kind_Group && conv.size() != 65) ||
(kind != Kind_Group && conv.size() != 33)) {
return false;
}
switch (kind) {
case Kind_Single:
case Kind_Account:
case Kind_Multisig:
assert(conv.size() == 33);
key1 = Data(32);
std::copy(conv.begin() + 1, conv.begin() + 33, key1.begin());
return true;
case Kind_Group:
assert(conv.size() == 65);
key1 = Data(32);
key2 = Data(32);
std::copy(conv.begin() + 1, conv.begin() + 33, key1.begin());
std::copy(conv.begin() + 33, conv.begin() + 65, key2.begin());
return true;
default:
return false;
}
} catch (...) {
return false;
}
}
bool AddressV3::isValid(const std::string& addr) {
Discrimination discrimination;
Kind kind;
Data key1;
Data key2;
if (parseAndCheckV3(addr, discrimination, kind, key1, key2)) {
return true;
}
// not V3, try older
return AddressV2::isValid(addr);
}
AddressV3 AddressV3::createSingle(Discrimination discrimination_in, const Data& spendingKey) {
if (spendingKey.size() != 32) {
throw std::invalid_argument("Wrong spending key size");
}
auto addr = AddressV3();
addr.discrimination = discrimination_in;
addr.kind = Kind_Single;
addr.key1 = spendingKey;
return addr;
}
AddressV3 AddressV3::createGroup(Discrimination discrimination_in, const Data& spendingKey, const Data& groupKey) {
if (spendingKey.size() != 32) {
throw std::invalid_argument("Wrong spending key size");
}
if (groupKey.size() != 32) {
throw std::invalid_argument("Wrong group key size");
}
auto addr = AddressV3();
addr.discrimination = discrimination_in;
addr.kind = Kind_Group;
addr.key1 = spendingKey;
addr.groupKey = groupKey;
return addr;
}
AddressV3 AddressV3::createAccount(Discrimination discrimination_in, const Data& accountKey) {
if (accountKey.size() != 32) {
throw std::invalid_argument("Wrong spending key size");
}
auto addr = AddressV3();
addr.discrimination = discrimination_in;
addr.kind = Kind_Account;
addr.key1 = accountKey;
return addr;
}
AddressV3::AddressV3(const std::string& addr) : legacyAddressV2(nullptr) {
if (parseAndCheckV3(addr, discrimination, kind, key1, groupKey)) {
// values stored
return;
}
// try legacy
// throw on error
legacyAddressV2 = new AddressV2(addr);
}
AddressV3::AddressV3(const PublicKey& publicKey) : legacyAddressV2(nullptr) {
// input is extended pubkey, 64-byte
if (publicKey.type != TWPublicKeyTypeED25519Extended) {
throw std::invalid_argument("Invalid public key type");
}
discrimination = Discrim_Test;
kind = Kind_Group;
key1 = Data(32);
groupKey = Data(32);
std::copy(publicKey.bytes.begin(), publicKey.bytes.begin() + 32, key1.begin());
std::copy(publicKey.bytes.begin() + 32, publicKey.bytes.begin() + 64, groupKey.begin());
}
AddressV3::AddressV3(const Data& data) : legacyAddressV2(nullptr) {
// min 4 bytes, 2 prefix + 2 len
if (data.size() < 4) { throw std::invalid_argument("Address data too short"); }
assert(data.size() >= 4);
int index = 0;
discrimination = (Discrimination)data[index++];
kind = (Kind)data[index++];
// key1:
byte len1 = data[index++];
if (data.size() < 4 + len1) { throw std::invalid_argument("Address data too short"); }
assert(data.size() >= 4 + len1);
key1 = Data(len1);
std::copy(data.begin() + index, data.begin() + index + len1, key1.begin());
index += len1;
// groupKey:
byte len2 = data[index++];
if (data.size() < 4 + len1 + len2) { throw std::invalid_argument("Address data too short"); }
assert(data.size() >= 4 + len1 + len2);
groupKey = Data(len2);
std::copy(data.begin() + index, data.begin() + index + len2, groupKey.begin());
}
AddressV3::AddressV3(const AddressV3& other) :
discrimination(other.discrimination),
kind(other.kind),
key1(other.key1),
groupKey(other.groupKey),
legacyAddressV2(other.legacyAddressV2 == nullptr ? nullptr : new AddressV2(*other.legacyAddressV2))
{}
void AddressV3::operator=(const AddressV3& other)
{
discrimination = other.discrimination;
kind = other.kind;
key1 = other.key1;
groupKey = other.groupKey;
if (!legacyAddressV2) {
delete legacyAddressV2;
}
legacyAddressV2 = other.legacyAddressV2 == nullptr ? nullptr : new AddressV2(*other.legacyAddressV2);
}
string AddressV3::string() const {
std::string hrp;
switch (kind) {
case Kind_Single:
case Kind_Group:
case Kind_Account:
hrp = stringForHRP(TWHRPCardano); break;
default:
hrp = ""; break;
}
return string(hrp);
}
string AddressV3::string(const std::string& hrp) const {
if (legacyAddressV2 != nullptr) {
return legacyAddressV2->string();
}
byte first = (byte)kind;
if (discrimination == Discrim_Test) first = first | 0b10000000;
Data keys;
TW::append(keys, first);
TW::append(keys, key1);
if (groupKey.size() > 0) {
TW::append(keys, groupKey);
}
// bech
Data bech;
if (!Bech32::convertBits<8, 5, true>(bech, keys)) {
return "";
}
return Bech32::encode(hrp, bech);
}
string AddressV3::stringBase32() const {
if (legacyAddressV2 != nullptr) {
return legacyAddressV2->string();
}
byte first = (byte)kind;
if (discrimination == Discrim_Test) first = first | 0b10000000;
Data keys;
TW::append(keys, first);
TW::append(keys, key1);
if (groupKey.size() > 0) {
TW::append(keys, groupKey);
}
std::string base32 = Base32::encode(keys, "abcdefghijklmnopqrstuvwxyz23456789");
return base32;
}
Data AddressV3::data() const {
Data data;
TW::append(data, (uint8_t)discrimination);
TW::append(data, (uint8_t)kind);
TW::append(data, (uint8_t)key1.size());
TW::append(data, key1);
TW::append(data, (uint8_t)groupKey.size());
TW::append(data, groupKey);
return data;
}
| true |
ea695002e300492ed38d65edeed481b599bf61bc | C++ | DanEternity/game-main-sfml-project | /game-main/sources/ui-controller.cpp | UTF-8 | 3,305 | 2.5625 | 3 | [] | no_license | #include "ui-controller.h"
int UI_Controller::AddElement(BaseUIElem * ui_element)
{
p_list.push_back(UIEventState_private());
int idx = p_list.size() - 1;
p_list[idx].p = ui_element;
return idx;
}
bool UI_Controller::RegisterEvent(int id, UIEventType eventType, func_pointer_void_data_uiHandler eventHandler)
{
if (id < 0 || id > p_list.size() - 1)
return false;
if (eventHandler == NULL)
return false;
switch (eventType)
{
case onPress:
case onRelease:
case onHoverBegin:
case onHoverEnd:
p_list[id].flagReg[eventType] = true;
p_list[id].funcPointer[eventType] = eventHandler;
return true;
default:
return false;
}
return false;
}
bool UI_Controller::DeleteEvent(int id, UIEventType eventType)
{
if (id < 0 || id > p_list.size() - 1)
return false;
switch (eventType)
{
case onPress:
case onRelease:
case onHoverBegin:
case onHoverEnd:
p_list[id].flagReg[eventType] = false;
p_list[id].funcPointer[eventType] = NULL;
return true;
default:
return false;
break;
}
return false;
}
void UI_Controller::DispatchEvents()
{
//int m_x, m_y;
auto mp = sf::Mouse().getPosition();
bool m_left = sf::Mouse().isButtonPressed(sf::Mouse().Left);
bool m_right = sf::Mouse().isButtonPressed(sf::Mouse().Right);
auto wnd_pos = g_wnd->getPosition();
//Log("MOUSE -> " + std::to_string(mp.x) + " " + std::to_string(mp.y));
mp -= wnd_pos;
mp.x -= 7;
mp.y -= 31;
UIEventData buff;
buff.mouse_x = mp.x;
buff.mouse_y = mp.y;
buff.mouse_bt_l = m_left;
buff.mouse_bt_r = m_right;
buff.mouse_change_l = (m_left != p_m_l);
buff.mouse_change_r = (m_right != p_m_r);
for (int i(0); i < p_list.size(); i++)
{
UIEventState_private* q = &p_list[i];
buff.objectID = i;
buff.ref = q->p;
if (q->p->inside(mp.x, mp.y))
{
if (!q->p_inside)
{
q->p_inside = true;
if (q->flagReg[onHoverBegin])
{
// call onHoverBegin
Logs("Call onHoverBegin for object [");
Logp(q->p);
Logln("]");
buff.eventType = onHoverBegin;
q->funcPointer[onHoverBegin](&buff);
}
}
if ((!p_m_l && m_left || !p_m_r && m_right)&& q->flagReg[onPress])
{
// call onPress
Logs("Call onPress for object [");
Logp(q->p);
Logln("]");
buff.eventType = onPress;
q->funcPointer[onPress](&buff);
}
if ((p_m_l && !m_left || p_m_r && !m_right)&& q->flagReg[onRelease])
{
// call onRelease
Logs("Call onRelease for object [");
Logp(q->p);
Logln("]");
buff.eventType = onRelease;
q->funcPointer[onRelease](&buff);
}
}
else
if (q->p_inside)
{
q->p_inside = false;
if (q->flagReg[onHoverEnd])
{
// call onHoverEnd
Logs("Call onHoverEnd for object [");
Logp(q->p);
Logln("]");
buff.eventType = onHoverEnd;
q->funcPointer[onHoverEnd](&buff);
}
}
}
p_m_l = m_left;
p_m_r = m_right;
}
void UI_Controller::Update()
{
DispatchEvents();
}
sf::Vector2i UI_Controller::getMouseXY()
{
auto mp = sf::Mouse().getPosition();
auto wnd_pos = g_wnd->getPosition();
mp -= wnd_pos;
mp.x -= 7;
mp.y -= 31;
return mp;
}
bool UI_Controller::mouseLeftButton()
{
return sf::Mouse().isButtonPressed(sf::Mouse().Left);
}
bool UI_Controller::mouseRightButton()
{
return sf::Mouse().isButtonPressed(sf::Mouse().Right);
}
| true |
1f80bc5f0d8a441e85d245de197773999b912946 | C++ | AYUSHNSUT/Algorithms-Specialization-Coursera | /Data-Structures/week1_basic_data_structures/2_tree_height/th.cpp | UTF-8 | 643 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int height(int k, vector <int> &a, int h[])
{
if(a[k]==-1)
{
h[k]= 1;
return 1;
}
if(h[k]!= -1)
return h[k];
h[k] = 1 + height(a[k],a,h);
return h[k];
}
int main()
{
int n;
cin >> n;
vector <int> a(n);
int prnt;
for(int i = 0;i<n;i++)
{
cin >> a[i];
if(a[i]== -1)
prnt = a[i];
}
int mx = -1;
int h[n];
memset(h,-1,sizeof(h));
for(int i = 0;i<n;i++)
{
int hm = height(i,a,h);
if(hm > mx)
{
mx = hm;
}
}
for(int i = 0;i<n;i++)
{
printf("%d ",h[i]);
}
cout << endl;
cout << mx << endl;
}
| true |
9dd8d4916168f9b3cd9c7abc0671cd6e3a4989af | C++ | bodhicheng/algorithm_practise | /leetcode1171.cpp | UTF-8 | 831 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
map<int,ListNode*> mp;
mp[0] = NULL;
ListNode *x = new ListNode(head->val);
x->next = head->next;
int s = 0,cnt = 0;
while(x!=NULL) {
s += x->val;
if(mp.count(s)) {
if(s==0) head = x->next;
else {
ListNode *p = mp[s];
p->next = x->next;
}
}
else {
mp[s] = x;
}
x = x->next;
}
return head;
}
};
int main() {
return 0;
}
| true |
4720cb99442e9c17c1deeb1121456d33bb7be3a1 | C++ | rahulchhabra07/CompetitiveProgramming | /My Programs/Unlucky ticket.cpp | UTF-8 | 481 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
cin.ignore(5,'\n');
char str[(2*n)+1];
gets(str);
sort(str,str+n);
sort(str+n,str+(2*n));
int c1=0,c2=0;
for(int i=0;i<n;i++)
{
if(str[i]<str[n+i])
{
c1++;
}
if(str[i]>str[n+i])
{
c2++;
}
}
if((c1==n)||(c2==n))
{
cout<<"YES";
}
else
{
cout<<"NO";
}
return 0;
}
| true |
b0c4f82adb853115ed63ccb7f5d761cb95dfd49a | C++ | FubuFabian/PruebasITK | /HolaMundo.cxx | UTF-8 | 6,438 | 3.328125 | 3 | [] | no_license | #include "itkImage.h" //para trabajar con imagenes
#include "itkImageFileReader.h" //para leer imagenes
#include <iostream> //para imprimir en pantalla
int main(int argc, char * argv[]){
//Crear Nueva Imagen ///////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
typedef itk::Image<unsigned char, 2> ImageType; //nuevo tipo de imagen
ImageType::Pointer image = ImageType::New(); //se crea una instancia al nuevo tipo de imagen
ImageType::IndexType start; //el origen de la imagen
start[0] = 0;
start[1] = 0;
start[2] = 0;
ImageType::SizeType size; //el tamaÔøΩo de la imagen
size[0] = 200;
size[1] = 200;
size[2] = 200;
ImageType::RegionType region; //indica una nueva regiÔøΩn de la imagen
region.SetSize(size);
region.SetIndex(start);
image->SetRegions(region); //indica que region va a ser el tamaÔøΩo de todos los tipos de regiones de imagen
image->Allocate(); //asigna espacio en memoria para la informaciÔøΩn de los pixeles de la imagen
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//Leer Imagen //////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
typedef unsigned char PixelType; //indica el tipo de reppresentaciÔøΩn de los pixeles
const unsigned int dimension = 2; //indica las dimensiones de la imagen
typedef itk::Image<PixelType, dimension> ImageTypeReader; //crea un nuevo tipo de imagen
typedef itk::ImageFileReader<ImageTypeReader> ReaderType; //crea un nuevo tipo de lector de imagen para ImageTypeReader
ReaderType::Pointer reader = ReaderType::New(); //crea una nueva instancia a un lector de imagenes
const char * filename = "../../Imagenes_Prueba/lena.jpg";
std::cout<<filename<<std::endl;
reader->SetFileName(filename); //le indica al lector que archivo leer
try{
reader->Update(); //actualiza la informaciÔøΩn del lector, en una aplicaciÔøΩn normal no se usa ya que los filtros hacen esta operaciÔøΩn
}catch(itk::ExceptionObject exp){
std::cout<<"Excepcion de update"<<std::endl<<exp<<std::endl;
}
ImageTypeReader::Pointer imagenleida = reader->GetOutput(); //crea un objeto de imagen con la informaciÔøΩn leida por el lector
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//Modificar pixeles ////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
ImageType::IndexType pixelIndex; //crea un objeto de tipo index para indexar un pixel
pixelIndex[0]=27; //x
pixelIndex[1]=29; //y
pixelIndex[2]=30; //z
ImageType:PixelType pixelValue = image->GetPixel(pixelIndex); //obtiene el valor del pixel
image->SetPixel(pixelIndex, pixelValue+1); //pone el valor del pixel
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//elementos geomÔøΩtricos de las imagenes ////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
const ImageType::SpacingType& spacing = image->GetSpacing(); //lee el spacing de la imagen
std::cout<<"Spacing "<<spacing[0]<<", "<<spacing[1]<<", "<<spacing[2]<<std::endl;
ImageType::SpacingType sp; //objeto de tipo spacing, indica el espacio entre el centro de los pixeles
sp[0] = 1;
sp[1] = 0.3;
sp[2] = 1.2;
image->SetSpacing(sp); //pone el spacing a la imagen
const ImageType::PointType& origin = image->GetOrigin(); //lee el origen de la imagen
std::cout<<"Origen "<<origin[0]<<", "<<origin[1]<<", "<<origin[2]<<std::endl;
ImageType::PointType org; //objeto de tipo point. indica la posiciÔøΩn de un pixel
org[0] = 0.0;
org[1] = 0.0;
org[2] = 0.0;
image->SetOrigin(org); //pone el origen a la imagen
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
//leer el contenido del pixel mas cercano //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
typedef itk::Point<double, ImageType::ImageDimension> PointType; //se crea un nuevo tipo de punto
PointType punto; //no se crea una nstancia proque es un objeto muy pequeÔøΩo
punto[0] = 1.45;
punto[1] = 7.21;
punto[2] = 9.28;
ImageType::IndexType pixelMCIndex;
bool existe = image->TransformPhysicalPointToIndex(punto, pixelMCIndex); //transforma las coordenadas fisicas a las coordenadas del pixel mÔøΩs cercano
if(existe){ //si existia un pixel de la imagen cerca de las coordenadas fisicas del punto
ImageType::PixelType pixelMC = image->GetPixel(pixelMCIndex);
std::cout<<"Pixel mÔøΩs cercano "<<pixelMC<<std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
std::cout<<"Presiona Enter Para salir"<<std::endl;
bool salir = true;
while(salir){
if(std::cin.get()=='\n')
salir=false;
}*/
return 0;
}
| true |
0085460ef63081784e2d494020aa498d230b683e | C++ | coder3101/testcaser | /testcaser/core/integrator/result.hpp | UTF-8 | 5,946 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2018-2019 Ashar <ashar786khan@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef RESULT_HPP
#define RESULT_HPP
#include <iostream>
namespace testcaser {
namespace integrator {
/**
* @brief Enum about the exit status of the program.
*
*
*/
enum ExitStatus {
/**
* @brief The process compleed under time and memory limit and reurned 0.
*
*/
SUCCESS,
/**
* @brief Time limit was exceeded by running program.
*
*/
TIME_LIMIT_EXCEEDED,
/**
* @brief Memory limit was exceeded by running program.
*
*/
MEMORY_LIMIT_EXCEEDED,
/**
* @brief Non Zero exit code returned by the process.
*
*/
NON_ZERO_EXIT_CODE,
/**
* @brief Program did not exited normally usually because of some runtime
* errors.
*
*/
ABNORMAL_EXIT,
/**
* @brief No information available about exit status. Maybe because child
* hasn't executed at all.
*
*/
NONE
};
/**
* @brief The Wrapper that holds the complete result about the running of the
* program as child process
*
*/
class Result {
size_t runtime_memory, virtual_memory, time_taken;
size_t allocated_time, allocated_memory;
ExitStatus exit_status;
int exit_code;
public:
/**
* @brief Construct a new Result object
*
* @param runtimeMemory The RAM Memory used. Also called Physical memory used
* by the process
* @param virtualMemory The Virtual Memory Used
* @param runtime The total execution time in micro-seconds
* @param allocatedTime The total allocated time in micro-seconds.
* @param allocatedMemory The total memory that was allocated to the program.
* Virtual Memory
* @param exit_stats The exit status. It is the final verdict of the program.
* @param exit_c the process returned exit code.
*/
Result(size_t runtimeMemory, size_t virtualMemory, size_t runtime,
size_t allocatedTime, size_t allocatedMemory, ExitStatus exit_stats,
int exit_c) {
runtime_memory = runtimeMemory;
virtual_memory = virtualMemory;
time_taken = runtime;
allocated_time = allocatedTime;
allocated_memory = allocatedMemory;
exit_status = exit_stats;
exit_code = exit_c;
}
/**
* @brief parses ExitStatus into a message
*
* @param status the object to parse.
* @return std::string the parsed message.
*/
std::string parse_exit_status(testcaser::integrator::ExitStatus status) {
switch (status) {
case testcaser::integrator::ExitStatus::SUCCESS:
return "Success. Ran under memory and time limit";
case testcaser::integrator::ExitStatus::TIME_LIMIT_EXCEEDED:
return "Failure. Time limit was exceeded";
case testcaser::integrator::ExitStatus::MEMORY_LIMIT_EXCEEDED:
return "Failure. Memory Limit was exceeded";
case testcaser::integrator::ExitStatus::NON_ZERO_EXIT_CODE:
return "Unknown. Ran under time and memory but main returned non zero "
"exit code";
case testcaser::integrator::ExitStatus::ABNORMAL_EXIT:
return "Failure. Runtime Error was encountered.";
case testcaser::integrator::ExitStatus::NONE:
return "Unknown. Unknown";
break;
}
return "Unknown. Unknown. No status was reported";
}
/**
* @brief Formats and prints the result on stdout (console)
*
*/
void print_result() {
std::cout << "\n************** RESULTS ***************\n";
std::cout << "Allocted Physical Memory : " << allocated_memory << " KB ("
<< allocated_memory / 1024.0 << " MB)"
<< "\n";
std::cout << "Physical Memory Used : " << runtime_memory << " KB ("
<< runtime_memory / 1024.0 << " MB)"
<< "\n";
std::cout << "Virtual Memory Used : " << virtual_memory << " KB ("
<< virtual_memory / 1024.0 << " MB)"
<< "\n";
std::cout << "Allocated Time : "
<< static_cast<double>(allocated_time) / 1000000.0
<< " second(s) "
<< "\n";
std::cout << "Execution Time : "
<< static_cast<double>(time_taken) / 1000000.0 << " second(s) "
<< "\n";
std::cout << "Exit Code : " << exit_code << "\n";
std::cout << "Remark : " << parse_exit_status(exit_status)
<< "\n";
std::cout << "***************************************\n";
}
/**
* @brief Get the execution time of program in seconds
*
* @return double the execution time of the program.
*/
double get_execution_time() const { return time_taken / 1000000.0; }
/**
* @brief Get the virtual memory used by the program in KB
*
* @return size_t the used virtual memory in KB
*/
size_t get_virtual_memory_used() const { return virtual_memory; }
/**
* @brief Get the physical memory used by the program in KB
*
* @return size_t the used physical memory in KB
*/
size_t get_physical_memory_used() const { return runtime_memory; }
/**
* @brief Get the exit code of the program
*
* @return int the exit code
*/
int get_exit_code() const { return exit_code; }
/**
* @brief Get the exit status of the program.
*
* @return testcaser::integrator::ExitStatus the exit status
*/
testcaser::integrator::ExitStatus get_exit_status() const {
return exit_status;
}
};
} // namespace integrator
} // namespace testcaser
#endif
| true |
7732e8ae1159d213561ba61121a0122d1589ff26 | C++ | Lucria/MyKattisSolutions | /Planina.cpp | UTF-8 | 390 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <string>
using namespace std;
int main() {
int input;
cin >> input;
int side = 3;
int difference = input - 1;
for (int i = 0; i < difference; i++) {
side*=2;
side -= 1;
}
cout << (int)pow(side, 2) << endl;
return 0;
} | true |
b359d88080fc92fdef7f296cb42720755c949406 | C++ | CalderLund/Data-Structures-and-Algorithms | /priority_heap.h | UTF-8 | 3,669 | 3.875 | 4 | [] | no_license | //
// Created by Calder Lund on 2019-08-13.
//
#ifndef HEAP_PRIORITY_HEAP_H
#define HEAP_PRIORITY_HEAP_H
#include <vector>
#include <utility>
#include <functional>
template <typename T>
class Heap {
private:
std::function<bool(T,T)> priority;
std::vector<T> array;
// returns index of node i's parent/left/right
int parent(int i) {
if (i % 2 == 1) {
return i/2;
}
return i/2 - 1;
}
int left(int i) {
return 2 * i + 1;
}
int right(int i) {
return 2 * i + 2;
}
bool leaf(int i, int n) {
return left(i) >= n;
}
/* "bubbles up" until new node is in correct place on heap
* Time Complexity: O(log n)
*/
void fix_up(int i) {
while (i < array.size() && i > 0 &&
priority(array[parent(i)], array[i])) { // A[parent] < A[i]
// swap A[i] & A[parent]
iter_swap(array.begin()+parent(i),
array.begin()+i);
i = parent(i);
}
}
/* heapify converts and array into a heap
* Time Complexity: O(n)
*/
void heapify() {
int n = array.size();
for (int i = parent(n-1); i >= 0; i--) {
fix_down(i, n);
}
}
public:
/* Empty heap with comparison function
* Time Complexity: O(1)
*/
explicit Heap(std::function<bool(T,T)> f): priority(f) {}
/* Heapify's array anf gives comparison function
* Time Complexity: O(n)
*/
Heap(std::vector<T> arr, std::function<bool(T,T)> f):
priority(f), array(arr) {
heapify();
}
/* Preserves heap order through fixing downwards
* Time Complexity: O(log n)
*/
void fix_down(int i, int n) {
int j;
while (!leaf(i, n)) {
j = left(i);
if (j < n - 1 && priority(array[j], array[j+1])) // A[j] < A[j+1]
j++;
if (!priority(array[i], array[j])) // A[i] >= A[j]
break;
// swap A[i] and A[j]
iter_swap(array.begin()+i, array.begin()+j);
i = j;
}
}
/* Inserts new element in the heap
* O(log n)
*/
void insert(T value) {
array.emplace_back(value);
fix_up(array.size()-1);
}
void print() {
for (auto &x: array) {
std::cout << x << std::endl;
}
}
/* Pops element of highest priority
* O(log n)
*/
T pop() {
T highest_priority = array[0];
iter_swap(array.begin(), array.begin()+array.size()-1);
array.pop_back();
fix_down(0, array.size());
return highest_priority;
}
/* Moves highest priority element to the back
* O(log n)
*/
T deleteMax(int n) {
T highest_priority = array[0];
iter_swap(array.begin(), array.begin()+n-1);
fix_down(0, n-1);
return highest_priority;
}
/* Returns a reference to the array
* O(1)
*/
std::vector<T> &get_array() {return array;}
};
/* Sorts array using heap
* Time Complexity: O(n log n)
* Space Complexity: O(n)
*
* NOTE: space can be reduced to O(1) by making
* functions outside of class. Current set
* up requires building a Heap object, but
* we could easily do this in-place.
*/
template <typename T>
std::vector<T> heapsort(std::vector<T> array,
std::function<bool(T, T)> priority) {
Heap<T> heap(array, priority);
int n = array.size();
while (n > 1) {
heap.deleteMax(n);
heap.fix_down(0, --n);
}
return heap.get_array();
}
#endif //HEAP_PRIORITY_HEAP_H
| true |
cdeac0f7eee4ecc111fb5686e810ec83201e386b | C++ | Forrest-Z/liv_slam | /include/information_matrix_calculator.hpp | UTF-8 | 2,392 | 2.609375 | 3 | [] | no_license | #ifndef INFORMATION_MATRIX_CALCULATOR_HPP
#define INFORMATION_MATRIX_CALCULATOR_HPP
#include <ros/ros.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
class InformationMatrixCalculator {
public:
using PointT = pcl::PointXYZI;
InformationMatrixCalculator(){}
InformationMatrixCalculator(ros::NodeHandle& nh);
~InformationMatrixCalculator();
template<typename ParamServer>
void load(ParamServer& params) {
use_const_inf_matrix = params.template param<bool>("use_const_inf_matrix", false);
const_stddev_x = params.template param<double>("const_stddev_x", 0.5);
const_stddev_q = params.template param<double>("const_stddev_q", 0.1);
var_gain_a = params.template param<double>("var_gain_a", 20.0);
min_stddev_x = params.template param<double>("min_stddev_x", 0.1);
max_stddev_x = params.template param<double>("max_stddev_x", 5.0);
min_stddev_q = params.template param<double>("min_stddev_q", 0.05);
max_stddev_q = params.template param<double>("max_stddev_q", 0.2);
fitness_score_thresh = params.template param<double>("fitness_score_thresh", 2.5);
}
static double calc_fitness_score(const pcl::PointCloud<PointT>::ConstPtr& cloud1, const pcl::PointCloud<PointT>::ConstPtr& cloud2, const Eigen::Isometry3d& relpose, double max_range = std::numeric_limits<double>::max());
Eigen::MatrixXd calc_information_matrix(const pcl::PointCloud<PointT>::ConstPtr& cloud1, const pcl::PointCloud<PointT>::ConstPtr& cloud2, const Eigen::Isometry3d& relpose) const;
private:
// (1 - e^-a*x) / (1.0 - e^-a*max_x)
double weight(double a, double fitness_score_thresh, double min_y, double max_y, double fitness_score) const {
// fitness_score 越大 y就越大 fitness_score <= fitness_score_thresh 一般 fitness_score_thresh = 0.5
double y = (1.0 - std::exp(-a * fitness_score)) / (1.0 - std::exp(-a * fitness_score_thresh));
return min_y + (max_y - min_y) * y; // fitness_score 越小 越接近min_y 当 fitness_score = 0 则 = min_y, 若fitness_score 越大 越接近max_y
}
private:
bool use_const_inf_matrix;
double const_stddev_x;
double const_stddev_q;
double max_range;
double var_gain_a;
double min_stddev_x;
double max_stddev_x;
double min_stddev_q;
double max_stddev_q;
double fitness_score_thresh;
};
#endif // INFORMATION_MATRIX_CALCULATOR_HPP
| true |
c779c1020859437b266aea9946a8019e20f65919 | C++ | Sevla8/AirWatcher | /app/src/factory/Reader.h | UTF-8 | 6,216 | 2.6875 | 3 | [] | no_license | /*************************************************************************
Reader - description
-------------------
beginning : $07/05/2021$
copyright : (C) $2021$ by $B3204 and B3025 $
e-mail : $adrien.jaillet@insa-lyon.fr / william.jean@insa-lyon.fr / matheus.de-barros-silva@insa-lyon.fr
brandon.da-silva-alves@insa-lyon.fr / jade.prevot@insa-lyon.fr$
*************************************************************************/
//---------- Interface of <Reader> (file Reader.h) ----------------
#ifndef Reader_H
#define Reader_H
//--------------------------------------------------- Used Interfaces
#include <string>
#include <set>
#include <fstream>
#include "../model/Date.h"
//------------------------------------------------------------- Constants
//------------------------------------------------------------------ Types
struct SensorData {
string id;
float latitude;
float longitude;
bool operator<(const SensorData&) const;
friend std::istream& operator>>(std::istream&, SensorData&);
friend ostream& operator<<(std::ostream&, const SensorData&);
};
struct UserData {
string id;
string sensorId;
UserData() {}
UserData(const string& s) : id(""), sensorId(s) {}
bool operator<(const UserData&) const;
friend istream& operator>>(std::istream&, UserData&);
friend ostream& operator<<(std::ostream&, const UserData&);
};
struct MeasurementData {
float value;
Date date;
string sensorId;
string attributeId;
MeasurementData() {}
MeasurementData(const string& s) : sensorId(s) {}
bool operator<(const MeasurementData&) const;
friend std::istream& operator>>(std::istream&, MeasurementData&);
friend ostream& operator<<(std::ostream&, const MeasurementData&);
};
struct AttributeData {
string id;
string unit;
string description;
AttributeData() {}
AttributeData(const string& s) : id(s) {}
bool operator<(const AttributeData&) const;
friend istream& operator>>(std::istream&, AttributeData&);
friend ostream& operator<<(std::ostream&, const AttributeData&);
};
struct CleanerData {
string id;
float latitude;
float longitude;
Date start;
Date stop;
bool operator<(const CleanerData&) const;
friend istream& operator>>(std::istream&, CleanerData&);
friend ostream& operator<<(std::ostream&, const CleanerData&);
};
struct ProviderData {
string id;
string cleanerId;
ProviderData(const string& s) : id(""), cleanerId(s) {}
ProviderData() {}
bool operator<(const ProviderData&) const;
friend istream& operator>>(std::istream&, ProviderData&);
friend ostream& operator<<(std::ostream&, const ProviderData&);
};
//------------------------------------------------------------------------
// Role of <Reader>
//
// Read and parse data contained in csv files into the correspondig structures defined above
//
//------------------------------------------------------------------------
class Reader {
//----------------------------------------------------------------- PUBLIC
public:
//----------------------------------------------------- Public methods
static set<SensorData> readSensors(string filepath);
// How to use : Parse the data contained in the file whose path is given by filepath
// into SensorDatas that are inserted in a set. The set is returned.
// Precondition : The document has the following structure :
// SensorNumber;latitude;longitude;
// Example : Sensor0;44;-1;
// Precondition :
//
static set<UserData> readUsers(string filepath);
// How to use : Parse the data contained in the file whose path is given by filepath
// into UserDatas that are inserted in a set. The set is returned.
// Precondition : The document has the following structure :
// UserNumber;SensorTheyHave;
// Example : User0;Sensor70;
// Precondition :
//
static multiset<MeasurementData> readMeasurements(string filepath);
// How to use : Parse the data contained in the file whose path is given by filepath
// into MeasurementDatas that are inserted in a multiset. The multiset is returned.
// Precondition : The document has the following structure :
// DateofMeasure TimeOfMeasure;SensorNumber;AttributeMeasured;ValueOfMeasure;
// Example : 2019-01-01 12:00:00;Sensor0;O3;50.25;
// Precondition :
//
static set<AttributeData> readAttributes(string filepath);
// How to use : Parse the data contained in the file whose path is given by filepath
// into AttributeDatas that are inserted in a set. The set is returned.
// Precondition : The document has the following structure :
// AttributeMeasured;UnitsOfMeasure;TextDescriptionInFrench
// Example : O3;µg/m3;concentration d'ozone;
// Precondition :
//
static set<CleanerData> readCleaners(string filepath);
// How to use : Parse the data contained in the file whose path is given by filepath
// into CleanerDatas that are inserted in a set. The set is returned.
// Precondition : The document has the following structure :
// CleanerNumber;Latitude;Longitude;DateBeginOfOperation TimeBeginOfOperation;DateEndOfOperation TimeEndOfOperation;
// Example : Cleaner0;45.333333;1.333333;2019-02-01 12:00:00;2019-03-01 00:00:00;
// Precondition :
//
static set<ProviderData> readProviders(string filepath);
// How to use : Parse the data contained in the file whose path is given by filepath
// into ProviderDatas that are inserted in a set. The set is returned.
// Precondition : The document has the following structure :
// ProviderNumber;CleanerTheyHave;
// Example : Provider0;Cleaner0;
// Precondition :
//
//------------------------------------------------- Operators overloading
//-------------------------------------------- Constructors - destructor
//------------------------------------------------------------------ PROTECTED
protected:
//----------------------------------------------------- Protected Methods
//----------------------------------------------------- Protected Attributes
//------------------------------------------------------------------ PRIVATE
private:
//----------------------------------------------------- Private Methods
//----------------------------------------------------- Private Attributes
};
//-------------------------------- Other definitions depending on <Reader>
#endif // Reader_H
| true |
b4d09915b3907f31b49bd61fa4a693c1a0c920a6 | C++ | l24cui/Group-Project-CC3K-Game | /goblin.cc | UTF-8 | 1,686 | 2.921875 | 3 | [] | no_license | #include "goblin.h"
#include <string>
#include <sstream>
#include <cstdlib>
#include <math.h>
#include <sstream>
#include "enemy.h"
using namespace std;
Goblin::Goblin(int x, int y, int bc, Floor *fl): Player(15,20,110,"goblin",x,y,bc,fl,0,1,'.',110) {}
void Goblin::reset_Atk() {
Atk = 15;
}
Goblin::~Goblin() {}
void Goblin::reset_Def() {
Def = 20;
}
void Goblin::attack(Enemy *e) {
// cout << "Attack Enemy!" << endl;
if (e->getType() == "halfling") {
int i = rand() % 2;
if (i == 0) {
e->getAttack(this);
} else {
// cout << "Oops~ Miss!" << endl;
updateAction("PC Attack Miss ");
return;
}
} else {
e->getAttack(this);
}
string s = e->getType();
if (e->isDead() && s != "dragon" && s != "human" && s != "merchant") {
int g = rand() % 2 + 1;
Gold += g;
}
double damage2 = ceil((100/(100 + e->getDef())) * getAtk());
ostringstream ss;
ss << "PC deals " << damage2 << " damage to " << e->getType() << "(HP: " << e->getHP() << ")";
if (e->isDead()) {
Gold += 5;
ss << e->getType() << " was killed! PC steals 5 Gold!";
string q = ss.str();
updateAction(q);
} else {
string q = ss.str();
updateAction(q);
}
}
void Goblin::getAttack(Enemy *e) {
double damage = ceil((100/(100+this->getDef())) * e->getAtk());
if (e->getType() == "orc") {
if (HP >= 1.5 * damage) {
HP -= 1.5 * damage;
} else {
HP = 0;
}
// cout << "Caution! Enemy deals " << 1.5 * damage << " to PC" << endl;
} else {
if (HP >= damage) {
HP -= damage;
} else {
HP = 0;
}
// cout << "Caution! Enemy deals "<< damage <<" to PC" << endl;
}
}
| true |
ef4b2b35020214050474595b54d3e8ed7099770d | C++ | Tryneus/indecorous | /src/containers/intrusive.hpp | UTF-8 | 8,936 | 2.984375 | 3 | [] | no_license | #ifndef CONTAINERS_INTRUSIVE_HPP_
#define CONTAINERS_INTRUSIVE_HPP_
#include <atomic>
#include <cassert>
#include <cstddef>
#include <type_traits>
#include <utility>
#include "common.hpp"
namespace indecorous {
template <typename T>
class intrusive_list_t;
template <typename T>
class intrusive_node_t {
public:
intrusive_node_t() : m_next(nullptr), m_prev(nullptr) { }
intrusive_node_t(intrusive_node_t &&other) :
m_next(other.m_next),
m_prev(other.m_prev) {
if (m_next != nullptr) { m_next->m_prev = this; }
if (m_prev != nullptr) { m_prev->m_next = this; }
other.m_next = nullptr;
other.m_prev = nullptr;
}
virtual ~intrusive_node_t() {
assert(!in_a_list());
}
bool in_a_list() {
return (m_next != nullptr) || (m_prev != nullptr);
}
// TODO: make these private? they shouldn't be used by anyone but the list
void clear() { m_next = nullptr; m_prev = nullptr; }
void set_next_node(intrusive_node_t *next) { m_next = next; }
void set_prev_node(intrusive_node_t *prev) { m_prev = prev; }
intrusive_node_t *next_node() const { return m_next; }
intrusive_node_t *prev_node() const { return m_prev; }
private:
intrusive_node_t* m_next;
intrusive_node_t* m_prev;
DISABLE_COPYING(intrusive_node_t);
};
template <typename T>
class intrusive_list_t : public intrusive_node_t<T> {
public:
intrusive_list_t() :
m_size(0) {
this->set_prev_node(this);
this->set_next_node(this);
}
intrusive_list_t(intrusive_list_t<T> &&other) :
intrusive_node_t<T>(std::move(other)),
m_size(other.m_size) {
if (this->next_node() == &other) {
assert(m_size == 0);
assert(this->prev_node() == &other);
this->set_prev_node(this);
this->set_next_node(this);
}
other.set_next_node(&other);
other.set_prev_node(&other);
other.m_size = 0;
}
virtual ~intrusive_list_t() {
assert(m_size == 0);
assert(this->next_node() == this);
assert(this->prev_node() == this);
this->set_next_node(nullptr);
this->set_prev_node(nullptr);
}
void swap(intrusive_list_t<T> *other) {
if (m_size == 0) {
if (other->m_size == 0) {
// Both lists empty - do nothing
} else {
// This list empty, other has entries
this->set_next_node(other->next_node());
this->set_prev_node(other->prev_node());
this->next_node()->set_prev_node(this);
this->prev_node()->set_next_node(this);
other->set_next_node(other);
other->set_prev_node(other);
}
} else {
if (other->m_size == 0) {
// This list has entries, other is empty
other->set_next_node(this->next_node());
other->set_prev_node(this->prev_node());
other->next_node()->set_prev_node(other);
other->prev_node()->set_next_node(other);
this->set_next_node(this);
this->set_prev_node(this);
} else {
// Both lists have entries
intrusive_node_t<T> *tmp;
tmp = this->next_node();
this->set_next_node(other->next_node());
other->set_next_node(tmp);
tmp = this->prev_node();
this->set_prev_node(other->prev_node());
other->set_prev_node(tmp);
other->next_node()->set_prev_node(other);
other->prev_node()->set_next_node(other);
this->next_node()->set_prev_node(this);
this->prev_node()->set_next_node(this);
}
}
std::swap(m_size, other->m_size);
}
size_t size() const {
return m_size;
}
template <typename Callable>
void each(Callable &&callable) {
T *item = front();
while (item != nullptr) {
callable(item);
item = next(item);
}
}
template <typename Callable>
void clear(Callable &&callable) {
while (!empty()) {
callable(pop_front());
}
}
T* front() {
return get_value(this->next_node());
}
T* back() {
return get_value(this->prev_node());
}
T* next(T* item) {
intrusive_node_t<T> *node = item;
return get_value(node->next_node());
}
T* prev(T* item) {
intrusive_node_t<T> *node = item;
return get_value(node->prev_node());
}
void push_back(T *item) {
insert_between(item, this->prev_node(), this);
}
void push_front(T *item) {
insert_between(item, this, this->next_node());
}
T *pop_front() {
T *res = get_value(this->next_node());
if (res != nullptr) remove_node(res);
return res;
}
T *pop_back() {
T *res = get_value(this->prev_node());
if (res != nullptr) remove_node(res);
return res;
}
void insert_before(T *after, T *item) {
insert_between(item, after->intrusive_node_t<T>::prev_node(), after);
}
void remove(T* item) {
remove_node(item);
}
bool empty() const {
return (this->next_node() == this);
}
private:
T *get_value(intrusive_node_t<T> *node) {
if (node == this) return nullptr;
return static_cast<T *>(node);
}
void insert_between(T *item,
intrusive_node_t<T> *before,
intrusive_node_t<T> *after) {
item->intrusive_node_t<T>::set_prev_node(before);
item->intrusive_node_t<T>::set_next_node(after);
before->intrusive_node_t<T>::set_next_node(item);
after->intrusive_node_t<T>::set_prev_node(item);
++m_size;
}
void remove_node(intrusive_node_t<T> *node) {
node->prev_node()->set_next_node(node->next_node());
node->next_node()->set_prev_node(node->prev_node());
node->clear();
--m_size;
}
size_t m_size;
DISABLE_COPYING(intrusive_list_t);
};
// This is a singly-linked list and does not use 'prev'
// Implementation copied from:
// http://www.1024cores.net/home/lock-free-algorithms/queues/intrusive-mpsc-node-based-queue
template <typename T>
class mpsc_queue_t : private intrusive_node_t<T> {
public:
mpsc_queue_t() : m_front(this), m_back(reinterpret_cast<intptr_t>(this)) {
this->set_next_node(nullptr);
}
~mpsc_queue_t() {
assert(this == m_front);
assert(this == reinterpret_cast<intrusive_node_t<T> *>(m_back.load()));
assert(this->next_node() == nullptr);
}
void push(T *item) {
logDebug("mpsc_queue_t enqueueing %p", item);
item->set_next_node(nullptr);
intrusive_node_t<T> *prev = exchange_back(item);
prev->set_next_node(item);
}
T *pop() {
if (m_front == this) {
if (this->next_node() == nullptr) { return nullptr; }
m_front = this->next_node();
this->set_next_node(nullptr);
}
assert(m_front != this);
intrusive_node_t<T> *node = m_front;
intrusive_node_t<T> *next = m_front->next_node();
if (next != nullptr) {
assert(node != this);
m_front = next;
node->set_next_node(nullptr);
logDebug("mpsc_queue_t popped %p", node);
return static_cast<T *>(node);
}
if (m_front != reinterpret_cast<intrusive_node_t<T> *>(m_back.load())) {
return nullptr;
}
push_self();
next = m_front->next_node();
if (next != nullptr) {
m_front = next;
node->set_next_node(nullptr);
logDebug("mpsc_queue_t popped %p", node);
return static_cast<T *>(node);
}
return nullptr;
}
// This may not be accurate if called when other threads could be writing to the queue
size_t size() const {
size_t res = 0;
for (auto cursor = m_front; cursor != nullptr; cursor = cursor->next_node()) {
if (cursor != this) { ++res; }
}
return res;
}
private:
void push_self() {
assert(this->next_node() == nullptr);
intrusive_node_t<T> *prev = exchange_back(this);
prev->set_next_node(this);
}
intrusive_node_t<T> *exchange_back(intrusive_node_t<T> *item) {
return reinterpret_cast<intrusive_node_t<T> *>(m_back.exchange(
reinterpret_cast<intptr_t>(item)));
}
intrusive_node_t<T> *m_front;
std::atomic<intptr_t> m_back; // intrusive_node_t<T> *
DISABLE_COPYING(mpsc_queue_t);
};
} // namespace indecorous
#endif // CONTAINERS_INTRUSIVE_HPP_
| true |
0a86632e34131dfa206f41f6bbb34e567311ae02 | C++ | bbhavsar/ltc | /longestCommonSubstr.cc | UTF-8 | 1,315 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
string findLongestCommonSubstring(const string& s1, const string& s2) {
int lcs[s1.length()][s2.length()];
int max = 0;
int maxEndIdxS1 = 0;
for (int i = 0; i < s1.length(); ++i) {
for (int j = 0; j < s2.length(); ++j) {
if (s1[i] == s2[j]) {
if (i == 0 || j == 0) {
lcs[i][j] = 1;
} else {
lcs[i][j] = lcs[i-1][j-1]+ 1;
}
if (max < lcs[i][j]) {
max = lcs[i][j];
maxEndIdxS1 = i;
}
} else {
// Imp: Moment we encounter unequal char drop count
// to 0 else it becomes longest common subsequence
// and we can't compare multiple substring matches.
lcs[i][j] = 0;
}
}
}
if (max > 0) {
return s1.substr(maxEndIdxS1 - max + 1, max);
} else {
return string();
}
}
int main() {
pair<string, string> pairs[] = {
make_pair("abcdef", "xbcxyz"),
make_pair("abcdefabcdefg", "xbcdyfabcdzy")
};
for (auto& p : pairs) {
cout << findLongestCommonSubstring(p.first, p.second) << endl;
}
return 0;
}
| true |
0a929fa739e14923940b2b8eca37a84ce4015082 | C++ | Xiphoseer/Assembly | /src/filesystem_windows.cpp | UTF-8 | 1,465 | 2.828125 | 3 | [] | no_license | #include "filesystem.hpp"
#ifdef _MSC_VER
#include <Windows.h>
std::vector<std::string>
fs::files_in_dir ( const std::string& dir,
const std::string& filter )
{
std::vector<std::string> files;
WIN32_FIND_DATA fd;
std::string search = dir + "\\" + filter;
HANDLE h = FindFirstFile(search.c_str(), &fd);
while (h != INVALID_HANDLE_VALUE)
{
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
files.push_back(fd.cFileName);
}
if (!FindNextFile(h, &fd))
{
FindClose(h);
h = INVALID_HANDLE_VALUE;
}
}
return files;
}
typedef bool (*fd_check) (WIN32_FIND_DATA);
bool is_dir(WIN32_FIND_DATA fd)
{
return fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
}
bool is_not_dir(WIN32_FIND_DATA fd)
{
return !is_dir(fd);
}
bool is_any(WIN32_FIND_DATA fd)
{
return true;
}
bool
exists(const std::string& path, fd_check test)
{
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFile(dir.c_str(), &fd);
if (h != INVALID_HANDLE_VALUE)
{
if (fd_check(fd))
{
FindClose(h);
return true;
}
}
FindClose(h);
return false;
}
bool
fs::dir_exists ( const std::string& path )
{
return exists(path, *is_dir);
}
bool
fs::file_exists ( const std::string& path )
{
return exists(path, *is_not_dir);
}
bool
fs::exists ( const std::string& path )
{
return exists(path, *is_any);
}
int
fs::create_dir ( const std::string& path )
{
return CreateDirectory(dir.c_str(), NULL);
}
#endif // defined _MSC_VER
| true |
29f12a14daa6eb1e817a278695fcd01868744669 | C++ | kyelin/ClanLib | /Utilities/SwrCompiler/GLSL/FixedFunction/SSA/ssa_ubyte_ptr.h | UTF-8 | 810 | 2.53125 | 3 | [
"Zlib"
] | permissive |
#pragma once
#include "ssa_ubyte.h"
#include "ssa_int.h"
#include "ssa_vec4i.h"
#include "ssa_vec8s.h"
#include "ssa_vec16ub.h"
namespace llvm { class Value; }
namespace llvm { class Type; }
class SSAUBytePtr
{
public:
SSAUBytePtr();
explicit SSAUBytePtr(llvm::Value *v);
static SSAUBytePtr from_llvm(llvm::Value *v) { return SSAUBytePtr(v); }
static llvm::Type *llvm_type();
SSAUBytePtr operator[](SSAInt index) const;
SSAUByte load() const;
SSAVec4i load_vec4ub() const;
SSAVec8s load_vec8s() const;
SSAVec16ub load_vec16ub() const;
SSAVec16ub load_unaligned_vec16ub() const;
void store(const SSAUByte &new_value);
void store_vec4ub(const SSAVec4i &new_value);
void store_vec16ub(const SSAVec16ub &new_value);
void store_unaligned_vec16ub(const SSAVec16ub &new_value);
llvm::Value *v;
};
| true |
f30a30127455020281545f629ee91d98d604aa28 | C++ | mazoku/Arduino | /sketches/digi_3_butts_press/digi_3_butts_press.ino | UTF-8 | 1,525 | 3 | 3 | [] | no_license | const byte rLed = 13; // cervena LED
const byte tl1 = 2; // tlacitko 1
int stavLed = LOW; // soucasny stav LEDky
int stavTlac; // soucasny stav tlacitka
int poslStavTlac = LOW; // predchozi stav tlacitka
long poslCasDebounce = 0; // cas posledni zmeny stavu tlacitka
long debounceSirka = 50; // sirka okna the debounce time; increase if the output flickers
void setup() {
pinMode(tl1, INPUT);
pinMode(rLed, OUTPUT);
// vychozi stav LED
digitalWrite(rLed, stavLed);
}
void loop() {
// read the state of the switch into a local variable:
int stav = digitalRead(tl1);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (stav != poslStavTlac) {
// reset the debouncing timer
poslCasDebounce = millis();
}
if ((millis() - poslCasDebounce) > debounceSirka) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (stav != stavTlac) {
stavTlac = stav;
// only toggle the LED if the new button state is HIGH
if (stavTlac == HIGH) {
stavLed = !stavLed;
}
}
}
// set the LED:
digitalWrite(rLed, stavLed);
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
poslStavTlac = stav;
}
| true |
8bc4a8747ab2f45155d69b83ff1506bbf54894d5 | C++ | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Evan-En | /src/classwork/03_assign/main.cpp | UTF-8 | 427 | 3.46875 | 3 | [
"MIT"
] | permissive | //Write the include statement for decision.h here
#include "decision.h"
//Write namespace using statements for cout and cin
#include<iostream>
using std::cout; using std::cin; using std::endl;
int main()
{
int grade;
cout << "Enter your grade: ";
cin >> grade;
cout << "If Letter Grade: " << get_letter_grade_using_if(grade) << endl;
cout << "Switch Letter grade: " << get_letter_grade_using_switch(grade);
return 0;
}
| true |
2de5a838448c3f0faf60b09ea827f8e0906fa75a | C++ | johnathan79717/competitive-programming | /TopCoder/UndoHistory.cpp | UTF-8 | 1,008 | 2.65625 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <map>
#include <cstring>
#include <cstdio>
#include <cassert>
#include <cstdlib>
#include <sstream>
#include <queue>
using namespace std;
class UndoHistory {
public:
int minPresses(vector <string> lines) {
int ans = lines[0].size() + 1;
for(int i = 1; i < lines.size(); ++i) {
// cout << ans << endl;
if(lines[i-1].size() <= lines[i].size()) {
int k;
for(k = 0; k < lines[i-1].size(); ++k)
if(lines[i-1][k] != lines[i][k]) break;
if(k == lines[i-1].size()) {
ans += (lines[i].size() - lines[i-1].size() + 1);
continue;
}
}
int best = 0;
for(int j = 0; j < i; ++j) {
int k;
for(k = 0; k < min(lines[i].size(), lines[j].size()); ++k)
if(lines[i][k] != lines[j][k]) break;
best = max(best, k);
}
ans += (3 + lines[i].size() - best);
}
return ans;
}
};
| true |
bbadc5a9ff5b52ae9b3482fb9df1ffde8bd982b9 | C++ | peterzxli/cvpp | /structs/struct_screen.h | UTF-8 | 2,463 | 2.53125 | 3 | [] | no_license | #ifndef STRUCT_SCREEN_H
#define STRUCT_SCREEN_H
#include <cvpp/structs/struct_borders2.h>
#include <cvpp/properties/pose.h>
namespace cvpp
{
class Screen
{
protected:
public:
unsigned type,view;
Borders2f borders,resolution,resoriginal;
Scalar background;
String title;
bool lockX,lockY,lockZ,changed;
unsigned nTickX,nTickY,nTickZ;
float fov , fx , fy , cx , cy ;
float w , h , far , near ;
Pointer< Posef > viewer;
Posef view_original;
bool isCalibrated;
double perspective[16];
public:
bool isLocked() const { return lockX && lockY && lockZ; }
Screen()
{
fov = 45; view = 0;
nTickX = nTickY = nTickZ = 5;
fx = 600 , fy = 600 , cx = 640 , cy = 480 ;
w = 1280 , h = 960 , far = 1000 , near = 0.001 ;
isCalibrated = false;
lockX = lockY = lockZ = false;
changed = false;
viewer = std::make_shared< Posef >();
}
Screen( const Screen& scr )
{
*this = scr;
}
Screen& operator=( const Screen& scr )
{
this->fov = scr.fov;
this->view = scr.view;
this->lockX = scr.lockX;
this->lockY = scr.lockY;
this->lockZ = scr.lockZ;
this->viewer = scr.viewer;
}
void initialise( const Borders2f& borders ,
const Scalar& background )
{
this->borders = borders;
this->background = background;
}
void calibrate()
{
perspective[0] = 2 * fx / w ;
perspective[5] = 2 * fy / h ;
perspective[1] = perspective[2] = perspective[3] = 0 ;
perspective[4] = perspective[6] = perspective[7] = 0 ;
perspective[8] = 2.0 * ( cx / w ) - 1.0 ;
perspective[9] = 2.0 * ( cy / h ) - 1.0 ;
perspective[10] = - ( far + near ) / ( far - near ) ;
perspective[11] = - 1.0 ;
perspective[12] = perspective[13] = perspective[15] = 0;
perspective[14] = - 2.0 * far * near / ( far - near );
isCalibrated = true;
}
TPL_T void remOffset( Pts2<T>* pts ) const
{
(*pts) -= resolution.lu();
pts->mat().c(0) *= borders.w() / resolution.w();
pts->mat().c(1) *= borders.h() / resolution.h();
(*pts) += borders.lu();
}
TPL_T Pts2<T> remOffset( const Pts2<T>& pts ) const
{
Pts2<T> tmp = pts.clone();
remOffset( &tmp );
return tmp;
}
};
}
#endif
| true |
c52b4df4375278e3db720f39ebbcc36bca796deb | C++ | yejin5/simple_cpp | /58/58/ReadNumber.cpp | UTF-8 | 2,902 | 3.3125 | 3 | [] | no_license |
#include <iostream>
#include <cstdlib>
#include <fstream>
#include "ReadNumber.h"
using namespace std;
char ReadNumber::digits[10][MAX_Length] = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
char ReadNumber::teens[20][MAX_Length] = {
"", "", "", "", "", "", "", "", "", "",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
char ReadNumber::ties[10][MAX_Length] = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
char ReadNumber::units[4][MAX_Length] = {
"Hundred", "Thousand", "Million", "Billion" };
ReadNumber::ReadNumber() :number(1)
{}
ReadNumber::ReadNumber(unsigned int num) : number(num)
{}
void ReadNumber::setNumber(unsigned int num)
{
number = num;
}
void ReadNumber::read() const
{
int compute_num[4];
unsigned int num_2 = number;
for (int i = 3; i >= 0; i--)
{
compute_num[i] = num_2 % 1000;
num_2 = num_2 / 1000;
}
if (compute_num[0] > 0)
{
cout << digits[compute_num[0]] << "_" << units[3];
if (number % 1000000000 != 0)
cout << "_";
}
if (compute_num[1] > 0)
{
if (compute_num[1] >= 100)
{
cout << digits[compute_num[1] / 100] << "_" << units[0];
if (compute_num[1] % 100 != 0)
cout << "_";
}
if (compute_num[1] % 100 >= 20)
{
cout << ties[(compute_num[1] % 100) / 10] << "_";
if (compute_num[1] % 10 > 0)
cout << digits[compute_num[1] % 10] << "_";
}
else if (compute_num[1] % 100 >= 10)
cout << teens[compute_num[1] % 100] << "_";
else
cout << digits[compute_num[1] % 10] << "_";
cout << units[2];
if (number % 1000000 != 0)
cout << "_";
}
if (compute_num[2] > 0)
{
if (compute_num[2] >= 100)
{
cout << digits[compute_num[2] / 100] << "_" << units[0];
if (compute_num[2] % 100 != 0)
cout << "_";
}
if (compute_num[2] % 100 >= 20)
{
cout << ties[(compute_num[2] % 100) / 10] << "_";
if (compute_num[2] % 10 > 0)
cout << digits[compute_num[2] % 10] << "_";
}
else if (compute_num[2] % 100 >= 10)
cout << teens[compute_num[2] % 100] << "_";
else
cout << digits[compute_num[2] % 10] << "_";
cout << units[1];
if (number % 1000 != 0)
cout << "_";
}
if (compute_num[3] > 0)
{
if (compute_num[3] >= 100)
{
cout << digits[compute_num[3] / 100] << "_" << units[0];
if (number % 100 != 0)
cout << "_";
}
if (compute_num[3] % 100 >= 20)
{
cout << ties[(compute_num[3] % 100) / 10];
if (number % 10 != 0)
cout << "_" << digits[compute_num[3] % 10];
}
else if (compute_num[3] % 100 >= 10)
cout << teens[compute_num[3] % 100];
else
cout << digits[compute_num[3] % 10];
}
cout << endl;
} | true |
a24c401f38b164c3f2cd4d2d787b391ef51841e9 | C++ | sing-dance-rap-basketball/leetcode | /zxq/cpp/167-two-sum-ii-input-array-is-sorted.cpp | UTF-8 | 1,072 | 3.296875 | 3 | [] | no_license | /*
* @lc app=leetcode id=167 lang=cpp
*
* [167] Two Sum II - Input array is sorted
*/
/*
√ Accepted
√ 17/17 cases passed (4 ms)
√ Your runtime beats 97.6 % of cpp submissions
√ Your memory usage beats 79.27 % of cpp submissions (9.4 MB)
*/
class Solution {
public:
int FindTarget(vector<int>& nums, int target, int f, int b)
{
while (f <= b) {
int m = (f + b) / 2;
if (nums[m] == target) {
return m;
}
else if (nums[m] > target) {
b = m - 1;
}
else {
f = m + 1;
}
}
return -1;
}
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res(2, 0);
for (int i = 0; i < numbers.size() - 1; ++i) {
int j = FindTarget(numbers, target-numbers[i], i+1, numbers.size()-1);
if (j >= 0) {
res[0] = i + 1;
res[1] = j + 1;
break;
}
}
return res;
}
};
| true |
2f7b201d4e1b089f04ed47d8a4a054910d73c787 | C++ | david30907d/Online-judge | /ITSA/中文題庫/競賽/38屆/Problem3.糖果分享.cpp | BIG5 | 968 | 2.875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char *argv[]){
int input[22][22]={0};
int time=0;
while(scanf("%d",&time)!=EOF){
while(time>0){
memset(input,0,sizeof(input));//l]0 L}G1
int col,row;
scanf("%d",&col);
scanf("%d",&row);//J C
int i=0,j=0;
/*
for(i=1;i<=row;i++){
for(j=1;j<=col;j++){
scanf("%d",&input[row][col]);
}
}//J*/
int bags=0;//}GN
scanf("%d",&bags);
int x,y;
for(i=1;i<=bags;i++){//}GXhA쬰1
scanf("%d",&x);
scanf("%d",&y);
input[y+1][x]=1;
input[y-1][x]=1;
input[y][x+1]=1;
input[y][x-1]=1;
}
int check=1;
for(i=1;i<=row;i++){
if(check!=1)break;
for(j=1;j<=col;j++){
if(input[i][j]!=1){
check=0;
break;
}
}
}
if(check!=1){
printf("N\n");
}
else{
printf("Y\n");
}
time--;
}
}
return 0;
}
| true |
d78cc86c20238b2540c073fb592d402f41c638de | C++ | TPS/mango | /include/mango/math/vector512_int8x64.hpp | UTF-8 | 9,067 | 2.5625 | 3 | [
"Zlib"
] | permissive | /*
MANGO Multimedia Development Platform
Copyright (C) 2012-2020 Twilight Finland 3D Oy Ltd. All rights reserved.
*/
#pragma once
#include <mango/math/vector.hpp>
namespace mango
{
template <>
struct Vector<s8, 64>
{
using VectorType = simd::s8x64;
using ScalarType = s8;
enum { VectorSize = 64 };
VectorType m;
ScalarType& operator [] (size_t index)
{
assert(index < VectorSize);
return data()[index];
}
ScalarType operator [] (size_t index) const
{
assert(index < VectorSize);
return data()[index];
}
ScalarType* data()
{
return reinterpret_cast<ScalarType *>(this);
}
const ScalarType* data() const
{
return reinterpret_cast<const ScalarType *>(this);
}
explicit Vector() {}
Vector(s8 s)
: m(simd::s8x64_set(s))
{
}
Vector(
s8 v00, s8 v01, s8 v02, s8 v03, s8 v04, s8 v05, s8 v06, s8 v07,
s8 v08, s8 v09, s8 v10, s8 v11, s8 v12, s8 v13, s8 v14, s8 v15,
s8 v16, s8 v17, s8 v18, s8 v19, s8 v20, s8 v21, s8 v22, s8 v23,
s8 v24, s8 v25, s8 v26, s8 v27, s8 v28, s8 v29, s8 v30, s8 v31,
s8 v32, s8 v33, s8 v34, s8 v35, s8 v36, s8 v37, s8 v38, s8 v39,
s8 v40, s8 v41, s8 v42, s8 v43, s8 v44, s8 v45, s8 v46, s8 v47,
s8 v48, s8 v49, s8 v50, s8 v51, s8 v52, s8 v53, s8 v54, s8 v55,
s8 v56, s8 v57, s8 v58, s8 v59, s8 v60, s8 v61, s8 v62, s8 v63)
: m(simd::s8x64_set(
v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15,
v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31,
v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47,
v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63))
{
}
Vector(simd::s8x64 v)
: m(v)
{
}
template <typename T, int I>
Vector& operator = (const ScalarAccessor<ScalarType, T, I>& accessor)
{
*this = ScalarType(accessor);
return *this;
}
Vector(const Vector& v) = default;
Vector& operator = (const Vector& v)
{
m = v.m;
return *this;
}
Vector& operator = (simd::s8x64 v)
{
m = v;
return *this;
}
Vector& operator = (s8 s)
{
m = simd::s8x64_set(s);
return *this;
}
operator simd::s8x64 () const
{
return m;
}
#ifdef int512_is_hardware_vector
operator simd::s8x64::vector () const
{
return m.data;
}
#endif
static Vector ascend()
{
return Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63);
}
};
static inline const Vector<s8, 64> operator + (Vector<s8, 64> v)
{
return v;
}
static inline Vector<s8, 64> operator - (Vector<s8, 64> v)
{
return simd::neg(v);
}
static inline Vector<s8, 64>& operator += (Vector<s8, 64>& a, Vector<s8, 64> b)
{
a = simd::add(a, b);
return a;
}
static inline Vector<s8, 64>& operator -= (Vector<s8, 64>& a, Vector<s8, 64> b)
{
a = simd::sub(a, b);
return a;
}
static inline Vector<s8, 64> operator + (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::add(a, b);
}
static inline Vector<s8, 64> operator - (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::sub(a, b);
}
static inline Vector<s8, 64> unpacklo(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::unpacklo(a, b);
}
static inline Vector<s8, 64> unpackhi(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::unpackhi(a, b);
}
static inline Vector<s8, 64> abs(Vector<s8, 64> a)
{
return simd::abs(a);
}
static inline Vector<s8, 64> abs(Vector<s8, 64> a, mask8x64 mask)
{
return simd::abs(a, mask);
}
static inline Vector<s8, 64> abs(Vector<s8, 64> a, mask8x64 mask, Vector<s8, 64> value)
{
return simd::abs(a, mask, value);
}
static inline Vector<s8, 64> add(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask)
{
return simd::add(a, b, mask);
}
static inline Vector<s8, 64> add(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask, Vector<s8, 64> value)
{
return simd::add(a, b, mask, value);
}
static inline Vector<s8, 64> sub(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask)
{
return simd::sub(a, b, mask);
}
static inline Vector<s8, 64> sub(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask, Vector<s8, 64> value)
{
return simd::sub(a, b, mask, value);
}
static inline Vector<s8, 64> adds(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::adds(a, b);
}
static inline Vector<s8, 64> adds(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask)
{
return simd::adds(a, b, mask);
}
static inline Vector<s8, 64> adds(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask, Vector<s8, 64> value)
{
return simd::adds(a, b, mask, value);
}
static inline Vector<s8, 64> subs(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::subs(a, b);
}
static inline Vector<s8, 64> subs(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask)
{
return simd::subs(a, b, mask);
}
static inline Vector<s8, 64> subs(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask, Vector<s8, 64> value)
{
return simd::subs(a, b, mask, value);
}
static inline Vector<s8, 64> min(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::min(a, b);
}
static inline Vector<s8, 64> min(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask)
{
return simd::min(a, b, mask);
}
static inline Vector<s8, 64> min(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask, Vector<s8, 64> value)
{
return simd::min(a, b, mask, value);
}
static inline Vector<s8, 64> max(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::max(a, b);
}
static inline Vector<s8, 64> max(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask)
{
return simd::max(a, b, mask);
}
static inline Vector<s8, 64> max(Vector<s8, 64> a, Vector<s8, 64> b, mask8x64 mask, Vector<s8, 64> value)
{
return simd::max(a, b, mask, value);
}
static inline Vector<s8, 64> clamp(Vector<s8, 64> a, Vector<s8, 64> low, Vector<s8, 64> high)
{
return simd::clamp(a, low, high);
}
// ------------------------------------------------------------------
// bitwise operators
// ------------------------------------------------------------------
static inline Vector<s8, 64> nand(Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::bitwise_nand(a, b);
}
static inline Vector<s8, 64> operator & (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::bitwise_and(a, b);
}
static inline Vector<s8, 64> operator | (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::bitwise_or(a, b);
}
static inline Vector<s8, 64> operator ^ (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::bitwise_xor(a, b);
}
static inline Vector<s8, 64> operator ~ (Vector<s8, 64> a)
{
return simd::bitwise_not(a);
}
// ------------------------------------------------------------------
// compare / select
// ------------------------------------------------------------------
static inline mask8x64 operator > (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::compare_gt(a, b);
}
static inline mask8x64 operator < (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::compare_gt(b, a);
}
static inline mask8x64 operator == (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::compare_eq(a, b);
}
static inline mask8x64 operator >= (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::compare_ge(a, b);
}
static inline mask8x64 operator <= (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::compare_le(b, a);
}
static inline mask8x64 operator != (Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::compare_neq(a, b);
}
static inline Vector<s8, 64> select(mask8x64 mask, Vector<s8, 64> a, Vector<s8, 64> b)
{
return simd::select(mask, a, b);
}
} // namespace mango
| true |
af52b9841002805ff5b972d6da20fdcc823b93af | C++ | OnkarSD/react-all | /oop/template1.cpp | UTF-8 | 274 | 3.359375 | 3 | [] | no_license | #include<iostream>
using namespace std;
template <typename T>
void add(T a, T b)
{
cout<<a+b<<endl;
}
template<typename T>
void sub(T a, T b)
{
cout<<a-b;
}
int main()
{
add<int>(10, 20);
add<int>(30, 40);
sub<float>(10.20, 34.50);
return 0;
} | true |
4b72f863b196074d3ad518e80e41295deb81f55f | C++ | H-Shen/Collection_of_my_coding_practice | /Leetcode/13/13.cpp | UTF-8 | 1,287 | 2.828125 | 3 | [] | no_license | class Solution {
public:
int romanToInt(string s) {
unordered_map<string,int> unmap;
unmap["I"] = 1;
unmap["V"] = 5;
unmap["X"] = 10;
unmap["L"] = 50;
unmap["C"] = 100;
unmap["D"] = 500;
unmap["M"] = 1000;
unmap["IV"] = 4;
unmap["IX"] = 9;
unmap["XL"] = 40;
unmap["XC"] = 90;
unmap["CD"] = 400;
unmap["CM"] = 900;
deque<char> dq(s.begin(),s.end());
int result = 0;
string str;
// greedy
while (!dq.empty()) {
if (dq.size() == 1) {
str.clear();
str.push_back(dq.front());
result += unmap[str];
dq.pop_front();
}
else {
str.clear();
str.push_back(dq.front());
dq.pop_front();
str.push_back(dq.front());
dq.pop_front();
if (unmap.count(str) > 0) {
result += unmap[str];
}
else {
dq.push_front(str.back());
str.pop_back();
result += unmap[str];
}
}
}
return result;
}
}; | true |
07a2402604b3c4d89222694161f167aa66c0afe7 | C++ | ravendb/ravendb-cpp-client | /Raven.CppClient.Tests/User.h | UTF-8 | 1,199 | 2.828125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "json_utils.h"
namespace ravendb::client::tests::infrastructure::entities
{
struct User
{
std::string id{};
std::string name{};
std::string lastName{};
std::string addressId{};
int32_t count{};
int32_t age{};
friend bool operator==(const User& lhs, const User& rhs)
{
return //lhs.id == rhs.id
lhs.name == rhs.name
&& lhs.lastName == rhs.lastName
&& lhs.addressId == rhs.addressId
&& lhs.count == rhs.count
&& lhs.age == rhs.age;
}
};
inline void to_json(nlohmann::json& j, const User& u)
{
using ravendb::client::impl::utils::json_utils::set_val_to_json;
set_val_to_json(j, "name", u.name);
set_val_to_json(j, "lastName", u.lastName);
set_val_to_json(j, "addressId", u.addressId);
set_val_to_json(j, "count", u.count);
set_val_to_json(j, "age", u.age);
}
inline void from_json(const nlohmann::json& j, User& u)
{
using ravendb::client::impl::utils::json_utils::get_val_from_json;
get_val_from_json(j, "name", u.name);
get_val_from_json(j, "lastName", u.lastName);
get_val_from_json(j, "addressId", u.addressId);
get_val_from_json(j, "count", u.count);
get_val_from_json(j, "age", u.age);
}
}
| true |
7b9d34bf7cf2c5c2a73f7489ae58b6ecade50453 | C++ | j0sht/csci161 | /absolute-c++/c09-strings/selftests/e10.cpp | UTF-8 | 320 | 4.03125 | 4 | [] | no_license | /*
* Write code using a library function to copy the string constant
* "Hello" into the string variable char aString[10]
*/
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char aString[10];
strncpy(aString, "Hello", 10);
cout << "aString = " << aString << endl;
return 0;
}
| true |
3d72fff534fe7b69a217d15a41d39f2829699a7f | C++ | Roller23/webpp | /webpp/server.hpp | UTF-8 | 1,653 | 2.65625 | 3 | [] | no_license | #if !defined(__WEBPP_SERVER_)
#define __WEBPP_SERVER_
#include <cstdint>
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
typedef std::unordered_map<std::string, std::string> HeadersMap;
typedef std::unordered_map<std::string, std::string> QueryMap;
class WebServer;
class Query {
private:
const QueryMap query;
public:
Query(const QueryMap &_query) : query(_query) {}
bool has(const std::string &key) const;
std::string get(const std::string &key) const;
};
class Request {
public:
Query query;
Request(const QueryMap &_query) : query(_query) {}
};
class Response {
friend class WebServer;
private:
std::string buffer = "";
HeadersMap headers;
public:
void append(const std::string &str);
void add_header(const std::string &key, const std::string &value);
void append_file(const std::string &path);
Response() {
headers["Content-Type"] = "text/html; charset=utf-8";
headers["Content-Length"] = "0";
}
};
typedef std::function<void(const Request &, Response &)> RouteCallback;
class WebServer {
private:
std::unordered_map<std::string, RouteCallback> routes;
std::vector<std::string> static_paths;
int socket_fd;
bool has_path(const std::string &path);
public:
void make_static(const std::string &path);
void on(const std::string &method, const std::string &route, const RouteCallback &callback);
void get(const std::string &route, const RouteCallback &callback);
void post(const std::string &route, const RouteCallback &callback);
void listen(const uint16_t port);
};
#endif // __WEBPP_SERVER_ | true |
57f7db4cb402ce86a6b416e07f86fb7603f43cdb | C++ | bennisverrir/GucciManeFanclub | /computer.h | UTF-8 | 762 | 3.0625 | 3 | [] | no_license | #ifndef COMPUTER_H
#define COMPUTER_H
#include <string>
using namespace std;
class Computer
{
public:
Computer();
Computer(string name, int buildYear, string computerType, bool wasBuilt);
Computer (int iD, string name, int buildYear, string computerType, bool wasBuilt);
friend bool operator == (Computer &lhs, Computer &rhs);
int getID();
void setID(int ID);
void setName(string);
void setBuildYear(int);
void setComputerType(string);
void setWasBuilt(bool);
string getName() const;
int getBuildYear() const;
string getComputerType() const;
bool getWasBuilt() const;
private:
string _name;
int _buildYear;
string _computerType;
bool _wasBuilt;
int _myID;
};
#endif // COMPUTER_H
| true |
c9002a2721023af2ba0838a39891195083af4fe8 | C++ | ltr01/stroustrup-ppp-1 | /chapter16/chapter16_ex03.cpp | UTF-8 | 442 | 2.78125 | 3 | [
"MIT"
] | permissive | // Chapter 16 exercise 03:
// Button with image on top, moves when clicked
#include "../lib_files/Simple_window.h"
#include "../lib_files/Graph.h"
int main()
try {
Point tl(100,100);
Imagebutton_window imbwin(tl,600,400,"Click image to move");
return gui_main();
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
keep_window_open();
}
catch (...) {
cerr << "exception\n";
keep_window_open();
}
| true |
1e3c655990c9bcdbb17e6d7cce8289b5db0961d9 | C++ | AD-sect/lab3 | /interface.h | UTF-8 | 6,284 | 3.796875 | 4 | [] | no_license | #pragma once
#include<iostream>
#include<complex>
#include<string>
#include "test.h"
void binaryTreeInterface()
{
BinaryTree<int> tree;
BinaryTree<int>* subTree{ nullptr };
int choice{ 0 };
int item{ 0 };
int* items{ 0 };
int size{ 0 };
BinaryTree<int>* tree2 = new BinaryTree<int>;
while (true)
{
std::cout << "Choose the action:" << std::endl;
std::cout <<
"1. Make tree" << std::endl <<
"2. Add element" << std::endl <<
"3. Remove element" << std::endl <<
"4. Find element" << std::endl <<
"5. Print tree" << std::endl <<
"6. Print maximum" << std::endl <<
"7. Print minimum" << std::endl <<
"8. Make subtree" << std::endl <<
"9. Print subtree" << std::endl <<
"10. Check subtree for entry" << std::endl <<
"11. Check test's rezults" << std::endl <<
"12. Exit" << std::endl;
std::cin >> choice;
switch (choice)
{
case 1:
std::cout << "Write the quantaty of elements:" << std::endl;
std::cin >> size;
if (size == 0)
std::cout << "The tree is not made" << std::endl;
else
{
std::cout << "Write the elements:" << std::endl;
items = new int[size];
for (int i(0); i < size; ++i)
{
std::cin >> items[i];
tree.insert(items[i]);
}
delete[] items;
std::cout << "The tree is made" << std::endl;
}
break;
case 2:
std::cout << "Write the element to add: ";
std::cin >> item;
tree.insert(item);
std::cout << "The element is added" << std::endl;
break;
case 3:
std::cout << "Write the element to remove: ";
std::cin >> item;
if(tree.search(item) == nullptr)
std::cout << "Element for removing is not exsist" << std::endl;
else
{
tree.remove(item);
std::cout << "The element is removed" << std::endl;
}
break;
case 4:
std::cout << "Write the element to find: ";
std::cin >> item;
if (tree.search(item) == nullptr)
std::cout << "Element doesn't exsist in the tree" << std::endl;
else
std::cout << "Element exist in the tree" << std::endl;
break;
case 5:
if (tree.getRoot() == nullptr)
std::cout << "Tree is empty";
else
{
std::cout << "Elements or the tree (symetrical order): ";
tree.print();
}
break;
case 6:
if (tree.getRoot() == nullptr)
std::cout << "The tree isn't exist" << std::endl;
else
{
std::cout << "Maximum is : ";
std::cout << tree.getMax(tree.getRoot()) << std::endl;
}
break;
case 7:
if (tree.getRoot() == nullptr)
std::cout << "The tree isn't exist" << std::endl;
else
{
std::cout << "Mininum is : ";
std::cout << tree.getMin(tree.getRoot()) << std::endl;
}
break;
case 8:
std::cout << "Write the element - root of subtree: ";
std::cin >> item;
subTree = tree.subTree(item);
std::cout << "The subtree is made" << std::endl;
break;
case 9:
if (subTree == nullptr)
std::cout << "Subtree isn't made" << std::endl;
else
subTree->print();
break;
case 10:
std::cout << "Write the quantaty of other tree's elements to check:" << std::endl;
std::cin >> size;
std::cout << "Write the elements of other tree to check:" << std::endl;
items = new int[size];
for (int i(0); i < size; ++i)
std::cin >> items[i];
tree2 = new BinaryTree<int>{ items, size };
delete[] items;
if (tree.getRoot() == nullptr)
std::cout << "The tree to check isn't exist";
else if (tree.subTreeCheck(tree2) == true)
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
break;
case 11:
testBinaryTree();
break;
case 12:
std::cout << "Goodbye!" << std::endl;
exit(1);
default:
std::cout << "WRONG CHOISE!" << std::endl;
}
std::cout << std::endl;
}
}
void binaryHeapInterface()
{
BinaryHeap<int> heap;
int choice{ 0 };
int* items{ 0 };
int size{ 0 };
int key{ 0 };
while (true)
{
std::cout << "Choose the action:" << std::endl;
std::cout <<
"1. Make heap" << std::endl <<
"2. Add element" << std::endl <<
"3. Remove element" << std::endl <<
"4. Find element" << std::endl <<
"5. Print heap" << std::endl <<
"6. Print maximum" << std::endl <<
"7. Print high" << std::endl <<
"8. Check test's rezults" << std::endl <<
"9. Exit" << std::endl;
std::cin >> choice;
switch (choice)
{
case 1:
std::cout << "Write the quantaty of elements:" << std::endl;
std::cin >> size;
std::cout << "Write the elements:" << std::endl;
items = new int[size];
for (int i(0); i < size; ++i)
{
std::cin >> items[i];
heap.insert(items[i]);
}
delete[] items;
std::cout << "The heap is made" << std::endl;
break;
case 2:
std::cout << "Write the element to add: ";
std::cin >> key;
heap.insert(key);
std::cout << "The element is added" << std::endl;
break;
case 3:
std::cout << "Write the element to remove: ";
std::cin >> key;
if (heap.search(key) == -1)
std::cout << "The heap is empty" << std::endl;
else
{
heap.remove(key);
std::cout << "The element is removed" << std::endl;
}
break;
case 4:
std::cout << "Write the element to find: ";
std::cin >> key;
if (heap.search(key) == -1)
std::cout << "Element doesn't exsist in the tree" << std::endl;
else
std::cout << "Element exist in the tree" << std::endl;
break;
case 5:
if (heap.getSize() == 0)
std::cout << "the heap is empty" << std::endl;
else
{
std::cout << "Elements of the heap: ";
heap.print();
}
break;
case 6:
if (heap.getSize() == 0)
std::cout << "Heap is empty" << std::endl;
else
std::cout << heap.getMax() << std::endl;
break;
case 7:
if (heap.getSize() == 0)
std::cout << "Heap is empty" << std::endl;
else
std::cout << heap.getHigh() << std::endl;
break;
case 8:
testBinaryHeap();
break;
case 9:
std::cout << "Goodbye!" << std::endl;
exit(1);
default:
std::cout << "WRONG CHOISE";
}
std::cout << std::endl;
}
}
| true |
d95205d0fc7dbfee1160b28fb5093c923c7e8b7a | C++ | gamavinicius/reativos | /event_driven.cpp | UTF-8 | 1,383 | 2.859375 | 3 | [] | no_license | #include "event_driven.h"
#include <Arduino.h>
EventDriven::EventDriven()
: m_pin_count(0)
{
}
EventDriven::~EventDriven()
{
}
void EventDriven::ButtonListenCb(void(*bt_cb)(int, int))
{
m_bt_cb = bt_cb;
}
bool EventDriven::ButtonListen(int pin)
{
m_pin_count++;
if (m_pin_count >= BUTTON_TOTAL)
return false;
int pos = m_pin_count - 1;
m_pin[pos] = pin;
pinMode(m_pin[pos], INPUT);
m_state[pos] = digitalRead(m_pin[pos]);
return true;
}
void EventDriven::TimerSetCb(void(*timer_cb)(int))
{
m_timer_cb = timer_cb;
}
bool EventDriven::TimerSet(int id, unsigned long ms, bool reset)
{
if (id >= TIMER_TOTAL)
return false;
if (reset) {
m_old_time[id] = millis();
m_new_time[id] = millis();
}
m_timer[id] = ms;
return true;
}
void EventDriven::Setup(void(*init_cb)())
{
for (int i=0; i<TIMER_TOTAL; i++) {
m_old_time[i] = millis();
m_new_time[i] = millis();
m_timer[i] = 0;
}
init_cb();
}
void EventDriven::Loop()
{
for (int i=0; i<m_pin_count; i++) {
int state = digitalRead(m_pin[i]);
if (m_state[i] != state) {
m_state[i] = state;
m_bt_cb(m_pin[i], m_state[i]);
}
}
for (int i=0; i<TIMER_TOTAL; i++) {
m_new_time[i] = millis();
if (m_timer[i] != 0 && m_new_time[i] - m_old_time[i] >= m_timer[i]) {
m_old_time[i] = m_new_time[i];
m_timer_cb(i);
}
}
} | true |
4ead5357d26cf16780855cf894fa0a2b025065cc | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/43/635.c | UTF-8 | 360 | 2.578125 | 3 | [] | no_license | void main()
{
int i,j,n,sqrti,m=0,a[10000];
scanf("%d",&n);
for(i=3;i<=n;i+=2)
{
sqrti=(int)sqrt(i);
for(j=3;j<=sqrti;j+=2)
{
if(i%j==0)
{
break;
}
}
if(j>sqrti)
{
a[m]=i;
m++;
}
}
for(i=0;i<=m;i++)
{
for(j=i;j<=m;j++)
if(n==a[i]+a[j])
{
printf("%d %d\n",a[i],a[j]);
}
}
}
| true |
df74bf11e277bd3e48cb1391b5328b6d60c46e75 | C++ | MachineryZ/Leetcode | /1525. Good Split.cpp | UTF-8 | 699 | 2.78125 | 3 | [] | no_license | class Solution {
public:
int numSplits(string s) {
vector<int> s_left(26, 0);
vector<int> s_right(26, 0);
int ret = 0;
for(int i = 0; i < s.size(); i++) {
s_right[s[i] - 'a']++;
}
for(int i = 0; i < s.size(); i++) {
s_left[s[i] - 'a']++;
s_right[s[i] - 'a']--;
int sum_left = 0;
int sum_right = 0;
for(int j = 0; j < 26; j++) {
if(s_left[j] > 0)
sum_left++;
if(s_right[j] > 0)
sum_right++;
}
if(sum_left == sum_right)
ret++;
}
return ret;
}
}; | true |
200709976337184d007cb104995404342cfbe5a6 | C++ | alexandraback/datacollection | /solutions_5686313294495744_0/C++/syboy/C.cpp | UTF-8 | 707 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
const int MN=1000;
string st[MN][2];
int mark[MN];
int main(){
int tt;
cin>>tt;
for(int ii=0;ii<tt;ii++){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>st[i][0]>>st[i][1];
}
int Max=0;
for(int mk=0;mk<(1<<n);mk++){
for(int i=0;i<n;i++){
mark[i]=(mk>>(i))%2;
}
int con=0;
for(int i=0;i<n;i++){
if(mark[i]==0){
int f=0,s=0;
for(int j=0;j<n;j++){
if(mark[j]==1){
if(st[i][0]==st[j][0]){
f=1;
}
if(st[i][1]==st[j][1]){
s=1;
}
}
}
if(s&&f){
con++;
}
}
}
Max=max(con,Max);
}
cout<<"Case #"<<ii+1<<": "<<Max<<endl;
}
return 0;
}
| true |
69e3bd8f10e7f03c01f679221481c07fd0329875 | C++ | serge-sans-paille/frozen | /tests/test_elsa_std.cpp | UTF-8 | 1,174 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #include <frozen/bits/defines.h>
#ifdef FROZEN_LETITGO_HAS_STRING_VIEW
#include <frozen/bits/elsa_std.h>
#include <frozen/map.h>
#include <frozen/set.h>
#include <frozen/unordered_map.h>
#include <frozen/unordered_set.h>
#include "catch.hpp"
#include <string_view>
#ifdef FROZEN_LETITGO_HAS_CONSTEXPR_STRING
#include <string>
using StringTypes = std::tuple<std::string_view, std::string>;
#else
using StringTypes = std::tuple<std::string_view>;
#endif
TEMPLATE_LIST_TEST_CASE("frozen containers work with standard string types", "[elsa_std]", StringTypes)
{
constexpr TestType str = "string";
const auto is_found_in = [&str](const auto& container){ return container.count(str) == 1; };
constexpr frozen::set<TestType, 1> set{str};
constexpr frozen::unordered_set<TestType, 1> unordered_set{str};
constexpr auto map = frozen::make_map<TestType, int>({{str, 0}});
constexpr auto unordered_map = frozen::make_unordered_map<TestType, int>({{str, 0}});
REQUIRE(is_found_in(set));
REQUIRE(is_found_in(unordered_set));
REQUIRE(is_found_in(map));
REQUIRE(is_found_in(unordered_map));
}
#endif // FROZEN_LETITGO_HAS_STRING_VIEW
| true |
27b0ce1503a86a0b3d3e9104952ba2530db90035 | C++ | d-zhelyazkov/CompetitiveProgramming | /HackerRank_C/XOR_Matrix/src/XOR_Matrix.cpp | UTF-8 | 1,643 | 2.921875 | 3 | [] | no_license | //============================================================================
// Name : XOR_Matrix.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <stdio.h>
#include <vector>
using namespace std;
#define MAX_COL 100000
unsigned int N;
unsigned long long M;
unsigned CURR[MAX_COL];
unsigned NEW[MAX_COL] = { 0 };
bool IXs[MAX_COL] = { 0 };
void init();
void process();
void print(unsigned* arr, unsigned int size);
int main() {
scanf("%u %llu", &N, &M);
init();
// printf("Row 0 |");
// print(CURR, N);
unsigned long long m = M;
for (unsigned long long i = 0; i < m; i++) {
M = i;
process();
printf("Row %2d | ", i);
print(NEW, N);
printf("\n");
}
return 0;
}
void process() {
unsigned long long lastRow = M - 1;
for (unsigned long long i = 0; i < M; i++) {
if ((i & lastRow) == i) {
IXs[i % N] ^= 1;
}
}
vector<unsigned> ixs;
for (unsigned i = 0; i < N; i++) {
if (IXs[i])
ixs.push_back(i);
NEW[i] = 0;
}
for (unsigned i = 0; i < N; i++) {
for (unsigned ix : ixs) {
NEW[i] ^= CURR[(i + ix) % N];
}
}
}
void init() {
for (unsigned i = 0; i < N; i++) {
CURR[i] = i;
//scanf("%u", CURR + i);
}
}
void print(unsigned* arr, unsigned int size) {
for (unsigned i = 0; i < size; i++) {
printf("%2u ", arr[i]);
}
//printf("\n");
}
| true |
1aa9d0fa21fc4136ed1449eef0e8a02bd7a79169 | C++ | xBorox1/Codeforces-Algorithms | /2sat.cpp | UTF-8 | 1,336 | 2.515625 | 3 | [] | no_license | #define make_pair mp
#define emplace_back pb
#include <bits/stdc++.h>
using namespace std;
mt19937 mt_rand(time(0));
const int N = 1e5 + 5;
int n, m;
vector<int> v[2*N];
int norm(int x) {
if(x < 0) return (-x - 1) * 2 + 1;
return 2 * (x - 1);
}
void add_edge(int x, int y) {
x = norm(x);
y = norm(y);
v[x].pb(y);
}
void add_alt(int x, int y) {
add_edge(-x, y);
add_edge(-y, x);
}
stack<int> S;
bool inv1[2*N], inv2[2*N];
int spoj[2*N], spojwsk;
void dfs1(int x) {
inv1[x] = 1;
for(auto y : v[x]) if(!inv1[y]) dfs1(y);
S.push(x);
}
void dfs2(int x) {
inv2[x] = 1;
spoj[x] = spojwsk;
for(auto y : v[x^1]) if(!inv2[y^1]) dfs2(y ^ 1);
}
bool sat() {
for(int i=0;i<2*n;i++) if(!inv1[i]) dfs1(i);
while(!S.empty()) {
int x = S.top();
S.pop();
if(!inv2[x]) {
spojwsk++;
dfs2(x);
}
}
for(int i=0;i<2*n;i++) if(spoj[i] == spoj[i^1]) return 0;
return 1;
}
vector<int> spojne[2*N];
bool ozn[2*N];
bool rozw[N];
void roz() {
for(int i=0;i<2*n;i++) spojne[spoj[i]].pb(i);
for(int i=2*n;i>=1;i--) for(auto x : spojne[i]) {
if(!ozn[x^1]) ozn[x] = 1;
}
for(int i=0;i<n;i++) if(ozn[2*i]) rozw[i] = 1;
}
int main() {
scanf("%d%d", &n, &m);
while(m--) {
int a, b;
scanf("%d%d", &a, &b);
add_alt(a, b);
}
printf("%d\n", (int)sat());
roz();
for(int i=0;i<n;i++) cout<<rozw[i]<<" ";
return 0;
}
| true |
b90ec2d52d23a256f1a052728e1236e9d92f43c8 | C++ | gaode80/record_dll | /record_dll/CLog.cpp | GB18030 | 6,838 | 2.671875 | 3 | [] | no_license | #include "CLog.h"
#include <direct.h>
#include <windows.h>
//CLog::CLog(int islog,const char* basepath,const char* filename,int maxsize)
CLog::CLog(int islog, QString basepath, QString filename, int maxsize)
{
m_islog = islog;
m_basepath = basepath;
m_logname = filename;
m_maxsize = maxsize;
m_fHandle = nullptr;
QString slogpath = MakeDir(basepath);
if ("" != slogpath) //·ɹ
{
QString sfullname = slogpath + "\\" + filename;
QByteArray qba = sfullname.toLatin1();
char *chfullname = qba.data();
struct _stat filestat = { 0 };
if (0 == _stat(chfullname, &filestat)) //ļڣ
{
//ļ
struct tm ptm;
char timestamp[32];
memset(timestamp, 0, sizeof(timestamp));
time_t now = time(0);
//ptm = localtime(&now);
localtime_s(&ptm, &now);
ptm.tm_year += 1900;
ptm.tm_mon += 1;
//sprintf(timestamp, "_%04d-%02d-%02d-%02d-%02d-%02d.log", ptm->tm_year, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
sprintf_s(timestamp, "_%04d-%02d-%02d-%02d-%02d-%02d.log", ptm.tm_year, ptm.tm_mon, ptm.tm_mday, ptm.tm_hour, ptm.tm_min, ptm.tm_sec);
QString bakName = sfullname + timestamp;
QByteArray qba2 = bakName.toLatin1();
rename(chfullname,qba2.data());
}
//m_fHandle = fopen(chfullname, "w");
fopen_s(&m_fHandle, chfullname, "w");
m_fullpath = slogpath;
}
}
CLog::~CLog()
{
if (m_fHandle)
{
fclose(m_fHandle);
}
}
//д־ļĴ
void CLog::Trace(const char* format, ...)
{
if (!m_islog)
return;
if (!m_fHandle)
return;
va_list mark;
va_start(mark, format);
SYSTEMTIME lpsystime;
GetLocalTime(&lpsystime);
char chtime[32];
memset(chtime, 0, sizeof(chtime));
sprintf_s(chtime, "%04d-%02d-%02d %02d:%02d:%02d:%03d", lpsystime.wYear, lpsystime.wMonth, lpsystime.wDay,\
lpsystime.wHour,lpsystime.wMinute,lpsystime.wSecond,lpsystime.wMilliseconds);
fprintf(m_fHandle, "[%s] ",chtime);
vfprintf(m_fHandle,format,mark);
fprintf(m_fHandle, "\n");
va_end(mark);
fflush(m_fHandle);
//д־Ѿǵڶˣ־·
if (!IsTodayPath())
ChangeLogPath();
//־ļֵļ
struct stat buf;
//int fdsb = fileno(m_fHandle);
int fdsb = _fileno(m_fHandle);
fstat(fdsb,&buf);
if (buf.st_size >= m_maxsize)
BackupLog();
}
//Ƿӡ־ʶ
void CLog::set_logflag(bool bflag)
{
if (bflag)
m_islog = 1;
else
m_islog = 0;
}
//begin private functions
//־·͵ǰ־·
QString CLog::MakeDir(QString sbasepath)
{
struct tm ptm;
time_t now = time(0);
//ptm = localtime(&now);
localtime_s(&ptm,&now);
int iyear = ptm.tm_year+1900;
int imonth = ptm.tm_mon + 1;
int iday = ptm.tm_mday;
struct _stat filestat = { 0 };
char* chpath = nullptr;
QByteArray qba = sbasepath.toLatin1();
chpath = qba.data();
QString spath = "";
if (_stat(chpath,&filestat) != 0) //·
{
if (-1 == _mkdir(chpath))
return "";
sbasepath = sbasepath + "\\" + QString::number(iyear);
qba = sbasepath.toLatin1();
chpath = qba.data();
if (-1 == _mkdir(chpath))
return "";
sbasepath = sbasepath + "\\" + QString::number(imonth);
qba = sbasepath.toLatin1();
chpath = qba.data();
if (-1 == _mkdir(chpath))
return "";
sbasepath = sbasepath + "\\" + QString::number(iday);
qba = sbasepath.toLatin1();
chpath = qba.data();
if (-1 == _mkdir(chpath))
return "";
spath = sbasepath;
}//if (_stat(chpath,&filestat) != 0)
else //·
{
spath = sbasepath + "\\" + QString::number(iyear);
chpath = nullptr;
qba = spath.toLatin1();
chpath = qba.data();
if (_stat(chpath, &filestat) != 0) //·
{
if (-1 == _mkdir(chpath))
return "";
spath = spath + "\\" + QString::number(imonth);
qba = spath.toLatin1();
chpath = qba.data();
if (-1 == _mkdir(chpath))
return "";
spath = spath + "\\" + QString::number(iday);
qba = spath.toLatin1();
chpath = qba.data();
if (-1 == _mkdir(chpath))
return "";
}
else //·
{
spath = spath + "\\" + QString::number(imonth);
qba = spath.toLatin1();
chpath = qba.data();
if (_stat(chpath, &filestat) != 0) //·ļв
{
if (-1 == _mkdir(chpath))
return "";
spath = spath + "\\" + QString::number(iday);
qba = spath.toLatin1();
chpath = qba.data();
if (-1 == _mkdir(chpath))
return "";
}//if (_stat(chpath, &filestat) != 0)
else //·ļд
{
spath = spath + "\\" + QString::number(iday);
qba = spath.toLatin1();
chpath = qba.data();
if (_stat(chpath, &filestat) != 0) //ļв
{
if (-1 == _mkdir(chpath))
return "";
}
}//end else //·ļд
}//end else //·
}//end else //·
return spath;
}//end function MakeDir
//жϵǰд־·Ƿǵ
bool CLog::IsTodayPath()
{
struct tm ptm;
char timestamp[32];
memset(timestamp, 0, sizeof(timestamp));
time_t now = time(0);
//ptm = localtime(&now);
localtime_s(&ptm,&now);
ptm.tm_year += 1900;
ptm.tm_mon += 1;
sprintf_s(timestamp, "%04d\\%d\\%d", ptm.tm_year, ptm.tm_mon, ptm.tm_mday);
if (m_fullpath.contains(timestamp))
return true;
else
return false;
}//end function IsTodayPath
//ıд־·
void CLog::ChangeLogPath()
{
if (m_fHandle != nullptr)
{
fclose(m_fHandle);
m_fHandle = nullptr;
}
m_fullpath = MakeDir(m_basepath);
QString snew_logfile = m_fullpath + "\\" + m_logname;
QByteArray qba = snew_logfile.toLatin1();
//m_fHandle = fopen(qba.data(), "w");
fopen_s(&m_fHandle, qba.data(), "w");
}
//־ļСõֵ־ļ
void CLog::BackupLog()
{
if (m_fHandle != nullptr)
{
fclose(m_fHandle);
m_fHandle = nullptr;
}
struct tm ptm;
char timestamp[32];
memset(timestamp, 0, sizeof(timestamp));
time_t now = time(0);
//ptm = localtime(&now);
localtime_s(&ptm,&now);
ptm.tm_year += 1900;
ptm.tm_mon += 1;
sprintf_s(timestamp, "_%04d-%02d-%02d-%02d-%02d-%02d.log", ptm.tm_year, ptm.tm_mon, ptm.tm_mday, ptm.tm_hour, ptm.tm_min, ptm.tm_sec);
QString bakName = m_fullpath +"\\"+ m_logname + timestamp;
QByteArray qba = bakName.toLatin1();
QString sold_fullname = m_fullpath + "\\" + m_logname;
QByteArray qba2 = sold_fullname.toLatin1();
rename(qba2.data(), qba.data());
//m_fHandle = fopen(qba2.data(),"w");
fopen_s(&m_fHandle, qba2.data(), "w");
}
//end private functions
| true |
157be32fd79261d4d37bf09f6415e0765f3bb377 | C++ | RedstoneCMX/LeetCode | /#258-Add Digits.cpp | UTF-8 | 1,307 | 3.90625 | 4 | [] | no_license | #include<iostream>
using namespace std;
/*简单题,如果仅仅就按照题目的意思的思路去写,这个题其实确实非常简单,没有什么难点。而题目建议能否不使用循环和递归,
在O(1)的时间复杂度内完成。其实就是一个找规律的题。
输入:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
结果:1, 2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2
根据上面的尝试,我们可以发现,这里是有规律的。
即结果满足,(num-1)%9+1
*/
/*************************在leetcode上直接提交以下代码即可******************************/
/*class Solution
{
public:
int addDigits(int num)
{
int add = num;
while(num / 10)
{
int temp_num = num;
add = 0;
while(temp_num)
{
add = add + temp_num % 10;
temp_num = temp_num / 10;
}
num =add;
}
return add;
}
};*/
class Solution
{
public:
int addDigits(int num)
{
int add = (num - 1) % 9 + 1;
return add;
}
};
/*************************在leetcode上直接提交以上代码即可******************************/
int main()
{
int num;
cin >> num;
Solution solu;
int add_digit = solu.addDigits(num);
cout << add_digit << endl;
return 0;
} | true |
29d24cbf4aa1873055d671587c01593427d43cf7 | C++ | SyreenBn/Program-Design-and-Development-Senior-Project | /project/iteration3/src/event_type_emit.h | UTF-8 | 2,115 | 2.828125 | 3 | [] | no_license | /**
* @file event_type_emit.h
*
* @copyright 2017 3081 Staff, All rights reserved.
*/
#ifndef SRC_EVENT_TYPE_EMIT_H_
#define SRC_EVENT_TYPE_EMIT_H_
/*******************************************************************************
* Includes
******************************************************************************/
#include <stdlib.h>
#include "src/event_base_class.h"
#include "src/entity_type.h"
/*******************************************************************************
* Namespaces
******************************************************************************/
/** Namespaces Begin */
NAMESPACE_BEGIN(csci3081);
/*******************************************************************************
* Class Definitions
******************************************************************************/
/**
* @brief The event type emit is a class to check the event the entity and
* provide information regarding the entities involved and the location of the
* event.
*/
class EventEntityTypeEmit : public EventBaseClass {
public:
EventEntityTypeEmit();
EventEntityTypeEmit(int id, Position p, enum entity_type ent_type) {
id_ = id;
p_ = p;
ent_type_ = ent_type;
}
/*
* @brief EmitMessage to print the point of contact and the angle of contact
*/
void EmitMessage(void);
/*
* @brief return ture if the event is emited and false if not
*/
bool Emitted(void) { return emitted_; }
void Emitted(bool e) { emitted_ = e; }
/*
* @brief this fuction is to the position of contact of the event
*/
Position point_of_contact() { return point_of_contact_; }
void point_of_contact(Position p) { point_of_contact_ = p; }
/*
* @brief this fuction is to the angle of contact of the event
*/
double angle_of_contact() { return angle_of_contact_; }
void angle_of_contact(double aoc) { angle_of_contact_ = aoc; }
private:
bool emitted_;
Position point_of_contact_;
double angle_of_contact_;
int id_;
Position p_;
enum entity_type ent_type_;
};
/*! Namespaces End */
NAMESPACE_END(csci3081);
#endif // SRC_EVENT_TYPE_EMIT_H_
| true |
8f9894e48f19bfab14a751508cad98a82d19e36e | C++ | UsuallyGO/Qstl | /include/qstl/qalgo.h | UTF-8 | 3,707 | 3.109375 | 3 | [] | no_license |
#ifndef _QSTL_ALGO_
#define _QSTL_ALGO_
template<class T>
inline const T& __median(const T& a, const T& b, const T& c)
{
if(a < b)
if(b < c)
return b;
else if(a < c)
return c;
else
return a;
else//b < a
if(a < c)
return a;
else if(c < b)
return b;
else
return c;
}
template<class T, class Compare>
inline const T& __median(const T& a, const T& b, const T& c, Compare comp)
{
if(comp(a, b))//a>b
if(comp(b, c))//a>b>c
return b;
else if(comp(c, a))//c>a>b
return a;
else
return c;
else//b>a
if(comp(c, b))//c>b>a
return b;
else if(comp(a, c))//b>a>c
return a;
else
return c;
}
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
while(first != last) f(*first++);
return f;
}
template<class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last, const T& value)
{
while(first != last && *first != value) ++first;
return first;
}
template<class InputIterator, class Predicate>
InputIterator find_if(InputIterator first, InputIterator last, Predicate pred)
{
while(first != last && !pred(*first)) ++first;
return first;
}
template<class ForwardIterator>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last)
{
if(first == last) return last;
ForwardIterator next = first;
while(++next != last){
if(*first == *next) return first;
first = next;
}
return last;
}
template<class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last,
BinaryPredicate binary_pred)
{
if(first == last) return last;
ForwardIterator next = first;
while(++next != last){
if(binary_pred(*first, *next)) return first;
first = next;
}
return last;
}
template<class InputIterator, class T, class Size>
void count(InputIterator first, InputIterator last, const T& value, Size& n)
{
while(first != last)
if(*first++ == value) ++n;
}
template<class InputIterator, class Predicate, class Size>
void count_if(InputIterator first, InputIterator last, Predicate pred, Size& n)
{
while(first != last)
if(pred(*first++)) ++n;
}
template<class ForwardIterator1, class ForwardIterator2, class Distance1,
class Distance2>
ForwardIterator __search(ForwardIterator first1, ForwardIterator last1,
ForwardIterator2 first2, ForwardIterator last2,
Distance1*, Distance2*)
{
Distance1 d1 = 0;
distance(first1, last1, d1);
Distance2 d2 = 0;
distance(first2, last2, d2);
if(d1 < d2) return last1;//must can't find 'second' in 'first'
ForwardIterator1 current1 = first1;
ForwardIterator2 current2 = first2;
while(current2 != last2)
if(*current1++ != *current2++)
if(d1-- == d2)//just skip the first + d1 elements in first
return last1;
else{
current1 = ++first1;
current2 = first2;
}
return (current2 == last2) ? first1 : last1;
}
template<class ForwardIterator1, class ForwardIterator2>
inline ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator last1,
ForwardIterator2 first2, ForwardIterator last2)
{
return __search(first1, last1, first2, last2, distance_type(first1),
distance_type(first2));
}
#endif //!_QSTL_ALGO_
| true |
41682d932a1e0e2d16c70145dad190d76141648c | C++ | avc9/ladder-2A | /a2oj_14.cpp | UTF-8 | 770 | 3 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
string s1;
cin>>s1;
string :: iterator itr_start=s1.begin();
string :: iterator itr_end=s1.end();
//cout<<*itr_start<<" "<<*itr_end<<endl;
while((*itr_start=='W')&&(*(itr_start+1)=='U')&&(*(itr_start+2)=='B')){
itr_start=itr_start+3;
}
//cout<<*itr_start<<" "<<*itr_end<<endl;
while((*(itr_end-1)=='B')&&(*(itr_end-2)=='U')&&(*(itr_end-3)=='W')){
itr_end=itr_end-3;
}
//cout<<*itr_start<<" "<<*(itr_end-1)<<endl;
for(auto itr=itr_start;itr!=itr_end;itr++){
if((*itr=='W')&& (*(itr+1)=='U') && (*(itr+2)=='B')){
itr+=2;
cout<<" ";
continue;
}
cout<<*itr;
}
}
| true |
21e7384cc1e7c666fd5faa11f71a9fb0077d2a58 | C++ | shiro-saber/Estructura_Datos | /Examen_Parcial1/EP1_E2_Coches/src/concesionaria.cpp | UTF-8 | 812 | 2.796875 | 3 | [] | no_license | #include "concesionaria.h"
concesionaria::concesionaria(const string& name, int maxClientes, int maximoAutos) : name(name), maxClientes(maxClientes), maximoAutos(maximoAutos)
{
siguienteCliente = 0;
siguienteVenta = 0;
if(maxClientes <= 0)
throw "Numero de cuentas debe ser positivo";
else
accounts = new Cliente*[maxClientes];
}
concesionaria::~concesionaria()
{
//dtor
}
concesionaria& concesionaria::creaCliente(int numeroCliente)
{
}
concesionaria& concesionaria::ventaCoche(int numeroCliente)
{
}
ostream& concesionaria::printCuentas(ostream& os)const
{
}
ostream& concesionaria::printCuentasCompras(ostream & os)const
{
}
ostream& operator << (ostream& os, const concesionaria& c)
{
}
Cliente& concesionaria::encuentraCliente(int cuentaCliente) const
{
}
| true |
e087183e40b471a57b59df1330a1dd79881cd39e | C++ | chetanpant11/InterviewBit-Solution | /Edit_Distance.cpp | UTF-8 | 972 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int ED(string s1, string s2)
{
vector<vector<int>>dp(s1.size()+1, vector<int>(s2.size()+1,0));
for(int i=0;i<=s1.size();i++)
{
for(int j=0;j<=s2.size();j++)
{
//cout<<"he"<<endl;
if(i==0&&j==0)
{dp[i][j]=0;
continue;}
else if(i==0)
dp[i][j]=1+dp[i][j-1];
else if(j==0)
dp[i][j]=1+dp[i-1][j];
else
if(s1[i-1]==s2[j-1])
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=min(min(1+dp[i-1][j], 1+dp[i-1][j-1]),1+dp[i][j-1]);
}
}
for(int i=0;i<=s1.size();i++)
{
for(int j=0;j<=s2.size();j++)
{
cout<<dp[i][j]<<" ";}
cout<<endl;
return dp[s1.size()][s2.size()];
}}
int main()
{
string s1, s2;
s1="ba";
s2="aa";
int ans=ED(s1, s2);
cout<<ans;
}
| true |
74e8042a2e69d37f22df65a5528c0b2aa8ea4ddd | C++ | XuPeng-SH/cxx_lab | /db_lab/user_schema.h | UTF-8 | 975 | 3 | 3 | [] | no_license | #pragma once
#include <string>
#include <sstream>
#include <memory.h>
struct UserSchema {
constexpr static const uint16_t NameSize = 32;
constexpr static const uint16_t EMailSize = 255;
uint32_t id;
char username[NameSize];
char email[EMailSize];
void
SetUserName(const char* un) {
memset(username, 0, NameSize);
if (!un) return;
strncpy(username, un, sizeof(username));
}
void
SetEmail(const char* e) {
memset(email, 0, EMailSize);
if (!e) return;
strncpy(email, e, sizeof(email));
}
void
SerializeTo(void* destination) const {
memcpy(destination, this, sizeof(UserSchema));
}
void
DeserializeFrom(void* source) {
memcpy((void*)this, source, sizeof(UserSchema));
}
std::string
ToString() const {
std::stringstream ss;
ss << "(" << id << ", " << username << ", " << email << ")";
return ss.str();
}
};
| true |
246b518177bed9305a2b54451adc7972bf4d8e54 | C++ | SunHongYang7/cccccccccccc | /charge.cpp | GB18030 | 396 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
int charge(int time1, int tour)
{
int money=13;
if(tour>3){
if(time1>=23||time1<5)
money+=(tour-3)*2;
else
money+=(tour-3);
}
return money;
}
int main()
{
int time1=9;
int time2=18;
int tour=12;
int money=charge(time1,tour)+charge(time2,tour);
printf("һΪ%d",charge);
return 0;
}
| true |
59b147198630418f705ca62487078b702ea71d7d | C++ | sereslorant/logan_engine | /LoganEngine/src/lCore/lRenderer/lrRenderer/lGLRenderer/lGL3Renderer/lGL3DShaders/lrGLPointLightShader.h | UTF-8 | 2,208 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef LR_GL_POINT_LIGHT_SHADER
#define LR_GL_POINT_LIGHT_SHADER
#include <lRenderer/lrRenderer/lGLRenderer/liGLShaderInterfaces.h>
#include <lRenderer/lrRenderer/lGLRenderer/lGLShaders/lrGLShader.h>
#include <string>
class lrGLPointLightShader : public liGLPointLightShader
{
protected:
lrGLShader &Shader;
public:
virtual GLint GetLightCountLocation() override
{
return Shader.GetUniformLocation("NumLights");
}
virtual GLint GetLightPositionLocation() override
{
return Shader.GetUniformLocation("LightPosition[0]");
}
virtual GLint GetLightColorLocation() override
{
return Shader.GetUniformLocation("LightColor[0]");
}
virtual GLint GetLightIntensityLocation() override
{
return Shader.GetUniformLocation("LightIntensity[0]");
}
/*
virtual GLint GetLightPositionLocation(unsigned int id) override
{
std::string VariableName = "LightPosition[" + std::to_string(id) + "]";
return Shader.GetUniformLocation(VariableName.c_str());
}
virtual GLint GetLightColorLocation(unsigned int id) override
{
std::string VariableName = "LightColor[" + std::to_string(id) + "]";
return Shader.GetUniformLocation(VariableName.c_str());
}
virtual GLint GetLightIntensityLocation(unsigned int id) override
{
std::string VariableName = "LightIntensity[" + std::to_string(id) + "]";
return Shader.GetUniformLocation(VariableName.c_str());
}
*//*
virtual GLint GetLightPositionLocation(unsigned int id) override
{
std::string VariableName = "Lights[" + std::to_string(id) + "].LightPosition";
return Shader.GetUniformLocation(VariableName.c_str());
}
virtual GLint GetLightColorLocation(unsigned int id) override
{
std::string VariableName = "Lights[" + std::to_string(id) + "].LightColor";
return Shader.GetUniformLocation(VariableName.c_str());
}
virtual GLint GetLightIntensityLocation(unsigned int id) override
{
std::string VariableName = "Lights[" + std::to_string(id) + "].LightIntensity";
return Shader.GetUniformLocation(VariableName.c_str());
}
*/
lrGLPointLightShader(lrGLShader &shader)
:Shader(shader)
{}
virtual ~lrGLPointLightShader() override
{}
/*
* End of class
*/
};
#endif // LR_GL_POINT_LIGHT_SHADER
| true |
b791905c6e24f86df41f8010756206f429b9a3f3 | C++ | aswiezowski/GraphAlgorithms | /src/Results.cpp | UTF-8 | 277 | 2.53125 | 3 | [] | no_license | #include "Results.h"
Results::Results(int *distance, int *previous)
{
this->distance = distance;
this->previous = previous;
}
int* Results::getDistances(){
return this->distance;
}
int* Results::getPreviouses(){
return this->previous;
}
Results::~Results()
{
//dtor
}
| true |
38bac2e371ee9bcae043da3c7a34261a1b7ca24c | C++ | RedBoxer/tp-lab-6 | /test/tests.cpp | UTF-8 | 901 | 2.875 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "WFactory.h"
//basic function test
TEST(test1,task1)
{
WFactory fact;
Driver* dean = fact.createDriver("Test", 123);
EXPECT_EQ("Test", dean->getName());
}
//personal calc() test
TEST(test1,task2)
{
WFactory fact;
Driver* dean = fact.createDriver("Test", 123);
dean->setWorktime(20);
dean->calc();
EXPECT_EQ(2460, dean->Employee::getSal());
}
//engineer calc() test
TEST(test1,task3)
{
WFactory fact;
Programmer* dean = fact.createProg("Test", 123);
dean->setWorktime(20);
dean->calc(10, 2000);
EXPECT_EQ(2660, dean->Employee::getSal());
}
//heading calc() test
TEST(test1,task4)
{
WFactory fact;
TeamLeader* dean = fact.createTL("Test", 123);
dean->setWorktime(20);
dean->setEmpCount(20);
dean->calc(10, 2000);
EXPECT_EQ(3460, dean->Employee::getSal());
}
| true |
c5078053420d8c48731f330065c4037e013d0ac7 | C++ | PlamenaTodorova/Bank | /PrivilegeAccount.h | UTF-8 | 612 | 2.828125 | 3 | [] | no_license | #ifndef PRIVILEGE_ACCOUNT_H
#define PRIVILEGE_ACCOUNT_H
#include "Account.h"
class PrivilegeAccount :
public Account
{
public:
PrivilegeAccount(const String& iban, int ownerId, double amount);
PrivilegeAccount(const String& iban, int ownerId, double amount, double overdrafr);
double GetOverdraft() const { return overdraft; }
//Overriding the inherited functions
virtual void Deposit(double amount);
virtual bool Withdraw(double amount);
virtual void Display() const;
private:
double overdraft;
void SetOverdragt(double overdraft);
};
#endif // !PRIVILEGE_ACCOUNT_H
| true |
f74f5e321d8ff300e7d32e7c7b6a65e39792dc39 | C++ | YuzukiTsuru/SingSyn | /lib/libSinsy/converter/PhonemeInfo.h | UTF-8 | 1,255 | 2.875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef SINSY_PHONEME_INFO_H_
#define SINSY_PHONEME_INFO_H_
#include <string>
#include "util_converter.h"
namespace sinsy {
class PhonemeInfo {
public:
static const std::string TYPE_SILENT;
static const std::string TYPE_PAUSE;
static const std::string TYPE_VOWEL;
static const std::string TYPE_CONSONANT;
static const std::string TYPE_BREAK;
//! constructor
PhonemeInfo();
//! constructor
PhonemeInfo(const std::string &type, const std::string &phoneme, ScoreFlag flag = 0);
//! copy constructor
PhonemeInfo(const PhonemeInfo &obj);
//! destructor
virtual ~PhonemeInfo();
//! assignment operator
PhonemeInfo &operator=(const PhonemeInfo &);
//! get type
const std::string &getType() const;
//! get phoneme
const std::string &getPhoneme() const;
//! set phoneme
void setPhoneme(const std::string &p);
ScoreFlag getScoreFlag() const;
private:
//! type (TYPE_SILENT, TYPE_PAUSE, ..., or TYPE_BREAK)
std::string type;
//! phoneme
std::string phoneme;
ScoreFlag scoreFlag;
};
};
#endif // SINSY_PHONEME_INFO_H_
| true |
bc6d7b5e8d4bd10ab7d7d3b6b420aeb1cb26487e | C++ | ids1024/gphoto2-webcam | /src/GphotoCameraWidget.h | UTF-8 | 2,919 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef GPHOTO_CAMERA_WIDGET_H
#define GPHOTO_CAMERA_WIDGET_H
#include <gphoto2/gphoto2.h>
#include <iterator>
#include "GphotoError.h"
#include "GphotoRefCount.h"
#include "GphotoBaseIterator.h"
class GphotoCamera;
class GphotoCameraWidget {
public:
GphotoCameraWidget(CameraWidgetType type, const char *label);
template <class T> GphotoCameraWidget(CameraWidgetType type, const char *label, T value) : GphotoCameraWidget(type, label) {
set_value(value);
}
const char *get_name();
const char *get_label();
bool get_readonly();
CameraWidgetType get_type();
template <class T> T get_value() {
T value;
int ret = gp_widget_get_value(widget.get(), &value);
if (ret != GP_OK) {
throw GphotoError("gp_widget_get_value", ret);
}
return value;
}
template <class T> void set_value(T value) {
int ret = gp_widget_set_value(widget.get(), value);
if (ret != GP_OK) {
throw GphotoError("gp_widget_set_value", ret);
}
}
void get_range(float *min, float *max, float *increment);
void write_to_camera(GphotoCamera &camera);
void read_from_camera(GphotoCamera &camera);
class choice_iterator : public GphotoBaseIterator<CameraWidget, const char*> {
public:
using GphotoBaseIterator::GphotoBaseIterator;
inline const char *operator*() {
const char *choice;
int ret = gp_widget_get_choice(obj, n, &choice);
if (ret != GP_OK) {
throw GphotoError("gp_widget_get_choice", ret);
}
return choice;
}
};
class child_iterator : public GphotoBaseIterator<CameraWidget, GphotoCameraWidget> {
public:
using GphotoBaseIterator::GphotoBaseIterator;
inline GphotoCameraWidget operator*() {
CameraWidget *child;
int ret = gp_widget_get_child(obj, n, &child);
if (ret != GP_OK) {
throw GphotoError("gp_widget_get_child", ret);
}
gp_widget_ref(child);
return GphotoCameraWidget(child);
}
};
class children : public GphotoBaseIterable<CameraWidget, child_iterator> {
using GphotoBaseIterable::GphotoBaseIterable;
inline int count() {
return gp_widget_count_children(obj);
}
friend class GphotoCameraWidget;
};
class choices : public GphotoBaseIterable<CameraWidget, choice_iterator> {
using GphotoBaseIterable::GphotoBaseIterable;
inline int count() {
return gp_widget_count_choices(obj);
}
friend class GphotoCameraWidget;
};
children get_children();
choices get_choices();
private:
GphotoCameraWidget(CameraWidget *widget);
GphotoRefCount<CameraWidget, gp_widget_ref, gp_widget_unref> widget;
friend class GphotoCamera;
};
#endif
| true |
3dcb9fdc663dbe4ec5956a5859728a0f980f208b | C++ | baixiaoxi/newStyleCpp | /newStyleCpp/CerrnoTest.cpp | UTF-8 | 986 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "CerrnoTest.h"
#include <cerrno>
namespace CerrnoTest
{
using namespace std;
bool CerrnoTest::test()
{
// Error codes
int errorCode;
errorCode = EPERM;
errorCode = ENOENT;
errorCode = ESRCH;
errorCode = EINTR;
errorCode = EIO;
errorCode = ENXIO;
errorCode = E2BIG;
errorCode = ENOEXEC;
errorCode = EBADF;
errorCode = ECHILD;
errorCode = EAGAIN;
errorCode = ENOMEM;
errorCode = EACCES;
errorCode = EFAULT;
errorCode = EBUSY;
errorCode = EEXIST;
errorCode = EXDEV;
errorCode = ENODEV;
errorCode = ENOTDIR;
errorCode = EISDIR;
errorCode = ENFILE;
errorCode = EMFILE;
errorCode = ENOTTY;
errorCode = EFBIG;
errorCode = ENOSPC;
errorCode = ESPIPE;
errorCode = EROFS;
errorCode = EMLINK;
errorCode = EPIPE;
errorCode = EDOM;
errorCode = EDEADLK;
errorCode = ENAMETOOLONG;
errorCode = ENOLCK;
errorCode = ENOSYS;
errorCode = ENOTEMPTY;
return true;
}
} | true |
8b9d5e63a9607866a1e0b8065f817198ffe3a5e3 | C++ | erjiaqing/my_solutions | /cf/610/c.cpp | UTF-8 | 1,715 | 2.640625 | 3 | [] | no_license | // Happy new year!
//
// Why "good bye 2015" at Dec. 30 ?
// I have classes at 8 am the next day!
// Sad story!
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
using namespace std;
#define LS( _x ) ( ( _x ) << 1 )
#define RS( _x ) ( ( _x ) << 1 | 1 )
#define LOWBIT( _x ) ( ( _x ) & ( - ( _x ) ) )
#define pb push_back
#define x first
#define y second
#define mp make_pair
namespace sol {
// BEBIN OF NORMAL PROGRAM
int ans[1024][1024];
void check(int lim)
{
for (int i = 0; i < lim; i++)
{
for (int j = 0; j < i; j++)
{
int an = 0;
for (int k = 0; k < lim; k++)
{
an += ans[i][k] * ans[j][k];
}
if (an != 0)
cerr << "X\n";
}
}
}
int main() // The true main()
{
ios::sync_with_stdio(0);
ans[0][0] = 1;
int cur = 1;
for (int i = 1; i <= 9; i++)
{
int ncur = cur * 2;
for (int j = 0; j < cur; j++)
for (int k = cur; k < ncur; k++)
ans[j][k] = -ans[j][ncur - k - 1];
for (int j = cur; j < ncur; j++)
{
for (int k = 0; k < cur; k++)
ans[j][k] = ans[j - cur][k];
for (int k = cur; k < ncur; k++)
ans[j][k] = ans[j][ncur - k - 1];
}
cur = ncur;
}
int n;
cin >> n;
int lim = (1 << n);
for (int i = 0; i < lim; i++)
{
for (int j = 0; j < lim; j++)
cout << ((ans[i][j] == -1) ? '*' : '+');
cout << "\n";
}
check(lim);
return 0;
}
// END OF NORMAL PROGRAM
}
int main() // The fake main()
{
return sol::main();
}
| true |
4f1bc30a1f7ed71a68f2bf2486830521aa14623e | C++ | jomarderrie/pizzatime-CPP | /Ingredient.cpp | UTF-8 | 370 | 2.734375 | 3 | [] | no_license | //
// Created by kimjongun on 24-3-2021.
//
#include "Ingredient.h"
Ingredient::Ingredient(float price, const std::string &name) : price(price), name(name) {}
float Ingredient::getPrice() const {
return price;
}
const std::string &Ingredient::getName() const {
return name;
}
const std::string &Ingredient::getPizzaName() const {
return pizzaName;
}
| true |
a4def83f03da0737d870600f7e3a894951e852c0 | C++ | spirosikmd/inmsv-08 | /SciVis2012/source/Application.h | UTF-8 | 3,011 | 2.5625 | 3 | [] | no_license | #ifndef APPLICATION_H_INCLUDED
#define APPLICATION_H_INCLUDED
#include <GLUI/glui.h>
#include "Simulation.h"
#include "Visualization.h"
#include "Colormap.h"
#include <map>
class Application {
private:
// GLUI control IDs
enum UiControlID {
QUIT_BUTTON,
COLORMAP_LIST,
NUMBER_OF_COLORS_LIST,
HUE_SPINNER,
SATURATION_SPINNER,
TUBE_SPINNER,
SCALAR_DATASET_LIST,
SCALAR_MODE_LIST,
SCALAR_MAX_SPINNER,
SCALAR_MIN_SPINNER,
VECTOR_DATASET_LIST,
GLYPH_TYPE_LIST,
DENSITY_ISOLINE_SPINNER,
DENSITY_RHO1_ISOLINE_SPINNER,
DENSITY_RHO2_ISOLINE_SPINNER,
NUMBER_ISOLINES_SPINNER,
HEIGHTPLOT_DATASET_LIST,
DIM_SPINNER,
SEGMENT_SPINNER,
SAMPLE_X_SPINNER,
SAMPLE_Y_SPINNER,
SEED_X,
SEED_Y,
SEED_Z,
ADD_SEEDPOINT_BUTTON
};
public:
Application();
~Application();
static void initialize(int *argc, char** argv);
static void initUI();
static void outputUsage();
static void display();
static void update();
static void reshape(int w, int h); // Handle window resizing (reshaping) events
static void keyboard(unsigned char key, int x, int y); // Handle key presses
static void special(int key, int x, int y); // Handle key presses
static void drag(int mx, int my); // Handle mouse drag
static void visualize();
static void quit();
static void buttonHandler(int id);
static void updateMenu();
static void displayMenu();
static void click(int,int,int,int);
static DataBuffer timeslices;
private:
static Simulation simulation; // the smoke simulation
static Visualization visualization; // visualization of the simulation
static int winWidth, winHeight; //size of the graphics window, in pixels
static GLUI *glui; // user interface
static int main_window;
static int menu_window;
static Visualization::ColorMode selectedColormap;
static void initializeColormaps();
static std::map<Visualization::ColorMode, Colormap*> colormaps;
static Colormap *colormap;
static int selectedNumOfColors;
static Visualization::DatasetType scalarDataset;
static float scalarMax, scalarMin;
static Visualization::DatasetType vectorDataset;
static Visualization::DatasetType heightplotDataset;
static Visualization::GlyphType glyphType;
static GLUI_Panel *streamtube_options;
static float hueValue;
static float saturationValue;
static int dim;
static int numberOfSegments;
static int sample_x, sample_y;
static float densityIsoline;
static float densityRHO1Isoline;
static float densityRHO2Isoline;
static int numberIsolines;
static int angle;
static int translate_x, translate_z, translate_y, distance;
static Visualization::Mode scalarMode;
static int seed_x,seed_y,seed_z;
static void renderColormap();
};
#endif
| true |
1cb283a79ece78f34eab341dd7766d4054a175d6 | C++ | marcosrodriigues/ufop | /conteudo/Introdução à Programação (Prática)/Exercicios/P03_Marcos_Rodrigues/Exercício 17.cpp | UTF-8 | 376 | 3.953125 | 4 | [] | no_license | /*
Criar um programa que imprima todos os números de 1 até 100, inclusive, e a soma do quadrado desses números.
*/
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int soma, i;
for(i = 1; i <= 100; i++) {
cout << i << "\n";
soma = soma + pow(i, 2);
}
cout << "Soma do quadrado dos numeros: " << soma;
return 0;
} | true |
a22fdf360662e7c5d627fef68635eafbf9bf78a2 | C++ | chandradharrao/Dynamic-Programming-CPP | /lcsMemo.cpp | UTF-8 | 1,151 | 3.734375 | 4 | [] | no_license | //bottom to top solution
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int lcs(string s1,string s2){
int m = s1.length();
int n = s2.length();
//2d matrix to store the longest sub sequence count for each sub sequence
vector< vector<int> > table(m+1,vector<int>(n+1,0));
//bottom up -> start from the smallest sub problem and build to the final solution
for(int i = 0;i<=m;i++){
for(int j = 0;j<=n;j++){
//empty strings dont have sub sequences
if(i == 0 || j == 0){
table[i][j] = 0;
}
//if both the letters are same,then move equally back
else if( s1[i - 1] == s2[j - 1] ){
table[i][j] = 1 + table[i-1][j-1];
}
else{
//else if not same,then we have to take max of the two choices
table[i][j] = max(table[i-1][j],table[i][j-1]);
}
}
}
return table[m][n];
}
int main(){
string s1 = "acadb";
string s2 = "cbda";
cout << "The longest subsequence is " << lcs(s1,s2) << endl;
} | true |
0d38f151fd538caeabd714a3343f77b25118b299 | C++ | Barvius/esp8266 | /light/config.ino | UTF-8 | 3,504 | 2.78125 | 3 | [] | no_license | String jsonConfig = "{}";
bool loadConfig() {
// Открываем файл для чтения
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
// если файл не найден
Serial.println("Failed to open config file");
// Создаем файл запиав в него аные по умолчанию
saveConfig();
return false;
}
// Проверяем размер файла, будем использовать файл размером меньше 1024 байта
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
return false;
}
// загружаем файл конфигурации в глобальную переменную
jsonConfig = configFile.readString();
// Резервируем памяь для json обекта буфер может рости по мере необходимти предпочтительно для ESP8266
DynamicJsonBuffer jsonBuffer;
// вызовите парсер JSON через экземпляр jsonBuffer
// строку возьмем из глобальной переменной String jsonConfig
JsonObject& root = jsonBuffer.parseObject(jsonConfig);
// Теперь можно получить значения из root
//timezone = root["timezone"]; // Так получаем число
//_ssid = root["ssidName"].as<String>();
//_password = root["ssidPassword"].as<String>();
M_Server = root["M_Server"].as<String>();
M_Port = root["M_Port"];
M_User = root["M_User"].as<String>();
M_Password = root["M_Password"].as<String>();
GpioTopics[0] = root["IO_topic_0"].as<String>();
GpioTopics[1] = root["IO_topic_1"].as<String>();
GpioTopics[2] = root["IO_topic_2"].as<String>();
GpioTopics[3] = root["IO_topic_3"].as<String>();
GpioDescription[0] = root["IO_description_0"].as<String>();
GpioDescription[1] = root["IO_description_1"].as<String>();
GpioDescription[2] = root["IO_description_2"].as<String>();
GpioDescription[3] = root["IO_description_3"].as<String>();
return true;
}
// Запись данных в файл config.json
bool saveConfig() {
// Резервируем памяь для json обекта буфер может рости по мере необходимти предпочтительно для ESP8266
DynamicJsonBuffer jsonBuffer;
// вызовите парсер JSON через экземпляр jsonBuffer
JsonObject& json = jsonBuffer.parseObject(jsonConfig);
json["M_Server"] = M_Server;
json["M_Port"] = M_Port;
json["M_User"] = M_User;
json["M_Password"] = M_Password;
json["IO_topic_0"] = GpioTopics[0];
json["IO_topic_1"] = GpioTopics[1];
json["IO_topic_2"] = GpioTopics[2];
json["IO_topic_3"] = GpioTopics[3];
json["IO_description_0"] = GpioDescription[0];
json["IO_description_1"] = GpioDescription[1];
json["IO_description_2"] = GpioDescription[2];
json["IO_description_3"] = GpioDescription[3];
// Помещаем созданный json в глобальную переменную json.printTo(jsonConfig);
json.printTo(jsonConfig);
// Открываем файл для записи
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
//Serial.println("Failed to open config file for writing");
return false;
}
// Записываем строку json в файл
json.printTo(configFile);
return true;
}
| true |
44a06393893dd03e20600f6d1fef038d1ee22095 | C++ | aeremenok/a-team-777 | /10/oot_Mozg/SRC/Player.cpp | WINDOWS-1251 | 694 | 2.640625 | 3 | [] | no_license | // **************************************************************************
//! \file Player.cpp
//! \brief
//! \author Bessonov A.V.
//! \date 17.May.2008 - 17.May.2008
// **************************************************************************
#include "stdafx.h"
#include "Player.h"
// ==========================================================================
namespace Game
{
void Player::setName (std::string newName)
{
name = newName;
}
std::string Player::getName () const
{
return name;
}
}//end of namespace Game
// ==========================================================================
| true |
b63abbc6f31acf1008969b52f7a61d43d86ab162 | C++ | tiankonguse/ACM | /contest/poj/shen1000/1011/9604629_WA.cpp | UTF-8 | 1,023 | 2.546875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int N=65;
class T{public:int l,num;}str[N];
int ss[N];
int n,len,k,num;
int cmp(const void *a,const void *b)
{
return ((T*)b)->l - ((T*)a)->l;
}
bool dfs(int left,int i,int tatol)
{
if(i==tatol)return true;
for(int j=i;j<k;j++)
{
int l=str[j].l;
int &numb=str[j].num;
if(numb==0 || l>left)continue;
numb--;
if(l==left)
{
if(dfs(len,0,tatol+1))return true;
numb++; return false;
}
if(dfs(left-l,j,tatol))return true;
numb++;
if(left == len || j+1==k)return false;
}
return false;
}
int main()
{
int n;
while(scanf("%d",&n),n)
{
memset(ss,-1,sizeof(ss));
k=0;
int sum=0;
while(n--)
{
scanf("%d",&len);
sum+=len;
if(ss[len]==-1){str[k].l=len;str[k].num=1;ss[len]=k;k++;}
else str[ss[len]].num++;
}
qsort(str,k,sizeof(T),cmp);
for(int i=str[0].l;i<=sum;i++)
{
while(sum%i)i++;
num=sum/i;
len=i;
if(dfs(len,0,0))
{
printf("%d\n",i);break;
}
}
}
return 0;
}
| true |
96628df58168f64e619ba0d3625d4cf0cf583c40 | C++ | jJayyyyyyy/OJ | /PAT/basic_level/1042_字符统计/count_char.cpp | UTF-8 | 453 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(){
string us_str;
getline(cin, us_str);
int cnt[32]={0}, len=us_str.size(), i=0;
char ch;
for( i=0; i<len; i++ ){
ch = tolower(us_str[i]);
if( isalpha(ch) ){
cnt[ ch-'a' ]++;
}
}
int n_max=0, ix_max=0;
for( i=0; i<26; i++ ){
if( cnt[i]>n_max ){
n_max = cnt[i];
ix_max = i;
}
}
ch = ix_max + 'a';
cout<<ch<<' '<<n_max;
return 0;
}
| true |
05e56d618dbbc9bfe1676af733c264e85c822393 | C++ | visualzhou/simple-rpc | /rpc/utils.cc | UTF-8 | 4,093 | 2.765625 | 3 | [] | no_license | #include <utility>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/time.h>
#include "utils.h"
using namespace std;
namespace rpc {
struct start_thread_pool_args {
ThreadPool* thrpool;
int id_in_pool;
};
void* ThreadPool::start_thread_pool(void* args) {
start_thread_pool_args* t_args = (start_thread_pool_args *) args;
t_args->thrpool->run_thread(t_args->id_in_pool);
delete t_args;
pthread_exit(NULL);
return NULL;
}
ThreadPool::ThreadPool(int n /* =... */)
: n_(n) {
th_ = new pthread_t[n_];
q_ = new Queue<function<void()>*> [n_];
for (int i = 0; i < n_; i++) {
start_thread_pool_args* args = new start_thread_pool_args();
args->thrpool = this;
args->id_in_pool = i;
Pthread_create(&th_[i], NULL, ThreadPool::start_thread_pool, args);
}
}
ThreadPool::~ThreadPool() {
for (int i = 0; i < n_; i++) {
q_[i].push(nullptr); // nullptr is used as a termination token
}
for (int i = 0; i < n_; i++) {
Pthread_join(th_[i], nullptr);
}
delete[] th_;
delete[] q_;
}
void ThreadPool::run_async(const std::function<void()>& f) {
// Randomly select a thread for the job.
// There could be better schedule policy.
int queue_id = rand() % n_;
q_[queue_id].push(new function<void()>(f));
}
void ThreadPool::run_thread(int id_in_pool) {
for (;;) {
function<void()>* f = q_[id_in_pool].pop();
if (f == nullptr) {
return;
}
(*f)();
delete f;
}
}
int Log::level = Log::DEBUG;
FILE* Log::fp = stdout;
pthread_mutex_t Log::m = PTHREAD_MUTEX_INITIALIZER;
void Log::set_level(int level) {
Pthread_mutex_lock(&Log::m);
Log::level = level;
Pthread_mutex_unlock(&Log::m);
}
void Log::set_file(FILE* fp) {
verify(fp != NULL);
Pthread_mutex_lock(&Log::m);
Log::fp = fp;
Pthread_mutex_unlock(&Log::m);
}
void Log::log_v(int level, const char* fmt, va_list args) {
static char indicator[] = { 'F', 'E', 'W', 'I', 'D' };
assert(level <= Log::DEBUG);
if (level <= Log::level) {
Pthread_mutex_lock(&Log::m);
fprintf(Log::fp, "%c: ", indicator[level]);
vfprintf(Log::fp, fmt, args);
fprintf(Log::fp, "\n");
fflush(Log::fp);
Pthread_mutex_unlock(&Log::m);
}
}
void Log::log(int level, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
log_v(level, fmt, args);
va_end(args);
}
void Log::fatal(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
log_v(Log::FATAL, fmt, args);
va_end(args);
}
void Log::error(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
log_v(Log::ERROR, fmt, args);
va_end(args);
}
void Log::warn(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
log_v(Log::WARN, fmt, args);
va_end(args);
}
void Log::info(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
log_v(Log::INFO, fmt, args);
va_end(args);
}
void Log::debug(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
log_v(Log::DEBUG, fmt, args);
va_end(args);
}
int set_nonblocking(int fd, bool nonblocking) {
int ret = fcntl(fd, F_GETFL, 0);
if (ret != -1) {
if (nonblocking) {
ret = fcntl(fd, F_SETFL, ret | O_NONBLOCK);
} else {
ret = fcntl(fd, F_SETFL, ret & ~O_NONBLOCK);
}
}
return ret;
}
Timer::Timer() {
reset();
}
void Timer::reset() {
start_.tv_sec = 0;
start_.tv_usec = 0;
end_.tv_sec = 0;
end_.tv_usec = 0;
}
void Timer::start() {
gettimeofday(&start_, NULL);
}
void Timer::end() {
gettimeofday(&end_, NULL);
}
double Timer::elapsed() const {
// assumes end_ >= start_
double sec = 0;
double usec = 0;
if (end_.tv_usec < start_.tv_usec) {
sec = end_.tv_sec - 1 - start_.tv_sec;
usec = (end_.tv_usec + 1000000 - start_.tv_usec) / 1000000.0;
} else {
sec = end_.tv_sec - start_.tv_sec;
usec = (end_.tv_usec - start_.tv_usec) / 1000000.0;
}
return sec+usec;
}
}
| true |
38b8ff52561913bd268da10dc3c4bf14f8faa15c | C++ | kantamRobo/Xbox-GDK-Samples | /Samples/Tools/MeshletConverter/ConverterApp/TriangleAllocator.h | UTF-8 | 2,167 | 2.8125 | 3 | [
"MIT"
] | permissive | //--------------------------------------------------------------------------------------
// TriangleAllocator.h
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#pragma once
#include <DirectXMath.h>
#include <list>
#include <memory>
#include <vector>
namespace ATG
{
struct Vertex
{
uint32_t DCCVertexIndex;
DirectX::XMFLOAT3 Position;
DirectX::XMFLOAT3 Normal;
Vertex* NextDuplicateVertex;
Vertex()
{
Initialize();
}
void Initialize()
{
std::memset(this, 0, sizeof(Vertex));
}
bool Equals(const Vertex* pOtherVertex) const;
};
using VertexArray = std::vector<Vertex*>;
struct Triangle
{
Vertex Vertex[3];
int SubsetIndex;
int PolygonIndex;
Triangle()
: SubsetIndex(0)
, PolygonIndex(-1)
{ }
void Initialize()
{
SubsetIndex = 0;
Vertex[0].Initialize();
Vertex[1].Initialize();
Vertex[2].Initialize();
}
};
using TriangleArray = std::vector<Triangle*>;
class TriangleAllocator
{
public:
TriangleAllocator()
: m_totalCount(0)
, m_allocatedCount(0)
{ }
~TriangleAllocator()
{
Terminate();
}
void Initialize() { SetSizeHint(50000); }
void Terminate();
void SetSizeHint(uint32_t uAnticipatedSize);
Triangle* GetNewTriangle();
void ClearAllTriangles();
private:
struct AllocationBlock
{
Triangle* TriangleArray;
uint32_t TriangleCount;
};
using AllocationBlockList = std::list<AllocationBlock>;
AllocationBlockList m_allocationBlocks;
uint32_t m_totalCount;
uint32_t m_allocatedCount;
};
uint32_t FindOrAddVertex(VertexArray& vertsArray, Vertex* testVertex);
}
| true |
c7f6e92a836f9707f05b41f5c04071c45b5eba03 | C++ | vgrahul/Codings | /logisticsmap.cpp | UTF-8 | 1,301 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <fstream>
#include <bitset>
#include <stdint.h>
#include <limits.h>
#include <iostream>
using namespace std;
int next=80000;
int i=0;
/*std::string GetBinary32( float value )
{
union
{
float input; // assumes sizeof(float) == sizeof(int)
int output;
} data;
data.input = value;
std::bitset<sizeof(float) * CHAR_BIT> bits(data.output);
std::string mystring = bits.to_string<char,
std::char_traits<char>,
std::allocator<char> >();
return mystring;
}
std::string float_binary(float a1)
{
std::string str = GetBinary32( a1 );
std::cout<<str<<"\n";
}*/
void float_binary( float f)
{
cout<<bitset<sizeof f*8>(*(long unsigned int*)(&f))<<endl;
}
/*void save_text(float a)
{
float_binary(a);
}*/
int logistic_fun(float x,float r)
{
float x1;
x1 = r*x*(1-x);
if(next)
{
next = next - 1;
i+=1;
float_binary(x1);
logistic_fun(x1,r);
}
}
int main()
{
float x,r;
scanf("%f%f",&x,&r);
logistic_fun(x,r);
return 0;
}
| true |
eda6ad3bfa7c1db85e9072e408091f4de2c854be | C++ | moonmile/gyakubiki-cpp | /gcc/ch04/stl344.cpp | UTF-8 | 347 | 2.984375 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
int main( void )
{
string str1("Hello world.");
cout << "[" << str1 << "] 文字数は " << str1.length() << endl;
string str2("");
cout << "[" << str2 << "] 文字数は " << str2.length() << endl;
string str3;
cout << "[" << str3 << "] 文字数は " << str3.length() << endl;
}
| true |
029ea329e073ecdc9bdb4592f194c534f1487adb | C++ | yaboyd1/DataStructures | /p5/rec_fun.cpp | UTF-8 | 2,851 | 3.875 | 4 | [] | no_license | #include <iostream> // Provides cout
#include <string> // Provides string
#include <cmath> // Provides pow()
using namespace std;
void triangle(ostream& outs, unsigned int m, unsigned int n) {
// Precondition: m <= n
// Postcondition: The function has printed a pattern of 2*(n-m+1) lines
// to the output stream outs. The first line contains m asterisks, the next
// line contains m+1 asterisks, and so on up to a line with n asterisks.
// Then the pattern is repeated backwards, going n back down to m.
/* Example output:
triangle(cout, 3, 5) will print this to cout:
***
****
*****
*****
****
***
*/
if (m > n) return;
for (unsigned int i = 0; i < m; ++i) outs << "*";
cout << endl;
triangle(outs, m + 1, n);
for (unsigned int i = 0; i < m; ++i) outs << "*";
cout << endl;
}
void numbers(ostream& outs, const string& prefix, unsigned int levels) {
if (levels == 0) {
outs << prefix << endl;
return;
}
for (char i = '1'; i <= '9'; ++i) {
numbers(outs, prefix + i + '.', levels - 1);
}
}
bool bears(int n) {
// Postcondition: A true return value means that it is possible to win
// the bear game by starting with n bears. A false return value means that
// it is not possible to win the bear game by starting with n bears.
// Examples:
// bear(250) is true (as shown above)
// bear(42) is true
// bear(84) is true
// bear(53) is false
// bear(41) is false
if (n == 42) return true;
if (n < 42) return false;
if (n % 5 == 0) bears(n - 42);
else if ((n % 4 == 0 || n % 3 == 0) && (((n % 10) * ((n / 10) % 10)) != 0)) bears(n - ((n % 10) * ((n / 10) % 10)));
else if (n % 2 == 0) bears(n / 2);
else return false;
}
void pattern(ostream& outs, unsigned int n, unsigned int i) {
// Precondition: n is a power of 2 greater than zero.
// Postcondition: A pattern based on the above example has been
// printed to the ostream outs. The longest line of the pattern has
// n stars beginning in column i of the output. For example,
// The above pattern is produced by the call pattern(cout, 8, 0).
if (n == 0) return;
pattern(outs, n / 2, i);
for (int j = 0; j < i; ++j) outs << " ";
for (int j = 0; j < n; ++j) outs << "* ";
outs << endl;
pattern(outs, n / 2, i + n / 2);
}
int main() {
cout << "Printing a triangle..." << endl;
triangle(cout, 3, 5);
cout << endl << "Printing some numbers..." << endl;
numbers(cout, "PREFIX", 2);
cout << endl << "Bears problem for 5 integers..." << endl;
int test[] = {250, 42, 84, 53, 41};
bool correct[] = {1, 1, 1, 0, 0};
bool output[5];
for (int i = 0; i < 5; ++i) {
output[i] = bears(test[i]);
cout << test[i] << ": " << output[i];
output[i] != correct[i] ? cout << " X " : cout << " Correct! ";
cout << endl;
}
cout << endl << "Printing a pattern..." << endl;
pattern(cout, 8, 0);
return 0;
} | true |
72ed32fb219bf91c7ea1d2225ee1ebd1dc4cd774 | C++ | kmichalk/PhysicalEngine | /Handler.h | UTF-8 | 3,013 | 2.578125 | 3 | [] | no_license | #pragma once
#include "ThreadProcess.h"
#include "Reliant.h"
namespace game
{
//class Reliant;
//template<class = Reliant>
//class Handler;
//template<>
//class Handler<Reliant>: public ThreadProcess
//{
// x::vector<Reliant*>& reliantsRef_;
//protected:
// Handler(x::vector<Reliant*>& reliants);
//public:
// virtual void process() abstract override;
// virtual void clear() override;
// size_t getReliantsNumber() const;
// bool hasReliant(Reliant* reliant) const;
// void addReliant(Reliant* reliant);
// void detachReliant(Reliant* reliant);
// virtual ~Handler();
//};
/////////////////////////////////////////////////////////////////////////////////
//
//template<class _Type>
//class Handler: public Handler<Reliant>
//{
// static_assert(std::is_base_of<Reliant, _Type>::value,
// "Handled objects type must derive from HandledObject.");
//protected:
// x::vector<_Type*> reliants_;
// Handler();
//public:
//
//};
/////////////////////////////////////////////////////////////////////////////////
//template<class _Type>
//inline Handler<_Type>::Handler():
// Handler<>(reliants_)
//{
//}
///////////////////////////////////////////////////////////////////////////////
template<class _Type>
class Handler: public ThreadProcess
{
G_OBJECT;
//static_assert(std::is_base_of<Reliant<_Type>, _Type>::value,
// "Handled _Type must derive from Reliant<_Type>");
protected:
x::vector<_Type*> reliants_;
Handler();
public:
virtual void process() abstract override;
virtual void clear() override;
size_t getReliantsNumber() const;
bool hasReliant(_Type* reliant) const;
void addReliant(_Type* reliant);
void detachReliant(_Type* reliant);
virtual ~Handler();
};
///////////////////////////////////////////////////////////////////////////////
template<class _Type>
Handler<_Type>::Handler()
{
}
template<class _Type>
void Handler<_Type>::clear()
{
reliants_.delete_each();
reliants_.clear();
}
template<class _Type>
size_t Handler<_Type>::getReliantsNumber() const
{
return reliants_.size();
}
template<class _Type>
bool Handler<_Type>::hasReliant(_Type * reliant) const
{
return (bool)reliants_.find(reliant);
}
template<class _Type>
void Handler<_Type>::addReliant(_Type * reliant)
{
if (!reliant)
return;
auto relHandler = reliant->getHandler();
if (!relHandler)
static_cast<Reliant<_Type>*>(reliant)->register_(this);
/*if (relHandler != this)
return;*/
if (!hasReliant(reliant))
reliants_.push_back(reliant);
/*if (reliant && reliant->getHandler() == this && !hasReliant(reliant))
reliants_.push_back(reliant);*/
}
template<class _Type>
void Handler<_Type>::detachReliant(_Type * reliant)
{
if (reliant)
reliants_.remove(reliant);
}
template<class _Type>
Handler<_Type>::~Handler()
{
clear();
}
}
| true |
62c755dd6ed22120555b6249b04d7f659a1800f1 | C++ | wujingyue/leetcode | /315.cc | UTF-8 | 1,676 | 3.75 | 4 | [] | no_license | #include <cassert>
#include <iostream>
#include <vector>
struct IndexCount {
IndexCount(int i, int c) : index(i), count(c) {}
int index;
int count;
};
class Solution {
public:
std::vector<int> countSmaller(std::vector<int>& nums) {
int n = nums.size();
std::vector<IndexCount> index_counts;
index_counts.reserve(n);
for (int i = 0; i < n; ++i) {
index_counts.push_back(IndexCount(i, 0));
}
MergeSort(nums, 0, n - 1, &index_counts);
std::vector<int> answer(n);
for (const auto& index_count : index_counts) {
answer[index_count.index] = index_count.count;
}
return answer;
}
private:
void MergeSort(const std::vector<int>& nums, int i, int j,
std::vector<IndexCount>* index_counts) {
if (i >= j) {
return;
}
int k = i + (j - i) / 2;
MergeSort(nums, i, k, index_counts);
MergeSort(nums, k + 1, j, index_counts);
std::vector<IndexCount> merged;
int p1 = i;
int p2 = k + 1;
while (p1 <= k || p2 <= j) {
if (p1 <= k && (p2 > j || nums[(*index_counts)[p1].index] <=
nums[(*index_counts)[p2].index])) {
merged.push_back((*index_counts)[p1]);
p1++;
merged.back().count += p2 - (k + 1);
} else {
merged.push_back((*index_counts)[p2]);
p2++;
}
}
assert(merged.size() == j - i + 1);
std::copy(merged.begin(), merged.end(), index_counts->begin() + i);
}
};
int main() {
std::vector<int> nums({5, 2, 6, 1});
std::vector<int> answer = Solution().countSmaller(nums);
for (const auto& elem : answer) {
std::cout << elem << std::endl;
}
}
| true |
067ec0b9d87732e583540c47f2d02d0fdc94bb8d | C++ | mopack/OnlineJudgeCode | /OnlineJudgeCode/冼鏡光9-7 最大連續元素積.cpp | UTF-8 | 962 | 2.59375 | 3 | [] | no_license | //#include <iostream>
//#include <cstdlib>
//#include <vector>
//#include <string>
//
//#define max(a,b) (((a) > (b)) ? (a) : (b))
//#define min(a,b) (((a) < (b)) ? (a) : (b))
//
//using namespace std;
//
//vector<int> x = { -2,3,4,-4 };
//
//int main() {
// // no positive
// bool nopos = 1; long long Ma = -2147483647;
// for (int i = 0; i < x.size(); i++) {
// if (x[i] > 0) { nopos = 0; break;}
// if (Ma < x[i]) Ma = x[i];
// }
// if (nopos) { cout << Ma << endl; system("pause"); return 0; }
//
// // init
// int ma = 1, mi = 1; // currently max & min
// int ans = 1; // currently ans (the largest)
//
// for (int i = 0; i < x.size(); i++) {
// if (x[i] > 0) {
// ma *= x[i];
// mi = min(mi*x[i], 1);
// }
// else if (x[i] == 0) {
// ma = 1;
// mi = 0;
// }
// else {
// int temp = ma;
// ma = max(mi*x[i], 1);
// mi = temp * x[i];
// }
// ans = max(ans, ma);
// }
// cout << ans << endl;
//
//
// system("pause");
// return 0;
//} | true |
7bba000feb12d3ab805f56dc9ce78768c73cdebd | C++ | MadhuriK-14/C-Programs | /CPP/TemplateFunction1.cpp | UTF-8 | 318 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
template <class T>
void templateFunction(T para)
{
cout<<"\npara = "<<para<<endl;
cout<<"sizeof(para) = "<<sizeof(para)<<endl;
}
int main()
{
templateFunction(25);
templateFunction(2.5);
templateFunction("String");
templateFunction('c');
return 0;
}
| true |
49b0870ab47b48335dd22ef3070f7f2b4ac6d469 | C++ | metalZK/testgit | /set.cpp | GB18030 | 1,278 | 3.75 | 4 | [] | no_license | #include <iostream>
#include <string>
#include<set>
#include <algorithm>
using namespace std;
struct A
{
int no;
string name;
bool operator < (const A &a) const // ء<Զ
{
//scoreɴСҪСʹá>ɡ
return a.no < no;
}
};
int main_set()
{
A a1, a2, a3;
a1.no = 1; a2.no = 2; a3.no = 3;
a1.name = "a1"; a2.name = "a2"; a3.name = "a3";
set<int> s; //һint͵set
s.insert(10); //
s.insert(30);
s.insert(20);
s.insert(40);
//ݣõ
for (set<int>::iterator it = s.begin(); it != s.end(); ++it)
{
cout << *it << endl;
int tmp = (*it);
cout << tmp << endl << endl;
}
//õsetеԪѾСź
set<int>::iterator result = find(s.begin(), s.end(), 30);
if (result != s.end()){
cout << "find:" << "\t"<< *result << endl;
}
else{
cout << "not found" << endl << endl;
}
set<A> aa;
aa.insert(a1);
aa.insert(a2);
aa.insert(a3);
for (set<A>::iterator it = aa.begin(); it != aa.end(); ++it)
{
cout << (*it).no << endl;
cout << (*it).name << endl << endl;
}
return 0;
}
| true |
a76dcd7518a3ebe92fcedbb1153eaf7741397631 | C++ | gloshkaj/Duell-Project-1 | /Player.h | UTF-8 | 372 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Board.h"
#include "BoardView.h"
using namespace std;
#pragma once
class Player
{
public:
Player();
// Pure virtual function. So we have to use a pointer to a player when we declare an object of the class.
virtual void Play(Board & a_board, int a_turn, string a_first, string a_player) = 0;
~Player();
};
| true |
8b3d2def56033e83783bbddd74b15c90b5e68069 | C++ | mikoval/GraphicsProject | /src/Rasterizer/Shapes/glMesh.cpp | UTF-8 | 1,253 | 2.71875 | 3 | [] | no_license | #include <Shapes/glMesh.h>
#include <Core/Base.h>
void glMesh::draw(){
draw(Mat4x4());
}
void glMesh::draw(Mat4x4 transform){
glBindVertexArray(VAO);
if(material.enabled){
renderer.setMaterial(&material);
}
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void glMesh::drawInstanced(int count, Mat4x4 transform){
glBindVertexArray(VAO);
//renderer.setMaterial(&material);
glDrawElementsInstanced(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0, count);
glBindVertexArray(0);
}
void glMesh::print(){
// cout << "PRINTING glMesh" << endl;
}
void glMesh::getMinMax(float *minX_out, float *maxX_out, float *minY_out, float *maxY_out, float *minZ_out, float *maxZ_out){
float minX = INF;
float minY = INF;
float minZ = INF;
float maxX = -INF;
float maxY = -INF;
float maxZ = -INF;
for(int i = 0; i < vertices.size(); i++){
Vec3f p = vertices[i].Position;
minX = MIN(minX, p.x);
maxX = MAX(maxX, p.x);
minY = MIN(minY, p.y);
maxY = MAX(maxY, p.y);
minZ = MIN(minZ, p.z);
maxZ = MAX(maxZ, p.z);
}
*minX_out = minX;
*maxX_out = maxX;
*minY_out = minY;
*maxY_out = maxY;
*minZ_out = minZ;
*maxZ_out = maxZ;
}
| true |
ea1064b2f23f86c04778a19a601fd6bfddad6a31 | C++ | leights/sandbox | /core/lib/Logger.cpp | UTF-8 | 1,339 | 3 | 3 | [] | no_license | #include "../include/Logger.h"
std::queue<LogMessage> * Logger::inlogs = new std::queue<LogMessage>();;
pthread_mutex_t Logger::logmutex;
LogMessage::LogMessage(std::string f, int l, std::string fun, int le , std::string m) {
time(&mytime);
file = f;
line = l;
function = fun;
level = le;
message = m;
}
Logger::Logger() {
started = false;
pthread_mutex_init(&logmutex, NULL);
outlogs = new std::queue<LogMessage>();
}
void Logger::switchq() {
std::queue<LogMessage> * tmp;
pthread_mutex_lock(&logmutex);
tmp = inlogs;
inlogs = outlogs;
outlogs = tmp;
pthread_mutex_unlock(&logmutex);
}
void Logger::Log(std::string m) {
LogMessage msg(std::string(), 0, std::string(), 5, m);;
pthread_mutex_lock(&logmutex);
inlogs->push(msg);
pthread_mutex_unlock(&logmutex);
}
void Logger::Log(std::string f, int l, std::string fun, int le, std::string m) {
LogMessage msg(f , l, fun, le, m);;
pthread_mutex_lock(&logmutex);
inlogs->push(msg);
pthread_mutex_unlock(&logmutex);
}
void Logger::Setup() {}
void Logger::Execute(void* args) {
LogMessage message;
while (running) {
switchq();
while (outlogs->size() > 0) {
message = outlogs->front();
std::cout << message.GetMessage() << std::endl;
outlogs->pop();
}
//std::cout << "Logger thread sleeping." << std::endl;
sleep(1);
}
}
| true |
c11c8e69bdeab25957a037ec2bb972cce6244c9a | C++ | pzenie1/Pipeline | /Project1/Rasterizer.cpp | UTF-8 | 4,286 | 3.125 | 3 | [] | no_license | //
// Rasterizer.cpp
//
// Created by Joe Geigel on 11/30/11.
// Modifications by Warren R. Carithers.
// Copyright 2011 Rochester Institute of Technology. All rights reserved.
//
// Contributor: Paul Zenie, pxz5572
//
#include <list>
#include <algorithm>
#include <iostream>
#include <cmath>
#include "Rasterizer.h"
#include "Canvas.h"
using namespace std;
///
// Simple class that performs rasterization algorithms
///
///
// Constructor
//
// @param n number of scancurrentLines
// @param C The Canvas to use
///
Rasterizer::Rasterizer(int n, Canvas &canvas) : n_scanlines(n), C(canvas)
{
}
class EdgeBucket
{
public:
int yMin;
int yMax;
double x; //x value associated with yMin coordinate
double m; //inverse of slope
};
struct SortByY
{
inline bool operator() (const EdgeBucket struct1, const EdgeBucket struct2)
{
return (struct1.yMin < struct2.yMin);
}
};
struct SortByX
{
inline bool operator() (const EdgeBucket struct1, const EdgeBucket struct2)
{
return (struct1.x < struct2.x);
}
};
///
//Initializes the edge table with the appropriate values
// from x[] and y[]
///
vector<EdgeBucket> CreateEdgeTable(int n, const int x[], const int y[])
{
vector<EdgeBucket> edgeTable;
EdgeBucket bucket;
for (int i = 0; i < n; i++) // loop through x and y and create buckets
{
if (y[i % n] < y[(i + 1) % n])
{
bucket.yMin = y[i % n];
bucket.yMax = y[(i + 1) % n];
bucket.x = x[i % n];
}
else
{
bucket.yMin = y[(i + 1) % n];
bucket.yMax = y[i % n];
bucket.x = x[(i + 1) % n];
}
if (bucket.yMax - bucket.yMin != 0)
{
bucket.m = (double)(x[i % n] - x[(i + 1) % n]) / (double)(y[i % n] - y[(i + 1) % n]);
edgeTable.push_back(bucket); // add bucket to table
}
}
return edgeTable;
}
double RoundDouble(double d)
{
return floor(d + 0.5);
}
///
// Draw a filled polygon.
//
// Implementation should use the scan-currentLine polygon fill algorithm
// discussed in class.
//
// The polygon has n distinct vertices. The coordinates of the vertices
// making up the polygon are stored in the x and y arrays. The ith
// vertex will have coordinate (x[i],y[i]).
//
// You are to add the implementation here using only calls to the
// setPixel() function.
//
// @param n - number of vertices
// @param x - array of x coordinates
// @param y - array of y coordinates
///
void Rasterizer::drawPolygon(int n, const int x[], const int y[])
{
std::vector<EdgeBucket> edgeTable = CreateEdgeTable(n, x, y); // main edge table
EdgeBucket bucket;
// sort by yMin
sort(edgeTable.begin(), edgeTable.end(), SortByY());
bool inside;
vector<EdgeBucket> activeList;
int endScanLine = edgeTable[edgeTable.size() - 1].yMax;
for (int currentLine = edgeTable[0].yMin; currentLine <= endScanLine; currentLine++)
{
inside = false;
int i = 0;
while (i < edgeTable.size())
{
bucket = edgeTable[i];
if (bucket.yMin == currentLine) //if currentline is at ymin of the
{ //bucket add it to the activelist
activeList.push_back(bucket);
edgeTable.erase(edgeTable.begin() + i);//and remove from table
}
else
{
i++;
}
}
if (currentLine < endScanLine)
{
i = 0;
while (i < activeList.size())
{
bucket = activeList[i];
if (bucket.yMax == currentLine) //if the buckets y.max is at
{ //current scan line remove it
activeList.erase(activeList.begin() + i);//from the active list
}
else
{
i++;
}
}
}
//sort the active list by x
sort(activeList.begin(), activeList.end(), SortByX());
int edgeIndex = 0;
int endX = *max_element(x, x + n);
for (int currentX = 0; currentX <= endX && edgeIndex < activeList.size(); currentX++)
{
if (currentX == RoundDouble(activeList[edgeIndex].x))
{
if (edgeIndex + 1 < activeList.size() && currentX != RoundDouble(activeList[edgeIndex + 1].x))
{
inside = !inside; //crossed line, change whether inside or out
}
while (edgeIndex < activeList.size() && currentX == RoundDouble(activeList[edgeIndex].x))
{
//update x values
activeList[edgeIndex].x += activeList[edgeIndex].m;
C.setPixel(currentX, currentLine); //set the buckets last pixel
edgeIndex++;
}
}
if (inside)//set pixel if inside polygon
{
C.setPixel(currentX, currentLine);
}
}
}
} | true |
e50d8f8087277c75de13ae5f8211ee8caaaa4ea6 | C++ | el-bart/build_process | /test_app/lib3/Lib3/ObjectToForceLink.mt.cpp | UTF-8 | 539 | 2.796875 | 3 | [] | no_license | /*
* ObjectToForceLink.mt.cpp
*
*/
#include <string>
#include <iostream>
#include <cassert>
#include "Lib3/Reg.hpp"
using namespace std;
using namespace Lib3;
int main(void)
{
assert( Reg::get().size()==1 && "object not registered" );
assert("invalid string registered" &&
Reg::get().at(0)==string("hello Lib3/ObjectToForceLink.cpp :)") );
cout<<"registered strings:"<<endl;
for(Reg::StrVec::const_iterator it=Reg::get().begin();
it!=Reg::get().end();
++it)
cout<<" -> "<<*it<<endl;
return 0;
}
| true |