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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
be6f40eab10a617797ffad4ea45284071f31aef7 | C++ | nanlan2017/lang-cpp | /TemplateLang/haskell_subset.h | GB18030 | 5,310 | 3.125 | 3 | [] | no_license | #ifndef h_haskellsubset
#define h_haskellsubset
#include "for_test_use.h"
#include <string>
/*
"ͨ"/) Ҫдǰ桪 HaskellͬHaskellǰǰֻҪƥ䵽ãͨ䶼д
C++ requires template specialization to follow the templates general definition (or declaration, as well see later).
The pattern matching of arguments in C++ does not follow the order of declarations but rather is based on best match.
*/
template<class T> struct
isPtr
{
static const bool value = false;
};
template<class U> struct
isPtr<U*>
{
static const bool value = true;
};
template<class U> struct
isPtr<U * const>
{
static const bool value = true;
};
//x=============================================================================================================
/*
count [] = 0
count (head:tail) = 1 + count tail
*/
//thanks to variadic templates and template parameter packs
// Just a declaration
template<class... list>
struct count; //! ~~~~~~~~~~~~~~~~~~ <> ͨ֡ ֻ ʵ֡
template<>
struct count<>
{
static const int value = 0;
};
template<class head, class... tail>
struct count<head, tail...>
{
static const int value = 1 + count<tail...>::value;
};
inline void test_count()
{
auto r = count<int, std::string, double>::value; // 3
}
//x=============================================================================================================
/*
or_combinator f1 f2 = x -> (f1 x) || (f2 x)
*/
template<template<int> class F1
, template<int> class F2>
struct or_comb
{
template<int n>
struct Ret
{
static const bool val = F1<n>::val || F2<n>::val;
};
};
inline void test_comb()
{
auto r1 = or_comb<is_zero, is_one>::Ret<1>::val;
auto r2 = or_comb<is_zero, is_one>::Ret<3>::val;
}
//x=============================================================================================================
/*
f : [T] -> a
f [] = ...
f [x] = // һԪֹݹҲԣ
f (x:xs) = ..x.. # f xs
//todo ~~~~~~~~~~~~~~~~~~~~ LIST ػģʽ
template <typename... List>
struct f; // ֻһ <> ģұ ϶ӣ
template<typename head, typename... tail>
struct f <head,tail...>
{ }
template<> // nilԪ бֵ
struct f <>
{ }
*/
template<template<typename> class Predict
, typename ...List>
struct all;
template<template<typename> class Predict
, typename Head,typename ...Rest>
struct all<Predict,Head,Rest...>
{
static const bool val = Predict<Head>::value && all<Predict, Rest...>::val;
};
template<template<typename> class Predict>
struct all<Predict>
{
static const bool val = true;
};
inline void test_all_temp()
{
auto r = all<isPtr, int*, double*>::val;
}
//x=============================================================================================================
/*
foldr :: (a->a->a) -> a -> [a] -> a
foldr f acc [x] = f acc x
foldr f acc (x:xs) =
*/
template<template<class, int> class, int, class...> struct
fold_right;
template<template<class, int> class f, int init> struct
fold_right<f, init> {
static const int value = init;
};
template<template<class, int> class f, int init, class head, class...tail> struct
fold_right<f, init, head, tail...> {
static const int value = f<head, fold_right<f, init, tail...>::value>::value;
};
//x=============================================================================================================
template<int...> struct
sum;
template<> struct
sum<> {
static const int value = 0;
};
template<int i, int... tail> struct
sum<i, tail...> {
static const int value = i + sum<tail...>::value;
};
//x=============================================================================================================
// one x = 1
template<class T> struct
one {
static const int value = 1;
};
// count lst = sum [one x | x <- lst]
template<typename ...List>
struct Count_
{
//todo [Pattern(E1), Pattern(E2), Pattern(E3) ...]
//todo Haskell [ Pattern(x) | x <- lst ]
//todo C++TMP Pattern(List)... // Listһ
static const int value = sum<one<List>::value...>::value;
// sum< one<E1>::value, one<E2>::value, ,,,
};
//template<typename Head,typename...Tail>
//struct Count_<Head,Tail...>
//{
// static const int value = sum<one<Head>::value>::value + Count_<Tail...>::value;
//};
//template<>
//struct Count_<>
//{
// static const int value = 0;
//};
inline void test_count__()
{
}
//x=============================================================================================================
template<template<typename> class F
,typename ...List>
struct map_
{
/*
The problem is that it doesnt compile.
As far as I know there is no way for a template to return a variable list of elements.
In my opinion, this is a major language design flaw
*/
//typedef F<List>... Ret;
};
template<typename hd,typename ...tl>
struct typelist<hd, tl...> {
typedef hd head;
typedef typelist<tl...> tail;
};
#endif
| true |
4b7e992fb0d17356ae18cf546fbc1e2d9baceb10 | C++ | thenewguy39/OOP-in-CPP | /INHERITANCE/41.cpp | UTF-8 | 1,623 | 3.65625 | 4 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
class Person{
private:
char *name;
int age, height;
public:
Person():age(0),height(0){
strcpy(name, "x");
}
Person(char* s, int a, int h):age(a),height(h) {
name = s;
}
void set(char* n, int a, int h) {
name = n;
age = a;
height = h;
}
char* getname() { return name; }
int getage() { return age; }
int getheight() { return height; }
virtual void printDetails() {
cout<<"Name: "<<getname()<<endl;
cout<<"Age: "<<getage()<<endl;
cout<<"Height: "<<getheight()<<endl;
}
};
class Student:public Person {
private:
int roll;
int year;
public:
Student():Person() {
roll = 0;
year = 0;
}
Student(char* n, int a, int h, int r, int y):Person(n,a,h) {
roll = r;
year = y;
}
void set(char* s, int a, int h, int r, int y) {
Person::set(s,a,h);
roll = r;
year = y;
}
int getroll() { return roll; }
int getyear() { return year; }
void printDetails() {
Person::printDetails();
cout<<"Roll: "<<getroll()<<endl;
cout<<"Year: "<<getyear()<<endl<<endl;
}
};
int main(){
Person a((char*)"abc",19,170);
Student b((char*)"bcd",18,160,15,2018);
cout<<"Test: \n\n";
a.printDetails();
cout<<endl;
b.printDetails();
Person **p=new Person*[4];
p[0] = new Person((char*)"ABC", 19, 170);
p[1] = new Person((char*)"BCD", 19, 180);
p[2] = new Student((char*)"CDE", 20, 183, 26, 2019);
p[3] = new Student((char*)"DEF", 20, 180, 28, 2019);
cout<<endl<<endl;
for(int i=0;i<4;i++){
p[i]->printDetails();
cout<<endl;
}
return 0;
}
| true |
3334de25afb016d9b402ea8030aa8ec23db988f0 | C++ | bradlarsen/switchback | /src/search/Node.hpp | UTF-8 | 2,737 | 3.484375 | 3 | [] | no_license | #ifndef _NODE_HPP_
#define _NODE_HPP_
template <
class StateT,
class CostT
>
class Node
{
public:
typedef StateT State;
typedef CostT Cost;
private:
const Node<State, Cost> *parent;
State state;
Cost g;
Cost h;
#ifdef CACHE_NODE_F_VALUE
Cost f;
#endif
public:
Node(const State &s,
Cost g,
Cost h,
const Node<State, Cost> *p = NULL)
: parent(p)
, state(s)
, g(g)
, h(h)
#ifdef CACHE_NODE_F_VALUE
, f(g + h)
#endif
{
}
Cost get_f() const
{
#ifdef CACHE_NODE_F_VALUE
return f;
#else
return g + h;
#endif
}
Cost get_g() const
{
return g;
}
void set_g(Cost new_g)
{
g = new_g;
#ifdef CACHE_NODE_F_VALUE
f = g + h;
#endif
}
Cost get_h() const
{
return h;
}
void set_h(Cost new_h)
{
h = new_h;
#ifdef CACHE_NODE_F_VALUE
f = g + h;
#endif
}
const State & get_state() const
{
return state;
}
const Node<State, Cost> * get_parent() const
{
return parent;
}
unsigned num_nodes_to_start() const
{
unsigned num_nodes = 1;
const Node<State, Cost> *parent_ptr = get_parent();
while (parent_ptr != NULL) {
num_nodes += 1;
parent_ptr = parent_ptr->get_parent();
}
return num_nodes;
}
bool is_descendent_of(const Node<State, Cost> *node) const
{
const Node *p = this;
while (p != NULL) {
if (p->get_state() == node->get_state())
return true;
p = p->get_parent();
}
return false;
}
/**
* Compare nodes by f-value, breaking ties in favor of high g-value.
*/
bool operator <(const Node<State, Cost> &other) const
{
Cost my_f = get_f();
Cost other_f = other.get_f();
return my_f < other_f || (my_f == other_f && get_g() > other.get_g());
}
bool operator >=(const Node<State, Cost> &other) const
{
return !(*this < other);
}
/**
* Equality is determined by the enclosed states.
*
* This is kind of horrible.
*/
bool operator ==(const Node<State, Cost> &other) const
{
return state == other.state;
}
};
/**
* To hash a TilesNode15, simply use the hash value of the enclosed
* tile puzzle state.
*/
template <
class State,
class Cost
>
std::size_t hash_value(Node<State, Cost> const &node)
{
return hash_value(node.get_state());
}
template <
class State,
class Cost
>
std::ostream & operator <<(std::ostream &o, const Node<State, Cost> &n)
{
/* This will print the solution path.
if (n.get_parent())
o << *n.get_parent();
*/
o << n.get_state() << std::endl
<< "f: " << n.get_f() << std::endl
<< "g: " << n.get_g() << std::endl
<< "h: " << n.get_h() << std::endl;
return o;
}
#endif /* !_NODE_HPP_ */
| true |
28629e4da1c03a0664959ca4023463c7696b8d86 | C++ | dctucker/neural-tetris | /neuralfloat.cc | UTF-8 | 5,198 | 2.875 | 3 | [] | no_license | #define WeightI(i,j) weightIn[i*Ninputs+j]
#define WeightO(i,j) weightOut[i*Nhidden+j]
class NeuralNet {
private:
float *output, *hidden,
*weightIn,*weightOut,
*biasHid,*biasOut,
*errorHid, *errorOut;
int Ninputs,Nhidden,Noutputs;
public:
float *input,*target;
float bias, eta,RMSE;
private:
float sigmoid(float x){
return 1.0F / ( 1.0F + exp(-x) );
}
void initWeights(){
for(int i=0; i<Ninputs; i++){
for(int j=0; j<Nhidden; j++){
// std::cout << (i*Ninputs+j)<<"\n";
WeightI(i,j)=sigmoid(rho);
std::cout << WeightI(i,j);
}
}
char c;
std::cin >> c;
for(int i=0; i<Nhidden; i++){
biasHid[i]=0.0F;
for(int j=0; j<Noutputs;j++){
WeightO(i,j)=sigmoid(rho);
if(i==0) biasOut[j]=0.0F;
}
}
}
public:
NeuralNet(int ni,int nh,int no){
bias=1.0F;
eta=1.9F;
Ninputs=ni;
Nhidden=nh;
Noutputs=no;
input = new float [Ninputs];
target= new float [Noutputs];
hidden= new float [Nhidden];
output= new float [Noutputs];
weightIn= new float [Ninputs*Nhidden];
weightOut=new float [Nhidden*Noutputs];
biasHid= new float [Nhidden];
biasOut= new float [Noutputs];
errorHid= new float [Nhidden];
errorOut= new float [Noutputs];
initWeights();
}
void print(bool header=false){
std::cout.precision(4);
if(header) std::cout << "In:\n";
for(int i=0; i<Ninputs; i++){
std::cout << input[i] << "\t";
for(int j=0; j<Nhidden; j++)
std::cout << WeightI(i,j) << "\t";
std::cout << "\n";
}
if(header) std::cout << "Hid:";
for(int i=0; i<Nhidden; i++){
std::cout << "\t" << hidden[i];
}
std::cout << "\n\n";
if(header) std::cout << "Hid:\n";
for(int i=0; i<Nhidden; i++){
std::cout << hidden[i] << "\t";
for(int j=0; j<Noutputs; j++){
std::cout << WeightO(i,j) << "\t";
}
std::cout << "\n";
}
if(header) std::cout << "Out:";
for(int i=0; i<Noutputs; i++){
std::cout << "\t" << output[i];
}
std::cout << "\nTarget:";
for(int i=0; i<Noutputs; i++){
std::cout << "\t" << target[i];
}
std::cout << "\n\n";
}
void printIO(){
for(int i=0; i<Ninputs; i++){
std::cout << input[i] << " ";
}
std::cout << ": ";
for(int i=0; i<Noutputs; i++){
std::cout << target[i] << " ";
}
std::cout << " -> ";
for(int i=0; i<Noutputs; i++){
std::cout << ((output[i]<0.5) ? "0.1 " : "0.9 ");
}
std::cout << " (";
for(int i=0; i<Noutputs; i++){
std::cout << output[i] << " ";
}
std::cout << ")\n";
}
void printO(){
std::cout.precision(4);
for(int k=0; k<Noutputs; k++)
//std::cout << ((output[k]>0.7)?":":".") << (int)(output[k]*10)
// << ((int)(output[k]*100)%10) << " ";
std::cout << output[k];
std::cout << "\n";
}
void calculate(){
float netj;
for(int j=0; j<Nhidden; j++){
float s=0;
for(int i=0; i<Ninputs; i++){
s+=input[i]*WeightI(i,j);
}
netj=bias*biasHid[j]+s;
hidden[j]=sigmoid(netj);
}
for(int k=0; k<Noutputs; k++){
float s=0;
for(int j=0; j<Nhidden; j++){
s+=hidden[j]*WeightO(j,k);
}
netj=bias*biasOut[k]+s;
output[k]=sigmoid(netj);
}
}
void updateErrors(){
//calculate error at outputs
for(int k=0; k<Noutputs; k++){
errorOut[k] =
(target[k]-output[k]) * output[k] * (1-output[k]);
}
//use output error to compute error for hidden
for(int j=0; j<Nhidden; j++){
float s=0;
for(int k=0; k<Noutputs; k++){
s+=errorOut[k]*WeightO(j,k);
}
errorHid[j] = hidden[j]*(1-hidden[j])*s;
}
}
void updateW(){
//use hidden error to compute weight adjustments
for(int k=0; k<Noutputs; k++){
for(int j=0; j<Nhidden; j++){
WeightO(j,k)+=eta*errorOut[k]*hidden[j];
}
}
for(int j=0; j<Nhidden; j++){
for(int i=0; i<Ninputs; i++){
WeightI(i,j)+=eta*errorHid[j]*input[i];
}
}
}
void train(float *in, float *tar){
//apply inputs
std::cout << "I=";
for(int i=0; i<Ninputs; i++){
input[i]=in[i];
std::cout << (input[i]>0.5)?"1":"0";
}
std::cout << "\nT=";
for(int i=0; i<Noutputs; i++){
target[i]=tar[i];
std::cout << (target[i]>0.5)?"1":"0";
}
std::cout << "\nO=";
calculate();
for(int i=0; i<Noutputs; i++){
std::cout << output[i]<<
" ";
}
std::cout << "\n";
updateErrors();
updateW();
// TSSE+=tsse();
char c; std::cin>>c;
}
void train(unsigned char m[20][10],float *tar){
for(int i=0; i<Ninputs; i++){
input[i]=(m[i/10][i%10]==1)?0.999:0.001;
}
for(int k=0; k<Noutputs; k++){
target[k]=tar[k];
}
calculate();
updateErrors();
updateW();
}
void test(unsigned char m[20][10]){
for(int i=0; i<Ninputs; i++){
input[i]=m[i/10][i%10];
}
calculate();
}
void test(float *in){
for(int i=0; i<Ninputs; i++){
input[i]=in[i];
}
calculate();
}
float tsse(){
float r=0;
for(int k=0; k<Noutputs; k++){
r+=(target[k]-output[k])*(target[k]-output[k]);
}
return r;
}
float rmse(float Npatterns){
return sqrt((tsse())/(Npatterns*Noutputs));
}
};
| true |
848066fd94f6515549d2760a0f289d8e7bed85f5 | C++ | deryrahman/if2210-virtual-zoo | /C++/VZ03/src/AnimalType/Species/puma.cpp | UTF-8 | 1,024 | 2.921875 | 3 | [] | no_license |
#include "../../../include/AnimalType/Species/puma.h"
using namespace std;
/** @brief constructor
* tanpa parameter
*/
Puma::Puma(){
setBioType('L');
setDietType('C');
setWeight(180);
setTamed(false);
setName("Puma");
Flexibility = 5;
}
/** @brief constructor
* @param _Flexibility : nilai dari Flexibility
* @param tamed : jinak ataut tidaknya hewan
*/
Puma::Puma(int _Flexibility, bool tamed){
setBioType('L');
setDietType('C');
setWeight(180);
setTamed(tamed);
setName("Puma");
Flexibility = _Flexibility;
}
/**
* @brief fungsi interact
* memberikan respons dari Puma ketika dikunjungi
* berupa suara Puma
*/
void Puma::interact(){
cout << "Puma: Ghruarrr" << endl;
}
/** @brief fungsi render
* menampilkan Puma di layar pada virtual zoo
*/
void Puma::render() {
Color::Modifier text(Color::FG_YELLOW);
Color::Modifier cleartext(Color::FG_DEFAULT);
cout << text << "Pm" << cleartext;
} | true |
b1fcabf8f900047e4a8f9d7412976dc1b0701528 | C++ | leolnid/itmo-cpp-2018 | /(task_8)game_context/headers/functions.h | UTF-8 | 564 | 2.96875 | 3 | [] | no_license | #pragma once
/////TASK 2
typedef int*(*resultFunction)(char const*);
typedef int(*otherFunction)(double);
typedef resultFunction (*complexFunction)(int, otherFunction);
/////TASK 3
template<class T, class R>
bool compare(const T& first, const T& second, R (T::*temporaryFunction)() const) {
return ((first.*temporaryFunction)() < (second.*temporaryFunction)());
}
/////TASK 4
template<class T>
bool isSameObject(T const* firstObject, T const* secondObject){
return (dynamic_cast<const void*>(firstObject)) == (dynamic_cast<const void*>(secondObject));
} | true |
bbc86d6d7188c29c208884236b91ea1a50cb7cb0 | C++ | bentzirozen/project | /src/Interpeter/Lexer.h | UTF-8 | 664 | 2.515625 | 3 | [] | no_license | //
// Created by bentzirozen on 12/17/18.
//
#ifndef PROJECT_LEXER_H
#define PROJECT_LEXER_H
#define SPECIAL_OPERATOR {"+","-","*","/", "\"","<",">","<=",">=","=="}
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#define SEPARATOR " "
#define ASSERTSEPAR "="
using namespace std;
class Lexer{
vector<string> cur_lex;
vector<vector<int>> matrix;
public:
Lexer(){};
bool isOperator(string & c);
vector<string>split_from_file(string fileName);
vector<string>fromStringtoLex(vector<string> lines);
vector<vector<int>>convert_to_matrix(vector<string>values);
~Lexer(){};
};
#endif //PROJECT_LEXER_H
| true |
29e4fae788c06c04dbbd29253f49128f2c520778 | C++ | GeoffreyHervet/epitek | /2/piscine/piscine_cpp_d10-2015-hervet_g/ex00/Sorcerer.cpp | UTF-8 | 1,054 | 2.875 | 3 | [] | no_license | //
// Sorcerer.cpp for ex00 in /home/hervet_g/piscine/piscine_cpp_d10-2015-hervet_g/ex00
//
// Made by geoffrey hervet
// Login <hervet_g@epitech.net>
//
// Started on Fri Jan 13 09:59:00 2012 geoffrey hervet
// Last update Fri Jan 13 09:59:00 2012 geoffrey hervet
//
#include <iostream>
#include "Sorcerer.hh"
Sorcerer::Sorcerer(std::string const &name, std::string const &title)
: _name(name),
_title(title)
{
std::cout << this->getName() << ", "
<< this->getTitle() << ", is born !"
<< std::endl;
}
Sorcerer::~Sorcerer()
{
std::cout << this->getName() << ", "
<< this->getTitle() << ", is dead. Consequences will never be the same !"
<< std::endl;
}
const std::string &Sorcerer::getTitle(void) const
{
return this->_title;
}
const std::string &Sorcerer::getName(void) const
{
return this->_name;
}
std::ostream &operator<<(std::ostream &os, const Sorcerer &c)
{
os << "I am " << c.getName() << ", " << c.getTitle() << ", and I like ponies !" << std::endl;
return os;
}
void Sorcerer::polymorph(Victim const &v) const
{
v.getPolymorphed();
}
| true |
bfa2121dc8369126c90e5940ad372fd0cfb8df52 | C++ | jsheo96/OpenGLAssn3 | /bullet.cpp | UTF-8 | 3,415 | 2.71875 | 3 | [] | no_license | #pragma once
#include "bullet.hpp"
#include <cmath>
#include <iostream>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "objloader.hpp"
#include "shader.hpp"
#include "map.hpp"
#include "player.hpp"
#define PI 3.141592f
using namespace std;
extern bool map_bullet[ArrSize][ArrSize];
extern bool map_wall[ArrSize][ArrSize];
extern bool map_enemy[ArrSize][ArrSize];
extern GLuint ModelID;
GLuint Bullet::VertexArrayID;
int Bullet::dummy_obj_size;
vector<Bullet> Bullet::vectorBullet;
Bullet::Bullet(float direction, float x, float y)
{
this->x = x;
this->y = y;
this->direction = direction;
map_bullet[int(x / 200)][int(y / 200)] = 1;
}
Bullet::~Bullet()
{
}
void Bullet::draw() {
//rotation();
glBindVertexArray(VertexArrayID);
glm::mat4 Model = glm::translate(glm::mat4(1.0), glm::vec3(x, y, 150.0f))*
/*scale */ glm::scale(glm::mat4(1.0f), glm::vec3(10.0f))*
/*rotation */ glm::rotate(glm::mat4(1.0f), PI/180*direction, glm::vec3(0.0f, 0.0f, 1.0f)) *
/*translate*/ glm::rotate(glm::mat4(1.0f), PI / 180 * 90.0f, glm::vec3(0.0f,1.0f, 0.0f));
glUniformMatrix4fv(ModelID, 1, GL_FALSE, &Model[0][0]);
for (int i = 0; i < dummy_obj_size / 4; i++) {
glDrawArrays(GL_LINE_LOOP, i * 4, 4);
}
glBindVertexArray(0);
}
void Bullet::initVAO() {
vector<glm::vec3> vertices;
bool res = loadOBJ2("obj_files/bullet.obj", vertices);
dummy_obj_size = vertices.size();
GLuint vertexbuffer;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, dummy_obj_size * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(
0, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer
);
}
void Bullet::move() {
//0: up, 1:down, 2:left, 3:right
float dir = this->direction;
int prev_x_fit =int(this->x / 200);
int prev_y_fit = int(this->y / 200);
int x_fit, y_fit;
if (dir == 0.0f) {//up
this->x = this->x + 200.0f;
}
else if (dir == 90.f) {//down
this->y = this->y + 200.0f;
}
else if (dir == 180.0f) {//left
this->x = this->x- 200.0f;
}
else if (dir == 270.0f){//right
this->y = this->y - 200.0f;
}
x_fit = int(this->x / 200);
y_fit = int(this->y / 200);
if ((x_fit != prev_x_fit )|| (y_fit!=prev_y_fit)) { //if there was any position change in block unit
map_bullet[prev_x_fit][prev_y_fit] = 0;
map_bullet[x_fit][y_fit] = 1;
}
}
bool Bullet::wallCollision() {
//collision check!!!
int x_fit = this->x / 200;
int y_fit = this->y / 200;
if (map_wall[x_fit][y_fit]) {//collision
map_bullet[x_fit][y_fit] = 0;
return true;
}
return false;
}
bool Bullet::enemyCollision() {
//collision check!!!
int x_fit = this->x / 200;
int y_fit = this->y / 200;
if (map_enemy[x_fit][y_fit]) {//collision
map_bullet[x_fit][y_fit] = 0;
return true;
}
return false;
}
void Bullet::update() {
for (int i = 0; i <vectorBullet.size(); i++) {
vectorBullet[i].move();
if (vectorBullet[i].wallCollision()) {
vectorBullet[i].~Bullet();
vectorBullet.erase(vectorBullet.begin() + i);
}
}
}
void Bullet::drawAll() {
int size =vectorBullet.size();
for (int i = 0; i < size; i++) {
vectorBullet[i].draw();
}
} | true |
3d96cff76ed969caf83c48347410bada749f69cd | C++ | Iggytung/GeneralRegressionNeuralNetwork | /src/grnn.cpp | UTF-8 | 864 | 3.109375 | 3 | [] | no_license | #include <cmath>
#include <iostream>
#include "grnn.h"
const double activator(const std::vector<double> input, const std::vector<double> x, const double sigma) {
double distance = 0;
for(int i = 0; i < input.size(); i += 1) {
distance += std::pow(input[i] - x[i], 2);
}
return std::exp(-distance / std::pow(sigma, 2));
}
const std::vector<double> grnn(const std::vector<double> input, const std::vector< std::vector<double> > train_x, const std::vector< std::vector<double> > train_y, const double sigma) {
std::vector<double> result;
for (int dim = 0; dim < train_y[0].size(); dim += 1) {
double factor = 0, divide = 0;
for (int i = 0; i < train_x.size(); i += 1) {
double cache = activator(input, train_x[i], sigma);
factor += train_y[i][dim] * cache;
divide += cache;
}
result.push_back(factor/divide);
}
return result;
}
| true |
7991de1ba57e1d4b3084fc96378919ccef22731e | C++ | kks227/BOJ | /3000/3009.cpp | UTF-8 | 342 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int x[4], y[4];
for(int i=0; i<3; i++)
cin >> x[i] >> y[i];
if(x[0] == x[1]) x[3] = x[2];
else if(x[1] == x[2]) x[3] = x[0];
else x[3] = x[1];
if(y[0] == y[1]) y[3] = y[2];
else if(y[1] == y[2]) y[3] = y[0];
else y[3] = y[1];
cout << x[3] << ' ' << y[3] << endl;
return 0;
} | true |
0e561e5404bc9fc07acf3948fd98b65781e847a3 | C++ | mathurinm/Sudoku-Centrale | /SudokuSolver/TwoOutOfThreeColumnVisitor.cpp | UTF-8 | 4,923 | 3.15625 | 3 | [] | no_license | #include "TwoOutOfThreeColumnVisitor.h"
#include "NineHolder.h"
#include "ValueEliminator.h"
#include <set>
using namespace std;
TwoOutOfThreeColumnVisitor::TwoOutOfThreeColumnVisitor()
{
}
TwoOutOfThreeColumnVisitor::~TwoOutOfThreeColumnVisitor()
{
}
//This method is quite similar to TwoOutOfThreeRowVisitor::Visit(). Make sure to change both when editting.
bool TwoOutOfThreeColumnVisitor::Visit(Grid& ioGrid) const
{
bool visited = false;
for (unsigned char i = 0; i < 3; i++)
{
NineHolder FullLeftColumn = ioGrid.getColumn(3 * i);
NineHolder FullMiddleColumn = ioGrid.getColumn(3 * i + 1);
NineHolder FullRightColumn = ioGrid.getColumn(3 * i + 2);
for (unsigned char digit = 1; digit < 10; digit++)
{
unsigned char columnDigitAbsent = 0;
unsigned char absences = 0;
set<unsigned char> rowAbsence;
rowAbsence.insert(0);
rowAbsence.insert(1);
rowAbsence.insert(2);
if (!FullLeftColumn.isValuePresent(digit))
{
columnDigitAbsent = 3 * i;
absences++;
}
else{ //erase Row in which the digit is present from the set rowAbsence
if (FullLeftColumn.getCell(0).getValue() == digit || FullLeftColumn.getCell(1).getValue() == digit
|| FullLeftColumn.getCell(2).getValue() == digit)
{
rowAbsence.erase(0);
}
if (FullLeftColumn.getCell(3).getValue() == digit || FullLeftColumn.getCell(4).getValue() == digit
|| FullLeftColumn.getCell(5).getValue() == digit)
{
rowAbsence.erase(1);
}
if (FullLeftColumn.getCell(6).getValue() == digit || FullLeftColumn.getCell(7).getValue() == digit
|| FullLeftColumn.getCell(8).getValue() == digit)
{
rowAbsence.erase(2);
}
}
if (!FullMiddleColumn.isValuePresent(digit))
{
columnDigitAbsent = 3 * i + 1; absences++;
}
else{ //erase Row in which the digit is present from the set rowAbsence
if (FullMiddleColumn.getCell(0).getValue() == digit || FullMiddleColumn.getCell(1).getValue() == digit
|| FullMiddleColumn.getCell(2).getValue() == digit)
{
rowAbsence.erase(0);
}
if (FullMiddleColumn.getCell(3).getValue() == digit || FullMiddleColumn.getCell(4).getValue() == digit
|| FullMiddleColumn.getCell(5).getValue() == digit)
{
rowAbsence.erase(1);
}
if (FullMiddleColumn.getCell(6).getValue() == digit || FullMiddleColumn.getCell(7).getValue() == digit
|| FullMiddleColumn.getCell(8).getValue() == digit)
{
rowAbsence.erase(2);
}
}
if (!FullRightColumn.isValuePresent(digit))
{
columnDigitAbsent = 3 * i + 2;
absences++;
}
else{ //erase Column in which the digit is present from the set rowAbsence
if (FullRightColumn.getCell(0).getValue() == digit || FullRightColumn.getCell(1).getValue() == digit
|| FullRightColumn.getCell(2).getValue() == digit)
{
rowAbsence.erase(0);
}
if (FullRightColumn.getCell(3).getValue() == digit || FullRightColumn.getCell(4).getValue() == digit
|| FullRightColumn.getCell(5).getValue() == digit)
{
rowAbsence.erase(1);
}
if (FullRightColumn.getCell(6).getValue() == digit || FullRightColumn.getCell(7).getValue() == digit
|| FullRightColumn.getCell(8).getValue() == digit)
{
rowAbsence.erase(2);
}
}
if (absences == 1 && rowAbsence.size() == 1) //we've been twice in the else, rowAbsence has one element exactly
{
//the digit is absent of exactly column row out of three
//it is absent of column columnDigitAbsent
//there is exactly 1 element in the set rowAbsence: 0, 1 or 2
//Get 3 nineholder (row) on the 3 corresponding row (3rowRegIndex, .., 3rowRegIndex+2)
set<unsigned char>::iterator iter = rowAbsence.begin();
int rowRegIndex = *iter;
//We could have a loop here but I think it is more readable this way.
NineHolder nh1 = ioGrid.getRow(3 * rowRegIndex);
NineHolder nh2 = ioGrid.getRow(3 * rowRegIndex + 1);
NineHolder nh3 = ioGrid.getRow(3 * rowRegIndex + 2);
set<unsigned char> possiblePlaces;
possiblePlaces.insert(0);
possiblePlaces.insert(1);
possiblePlaces.insert(2);
RegionHolder regHolder = ioGrid.getRegion(rowRegIndex, columnDigitAbsent / 3);
if (!regHolder.getCell(0, columnDigitAbsent % 3).IsEmpty()
|| nh1.isValuePresent(digit))
{
possiblePlaces.erase(0);
}
if (!regHolder.getCell(1, columnDigitAbsent % 3).IsEmpty()
|| nh2.isValuePresent(digit))
{
possiblePlaces.erase(1);
}
if (!regHolder.getCell(2, columnDigitAbsent % 3).IsEmpty()
|| nh3.isValuePresent(digit))
{
possiblePlaces.erase(2);
}
//If it is, set value of corresponding cell to digit
if (possiblePlaces.size() == 1)
{
set<unsigned char>::iterator iter3 = possiblePlaces.begin();
int place = *iter3;
regHolder.getCell(place, columnDigitAbsent % 3) = digit;
visited = true;
}
}
}
}
return visited;
}
| true |
d2f6356c13b4b0bb1b2a4aea06b5feea580e61b5 | C++ | kulate/leetcode | /src/leetcode1248.cpp | UTF-8 | 685 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
vector<int> idx;
idx.push_back(-1);
for (int i = 0; i < nums.size(); i++)
if (nums[i] & 1) idx.push_back(i);
idx.push_back(nums.size());
int ans = 0;
for (int i = 1 + k; i < idx.size(); i++) {
int l = idx[i - k] - idx[i - k - 1], r = idx[i] - idx[i - 1];
ans += l * r;
}
return ans;
}
};
int main(void) {
vector<int> nums = {1,1,2,1,1};
int k = 3;
Solution solu;
cout << solu.numberOfSubarrays(nums, k) << endl;
return 0;
} | true |
7493e97b154c59f0e6615f68d46999c513b9ced0 | C++ | PraneshASP/COMPETITVE-PROGRAMMING | /LEETCODE/ALL PROBLEMS/654.cpp | UTF-8 | 776 | 3.359375 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | #include <bits/stdc++.h>
using namespace std;
// Definition for a binary tree node.
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *constructMaximumBinaryTree(vector<int> &nums, int start = 0, int stop = INT_MAX)
{
if (stop == INT_MAX)
stop = nums.size();
if (start > stop)
return nullptr;
auto middle = max_element(nums.begin(), nums.end() + stop + 1) - nums.begin();
TreeNode *root = new TreeNode(nums[middle]);
root->left = constructMaximumBinaryTree(nums, start, middle + 1);
root->right = constructMaximumBinaryTree(nums, middle + 1, stop);
return root;
}
}; | true |
c97b43870636959947564db75cfa30b2bc1f68a6 | C++ | rollfatcat/ProblemSet | /演算法題型分類/Dynamic-Program/應用題/數列相關/e562-UVa11401.cc | UTF-8 | 686 | 3.046875 | 3 | [] | no_license | /* 給 N根長度為1、2 ...、N的棍子,任選3根可以構成三角形的方法數
* 標準動態規劃解, 狀態轉移:
* 1. (不選定最長邊 N ) = N-1 根的方法數
* 2. (選定最長邊 N ) = 枚舉剩餘2根的選取方法數
* N-1時可以搭配 (2...N-2)
* N-2時可以搭配 (3...N-3)
*/
#include<bits/stdc++.h>
using namespace std;
const int MaxN=1000000;
long cnt[MaxN+1]={}; // 注意方法數需要longlong儲存
int main(){
//
for(long i=4;i<=MaxN;i++)
if(i&1) cnt[i]=cnt[i-1]+(i-3)*((i-2)/2+1)/2;
else cnt[i]=cnt[i-1]+(i-2)*((i-4)/2+1)/2;
//
for(int N;scanf("%d",&N) and N>0;)
printf("%ld\n",cnt[N]);
} | true |
099f6cdb34431076b658c6d41e78ceb8d7697a86 | C++ | odnaks/Codeforces | /B/266b.cpp | UTF-8 | 446 | 2.671875 | 3 | [] | no_license | //29.01.19 @odnaks
#include <iostream>
using namespace std;
int main()
{
int n;
int t;
char temp;
cin >> n >> t;
char a[n];
for (int i = 0; i < n; i++)
cin >> a[i];
if (n < t)
t = n;
for (int i = 0; i < t; i++)
{
for (int j = 0; j < n; j++)
{
if (a[j] == 'B' && a[j + 1] == 'G')
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
j++;
}
}
}
for (int i = 0; i < n; i++)
cout << a[i];
return (0);
} | true |
ffa360bc7e55384e0de47de898498896de8f5ffa | C++ | josephkott/subshift | /mex/functions.h | UTF-8 | 762 | 2.796875 | 3 | [] | no_license | #ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <cmath>
#include "Point.h"
using namespace NR;
using namespace std;
// NLS with piecewise constant nonlinearity with absence of linear potential.
// Equation for nonlinear stationary modes:
// u_{xx} + \mu u + \sigma(x) u^3 = 0
// where \sigma(x) = -1, x \in [0, L_1) & \sigma = +1, x \in [L_1, L_2),
// L = L_1 + L_2 -- period of nonlinear potential.
// Parameters: [\mu L_1 L_2]
Point<2> f(double x, Point<2> u, double* param)
{
Point<2> du;
double mu = param[0], L1 = param[1], L2 = param[2];
double L = L1 + L2;
double n = floor(x / L);
double x0 = x - n * L;
double sigma = (x0 < L1 ? -1 : +1);
du[0] = u[1];
du[1] = -mu * u[0] - sigma * pow(u[0], 3);
return du;
}
#endif | true |
f7ec9a3f9bb84c86030217a9bbd63ae90e3a8cb4 | C++ | Rr1901/C-with-DS | /Opensource Programs/max_path_sum.cpp | UTF-8 | 526 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | class Solution {
private :
int solve(TreeNode* root, int& res){
if(root==nullptr){
return 0;
}
int l=solve(root->left,res);
int r=solve(root->right,res);
int temp=max(max(l,r)+root->val,root->val);
int ans=max(temp, l+r+root->val);
res=max(res,ans);
return temp;
}
public:
int maxPathSum(TreeNode* root ){
int res=INT_MIN;
solve(root,res);
return res;
}
};
| true |
042c81722e5fa70efd6f2a7c514d2296de4ee9f0 | C++ | Mit25/BoatmanProblem | /greedy1.cpp | UTF-8 | 361 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int findTime(int arr[], int n){
if(n<=2)
return arr[n-1];
int i,ans=0;
for(i=1;i<n;i++)
ans += arr[i];
ans += (n-2)*arr[0];
return ans;
}
int main() {
int n;
cin >>n;
int arr[n];
int i;
for(i=0;i<n;i++)
cin >>arr[i];
cout << findTime(arr, n);
return 0;
} | true |
f22144f989c6c23cbeded365d2f764e04c6fe143 | C++ | hinike/The-Nature-of-Cinder | /Chapter02_Forces/Ex24FluidResistance/src/Mover.cpp | UTF-8 | 1,250 | 2.890625 | 3 | [] | no_license | //
// Mover.cpp
// Ex24FluidResistance
//
// Created by Ilya Rostovtsev on 7/6/13.
//
// HWH Maintenance 8/17/13
//
#include "Mover.h"
Mover::Mover( const float mass_, const float x, const float y )
: location{ x, y },
velocity{ Vec2f::zero() },
acceleration{ Vec2f::zero() },
mass{ mass_ },
radius{ mass * 8 }
{ }
const float Mover::getMass() const
{
return mass;
}
const Vec2f& Mover::getLocation() const
{
return location;
}
const Vec2f& Mover::getVelocity() const
{
return velocity;
}
void Mover::applyForce( const Vec2f& force )
{
acceleration += force / mass;
}
void Mover::update()
{
velocity += acceleration;
location += velocity;
checkEdges();
acceleration = Vec2f::zero();
}
void Mover::draw() const
{
gl::color( 1.f, 1.f, 1.f );
gl::drawSolidCircle( location, radius );
}
void Mover::checkEdges()
{
if ( location.x > app::getWindowWidth() - radius ) {
location.x = app::getWindowWidth() - radius;
velocity.x *= -1;
} else if ( location.x < radius ) {
location.x = radius;
velocity.x *= -1;
}
if ( location.y > app::getWindowHeight() - radius ) {
location.y = app::getWindowHeight() - radius;
velocity.y *= -1;
}
}
| true |
8008b1e5c885d2a367c20b084e9af4c38d583486 | C++ | ghj0504520/UVA | /11700/11777.cpp | UTF-8 | 541 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int r;
cin>>r;
for (int t = 0; t < r; ++t)
{
int G[4];
cin>>G[0]>>G[1]>>G[2]>>G[3];
int T[3];
cin>>T[0]>>T[1]>>T[2];
sort(T,T+3);
int sum=G[0]+G[1]+G[2]+G[3]+(T[2]+T[1])/2;
cout<<"Case "<<t+1<<": ";
if(sum>=90)
{
cout<<"A\n";
}
else if(sum>=80&&sum<90)
{
cout<<"B\n";
}
else if(sum>=70&&sum<80)
{
cout<<"C\n";
}
else if(sum>=60&&sum<70)
{
cout<<"D\n";
}
else if(sum<60)
{
cout<<"F\n";
}
}
return 0;
} | true |
9cc28ce8db68b2b1ca1436aa136c05d64f30efff | C++ | erdoukki/PraeTor | /Tools/WebSvcApp/include/Tools/WebSvcApp/WebSvcApp.h | UTF-8 | 4,475 | 2.578125 | 3 | [] | no_license | #ifndef INCLUDE_SERVICESLIBS_WEBSVCAPP_WEBSVCAPP_H_
#define INCLUDE_SERVICESLIBS_WEBSVCAPP_WEBSVCAPP_H_
// C++
#include <string>
// Boost
#include <boost/noncopyable.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/shared_ptr.hpp>
// Tools
#include "Tools/Configuration/Configuration.h"
#include "Tools/Logger/Logger.h"
#include "Tools/WebServer/WebServer.h"
namespace Tools
{
namespace WebSvcApp
{
/**
* Класс для реализации веб-сервисов
*
*/
class WebSvcApp : boost::noncopyable
{
public:
class WebServiceRegistrar
{
public:
explicit WebServiceRegistrar(boost::shared_ptr<Tools::WebServer::WebServer> webServerPtr):
m_webServerPtr(webServerPtr), m_addedServices(false)
{
}
void registerService(const std::string &resource, Tools::WebServer::IWebServicePtr servicePtr)
{
m_webServerPtr->addService(resource, servicePtr);
m_addedServices = true;
}
bool hasServices() const
{
return m_addedServices;
}
private:
boost::shared_ptr<Tools::WebServer::WebServer> m_webServerPtr;
bool m_addedServices;
};
public:
WebSvcApp(const std::string &project, const std::string &version, const std::string &revision);
virtual ~WebSvcApp();
/**
* Запускает сервис
* @param argc количество параметров
* @param argv параметры
* @return код возврата
*/
int run(int argc, char **argv);
/**
* Запускает сервис
* @param argc количество параметров
* @param argv параметры
* @return код возврата
*/
int run(Tools::Configuration::Configuration &conf);
/**
* Возвращает название проекта
* @return название проекта
*/
const std::string &getProject() const;
/**
* Возвращает версию проекта
* @return версия проекта
*/
const std::string &getVersion() const;
/**
* Возвращает путь к конфигурационному файлу
* @return путь к конфигурационному файлу
*/
const std::string &getConfigFileName() const;
/**
* Возвращает конфигурацию
* @return конфигурация
*/
Tools::Configuration::ConfigurationView getConf() const;
/**
* Возвращает логгер
* @return логгер
*/
Tools::Logger::Logger &getLogger();
/**
* Возвращает имя хоста
* @return имя хоста
*/
static std::string getHostName();
protected:
/**
* Добавляет пользовательские параметры командной строки
* @param options описание параметров командной стоки
*/
virtual void registerOptions(boost::program_options::options_description &options);
/**
* Выполняет инициализацию веб-сервисов
* @param webServiceRegistrar объект для регистрации сервисов
* @param statPtr объект для настойки параметров статистики
*/
virtual void initialize(WebServiceRegistrar &webServiceRegistrar, Tools::WebServer::IStatPtr statPtr) = 0;
/**
* Выполняет очистку перед остановкой сервиса
*/
virtual void cleanup();
private:
/**
* Производит обработку параметров командной строки
* @param argc - количество параметров
* @param argv - параметры
* @return Возвращает false если необходимо завершить выполнение программы, иначе - true
* @throw program_options::error - если произошла ошибка обработки
*/
bool processCommandLine(int argc, char **argv);
private:
std::string m_project;
std::string m_version;
std::string m_revision;
std::string m_configFileName;
Tools::Configuration::Configuration m_config;
};
} // namespace WebSvcApp
} // namespace Tools
#endif /* INCLUDE_SERVICESLIBS_WEBSVCAPP_WEBSVCAPP_H_ */
| true |
0461354456dec246438857b83542092349f253fb | C++ | AliA1997/Halo-React-Hooks-Graphql | /server/utils/cppsrc/src/classes/postInput.cpp | UTF-8 | 2,722 | 2.828125 | 3 | [] | no_license | #include "postInput.h"
PostInput::PostInput(std::string title, std::string image, std::string dateCreated, std::string dateUpdated, int deletedInd, int permanentlyDeletedInd, std::string userId) {
this->title_ = title;
this->image_ = image;
this->dateCreated_ = dateCreated;
this->dateUpdated_ = dateUpdated;
this->deletedInd_ = deletedInd;
this->permanentlyDeletedInd_ = permanentlyDeletedInd;
this->userId_ = userId;
}
//Define methods for defining a passed instance of the input wrapper class which is wrapping
//the RegiserForm, PostInput, and CommentInput class.
std::string PostInput::getTitle() {
return this->title_;
}
std::string PostInput::getImage() {
return this->image_;
}
std::string PostInput::getDateCreated() {
return this->dateCreated_;
}
std::string PostInput::getDateUpdated() {
return this->dateUpdated_;
}
int PostInput::getDeletedInd() {
return this->deletedInd_;
}
int PostInput::getPermanentlyDeletedInd() {
return this->permanentlyDeletedInd_;
}
std::string PostInput::getUserId() {
return this->userId_;
}
Napi::Object PostInput::returnObj(Napi::Env env) {
Napi::Object objToReturn = Napi::Object::New(env);
//Define your value and keys for the object you will return.
Napi::String titleKey = Napi::String::New(env, "title");
Napi::String titleValue = Napi::String::New(env, this->title_);
Napi::String avatarKey = Napi::String::New(env, "image");
Napi::String avatarValue = Napi::String::New(env, this->image_);
Napi::String dateCreatedKey = Napi::String::New(env, "dateCreated");
Napi::String dateCreatedValue = Napi::String::New(env, this->dateCreated_);
Napi::String dateUpdatedKey = Napi::String::New(env, "dateUpdated");
Napi::String dateUpdatedValue = Napi::String::New(env, this->dateUpdated_);
Napi::String deletedIndKey = Napi::String::New(env, "deletedInd");
Napi::Number deletedIndValue = Napi::Number::New(env, this->deletedInd_);
Napi::String permanentlyDeletedIndKey = Napi::String::New(env, "permanentlyDeletedInd");
Napi::Number permanentlyDeletedIndValue = Napi::Number::New(env, this->permanentlyDeletedInd_);
Napi::String userIdKey = Napi::String::New(env, "userId");
Napi::String userIdValue = Napi::String::New(env, this->userId_);
objToReturn.Set(titleKey, titleValue);
objToReturn.Set(avatarKey, avatarValue);
objToReturn.Set(dateCreatedKey, dateCreatedValue);
objToReturn.Set(dateUpdatedKey, dateUpdatedValue);
objToReturn.Set(deletedIndKey, deletedIndValue);
objToReturn.Set(permanentlyDeletedIndKey, permanentlyDeletedIndValue);
objToReturn.Set(userIdKey, userIdValue);
return objToReturn;
}
| true |
bd94ea2c79f3a4992158df1f9dbbf35529be6c8d | C++ | hideindark/CCpp2017 | /practices/cpp/level1/p06_CircleAndPoint/CircleAndPoint.cpp | UTF-8 | 386 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
void draw(point p,int size)
class point
{
private:
int cx;
int cy;
public:
void move(int x1,int y1)
{
cx+=x1;
cy+=y1;
}
point(int x1,int y1):cx(x1),cy(y1){}
}
int main()
{
int size=3;
point center(5,5);
draw(center,size);
center.move(5,7);
}
void draw(point p,size)
{
}
| true |
c356f14d5b132881d9de4bb331a12133e2b77a40 | C++ | Ricky-Robot/CPCFI | /UVa/1. Introduction/Splitting Numbers/SplittingNumbers.cpp | UTF-8 | 487 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <bitset>
#define max 32
using namespace std;
int main(){
int n;
bool flag;
bitset<max> a;
bitset<max> b;
while(cin >> n, n != 0){
bitset<max> number(n);
flag = true;
for(int i = 0; i < max; i++){
if(number.test(i)){
if(flag){
a.set(i, true);
flag = false;
}
else{
b.set(i, true);
flag = true;
}
}
}
cout << a.to_ulong() << " " << b.to_ulong() << endl;
a.reset();
b.reset();
}
return 0;
} | true |
a9dc2e47e57aa2e3cb98de7d23285afe1f27a052 | C++ | young1928/Cpp | /leetcode/打家劫舍 II.cpp | GB18030 | 1,656 | 3.28125 | 3 | [] | no_license | class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 1)
return nums[0];
return max(check(nums,0,n - 2),check(nums,1,n - 1));
}
int check(vector<int>& nums,int le,int ri) {
int f_0 = 0, f_1 = 0;
for(int i = le; i <= ri; i ++) {
int t = f_0;
f_0 = max(f_0,f_1);
f_1 = t + nums[i];
}
return max(f_0,f_1);
}
};
һרҵС͵ƻ͵ؽֵķݣÿ䷿ڶһֽطеķݶ ΧһȦ ζŵһݺһǽŵġͬʱڵķװͨķϵͳڵķͬһϱС͵룬ϵͳԶ
һÿݴŽķǸ飬 ڲװõ ܹ͵Ե߽
?
ʾ?1
룺nums = [2,3,2]
3
ͣ㲻͵ 1 ŷݣ = 2Ȼ͵ 3 ŷݣ = 2, Ϊڵġ
ʾ 2
룺nums = [1,2,3,1]
4
ͣ͵ 1 ŷݣ = 1Ȼ͵ 3 ŷݣ = 3
? ͵Ե߽ = 1 + 3 = 4
ʾ 3
룺nums = [0]
0
?
ʾ
1 <= nums.length <= 100
0 <= nums[i] <= 1000
ԴۣLeetCode
ӣhttps://leetcode-cn.com/problems/house-robber-ii
ȨСҵתϵٷȨҵתע
| true |
64527acde2bedde91461916120c84c1efb2c8157 | C++ | guowee/minicap-YUV | /jni/minicap-shared/aosp/include/Minicap.hpp | UTF-8 | 3,773 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef MINICAP_HPP
#define MINICAP_HPP
#include <cstdint>
class Minicap {
public:
enum CaptureMethod {
METHOD_FRAMEBUFFER = 1,
METHOD_SCREENSHOT = 2,
METHOD_VIRTUAL_DISPLAY = 3,
};
enum Format {
FORMAT_NONE = 0x01,
FORMAT_CUSTOM = 0x02,
FORMAT_TRANSLUCENT = 0x03,
FORMAT_TRANSPARENT = 0x04,
FORMAT_OPAQUE = 0x05,
FORMAT_RGBA_8888 = 0x06,
FORMAT_RGBX_8888 = 0x07,
FORMAT_RGB_888 = 0x08,
FORMAT_RGB_565 = 0x09,
FORMAT_BGRA_8888 = 0x0a,
FORMAT_RGBA_5551 = 0x0b,
FORMAT_RGBA_4444 = 0x0c,
FORMAT_UNKNOWN = 0x00,
};
enum Orientation {
ORIENTATION_0 = 0,
ORIENTATION_90 = 1,
ORIENTATION_180 = 2,
ORIENTATION_270 = 3,
};
struct DisplayInfo {
uint32_t width;
uint32_t height;
uint8_t orientation;
float fps;
float density;
float xdpi;
float ydpi;
bool secure;
float size;
};
struct Frame {
void const* data;
Format format;
uint32_t width;
uint32_t height;
/*
stride指在内存中每行像素所占的空间
因为涉及到内存对其的问题,所以stride/bpp并不能代表图片的宽度
如果 Stride 不是 4 的倍数, 那么 Stride = Stride + (4 - Stride mod 4);
*/
uint32_t stride;
/*
Byte per pixel
*/
uint32_t bpp;
size_t size;
};
struct FrameAvailableListener {
virtual
~FrameAvailableListener() {}
virtual void
onFrameAvailable() = 0;
};
Minicap() {}
virtual
~Minicap() {}
// Applies changes made by setDesiredInfo() and setRealInfo(). Must be
// called before attempting to wait or consume frames.
virtual int
applyConfigChanges() = 0;
// Consumes a frame. Must be called after waitForFrame().
virtual int
consumePendingFrame(Frame* frame) = 0;
// Peek behind the scenes to see which capture method is actually
// being used.
virtual CaptureMethod
getCaptureMethod() = 0;
// Get display ID.
virtual int32_t
getDisplayId() = 0;
// Release all resources.
virtual void
release() = 0;
// Releases a consumed frame so that it can be reused by Android again.
// Must be called before consumePendingFrame() is called again.
virtual void
releaseConsumedFrame(Frame* frame) = 0;
// Set desired information about the display. Currently, only the
// following properties are actually used: width, height and orientation.
// After the configuration has been applied, new frames should satisfy
// the requirements.
virtual int
setDesiredInfo(const DisplayInfo& info) = 0;
// Sets the frame available listener.
virtual void
setFrameAvailableListener(FrameAvailableListener* listener) = 0;
// Set the display's real information. This cannot be accessed automatically
// due to manufacturers (mainly Samsung) having customized
// android::DisplayInfo. The information has to be gathered somehow and then
// passed on here. Currently only the following properties are actually
// used: width and height.
virtual int
setRealInfo(const DisplayInfo& info) = 0;
};
// Attempt to get information about the given display. This may segfault
// on some devices due to manufacturer (mainly Samsung) customizations.
int
minicap_try_get_display_info(int32_t displayId, Minicap::DisplayInfo* info);
// Creates a new Minicap instance for the current platform.
Minicap*
minicap_create(int32_t displayId);
// Frees a Minicap instance. Don't call delete yourself as it won't have
// access to the platform-specific modifications.
void
minicap_free(Minicap* mc);
// Starts an Android thread pool. Must be called before doing anything else.
void
minicap_start_thread_pool();
#endif
| true |
5100ba1c3de9b2adf359a0c90d008b74a4c6eae4 | C++ | sinjar666/nokia-n900-workspace | /modules/data-model/surgery.h | UTF-8 | 624 | 2.515625 | 3 | [] | no_license | #ifndef SURGERY_H
#define SURGERY_H
#include <QObject>
#include <QString>
#include <QDate>
#define ID_TYPE QString
class Surgery : public QObject
{
Q_OBJECT
ID_TYPE *id;
QString *details;
QDate *date;
QList<ID_TYPE> *linkedTo;
public:
explicit Surgery(QObject *parent = 0);
~Surgery();
void setDetails(QString arg);
QString getDetails();
void setDate(QDate arg);
void setDate(int day, int month, int year);
QDate getDate();
QList<ID_TYPE> getLinkedTo();
bool addLink(ID_TYPE arg);
bool removeLink(ID_TYPE arg);
signals:
public slots:
};
#endif // SURGERY_H
| true |
c89bef493b80b833545893c802e05336e4633b90 | C++ | Yunping/leetCode | /ReverseNodesInk-Group.h | UTF-8 | 2,376 | 3.703125 | 4 | [] | no_license | /*
Problem: Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
====================================================================================
Author: Yunping, qufang83@gmail.com
Date: 11/21/2015
Difficulty: ***
Review: **^
Solution:
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
// revert k nodes from head. return new head and next head.
pair<ListNode*, ListNode*> reverseKNodes(ListNode *head, int k) {
pair<ListNode*, ListNode*> ret;
// check if there is enough nodes left.
int totalCount = 0;
ListNode *p = head;
while (p) {
if (++totalCount >= k)
break;
p = p->next;
}
if (totalCount < k) {
ret.first = head;
ret.second = 0;
return ret;
}
// reverse k nodes
ListNode *prev = 0, *cur = head;
int count = 0;
while (cur) {
ListNode *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
if (++count == k)
break;
}
ret.first = prev;
ret.second = cur;
return ret;
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || k <= 1) return head;
ListNode dummy(0);
dummy.next = head;
ListNode *curHead = head;
ListNode *prevTail = &dummy;
while (curHead) {
pair<ListNode*, ListNode*> heads = reverseKNodes(curHead, k);
ListNode* reversedTail = curHead;
ListNode* reversedHead = heads.first;
prevTail->next = reversedHead;
prevTail = reversedTail;
curHead = heads.second;
}
return dummy.next;
}
}; | true |
3e4cbc720bbed6da2f312b25992a01df4a64e62e | C++ | iNotacat/CyberEngineTweaks | /src/common/Meta.h | UTF-8 | 978 | 2.921875 | 3 | [
"MIT"
] | permissive | #pragma once
// Source: https://stackoverflow.com/questions/4041447/how-is-stdtuple-implemented
template<std::size_t i, typename Item>
struct MetaArrayEntry
{
Item value;
};
template<std::size_t i, typename... Items>
struct MetaArrayImpl;
template<std::size_t i>
struct MetaArrayImpl<i> {};
template<std::size_t i, typename HeadItem, typename... TailItems>
struct MetaArrayImpl<i, HeadItem, TailItems...> :
MetaArrayEntry<i, HeadItem>,
MetaArrayImpl<i + 1, TailItems...>
{};
template<typename... Items>
using MetaArray = MetaArrayImpl<0, Items...>;
// Source: https://www.reddit.com/r/cpp/comments/bhxx49/c20_string_literals_as_nontype_template/elwmdjp/
template<unsigned N>
struct FixedString {
char buf[N + 1]{};
constexpr FixedString(char const* s) {
for (unsigned i = 0; i != N; ++i) buf[i] = s[i];
}
constexpr operator char const* () const { return buf; }
};
template<unsigned N> FixedString(char const (&)[N])->FixedString<N - 1>; | true |
3a75ecb91eb5c46435eb0a0d7bd796dbddb5db8d | C++ | snowrain10/BOJ | /2577.cpp | UTF-8 | 506 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int s[10];
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int a, b, c;
// 세 수의 입력, 한 줄에 하나씩
cin >> a >> b >> c;
// a,b,c : 100 ~ 1000 (보다 작음)
int d = a*b*c;
while(d) {
// d%10 = 1의 자리
s[d % 10]++;
// 다음 1의 자리를 뽑아내기 위해 나누기
d /= 10;
}
for (int i = 0; i < 10; i++) {
cout << s[i] << "\n";
}
return 0;
}
| true |
a79a1f034631264ed5eeaa0425bd7e3a3488f7ab | C++ | YanjieHe/RegularExpression | /src/DFA.cpp | UTF-8 | 10,478 | 2.984375 | 3 | [] | no_license | #include "DFA.hpp"
#include <stack>
#include <stdexcept>
namespace regex
{
u32string UnicodeRange::ToString() const
{
if (IsEpsilon())
{
return U"ε";
}
else if (rangeType == RangeType::LineBegin)
{
return U"^";
}
else if (rangeType == RangeType::LineEnd)
{
return U"$";
}
else if (lower == upper)
{
return u32string({lower});
}
else
{
return U"[" + u32string({lower}) + U" - " + u32string({upper}) + U"]";
}
}
UnicodeRange UnicodeRange::EPSILON = UnicodeRange();
DFA DFATableRowsToDFAGraph(
const vector<DFATableRow> &rows, const UnicodePatterns &patterns, const Graph &nfaGraph, int nfaEndState)
{
unordered_map<std::set<StateID>, StateID, StateIDSetHash> statesID;
DFA graph;
for (int i = 0, n = static_cast<int>(patterns.Size()); i < n - 1; i++)
{
// add all the patterns except epsilon
auto pattern = patterns.GetPatternByID(i);
graph.patterns.Add(pattern, i);
}
for (auto row : rows)
{
const auto &nextStates = row.nextStates;
if (!row.index.empty())
{
if (IsEndState(row.index, nfaGraph, nfaEndState))
{
StateID id = RecordState(statesID, row.index);
graph.endStates.insert(id);
}
StateID from = RecordState(statesID, row.index);
int patternID = 0;
for (auto nextState : nextStates)
{
if (!nextState.empty())
{
StateID to = RecordState(statesID, nextState);
auto pattern = patterns.GetPatternByID(patternID);
graph.G.AddEdge(Edge(from, to, pattern));
}
patternID++;
}
}
}
return graph;
}
bool IsEndState(const std::set<StateID> &index, const Graph &nfaGraph, StateID nfaEndState)
{
for (StateID i : index)
{
if (i == nfaEndState)
{
return true;
}
else if (CanTransit(nfaGraph, i, nfaEndState))
{
return true;
}
else
{
// pass
}
}
return false;
}
StateID RecordState(
unordered_map<std::set<StateID>, StateID, StateIDSetHash> &stateMap, const std::set<StateID> &state)
{
if (stateMap.count(state))
{
return stateMap[state];
}
else
{
size_t n = stateMap.size();
stateMap[state] = n;
return n;
}
}
DFAMatrix::DFAMatrix(const DFA &dfaGraph)
: matrix(dfaGraph.G.NodeCount(), vector<int>(dfaGraph.patterns.Size(), -1)), patterns{dfaGraph.patterns},
endStates{dfaGraph.endStates}
{
for (auto edges : dfaGraph.G.adj)
{
for (auto edge : edges)
{
int patternID = dfaGraph.patterns.GetIDByPattern(edge.pattern);
matrix.at(edge.from).at(patternID) = edge.to;
}
}
}
/**
* DFAMatrix::FullMatch
*
* @param {u32string} str : check if the pattern can be applied to all of the string
* @return {bool} : returns true if can
*/
bool DFAMatrix::FullMatch(const u32string &str) const
{
return Match(str.begin(), str.end(), true) == static_cast<int>(str.size());
}
/**
* DFAMatrix::Search
*
* @param {u32string::const_iterator} strBegin : start of the target character range
* @param {u32string::const_iterator} strEnd : end of the target character range
* @return {u32string::const_iterator} : The start position of the first occurrence of the pattern. It equals to "strEnd" if the pattern is not found.
*/
u32string::const_iterator DFAMatrix::Search(u32string::const_iterator strBegin, u32string::const_iterator strEnd) const
{
if (matrix.size() > 0)
{
for (u32string::const_iterator start = strBegin; start < strEnd; start++)
{
int length = Match(start, strEnd, false);
if (length != -1)
{
return start;
}
}
return strEnd;
}
else
{
return strEnd;
}
}
/**
* DFAMatrix::Match
*
* Match the pattern from the beginning.
*
* @param {u32string::const_iterator} strBegin : start of the target character range
* @param {u32string::const_iterator} strEnd : end of the target character range
* @param {bool} greedyMode : If true, search for the longest match. Otherwise, return immediately once matched.
* @return {int} : the length of the matched string. -1 if no match.
*/
int DFAMatrix::Match(u32string::const_iterator strBegin, u32string::const_iterator strEnd, bool greedyMode) const
{
if (matrix.size() > 0)
{
int state = 0;
int lastMatchedLength = -1;
u32string::const_iterator i = strBegin;
while (i < strEnd)
{
char32_t c = *i;
bool matched = false;
if (IsEndState(state))
{
if (greedyMode)
{
/* if in greedy mode, keep matching */
/* try to find the longest match */
lastMatchedLength = static_cast<int>(i - strBegin);
}
else
{
/* if not in greedy mode, return the matched length */
return i - strBegin;
}
}
for (size_t j = 0; j < matrix.at(0).size(); j++)
{
if (matrix.at(state).at(j) != -1)
{
/* can transit from the current state to the next state if pattern j is matched */
auto pattern = patterns.GetPatternByID(static_cast<int>(j));
matched = MatchPattern(state, pattern, c, i, j, strBegin, strEnd);
if (matched)
{
/* if found a viable transition, jump out of the searching loop. */
break;
}
else
{
/* keep searching the next possible transition */
}
}
}
if (!matched)
{
/* if cannot match any pattern */
if (IsEndState(state))
{
/* if the current state is acceptable, return the current match. */
return i - strBegin;
}
else
{
/* if the current state is not acceptable, return the previous longest match */
return lastMatchedLength;
}
}
}
/* reaches to the end of the string */
if (IsEndState(state))
{
/* if the current state is acceptable, return the current match. */
return strEnd - strBegin;
}
else
{
/* if the current state is not acceptable, return the previous longest match */
return lastMatchedLength;
}
}
else
{
return (-1);
}
}
bool DFAMatrix::MatchPattern(
int &state,
const UnicodeRange &pattern,
char32_t c,
u32string::const_iterator &i,
size_t j,
u32string::const_iterator strBegin,
u32string::const_iterator strEnd) const
{
switch (pattern.rangeType)
{
case RangeType::CharacterRange:
{
if (pattern.InBetween(c))
{
// move to the next state
state = matrix.at(state).at(j);
i++;
return true;
}
else
{
return false;
}
}
case RangeType::LineBegin:
{
if (i == strBegin)
{
// move to the next state
state = matrix.at(state).at(j);
return true;
}
else
{
return false;
}
}
case RangeType::LineEnd:
{
if (i + 1 == strEnd)
{
// move to the next state
state = matrix.at(state).at(j);
return true;
}
else
{
return false;
}
}
default:
{
/* all the epsilon edges have been eliminated */
throw std::runtime_error("unreachable case branch");
}
}
}
bool DFAMatrix::IsEndState(int state) const
{
return endStates.count(state);
}
bool CanTransit(const Graph &G, StateID s1, StateID s2)
{
std::stack<StateID> stack;
unordered_set<StateID> visited;
stack.push(s1);
while (!stack.empty())
{
StateID current = stack.top();
stack.pop();
if (current == s2)
{
return true;
}
else
{
if (!visited.count(current))
{
visited.insert(current);
for (auto edge : G.Adj(current))
{
if (edge.pattern.IsEpsilon())
{
stack.push(edge.to);
}
}
}
}
}
return false;
}
} // namespace regex | true |
dc102e460b18bacc69f1fb53b9ee7ab8442c7b04 | C++ | bryding/Playlist-Helper | /Sources/MyHash.cpp | UTF-8 | 5,161 | 3.296875 | 3 | [] | no_license | #include "MyHash.h"
MyHash::MyHash(){
table.reserve(TABLE_SIZE);
}
int MyHash::hashing(string key){
const char* temp = key.c_str();
int c;
unsigned int hash = 5381;
while(c = *temp++){
hash = ((hash << 5) + hash) + c;
}
return hash;
}
void MyHash::insert(string key, int index){
unsigned int loc = findTableIndex(key);
if(table[loc].size() == 0){
Bucket temp(key, index);
table[loc].push_back(temp);
} else {
bool repeatWord = false;
unsigned int i = 0;
for (; i < table[loc].size(); i++){
if(key == table[loc][i].key){
repeatWord = true;
break;
}
}
if(repeatWord){
bool indexFound = false;
for(unsigned int j = 0; j < table[loc].size(); j++){
for (unsigned int k = 0; k < table[loc][j].indices.size(); k++){
if(index == table[loc][j].indices[k]) indexFound = true;
}
}
if(!indexFound) table[loc][i].indices.push_back(index);
} else{
Bucket temp(key, index);
table[loc].push_back(temp);
}
}
}
unsigned int MyHash::findTableIndex(string key){
unsigned int WHY = hashing(key);
WHY = WHY % TABLE_SIZE;
return WHY;
}
void MyHash::printBuckets() const{
std::cout << table[342][0].key;
std::cout << table[342][0].indices[0];
std::cout << table[342][0].indices[1];
std::cout << table[342][0].indices[2];
/*std::set<int>::const_iterator it;
for(unsigned int i = 0; i < buckets.size(); i++){
std::cout << buckets[i].keyword << ": ";
for(it = buckets[i].indices.begin(); it != buckets[i].indices.end(); it++){
std::cout << *it << ", ";
}
std::cout << "\n\n";
}
for(unsigned int i = 0; i < TABLE_SIZE; i++){
if(table[i].size() > 0){
std::cout << "Table Entry " << i << ": \n";
for (unsigned int j = 0; table[i].size(); j++){
std::cout << "Bucket" << j << " | " << "word: " << table[i][j].key << ": ";
for(unsigned int k = 0; k < table[i][j].indices.size(); k++){
std::cout << table[i][j].indices[k];
}
std::cout << "\n";
}
std::cout << "\n";
}
}*/
}
void MyHash::search(vector<string> keys, vector<int>& intersect){
vector<int> a, b;
bool match;
for(unsigned int i = 0; i < keys.size(); i++){
match = false;
//Find the index into the hash table
int loc = findTableIndex(keys[i]);
//Make sure there's actually a keyword corresponding to the key.
if(table[loc].size() > 0){
//Loop through each bucket at that table entry.
for(unsigned int j = 0; j < table[loc].size(); j++){
//If there is a match with the current key and the key at that table entry
if(table[loc][j].key == keys[i]){
//Loop through all the data at that table entry and place them in a.
for (unsigned int k = 0; k < table[loc][j].indices.size(); k++){
a.push_back(table[loc][j].indices[k]);
}
}
}
//Assuming out intersect vector has stuff in it..
if(intersect.size() > 0){
//Loop through a and intersect and any matching indices will be placed in b.
// There is where the intersection happens.
for(unsigned int j = 0; j < a.size(); j++){
for(unsigned int k = 0; k < intersect.size(); k++){
if(a[j] == intersect[k]){
match = true;
b.push_back(a[j]);
break;
}
}
}
} else {
//If intersect is empty we can just skip right to making b = a
match = true;
b = a;
}
//Set intersect = b, since b currently holds the intersection between a and intersect.
//Afterwards clear a and b to start again.
intersect = b;
b.clear();
a.clear();
}
//If no matches were found for this word, then clear out the whole intersect vector
// since no songs match one word in the keyword search.
if(!match) intersect.clear();
}
/*std::set<int> a, b, inter;
std::set<int>::iterator it, it2;
bool match = false;
for(unsigned int i = 0; i < keys.size(); i++){
for(unsigned int j = 0; j < buckets.size(); j++){
if(keys[i] == buckets[j].keyword){
match = true;
for(it = buckets[j].indices.begin(); it != buckets[j].indices.end(); it++){
a.insert(*it);
}
if(inter.size() > 0){
for(it = a.begin(); it != a.end(); it++){
for(it2 = inter.begin(); it2 != inter.end(); it2++){
if(*it == *it2){
b.insert(*it);
break;
}
}
}
} else {
b = a;
}
inter = b;
b.clear();
a.clear();
break;
}
if(j == buckets.size()-1 && !match){
inter.clear();
b.clear();
a.clear();
}
}
}
intersect = inter;
*/
}
| true |
fe7fccd268101b779c805d46a84994158e631295 | C++ | mark-tilton/quoridor | /game/src/vectord.cc | UTF-8 | 997 | 3.203125 | 3 | [
"MIT"
] | permissive | #include "vectord.h"
#include "vectori.h"
using namespace std;
Vectord::Vectord() : Vectord(0, 0) {
}
Vectord::Vectord(const double x, const double y) : x(x), y(y) {
}
Vectord::Vectord(const Vectori& vector) : x(vector.x), y(vector.y) {
}
Vectord Vectord::operator+(const Vectord &v) const {
return Vectord(x+v.x, y+v.y);
}
Vectord Vectord::operator-(const Vectord &v) const {
return Vectord(x-v.x, y-v.y);
}
bool Vectord::operator==(const Vectord &v) const {
return (x == v.x && y == v.y);
}
bool Vectord::operator!=(const Vectord &v) const {
return (x != v.x || y != v.y);
}
Vectord Vectord::operator-() const {
return Vectord(-x, -y);
}
Vectord Vectord::operator*(const float& scalar) const {
return Vectord(x*scalar, y*scalar);
}
Vectord Vectord::operator/(const float& scalar) const {
return Vectord(x/scalar, y/scalar);
}
std::ostream &operator<< (std::ostream &os, const Vectord &v) {
os << "(" << v.x << ", " << v.y << ")";
return os;
}; | true |
4e2ee7e4dfa1a51aca526eec062313d571333762 | C++ | araetoro/C-Plus-Plus-Final-Project | /Roster.cpp | UTF-8 | 7,346 | 3.171875 | 3 | [] | no_license | #include"Degree.h"
#include"Roster.h"
#include"NetworkStudent.h"
#include"SecurityStudent.h"
#include"SoftwareStudent.h"
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
Roster::Roster() {}
//Deconstructor
Roster::~Roster() {}
//Updateing the class roster array
void Roster::add(string sID, string fName, string lName, string e, int a, int day0, int day1, int day2, Degree degree) {
int numDaysIn[] = { day0, day1, day2 };
if (degree == Degree::NETWORKING) {
classRosterArray[addIndex++] = new NetworkStudent(sID, fName, lName, e, a, numDaysIn, degree);
}
if (degree == Degree::SOFTWARE) {
classRosterArray[addIndex++] = new SoftwareStudent(sID, fName, lName, e, a, numDaysIn, degree);
}
if (degree == Degree::SECURITY) {
classRosterArray[addIndex++] = new SecurityStudent(sID, fName, lName, e, a, numDaysIn, degree);
}
}
//printing the entire clas sroster
void Roster::printAll() {
cout << "Class Roster:" << endl;
cout << endl;
for (int i = 0; i < 5; i++) {
(classRosterArray[i])->print();
cout << endl;
}
cout << endl;
}
//printing the average days to complete 3 courses
//void Roster::printnumDays() {
// for (int i = 0; i < 5; i++) {
// int avg = 0;
// avg = ((classRosterArray[i])->getNumDays()[0] + (classRosterArray[i])->getNumDays()[1] + (classRosterArray[i])->getNumDays()[2]) / 3;
// cout << "The average number of days it took the student with Student ID #: " << (classRosterArray[i])->getStudentID() <<
// " to finish their coursework was " << avg << endl;
// cout << endl;
// }
//}
//printing the average days to complete 3 courses
void Roster::printnumDays(string aID) {
for (int i = 0; i < 5; i++) {
int avg = 0;
if (aID == classRosterArray[i]->getStudentID()) {
avg = ((classRosterArray[i])->getNumDays()[0] + (classRosterArray[i])->getNumDays()[1] + (classRosterArray[i])->getNumDays()[2]) / 3;
cout << "The average number of days it took the student with Student ID #: " << (classRosterArray[i])->getStudentID() <<
" to finish their coursework was " << avg << endl;
cout << endl;
}
}
}
//Printing students by degree program
void Roster::printByDegree(string degree) {
Degree degreeType = Degree::SOFTWARE;
if (degree == "NETWORKING") {
degreeType = Degree::NETWORKING;
cout << "Displaying students in the Netwroking degree program: " << endl;
cout << endl;
for (int i = 0; i < 5; i++) {
if (degreeType == (classRosterArray[i])->getDegree()) {
(classRosterArray[i])->print();
}
else {
continue;
}
}
cout << endl;
}
if (degree == "SOFTWARE") {
degreeType = Degree::SOFTWARE;
cout << "Displaying students in the Software degree program: " << endl;
cout << endl;
for (int i = 0; i < 5; i++) {
if (degreeType == (classRosterArray[i])->getDegree()) {
(classRosterArray[i])->print();
}
else {
continue;
}
}
cout << endl;
}
if (degree == "SECURITY") {
degreeType = Degree::SECURITY;
cout << "Displaying students in the Security degree program: " << endl;
cout << endl;
for (int i = 0; i < 5; i++) {
if (degreeType == (classRosterArray[i])->getDegree()) {
(classRosterArray[i])->print();
}
else {
continue;
}
}
cout << endl;
}
cout << endl;
}
//Checking Emails for invalid entries
void Roster::printBadEmails() {
cout << "Displaying invalid Emails:" << endl;
cout << endl;
for (int i = 0; i < 5; i++) {
bool foundCharAt = false;
bool foundCharPeriod = false;
bool foundCharSpace = false;
string email = "";
email = (*classRosterArray[i]).getEmail();
for (char& c : email) {
if (c == '@') {
foundCharAt = true;
}
if (c == '.') {
foundCharPeriod = true;
}
if (c == ' ') {
foundCharSpace = true;
}
}
if (foundCharAt == false || foundCharPeriod == false || foundCharSpace == true) {
cout << (*classRosterArray[i]).getEmail() << endl;
cout << endl;
}
}
}
//removing students from class roster array
void Roster::remove(string id) {
bool removed = false;
for (int i = 0; i < 5; i++) {
string getID = classRosterArray[i]->getStudentID();
if (classRosterArray[i] != NULL) {
if (id == getID) {
classRosterArray[i] = NULL;
//delete classRosterArray[i];
removed = true;
}
}
}
if (removed == true) {
cout << "The student with student ID #: " << id << " was not found." << endl;
}
//else {
//cout << "The student with student ID #: " << id << " was not found." << endl;
//}
}
int main() {
//Student Data
const string studentData[] = {
"A1,John,Smith,John1989@gm ail.com,20,30,35,40,NETWORKING",
"A2,Suzan,Erickson,Erickson_1990@gmailcom,19,50,30,40,NETWORKING",
"A3,Jack,Napoli,The_lawyer99yahoo.com,19,20,40,33,SOFTWARE",
"A4,Erin,Black,Erin.black@comcast.net,22,50,58,40,SECURITY",
"A5,Amber,Keech,akeech1@wgu.edu,30,30,33,40,SOFTWARE"
};
//Class Roster Instance
Roster *classRoster=new Roster();
//Degree Instance
Degree myDegree = Degree::SECURITY;
//adding students to the class roster array
for (int i = 0; i < 5; i++) {
stringstream ss(studentData[i]);
vector <string> result;
while (ss.good()) {
string substr;
getline(ss, substr, ',');
result.push_back(substr);
}
if (result[8] == "NETWORKING") {
myDegree = Degree::NETWORKING;
}
if (result[8] == "SECURITY") {
myDegree = Degree::SECURITY;
}
if (result[8] == "SOFTWARE") {
myDegree = Degree::SOFTWARE;
}
classRoster->add(result[0], result[1], result[2], result[3], stoi(result[4]), stoi(result[5]), stoi(result[6]), stoi(result[7]), myDegree);
}
//Print personal information
cout << "Scripting and Programming - Applications C867" << endl;
cout << "C++" << endl;
cout << "Student ID: #000938334" << endl;
cout << "Amber Keech" << endl;
cout << endl;
//printing all requirments
classRoster->printAll();
classRoster->printBadEmails();
classRoster->printnumDays("A1");
classRoster->printnumDays("A2");
classRoster->printnumDays("A3");
classRoster->printnumDays("A4");
classRoster->printnumDays("A5");
classRoster->printByDegree("SOFTWARE");
classRoster->remove("A3");
classRoster->remove("A3");
}
| true |
ca2b4f9aec7b412c737234ca58a7e5764a25ab69 | C++ | naiyer-abbas/Code-Forces | /Contests/18 MRACH 2021/B.cpp | UTF-8 | 1,948 | 2.546875 | 3 | [] | no_license | #pragma GCC optimize("O2")
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ull unsigned long long int
#define pb push_back
#define mp make_pair
#define fast ios_base :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define MOD 1000000007
int main()
{
fast;
int t;
cin >> t;
while(t --)
{
string s;
cin >> s;
int br= 0;
bool adj_0 = false;
bool adj_1 = false;
if(is_sorted(s.begin(), s.end()))
{
cout << "YES" << endl;
continue;
}
for(int i = 0; i < s.size() - 1; i++)
{
if(s.at(i) == '0' && s.at(i + 1) == '0')
{
br = 1;
adj_0 = true;
break;
}
}
if(!br) // if no adjacent zeroes are present
{
cout << "YES" << endl;
continue;
}
br = 0;
for(int i = 0; i < s.size() - 1; i++)
{
if(s.at(i) == '1' && s.at(i + 1) == '1')
{
br = 1;
adj_1 = true;
break;
}
}
if(!br) // if no adjacet ones
{
cout << "YES" << endl;
continue;
}
int first = -1;
for(int i = 0; i < s.size() - 1; i++)
{
if(s.at(i) == '1' && s.at(i + 1) == '1')
{
first = i;
break;
}
}
int last = -1;
for(int i = s.size() - 1; i > 0; i--)
{
if(s.at(i) == '0' && s.at(i - 1) == '0')
{
last = i;
break;
}
}
if(last > first) // if adjacent ones are present before adjacent zeroes
{
cout << "NO" << endl;
continue;
}
cout << "YES" << endl;
}
}
| true |
11a2d802007c39ca084bebeec24c1f9498ae3725 | C++ | aphilippe/ClappLauncher | /src/FileSystem/Operations/ReadInformationOperationUnix.cpp | UTF-8 | 385 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "ReadInformationOperation.h"
#ifndef WIN32
#include <unistd.h>
#include <sys/stat.h>
using file_system::operations::ReadInformationOperation;
using file_system::Path;
bool ReadInformationOperation::isExecutable(const Path & path) const
{
struct stat st;
if (stat(path.stringValue().c_str(), &st) < 0)
return false;
return (st.st_mode & S_IEXEC) != 0;
}
#endif | true |
1fb0fddd685e0016683b2d0e691905839a748950 | C++ | Imagine-Programming/hindsight | /hindsight/Process.cpp | UTF-8 | 6,242 | 3.28125 | 3 | [
"MIT"
] | permissive | #include "Process.hpp"
using namespace Hindsight::Process;
/// <summary>
/// Construct a new process based on a const reference to a <see cref="PROCESS_INFORMATION"/> instance, a path, a working directory and program arguments.
/// </summary>
/// <param name="pi">A const reference to a <see cref="PROCESS_INFORMATION"/> struct.</param>
/// <param name="path">The program path.</param>
/// <param name="workingDirectory">The program starting working directory.</param>
/// <param name="args">The program arguments.</param>
Process::Process(
const PROCESS_INFORMATION& pi,
const std::string& path,
const std::string& workingDirectory,
const std::vector<std::string>& args) :
hProcess(pi.hProcess),
hThread(pi.hThread),
dwProcessId(pi.dwProcessId),
dwThreadId(pi.dwThreadId),
Path(path),
WorkingDirectory(workingDirectory),
Arguments(args) {
}
/// <summary>
/// The destructor which closes the process and thread handles.
/// </summary>
Process::~Process() {
Close();
}
/// <summary>
/// Create a <see cref="PROCESS_INFORMATION"/> struct about this instance.
/// </summary>
/// <returns>A <see cref="PROCESS_INFORMATION"/> struct.</returns>
PROCESS_INFORMATION Process::GetProcessInformation() {
return {
hProcess,
hThread,
dwProcessId,
dwThreadId
};
}
/// <summary>
/// Resume the main thread.
/// </summary>
/// <returns>When successful, true is returned.</returns>
bool Process::Resume() {
return ResumeThread(hThread) != (DWORD)-1;
}
/// <summary>
/// Suspend the main thread.
/// </summary>
/// <returns>When successful, true is returned.</returns>
bool Process::Suspend() {
return SuspendThread(hThread) != (DWORD)-1;
}
/// <summary>
/// Determine if the process is still running/alive.
/// </summary>
/// <returns>When the process is alive, true is returned.</returns>
/// <remarks>
/// note: when the process has an exit code STILL_ACTIVE, this function will return true.
/// </remarks>
bool Process::Running() {
DWORD exitCode;
return GetExitCodeProcess(hProcess, &exitCode) && exitCode == STILL_ACTIVE;
}
/// <summary>
/// Determines if the process is a 32-bit program running in WOW64 mode.
/// </summary>
/// <returns>When the process is a WOW64 process, true is returned.</returns>
bool Process::IsWow64() {
BOOL iswow;
return IsWow64Process(hProcess, &iswow) && iswow;
}
/// <summary>
/// Determines if the process is a 64-bit native program.
/// </summary>
/// <returns>When the process is not a WOW64 process, true is returned.</returns>
/// <remarks>note: identical to !<see cref="IsWow64"/>().</remarks>
bool Process::Is64() {
return !IsWow64();
}
/// <summary>
/// Close the process and thread handles.
/// </summary>
void Process::Close() {
if (hThread) { CloseHandle(hThread); hThread = NULL; }
if (hProcess) { CloseHandle(hProcess); hProcess = NULL; }
}
/// <summary>
/// Kill the process forcefully.
/// </summary>
/// <param name="exitCode">The exit code to terminate the process with, such as an exception code.</param>
/// <remarks>
/// note: This is used in post-mortem debugging to kill the process.
/// </remarks>
void Process::Kill(UINT exitCode) {
TerminateProcess(hProcess, exitCode);
}
/// <summary>
/// Read a string from the memory space of the process.
/// </summary>
/// <param name="address">The address in the memory space of the process where the string is stored.</param>
/// <param name="length">The length of the string, in bytes.</param>
/// <returns>The resulting string, or "" when something went wrong.</returns>
std::string Process::ReadString(void* address, size_t length) const {
if (length == 0)
return "";
SIZE_T read;
std::string result(length, ' ');
if (!ReadProcessMemory(hProcess, reinterpret_cast<LPCVOID>(address), reinterpret_cast<LPVOID>(&result[0]), length, &read))
return "";
return result;
}
/// <summary>
/// Read a wchar_t string from the memory space of the process.
/// </summary>
/// <param name="address">The address in the memory space of the process where the string is stored.</param>
/// <param name="length">The length of the string, in bytes.</param>
/// <returns>The resulting string, or L"" when something went wrong.</returns>
std::wstring Process::ReadStringW(void* address, size_t length) const {
if (length == 0)
return L"";
SIZE_T read;
std::wstring result(length / sizeof(wchar_t), L' ');
if (!ReadProcessMemory(hProcess, reinterpret_cast<LPCVOID>(address), reinterpret_cast<LPVOID>(&result[0]), length, &read))
return L"";
return result;
}
/// <summary>
/// Read an arbitrary amount of memory from the memory space of the process.
/// </summary>
/// <param name="address">The address in the memory space of the process where the value is stored.</param>
/// <param name="length">The length of data to read, in bytes.</param>
/// <param name="output">The output buffer that will contain the read data.</param>
/// <returns>When successful, true is returned.</returns>
bool Process::Read(const void* address, size_t length, void* output) const {
if (length == 0)
return false;
SIZE_T readSize;
if (!ReadProcessMemory(hProcess, reinterpret_cast<LPCVOID>(address), reinterpret_cast<LPVOID>(output), length, &readSize))
return false;
if (static_cast<size_t>(readSize) != length)
return false;
return true;
}
/// <summary>
/// Read a (c-style) string from the memory space of the process which should terminate with a single or more \0 character(s).
/// </summary>
/// <param name="address">The address in the memory space of the process where the string is stored.</param>
/// <param name="maximumLength">The length in bytes at which the scan should stop searching for NUL.</param>
/// <returns>The resulting string, or "" when something went wrong.</returns>
std::string Process::ReadNulTerminatedString(const void* address, size_t maximumLength) const {
std::vector<char> data;
char character;
size_t offset = 0;
while (true) {
if (!Read(static_cast<const void*>(static_cast<const uint8_t*>(address) + offset), character))
return "";
data.push_back(character);
if (character == 0)
break;
offset += 1;
if (maximumLength != 0 && offset >= maximumLength) {
data.push_back(0);
break;
}
}
return std::string(data.begin(), data.end());
} | true |
4f0113e4a1a9a44b25c156c94fccca74053b6881 | C++ | ali-bibak/corrida | /src/Intelligence.cpp | UTF-8 | 22,868 | 2.859375 | 3 | [] | no_license | /***********************************************
Intelligence.cpp
Artificial Intelligence source for Corrida
by: Ali Bibak
last modified: Jul 20, 2014
***********************************************/
#include "Intelligence.h"
// bfi's for bfsMonster and bfsStars
int bfiM[8][8], bfiS[8][8];
// check if the requested move is valid
bool check_validity(int player, int ind, const Movement &m, const Map &map, int walls1, int walls2, bool monsterPause){
int x1 = m.x1, x2 = m.x2, y1 = m.y1, y2 = m.y2;
// wrong initial cell
if(x1 < 0 || x1 > 7 || y1 < 0 || y1 > 7)
return false;
char before = map.get_cell(x1,y1), chars[5] = {'M', 'p', 'P', 'q', 'Q'};
if(player == 0 && before != 'M')
return false;
else if(player == 1 && before != chars[ind])
return false;
else if(player == 2 && before != chars[2+ind])
return false;
// walking out of the grid
if(x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7)
return false;
// wrong wall char
if(m.wall != 'n' && m.wall != 'U' && m.wall != 'L' && m.wall != 'D' && m.wall != 'R')
return false;
char after = map.get_cell(x2,y2);
bool isMonster = before == 'M';
point dir(x2-x1, y2-y1);
// walking in wrong directions
if(dir != steady && dir != up && dir != left && dir != down && dir != right)
return false;
// walking through a wall
if((dir == up && map.is_h_wall(x1-1,y1))
|| (dir == left && map.is_v_wall(x1,y1-1))
|| (dir == down && map.is_h_wall(x1,y1))
|| (dir == right && map.is_v_wall(x1,y1)))
return false;
// monster
if(isMonster){
// doing anything when supposed to stop
if(monsterPause && (dir != steady || m.wall != 'n'))
return false;
// moving to a box
if(after == '#')
return false;
// destroying a wall outside of grid or a non-existing wall
switch(m.wall){
case 'U':
if(x2 == 0 || !map.is_h_wall(x2-1,y2))
return false;
break;
case 'L':
if(y2 == 0 || !map.is_v_wall(x2,y2-1))
return false;
break;
case 'D':
if(x2 == 7 || !map.is_h_wall(x2,y2))
return false;
break;
case 'R':
if(y2 == 7 || !map.is_v_wall(x2,y2))
return false;
break;
}
// otherwise
return true;
}
else{
// moving to monster
if(after == 'M')
return false;
// moving to another player
if(dir != steady && (after == 'p' || after == 'q' || after == 'P' || after == 'Q'))
return false;
// pushing a box outside of the grid, or to a non-empty cell or through a wall
if(after == '#')
if((dir == up && (x2 == 0 || (map.get_cell(x2-1,y2) != '.' && map.get_cell(x2-1,y2) != 's') || map.is_h_wall(x2-1,y2)))
|| (dir == left && (y2 == 0 || (map.get_cell(x2,y2-1) != '.' && map.get_cell(x2,y2-1) != 's') || map.is_v_wall(x2,y2-1)))
|| (dir == down && (x2 == 7 || (map.get_cell(x2+1,y2) != '.' && map.get_cell(x2+1,y2) != 's') || map.is_h_wall(x2,y2)))
|| (dir == right && (y2 == 7 || (map.get_cell(x2,y2+1) != '.' && map.get_cell(x2,y2+1) != 's') || map.is_v_wall(x2,y2))))
return false;
// making more walls than possible
if(m.wall != 'n')
switch(before){
case 'p':
case 'P':
if(walls1 == 0)
return false;
break;
case 'q':
case 'Q':
if(walls2 == 0)
return false;
break;
}
// pulling a box when steady
if(dir == steady && m.pull)
return false;
// pulling a non-existing box, or a box through a wall
if(m.pull)
if((dir == up && (x1 == 7 || map.get_cell(x1+1,y1) != '#' || map.is_h_wall(x1,y1)))
|| (dir == left && (y1 == 7 || map.get_cell(x1,y1+1) != '#' || map.is_v_wall(x1,y1)))
|| (dir == down && (x1 == 0 || map.get_cell(x1-1,y1) != '#' || map.is_h_wall(x1-1,y1)))
|| (dir == right && (y1 == 0 || map.get_cell(x1,y1-1) != '#' || map.is_v_wall(x1,y1-1))))
return false;
// making a wall outside of grid or over an existing wall
switch(m.wall){
case 'U':
if(x2 == 0 || map.is_h_wall(x2-1,y2))
return false;
break;
case 'L':
if(y2 == 0 || map.is_v_wall(x2,y2-1))
return false;
break;
case 'D':
if(x2 == 7 || map.is_h_wall(x2,y2))
return false;
break;
case 'R':
if(y2 == 7 || map.is_v_wall(x2,y2))
return false;
break;
}
// otherwise
return true;
}
}
// find a character in a map
bool findChar(const Map &map, char ch, int &x, int &y){
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
if(map.get_cell(i,j) == ch){
x = i;
y = j;
return true;
}
return false;
}
// bfs from a cell to find the best path for monster/stars
void bfs(int x, int y, const Map &map, bool isMonster, int bfi[8][8], bool monsterPause){
point move[4] = {up, left, down, right};
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
bfi[i][j] = inf;
bfi[x][y] = monsterPause;
queue<point> que;
que.push(point(x, y));
while(!que.empty()){
point top = que.front();
que.pop();
// considering all possible directions to go
for(int i = 0; i < 4; i++){
point to = top + move[i], dir = -move[i];
if(to.X() >= 0 && to.X() < 8 && to.Y() >= 0 && to.Y() < 8 && (map.get_cell(to.X(),to.Y()) == '.' || map.get_cell(to.X(),to.Y()) == 's' || (map.get_cell(to.X(),to.Y()) == 'M' && isMonster) || ((map.get_cell(to.X(),to.Y()) != '#' && map.get_cell(to.X(),to.Y()) != 'M' && !isMonster)))){
int add = 1;
// chekcing for breaking the walls (for monsters)
if((dir == up && map.is_h_wall(to.X()-1,to.Y()))
|| (dir == left && map.is_v_wall(to.X(),to.Y()-1))
|| (dir == down && map.is_h_wall(to.X(),to.Y()))
|| (dir == right && map.is_v_wall(to.X(),to.Y()))){
if(isMonster)
add++;
else
continue;
}
switch(map.get_cell(top.X(),top.Y())){
case 'p':
case 'P':
case 'q':
case 'Q':
if(isMonster)
add += top != point(x, y);
else
continue;
break;
}
if(bfi[to.X()][to.Y()] > (bfi[top.X()][top.Y()] + add)){
bfi[to.X()][to.Y()] = bfi[top.X()][top.Y()] + add;
if(isMonster && map.get_cell(to.X(),to.Y()) == 'M')
return;
que.push(to);
}
}
}
}
}
// bfs from a cell to find the best path for monster
void bfsMonster(int x, int y, const Map &map, bool monsterPause){
bfs(x, y, map, true, bfiM);
}
// bfs from a cell to find the best path for stars
void bfsStars(int x, int y, const Map &map){
bfs(x, y, map, false, bfiS);
}
// cmp for sorting moves according to their goodness
bool cmp(const pair<pair<int, Movement>, char> &pr1, const pair<pair<int, Movement>, char> &pr2){
return pr1.first.first < pr2.first.first;
}
// next movement for monster
Movement monster_next(const Map &map, char &target, bool monsterPause){
int dummy;
bool p1alive1, p1alive2, p2alive1, p2alive2;
p1alive1 = findChar(map, 'p', dummy, dummy);
p1alive2 = findChar(map, 'P', dummy, dummy);
p2alive1 = findChar(map, 'q', dummy, dummy);
p2alive2 = findChar(map, 'Q', dummy, dummy);
pair<pair<int, Movement>, char> bestMove[4];
int num = 0, x, y, X, Y, x1, y1, x2, y2;
findChar(map, 'M', X, Y);
// if it should stop
if(monsterPause){
Movement m(X, Y, X, Y, 'n', false);
return m;
}
x1 = X;
y1 = Y;
char wall;
point move[4] = {up, left, down, right};
bool alive[4] = {p1alive1, p1alive2, p2alive1, p2alive2};
char chars[4] = {'p', 'P', 'q', 'Q'};
// analyze all players that are still alive
for(int i = 0; i < 4; i++)
if(alive[i]){
findChar(map, chars[i], x, y);
bfsMonster(x, y, map);
int minimum = inf;
// analyzing the neighbour cells
x2 = x1;
y2 = y1;
for(int j = 0; j < 4; j++){
point N = point(X, Y) + move[j];
if(N.X() >= 0 && N.X() < 8 && N.Y() >= 0 && N.Y() < 8 && bfiM[N.X()][N.Y()] <= minimum){
minimum = bfiM[N.X()][N.Y()];
x2 = N.X();
y2 = N.Y();
}
}
minimum = inf;
int nx, ny;
char wall = 'n';
bool stay = true;
point dir = point(x2, y2) - point(x1, y1);
// checking if we need to stay (because of a wall) and break it
if(dir == up && map.is_h_wall(x1-1,y1))
wall = 'U';
else if(dir == left && map.is_v_wall(x1,y1-1))
wall = 'L';
else if(dir == down && map.is_h_wall(x1,y1))
wall = 'D';
else if(dir == right && map.is_v_wall(x1,y1))
wall = 'R';
else
stay = false;
if(stay){
Movement m(x1, y1, x1, y1, wall, false);
bestMove[num++] = make_pair(make_pair(bfiM[X][Y], m), chars[i]);
continue;
}
// if we will reach the player in the next turn
if(bfiM[x2][y2] == 0){
Movement m(x1, y1, x2, y2, wall, false);
bestMove[num++] = make_pair(make_pair(bfiM[X][Y], m), chars[i]);
continue;
}
// analyzing the next wall to break (if any)
for(int j = 0; j < 4; j++){
point N = point(x2, y2) + move[j];
if(N.X() >= 0 && N.X() < 8 && N.Y() >= 0 && N.Y() < 8 && bfiM[N.X()][N.Y()] <= minimum){
minimum = bfiM[N.X()][N.Y()];
nx = N.X();
ny = N.Y();
}
}
dir = point(nx, ny) - point(x2, y2);
// checking if we need to break a wall after the move
if(dir == up && map.is_h_wall(x2-1,y2))
wall = 'U';
else if(dir == left && map.is_v_wall(x2,y2-1))
wall = 'L';
else if(dir == down && map.is_h_wall(x2,y2))
wall = 'D';
else if(dir == right && map.is_v_wall(x2,y2))
wall = 'R';
Movement m(x1, y1, x2, y2, wall, false);
bestMove[num++] = make_pair(make_pair(bfiM[X][Y], m), chars[i]);
}
// sort moves based on their goodness
sort(bestMove, bestMove + num, cmp);
int last = 0;
while(last < num && bestMove[last].first.first == bestMove[0].first.first){
// if the last target is one of the best moves
if(target == bestMove[last].second)
return bestMove[last].first.second;
last++;
}
// randomly select one of the candidates
srand(time(0));
int r = rand() % last;
// change the target
target = bestMove[r].second;
return bestMove[r].first.second;
}
// change the map after a valid movement
void change(const Movement &m, Map &map){
int x1 = m.x1, y1 = m.y1, x2 = m.x2, y2 = m.y2;
char before = map.get_cell(x1,y1), after = map.get_cell(x2,y2);
map.set_cell(x2,y2,before);
bool isMonster = before == 'M';
point dir(x2-x1, y2-y1);
// monster
if(isMonster){
// cleaning the previous cell
if(dir != steady)
map.set_cell(x1,y1,'.');
}
// player
else{
// managing the previous cell
if(dir != steady)
if(!m.pull)
map.set_cell(x1,y1,'.');
// pulling a box
else{
map.set_cell(x1,y1,'#');
map.set_cell(x1-(x2-x1),y2-(y2-y1),'.');
}
// pushing a box
if(after == '#')
map.set_cell(x2+(x2-x1),y2+(y2-y1),'#');
}
// making/destroying a wall
switch(m.wall){
case 'U':
map.set_h_wall(x2-1,y2,!isMonster);
break;
case 'L':
map.set_v_wall(x2,y2-1,!isMonster);
break;
case 'D':
map.set_h_wall(x2,y2,!isMonster);
break;
case 'R':
map.set_v_wall(x2,y2,!isMonster);
break;
}
}
// update server variables after a move
void update(const Movement &m, const Map &map, bool &monsterPause, bool &p1alive1, bool &p1alive2, bool &p2alive1, bool &p2alive2, int &walls1, int &walls2, int &p1score, int &p2score){
int x1 = m.x1, y1 = m.y1, x2 = m.x2, y2 = m.y2;
char before = map.get_cell(x1,y1), after = map.get_cell(x2,y2);
bool isMonster = before == 'M';
point dir(x2-x1, y2-y1);
// monster
if(isMonster){
// should pause the next time
if(m.wall != 'n' || after == 'p' || after == 'P' || after == 'q' || after == 'Q')
monsterPause = true;
else
monsterPause = false;
// moving to a player
switch(after){
case 'p':
p1alive1 = false;
break;
case 'P':
p1alive2 = false;
break;
case 'q':
p2alive1 = false;
break;
case 'Q':
p2alive2 = false;
break;
}
}
// player
else{
// number of walls
if(m.wall != 'n')
switch(before){
case 'p':
case 'P':
walls1--;
break;
case 'q':
case 'Q':
walls2--;
break;
}
// getting a star
if(after == 's')
switch(before){
case 'p':
case 'P':
p1score++;
break;
case 'q':
case 'Q':
p2score++;
break;
}
}
}
// calculating value of a board for a player
double evaluate(bool color, const Map &map, bool p1alive1, bool p1alive2, bool p2alive1, bool p2alive2, int star){
char chars[4] = {'p', 'P', 'q', 'Q'};
bool alive[5] = {p1alive1, p1alive2, p2alive1, p2alive2};
int c = 0;
if(!color)
c = 2;
double value = 0.0;
// considering alive pieces
int X, Y;
findChar(map, 'M', X, Y);
for(int i = 0; i < 2; i++){
int ind = c + i, x, y;
if(alive[ind]){
char ch = chars[ind];
findChar(map, ch, x, y);
bfsMonster(x, y, map);
int numStars = 0;
for(int j = 0; j < 8; j++)
for(int k = 0; k < 8; k++)
if(map.get_cell(j,k) == 's')
numStars++;
if(numStars == 0)
return pow(star+1, 2) * pow(bfiM[X][Y] - 1, 2);
// gain (player/stars situation)
double D = 50;
double gain = 0.0;
for(int j = 0; j < 8; j++)
for(int k = 0; k < 8; k++)
if(map.get_cell(j,k) == 's'){
bfsStars(j, k, map);
if(numStars == 1)
return (pow(star+1, 2) * pow(min(bfiM[X][Y] - 1, 10), 2)) / (double) pow(bfiS[x][y], 2);
int ds2s_sum = 0;
for(int u = 0; u < 8; u++)
for(int v = 0; v < 8; v++)
if(map.get_cell(u,v) == 's')
if(bfiS[u][v] != inf)
ds2s_sum += bfiS[u][v];
// sparseness (star/stars situation)
double sparseness = (double) ds2s_sum / numStars, d, thisGain;
if(bfiS[x][y] != inf){
d = bfiS[x][y];
D = min(d, D);
}
else{
d = 2 * (abs(x-j) + abs(y-k)) * (abs(x-j) + abs(y-k));
D = min(d, D);
}
thisGain = pow(d, 3) * sparseness;
gain += thisGain;
}
gain /= numStars;
// value depending on gain, number of stars taken, and distance from monster
value += (pow(star+1, 2) * min(bfiM[X][Y] - 1, 10)) / (gain * pow(D, 2));
}
}
return value;
}
// calculate the best next move for a player
Movement player_next(const Map &const_map, bool color, int ind, int numWalls){
char chars[4] = {'p', 'P', 'q', 'Q'};
int c = (1-color)*2 + (ind-1), x, y, x2, y2, X, Y, dm = inf, star;
Map temporary_map, map;
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
map.set_cell(i, j, const_map.get_cell(i, j));
for(int i = 0; i < 7; i++)
for(int j = 0; j < 8; j++){
map.set_h_wall(i, j, const_map.is_h_wall(i, j));
map.set_v_wall(j, i, const_map.is_v_wall(j, i));
}
findChar(map, 'M', X, Y);
findChar(map, chars[c], x, y);
point pts[5] = {up, left, down, right, steady};
char walls[5] = {'U', 'L', 'D', 'R', 'n'};
Movement mv(x, y, x, y, 'n', false);
bfsMonster(x, y, map, false);
dm = bfiM[X][Y];
// if distance from monster is 1
if(dm == 1){
int maxi = 0;
char andWall = 'n';
for(int i = 0; i < 4; i++)
for(int j = 0; j < 5; j++)
for(int p = 0; p < 2; p++){
x2 = x+pts[i].X(), y2 = y+pts[i].Y();
andWall = walls[j];
Movement m = Movement(x, y, x2, y2, andWall, p);
temporary_map.set(map);
if(check_validity(!color+1, ind, m, temporary_map, numWalls, numWalls, false)){
change(m, temporary_map);
bfsMonster(x2, y2, temporary_map);
int newD = bfiM[X][Y];
if(newD == inf)
newD = 10 * (abs(x2-X) + abs(y2-Y));
if(newD > maxi){
maxi = newD;
mv = m;
}
}
}
if(maxi > 2)
return mv;
if((x != 7 && map.get_cell(x+1,y) == 'M') || (x != 0 && map.get_cell(x-1,y) == 'M')){
mv = Movement(x, y, x+1, y, 'U', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x+1, y, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x-1, y, 'D', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x-1, y, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x, y+1, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x, y-1, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
if(x != 7 && map.get_cell(x+1,y) == 'M'){
mv = Movement(x, y, x, y, 'D', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
}
else{
mv = Movement(x, y, x, y, 'U', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
}
}
if((y != 7 && map.get_cell(x,y+1) == 'M') || (y != 0 && map.get_cell(x,y-1) == 'M')){
mv = Movement(x, y, x, y+1, 'L', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x, y+1, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x, y-1, 'R', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x, y-1, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x+1, y, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
mv = Movement(x, y, x-1, y, 'n', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
if(y != 7 && map.get_cell(x,y+1) == 'M'){
mv = Movement(x, y, x, y, 'R', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
}
else{
mv = Movement(x, y, x, y, 'L', false);
if(check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
return mv;
}
}
}
double maximum = -1, fmaximum = -1;
int dummy;
bool p1alive1, p1alive2, p2alive1, p2alive2;
p1alive1 = findChar(map, 'p', dummy, dummy);
p1alive2 = findChar(map, 'P', dummy, dummy);
p2alive1 = findChar(map, 'q', dummy, dummy);
p2alive2 = findChar(map, 'Q', dummy, dummy);
Map best;
bool gotStar = false;
// calculating the best next move based on evaluation in evaluate()
for(int i = 0; i < 5; i++)
for(int p = 0; p < 2; p++){
x2 = x + pts[i].X();
y2 = y + pts[i].Y();
Movement m(x, y, x2, y2, 'n', p);
temporary_map.set(map);
if(check_validity(!color+1, ind, m, temporary_map, numWalls, numWalls, false)){
star = temporary_map.get_cell(m.x2,m.y2) == 's';
change(m, temporary_map);
bfsMonster(x, y, temporary_map, false);
bool nowGotStar = false, inDanger = bfiM[X][Y] <= 2;
if(star)
gotStar = nowGotStar = true;
double value = evaluate(color, temporary_map, p1alive1, p1alive2, p2alive1, p2alive2, star);
if((!inDanger) && ((gotStar && nowGotStar && value > fmaximum) || (!gotStar && value > maximum))){
if(gotStar)
fmaximum = value;
else
maximum = value;
mv = m;
}
}
}
if(!check_validity(!color+1, ind, mv, map, numWalls, numWalls, false))
mv = Movement(x, y, x, y, 'n', false);
Movement save = mv;
x2 = mv.x2, y2 = mv.y2;
char andWall = mv.wall;
bfsMonster(x2, y2, map, false);
dm = bfiM[X][Y];
if(bfiM[X][Y] == inf)
dm = 10 * (abs(X-x2) + abs(Y-y2));
// if distance from monster will be 1
if(dm == 1){
int maxi = 0;
char andWall = 'n';
for(int i = 0; i < 5; i++)
for(int j = 4; j >= 0; j--)
for(int p = 0; p < 2; p++){
x2 = x+pts[i].X(), y2 = y+pts[i].Y();
andWall = walls[j];
Movement m = Movement(x, y, x2, y2, andWall, p);
temporary_map.set(map);
if(check_validity(!color+1, ind, m, temporary_map, numWalls, numWalls, false)){
change(m, temporary_map);
bfsMonster(x2, y2, temporary_map);
int newD = bfiM[X][Y];
if(newD == inf)
newD = 10 * (abs(x2-X) + abs(y2-Y));
if(newD > maxi){
maxi = newD;
mv = m;
}
}
}
if((maxi > 1) || (maxi >= 1 && andWall == 'n'))
return mv;
andWall = 'n';
if(x2 != 0 && map.get_cell(x2-1,y2) == 'M' && !map.is_v_wall(x2-1,y2) && numWalls)
andWall = 'U';
else if(x2 != 7 && map.get_cell(x2+1,y2) == 'M' && !map.is_v_wall(x2,y2) && numWalls)
andWall = 'D';
else if(y2 != 0 && map.get_cell(x2,y2-1) == 'M' && !map.is_h_wall(x2,y2-1) && numWalls)
andWall = 'L';
else if(y2 != 7 && map.get_cell(x2,y2+1) == 'M' && !map.is_h_wall(x2,y2) && numWalls)
andWall = 'R';
mv = Movement(x, y, x2, y2, andWall, false);
return mv;
}
// if distance from monster will be 2
else if(dm == 2){
int maxi = 0;
for(int i = 0; i < 5; i++)
for(int p = 0; p < 2; p++){
x2 = x+pts[i].X(), y2 = y+pts[i].Y();
Movement m = Movement(x, y, x2, y2, 'n', p);
temporary_map.set(map);
if(check_validity(!color+1, ind, m, temporary_map, numWalls, numWalls, false)){
change(m, temporary_map);
bfsMonster(x2, y2, temporary_map);
int newD = bfiM[X][Y];
if(newD == inf)
newD = 10 * (abs(x2-X) + abs(y2-Y));
if(newD > maxi){
maxi = newD;
mv = m;
}
}
}
if(maxi > 2 || (maxi >= 2 && mv.wall == 'n'))
return mv;
x2 = mv.x2;
y2 = mv.y2;
mv = Movement(x, y, x, y, 'n', false);
if(x2 == X){
if(Y < y2 && !map.is_h_wall(x2,y2-1) && numWalls)
andWall = 'L';
else if(Y > y2 && !map.is_h_wall(x2,y2) && numWalls)
andWall = 'R';
else
andWall = 'n';
}
else if(y2 == Y){
if(X < x2 && !map.is_v_wall(x2-1,y2) && numWalls)
andWall = 'U';
else if(X > x2 && !map.is_v_wall(x2,y2) && numWalls)
andWall = 'D';
else
andWall = 'n';
}
else
andWall = 'n';
}
// if distance from monster will be 3
else if(dm == 3 && x == x2 && y == y2){
int maxi = 0;
for(int i = 0; i < 5; i++)
for(int p = 0; p < 2; p++){
x2 = x+pts[i].X(), y2 = y+pts[i].Y();
Movement m = Movement(x, y, x2, y2, 'n', p);
temporary_map.set(map);
if(check_validity(!color+1, ind, m, temporary_map, numWalls, numWalls, false)){
change(m, temporary_map);
bfsMonster(x2, y2, temporary_map);
int newD = bfiM[X][Y];
if(newD == inf)
newD = 10 * (abs(x2-X) + abs(y2-Y));
if(newD > maxi){
maxi = newD;
mv = m;
}
}
}
return mv;
}
// not moving or making any walls far from monster
else if(x == x2 && y == y2 && !andWall){
int minimumD = inf;
// go to the nearest star
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
if(map.get_cell(i,j) == 's'){
bfsStars(i, j, map);
if(bfiS[x][y] < minimumD){
minimumD = bfiS[x][y];
int minimum = inf;
Movement m;
for(int k = 0; k < 4; k++){
m = Movement(x, y, x+pts[k].X(), y+pts[k].Y(), 'n', false);
if(check_validity(!color+1, ind, m, map, numWalls, numWalls, 0) && bfiS[x+pts[k].X()][y+pts[k].Y()] < minimum){
minimum = bfiS[x+pts[k].X()][y+pts[k].Y()];
mv = m;
}
}
}
}
return mv;
}
if(gotStar)
return save;
mv = Movement(x, y, mv.x2, mv.y2, andWall, mv.pull);
return mv;
}
| true |
f350716dca3f46efa081de28e0c95ce583b55f46 | C++ | JohnMichaelTO/VehiclesLocation | /ClassExemplaire.cpp | UTF-8 | 711 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "ClassVehicule.h"
#include "ClassExemplaire.h"
using namespace std;
ClassExemplaire::ClassExemplaire()
{
}
ClassExemplaire::ClassExemplaire(unsigned int numero, ClassVehicule *vehicule, unsigned int Km, std::string couleur, bool disponible)
{
_numero = numero;
_vehicule = vehicule;
_Km = Km;
_couleur = couleur;
_disponible = disponible;
}
ClassExemplaire::~ClassExemplaire()
{
}
void ClassExemplaire::setExemplaire(unsigned int numero, ClassVehicule *vehicule, unsigned int Km, std::string couleur, bool disponible)
{
_numero = numero;
_vehicule = vehicule;
_Km = Km;
_couleur = couleur;
_disponible = disponible;
}
| true |
1282bab2228f2973694ab07b4c584c838e8ffcce | C++ | Lujie1996/Leetcode | /837. New 21 Game/837. New 21 Game/main.cpp | UTF-8 | 774 | 3.0625 | 3 | [] | no_license | //
// main.cpp
// 837. New 21 Game
//
// Created by Jie Lu on 2018/10/27.
// Copyright © 2018 Jie Lu. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
double new21Game(int N, int K, int W) {
if (K == 0) {
return 1.0;
}
vector<double> dp(N+1, 0);
dp[0] = 1.0;
double sum = 1.0;
for (int i = 1; i <= N; i++) {
dp[i] = sum / W;
if (i < K) {
sum += dp[i];
}
if (i - W >= 0 && i - W < K) {
sum -= dp[i-W];
}
}
double res = 0;
for (int i = K; i <= N; i++) {
res += dp[i];
}
return res;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| true |
fc98f74cfb349035dd1b49ea28ba84735554ee96 | C++ | eliberumen27/CSCI2270 | /Homework:Quizzes/Lab7Trees.cpp | UTF-8 | 2,769 | 3.796875 | 4 | [] | no_license | /*
Elijah Berumen
Lab 7
Instructor: Boese
*/
#include <iostream>
using namespace std;
struct Node
{
int key;
Node* left;
Node* right;
};
//function prototypes
Node* addNode(Node* root, int value);
void addHelper(Node* root, Node* newNode);
int getSize(Node* root);
int getMinValue(Node* root);
int getMaxDepth(Node* root);
void printTree(Node* root);
//main for testing functions
int main()
{
Node* root = nullptr;
int size, min, depth;
root = addNode(root, 8);
root = addNode(root, 0);
root = addNode(root, -12);
root = addNode(root, 15);
root = addNode(root, 8);
root = addNode(root, 6);
root = addNode(root, 2);
root = addNode(root, 1);
root = addNode(root, 1);
root = addNode(root, 17);
root = addNode(root, -600);
printTree(root);
size = getSize(root);
cout << "Size: " << size << endl;
depth = getMaxDepth(root);
cout << "Max depth: " << depth << endl;
min = getMinValue(root);
cout << "Minimum value: " << min << endl;
return 0;
}
//adds a node to the binary tree
Node* addNode(Node* root, int value)
{
Node* newNode = new Node;
newNode->key = value;
newNode->left = nullptr;
newNode->right = nullptr;
if(root == nullptr)
root = newNode;
else
addHelper(root, newNode);
return root;
}
//helper function to addNode
void addHelper(Node* root, Node* newNode)
{
if(newNode->key < root->key)
if(root->left != nullptr)
addHelper(root->left,newNode);
else
root->left = newNode;
else//newNode->key >= root->key
if(root->right != nullptr)
addHelper(root->right,newNode);
else
root->right = newNode;
}
//returns the number of nodes in the tree
int getSize(Node* root)
{
int size = 0;
if (root != nullptr)
{
if(root->left != nullptr)
size += getSize(root->left);
size++;
if(root->right != nullptr)
size += getSize(root->right);
}
return size;
}
//returns the minimum value in the binary tree
int getMinValue(Node* root)
{
//int temp; can use temp variable to return if desired
if(root != nullptr)
{
while(root->left != nullptr)
{
root = root->left;
}
return root->key;
}
return 0;
}
//returns maximum depth of the binary tree
int getMaxDepth(Node* root)
{
int depthLeft = 0;
int depthRight = 0;
if(root != nullptr)
{
if(root->left != nullptr)
depthLeft += getMaxDepth(root->left);
depthLeft++;
depthRight++;
if(root->right != nullptr)
depthRight += getMaxDepth(root->right);
}
if(depthLeft > depthRight)
return depthLeft;
else
return depthRight;
//return (depthLeft > depthRight ? depthLeft : depthRight);
}
void printTree(Node* root)
{
if(root != nullptr)
{
if(root->left != nullptr)
printTree(root->left);
cout << root->key << endl;
if(root->right != nullptr)
printTree(root->right);
}
else
cout << "Tree empty." << endl;
} | true |
36463643fc81632c4894ceeec13094ac03c3e066 | C++ | jinhoyoo/GameCodeTest | /GameCodeTest/AnimationPlaybackTest.cpp | UTF-8 | 2,360 | 3.125 | 3 | [] | no_license | //
// AnimationPlaybackTest.cpp
// GameCodeTest
//
// Created by Jinho Yoo on 10/13/14.
// Copyright (c) 2014 Jinho Yoo. All rights reserved.
//
#include <math.h>
#include "PingPongLoopingAnimationController.h"
#include "GameCodeException.h"
#include "gtest/gtest.h"
const float fDiff = 0.1;
TEST(PingPongLoopingAnimationController, normal){
//Set animation with 100.0sec.
const float maxFrame = 100.0;
const float deltaTimePerSec = 1.0;
PingPongLoopingAnimationController controller(maxFrame);
EXPECT_FLOAT_EQ(controller.GetTime(), 0.0);
//Forward playing of animation.
for ( float frameSecond = deltaTimePerSec; frameSecond<= maxFrame ;
frameSecond +=deltaTimePerSec ) {
controller.Update(frameSecond);
EXPECT_NE(controller.GetTime(), 0.0);
EXPECT_FLOAT_EQ(controller.GetTime(), frameSecond);
}
//Play more time: It should play animation reversly.
for ( float frameSecond = maxFrame+deltaTimePerSec; frameSecond<= 2*maxFrame ;
frameSecond +=deltaTimePerSec ) {
controller.Update(frameSecond);
if ( controller.GetTime() != 0.0 )
EXPECT_FLOAT_EQ(controller.GetTime(), maxFrame - (frameSecond - maxFrame) );
}
}
TEST(PingPongLoopingAnimationController, preciseDeltaFrameTime){
//Set animation with 300.0sec. => 100 Frame.
const float maxFrameSec = 300.0;
const float deltaTimePerSec = 0.0333; // 30 Frame per second.
PingPongLoopingAnimationController controller(maxFrameSec);
EXPECT_FLOAT_EQ(controller.GetTime(), 0.0);
//Forward playing of animation.
for ( float frameSecond = deltaTimePerSec; frameSecond<= maxFrameSec ;
frameSecond +=deltaTimePerSec ) {
controller.Update(frameSecond);
float diff = fabs(controller.GetTime() - frameSecond);
EXPECT_LE(diff, fDiff);
}
//Play more time: It should play animation reversly.
for ( float frameSecond = maxFrameSec+deltaTimePerSec; frameSecond<= 2*maxFrameSec ;
frameSecond +=deltaTimePerSec ) {
controller.Update(frameSecond);
if ( controller.GetTime() != 0.0 ){
float diff = fabs(controller.GetTime() -
( maxFrameSec - (frameSecond - maxFrameSec)) );
EXPECT_LE(diff, fDiff);
}
}
}
| true |
d5899e62f8821e4f7ca654820206d5f7173ebffa | C++ | jpeasgood/aalib | /headers/singleton.h | UTF-8 | 491 | 2.953125 | 3 | [] | no_license | #ifndef AA_SINGLETON_H
#define AA_SINGLETON_H
namespace aa
{
template<typename T>
class singleton
{
public:
static T *get_instance()
{
static T instance;
return &instance;
}
protected:
singleton() = default;
~singleton() = default;
private:
singleton(const singleton &other) = delete;
singleton(singleton &&other) = delete;
singleton &operator=(const singleton &other) = delete;
singleton &operator=(singleton &&other) = delete;
};
}
#endif
| true |
c05f08ad64fc18c1948cd1835332b4876eecf645 | C++ | pmichaeldev/Ray-Tracer | /Ray-Tracer/Ray-Tracer/Triangle.h | UTF-8 | 1,320 | 3.28125 | 3 | [] | no_license | /*
* TRIANGLE SHAPE THAT INHERITS FROM GEOMETRY
*/
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include "CommonIncludes.h"
#include "Geometry.h"
#include "Plane.h"
#include <vector>
class Triangle : public Geometry {
private:
vector<vec3> vertices; // The vertices that make up the triangle
Plane* plane; // A triangle also holds a plane since the 2D surface can be considered a plane
public:
// --- CONSTRUCTORS --- //
Triangle() : vertices(vector<vec3>()), Geometry() { } // Empty vertices & call base class to empty
Triangle(vec3 v1, vec3 v2, vec3 v3, vec3 ambient, vec3 diffuse, vec3 specular, float alpha);
~Triangle(); // Destructor
// --- SETTER --- //
void setVertices(vector<vec3> vertices);
void setPlane(Plane* plane);
// --- GETTER --- //
vector<vec3> getVertices() const;
Plane* getPlane();
// --- HELPERS --- //
vec3 getVertex(int index); // Returns a vec3 vertex based on passed index
void setVertex(int index, vec3 vertex); // Sets a vertex to replace one based on index
virtual pair<bool, float> intersection(Rays ray); // The triangle's intersection case
pair<vector<vec2>, vec2> projection(vec3 &intersect_point); // A projection of the triangle in 2D
float area(vec2 p1, vec2 p2, vec2 p3);
virtual vec3 phong(vec3 q, Lights* light);
static const int TRIANGLE_EDGES = 3;
};
#endif | true |
a94a6cd0fe3fe986e0aa08fabbd8bcfdd1e71d36 | C++ | Code-Cube-NITP/Competitive-Programming | /monis_code.cpp | UTF-8 | 4,150 | 2.515625 | 3 | [] | no_license | // g++ monis_code.cpp -o monis_code && ./monis_code
/* ....!!!JAI SAI RAM!!!.... */
/* Writing Segment tree god support me*/
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll prime[1000001];
void seive()
{
ll i,j,k,l,m,n,o,p;
for(i=1;i<=1000000;i++)
prime[i]=1;
for(i=1;i<=1000000;i++)
{
if(prime[i]==1)
{
for(j=2*i;j<=1000000;j+=i)
{
if(prime[j]==1)
prime[j]=i;
}
prime[i]=i;
}
}
prime[0]=prime[1]=0;
}
vector<ll> prime_factors(ll n)
{
vector<ll> v(101,0);
while(n!=1)
{
ll k=prime[n];
ll s=0;
while(n%k==0)
{
n=n/k;
s++;
}
v[k]+=s;
}
return v;
}
vector<ll> segtree[900000];
vector<ll> temp(101,0);
vector<ll> build(ll idx,ll start,ll end,ll a[])
{
if(start>end)
return temp;
if(start==end)
{
segtree[idx]=prime_factors(a[start]);
return segtree[idx];
}
vector<ll> x(101,0);
vector<ll> y(101,0);
vector<ll> z(101,0);
ll mid=(start+end)/2;
x=build(2*idx+1,start,mid,a);
y=build(2*idx+2,mid+1,end,a);
for(ll i=0;i<=100;i++)
{
z[i]=x[i]+y[i];
}
//now calling on two separate nodes.
segtree[idx]=z;
return segtree[idx] ;
}
vector<ll> query(ll idx,ll start,ll end,ll l,ll r)
{
//no overlap then return temporary vector.
if(r<start||l>end)
return temp;
//complete overlap.
if(start>=l&&end<=r)
{
return segtree[idx];
}
//partial overlap then call both the childs.
vector<ll> x(101,0);
vector<ll> y(101,0);
vector<ll> z(101,0);
ll mid=(start+end)/2;
x=query(2*idx+1,start,mid,l,r);
y=query(2*idx+2,mid+1,end,l,r);
for(ll i=0;i<=100;i++)
{
z[i]=x[i]+y[i];
}
return z;
}
vector<ll> update(ll idx,ll start,ll end,ll index,vector<ll> val)
{
if(start>end||start>index||end<index)
{
return temp;
}
if(index>=start&&index<=end)
{
for(ll i=0;i<=100;i++)
{
segtree[idx][i]+=val[i];
}
}
if(start<end)
{
ll mid=(start+end)/2;
update(2*idx+1,start,mid,index,val);
update(2*idx+2,mid+1,end,index,val);
}
return segtree[idx];
}
// Hence now update , query and build all three parts are over.
int main()
{
seive();
ios_base::sync_with_stdio(false);
cin.tie(0);
ll n,start,end,a[100000],i,j,k,l,m,o,p,q,r,s,t;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
vector<ll> init=build(1,0,n-1,a);
/*for(i=1;i<=10;i++)
{
cout<<init[i]<<" ";
}*/
// Use of segment tree with number theory and maths
//cool problem .
cin>>q;
while(q--)
{
cin>>o;
// o for type of query. 1 for normal query over a range and 2 for updating an index i in the original array that is multiply the given index with value val;
if(o==1)
{
cin>>l>>r;
vector<ll> ans=query(1,0,n-1,l-1,r-1);
ll flag=1;
for(i=0;i<=100;i++)
{
if(ans[i]%2==1)
{
flag=0;
break;
}
}
//cout<<endl;
if(flag)
{
cout<<"YES\n";
}
else
{
cout<<"NO\n";
}
}
else
{
ll index,val;
cin>>index>>val;
vector<ll> xx=prime_factors(val);
update(1,0,n-1,index-1,xx);
/* for(i=1;i<=10;i++)
{
// cout<<segtree[1][i]<<" ";
}*/
}
}
return 0;
} | true |
2611c976a6850a3b71fd39987c208ff5c586672a | C++ | tbhova/YSU-Micromouse-SAC-2017 | /src/src/motor.cpp | UTF-8 | 702 | 3.21875 | 3 | [] | no_license | #include "motors.h"
Motors::Motor::Motor(const int forward, const int reverse, const int speed) {
forwardPin = forward;
reversePin = reverse;
speedPin = speed;
}
void Motors::Motor::coast() {
digitalWriteFast(forwardPin, HIGH);
digitalWriteFast(reversePin, HIGH);
}
void Motors::Motor::brake() {
digitalWriteFast(forwardPin, LOW);
digitalWriteFast(reversePin, LOW);
}
void Motors::Motor::setSpeed(short int speed) {
if (speed < 0) {
digitalWriteFast(reversePin, HIGH);
digitalWriteFast(forwardPin, LOW);
} else {
digitalWriteFast(reversePin, LOW);
digitalWriteFast(forwardPin, HIGH);
}
analogWrite(speedPin, abs(speed));
}
| true |
696ff5032838472ba7445250d288dc6ca6d63e45 | C++ | AutumnKite/Codes | /Codeforces/1728E Red-Black Pepper/std.cpp | UTF-8 | 1,277 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
int exgcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1, y = 0;
return a;
}
int g = exgcd(b, a % b, y, x);
y -= a / b * x;
return g;
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int n;
std::cin >> n;
std::vector<int> w(n);
long long sum = 0;
for (int i = 0; i < n; ++i) {
int a, b;
std::cin >> a >> b;
sum += a;
w[i] = b - a;
}
std::sort(w.begin(), w.end(), std::greater<int>());
std::vector<long long> pre(n + 1);
for (int i = 0; i < n; ++i) {
pre[i + 1] = pre[i] + w[i];
}
int q;
std::cin >> q;
while (q--) {
int a, b;
std::cin >> a >> b;
int x, y;
int g = exgcd(a, b, x, y);
if (n % g != 0) {
std::cout << -1 << "\n";
continue;
}
a /= g, b /= g;
x = (1ll * x * (n / g) % b + b) % b;
y = (n / g - 1ll * a * x) / b;
if (y < 0) {
std::cout << -1 << "\n";
continue;
}
int l = 0, r = y / a + 1;
auto calc = [&](int t) {
return pre[b * g * (y - a * t)];
};
while (l + 1 < r) {
int mid = (l + r) >> 1;
if (calc(mid - 1) < calc(mid)) {
l = mid;
} else {
r = mid;
}
}
std::cout << sum + calc(l) << "\n";
}
}
| true |
dab2512a65aa4268b6302bc4713241e9fb9eccd3 | C++ | Shobhit130/OOPS | /multipath.cpp | UTF-8 | 2,254 | 3.375 | 3 | [] | no_license | // #include <iostream>
// using namespace std;
// class person
// {
// public:
// char name[100];
// int code;
// void input()
// {
// cout<<"\nEnter the name of the person : ";
// cin>>name;
// cout<<endl<<"Enter the code of the person : ";
// cin>>code;
// }
// void display()
// {
// cout<<endl<<"Name of the person : "<<name;
// cout<<endl<<"Code of the person : "<<code;
// }
// };
// class account:virtual public person
// {
// public:
// float pay;
// void getpay()
// {
// cout<<endl<<"Enter the pay : ";
// cin>>pay;
// }
// void display()
// {
// cout<<endl<<"Pay : "<<pay;
// }
// };
// class admin: virtual public person
// {
// public:
// int experience;
// void getexp()
// {
// cout<<endl<<"Enter the experience : ";
// cin>>experience;
// }
// void display()
// {
// cout<<endl<<"Experience : "<<experience;
// }
// };
// class master:public account,public admin
// {
// public:
// char n[100];
// void gettotal()
// {
// cout<<endl<<"Enter the company name : ";
// cin>>n;
// }
// void display()
// {
// cout<<endl<<"Company name : "<<n;
// }
// };
// int main()
// {
// master m1;
// m1.input();
// m1.getpay();
// m1.getexp();
// m1.gettotal();
// m1.person::display();
// m1.account::display();
// m1.admin::display();
// m1.display();
// return 0;
// }
#include<iostream>
using namespace std;
class fruit
{
protected:
int a;
public:
void get()
{
cout<<"\n Enter a value:";
cin>>a;
}
};
class mango: virtual public fruit
{
protected:
int b;
public:
void get1() {
cout<<"\n Enter b value";
cin>>b; }};
class orange: virtual public fruit {
protected:
int c;
public:
void get2() {
cout<<"\n Enter c value:";
cin>>c; }};
class apple:public mango,public orange
{
public:
void display()
{
get();
get1();
get2();
cout<<"\n Multiplication value is "<<a*b*c;
}
};
int main() {
apple a;
a.display();
return 0;
} | true |
6c4d7095e9a3d9d734a75714a6a53eaef37af6c2 | C++ | adfilm2/algorithm | /전호설/Programmers/뉴스클러스터링.cpp | UTF-8 | 1,164 | 3.03125 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
string a;
string b;
int up;
int down;
map<string, int> Hash;
void strSet()
{
int len = a.size();
for (int i = 0; i < len - 1; i++)
{
string temp = "";
if (!(a[i] >= 'A'&&a[i] <= 'Z')) { temp = ""; continue; }
if (!(a[i + 1] >= 'A'&&a[i + 1] <= 'Z')) { temp = ""; continue; }
temp += a[i]; temp += a[i + 1];
cout << temp << " ";
Hash[temp]++;
down++;
}cout << endl;
len = b.size();
for (int i = 0; i < len - 1; i++)
{
string temp = "";
if (!(b[i] >= 'A'&&b[i] <= 'Z')) { temp = ""; continue; }
if (!(b[i + 1] >= 'A'&&b[i + 1] <= 'Z')) { temp = ""; continue; }
temp += b[i]; temp += b[i + 1];
cout << temp << " ";
if (Hash[temp] > 0)
{
up++; Hash[temp]--;
}
else
{
down++;
}
}
cout << endl;
cout << up << " " << down;
}
int solution(string str1, string str2) {
a = str1;
b = str2;
transform(a.begin(), a.end(), a.begin(), ::toupper);
transform(b.begin(), b.end(), b.begin(), ::toupper);
if (a == b) { return 65536; }
strSet();
float temp = (float)up / down;
float answer = temp * 65536;
return (int)answer;
} | true |
887971a2f06f5ce1dfed549b63b20df1471b90fe | C++ | Legend-sky/vscode | /hdu-1013.cpp | GB18030 | 345 | 2.875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
char s[1000];
int res,i;
while(cin >> s){ //cin.getline(s,1000)ᱨ
if(s[0] == '0'){
break;
}
res = 0;
for(i = 0; s[i] != '\0'; i++){
res += s[i] - '0';
if(res > 9){
res = res % 10 + res / 10;
}
}
cout << res << endl;
}
}
| true |
4c233cab5d34713068bae47b901133736c41465e | C++ | Aomandeyi/Cpp-0-1-Resource | /第5阶段-C++提高编程资料/提高编程能力资料/代码/第三阶段-录制代码/01 常用遍历算法/01 常用遍历算法/01 常用遍历算法_for_each.cpp | GB18030 | 666 | 3.375 | 3 | [] | no_license | //#include<iostream>
//using namespace std;
//#include<vector>
//#include<algorithm>
//
////ñ㷨 for_each
//
////ͨ
//void print01(int val)
//{
// cout << val << " ";
//}
//
////º
//class print02
//{
//public:
// void operator()(int val)
// {
// cout << val << " ";
// }
//
//};
//
//void test01()
//{
// vector<int>v;
// for (int i = 0; i < 10; i++)
// {
// v.push_back(i);
// }
//
// for_each(v.begin(), v.end(), print01);
// cout << endl;
//
// for_each(v.begin(), v.end(), print02());
// cout << endl;
//}
//
//int main() {
//
// test01();
//
// system("pause");
//
// return 0;
//} | true |
4bdea89131e0ac385953c58929fb5f6bffd89ca3 | C++ | phepthanthong/AP1 | /TD_Mihu/Semaine11/TP11.cpp | UTF-8 | 703 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void substituer(string & mot, char s2, int n) {
for (int i = 0 ; i < mot.length() ; i++)
if (i == n)
mot[i] = s2;
}
int main()
{
string mot, find;
char replace;
int n;
cout << "Entrez le mot : ";
cin >> mot;
cout << "Entrez le mot a trouver : ";
cin >> find;
n = mot.find(find);
if (n == string::npos)
cout << find << " pas trouve dans " << mot << endl;
else
cout << find << " trouve dans " << mot << " a la position " << n << endl;
cout << "Entrez le mot a remplacer : ";
cin >> replace;
substituer(mot, replace, n);
cout << mot << endl;
return EXIT_SUCCESS;
}
| true |
62f724a97edfb0b2ba9bd3e30c40ec679825cf19 | C++ | DAN-1984/Algoritmi_1 | /Индекс массы тела/Индекс массы тела.cpp | UTF-8 | 945 | 3.328125 | 3 | [] | no_license | // Индекс массы тела.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
// 1. Ввести вес и рост человека.Рассчитать и вывести индекс массы тела по формуле I = m / (h * h); где m - масса
// тела в килограммах, h - рост в метрах.
int main()
{
setlocale(LC_ALL, "Russian");
double m = 0.0f;
double h = 0.0f;
double I = 0.0f;
printf("Введите вес: ");
std::cin >> m; // Не получилось использовать scanf функция устарела.
printf("Введите рост: ");
std::cin >> h;
I = m / (h * h);
std::cout << "Индекс массы тела = " << I << std::endl;
std::cin.get();
std::cin.get();
return 0;
}
| true |
e5ace7bb51d30ff68e4b2224dc9490fb200afe6e | C++ | pravirtual/Leetcode | /nandincpp/Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.cpp | UTF-8 | 538 | 2.828125 | 3 | [] | no_license | class Solution {
public:
int maxNonOverlapping(vector<int>& a, int target)
{
set<int> s;
s.insert(0);
int sum = 0;
int ans = 0;
for(auto i : a)
{
sum += i;
if(s.count(sum - target))
{
ans++;
s.clear();
s.insert(0);
sum = 0;
}
else
s.insert(sum);
}
return ans;
}
}; | true |
17e0756b54aef60b3311ef18a572e60b3b15e080 | C++ | jiffybaba/Baba | /BABA/Cc/pointers3.cpp | UTF-8 | 221 | 2.9375 | 3 | [] | no_license | //Write a program to print the address of a variable whose value is input from user.
#include "iostream"
using namespace std;
int main()
{
int x;
int *ptr = &x;
cin >> *ptr;
cout << *ptr<<endl;
cout << ptr;
;
}
| true |
247688f6c7ba7e0364b980fdd3d9c0eb6576a5b6 | C++ | dgallitelli/ParadigmesProgramation-TPT | /ServerCPP/MultimediaObject.cpp | UTF-8 | 1,493 | 3.46875 | 3 | [] | no_license | #include "MultimediaObject.h"
/**
* @brief MultimediaObject::getName
* Getter method for the name variable
* @return the name of the object
*/
string MultimediaObject::getName() const
{
return name;
}
/**
* @brief MultimediaObject::setName
* Setter method for the name of the object
* @param _objectName - a string containing the new name of the object
*/
void MultimediaObject::setName(const string &_objectName)
{
name = _objectName;
}
/**
* @brief MultimediaObject::getPath
* Getter method for the path of the file
* @return the path of the file
*/
string MultimediaObject::getPath() const
{
return path;
}
/**
* @brief MultimediaObject::setPath
* Setter method for the path of the file
* @param _fileName - a string containing the full path to the file
*/
void MultimediaObject::setPath(const string &_fileName)
{
path = _fileName;
}
/**
* @brief MultimediaObject::print - Function to print on an outstream the values of the object
* Attaches on an output stream the values of the private variable name and path.
* @param outStream has to point to a valid output stream, eg cout or a stringstream
*/
void MultimediaObject::print(ostream &outStream)
{
if (outStream.rdbuf() == cout.rdbuf()){
// output on stdout
cout << "Objectname: " << name << " | Filename: " << path << endl;
} else {
// output on a different output stream
outStream << "Objectname: " << name << " | Filename: " << path << endl;
}
}
| true |
098c88da1a0fefe4ce0ca8c5fabc1184163f9182 | C++ | tku-iarc/wrs2020 | /disposing/librealsense/examples/cpp-headless.cpp | UTF-8 | 4,728 | 2.578125 | 3 | [
"Apache-2.0",
"Zlib",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LGPL-2.1-only",
"BSD-1-Clause",
"MIT"
] | permissive | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
///////////////////
// cpp-headless //
///////////////////
// This sample captures 30 frames and writes the last frame to disk.
// It can be useful for debugging an embedded system with no display.
#include <librealsense/rs.hpp>
#include <cstdio>
#include <stdint.h>
#include <vector>
#include <map>
#include <limits>
#include <iostream>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "third_party/stb_image_write.h"
void normalize_depth_to_rgb(uint8_t rgb_image[], const uint16_t depth_image[], int width, int height)
{
for (int i = 0; i < width * height; ++i)
{
if (auto d = depth_image[i])
{
uint8_t v = d * 255 / std::numeric_limits<uint16_t>::max();
rgb_image[i*3 + 0] = 255 - v;
rgb_image[i*3 + 1] = 255 - v;
rgb_image[i*3 + 2] = 255 - v;
}
else
{
rgb_image[i*3 + 0] = 0;
rgb_image[i*3 + 1] = 0;
rgb_image[i*3 + 2] = 0;
}
}
}
std::map<rs::stream,int> components_map =
{
{ rs::stream::depth, 3 }, // RGB
{ rs::stream::color, 3 },
{ rs::stream::infrared , 1 }, // Monochromatic
{ rs::stream::infrared2, 1 },
{ rs::stream::fisheye, 1 }
};
struct stream_record
{
stream_record(void): frame_data(nullptr) {};
stream_record(rs::stream value): stream(value), frame_data(nullptr) {};
~stream_record() { frame_data = nullptr;}
rs::stream stream;
rs::intrinsics intrinsics;
unsigned char * frame_data;
};
int main() try
{
rs::log_to_console(rs::log_severity::warn);
//rs::log_to_file(rs::log_severity::debug, "librealsense.log");
rs::context ctx;
printf("There are %d connected RealSense devices.\n", ctx.get_device_count());
if(ctx.get_device_count() == 0) return EXIT_FAILURE;
rs::device * dev = ctx.get_device(0);
printf("\nUsing device 0, an %s\n", dev->get_name());
printf(" Serial number: %s\n", dev->get_serial());
printf(" Firmware version: %s\n", dev->get_firmware_version());
std::vector<stream_record> supported_streams;
for (int i=(int)rs::capabilities::depth; i <=(int)rs::capabilities::fish_eye; i++)
if (dev->supports((rs::capabilities)i))
supported_streams.push_back(stream_record((rs::stream)i));
for (auto & stream_record : supported_streams)
dev->enable_stream(stream_record.stream, rs::preset::best_quality);
/* activate video streaming */
dev->start();
/* retrieve actual frame size for each enabled stream*/
for (auto & stream_record : supported_streams)
stream_record.intrinsics = dev->get_stream_intrinsics(stream_record.stream);
/* Capture 30 frames to give autoexposure, etc. a chance to settle */
for (int i = 0; i < 30; ++i) dev->wait_for_frames();
/* Retrieve data from all the enabled streams */
for (auto & stream_record : supported_streams)
stream_record.frame_data = const_cast<uint8_t *>((const uint8_t*)dev->get_frame_data(stream_record.stream));
/* Transform Depth range map into color map */
stream_record depth = supported_streams[(int)rs::stream::depth];
std::vector<uint8_t> coloredDepth(depth.intrinsics.width * depth.intrinsics.height * components_map[depth.stream]);
/* Encode depth data into color image */
normalize_depth_to_rgb(coloredDepth.data(), (const uint16_t *)depth.frame_data, depth.intrinsics.width, depth.intrinsics.height);
/* Update captured data */
supported_streams[(int)rs::stream::depth].frame_data = coloredDepth.data();
/* Store captured frames into current directory */
for (auto & captured : supported_streams)
{
std::stringstream ss;
ss << "cpp-headless-output-" << captured.stream << ".png";
std::cout << "Writing " << ss.str().data() << ", " << captured.intrinsics.width << " x " << captured.intrinsics.height << " pixels" << std::endl;
stbi_write_png(ss.str().data(),
captured.intrinsics.width,captured.intrinsics.height,
components_map[captured.stream],
captured.frame_data,
captured.intrinsics.width * components_map[captured.stream] );
}
printf("wrote frames to current working directory.\n");
return EXIT_SUCCESS;
}
catch(const rs::error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
| true |
3886e25ed90cc3e561b872d3808287d7c4b13c07 | C++ | OpticalTweezers/Optical_Tweezers | /mirror.cpp | UTF-8 | 2,201 | 2.5625 | 3 | [] | no_license | #include "mirror.h"
#include "Light.h"
#include <QTimer>
#include "game.h"
extern Game*game;
Mirror::Mirror(QLineF l){
setPixmap(QPixmap(":/images/mirror.jpg"));
setPos(l.p1());
this->mid_line = l;
this->mid_point = QPointF(0.5*(l.p1().x()+l.p2().x()),
0.5*(l.p1().y()+l.p2().y()));
this->setTransformOriginPoint(mid_point);
this->setRotation(l.angle());
qDebug()<<"mirror";
QTimer *timer =new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(reflect_light()));
timer->start(100);
}
void Mirror::reflect(Light *lt){
if(mid_line.intersect(lt->line(),nullptr)!=1){ //If the class definition declares a move constructor or move assignment operator,
qDebug()<<mid_line;
qDebug()<<"enter reflect";
return ;
} //the implicitly declared copy constructor is defined as deleted
else {
QPointF p=*lt->intersect_point(mid_line);
QLineF reflected_light_line(lt->line().p1(),p) ;
game->get_lasergenerator()->get_lg_light()->setLine(reflected_light_line);
double alpha = lt->line().angle();
double beta = mid_line.angle();
double ref_angle;
ref_angle = (2*beta-alpha)>360 ? (2*beta-alpha)-360:(2*beta-alpha);
mirror_reflected_light.append(new Light(p,ref_angle));
int index=mirror_reflected_light.size()-1;
scene()->addItem(mirror_reflected_light[index]);
}
}
void Mirror::reflect_light(){
if(game->get_lasergenerator()->get_lg_light()){
qDebug()<<"reflect?";
for(int i=0;i<mirror_reflected_light.size();i++){
scene()->removeItem(mirror_reflected_light[i]);
}
mirror_reflected_light.clear();
reflect(game->get_lasergenerator()->get_lg_light());
}
}
void Mirror::rotate(double rotate_angle){
this->setRotation(rotate_angle);
QLineF line1 = QLineF(mid_point,mid_line.p1());
line1.setAngle(line1.angle()+rotate_angle);
QLineF line2 = QLineF(mid_point,mid_line.p2());
line2.setAngle(line2.angle()+rotate_angle);
mid_line.setP1(line1.p2());
mid_line.setP2(line2.p2());
}
| true |
efedf12201111fb03c4a634c081e818980a97952 | C++ | yuchaozh/Cracking-The-Coding-Interview | /Chapter 2/2.3/2.3.cpp | UTF-8 | 1,896 | 4.25 | 4 | [] | no_license | /*Question:
*Implement an algorithm to delete a node in the middle of a
*single linked list, given only access to that node.
*EXAMPLE
*Innput:the node 'c' from the linked list a->b->c->d->e
*Result:nothing is returned, but the new linked list like
*a->b->d->e
*
*在删除指定节点的时候,不一定非要让前面那个节点的next指向删除节点的后一个节点
*可以让删除节点的后一个节点复制给删除节点,然后跳过后面节点,指向后面的后面节点
*Author: Yuchao Zhou
*/
#include <string>
#include <iostream>
#include <stdlib.h> //exit(0);
#include <cstdlib>
using namespace std;
class node
{
public:
string str;
node* next;
node()
{
str = "";
next = NULL;
}
};
void print(node* head)
{
while(head)
{
cout<<head->str<<" ";
head = head->next;
}
cout<<endl;
}
/** there is no need to implement a list class**/
node* initiate(string str)
{
node* head, *p;
for (int i = 0; i < str.length(); i++)
{
node* nd = new node();
nd->str = str[i];
nd->next = NULL;
if (i == 0)
{
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
void removenth(node* n)
{
if (n == NULL || n->next == NULL)
{
cout<<"failure"<<endl;
return;
}
node* p1 = n->next;
n->str = p1->str;
n->next = p1->next;
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout<<"Please input one series of number and n."<<endl;
exit(0);
}
string input = argv[1];
int length = input.length();
//argv's calss is char*, so need to change string into int
int nth = atoi(argv[2]);
if (nth > length)
{
cout<<"string's length is less than n"<<endl;
exit(0);
}
if (nth < 1)
{
cout<<"n is less than 1"<<endl;
exit(0);
}
node* head = initiate(input);
node* target = head;
for (int i = 1; i < nth; i++)
{
target = target->next;
}
removenth(target);
print(head);
return 0;
}
| true |
6ad5a37f1a80935380b58d54fa90afbfeba64b29 | C++ | BrainSpawnInfosphere/dfec-robot | /robot/TB6612FNG.h | UTF-8 | 2,281 | 3.1875 | 3 | [
"MIT"
] | permissive |
#ifndef __TB6612FNG_H__
#define __TB6612FNG_H__
// #include <Arduino.h>
#include <stdint.h>
/**
* ATmega328P, pwm works on pins 3, 5, 6, 9, 10, and 11 at 490/980Hz
*/
class MotorDriver {
public:
MotorDriver(void){
;
}
void init(int pwmA, int a0, int a1, int pwmB, int b0, int b1, int reset=-1){
pwmA_pin = pwmA;
pwmB_pin = pwmB;
A0_pin = a0;
A1_pin = a1;
B0_pin = b0;
B1_pin = b1;
reset_pin = reset;
pinMode(pwmA_pin, OUTPUT);
pinMode(pwmB_pin, OUTPUT);
pinMode(A0_pin, OUTPUT);
pinMode(A1_pin, OUTPUT);
pinMode(B0_pin, OUTPUT);
pinMode(B1_pin, OUTPUT);
if(reset_pin){
pinMode(reset_pin, OUTPUT);
digitalWrite(reset_pin, HIGH);
}
}
void begin(){
if(reset_pin){
digitalWrite(reset_pin, LOW);
delay(100);
digitalWrite(reset_pin, HIGH);
}
}
void motor0Forward(uint8_t speed){
// Serial.println("motor0Forward");
digitalWrite(A0_pin,LOW);
digitalWrite(A1_pin,HIGH);
analogWrite(pwmA_pin, speed);
}
void motor1Forward(uint8_t speed){
digitalWrite(B0_pin,LOW);
digitalWrite(B1_pin,HIGH);
analogWrite(pwmB_pin, speed);
}
void motor0Reverse(uint8_t speed){
digitalWrite(A0_pin,HIGH);
digitalWrite(A1_pin,LOW);
analogWrite(pwmA_pin, speed);
}
void motor1Reverse(uint8_t speed){
digitalWrite(B0_pin,HIGH);
digitalWrite(B1_pin,LOW);
analogWrite(pwmB_pin, speed);
}
/**
* Stop is defined as break. It locks both motors up.
*/
void stopBothMotors(){
stopMotor0();
stopMotor1();
}
void stopMotor0(){
digitalWrite(A0_pin,HIGH);
digitalWrite(A1_pin,HIGH);
}
void stopMotor1(){
digitalWrite(B0_pin,HIGH);
digitalWrite(B1_pin,HIGH);
}
/**
* Coast is defined as a high impedance state. No current runs through motors
* and they just spin.
*/
void coastBothMotors(){
motor0Coast();
motor1Coast();
}
void motor0Coast(){
digitalWrite(A0_pin,LOW);
digitalWrite(A1_pin,LOW);
analogWrite(pwmA_pin, 255);
}
void motor1Coast(){
digitalWrite(B0_pin,LOW);
digitalWrite(B1_pin,LOW);
analogWrite(pwmB_pin, 255);
}
protected:
int pwmA_pin, pwmB_pin, A0_pin, A1_pin, B0_pin, B1_pin, reset_pin;
};
#endif
| true |
d090e2ed4d1a260226c0caea392ec1f6581d11b0 | C++ | bitlucky/hackerrank | /jim-and-the-orders.cpp | UTF-8 | 923 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
// #include <fstream>
using namespace std;
int main() {
// fstream fin("/home/saubhik/problems/jim-and-the-orders-testcases/input/input01.txt");
// fstream fout("output.o");
int n, ti, di;
// fin >> n;
cin >> n;
vector<pair<int, int> > end_times;
for (int i = 1; i <= n; i++) {
// fin >> ti >> di;
cin >> ti >> di;
end_times.push_back(make_pair(ti + di, i));
}
sort(end_times.begin(), end_times.end());
vector<pair<int, int> >::iterator it;
for (it = end_times.begin(); it != end_times.end(); ++it) {
if (it == end_times.begin()) {
// fout << it->second;
cout << it->second;
}
else {
// fout << " " << it->second;
cout << " " << it->second;
}
}
// fin.close();
// fout.close();
}
| true |
9d9e359683518a775fb0a3c4ccb148590e5e238c | C++ | marccane/Projectes-CPP | /Exercicis EDA/ArbresBinaris Practiques/ArbreBinari.h | UTF-8 | 2,591 | 3.109375 | 3 | [] | no_license | //Marc Cané Salamià
//u1939666
//Pràctica 4
/*******************************************************************************
* Arbre Binari Caracters
*
* Conte totes les operacions, pero nomes cal implementar les necessaries
* Si no es demana el contrari, millor no implementar el destructor.
*
* 2008
* JSS - Actualitzats els metodes
*******************************************************************************/
#ifndef ARBRE_BINARI_CARACTER_H
#define ARBRE_BINARI_CARACTER_H
#include <cstdlib>
#include <string>
using namespace std;
struct node {
node();
node(node*,node*,int);
void node_preordre(string &s);
node* nodePoda();
~node();
node * fe, * fd;
int c;
};
class ArbreBinari{
// inv: arrel=NULL o arrel és un punter a una jerarquia disjunta de nodes
node * arrel;
node * iArbreBinari(char[], int &i);
// pre: cert; post: retorna cert si el caràcter es un numero
static inline bool esnumero(char);
// pre: cert; post: retorna l'enter que s'ha llegit del vector
static int Llegir_numeros(char*, int &i);
// pre: cert; post: retorna el numero de fulles de l'arbre
int nFulles() const;
// pre: cert; post: cert si l’arbre és buit
bool esBuit() const;
// pre: no buit; post: retorna el fill dret
ArbreBinari * FillDret() const;
// pre: no buit; post: retorna el fill esquerre
ArbreBinari * FillEsquerre() const;
// pre: cert; post: retorna l’element que hi ha a l’arrel
int contingut() const;
// pre: cert; post: fa un arbre amb els subarbres a i b
void arrelar(ArbreBinari & a, ArbreBinari & b, int c);
public:
//Constructors
// pre: -; post: crea un arbre buit
ArbreBinari();
ArbreBinari(node * a);
// pre: a<>NULL ^ b<>NULL; post: crea un arbre amb els parametres donats
ArbreBinari(ArbreBinari & a, ArbreBinari & b, int c);
ArbreBinari(char cadena[]);
// Pre: cadena conte el recorregut en preordre d'un arbre d'enters en el format vist a teoria
// Post: s'ha creat un arbre que correspon al recorregut en preordre que hi ha a cadena
ArbreBinari(string cadena);
// pre: cert; post: elimina la memòria que té reservada l’arbre
~ArbreBinari();
// Metodes per resoldre el problema plantejat
// Pre: --
// Post: diu si el nombre de fulles d'aquest arbre coincideix amb el valor del node arrel
bool teArrelFulles() const;
// Pre: --
// Post: s'han eliminat tots els nodes fulla d'aquest arbre
void podaFulles();
// Pre: --
// Post: retorna cadena amb el recorregut en preordre d'aquest arbre en el format vist a teoria o "<<arbre buit>>" si l'arbre es buit
string preOrdre() const;
};
#endif
| true |
60077c0ffcb985d09c69b9d7f57bebdb08b12309 | C++ | emollerstedt/arduino-halloween | /DigitalPin/Examples/RelayToggle/RelayToggle.ino | UTF-8 | 334 | 2.671875 | 3 | [] | no_license | #include <DigitalPin.h>
DigitalPin Relay1(10); // Instantiates a DigitalPin object called "Relay1" that uses pin10
DigitalPin Relay2(11);
void setup() {
Relay1.begin();
Relay2.begin();
}
void loop() {
Relay1.on();
delay(1000);
Relay1.off();
delay(1000);
Relay2.on();
delay(1000);
Relay2.off();
delay(1000);
}
| true |
5e6fd9babe7a8b16dbae839d0bd031c3cba116b3 | C++ | PierreINP/ProjetC | /ProjetC/Software/Install/Source/test.cpp | UTF-8 | 652 | 3 | 3 | [] | no_license | /*
This programm is here to perform some functions. It must identify the lexemes, compute them to validate their conformity and then give them a type.
Input : SourceFile.vhd
Output : Data structure
*/
#include"./../Header/Lexeur.h"
#include"./../Header/Lexeme.h"
#define path_size 100
using namespace std;
int main()
{
std::list<Lexeme> lexeme_list;
list<Lexeme>::iterator iter;
char fichier [path_size]= "/users/phelma/phelma2015/lamypi/ProjetC/SourceCode/test.vhdl";
lexeme_list = readSource(fichier);
//Test lecture lexeme dans liste
for(iter = lexeme_list.begin(); iter != lexeme_list.end(); iter ++)
{
cout << *iter << endl;
}
}
| true |
5359e386b18758dd8f66b9a6dd9f091091840258 | C++ | hubert-mazur/Cpp-2019-4th-sem- | /Lokaj/include/Pomieszczenie.h | UTF-8 | 873 | 3.25 | 3 | [] | no_license | //
// Created by hubert on 09.05.19.
//
#ifndef LAB08_POMIESZCZENIE_H
#define LAB08_POMIESZCZENIE_H
#include <string>
#include <iostream>
class Pomieszczenie
{
public:
explicit Pomieszczenie (std::string str) : name (str)
{
std::cout << "Tworze pomieszczenie: " << name << std::endl;
};
void zetrzyj_kurze () const
{
std::cout << "Scieram kurze w pomieszczeniu: " << name << std::endl;
}
void odkurz () const
{
std::cout << "Odkurzam w pomieszczeniu: " << name << std::endl;
}
void umyj_podloge () const
{
std::cout << "Myje podloge w pomieszczeniu: " << name << std::endl;
}
template<typename T>
void wstaw (const T &object)
{
std::cout << "Wstawiam " << object << " do pomieszczenia: " << name << std::endl;
}
const std::string &getName () const
{
return name;
}
protected:
std::string name;
};
#endif //LAB08_POMIESZCZENIE_H
| true |
3ebeb6f547d3b520d1a95e869bee535bd9176141 | C++ | anandman/ukf | /src/ukf.cpp | UTF-8 | 10,101 | 2.859375 | 3 | [] | no_license | #include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::IOFormat;
using std::vector;
#define PI 3.14159265358979323
#define PI2 (2.0 * PI)
/**
* Initializes Unscented Kalman filter
*/
UKF::UKF() {
// initially set to false, set to true in first call of ProcessMeasurement
is_initialized_ = false;
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
//time when the state is true, in us
time_us_ = 0;
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 1;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 1;
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
// State dimension
n_x_ = 5;
// Augmented state dimension
n_aug_ = 7;
// Sigma point spreading parameter
lambda_ = 3 - n_aug_;
// Weights of sigma points
weights_ = VectorXd(2 * n_aug_ + 1);
weights_.fill(0.5/(lambda_ + n_aug_));
weights_(0) = lambda_/(lambda_+n_aug_);
// initial state vector
// px, py, vel, yaw, yawd
x_ = VectorXd::Zero(n_x_);
// initial covariance matrix
P_ = MatrixXd::Identity(n_x_, n_x_);
// predicted sigma points matrix
Xsig_pred_ = MatrixXd::Zero(n_x_, 2 * n_aug_ + 1);
}
UKF::~UKF() = default;
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
/*****************************************************************************
* Initialization
****************************************************************************/
if (!is_initialized_) {
// first measurement
cout << "UKF: " << endl;
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
/**
Convert radar from polar to cartesian coordinates and initialize state.
*/
double rho = meas_package.raw_measurements_[0];
double phi = meas_package.raw_measurements_[1];
double rho_dot = meas_package.raw_measurements_[2];
x_ << cos(phi) * rho, sin(phi) * rho, sqrt(cos(phi) * rho_dot + sin(phi) * rho_dot), 0, 0;
} else if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
/**
Initialize the state with the initial location and zero velocity.
*/
x_ << meas_package.raw_measurements_[0], meas_package.raw_measurements_[1], 0, 0, 0;
}
time_us_ = meas_package.timestamp_;
// done initializing, no need to predict or update
is_initialized_ = true;
return;
}
// ignore LIDAR or RADAR measurements if specified
if (!use_laser_ && meas_package.sensor_type_ == MeasurementPackage::LASER) return;
if (!use_radar_ && meas_package.sensor_type_ == MeasurementPackage::RADAR) return;
/*****************************************************************************
* Prediction
****************************************************************************/
//compute the time elapsed between the current and previous measurements
double dt = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds
time_us_ = meas_package.timestamp_;
Prediction(dt);
/*****************************************************************************
* Update
****************************************************************************/
Update(meas_package);
// print the output
IOFormat xFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", ", ", "", "", "x_ = [", "]");
IOFormat pFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", ", ", "[", "]", "P_ = [", "]");
cout << x_.format(xFmt) << endl;
cout << P_.format(pFmt) << endl;
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
// augmented state mean vector
VectorXd x_aug_ = VectorXd::Zero(n_aug_);
x_aug_.head(n_x_)=x_;
// augmented state covariance matrix
MatrixXd P_aug_ = MatrixXd::Zero(n_aug_, n_aug_);
P_aug_.topLeftCorner(n_x_, n_x_) = P_;
P_aug_(5,5) = std_a_ * std_a_;
P_aug_(6,6) = std_yawdd_ * std_yawdd_;
MatrixXd sqrtP_aug_ = P_aug_.llt().matrixL();
// augmented sigma points matrix
MatrixXd Xsig_aug_ = MatrixXd::Zero(n_aug_, 2 * n_aug_ + 1);
Xsig_aug_.col(0) = x_aug_;
double ofs = sqrt(lambda_ + n_aug_);
for (int i=0; i < n_aug_; i++) {
Xsig_aug_.col(i+1) = x_aug_ + ofs * sqrtP_aug_.col(i);
Xsig_aug_.col(n_aug_+i+1) = x_aug_ - ofs * sqrtP_aug_.col(i);
}
// predict sigma points
Xsig_pred_.fill(0.0);
for (int i=0; i < Xsig_aug_.cols(); i++) {
//double px = Xsig_aug_(0,i);
//double py = Xsig_aug_(1,i);
double v = Xsig_aug_(2,i);
double yaw = Xsig_aug_(3,i);
double yaw_dot = Xsig_aug_(4,i);
double nu_a = Xsig_aug_(5,i);
double nu_yaw = Xsig_aug_(6,i);
// calculate prediction integral
VectorXd integral = VectorXd::Zero(n_x_);
// check for yaw_dot = 0 which implies car is moving in a straight line
if (fabs(yaw_dot) < 0.001) {
integral << v * cos(yaw) * delta_t,
v * sin(yaw) * delta_t,
0,
0, //yaw_dot * delta_t,
0;
}
else {
integral << v/yaw_dot * (sin(yaw + (yaw_dot*delta_t)) - sin(yaw)),
v/yaw_dot * (cos(yaw) - cos(yaw + (yaw_dot*delta_t))),
0,
yaw_dot * delta_t,
0;
}
// calculate noise influence on predicted state
VectorXd noise = VectorXd::Zero(n_x_);
noise << 0.5 * pow(delta_t,2) * cos(yaw) * nu_a,
0.5 * pow(delta_t,2) * sin(yaw) * nu_a,
delta_t * nu_a,
0.5 * pow(delta_t,2) * nu_yaw,
delta_t * nu_yaw;
Xsig_pred_.col(i) = Xsig_aug_.col(i).head(5) + integral + noise;
}
// mean of predicted sigma points
x_.fill(0.0);
P_.fill(0.0);
x_ = Xsig_pred_ * weights_;
for (int i=0; i < Xsig_pred_.cols(); i++) {
VectorXd x_diff = Xsig_pred_.col(i) - x_;
while (x_diff(3) < -PI) x_diff(3) += PI2;
while (x_diff(3) > PI) x_diff(3) -= PI2;
P_ += weights_(i) * x_diff * x_diff.transpose();
}
}
/**
* Updates the state and the state covariance matrix using a radar or laser measurement
* @param n_z measurement dimensions (RADAR[0:2] = rho, phi, rho_dot; LIDAR[0:1] = px, py)
* @param meas_package The measurement at k+1
*/
void UKF::Update(MeasurementPackage meas_package) {
int n_z;
bool is_radar;
// figure out whether we're operating on laser or radar
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
// RADAR updates
n_z = 3;
is_radar = true;
} else {
// LIDAR updates
n_z = 2;
is_radar = false;
}
//transform sigma points into measurement space
MatrixXd Zsig = MatrixXd::Zero(n_z, 2 * n_aug_ + 1);
for (int i = 0; i < Xsig_pred_.cols(); i++) {
// extract values
double p_x = Xsig_pred_(0,i);
double p_y = Xsig_pred_(1,i);
if (is_radar) {
double v = Xsig_pred_(2,i);
double yaw = Xsig_pred_(3,i);
double v1 = v * cos(yaw);
double v2 = v * sin(yaw);
// radar measurement model
Zsig(0,i) = sqrt(p_x*p_x + p_y*p_y); //rho
Zsig(1,i) = atan2(p_y,p_x); //phi
Zsig(2,i) = (p_x*v1 + p_y*v2 ) / sqrt(p_x*p_x + p_y*p_y); //rho_dot
} else {
// laser measurement model
Zsig(0,i) = p_x;
Zsig(1,i) = p_y;
}
}
// calculate predicted state mean in measurement space
VectorXd z_ = Zsig * weights_;
// normalize angles
if (is_radar) {
while (z_(1) > PI) z_(1) -= 2. * PI;
while (z_(1) < -PI) z_(1) += 2. * PI;
}
// calculate predicted state covariance in measurement space
MatrixXd S_ = MatrixXd::Zero(n_z, n_z);
for (int i=0; i < Zsig.cols(); i++) {
VectorXd z_diff = Zsig.col(i) - z_;
//normalize angles
if (is_radar) {
while (z_diff(1) < -PI) z_diff(1) += PI2;
while (z_diff(1) > PI) z_diff(1) -= PI2;
}
S_ += weights_(i) * z_diff * z_diff.transpose();
}
// add measurement noise covariance matrix
MatrixXd R_ = MatrixXd::Zero(n_z, n_z);
if (is_radar) {
R_(0,0) = std_radr_ * std_radr_;
R_(1,1) = std_radphi_ * std_radphi_;
R_(2,2) = std_radrd_ * std_radrd_;
} else {
R_(0,0) = std_laspx_ * std_laspx_;
R_(1,1) = std_laspy_ * std_laspy_;
}
S_ += R_;
// calculate cross-correlation between state and measurement spaces
MatrixXd Tc = MatrixXd::Zero(n_x_, n_z);
for (int i=0; i < Zsig.cols(); i++) {
VectorXd x_diff = Xsig_pred_.col(i) - x_;
//normalize angles
while (x_diff(3) < -PI) x_diff(3) += PI2;
while (x_diff(3) > PI) x_diff(3) -= PI2;
VectorXd z_diff = Zsig.col(i) - z_;
if (is_radar) {
//normalize angles
while (z_diff(1) < -PI) z_diff(1) += 2 * PI;
while (z_diff(1) > PI) z_diff(1) -= 2 * PI;
}
Tc += weights_(i) * x_diff * z_diff.transpose();
}
// calculate Kalman gain
MatrixXd K = Tc * S_.inverse();
// calculate error
VectorXd z = meas_package.raw_measurements_;
VectorXd z_diff = z - z_;
if(is_radar) {
while (z_diff(1) < -PI) z_diff(1) += PI2;
while (z_diff(1) > PI) z_diff(1) -= PI2;
}
// update state
x_ += K * z_diff;
P_ -= K * S_ * K.transpose();
// normalize angles
while (x_(3)> PI) x_(3)-=PI2;
while (x_(3)< -PI) x_(3)+=PI2;
// calculate NIS
double nis = z_diff.transpose() * S_.inverse() * z_diff;
cout << "NIS = " << nis << endl;
} | true |
454123d23712011f1eebe58cf72ea93f6e5c3ae6 | C++ | chickenfingerwu/Chess-SFML | /Game/include/GUI.h | UTF-8 | 954 | 2.734375 | 3 | [] | no_license | #pragma once
#include <SFML/Graphics.hpp>
#include "Game.h"
/*GUI class to handle all the graphics and inputs from mouse stuff*/
class GUI
{
public:
Game ChessGame;
sf::Event event;
sf::RenderWindow window;
sf::Texture PieceTexture[2][6];
sf::RectangleShape ChessBoard[8][8];
sf::Sprite PieceSprite[4][8];
//Sprite state: Decide which piece sprite should be drawn to screen
bool ToDrawOrNotToDraw[4][8];
GUI();
~GUI();
//change a square's color to red to indicate the player's chosen piece
void fillSquareRed(sf::Color &pre_square_color,int &x,int &y);
void update();
void selectPiece(sf::Event& event,int& selected_posX,int& selected_posY, int& sprite_posX,int& sprite_posY, bool &selected);
bool IsSpritePressed(sf::Sprite &sprite,sf::RenderWindow &window);
void moveSpriteToMouse(sf::Sprite &sprite,sf::Vector2i &mouse_pos);
void LoadGameTexture();
};
| true |
68f97ae2fb979a1b8115a14752d2f997accb9ad8 | C++ | LinggYuu/shua-ti | /MINGW&c++/shuangzhizhen.cpp | UTF-8 | 1,626 | 3.109375 | 3 | [] | no_license | // //模板
// for(i=0,j=0;i<n;i++)
// {
// while(j<i&&check(i,j))
// j++;
// //每道题具体逻辑
// }
// // 可用于优化,朴素算法优化到O(n)
// // 输出单词
// // abc def ghi将其输出每个一行
// #include<iostream>
// #include<string.h>
// using namespace std;
// int main()
// {
// char str[1000];
// gets(str);
// int n=strlen(str);
// for(int i=0;i<n;i++)
// {
// int j=i;
// while(j<n&&str[j]!=' ')
// j++;
// //该题具体逻辑
// for(int k=i;k<j;k++)
// cout<<str[i];
// cout<<endl;
// i=j;
// }
// return 0;
// }
// //最长连续无重复子序列
// for(int i=0;i<n;i++)
// {
// for(int j=0;j<=i;j++)
// {
// if(check(j,i))
// {
// res=max(res, i-j+1);
// }
// }
// }//朴素
// //1 2 2 3 5
// //2 3 5
// for(int i=0;j=0;i<n;i++)
// {
// while(j<=i&&check(j,i))
// //j到i有重复元素;a[i]!=a[j]
// j++;
// res=max(res,i-j+1);
// }
// // 开数组动态记录数出现次数
// // S[N]
// // S[a[i]]++
// #include<iostream>
// using namespace std;
// const int N=100010;
// int n;
// int a[N],s[N];//s计数器
// int main()
// {
// cin>>n;
// for(int i=0;i<n;i++)
// cin>>a[i];
// int res=0;
// for(int i=0,j=0;i<n;i++)
// {
// s[a[i]]++;
// while(j<=i&&s[a[i]]>1)
// {
// s[a[j]]--;
// j++;
// }
// res=max(res,i-j+1);
// }
// cout<<res<<endl;
// }
| true |
38f4f2c0028be140113794880c05aa418f330d66 | C++ | vaibhavjain2391/Spoj-Practise | /pebble_solver.cpp | UTF-8 | 1,039 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
int findRes(char *str, int len);
int main()
{
int count,len,result,num;
char str[1000000];
count=1;
//while(~scanf("%s",str))
while(cin>>str)
{
num=1;
result=0;
len = strlen(str);
//result = findRes(str, len);
for(int i=0;i<len;i++)
{
if(str[i]=='0' + num)
{
result++;
if(num==0)
num=1;
else
num=0;
}
}
printf("Game #%d: %d\n",count,result);
count++;
}
return 0;
}
int findRes(char *str, int len)
{
int count = 0,num=1;
for(int i=0;i<len;i++)
{
if(str[i]=='0' + num)
{
count++;
if(num==0)
num=1;
else
num=0;
}
}
return count;
}
//Though this method is also O(n), it gives TLE.
/*void findRes(char *str, int len)
{
bool flip = false;
int count = 0;
for(int i=0;i<len;i++)
{
if(!flip)
{
if(str[i]=='1')
{
flip=true;
count++;
}
}
else
{
if(str[i]=='0')
{
flip=false;
count++;
}
}
}
printf("%d\n",count);
}*/
| true |
d3687f50172c2693b3abf2a67ec06645ace41596 | C++ | Strel04ka/WORKs31 | /WORK31/WORK31.cpp | WINDOWS-1251 | 805 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x;
double y;
double A;
double B;
cout << "x = ";
cin >> x;
A = 8.1 + pow(x, 3);
//1
if (x < -3.5)
{
B = 1 - pow(x, -5);
}
if (-3.5 <= x && x < 1)
{
B = 1 / tan(x + 1);
}
if (1 <= x)
{
B = atan(2 * x) - log10(x / 2);
}
y = A + B;
cout << "1) y = " << y << endl;
//2
if (x < -3.5)
{
B = 1 - pow(x, 5);
}
else
{
if (-3.5 <= x && x < 1)
{
B = 1 / tan(x + 1);
}
else if (1 <= x) //else
{ //{
B = atan(2 * x) - log10(x / 2); // B = atan(2 * x) - log10(x / 2);
} //}
}
y = A + B;
cout << "2) y = " << y;
cin.get();
return 0;
}
| true |
0369ecd71e40d61f6b6030fc9695b682239851da | C++ | dSyncro/Honey | /Projects/Honey/Honey/Renderer/Image.h | UTF-8 | 2,289 | 3.109375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <cstddef>
#include <Honey/Math/Math.h>
namespace Honey {
/**
* @brief Image representation.
*/
class Image {
public:
/**
* @brief Construct Image from its components.
* @param width Image width.
* @param height Image height.
* @param channels Image channels.
*/
Image(UInt width, UInt height, UInt channels = 3);
~Image();
/**
* @brief Set new data to image.
* @param data New data.
* @param size Size of data in byte.
* @param offset Offset from beginning.
*/
void setData(Byte* data, UInt size, UInt offset = 0);
/**
* @brief Create a new Image.
* @param width Image width.
* @param height Image height.
* @param channels Image channels.
* @return A new memory managed Image.
*/
static Reference<Image> create(UInt width, UInt height, UInt channels = 3);
/**
* @brief Create a new Image from file.
* @param path File path.
* @return A new memory managed file loaded from disk.
*/
static Reference<Image> createFromFile(const std::string& path);
/**
* @brief Get underlying bitmap.
* @return Raw bitmap.
*/
Byte* getRawBitmap() const { return _bitmap; }
/**
* @brief Get image width.
* @return The width.
*/
UInt getWidth() const { return _width; }
/**
* @brief Get image height.
* @return The height.
*/
UInt getHeight() const { return _height; }
/**
* @brief Get image channels.
* @return The channels.
*/
UInt getChannels() const { return _channels; }
/**
* @brief Get image pixel count.
* @return Pixel count.
*/
UInt getPixelCount() const { return _width * _height; }
/**
* @brief Get image size in byte.
* @return Size in bytes.
*/
UInt getSizeInBytes() const { return getPixelCount() * _channels; }
/**
* @brief Get image stride.
* @return Stride.
*/
UInt getStride() const { return _width * _channels; }
/**
* @brief Get image size.
* @return Size.
*/
Math::Size getSize() const { return Math::Size(_width, _height); }
/**
* @brief Write image to a PNG file.
* @param filename Image file path.
*/
void writeToPNG(const std::string& filename) const;
private:
void free();
Byte* _bitmap;
UInt _width;
UInt _height;
UInt _channels;
};
}
| true |
d8194dc1f9ededbef226363d33fd9e7bd9e87592 | C++ | RayquazaW/cpp_learning | /chapter2/practice5.cpp | UTF-8 | 378 | 3.515625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
double transform(double cel);
int main()
{
double cel, fah;
cout << "Please enter a Celsius value: ";
cin >> cel;
fah = transform(cel);
cout << cel << " degrees Celsuis is " << fah << " degrees Fahrenheit.";
cin.get();
cin.get();
return 0;
}
double transform(double cel)
{
return cel * 1.8 + 32.0;
} | true |
fe11bc4500f3a9b37c3bed3a70ff7b880dea3298 | C++ | Xiaoyancg/CS307team12 | /editor/src/windows/MapWindow.cpp | UTF-8 | 7,877 | 2.734375 | 3 | [] | no_license | #include "windows/MapWindow.h"
#include "windows/MapEditor.h"
ImVec2 prevClick(0, 0);
// handleClick will return a pointer to a Tile on the current Map based on whether
// a click has occurred, or nullptr
Core::Tile *MapWindow::handleClick()
{
// Calculate the min/max coords of the MapView window
// min/max are used to check for click detection within the coordinates of the window
ImVec2 min = ImGui::GetWindowPos();
ImVec2 max = min;
min.y += ImGui::GetWindowContentRegionMin().y; // Get y value of window past the title bar
max.x += ImGui::GetWindowContentRegionMax().x; // Get max x value of MapView
max.y += ImGui::GetWindowContentRegionMax().y; // Get max y value of MapView
// Get width/height and the center coordinates of the ImGui drawable space.
// Clicks are sent to the core based on their distance from the center.
ImVec2 canvasDimensions(ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x,
ImGui::GetWindowContentRegionMax().y - ImGui::GetWindowContentRegionMin().y);
glm::ivec2 center(canvasDimensions.x / 2, canvasDimensions.y / 2);
//////////// Mouse handling within the MapView window ////////////
// If mouse left is currently pressed and the MapView is focused
if (ImGui::IsMouseClicked(ImGuiMouseButton_Left))
{
ImGui::GetIO();
}
if (ImGui::IsMouseReleased(ImGuiMouseButton_Left))
{
lastTile = nullptr;
}
if (ImGui::IsMouseDown(ImGuiMouseButton_Left) && ImGui::IsWindowFocused()) {
// If click is within the coordinates of the MapView window (in global coords based on top right corner)
ImVec2 click_pos = ImGui::GetMousePos();
if ((min.x < click_pos.x && click_pos.x < max.x) && (min.y < click_pos.y && click_pos.y < max.y))
{
// Get x and y of the click based on their distance from the center of the MapView screen.
// This lets MapPage::getTileFromClick() understand the click as a point in its coordinate system without orthographic projection / zoom.
// The orthographic projection is calculated on the click later in MapPage::getTileFromClick() based on the current Map's Camera.
glm::vec2 windowClick = glm::vec2(
(click_pos.x - min.x) / canvasDimensions.x,
1 - (click_pos.y - min.y) / canvasDimensions.y
);
// NOTE: Right now the code just gets the clicked Tile and sets its sprite ID to 1. It should probably do something else...
Core::Tile *clicked_tile = editor->getCurrentMap()->getTileFromClick(cam, windowClick.x, windowClick.y);
if (clicked_tile && clicked_tile != lastTile)
{
MapEditor* mapEditor = static_cast<MapEditor*>(editor->getWindowList()[MAPEDITOR]);
switch (mapEditor->getEditMode()) {
case EditMode::Collision:
clicked_tile->setSolid(!clicked_tile->isSolid());
break;
case EditMode::Sprite:
clicked_tile->setSpriteID(mapEditor->getSelectedSpriteID());
break;
}
lastTile = clicked_tile;
return clicked_tile;
}
}
}
// Handle mouse wheel zoom
if (ImGui::GetIO().MouseWheel != 0.0f)
{
float wheel = ImGui::GetIO().MouseWheel;
// If click is within the coordinates of the MapView window (in global coords based on top right corner)
ImVec2 click_pos = ImGui::GetMousePos();
if ((min.x < click_pos.x && click_pos.x < max.x) && (min.y < click_pos.y && click_pos.y < max.y))
{
// The click is valid within the MapView window.
if (wheel > 0)
{
cam->setZoom(cam->getZoom() + 0.05f); // Zoom in
}
else if (wheel < 0)
{
cam->setZoom(cam->getZoom() - 0.05f); // Zoom out
}
}
}
// Handle middle-click drag
if (ImGui::IsMouseDown(ImGuiMouseButton_Middle) && ImGui::IsMouseDragging(ImGuiMouseButton_Middle) && ImGui::IsWindowFocused())
{
// If click is within the coordinates of the MapView window (in global coords based on top right corner)
ImVec2 click_pos = ImGui::GetMousePos();
// The click is valid within the MapView window.
// Move the position to the offset of the drag. Using ImGui::GetMouseDrag messed things up here, so I'm doing it this way
cam->offsetPosition(glm::vec2(-(click_pos.x - prevClick.x), click_pos.y - prevClick.y));
// Set previous click position to calculate next drag
prevClick.x = click_pos.x;
prevClick.y = click_pos.y;
}
// Handle initial right-click
if (ImGui::IsMouseDown(ImGuiMouseButton_Middle) && ImGui::IsWindowFocused())
{
ImVec2 click_pos = ImGui::GetMousePos();
// Set prevClick in case of dragging
if ((min.x < click_pos.x && click_pos.x < max.x) && (min.y < click_pos.y && click_pos.y < max.y))
{
prevClick.x = click_pos.x;
prevClick.y = click_pos.y;
}
}
return nullptr;
}
void MapWindow::draw()
{
if (visible)
{
// possibly implement a new function here for readability purposes
if (editor->getCurrentMap() != nullptr)
{
Core::Map *currMap = editor->getCurrentMap();
// set the windows default size
ImGui::SetNextWindowSize(size, ImGuiCond_FirstUseEver);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
// the game view window itself
ImGui::Begin("Map View", &visible);
updateWindowFocus();
// Get size of drawable space on the window, instead of the entire size of the window
ImVec2 canvas_size = ImGui::GetContentRegionAvail();
glm::ivec2 icanvas_size = glm::ivec2((int)canvas_size.x, (int)canvas_size.y);
glm::ivec2 dims = currMap->getDimensions();
int tileSize = currMap->getTileSize();
int mapWidth = (dims.x + 1) * tileSize;
int mapHeight = (dims.y + 1) * tileSize;
// set texture size to map dimensions so that we don't get quality loss
// --initially I thought about only rendering the visible part of the map
// --but that won't work without a shader rework
glBindTexture(GL_TEXTURE_2D, mMapTexCBO);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, icanvas_size.x, icanvas_size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
cam->setDimensions(icanvas_size.x, icanvas_size.y);
//cam->setPosition(mapWidth/2.0f, mapHeight/2.0f);
cam->use();
// render the map
glBindFramebuffer(GL_FRAMEBUFFER, mMapFBO);
// and make sure the viewport knows the size of the output texture
glm::vec4 bgCol(0.1f, 0.9f, 0.59f, 1.0f);
glViewport(0, 0, icanvas_size.x, icanvas_size.y);
glClearColor(bgCol.r, bgCol.g, bgCol.b, bgCol.a);
glClear(GL_COLOR_BUFFER_BIT);
currMap->render();
if (static_cast<MapEditor*>(editor->getWindowList()[MAPEDITOR])->getEditMode() == EditMode::Collision) {
currMap->renderCollisionHelper(mTintTexture);
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// draw the rendered image to the window
ImGui::Image((ImTextureID)mMapTexCBO, ImVec2(canvas_size.x, canvas_size.y), ImVec2(0, 1), ImVec2(1, 0));
// Handle clicks within the MapView window
handleClick();
ImGui::End();
ImGui::PopStyleVar();
}
}
} | true |
e763b99f33c5cacdb7fd6646c5100c653a630c2e | C++ | jeanlouhallee/inf3105-tp2 | /Histoire.cpp | UTF-8 | 3,106 | 3.03125 | 3 | [] | no_license | /*
* Histoire.cpp
*
* Created on: Mar 18, 2017
* Author: Bruno Malenfant
*/
#include "Histoire.h"
#include <sstream>
Histoire::Histoire(void) {
}
Histoire::Histoire(string a_titre) :
_titre( a_titre )
{
}
Histoire::Histoire(const Histoire& a_histoire) :
_titre( a_histoire._titre ),
_mots( a_histoire._mots )
{
}
Histoire::~Histoire(void) {
}
string Histoire::titre(void) const {
return _titre;
}
void Histoire::ajouterMot(string a_mot) {
_mots.push_back( a_mot );
}
vector<string>::const_iterator Histoire::begin(void) const {
return _mots.begin();
}
vector<string>::const_iterator Histoire::end(void) const {
return _mots.end();
}
bool estCaractereMot( char c ) {
return ( 'A' <= c && c <= 'Z' ) ||
( 'a' <= c && c <= 'z' ) ||
( '-' == c );
}
vector<Histoire *> * extraireHistoires(const DocumentXML& a_document) {
vector< Histoire * > * resultat = new vector< Histoire * >();
Element * courrant = a_document.racine();
vector< Contenu * >::const_iterator it = courrant->begin();
// trouver <magasine>
while( ! ( * it )->estElement() ) ++ it;
courrant = ( Element * )( * it );
it = courrant->begin();
// trouver <contenus>
while( ! ( * it )->estElement() ) ++ it;
courrant = ( Element * )( * it );
it = courrant->begin();
vector< Contenu * >::const_iterator fin = courrant->end();
for( ; it < fin; ++ it ) {
if( ( * it )->estElement() ) {
Element * histoire = ( Element * )( * it );
string titre = histoire->attribut( string( "titre" ) );
try {
titre += " (partie " + histoire->attribut( string( "partie" ) ) + ")";
} catch( AttributNonDefinie & a_e ) {
// rien
}
Histoire * nouvelle = new Histoire( titre );
stringstream texte( histoire->texte() );
stringstream accumulateur;
char c;
while( ! texte.eof() ) {
do {
texte.get( c );
} while( ! estCaractereMot( c ) && ! texte.eof() );
while( estCaractereMot( c ) && ! texte.eof() ) {
accumulateur << c;
texte.get( c );
}
string mot = accumulateur.str();
accumulateur.str( "" );
if( mot.length() != 0 ) {
nouvelle->ajouterMot( mot );
}
}
resultat->push_back( nouvelle );
}
}
return resultat;
}
ostream & operator << ( ostream & a_out, const Histoire & a_histoire ){
int compteur = 0;
a_out << a_histoire._titre << endl << endl;
for( string mot : a_histoire ) {
a_out << mot << ' ';
compteur += mot.length();
if( compteur > TAILLE_LIGNE ) {
a_out << endl;
compteur -= TAILLE_LIGNE;
}
}
return a_out;
}
| true |
c1f38283f7304c4aa3c1e23dcae0815c951851e1 | C++ | seromerol/swarmNoise | /sensibleNeuronDosServos/sensibleNeuronDosServos.ino | UTF-8 | 4,285 | 3.15625 | 3 | [] | no_license | #include <Servo.h>
#define actData 9 //pin (PWM) donde conectar servo/actuador que transmite el dato input
#define senData 0 //pin (A?) donde conectar flexor/sensor que recibe el dato input
#define actWeight 11 //pin (PWM) donde conectar servo/actuador que transmite el peso del input
#define senWeight 1 //pin (A?) donde conectar flexor/sensor que recibe el peso del input
#define output_pin 12 // pin (PWM) de salida de la neurona
Servo servoData; //controlador servo transmite datos de input
Servo servoWeight; //controlador servo transmite datos del peso de cada input
//pines analogos de entrada (diferentes a los senData y senWeight)
byte input_pins[] = {2, 3, 4, 5};
//data
float bias = 1;
float input[sizeof(input_pins)]; //array para guardar datos de entrada
float data; //almacena el valor de la suma de las entradas por el peso y bias
float weight[sizeof(input_pins)]; //array para guardar datos de los pesos de cada entrada
float output; //dato de salida de la funcion de activacion
void setup() {
Serial.begin(9600);
//asociacion de los controladores servo con los pines
servoData.attach(actData);
servoWeight.attach(actWeight);
//configuracion pines PWM como salidas
pinMode(actData, OUTPUT);
pinMode(actWeight, OUTPUT);
pinMode(output_pin, OUTPUT);
//semilla para pseudoaleatorio
randomSeed(analogRead(0));
//asigna los pesos
setWeights(weight);
}
void loop() {
//lee datos de las entradas
for (byte i = 0; i < sizeof(input_pins); i++) {
input[i] = analogRead(input_pins[i]);
printLine("input: ", input[i]);
}
//suma ponderada de las entradas + bias
data = sumFunction(input, weight, bias);
printLine("sum ax +b: ", data);
//calcula la salida con la funcion de activacion
output = activation(data);
printLine("Neuron value: ", output);
//escribe el dato de salida como PWM en el pin de salida
analogWrite(output_pin, output * 255);
Serial.println("");
}
//funcion que carga la matriz de pesos con aleatorios entre -1 y 1
void setWeights(float w[]) {
for (byte i = 0; i < sizeof(input_pins); i++) {
w[i] = random(-100, 100);
w[i] = w[i] / 100;
//w[i] = 1.0/sizeof(input_pins);
//para imprimir los pesos en serial
String s1 = "Weight ";
String s2 = ": ";
String s = s1 + i + s2;
printLine(s, w[i]);
}
Serial.println("");
}
//funcion que imprime un dato con su etiqueta en la misma linea y separa con tab
void printLine(String n, float b) {
Serial.print(n);
Serial.print(b);
Serial.print("\t");
}
//funcion que suma todos los productos del dato por el peso y le agrega el bias
float sumFunction(float in[], float w[], float b) {
float d = 0; //temporal para guardar la suma
//suma cada entrada por el peso de la misma
for (byte i = 0; i < sizeof(input_pins); i++) {
//si se quiere redimensionar a mano (a veces falla el map
//(valoraredimensionar - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
//float ang = ((in[i] + 1) * 180) / 2;
//se redimensionan los valores leidos de la entrada y el peso para un angulo
float angD = map(in[i], 0, 1024, 0, 180);
float angW = ((w[i] + 1) * 180) / 2;
//para imprimir los angulos en serial
String s1 = "ang servoData ";
String s2 = "ang servoWeight ";
String s3 = ": ";
String sD = s1 + i + s3;
String sW = s2 + i + s3;
printLine(sD, angD);
printLine(sW, angW);
//se ubican los servos en el angulo
servoData.write(angD);
servoWeight.write(angW);
delay(15); //tiempo de respuesta del servo
//multiplica el valor leido por el sensor del dato de entrada por el sensor del peso y los suma a d
d += (analogRead(senData) * analogRead(senWeight));
}
//suma el bias
d += bias;
//devuelve el resultado de la suma de cada (input*weight) mas el bias
return d;
}
//funcion que recibe la suma de los datos de entrada y activa la neurona
float activation(float sum) {
//sigmoid (devuelve valores entre 0 y 1)
return (1 / (1 + exp(-1 * sum)));
//tanh (devuelve valores entre -1 y 1)
//return ((2 / (1 + exp(2 * sum)))-1);
//ReLU (anula valores negativos volviendolos 0)
//return ((sum<0)?0:sum);
//Leaky ReLU (mismo pero los negativos los "rectifica")
//return ((sum<0)?(sum*0.01):sum);
}
| true |
97edc74c378de0f899af17af190aebc9e49fda15 | C++ | tmf/kicker-tacho | /speaker.h | UTF-8 | 1,729 | 2.90625 | 3 | [] | no_license | /*
* Play example using Time3 library.
*
* The sample must be raw 8bits 8KHz, please read README.md.
*
* Juan J. Martinez <jjm@usebox.net>
* https://github.com/reidrac/play-pcm-example
*/
#include <avr/pgmspace.h>
#include "TimerOne.h"
class Speaker
{
static void playISR();
static Speaker * instance;
private:
volatile unsigned char *play_sample;
volatile unsigned short play_sample_length;
volatile unsigned short play_sample_ptr;
volatile int speakerPin;
public:
Speaker(int pin);
void playCallback();
void play(const unsigned char *sample, const unsigned short length);
void stop();
};
Speaker::Speaker(int pin) : speakerPin(pin)
{
pinMode(speakerPin, OUTPUT);
instance = this;
}
void Speaker::playISR(){
instance->playCallback();
}
// for use by ISR glue routines
Speaker * Speaker::instance;
void Speaker::playCallback(void)
{
if(play_sample_length)
{
Timer1.setPwmDuty(speakerPin, pgm_read_byte(&play_sample[play_sample_ptr]));
play_sample_ptr++;
if(play_sample_ptr == play_sample_length)
{
play_sample_length = 0;
Timer1.setPwmDuty(speakerPin, 0);
}
}
}
/* for Teensy 2.0: pin 9 */
void Speaker::play(const unsigned char *sample, const unsigned short length)
{
play_sample_length = 0;
// 8KHz are 125 microsenconds
Timer1.initialize(125);
Timer1.attachInterrupt(playISR);
Timer1.pwm(speakerPin, HIGH);
noInterrupts();
play_sample = (unsigned char *)sample;
play_sample_ptr = 0;
play_sample_length = length;
interrupts();
}
void Speaker::stop(){
noInterrupts();
play_sample_length = 0;
Timer1.setPwmDuty(speakerPin, 0);
Timer1.stop();
Timer1.detachInterrupt();
interrupts();
}
| true |
41a477aaffc1f4fa11b74cc04c45eab55b89b6ba | C++ | kkllPreciel/cpp14 | /cpp14/return type deduction for normal functions/main.cpp | SHIFT_JIS | 325 | 3.421875 | 3 | [] | no_license | #include <iostream>
// IuWFNgfĂяoʂ̌^Ag()̖߂l^Ƃ
template <class F>
auto g(F f)
{
return f();
}
int main()
{
// ϐresulť^int
auto result = g([] { return 3; });
std::cout << result << std::endl;
return 0;
} | true |
ec05e74871d44e948d90e03ff9717d472b56759e | C++ | henrywalters/have-some-pi | /Source/Scripts/Blink.hpp | UTF-8 | 554 | 2.578125 | 3 | [] | no_license | #ifndef BLINK_SCRIPT_HPP
#define BLINK_SCRIPT_HPP
#include <wiringPi.h>
#include "../BaseScript.hpp"
#include "../Components/LED.hpp"
class BlinkScript : public BaseScript {
LED* _led;
public:
BlinkScript() : BaseScript("Blink LED") {
_led = NULL;
}
void OnCreate() {
wiringPiSetup();
_led = new LED(0);
}
void OnUpdate() {
_led->on();
delay(1000);
_led->off();
delay(1000);
_running = false;
}
void OnDestroy() {
delete _led;
}
};
#endif | true |
8b718f19dceb178db9d9aeb4a7c95bd044121e13 | C++ | DMurataj01/COMS3015-Graphics-Rendering-Engine | /libs/sdw/ModelTriangle.h | UTF-8 | 2,016 | 3.0625 | 3 | [] | no_license | #include <glm/glm.hpp>
#include <Colour.h>
#include <string>
#include "Materials.h"
class ModelTriangle {
public:
glm::vec3 vertices[3];
glm::vec2 vertices_textures[3];
Colour colour;
glm::vec3 normals[3]; // these correspond to the averaged normals of the vertices
MATERIAL material;
int faceIndex; // stores the number of which face it is out of all of them
int objectIndex; // used in OBJ - stores the group this triangle is in.
bool culled; // has this face been culled or not? do we need to check for intersections with it?
ModelTriangle() {
normals[0] = glm::vec3 (0,0,0);
normals[1] = glm::vec3 (0,0,0);
normals[2] = glm::vec3 (0,0,0);
material = NONE;
culled = false;
faceIndex = -1;
objectIndex = -1;
}
ModelTriangle(glm::vec3 v0, glm::vec3 v1, glm::vec3 v2, Colour trigColour) {
vertices[0] = v0;
vertices[1] = v1;
vertices[2] = v2;
colour = trigColour;
normals[0] = glm::vec3 (0,0,0);
normals[1] = glm::vec3 (0,0,0);
normals[2] = glm::vec3 (0,0,0);
material = NONE;
culled = false;
faceIndex = -1;
objectIndex = -1;
}
glm::vec3 getNormal() {
const glm::vec3 e0 = (vertices[1] - vertices[0]); //v1 - v0
const glm::vec3 e1 = (vertices[2] - vertices[0]); //v2 - v1
// return the normal = glm::cross(e0, e1);
return glm::normalize(glm::cross(e0, e1));
}
};
std::ostream& operator<<(std::ostream& os, const ModelTriangle& triangle)
{
os << "(" << triangle.vertices[0].x << ", " << triangle.vertices[0].y << ", " << triangle.vertices[0].z << ")" << std::endl;
os << "(" << triangle.vertices[1].x << ", " << triangle.vertices[1].y << ", " << triangle.vertices[1].z << ")" << std::endl;
os << "(" << triangle.vertices[2].x << ", " << triangle.vertices[2].y << ", " << triangle.vertices[2].z << ")" << std::endl;
os << std::endl;
return os;
}
| true |
9f7dc7a0ae34c55ce595f58ce2fb5c4f09051158 | C++ | OrsoEric/2020-07-06-Longan-Nano-RTC-Interrupt | /init.cpp | UTF-8 | 7,822 | 2.828125 | 3 | [] | no_license | /****************************************************************************
** init.cpp
*****************************************************************************
** Board initializations
** >GPIO
** >EXTI
** >ECLIC
****************************************************************************/
/****************************************************************************
** INCLUDE
****************************************************************************/
#include <gd32vf103.h>
//Onboard RBG LEDs of the Longan Nano
#include "longan_nano_led.hpp"
/****************************************************************************
** NAMESPACES
****************************************************************************/
//using namespace std;
/****************************************************************************
** GLOBAL VARIABILE
****************************************************************************/
/****************************************************************************
** FUNCTION PROTOTYPES
****************************************************************************/
//Initialize the board
extern bool init( void );
//Initialize RTC Timer to generate a system tick
extern bool init_rtc( void );
//Initialize the EXTI edge detection interrupt from the GPIO
extern bool init_exti(void);
//Initialize the ECLIC interrupt controller
extern bool init_eclic(void);
/****************************************************************************
** FUNCTION
****************************************************************************/
/***************************************************************************/
//! @brief init
//! init |
/***************************************************************************/
//! @return bool | false = OK | true = ERR
//! @details
//! initialize the longan nano pheriperals
/***************************************************************************/
bool init( void )
{
//----------------------------------------------------------------
// VARS
//----------------------------------------------------------------
//Return
bool f_ret = false;
//----------------------------------------------------------------
// BODY
//----------------------------------------------------------------
// GPIO
// ECLIC
// EXTI
//Initialize the Longan Nano builtin RBG LEDs
f_ret |= Longan_nano::Leds::init();
//Initialize LEDs to OFF
Longan_nano::Leds::set_color( Longan_nano::Led_color::BLACK );
//EXTI GPIO interrupt: PA8 R/F -> EXTI_5_9
f_ret |= init_exti();
//RTC system tick
f_ret |= init_rtc();
//Initialize ECLIC Interrupt controller. Interrupts can now be generated
f_ret |= init_eclic();
//if: initialization failed
if (f_ret == true)
{
}
//----------------------------------------------------------------
// RETURN
//----------------------------------------------------------------
return f_ret;
} //end init: init |
/***************************************************************************/
//! @brief init
//! init_exti |
/***************************************************************************/
//! @return bool | false = OK | true = ERR
//! @details
//! initialize the EXTI edge detection interrupt from the GPIO
//! PA8 R/F -> EXTI_5_9
/***************************************************************************/
bool init_exti(void)
{
//----------------------------------------------------------------
// VARS
//----------------------------------------------------------------
//----------------------------------------------------------------
// BODY
//----------------------------------------------------------------
//Setup the boot button
gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ,GPIO_PIN_8);
//Clock the alternate functions
rcu_periph_clock_enable(RCU_AF);
//Initialize the EXTI. IRQ can be generated from GPIO edge detectors
gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOA, GPIO_PIN_SOURCE_8);
exti_init(EXTI_8, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
//Clear interrupt flag. Ensure no spurious execution at start
exti_interrupt_flag_clear(EXTI_8);
//----------------------------------------------------------------
// RETURN
//----------------------------------------------------------------
return false; //OK
} //end init: init_exti |
/***************************************************************************/
//! @brief init
//! init_rtc |
/***************************************************************************/
//! @return bool | false = OK | true = ERR
//! @details
//! initialize the RTC Real Time Counter
//! setup to emit a 4Hz SECOND interrupt
//!
//! RTC Interrupts:
//! RTC_INT_SECOND: Generated every time RTC_CNT changes (after the prescaler RTC_PSC)
//! RTC_INT_ALARM: Generated when RTC_CNT equals RTC_ALRM
//! RTC_INT_OV: Generated when the 32b RTC_CNT counter overflows to zero
/***************************************************************************/
bool init_rtc(void)
{
//----------------------------------------------------------------
// VARS
//----------------------------------------------------------------
//----------------------------------------------------------------
// BODY
//----------------------------------------------------------------
//Backup Clock
rcu_periph_clock_enable(RCU_BKPI);
//
rcu_periph_clock_enable(RCU_PMU);
//Enter configuration mode
pmu_backup_write_enable();
//
bkp_deinit();
//Enable LX crystal 32768 [Hz]
rcu_osci_on(RCU_LXTAL);
//Wait for crystal to stabilize
rcu_osci_stab_wait(RCU_LXTAL);
//Clock the RTC with the LX Crystal
rcu_rtc_clock_config(RCU_RTCSRC_LXTAL);
rcu_periph_clock_enable(RCU_RTC);
//wait for RTC registers synchronization
rtc_register_sync_wait();
//wait until last write operation on RTC registers has finished
rtc_lwoff_wait();
//Set the RTC Prescaler
rtc_prescaler_set(8192);
//wait until last write operation on RTC registers has finished
rtc_lwoff_wait();
//Emit an interrupt each time RTC_CNT counts
rtc_interrupt_enable(RTC_INT_SECOND);
//wait until last write operation on RTC registers has finished
rtc_lwoff_wait();
//----------------------------------------------------------------
// RETURN
//----------------------------------------------------------------
return false; //OK
} //end init: init_rtc |
/***************************************************************************/
//! @brief init
//! init_eclic |
/***************************************************************************/
//! @return bool | false = OK | true = ERR
//! @details
//! Initialize the ECLIC interrupt controller
/***************************************************************************/
bool init_eclic(void)
{
//----------------------------------------------------------------
// VARS
//----------------------------------------------------------------
//----------------------------------------------------------------
// BODY
//----------------------------------------------------------------
//Initialize the ECLIC IRQ lines
eclic_priority_group_set(ECLIC_PRIGROUP_LEVEL3_PRIO1);
eclic_irq_enable(EXTI5_9_IRQn, 1, 1);
//Enable the RTC Interrupt
eclic_priority_group_set(ECLIC_PRIGROUP_LEVEL1_PRIO3);
eclic_irq_enable(RTC_IRQn, 1, 0);
//Enable the interrupts. From now on interrupt handlers can be executed
eclic_global_interrupt_enable();
//----------------------------------------------------------------
// RETURN
//----------------------------------------------------------------
return false; //OK
} //end init: init_eclic | | true |
36fe1fd96ad167569c75c404a751d62bdd4c29a9 | C++ | Antero-Gandra/AEDA | /FinalProj/Project/Participation.h | UTF-8 | 1,347 | 2.875 | 3 | [] | no_license | class Participation {
unsigned int auditionId;
unsigned int place;
unsigned int chiefJudgeGrade;
public:
/**
* @brief Participation Contructor with their audition id, place and the resposible judge's grade
* @param auditionId an unsigned integer
* @param place an unsigned integer
* @param chiefJudgeGrade an unsigned integer
*/
Participation(unsigned int auditionId, unsigned int place, unsigned int chiefJudgeGrade);
/**
* @brief Manages to access the Audition's ID the contestant was in
* @return unsigned integer of the Audition's ID
*/
unsigned int getAuditionId() const;
/**
* @brief Manages to access the ranking the contestant got
* @return unsigned integer of the ranking of the contestant
*/unsigned int getPlace() const;
/**
* @brief Manages to access the value that the responsible judge grade the contestant
* @return unsigned integer of the grade
*/
unsigned int getChiedJudgeGrade() const;
/**
* @brief Changes the audition's id
* @param auditionId unsigned integer
*/
void setAuditionId(unsigned int auditionId);
/**
* @brief Changes the contestant's ranking
* @param place unsigned integer
*/
void setPlace(unsigned int place);
/**
* @brief Changes the reposible judge's grade
* @param chiefJudgeGrade unsigned integer
*/
void setChiefJudgeGrade(unsigned int chiefJudgeGrade);
};
| true |
9522c403520125c562bae66fe0f94f0a82602778 | C++ | RobTillaart/Arduino | /libraries/PinOutGroup/PinOutGroup.cpp | UTF-8 | 2,584 | 2.90625 | 3 | [
"MIT"
] | permissive | //
// FILE: PinOutGroup.cpp
// AUTHOR: Rob Tillaart
// VERSION: 0.1.7
// DATE: 2017-04-26
// PURPOSE: PinOutGroup library for Arduino
// goal is to easily change a group of pins that logically
// belong to each other e.g. 8 data pins of a parallel printer.
// these pins can be in any order.
// URL: https://github.com/RobTillaart/PinOutGroup
// http://forum.arduino.cc/index.php?topic=469599.0
#include "PinOutGroup.h"
PinOutGroup::PinOutGroup()
{
clear();
}
void PinOutGroup::clear()
{
// safety: set all to LOW before cleaning up.
allLOW();
_size = 0;
}
uint8_t PinOutGroup::add(uint8_t size, uint8_t* pinArray, uint8_t value)
{
int n = 0;
for (uint8_t i = 0; i < size; i++)
{
n += add(pinArray[i], value);
}
return n;
}
uint8_t PinOutGroup::add(uint8_t pin, uint8_t value)
{
if (_size >= PINOUTGROUP_MAXSIZE) return 0;
_pins[_size] = pin;
pinMode(pin, OUTPUT);
write(_size, value); // takes care of _lastValue
_size++;
return 1;
}
uint8_t PinOutGroup::isInGroup(uint8_t pin)
{
uint8_t count = 0;
for (uint8_t i = 0; i < _size; i++)
{
if (_pins[i] == pin) count++;
}
return count;
}
uint8_t PinOutGroup::write(uint16_t value)
{
uint16_t changed = _lastValue ^ value; // detect pins that changed
if (changed == 0) return 0;
uint16_t bitMask = 1;
uint8_t changeCount = 0;
for (uint8_t i = 0; i < _size; i++)
{
if ((changed & bitMask) > 0)
{
digitalWrite(_pins[i], (value & bitMask) > 0);
changeCount++;
}
bitMask <<= 1;
}
_lastValue = value;
return changeCount;
}
uint8_t PinOutGroup::write(uint8_t index, uint8_t value)
{
if (index >= _size) return 0;
uint16_t mask = (1 << index);
uint16_t lastValue = _lastValue & mask;
if ((value > 0) == (lastValue > 0)) return 0; // no change
digitalWrite(_pins[index], value);
if (value == LOW) _lastValue &= ~mask;
else _lastValue |= mask;
return 1;
}
void PinOutGroup::allLOW()
{
for (uint8_t i = 0; i < _size; i++)
{
digitalWrite(_pins[i], LOW);
}
_lastValue = 0;
}
void PinOutGroup::allHIGH()
{
uint16_t value = 0;
for (uint8_t i = 0; i < _size; i++)
{
digitalWrite(_pins[i], HIGH);
value |= (1 << i); // set flags.
}
_lastValue = value;
}
uint8_t PinOutGroup::getPin(uint8_t index)
{
if (index >= _size) return 0xFF;
return _pins[index];
}
uint8_t PinOutGroup::getIndex(uint8_t pin)
{
for (uint8_t i = 0; i < _size; i++)
{
if (_pins[i] == pin) return i;
}
return 0xFF;
}
// -- END OF FILE --
| true |
a1fa7ce68e5c48463bd92fca077cc00eb1f308da | C++ | ordinary-developer/education | /cpp/std-11/r_lischner-exploring_cpp_11-2_ed/ch_70-metaprogramming/11-using_enabled_if_for_functions/main.cpp | UTF-8 | 299 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <limits>
#include <type_traits>
template <class T>
typename std::enable_if<std::numeric_limits<T>::is_signed, T>::type
minus(T const& x)
{
return -x;
}
int main() {
int a{};
minus(a); // ok
// unsigned int b{};
// minus(b); // compilation error
return 0;
}
| true |
fa3f509c7916d20e8bf27c6f849dbecafece9cc4 | C++ | Alexis-BX/CSE306-Raytracer | /objects.cpp | UTF-8 | 1,010 | 2.984375 | 3 | [] | no_license | #ifndef OBJ
#define OBJ
#include "vector.cpp"
enum Materials{
opaque,
miror,
transparent
};
class Sphere{
public:
Sphere(Vector& center, double r, Vector& color, Materials material=opaque){
R = r;
p = center;
c = color;
m = material;
}
Vector p, c;
double R;
Materials m;
};
class Ray {
public:
Ray(Vector& point, Vector& direction){
p = point;
d = direction;
}
Vector p, d;
};
class Camera {
public:
Camera(){}
Camera(Vector& point, double fieldOfView, double aperatureRad=.1){
p = point;
fov = fieldOfView;
f = w/(2.*tan(fov/2.*PI/180.));
R = aperatureRad;
}
Vector p;
double fov, f, R;
};
class Light {
public:
Light(){}
Light(Vector& point, int intensity, double radius){
p = point;
I = intensity;
R = radius;
}
Vector p;
double R;
int I;
};
#endif | true |
cb90f8beed85a8ea4a31e998d9c6b7a589605d03 | C++ | duongnguyencp/C-collection | /Untitled6.cpp | UTF-8 | 238 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void ThuaSo (int a)
{ int i=2;
while(a>0)
{
if(a%i==0)
{
cout<<i;
a=a/i;
if(a!=1) cout<<"x";
}
if(a%i!=0)
{
i++;
}
}
}
int main()
{
int a;
cin>>a;
ThuaSo(a);
}
| true |
e915f5fef19c4bfdde2f28f66b5d84122dabcc42 | C++ | Riteshy123/CPP | /DemoCompoundAssignment34.cpp | UTF-8 | 225 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int sum=10,x=5;
sum+=x;
cout<<sum<<endl;
int fact=10,y=5;
fact*=y;
cout<<fact<<endl;
return 0;
}
| true |
36ae8001cea059ae4d9daaec0b7772aaa4a1ce06 | C++ | PlCpp/11_gy | /aamain.cpp | UTF-8 | 1,861 | 3.125 | 3 | [] | no_license | #include <string>
#include <iostream>
#include "arrapp.h"
#include <algorithm>
#include <vector>
#include "arrapp.h"
const int max = 1000;
int main()
{
int your_mark = 1;
// 2-es
int s[] = {3, 2};
array_appender<int> ia ( s, sizeof( s ) / sizeof( s[ 0 ] ) );
for( int i = 0; i < max - 1; ++i )
{
ia.append( s, sizeof( s ) / sizeof( s[ 0 ] ) );
}
std::string hw[] = { "Hello", "World" };
std::string langs[] = { "C++", "Ada", "Brainfuck" };
std::string x[] = { "Goodbye", "Cruel", "World" };
array_appender<std::string> sa ( hw, sizeof( hw ) / sizeof( hw[ 0 ] ) );
sa.append( langs, sizeof( langs ) / sizeof( langs[ 0 ] ) );
sa.append( x, sizeof( x ) / sizeof( x[ 0 ] ) );
const array_appender<std::string> ha( hw, sizeof( hw ) / sizeof( hw[ 0 ] ) );
if ( max * 2 == ia.size() && 3 == ia.at( max ) && 2 == ia.at( 3 ) &&
&( s[ 0 ] ) == &(ia.at( max / 2 ) ) && 2 == ha.size() && 8 == sa.size() &&
"C++" == sa.at( 2 ) && 7 == sa.at( 5 ).length() && &( ha.at( 0 ) ) == hw )
{
your_mark = ia.at( max + 1 );
}
// 3-as
sa[ 0 ] = "Hallo";
++ia[ 1 ];
if ( 'a' == hw[ 0 ][ 1 ] && "Ada" == sa[ 3 ] && "World" == ha[ 1 ] )
{
your_mark = ia[ max - 1 ];
}
//4-es
std::vector<int> vi;
vi.push_back( 1 );
ia.append( vi );
ia[ 2 * max ] = 4;
std::vector<std::string> vs;
vs.push_back( "Some" );
vs.push_back( "Text" );
sa.append( vs );
sa.append( vs );
if ( 1 + 2 * max == ia.size() && 12 == sa.size() && "Some" == sa[ 10 ] )
{
your_mark = vi[ 0 ];
}
// 5-os
array_appender<std::string>::iterator i = std::find( sa.begin(), sa.end(), "Hallo" );
if ( 1 == std::count( ia.begin(), ia.end(), 4 ) && i == sa.begin() )
{
your_mark += std::count( sa.begin(), sa.end(), "C++" );
}
std::cout << "Your mark is " << your_mark;
std::endl( std::cout );
} | true |
61e08a0626478198d58e1319634ba0bc65f3ae23 | C++ | sirlancer/Algorithm | /List/数组中次数超过一半的数字.cpp | UTF-8 | 834 | 3.203125 | 3 | [] | no_license | class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int res = numbers[0];
int times = 1;
for(int i=1; i<numbers.size(); i++){
if(res == numbers[i]){
++times;
}else if(times == 0){
res = numbers[i];
times = 1;
}else{
--times;
}
}
if(!checkMoreThanHalf(numbers, res)){
return 0;
}
return res;
}
bool checkMoreThanHalf(vector<int> numbers, int target){
int times = 0;
for(int i=0; i<numbers.size(); i++){
if(target == numbers[i]){
++times;
}
}
if(times * 2 <= numbers.size())
return false;
else
return true;
}
}; | true |
9f85bd82d4b09e025212b64c8dad1f86ad9da30c | C++ | yanes328/oop | /inheritance_MakawekesYanes.cpp | UTF-8 | 812 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Person {
private:
string name;
char gender;
public:
Person();
void setName (string name);
void setGender (char gender);
string getName();
char getGender();
};
class Teacher {
private:
int nik;
string faculty;
public:
void setNik (int nik);
int getNik();
void SetFaculty (string faculty);
string getFaculty();
void setData();
void displayData();
};
class Student {
private:
int nim;
string registration_number;
string prodi;
public:
void setNim (int nim);
void SetRegistrationNumber (string registration_number);
void setProdi (string prodi);
int getNim();
string getRegistrationNumber();
string getProdi();
};
int main () {
return 0;
}
| true |
c4a46f529696b3c5e5a5b360b64413cc3b4323c7 | C++ | chingdae1/Algorithm-2017 | /SelectionSort.cpp | UTF-8 | 513 | 2.671875 | 3 | [] | no_license | //2012017850_박창대
#include <stdio.h>
#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t))
int main(){
int n,m,i,j,least,temp;
scanf("%d %d",&n,&m);
int array[n];
for(int i=0 ; i<n ; i++){
scanf("%d", &array[i]);
}
for(i=0;i<m;i++){
least = i;
for(j=i+1;j<n;j++){
if(array[j]<array[least])
least=j;
}
SWAP(array[i],array[least],temp);
}
for(i=0;i<n;i++){
printf("%d\n",array[i]);
}
return 0;
} | true |
90ef66cf2c4fe1eb9214e0672cbcd45549e58531 | C++ | xiongyihui/lsdcomm | /src/SubclassWnd.cpp | UTF-8 | 12,644 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | /** @file SubclassWnd.cpp
*
* Implementation file for CSubclassWnd.
*
* @author William E. Kempf
* @version 2.0
*
* Copyright © 2000 NEWare Software.
*
* This code may be used in compiled form in any way you desire (including
* commercial use). The code may be redistributed unmodified by any means providing
* it is not sold for profit without the authors written consent, and providing that
* this notice and the authors name and all copyright notices remains intact. However,
* this file and the accompanying source code may not be hosted on a website or bulletin
* board without the authors written permission.
*
* <b><i>This software is provided "as is" without express or implied warranty. Use it
* at your own risk!</i></b>
*/
#include "stdafx.h"
#include "Debug.h"
#include "SubclassWnd.h"
namespace
{
/*
* Sends a message to all child controls of a specified window.
*
* @param message [in] Specifies the message id.
* @param wParam [in] Specifies additional message-specific information.
* @param lParam [in] Specifies additional message-specific information.
* @param bDeep [in] Specifies whether or not the message should be sent
* recursively to all children.
*/
void SendMessageToDescendantsImp(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam, BOOL bDeep)
{
// walk through HWNDs to avoid creating temporary CWnd objects
// unless we need to call this function recursively
for (HWND hWndChild = ::GetTopWindow(hWnd); hWndChild != NULL;
hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT))
{
// send message with Windows SendMessage API
::SendMessage(hWndChild, message, wParam, lParam);
if (bDeep && ::GetTopWindow(hWndChild) != NULL)
{
// send to child windows after parent
SendMessageToDescendantsImp(hWndChild, message, wParam, lParam,
bDeep);
}
}
}
};
/*
* Message used to unsubclass CSubclassWnd objects.
*/
const UINT WM_UNSUBCLASS = RegisterWindowMessage("{207D9568-FF3C-11D3-A469-000629B2F855}");
/*
* Message used to reflect messages back to child controls.
*/
const UINT WM_REFLECT = RegisterWindowMessage("{9688DAE5-3736-11D4-A48C-000629B2F855}");
/*
* Message used to get the reflector plugin from a window if one exists.
*/
const UINT WM_GETREFLECTOR = RegisterWindowMessage("{9688DAE6-3736-11D4-A48C-000629B2F855}");
/*
* Specifies the reflected message information. Used by WM_REFLECT.
*/
struct MSGREFLECTSTRUCT
{
UINT message;
WPARAM wParam;
LPARAM lParam;
BOOL bHandled;
};
/*
* Message handler used to reflect messages from a parent window to a child window.
*/
class CMessageReflector : public CSubclassWnd
{
private:
CMessageReflector(HWND hWnd);
public:
static CMessageReflector* FromHandle(HWND hWnd);
virtual BOOL ProcessWindowMessage(UINT message, WPARAM wParam, LPARAM lParam,
LRESULT& lResult);
virtual void OnFinalMessage();
};
/*
* Constructor. Subclasses the specified window.
*
* @param hWnd [in] Handle to the window to be subclassed.
*/
CMessageReflector::CMessageReflector(HWND hWnd)
{
ASSERT(::IsWindow(hWnd));
SubclassWindow(hWnd, FALSE);
}
/*
* This method retrieves a pointer to a CMessageReflector object from a handle to a
* window. If the specified window has not yet been subclassed by a CMessageReflector
* instance then a new instance is created on the heap.
*
* @param hWnd [in] Handle to the window to retrieve the CMessageReflector from.
*
* @return A pointer to the message reflector associated with the window.
*/
CMessageReflector* CMessageReflector::FromHandle(HWND hWnd)
{
CMessageReflector* pReflector =
(CMessageReflector*)::SendMessage(hWnd, WM_GETREFLECTOR, 0, 0);
if (!pReflector)
pReflector = new CMessageReflector(hWnd);
return pReflector;
}
/*
* Called to handle window messages. Derived classes can override this
* method to handle any window messages sent to the subclassed window.
* Normally the programmer won't code this directly, but will instead use
* the BEGIN_MSG_DISPATCH/END_MSG_DISPATCH macros.
*
* @param message [in] Specifies the message id.
* @param wParam [in] Specifies additional message-specific information.
* @param lParam [in] Specifies additional message-specific information.
* @param lResult [in] A reference to the result value to be returned to
* the caller.
*
* @return TRUE if the message was handled, otherwise FALSE.
*/
BOOL CMessageReflector::ProcessWindowMessage(UINT message, WPARAM wParam, LPARAM lParam,
LRESULT& lResult)
{
if (message == WM_GETREFLECTOR)
{
lResult = (LRESULT)this;
return TRUE;
}
HWND hWndChild = NULL;
switch (message)
{
case WM_COMMAND:
if (lParam != NULL) // not from a menu
hWndChild = (HWND)lParam;
break;
case WM_NOTIFY:
hWndChild = ((LPNMHDR)lParam)->hwndFrom;
break;
case WM_PARENTNOTIFY:
switch (LOWORD(wParam))
{
case WM_CREATE:
case WM_DESTROY:
hWndChild = (HWND)lParam;
break;
default:
hWndChild = GetDlgItem(GetHandle(), HIWORD(wParam));
break;
}
break;
case WM_DRAWITEM:
if (wParam) // not from a menu
hWndChild = ((LPDRAWITEMSTRUCT)lParam)->hwndItem;
break;
case WM_MEASUREITEM:
if (wParam) // not from a menu
hWndChild = GetDlgItem(GetHandle(), ((LPMEASUREITEMSTRUCT)lParam)->CtlID);
break;
case WM_COMPAREITEM:
if (wParam) // not from a menu
hWndChild = GetDlgItem(GetHandle(), ((LPCOMPAREITEMSTRUCT)lParam)->CtlID);
break;
case WM_DELETEITEM:
if (wParam) // not from a menu
hWndChild = GetDlgItem(GetHandle(), ((LPDELETEITEMSTRUCT)lParam)->CtlID);
break;
case WM_VKEYTOITEM:
case WM_CHARTOITEM:
case WM_HSCROLL:
case WM_VSCROLL:
hWndChild = (HWND)lParam;
break;
case WM_CTLCOLORBTN:
case WM_CTLCOLORDLG:
case WM_CTLCOLOREDIT:
case WM_CTLCOLORLISTBOX:
case WM_CTLCOLORMSGBOX:
case WM_CTLCOLORSCROLLBAR:
case WM_CTLCOLORSTATIC:
hWndChild = (HWND)lParam;
break;
default:
break;
}
if (hWndChild == NULL)
return FALSE;
ASSERT(::IsWindow(hWndChild));
MSGREFLECTSTRUCT rs;
rs.message = OCM__BASE + message;
rs.wParam = wParam;
rs.lParam = lParam;
rs.bHandled = FALSE;
lResult = ::SendMessage(hWndChild, WM_REFLECT, 0, (LPARAM)&rs);
return rs.bHandled;
}
/*
* Called after the last message has been dispatched to the window.
*/
void CMessageReflector::OnFinalMessage()
{
delete this;
}
/**
* Default contructor.
*/
CSubclassWnd::CSubclassWnd()
: m_hWnd(0), m_pfnSuperWindowProc(::DefWindowProc), m_pCurrentMsg(0)
{
}
/**
* Destructor.
*/
CSubclassWnd::~CSubclassWnd()
{
if (m_hWnd != NULL)
UnsubclassWindow();
}
/**
* Called to subclass the specified window. If the @a bReflect
* parameter is non-zero then the parent window will be subclassed to
* support message reflection.
*
* @param hWnd [in] Specifies the handle of the window to be subclassed.
* @param bReflect [in] Specifies whether or not the parent should
* reflect messages back to the window.
*
* @return If the window was subclassed, the return value is non-zero. If the
* window was not subclassed, the return value is zero.
*/
BOOL CSubclassWnd::SubclassWindow(HWND hWnd, BOOL bReflect)
{
if (m_hWnd != NULL || !::IsWindow(hWnd))
return FALSE;
m_thunk.Init(WindowProc, this);
WNDPROC pProc = (WNDPROC)&(m_thunk.thunk);
WNDPROC pfnWndProc = (WNDPROC)::SetWindowLong(hWnd, GWL_WNDPROC, (LONG)pProc);
if (pfnWndProc == NULL)
return FALSE;
m_pfnSuperWindowProc = pfnWndProc;
m_hWnd = hWnd;
if (bReflect && (GetWindowLong(hWnd, GWL_STYLE) & WS_CHILD) == WS_CHILD)
{
HWND hWndParent = GetParent(hWnd);
ASSERT(::IsWindow(hWndParent));
CMessageReflector::FromHandle(hWndParent);
}
return TRUE;
}
/**
* Called to unsubclass the specified window.
*
* @return The handle to the window previously subclassed.
*/
HWND CSubclassWnd::UnsubclassWindow()
{
return (HWND)SendMessage(WM_UNSUBCLASS, 0, (LPARAM)this);
}
/**
* Implementation detail. This is the actual WindowProc installed by
* the thunk.
*
* @param hWnd [in] Handle to the window.
* @param message [in] Specifies the message id.
* @param wParam [in] Specifies additional message-specific information.
* @param lParam [in] Specifies additional message-specific information.
*
* @return The return value is the result of the message processing and
* depends on the message sent.
*/
LRESULT CALLBACK CSubclassWnd::WindowProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
CSubclassWnd* pThis = (CSubclassWnd*)hWnd;
// set a ptr to this message and save the old value
MSG msg = { pThis->m_hWnd, message, wParam, lParam, 0, { 0, 0 } };
// check to see if this is a reflected message and adjust accordingly
MSGREFLECTSTRUCT* rs = 0;
if (message == WM_REFLECT)
{
rs = (MSGREFLECTSTRUCT*)lParam;
ASSERT(rs);
msg.message = rs->message;
msg.wParam = rs->wParam;
msg.lParam = rs->lParam;
}
// save the message information and set the new current
const MSG* pOldMsg = pThis->m_pCurrentMsg;
pThis->m_pCurrentMsg = &msg;
// pass to the message map to process
LRESULT lRes;
BOOL bRet = pThis->ProcessWindowMessage(msg.message, msg.wParam, msg.lParam, lRes);
// if this is a reflected message let parent know if it was handled
if (rs)
rs->bHandled = bRet;
// restore saved value for the current message
pThis->m_pCurrentMsg = pOldMsg;
// do the default processing if message was not handled
// note that we need to use the original values, so that reflected
// messages can properly set the 'bHandled' flag.
if (!bRet)
lRes = pThis->DefWindowProc(message, wParam, lParam);
if (message == WM_NCDESTROY)
{
// unsubclass, if needed
pThis->UnsubclassWindow();
// clean up after window is destroyed
pThis->OnFinalMessage();
}
return lRes;
}
/**
* Sends a message to all child windows of the subclassed window.
*
* @param message [in] Specifies the message id.
* @param wParam [in] Specifies additional message-specific information.
* @param lParam [in] Specifies additional message-specific information.
* @param bDeep [in] Specifies whether or not the message should be sent
* recursively to all children.
*/
void CSubclassWnd::SendMessageToDescendants(UINT message, WPARAM wParam, LPARAM lParam,
BOOL bDeep)
{
SendMessageToDescendantsImp(GetHandle(), message, wParam, lParam, bDeep);
}
/**
* Called after the last message has been dispatched to the window.
*/
void CSubclassWnd::OnFinalMessage()
{
}
/**
* Called to handle window messages. Derived classes can override this
* method to handle any window messages sent to the subclassed window.
* Normally the programmer won't code this directly, but will instead use
* the #BEGIN_MSG_DISPATCH/#END_MSG_DISPATCH macros.
*
* @param message [in] Specifies the message id.
* @param wParam [in] Specifies additional message-specific information.
* @param lParam [in] Specifies additional message-specific information.
* @param lResult [out] A reference to the result value to be returned to
* the caller.
*
* @return If the message was handled, the return value is non-zero. If the
* message was not handled, the return value is zero.
*/
BOOL CSubclassWnd::ProcessWindowMessage(UINT message, WPARAM wParam, LPARAM lParam,
LRESULT& lResult)
{
if (message == WM_UNSUBCLASS)
{
if ((CSubclassWnd*)lParam == this)
{
if (m_hWnd == NULL)
lResult = NULL;
else
{
if (wParam)
{
CSubclassWnd* pPrevious = (CSubclassWnd*)wParam;
ASSERT(pPrevious->m_pfnSuperWindowProc == (WNDPROC)&(m_thunk.thunk));
pPrevious->m_pfnSuperWindowProc = m_pfnSuperWindowProc;
lResult = (LRESULT)m_hWnd;
m_pfnSuperWindowProc = ::DefWindowProc;
m_hWnd = NULL;
}
else
{
WNDPROC pOurProc = (WNDPROC)&(m_thunk.thunk);
WNDPROC pActiveProc = (WNDPROC)::GetWindowLong(m_hWnd, GWL_WNDPROC);
ASSERT(pOurProc == pActiveProc);
if (!::SetWindowLong(m_hWnd, GWL_WNDPROC, (LONG)m_pfnSuperWindowProc))
lResult = NULL;
else
{
m_pfnSuperWindowProc = ::DefWindowProc;
lResult = (LRESULT)m_hWnd;
m_hWnd = NULL;
}
}
}
}
else
lResult = DefWindowProc(message, (WPARAM)this, lParam);
return TRUE;
}
return FALSE;
}
| true |
5289a0b00d428a041d74929d4c10f9394c804cf9 | C++ | BackupGGCode/fgv-master-quant | /PROG1/PROG1-Lista01/src/Lista01.cpp | ISO-8859-1 | 7,269 | 3.296875 | 3 | [] | no_license | //=======================================================================
// Author : Milton Yukio Godoy Saito
// Name : Lista01.cpp
// Discipline : FGV - MPE -Programao e Mtodos Numricos em Finanas I
// Date : 13/02/2012
// Description : Lista de exerccios 1
//=======================================================================
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void EX01(void);
void EX02(void);
void EX03(void);
void EX04(void);
void EX05(void);
void EX06(void);
void EX07(void);
void EX08(void);
void EX09(void);
void EX10(void);
void EX11(void);
void EX12(void);
bool validParam(double param1);
bool validParam(double param1, double param2);
bool validParam(double param1, double param2, double param3);
int main(void)
{
setlocale(LC_ALL, "ptb");
int menu=-1;
do{
switch(menu){
case 0: return 0;
case 1: EX01(); menu=-1; break;
case 2: EX02(); menu=-1; break;
case 3: EX03(); menu=-1; break;
case 4: EX04(); menu=-1; break;
case 5: EX05(); menu=-1; break;
case 6: EX06(); menu=-1; break;
case 7: EX07(); menu=-1; break;
case 8: EX08(); menu=-1; break;
case 9: EX09(); menu=-1; break;
case 10: EX10(); menu=-1; break;
case 11: EX11(); menu=-1; break;
case 12: EX12(); menu=-1; break;
default:
cout << endl << "Digite o nmero do exerccio [1-12 ou 0-sair]: ";
cin >> menu;
cout << endl;
break;
}
}while(menu!=0);
return 0;
}
/*********************************************************************************/
void EX01(void)
{
double n = 0;
double soma = 0;
do{
cout << "[EX01 in] Digite o nmero N: ";
cin >> n;
}while(!validParam(n));
n = 2*n+1;
for(int i=0;i<n;i++){
soma+=(i%2>0?i:0);
}
cout << "[EX01 out] O quadrado de N "<< soma << endl;
}
/*********************************************************************************/
void EX02(void)
{
int ano = 0;
do{
cout << "[EX02 in] Digite um ano: ";
cin >> ano;
}while(!validParam(ano));
if(((ano%4==0) && (ano%100!=0)) || (ano%400==0))
cout << "[EX02 out] Ano Bissexto" << endl;
else
cout << "[EX02 out] Ano no bissexto" << endl;
}
/*********************************************************************************/
void EX03(void)
{
double cabeca=0, pe=0, pato=0,coelho=0;
do{
cout << "[EX03 in] Nmero de cabeas: ";
cin >> cabeca;
cout << "[EX03 in] Nmero de ps: ";
cin >> pe;
}while(!validParam(cabeca,pe));
coelho = pe/2 - cabeca;
pato = 2*cabeca - pe/2;
if(coelho<0 || pato <0)
cout << "[EX03 out] Nmeros de ps e cabeas Invlidos" << endl;
else
cout << "[EX03 out] So "<<pato<<" patos e "<<coelho<< " coelhos."<< endl;
}
/*********************************************************************************/
void EX04(void)
{
char c;
cout << "[EX04 in] Digite um caractere: ";
cin >> c;
if((c>='a')&&(c<='z'))c-=32;
cout << "[EX04 out] " << c << endl;
}
/*********************************************************************************/
void EX05(void)
{
double n=0, n1=1, n2=0, fib=0;
do{
cout << "[EX05 in] Digite o termo da srie de Fibonacci: ";
cin >> n;
}while(!validParam(n));
if (n <= 1){
fib = n;
}
else
for(double i=2;i<=n;i++){
fib = n1 + n2;
n2=n1;
n1=fib;
}
cout << "[EX05 out] O n-simo nmero da srie Fibonacci " << fib << endl;
}
/*********************************************************************************/
void EX06(void)
{
int n=0, tmp=0, inv=0;
cout << "[EX06 in] Digite um nmero inteiro: ";
cin >> n;
tmp=n;
while(tmp != 0){
int digit = tmp%10;
inv = inv*10 + digit;
tmp = tmp/10;
}
cout << "[EX06 out] Seu nmero invertido : " << inv << endl;
cout << "[EX06 out] O nmero " << n << (inv!=n?" no ":" ")<< " palndromo"<< endl;
}
/*********************************************************************************/
void EX07(void)
{
double n=0,fat=1;
do{
cout << "[EX07 in] Digite um nmero inteiro: ";
cin >> n;
}while(!validParam(n));
while(n>0)
fat*=n--;
cout << "[EX07 out] O fatorial do nmero : " << fat << endl;
}
/*********************************************************************************/
void EX08(void)
{
double x=1,e=1;
double i=1;
//cout << "[EX08 in] Digite o valor x : ";
//cin >> x;
while(x>0.000001){
e+=x;
x*=1/(i++);
}
cout << "[EX08 out] A constante e vale: " << e << endl;
}
/*********************************************************************************/
void EX09(void)
{
double pi=0.0;
double termo=4.0;
double denominador=3.0;
bool sinal = true;
do{
pi+=termo;
termo=4.0/(denominador);
termo=(sinal?-termo:termo);
sinal = !sinal;
denominador+=2;
}while(termo>0.000001 ||termo<-0.000001);
cout << "[EX09 out] A constante PI vale: " << pi << endl;
}
/*********************************************************************************/
void EX10(void)
{
int n=0, codificado=0;
int digito[4] ={0,0,0,0};
cout << "[EX10 in] Digite um nmero inteiro: ";
cin >> n;
for(int i=3;i>=0;i--){
digito[i] = ((n%10)+7)%10;
n = n/10;
}
codificado=1000*digito[2]+100*digito[3]+10*digito[0]+digito[1];
cout << "[EX10 out] O nmero codificado "<< setfill('0') << setw(4) << codificado << endl;
}
/*********************************************************************************/
void EX11(void)
{
int n=0, decodificado=0;
int digito[4] ={0,0,0,0};
cout << "[EX11 in] Digite um nmero codificado: ";
cin >> n;
for(int i=3;i>=0;i--){
digito[i] = (((n%10)+10)-7)%10;
n = n/10;
}
decodificado=1000*digito[2]+100*digito[3]+10*digito[0]+digito[1];
cout << "[EX11 out] O nmero decodificado "<< setfill('0') << setw(4) << decodificado << endl;
}
/*********************************************************************************/
void EX12(void)
{
double emprestimo=0,parcela=0,txjuro=0,pmt=0, juros=0;
do{
cout << "[EX12 in] Valor do emprstimo (R$): ";
cin >> emprestimo;
cout << "[EX12 in] Nmero de parcelas: ";
cin >> parcela;
cout << "[EX12 in] Taxa de juros: ";
cin >> txjuro;
txjuro = txjuro/100.0;
}while(!validParam(emprestimo,parcela,txjuro));
cout << "[EX12 out]\t#Parcela\tSaldo Devedor\tAmortizao\tJuros" <<endl;
pmt = (emprestimo*txjuro)/(1-1/pow((1+txjuro),parcela));
for(int i=1; i<=parcela;i++){
juros = emprestimo*txjuro;
double amortizacao = pmt - juros;
emprestimo-=amortizacao;
cout << "[EX12 out]\t" <<i<<"\t\t"<<emprestimo<<"\t\t"<<amortizacao<<"\t\t"<<juros<<endl;
}
}
/*********************************************************************************/
bool validParam(double param1, double param2, double param3){
if (param1 >= 0 && param2 >= 0 && param3 >= 0)
return true;
else{
cout << "Voc digitou parmetro(s) invlido(s)! .. tente novamente." <<endl;
return false;
}
}
bool validParam(double param1, double param2){
if (param1 >= 0 && param2 >= 0)
return true;
else{
cout << "Voc digitou parmetro(s) invlido(s)! .. tente novamente." <<endl;
return false;
}
}
bool validParam(double param1){
if (param1 >= 0)
return true;
else{
cout << "Voc digitou um parmetro invlido! .. tente novamente." <<endl;
return false;
}
}
/*********************************************************************************/
| true |
3370d8b733ba56da7f6aebefe50c4e99c5b5e192 | C++ | Airbroub2019/C- | /TP4/Qt_Calculatrice/qt.cc | UTF-8 | 1,846 | 2.71875 | 3 | [] | no_license | #include "qt.hh"
#include <iostream>
calcul::calcul()
:QWidget() {
resize(450,50);
_operande1 = new QLineEdit("", this);
_operande2 = new QLineEdit("", this);
_operator = new QComboBox(this);
_resultat = new QLabel("",this);
_calculer = new QPushButton("=", this);
_quitter = new QPushButton("Quitter", this);
_operator ->addItem("+");
_operator ->addItem("-");
_operator ->addItem("*");
_operator ->addItem("/");
_operande1 -> setGeometry(10,10,70,30);
_operande2 -> setGeometry(150,10,70,30);
_operator -> setGeometry(90,10,50,30);
_calculer -> setGeometry(230,10,50,30);
_resultat -> setGeometry(290,10,50,30);
_quitter -> setGeometry(350,10,70,30);
connect(_quitter, &QPushButton::clicked, this, &calcul::close);
connect(_calculer, &QPushButton::clicked, this, &calcul::oncliccalculer);
connect(_operande1 , &QLineEdit::textChanged , this , &calcul::oncliccalculer);
connect(_operande2 , &QLineEdit::textChanged , this , &calcul::oncliccalculer);
connect(_operator , &QComboBox::currentTextChanged , this , &calcul::oncliccalculer);
}
void calcul::oncliccalculer() {
float f1(0) , f2(0);
auto v1(_operande1->text().toStdString());
if (!v1.empty())
f1 = std::stof(v1);
auto v2(_operande2->text().toStdString());
if (!v2.empty())
f2 = std::stof(v2);
std::cout << f1 << " " << f2 << std::endl;
auto op(_operator->currentText().toStdString());
float resultat;
switch (_operator->currentText().toStdString()[0]) {
case '+': resultat = f1+f2; break;
case '-': resultat = f1-f2; break;
case '*': resultat = f1*f2; break;
case '/': resultat = f1/f2; break;
}
std::cout << resultat;
_resultat->setText(QString::fromStdString(std::to_string(resultat)));
}
| true |
e54a8c74d78d3e4d07c75e85aff01c55b5d17917 | C++ | brunoalvaro130/URI-C-plus | /URI1065.cpp | UTF-8 | 254 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n;
int val, vez;
val = 0;
for(vez = 1; vez <= 5; vez++){
cin >> n;
if(n%2 == 0){
val = val + 1;
}
}
cout << val << " valores pares" << endl;
return 0;
} | true |
9a0373c39601a05426d8161a492e1d44fc4e421b | C++ | mull-project/mull | /tests/fixtures/mutators/replace_call/junk.cpp | UTF-8 | 848 | 3.296875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #define call_wrap(x) x()
extern "C" int external_function(int a, int b, int c);
extern "C" float external_function_f(float a, float b, float c);
int sum(int x, int b) {
return x + b;
}
int bar();
int foo() {
int r = sum(5, 8);
int s = bar();
int q = call_wrap(bar);
int a = external_function(r, s, q);
int b = external_function_f(r, s, q);
return r + s + q + a + b;
}
class FooBar {
public:
FooBar(int x) : i(x) {}
int getValue() { return i; }
int increment() { return i++; }
int decrement() { return i--; }
private:
int i;
};
struct Buzz {
int x;
int y;
int z;
int w;
};
int bar() {
FooBar fbr(42);
external_function(fbr.increment(), fbr.increment(), fbr.increment());
external_function(fbr.getValue(), 0, 0);
return fbr.decrement();
}
void buzz() {
Buzz b;
Buzz a = b;
Buzz c;
c = a;
}
| true |
d3d8a0b77f04e921c0bbcb9c7178a069797f1d95 | C++ | GabrieleRolleri/competitive_programming | /training-olinfo/convegno/main.cpp | UTF-8 | 973 | 3.09375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
int nFigli(int, std::list<int>*);
int coppie(int N, int C[]);
std::vector<int> under; //sottoposti of every employee
int main() {
std::ifstream in;
in.open("input.txt");
std::ofstream out;
out.open("output.txt");
int N;
in>>N;
under.resize(N);
int te[N];
for(int i=0; i<N; i++){
in>>te[i];
}
std::cout<<coppie(N, te);
return 0;
}
int coppie(int N, int C[]){
std::list<int> adj[N]; //adjancency list of employees
int t;
int pCapo;
for(int i=0; i<N; i++){
t=C[i];
if(t!=-1)
adj[t].push_back(i);
else
pCapo=i;
}
nFigli(pCapo, adj);
int S=0;
for(int i=0; i<N; i++){
S+=under.at(i);
}
return S;
}
int nFigli(int n, std::list<int> *adj){
int S=0;
for(auto it=adj[n].begin(); it!=adj[n].end(); it++){
S+=nFigli((*it), adj)+1;
}
under.at(n)=S;
return S;
}
| true |
e8979fc7eeea25ae06c2cd0275467429efe158ed | C++ | scmikezhang/sqlite_wrapper | /test/test.cpp | UTF-8 | 15,854 | 3 | 3 | [] | no_license | #include "sqlite_wrapper.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
const std::string db_file_path = "./test.db";
class TestSqliteWrapper : public testing::Test
{
public:
SqliteWrapper *sw = nullptr;
void SetUp(void) {
sw = new SqliteWrapper(db_file_path);
}
void TearDown(void) {
if (sw != nullptr) {
delete sw;
sw = nullptr;
}
remove(db_file_path.c_str());
}
};
TEST_F(TestSqliteWrapper, test_create_db)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
}
TEST_F(TestSqliteWrapper, test_create_table)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string sql_str = "num1 INT, str1 TEXT, data BLOB";
std::string table_name = "dummy_1";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
TEST_F(TestSqliteWrapper, test_insert_simple)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
//create table
{
std::string sql_str = "num1 INT, str1 TEXT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//insert a simple entry
{
int src_num = 123456;
std::string src_str = "hello world";
std::string sql_str = "(num1, str1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\")";
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str));
}
}
TEST_F(TestSqliteWrapper, test_peek_simple_ok)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
//create table
{
std::string sql_str = "num1 INT, str1 TEXT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//expect could not be queried, as there is no entry yet
{
std::string sql_str = "num1 = " + std::to_string(src_num);
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
//insert a simple entry
{
std::string sql_str = "(num1, str1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\")";
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str));
}
//expect could be queried, with correct num1
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_TRUE(sw->peek_entry(table_name, sql_str));
}
//expect could be queried, with correct num1 and correct str1
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num) +
" AND str1 = \"" + src_str + "\"";
ASSERT_TRUE(sw->peek_entry(table_name, sql_str));
}
//expect could be queried, with correct num1 or incorrect str1
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num) +
" OR str1 = \"" + std::to_string(654321) + "\"";
ASSERT_TRUE(sw->peek_entry(table_name, sql_str));
}
}
TEST_F(TestSqliteWrapper, test_peek_simple_notexist)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
//create table
{
std::string sql_str = "num1 INT, str1 TEXT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//expect could not be queried, as there is no entry yet
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
//insert a simple entry
{
std::string sql_str = "(num1, str1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\")";
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str));
}
//expect could not be queried, with correct num1 and incorrect str1
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num) +
" AND str1 = \"" + std::to_string(654321) + "\"";
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
}
TEST_F(TestSqliteWrapper, test_delete_simple)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
//create table
{
std::string sql_str = "num1 INT, str1 TEXT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//expect could not be queried, as there is no entry yet
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
//insert a simple entry
{
std::string sql_str = "(num1, str1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\")";
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str));
}
//expect could be queried, with correct num1
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_TRUE(sw->peek_entry(table_name, sql_str));
}
//Delete the entry
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_EQ(0, sw->delete_entry(table_name, sql_str));
}
//expect could not be queried
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
}
TEST_F(TestSqliteWrapper, test_insert_blob)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
std::vector<uint8_t> data = {65, 66, 67, 68, 69, 70};
//create table
{
std::string sql_str = "num1 INT, str1 TEXT, data1 BLOB";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//insert
{
std::string sql_str = "(num1, str1, data1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\", @_p1)"; //place holder variable as _p1
std::map<const std::string, std::vector<uint8_t>*> blobs = {
std::make_pair("@_p1", &data) //should have the same place holder variable name
};
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str, &blobs));
}
}
TEST_F(TestSqliteWrapper, test_get_blob)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
std::vector<uint8_t> src_data = {65, 66, 67, 68, 69, 70};
//create table
{
std::string sql_str = "num1 INT, str1 TEXT, data1 BLOB";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//insert
{
std::string sql_str = "(num1, str1, data1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\", @_p1)"; //place holder variable as _p1
std::map<const std::string, std::vector<uint8_t>*> blobs = {
std::make_pair("@_p1", &src_data) //should have the same place holder variable name
};
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str, &blobs));
}
//get
{
std::string sql_values = "num1, data1";
std::string sql_filter = "WHERE num1 = " + std::to_string(src_num);
int out_num;
std::vector<uint8_t> out_buf;
out_buf.resize(16);
std::vector<SqliteWrapper::GetItem> out = {
SqliteWrapper::GetItem(&out_num, 0),
SqliteWrapper::GetItem(out_buf.data(), out_buf.size())
};
ASSERT_EQ(0, sw->get_entry(out, table_name, sql_values, sql_filter));
//check result
ASSERT_EQ(src_num, out_num);
ASSERT_EQ(0, memcmp(src_data.data(), out_buf.data(), src_data.size()));
}
}
TEST_F(TestSqliteWrapper, test_update_blob)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
std::vector<uint8_t> src_data = {65, 66, 67, 68, 69, 70};
//create table
{
std::string sql_str = "num1 INT, str1 TEXT, data1 BLOB";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//first insert_update, should be insert operation
{
std::string sql_str = "(num1, str1, data1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\", @_p1)"; //place holder variable as _p1
std::map<const std::string, std::vector<uint8_t>*> blobs = {
std::make_pair("@_p1", &src_data) //should have the same place holder variable name
};
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str, &blobs));
}
//first get
{
std::string sql_values = "num1, data1";
std::string sql_filter = "WHERE num1 = " + std::to_string(src_num);
int out_num;
std::vector<uint8_t> out_buf;
out_buf.resize(16);
std::vector<SqliteWrapper::GetItem> out = {
SqliteWrapper::GetItem(&out_num, 0),
SqliteWrapper::GetItem(out_buf.data(), out_buf.size())
};
ASSERT_EQ(0, sw->get_entry(out, table_name, sql_values, sql_filter));
//check result
ASSERT_EQ(src_num, out_num);
ASSERT_EQ(0, memcmp(src_data.data(), out_buf.data(), src_data.size()));
}
//second insert_update, should be update operation
src_data = {31, 32, 33, 34};
{
std::string sql_str = "num1 = " + std::to_string(src_num) +
", data1 = @_p1"; //place holder variable as _p1
std::string sql_filter = "WHERE num1 = " + std::to_string(src_num);
std::map<const std::string, std::vector<uint8_t>*> blobs = {
std::make_pair("@_p1", &src_data) //should have the same place holder variable name
};
ASSERT_EQ(0,sw->update_entry(table_name, sql_str, sql_filter, &blobs));
}
//second get
{
std::string sql_values = "num1, data1";
std::string sql_filter = "WHERE num1 = " + std::to_string(src_num);
int out_num;
std::vector<uint8_t> out_buf;
out_buf.resize(16);
std::vector<SqliteWrapper::GetItem> out = {
SqliteWrapper::GetItem(&out_num, 0),
SqliteWrapper::GetItem(out_buf.data(), out_buf.size())
};
ASSERT_EQ(0, sw->get_entry(out, table_name, sql_values, sql_filter));
//check result
ASSERT_EQ(src_num, out_num);
ASSERT_EQ(0, memcmp(src_data.data(), out_buf.data(), src_data.size()));
}
}
TEST_F(TestSqliteWrapper, test_insert_update_ok)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
int old_src_num = src_num;
std::string src_str = "hello world";
//create table
{
std::string sql_str = "num1 INT, str1 TEXT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//expect could not be queried, as there is no entry yet
{
std::string sql_str = "num1 = " + std::to_string(src_num);
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
//insert a simple entry
{
std::string sql_str_insert = "(num1, str1) VALUES (" +
std::to_string(src_num) + ", \"" + src_str + "\")";
std::string sql_str_update = "num1 = " + std::to_string(src_num) +
", str1 = \"" + src_str + "\"";
std::string sql_str_filter = "WHERE num1 = " + std::to_string(src_num);
ASSERT_EQ(0,sw->insert_update_entry(table_name, sql_str_insert,
sql_str_update, sql_str_filter));
}
//expect could be queried
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_TRUE(sw->peek_entry(table_name, sql_str));
}
{
src_num = 654321;
std::string sql_str_insert = "(num1, str1) VALUES (" +
std::to_string(src_num) + ", \"" + src_str + "\")";
std::string sql_str_update = "num1 = " + std::to_string(src_num) +
", str1 = \"" + src_str + "\"";
std::string sql_str_filter = "WHERE num1 = " + std::to_string(old_src_num);
ASSERT_EQ(0,sw->insert_update_entry(table_name, sql_str_insert,
sql_str_update, sql_str_filter));
}
//expect could be queried, with modified value
{
std::string sql_str = "WHERE num1 = " + std::to_string(src_num);
ASSERT_TRUE(sw->peek_entry(table_name, sql_str));
}
//expect could not be queried, with old value
{
std::string sql_str = "WHERE num1 = " + std::to_string(old_src_num);
ASSERT_FALSE(sw->peek_entry(table_name, sql_str));
}
}
TEST_F(TestSqliteWrapper, test_get_int64)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
int64_t dummy_num = 1565578818000; //a dummy long int
//create table
{
std::string sql_str = "num1 INT, num2 INT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//insert
{
std::string sql_str = "(num1, num2) VALUES (" + std::to_string(src_num) + ", " +
std::to_string(dummy_num) +
")";
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str));
}
//get
{
std::string sql_values = "num2";
std::string sql_filter = "WHERE num1 = " + std::to_string(src_num);
int64_t out_dummy_num = 0;
std::vector<SqliteWrapper::GetItem> out = {
SqliteWrapper::GetItem(&out_dummy_num, sizeof(out_dummy_num)),
};
ASSERT_EQ(0, sw->get_entry(out, table_name, sql_values, sql_filter));
//check result
ASSERT_EQ(dummy_num, out_dummy_num);
}
}
TEST_F(TestSqliteWrapper, test_get_blob_dynamic_alloc)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
int src_num = 123456;
std::string src_str = "hello world";
std::vector<uint8_t> src_data = {65, 66, 67, 68, 69, 70};
//create table
{
std::string sql_str = "num1 INT, str1 TEXT, data1 BLOB";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//insert
{
std::string sql_str = "(num1, str1, data1) VALUES (" + std::to_string(src_num) + ", \"" + src_str +
"\", @_p1)"; //place holder variable as _p1
std::map<const std::string, std::vector<uint8_t>*> blobs = {
std::make_pair("@_p1", &src_data) //should have the same place
};
ASSERT_EQ(0,sw->insert_entry(table_name, sql_str, &blobs));
}
//get
{
std::string sql_values = "num1, data1";
std::string sql_filter = "WHERE num1 = " + std::to_string(src_num);
int out_num;
std::vector<uint8_t> out_buf;
auto copy = [&out_buf](const void* src, uint32_t size) {
out_buf.resize(size);
memcpy(out_buf.data(), src, size);
return 0;
};
std::vector<SqliteWrapper::GetItem> out = {
SqliteWrapper::GetItem(&out_num, 0),
SqliteWrapper::GetItem(nullptr, 0, copy)
};
ASSERT_EQ(0, sw->get_entry(out, table_name, sql_values, sql_filter));
//check result
ASSERT_EQ(src_num, out_num);
ASSERT_EQ(0, memcmp(src_data.data(), out_buf.data(), src_data.size()));
}
}
//place holder
/*
TEST_F(TestSqliteWrapper, test_dummy)
{
ASSERT_TRUE(sw != nullptr);
ASSERT_TRUE(sw->is_ok());
std::string table_name = "dummy_1";
//create table
{
std::string sql_str = "num1 INT, num2 INT, num3 INT";
ASSERT_EQ(0,sw->create_table(table_name, sql_str));
}
//try update empty entry
{
std::string sql_str = "num3 = 99";
std::string sql_filter = "num3 > 1";
ASSERT_EQ(0,sw->update_entry(table_name, sql_str, sql_filter));
}
}
*/
| true |
d04f0d4495b80778f9b83b719c7225805acf8683 | C++ | MaclaurinYudhisthira/MySql-connection-with-c- | /mySQLwithC++/main.cpp | UTF-8 | 631 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include<windows.h>
#include<mysql.h>
using namespace std;
void exeQuery(MYSQL *conn);
int main()
{
cout << "Hello world!" << endl;
MYSQL *conn;
conn=mysql_init(0);
conn=mysql_real_connect(conn,"localhost","USER","PASSWORD","DB_NAME",0, NULL,0);
if(conn)
{
printf("Connected");
exeQuery(conn);
}
else
{
printf("Not Connected");
}
return 0;
}
void exeQuery(MYSQL *conn)
{
string q="create table my_table(name varchar(10),age int)";
const char *query=q.c_str();
mysql_query(conn,query);
}
| true |
fbac06de3b614d66625235d3b356585658687d05 | C++ | nmraz/mparse | /mparse/src/mparse/source_range.h | UTF-8 | 965 | 3.171875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <algorithm>
#include <cstdlib>
namespace mparse {
class source_range {
public:
constexpr source_range() = default;
constexpr explicit source_range(std::size_t col) : from_(col), to_(col + 1) {}
constexpr source_range(std::size_t from, std::size_t to)
: from_(from), to_(to) {}
constexpr std::size_t from() const { return from_; }
constexpr std::size_t to() const { return to_; }
constexpr void set_from(std::size_t from) { from_ = from; }
constexpr void set_to(std::size_t to) { to_ = to; }
static constexpr source_range merge(const source_range& lhs,
const source_range& rhs);
private:
std::size_t from_ = 0;
std::size_t to_ = 0;
};
constexpr source_range source_range::merge(const source_range& lhs,
const source_range& rhs) {
return {std::min(lhs.from(), rhs.from()), std::max(lhs.to(), rhs.to())};
}
} // namespace mparse | true |