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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
73f991969f73d6903431660e95ee351d1f51e8bc | C++ | nafejul75/URI_SOLUTIONS | /uri1096.cpp | UTF-8 | 313 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
/**
* Escreva a sua solução aqui
* Code your solution here
* Escriba su solución aquí
*/
for(int i=1; i<=9; i+=2) {
for(int j=7; j>=5; j--) {
printf("I=%d J=%d\n",i,j);
}
}
return 0;
}
| true |
908a2790c4777a73e7a85367d21268c6d44fbd7e | C++ | Chriskkirilov/Diploma | /AutomatedGarden.ino | UTF-8 | 1,507 | 2.640625 | 3 | [] | no_license | #include <FastLED.h>
#include "garden_config.h"
const int LED_PIN = 7;
const int NUM_LEDS = 10;
CRGB leds[NUM_LEDS];
const int tempPin = A0;
int tempInput;
double temp;
const int lightPin = A1;
int lightInput;
const int humidityPin = A2;
int humidityValue;
const int motorPin = 9;
void setup() {
Serial.begin(9600);
pinMode(motorPin, OUTPUT);
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
}
void loop() {
tempInput = analogRead(tempPin);
float humidityValue = analogRead(humidityPin);
float lightInput = analogRead(lightPin);
//converting that reading to voltage
double voltage = tempInput * 5.0;
voltage /= 1024;
float temperatureC = (voltage - 0.5) * 100 ;
humidityValue = humidityValue - 1023;
humidityValue = abs(humidityValue);
humidityValue = map(humidityValue, 0, 1023, 0, 100);
lightInput = analogRead(lightPin);
lightInput = map(lightInput, 0, 1023, 0, 100);
if (humidityValue < humidityPeak) {
digitalWrite(motorPin, HIGH);
}
else {
digitalWrite(motorPin, LOW);
}
if (lightInput < lightPeak) {
for (int i = 0; i < 10; i++) {
leds[i] = CRGB(255, 249, 253);
FastLED.show();
}
}
else {
for (int i = 0; i < 10; i++) {
leds[i] = CRGB::Black;
FastLED.show();
}
}
Serial.print(temperatureC);
Serial.print(" ");
Serial.print(lightInput);
Serial.print(" ");
Serial.println(humidityValue);
delay(5000);
}
| true |
75817b8d349cd55c0ad24f60dfba23c604e6b783 | C++ | AnkitMohapatra/Tree | /Binary Search Tree Implementation.cpp | UTF-8 | 2,359 | 3.9375 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
node *NewNode(int data)
{
node *temp = new node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
node* insert(node *root, int data)
{
if (root == NULL)
{
return NewNode(data);
}
else
if (data <= root->data)
{
root->left = insert(root->left, data);
}
else
root->right = insert(root->right, data);
return root;
}
struct node * minValueNode(struct node* node)
{
struct node* current = node;
while (current->left != NULL)
{
current = current->left;
}
return current;
}
node* deleteNode(node *root, int data)
{
if (root == NULL)
{
return root;
}
if (data < root->data)
{
root->left = deleteNode(root->left, data);
}
else
if (data > root->data)
{
root->right = deleteNode(root->right, data);
}
else
{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else
if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node *temp = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void search(node *root, int data)
{
int pos = 0;
node *temp = new node;
temp = root;
while (temp != NULL)
{
pos++;
if (temp->data == data)
{
cout << "\nData found at: " << pos;
}
else if (temp->data > data)
temp = temp->left;
else
temp = temp->right;
}
cout << "\n Data not found";
return;
}
int main()
{
node *root = NULL; //creating an empty tree
int n, i, a[20] = { 89, 53, 95, 1, 9, 67, 72, 66, 75, 77, 18, 24, 35, 90, 38, 41, 49, 81, 27, 97 };
for (i = 0; i < 20; i++)
root = insert(root, a[i]);
up:
char ch;
cout << "Choose:" << '\n' << "a = Insert node" << '\n' << "b = Delete node" << '\n' << "c = Search";
cin >> ch;
if (ch == 'a')
{
int a;
cout << "\nEnter node:";
cin >> a;
insert(root, a);
}
if (ch == 'b')
{
int b;
cout << "\nEnter which node to delete:";
cin >> b;
deleteNode(root, b);
}
if (ch == 'c')
{
cout << "\nEnter the Element to be searched: ";
cin >> n;
search(root, n);
}
cout << "\n\n\tDo you want to search more...enter choice(y/n)?";
cin >> ch;
if (ch == 'y')
goto up;
return 0;
}
| true |
a0029aa0f8f8ecf32d1e426f01b30fe7330c2ece | C++ | kpu/moses-emnlp | /moses/src/PCNTools.cpp | UTF-8 | 3,652 | 2.921875 | 3 | [] | no_license | #include "PCNTools.h"
#include <iostream>
#include <cstdlib>
namespace PCN
{
const std::string chars = "'\\";
const char& quote = chars[0];
const char& slash = chars[1];
// safe get
inline char get(const std::string& in, int c)
{
if (c < 0 || c >= (int)in.size()) return 0;
else return in[(size_t)c];
}
// consume whitespace
inline void eatws(const std::string& in, int& c)
{
while (get(in,c) == ' ') {
c++;
}
}
// from 'foo' return foo
std::string getEscapedString(const std::string& in, int &c)
{
eatws(in,c);
if (get(in,c++) != quote) return "ERROR";
std::string res;
char cur = 0;
do {
cur = get(in,c++);
if (cur == slash) {
res += get(in,c++);
} else if (cur != quote) {
res += cur;
}
} while (get(in,c) != quote && (c < (int)in.size()));
c++;
eatws(in,c);
return res;
}
// basically atof
float getFloat(const std::string& in, int &c)
{
std::string tmp;
eatws(in,c);
while (c < (int)in.size() && get(in,c) != ' ' && get(in,c) != ')' && get(in,c) != ',') {
tmp += get(in,c++);
}
eatws(in,c);
return atof(tmp.c_str());
}
// basically atof
int getInt(const std::string& in, int &c)
{
std::string tmp;
eatws(in,c);
while (c < (int)in.size() && get(in,c) != ' ' && get(in,c) != ')' && get(in,c) != ',') {
tmp += get(in,c++);
}
eatws(in,c);
return atoi(tmp.c_str());
}
// parse ('foo', 0.23)
CNAlt getCNAlt(const std::string& in, int &c)
{
if (get(in,c++) != '(') {
std::cerr << "PCN/PLF parse error: expected ( at start of cn alt block\n"; // throw "expected (";
return CNAlt();
}
std::string word = getEscapedString(in,c);
if (get(in,c++) != ',') {
std::cerr << "PCN/PLF parse error: expected , after string\n"; // throw "expected , after string";
return CNAlt();
}
size_t cnNext = 1;
std::vector<float> probs;
probs.push_back(getFloat(in,c));
while (get(in,c) == ',') {
c++;
float val = getFloat(in,c);
probs.push_back(val);
}
//if we read more than one prob, this was a lattice, last item was column increment
if (probs.size()>1) {
cnNext = static_cast<size_t>(probs.back());
probs.pop_back();
if (cnNext < 1) {
; //throw "bad link length"
std::cerr << "PCN/PLF parse error: bad link length at last element of cn alt block\n";
return CNAlt();
}
}
if (get(in,c++) != ')') {
std::cerr << "PCN/PLF parse error: expected ) at end of cn alt block\n"; // throw "expected )";
return CNAlt();
}
eatws(in,c);
return CNAlt(std::pair<std::string, std::vector<float> >(word,probs), cnNext);
}
// parse (('foo', 0.23), ('bar', 0.77))
CNCol getCNCol(const std::string& in, int &c)
{
CNCol res;
if (get(in,c++) != '(') return res; // error
eatws(in,c);
while (1) {
if (c > (int)in.size()) {
break;
}
if (get(in,c) == ')') {
c++;
eatws(in,c);
break;
}
if (get(in,c) == ',' && get(in,c+1) == ')') {
c+=2;
eatws(in,c);
break;
}
if (get(in,c) == ',') {
c++;
eatws(in,c);
}
res.push_back(getCNAlt(in, c));
}
return res;
}
// parse ((('foo', 0.23), ('bar', 0.77)), (('a', 0.3), ('c', 0.7)))
CN parsePCN(const std::string& in)
{
CN res;
int c = 0;
if (in[c++] != '(') return res; // error
while (1) {
if (c > (int)in.size()) {
break;
}
if (get(in,c) == ')') {
c++;
eatws(in,c);
break;
}
if (get(in,c) == ',' && get(in,c+1) == ')') {
c+=2;
eatws(in,c);
break;
}
if (get(in,c) == ',') {
c++;
eatws(in,c);
}
res.push_back(getCNCol(in, c));
}
return res;
}
}
| true |
aeada348dce502d0a5d42fb1b03fb5b20095dace | C++ | viennamath/viennamath-dev | /viennamath/runtime/constant.hpp | UTF-8 | 5,692 | 2.890625 | 3 | [
"MIT"
] | permissive | #ifndef VIENNAMATH_RUNTIME_CONSTANT_HPP
#define VIENNAMATH_RUNTIME_CONSTANT_HPP
/* =======================================================================
Copyright (c) 2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaMath - Symbolic and Numerical Math in C++
-----------------
Author: Karl Rupp rupp@iue.tuwien.ac.at
License: MIT (X11), see file LICENSE in the ViennaMath base directory
======================================================================= */
#include <ostream>
#include "viennamath/forwards.h"
//#include "viennamath/expression_compile_time.hpp"
#include "viennamath/runtime/expression_interface.hpp"
//#include "viennamath/expression_run_time.hpp"
/** @file viennamath/runtime/constant.hpp
@brief Defines the ViennaMath runtime constant class.
*/
namespace viennamath
{
//per default, we assume floating point constants, which cannot be tackled with template arguments
/** @brief Representation of a constant within the expression setting of ViennaMath.
*
* @tparam InterfaceType The expression runtime interface to inherit from. Usually rt_expression_interface, but extensions are possible.
*/
template <typename ScalarType, /* see forwards.h for default argument */
typename InterfaceType /* see forwards.h for default argument */>
class rt_constant : public InterfaceType
{
typedef rt_constant<ScalarType, InterfaceType> self_type;
public:
typedef typename InterfaceType::numeric_type numeric_type;
explicit rt_constant(ScalarType s_) : s(s_) {}
/** @brief Evaluates the constant. */
self_type operator() () const
{
return *this;
}
/** @brief Evaluates the constant by returning its value. */
template <typename VectorType>
self_type operator() (const VectorType & /*p*/) const
{
return *this;
}
/** @brief A ViennaMath constant is implicity convertible to its underlying scalar. Since the constructor is explicit, this operation is safe. */
operator ScalarType() const { return s; }
//interface requirements:
/** @brief Returns a copy of the constant. The object referred by the pointer is not automatically deleted, thus the caller needs to ensure deletion. */
InterfaceType * clone() const { return new self_type(s); }
/** @brief (Trivially) Evaluates the constant. */
numeric_type eval(std::vector<numeric_type> const & /*v*/) const { return s; }
/** @brief (Trivially) Evaluates the constant. */
numeric_type eval(numeric_type /*v*/) const { return s; }
/** @brief A constant is a constant :-) */
bool is_constant() const { return true; }
/** @brief Returns a textual representation of the constant */
std::string deep_str() const
{
std::stringstream ss;
ss << "constant(" << s << ")";
return ss.str();
}
/** @brief Interface requirement: Returns the value of the constant */
numeric_type unwrap() const { return s; }
/** @brief Substitutes the constant with an expression 'repl' if it matches the expression 'e'. The object referred by the pointer is not automatically deleted, thus the caller needs to ensure deletion. */
InterfaceType * substitute(const InterfaceType * e,
const InterfaceType * repl) const
{
if (deep_equal(e))
return repl->clone();
//std::cout << "FALSE" << std::endl;
return clone();
};
/** @brief If any of the expressions in 'e' match the constant, the expression in 'repl' is returned. Otherwise, a copy of the constant is returned. The object referred by the pointer is not automatically deleted, thus the caller needs to ensure deletion. */
InterfaceType * substitute(std::vector<const InterfaceType *> const & e,
std::vector<const InterfaceType *> const & repl) const
{
//std::cout << "Comparing variable<" << id << "> with " << e->str() << ", result: ";
for (size_t i=0; i<e.size(); ++i)
if (deep_equal(e[i]))
return repl[i]->clone();
//std::cout << "FALSE" << std::endl;
return clone();
};
/** @brief Returns true if 'other' points to a constant with the same value */
bool deep_equal(const InterfaceType * other) const
{
const self_type * ptr = dynamic_cast< const self_type *>(other);
if (ptr != NULL)
return (ptr->s <= s) && (ptr->s >= s); //to suppress warnings on Clang when using ==
return false;
}
/** @brief Returns true if 'other' is also a constant */
bool shallow_equal(const InterfaceType * other) const
{
return dynamic_cast< const self_type * >(other) != NULL;
}
/** @brief Returns the result of differentiating the constant with respect to a variable, i.e. zero. */
InterfaceType * diff(const InterfaceType * /*diff_var*/) const
{
return new self_type(0);
}
private:
ScalarType s;
};
/** @brief Convenience operator overload for streaming a runtime constant to std::cout or any other STL-compatible output stream. */
template <typename ScalarType, typename InterfaceType>
std::ostream& operator<<(std::ostream & stream,
rt_constant<ScalarType, InterfaceType> const & c)
{
stream << c.deep_str();
return stream;
}
}
#endif
| true |
c6c1910d5c0ec8c6150386e999f8b3d4f415f3c0 | C++ | amd/libflame | /test/lapacke/EIG/ORTHO/lapacke_gtest_geqrt.cc | UTF-8 | 18,538 | 2.546875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive"
] | permissive | #include "gtest/gtest.h"
#include "../../lapacke_gtest_main.h"
#include "../../lapacke_gtest_helper.h"
#define geqrt_free() \
if (A!=NULL) free(A); \
if (Aref!=NULL) free(Aref);\
if (tau!=NULL) free(tau);\
if (tauref!=NULL) free(tauref); \
if( hModule != NULL) dlclose(hModule); \
if(dModule != NULL) dlclose(dModule)
// index of the 'config parameter struct' array to enable multiple sub-tests.
static int idx = 0;
/* Begin float_common_parameters class definition */
class geqrt_float_parameters{
public:
int bufsize;
void *hModule, *dModule;
float diff;
/*input parameters */
int matrix_layout;
lapack_int n;
lapack_int m;
lapack_int nb;
lapack_int ldt;
float* A;
lapack_int lda;
/*Output Parameter*/
float* tau;
float *Aref, *tauref;
/*Return Values*/
lapack_int info, inforef;
public:
geqrt_float_parameters (int matrix_layout, lapack_int m , lapack_int n, lapack_int nb, lapack_int lda, lapack_int ldt);
~geqrt_float_parameters ();
};
/* Constructor definition float_common_parameters */
geqrt_float_parameters:: geqrt_float_parameters (int matrix_layout_i, lapack_int m_i , lapack_int n_i, lapack_int nb_i, lapack_int lda_i, lapack_int ldt_i)
{
int i;
matrix_layout = matrix_layout_i;
n = n_i;
m = m_i;
lda = lda_i;
nb = nb_i;
ldt = ldt_i;
#if LAPACKE_TEST_VERBOSE
printf(" \n geqrt float: m: %d, n: %d lda: %d \n", m, n, lda);
#endif
if (matrix_layout == LAPACK_COL_MAJOR)
bufsize = lda*n*sizeof(float);
else if (matrix_layout == LAPACK_ROW_MAJOR)
bufsize = lda*m*sizeof(float);
else
EXPECT_TRUE(false) << "matrix_layout invalid";
/*Memory allocation */
lapacke_gtest_alloc_float_buffer_pair(&A, &Aref, bufsize);
lapacke_gtest_alloc_float_buffer_pair(&tau, &tauref, (min(m,n)*sizeof(float)));
if ((A==NULL) || (Aref==NULL) || \
(tau==NULL) || (tauref==NULL)){
EXPECT_FALSE( true) << "geqrt_float_parameters object: malloc error.";
geqrt_free();
exit(0);
}
/* Initialization of input matrices */
lapacke_gtest_init_float_buffer_pair_rand( A, Aref, bufsize);
/*initialize output matrix by 0 */
for(i=0;i<(min(m,n));i++) {
tau[i] = 0;
tauref[i] = tau[i];
}
} /* end of Constructor */
/* Destructor definition 'float_common_parameters' class */
geqrt_float_parameters :: ~geqrt_float_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" geqrt_float_parameters object: destructor invoked. \n");
#endif
/* De-Allocate memory for the input matrices */
geqrt_free();
}
/* Test fixture class definition */
class sgeqrt_test : public ::testing::Test {
public:
geqrt_float_parameters *sgeqrt_obj;
void SetUp();
void TearDown () { delete sgeqrt_obj; }
};
void sgeqrt_test::SetUp(){
/* LAPACKE sgeqrt prototype */
typedef int (*Fptr_NL_LAPACKE_sgeqrt) (int matrix_layout, lapack_int m,lapack_int n,
float *A, lapack_int lda, float* tau);
Fptr_NL_LAPACKE_sgeqrt sgeqrt;
sgeqrt_obj = new geqrt_float_parameters ( eig_paramslist[idx].matrix_layout,
eig_paramslist[idx].m,
eig_paramslist[idx].n,
eig_paramslist[idx].lda);
idx = Circular_Increment_Index(idx);
sgeqrt_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
sgeqrt_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(sgeqrt_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(sgeqrt_obj->hModule != NULL) << "Netlib lapacke handle NULL";
sgeqrt = (Fptr_NL_LAPACKE_sgeqrt)dlsym(sgeqrt_obj->hModule, "LAPACKE_sgeqrt");
ASSERT_TRUE(sgeqrt != NULL) << "failed to get the Netlib LAPACKE_sgeqrt symbol";
sgeqrt_obj->inforef = sgeqrt( sgeqrt_obj->matrix_layout, sgeqrt_obj->m,
sgeqrt_obj->n,sgeqrt_obj->Aref,
sgeqrt_obj->lda, sgeqrt_obj->tauref);
/* Compute libflame's Lapacke o/p */
sgeqrt_obj->info = LAPACKE_sgeqrt( sgeqrt_obj->matrix_layout, sgeqrt_obj->m,
sgeqrt_obj->n,sgeqrt_obj->A,
sgeqrt_obj->lda, sgeqrt_obj->tau);
if( sgeqrt_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_sgeqrt is wrong\n", sgeqrt_obj->info );
}
if( sgeqrt_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_sgeqrt is wrong\n",
sgeqrt_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
sgeqrt_obj->diff = computeDiff_s( sgeqrt_obj->bufsize,
sgeqrt_obj->A, sgeqrt_obj->Aref );
}
TEST_F(sgeqrt_test, sgeqrt1) {
EXPECT_NEAR(0.0, sgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(sgeqrt_test, sgeqrt2) {
EXPECT_NEAR(0.0, sgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(sgeqrt_test, sgeqrt3) {
EXPECT_NEAR(0.0, sgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(sgeqrt_test, sgeqrt4) {
EXPECT_NEAR(0.0, sgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
/* Begin double_common_parameters class definition */
class geqrt_double_parameters{
public:
int bufsize;
double diff;
void *hModule, *dModule;
/*input parameters */
int matrix_layout;
lapack_int n;
lapack_int m;
lapack_int nb;
lapack_int ldt
double* A;
lapack_int lda;
/*Output Parameter*/
double* tau;
double *Aref, *tauref;
/*Return Values*/
lapack_int info, inforef;
public:
geqrt_double_parameters (int matrix_layout, lapack_int m , lapack_int n, lapack_int lda);
~geqrt_double_parameters ();
};
/* Constructor definition double_common_parameters */
geqrt_double_parameters:: geqrt_double_parameters (int matrix_layout_i, lapack_int m_i, lapack_int n_i, lapack_int lda_i)
{
int i;
matrix_layout = matrix_layout_i;
n = n_i;
m = m_i;
lda = lda_i;
#if LAPACKE_TEST_VERBOSE
printf(" \n geqrt double: m: %d, n: %d lda: %d \n", m, n, lda);
#endif
if (matrix_layout == LAPACK_COL_MAJOR)
bufsize = lda*n*sizeof(double);
else if (matrix_layout == LAPACK_ROW_MAJOR)
bufsize = lda*m*sizeof(double);
else
EXPECT_TRUE(false) << "matrix_layout invalid";
/*Memory allocation */
lapacke_gtest_alloc_double_buffer_pair(&A, &Aref, bufsize);
lapacke_gtest_alloc_double_buffer_pair(&tau, &tauref, (min(m,n)*sizeof(double)));
if ((A==NULL) || (Aref==NULL) || \
(tau==NULL) || (tauref==NULL)){
EXPECT_FALSE( true) << "geqrt_double_parameters object: malloc error.";
geqrt_free();
exit(0);
}
/* Initialization of input matrices */
lapacke_gtest_init_double_buffer_pair_rand( A, Aref, bufsize);
/*initialize output matrix by 0 */
for(i=0;i<(min(m,n));i++) {
tau[i] = 0;
tauref[i] = tau[i];
}
} /* end of Constructor */
/* Destructor definition 'double_common_parameters' class */
geqrt_double_parameters :: ~geqrt_double_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" geqrt_double_parameters object: destructor invoked. \n");
#endif
/* De-Allocate memory for the input matrices */
geqrt_free();
}
/* Test fixture class definition */
class dgeqrt_test : public ::testing::Test {
public:
geqrt_double_parameters *dgeqrt_obj;
void SetUp();
void TearDown () { delete dgeqrt_obj; }
};
void dgeqrt_test::SetUp(){
/* LAPACKE dgeqrt prototype */
typedef int (*Fptr_NL_LAPACKE_dgeqrt) (int matrix_layout, lapack_int m,lapack_int n,
double *A, lapack_int lda, double* tau);
Fptr_NL_LAPACKE_dgeqrt dgeqrt;
dgeqrt_obj = new geqrt_double_parameters ( eig_paramslist[idx].matrix_layout,
eig_paramslist[idx].m,
eig_paramslist[idx].n,
eig_paramslist[idx].lda);
idx = Circular_Increment_Index(idx);
dgeqrt_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
dgeqrt_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(dgeqrt_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(dgeqrt_obj->hModule != NULL) << "Netlib lapacke handle NULL";
dgeqrt = (Fptr_NL_LAPACKE_dgeqrt)dlsym(dgeqrt_obj->hModule, "LAPACKE_dgeqrt");
ASSERT_TRUE(dgeqrt != NULL) << "failed to get the Netlib LAPACKE_dgeqrt symbol";
dgeqrt_obj->inforef = dgeqrt( dgeqrt_obj->matrix_layout, dgeqrt_obj->m,
dgeqrt_obj->n,dgeqrt_obj->Aref,
dgeqrt_obj->lda, dgeqrt_obj->tauref);
/* Compute libflame's Lapacke o/p */
dgeqrt_obj->info = LAPACKE_dgeqrt( dgeqrt_obj->matrix_layout, dgeqrt_obj->m,
dgeqrt_obj->n,dgeqrt_obj->A,
dgeqrt_obj->lda, dgeqrt_obj->tau);
if( dgeqrt_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_dgeqrt is wrong\n", dgeqrt_obj->info );
}
if( dgeqrt_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_dgeqrt is wrong\n",
dgeqrt_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
dgeqrt_obj->diff = computeDiff_d( dgeqrt_obj->bufsize,
dgeqrt_obj->A, dgeqrt_obj->Aref );
}
TEST_F(dgeqrt_test, dgeqrt1) {
EXPECT_NEAR(0.0, dgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dgeqrt_test, dgeqrt2) {
EXPECT_NEAR(0.0, dgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dgeqrt_test, dgeqrt3) {
EXPECT_NEAR(0.0, dgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dgeqrt_test, dgeqrt4) {
EXPECT_NEAR(0.0, dgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
/* Begin scomplex_common_parameters class definition */
class geqrt_scomplex_parameters{
public:
int bufsize;
void *hModule, *dModule;
float diff;
/*input parameters */
int matrix_layout;
lapack_int n;
lapack_int m;
lapack_int nb;
lapack_int ldt;
lapack_complex_float* A;
lapack_int lda;
/*Output Parameter*/
lapack_complex_float* tau;
lapack_complex_float *Aref, *tauref;
/*Return Values*/
lapack_int info, inforef;
public:
geqrt_scomplex_parameters (int matrix_layout, lapack_int m , lapack_int n, lapack_int lda);
~geqrt_scomplex_parameters ();
};
/* Constructor definition float_common_parameters */
geqrt_scomplex_parameters:: geqrt_scomplex_parameters (int matrix_layout_i, lapack_int m_i, lapack_int n_i, lapack_int lda_i)
{
int i;
matrix_layout = matrix_layout_i;
n = n_i;
m = m_i;
lda = lda_i;
#if LAPACKE_TEST_VERBOSE
printf(" \n geqrt scomplex: m: %d, n: %d lda: %d \n", m, n, lda);
#endif
if (matrix_layout == LAPACK_COL_MAJOR)
bufsize = lda*n*sizeof(lapack_complex_float);
else if (matrix_layout == LAPACK_ROW_MAJOR)
bufsize = lda*m*sizeof(lapack_complex_float);
else
EXPECT_TRUE(false) << "matrix_layout invalid";
/*Memory allocation */
lapacke_gtest_alloc_lapack_scomplex_buffer_pair(&A, &Aref, bufsize);
lapacke_gtest_alloc_lapack_scomplex_buffer_pair(&tau, &tauref, (min(m,n)*sizeof(lapack_complex_float)));
if ((A==NULL) || (Aref==NULL) || \
(tau==NULL) || (tauref==NULL)){
EXPECT_FALSE( true) << "geqrt_float_parameters object: malloc error.";
geqrt_free();
exit(0);
}
/* Initialization of input matrices */
lapacke_gtest_init_scomplex_buffer_pair_rand( A, Aref, bufsize);
/*initialize output matrix by 0 */
for(i=0;i<(min(m,n));i++) {
tau[i] = 0;
tauref[i] = tau[i];
}
} /* end of Constructor */
/* Destructor definition 'float_common_parameters' class */
geqrt_scomplex_parameters :: ~geqrt_scomplex_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" geqrt_scomplex_parameters object: destructor invoked. \n");
#endif
/* De-Allocate memory for the input matrices */
geqrt_free();
}
/* Test fixture class definition */
class cgeqrt_test : public ::testing::Test {
public:
geqrt_scomplex_parameters *cgeqrt_obj;
void SetUp();
void TearDown () { delete cgeqrt_obj; }
};
void cgeqrt_test::SetUp(){
/* LAPACKE cgeqrt prototype */
typedef int (*Fptr_NL_LAPACKE_cgeqrt) (int matrix_layout, lapack_int m,lapack_int n,
lapack_complex_float *A, lapack_int lda, lapack_complex_float* tau);
Fptr_NL_LAPACKE_cgeqrt cgeqrt;
cgeqrt_obj = new geqrt_scomplex_parameters ( eig_paramslist[idx].matrix_layout,
eig_paramslist[idx].m,
eig_paramslist[idx].n,
eig_paramslist[idx].lda);
idx = Circular_Increment_Index(idx);
cgeqrt_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
cgeqrt_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(cgeqrt_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(cgeqrt_obj->hModule != NULL) << "Netlib lapacke handle NULL";
cgeqrt = (Fptr_NL_LAPACKE_cgeqrt)dlsym(cgeqrt_obj->hModule, "LAPACKE_cgeqrt");
ASSERT_TRUE(cgeqrt != NULL) << "failed to get the Netlib LAPACKE_cgeqrt symbol";
cgeqrt_obj->inforef = cgeqrt( cgeqrt_obj->matrix_layout, cgeqrt_obj->m,
cgeqrt_obj->n,cgeqrt_obj->Aref,
cgeqrt_obj->lda, cgeqrt_obj->tauref);
/* Compute libflame's Lapacke o/p */
cgeqrt_obj->info = LAPACKE_cgeqrt( cgeqrt_obj->matrix_layout, cgeqrt_obj->m,
cgeqrt_obj->n,cgeqrt_obj->A,
cgeqrt_obj->lda, cgeqrt_obj->tau);
if( cgeqrt_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_cgeqrt is wrong\n", cgeqrt_obj->info );
}
if( cgeqrt_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_cgeqrt is wrong\n",
cgeqrt_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
cgeqrt_obj->diff = computeDiff_c( cgeqrt_obj->bufsize,
cgeqrt_obj->A, cgeqrt_obj->Aref );
}
TEST_F(cgeqrt_test, cgeqrt1) {
EXPECT_NEAR(0.0, cgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(cgeqrt_test, cgeqrt2) {
EXPECT_NEAR(0.0, cgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(cgeqrt_test, cgeqrt3) {
EXPECT_NEAR(0.0, cgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(cgeqrt_test, cgeqrt4) {
EXPECT_NEAR(0.0, cgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
/* Begin dcomplex_common_parameters class definition */
class geqrt_dcomplex_parameters{
public:
int bufsize;
void *hModule, *dModule;
double diff;
/*input parameters */
int matrix_layout;
lapack_int n;
lapack_int m;
lapack_int nb;
lapack_int ldt;
lapack_complex_double* A;
lapack_int lda;
/*Output Parameter*/
lapack_complex_double* tau;
lapack_complex_double *Aref, *tauref;
/*Return Values*/
lapack_int info, inforef;
public:
geqrt_dcomplex_parameters (int matrix_layout, lapack_int m , lapack_int n, lapack_int lda);
~geqrt_dcomplex_parameters ();
};
/* Constructor definition domplex_common_parameters */
geqrt_dcomplex_parameters:: geqrt_dcomplex_parameters (int matrix_layout_i, lapack_int m_i, lapack_int n_i, lapack_int lda_i)
{
int i;
matrix_layout = matrix_layout_i;
n = n_i;
m = m_i;
lda = lda_i;
#if LAPACKE_TEST_VERBOSE
printf(" \n geqrt dcomplex: m: %d, n: %d lda: %d \n", m, n, lda);
#endif
if (matrix_layout == LAPACK_COL_MAJOR)
bufsize = lda*n*sizeof(lapack_complex_double);
else if (matrix_layout == LAPACK_ROW_MAJOR)
bufsize = lda*m*sizeof(lapack_complex_double);
else
EXPECT_TRUE(false) << "matrix_layout invalid";
/*Memory allocation */
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair(&A, &Aref, bufsize);
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair(&tau, &tauref, (min(m,n)*sizeof(lapack_complex_double)));
if ((A==NULL) || (Aref==NULL) || \
(tau==NULL) || (tauref==NULL)){
EXPECT_FALSE( true) << "geqrt_float_parameters object: malloc error.";
geqrt_free();
exit(0);
}
/* Initialization of input matrices */
lapacke_gtest_init_dcomplex_buffer_pair_rand( A, Aref, bufsize);
/*initialize output matrix by 0 */
for(i=0;i<(min(m,n));i++) {
tau[i] = 0;
tauref[i] = tau[i];
}
} /* end of Constructor */
/* Destructor definition 'dcomplex_common_parameters' class */
geqrt_dcomplex_parameters :: ~geqrt_dcomplex_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" geqrt_dcomplex_parameters object: destructor invoked. \n");
#endif
/* De-Allocate memory for the input matrices */
geqrt_free();
}
/* Test fixture class definition */
class zgeqrt_test : public ::testing::Test {
public:
geqrt_dcomplex_parameters *zgeqrt_obj;
void SetUp();
void TearDown () { delete zgeqrt_obj; }
};
void zgeqrt_test::SetUp(){
/* LAPACKE zgeqrt prototype */
typedef int (*Fptr_NL_LAPACKE_zgeqrt) (int matrix_layout, lapack_int m,lapack_int n,
lapack_complex_double *A, lapack_int lda, lapack_complex_double* tau);
Fptr_NL_LAPACKE_zgeqrt zgeqrt;
zgeqrt_obj = new geqrt_dcomplex_parameters ( eig_paramslist[idx].matrix_layout,
eig_paramslist[idx].m,
eig_paramslist[idx].n,
eig_paramslist[idx].lda);
idx = Circular_Increment_Index(idx);
zgeqrt_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
zgeqrt_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(zgeqrt_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(zgeqrt_obj->hModule != NULL) << "Netlib lapacke handle NULL";
zgeqrt = (Fptr_NL_LAPACKE_zgeqrt)dlsym(zgeqrt_obj->hModule, "LAPACKE_zgeqrt");
ASSERT_TRUE(zgeqrt != NULL) << "failed to get the Netlib LAPACKE_zgeqrt symbol";
zgeqrt_obj->inforef = zgeqrt( zgeqrt_obj->matrix_layout, zgeqrt_obj->m,
zgeqrt_obj->n,zgeqrt_obj->Aref,
zgeqrt_obj->lda, zgeqrt_obj->tauref);
/* Compute libflame's Lapacke o/p */
zgeqrt_obj->info = LAPACKE_zgeqrt( zgeqrt_obj->matrix_layout, zgeqrt_obj->m,
zgeqrt_obj->n,zgeqrt_obj->A,
zgeqrt_obj->lda, zgeqrt_obj->tau);
if( zgeqrt_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame \
LAPACKE_zgeqrt is wrong\n", zgeqrt_obj->info );
}
if( zgeqrt_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_zgeqrt is wrong\n",
zgeqrt_obj->inforef );
}
/* Compute Difference between libflame and Netlib o/ps */
zgeqrt_obj->diff = computeDiff_z( zgeqrt_obj->bufsize,
zgeqrt_obj->A, zgeqrt_obj->Aref );
}
TEST_F(zgeqrt_test, zgeqrt1) {
EXPECT_NEAR(0.0, zgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zgeqrt_test, zgeqrt2) {
EXPECT_NEAR(0.0, zgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zgeqrt_test, zgeqrt3) {
EXPECT_NEAR(0.0, zgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zgeqrt_test, zgeqrt4) {
EXPECT_NEAR(0.0, zgeqrt_obj->diff, LAPACKE_GTEST_THRESHOLD);
}
| true |
115be3afb61c1d4c24558d08c5c856bfa8bc46e7 | C++ | AKGP/InterviewBit | /IB/dp/maxProduct.cpp | UTF-8 | 841 | 2.75 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
int maxProduct(vector<int> &A){
int dp[A.size()];
int m = A[0];
int curr_max = A[0];
int curr_min = A[0];
int prev_max = A[0];
int prev_min = A[0];
int ans = A[0];
for(int i =1;i<A.size();i++){
curr_max = max(prev_max*A[i],max(prev_min*A[i],A[i]));
curr_min = min(prev_min*A[i],min(A[i],prev_max*A[i]));
ans = max(ans,curr_max);
prev_max = curr_max;
prev_min = curr_min;
}
// for(int i =0;i<A.size();i++){
// cout<<dp[i]<<" ";
// }
return ans;
}
int main(){
int n;
cin>>n;
vector<int> A(n);
for(int i =0;i<n;i++){
cin>>A[i];
}
cout<<maxProduct(A);
return 0;
} | true |
4cf9d7c257787ad6e2b8fc6421e4a389bc5dd590 | C++ | gauravghati/Advance-Datastructure | /implement_of_stack/Stack.h | UTF-8 | 335 | 2.703125 | 3 | [] | no_license | /*
* Stack.h
*
* Created on: Dec 16, 2019
* Author: f10
*/
#ifndef STACK_H_
#define STACK_H_
template <class T>
class Node{
public:
T data;
Node * next;
};
template <class T>
class Stack{
Node<T> *top;
public:
Stack();
void push(T);
T pop();
T Top();
bool empty();
virtual ~Stack();
};
#endif /* STACK_H_ */
| true |
88d753f6fe23250573e8dc4a3de50d7dfad08c9d | C++ | tokbaev-a/auca-ds-2020 | /project-01/uva-10295/main.cpp | UTF-8 | 963 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Skill
{
string mName;
int mMoney;
Skill(string name, int money) : mName(name), mMoney(money)
{
}
};
int main()
{
int m, n;
cin >> m >> n;
vector<Skill> skills;
for (int i = 0; i < m; i++)
{
string s;
int num;
cin >> s >> num;
skills.emplace_back(s, num);
}
sort(begin(skills), end(skills), [](Skill s1, Skill s2) {
return s1.mName < s2.mName;
});
for (int i = 0; i < n; i++)
{
int points = 0;
for (string w; cin >> w && w != ".";)
{
auto p = lower_bound(begin(skills), end(skills), Skill(w, 0), [](const Skill &s1, const Skill &s2) {
return s1.mName < s2.mName;
});
if (p != end(skills) && (*p).mName == w)
{
points += (*p).mMoney;
}
}
cout << points << "\n";
}
} | true |
e53b0c79879a40c7a05682eccada14e63f59c1f2 | C++ | OsmanPL/EDD_1S2020_P1_201801229 | /[EDD]Practica1_201801229/[EDD]Practica1_201801229/ListaCiruclar.h | UTF-8 | 897 | 3.1875 | 3 | [] | no_license | #ifndef LISTACIRCULAR
#define LISTACIRCULAR
#include "Ruta.h"
#include <string.h>
#include <curses.h>
class ListaCircular {
private:
public:
Ruta* inicioLista;
Ruta* finalLista;
bool listaVacia() {
if (inicioLista == NULL || finalLista == NULL) {
return true;
}
else {
return false;
}
}
Ruta* retornarInicio() {
return inicioLista;
}
void agregarLista(string nuevaruta) {
Ruta* nueva = new Ruta();
nueva->setRuta(nuevaruta);
if (listaVacia())
{
nueva->setSiguiente(nueva);
inicioLista = nueva;
finalLista = nueva;
}
else {
nueva->setSiguiente(inicioLista);
finalLista->setSiguiente(nueva);
inicioLista = nueva;
}
}
void mostrar() {
Ruta* aux = inicioLista;
int i = 1;
if (aux!=NULL)
{
do
{
cout << "\n" << i << ". " << aux->getRuta();
aux = aux->getSiguiente();
} while (aux != inicioLista);
}
}
};
#endif
| true |
fb4f747eab17e94d8c635526a820b634bf86b860 | C++ | dhruvpatel348/C-Programming | /file-7.cpp | UTF-8 | 399 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
int main()
{
FILE *f1,*f2,*f3;
f1=fopen("D:\\1.txt","r");
f2=fopen("D:\\2.txt","r");
f3=fopen("D:\\3.txt","w");
char ch,ch1;
while(ch!=EOF)
{
ch = getc(f1);
putc(ch,f3);
}
while(ch1!=EOF)
{
ch1 = getc(f2);
putc(ch1,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
}
| true |
bb79540180df3e38a4fb2e33a76a639ec7b484a3 | C++ | ozcoco/AppFramework | /main.cpp | UTF-8 | 868 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <queue>
#include <algorithm>
#include <thread>
#include <chrono>
int main()
{
std::map<char, int> first;
first['a'] = 10;
first['b'] = 30;
first['c'] = 50;
first['d'] = 70;
for (auto &e: first)
{
std::cout << e.first << "=" << e.second << std::endl;
}
std::queue<std::string> qa;
qa.push("123");
qa.push("abc");
qa.push("!@#$");
qa.push("aaaa");
qa.push("sdsd");
qa.push("5675467");
for (auto &item = qa.front(); !qa.empty(); qa.pop(), item = qa.front())
{
std::cout << item << std::endl;
};
const auto &task = [](int arg) -> void
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "!!!!!!!!!!!!!!!!!" << std::endl;
};
std::thread t1(task, 1);
t1.join();
return 0;
} | true |
b7e4ac423d116bd40ac086cdafc7fa498141e110 | C++ | DionysiosB/CodeAbbey | /GreatestCommonDivisor.cpp | UTF-8 | 346 | 3.359375 | 3 | [] | no_license | #include <iostream>
long gcd (long a, long b){return (b == 0) ? a : gcd (b, a%b);}
int main(){
long t; std::cin >> t;
while(t--){
long x, y; std::cin >> x >> y;
long a = gcd(x, y);
long b = x * y / gcd(x, y);
std::cout << "(" << a << " " << b << ") ";
}
std::cout << std::endl;
return 0;
}
| true |
5bab699f940f7eb4fcc333a60da89bbf5e0b9758 | C++ | GermanAizek/felf | /app/ELF.h | UTF-8 | 2,503 | 2.546875 | 3 | [] | no_license | #pragma once
#include <elf.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <utility>
#include <string>
#include <cstdio>
#include <errno.h>
#include <string.h>
#define MAP_RW PROT_WRITE | PROT_READ
#define MAP_RO PROT_READ
#define MAP_EX PROT_READ | PROT_EXEC
struct SymbolData {
Elf64_Sym* symbol;
unsigned char* data;
uint64_t size;
};
struct SectionData {
Elf64_Shdr* section;
unsigned char* data;
uint64_t size;
};
struct SectionHeaderTable {
Elf64_Shdr* section_head;
uint16_t length;
uint16_t size;
std::vector<Elf64_Shdr*> sectionArray;
std::unordered_map<std::string , Elf64_Shdr*> sectionsMapped;
std::unordered_map<std::string , Elf64_Shdr*>::iterator sectionsMappedIter;
std::unordered_map<std::string, SectionData*> sectionData;
std::unordered_map<std::string , SectionData*>::iterator sectionDatIter;
};
struct SymbolTable {
Elf64_Sym* symbol_head;
Elf64_Shdr* section;
uint16_t size;
uint16_t length;
std::unordered_map<std::string , Elf64_Sym*> symbolsMapped;
std::unordered_map<std::string , Elf64_Sym*>::iterator symbolsMappedIter;
std::unordered_map<std::string, SymbolData*> symbolDataMapped;
std::unordered_map<std::string , SymbolData*>::iterator symbolDataMappedIter;
};
struct ProgramHeaderTable {
Elf64_Phdr* program_head;
uint16_t size;
uint16_t length;
std::vector<Elf64_Phdr*> phrVector;
};
class ELF {
public:
ELF(const std::string& fPath, int mode = MAP_RO);
~ELF();
bool valid() const { return this->validELF; };
void displayHeader() const;
bool save(const std::string& output) const;
void incFileSize(uint value);
void decFileSize(uint value);
inline int getFileSize() const { return this->fileSize; }
private:
void* map_file(const std::string& file, int mode);
void build_quick_elf();
Elf64_Section* getSectionByIndex(int index) const;
std::string getNameFromStringTable(uint64_t index) const;
std::string getNameFromSymbolStringTable(uint64_t index) const;
private:
bool validELF;
void* mappedFile;
off_t fileSize;
#if __BYTE_ORDER == __ORDER_LITTLE_ENDIAN__
uint32_t elf_magic = 0x464c457f;
#else
uint32_t elf_magic = 0x7f454c46;
#endif
public:
// Elf structs
Elf64_Ehdr* elfHeader;
Elf64_Shdr* stringSectionHdr;
Elf64_Shdr* stringSymbolTable;
SectionHeaderTable elfSection;
SymbolTable symbolTable;
ProgramHeaderTable phrTable;
};
| true |
b73a7af9f4fee00573bd4282a1b0671ae47348d8 | C++ | Hou-vst/read-data | /test/源.cpp | GB18030 | 2,686 | 2.875 | 3 | [] | no_license | #include<string>
#include<iostream>
#include<fstream>
#include<vector>
#include<map>
#include<set>
#include"usercf.h"
using namespace std;
void dealStrTemp(const string& temp,int& result1,int& result2)
{
int i_start = 0;
int size = static_cast<int>(temp.size());
int find_num = 0;
for (int i = 0; i < size && find_num<2; i++)
{
if (temp[i] == ':' && i+1<size && temp[i+1] == ':')
{
int t = atoi(temp.substr(i_start,i-i_start).c_str());
i_start = i + 2;
find_num++;
if (find_num == 1)
{
result1 = t;
}
else if (find_num == 2)
{
result2 = t;
}
}
}
}
void testUserCF(map<int, set<int>>& user_to_item,map<int, map<int, float>>& result)
{
// û-Ʒ ת Ʒ-û ű
map<int, set<int>> item_to_user;
TransferTo_ItemToUser(user_to_item, item_to_user);
// ݵűϡ
map<int, map<int, int>> CoRated_table;
Create_CoRated_table(item_to_user, CoRated_table);
// ûû֮ƶ
Calculate_Similarity(CoRated_table, user_to_item, result);
//
//PrintResult(result);
}
int main()
{
string path = "ratings.dat";
ifstream fin(path.c_str(), std::ios::binary);
if (!fin)
{
return - 1;
}
//seekgǶļλһƫڶǻַ
//tellgҪصǰλָλãҲĴС
std::streamsize size = fin.seekg(0, std::ios::end).tellg();
char* buff = (char*)malloc(size);
fin.seekg(0, std::ios::beg).read(&buff[0], size);
string str_buff = buff;
free(buff);
buff = NULL;
// userid movieid rating timestamp
map<int, set<int>> user_to_item;
int str_size = static_cast<int>(str_buff.size());
int start = 0;
bool skip = false;
int count = 0;
for (int i = 0; i < str_size; i++)
{
if (str_buff[i] == '\n')
{
string&& temp = str_buff.substr(start, i - start + 1);
start = i + 1;
i = i + 10;
/* if (!skip)
{
skip = true;
continue;
}*/
int result1 = 0;
int result2 = 0;
dealStrTemp(temp,result1,result2);
//13.301s
user_to_item[result1].insert(result2);
//13.897s
/*map<int, set<int>>::iterator iter= user_to_item.find(result1);
if (iter != user_to_item.end())
{
iter->second.insert(result2);
}
else
{
set<int> set_temp;
set_temp.insert(result2);
user_to_item.insert(pair<int, set<int>>(result1, set_temp));
}*/
count++;
if (count % 10000 == 0)
{
cout << count << endl;
}
}
}
//usercf
map<int, map<int, float>> result;
testUserCF(user_to_item, result);
return 0;
} | true |
4355441f64e7b6d56a932f741fb77cc7252db44b | C++ | SebastianJM/Competitive-Programming | /UVa Online Judge/UVA 1174 - IP-TV.cc | UTF-8 | 1,526 | 2.796875 | 3 | [] | no_license |
#include <iostream>
#include <math.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <string>
#include <map>
using namespace std;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
vi pset;
int numSets;
int n;
void init(int n)
{
pset = vi(n); for (int i = 0; i < n; i++) pset[i] = i;
}
int findSet(int i)
{
return (pset[i] == i) ? i : (pset[i] = findSet(pset[i]));
}
void unionSet(int i, int j) { pset[findSet(i)] = findSet(j); }
bool isSameSet(int i, int j) { return findSet(i) == findSet(j); }
priority_queue<iii> edges;
ii mst(int n)
{
int mstSize = 0;
int mstCost = 0;
init(n);
while (!edges.empty() && mstSize < n - 1)
{
iii edge = edges.top();
edges.pop();
int x = edge.second.first;
int y = edge.second.second;
int w = abs(edge.first);
if (!isSameSet(x, y))
{
unionSet(x, y);
mstSize++;
mstCost += w;
}
}
return ii(mstSize, mstCost);
}
int main()
{
map<string,int> mapa;
int m,q;
string s,t;
int j;
cin >> q;
while (q--)
{
getchar();
cin >> n >> m;
int x = 0, a1, a2;
while (!edges.empty())
edges.pop();
for (int i = 0; i < m; i++)
{
cin >> s >> t >> j;
if (mapa.find(s) == mapa.end())
{
mapa[s] = x; a1 = x; x++;
}
else
a1 = mapa[s];
if (mapa.find(t) == mapa.end())
{
mapa[t] = x; a2 = x; x++;
}
else
a2 = mapa[t];
edges.push(iii(-j, ii(a1, a2)));
}
ii ans = mst(n);
cout << ans.second << endl;
if (q >= 1)
cout << endl;
}
return 0;
}
| true |
5337e2778600918a275799711577d19d5f6a42fc | C++ | TheCharmingSociopath/JetpackJoyride | /src/fireline.cpp | UTF-8 | 2,099 | 3.21875 | 3 | [
"MIT"
] | permissive | #include "fireline.h"
#include "main.h"
#define GLM_ENABLE_EXPERIMENTAL
Fireline::Fireline(float x, float y, color_t color, float rot) {
this->position = glm::vec3(x, y, 0);
this->rotation = rot;
this->direction = true;
// Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
// A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
static const GLfloat vertex_buffer_data[] = {
3.0f, 0.2f, 0.0f, // triangle 1 : begin
3.0f, -0.2f, 0.0f,
-3.0f, 0.2f, 0.0f, // triangle 1 : end
3.0f,-0.2f,0.0f, // triangle 2 : begin
-3.0f,0.2f,0.0f,
-3.0f,-0.2f,0.0f, // triangle 2 : end
};
static const GLfloat vertex_buffer_data1[] = {
3.0f, 0.3f, 0.0f,
3.5f, 0.3f, 0.0f,
3.5f, -0.3f, 0.0f,
3.0f, 0.3f, 0.0f,
3.5f, -0.3f, 0.0f,
3.0f, -0.3f, 0.0f,
-3.0f, 0.3f, 0.0f,
-3.5f, 0.3f, 0.0f,
-3.5f, -0.3f, 0.0f,
-3.0f, 0.3f, 0.0f,
-3.5f, -0.3f, 0.0f,
-3.0f, -0.3f, 0.0f,
};
this->object[0] = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, COLOR_LAZER, GL_FILL);
this->object[1] = create3DObject(GL_TRIANGLES, 12, vertex_buffer_data1, COLOR_LAZER_EDGE, GL_FILL);
}
void Fireline::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
// No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate
// rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object[0]);
draw3DObject(this->object[1]);
}
void Fireline::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
void Fireline::tick() {
// STATIC
}
| true |
d9b84ab7cd6b8a50e65fa21912f6196232f9c8c8 | C++ | mcgoughc/220Project | /Person.cpp | UTF-8 | 1,499 | 3.328125 | 3 | [] | no_license | /*
* Person.cpp
* Comp 220 Bookstore Project
* Written by Joe Cleveland, Chase McGough, and Anthony Pizzo
* This file is the method definitions of the Person class
*/
#include "Person.h"
Person::Person(std::string first, std::string last, std::string phoneNumberIn, std::string emailIn, int commMethodIN) {
name = first + " " + last;
phoneNumber = phoneNumberIn;
email = emailIn;
commMethod = commMethodIN;
}
void Person::setName(std::string first, std::string last) {
name = first + " " + last;
}
void Person::setPhoneNumber(std::string number) {
phoneNumber = number;
}
void Person::setEmail(std::string email) {
this->email = email;
}
void Person::setCommMethod(int commMethod) {
if (commMethod > 3 or commMethod < 1) {
throw std::out_of_range("Invalid Value for person's comm method");
}
this->commMethod = commMethod;
}
std::string Person::getName() {
return this->name;
}
std::string Person::getPhoneNumber() {
return this->phoneNumber;
}
std::string Person::getEmail() {
return this->email;
}
std::string Person::getCommMethod() {
switch(commMethod){
case PHONE_CALL:
return "Phone Call";
case SEND_TEXT:
return "Send Text";
case SEND_EMAIL:
return "Send Email";
default:
return "None";
}
}
std::string Person::toString() {
std::string result = name +
"\n" + phoneNumber +
"\n" + email +
"\n" + getCommMethod();
return result;
}
| true |
2693cd76b9b49ee711d2268eca4509a52862a6d6 | C++ | Live4dreamCH/AI_Searchs | /BFsearch.h | GB18030 | 2,509 | 2.765625 | 3 | [] | no_license | #pragma once
#include "GeneralSearch.h"
#include <list>
#include <iostream>
//#include "NineState_new.h"
//
template<class S, class Code>
class BFsearch : public GeneralSearch<S, std::list<S*>, Code>
{
public:
BFsearch(S start, S target) :GeneralSearch<S, std::list<S*>, Code>(start, target) {}
//openеĵһڵopenתƵclose,
//Ϊn, (S::setNum)
//Snָ
void open2close() override {
this->Sn = this->open.front();
this->open.pop_front();
this->Sn->setNum(this->n);
this->close[this->Sn->getCode()] = this->Sn;
this->n++;
//std::cout << "open--\n";
//this->Sn->print();
}
//M,
//չǰSnڵ, ݲȵĽһ(S::generate, S::isAncestor)
//G,newһ, Snchild,M,G,delϵ(S::operator <),MΪfalse
//, Snchild, M, MΪtrue
//(ȵ)ӽڵʱ, true
bool generate() override {
this->M.clear();
return this->Sn->generate(this->M, this->graph, &(this->target));
}
//M
//G,Ͳκβ;G,setParentҼopen
bool changeM() override {
//std::cout << "open++\n";
for (auto it = this->M.begin(); it != this->M.end(); it++) {
if (!(*it).second) {
(*it).first->setParent(this->Sn);
//this->open.remove(*it);
this->open.push_back((*it).first);
}
//(*it)->print();
}
return false;
}
//open
void sortOpen() override {}
//ȫ,trueʾҵ,ʧ
//ɹ, ·ϴʼĿĽڵ˳дstates(β)
bool search(std::stack<S*>& states) override {
auto it = this->graph.insert({ this->start.getCode(),this->start }).first;
this->open.push_front(&(it->second));
while (true) {
//std::cout << "-----------------------------------\n";
if (this->open.empty()) {
//this->Sn->print();
return false;
}
//for (auto it = this->graph.begin(); it != this->graph.end(); it++) {
// it->second.print();
//}
//std::cout << "open = " << this->open.size() << '\n';
//std::cout << "graph = " << this->graph.size() << '\n';
this->open2close();
if (this->Sn->getCode() == this->target.getCode()) {
S* curr = this->Sn;
while (curr != NULL)
{
states.push(curr);
curr = curr->getParent();
}
return true;
}
if (this->generate()) {
if (this->changeM())
this->sortOpen();
}
}
}
};
| true |
99415566cc02153800a1146dec7a42fe95a8da0c | C++ | evancheng1006/dsa2016_038 | /hw5/queryProcess.cpp | UTF-8 | 3,485 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cctype>
#include <algorithm>
#include <string>
#include <vector>
#include "database.h"
void generateConfusionSetSingleWord(const std::string & str, std::vector<std::string> & result) {
result.clear();
result.push_back(str);
unsigned int len = str.length();
std::string tmp;
// Insert
for (unsigned int insertPlace = 0; insertPlace <= len; insertPlace++) {
for (char insertChar = 'a'; insertChar <= 'z'; insertChar++) {
tmp.clear();
for (unsigned int i = 0; i < insertPlace; i++) {
tmp.push_back(str[i]);
}
tmp.push_back(insertChar);
for (unsigned int i = insertPlace; i < len; i++) {
tmp.push_back(str[i]);
}
result.push_back(tmp);
}
}
// Delete
if (len > 0) {
for (unsigned int deletePlace = 0; deletePlace < len; deletePlace++) {
tmp.clear();
for (unsigned int i = 0; i < len; i++) {
if (i != deletePlace) {
tmp.push_back(str[i]);
}
}
result.push_back(tmp);
}
}
// Subsitute
for (unsigned int substitudePlace = 0; substitudePlace < len; substitudePlace++) {
for (char substitudeChar = 'a'; substitudeChar <= 'z'; substitudeChar++) {
tmp = str;
tmp[substitudePlace] = substitudeChar;
result.push_back(tmp);
}
}
// Transpose
if (len > 1) {
for (unsigned int transPlace = 1; transPlace < len; transPlace++) {
tmp = str;
char tmpChar;
tmpChar = tmp[transPlace];
tmp[transPlace] = tmp[transPlace - 1];
tmp[transPlace - 1] = tmpChar;
result.push_back(tmp);
}
}
}
void generateConfusionSetWithDuplication(const std::string & str, int distance, std::vector<std::string> & result) {
result.clear();
result.push_back(str);
for (int i = 0; i < distance; i++) {
unsigned int currentSize = result.size();
std::vector<std::string> tmp;
for (unsigned int j = 0; j < currentSize; j++) {
generateConfusionSetSingleWord(result[j], tmp);
// add result
result.insert(result.end(), tmp.begin(), tmp.end());
}
}
}
void QueryProcess(std::istream & input, DATABASE & db, std::ostream & output) {
std::string buffer;
std::string word;
std::string originalWord;
while (std::getline(input, buffer)) {
word.clear();
originalWord.clear();
unsigned int len = buffer.length();
// get first word
for (unsigned int i = 0; i < len; i++) {
if (!isblank(buffer[i])) {
originalWord.push_back(buffer[i]);
// word.push_back(tolower(buffer[i]));
word.push_back(buffer[i]);
} else {
i = len; //end loop
}
}
std::cout << originalWord << " ==>";
if (db.exist(word)) {
std::cout << " OK\n";
} else {
// generate confusion set if not OK
// this operation does not remove duplication
std::vector<std::string> confusion;
generateConfusionSetWithDuplication(word, 2, confusion);
std::vector<std::string> outWord;
for (unsigned int i = 0; i < confusion.size(); i++) {
if (db.exist(confusion[i])) {
outWord.push_back(confusion[i]);
}
}
if (outWord.empty()) {
std::cout << " NONE\n";
} else {
sort(outWord.begin(), outWord.end());
unsigned int currentEnd = 0;
std::string prev = outWord[0];
for (unsigned int i = 1; i < outWord.size(); i++) {
if (outWord[i] != prev) {
currentEnd++;
outWord[currentEnd] = outWord[i];
prev = outWord[i];
}
}
outWord.resize(currentEnd + 1);
for (unsigned int i = 0; i <= currentEnd; i++) {
std::cout << ' ' << outWord[i];
}
std::cout << "\n";
}
}
}
return;
}
| true |
9757fbdc3e9bc4af57af3a57342c4be8dad1f922 | C++ | akashrautela/p3 | /Class Work (13-6-19)/loop_in_a-LL.cpp | UTF-8 | 763 | 3.609375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
};
string isloop(node *h)
{
node *p1=h,*p2=h;
if(h == NULL) return "empty list";
while(p2!=NULL && p2->next!=NULL)
{
if(p1 == p2) return "LOOP EXITS";
p1 = p1->next;
p2 = p2->next->next;
}
return "NO LOOP";
}
int main()
{
node *head = NULL;
node *n1 = new node();
n1->data = 10;
node *n2 = new node();
node *n3 = new node();
node *n4 = new node();
node *n5 = new node();
n1->next =n2;
head = n1;
n2->data = 20;
n2->next = n3;
n3->data = 30;
n3->next = n4;
n4->data = 40;
n4->next = n5;
n5->data = 50;
n5->next = n3;
cout<<isloop(head);
return 0;
}
| true |
9a2230edd4c1df1cddcc17ad125606c4c0ac002a | C++ | MatanelAbayof/Robbery-in-the-Depths | /oop2_project/LifeView.cpp | UTF-8 | 1,764 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | #include "LifeView.h"
LifeView::LifeView(sf::RenderWindow& window, int numOfLife)
: HorizontalLayout(window)
{
init();
if (numOfLife > Character::getMaxLife()) {
throw(std::out_of_range("Cant have more life then " + Character::getMaxLife()));
}
setNumOfLife(numOfLife);
}
void LifeView::updateLifeParts(int numOfLife)
{
float lifeMissingPrecent, lifeLeftPrecent;
lifeMissingPrecent = lifeLeftPrecent = static_cast<float>(numOfLife);
lifeLeftPrecent /= Character::getMaxLife();
lifeMissingPrecent = (Character::getMaxLife() - lifeMissingPrecent) / Character::getMaxLife();
this->setRelativeWidth(0, lifeLeftPrecent);
this->setRelativeWidth(1, lifeMissingPrecent);
if (lifeLeftPrecent > lifeMissingPrecent) {
m_barFullPart->getBackground().setColor(sf::Color(int(255.f * lifeMissingPrecent * 2.f), 255, 0));
}
else {
m_barFullPart->getBackground().setColor(sf::Color(255, int(255.f * lifeLeftPrecent * 2.f), 0));
}
}
void LifeView::setNumOfLife(int numOfLife)
{
checkLegalLife(numOfLife);
if (numOfLife <= Character::getMaxLife()) {
m_numOfLife = numOfLife;
updateLifeParts(numOfLife);
}
}
string LifeView::toString() const
{
return "LifeView: { " + HorizontalLayout::toString() + " }";
}
void LifeView::checkLegalLife(int numOfLife) const
{
if (numOfLife < 0)
throw std::out_of_range("Number of life (=" + std::to_string(numOfLife) + ") is illegal");
}
void LifeView::init()
{
getBorder().setColor(sf::Color::Black);
m_barFullPart = std::make_shared<GUI::ImageView>(getWindow());
m_barFullPart->getBackground().setColor(sf::Color::Green);
addView(m_barFullPart);
m_barEmptyPart = std::make_shared<GUI::ImageView>(getWindow());
m_barEmptyPart->getBackground().setColor(sf::Color(100,100,100));
addView(m_barEmptyPart);
}
| true |
af874ef6bdfde901c08dc7842df998d49b313542 | C++ | luoshaochuan/hihocoder | /solutions/1041.cpp | UTF-8 | 1,902 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
using namespace std;
map<int,set<int>> dict;
map<int,pair<int,int>> fdict;
vector<int> visit;
void dict2tree(int currnode,int fathernode = 0,int height = 1){
if(fathernode != 0) fdict[currnode] = make_pair(fathernode,height);
for(auto ch:dict[currnode]){
if(ch == fathernode) dict[currnode].erase(ch);
else dict2tree(ch,currnode,height+1);
}
}
bool solve(){
set<int> rec;
for(int i=visit.size()-1;i>=0;i--){
int node = visit[i];
while(node != 1){
if(rec.find(node) != rec.end()) return false;
node = fdict[node].first;
}
rec.insert(visit[i]);
}
int maxheight = 0;
for(int i=0;i<visit.size();i++) maxheight = max(maxheight,fdict[visit[i]].second);
for(int j=maxheight;j>0;j--){
set<int> recmap;
for(int k=0;k<visit.size();k++){
if(fdict[visit[k]].second == j){
visit[k] = fdict[visit[k]].first;
}
if(recmap.size() == 0 || visit[k] != visit[k-1]){
if(recmap.find(visit[k]) != recmap.end()) return false;
else recmap.insert(visit[k]);
}
}
}
return true;
}
int main(){
//freopen("../input.txt","r",stdin);
int t,m,n,v;
set<int> tmp;
cin>>t;
for(int i=0;i<t;i++){
cin>>n;
dict.clear(),visit.clear();
for(int j=0;j<n-1;j++){
int n1,n2;
cin>>n1>>n2;
if(dict.find(n1) == dict.end()) dict[n1] = tmp;
if(dict.find(n2) == dict.end()) dict[n2] = tmp;
dict[n1].insert(n2),dict[n2].insert(n1);
}
dict2tree(1);
cin>>m;
for(int k=0;k<m;k++) cin>>v,visit.push_back(v);
bool res = solve();
cout<<(res?"YES":"NO")<<endl;
}
return 0;
}
| true |
4aec46330b71ed74df6e469277ae0071fe3df6bd | C++ | wolf-git-creator/cpp | /visitor/visitor-test.cc | UTF-8 | 843 | 2.953125 | 3 | [] | no_license | #include <cassert>
#include <iostream>
#include "builder.hh"
#include "compute-visitor.hh"
void test(const std::string& input, int expected, bool div_zero = false)
{
auto builder = Builder(input);
auto t = builder.build();
auto e = visitor::ComputeVisitor();
try
{
t->accept(e);
}
catch (std::overflow_error& e)
{
assert(div_zero);
}
assert(e.value_get() == expected);
}
int main()
{
test("+ 4 32", 36);
test("+ - 4 32 3", -25);
test("+ 432 / 23 2", 443);
test("- 3 -2", 5);
test("* 32 / 89 + 34 -384", 0);
test("/ + * 2 5 -54 0", 0, true);
test("* 32 / 89 + 34 -34", 0, true);
test("- / + / * * 2 3 4 2 321 -65 42", -47);
test("+ / * - - * 32 -567 -22 785 -44 322 12", 2595);
test("- 432 * 4364 / -7422 + 22 21", 751040);
return 0;
}
| true |
ee3d558a6749ca4de37f45950107216c8ab65ce4 | C++ | Connor-A/Chess_WIP | /piece.h | UTF-8 | 1,203 | 3.421875 | 3 | [] | no_license | /****************************************************************************************************************
This is the parent class for all the pieces of the chess board. It will be usre in a two
dimensional array to simulate the board, and the pieces will be saved by passing them into the board array
via polymorphism.
*****************************************************************************************************************/
#include <string>
class piece
{
protected:
bool team; // black == 0 white == 1
bool has_moved;
//bool color; //Color of the space black == 0, white == 1
std::string type;
public:
piece(); //piece constructor
virtual bool is_legal(std::string move){return false;} //checks the legality of the move
void make_move(std::string move); //makes the move, and changes the board state
std::string get_type(){return type;}
bool get_team(){return team;}
void set_type(std::string new_type){type = new_type; return;}
//legal_moves(); A function that detects available moves for a piece
//guardian(); returns pieces that are protected by this piece
//damsel(); returns pieces that protect this piece. This may be inefficient.
}; | true |
189f9fe0797819f3b74f835ebae7add9be5e77b2 | C++ | ashayaan/codeforces | /countereg.cpp | UTF-8 | 756 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
long long int gcd(long long int a,long long int b){
if(b){
return gcd(b,a%b);
}
else
return a;
}
int main(){
long long int l,r;
cin>>l>>r;
if(abs(l-r) < 2){
cout<<"-1"<<endl;
return 0;
}
long long int i=0,j=0,k=0;
long long int ans1=0,ans2=0,ans3=0;
bool a=false;
for(i=l;i<=r;i+=1){
//cout<<i<<endl;
for(j=i+1;j<=r;j+=1){
if(gcd(i,j) == 1){
for(k=j+1;j<r;j+=1){
if(gcd(j,k) == 1 and gcd(i,k)!=1){
//cout<<i<<j<<k<<endl;
a=true;
break;
}
}
}
if(a==true)
break;
}
if(a==true)
break;
}
if(a ==true)
cout<<i<<" "<<j<<" "<<k<<endl;
else
cout<<"-1"<<endl;
return 0;
}
| true |
2ff053645e9c08405522b1b1f6cd58052df44f03 | C++ | searleser97/DistribuitedSystems | /ConstructoresYParametros/Ej1.cpp | UTF-8 | 1,189 | 3.421875 | 3 | [] | no_license | #include "Fecha.h"
#include <ctime>
#include <iostream>
using namespace std;
int random(int min, int max) { return min + rand() % (max - min + 1); }
int masVieja(Fecha &fecha1, Fecha &fecha2) {
if (fecha1.convierte() > fecha2.convierte()) return 1;
if (fecha1.convierte() < fecha2.convierte()) return -1;
return 0;
}
int main() {
Fecha f(1, 12, 2019);
Fecha ff(31, 12, 2019);
for (int i = 0; i < 100000; i++) {
f.inicializaFecha(random(1, 31), random(1, 12), random(2000, 2019));
ff.inicializaFecha(random(1, 31), random(1, 12), random(2000, 2019));
masVieja(f, ff);
}
return 0;
}
// int masVieja(Fecha *fecha1, Fecha *fecha2) {
// if (fecha1->convierte() > fecha2->convierte())
// return 1;
// if (fecha1->convierte() < fecha2->convierte())
// return -1;
// return 0;
// }
// int main() {
// srand(time(0));
// Fecha *f = new Fecha(1, 12, 2019);
// Fecha *ff = new Fecha(31, 12, 2019);
// for (int i = 0; i < 10000000; i++) {
// f->inicializaFecha(random(1, 31), random(1, 12), random(2000, 2019));
// ff->inicializaFecha(random(1, 31), random(1, 12), random(2000, 2019));
// masVieja(f, ff);
// }
// return 0;
// } | true |
4b650200a88118d4523bf0701e86cee6af2cd12b | C++ | njshah301/it-lab | /nj.cpp | UTF-8 | 223 | 3.046875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class complex{
public:
int x,y;
complex(int x1,int y1){
x=x1;
y=y1;
}
int getX(){
return x;}
int gety(){
return y;}
};
int main(){
complex p(10,20);
cout<<p.x<<p.y;
return 0;
}
| true |
e680232d5cacc6a614643685b519a17e70592877 | C++ | ramonjunquera/GlobalEnvironment | /RPi/Geany/02 cpp/09 FilesIO/03 Array/Array.cpp | UTF-8 | 2,544 | 3.90625 | 4 | [] | no_license | /*
* Autor: Ramón Junquera
* Tema: Programación en C++
* Objetivo: Archivos binarios
* Material: Raspberry Pi
* Descripción:
* Para gestionar archivos binarios tenemos suficiente con las funciones
* proporcionadas por la librería iostream.
*
* En este ejercicio crearemos un array dinámico de números enteros con
* tantos elementos como se nos indique en la variable itemsCountOut.
* Lo llenaremos con números consecutivos comenzando con el 0.
* Crearemos un archivo binario.
* Guardaremos el número de elementos del array.
* Guardaremos a continuación el array completo y cerraremos el archivo.
*
* Abriremos al archivo, leeremos el número de elementos del array.
* Crearemos un nuevo array dinámico. Leeremos su contenido del archivo.
* Finalmente mostraremos su contenido en pantalla.
*/
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
//Variable que contiene el número de elementos del array a escribir
int itemsCountOut = 14;
//Creamos un array dinámico del tamaño indicado
//No le añadimos () al final porque no necesitamos que lo inicialice
//con ceros. Lo llenaremos nosotros
int *itemsOut = new int[itemsCountOut];
//Llenamos el array con números consecutivos desde el 0
for(int i=0;i<itemsCountOut;i++) itemsOut[i]=i;
//Creamos el archivo de salida
FILE *fileWrite = fopen("array.bin","wb");
//Escribimos el número de elementos del array
fwrite(&itemsCountOut,sizeof(int),1,fileWrite);
//Escribimos el array
//Es de numeros enteros
//Indicamos el número de elementos
fwrite(itemsOut,sizeof(int),itemsCountOut,fileWrite);
//Cerramos el archivo
fclose(fileWrite);
//Ya no necesitamos el array. Liberamos su memoria
delete[] itemsOut;
//Variable que contiene el número de elementos del array leido
int itemsCountIn;
//Abrimos el archivo como lectura
FILE *fileRead = fopen("array.bin","rb");
//Si hubo alg'ún problema...
if(!fileRead)
{
cout << "Problema al leer el archivo\n";
//Salimos con error
return 1;
}
//Leemos el número de elementos del array
fread(&itemsCountIn,sizeof(int),1,fileRead);
//Creamos un array dinámico
int *itemsIn = new int[itemsCountIn];
//Leemos el contenido del archivo al array
fread(itemsIn,sizeof(int),itemsCountIn,fileRead);
//Cerramos el archivo
fclose(fileRead);
//Mostramos el contenido del array
for(int i=0;i<itemsCountIn;i++) cout << itemsIn[i] << " ";
cout << endl;
//Ya no necesitamos el array. Liberamos su memoria
delete[] itemsIn;
//Todo ok
return 0;
}
| true |
54228361e79af96649d183fbcfb737de90e29408 | C++ | PauloFAragao/Jogo-de-Luta | /algoritimo para ataques de comando/Personagem.cpp | UTF-8 | 9,036 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "Personagem.h"
Personagem::Personagem(){}
Personagem::Personagem(int *ponteiro)
{
bts = ponteiro;
}
bool Personagem::controleGopes(int bt)
{
if(sequencia13()) return true;
else if(sequencia05()) return true;
else if(sequencia09()) return true;
else if(sequencia02()) return true;
else if(sequencia06()) return true;
else if(sequencia10()) return true;
else if(sequencia03()) return true;
else if(sequencia07()) return true;
else if(sequencia11()) return true;
else if(sequencia04()) return true;
else if(sequencia08()) return true;
else if(sequencia12()) return true;
else if(sequencia01()) return true;
return false;
}
//baixo + tras + soco fraco (A-u)
bool Personagem::sequencia01()
{
if( *(bts+ 8) - *(bts+18) > 20 && //a diferenca de tempo entre o bt0[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+ 8) < 150 && *(bts+19) - *(bts+ 8) > 0 && //a diferenca de tempo entre o bt1[solto] e bt0[pressionado] tem que ser menor que 120 e maior que 0
*(bts+48) - *(bts+ 8) < 150 && *(bts+48) - *(bts+ 8) > 0 //a diferenca de tempo entre o bt4[pressionado] e bt0[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + tras + soco forte (C-j)
bool Personagem::sequencia02()
{
if( *(bts+ 8) - *(bts+18) > 20 && //a diferenca de tempo entre o bt0[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+ 8) < 150 && *(bts+19) - *(bts+ 8) > 0 && //a diferenca de tempo entre o bt1[solto] e bt0[pressionado] tem que ser menor que 120 e maior que 0
*(bts+58) - *(bts+ 8) < 150 && *(bts+58) - *(bts+ 8) > 0 //a diferenca de tempo entre o bt5[pressionado] e bt0[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + tras + chute fraco (B-i)
bool Personagem::sequencia03()
{
if( *(bts+ 8) - *(bts+18) > 20 && //a diferenca de tempo entre o bt0[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+ 8) < 150 && *(bts+19) - *(bts+ 8) > 0 && //a diferenca de tempo entre o bt1[solto] e bt0[pressionado] tem que ser menor que 120 e maior que 0
*(bts+68) - *(bts+ 8) < 150 && *(bts+68) - *(bts+ 8) > 0 //a diferenca de tempo entre o bt6[pressionado] e bt0[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + tras + chute forte (D-k)
bool Personagem::sequencia04()
{
if( *(bts+ 8) - *(bts+18) > 20 && //a diferenca de tempo entre o bt0[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+ 8) < 150 && *(bts+19) - *(bts+ 8) > 0 && //a diferenca de tempo entre o bt1[solto] e bt0[pressionado] tem que ser menor que 120 e maior que 0
*(bts+78) - *(bts+ 8) < 150 && *(bts+78) - *(bts+ 8) > 0 //a diferenca de tempo entre o bt7[pressionado] e bt0[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + frente + chute forte (A-u)
bool Personagem::sequencia05()
{
if( *(bts+28) - *(bts+18) > 20 && //a diferenca de tempo entre o bt2[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+28) < 150 && *(bts+19) - *(bts+28) > 0 && //a diferenca de tempo entre o bt1[solto] e bt2[pressionado] tem que ser menor que 120 e maior que 0
*(bts+48) - *(bts+28) < 150 && *(bts+48) - *(bts+28) > 0 //a diferenca de tempo entre o bt4[pressionado] e bt2[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + frente + chute forte (C-j)
bool Personagem::sequencia06()
{
if( *(bts+28) - *(bts+18) > 20 && //a diferenca de tempo entre o bt2[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+28) < 150 && *(bts+19) - *(bts+28) > 0 && //a diferenca de tempo entre o bt1[solto] e bt2[pressionado] tem que ser menor que 120 e maior que 0
*(bts+58) - *(bts+28) < 150 && *(bts+58) - *(bts+28) > 0 //a diferenca de tempo entre o bt5[pressionado] e bt2[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + frente + chute forte (B-i)
bool Personagem::sequencia07()
{
if( *(bts+28) - *(bts+18) > 20 && //a diferenca de tempo entre o bt2[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+28) < 150 && *(bts+19) - *(bts+28) > 0 && //a diferenca de tempo entre o bt1[solto] e bt2[pressionado] tem que ser menor que 120 e maior que 0
*(bts+68) - *(bts+28) < 150 && *(bts+68) - *(bts+28) > 0 //a diferenca de tempo entre o bt6[pressionado] e bt2[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//baixo + frente + chute forte (D-k)
bool Personagem::sequencia08()
{
if( *(bts+28) - *(bts+18) > 20 && //a diferenca de tempo entre o bt2[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+19) - *(bts+28) < 150 && *(bts+19) - *(bts+28) > 0 && //a diferenca de tempo entre o bt1[solto] e bt2[pressionado] tem que ser menor que 120 e maior que 0
*(bts+78) - *(bts+28) < 150 && *(bts+78) - *(bts+28) > 0 //a diferenca de tempo entre o bt7[pressionado] e bt2[pressionado] tem que sem menor que 120 e maior que 0
)return true;
return false;
}
//(baixo segura) + cima + soco fraco
bool Personagem::sequencia09()
{
if( *(bts+19) - *(bts+18) > 150 && //a diferenca de tempo entre o bt1[solto] e o bt1[pressionado] tem que ser maior que 150
*(bts+39) - *(bts+19) < 150 && *(bts+39) - *(bts+19) > 0 && //a diferenca de tempo entre o bt3[pressionado] e bt1[pressionado] tem que ser menor que 120 e maior que 0
*(bts+48) - *(bts+38) < 150 && *(bts+49) - *(bts+38) > 0 //a diferenca de tempo entre o bt4[pressionado] e bt3[pressionado] tem que ser menor que 120 e maior que 0
) return true;
return false;
}
//(baixo segura) + cima + soco forte
bool Personagem::sequencia10()
{
if( *(bts+19) - *(bts+18) > 150 && //a diferenca de tempo entre o bt1[solto] e o bt1[pressionado] tem que ser maior que 150
*(bts+39) - *(bts+19) < 150 && *(bts+39) - *(bts+19) > 0 && //a diferenca de tempo entre o bt3[pressionado] e bt1[pressionado] tem que ser menor que 120 e maior que 0
*(bts+59) - *(bts+38) < 150 && *(bts+59) - *(bts+38) > 0 //a diferenca de tempo entre o bt5[pressionado] e bt3[pressionado] tem que ser menor que 120 e maior que 0
) return true;
return false;
}
//frente + baixo + frente + chute fraco
bool Personagem::sequencia11()
{
if( *(bts+18) - *(bts+29) < 150 && //a diferenca de tempo entre o bt1[pressionado] e o bt2[solto] tem que ser menor que 150
*(bts+28) - *(bts+18) < 150 && *(bts+39) - *(bts+19) > 20 && //a diferenca de tempo entre o bt2[pressionado] e bt1[pressionado] tem que ser menor que 150 e maior que 20
*(bts+48) - *(bts+28) < 150 && *(bts+48) - *(bts+28) > 0 //a diferenca de tempo entre o bt4[pressionado] e o bt2[pressionado] tem que ser menor que 150 e maior que 0
) return true;
return false;
}
//frente + baixo + frente + chute forte
bool Personagem::sequencia12()
{
if( *(bts+18) - *(bts+29) < 150 && //a diferenca de tempo entre o bt1[pressionado] e o bt2[solto] tem que ser menor que 150
*(bts+28) - *(bts+18) < 150 && *(bts+39) - *(bts+19) > 20 && //a diferenca de tempo entre o bt2[pressionado] e bt1[pressionado] tem que ser menor que 150 e maior que 20
*(bts+58) - *(bts+28) < 150 && *(bts+58) - *(bts+28) > 0 //a diferenca de tempo entre o bt4[pressionado] e o bt2[pressionado] tem que ser menor que 150 e maior que 0
) return true;
return false;
}
//baixo + traz + baixo + frente + soco fraco ou soco forte
bool Personagem::sequencia13()
{
if( *(bts+8 ) - *(bts+16) > 20 && //a diferenca de tempo entre o bt0[pressionado] e o bt1[pressionado] tem que ser maior que 20
*(bts+17) - *(bts+8 ) < 150 && *(bts+17) - *(bts+8 ) > 0 && //a diferenca de tempo entre o bt1[pressionado] e o bt0[solto] tem que ser menor que 150 e maior que 0
*(bts+18) - *(bts+17) < 150 && *(bts+18) - *(bts+17) > 0 && //a diferenca de tempo entre o bt1[pressionado] e o bt1[solto] tem que ser menor que 150 e maior que 0
*(bts+9 ) - *(bts+18) < 150 && *(bts+9 ) - *(bts+18) > 0 && //a diferenca de tempo entre o bt0[solto] e o bt1[pressionado] tem que ser menor que 150 e maior que 0
*(bts+28) - *(bts+9 ) < 150 && *(bts+28) - *(bts+9 ) > 0 && //a diferenca de tempo entre o bt2[pressionado] e o bt0[solto] tem que ser menor que 150 e maior que 0
( *(bts+48) - *(bts+28) < 150 && *(bts+48) - *(bts+28) > 0 || *(bts+58) - *(bts+28) < 150 && *(bts+58) - *(bts+28) > 0 ) &&
//a diferenca de tempo entre o bt4[pressionado] e o bt2[pressionado] tem que ser menor que 150 e maior que 0 ou
//a diferenca de tempo entre o bt5[pressionado] e o bt2[pressionado] tem que ser menor que 150 e maior que 0
( *(bts+48) - *(bts+58) <= 20 && *(bts+48) - *(bts+58) >= -20) //a diferenca de tempo entre o bt4[pressionado] e o bt5[pressionado] tem que estar entre 20 e -20
) return true;
return false;
}
| true |
0742583833c54b13e602b73aada2e77231f15f22 | C++ | totally-A/studentshelper | /IfElse.cpp | UTF-8 | 638 | 3.015625 | 3 | [] | no_license | //defines the entry point for the console application
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
system("color F0");
int input;
printf("1. Play a game\n");
printf("2. Load a game\n");
printf("3. Go to a multiplayer\n");
printf("4. Exit\n");
printf("Choice:\n");
scanf("%d", &input);
if (input == 1) printf("Starting a game...\n");
else if (input == 2) printf("Game is loading...\n");
else if (input == 3) printf("Going to a multiplayer...\n");
else if (input == 4) printf("Thank you for the game!");
else printf("Try again!");
system("pause");
} | true |
5a6bd8ffd9f222645ddece9c69c01f57a783234d | C++ | sushil-lakra/learning_in_depth | /rod_cutting.h | UTF-8 | 1,760 | 3 | 3 | [] | no_license | #pragma once
/*
60 100 120 200
1 2 3 4
len = 5
5 41 32 311 221 2111 11111
*/
int rcp(int p[], int l[], int n, int rl)
{
if (n <= 0 || rl == 0) return 0;
if (l[n - 1] > rl)
return rcp(p, l, n - 1, rl);
return std::max(
p[n - 1] + rcp(p, l, n, rl - l[n - 1]),
rcp(p, l, n - 1, rl));
}
int rcp(int p[], int l[], int n, int rl, int** aux)
{
if (n <= 0 || rl == 0) return 0;
if (aux[n][rl] != -1) return aux[n][rl];
if (l[n - 1] > rl)
aux[n][rl] = rcp(p, l, n - 1, rl, aux);
else
aux[n][rl] = std::max(
p[n - 1] + rcp(p, l, n, rl - l[n - 1], aux),
rcp(p, l, n - 1, rl, aux));
return aux[n][rl];
}
/*
0 1 2 3 4 5
0 0 0 0 0 0 0
6 1 0 6 12 18 24 30
10 2 0 6 12 18 24 30
12 3 0 6 12 18 24 30
20 4 0 6 12 18 24 30
*/
int rcp_itr(int p[], int l[], int n, int rl, int** aux)
{
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= rl; ++j)
{
if (l[i - 1] > j)
aux[i][j] = aux[i - 1][j];
else
aux[i][j] = std::max(
p[i - 1] + aux[i][j - l[i - 1]],
aux[i - 1][j]);
}
return aux[n][rl];
}
/*
int main()
{
int p[] = {60, 100, 120, 200};
int l[] = {1, 2, 3, 4};
int m = sizeof(p) / sizeof(p[0]);
int n = 5;
int** aux = new int*[m + 1];
for (int i = 0; i < m + 1; ++i)
aux[i] = new int[n + 1];
for (int i = 0; i < m + 1; ++i)
for (int j = 0; j < n + 1; ++j)
aux[i][j] = 0;
std::cout << rcp_itr(p, l, m, n, aux) << std::endl;
int stop;
std::cin >> stop;
}
*/
| true |
099b55b1b69e653b926e24986dd737caa4f43bf6 | C++ | dmikushin/Graduation-Work | /MPS_VOXAR/include/vnl/tests/test_na.cxx | UTF-8 | 4,545 | 2.78125 | 3 | [] | no_license | #include <vcl_iostream.h>
#include <vcl_iomanip.h>
#include <vcl_sstream.h>
#include <vcl_limits.h> // for infinity()
#include <vnl/vnl_math.h>
#include <vnl/vnl_na.h>
#include <testlib/testlib_test.h>
void test_na()
{
// Create NaN, NA
double qnan_d = vcl_numeric_limits<double>::quiet_NaN();
double na_d = vnl_na();
#define print_hex(p) \
vcl_hex<<vcl_setfill('0')<<vcl_setw(2)<<(short)reinterpret_cast<unsigned char*>(&p)[sizeof(p)-1]; \
for (unsigned int i=2; i<=sizeof(p); ++i) \
vcl_cout<<vcl_setfill('0')<<vcl_setw(2)<<(short)(reinterpret_cast<unsigned char*>(&p))[sizeof(p)-i]; \
vcl_cout<<vcl_dec
vcl_cout << "qnan_d = " << qnan_d << " = " << print_hex(qnan_d) << vcl_endl
<< "na_d = " << na_d << " = " << print_hex(na_d) << vcl_endl
<< vcl_endl;
TEST("isnan(NA)", vnl_math_isnan(vnl_na()), true);
TEST("isnan(NA2)", vnl_math_isnan(na_d), true);
TEST("isnan(1/NA2)", vnl_math_isnan(1.0/na_d), true);
TEST("isna(NA)", vnl_na_isna(vnl_na()), true);
TEST("isna(NA2)", vnl_na_isna(na_d), true);
TEST("isna(1/NA2)", vnl_na_isna(1.0/na_d), true);
TEST("!isfinite(NA)", !vnl_math_isfinite(na_d), true);
TEST("!isinf(NA)", !vnl_math_isinf(na_d), true);
TEST("!isna(0)", !vnl_na_isna(0), true);
TEST("!isna(-0)", !vnl_na_isna(-0), true);
TEST("!isna(-1.0)", !vnl_na_isna(-1.0), true);
TEST("!isna(inf)", !vnl_na_isna(vcl_numeric_limits<double>::infinity()), true);
TEST("!isna(NaN)", !vnl_na_isna(qnan_d), true);
{
double x=0.0;
vcl_istringstream ss("NA");
vnl_na_double_extract(ss, x);
TEST("x=\"NA\"", vnl_na_isna(x), true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0;
vcl_istringstream ss("NA ");
vnl_na_double_extract(ss, x);
TEST("x=\"NA \"", vnl_na_isna(x), true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0;
vcl_istringstream ss("1.0 ");
vnl_na_double_extract(ss, x);
TEST("x=\"1.0\"", x, 1.0);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("NA1.0");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"NA1.0\"", vnl_na_isna(x) && y==1.0, true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("1.0NA");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"1.0NA\"", vnl_na_isna(y) && x==1.0, true);
vcl_cout << "y = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("NANA");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"NANA\"", vnl_na_isna(x) && vnl_na_isna(y), true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("NA 1.0");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"NA 1.0\"", vnl_na_isna(x) && y==1.0, true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("1.0 NA");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"1.0 NA\"", vnl_na_isna(y) && x==1.0, true);
vcl_cout << "y = " << y << " = " << print_hex(y) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("NA NA");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"NA NA\"", vnl_na_isna(x) && vnl_na_isna(y), true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
double x=0.0, y=0.0;
vcl_istringstream ss("-1.0-1.0");
vnl_na_double_extract(ss, x);
vnl_na_double_extract(ss, y);
TEST("x,y=\"-1.0-1.0\"", x==-1.0 && y==-1.0, true);
vcl_cout << "x = " << x << " = " << print_hex(x) << vcl_endl;
}
{
vcl_ostringstream ss;
vnl_na_double_insert(ss, -1.5);
vnl_na_double_insert(ss, vnl_na());
TEST("output \"-1.5NA\"", ss.str(), "-1.5NA");
vcl_cout << "ss = " << ss.str() << vcl_endl;
}
{
vcl_stringstream ss;
ss << vnl_na_stream(-1.0) << ' ' << vnl_na_stream(vnl_na());
double x=0.0, y=0.0;
ss >> vnl_na_stream(x) >> vnl_na_stream(y);
TEST("x,y=\"-1.0 NA\"", vnl_na_isna(y) && x==-1.0, true);
vcl_cout << "y = " << y << " = " << print_hex(y) << vcl_endl;
vcl_cout << "ss = " << ss.str() << vcl_endl;
}
#undef print_hex
}
TESTMAIN(test_na);
| true |
3182fe73eb0075a7af783cd2b6499cd21a0c9250 | C++ | checkoutb/LeetCodeCCpp | /daily_challenge/2022/LT_2022-07-07_97._Interleaving_String.cpp | UTF-8 | 2,346 | 2.953125 | 3 | [] | no_license |
#include "../../header/myheader.h"
class LT
{
public:
// D D
//if (i == 0 && j == 0) dp[i][j] = 1;
//else if (i == 0) dp[i][j] = dp[i][j - 1] && s2[j - 1] == s3[i + j - 1];
//else if (j == 0) dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1];
//else dp[i][j] = ((dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) || (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]));
//if (i == 0 && j == 0)
// table[i][j] = true;
//else if (i == 0)
// table[i][j] = (table[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
//else if (j == 0)
// table[i][j] = (table[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
//else
// table[i][j] = (table[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (table[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
//Runtime: 0 ms, faster than 100.00 % of C++ online submissions for Interleaving String.
//Memory Usage : 6.7 MB, less than 66.40 % of C++ online submissions for Interleaving String.
// dp?
bool lta(string s1, string s2, string s3)
{
int sz1 = s1.size();
int sz2 = s2.size();
if (sz1 == 0)
return s3 == s2;
if (sz2 == 0)
return s1 == s3;
if (sz1 + sz2 != s3.size())
return false;
vector<vector<bool>> vvb(sz1 + 1, vector<bool>(sz2 + 1, false));
for (int i = 0; i < sz1; ++i)
{
if (s1[i] == s3[i])
vvb[i + 1][0] = true;
else
break;
}
for (int i = 0; i < sz2; ++i)
{
if (s2[i] == s3[i])
vvb[0][i + 1] = true;
else
break;
}
vvb[0][0] = true;
for (int i = 1; i <= sz1; ++i) // length
{
for (int j = 1; j <= sz2; ++j)
{
if (vvb[i - 1][j] && s3[i + j - 1] == s1[i - 1])
vvb[i][j] = true;
else
{
if (vvb[i][j - 1] && s3[i + j - 1] == s2[j - 1])
vvb[i][j] = true;
}
}
}
return vvb[sz1][sz2];
}
};
int main()
{
LT lt;
//string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac";
string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc";
cout << lt.lta(s1, s2, s3) << endl;
return 0;
}
| true |
5523222f2eb865d8e45ed8a6f2b058cf2623f1d2 | C++ | hakerg/Useful-Code | /Useful Code/State.h | UTF-8 | 479 | 3.25 | 3 | [] | no_license | #pragma once
namespace uc
{
// class used by AI
// contains information about some situation
// _Turn - turn; can be applied to the State
template <class _Turn>
class State
{
public:
State() {}
virtual ~State() {}
// set new state based on player's turn
virtual void apply_turn(const _Turn& turn) = 0;
// compare fitnesses
// returns true if state on the right is better for the player
virtual bool operator < (const State<_Turn>& rhs) const = 0;
};
} | true |
3c7a02a376c3ce4ee37318514f382a812dab6a71 | C++ | linghuiliu/CosmiTestLCIO | /calice_userlib/include/SimpleValueVector.hh | UTF-8 | 2,366 | 2.8125 | 3 | [] | no_license | #ifndef __SimpleValueVector_hh__
#define __SimpleValueVector_hh__
#include "IMPL/LCGenericObjectImpl.h"
#include "UTIL/LCFixedObject.h"
#include "EVENT/LCObject.h"
#include <vector>
namespace CALICE {
class SimpleValueVector : public IMPL::LCGenericObjectImpl {
public:
/** Empty constructor
*/
SimpleValueVector(){}
/** Constructor
*/
SimpleValueVector( const int id,
const unsigned int nMemo,
const std::vector<float> val,
const std::vector<float> err,
const std::vector<int> stat );
/** Constructor from LCObject
*/
SimpleValueVector( EVENT::LCObject* obj );
/** Destructor
*/
~SimpleValueVector(){}
/** Return index identifier
*/
int getCellID() const {
return getIntVal( 0 );
}
/** Return size array
*/
int getSize() const {
return getIntVal( 1 );
}
/** Return the value
*/
float getValue( const unsigned int i) const {
return getFloatVal( 2*i );
}
/** Return the error on the value
*/
float getError( const unsigned int i) const {
return getFloatVal( 2*i+1 );
}
/** Return the status
*/
int getStatus(const unsigned int i) const {
return getIntVal( i+2 );
}
/** set index identifier
*/
void setCellID(const int ID) {
setIntVal( 0, ID );
}
/** set size
*/
void setSize(const int size) {
setIntVal( 1, size );
}
/** set the value
*/
void setValue( const unsigned int i,
const float val ) { setFloatVal( 2*i, val ); }
/** set the error on the value
*/
void setError(const unsigned int i,
const float err ) { setFloatVal( 2*i+1, err ); }
/** set the status
*/
void setStatus(const unsigned int i,
const int stat ) { setIntVal( i+2, stat ); }
/** Implementation of LCGenericObject::getTypeName
*/
const std::string getTypeName() const {
return "SimpleValueVector";
}
/** Implementation of LCGenericObject::getDataDescription
*/
const std::string getDataDescription() const {
return "i:CellID, i:nMemo, f:value[nMemo],f:error[nMem],i:status[nMemo]";
}
protected:
private:
}; // classs SimpleValueVector
} // namespace CALICE
#endif // __SimpleValueVector_hh__
| true |
b5648d3181ca3dd3d543bcdb2c0864989758f4c9 | C++ | ArtemVasilev/P-AA | /Khanova_Yulya/lab1/lr1.cpp | UTF-8 | 4,066 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Point{
int x;
int y;
int len; //сторона квадрата
};
class Square{
public:
Square(int k)
{
arr = new int[(k + 1)*(k + 1)]();
this->num = 0;
this->k = k;
}
~Square()
{
delete[] arr;
}
void Insert(int x, int y, int k)
{
for (int i = 0; i < k; i++)
for (int j = 0; j < k; j++)
arr[(i + y)*this->k + (j + x)] = k;
num++;
}
void Insert(int x, int y, int k, Point &len)
{
for (int i = 0; i < k; i++)
for (int j = 0; j < k; j++)
arr[(i + y)*this->k + (j + x)] = k;
len.x = x;
len.y = y;
len.len = k;
num++;
}
bool Check_this_position(int x, int y, int k)
{
if ((k > this->k - x) || (k > this->k - y)) return false;
for (int i = 0; i < k; i++)
for (int j = 0; j < k; j++)
if (arr[(i + y)*this->k + (j + x)]) return 0;
return true;
}
void Remove_elements(int x, int y, int k)
{
for (int i = 0; i < k; i++)
for (int j = 0; j < k; j++)
arr[(i + y)*this->k + (j + x)] = 0;
num--;
}
void Backtracking_of_square(int x, int y, int k)
{
for (int i = 2; i < k*k; i++)
{
point = new Point[i + 3];
if (Backtracking(x, y, k, i, 0, 0, 0)) break;
delete point;
}
}
bool Backtracking(const int &x0, const int &y0, const int &k, const int &num, int r, int x, int y)
{
if (num == r)
{
for (int i = 0; i < k; i++)
{
if (!(arr[(y0 + i)*this->k + (x0 + k - 1)]
&& arr[(y0 + k - 1)*this->k + (x0 + i)])) return false;
}
return true;
}
while ((arr[(y0 + y)*this->k + (x0 + x)]) || (x == k))
{
if (x >= k)
{
if (y == k) return true;
y++;
x = 0;
}
else x++;
}
for (int i = 1; i<k; i++)
{
if (Check_this_position(x0 + x, y0 + y, i))
{
Insert(x0 + x, y0 + y, i, point[r]); r++;
if (Backtracking(x0, y0, k, num, r, x + i, y)) return true;
Remove_elements(x0 + x, y0 + y, i); r--;
}
}
return false;
}
void Print()
{
cout << num;
for (int i = 0; i < num; i++)
cout << endl << point[i].x + 1 << " " << point[i].y + 1 << " " << point[i].len;
}
void Split()
{
if (!(k % 2))
{
point = new Point[4];
Insert(0, 0, k / 2, point[0]);
Insert(0, k / 2, k / 2, point[1]);
Insert(k / 2, 0, k / 2, point[2]);
Insert(k / 2, k / 2, k / 2, point[3]);
return;
}
if (!(k % 3))
{
point = new Point[6];
Insert(0, 0, k * 2 / 3, point[0]);
Insert(0, k * 2 / 3, k / 3, point[1]);
Insert(k * 2 / 3, 0, k / 3, point[2]);
Insert(k / 3, k * 2 / 3, k / 3, point[3]);
Insert(k * 2 / 3, k / 3, k / 3, point[4]);
Insert(k * 2 / 3, k * 2 / 3, k / 3, point[5]);
return;
}
if (!(k % 5))
{
point = new Point[8];
Insert(0, 0, k * 3 / 5, point[0]);
Insert(k * 3 / 5, k / 5, k * 2 / 5, point[1]);
Insert(k / 5, k * 3 / 5, k * 2 / 5, point[2]);
Insert(k * 3 / 5, k * 3 / 5, k * 2 / 5, point[3]);
Backtracking(0, 0, k, 8, 4, k * 3 / 5, 0);
return;
}
int m = k / 2 + 1;
Insert(0, 0, m);
Insert(0, m, m - 1);
Insert(m, 0, m - 1);
Backtracking_of_square(m - 1, m - 1, m);
point[num - 3].x = 0; point[num - 3].y = 0; point[num - 3].len = m;
point[num - 2].x = 0; point[num - 2].y = m; point[num - 2].len = m - 1;
point[num - 1].x = m; point[num - 1].y = 0; point[num - 1].len = m - 1;
}
private:
int* arr; //заполнение квадрата
int k; //размер квадрата
Point* point; //верхний левый угол и сторона квадрата
int num; //колличество обрезков
};
int main()
{
int n;
cin >> n;
Square Big_square(n);
Big_square.Split();
Big_square.Print();
return 0;
}
| true |
33ead1a4b4ae146d45c6dc7cb074a7d52a84b01a | C++ | zeropoint-t/GCSDD | /Data Structures & Algorithm I/Project7/main.cpp | UTF-8 | 7,674 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <memory>
#include <map>
#include <queue>
#include "BinaryNode.h"
#include "BinaryTree.h"
using namespace std;
template<class K, class V>
void visit(K& key, V& value){
cout << "Key: " << key << endl;
}
int main(){
///////////////////////////////////////
//--------Left Unbalanced Tree--------
///////////////////////////////////////
// 6
// 4 7
// 2 5
//1 3
cout << "*******************************" << endl;
cout << "-----Left Unbalanced Tree-----" << endl;
cout << "*******************************" << endl;
cout << " 6" << endl;
cout << " 4 7" << endl;
cout << " 2 5" << endl;
cout << "1 3" << endl;
BinaryTree<int,int> bt;
bt.add(6,0);
bt.add(4,0);
bt.add(7,0);
bt.add(5,0);
bt.add(2,0);
bt.add(3,0);
bt.add(1,0);
cout << "Preorder Traversal: " << endl;
bt.preorderTraversal(visit);
cout << endl;
cout << "Inorder Traversal: " << endl;
bt.inorderTraversal(visit);
cout << endl;
cout << "Postorder Traversal: " << endl;
bt.postorderTraversal(visit);
cout << endl;
cout << "BreadthFirstSearch Traversal: " << endl;
bt.breadthFirstSearch(visit);
cout << endl;
cout << "DepthFirstSearch Traversal: " << endl;
bt.depthFirstSearch(visit);
cout << endl;
bt.clear();
cout << endl;
///////////////////////////////////////
//--------Right Unbalanced Tree--------
///////////////////////////////////////
// 2
// 1 4
// 3 6
// 5 7
cout << "*******************************" << endl;
cout << "-----Right Unbalanced Tree-----" << endl;
cout << "*******************************" << endl;
cout << " 2" << endl;
cout << " 1 4" << endl;
cout << " 3 6" << endl;
cout << " 5 7" << endl;
bt.add(2,0);
bt.add(1,0);
bt.add(4,0);
bt.add(3,0);
bt.add(6,0);
bt.add(5,0);
bt.add(7,0);
cout << "Preorder Traversal: " << endl;
bt.preorderTraversal(visit);
cout << endl;
cout << "Inorder Traversal: " << endl;
bt.inorderTraversal(visit);
cout << endl;
cout << "Postorder Traversal: " << endl;
bt.postorderTraversal(visit);
cout << endl;
cout << "BreadthFirstSearch Traversal: " << endl;
bt.breadthFirstSearch(visit);
cout << endl;
cout << "DepthFirstSearch Traversal: " << endl;
bt.depthFirstSearch(visit);
cout << endl;
bt.clear();
cout << endl;
///////////////////////////////////////
//--------Balanced Tree--------
///////////////////////////////////////
// 4
// 2 6
// 1 3 5 7
cout << "************************" << endl;
cout << "-----Balanced Tree-----" << endl;
cout << "************************" << endl;
cout << " 4" << endl;
cout << " 2 6" << endl;
cout << " 1 3 5 7" << endl;
bt.add(4,0);
bt.add(2,0);
bt.add(1,0);
bt.add(3,0);
bt.add(6,0);
bt.add(5,0);
bt.add(7,0);
cout << "Preorder Traversal: " << endl;
bt.preorderTraversal(visit);
cout << endl;
cout << "Inorder Traversal: " << endl;
bt.inorderTraversal(visit);
cout << endl;
cout << "Postorder Traversal: " << endl;
bt.postorderTraversal(visit);
cout << endl;
cout << "BreadthFirstSearch Traversal: " << endl;
bt.breadthFirstSearch(visit);
cout << endl;
cout << "DepthFirstSearch Traversal: " << endl;
bt.depthFirstSearch(visit);
cout << endl;
bt.clear();
cout << endl << endl;
cout << "***********************************************************" << endl;
cout << "Demonstration of using a binary tree to compress a message" << endl;
cout << "***********************************************************" << endl;
//step 1 create a string to compress
string origMsg = "This is a demonstration of using a binary tree to compress a message using Hoffman Code!!";//"SUSIE SAYS IT IS EASY\n";
//step 2 - create a frequency table and save the unique characters
map<char,int> frequencyMap;
for(auto it = origMsg.begin(); it != origMsg.end(); it++){
auto c = frequencyMap.find(*it);
if(c != frequencyMap.end()){
frequencyMap[*it] += 1;
}else{
frequencyMap.insert(pair<char,int>(*it,1));
}
}
int numOfAlphabets = frequencyMap.size();
char alphabets[numOfAlphabets];
int cnt = 0;
for(auto it = frequencyMap.begin(); it != frequencyMap.end(); it++){
alphabets[cnt++] = (*it).first;
}
//step 3 - create a node for each alphabet and put them into a priority queue & save the number of alphabets
priority_queue<BinaryNode<char,int>> pq;
for(auto pair : frequencyMap){
// cout << pair.first << " " << pair.second << endl;
BinaryNode<char,int> n(pair.first, pair.second);
pq.push(n);
}
//step 4 - pop 2 at a time and create a offman tree root
while(pq.size() >= 2){
BinaryNode<char,int> bn1 = pq.top();
pq.pop();
BinaryNode<char,int> bn2 = pq.top();
pq.pop();
BinaryNode<char,int> bn3('-',bn1.getValue() + bn2.getValue());
bn3.setLeftChildPtr(make_shared<BinaryNode<char,int>>(bn1));
bn3.setRightChildPtr(make_shared<BinaryNode<char,int>>(bn2));
pq.push(bn3);
}
//step 5 - complete Hoffman Tree
BinaryNode<char,int> hoffmanBT = pq.top();
shared_ptr<BinaryNode<char,int>> nptr = make_shared<BinaryNode<char,int>>(hoffmanBT);
BinaryTree<char,int> hoffmanTree(nptr);
//step 6 - create Code Table
map<string,char> codeMap;//maps hoffman code to a character - used to decode
map<char,string> charMap;//maps a character t0 a hoffman code - used to encode
//get hoffman code for each unique character in the original message
cout << "-----Hoffman Code for each alphabet-----" << endl;
for(int i = 0; i < numOfAlphabets; i++){
string hcode = hoffmanTree.getHoffmanCode(alphabets[i]);
cout << "Alphabet: " << alphabets[i] << " Freq.: " << frequencyMap[alphabets[i]] << " Hoffman Code: " << hcode << endl;
codeMap.insert(pair<string,char>(hcode,alphabets[i]));
charMap.insert(pair<char,string>(alphabets[i],hcode));
}
cout << endl;
//step 7 - create hoffmancode encoded message using a code table
string encodedMessage;
for(auto it = origMsg.begin(); it != origMsg.end(); it++){
encodedMessage += charMap[*it];
// cout << encodedMessage << endl;
}
//step 8 - now that we have a encoded message, let's decode it back to the original message
string codeTrack;//track encoded message for pattern match
string decodedOrigMsg;//original message
for(auto it = encodedMessage.begin(); it != encodedMessage.end(); it++){
codeTrack.push_back(*it);
auto c = codeMap.find(codeTrack);
if(c != codeMap.end()){//found a pattern!
decodedOrigMsg += codeMap[codeTrack];
codeTrack.clear();
}
}
cout << "-----Original Message-----" << endl;
cout << decodedOrigMsg << endl << endl;
cout << "-----Encoded Message-----" << endl;
cout << encodedMessage << endl << endl;
cout << "-----Decoded original Message-----" << endl;
cout << decodedOrigMsg << endl << endl;
double compressionRate = (double)encodedMessage.size() / (origMsg.size() * 8);
cout << "-----Compression Rate-----" << endl;
cout << compressionRate << endl;
int a;
cin >> a;
} | true |
4513239880b2db278bc48577ba2d243f47289de9 | C++ | vincentma0001/vm_tools | /tst/vm_test/tst_cfgs/tst_cfgs.cpp | UTF-8 | 1,474 | 2.796875 | 3 | [] | no_license | //*
#include <limits.h>
#include <stdio.h>
#include <iostream>
#include <vm_cfgs.h>
//*/
int main(int argc, char *argv[])
{
//*
vTry
throw("throw string!");
vCatch(...)
vCout << "try catched...!"<< vEndl;
vEnd
vCout << "try sucesss!" << vEndl;
printf( "Test %d\n", vMax(10, 20) );
//*/
//*
printf( "int Max size : %d\n", INT_MAX );
printf( "int Min size : %d\n", INT_MIN );
printf( "int Max size : %d\n", vMaxsInt );
printf( "int Min size : %d\n", vMinsInt );
//*/
//*
std::cout.imbue(std::locale("zh_CN"));
std::string lsTmp = "this is text! 测试";
std::cout << "tst_cfgs cout is running! str = "<< lsTmp << " len = " << lsTmp.length() << std::endl;
std::cout << "tst_cfgs cout is running! str = "<< lsTmp << " len = " << lsTmp.size() << std::endl;
std::wcout.imbue(std::locale("zh_CN"));
std::wstring lsTmpw = L"this is text! 测试";
std::wcout << L"tst_cfgs wcout is running! wstr = " << lsTmpw << " len = " << lsTmpw.length() << std::endl;
std::wcout << L"tst_cfgs wcout is running! wstr = " << lsTmpw << " len = " << lsTmpw.size() << std::endl;
vString lsTmpv = vT("this is text! 测试");
vCout << vT("tst_cfgs vCout is running! vstr = ") << lsTmpv << " len = " << lsTmpv.length() << vEndl;
vCout << vT("tst_cfgs vCout is running! vstr = ") << lsTmpv << " len = " << lsTmpv.size() << vEndl;
//*/
return 0;
}
| true |
96819828eb95bdf7ab5d15fb91b5f860c97b7b32 | C++ | anjanesh/vlbjcas | /PRACT/13.CPP | UTF-8 | 464 | 2.84375 | 3 | [] | no_license | // Command Line Arguments
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
float result;
if (strcmp(argv[1],"add")==0) result=atof(argv[2])+atof(argv[3]);
if (strcmp(argv[1],"sub")==0) result=atof(argv[2])-atof(argv[3]);
if (strcmp(argv[1],"mul")==0) result=atof(argv[2])*atof(argv[3]);
if (strcmp(argv[1],"div")==0) result=atof(argv[2])/atof(argv[3]);
cout << result << '\n';
}
| true |
61acac4d0ef7bbaf34a179b8d33b0ec11f185256 | C++ | xingfeT/c-practice | /day-001-100/day-071/problem-3/main.cpp | UTF-8 | 901 | 3.90625 | 4 | [] | no_license | /*
* NOTE(nick): problem not well defined in book ...
* should have input / output - this is problem wrong ...
*
* Write a function that recursively determines the value
* of the nth term of an arithmetic sequence defined by the
* terms
*
* a, a + d, a + 2d, a + 3d, ..... a + (n - 1)d
*
* a = 3
* n = 3
* d = 2
*
* a + (n - 1) * d
*
* 3 + (3 - 1) * 2 =
* 3 + (2 * 2) =
* 3 + 4 = 7
*
* 3 + (2 - 1) * 2 =
* 3 + (1 * 2) =
* 3 + 2 = 5
*
* 3 + (1 - 1) * 2 =
* 3 + (0 * 2) =
* 3 + 0 = 3
*
* The argument to the function should be the first term, a,
* the common difference, d, and the value of n.
*
*/
#include <stdio.h>
int
RecursiveFunc(int a, int n, int d);
int
main()
{
int n = 0;
printf("%d", RecursiveFunc(3, 3, 2));
return 0;
}
int
RecursiveFunc(int a, int n, int d)
{
if (n == 0)
{
return n;
}
return a + RecursiveFunc(a, (n - 1), d) * d;
}
| true |
42f7ed37f8dcfb4827cec30bbd91fe8f42341185 | C++ | zahybnaya/mnk | /src/dotexporter.cpp | UTF-8 | 1,009 | 2.796875 | 3 | [] | no_license | #include "dotexporter.h"
#include <string.h>
#include <sstream>
static void print_node(Node* n, std::ostream& out) ;
static void print_path(std::string p, Node* n, std::ostream& out);
void todot(Node* n , std::ostream& out){
out << " digraph g {" <<std::endl;
print_path("", n, out);
print_node(n, out) ;
out << " }" <<std::endl;
}
static void print_node(Node* n, std::ostream& out) {
std::string shape=(n->player==BLACK)?"box":"circle";
out<<"\"" << n << "\"" <<"[label=\""<<n->val/n->visits <<"\"" <<" shape="<<shape <<"];"<<std::endl;
for (child_map::const_iterator i = n->children.begin(); i != n->children.end(); ++i) {
print_node(i->second, out);
}
}
static void print_path(std::string p, Node* n, std::ostream& out) {
std::stringstream ss;
ss<< p << (p==""?"":" -> ") << "\"" << n << "\"" ;
if(n->children.empty()) {
out << ss.str() << std::endl;
}
for (child_map::const_iterator i = n->children.begin(); i != n->children.end(); ++i) {
print_path(ss.str(), i->second, out);
}
}
| true |
60b1d24943351cabfd2531a9b97272e8850a03f7 | C++ | gm561/algolab | /week4/tournament.cpp | UTF-8 | 3,623 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include <map>
#include <boost/graph/adjacency_list.hpp>
#include<boost/graph/push_relabel_max_flow.hpp>
using namespace std;
using namespace boost;
typedef adjacency_list_traits<vecS, vecS, directedS> Traits;
typedef adjacency_list<vecS, vecS, directedS,
no_property,
property<edge_capacity_t, long,
property<edge_residual_capacity_t, long,
property<edge_reverse_t, Traits::edge_descriptor> > >
> Graph;
typedef Graph::vertex_descriptor Vertex;
typedef Graph::edge_descriptor Edge;
struct Team {
int points;
string name;
int matches;
int toWin;
int index;
Team() : points(0), matches(0), index(-1), toWin(0) {}
};
int main(int argc, char *argv[])
{
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
int TC; cin>>TC;
for(int tc = 0; tc < TC; ++tc) {
map<string, Team> teams;
int teams_number; cin>>teams_number;
int matchups; cin>>matchups;
Graph g(teams_number + 2);
property_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);
property_map<Graph, edge_reverse_t>::type reverse_edges = get(edge_reverse, g);
Vertex source(teams_number);
Vertex sink(teams_number + 1);
int total_points = 0;
//read teams
for(int t = 0; t < teams_number; ++t) {
int points; cin>>points;
string name; cin>>name;
Team team; team.points = points; team.name = name; team.index = t;
// cerr<<"Team: " <<team.name<<" scored: " << team.points <<"\n";
teams[name] = team;
total_points += points;
}
//read matches, add to the graph as edges
for(int m = 0; m < matchups; ++m) {
string t1,t2,empty;
cin>>t1>>empty>>t2;
int u = teams[t1].index;
int v = teams[t2].index;
++teams[t1].matches;
++teams[t2].matches;
teams[t1].toWin += 1;
Edge edge, reverse; bool result;
tie(edge, result) = add_edge(u,v,g); assert(result);
tie(reverse, result) = add_edge(v,u,g); assert(result);
capacity[edge] = 1;
capacity[reverse] = 0;
reverse_edges[edge] = reverse;
reverse_edges[reverse] = edge;
++total_points;
}
//add source
for(std::map<string, Team>::iterator it = teams.begin();
it != teams.end();
++it) {
Edge edge, reverse; bool result;
int v = (*it).second.index;
tie(edge, result) = add_edge(source, v, g);
tie(reverse, result) = add_edge(v, source, g);
capacity[edge] = (*it).second.points + (*it).second.toWin;
capacity[reverse] = 0;
reverse_edges[edge] = reverse;
reverse_edges[reverse] = edge;
}
//add sink
for(std::map<string, Team>::iterator it = teams.begin();
it != teams.end();
++it) {
Edge edge, reverse; bool result;
int v = (*it).second.index;
tie(edge, result) = add_edge(sink, v, g);
tie(reverse, result) = add_edge(v, sink, g);
capacity[edge] = 0;
capacity[reverse] = 0;
reverse_edges[edge] = reverse;
reverse_edges[reverse] = edge;
}
//run algorithm
for(std::map<string, Team>::iterator it = teams.begin();
it != teams.end();
++it) {
int winningPoints = (*it).second.matches + (*it).second.points;
for(int i = 0; i < teams_number; ++i) {
bool result; Edge edge;
tie(edge,result) = boost::edge(i, sink, g);
assert(result);
capacity[edge] = winningPoints;
}
long flow = push_relabel_max_flow(g, source, sink);
// cerr<<"Flow: "<<flow<<" from " << total_points<< " winning points "
// <<winningPoints<<"\n";
if(flow == total_points) {
cout<<(*it).second.name << " ";
}
}
cout<<"\n";
}
return 0;
}
| true |
56142526bce477c394aa7d493aacbf7cb0618a8d | C++ | zabodan/factory | /logger/inc/LogLevel.h | UTF-8 | 610 | 3.1875 | 3 | [] | no_license | #pragma once
namespace core
{
struct LogLevel
{
enum Type
{
Trace = 0,
Debug,
Info,
Warning,
Error,
Assert
};
LogLevel(Type v) : m_value(v) {}
operator Type() const { return m_value; }
private:
Type m_value;
};
template <typename Stream>
Stream& operator<<(Stream& out, const LogLevel& level)
{
static const char* c_levelStr[] = { " -T- ", " -D- ", " -I- ", " -W- ", " -E- ", " -A- " };
out << c_levelStr[level];
return out;
}
}
| true |
6f40e27683d4a0d81e9978ad042db0378ce7e853 | C++ | shudal/WhutLab1 | /src/piczip/Huffman.cpp | UTF-8 | 1,916 | 2.9375 | 3 | [] | no_license | //
// Created by perci on 2020/5/12.
//
#include "Huffman.h"
#include <limits>
int Huffman::getMinWeightIndex (int to) {
int min_index = -1;
int min_weight = std::numeric_limits<int>::max();
for (auto i=0; i<=to; ++i) {
if (vs_[i].f == 0) {
if (vs_[i].w <= min_weight) {
min_weight = vs_[i].w;
min_index = i;
}
}
}
if (min_index == -1) {
throw "invalid min index";
}
return min_index;
};
std::vector<Node> Huffman::constructTree (std::vector<int> weight) {
status_ = false;
auto n = weight.size();
if (n < 2) {
return vs_;
}
auto n2 = n * 2 - 1;
vs_.resize(n2);
for (auto i=0; i<n; ++i) {
vs_[i] = Node(weight[i]);
}
for (auto i=n; i < n2; ++i) {
int l = getMinWeightIndex(i-1);
vs_[i].l = l;
vs_[l].f = i;
int r = getMinWeightIndex(i-1);
vs_[i].r = r;
vs_[r].f = i;
vs_[i].w = vs_[l].w + vs_[r].w;
}
status_ = true;
return vs_;
}
std::vector<std::string> Huffman::encode(std::vector<Node> vns) {
status_ = false;
std::vector<std::string> ans;
int n2 = vns.size();
// n2为奇数
if (n2 < 3 || (n2 % 2 != 1)) {
return ans;
}
int n = (n2 + 1) / 2;
vs_ = std::move(vns);
now_code = "";
codes_.resize(n);
// dfs
dfs(vs_[n2 - 1], n2 - 1);
ans = std::move(codes_);
status_ = true;
return ans;
}
void Huffman::dfs(Node head, int index) {
int l = head.l;
int r = head.r;
if (l == -1 && r == -1) {
std::string s (now_code);
codes_[index] = s;
}
if (l != -1) {
now_code.push_back(left_value_);
dfs(vs_[l], l);
now_code.pop_back();
}
if (r != -1) {
now_code.push_back(right_value_);
dfs(vs_[r], r);
now_code.pop_back();
}
} | true |
eb2724821fb8d26463024bcf7ef83b5ce5f2a579 | C++ | siddhshenoy/SAMPGamemodeAPI | /GamemodeApi/Utils/VectorFunctions.h | UTF-8 | 568 | 3.25 | 3 | [] | no_license | #pragma once
#include <vector>
namespace Utils
{
namespace Vector
{
template<class T>
static std::vector<T> CreateVector(std::vector<T> input, size_t start = 0, size_t end = -1);
template<class T>
std::vector<T> CreateVector(std::vector<T> input, size_t start, size_t end)
{
typename std::vector<T>::const_iterator it_first = input.begin() + start;
typename std::vector<T>::const_iterator it_end = ((end == -1 || end == input.size()) ? input.end() : input.begin() + end + 1);
std::vector<T> result(it_first, it_end);
return result;
}
}
} | true |
305c52042ea6f0cf29b62a3985635dbf08796490 | C++ | habib302/leetcode-1 | /987. Vertical Order Traversal of a Binary Tree.cpp | UTF-8 | 1,547 | 3.140625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
map < int, map < int, vector < int > > > nodes;
queue < TreeNode* > q;
q.push(root);
queue < pair < int, int > > order;
order.push({0,0});
while( !q.empty() ) {
TreeNode* now = q.front();
q.pop();
pair < int, int > o = order.front();
order.pop();
nodes[o.second][o.first].push_back(now->val);
if( now->left ) {
q.push( now->left );
order.push( {o.first + 1, o.second - 1 });
}
if( now->right ) {
q.push( now->right );
order.push( {o.first + 1, o.second + 1} );
}
}
vector < vector < int > > ans;
for( auto values: nodes ) {
vector < int > tmp;
for( auto now: values.second ) {
sort( now.second.begin(), now.second.end() );
for( auto add: now.second ) {
tmp.push_back(add);
}
}
ans.push_back(tmp);
}
return ans;
}
};
| true |
7921eaa3dfcd6285818742ba66e106801d2e95ff | C++ | hoangtuanhedspi/hermes | /include/hermes/Regex/RegexTraits.h | UTF-8 | 9,950 | 2.796875 | 3 | [
"MIT",
"NCSA"
] | permissive | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
//===----------------------------------------------------------------------===//
/// \file
/// Regex traits appropriate for Hermes regex.
//===----------------------------------------------------------------------===//
#ifndef HERMES_REGEX_TRAITS_H
#define HERMES_REGEX_TRAITS_H
#include "hermes/Platform/Unicode/CharacterProperties.h"
#include "hermes/Platform/Unicode/PlatformUnicode.h"
#include "hermes/Regex/Compiler.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
namespace hermes {
namespace regex {
enum CaseCanonicalization { CaseLower, CaseUpper };
/// \return the character \p ch converted to lowercase or uppercase, subject
/// to the requirements of ES5.1 15.10.2.8. Specifically a non-ASCII character
/// may not canonicalize to an ASCII character, and eszett does not
/// canonicalize to Z.
inline char16_t canonicalizeToCase(
char16_t ch,
CaseCanonicalization whichCase) {
// Fast ASCII path.
if (ch <= 127) {
if (whichCase == CaseLower && 'A' <= ch && ch <= 'Z') {
return ch | 32;
} else if (whichCase == CaseUpper && 'a' <= ch && ch <= 'z') {
return ch & ~32;
} else {
return ch;
}
}
// "Let u be ch converted to upper case as if by calling the standard
// built-in method String.prototype.toUpperCase on the one-character String
// ch"
llvm::SmallVector<char16_t, 2> u = {ch};
auto caseConv = whichCase == CaseLower
? platform_unicode::CaseConversion::ToLower
: platform_unicode::CaseConversion::ToUpper;
platform_unicode::convertToCase(u, caseConv, false /* useCurrentLocale */);
// "If u does not consist of a single character, return ch."
if (u.size() != 1)
return ch;
// "Let cu be u's character"
char16_t cu = u[0];
// "If ch's code unit value is greater than or equal to decimal 128 and
// cu's code unit value is less than decimal 128, then return ch"
// (Note we checked for ch <= 127 above.)
assert(ch >= 128 && "ch should be >= 128");
if (cu < 128)
return ch;
// "Return cu."
return cu;
}
/// \return whether any range in \p ranges contains the character \p c,
/// inclusive of both ends.
inline bool anyRangeContainsChar(
llvm::ArrayRef<BracketRange16> ranges,
char16_t c) {
for (const auto &r : ranges) {
if (r.start <= c && c <= r.end) {
return true;
}
}
return false;
}
/// Implementation of regex::Traits for char16_t
struct U16RegexTraits {
private:
// A DenseMapInfo for our canonicalization cache.
// Use 0 and 1 as empty and tombstone; we skip the cache for ASCII but wish to
// support 0xFFFF and 0xFFFE as keys.
struct CanonicalizationDenseMapInfo {
static inline char16_t getEmptyKey() {
return 0;
}
static inline char16_t getTombstoneKey() {
return 1;
}
static unsigned getHashValue(char16_t c) {
return llvm::DenseMapInfo<uint16_t>::getHashValue(c);
}
static bool isEqual(char16_t lhs, char16_t rhs) {
return lhs == rhs;
}
};
using CanonicalizeCache =
llvm::SmallDenseMap<uint16_t, uint16_t, 16, CanonicalizationDenseMapInfo>;
mutable CanonicalizeCache toLowerCache_;
mutable CanonicalizeCache toUpperCache_;
/// ES5.1 7.2
static bool isWhiteSpaceChar(char16_t c) {
return c == u'\u0009' || c == u'\u000B' || c == u'\u000C' ||
c == u'\u0020' || c == u'\u00A0' || c == u'\uFEFF' || c == u'\u1680' ||
(c >= u'\u2000' && c <= u'\u200A') || c == u'\u202F' ||
c == u'\u205F' || c == u'\u3000';
}
/// ES5.1 7.3
static bool isLineTerminatorChar(char16_t c) {
return c == u'\u000A' || c == u'\u000D' || c == u'\u2028' || c == u'\u2029';
}
// Optimized variant of canonicalizeToCaseSlowPath. Convert \p ch to lowecase
// or uppercase, storing cached values in \p cache.
char16_t cachingCanonicalizeToCase(
char16_t ch,
CaseCanonicalization whichCase) const {
// canonicalizeToCase has a fast ASCII path.
// Note that we use 0 and 1 as sentinel values in the map so they must not
// be placed in the cache.
if (ch <= 127) {
return canonicalizeToCase(ch, whichCase);
}
// Read from the cache by inserting a bogus value of zero. If the cache
// probe is a miss, we'll populate it.
CanonicalizeCache &cache =
whichCase == CaseLower ? toLowerCache_ : toUpperCache_;
auto emplaced = cache.try_emplace(ch, 0);
auto &cachedChar = emplaced.first->second;
if (emplaced.second) {
cachedChar = canonicalizeToCase(ch, whichCase);
}
return cachedChar;
}
/// Given a list of inclusive ranges, a character \p c, and its
/// canonicalized form \p cc, return whether any character that canonicalizes
/// to cc is contained within the range. The caller will have already checked
/// both c and cc (which may be the same character). This implements
/// ES5.1 15.10.2.8 "CharacterSetMatcher".
bool rangeContainsPrecanonicalizedForm(
llvm::ArrayRef<BracketRange16> ranges,
char16_t cc,
char16_t c) const {
// Check special cases. These are all the cases where simple case mapping is
// not sufficient, that is, where the lowercase and uppercase variants are
// not in 1-1 correspondence. Examples include dotted capital I, Greek
// sigma, etc.
if (const auto *pclist = hermes::getExceptionalPrecanonicalizations(cc)) {
// 0 is used to indicate a missing entry.
for (auto pc : *pclist) {
if (pc != 0 && anyRangeContainsChar(ranges, pc)) {
return true;
}
}
return false;
} else {
// If we get here, then the only character which may match is the
// lowercase form. The caller already checked c and cc, so we can skip the
// check for those.
char16_t lowc = cachingCanonicalizeToCase(cc, CaseLower);
return lowc != c && lowc != cc && anyRangeContainsChar(ranges, lowc);
}
}
public:
using char_type = char16_t;
using CharT = char_type;
/// \return whether the character \p c has the character type \p type.
bool characterHasType(char_type c, regex::CharacterClass::Type type) const {
switch (type) {
case regex::CharacterClass::Digits:
return u'0' <= c && c <= u'9';
case regex::CharacterClass::Spaces:
return isWhiteSpaceChar(c) || isLineTerminatorChar(c);
case regex::CharacterClass::Words:
return (u'a' <= c && c <= u'z') || (u'A' <= c && c <= u'Z') ||
(u'0' <= c && c <= u'9') || (c == u'_');
}
llvm_unreachable("Unknown character type");
}
/// \return the case-insensitive equivalence key for \p c.
/// Our implementation follows ES5.1 15.10.2.8.
char_type caseFold(char_type c) const {
static_assert(
std::numeric_limits<char_type>::min() == 0,
"char_type must be unsigned");
if (c <= 127) {
// ASCII fast path. Uppercase by clearing bit 5.
if ('a' <= c && c <= 'z') {
c &= ~(1 << 5);
}
return c;
}
// Canonicalize (i.e. uppercase) the 1-character string.
return cachingCanonicalizeToCase(c, CaseUpper);
}
/// \return whether the character c is contained within the range [first,
/// last]. If ICase is set, perform a canonicalizing membership test as
/// specified in "CharacterSetMatcher" ES5.1 15.10.2.8.
template <bool ICase>
bool rangesContain(llvm::ArrayRef<BracketRange16> ranges, char16_t c) const {
if (anyRangeContainsChar(ranges, c)) {
return true;
}
if (ICase) {
// Canonicalize and check for membership in the range again, if the
// character changed.
char16_t cc = cachingCanonicalizeToCase(c, CaseUpper);
if (cc != c && anyRangeContainsChar(ranges, cc))
return true;
// Check for other pre-canonicalizations of cc.
return rangeContainsPrecanonicalizedForm(ranges, cc, c);
}
return false;
}
};
/// Implementation of regex::Traits for 7-bit ASCII.
struct ASCIIRegexTraits {
using char_type = char;
bool characterHasType(char c, regex::CharacterClass::Type type) const {
switch (type) {
case regex::CharacterClass::Digits:
return '0' <= c && c <= '9';
case regex::CharacterClass::Spaces:
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
case '\v':
case '\f':
return true;
default:
return false;
}
case regex::CharacterClass::Words:
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9') || (c == '_');
}
llvm_unreachable("Unknown character type");
}
static char caseFold(char c) {
if ('a' <= c && c <= 'z')
c &= ~('a' ^ 'A'); // toupper
return c;
}
/// \return whether any of a list of ranges contains \p c.
/// Note that our ranges contain char16_t, but we test chars for membership.
template <bool ICase>
bool rangesContain(llvm::ArrayRef<BracketRange16> ranges, char16_t c) const {
if (anyRangeContainsChar(ranges, c))
return true;
if (ICase) {
// We need to do a case-insensitive comparison.
// We need to check if toupper(c) is equal to toupper of any character in
// our range [first_, last_]. This can't be done naively, for example,
// calling toupper on the endpoints of the range [0-a] would result in the
// range [_-A] which is invalid. Instead we simply check if c is a letter
// and, if so, whether its other case is in the range.
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) {
c ^= 0x20; // flip case!
return anyRangeContainsChar(ranges, c);
}
}
return false;
}
};
} // end namespace regex
} // end namespace hermes
#endif
| true |
d5b7fe3be4e0fdd8c04738e1cde6f4999d214155 | C++ | nolandoktor/Vortex_Watch_Code | /LedBuffer.h | UTF-8 | 1,175 | 3.171875 | 3 | [] | no_license | #ifndef LED_BUFFER_LIB
#define LED_BUFFER_LIB
#include <Arduino.h>
#include "GlobalDefines.h"
//#define N_LEDS 12
class LedBuffer
{
private:
int ledBuffer[N_LEDS][3];
public:
enum COLORS{RED, GREEN, BLUE};
LedBuffer();
void setColorVal(int idx, int color_idx, int val);
void setColorVal(int idx, int rVal, int gVal, int bVal);
int getColorVal(int idx, int color_idx);
void clear();
void copyFrom(LedBuffer* src);
};
LedBuffer::LedBuffer()
{
clear();
}
void LedBuffer::setColorVal(int idx, int color_idx, int val)
{
ledBuffer[idx][color_idx] = val;
}
void LedBuffer::setColorVal(int idx,int rVal, int gVal, int bVal)
{
ledBuffer[idx][RED] = rVal;
ledBuffer[idx][GREEN] = gVal;
ledBuffer[idx][BLUE] = bVal;
}
int LedBuffer::getColorVal(int idx, int color_idx)
{
return ledBuffer[idx][color_idx];
}
void LedBuffer::clear()
{
for (int i=0; i<N_LEDS; i++)
{
for (int j=0; j<3; j++)
{
ledBuffer[i][j] = 0;
}
}
}
void LedBuffer::copyFrom(LedBuffer* src)
{
for (int i=0; i<N_LEDS; i++)
{
for (int j=0; j<3; j++)
{
ledBuffer[i][j] = src->getColorVal(i, j);
}
}
}
#endif
| true |
95b0255d3f8af1492ddfca656c0b52f72a9f60e6 | C++ | Ma-qingsheng/summary | /C and C++/练习Dev/ddd1.cpp | GB18030 | 744 | 2.953125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(){
typedef struct student{
char stu_number[20];
char stu_name[20];
float usual_mark;
float exam_mark;
float overall_mark;
}Student;
Student * stus,* p,* next,* head;
int N,i=0;
//ѧ
printf("ѧN=");
scanf("%d",&N);
//̬ṹ
p=stus=(Student*)malloc(sizeof(Student)*N);
while(i < N){
if(i == 0) head=stus;
scanf("%s %s %f %f",stus->stu_number,stus->stu_name,&stus->usual_mark,&stus->exam_mark);
stus->overall_mark = 0.2*stus->usual_mark + 0.8*stus->exam_mark;
i++;
}
printf("%s %s %f %f",head->stu_number,head->stu_name,head->usual_mark,head->exam_mark);
return 0;
}
| true |
6a66cb72d7b7b3e24d74099dc6db27ad3200adee | C++ | Cimera42/2DGame | /2DGame/keyboardHandler.cpp | UTF-8 | 928 | 3 | 3 | [
"MIT"
] | permissive | #include "keyboardHandler.h"
std::unordered_map<int, int> keyList;
unsigned short modList;
void keyboardInput(GLFWwindow* inWindow, int keyCode, int scanCode, int action, int modifiers)
{
keyList[keyCode] = action;
modList = modifiers;
}
bool checkModifiers(unsigned short inMods, bool strict)
{
if(strict)
{
return modList == inMods;
}
else
{
return modList & inMods == inMods;
}
}
bool isKeyPressed(int keyCode)
{
std::unordered_map<int, int>::iterator fi = keyList.find(keyCode);
if(fi != keyList.end())
{
if(fi->second == GLFW_PRESS || fi->second == GLFW_REPEAT)
{
return true;
}
}
return false;
}
bool isKeyPressed(int keyCode, int modifiers, bool strict)
{
if(checkModifiers(modifiers, strict))
{
return isKeyPressed(keyCode);
}
return false;
}
| true |
0dd4f0c4aba0542f01a43976de2754ecde370c80 | C++ | Elisabethp7/Projet | /Case.cpp | UTF-8 | 866 | 3.09375 | 3 | [] | no_license | /*
* File: Case.cpp
* Author: Bienvenue
*
* Created on 30 novembre 2015, 23:19
*/
#include "Case.h"
#include <iostream>
using namespace std;
Case::Case(char c, int pion, int m, int max, int lien): symbole(c), nombrepions(pion), jouer(m), numerocase(nbrecases), nombrepionsmax(max), liencase(lien) {
nbrecases++;
}
Case::Case(const Case& orig) {
}
Case::~Case() {
cout << "destruction d'une case" << endl;
}
int Case::getNombrePions(){
return nombrepions;
}
int Case::getNombrePionsMax(){
return nombrepionsmax;
}
void Case::setNombrePions(int i){
nombrepions = i;
}
int Case::getJouer(){
return jouer;
}
int Case::getNumeroCase(){
return numerocase;
}
int Case::getLienCase(){
return liencase;
}
char Case::getSymbole(){
return symbole;
}
bool Case::caseEstLibre(){
return nombrepions<nombrepionsmax;
}
| true |
167b967311d9f0505d0b89964ea93794bfda4074 | C++ | mission-interview/interview | /ctci/array/urlify.cpp | UTF-8 | 1,233 | 4.25 | 4 | [
"Apache-2.0"
] | permissive | /*
* Cracking the coding interview Edition 6
* Problem 1.3 URLify --> Replace all the spaces in a string with '%20'.
* Assumption : We have enough space to accomodate addition chars
* Preferebly in place
*/
#include <iostream>
#include <cstring>
/*
* Function : urlify
* Args : string long enough to accomodate extra chars + true len
* Return : void (in place transformation of string)
*/
void urlify(char *str, int len) {
int numOfSpaces = 0;
int i = 0, j = 0;
for ( i = 0; i < len; ++i ) {
if (str[i] == ' ') {
numOfSpaces++;
}
}
int extendedLen = len + 2 * numOfSpaces;
i = extendedLen - 1;
for( j = len - 1; j >= 0; --j ) {
if ( str[j] != ' ' ) {
str[i--] = str[j];
} else {
str[i--] = '0';
str[i--] = '2';
str[i--] = '%';
}
}
}
int main() {
char str[] = "Mr John Smith "; //String with extended length ( true length + 2* spaces)
std::cout << "Actual string : " << str << std::endl;
urlify(str, 13); //Length of "Mr John Smith" = 13
std::cout << "URLified string : " << str << std::endl;
return 0;
} | true |
d488b5b24b22c988988d39391d34d230415e14fd | C++ | masterserge/Cpp | /MT_Proxy_Server/libs/Buffer/Buffer.h | UTF-8 | 1,019 | 2.890625 | 3 | [] | no_license | #pragma once
#include <string>
class Buffer {
public:
virtual void append(const Buffer &buffer) = 0;
virtual void append(const Buffer *buffer) = 0;
virtual void append(const char *buf, size_t length) = 0;
virtual void append(const char *buf) = 0;
virtual const char* buf() const = 0;
virtual size_t size() const = 0;
virtual bool is_empty() const = 0;
virtual Buffer *subbuf(size_t start, size_t end) const = 0;
virtual Buffer *first(size_t count) const = 0;
virtual Buffer *last(size_t count) const = 0;
virtual void drop_first(size_t count) = 0;
virtual void drop_last(size_t count) = 0;
virtual char at(size_t index) const = 0;
virtual Buffer & operator+=(const Buffer &another) = 0;
virtual Buffer & operator+=(const Buffer *another) = 0;
virtual char operator[](size_t index) const = 0;
virtual void clear() = 0;
virtual operator std::string() const = 0;
virtual std::string toStr() = 0; // for fut upd
virtual ~Buffer() {
}
};
| true |
6363c9d58b3b06f33453403998ddc611b25cf5f8 | C++ | JoakoI98/QTMathExp | /ModelView/modelviewlinker.cpp | UTF-8 | 1,276 | 2.796875 | 3 | [] | no_license | #include "modelviewlinker.h"
ModelViewLinker::ModelViewLinker(ModelViewPrimitives *primitives) : primitives(primitives)
{
}
bool ModelViewLinker::getReadyToDraw() const
{
return readyToDraw;
}
void ModelViewLinker::setReadyToDraw(bool value)
{
readyToDraw = value;
}
std::tuple<int, int, int, int> ModelViewLinker::sendDraw()
{
if(linkedExp == nullptr) throw "Not linked expression";
return linkedExp->drawExpression();
}
std::tuple<int, int, int, int> ModelViewLinker::getSize()
{
if(linkedExp == nullptr) throw "Not linked expression";
return linkedExp->getSize();
}
void ModelViewLinker::link(MathOperand *exp)
{
this->linkedExp = exp;
this->linkedExp->setModelView(primitives);
}
bool ModelViewLinker::isLinked()
{
return linkedExp == nullptr ? false: true;
}
int ModelViewLinker::txtSizeFromHeight(int height)
{
int x0, x1, y0, y1;
std::tie(x0,y0,x1,y1) = getSize();
int fz = primitives->getTextSize();
if(abs(y1-y0) < height){
do {
primitives->setTextSizeNF(fz);
std::tie(x0,y0,x1,y1) = getSize();
fz++;
std::cout << "real: " << abs(y1-y0) << " buscado: " << height << std::endl;
} while (abs(height - abs(y1-y0)) >=3);
}
return fz;
}
| true |
cecff981bbafbede8010c7019a976196a6bd13db | C++ | wellisonraul/DesenvolvimentoUniversidade | /Semestre5/IA/BuscaEmLargura.cpp | ISO-8859-1 | 5,085 | 2.8125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
typedef struct grafo Grafo;
struct grafo{
int eh_ponderado,nro_vertices,grau_max;
int** arestas;
float** pesos;
int* grau;
};
Grafo* cria_Grafo(int nro_vertices, int grau_max, int eh_ponderado){
Grafo *gr;
gr = (Grafo*) malloc(sizeof(struct grafo));
if(gr==NULL){
printf("No foi possivel alocar memoria");
return 0;
}
else{
int i;
gr->nro_vertices = nro_vertices;
gr->grau_max = grau_max;
gr->eh_ponderado = (eh_ponderado != 0)?1:0;
gr->grau = (int*) calloc(nro_vertices,sizeof(int));
if(gr->grau==NULL){
printf("No foi possivel alocar memoria para o grau!");
return 0;
}
gr->arestas = (int**) malloc(nro_vertices * sizeof(int*));
if(gr->arestas==NULL){
printf("No foi possivel alocar memoria para arestas!");
return 0;
}
for(i=0; i<nro_vertices; i++){
gr->arestas[i] = (int*) malloc(grau_max * sizeof(int));
if(gr->arestas[i]==NULL){
printf("No foi possivel alocar memoria para arestas!");
return 0;
}
}
if(gr->eh_ponderado){
gr->pesos = (float**) malloc(nro_vertices * sizeof(float*));
if(gr->pesos==NULL){
printf("No foi possivel alocar memoria para pesos!");
return 0;
}
for(i=0; i<nro_vertices; i++){
gr->pesos[i] = (float*) malloc(grau_max * sizeof(float));
if(gr->pesos[i]==NULL){
printf("No foi possivel alocar memoria para pesos!");
return 0;
}
}
}
}
return gr;
}
void libera_Grafo(Grafo* gr){
if(gr != NULL){
int i;
for(i=0; i<gr->nro_vertices; i++)
free(gr->arestas[i]);
free(gr->arestas);
if(gr->eh_ponderado){
for(i=0; i<gr->nro_vertices; i++)
free(gr->pesos[i]);
free(gr->pesos);
}
free(gr->grau);
free(gr);
}
}
int insereAresta(Grafo* gr, int orig, int dest, int eh_digrafo, float peso){
if(gr == NULL)
return 0;
if(orig < 0 || orig >= gr->nro_vertices){
return 0;
}
if(dest < 0 || dest >= gr->nro_vertices){
return 0;
}
gr->arestas[orig][gr->grau[orig]] = dest;
if(gr->eh_ponderado) {
gr->pesos[orig][dest] = peso;
}
gr->grau[orig]++;
if(eh_digrafo == 0)
insereAresta(gr,dest,orig,1,peso);
return 1;
}
void buscaLargura_Grafo(Grafo *gr, int ini , int *visitado,int *caminho){
int i, vert, NumeroV , cont=1 , *fila, InicioF=0 , FinalF = 0;
//marca vertices como nao visitdos
for(i=0; i<gr->nro_vertices; i++)
visitado[i]=0;
//cria fila. visita e insere na fila
NumeroV = gr-> nro_vertices;
fila = (int*) malloc(NumeroV * sizeof(int));
FinalF++ ;
fila[FinalF]= ini ;
visitado[ini]=cont ;
//condio de parada
while(InicioF != FinalF){
//pega primeiro da fila
InicioF=(InicioF+1) % NumeroV ;
vert= fila[InicioF];
caminho[cont-1] = vert;
cont++;
//visita os vizinhos ainda no visitados e coloca na fila
for(i=0;i<gr->grau[vert];i++){
if(!visitado[gr->arestas[vert] [i]]){
FinalF = (FinalF + 1) % NumeroV ;
fila[FinalF]=gr->arestas[vert][i];
visitado[gr->arestas[vert][i]]=cont;
}
}
}
free(fila);
for(i=0;i < gr->nro_vertices; i++){
printf("%d -> %d \n",i,caminho[i]);
}
}
int main(){
int eh_digrafo=0 ;
//exemplo de grafo
Grafo* gr =cria_Grafo(5,5,0);
Grafo* gr1 = cria_Grafo(10,10,0);
Grafo* gr2 = cria_Grafo(10,10,0);
// GRAFO 1
insereAresta(gr, 0 , 1, eh_digrafo, 0);
insereAresta(gr, 1 , 3, eh_digrafo, 0);
insereAresta(gr, 1 , 2, eh_digrafo, 0);
insereAresta(gr, 2 , 4, eh_digrafo, 0);
insereAresta(gr, 3 , 0, eh_digrafo, 0);
insereAresta(gr, 3 , 4, eh_digrafo, 0);
insereAresta(gr, 4 , 1, eh_digrafo, 0);
//GRAFO 2 - SEM PESO; DIGRAFO
insereAresta(gr1,1,2,eh_digrafo,0);
insereAresta(gr1,2,6,eh_digrafo,0);
insereAresta(gr1,6,3,eh_digrafo,0);
insereAresta(gr1,3,1,eh_digrafo,0);
insereAresta(gr1,2,7,eh_digrafo,0);
insereAresta(gr1,7,8,eh_digrafo,0);
insereAresta(gr1,8,4,eh_digrafo,0);
insereAresta(gr1,4,5,eh_digrafo,0);
insereAresta(gr1,5,9,eh_digrafo,0);
insereAresta(gr1,5,1,eh_digrafo,0);
insereAresta(gr1,4,1,eh_digrafo,0);
insereAresta(gr1,7,4,eh_digrafo,0);
//GRAFO 3 - SEM PESO; DIGRAFO
insereAresta(gr2,1,2,eh_digrafo,0);
insereAresta(gr2,2,5,eh_digrafo,0);
insereAresta(gr2,2,6,eh_digrafo,0);
insereAresta(gr2,2,7,eh_digrafo,0);
insereAresta(gr2,1,3,eh_digrafo,0);
insereAresta(gr2,1,4,eh_digrafo,0);
insereAresta(gr2,4,8,eh_digrafo,0);
insereAresta(gr2,4,9,eh_digrafo,0);
int vis[5];
int caminho[5];
//fazer uma busca no grafo iniciando no vertice 0
buscaLargura_Grafo(gr1,0,vis,caminho);
libera_Grafo(gr);
system("pause");
return 0 ;
}
| true |
54e4606e8fe8082cbf50f1f312f4808d192b341e | C++ | Spicy-Noodles-Studio/Ultimate-Ghost-Punch | /UltimateGhostPunch/Src/CameraEffects.cpp | UTF-8 | 4,063 | 2.546875 | 3 | [
"CC-BY-4.0"
] | permissive | #include "CameraEffects.h"
#include <ComponentRegister.h>
#include <RenderSystem.h>
#include <WindowManager.h>
#include <GameObject.h>
#include <MathUtils.h>
#include <Camera.h>
#include <sstream>
REGISTER_FACTORY(CameraEffects);
CameraEffects::CameraEffects(GameObject* gameObject) : UserComponent(gameObject), min(0), max(1), current(0), state(IDLE), mainCameraTransform(nullptr), shakeDir(Vector3::ZERO), rotationDir(Vector3::ZERO),
initialRotation(Vector3::ZERO), dirX(1), dirY(1), dirZ(1), moves(0), time(0), vel(2), minRange(-5), maxRange(5), duration(2000)
{
}
CameraEffects::~CameraEffects()
{
mainCameraTransform = nullptr;
}
void CameraEffects::start()
{
if (notNull(WindowManager::GetInstance()))
max = WindowManager::GetInstance()->getBrightness() + 0.5;
if (max == 0) max = 0.00001;
current = max;
state = IDLE;
mainCameraTransform = gameObject->getComponent<Transform>();
checkNullAndBreak(mainCameraTransform);
initialRotation = mainCameraTransform->getRotation();
initialPosition = mainCameraTransform->getPosition();
}
void CameraEffects::update(float deltaTime)
{
if (state == FADEOUT)
{
current -= (0.4 * max * deltaTime);
if (current < min)
{
current = min;
state = IDLE;
}
if (notNull(RenderSystem::GetInstance()))
RenderSystem::GetInstance()->changeParamOfShader("Brightness", "bright", current);
}
else if (state == FADEIN)
{
current += (0.4 * max * deltaTime);
if (current > max)
{
current = max;
state = IDLE;
}
if (notNull(RenderSystem::GetInstance()))
RenderSystem::GetInstance()->changeParamOfShader("Brightness", "bright", current);
}
else if (state == SHAKE)
{
time += deltaTime * 1000;
float moveX, moveY, moveZ;
moveX = random() * vel * dirX;
moveY = random() * vel * dirY;
moveZ = random() * vel * dirZ;
checkNullAndBreak(mainCameraTransform);
Vector3 pos = mainCameraTransform->getPosition();
mainCameraTransform->setPosition(Vector3(pos.x + moveX * rotationDir.x, pos.y + moveY * rotationDir.y, pos.z + moveZ * rotationDir.z));
Vector3 newPos = mainCameraTransform->getPosition();
if ((newPos.x >= initialPosition.x + maxRange && dirX > 0) || (newPos.x <= initialPosition.x + minRange && dirX < 0))
dirX *= -1;
if ((newPos.y >= initialPosition.y + maxRange && dirY > 0) || (newPos.y <= initialPosition.y + minRange && dirY < 0))
dirY *= -1;
if ((newPos.z >= initialPosition.z + maxRange && dirZ > 0) || (newPos.z <= initialPosition.z + minRange && dirZ < 0))
dirZ *= -1;
if (time >= duration)
{
state = IDLE;
mainCameraTransform->setRotation(initialRotation);
mainCameraTransform->setPosition(initialPosition);
time = 0;
moves = 0;
}
}
}
void CameraEffects::handleData(ComponentData* data)
{
checkNullAndBreak(data);
for (auto prop : data->getProperties())
{
std::stringstream ss(prop.second);
if (prop.first == "vel")
{
setFloat(vel);
}
else if (prop.first == "minRange")
{
setFloat(minRange);
}
else if (prop.first == "maxRange")
{
setFloat(maxRange);
}
else if (prop.first == "duration")
{
setFloat(duration);
}
else
LOG("DODGE: Invalid property name %s", prop.first.c_str());
}
}
void CameraEffects::fadeOut()
{
if (state == IDLE)
state = FADEOUT;
else if (state == SHAKE) {
state = FADEOUT;
if (notNull(mainCameraTransform)) mainCameraTransform->setRotation(initialRotation);
}
}
void CameraEffects::fadeIn()
{
if (state == IDLE)
state = FADEIN;
else if (state == SHAKE) {
state = FADEIN;
if (notNull(mainCameraTransform)) mainCameraTransform->setRotation(initialRotation);
}
}
void CameraEffects::setDarkness()
{
checkNullAndBreak(RenderSystem::GetInstance());
RenderSystem::GetInstance()->changeParamOfShader("Brightness", "bright", 0);
current = 0;
}
bool CameraEffects::isFading()
{
return state != IDLE;
}
void CameraEffects::shake(Vector3 rotDir)
{
if (state == IDLE)
{
state = SHAKE;
rotationDir = rotDir;
if (notNull(mainCameraTransform)) initialPosition = mainCameraTransform->getPosition();
}
} | true |
e8a7eee053e34d7cd6039be2bfddb1c2aab8c953 | C++ | CrazyThink/Arduino | /_2_1/_2_1.ino | UTF-8 | 521 | 2.671875 | 3 | [] | no_license | int t = 0;
int sw1 = 0;
int sw2 = 0;
void setup() {
pinMode(2, OUTPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
}
void loop() {
if(t != 0){
digitalWrite(2, HIGH);
delay(t);
digitalWrite(2, LOW);
delay(10 - t);
}
if(digitalRead(12) == LOW && sw1 == 0){
t++;
if(t == 11) t = 10;
sw1 = 1;
}
if(digitalRead(13) == LOW && sw2 == 0){
t--;
if(t == -1) t = 0;
sw2 = 1;
}
if(digitalRead(12) == HIGH)
sw1 = 0;
if(digitalRead(13) == HIGH)
sw2 = 0;
}
| true |
c63507269345b3598244cfba4d2aab0d4fa28bc4 | C++ | powerLEO101/Work | /Code/LOJ/LOJ10081/code.cpp | UTF-8 | 1,670 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<deque>
#define File(s) freopen(#s".in","r",stdin);freopen(#s".out","w",stdout)
#define gi get_int()
#define _ 2000000
#define for_edge(i,x) for(int i = Head[x];i!=-1;i = Edges[i].Next)
#define INF 0x3f3f3f3f
int get_int()
{
int x = 0,y = 1;char ch = getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch = getchar();
if(ch=='-')y = -1,ch = getchar();
while(ch<='9'&&ch>='0')x = x*10+ch-'0',ch = getchar();
return x*y;
}
class Edge
{
public:
int Next,To,Value;
}Edges[_];
int E_num,Head[_];
void Add_edge(int From,int To,int Value)
{
Edges[E_num] = (Edge){Head[From],To,Value};
Head[From] = E_num++;
}
int Dist[_];
bool Vis[_];
void SPFA(int s)
{
memset(Dist,0x3f,sizeof(Dist));
memset(Vis,0,sizeof(Vis));
std::deque<int> Q;
Q.push_back(s);
Dist[s] = 0;
Vis[s] = true;
while(!Q.empty())
{
int Now = Q.front();Q.pop_front();
Vis[Now] = false;
for_edge(i,Now)
{
int To = Edges[i].To,Value = Edges[i].Value;
if(Dist[To]<=Dist[Now]+Value)continue;
Dist[To] = Dist[Now]+Value;
if(Vis[To]==false)
{
Vis[To] = true;
if(Dist[To]<=Dist[Q.front()])Q.push_front(To);
else Q.push_back(To);
}
}
}
}
int main()
{
File(code);
int n = gi,r = gi,p = gi,s = gi-1;
memset(Head,-1,sizeof(Head));
for(int i = 0;i<r;i++)
{
int From = gi-1,To = gi-1,Value = gi;
Add_edge(From,To,Value);
Add_edge(To,From,Value);
}
for(int i = 0;i<p;i++)
{
int From = gi-1,To = gi-1,Value = gi;
Add_edge(From,To,Value);
}
SPFA(s);
for(int i = 0;i<n;i++)
if(Dist[i]==INF)std::cout<<"NO PATH"<<std::endl;
else std::cout<<Dist[i]<<std::endl;
return 0;
}
| true |
34257d5faea4f66b6af0a82740889b2aba4ca07b | C++ | lasimondep/spbu-practice | /07.09.2017/problem1.cpp | UTF-8 | 783 | 2.609375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
const int MAXN(10), STEP[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
void f(int n, int a[MAXN][MAXN]) {
int p(3), x(0), y(n - 1), k(1), l(0), nx, ny;
a[x][y] = 2;
bool t;
while (k < n * n) {
nx = x + STEP[l][0], ny = y + STEP[l][1];
if (0 <= nx && nx < n && 0 <= ny && ny < n && !a[nx][ny]) {
x = nx, y = ny, k++;
a[x][y] = p++;
for (;; ++p) {
t = true;
for (int d(2); t && d * d <= p; ++d)
t = p % d;
if (t)
break;
}
}
else
l = (l + 1) % 4;
}
}
int main() {
int n, a[MAXN][MAXN];
memset(a, 0, sizeof a);
scanf("%d", &n);
f(n, a);
for (int i(0); i < n; ++i) {
for (int j(0); j < n; ++j)
printf("%d ", a[i][j]);
putchar('\n');
}
return 0;
}
| true |
fa2b8cb3aecce5b6a6ec0fd45395eb3989547848 | C++ | sunsetwarrior/kakuro-game | /removed from project/puzzle.h | UTF-8 | 581 | 2.78125 | 3 | [] | no_license | #ifndef PUZZLE_H
#define PUZZLE_H
#include <QJsonArray>
#include <QJsonObject>
#include <QVector>
#include "puzzle.h"
class Puzzle
{
public:
Puzzle();
Puzzle(const QVector<double>& row);
void read(const QJsonObject& json);
void write(QJsonObject& json) const;
double getCell();
void setCell(double cell);
private:
/*
* puzzle is an array of row.
* row is an array of double values.
*/
QVector<QVector<double>> vPuzzle;
QVector<double> vRow;
QJsonArray puzzle;
QJsonArray row;
double dCell;
};
#endif // PUZZLE_H
| true |
c81736f9130dee8134c2f04c38bc78aea48e0b7c | C++ | PhuongNam-19127480/ktlt-19clc9-group03 | /Student management system/header.h | UTF-8 | 8,897 | 2.890625 | 3 | [] | no_license | #ifndef _SS_
#define _SS_
#include<iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include <iomanip>
#include <ctime>
#include <sstream>
using namespace std;
struct Semester
{
int n = 0;
char Semesters[11];
char academic[20];
};
struct StudentFromCSV {
string No;
string ID;
string Lastname;
string Firstname;
string Gender;
string Day;
string Month;
string Year;
string DoB;
string Password;
};
struct Subjects {
string name;
Subjects* next;
};
struct Classes {
string name;
Subjects *next;
};
struct Staff {
string username, name, password, gender;
};
struct Lecturer {
string username, name, password, degree, gender;
int order;
};
struct CheckIn {
//Name
string name;
//Day
int startDay, startMonth, startYear; //start
//Hour, Minutes
int startHour, startMinute; //start
int endHour, endMinute; //end
//check
int check;
CheckIn* next;
};
struct Student {
//Node Student
string username, name, password, DOB, classes, gender;
//Score
float midterm = NULL, final = NULL, bonus = NULL, total = NULL;
//check in
CheckIn *checkIn;
//active
int status = 1;
};
struct Schedule {
//Node courses
string no, id, name, classes;
//Node lecturers
Lecturer lecturer;
//Day
string startDay, startMonth, startYear; //start
string endDay, endMonth, endYear; //end
//Hour, Minutes
string startHour, startMinute; //start
string endHour, endMinute; //end
//lecturer
string LecturerUsername;
string LecturerName;
string LecturerDegree;
string lecturerGender;
//??
string DayOfWeek;
//Room
string Room;
Schedule *next;
};
struct Time {
int seconds, minutes, hours, days, months, years;
};
struct Course {
string id;
string classes;
};
struct Node {
Staff staff; //1
Lecturer lecturer; //2
Student student; //3
Schedule schedule; //4
Classes classes; //5
StudentFromCSV Info; //6
Course course; //7
Semester data;
Node* next;
int type;
//type Staff:0, Lecturer:1 -> cmt after struct is type
//the type of empty list is -1
};
struct LinkedList {
Node *head;
Node *tail;
int count;
string ClassName;
};
//Read File
Node* createNode();
void loadStaff(fstream& fin, LinkedList& list);
void readStaffFile(LinkedList& list);
void loadLecturer(fstream& fin, LinkedList& list);
void readLecturerFile(LinkedList& list);
//write
void save(ofstream& fout, LinkedList list, Node user);
void write(LinkedList list, Node user);
//Login
int checkLogin(string username, string password, Node &user, LinkedList list);
Node login();
//Menu
void menuLogin();
void menuFunction(Node user);
void menuShow(Node user);
void menuStudent(Node user);
//View profile
string gender(Node user);
void viewProfile(Node user);
//Change password
void saveNewPassword(LinkedList& list, Node& user);
void changePassword(Node& user);
//Student function
void loadStudent(ifstream& fin, LinkedList& list);
void readStudentFile(LinkedList& list);
void saveCheckIn(ofstream& fout, LinkedList studentList);
void readCheckIn(string path, LinkedList studentList);
CheckIn* createCheckIn();
//Check in
tm currentDateTime();
void saveCheckIn(LinkedList& list, Node& user);
int isCheckIn(LinkedList& studentList, Node user);
void checkIn(Node user);
void viewCheckIn(Node user);
void viewSchedules(Node user);
void viewScore(Node user);
//Thien
void menuStaff(Node user);
Node* CreateNodeCSV(string No, string ID, string Lastname, string Firstname, string Gender, string Day, string Month, string Year);
void LoadStudent(ifstream& finput, LinkedList& Stu);
void Load_Option(LinkedList& CLC1, LinkedList& CLC2, LinkedList& CLC3, LinkedList& CLC4, LinkedList& CLC5, LinkedList& CLC6, LinkedList& CLC7, LinkedList& CLC8, LinkedList& CLC9, LinkedList& CLC10, LinkedList& APCS1, LinkedList& APCS2);
void InsertStudent(LinkedList& Stu);
void EditStudent(LinkedList& Stu);
void Delete_Student(LinkedList& Class);
void SaveStudentFile(LinkedList Stu);
void OuputStudentList(LinkedList Stu);
void Insert_Option(LinkedList& CLC1, LinkedList& CLC2, LinkedList& CLC3, LinkedList& CLC4, LinkedList& CLC5, LinkedList& CLC6, LinkedList& CLC7, LinkedList& CLC8, LinkedList& CLC9, LinkedList& CLC10, LinkedList& APCS1, LinkedList& APCS2);
void Edit_Option(LinkedList& CLC1, LinkedList& CLC2, LinkedList& CLC3, LinkedList& CLC4, LinkedList& CLC5, LinkedList& CLC6, LinkedList& CLC7, LinkedList& CLC8, LinkedList& CLC9, LinkedList& CLC10, LinkedList& APCS1, LinkedList& APCS2);
void View_Class_List(LinkedList CLC1, LinkedList CLC2, LinkedList CLC3, LinkedList CLC4, LinkedList CLC5, LinkedList CLC6, LinkedList CLC7, LinkedList CLC8, LinkedList CLC9, LinkedList CLC10, LinkedList APCS1, LinkedList APCS2);
void View_Student_List_Option(LinkedList CLC1, LinkedList CLC2, LinkedList CLC3, LinkedList CLC4, LinkedList CLC5, LinkedList CLC6, LinkedList CLC7, LinkedList CLC8, LinkedList CLC9, LinkedList CLC10, LinkedList APCS1, LinkedList APCS2);
void Delete_Option(LinkedList& CLC1, LinkedList& CLC2, LinkedList& CLC3, LinkedList& CLC4, LinkedList& CLC5, LinkedList& CLC6, LinkedList& CLC7, LinkedList& CLC8, LinkedList& CLC9, LinkedList& CLC10, LinkedList& APCS1, LinkedList& APCS2);
void Change_Class_Option(LinkedList& CLC1, LinkedList& CLC2, LinkedList& CLC3, LinkedList& CLC4, LinkedList& CLC5, LinkedList& CLC6, LinkedList& CLC7, LinkedList& CLC8, LinkedList& CLC9, LinkedList& CLC10, LinkedList& APCS1, LinkedList& APCS2);
void Add_Student_To_Class(LinkedList& Stu, LinkedList TempList);
void Delete_Student_From_Class(LinkedList& Class, LinkedList& TempList);
//Anh An
Node* createNodeAnh(Schedule s);
Node* createNodeLtr(Lecturer lecturer);
void load_file(LinkedList& lst, ifstream& fin, int& count);
void output_file(LinkedList lst, ofstream& fout);
int string_to_int(string temp);
void load_file_Student(ifstream& fin, LinkedList& lst2);
Node* create_Node_Student(Student s);
void output_file_Student_from_csv_to_txt(ofstream& fout, LinkedList lst2, LinkedList lst, Node* currentlst);
int day_of_month(int thang, int nam);
int day_after_1_week(int day, int thang, int nam);
bool isCheck(int nam);
//void remove_specific_student( LinkedList &lst2, LinkedList lst);
void main_schedule_from_csv_to_txt(LinkedList& lst, LinkedList& lst2);
void option_course(LinkedList& lst);
void load_file_schedule_txt(LinkedList& lst, ifstream& fin, int& count);
void Add_course(LinkedList& lst, int& count, Schedule& s);
void output_file_schedule_txt(LinkedList lst, ofstream& fout);
void main_add_course(LinkedList& lst, LinkedList& lst2);
void output_file_Student_Add(ofstream& fout, LinkedList lst2, Schedule s);
//edit course
void edit_course(LinkedList& lst, Node*& current1, string& inputpath, LinkedList& lst2);
void main_edit_course(LinkedList& lst, LinkedList& lst2);
void view_schedule(LinkedList lst);
void load_file_course_student(LinkedList lst2, LinkedList& lst1, string inputpath, string outputpath, Node* currentlst);
// delete course
void delete_course(LinkedList& lst, int& count);
void main_delete_course(LinkedList& lst);
void remove_specific_student(LinkedList& lst2, LinkedList lst, string classes);
void main_remove_specific_student(LinkedList lst, LinkedList& lst2);
int string_to_int2(string temp);
void Add_specific_student(LinkedList& lst);
Node* create_Node_course_student(Student s);
Node* createNode_Course(Course c);
void load_List_Of_Course2(LinkedList& lstCourse);
void save_list_of_course(ofstream& fout, LinkedList lstCourse);
void view_List_Of_Course2(LinkedList& lstCourse);
void export_Score_Board_csv(string inputpath, string outputpath);
void main_export_Score_Board_csv();
void view_ScoreBoard2(string inputPath);
void main_View_Score_Board();
void view_Student(string inputPath);
void main_View_Student_Of_Course();
void view_3(string inputPath);
void main_View_Attendence_List_Of_Course();
void viewLecturer(LinkedList& lst);
//Bonus
Node* createNoteSemester(Semester& s);
void create_file(LinkedList& lst, Semester s, ofstream& fout);
void input_Semester(LinkedList& lst, ifstream& fin);
void view_Semester(LinkedList lst);
void update_Semester(LinkedList& lst, Semester& s);
void output_Semester(LinkedList lst, ofstream& fout);
void delete_Semester(LinkedList& lst);
void main_semester();
void export_3(string inputPath, string outputpath);
void main_Export_Attendence_csv_File();
void edit_Attendence2(string inputPath);
void main_Edit_Attendence();
void import_Score_Board2(string inputPath);
void main_import_ScoreBoard();
void edit_Grade2(string inputPath);
void main_Edit_Grade();
void menuLecturer();
void view_schedule_2(LinkedList lst);
void courseFunction(LinkedList& APCS1);
#endif | true |
41887573169b62285fcd5a408e3d738ead8713bc | C++ | arthurquinn/solitaire | /solitaire_engine_linux/src/gameplay/foundation_pile.cpp | UTF-8 | 1,573 | 3.328125 | 3 | [] | no_license | #include "stdafx.h"
#include "gameplay/foundation_pile.h"
FoundationPile::FoundationPile() {}
const void FoundationPile::push(Card* card) {
pile.push_back(card);
}
const std::string FoundationPile::push(const pile_t cards) {
const std::string response = is_valid(cards);
if(response.find(ERROR_TAG) == std::string::npos) {
push(cards.back());
}
return response;
}
const std::string FoundationPile::is_valid(const pile_t cards) const {
std::string response = EMPTY_RESPONSE;
const size_t size = cards.size();
if (size == 1) {
Card* card = cards.back();
Card* pile_card = (pile.size() > 0) ? pile.back() : NULL;
bool is_empty_and_ace = pile_card == NULL && card->get_rank() == 0;
bool is_valid_move = pile_card != NULL && pile_card->is_same_suit(*card) && !pile_card->is_opposite_color(*card) && !pile_card->is_rank_lower(*card);
if (is_empty_and_ace || is_valid_move) {
response = std::string(card->as_str());
}
else if (pile_card == NULL) {
response = ERROR_TAG + std::string("You can only bring an Ace to an empty position.");
}
else {
response = ERROR_TAG + std::string(card->as_str()) + " is not the same suit, is not the same color, or rank is lower.";
}
}
else if(size > 1) {
response = ERROR_TAG + std::string("Cannot add a group of cards to a foundation pile.");
}
else {
response = ERROR_TAG + std::string("No cards selected.");
}
return response;
}
const int FoundationPile::count() const {
return pile.size();
}
FoundationPile::~FoundationPile() {}
| true |
150cef8c591735814bac81ba2b8b1f4c02b718e4 | C++ | salileo/RatnaKiran | /RatnaKiran/RatnakiranDatabase/Permissions.cpp | UTF-8 | 16,353 | 2.5625 | 3 | [] | no_license | #include "DatabaseGlobals.h"
#define ADMIN_USERNAME "admin"
#define ADMIN_PASSWORD "jaiganesh"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define ADDENTRY(x,y) \
case x:\
retval = y;\
break;
#define CHECKENTRY(x,y) \
{\
CString str = y;\
if(str == action)\
return x;\
}
static CPermissions gPermissions;
CPermissions::CPermissions()
{
m_PermsInitialized = FALSE;
}
CPermissions::~CPermissions()
{
m_PermsInitialized = FALSE;
}
CString CPermissions::GetStringFromAction(AppAction action)
{
CString retval;
switch(action)
{
ADDENTRY(changefilepath, "Change file path");
ADDENTRY(updategoldrate, "Update gold rate")
ADDENTRY(updateusingcurrency, "Update using currency");
ADDENTRY(updatedescriptiondatabase, "Update description database");
ADDENTRY(addset, "Add set");
ADDENTRY(deleteset, "Delete set");
ADDENTRY(editset, "Edit set");
ADDENTRY(moveset, "Move set");
ADDENTRY(viewsets, "View sets");
ADDENTRY(createvoucher, "Create voucher");
ADDENTRY(deletevoucher, "Delete voucher");
ADDENTRY(updatevoucherinfo, "Update voucher info");
ADDENTRY(stockreports, "Create stock reports");
ADDENTRY(exportreports, "Create export reports");
ADDENTRY(kundanreports, "Create kundan reports");
ADDENTRY(adduser, "Add user");
ADDENTRY(deleteuser, "Delete user");
ADDENTRY(edituser, "Edit user");
ADDENTRY(enderror, "--error--");
}
return retval;
}
AppAction CPermissions::GetActionFromString(CString action)
{
CHECKENTRY(changefilepath, "Change file path");
CHECKENTRY(updategoldrate, "Update gold rate")
CHECKENTRY(updateusingcurrency, "Update using currency");
CHECKENTRY(updatedescriptiondatabase, "Update description database");
CHECKENTRY(addset, "Add set");
CHECKENTRY(deleteset, "Delete set");
CHECKENTRY(editset, "Edit set");
CHECKENTRY(moveset, "Move set");
CHECKENTRY(viewsets, "View sets");
CHECKENTRY(createvoucher, "Create voucher");
CHECKENTRY(deletevoucher, "Delete voucher");
CHECKENTRY(updatevoucherinfo, "Update voucher info");
CHECKENTRY(stockreports, "Create stock reports");
CHECKENTRY(exportreports, "Create export reports");
CHECKENTRY(kundanreports, "Create kundan reports");
CHECKENTRY(adduser, "Add user");
CHECKENTRY(deleteuser, "Delete user");
CHECKENTRY(edituser, "Edit user");
return enderror;
}
BOOL CPermissions::ReadUsers()
{
m_UserList.RemoveAll();
{
CString admin_password;
char val[256];
DWORD count = 256;
HKEY hKey;
CString main = "SOFTWARE\\Microsoft\\Stock";
CString entry = "Password";
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, main, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
{
SHOW_INTERNAL_ERROR_REASON("Could not find password location for admin.");
return FALSE;
}
if(RegQueryValueEx(hKey, entry, NULL, NULL, (LPBYTE)val, &count) != ERROR_SUCCESS)
admin_password = ADMIN_PASSWORD;
else
admin_password = val;
RegCloseKey(hKey);
UserInfo master_user;
strcpy(master_user.m_username, ADMIN_USERNAME);
strcpy(master_user.m_password, LPCTSTR(admin_password));
master_user.m_perms[0] = -1;
master_user.m_perms[1] = -1;
master_user.m_perms[2] = -1;
m_UserList.AddHead(master_user);
}
CString filename = gFilePath + "\\perms.rsf";
CFile inputfile;
CFileException openerror;
if(!inputfile.Open(LPCTSTR(filename), CFile::modeRead | CFile::shareExclusive | CFile::typeBinary, &openerror))
{
if(IsFileExisting(filename))
{
CString errstr;
errstr.Format("ERROR : #%d.", openerror.m_cause);
errstr = "Could not open permissions file '" + filename + "'.\n" + errstr;
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
else
{
m_PermsInitialized = TRUE;
return TRUE;
}
}
try
{
inputfile.SeekToBegin();
}
catch(CFileException *readerror)
{
CString errstr;
errstr.Format("ERROR : #%d.",readerror->m_cause);
SHOW_INTERNAL_ERROR_REASON(errstr);
inputfile.Close();
return FALSE;
}
while(TRUE)
{
UserInfo buffer;
int readcount;
try
{
readcount = inputfile.Read(&buffer,sizeof(UserInfo));
}
catch(CFileException *readerror)
{
CString errstr;
errstr.Format("ERROR : #%d.",readerror->m_cause);
errstr = "Could not read to permissions file '" + filename + "'.\n" + errstr;
SHOW_INTERNAL_ERROR_REASON(errstr);
inputfile.Close();
return FALSE;
}
if(readcount < sizeof(UserInfo))
break;
DECODE(&buffer, UserInfo);
m_UserList.AddTail(buffer);
}
inputfile.Close();
m_PermsInitialized = TRUE;
return TRUE;
}
BOOL CPermissions::WriteUsers()
{
CString filename = gFilePath + "\\temp_perms.tmp";
CFile outputfile;
CFileException openerror;
if(!outputfile.Open(LPCTSTR(filename), CFile::modeCreate | CFile::modeWrite | CFile::shareExclusive | CFile::typeBinary, &openerror))
{
CString errstr;
errstr.Format("ERROR : #%d.", openerror.m_cause);
errstr = "Could not open temporary permissions file '" + filename + "'.\n" + errstr;
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
try
{
outputfile.SeekToBegin();
}
catch(CFileException *readerror)
{
CString errstr;
errstr.Format("ERROR : #%d.",readerror->m_cause);
SHOW_INTERNAL_ERROR_REASON(errstr);
outputfile.Close();
return FALSE;
}
POSITION pos = m_UserList.GetHeadPosition();
while(pos)
{
UserInfo entry = m_UserList.GetAt(pos);
if(strcmp(entry.m_username, ADMIN_USERNAME) == 0)
{
m_UserList.GetNext(pos);
continue;
}
ENCODE(&entry, UserInfo);
try
{
outputfile.Write(&entry, sizeof(UserInfo));
}
catch(CFileException *readerror)
{
CString errstr;
errstr.Format("ERROR : #%d.",readerror->m_cause);
errstr = "Could not write to temporary permissions file '" + filename + "'.\n" + errstr;
SHOW_INTERNAL_ERROR_REASON(errstr);
outputfile.Close();
return FALSE;
}
m_UserList.GetNext(pos);
}
outputfile.Close();
CString finalfile = gFilePath + "\\perms.rsf";
if(!MoveDatabaseFile(filename, finalfile))
{
CString errstr = "Could not move file '" + filename + "' to '" + finalfile + "'.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
return TRUE;
}
BOOL CPermissions::AddUser(CString user, CString password)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(user.IsEmpty())
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(user == ADMIN_USERNAME)
{
SHOW_INTERNAL_ERROR_REASON("Cannot add user 'admin', as it already exists.");
return FALSE;
}
if(IsUserExisting(user))
{
CString errstr = "Cannot add user '" + user + "' as it already exists.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
UserInfo entry;
strcpy(entry.m_username, LPCTSTR(user));
if(!password.IsEmpty())
strcpy(entry.m_password, LPCTSTR(password));
gPermissions.m_UserList.AddTail(entry);
if(!gPermissions.WriteUsers())
{
//restore state
gPermissions.m_UserList.RemoveTail();
SHOW_INTERNAL_ERROR_REASON("Unable to update stored permission.");
return FALSE;
}
return TRUE;
}
BOOL CPermissions::DeleteUser(CString user)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(user.IsEmpty())
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(user == ADMIN_USERNAME)
{
SHOW_INTERNAL_ERROR_REASON("Cannot delete the 'admin' user.");
return FALSE;
}
if(user == gPermissions.m_CurrentUser)
{
SHOW_INTERNAL_ERROR_REASON("Cannot delete the self username.");
return FALSE;
}
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
UserInfo orig_entry;
while(pos)
{
orig_entry = gPermissions.m_UserList.GetAt(pos);
if(strcmp(orig_entry.m_username, LPCTSTR(user)) == 0)
break;
gPermissions.m_UserList.GetNext(pos);
}
if(!pos)
{
CString errstr = "Could not find user '" + user + "' for deletion.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
gPermissions.m_UserList.RemoveAt(pos);
if(!gPermissions.WriteUsers())
{
//restore state
gPermissions.m_UserList.AddTail(orig_entry);
SHOW_INTERNAL_ERROR_REASON("Unable to update stored permission.");
return FALSE;
}
return TRUE;
}
BOOL CPermissions::GetUsernames(CList<CString, CString> *users)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(!users)
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
while(pos)
{
UserInfo entry = gPermissions.m_UserList.GetAt(pos);
CString str = entry.m_username;
if(str != ADMIN_USERNAME)
users->AddTail(str);
gPermissions.m_UserList.GetNext(pos);
}
return TRUE;
}
CString CPermissions::GetAdminUsername()
{
CString admin = ADMIN_USERNAME;
return admin;
}
BOOL CPermissions::IsUserExisting(CString user)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(user.IsEmpty())
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(user == ADMIN_USERNAME)
return TRUE;
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
UserInfo entry;
while(pos)
{
entry = gPermissions.m_UserList.GetAt(pos);
if(strcmp(entry.m_username, LPCTSTR(user)) == 0)
return TRUE;
gPermissions.m_UserList.GetNext(pos);
}
return FALSE;
}
BOOL CPermissions::SetPassword(CString user, CString password)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(user.IsEmpty())
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(user == ADMIN_USERNAME)
{
CString admin_password;
DWORD dwDisposition;
HKEY hKey;
HKEY hkSub;
CString main = "SOFTWARE\\Microsoft";
CString section = "Stock";
CString entry = "Password";
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, main, 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
{
SHOW_INTERNAL_ERROR_REASON("Could not find password location for admin.");
return FALSE;
}
if(RegCreateKeyEx(hKey, section, 0, "", 0, KEY_ALL_ACCESS, NULL, &hkSub, &dwDisposition) != ERROR_SUCCESS)
{
SHOW_INTERNAL_ERROR_REASON("Could not find password location for admin.");
return FALSE;
}
if(RegSetValueEx(hkSub, entry, 0, REG_SZ, (LPBYTE)(LPCTSTR(password)), (DWORD)(password.GetLength() + 1)) != ERROR_SUCCESS)
{
SHOW_INTERNAL_ERROR_REASON("Could not update admin password.");
return FALSE;
}
RegCloseKey(hkSub);
RegCloseKey(hKey);
return TRUE;
}
else
{
UserInfo orig_entry;
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
while(pos)
{
orig_entry = gPermissions.m_UserList.GetAt(pos);
if(strcmp(orig_entry.m_username, LPCTSTR(user)) == 0)
break;
gPermissions.m_UserList.GetNext(pos);
}
if(!pos)
{
CString errstr = "Could not find user '" + user + "'.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
UserInfo new_entry = orig_entry;
strcpy(new_entry.m_password, LPCTSTR(password));
gPermissions.m_UserList.RemoveAt(pos);
gPermissions.m_UserList.AddTail(new_entry);
if(!gPermissions.WriteUsers())
{
//restore state
gPermissions.m_UserList.RemoveTail();
gPermissions.m_UserList.AddTail(orig_entry);
SHOW_INTERNAL_ERROR_REASON("Unable to update stored permission.");
return FALSE;
}
return TRUE;
}
}
BOOL CPermissions::GetPassword(CString user, CString *password)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if((user.IsEmpty()) || !password)
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
UserInfo entry;
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
while(pos)
{
entry = gPermissions.m_UserList.GetAt(pos);
if(strcmp(entry.m_username, LPCTSTR(user)) == 0)
break;
gPermissions.m_UserList.GetNext(pos);
}
if(!pos)
{
CString errstr = "Could not find user '" + user + "'.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
*password = entry.m_password;
return TRUE;
}
BOOL CPermissions::SetPerm(CString user, AppAction action, BOOL allowed)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if((user.IsEmpty()) || (action == enderror))
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(user == ADMIN_USERNAME)
{
SHOW_INTERNAL_ERROR_REASON("Cannot cange permissions of 'admin' user.");
return FALSE;
}
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
UserInfo orig_entry;
while(pos)
{
orig_entry = gPermissions.m_UserList.GetAt(pos);
if(strcmp(orig_entry.m_username, LPCTSTR(user)) == 0)
break;
gPermissions.m_UserList.GetNext(pos);
}
if(!pos)
{
CString errstr = "Could not find user '" + user + "'.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
UserInfo new_entry = orig_entry;
int index = (int)action;
int sizeofperm = sizeof(int) * 8; //in bits
int bytenumber = index / sizeofperm;
int bitnumber = index % sizeofperm;
unsigned int *val = &(new_entry.m_perms[bytenumber]);
int join = 1 << bitnumber;
if(allowed)
{
*val = *val | join;
}
else
{
join = ~join;
*val = *val & join;
}
gPermissions.m_UserList.RemoveAt(pos);
gPermissions.m_UserList.AddTail(new_entry);
if(!gPermissions.WriteUsers())
{
//restore state
gPermissions.m_UserList.RemoveTail();
gPermissions.m_UserList.AddTail(orig_entry);
SHOW_INTERNAL_ERROR_REASON("Unable to update stored permission.");
return FALSE;
}
return TRUE;
}
BOOL CPermissions::GetPerm(CString user, AppAction action)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if((user.IsEmpty()) || (action == enderror))
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(user == ADMIN_USERNAME)
return TRUE;
POSITION pos = gPermissions.m_UserList.GetHeadPosition();
UserInfo entry;
while(pos)
{
entry = gPermissions.m_UserList.GetAt(pos);
if(strcmp(entry.m_username, LPCTSTR(user)) == 0)
break;
gPermissions.m_UserList.GetNext(pos);
}
if(!pos)
{
CString errstr = "Could not find user '" + user + "'.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
int index = (int)action;
int sizeofperm = sizeof(int) * 8; //in bits
int bytenumber = index / sizeofperm;
int bitnumber = index % sizeofperm;
unsigned int val = entry.m_perms[bytenumber];
val = val >> bitnumber;
BOOL allowed;
allowed = val & 1;
return allowed;
}
BOOL CPermissions::GetCurrentUser(CString *user)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(!user)
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
*user = gPermissions.m_CurrentUser;
return TRUE;
}
BOOL CPermissions::SetCurrentUser(CString user)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(user.IsEmpty())
{
SHOW_INTERNAL_ERROR;
return FALSE;
}
if(!IsUserExisting(user))
{
CString errstr = "Could not find the user '" + user + "'.";
SHOW_INTERNAL_ERROR_REASON(errstr);
return FALSE;
}
gPermissions.m_CurrentUser = user;
return TRUE;
}
BOOL CPermissions::IsAdmin()
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
CString admin = ADMIN_USERNAME;
return (gPermissions.m_CurrentUser == admin);
}
BOOL CPermissions::IsAllowed(AppAction action)
{
if(!gPermissions.m_PermsInitialized)
{
if(!gPermissions.ReadUsers())
{
SHOW_INTERNAL_ERROR_REASON("Unable to read stored permission.");
return FALSE;
}
}
if(gPermissions.m_CurrentUser.IsEmpty())
{
SHOW_INTERNAL_ERROR_REASON("No valid user selected.");
return FALSE;
}
if(IsAdmin())
return TRUE;
return GetPerm(gPermissions.m_CurrentUser, action);
}
| true |
272ee54be64510c3855838646c408f2d0625218d | C++ | Tasari/University_things | /Bioinformatics-intro/Zestaw 1/C++/Zadanie 5/main.cpp | UTF-8 | 428 | 3.28125 | 3 | [] | no_license | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int number, reversed = 0;
printf("Podaj liczbe aby pokazac ja w odwrotnej kolejnosci\n");
scanf("%d", &number);
while(number>0){
reversed = reversed*10 + number%10;
number = number/10;
}
printf("Twoja liczba w odwrotnej kolejnosci: %d", reversed);
return 0;
}
| true |
d020e31bb86f0720c16fa302544b02dddd8ee2c5 | C++ | sramepa1/qtunneler | /Projectile.h | UTF-8 | 1,211 | 2.5625 | 3 | [] | no_license | /*
* -----------------------------------------------
* QTunneler - a classic DOS game remake in QT
* -----------------------------------------------
*
* semestral project for API programming course
* (Y36API) at the FEE CTU Prague
*
* Created by:
* Pavel Sramek (sramepa1@fel.cvut.cz)
* Martin Smarda (smardmar@fel.cvut.cz)
*
* March & April 2010
*
* This is free software, licensed under GNU LGPL
* (GNU Lesser General Public License, version 3)
* http://www.gnu.org/licenses/lgpl.html
*
* Project homepage:
* http://code.google.com/p/qtunneler/
*
* Version 1.0
*
*/
#ifndef _PROJECTILE_H
#define _PROJECTILE_H
#include "DefaultValues.h"
#include "OrientedRoundObj.h"
/**
* This class represents the tank's shots.
*/
class Projectile : public OrientedRoundObj{
public:
Projectile(qint32 _x, qint32 _y, quint8 _color, qint32 _id, direction _rotation, qint32 _tankID = NO_PLAYER) : OrientedRoundObj(_x, _y, PROJECTILE_RADIUS, _color, _id, _rotation), tankID(_tankID) {}
//Projectile(const Projectile& orig) : OrientedRoundObj(orig) {} // implicit
virtual ~Projectile() {}
qint32 tankID;
};
#endif /* _PROJECTILE_H */
| true |
b4516a20c9babcd0d661048f2108f4b7f2221208 | C++ | YaelHacmon/reversi | /include/ViewGame.h | UTF-8 | 1,778 | 3.390625 | 3 | [] | no_license | /*
*/
#ifndef VIEWGAME_H_
#define VIEWGAME_H_
#include "Board.h"
#include <vector>
using namespace std;
/**
* Represents the view of the game, handles any interaction with the player.
* All functions are pure virtual, seeing as implementation depends on viewing tools (console, GUI, etc.)
*/
class ViewGame {
public:
//virtual c'tor and d'tor (must have - includes virtual methods)
ViewGame() {}
virtual ~ViewGame() {}
// present the board
virtual void printBoard(Board::ElementInBoard** board, int sizeOfBoard) const = 0;
// message to switch turns
virtual void messageForTurn (string curPlayer) const = 0;
// message of possible moves
virtual void messagePossibleMoves(const vector<Location> &possibleMoves) const = 0;
// display the player's last move
virtual void messagePlayerMove(Location pointToDisplay, string curPlayer) const = 0;
// message who is the winner
virtual void messageWinner(string winPlayer) const = 0;
//show any type of message
virtual void showMessage(string stringToShow) const = 0;
//shows switching turns message and waits for any key press
virtual void messageSwitchTurns() const = 0;
//gets move from outside user of game
virtual Location getMoveFromUser() const = 0;
/**
* Shows the options in the vector by option's index, and returns user's choice.
*
* Index 0 should be menu's title, and other indexes should hold the matching message for the option.
* Messages should fit the format: "To MESSAGE, press INDEX"
*
* @param options of menu to be presented
* @return chosen index
*/
virtual int presentMenu(const vector<string>& menuOpps) const = 0;
//returns the string input from user
virtual string getStringInput() const = 0;
};
#endif /* VIEWGAME_H_ */
| true |
b24c774ce67722c5ef02e107b087f97d95a2c77c | C++ | larajanecka/notes | /Old-Notes/2b/CS247/Tutorial/Resources6/examples/04-moving/main.cc | UTF-8 | 562 | 3 | 3 | [] | no_license | /*
* Ch. 3 of "Programming with gtkmm", pp. 11-14
*
* Displays a labelled button in a window. When the button is clicked, the text "Hello World" is printed
* to standard output.
*/
#include <gtkmm/main.h>
#include "hidebuttons.h"
int main( int argc, char * argv[] ) {
Gtk::Main kit( argc, argv ); // Initialize gtkmm with the command line arguments, as appropriate.
HideButtons mischief; // Create the window with the button.
Gtk::Main::run( mischief ); // Show the window and return when it is closed.
return 0;
} // main | true |
0fe956888f6b02282172289e73adfad37b0b092b | C++ | ariesha-1702/DSA-450 | /Matrix/9-Find distinct elements.cpp | UTF-8 | 645 | 2.765625 | 3 | [] | no_license | // https://practice.geeksforgeeks.org/problems/find-distinct-elements2054/1
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int distinct(vector<vector<int>> m, int n)
{
unordered_map<int,int> map;
int c=0;
for(int i=0;i<n;i++)
{
map[m[0][i]]=1;
}
for(int i=1;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(map[m[i][j]] && map[m[i][j]]==i)
{
map[m[i][j]]++;
if(i==n-1) c++;
}
}
}
return c;
}
}; | true |
15bfb2a262870c5d42663c4209ab97cd878afb25 | C++ | VitalSquared/OOP_CPP | /lab1/RNA.h | UTF-8 | 1,843 | 3.28125 | 3 | [] | no_license | #ifndef LAB1_RNA_H
#define LAB1_RNA_H
#include <unordered_map>
#define PAIRS_IN_SIZE_T (sizeof(size_t) * 4)
using namespace std;
enum Nucleotide { A, G, C, T };
class RNA {
private:
Nucleotide _nucl = A;
size_t _size = 0;
size_t _capacity = 0;
size_t *_nucleotides = nullptr;
void update_capacity();
size_t fill_nucleotides(Nucleotide nucleotide);
void add_nucleotide(Nucleotide);
Nucleotide get_nucleotide(size_t index) const;
void set_nucleotide(Nucleotide nucleotide, size_t index);
public:
class nucl_ref {
private:
RNA *_rna;
size_t _idx = 0;
public:
nucl_ref(RNA &rna, size_t idx);
operator Nucleotide() const;
nucl_ref& operator=(Nucleotide nucleotide);
};
class const_nucl_ref {
private:
const RNA *_rna;
size_t _idx = 0;
public:
const_nucl_ref(const RNA &rna, size_t idx);
operator Nucleotide() const;
};
//constructors and destructors//
RNA(Nucleotide nucleotide, size_t capacity);
RNA(const RNA &rna);
virtual ~RNA();
//general
size_t length();
size_t capacity();
void trim(size_t from);
std::pair<RNA, RNA> split(size_t index);
bool is_complementary(const RNA& rna);
size_t cardinality(Nucleotide value);
std::unordered_map<Nucleotide, int> cardinality();
//operators
RNA& operator=(const RNA& rna);
RNA& operator+=(Nucleotide nucleotide);
friend RNA operator+(const RNA& rna1, RNA const& rna2);
friend bool operator==(const RNA& rna1, const RNA& rna2);
friend bool operator!=(const RNA& rna1, const RNA& rna2);
RNA operator!();
nucl_ref operator[](size_t index);
const_nucl_ref operator[](size_t index) const;
friend std::ostream& operator<<(std::ostream& os, const RNA& rna);
};
#endif
| true |
cfc70c3013e46ffda1864019aac89af5cd66d384 | C++ | duanmao/leetcode | /198. House Robber.cpp | UTF-8 | 473 | 2.796875 | 3 | [] | no_license | // Time: O(n), space: O(n)
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (nums.empty()) return 0;
if (n == 1) return nums[0];
if (n == 2) return max(nums[0], nums[1]);
vector<int> f(n, 0);
f[0] = nums[0];
f[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; ++i) {
f[i] = max(f[i - 2] + nums[i], f[i - 1]);
}
return f[n - 1];
}
};
| true |
acff4722199dd4822cd4624ca54e9d4200307ae1 | C++ | tonaaskarwur/YARP-Behavior-Trees | /yarp_modules/include/blackboard.h | UTF-8 | 3,801 | 3.375 | 3 | [
"MIT"
] | permissive | #ifndef BLACK_BOARD_H
#define BLACK_BOARD_H
#include <memory> // for shared_ptr
#include <string>
#include <vector>
#include <yarp/os/Property.h> // the blackboard is a yarp property
#include <cmath> //double_t, int_t etc
#include <iostream>
class BlackBoard
{
public:
BlackBoard();
//template< typename T >
//void SetValue(const std::string& name,const std::string& type, const T& data)
void SetValue(const std::string& name,const std::string& type, yarp::os::Value data)
{
// for(std::shared_ptr<Property> p : content_)
// {
// /*Finds the variable in the blackboard. If exists, it checks that the type is correct.
// If it does not exists, it creates the new variable in the blackboard*/
// if (name == p.get()->name())
// {
// if (p.get()->type() == type)
// {
// Property* ptr = p.get();
// ((TypedProperty<T>*)ptr)->set_data(data);
// return;
// }
// else
// {
// std::string error_message = "The variable " + name + " exists already as type" + type;
// throw std::invalid_argument(error_message.c_str());
// return;
// }
// }
// }
//TODO check
//the variable is new
yarp::os::Value value = content_2.find(name);
/*Finds the variable in the blackboard. If exists, it checks that the type is correct.
If it does not exists, it creates the new variable in the blackboard*/
if(value.isNull())
{
std::cout << "setting new variable " << name<< "Value: " << data.asString()<< std::endl;
content_2.put(name,data);
std::cout << content_2.toString() << std::endl;
}
else
{
std::cout << "setting existing variable" << std::endl;
content_2.unput(name);
content_2.put(name,data);
}
}
//void PrintContent();
template< typename T >
void PrintContent()
{
// for(std::shared_ptr<Property> p : content_)
// {
// std::string name = p.get()->name();
// Property* ptr = p.get();
// T value = ((TypedProperty<T>*)ptr)->data();
// std::cout << name << " Has Value " << value <<std::endl;
// }
}
void PrintBlackBoard();
// void DeclareVariable(std::string name, std::string type);
// template< typename T >
// T GetValueOf(std::string name)
// {
// for(std::shared_ptr<Property> p : content_)
// {
// if (name == p.get()->name())
// {
// Property* ptr = p.get();
// return ((TypedProperty<T>*)ptr)->data();
// }
// }
// }
public:
int GetInt(std::string name);
int16_t GetI16(std::string name);
int32_t GetI32(std::string name);
int64_t GetI64(std::string name);
int8_t GetByte(std::string name);
bool GetBool(std::string name);
double_t GetDouble(std::string name);
std::string GetString(std::string name);
private:
//std::vector< std::shared_ptr<Property> > content_;
yarp::os::Property content_2;
//template< typename T >
//void SetNew(const std::string& name,const std::string& type, const T& value) //used by SetValue is variable is new
void SetNew(const std::string& name, yarp::os::Value value) //used by SetValue is variable is new
{
// std::shared_ptr<TypedProperty<T>> new_element (new TypedProperty<T>(name, type, data));
// content_.push_back(new_element);
content_2.put(name,value);
}
};
#endif // BLACK_BOARD_H
| true |
fe969e8960bfa5fa298a08224193b897889f8bc0 | C++ | HJPyo/C | /킹실한갓미.cpp | UTF-8 | 477 | 2.59375 | 3 | [] | no_license | #include <stdio.h>
int nx, ny, ar[12][12];
int main()
{
for(int i = 1; i <= 10; i++){
for(int j = 1; j <= 10; j++){
scanf("%d", &ar[i][j]);
}
}
nx = ny = 2;
while(ar[nx][ny] != 2){
ar[nx][ny] = 9;
if(ar[nx][ny+1] != 1 && nx <= 10){
ny++;
}
else if(ar[nx+1][ny] != 1 && ny <= 10){
nx++;
}
else{
break;
}
}
ar[nx][ny] = 9;
for(int i = 1; i <= 10; i++){
for(int j = 1; j <= 10; j++){
printf("%d ", ar[i][j]);
}
puts("");
}
}
| true |
be8c8b72de766cab525da58d041aa546fc8bd92f | C++ | Miliox/gb_emulator | /src/debugger.cpp | UTF-8 | 5,531 | 2.640625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | /*
* debugger.cpp
* Copyright (C) 2017 Emiliano Firmino <emiliano.firmino@gmail.com>
*
* Distributed under terms of the MIT license.
*/
#include "debugger.hpp"
#include <iostream>
#include <iomanip>
#include <utility>
#include <vector>
Debugger::Debugger(GBCPU& cpu, GBGPU& gpu, GBJoypad& joypad) :
cpu(cpu), gpu(gpu), mmu(cpu.mmu), joypad(joypad), window(nullptr), renderer(nullptr), font(nullptr) {
}
void Debugger::show() {
if (!window) {
window = SDL_CreateWindow("GBDebugger",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
700,
900,
SDL_WINDOW_SHOWN);
if (window) {
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
std::cerr << "SDL_CreateRenderer failed: " << SDL_GetError() << "\n";
}
font = TTF_OpenFont("res/font/DroidSansMono.ttf", 12);
if (font) {
TTF_SetFontHinting(font, TTF_HINTING_MONO);
} else {
std::cerr << "TTF_OpenFont failed: " << TTF_GetError() << "\n";
}
} else {
std::cerr << "SDL_CreateWindow failed: " << SDL_GetError() << "\n";
}
}
}
void Debugger::hide() {
if (!font) {
TTF_CloseFont(font);
font = nullptr;
}
if (renderer) {
SDL_DestroyRenderer(renderer);
renderer = nullptr;
}
if (window) {
SDL_DestroyWindow(window);
window = nullptr;
}
}
void Debugger::draw() {
if (!window || !renderer || !font) {
return;
}
auto reg_dump = dump_registers();
auto mem_dump = dump_memory();
auto cpu_dump = dump_executed_instructions();
std::vector<std::string> lines;
lines.push_back("CPU Registers:");
lines.insert(lines.end(), reg_dump.begin(), reg_dump.end());
lines.push_back("CPU History:");
lines.insert(lines.end(), cpu_dump.begin(), cpu_dump.end());
lines.push_back("IRAM Dump:");
lines.insert(lines.end(), mem_dump.begin(), mem_dump.end());
std::vector<std::pair<SDL_Surface*, SDL_Texture*>> render_list;
for (auto &line : lines) {
auto surface = TTF_RenderText_Shaded(font, line.c_str(), {0, 0, 0, 0}, {255, 255, 255, 0});
auto texture = SDL_CreateTextureFromSurface(renderer, surface);
render_list.push_back(std::make_pair(surface, texture));
}
SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
SDL_RenderClear(renderer);
int y = 0;
for (auto &render_pair : render_list) {
SDL_Rect rect = {0, y, 0, 0};
SDL_QueryTexture(render_pair.second, NULL, NULL, &rect.w, &rect.h);
SDL_RenderCopy(renderer, render_pair.second, NULL, &rect);
y += rect.h;
}
SDL_RenderPresent(renderer);
for (auto &render_pair : render_list) {
SDL_DestroyTexture(render_pair.second);
SDL_FreeSurface(render_pair.first);
}
}
std::vector<std::string> Debugger::dump_registers() {
std::stringstream cpu_register_dump;
cpu_register_dump << std::hex;
cpu_register_dump << "a:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.a) << " ";
cpu_register_dump << "f:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.f) << " ";
cpu_register_dump << "b:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.b) << " ";
cpu_register_dump << "c:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.c) << " ";
cpu_register_dump << "d:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.d) << " ";
cpu_register_dump << "e:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.e) << " ";
cpu_register_dump << "h:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.h) << " ";
cpu_register_dump << "l:" << std::setw(2) << std::setfill('0') << static_cast<uint16_t>(cpu.reg.l) << " ";
cpu_register_dump << ((cpu.reg.f & 0x80) ? "z" : "-");
cpu_register_dump << ((cpu.reg.f & 0x40) ? "n" : "-");
cpu_register_dump << ((cpu.reg.f & 0x20) ? "h" : "-");
cpu_register_dump << ((cpu.reg.f & 0x10) ? "c" : "-") << "\n";
cpu_register_dump << "bc:" << std::setw(4) << std::setfill('0') << cpu.reg.bc << " ";
cpu_register_dump << "de:" << std::setw(4) << std::setfill('0') << cpu.reg.de << " ";
cpu_register_dump << "hl:" << std::setw(4) << std::setfill('0') << cpu.reg.hl << " ";
cpu_register_dump << "sp:" << std::setw(4) << std::setfill('0') << cpu.reg.sp << " ";
cpu_register_dump << "pc:" << std::setw(4) << std::setfill('0') << cpu.reg.pc << "\n";
cpu_register_dump << std::dec;
return text_to_line_vector(cpu_register_dump);
}
std::vector<std::string> Debugger::dump_memory() {
std::stringstream iram_dump = print_bytes(mmu.iram.begin(), mmu.iram.begin() + 256);
return text_to_line_vector(iram_dump);
}
std::vector<std::string> Debugger::dump_executed_instructions() {
std::vector<std::string> lines;
while (!last_cpu_instructions.empty()) {
lines.push_back(last_cpu_instructions.front().to_string());
last_cpu_instructions.pop();
}
return lines;
}
void Debugger::log_instruction() {
if (last_cpu_instructions.size() > 32) {
last_cpu_instructions.pop();
}
last_cpu_instructions.push(Instruction(
cpu.reg.pc,
cpu.mmu.read_byte(cpu.reg.pc),
cpu.mmu.read_byte(cpu.reg.pc + 1),
cpu.mmu.read_byte(cpu.reg.pc + 2))
);
}
| true |
a9649b329cca0502a486172accdcefe5a080133a | C++ | cyph3rk/Challenges | /1117.cpp | UTF-8 | 429 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
double notas[2] = { 0, 0 };
int contador = 0;
while (contador < 2) {
cin >> notas[contador];
if ( (notas[contador] >= 0) && (notas[contador] <= 10) ) {
contador++;
}
else {
cout << "nota invalida" << endl;
}
}
cout.precision(2);
cout << fixed;
cout << "media = " << (notas[0] + notas[1]) / 2 << endl;
return 0;
}
| true |
45a77abaf898f1d7486c173239a9bb1792d96930 | C++ | AC3Productions/Forte | /Forte/Source/SpriteSystem.cpp | UTF-8 | 1,341 | 2.78125 | 3 | [] | no_license | // file: SpriteSystem.cpp
// author: Alfaroh Corney III
// date: 3/23/2021
//
// info:
// Description of the purpose of the file goes here.
#pragma once
#include <SpriteSystem.h>
#include <GameObject.h>
#include <SpriteComponent.h>
SpriteSystem* SpriteSystem::m_instance = nullptr;
SpriteSystem* SpriteSystem::Instance()
{
if (!m_instance)
{
m_instance = new SpriteSystem;
}
return m_instance;
}
SpriteSystem::SpriteSystem() : FSystem("Sprite System")
{
}
void SpriteSystem::Init()
{
}
FSprite* SpriteSystem::CreateComponent()
{
FSprite* new_comp = new FSprite;
m_components.push_back(new_comp);
return new_comp;
}
void SpriteSystem::DestroyComponent(FSprite*& sprite)
{
// Find the object and destroy it
for (auto it : m_components)
{
if (it == sprite)
{
delete it;
it = nullptr;
sprite = nullptr;
}
}
}
void SpriteSystem::Update(float dt)
{
UNREF_PARAM(dt);
m_world_to_window = static_cast<float>(GetScreenWidth()) / TRUE_WIDTH;
}
void SpriteSystem::Render()
{
// Render all sprites
for (auto it : m_components)
{
if (it)
{
GameObject* obj = it->GetParent();
if (obj && obj->IsEnabled())
{
it->Render();
}
}
}
}
SpriteSystem::~SpriteSystem()
{
for (auto it : m_components)
{
delete it;
}
}
| true |
9297a54cb1801afa1903c71737b5e62dfd1e7537 | C++ | acgourley/simple-disk-utils | /Windows/DiskUtilsWinAPI/DiskUtilsWinAPI/HardDiskManager.cpp | UTF-8 | 1,786 | 2.578125 | 3 | [
"MIT"
] | permissive | // HardDiskManager.cpp: implementation of the CHardDiskManager class.
// LICENSE: http://www.codeproject.com/info/cpol10.aspx
//////////////////////////////////////////////////////////////////////
#include "HardDiskManager.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHardDiskManager::CHardDiskManager()
{
// bytes available to caller
m_uliFreeBytesAvailable.QuadPart = 0L;
// bytes on disk
m_uliTotalNumberOfBytes.QuadPart = 0L;
// free bytes on disk
m_uliTotalNumberOfFreeBytes.QuadPart = 0L;
}
CHardDiskManager::~CHardDiskManager()
{
}
bool CHardDiskManager::CheckFreeSpace(LPCTSTR lpDirectoryName)
{
if( !GetDiskFreeSpaceEx(
lpDirectoryName, // directory name
&m_uliFreeBytesAvailable, // bytes available to caller
&m_uliTotalNumberOfBytes, // bytes on disk
&m_uliTotalNumberOfFreeBytes) ) // free bytes on disk
return false;
return true;
}
DWORD64 CHardDiskManager::GetFreeBytesAvailable(void)
{
return m_uliFreeBytesAvailable.QuadPart;
}
DWORD64 CHardDiskManager::GetTotalNumberOfBytes(void)
{
return m_uliTotalNumberOfBytes.QuadPart;
}
DWORD64 CHardDiskManager::GetTotalNumberOfFreeBytes(void)
{
return m_uliTotalNumberOfFreeBytes.QuadPart;
}
double CHardDiskManager::GetFreeGBytesAvailable(void)
{
return (double)( (signed __int64)(m_uliFreeBytesAvailable.QuadPart)/1.0e9 );
}
double CHardDiskManager::GetTotalNumberOfGBytes(void)
{
return (double)( (signed __int64)(m_uliTotalNumberOfBytes.QuadPart)/1.0e9 );
}
double CHardDiskManager::GetTotalNumberOfFreeGBytes(void)
{
return (double)( (signed __int64)(m_uliTotalNumberOfFreeBytes.QuadPart)/1.0e9 );
}
| true |
99f33f364ec7c97b106f68d5b0afeb4d8b0c7043 | C++ | JJJoonngg/Algorithm | /백준/1783_병든나이트.cpp | UHC | 1,457 | 3.328125 | 3 | [] | no_license | /*
https://www.acmicpc.net/problem/1783
Ʈ N * M ũ ü ʾƷ ĭ ġ ִ. Ʈ ǰ ü Ʈ ٸ 4θ ִ.
2ĭ , 1ĭ
1ĭ , 2ĭ
1ĭ Ʒ, 2ĭ
2ĭ Ʒ, 1ĭ
Ʈ , ü Ʈ̱ ĭ 湮ϰ ; Ѵ.
Ʈ ̵ ִ. , ̵ Ƚ 4 ̻ 쿡 ̵ ̻ ̿ؾ Ѵ.
ü ũⰡ ־ , Ʈ 湮 ִ ĭ ִ ϴ α ۼϽÿ. ó ִ ĭ .
Է
ù° ٿ ü N M ־. N M 2,000,000,000 ۰ų ڿ̴.
100 50
1 1
17 5
2 4
20 4
Ʈ 湮 ִ ĭ ִ Ѵ.
48
1
4
2
4
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n, m;
cin >> n >> m;
if (n == 1) cout << "1\n";
else if (n == 2) cout << min(4, (m + 1) / 2) << "\n";
else if (m < 7) cout << min(4, m) << "\n";
else cout << m - 2 << "\n";
} | true |
7112adb37b12139544b820f7f64bdc4d76313353 | C++ | hhhhicode/Algorithm_Study_ver.1 | /057. 재귀함수 이진수 출력/main_057.cpp | UTF-8 | 217 | 3.359375 | 3 | [] | no_license | #include <iostream>
void binaryRecursive(const int& N)
{
if (N == 0) return;
binaryRecursive(N / 2);
std::cout << N % 2;
}
int main()
{
using namespace std;
int N;
cin >> N;
binaryRecursive(N);
return 0;
} | true |
172f6cc739b71f2d98b4c88c6b03f5b26eda5bc6 | C++ | J4ck5ilver/DX12-Portfolio-Scene | /src/Engine/Assetmanager/AssetFile.hpp | UTF-8 | 4,793 | 2.609375 | 3 | [] | no_license | #ifndef ASSETFILE_HPP
#define ASSETFILE_HPP
#include<string>
#define FE_JPG "jpg"
#define FE_DDS "dds"
#define FE_PNG "png"
#define FE_OBJ "obj"
#define FE_MAT "mat"
#define FE_XML "xml"
template<typename T>
class AssetFile
{
public:
enum class FileType
{
EmptyType = 0,
MeshType = 1,
TextureType = 2,
MaterialType = 3,
XMLType = 4
};
private:
//may not be needed
//bool m_On_GPU;
//bool m_On_CPU;
T** m_Data;
FileType m_Type;
std::string m_FileName;
std::string m_FilePath;
std::string m_FileExtension;
friend class Assetmanager;
public:
AssetFile(const std::string& FilePath = "") noexcept;
~AssetFile() noexcept;
AssetFile(const AssetFile& other) noexcept;
AssetFile& operator=(const AssetFile& other) noexcept;
const bool& OnCPU() noexcept;
//May not be needed (if needed, inheritance to other classes?)
//const bool& OnGPU() noexcept;
inline T* GetData() noexcept { return *m_Data; }
inline const FileType& GetType() const noexcept { return m_Type; }
inline const std::string& GetFileName() noexcept { return m_FileName; }
inline const std::string& GetFilePath() noexcept { return m_FilePath; }
inline const std::string& GetFileExtension() noexcept { return m_FileExtension; }
private:
void Shutdown();
void RemoveFromCPU();
void SetDataPtr(T* dataPtr);
const void SetInfoFromPath() noexcept; // Should throw warning
FileType GetFileType();
//const void SetFileName() noexcept; // Should throw
};
template<typename T>
AssetFile<T>::AssetFile(const std::string& FilePath) noexcept :
m_FileExtension(""),
m_FilePath(FilePath),
m_Data(nullptr)
{
SetInfoFromPath();
if (m_Type != FileType::EmptyType)
{
m_Data = new T* {nullptr};
//*m_Data = nullptr;
}
}
template<typename T>
AssetFile<T>::~AssetFile() noexcept
{
//Use shutdown at the end
//if (m_Type == FileType::EmptyType)
//{
// delete m_Data;
// m_Data = nullptr;
//}
//if (m_Data)
//{
// //To Do
// //other assetfiles of same type will delete this. (made as copy)
// delete m_Data;
// m_Data = nullptr;
//}
}
template<typename T>
AssetFile<T>::AssetFile(const AssetFile& other) noexcept
{
m_Data = other.m_Data;
m_Type = other.m_Type;
m_FilePath = other.m_FilePath;
m_FileName = other.m_FileName;
m_FileExtension = other.m_FileExtension;
}
template<typename T>
AssetFile<T>& AssetFile<T>::operator=(const AssetFile& other) noexcept
{
if (this != &other)
{
m_Data = other.m_Data;
m_Type = other.m_Type;
m_FilePath = other.m_FilePath;
m_FileName = other.m_FileName;
m_FileExtension = other.m_FileExtension;
}
return *this;
}
template<typename T>
const bool& AssetFile<T>::OnCPU() noexcept
{
bool returnValue = true;
if (*m_Data == nullptr)
{
returnValue = false;
}
return returnValue;
// return *m_Data;
}
template<typename T>
typename AssetFile<T>::FileType AssetFile<T>::GetFileType()
{
AssetFile<T>::FileType returnValue(AssetFile<T>::FileType::EmptyType);
if (m_FileExtension == FE_JPG || m_FileExtension == FE_PNG || m_FileExtension == FE_DDS)
{
returnValue = AssetFile<T>::FileType::TextureType;
}
else if (m_FileExtension == FE_OBJ)
{
returnValue = AssetFile<T>::FileType::MeshType;
}
else if (m_FileExtension == FE_MAT)
{
returnValue = AssetFile<T>::FileType::MaterialType;
}
else if (m_FileExtension == FE_XML)
{
returnValue = AssetFile<T>::FileType::XMLType;
}
return returnValue;
}
template<typename T>
inline void AssetFile<T>::Shutdown()
{
if (m_Data)
{
if (*m_Data)
{
delete* m_Data;
*m_Data = nullptr;
}
delete m_Data;
m_Data = nullptr;
}
}
template<typename T>
void AssetFile<T>::RemoveFromCPU()
{
if (*m_Data)
{
delete* m_Data;
*m_Data = nullptr;
}
else
{
//RemoveIfNotNeeded
//Debug if getting here
__debugbreak();
}
}
template<typename T>
void AssetFile<T>::SetDataPtr(T* dataPtr)
{
if (*m_Data)
{
RemoveFromCPU();
}
*m_Data = dataPtr;
}
template<typename T>
const void AssetFile<T>::SetInfoFromPath() noexcept
{
int16_t counter = m_FilePath.size() - 1;
//Simple Design (To Do: Add checks)
while (counter >= 0 && m_FilePath[counter] != '.')
{
m_FileExtension += m_FilePath[counter];
counter--;
}
std::reverse(m_FileExtension.begin(), m_FileExtension.end());
if (counter != 0)
{
counter--;
}
while (counter >= 0 && m_FilePath[counter] != '/' && m_FilePath[counter] != '\\' )
{
m_FileName += m_FilePath[counter];
counter--;
}
std::reverse(m_FileName.begin(), m_FileName.end());
m_Type = GetFileType();
////fast fix for meshes
//if (m_FileName == "")
//{
// if (m_FilePath.size() != 0)
// {
// if (m_FilePath[0] != '.')
// {
// m_FileName = m_FilePath;
// m_Type = AssetFile<T>::FileType::MeshType;
// }
// }
//}
}
#endif // !ASSETFILE_HPP | true |
99c525c773b9a06e1da5fddccedd929b8d853a79 | C++ | CM4all/beng-proxy | /src/escape/Static.hxx | UTF-8 | 545 | 2.71875 | 3 | [] | permissive | // SPDX-License-Identifier: BSD-2-Clause
// Copyright CM4all GmbH
// author: Max Kellermann <mk@cm4all.com>
/*
* Escaping with a static destination buffer.
*/
#pragma once
#include <string_view>
struct escape_class;
/**
* Unescape the given string into a global static buffer. Returns
* NULL when the string is too long for the buffer.
*/
[[gnu::pure]]
const char *
unescape_static(const struct escape_class *cls, std::string_view p) noexcept;
[[gnu::pure]]
const char *
escape_static(const struct escape_class *cls, std::string_view p) noexcept;
| true |
04f831afbcd9aed5336d89129eb72a550a60e0c5 | C++ | MissingJoe/Data-Structure | /Supplemental questions/2-b4.cpp | GB18030 | 2,517 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
typedef int Status;
typedef int ElemType;
typedef struct DuLNode {
ElemType data;
DuLNode* prior;
DuLNode* next;
}DulNode, * DuLinkList;
Status InitialDuLinkList(DuLinkList& l) {
//l = (DuLinkList)malloc(sizeof(DuLNode));
l = new DuLNode;
if (!l)
return -2;
l->next = l->prior = l;
l->data = 9999;
return 0;
}
/*ݻ˫ѭ*/
Status Destroy_Dul(DuLinkList& l) {
DuLNode* p = l->next, * q;
DuLNode* head = l;
while (p != head) {
q = p->next;
delete p;
p = q;
}
delete head;//ͷͷ
l = NULL;
return 0;
}
DuLNode* GetElemP_Dul(DuLinkList l, int i) {
DuLNode* p = l->next;
int length = 1;
while (p != l && i > length) {
length++;
p = p->next;
}
if (p == l && i > length)
return NULL;
else
return p;
}
int DulLength(DuLinkList l) {
DuLNode* p = l->next;
int length = 0;
while (p != l) {
length++;
p = p->next;
}
return length;
}
Status ListInsert_Dul(DuLinkList& l, int i, ElemType e) {
DuLNode* p = GetElemP_Dul(l, i);
if (p == NULL)
return -1;
DuLNode* s = new DuLNode;
if (s == NULL)
return -2;
s->data = e;
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
return 0;
}
Status ListDeleteValue_Dul(DuLinkList& l, ElemType e) {
DuLNode* p = l->next;
while (p != l && p->data != e)
p = p->next;
if (p == l)
return -1;
p->next->prior = p->prior;
p->prior->next = p->next;
return 0;
}
Status traverse(DuLinkList l) {
DuLNode* p = l->prior;
while (p != l) {
cout << p->data << " ";
p = p->prior;
}
cout << endl;
return 0;
}
DuLNode* GetElemP_Dul_UP(DuLinkList l, int i) {
DuLNode* p = l->prior;
int length = 1;
while (p != l && i > length) {
length++;
p = p->prior;
}
if (p == l && i > length)
return NULL;
else
return p;
}
void Joseph(DuLinkList& l, int m, int k) {
DuLNode* p = GetElemP_Dul_UP(l, k);
int count = 1;
while (DulLength(l) != 1) {
if (p->data == 9999) {
p = p->prior;
continue;
}
if (count == m) {
ListDeleteValue_Dul(l, p->data);
cout << p->data << "" << endl;
traverse(l);
count = 1;
}
else
count++;
p = p->prior;
}
}
int main() {
DuLinkList l;
InitialDuLinkList(l);
int m, n, k;
cin >> n >> m >> k;
for (int i = 0; i < n; i++)
ListInsert_Dul(l, DulLength(l)+1, i);
traverse(l);
Joseph(l, m, k);
Destroy_Dul(l);
return 0;
} | true |
fbb6d2988dae384c27e1a2f9b74d58c67f2cf4eb | C++ | cairijun/pork | /tests/test_broker_mq.cc | UTF-8 | 7,600 | 2.515625 | 3 | [] | no_license | #include <algorithm>
#include <atomic>
#include <memory>
#include <random>
#include <thread>
#include <vector>
#include <boost/chrono.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "broker/message_queue.h"
#include "proto_types.h"
using namespace testing;
namespace pork {
class BrokerMqTest: public Test {
protected:
void SetUp() override {
// speed up the tests
MessageQueue::POP_FREE_TIMEOUT = boost::chrono::milliseconds(50);
}
static Dependency make_dep(const std::string& key, int n) {
Dependency dep;
dep.key = key;
dep.n = n;
return dep;
}
static std::shared_ptr<Message> make_msg(
id_t id, const std::string& resolve_dep = "") {
auto msg = std::make_shared<Message>();
msg->__set_id(id);
msg->payload = "msg" + std::to_string(id);
msg->type = MessageType::NORMAL;
if (!resolve_dep.empty()) {
msg->__set_resolve_dep(resolve_dep);
}
return msg;
}
MessageQueue mq;
};
TEST_F(BrokerMqTest, PopTimeout) {
std::vector<std::thread> ts;
for (int i = 0; i < 20; ++i) {
ts.emplace_back([this] () {
Message msg;
EXPECT_FALSE(mq.pop_free_message(msg));
});
}
for (auto& t : ts) {
t.join();
}
}
TEST_F(BrokerMqTest, PushPopFreeMsgs) {
int n_msgs = 2000;
int n_producers = 5;
int n_consumers = 10;
std::vector<std::thread> ts;
std::atomic_int n_sent(0);
std::atomic_int n_recv(0);
for (int i = 0; i < n_producers; ++i) {
ts.emplace_back([this, n_msgs, &n_sent] () {
while (n_sent < n_msgs) {
int id = ++n_sent;
if (id <= n_msgs) {
mq.push_message(make_msg(id), {});
}
}
});
}
for (int i = 0; i < n_consumers; ++i) {
ts.emplace_back([this, n_msgs, &n_recv] () {
while (n_recv < n_msgs) {
Message msg;
if (mq.pop_free_message(msg)) {
++n_recv;
EXPECT_EQ(msg.payload, "msg" + std::to_string(msg.id));
}
}
});
}
for (auto& t : ts) {
t.join();
}
}
TEST_F(BrokerMqTest, MsgsWithDeps) {
Message recv;
auto msg11 = make_msg(11, "dep1");
auto msg21 = make_msg(12, "dep2");
auto msg22 = make_msg(21, "dep2");
auto msg31 = make_msg(31, "dep3");
auto msg1 = make_msg(1);
auto msg2 = make_msg(2);
auto msg3 = make_msg(3);
mq.push_message(msg11, {});
mq.pop_free_message(recv);
mq.push_message(msg21, {});
mq.pop_free_message(recv);
mq.push_message(msg22, {});
mq.pop_free_message(recv);
mq.push_message(msg31, {});
mq.pop_free_message(recv);
mq.push_message(msg1, {make_dep("dep1", 1), make_dep("dep2", 2)});
EXPECT_FALSE(mq.pop_free_message(recv));
mq.ack(msg11->id);
mq.push_message(msg2, {make_dep("dep1", 1), make_dep("dep2", 1)});
EXPECT_FALSE(mq.pop_free_message(recv));
mq.ack(msg31->id);
mq.push_message(msg3, {make_dep("dep1", 1), make_dep("dep3", 1)});
EXPECT_TRUE(mq.pop_free_message(recv));
EXPECT_EQ(*msg3, recv);
EXPECT_FALSE(mq.pop_free_message(recv));
mq.ack(msg21->id);
EXPECT_TRUE(mq.pop_free_message(recv));
EXPECT_EQ(*msg2, recv);
EXPECT_FALSE(mq.pop_free_message(recv));
mq.ack(msg22->id);
EXPECT_TRUE(mq.pop_free_message(recv));
EXPECT_EQ(*msg1, recv);
EXPECT_FALSE(mq.pop_free_message(recv));
}
TEST_F(BrokerMqTest, AckNonInProgressMsgs) {
Message recv;
auto m_queuing = make_msg(1, "dep");
auto m_failed = make_msg(2, "dep");
auto m_acked = make_msg(3, "dep");
auto m_in_progress = make_msg(4, "dep");
auto msg = make_msg(5);
mq.push_message(m_queuing, {make_dep("impossible", 1)});
mq.push_message(m_failed, {});
mq.pop_free_message(recv);
mq.fail(m_failed->id);
mq.push_message(m_acked, {});
mq.pop_free_message(recv);
mq.ack(m_acked->id);
mq.push_message(m_in_progress, {});
mq.pop_free_message(recv);
mq.push_message(msg, {make_dep("dep", 2)});
mq.ack(m_queuing->id);
mq.ack(m_failed->id);
mq.ack(m_acked->id);
EXPECT_FALSE(mq.pop_free_message(recv));
mq.ack(m_in_progress->id);
EXPECT_TRUE(mq.pop_free_message(recv));
EXPECT_EQ(*msg, recv);
}
TEST_F(BrokerMqTest, FakeWorkLoad) {
int n_msgs = 0;
int n_groups = 100;
int group_size = 10;
std::vector<std::shared_ptr<Message>> msgs;
for (int i = 0; i < n_groups; ++i) {
for (int j = 0; j < group_size; ++j) {
msgs.push_back(make_msg(n_msgs++, "dep" + std::to_string(i)));
}
}
std::mt19937 rng((std::random_device())());
std::exponential_distribution<double> exp_dist(0.2);
std::random_shuffle(msgs.begin(), msgs.end(), [&rng, &exp_dist] (int n) {
int x = exp_dist(rng);
if (x >= n) {
x = n - 1;
}
return x;
});
std::vector<std::thread> ts;
std::atomic_int idx(-1);
int n_producers = 5;
for (int i = 0; i < n_producers; ++i) {
ts.emplace_back([&] () {
int local_idx;
while (idx < n_msgs) {
local_idx = ++idx;
if (local_idx >= n_msgs) {
break;
}
auto msg = msgs[local_idx];
int group_id = msg->id / group_size;
if (group_id == 0) { // first group
mq.push_message(msg, {});
} else {
Dependency dep;
dep.key = "dep" + std::to_string(group_id - 1);
dep.n = group_size;
mq.push_message(msg, {dep});
}
}
});
}
auto* ack_count = new std::atomic_int[n_groups];
for (int i = 0; i < n_groups; ++i) {
ack_count[i] = 0;
}
int n_consumers = 10;
std::atomic_int n_recv(0);
for (int i = 0; i < n_consumers; ++i) {
ts.emplace_back([&] () {
while (n_recv < n_msgs) {
Message recv;
if (mq.pop_free_message(recv)) {
++n_recv;
int group_id = recv.id / group_size;
if (group_id != 0) {
EXPECT_EQ(group_size, ack_count[group_id - 1]);
}
++ack_count[group_id];
mq.ack(recv.id);
}
}
});
}
for (auto& t : ts) {
t.join();
}
delete[] ack_count;
}
}
| true |
69af9d6d1c9971265de0bf52d37c483b462dd2a3 | C++ | Spectra456/LabsCPP2017 | /B6/main.cpp | UTF-8 | 681 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include "task-headers.hpp"
int main(int argc, char *argv[])
{
if (argc == 1)
{
std::cerr <<"Restart and type the arguments, please" <<std::endl;
return 1;
}
char * error;
int numsize = strtol(argv[1], &error, 10);
if (*error)
{
std::cerr <<"Restart and type correct arguments, please" <<std::endl;
return 1;
}
switch (numsize)
{
case 1:
return part_1();
case 2:
/*if (argc <= 2)
{
std::cerr <<"Restart and define name of file, please" <<std::endl;
return 1;
}*/
return part_2();
default:
std::cerr <<"Restart and type correct arguments, please" <<std::endl;
return 1;
}
}
| true |
f6fd53baaaaef11203321934ccafe6eea954f9fa | C++ | abhishekp314/-PC--Blazing-Racer | /Blazing Racer PC v1/Blazing Racer PC v1/Graphics/Camera.cpp | UTF-8 | 1,026 | 2.71875 | 3 | [] | no_license | #include "stdafx.h"
#include "Camera.h"
namespace Graphics
{
Camera::Camera(void)
{
m_mProjMat = XMMatrixIdentity();
m_mViewMat = XMMatrixIdentity();
m_vLookAt.x = 0.0f;
m_vLookAt.y = 0.0f;
m_vLookAt.z = -1.0f;
m_vLookAt.w = 0.0f;
m_vEye.x = 0.0f;
m_vEye.y = 0.0f;
m_vEye.z = 0.0f;
m_vEye.w = 0.0f;
m_Target = XMFLOAT3(0,0,0);
}
Camera::~Camera(void)
{
}
bool Camera::InitCamera()
{
//m_mProjMat = XMMatrixPerspectiveFovLH( XM_PIDIV4, (float)16/9, 1.0f, 200.0f );
return true;
}
void Camera::SetTarget(XMFLOAT3 _target,float _zoomFactor)
{
_zoomFactor = 1;
m_mProjMat = XMMatrixOrthographicLH(1280*_zoomFactor,720*_zoomFactor,-1,10);
m_Target = _target;
m_vLookAt = Float3ToVec(_target);
m_vLookAt.w = 0;
m_vEye.x = m_Target.x;
m_vEye.y = m_Target.y;
m_vEye.z = -1;
}
void Camera::Update()
{
XMVECTOR vUp = { 0.0f, 1.0f, 0.0f, 0.0f };
m_mViewMat = XMMatrixLookAtLH( m_vEye, m_vLookAt, vUp );
return;
}
void Camera::Destroy()
{
}
}
| true |
9990b21b02f2883839fb8b1612f59a0fa9ec27a5 | C++ | V-vp/SPOJ | /absp1.cpp | UTF-8 | 358 | 3.078125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
ll array[n];
for(int i=0;i<n;i++)
cin>>array[i];
ll sum=0;
for(int i=0;i<n;i++)
{
sum+=(array[i]*i);
sum-=array[i]*(n-i-1);
}
cout<<sum<<"\n";
}
}
| true |
7c88b86c58d83b8d55f6486d587aefd0a64e8eaf | C++ | dotQuestionmark/git-github-fundamentals-mukeshgurpude | /Learn-CPP/Day-05/array_intro.cpp | UTF-8 | 626 | 4.34375 | 4 | [] | no_license | // Arrays are the lists of similar data types
#include<iostream>
using namespace std;
int main(void){
// <datatype> arrayName [arraySize]
int arr[] = {1, 2, 3, 4, 5}; // With size as much as the given initialzers
int arr1[5] = {1, 2, 3}; // Give the values for 3 places, remaining are 0
int arr2[5] = {}; // All five elements are 0
// int arr[3] = {1, 2, 3, 4}; // Gives erros, as size of array is 3, but 4 initializers are given
// print array
for(int i=0; i<5; i++) cout<<arr[i]<<" ";
cout<<endl;
// Read array from the user
for(int i=0; i<5; i++) cin>>arr2[i];
return 0;
}
| true |
008b744f73c6922956009585fec9d0f577445b47 | C++ | amironi/Interviews | /Calculator/Utils.h | UTF-8 | 753 | 3.140625 | 3 | [] | no_license |
#pragma once
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <algorithm> // std::all_of
using namespace std;
inline vector<string> split(const string& str, const string& delim)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
inline bool is_number(const std::string &s) {
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
} | true |
faf1d274f962893b9f131756523a0c6431ad32c9 | C++ | OneMillionBytes/PWMControl | /Src/PWMTimer.cpp | UTF-8 | 1,147 | 2.640625 | 3 | [] | no_license | #include "PWMTimer.hpp"
#include "stm32f1xx_hal.h"
#include "stdio.h"
const char* timerStatusTemplate =
"Prescaler: %u\n"
"Period: %u\n"
"Compare: %u\n";
PWMTimer::PWMTimer(TIM_HandleTypeDef& a_TimerHandle) :
m_TimerHandle(a_TimerHandle) {}
void PWMTimer::setDutyCycle(uint8_t dutyCycle) {
float compare = m_TimerHandle.Instance->ARR;
compare /= 100;
compare *= dutyCycle;
m_TimerHandle.Instance->CCR1 = compare - 1;
}
void PWMTimer::setPeriod(uint16_t period) {
m_TimerHandle.Instance->ARR = period - 1;
m_TimerHandle.Instance->CNT = 0;
}
void PWMTimer::setCompare(uint16_t compare) {
m_TimerHandle.Instance->CCR1 = compare - 1;
}
void PWMTimer::setPrescaler(uint16_t prescaler) {
m_TimerHandle.Instance->PSC = prescaler - 1;
}
void PWMTimer::start() {
HAL_TIM_PWM_Start(&m_TimerHandle, TIM_CHANNEL_1);
}
void PWMTimer::stop() {
HAL_TIM_PWM_Stop(&m_TimerHandle, TIM_CHANNEL_1);
}
uint16_t PWMTimer::status(char* const buffer) {
return sprintf(buffer, timerStatusTemplate, m_TimerHandle.Instance->PSC, m_TimerHandle.Instance->ARR, m_TimerHandle.Instance->CCR1);
}
| true |
45431adefe80c56c1171f8a6b44416d0494ce369 | C++ | Zhichiang/Visual_Cpp_Design-Experiment | /Chapter_01/1_3.cpp | GB18030 | 326 | 2.96875 | 3 | [] | no_license | #include "stdafx.h"
#include <iostream> ///ͷļ
using namespace std; //ռ
int main()
{
//ʹcoutendlʾҪз
cout << "Hello C++" << endl;
//mainҪһط0
return 0;
}
| true |
ba3ce18445cd805fa43cb7eab8262724a79f2d82 | C++ | Kazanovitz/compiler | /codegen/codegen.cpp | UTF-8 | 20,054 | 2.890625 | 3 | [] | no_license | #include "ast.hpp"
#include "symtab.hpp"
#include "classhierarchy.hpp"
#include "primitive.hpp"
#include "assert.h"
#include <typeinfo>
#include <stdio.h>
class Codegen : public Visitor
{
private:
FILE * m_outputfile;
SymTab *m_symboltable;
ClassTable *m_classtable;
const char * heapStart="_heap_start";
const char * heapTop="_heap_top";
const char * printFormat=".LC0";
const char * printFun="Print";
OffsetTable*currClassOffset;
OffsetTable*currMethodOffset;
// basic size of a word (integers and booleans) in bytes
static const int wordsize = 4;
int label_count; //access with new_label
// ********** Helper functions ********************************
// this is used to get new unique labels (cleverly named label1, label2, ...)
int new_label() { return label_count++; }
// PART 1:
// 1) get arithmetic expressions on integers working:
// you wont really be able to run your code,
// but you can visually inspect it to see that the correct
// chains of opcodes are being generated.
// 2) get function calls working:
// if you want to see at least a very simple program compile
// and link successfully against gcc-produced code, you
// need to get at least this far
// 3) get boolean operation working
// before we can implement any of the conditional control flow
// stuff, we need to have booleans worked out.
// 4) control flow:
// we need a way to have if-elses and for loops in our language.
//
// Hint: Symbols have an associated member variable called m_offset
// That offset can be used to figure out where in the activation
// record you should look for a particuar variable
///////////////////////////////////////////////////////////////////////////////
//
// function_prologue
// function_epilogue
//
// Together these two functions implement the callee-side of the calling
// convention. A stack frame has the following layout:
//
// <- SP (before pre-call / after epilogue)
// high -----------------
// | actual arg 1 |
// | ... |
// | actual arg n |
// -----------------
// | Return Addr |
// =================
// | temporary 1 | <- SP (when starting prologue)
// | ... |
// | temporary n |
// low ----------------- <- SP (when done prologue)
//
//
// ||
// ||
// \ /
// \/
//
//
// The caller is responsible for placing the actual arguments
// and the return address on the stack. Actually, the return address
// is put automatically on the stack as part of the x86 call instruction.
//
// On function entry, the callee
//
// (1) allocates space for the callee's temporaries on the stack
//
// (2) saves callee-saved registers (see below) - including the previous activation record pointer (%ebp)
//
// (3) makes the activation record pointer (frame pointer - %ebp) point to the start of the temporary region
//
// (4) possibly copies the actual arguments into the temporary variables to allow easier access
//
// On function exit, the callee:
//
// (1) pops the callee's activation record (temporay area) off the stack
//
// (2) restores the callee-saved registers, including the activation record of the caller (%ebp)
//
// (3) jumps to the return address (using the x86 "ret" instruction, this automatically pops the
// return address off the stack
//
//////////////////////////////////////////////////////////////////////////////
//
// Since we are interfacing with code produced by GCC, we have to respect the
// calling convention that GCC demands:
//
// Contract between caller and callee on x86:
// * after call instruction:
// o %eip points at first instruction of function
// o %esp+4 points at first argument
// o %esp points at return address
// * after ret instruction:
// o %eip contains return address
// o %esp points at arguments pushed by caller
// o called function may have trashed arguments
// o %eax contains return value (or trash if function is void)
// o %ecx, %edx may be trashed
// o %ebp, %ebx, %esi, %edi must contain contents from time of call
// * Terminology:
// o %eax, %ecx, %edx are "caller save" registers
// o %ebp, %ebx, %esi, %edi are "callee save" registers
////////////////////////////////////////////////////////////////////////////////
void init()
{
fprintf( m_outputfile, ".text\n\n");
fprintf( m_outputfile, ".comm %s,4,4\n", heapStart);
fprintf( m_outputfile, ".comm %s,4,4\n\n", heapTop);
fprintf( m_outputfile, "%s:\n", printFormat);
fprintf( m_outputfile, " .string \"%%d\\n\"\n");
fprintf( m_outputfile, " .text\n");
fprintf( m_outputfile, " .globl %s\n",printFun);
fprintf( m_outputfile, " .type %s, @function\n\n",printFun);
fprintf( m_outputfile, ".global %s\n",printFun);
fprintf( m_outputfile, "%s:\n",printFun);
fprintf( m_outputfile, " pushl %%ebp\n");
fprintf( m_outputfile, " movl %%esp, %%ebp\n");
fprintf( m_outputfile, " movl 8(%%ebp), %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
fprintf( m_outputfile, " pushl $.LC0\n");
fprintf( m_outputfile, " call printf\n");
fprintf( m_outputfile, " addl $8, %%esp\n");
fprintf( m_outputfile, " leave\n");
fprintf( m_outputfile, " ret\n\n");
}
void start(int programSize)
{
fprintf( m_outputfile, "# Start Function\n");
fprintf( m_outputfile, ".global Start\n");
fprintf( m_outputfile, "Start:\n");
fprintf( m_outputfile, " pushl %%ebp\n");
fprintf( m_outputfile, " movl %%esp, %%ebp\n");
fprintf( m_outputfile, " movl 8(%%ebp), %%ecx\n");
fprintf( m_outputfile, " movl %%ecx, %s\n",heapStart);
fprintf( m_outputfile, " movl %%ecx, %s\n",heapTop);
fprintf( m_outputfile, " addl $%d, %s\n",programSize,heapTop);
fprintf( m_outputfile, " pushl %s \n",heapStart);
fprintf( m_outputfile, " call Program_start \n");
fprintf( m_outputfile, " leave\n");
fprintf( m_outputfile, " ret\n");
}
void allocSpace(int size)
{
// Optional WRITE ME
}
////////////////////////////////////////////////////////////////////////////////
public:
Codegen(FILE * outputfile, SymTab * st, ClassTable* ct)
{
m_outputfile = outputfile;
m_symboltable = st;
m_classtable = ct;
label_count = 0;
currMethodOffset=currClassOffset=NULL;
}
void printSymTab(){
FILE * pFile;
pFile = fopen ("myfile.txt" , "w");
m_symboltable->dump(pFile);
fclose (pFile);
}
void visitProgramImpl(ProgramImpl *p) {
init();
p->visit_children(this);
// WRITEME
}
void visitClassImpl(ClassImpl *p) {
ClassIDImpl * ClassIdP = dynamic_cast<ClassIDImpl*>(p->m_classid_1);
char * key1 = strdup(ClassIdP->m_classname->spelling());
Symbol * symPtr = new Symbol;
symPtr->classType.classID = ClassIdP->m_classname->spelling();
m_symboltable->insert((char *)"xxx", symPtr);
p->visit_children(this);
// WRITEME
}
void visitDeclarationImpl(DeclarationImpl *p) {
// cout<<"can i subtract here?"<<endl;
p->visit_children(this);
// cout<<"whaddabout here?"<<endl;
// WRITEME
}
void visitMethodImpl(MethodImpl *p) {
fprintf( m_outputfile, "#### METHOD IMPLEMENTATION\n");
int localSpace, args, mem;
int j=0;
int methMem = 0;
CompoundType info;
currMethodOffset = new OffsetTable();
// cout<<"before my childen"<<endl;
//this is to make the label name
Symbol * symbP;
SymScope * sync;
MethodIDImpl * MethIdP = dynamic_cast<MethodIDImpl*>(p->m_methodid);
char * funcName = strdup(MethIdP->m_symname->spelling());
sync = m_symboltable->get_current_scope();
symbP = sync->lookup((const char *)"xxx");
char * classMethName = strdup(symbP->classType.classID);
strcat(classMethName,"_");
strcat(classMethName,funcName);
fprintf( m_outputfile, "_%s:\n",classMethName);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fprintf( m_outputfile, " pushl %%ebp\n");
fprintf( m_outputfile, " movl %%esp , %%ebp\n");
MethodBodyImpl * MethBodP = dynamic_cast<MethodBodyImpl*>(p->m_methodbody);
localSpace = (p->m_parameter_list->size() + MethBodP->m_declaration_list->size());
localSpace = localSpace * wordsize;
// currMethodOffset->insert(classMethName, localSpace, 4,symbP->classType);
currMethodOffset->setTotalSize(localSpace);
currMethodOffset->setParamSize(p->m_parameter_list->size() * wordsize);
//### inserting paramaters into the offset table ###########
for (std::list<Parameter_ptr>::iterator it = p->m_parameter_list->begin() ; it != p->m_parameter_list->end(); ++it){
ParameterImpl * param = dynamic_cast<ParameterImpl*>(*it);
VariableIDImpl * VarId = dynamic_cast<VariableIDImpl*>(param->m_variableid);
info.baseType = param->m_type->m_attribute.m_type.baseType;
if(info.baseType == 8){
info.classID = param->m_type->m_attribute.m_type.classType.classID;
}
else{
info.classID = "NO CLASS";
}
methMem -= 4;
// cout<<"Offset-> symname: "<<VarId->m_symname->spelling()<<" offset: "<<methMem<<" class type: " <<info.baseType<<endl;
currMethodOffset->insert(VarId->m_symname->spelling(), methMem, 4,info);
}
//################################
//<><>Diving into Declaration <><><><>><><><><><><><><><><><>><><><><><><
typename std::list<Declaration_ptr>::iterator it = MethBodP->m_declaration_list->begin();
for( ; it != MethBodP->m_declaration_list->end(); ++it) {
DeclarationImpl * DeclaP = dynamic_cast<DeclarationImpl *> (*it);
typename std::list<VariableID_ptr>::iterator it = DeclaP->m_variableid_list->begin();
for( ; it != DeclaP->m_variableid_list->end(); ++it) {
methMem -= 4; // need to move to the next offset
VariableIDImpl * VarIdP = dynamic_cast<VariableIDImpl*>(*it);
char * var = strdup(VarIdP->m_symname->spelling());
// cout<<"Offset-> symname: "<<var<<" Offset: "<<methMem<<" Class type: " <<endl;
info.baseType = DeclaP->m_type->m_attribute.m_type.baseType;
if(info.baseType == 8){
info.classID = DeclaP->m_type->m_attribute.m_type.classType.classID;
}
else{
info.classID = "NO CLASS";
}
currMethodOffset->insert(var, methMem, 4,info);
}
}
//<><><><><><><><><><><><><><><><><>><><><><><><
//~~~~ allocating space on the stack and moves parameters into local ~~~~~~
// cout<<"param size: "<<currMethodOffset->getParamSize()<<endl;
// cout<<" LocalSpace: "<< -(methMem)<<endl;
fprintf( m_outputfile, " subl $%d, %%esp\n",-(methMem));
mem = -4;
for(int i = currMethodOffset->getParamSize() + 4; i>= 8; i = i-4){
fprintf( m_outputfile, " movl %d(%%ebp) , %%eax\n",i);
fprintf( m_outputfile, " movl %%eax , %d(%%ebp)\n",mem);
mem -= 4;
// symbP->methodType.argsType[j].baseType;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
p->visit_children(this);
// cout<<"after the children"<<endl;
fprintf( m_outputfile, " leave\n");
fprintf( m_outputfile, " ret\n");
// WRITEME
}
void visitMethodBodyImpl(MethodBodyImpl *p) {
p->visit_children(this);
// WRITEME
}
void visitParameterImpl(ParameterImpl *p) {
p->visit_children(this);
// WRITEME
}
void visitAssignment(Assignment *p) {
fprintf( m_outputfile, "#### ASSIGNMENT\n");
// cout<<"Before assignment@@@@@@@@@@@@@@@@@@@@@@ "<<endl;
p->visit_children(this);
// cout<<"AFTER assignment$$$$$$$$$$$$$$$$$$$$$$$$ "<<endl;
VariableIDImpl * VarId = dynamic_cast<VariableIDImpl*>(p->m_variableid);
char * varName = strdup(VarId->m_symname->spelling());
// fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " movl %%eax , %d(%%ebp)\n",currMethodOffset->get_offset(varName));
// WRITEME
}
void visitIf(If *p) {
fprintf( m_outputfile, "#### IF Statemet\n");
// cout<<"before IF Express"<<endl;
if (p->m_expression != NULL) {
p->m_expression->accept( this );
} else {
this->visitNullPointer();
}
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " movl $0 , %%ebx\n");
fprintf( m_outputfile, " cmp %%eax, %%ebx\n");
fprintf( m_outputfile, " je skip_%d\n", new_label());
// cout<<"the label count is: "<<label_count<<endl;
// cout<<"Before IF state after express"<<endl;
if (p->m_statement != NULL) {
p->m_statement->accept( this );
} else {
this->visitNullPointer();
}
// cout<<"After IF Statemetn"<<endl;
fprintf( m_outputfile, " skip_%d: \n",label_count-1);
// WRITEME
}
void visitPrint(Print *p) {
fprintf( m_outputfile, "#### PRINT\n");
p->visit_children(this);
// WRITEME
}
void visitReturnImpl(ReturnImpl *p) {
p->visit_children(this);
// WRITEME
}
void visitTInteger(TInteger *p) {
p->visit_children(this);
// WRITEME
}
void visitTBoolean(TBoolean *p) {
p->visit_children(this);
// WRITEME
}
void visitTNothing(TNothing *p) {
p->visit_children(this);
// WRITEME
}
void visitTObject(TObject *p) {
p->visit_children(this);
// WRITEME
}
void visitClassIDImpl(ClassIDImpl *p) {
p->visit_children(this);
// WRITEME
}
void visitVariableIDImpl(VariableIDImpl *p) {
p->visit_children(this);
// WRITEME
}
void visitMethodIDImpl(MethodIDImpl *p) {
p->visit_children(this);
// WRITEME
}
void visitPlus(Plus *p) {
fprintf( m_outputfile, "#### ADD\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " addl %%ebx, %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitMinus(Minus *p) {
fprintf( m_outputfile, "#### MINUS\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " subl %%ebx, %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitTimes(Times *p) {
fprintf( m_outputfile, "#### TIMES\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " imull %%ebx, %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitDivide(Divide *p) {
fprintf( m_outputfile, "#### DIVIDE\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " cdq\n");
fprintf( m_outputfile, " idivl %%ebx\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitAnd(And *p) {
fprintf( m_outputfile, "#### AND\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " andl %%ebx, %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitLessThan(LessThan *p) {
fprintf( m_outputfile, "#### LESSTHAN\n");
p -> visit_children(this);
new_label();
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " cmp %%ebx, %%eax\n");
fprintf( m_outputfile, " jl True_%d\n", label_count);
fprintf( m_outputfile, " jmp False_%d\n", label_count);
fprintf( m_outputfile, "True_%d: \n",label_count);
fprintf( m_outputfile, " movl $1 , %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
fprintf( m_outputfile, " jmp EndLT_%d\n", label_count);
fprintf( m_outputfile, "False_%d: \n",label_count);
fprintf( m_outputfile, " pushl %%eax\n");
fprintf( m_outputfile, " movl $0 , %%eax\n");
fprintf( m_outputfile, "EndLT_%d: \n",label_count);
// WRITEME
}
void visitLessThanEqualTo(LessThanEqualTo *p) {
fprintf( m_outputfile, "#### LESS THAN EQUAL TOO\n");
p -> visit_children(this);
new_label();
fprintf( m_outputfile, " popl %%ebx\n");
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " cmp %%ebx, %%eax\n");
fprintf( m_outputfile, " jle True_%d\n", label_count);
fprintf( m_outputfile, " jmp False_%d\n", label_count);
fprintf( m_outputfile, "True_%d: \n",label_count);
fprintf( m_outputfile, " movl $1 , %%eax\n");
fprintf( m_outputfile, " jmp EndLE_%d\n", label_count);
fprintf( m_outputfile, " pushl %%eax\n");
fprintf( m_outputfile, "False_%d: \n",label_count);
fprintf( m_outputfile, " pushl %%eax\n");
fprintf( m_outputfile, " movl $0 , %%eax\n");
fprintf( m_outputfile, "EndLE_%d: \n",label_count);
// WRITEME
}
void visitNot(Not *p) {
fprintf( m_outputfile, "#### NOT\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " notl %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitUnaryMinus(UnaryMinus *p) {
fprintf( m_outputfile, "#### UNARY MINUS\n");
p -> visit_children(this);
fprintf( m_outputfile, " popl %%eax\n");
fprintf( m_outputfile, " neg %%eax\n");
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitMethodCall(MethodCall *p) {
fprintf( m_outputfile, "#### METHOD CALL\n");
p->visit_children(this);
// WRITEME
}
void visitSelfCall(SelfCall *p) {
fprintf( m_outputfile, "#### SELF CALL\n");
int args;
Symbol * symbP;
SymScope * sync;
MethodIDImpl * MethIdP = dynamic_cast<MethodIDImpl*>(p->m_methodid);
char * funcName = strdup(MethIdP->m_symname->spelling());
sync = m_symboltable->get_current_scope();
symbP = sync->lookup((const char *)"xxx");
p->visit_children(this);
args = p->m_expression_list->size();
args = args * wordsize;
// cout<<"the number of params: "<<args<<endl;
char * className = strdup(symbP->classType.classID);
strcat(className,"_");
strcat(className,funcName);
fprintf( m_outputfile, "call %s\n",className);
fprintf( m_outputfile, "addl $%d , %%esp\n",args);
// WRITEME
}
void visitVariable(Variable *p) {
//get value put in eax and push
VariableIDImpl * VarId = dynamic_cast<VariableIDImpl*>(p->m_variableid);
char * varName = strdup(VarId->m_symname->spelling());
fprintf( m_outputfile, " movl %d(%%ebp) , %%eax\n",currMethodOffset->get_offset(varName));
fprintf( m_outputfile, " pushl %%eax\n");
p->visit_children(this);
// WRITEME
}
void visitIntegerLiteral(IntegerLiteral *p) {
p->visit_children(this);
// WRITEME
}
void visitBooleanLiteral(BooleanLiteral *p) {
p->visit_children(this);
// WRITEME
}
void visitNothing(Nothing *p) {
p->visit_children(this);
// WRITEME
}
void visitSymName(SymName *p) {
// WRITEME
}
void visitPrimitive(Primitive *p) {
fprintf( m_outputfile, "#### PRIMITIVE \n");
fprintf( m_outputfile, " movl $%d, %%eax\n", p->m_data);
fprintf( m_outputfile, " pushl %%eax\n");
// WRITEME
}
void visitClassName(ClassName *p) {
// WRITEME
}
void visitNullPointer() {}
};
| true |
2114e28191eb0ff766e479e86f693432c7c8f8c0 | C++ | viktorMirev/Personal-Projects | /CompaniesProjectExamPrep/CompaniesProjectExamPrep/Company.cpp | UTF-8 | 1,006 | 3.359375 | 3 | [] | no_license | #include "Company.h"
#include<cstring>
void Company::setName(const char * name)
{
if (this->name) delete[] this->name;
if (name)
{
int size = strlen(name) + 1;
this->name = new char[size];
memcpy(this->name, name, size);
}
}
void Company::copyFromAnother(const Company & other)
{
this->setName(other.name);
numberOfProjects = other.numberOfProjects;
}
int Company::numberOfExecutedProjects() const
{
return numberOfProjects;
}
const char * Company::getName() const
{
return this->name;
}
Company::Company() : name(nullptr), numberOfProjects(0)
{
}
Company::Company(const char * name) : numberOfProjects(0)
{
this->name = nullptr;
this->setName(name);
}
Company::~Company()
{
delete[] this->name;
}
Company::Company(const Company & other)
{
this->name = nullptr;
copyFromAnother(other);
}
Company & Company::operator=(const Company &other)
{
if (this != &other)
{
this->copyFromAnother(other);
}
return *this;
}
| true |
e1685d7c2b067067ebed0b2fe747f3e9a4a1927e | C++ | ccebinger/SWPSoSe14 | /rail-interpreter/src/Action.h | UTF-8 | 17,090 | 3.09375 | 3 | [] | no_license | // Action.h
#ifndef ACTION_H_RAIL_1
#define ACTION_H_RAIL_1
#include "Binding.h"
#include "Dir.h"
#include "NilVar.h"
#include "StringVar.h"
#include "ListVar.h"
#include "Closure.h"
#include "Board.h"
#include "ActivationRecord.h"
#include "Error.h"
class Action
{
public:
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> & globals)=0;
public:
// Helper functions. These are called from individual actions to do
// a common task.
static Action * charToAction(char current);
static void checkVarCount(std::list<Binding> const & theStack, int count);
static bool checkBool(Binding var);
static int checkNumeric(Binding var);
static ConsCell checkList(Binding var);
static std::string checkString(Binding var);
static bool areEqual(Binding left, Binding right);
static void runY(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
Dir::t first, Dir::t second, Dir::t third);
static void callFunctionByName(std::string const & name,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> const & globals);
};
class Nop : public Action
{
public:
static Nop v;
virtual void run(std::list<Binding> &, std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
}
};
class True : public Action
{
public:
static True v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
dataStack.push_front(Binding(new StringVar("1")));
}
};
class False : public Action
{
public:
static False v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
dataStack.push_front(Binding(new StringVar("0")));
}
};
// The direction before the y junction is the direction which the
// 'arrow' points to. So '>' is an EastY.
// This is the '>' junction.
class EastY : public Action
{
public:
static EastY v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
runY(dataStack, programStack, Dir::west, Dir::southeast, Dir::northeast);
}
};
// This is the '<' junction.
class WestY : public Action
{
public:
static WestY v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
runY(dataStack, programStack, Dir::east, Dir::northwest, Dir::southwest);
}
};
// This is the '^' junction.
class NorthY : public Action
{
public:
static NorthY v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
runY(dataStack, programStack, Dir::south, Dir::northeast, Dir::northwest);
}
};
// This is the 'v' junction.
class SouthY : public Action
{
public:
static SouthY v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
runY(dataStack, programStack, Dir::north, Dir::southwest, Dir::southeast);
}
};
class Boom : public Action
{
public:
static Boom v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 1);
std::string custom = checkString(dataStack.front());
throw CrashException(Error::custom, custom);
}
};
class EofCheck : public Action
{
public:
static EofCheck v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> & globals)
{
if (args::input->peek() == EOF)
{
True::v.run(dataStack, programStack, globals);
}
else
{
False::v.run(dataStack, programStack, globals);
}
}
};
class Input : public Action
{
public:
static Input v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
int val = args::input->get();
if (val == EOF)
{
throw CrashException(Error::noMoreInput);
}
else
{
dataStack.push_front(Binding(new StringVar(static_cast<char>(val)
+ std::string())));
}
}
};
class Output : public Action
{
public:
static Output v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 1);
std::string val = checkString(dataStack.front());
dataStack.pop_front();
*(args::output) << val;
}
};
class Underflow : public Action
{
public:
static Underflow v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
std::string count = intToString(static_cast<int>(dataStack.size()));
dataStack.push_front(Binding(new StringVar(count)));
}
};
class TypeP : public Action
{
public:
static TypeP v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 1);
Binding top = dataStack.front();
dataStack.pop_front();
std::string type;
if (top->getString() != NULL)
{
type = "string";
}
else if (top->getList() != NULL)
{
type = "list";
}
else if (top->getNil() != NULL)
{
type = "nil";
}
else if (top->getClosure() != NULL)
{
type = "lambda";
}
else
{
throw InternalException("TypeP::run(): Unknown type");
}
dataStack.push_front(Binding(new StringVar(type)));
}
};
class PushConstant : public Action
{
public:
static PushConstant v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
// Our job is done. The system pushed the string in delimiters
// onto the stack. That is just what we want to do.
checkVarCount(dataStack, 1);
checkString(dataStack.front());
}
};
class UseVariable : public Action
{
public:
static UseVariable v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 1);
std::string varName = checkString(dataStack.front());
dataStack.pop_front();
std::map<std::string, Binding>::const_iterator pos
= programStack.front().getEnvironment().find(varName);
if (pos != programStack.front().getEnvironment().end())
{
dataStack.push_front(pos->second);
}
else
{
throw CrashException(Error::localBindingNotFound);
}
}
};
class BindVariable : public Action
{
public:
static BindVariable v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
std::string varName = checkString(dataStack.front());
dataStack.pop_front();
programStack.front().bindVariable(varName, dataStack.front());
dataStack.pop_front();
}
};
class CallFunction : public Action
{
public:
static CallFunction v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> & globals)
{
checkVarCount(dataStack, 1);
std::string functionName = checkString(dataStack.front());
dataStack.pop_front();
if (functionName != "")
{
callFunctionByName(functionName, programStack, globals);
}
else
{
Binding function = dataStack.front();
if (function->getString() != NULL)
{
callFunctionByName(function->getString()->get(), programStack,
globals);
}
else if (function->getClosure() != NULL)
{
programStack.push_front(ActivationRecord(*(function->getClosure())));
}
else
{
throw CrashException(Error::typeMismatch);
}
dataStack.pop_front();
}
}
};
class Add : public Action
{
public:
static Add v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
int right = checkNumeric(dataStack.front());
dataStack.pop_front();
int left = checkNumeric(dataStack.front());
dataStack.pop_front();
dataStack.push_front(Binding(new StringVar(intToString(left + right))));
}
};
class Divide : public Action
{
public:
static Divide v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
int right = checkNumeric(dataStack.front());
dataStack.pop_front();
int left = checkNumeric(dataStack.front());
dataStack.pop_front();
dataStack.push_front(Binding(new StringVar(intToString(left / right))));
}
};
class Multiply : public Action
{
public:
static Multiply v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
int right = checkNumeric(dataStack.front());
dataStack.pop_front();
int left = checkNumeric(dataStack.front());
dataStack.pop_front();
dataStack.push_front(Binding(new StringVar(intToString(left * right))));
}
};
class Remainder : public Action
{
public:
static Remainder v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
int right = checkNumeric(dataStack.front());
dataStack.pop_front();
int left = checkNumeric(dataStack.front());
dataStack.pop_front();
dataStack.push_front(Binding(new StringVar(intToString(left % right))));
}
};
class Subtract : public Action
{
public:
static Subtract v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
int right = checkNumeric(dataStack.front());
dataStack.pop_front();
int left = checkNumeric(dataStack.front());
dataStack.pop_front();
dataStack.push_front(Binding(new StringVar(intToString(left - right))));
}
};
class Digit : public Action
{
public:
static Digit v0;
static Digit v1;
static Digit v2;
static Digit v3;
static Digit v4;
static Digit v5;
static Digit v6;
static Digit v7;
static Digit v8;
static Digit v9;
Digit(int newNum = 0) : num(newNum) {}
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
dataStack.push_front(Binding(new StringVar(intToString(num))));
}
private:
int num;
};
class Cut : public Action
{
public:
static Cut v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
int index = checkNumeric(dataStack.front());
dataStack.pop_front();
std::string str = checkString(dataStack.front());
dataStack.pop_front();
if (index < 0 || index > static_cast<int>(str.size()))
{
throw CrashException(Error::indexOutOfBounds);
}
std::string leftResult = str.substr(0, index);
std::string rightResult = str.substr(index);
dataStack.push_front(Binding(new StringVar(leftResult)));
dataStack.push_front(Binding(new StringVar(rightResult)));
}
};
class Append : public Action
{
public:
static Append v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
std::string right = checkString(dataStack.front());
dataStack.pop_front();
std::string left = checkString(dataStack.front());
dataStack.pop_front();
dataStack.push_front(Binding(new StringVar(left + right)));
}
};
class Size : public Action
{
public:
static Size v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 1);
std::string str = checkString(dataStack.front());
dataStack.pop_front();
int size = static_cast<int>(str.size());
dataStack.push_front(Binding(new StringVar(intToString(size))));
}
};
class PushNIL : public Action
{
public:
static PushNIL v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
dataStack.push_front(NIL);
}
};
class Cons : public Action
{
public:
static Cons v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 2);
Binding car = dataStack.front();
dataStack.pop_front();
Binding cdr = dataStack.front();
dataStack.pop_front();
dataStack.push_front(Binding(new ListVar(car, cdr)));
}
};
class ListBreakup : public Action
{
public:
static ListBreakup v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> &,
std::map<std::string, Board> &)
{
checkVarCount(dataStack, 1);
ConsCell cell = checkList(dataStack.front());
dataStack.pop_front();
dataStack.push_front(cell.cdr);
dataStack.push_front(cell.car);
}
};
class GreaterThan : public Action
{
public:
static GreaterThan v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> & globals)
{
checkVarCount(dataStack, 2);
int right = checkNumeric(dataStack.front());
dataStack.pop_front();
int left = checkNumeric(dataStack.front());
dataStack.pop_front();
if (left > right)
{
True::v.run(dataStack, programStack, globals);
}
else
{
False::v.run(dataStack, programStack, globals);
}
}
};
class IsEqualTo : public Action
{
public:
static IsEqualTo v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> & globals)
{
checkVarCount(dataStack, 2);
Binding right = dataStack.front();
dataStack.pop_front();
Binding left = dataStack.front();
dataStack.pop_front();
if (areEqual(left, right))
{
True::v.run(dataStack, programStack, globals);
}
else
{
False::v.run(dataStack, programStack, globals);
}
}
};
class Reflector : public Action
{
public:
static Reflector v;
virtual void run(std::list<Binding> &,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
ActivationRecord & record = programStack.front();
record.setDirection(Dir::back(record.getDirection()));
}
};
class Lambda : public Action
{
public:
static Lambda v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> & globals)
{
ActivationRecord & record = programStack.front();
if (record.getFunction() == NULL)
{
throw InternalException("Lambda: No function in the given record");
}
dataStack.push_front(Binding(new Closure(record.getEnvironment(),
*(record.getFunction()),
record.getPosition(),
record.getDirection())));
record.setDirection(Dir::back(record.getDirection()));
}
};
class End : public Action
{
public:
static End v;
virtual void run(std::list<Binding> & dataStack,
std::list<ActivationRecord> & programStack,
std::map<std::string, Board> &)
{
programStack.pop_front();
}
};
#endif
| true |
55b48b6a9ecbab6d11d9491a1c0c268780694f57 | C++ | JJackol/SDL | /src/InitError.cpp | UTF-8 | 307 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "InitError.h"
#include <SDL.h>
InitError::InitError() :
exception(),
msg( SDL_GetError() )
{
}
InitError::InitError( const std::string & m ) :
exception(),
msg( m )
{
}
InitError::~InitError() throw()
{
}
const char * InitError::what() const throw()
{
return msg.c_str();
}
| true |
328521bf34788172d01ca5af8b65116cfbed48b6 | C++ | nerdityourself/AnalogPadMidi | /AnalogMidiController.ino | UTF-8 | 4,065 | 2.84375 | 3 | [] | no_license | /*
@author NerdItYourself
@version 1.0, 05/10/2016
*/
// MIDI channel from 0 to 15
#define midichannel 1
#define nPad 6
// Note: we use the same trasmitter pin for all the sensor in order to use less digital pin.
// Note: change array size according to the number of resistive sensor that you want to manage.
byte Notes[nPad] = {67, 71 , 64, 66}; // MIDI notes associated with each sensor. Change these values to send other notes.
int Threshold[nPad] = {128, 128, 128, 128}; // Value that each sensor has to overcome to send a note
boolean VelocityFlag = false; // Velocity ON (true) or OFF (false)
boolean activePad[nPad] = {0,0,0,0}; // Array of flags indicating wich sensor is currently playing
int PinPlayTime[nPad] = {0,0,0,0}; // Counter since a note started to play
int MaxTime[nPad] = {0,0,0,0}; // Cycles before a 2nd hit is allowed
byte status1; // byte that we will use to compose a part of the MIDI message
int pads[6] = {A0,A1,A2,A3,A4,A5};
int pin = 0;
int velocity = 0;
bool debug = true; // Set this flag to true if you want to read cap sense values in Serila Monitor to check if everything is working properly
void setup()
{
// Initialize serial port (we will use serial to debug our code and then to send midi commands)
Serial.begin(115200);
}
void loop()
{
if(debug)
{
Serial.println("");
}
for(int pin=0; pin < nPad; pin++)
{
float resValue = analogRead(pads[pin]); // Read value of the resistive sensor
if(debug)
{
Serial.print(" pin: ");
Serial.print(pin);
Serial.print(" - ");
Serial.print(resValue);
}
// Check if cap. sensor value is above the threshold
if((resValue > Threshold[pin]))
{
if((activePad[pin] == false))
{
if(VelocityFlag == true)
{
velocity = (resValue / 8) -1 ;
}
else
{
velocity = 127;
}
MIDI_TX(144, Notes[pin], velocity); //note on (144 is signal for note on)
PinPlayTime[pin] = 0;
activePad[pin] = true;
}
else
{
PinPlayTime[pin] = PinPlayTime[pin] + 1;
}
}
else if(activePad[pin] == true)
{
PinPlayTime[pin] = PinPlayTime[pin] + 1;
if(PinPlayTime[pin] > MaxTime[pin])
{
activePad[pin] = false;
MIDI_TX(128, Notes[pin],0); //note off (128 is signal for note on)
}
}
}
}
//*******************************************************************************************************************
// Transmit MIDI Message
//*******************************************************************************************************************
void MIDI_TX(byte MESSAGE, byte PITCH, byte VELOCITY)
{
if(!debug)
{
status1 = MESSAGE + midichannel; // The first byte we have to send contains information about the command (note on ,note off, etc..) and the channel were we want to send the message
Serial.write(status1);
Serial.write(PITCH); // The second byte of the message contains the pitch
Serial.write(VELOCITY); // The last byte of the message contatins the velocity of the note
}
}
| true |
9b09cb0c061c6f30d5e40ffb09faa20f09679700 | C++ | ShresthSagar/CPP-Programs | /DS/directindex.cpp | UTF-8 | 454 | 3.234375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int ar[1000]={0};
void ins(int val)
{
ar[val]=1;
cout<<"inserted "<<val<<endl;
}
void sear(int val)
{
if(ar[val]==1)
cout<<"Found "<<val<<endl;
else
cout<<"Not Found "<<val<<endl;
}
void del(int val)
{
ar[val]=0;
cout<<"Deleted "<<val<<endl;
}
int main()
{
ins(20);
ins(30);
ins(32);
sear(20);
sear(12);
del(20);
sear(20);
return 0;
}
| true |
8dbd6a6dceaca60c3a57d6054011c4934be73e7a | C++ | hqnddw/leetcode | /smart-pointer智能指针/test.cpp | UTF-8 | 608 | 3.28125 | 3 | [] | no_license | //
// Created by lwl on 2020/8/7.
//
#include "smart-pointer.h"
class Point {
public:
Point(int xVal = 0, int yVal = 0) : x(xVal), y(yVal) {}
int getX() const { return x; }
int getY() const { return y; }
void setX(int xVal) { x = xVal; }
void setY(int yVal) { y = yVal; }
private:
int x, y;
};
int main() {
Point *p = new Point(20, 10);
{
smartPointer<Point> ptr1(p);
{
smartPointer<Point> ptr2(ptr1);
{
smartPointer<Point> ptr3(ptr1);
}
}
}
cout << p->getX() << endl;
return 0;
} | true |
2d54ead0de44d8f6f545fa4f4c758a6ead9bd0d5 | C++ | sahn93/problem-solving | /leetcode/hard/Array_and_Strings/5_Game_of_Life/Solution.cpp | UTF-8 | 1,333 | 2.9375 | 3 | [] | no_license | class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
// 0: 0 to 0, 1: 1 to 0, 2: 0 to 1, 3: 1 to 1
int rows = board.size();
int cols = board[0].size();
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
int curr = board[i][j];
int surr = -board[i][j];
int left = max(j-1, 0);
int right = min(j+1, cols-1);
int bot = min(i+1, rows-1);
int top = max(i-1, 0);
for (int k = top; k<=bot; k++) {
for (int l = left; l<=right; l++) {
surr += board[k][l] % 2;
}
}
if (curr == 0) {
if (surr == 3) {
board[i][j] = 2;
}
} else if (curr == 1) {
if (surr < 2) {
board[i][j] = 1;
} else if (surr < 4) {
board[i][j] = 3;
} else {
board[i][j] = 1;
}
}
}
}
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
board[i][j] /= 2;
}
}
}
};
| true |
df2013bdb02a1ffe019612a4079bcc0b4d2a18ae | C++ | espennordahl/iAurora | /src/geometry/shape.h | UTF-8 | 1,539 | 2.5625 | 3 | [] | no_license | //
// shape.h
// Aurora
//
// Created by Espen Nordahl on 01/07/2012.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef Aurora_shape_h
#define Aurora_shape_h
#include "core.h"
#include "geometry.h"
#include "attributeState.h"
#include "attributeChange.h"
#include <vector>
namespace Aurora {
class Shape {
public:
Shape( const Transform *o2c, const Transform *c2o ) : objectToCamera(o2c), cameraToObject(c2o) { };
virtual ~Shape(){};
// Handy information
virtual int numTriangles() = 0;
virtual int numVertices() = 0;
virtual BBox objectBound() const = 0;
virtual BBox worldBound() const = 0;
virtual void applyAttributeChange(const AttributeChange &change){
assert(false); // TODO: Not implemented;
}
virtual void clearCache() = 0;
void setDirtyGeometry(bool dirtyGeo){
m_dirtygeo = dirtyGeo;
}
virtual bool isGeometryCached(){
return !m_dirtygeo;
}
// Splits the geometry into triangles
virtual void dice( std::vector<std::shared_ptr<Geometry> > &diced) = 0;
// Object transforms. It's important that if the object moves,
// that we create new transforms as they're potentially shared
// for effeciency
const Transform *objectToCamera;
const Transform *cameraToObject;
private:
bool m_dirtygeo;
};
typedef std::shared_ptr<Shape> ShapePtr;
}
#endif | true |
151fceba9e5f8a7cc60b1163183fc69d6e12139f | C++ | tjoyjoseph/C-_Log_Class | /Log_Class/Log_Class/TestPurposes/SeminarC.cpp | UTF-8 | 2,018 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <string>
using namespace std;
map<char, string> parseArgsValues(int argc, char * argv[]){
vector<string>strings;
map<char, string> MapcharString;
for (int i = 0; i < argc; i++)
{
strings.push_back(string(argv[i]));
}
for (int i = 0; i < argc; i++)
{
if (strings[i].size() > 2)
{
if (strings[i][0] == '-')
{
//cout << strings[i] << endl;
char temC = strings[i][1];
// cout << temC << endl;
string temS;
for (int m = 3; m < strings[i].size(); m++)
{
temS += strings[i][m];
//cout << temS << endl;
}
MapcharString[temC] = temS;
cout << temC << " = " << MapcharString[temC] << endl;
}
}
}
cout << "" << endl;
cout << "" << endl;
return MapcharString;
}
set<char> parseArgsFlags(int argc, char * argv[])
{
vector<string>strings;
set<char> SetChar;
for (int i = 0; i < argc ; i++)
{
strings.push_back(string(argv[i]));
}
for (int i = 0; i < argc; i++)
{
if (strings[i].size() == 2)
{
if (strings[i][0] == '-')
{
//cout << strings[i] << " ";
SetChar.insert(strings[i][1]);
}
}
}
for (set<char>::iterator i = SetChar.begin(); i != SetChar.end(); i++) {
cout << *i <<endl;
}
cout << "" << endl;
return SetChar;
}
vector<string> parseArgv(int argc, char * argv[])
{
vector<string>strings;
for (int i = 0; i < argc; i++)
{
strings.push_back(string(argv[i]));
}
for (int i = 0; i <argc; i++)
{
cout << strings[i] << " ";
}
cout << "" << endl;
cout << "" << endl;
return strings;
}
int main(int argc, char* argv[])
{
cout << "" << endl;
cout << "Parse argv" << endl;
cout << "------------\n" << endl;
parseArgv(argc, argv);
cout << "Parse argv Flags" << endl;
cout << "------------------\n" << endl;
parseArgsFlags(argc, argv);
cout << "Parse argv Values" << endl;
cout << "-------------------\n" << endl;
parseArgsValues(argc, argv);
} | true |