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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ba98039de4b2ba432ed1fc831f08063333eeff88 | C++ | marlyhaas/CPE522_FinalExam | /Problem1/readswitch.cpp | UTF-8 | 1,990 | 2.984375 | 3 | [] | no_license | #include <iostream> // for the input/output
#include <stdlib.h> // for the getenv call
#include <sys/sysinfo.h> // for the system uptime call
#include <cgicc/Cgicc.h> // the cgicc headers
#include <cgicc/CgiDefs.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
#define SW_GPIO "/sys/class/gpio/gpio60/"
using namespace std;
using namespace cgicc;
void writeGPIO(string filename, string value){
fstream fs;
string path(SW_GPIO);
fs.open((path + filename).c_str(), fstream::out);
fs << value;
fs.close();
}
string readSwitch(){
ifstream fs;
string path(SW_GPIO);
fs.open((path + "/value").c_str());
string value, line;
while(getline(fs, line)) value = line;
if (value == "1"){
value = "On";
}
else if (value == "0"){
value = "Off";
}
fs.close();
return value;
}
int main(){
Cgicc form; // the CGI form object
string switchVal; // switch value
writeGPIO("direction", "in");
// get the state of the form that was submitted - script calls itself
bool isStatus = form.queryCheckbox("status");
char *value = getenv("REMOTE_ADDR"); // The remote IP address
// generate the form but use states that are set in the submitted form
cout << HTTPHTMLHeader() << endl; // Generate the HTML form
cout << html() << head() << title("CPE522 Final Exam: Reading Digital Input") << head() << endl;
cout << body() << h1("CPE522 Final Exam: Reading Digital Input") << endl;
cout << body() << ("Reading a GPIO Pin via a Web Browser\n") << endl;
cout << "<form action=\"/cgi-bin/readswitch.cgi\" method=\"POST\">\n";
cout << "<input type=\"submit\" value=\"Read Switch\" />";
cout << "</div></form>";
switchVal = readSwitch(); // read switch state and output to form
cout << "<div> The value of the switch is " << switchVal << "</div>";
cout << body() << html();
return 0;
}
| true |
8a4b07b07281f722e9d9b18c4ec676fb14ad3798 | C++ | NeoMopp/Undergrad_Work | /Level 2/Astar Path Finder/SAW11239411_CMP2067M_Item2/A_Star_Algoirthm/Node.h | UTF-8 | 734 | 3.09375 | 3 | [] | no_license | #pragma
#ifndef NODE_H
#define NODE_H
class Node
{
protected:
protected:
double FCost;
double GCost;
double HCost;
double Data;
int x;
int y;
int Parent;
public:
Node(double input_Data);
Node() { FCost = 0; GCost = 0; HCost = 0; Data = 0; x = 0; y = 0; Parent = -1;}
~Node();
Node(const Node& existingNode);
double get_FCost() const;
double get_GCost() const;
double get_HCost() const;
double get_Data() const;
int get_x() const;
int get_y() const;
int get_Parent() const;
const void set_GCost(double G);
const void set_HCost(double H);
const void set_x(int X);
const void set_y(int Y);
const void set_Parent(int K);
const void set_Data(double t) { Data = t;};
bool operator == (const Node& T);
};
#endif | true |
4391521753a33e7b36208d490779b0cbbb80733c | C++ | harry-dev98/CompetitiveCodingSolutions | /Strings/haiku.cpp | UTF-8 | 667 | 2.78125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
string s1, s2, s3;
getline(cin, s1);
getline(cin, s2);
getline(cin, s3);
unordered_set<char> S = {'a', 'e', 'i', 'o', 'u'};
int one = 0;
for(auto ch:s1){
if(S.find(ch) != S.end()){
one++;
}
}
int two = 0;
for(auto ch:s2){
if(S.find(ch) != S.end()){
two++;
}
}
int three = 0;
for(auto ch:s3){
if(S.find(ch) != S.end()){
three++;
}
}
if(one==5 && two==7 && three==5){
cout<<"YES";
}
else{
cout<<"NO";
}
cout<<"\n";
return 0;
} | true |
2cdda71a25b18bbffd1ba893fab0a9bd8e2ad800 | C++ | googol-lab/lang | /c++/tsp.cpp | UTF-8 | 2,131 | 2.984375 | 3 | [] | no_license | #include <cmath>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <limits>
using namespace std;
struct Coord {
int x,y,index;
Coord() : x(0),y(0),index(0){}
bool operator < (const Coord &x) const{
return ((this->y * this->y + this->x * this->x ) < (x.x * x.x + x.y * x.y));
}
};
inline double my_distance(const Coord &r1, const Coord &r2)
{
return sqrt((r1.x-r2.x)*(r1.x-r2.x)+(r1.y-r2.y)*(r1.y-r2.y));
}
template<typename Iterator>
inline double sum_distance(Iterator s, Iterator e){
double sum = 0.0;
for(Iterator i=s;i!=(e-1);i++){
sum += my_distance(*i,*(i+1));
}
sum += my_distance(*s,*(e-1));
return sum;
}
int main()
{
#ifdef L
const static int num = 16384;
#else
const static int num = 128;
#endif
Coord data[num],ans[num],cons[num];
for(int i=0;i<num;i++){
cin >> data[i].x >> data[i].y;
data[i].index = i;
}
copy(&data[0],&data[num],&cons[0]);
// sort(&data[0],&data[num]);
double min_distance = numeric_limits<double>::max();
for(int it=0;it<128;it++){
copy(&cons[0],&cons[num],&data[0]);
swap(data[0],data[it]);
for(int i=1;i<num+1;i++){
double min = numeric_limits<double>::max();
int index = i;
for(int j=i;j<num;j++){
double buf = my_distance(data[i-1],data[j]);
if(min > buf){
min = buf;
index = j;
}
}
swap(data[i],data[index]);
}
double buf = sum_distance(&data[0],&data[num]);
if(min_distance >buf){
min_distance = buf;
copy(&data[0],&data[num],&ans[0]);
}
}
srandom(time(0));
for(int i=0;i<100000;i++){
int r1 = static_cast<int>(double(random())/RAND_MAX*num);
int r2 = static_cast<int>(double(random())/RAND_MAX*num);
swap(ans[r1],ans[r2]);
double buf = sum_distance(&ans[0],&ans[num]);
if(min_distance > buf){
min_distance = buf;
}
else{
swap(ans[r1],ans[r2]);
}
}
for(int i=0;i<num;i++){
cout << ans[i].x << " " << ans[i].y << " " << ans[i].index << '\n';
}
cout << ans[0].x << " " << ans[0].y << " " << ans[0].index << endl;
cerr << min_distance << endl;
return 0;
}
| true |
93fc93fdb3bbf69f322b64ed8063e0b4b9ca4314 | C++ | SoPlump/POO2 | /src/Collection.h | UTF-8 | 3,809 | 3.046875 | 3 | [] | no_license | /*************************************************************************
Collection - description
-------------------
debut : 14 decembre 2018
copyright : (C) 2018 par CERBA, RAUDRANT
e-mail : guilhem.cerba@insa-lyon.fr, sophie.raudrant@insa-lyon.fr
*************************************************************************/
//---------- Interface de la classe <Collection> (fichier Collection.h) ----------------
#if ! defined ( Collection_H )
#define Collection_H
//--------------------------------------------------- Interfaces utilisees
#include "Trajet.h"
#include <cstring>
//------------------------------------------------------------- Constantes
//------------------------------------------------------------------ Types
typedef unsigned int uint;
//------------------------------------------------------------------------
// Role de la classe <Collection>
// Structure de donnees permettant de stocker des Trajets
// L'ajout dynamique est possible et est gere
// Propose plusieurs services sur les Trajets
//------------------------------------------------------------------------
class Collection
{
//----------------------------------------------------------------- PUBLIC
public:
//----------------------------------------------------- Methodes publiques
void Afficher(const char prefixe = '\0') const;
// Mode d'emploi :
// Parcours tous les Trajets de la collection et appelle leur fonction Afficher()
// -> prefixe peut servir a ajouter un character avant l'affichage de chaque Trajet , comme par exemple un \t
void AjouterTrajet(Trajet*);
// Mode d'emploi :
// Ajoute un Trajet* a la Collection courante
// Si la capacite maximale de la Collection est atteinte alors une nouvelle Collection de taille maximale egale au double
// de la taille maximale de la premiere collection est creee. Dedans on copie la premiere Collection. Cette nouvelle Collection remplace la premiere.
void DepilerTrajet();
// Mode d'emploi :
// Supprime le dernier trajet ajoute dans la Collection
// Decremente le nombre de Trajets presents dans la Collection ( m_nbTrajet )
// Contrat :
// On suppose qu'on ne depile jamais une Collection vide (sans Trajets)
bool isCityIn(const char * cityName) const;
// Mode d'emploi :
// Retourne True si la ville cityName est presente en tant que ville d'arrivee ou de depart d'un Trajet de la Collection
// Sinon retourne False
Collection* GetTrajetsFrom(const char * villeDepart) const;
// Mode d'emploi :
// Renvoie la liste des Trajets presents dans la Collection dont la ville de depart correspond a villeDepart
Collection* RechercheSimple(const char * villeDepart, const char * villeArrivee) const;
// Mode d'emploi :
// Parcours la liste des Trajets de Collection, renvoie la liste des Trajets dont
// -> la ville de depart correspond a villeDepart
// -> la ville d'arrivee correspond a villeArrivee
// La combinaison de Trajets n'est PAS permise
uint GetNbTrajet() const;
// Mode d'emploi :
// Retourne la valeur de m_nbTrajet
Trajet** GetListeTrajet();
// Mode d'emploi :
// Retourne m_listeTrajet
//-------------------------------------------- Constructeurs - destructeur
Collection(uint taille = 10);
//Cree une Collection de taille initiale 'taille'
Collection(Collection const& model);
//Constructeur par copie
virtual ~Collection();
//------------------------------------------------------------------ PRIVE
protected:
//----------------------------------------------------- Methodes protegees
//----------------------------------------------------- Attributs proteges
Trajet** m_listeTrajet; // Liste de pointeurs de Trajets
uint m_nbTrajet; // Nombre de Trajets dans la Collection
uint m_cardMax; // Nombre de Trajets maximal pouvant etre dans la Collection
};
#endif // Collection_H
| true |
bd9805177d6d428a72b7850eb08007b86d5c0297 | C++ | graybriggs/00s-engine | /shape_generator.h | UTF-8 | 1,007 | 2.546875 | 3 | [] | no_license | #pragma once
#ifndef SHAPEGENERATOR_H
#define SHAPEGENERATOR_H
#include <glew.h>
#include <gl/GL.h>
#include <gl/GLU.h>
#include <GLFW/glfw3.h>
#include <vector>
#include "vertex.h"
struct ShapeData {
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
};
class ShapeGenerator {
static ShapeData makePlaneVerts(int dimensions);
static ShapeData makePlaneIndices(int dimensons);
public:
static ShapeData makeTriangle();
static ShapeData makeRectangle();
static ShapeData makeQuad();
static ShapeData makeCube();
static ShapeData makeCircle(int subdivisions = 5);
static ShapeData makeSphere(int subdivisions = 5);
static ShapeData makeCone(int subdivisions = 5);
static ShapeData makeTorus();
static ShapeData makePlane(int dimensions, GLfloat step = 1.0f);
static ShapeData makeModel(const char* path);
static std::vector<GLfloat> extractVertices(const std::vector<Vertex>& vertices);
static std::vector<GLfloat> extractColors(const std::vector<Vertex>& colors);
};
#endif
| true |
046398a0309f8905bdf17ccd3145d1e5cb2a521d | C++ | mpublic/CPP | /PROGRAMMING_WITH_CPP Osman_AY Muhammed_Akif_HORASANLI/CH1 Introduction To Programming/Programms/24 Int code to ascii char.cpp | UTF-8 | 451 | 3.546875 | 4 | [] | no_license | /*
PROG: ASCIItoChar.cpp
DESCRIPTION: Convert ASCII Code to corresponding Character.
*/
#include<iostream>
using namespace std;
int main()
{
int code;
// get code from user
cout<<"Enter the ASCII code [0 - 127]: ";
cin>> code;
// use (char) casting to convert and show character
cout<<"\nThe corresponding character from the ASCII code "
<<code<<" is: "<<(char)code<<endl<<endl;
system("PAUSE");
return 0;
}
| true |
e740b310a16c76cca3684921575a2ec8595d4363 | C++ | kanpurin/kyoprolibrary | /graph/chromaticnumber.hpp | UTF-8 | 1,782 | 2.6875 | 3 | [] | no_license | #ifndef _CHROMATIC_NUMBER_HPP_
#define _CHROMATIC_NUMBER_HPP_
#include <vector>
// 単純無向グラフの彩色数
// G:隣接行列 O(N2^N)
int chromatic_number(std::vector<std::vector<int>> &G) {
auto powMod = [](long long k, long long n, long long mod) {
long long x = 1;
while (n > 0) {
if (n & 1) {
x = x * k % mod;
}
k = k * k % mod;
n >>= 1;
}
return x;
};
int n = G.size();
std::vector<int> neighbor(n, 0);
for (int i = 0; i < n; ++i) {
int S = (1<<i);
for (int j = 0; j < n; ++j)
if (G[i][j]) S |= (1<<j);
neighbor[i] = S;
}
std::vector<int> I(1<<n);
I[0] = 1;
for (int S = 1; S < (1<<n); ++S) {
int v = __builtin_ctz(S);
I[S] = I[S & ~(1<<v)] + I[S & ~neighbor[v]];
}
long long MOD1 = 998244353;
long long MOD2 = 1e9+7;
long long MOD3 = 1e9+9;
int l = 0, r = n;
while (r - l > 1) {
int mid = (l + r) >> 1;
long long g1 = 0;
long long g2 = 0;
long long g3 = 0;
for (int S = 0; S < (1<<n); ++S) {
if ((n - __builtin_popcount(S)) & 1) {
g1 -= powMod(I[S], mid, MOD1);
g2 -= powMod(I[S], mid, MOD2);
g3 -= powMod(I[S], mid, MOD3);
}
else {
g1 += powMod(I[S], mid, MOD1);
g2 += powMod(I[S], mid, MOD2);
g3 += powMod(I[S], mid, MOD3);
}
g1 = (g1 % MOD1 + MOD1) % MOD1;
g2 = (g2 % MOD2 + MOD2) % MOD2;
g3 = (g3 % MOD3 + MOD3) % MOD3;
}
if (g1 != 0 && g2 != 0 && g3 != 0) r = mid;
else l = mid;
}
return r;
}
#endif | true |
f24e36a93a4ed84b70592980b16055c7e300fce5 | C++ | ShravanCool/spoj-classical | /EvaluateThePolynomial.cpp | UTF-8 | 619 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
long long horner(vector<long long>& poly, long long x) {
long long sum = poly[0];
for(long long i = 1; i < poly.size(); i++)
sum = sum*x + poly[i];
return sum;
}
int main() {
long long nCase = 1;
while(true) {
long long N, Q;
cin >> N;
if(N == -1) break;
vector<long long> poly(N+1);
for(int i = 0; i <= N; i++)
cin >> poly[i];
cin >> Q;
cout << "Case " << nCase++ << ":\n";
for(int i = 0; i < Q; i++) {
long long x;
cin >> x;
cout << horner(poly, x) << endl;
}
}
return 0;
}
| true |
02e8d635bcbfed65975dcacaf84acf383c2e18d3 | C++ | madMAx43v3r/mmx-node | /src/vm/StorageProxy.cpp | UTF-8 | 1,661 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | /*
* StorageProxy.cpp
*
* Created on: Apr 24, 2022
* Author: mad
*/
#include <mmx/vm/StorageProxy.h>
namespace mmx {
namespace vm {
StorageProxy::StorageProxy(std::shared_ptr<Storage> backend, bool read_only)
: backend(backend),
read_only(read_only)
{
}
std::unique_ptr<var_t> StorageProxy::read_ex(std::unique_ptr<var_t> var) const
{
if(var) {
if(var->flags & FLAG_DELETED) {
var.reset();
}
}
if(var) {
var->flags &= ~FLAG_DIRTY;
var->flags |= FLAG_STORED;
if(read_only) {
var->flags |= FLAG_CONST;
}
}
return std::move(var);
}
std::unique_ptr<var_t> StorageProxy::read(const addr_t& contract, const uint64_t src) const
{
return read_ex(backend->read(contract, src));
}
std::unique_ptr<var_t> StorageProxy::read(const addr_t& contract, const uint64_t src, const uint64_t key) const
{
return read_ex(backend->read(contract, src, key));
}
void StorageProxy::write(const addr_t& contract, const uint64_t dst, const var_t& value)
{
if(read_only) {
throw std::logic_error("read-only storage");
}
if((value.flags & FLAG_KEY) && !(value.flags & FLAG_CONST)) {
throw std::logic_error("keys need to be const");
}
backend->write(contract, dst, value);
}
void StorageProxy::write(const addr_t& contract, const uint64_t dst, const uint64_t key, const var_t& value)
{
if(read_only) {
throw std::logic_error("read-only storage");
}
if(value.ref_count) {
throw std::logic_error("entries cannot have ref_count > 0");
}
backend->write(contract, dst, key, value);
}
uint64_t StorageProxy::lookup(const addr_t& contract, const var_t& value) const
{
return backend->lookup(contract, value);
}
} // vm
} // mmx
| true |
bdf703a70c25ac7e5245a1c0cc7dc91226c8b4d3 | C++ | stoyanov624/OOP_2020_2021_IS_GR4 | /Week13/livecode/Square.h | UTF-8 | 617 | 3.515625 | 4 | [] | no_license | #pragma once
#include "Shape.h"
class Square : public Shape {
private:
double a;
public:
Square() {
a = 0;
}
Square(double _a) : a(_a) {}
void printPerimeter() const override {
std::cout << "square perimeter: " << 4.0 * a << std::endl;
}
void printArea() const override {
std::cout << "squre area: " << a * a << std::endl;
}
void read(std::ostream& out) override {
out << "square\n";
out << "Side A: " << a << "\n";
}
void load(std::istream& in) override {
std::cout << "Enter square side: ";
in >> a;
}
};
| true |
b15878267723e881b6d8fbdbbb55ee23a1d04f37 | C++ | YannGarcia/repo | /dev/g++/projects/embedded/comm/include/ipvx_address.hh | UTF-8 | 2,606 | 3.171875 | 3 | [
"MIT"
] | permissive | /**
* \file ipvx_address.h
* \brief Header file for IPv4/IPv6 address abstraction.
* \author garciay.yann@gmail.com
* \copyright Copyright (c) 2015 ygarcia. All rights reserved
* \license This project is released under the MIT License
* \version 0.1
*/
#pragma once
#include <string>
#include <vector>
namespace comm {
namespace network {
/**
* \class ipvx_address (abstract)
* \brief This class implements abstraction for IPv4/IPv6 address management
*
* \see ipv4_address
* \see ipv6_address
*/
class ipvx_address {
public:
virtual ~ipvx_address() { };
/**
* \brief Indicate the IP address type
* \return true if the IP address is IPv4, false otherwise
*/
virtual const bool is_ipv4() const = 0;
/**
* \brief Indicate the IP address type
* \return true if the IP address is IPv6, false otherwise
*/
virtual const bool is_ipv6() const = 0;
/**
* \brief Indicate the IP address is a multicast address
* \return true if the IP address is a multicast address , false otherwise
*/
virtual const bool is_multicast() const = 0;
/**
* \brief Indicate the IP address is a broadcast address
* \return true if the IP address is a broadcast address , false otherwise
*/
virtual const bool is_broadcast() const = 0;
/**
* \brief Indicate the IP address is a localhost address
* \return true if the IP address is a localhost address , false otherwise
*/
virtual const bool is_localhost() const = 0;
/**
* \brief Retrieve the socket address information (struct in_address * for IPv4 or struct in6_address * for IPv6)
* \return The socket address information on success, NULL otherwise
*/
virtual const void * addr() const = 0;
/**
* \brief Retrieve the length of the socket address information data structure
* \return The length of the socket address information data structure
*/
virtual size_t length() const = 0;
/**
* \brief Retrieve the socket address in string format
* \return The socket address in string format
*/
virtual std::string to_string() const = 0;
/**
* \brief Retrieve the socket address in byte format
* \return The socket address in byte format
*/
virtual std::vector<uint8_t> to_numeric() const = 0;
}; // End of class ipvx_address
} // End of namespace network
} // End of namespace comm
using namespace comm::network;
| true |
4920a305d19bd0e8732100b1695dc8673772e5e0 | C++ | Zedtho/Iterated-Prisoner-s-Dilemma | /Simulation Reciprocal Altruism/Simulation Reciprocal Altruism.cpp | UTF-8 | 5,882 | 3.09375 | 3 | [] | no_license | // Simulation Reciprocal Altruism.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Simulation Reciprocal Altruism.h"
#include<time.h>
#include <random>
int main()
{
//Requests starting parameters of simulation.
InitializeInputs();
//Round-Organizer
for (int Generation = 0; Generation < AmountGenerations; ++Generation)
{
InitializeAgents();
for (int Round = 0; Round < AmountRounds; ++Round)
{
Meet();
TallyAndOutput();
}
//Calculate who was most successful, and distribute new guys accordingly.
int FinalAmountCoop = 0;
int FinalAmountDef = 0;
int FinalAmountTFT = 0;
int FinalAmountCrossEye = 0;
int FinalAmountTF2T = 0;
for (unsigned int i = 0; i < Agents.size(); ++i)
{
switch (Agents[i]->GetStrategy())
{
case Agent::Strategy::COOPERATOR:
FinalAmountCoop += Agents[i]->GetScore();
break;
case Agent::Strategy::DEFECTOR:
FinalAmountDef += Agents[i]->GetScore();
break;
case Agent::Strategy::TFT:
FinalAmountTFT += Agents[i]->GetScore();
break;
case Agent::Strategy::CROSSEYE:
FinalAmountCrossEye += Agents[i]->GetScore();
break;
case Agent::Strategy::TF2T:
FinalAmountTF2T += Agents[i]->GetScore();
}
}
/*const int CumulativeScore = FinalAmountCoop + FinalAmountDef + FinalAmountTFT + FinalAmountCrossEye + FinalAmountTF2T;
InitAmountCoop = std::floor(FinalAmountCoop / CumulativeScore);
InitAmountDef = std::floor(FinalAmountDef / CumulativeScore);
InitAmountTFT = std::floor(FinalAmountTFT / CumulativeScore);
InitAmountCrossEye = std::floor(FinalAmountCrossEye / CumulativeScore);
InitAmountTF2T = std::floor(FinalAmountTF2T / CumulativeScore);
while (Agents.size() != InitAmountCoop + InitAmountDef + InitAmountTFT + InitAmountCrossEye + InitAmountTF2T)
{
InitAmountCoop++; //Find a better way to do that
}
KillOff();*/
}
std::cout << "\n Final amount of agents of each type is: \n" << InitAmountCoop << "/" << InitAmountTFT << "/" <<
InitAmountDef << "/" << InitAmountCrossEye << "/" << InitAmountTF2T;
std::cout << "\n Thank you for using our simulation";
int WaitForInput;
std::cin >> WaitForInput;
KillOff();
return 0;
}
void InitializeInputs()
{
std::cout << "Insert the amount of starting cooperators \n";
std::cin >> InitAmountCoop;
std::cout << " \n" << "Insert the amount of starting Tit-for-tatters \n";
std::cin >> InitAmountTFT;
std::cout << " \n" << "Insert the amount of starting Defectors \n";
std::cin >> InitAmountDef;
std::cout << " \n" << "Insert the amount of starting CrossEyes \n";
std::cin >> InitAmountCrossEye;
std::cout << " \n" << "Insert the amount of starting Tit-for-two-tatters \n";
std::cin >> InitAmountTF2T;
std::cout << " \n" << "How many rounds should every generation have? \n";
std::cin >> AmountRounds;
std::cout << "\n" << "How many total generations until the simulation terminates? \n";
std::cin >> AmountGenerations;
}
void InitializeAgents()
{
for (int i = 0; i < InitAmountCoop; ++i)
{
Agents.push_back(new Cooperator);
}
for (int i = 0; i < InitAmountTFT; ++i)
{
Agents.push_back(new TFT);
}
for (int i = 0; i < InitAmountDef; ++i)
{
Agents.push_back(new Defector);
}
for (int i = 0; i < InitAmountCrossEye; ++i)
{
Agents.push_back(new CrossEye);
}
for (int i = 0; i < InitAmountTF2T; ++i)
{
Agents.push_back(new TF2T);
}
}
void TallyAndOutput()
{
int AmountCoop = 0;
int AmountDef = 0;
int AmountTFT = 0;
int AmountCrossEye = 0;
int AmountTF2T = 0;
for (unsigned int i = 0; i < Agents.size(); ++i)
{
switch (Agents[i]->GetStrategy())
{
case Agent::Strategy::COOPERATOR:
AmountCoop += Agents[i]->GetScore();
break;
case Agent::Strategy::DEFECTOR:
AmountDef += Agents[i]->GetScore();
break;
case Agent::Strategy::TFT:
AmountTFT += Agents[i]->GetScore();
break;
case Agent::Strategy::CROSSEYE:
AmountCrossEye += Agents[i]->GetScore();
break;
case Agent::Strategy::TF2T:
AmountTF2T += Agents[i]->GetScore();
}
}
std::cout << "\n" << AmountCoop << "/" << AmountTFT << "/" << AmountDef << "/" << AmountCrossEye << "/" << AmountTF2T;
}
void Meet()
{
std::uniform_int_distribution<int> distAlive(0, Agents.size() - 1);
for (int i = 0; i < std::floor(Agents.size()*nMeetingsProportion); ++i)
{
srand((unsigned int)time(NULL));
unsigned int FirstCandidateNumber = distAlive(rng);
unsigned int SecondCandidateNumber = distAlive(rng);
while (FirstCandidateNumber == SecondCandidateNumber)
{
SecondCandidateNumber = rand() % Agents.size();
} //playing against itself is normally a possibility within game theory as well, but personally I find it makes no sense. It gives rather unintuitive results.
bool WillFirstCoop = Agents[FirstCandidateNumber]->WillCooperate(Agents[SecondCandidateNumber]);
bool WillSecondCoop = Agents[SecondCandidateNumber]->WillCooperate(Agents[FirstCandidateNumber]);
//The actual meeting
switch (WillFirstCoop)
{
case true:
if (WillSecondCoop)
{
Agents[FirstCandidateNumber]->score += reward;
Agents[SecondCandidateNumber]->score += reward;
}
else
{
Agents[FirstCandidateNumber]->score += suckersPayoff;
Agents[SecondCandidateNumber]->score += temptation;
}
break;
case false:
if (WillSecondCoop)
{
Agents[FirstCandidateNumber]->score += temptation;
Agents[SecondCandidateNumber]->score += suckersPayoff;
}
else
{
Agents[FirstCandidateNumber]->score += punishment;
Agents[SecondCandidateNumber]->score += punishment;
}
break;
}
//Update strategies
Agents[FirstCandidateNumber]->Update(Agents[SecondCandidateNumber], WillSecondCoop);
Agents[SecondCandidateNumber]->Update(Agents[FirstCandidateNumber], WillFirstCoop);
}
}
void KillOff()
{
for (size_t i = 0; i < Agents.size(); i++)
{
delete Agents[i];
}
}
| true |
76033cbc1422fe044dc6d6817f6e1c1c2ec2eb3b | C++ | ayanami98/leetcode | /hard/4_Median_of_Two_Sorted_Arrays.cpp | UTF-8 | 2,125 | 3.6875 | 4 | [] | no_license | /******
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
******/
class Solution {
public:
using iterator = std::vector<int>::iterator;
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int sz1 = nums1.size();
int sz2 = nums2.size();
if (sz1 == 0 && sz2 == 0) {
return 0;
} else if (sz1 == 0) {
return (sz2 % 2 == 1) ? nums2[sz2 / 2] : (nums2[sz2 / 2 - 1] + nums2[sz2 / 2]) / 2.0;
} else if (sz2 == 0) {
return (sz1 % 2 == 1) ? nums1[sz1 / 2] : (nums1[sz1 / 2 - 1] + nums1[sz1 / 2]) / 2.0;
}
int total_size = sz1 + sz2;
if (total_size & 0x1) {
return topK(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), total_size / 2 + 1);
} else {
return topK(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), total_size / 2) / 2 +
topK(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), total_size / 2 + 1) / 2;
}
}
private:
double topK(iterator s1, iterator e1, iterator s2, iterator e2, int k) {
// cout << *s1 << ", " << *e1 << " -- " << *s2 << ", " << *e2 << " --- " << k << endl;
if (s1 == e1) {
return *(s2 + k - 1);
} else if (s2 == e2) {
return *(s1 + k - 1);
}
int distance = std::distance(s1, e1);
auto mid = s1 + distance / 2;
auto it2 = upper_bound(s2, e2, *mid);
int distance2 = std::distance(s2, it2);
int total_num = distance / 2 + 1 + distance2;
// cout << "mid = " << *mid << ":" << total_num << endl;
if (total_num == k) {
return *mid;
} else if (total_num > k) {
return topK(s1, mid, s2, it2, k);
} else {
return topK(mid + 1, e1, it2, e2, k - total_num);
}
}
};
| true |
87d22e9c06109041347ec6cac9bcc2d05bd2b1b7 | C++ | gottschalkbrigid89/netwars | /src/game/player.h | UTF-8 | 2,622 | 3.34375 | 3 | [] | no_license | #ifndef AW_PLAYER_H
#define AW_PLAYER_H
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include "units/units.h"
#include "terrain.h"
#include <map>
#include <stdexcept>
namespace aw
{
class player
{
public:
typedef boost::shared_ptr<player> ptr;
enum colors { RED, BLUE, GREEN, YELLOW, BLACK };
player(colors c);
colors get_color() const {
return m_color;
}
int get_funds() const {
return m_funds;
}
void set_funds(unsigned int funds) {
m_funds = funds;
}
void subtract_funds(unsigned int funds) {
if(static_cast<int>(m_funds - funds) < 0)
throw std::runtime_error("Not enough funds");
m_funds -= funds;
}
void add_funds(unsigned int funds) {
m_funds += funds;
}
unit::colors get_unit_color() const;
bool his_unit(const unit::ptr &u) const {
return (u->color() == this->get_unit_color());
}
terrain::extras get_building_color() const;
bool his_building(const terrain::ptr &p) const {
assert(p->is_building());
return (p->extra() == this->get_building_color());
}
void start_turn();
void end_turn();
bool has_units() const {
return m_has_units;
}
void has_units(bool u) {
m_has_units = u;
}
std::string get_color_string() const;
void print(std::ostream &o) const;
private:
int m_funds; //should not be negative
// int m_funds_per_turn;
const colors m_color;
bool m_has_units;
};
class player_manager
{
public:
typedef std::vector<player::ptr> container_t;
void add(const player::ptr &p) {
m_players.push_back(p);
}
void erase(const player::ptr &p) {
container_t::iterator it = std::find(m_players.begin(),
m_players.end(),
p);
assert(it != m_players.end());
m_players.erase(it);
}
void set_first_player(std::size_t index) {
m_active_player = m_players.begin()+index;
}
void set_first_player(const player::ptr& p) {
container_t::iterator it = std::find(m_players.begin(),
m_players.end(),
p);
assert(it != m_players.end());
m_active_player = it;
}
player::ptr &get_active_player() {
return *m_active_player;
}
void next() {
if(m_active_player+1 != m_players.end())
m_active_player++;
else
m_active_player = m_players.begin();
}
player::ptr at(std::size_t index) {
return m_players[index];
}
container_t &get_players() {
return m_players;
}
const container_t &get_players() const {
return m_players;
}
private:
container_t m_players;
container_t::iterator m_active_player;
};
std::ostream &operator<<(std::ostream &o, const player &p);
}
#endif
| true |
907fca4ca84134aed431d114f00dabe1af7c825d | C++ | jtrugman/dynamic-memory-charlesbethin-justintrugman | /WriteSTL/Design.hh | UTF-8 | 553 | 3.09375 | 3 | [] | no_license | #pragma once
#include "vector"
#include "iostream"
#include <fstream>
using namespace std;
class Design {
private:
vector<const Shape*> shapes;
public:
void add(const Shape& s) {
shapes.push_back(&s);
}
void write(string file) const {
ofstream f;
f.open(file);
for(int i=0;i<shapes.size();i++){
f << "solid Shape" << std::to_string(i) << '\n';
f << shapes[i]->stl() << '\n';
f<<"endsolid Shape" << std::to_string(i) <<'\n';
}
f.close();
}
}; | true |
85998ce1ae05d55d356cd25a0d548b02f776adad | C++ | banspatel58/Expressions-evaluator | /Unary_Expr_Node.h | UTF-8 | 1,074 | 2.703125 | 3 | [] | no_license | //==============================================================================
/**
* Honor Pledge:
*
* I pledge that I have neither given nor received any help
* on this assignment.
*/
//==============================================================================
#ifndef _UNARY_EXPR_NODE_H_
#define _UNARY_EXPR_NODE_H_
#include "Operator_Node.h"
/**
* @class Unary_Expr_Node
*
* Basic implementation of a standard Unary_Expr_Node for all kinds of binary
* expressions.
*/
class Unary_Expr_Node
: public Operator_Node
{
public:
/// Default constructor.
Unary_Expr_Node (void);
/// Destructor.
virtual ~Unary_Expr_Node(void);
/**
* Defines a pure virutal method called evaluate. Since each operator has its
* own method to evaluate an expression, Unary_Expr_Node does not define the
* method instead each and every operator(child) is forced to define its own method.
*/
virtual int execute(void);
virtual int get_Precedence() = 0;
protected:
Expr_Node * child_;
};
#include "Unary_Expr_Node.cpp"
#endif // !defined _UNARY_EXPR_NODE_H_
| true |
838b4b3be9a9f75d20433b802785c009950a5e51 | C++ | Moviw/C--_primer-_plus | /11.使用类/Complex类/complex0.cpp | UTF-8 | 1,467 | 3.078125 | 3 | [] | no_license | /************************************************
* @Author: Movix
* @Date: 2021-09-21 13:10:45
* @LastEditTime: 2021-09-22 02:36:28
* @Github: https://github.com/Moviw
* @FilePath: /C--_primer-_plus/11.使用类/Complex类/complex0.cpp
* @Description:
************************************************/
#include <iostream>
#include <cmath>
#include "complex0.h"
using namespace std;
Complex::Complex()
{
x = 0;
y = 0;
}
Complex::Complex(double n1, double n2)
{
this->x = n1;
this->y = n2;
}
//运算符重载
// Complex Complex::operator+(const Complex &c) const
// {
// return Complex(this->x + c.x, this->y + c.y);
// }
// Complex Complex::operator-(const Complex &c) const
// {
// return Complex(this->x - c.x, this->y - c.y);
// }
// Complex Complex::operator*(const double n) const
// {
// return Complex(this->x * n, this->y * n);
// }
// Complex Complex::operator*(const Complex &c) const
// {
// return Complex(this->x * c.x - this->y * c.y, this->x * c.y + this->y * c.x);
// }
// Complex Complex::operator~() const
// {
// return Complex(this->x, -this->y);
// }
// // //友元函数
// Complex operator*(const Complex &c, const double n)
// {
// return c * n;
// }
// ostream &operator<<(ostream &cout, Complex &c) //TODO
// {
// cout << "(" << c.x << "," << c.y << "i)";
// return cout;
// }
// istream &operator>>(istream &cin, Complex &c)
// {
// cin >> c.x >> c.y;
// return cin;
// } | true |
a293ef69b79d66c789c3c21982bb0a553567e153 | C++ | razor1111/LP2 | /8.cpp | UTF-8 | 532 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | #include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int vet[10];
int w [10];
void entrada()
{
for(int i = 0 ; i < 10; i++)
{
printf("Insira o %d valor do vetor ", i + 1);
scanf("%d", &vet[i]);
}
}
int fatorial(int n)
{
if ((n == 1) || (n == 0)) {
return 1;
}else{
return fatorial(n - 1) * n;
}
}
void saidaW()
{
for(int i = 0 ; i<10;i++){
w[i] = fatorial(vet[i]);
}
for(int i = 0 ; i<10;i++){
printf("{%d}\n",w[i]);
}
}
int main(int argc, char** argv)
{
entrada();
saidaW();
return 0;
}
| true |
2904746b8fe41de25151954ba3f36b491463d05a | C++ | cosmin-ionita/File-System-Manager | /File-System-Manager/File.h | UTF-8 | 641 | 3.234375 | 3 | [] | no_license | #ifndef FILE_H
#define FILE_H
#include <string>
using namespace std;
class File
{
public:
File(string owner_name, string file_name, int file_dimension)
{
name = file_name;
dimension = file_dimension;
owner = owner_name;
type = "SHARED";
}
File(string owner_name, string file_name, int file_dimension, string file_type)
{
name = file_name;
dimension = file_dimension;
owner = owner_name;
type = file_type;
}
bool operator==(const File file); // Overload this op for the "remove" method from STL
int dimension;
string name;
string owner;
string type; // private / shared
};
#endif | true |
736d713475e29aab851aca8767fa4c8089e36d27 | C++ | LauraDiosan-CS/lab8-11-polimorfism-diacata05 | /lab8-11/Data.cpp | UTF-8 | 2,499 | 3.296875 | 3 | [] | no_license | #include "Data.h"
#include <iostream>
using namespace std;
/*
descr: constructor implicit
in: -
out: entitate Data
*/
Data::Data() {
zi = 1;
luna = 1;
an = 2000;
}
/*
descr: constructor cu parametrii
in: integer z, integer l, interger a
out: entitate data cu parametrii setati
*/
Data::Data(int z, int l, int a) {
this->zi = z;
this->luna = l;
this->an = a;
}
/*
descr: constructor de copiere
in: ref entitate Data
out: entitate Data
*/
Data::Data(const Data& d) {
this->zi = d.zi;
this->luna = d.luna;
this->an = d.an;
}
/*
descr: destructor
in: -
out: -
*/
Data::~Data() {}
/*
descr: getter pentru atributul zi
in: -
out: integer - atribitul zi al entitatii
*/
int Data::getZi() {
return zi;
}
/*
descr: getter pentru atributul luna
in: -
out: integer - atribitul luna al entitatii
*/
int Data::getLuna() {
return luna;
}
/*
descr: getter pentru atributul an
in: -
out: integer - atribitul an al entitatii
*/
int Data::getAn() {
return an;
}
/*
descr: setter pentru atribitul zi
in: integer z
out: -
*/
void Data::setZi(int z) {
if (z > 0 && z <= 31) {
zi = z;
}
else {
zi = 1;
}
}
/*
descr: setter pentru atribitul luna
in: integer l
out: -
*/
void Data::setLuna(int l) {
if (l > 0 && l <= 12) {
luna = l;
}
else {
luna = 1;
}
}
/*
descr: setter pentru atribitul an
in: integer a
out: -
*/
void Data::setAn(int a) {
if (a > 0 && a < 2030) {
an = a;
}
else {
an = 2020;
}
}
/*
descr: operator >
in: Data& d;
out: bool
*/
bool Data::operator==(const Data& d) {
return this->zi == d.zi && this->luna == d.luna && this->an == d.an;
}
Data& Data::operator=(const Data& d) {
if (this != &d) {
this->zi = d.zi;
this->luna = d.luna;
this->an = d.an;
}
return *this;
}
char* Data::toString() {
char* s = new char[10];
char* zi = new char[3];
char* luna = new char[3];
char* an = new char[5];
strcpy_s(s, 10, "");
_itoa_s(this->zi, zi, 3, 10);
_itoa_s(this->luna, luna, 3, 10);
_itoa_s(this->an, an, 5, 10);
strcat_s(s, 10, zi);
strcat_s(s, 10, "/");
strcat_s(s, 10, luna);
strcat_s(s, 10, "/");
strcat_s(s, 10, an);
if (zi) {
delete[] zi;
zi = NULL;
}
if (luna) {
delete[] luna;
luna = NULL;
}
if (an) {
delete[] an;
an = NULL;
}
return s;
}
ostream& operator<<(ostream& os, const Data& d)
{
os << d.zi << "/" << d.luna << "/" << d.an;
return os;
}
istream& operator>>(istream& is, Data& d) {
char slash;
is >> d.zi >> slash >> d.luna >> slash >> d.an;
return is;
}
| true |
1b907ece1add3f129a8d57f5ed8ef859b38941e5 | C++ | raulgoce/porfolio | /Begginer/4.Estructuras_repetitivas/35.05.Ejercicio.Suma_cuadrados.cpp | UTF-8 | 410 | 3.625 | 4 | [] | no_license | /* 3.Realice un programa que calcule y muestre la suma de todos los cuadrados de los
10 primeros enteros mayores que 0. */
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
int sum=0,cuadrado;
for(int i=1;i<=10;i++){
cuadrado=i*i;
sum+=cuadrado;
}
cout<<"El resultado de la suma de todos los cuadrados de los 10 primeros numeros es: "<<sum<<endl;
getch();
return 0;
}
| true |
0b7c0697144db6e8f3b8b974edee672eec390fab | C++ | yjxiong/convnet | /src/sample.cc | UTF-8 | 1,456 | 3.09375 | 3 | [
"BSD-2-Clause"
] | permissive | // condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
using namespace std;
mutex fprop_start_mutex_, fprop_finished_mutex_;
condition_variable fprop_finish_cond_var_, fprop_start_cond_var_;
bool ready_for_fprop_ = false, fprop_finish_ = false;
void fprop () {
unique_lock<mutex> lock1(fprop_start_mutex_);
while (!ready_for_fprop_) {
// wait for TrainOneBatch to set this off.
cout << "Waiting for signal to start fprop " << endl;
fprop_start_cond_var_.wait(lock1);
cout << "Got signal" << endl;
}
ready_for_fprop_ = false;
cout << "Fproping" << endl;
unique_lock<mutex> lock2(fprop_finished_mutex_);
fprop_finish_ = true;
fprop_finish_cond_var_.notify_all();
}
void go() {
cout << "Starting fprop" << endl;
unique_lock<mutex> lock1(fprop_start_mutex_);
ready_for_fprop_ = true;
fprop_start_cond_var_.notify_all();
cout << "Started" << endl;
lock1.unlock();
unique_lock<mutex> lock2(fprop_finished_mutex_);
while (!fprop_finish_) {
cout << "Waiting to finish" << endl;
fprop_finish_cond_var_.wait(lock2);
}
fprop_finish_ = false;
cout << "Done" << endl;
}
int main (int argc, char** argv)
{
// spawn 10 threads:
thread th(fprop);
go(); // go!
th.join();
return 0;
}
| true |
9482241d89b0dd99b0284d3a2f5f6b0663f229d9 | C++ | FelixArg/CP-lib | /geom.cpp | UTF-8 | 4,112 | 2.875 | 3 | [] | no_license | const long double eps = 1e-9;
const long double pi = 3.14159265358979323846;
// ñêàëÿðíîå ïðîèçâåäåíèå âåêòîðîâ - x1 * x2 + y1 * y2
bool dequal(long double a, long double b) {
if (abs(a - b) < eps)
return 1;
return 0;
}
bool dless(long double a, long double b) {
if (!dequal(a, b) && a < b)
return 1;
return 0;
}
bool dgreater(long double a, long double b) {
if (!dequal(a, b) && a > b)
return 1;
return 0;
}
bool dlesseq(long double a, long double b) {
if (dequal(a, b) || a < b)
return 1;
return 0;
}
bool dgreatereq(long double a, long double b) {
if (dequal(a, b) || a > b)
return 1;
return 0;
}
struct doublep {
long double x;
long double y;
const bool operator <(doublep a) const {
if (dequal(this->x, a.x))
return dless(this->y, a.y);
return dless(this->x, a.x);
}
};
long double area(doublep a, doublep b, doublep c) {
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
}
long double dist(doublep a, doublep b) {
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
long double ang(doublep a, doublep b, doublep c) {
// óãîë abc
doublep v1 = { a.x - b.x, a.y - b.y };
doublep v2 = { c.x - b.x, c.y - b.y };
long double aa = sqrt(v1.x * v1.x + v1.y * v1.y);
long double bb = sqrt(v2.x * v2.x + v2.y * v2.y);
long double s = v1.x * v2.x + v1.y * v2.y;
return acos(s / (aa * bb));
}
vector<doublep> hull(vector<doublep> p) {
int n = p.size();
if (n == 1)
return p;
vector<doublep> u, d;
sort(p.begin(), p.end());
u.emplace_back(p[0]);
d.emplace_back(p[0]);
for (int i = 1; i < n; i++) {
if (i == n - 1 || dless(area(p[0], p[i], p[n - 1]), 0)) {
while (u.size() > 1 && dgreatereq(area(u[u.size() - 2], u[u.size() - 1], p[i]), 0))
u.pop_back();
u.emplace_back(p[i]);
}
if (i == n - 1 || dgreater(area(p[0], p[i], p[n - 1]), 0)) {
while (d.size() > 1 && dlesseq(area(d[d.size() - 2], d[d.size() - 1], p[i]), 0))
d.pop_back();
d.emplace_back(p[i]);
}
}
vector<doublep> res;
for (int i = 0; i < u.size(); i++) {
res.emplace_back(u[i]);
}
for (int i = d.size() - 2; i > 0; i--) {
res.emplace_back(d[i]);
}
return res;
}
struct intp {
int x;
int y;
const bool operator <(intp a) const {
if (this->x == a.x)
return this->y < a.y;
return this->x < a.x;
}
};
ll area(intp a, intp b, intp c) {
// |x2 - x1, y2 - y1|
// |x3 - x1, y3 - y1|
return (ll)(b.x - a.x) * (c.y - a.y) - (ll)(c.x - a.x) * (b.y - a.y);
// åñëè < 0, òî ïî ÷àñîâîé ñòðåëêå, åñëè > 0, òî ïðîòèâ ÷àñîâîé ñòðåëêè, åñëè 0, òî 3 òî÷êè ëåæàò íà 1 ïðÿìîé
}
long double dist(intp a, intp b) {
return sqrt((ll)(a.x - b.x) * (a.x - b.x) + (ll)(a.y - b.y) * (a.y - b.y));
}
ll distsq(intp a, intp b) {
return (ll)(a.x - b.x) * (a.x - b.x) + (ll)(a.y - b.y) * (a.y - b.y);
}
long double ang(intp a, intp b, intp c) {
// óãîë abc
intp v1 = { a.x - b.x, a.y - b.y };
intp v2 = { c.x - b.x, c.y - b.y };
long double aa = sqrt(v1.x * v1.x + v1.y * v1.y);
long double bb = sqrt(v2.x * v2.x + v2.y * v2.y);
long double s = v1.x * v2.x + v1.y * v2.y;
return acos(s / (aa * bb));
}
vector<intp> hull(vector<intp> p) {
int n = p.size();
if (n == 1)
return p;
vector<intp> u, d;
sort(p.begin(), p.end());
u.emplace_back(p[0]);
d.emplace_back(p[0]);
for (int i = 1; i < n; i++) {
if (i == n - 1 || area(p[0], p[i], p[n - 1]) < 0) {
while (u.size() > 1 && area(u[u.size() - 2], u[u.size() - 1], p[i]) >= 0)
u.pop_back();
u.emplace_back(p[i]);
}
if (i == n - 1 || area(p[0], p[i], p[n - 1]) > 0) {
while (d.size() > 1 && area(d[d.size() - 2], d[d.size() - 1], p[i]) <= 0)
d.pop_back();
d.emplace_back(p[i]);
}
}
vector<intp> res;
for (int i = 0; i < u.size(); i++) {
res.emplace_back(u[i]);
}
for (int i = d.size() - 2; i > 0; i--) {
res.emplace_back(d[i]);
}
return res;
}
| true |
78d31978ae9838547fd02067f23b0e809a9c92d3 | C++ | mjjq/ballEngine | /headers/classLight.h | UTF-8 | 932 | 2.75 | 3 | [
"MIT"
] | permissive | #ifndef CLASS_LIGHT_H
#define CLASS_LIGHT_H
#include "SFML/Graphics.hpp"
#include "Observer.h"
struct LightProperties
{
sf::Vector3f position;
sf::Vector3f color = sf::Vector3f(1.0, 1.0, 1.0);
float constant = 1.0f;
float linear = 0.00002f;
float quadratic = 0.000005f;
float lightMax = 1.0f;
float umbralRadius = 1.0f;
};
struct Ray
{
public:
Ray(sf::Vector2f const & _pos,
sf::Vector2f const & _dir,
float const & _maxT = 1e+15f) :
pos{_pos}, dir{_dir}, maxT{_maxT} {}
Ray() {}
sf::Vector2f pos;
sf::Vector2f dir;
float maxT;
};
class LightSource : public Component
{
public:
static Subject renderSubject;
LightProperties lightProperties;
sf::Vector3f position;
float effectiveRadius = 300.0f;
LightSource(LightProperties properties);
~LightSource();
void calcEffectiveRadius(float attFactor);
};
#endif // CLASS_LIGHT_H
| true |
043c3e8be02046c9e71646dcd21094589c4468df | C++ | shaszard/test | /depends/util/src/pathutils.cpp | UTF-8 | 3,624 | 2.75 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | /* Copyright 2013-2014 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "include/pathutils.h"
#include <QFileInfo>
#include <QDir>
#include <QDesktopServices>
#include <QUrl>
QString PathCombine(QString path1, QString path2)
{
return QDir::cleanPath(path1 + QDir::separator() + path2);
}
QString PathCombine(QString path1, QString path2, QString path3)
{
return PathCombine(PathCombine(path1, path2), path3);
}
QString AbsolutePath(QString path)
{
return QFileInfo(path).absolutePath();
}
/**
* Normalize path
*
* Any paths inside the current directory will be normalized to relative paths (to current)
* Other paths will be made absolute
*/
QString NormalizePath(QString path)
{
QDir a = QDir::currentPath();
QString currentAbsolute = a.absolutePath();
QDir b(path);
QString newAbsolute = b.absolutePath();
if (newAbsolute.startsWith(currentAbsolute))
{
return a.relativeFilePath(newAbsolute);
}
else
{
return newAbsolute;
}
}
QString badFilenameChars = "\"\\/?<>:*|!";
QString RemoveInvalidFilenameChars(QString string, QChar replaceWith)
{
for (int i = 0; i < string.length(); i++)
{
if (badFilenameChars.contains(string[i]))
{
string[i] = replaceWith;
}
}
return string;
}
QString DirNameFromString(QString string, QString inDir)
{
int num = 0;
QString dirName = RemoveInvalidFilenameChars(string, '-');
while (QFileInfo(PathCombine(inDir, dirName)).exists())
{
num++;
dirName = RemoveInvalidFilenameChars(dirName, '-') + QString::number(num);
// If it's over 9000
if (num > 9000)
return "";
}
return dirName;
}
bool ensureFilePathExists(QString filenamepath)
{
QFileInfo a(filenamepath);
QDir dir;
QString ensuredPath = a.path();
bool success = dir.mkpath(ensuredPath);
return success;
}
bool ensureFolderPathExists(QString foldernamepath)
{
QFileInfo a(foldernamepath);
QDir dir;
QString ensuredPath = a.filePath();
bool success = dir.mkpath(ensuredPath);
return success;
}
bool copyPath(QString src, QString dst)
{
QDir dir(src);
if (!dir.exists())
return false;
if (!ensureFolderPathExists(dst))
return false;
foreach(QString d, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
{
QString inner_src = src + QDir::separator() + d;
QString inner_dst = dst + QDir::separator() + d;
copyPath(inner_src, inner_dst);
}
foreach(QString f, dir.entryList(QDir::Files))
{
QFile::copy(src + QDir::separator() + f, dst + QDir::separator() + f);
}
return true;
}
void openDirInDefaultProgram(QString path, bool ensureExists)
{
QDir parentPath;
QDir dir(path);
if (!dir.exists())
{
parentPath.mkpath(dir.absolutePath());
}
QDesktopServices::openUrl(QUrl::fromLocalFile(dir.absolutePath()));
}
void openFileInDefaultProgram(QString filename)
{
QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
}
// Does the directory path contain any '!'? If yes, return true, otherwise false.
// (This is a problem for Java)
bool checkProblemticPathJava(QDir folder)
{
QString pathfoldername = folder.absolutePath();
return pathfoldername.contains("!", Qt::CaseInsensitive);
}
| true |
be69586d408120709869cfadd879347710b50026 | C++ | mrtullis/PF2-assignment-4 | /Testercpp final.cpp | UTF-8 | 3,141 | 3.4375 | 3 | [] | no_license | /*
author Michael Tullis
Date 10/27/2020
tester file for homework 4 slightly modified from original
*/
#include <cstdlib>
#include <iostream>
#include <string>
#include <iostream>
#include <fstream>
#include "mystring.h"
#define string Mystring
using namespace std;
/*
* Check function from the previous lab
*/
void check (const string s, const string name)
{
cout << "checking " << name << endl;
cout << name << " contains " << s << endl;
cout << name << " capacity() is " << s.capacity() << endl;
cout << name << " length() is " << s.length() << endl;
cout << name << " size() is " << s.size() << endl;
cout << name << " max_size() is " << s.max_size() << endl << endl;
}
int main()
{
string s1("Hello, World!");
string s1name("s1");
check(s1, s1name);
cout << "---Testing assignment operator and == operator---\n";
string s2;
s2=s1 ;
string s2name("s2");
check(s2,s2name);
check(s1, s1name);
if(s1== s2)
cout << "s1 and s2 are same string" << endl;
string s3("Hi");
check(s3,"s3");
s3 = "Hey";
check(s3,"s3");
cout << s3 << endl;
if(s3 != "Hey")
cout << "your assignment operator is wrong" << endl;
else
cout << "assignment operator is correct" << endl;
cout << "--------------------------------------\n\n" ;
cout << "---Testing Push Back---\n";
s2.push_back('?');
check(s2,s2name);
cout << "--------------------------------------\n\n" ;
cout << "---Testing array notation---\n";
cout << "second char of s1: "<< s1[1] << endl;
cout << "--------------------------------------\n\n" ;
cout << "---Testing += operator ---\n";
s2 += s1;
cout << "s2 after += s1: "<< s2 << endl;
s3 += " you";
cout << s3 << endl;
cout << "--------------------------------------\n\n" ;
cout << "---Testing append ---\n";
s2.append("??");
cout << "s2 after append s1: "<< s2 << endl;
check(s2,"s2");
cout << "--------------------------------------\n\n" ;
cout << "---Testing insert ---\n";
s2.insert(6, "c++");
cout << "s2 after insert: "<< s2 << endl;
cout << "--------------------------------------\n\n" ;
cout << "---Testing replace ---\n";
s2.replace(6, 7, "code");
cout << "s2 after replace: "<< s2 << endl;
cout << "--------------------------------------\n\n" ;
cout << "---Testing find_first_of ---\n";
cout << "s2 find first of aeiou after index 2: " << s2.find_first_of("aeiou", 2, 7);
cout << "--------------------------------------\n\n" ;
check(s1, s1name);
cout << "---Testing find_last_not_of ---\n";
cout << "s1: " << s1.length() << endl;
cout << "s1 find find_last_not_of !? after index 2: " << s1.find_last_not_of("!?");
cout << "--------------------------------------\n\n" ;
cout << "---Testing + ---\n";
s3 = s1 + s2;
cout << s3 << endl;
cout << "--------------------------------------\n\n" ;
// myfile.close();
return 0;
} | true |
3fda91e4a95b6b83c24af71aefa5163a0c208eb5 | C++ | piby/imp-sandbox | /imp/src/ShaderProgram.cpp | UTF-8 | 5,608 | 2.71875 | 3 | [] | no_license | #include "ShaderProgram.hpp"
#include <GL/glew.h>
#include <assert.h>
#include <vector>
using namespace imp;
ShaderProgram::ShaderProgram(): m_id(0)
{
}
ShaderProgram::~ShaderProgram()
{
if( m_id )
{
// automatically detaches all
// attached shaders and deletes program
glDeleteProgram( m_id );
m_id = 0;
}
}
bool ShaderProgram::create()
{
if( m_id )
glDeleteProgram( m_id );
// create an empty program object
m_id = glCreateProgram();
if( !m_id )
return 0;
return 1;
}
bool ShaderProgram::attach( const Shader& shader )
{
if( ( !m_id ) || ( !shader.getId() ) )
return 0;
// attach shader to program object
glAttachShader( m_id, shader.getId() );
if( glGetError() != GL_NO_ERROR )
return 0;
return 1;
}
bool ShaderProgram::detach( const Shader& shader )
{
if( ( !m_id ) || ( !shader.getId() ) )
return 0;
// detach shader from program object
glDetachShader( m_id, shader.getId() );
if( glGetError() != GL_NO_ERROR )
return 0;
return 1;
}
bool ShaderProgram::link() const
{
if( !m_id )
return 0;
// links program object
glLinkProgram( m_id );
if( glGetError() != GL_NO_ERROR )
return 0;
// check if linking was successful
int status;
glGetProgramiv( m_id, GL_LINK_STATUS, &status );
if( status )
return 1;
return 0;
}
void ShaderProgram::bind() const
{
glUseProgram( m_id );
}
void ShaderProgram::unbind() const
{
glUseProgram( 0 );
}
void ShaderProgram::setUniform( int uLoc, UniformType type, float* value, int arraySize )
{
assert( value );
assert( uLoc > -1 );
assert( arraySize > 0 );
using UniformMethod = void (*)(GLint, GLsizei, const GLfloat*);
UniformMethod uniformMethods[] =
{
glUniform1fv,
glUniform2fv,
glUniform3fv,
glUniform4fv
};
auto index = static_cast<int>(type);
auto method = uniformMethods[index];
method( uLoc, arraySize, value );
assert(glGetError() == GL_NO_ERROR);
}
void ShaderProgram::setUniform( int uLoc, UniformType type, int* value, int arraySize )
{
assert( value );
assert( uLoc > -1 );
assert( arraySize > 0 );
using UniformMethod = void (*)(GLint, GLsizei, const GLint*);
const UniformMethod uniformMethods[] =
{
glUniform1iv,
glUniform2iv,
glUniform3iv,
glUniform4iv
};
auto index = static_cast<int>(type);
auto method = uniformMethods[index];
method( uLoc, arraySize, value );
assert(glGetError() == GL_NO_ERROR);
}
void ShaderProgram::setUniformMatrix( int uLoc, UniformMatrixType type, float* value, int matricesCount, bool transpose )
{
assert( value );
assert( uLoc > -1 );
assert( matricesCount > 0 );
using UniformMethod = void (*)(GLint, GLsizei, GLboolean, const GLfloat*);
const UniformMethod uniformMethods[] =
{
glUniformMatrix4fv,
glUniformMatrix3fv,
glUniformMatrix3x4fv,
glUniformMatrix4x3fv,
glUniformMatrix2x4fv,
glUniformMatrix4x2fv,
glUniformMatrix2x3fv,
glUniformMatrix3x2fv,
glUniformMatrix2fv
};
auto index = static_cast<int>(type);
auto method = uniformMethods[index];
method( uLoc, matricesCount, transpose, value );
assert(glGetError() == GL_NO_ERROR);
}
int ShaderProgram::getUniformLocation( const char* variableName )
{
#ifdef IMP_DEBUG
assert( m_id );
#endif
return glGetUniformLocation( m_id, variableName );
}
void ShaderProgram::getUniform( int uLoc, float* buff )
{
#ifdef IMP_DEBUG
assert( m_id );
#endif
glGetUniformfv( m_id, uLoc, buff );
}
void ShaderProgram::getUniform( int uLoc, int* buff )
{
#ifdef IMP_DEBUG
assert( m_id );
#endif
glGetUniformiv( m_id, uLoc, buff );
}
int ShaderProgram::getUniformBlockIndex(const char* blockName) const
{
#ifdef IMP_DEBUG
assert( m_id );
#endif
return glGetUniformBlockIndex( m_id, blockName );
}
int ShaderProgram::getUniformBlockSize(int blockIndex) const
{
#ifdef IMP_DEBUG
assert( m_id );
#endif
int uniformBlockSize = 0;
glGetActiveUniformBlockiv( m_id, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlockSize);
return uniformBlockSize;
}
void ShaderProgram::assignBindingPointToUniformBlock(int blockIndex, int bindingPoint)
{
#ifdef IMP_DEBUG
assert( m_id );
#endif
glUniformBlockBinding( m_id, blockIndex, bindingPoint);
}
void ShaderProgram::getUniformInfo( int uLoc, char* nameBuff, unsigned int buffSize, int& varSize, unsigned int& varType )
{
if( ( !nameBuff ) || ( !buffSize ) )
return;
glGetActiveUniform( m_id, uLoc, buffSize, 0, &varSize, &varType, nameBuff );
}
void ShaderProgram::getLinkingLog(std::string& result) const
{
if( !m_id )
return;
int logLength = 0;
glGetProgramiv( m_id, GL_INFO_LOG_LENGTH, &logLength );
if( logLength > 1 )
{
std::vector<GLchar> log(logLength);
glGetProgramInfoLog( m_id, logLength, 0, &log[0] );
result = std::string(&log[0]);
}
}
unsigned int ShaderProgram::getAtachedShadersCount() const
{
if( !m_id )
return 0;
int count = 0;
glGetProgramiv( m_id, GL_ATTACHED_SHADERS, &count );
return count;
}
int ShaderProgram::getAtachedShaderIds( unsigned int* buff, unsigned int buffSize ) const
{
if( !buffSize )
return 0;
if( !m_id )
{
buff[0] = 0;
return 0;
}
int count = 0;
glGetAttachedShaders( m_id, buffSize, &count, buff );
if( ( count ) && ( (unsigned int)count > buffSize ) )
buff[ count-1 ] = 0;
return count;
}
GLuint ShaderProgram::getId() const
{
return m_id;
}
| true |
2e0ba301e093b4e7ad4ab925e78cffcc811cfb95 | C++ | Jackychen8/class_c- | /rle/rle.cpp | UTF-8 | 5,352 | 3.0625 | 3 | [] | no_license | // rle.cpp : Defines the entry point for the console application.
//
#include "rletest.h"
#include "rle-algo.hpp"
#include <iostream>
#include "rle-files.h"
void Part1Tests()
{
TestFixtureFactory::theInstance().runTests();
}
int main(int argc, char* argv[])
{
std::string choice;
int numChoice;
while( numChoice != 4 ){
// Main entry point
std::cout << "Select an option:" << std::endl;
std::cout << "1. Part 1 (Tests)" << std::endl;
std::cout << "2. Part 2 (Single Files)" << std::endl;
std::cout << "3. Part 3 (Directories)" << std::endl;
std::cout << "4. Exit" << std::endl;
std::cout << "> " ;
std::getline(std::cin, choice);
while( choice != "1" && choice != "2" && choice != "3" && choice != "4" ){
std::cout << "Invalid Choice! Input should only be 1, 2, 3, or 4. Try Again!" << std::endl << "> ";
choice.clear();
std::getline(std::cin, choice);
}
//String Stream or std::stoi both work
std::stringstream(choice) >> numChoice;
//numChoice = std::stoi(choice);
//std::cout << "You chose " << numChoice << std::endl;
if( numChoice == 1 ){
Part1Tests();
}
int newChoice = 0;
while ( numChoice == 2 && newChoice < 3 ){ // choice 3 will return to main menu and other choices will be invalid
std::cout << "Select an option:" << std::endl;
std::cout << "1. Create an Archive" << std::endl;
std::cout << "2. Extract an Archive" << std::endl;
std::cout << "3. Return to Main Menu" << std::endl;
std::cout << "> ";
std::getline(std::cin, choice);
// Checks if input is valid
while( choice != "1" && choice != "2" && choice != "3" ){
std::cout << "Invalid Choice! Input should only be 1, 2, or 3. Try Again!" << std::endl << "> ";
choice.clear();
std::getline(std::cin, choice);
}
std::stringstream(choice) >> newChoice;
if( newChoice == 1){
std::cout << "What is the name of the file you would like to compress?" << std::endl;
std::cout << "> ";
std::getline(std::cin, choice);// choice is a string
//create an instance of RLE_v1 and call the CreateArchive function with the file name as the parameter
RLE_v1 newArchive;
newArchive.CreateArchive(choice);
}
if( newChoice == 2){
std::cout << "What is the name of the file you would like to extract?" << std::endl;
std::cout << "> ";
std::getline(std::cin, choice);// choice is a string
RLE_v1 newArchive;
newArchive.ExtractArchive(choice);
}
if( newChoice == 3){// Return to Main menu
std::cout << "Returned to Main Menu" << std::endl;
}
}
while ( numChoice == 3 && newChoice < 3 ){ // choice 3 will return to main menu and other choices will be invalid
std::cout << "Select an option:" << std::endl;
std::cout << "1. Create an Archive" << std::endl;
std::cout << "2. Extract an Archive into a Directory" << std::endl;
std::cout << "3. Return to Main Menu" << std::endl;
std::cout << "> ";
std::getline(std::cin, choice);
// Checks if input is valid
while( choice != "1" && choice != "2" && choice != "3" ){
std::cout << "Invalid Choice! Input should only be 1, 2, or 3. Try Again!" << std::endl << "> ";
choice.clear();
std::getline(std::cin, choice);
}
std::stringstream(choice) >> newChoice;
if( newChoice == 1){
//ask for the name of a directory
std::cout << "What is the name of the directory you would like to compress?" << std::endl;
std::cout << "> ";
std::getline(std::cin, choice);// choice is a string
//create an instance of RLE_v2 and call the CreateArchive function with the file name as the parameter
RLE_v2 newArchive;
newArchive.CreateArchive(choice);
}
if( newChoice == 2){
std::cout << "What is the name of the directory you would like to extract?" << std::endl;
std::cout << "> ";
std::getline(std::cin, choice);// choice is a string
RLE_v2 newArchive;
newArchive.ExtractArchive(choice);
}
if( newChoice == 3){// Return to Main menu
std::cout << "Returned to Main Menu" << std::endl;
}
}
}
return 0;
}
| true |
ccc1ed52c8b767046976b28edeb4d016c353d634 | C++ | sundeepkaranam/Coding | /LinkedLists/PalindromeLinkedList.cpp | UTF-8 | 1,397 | 3.65625 | 4 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* curNode = head;
ListNode* prevNode = NULL;
ListNode* nextNode = NULL;
while (curNode != NULL) {
nextNode = curNode->next;
curNode->next = prevNode;
prevNode = curNode;
curNode = nextNode;
}
return prevNode;
}
ListNode* getMiddleNodeOfList(ListNode* head)
{
ListNode* slowNode = head;
ListNode* fastNode = head;
while (fastNode != NULL && fastNode->next != NULL) {
slowNode = slowNode->next;
fastNode = fastNode->next->next;
}
return slowNode;
}
bool isPalindrome(ListNode* head)
{
ListNode* midNode = getMiddleNodeOfList(head);
ListNode* firstHalf = head;
ListNode* secondHalf = reverseList(midNode);
while (firstHalf != midNode) {
if (firstHalf->val != secondHalf->val) {
return false;
}
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
}
return true;
}
}; | true |
9dd78675b7253eb94e3633b67c7e2b2c3dded84a | C++ | jasonblog/note | /ds_algo/src/leetcode_v2/algorithms/ContainsDuplicateII/solve.cpp | UTF-8 | 731 | 3.234375 | 3 | [
"MIT"
] | permissive | #include <vector>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
class Solution
{
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_map<int, int> map;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (map.find(nums[i]) != map.end()) {
int s = map[nums[i]];
if (i - s <= k) {
return true;
}
}
map[nums[i]] = i;
}
return false;
}
};
int main(int argc, char** argv)
{
Solution solution;
vector<int> nums = {2, 3, 4, 1};
cout << solution.containsNearbyDuplicate(nums, 1) << endl;
return 0;
}
| true |
08bd35125459d03f26b35b0463f83ba5ddbe6d6e | C++ | brenopoggiali/BCC | /alg1/TP3/sudoku.cpp | UTF-8 | 4,432 | 3.140625 | 3 | [
"MIT"
] | permissive | #include "sudoku.h"
Sudoku::Sudoku(std::ifstream &entrada) {
entrada >> this->N >> this->J >> this->I;
int aux;
for (int i=0; i < this->N; i++) {
this->sudoku.push_back({});
this->checked.push_back({});
for (int j=0; j < this->N; j++) {
entrada >> aux;
sudoku[i].push_back({aux});
if (aux != 0)
checked[i].push_back(true);
else
checked[i].push_back(false);
}
}
}
bool Sudoku::isResolved() {
for (int i = 0; i < this->N; i++) {
for (int j = 0; j < this->N; j++) {
if (checked[i][j] == false)
return false;
}
}
return true;
}
void Sudoku::solveSudoku() {
for (int k=0; k < (this->N*this->N); k++) {
for (int i=0; i < this->N; i++) {
for (int j=0; j < this->N; j++) {
if (sudoku[i][j].size() == 1 and checked[i][j] == false) {
checked[i][j] = true;
updatePossibilities();
} else if (checked[i][j] == false) {
tryAvailablePossibilities(i, j);
}
}
}
}
}
void Sudoku::printSudoku() {
for (int i=0; i < this->N; i++) {
for (int j=0; j < this->N; j++) {
if (checked[i][j] == 1)
std::cout << sudoku[i][j][0];
else
std::cout << "0";
if (j != this->N-1)
std::cout << " ";
}
std::cout << std::endl;
}
}
void Sudoku::tryAvailablePossibilities(int p_i, int p_j) {
std::map <int, int> possibilities;
int i_start, j_start;
i_start = (p_i/this->I)*this->I;
j_start = (p_j/this->J)*this->J;
for (int i=i_start; i < i_start+this->I; i++) {
for (int j=j_start; j < j_start+this->J; j++) {
if (i == p_i and j == p_j)
continue;
else {
for (auto element : sudoku[i][j]) {
if (possibilities.find(element) == possibilities.end())
possibilities[element] = 1;
}
}
}
}
for (auto i : sudoku[p_i][p_j]) {
if (possibilities.find(i) == possibilities.end()) {
sudoku[p_i][p_j] = {i};
checked[p_i][p_j] = 1;
break;
}
}
}
void Sudoku::updatePossibilities() {
for (int i=0; i < this->N; i++) {
for (int j=0; j < this->N; j++) {
if (sudoku[i][j][0] == 0 or checked[i][j] == false) {
std::vector <int> possibilities = getAllPossibilities(i, j);
sudoku[i][j] = possibilities;
}
}
}
}
std::vector <int> Sudoku::getAllPossibilities(int i, int j) {
std::vector <int> poss;
for (int i=1; i < this->N+1; i++) {
poss.push_back(i);
}
std::vector <int> cant = getAllThatCantBe(i, j);
for (auto i : cant) {
poss.erase(std::remove(poss.begin(), poss.end(), i), poss.end());
}
return poss;
}
std::vector <int> Sudoku::getAllThatCantBe(int i, int j) {
std::vector <int> cant;
std::vector <int> line = getElementsInLine(i, j);
std::vector <int> col = getElementsInCol(i, j);
std::vector <int> square = getElementsInSquare(i, j);
cant.insert(cant.end(), line.begin(), line.end());
cant.insert(cant.end(), col.begin(), col.end());
cant.insert(cant.end(), square.begin(), square.end());
return cant;
}
std::vector <int> Sudoku::getElementsInLine(int i, int j) {
std::vector <int> exists;
for (int k=0; k < this->N; k++) {
if (checked[i][k] == true)
exists.push_back(sudoku[i][k][0]);
}
return exists;
}
std::vector <int> Sudoku::getElementsInCol(int i, int j) {
std::vector <int> exists;
for (int k=0; k < this->N; k++) {
if (checked[k][j] == true)
exists.push_back(sudoku[k][j][0]);
}
return exists;
}
std::vector <int> Sudoku::getElementsInSquare(int i, int j) {
std::vector <int> exists;
int i_start, j_start;
i_start = (i/this->I)*this->I;
j_start = (j/this->J)*this->J;
for (int i=i_start; i < i_start+this->I; i++) {
for (int j=j_start; j < j_start+this->J; j++) {
if (checked[i][j] == true)
exists.push_back(sudoku[i][j][0]);
}
}
return exists;
}
Sudoku::~Sudoku() {
}
| true |
77037409cb2d02521bdc1914d547b54628c0f11e | C++ | TvGelderen/C-Programming-III | /set1/3/main.cc | UTF-8 | 282 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
template <typename T>
T *rawCapacity(size_t size)
{
return static_cast<T *>(operator new(size * sizeof(T)));
}
int main()
{
string *strPtr = rawCapacity<string>(1);
strPtr[0] = "First string";
cout << strPtr[0] << '\n';
}
| true |
cbb833e9595cfcc4567f9ee2c20337fc22ee1577 | C++ | conceptarc/ECE498A | /Pathing/Obstacle.h | UTF-8 | 217 | 2.578125 | 3 | [] | no_license | #ifndef OBSTACLE_H
#define OBSTACLE_H
#define nullptr 0
class Obstacle {
public:
Obstacle(int id, float x, float y, float radius);
~Obstacle();
int Id;
float X;
float Y;
float Radius;
};
#endif | true |
52229974ba46fae05d8ecc1045ed4ac1cb5f3142 | C++ | sakutty/zombie-rampage-wip | /Zombie Rampage 0.1v.cpp | UTF-8 | 3,027 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int
createZombie ()
{
if (rand () % 67 < 10)
return 11;
else
return rand () % 10 + 1;
}
int
main ()
{
srand (time (NULL));
char enter;
// game stats
int playerAlive = true;
int playerSkill = 9;
int playerScore = 1;
string playerName = "";
int zombieCount = 0;
int zombiesKilled = 0;
// title
cout << "Welcome to Zombies Rampage v0.1." << endl <<
"Press the ENTER key to start playing.";
cin.get ();
// player name
cout << "Input character name your name: ";
cin >> playerName;
// ask how many zombies
cout << "How many zombies do you wanna fight? ";
cin >> zombieCount;
cout << "Get ready for the fight of your life, " << playerName << "!" <<
endl;
// main game loop
while (playerAlive && zombiesKilled < zombieCount)
{
// create a random zombie
int zombieSkill = createZombie ();
// battle sequence
if (zombieSkill > 10)
{
cout << endl <<
"Here comes a huge horde of zombies!! You should run away" <<
endl;
}
else
{
cout << endl << "Here come the zombies! Good luck. " <<
zombiesKilled + 1 << endl;
}
cout << "Fighting and generating results..." << endl;
sleep (2);
// zombie killed the player
if (playerSkill < zombieSkill)
{
playerAlive = false;
cout << "You died. Sorry better luck next time" << endl;
}
// player killed the zombie
else
{
if (playerSkill - zombieSkill > 7)
{
cout << "You wasted the *living* hell out of the zombies!" <<
endl;
playerScore = playerScore * 2;
}
else if (playerSkill - zombieSkill > 5)
{
cout <<
"You decapitated the zombies and stepped on their heads! Wow gruesome."
<< endl;
playerScore = playerScore * 2;
}
else if (playerSkill - zombieSkill > 0)
{
cout <<
"You killed the zombie by cutting their throat and leaving them to bleed and die."
<< endl;
playerScore = playerScore * 2;
}
else
{
cout <<
"You killed the zombies, but suffered heavy and almost fatal injuries."
<< endl;
}
zombiesKilled++;
}
cout << endl;
sleep (1);
}
// end game
if (zombiesKilled == zombieCount)
{
// victory
cout << "You survived the gruesome ambush and retreated. GG!" << endl;
}
else
{
// lost
cout <<
"You were eaten by the zombies and your brain was taken out of your skull. You instatly die."
<< endl;
}
cout << "Zombies killed: " << zombiesKilled << endl;
cout << "Final score: " << playerScore << endl << endl;
}
| true |
c80205b6f8c714759441fca3e90ad8c8dda9db99 | C++ | sreekanth025/coding-problems | /DynamicProgramming/9b_maxProductSubarray.cpp | UTF-8 | 1,042 | 3.5 | 4 | [] | no_license | /*
Given an integer array nums, find the contiguous subarray within an
array (containing at least one number) which has the largest product.
*/
// Problem link: https://leetcode.com/problems/maximum-product-subarray/
// Time complexity: O(n)
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
int max_product[n], min_product[n];
max_product[0] = min_product[0] = nums[0];
int result = nums[0];
for(int i=1; i<n; i++)
{
if(nums[i] > 0) {
max_product[i] = max(nums[i], max_product[i-1]*nums[i]);
min_product[i] = min(nums[i], min_product[i-1]*nums[i]);
} else {
max_product[i] = max(nums[i], min_product[i-1]*nums[i]);
min_product[i] = min(nums[i], max_product[i-1]*nums[i]);
}
result = max(result, max_product[i]);
}
return result;
}
}; | true |
ad0891767e4bdaad9be8bb39038a85fbaca840b4 | C++ | eititg/ZPR | /Network/AcceptorTCP.hpp | UTF-8 | 2,663 | 3.21875 | 3 | [] | no_license | #ifndef ACCEPTORTCP_HPP
#define ACCEPTORTCP_HPP
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
namespace net
{
using boost::shared_ptr;
using boost::system::error_code;
using namespace boost::asio;
class NetService;
class SocketTCP;
/** Klasa służąca do nasłuchiwania na porcie TCP na połączenia przychodzące.
*/
class AcceptorTCP
{
public:
/** Konstruktor.
* \param netService wskaźnik do obiektu obsługującego komunikację
*/
AcceptorTCP(shared_ptr<NetService> netService);
/** Destruktor.
*/
virtual ~AcceptorTCP();
/** Przypisz do portu.
* \param host interfejs sieciowy
* \param port numer portu
*/
void bind(const std::string &host, unsigned short port);
/** Rozpocznij nasłuchiwanie na połączenia.
*/
void listen();
/** Akceptuj połączenie.
* \param socketTCP wskaźnik do klasy gniazda, które będzie obsługiwało nowe połączenie
*/
void accept(shared_ptr<SocketTCP> socketTCP);
private:
/** Rozpocznij asynchroniczne nasłuchiwanie.
* \param socketTCP wskaźnik do klasy gniazda, które będzie obsługiwało nowe połączenie
*/
void dispatchAccept(shared_ptr<SocketTCP> socketTCP);
/** Obsłuż zakończenie asynchronicznego nasłuchiwania.
* \param socketTCP gniazdo nowego połączenia
* \param error kod błędu
*/
void handleAccept(shared_ptr<SocketTCP> socketTCP, const error_code &error);
protected:
/** Metoda wywoływana po zaakceptowaniu nowego połączenia. Może zostać przeciążona.
* \param socketTCP gniazdo nowego połączenia
*/
virtual void onAccept(shared_ptr<SocketTCP> socketTCP);
private:
/** Konstruktor kopiujący
*/
AcceptorTCP(const AcceptorTCP&);
/** Operator przypisania.
*/
AcceptorTCP& operator=(const AcceptorTCP&);
shared_ptr<NetService> netService_; /**< wskaźnik do obiektu obsługującego komunikację*/
shared_ptr<io_service::strand> strand_; /**< wskaźnik do obiektu pozwalającego na sekwencyjne wykonywanie zadań asynchronicznych*/
shared_ptr<ip::tcp::acceptor> acceptor_; /**< wskaźnik na niskopoziomowy obiekt accptora*/
};
}
#endif // ACCEPTORTCP_HPP
| true |
2daa24deebbf4ed330eabdbb9ecf47fc0d1e678b | C++ | davetcoleman/visibility_graph | /point.h | UTF-8 | 357 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef POINT_H_INCLUDED
#define POINT_H_INCLUDED
#include <iostream>
#include "geometry.h"
class Point: public Geometry
{
public:
int x;
int y;
void* parentLine;
int id; // for removing, comparing, etc
double theta; // anglular amount from base line
Point();
Point(int _x1, int _y1);
virtual void print();
virtual double value();
};
#endif
| true |
cd05482c08ce8599083d78a1e6ba1dc37e8bdc44 | C++ | fofoni/openwar | /newgamedialog.cpp | UTF-8 | 5,207 | 2.625 | 3 | [
"MIT"
] | permissive | #include <string>
#include <sstream>
#include "newgamedialog.h"
#include "colors.h"
NewGameDialog::NewGameDialog(QWidget *parent) :
QDialog(parent)
{
for (int i = 0; i < MAX_PLAYERS; i++)
player_names << "";
player_colors << WARColor_RED;
player_colors << WARColor_GREEN;
player_colors << WARColor_BLUE;
player_colors << WARColor_YELLOW;
player_colors << WARColor_WHITE;
player_colors << WARColor_BLACK;
QVBoxLayout *layout = new QVBoxLayout(this);
QHBoxLayout *choose_layout = new QHBoxLayout();
num_players_box = new QSpinBox;
num_players_box->setMinimum(MIN_PLAYERS);
num_players_box->setMaximum(MAX_PLAYERS);
num_players_box->setMaximumWidth(60);
choose_layout->addWidget(num_players_box);
QLabel *label = new QLabel("players");
choose_layout->addWidget(label);
layout->addLayout(choose_layout);
QGridLayout *form_layout = new QGridLayout;
QLabel *header_name_label = new QLabel("Name:");
form_layout->addWidget(header_name_label, 0, 1, Qt::AlignLeft);
QLabel *header_color_label = new QLabel("Color:");
form_layout->addWidget(header_color_label, 0, 2, Qt::AlignLeft);
for (int i = 1; i <= MAX_PLAYERS; i++) {
std::stringstream label_txt; label_txt << "Player " << i << ":";
player_labels << new QLabel(label_txt.str().c_str());
form_layout->addWidget(player_labels[i-1], i, 0, Qt::AlignRight);
player_names_edit << new QLineEdit;
form_layout->addWidget(player_names_edit[i-1], i, 1);
player_colors_combo << new QComboBox;
player_colors_combo[i-1]->addItem("Red");
player_colors_combo[i-1]->addItem("Green");
player_colors_combo[i-1]->addItem("Blue");
player_colors_combo[i-1]->addItem("Yellow");
player_colors_combo[i-1]->addItem("White");
player_colors_combo[i-1]->addItem("Black");
player_colors_combo[i-1]->setCurrentIndex(i-1);
form_layout->addWidget(player_colors_combo[i-1], i, 2);
}
layout->addLayout(form_layout);
button_box = new QDialogButtonBox(
QDialogButtonBox::Ok |
QDialogButtonBox::Cancel
);
layout->addWidget(button_box);
connect(num_players_box, SIGNAL(valueChanged(int)),
this, SLOT(set_num_players(int)));
for (int i = 0; i < MAX_PLAYERS; i++) {
connect(player_names_edit[i], SIGNAL(textChanged(QString)),
this, SLOT(set_names_list()));
connect(player_colors_combo[i], SIGNAL(currentIndexChanged(int)),
this, SLOT(set_colors_list()));
}
connect(button_box, SIGNAL(accepted()), this, SLOT(accept()));
connect(button_box, SIGNAL(rejected()), this, SLOT(reject()));
setLayout(layout);
setWindowTitle("New game");
set_num_players(MIN_PLAYERS);
}
bool NewGameDialog::run(int &qtd,
QList<QString> &names, QList<QColor> &colors) {
exec();
if (result() == QDialog::Rejected)
return false;
qtd = num_players;
names = player_names;
colors = player_colors;
return true;
}
void NewGameDialog::set_num_players(int n) {
num_players = n;
for (int i = 0; i < n; i++) {
player_labels[i]->setEnabled(true);
player_names_edit[i]->setEnabled(true);
player_colors_combo[i]->setEnabled(true);
}
for (int i = n; i < MAX_PLAYERS; i++) {
player_labels[i]->setEnabled(false);
player_names_edit[i]->setEnabled(false);
player_colors_combo[i]->setEnabled(false);
}
button_box->buttons()[0]->setEnabled(names_are_ok() && colors_are_ok());
}
void NewGameDialog::set_names_list() {
for (int i = 0; i < MAX_PLAYERS; i++)
player_names[i] = player_names_edit[i]->text();
button_box->buttons()[0]->setEnabled(names_are_ok() && colors_are_ok());
}
void NewGameDialog::set_colors_list() {
for (int i = 0; i < MAX_PLAYERS; i++)
switch (player_colors_combo[i]->currentIndex()) {
case 0: player_colors[i] = WARColor_RED; break;
case 1: player_colors[i] = WARColor_GREEN; break;
case 2: player_colors[i] = WARColor_BLUE; break;
case 3: player_colors[i] = WARColor_YELLOW; break;
case 4: player_colors[i] = WARColor_WHITE; break;
case 5: player_colors[i] = WARColor_BLACK; break;
}
button_box->buttons()[0]->setEnabled(names_are_ok() && colors_are_ok());
}
bool NewGameDialog::names_are_ok() {
for (int i = 0; i < num_players; i++) {
// check if they are all nonempty
if (player_names[i].isEmpty()) return false;
// check if it is different from the others
for (int j = i+1; j < num_players; j++)
if (player_names[i] == player_names[j]) return false;
}
return true;
}
bool NewGameDialog::colors_are_ok() {
for (int i = 0; i < num_players; i++) {
// check if it is different from the others
for (int j = i+1; j < num_players; j++)
if (player_colors[i] == player_colors[j]) return false;
}
return true;
}
| true |
2fb7183f5ace88539a7ee41a1b8fffd046614bcc | C++ | NorwegianCreations/15-InteractiveLEDLamp | /stars.h | UTF-8 | 4,603 | 3.015625 | 3 | [] | no_license | #ifndef STARS_H
#define STARS_H
#include "lib/effect.h"
#include "lib/effect_runner.h"
#include "lib/color.h"
#include <stdio.h>
#include <stdlib.h>
#include <list>
#define NEW_STAR_FRAME_MIN 10
#define NEW_STAR_FRAME_MAX 200
#define TOTAL_LEDS 512
#define MAX_ACTIVE_STARS 10
#define FADE_RATE 0.005
class Star
{
public:
Star()
{
srand (time(NULL));
h = (float)rand()/(RAND_MAX);
srand (time(NULL));
s = (float)rand()/(RAND_MAX);
v = 1;
index = 0;
active = 0;
}
float get_h() const
{
return h;
}
float get_s() const
{
return s;
}
float get_v() const
{
return v;
}
int get_index() const
{
return index;
}
bool get_active() const
{
return active;
}
void set_h(float h_arg)
{
h = h_arg;
}
void set_s(float s_arg)
{
s = s_arg;
}
void set_v(float v_arg)
{
v = v_arg;
}
void set_index(float index_arg)
{
index = index_arg;
}
void set_active(bool active_arg)
{
active = active_arg;
}
private:
float h,s,v;
int index;
bool active;
};
class StarsEffect : public Effect
{
public:
StarsEffect()
{
frame_counter = 0;
frames_to_next_star = 0;
}
virtual void beginFrame(const FrameInfo &f)
{
timer += f.timeDelta;
for(int i=0; i<MAX_ACTIVE_STARS-1; i++)
{
float v_tmp = star_array[i].get_v();
if(v_tmp > 0) //fade all LEDs one step
{
v_tmp -= FADE_RATE;
star_array[i].set_v(v_tmp);
}
else
{
star_array[i].set_active(0); //if faded out, set star to inactive
}
}
if(frame_counter == frames_to_next_star) //start the process of new star creation
{
star_index_accepted = 0;
while(!star_index_accepted) //keep creating star indexes until it is not an active star
{
srand(time(NULL));
star_index = rand() % TOTAL_LEDS; //choose a random LED to be a star
star_index_accepted = 1;
for(int i=0; i<MAX_ACTIVE_STARS-1; i++)
{
if(star_array[i].get_index() == star_index)
{
star_index_accepted = 0; //if the LED is already active, choose a new one at random
break;
}
else
{
star_index_accepted = 1;
}
}
}
for(int i=0; i<MAX_ACTIVE_STARS-1; i++)
{
if(!star_array[i].get_active())
{
star_array[i].set_index(star_index); //set correct LED index for the new star
srand (time(NULL)); //set random hue and saturation
float h_tmp = (float)rand()/(RAND_MAX);
srand (time(NULL));
float s_tmp = (float)rand()/(RAND_MAX);
star_array[i].set_h(h_tmp);
star_array[i].set_s(s_tmp);
star_array[i].set_v(1.0);
star_array[i].set_active(1);
break;
}
}
srand(time(NULL)); //choose a time until a new star appear at random
frames_to_next_star = rand() % (NEW_STAR_FRAME_MAX-NEW_STAR_FRAME_MIN) + NEW_STAR_FRAME_MIN;
frame_counter = 0;
}
frame_counter++;
}
virtual void shader(Vec3& rgb, const PixelInfo &p) const
{
for(int i=0; i<MAX_ACTIVE_STARS-1; i++)
{
if(star_array[i].get_index() == p.index && star_array[i].get_active())
{
/*
float h_shader = star_array[i].get_h(); //possibility for random hue and saturation for stars
float s_shader = star_array[i].get_s();
*/
float v_shader = star_array[i].get_v();
hsv2rgb(rgb, 0, 0, v_shader);
break;
}
}
}
private:
int frame_counter, star_index, frames_to_next_star;
bool star_index_accepted;
float timer;
Star star_array[MAX_ACTIVE_STARS];
};
#endif // STARS_H
| true |
b99139442edba51ebd15a230986aff248e8fa85f | C++ | arsee11/mydes | /test_helper.h | UTF-8 | 414 | 2.8125 | 3 | [] | no_license | //file: test_helper.h
#include <iostream>
#ifndef TABLES_H
#include "tables.h"
#endif
using namespace std;
template<class BITSET>
void PrintBits(BITSET &bits)
{
cout<<"bits:";
for(int i=0; i<bits.size(); i++)
cout<<bits[i]?"1":"0";
cout<<endl;
}
void PrintBytes(const byte_t *bytes, int len)
{
cout<<"bytes:";
cout.width(2);
for(int i=0; i<len; i++)
cout<<hex<<(int)bytes[i]<<" ";
cout<<endl;
}
| true |
39b798a38a9678eca615ae25f2784efcdd5e5e40 | C++ | culhatsker/sfml-gamepadtest | /src/ButtonRect.cpp | UTF-8 | 640 | 2.84375 | 3 | [] | no_license | #include "ButtonRect.hpp"
ButtonRect::ButtonRect(
uint gamepadId,
uint buttonCode,
sf::Vector2f pos
) : gamepadId(gamepadId),
buttonCode(buttonCode)
{
rect = sf::RectangleShape();
rect.setSize(sf::Vector2f(20, 20));
rect.setOrigin(sf::Vector2f(10, 10));
rect.setPosition(pos);
}
void ButtonRect::update(float frameTime) {
if (sf::Joystick::isButtonPressed(gamepadId, buttonCode)) {
rect.setFillColor(sf::Color::Green);
} else {
rect.setFillColor(sf::Color::Blue);
}
}
void ButtonRect::draw(sf::RenderTarget& target, sf::RenderStates states) const {
target.draw(rect);
} | true |
278ac7c781f4de41f9dc8d160fccf83031be233a | C++ | sakibfuad001/ClassWorksAllTime | /2-1/Stack&Queue/queue.h | UTF-8 | 1,823 | 3.859375 | 4 | [] | no_license | #ifndef DS_QUEUE_H
#define DS_QUEUE_H
#include "stack.h"
#include "data.h"
#include <iostream>
#include <new>
using namespace std;
class Queue
{
Stack stack1, stack2;
public:
Queue(){};// constructor
void enqueue(Data x); // enqueues x
void dequeue(); // removes the front element
Data front(); // returns the element from the front (without removing it)
int size(); // returns the count of elements in the queue
bool isEmpty(); // returns true of the queue is empty
void print(); // print the elements of the queue in console
};
void Queue::enqueue(Data x)
{
stack1.push(x);
}
void Queue::dequeue()
{
if((stack2.isEmpty())){
while(!(stack1.isEmpty())){
stack2.push(stack1.top());
stack1.pop();
}
stack2.pop();
}
else{
stack2.pop();
}
}
Data Queue::front()
{
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.top());
stack1.pop();
}
return stack2.top();
}
else{
return stack2.top();
}
}
int Queue::size()
{
return (stack1.size()+stack2.size());
}
bool Queue::isEmpty()
{
if(size()==0){
return true;
}
else{
return false;
}
}
void Queue::print()
{
Stack temp;
if(!stack2.isEmpty()){
stack2.print();
}
while(!stack2.isEmpty()){
temp.push(stack2.top());
stack2.pop();
}
while(!stack1.isEmpty()){
stack2.push(stack1.top());
stack1.pop();
}
stack2.print();
while(!temp.isEmpty()){
stack2.push(temp.top());
temp.pop();
}
cout<<endl;
}
#endif
| true |
09e3f14def30d66e395912a4cae815f4bacbbd64 | C++ | rsaz/LeagueReverseEngineering | /LeagueReverseEngineering/Champions.h | UTF-8 | 876 | 2.78125 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include "Stats.h"
#include "Item.h"
using std::string;
using std::vector;
class Champions
{
private:
string name;
int economy;
short level; // max level 18
// stats
Stats *stats;
vector<Item> miniInventory;
public:
Champions() {} // Initialize the stats object
Champions(string pName, int health);
// Abilities generally binded to QWER
void virtual PassiveAbility() = 0;
void virtual Ability1() = 0;
void virtual Ability2() = 0;
void virtual Ability3() = 0;
void virtual Ability4() = 0;
// Speels generally used with D and F bind
void virtual Spells1() = 0;
void virtual Spells2() = 0;
// Recall
void Recall();
Stats* GetStats();
// Buy items to the mini inventory
void BuyItem(Item item);
vector<Item> GetItems() const;
}; | true |
40a8c970d2dff1e0e276dfa2bcd043228a705c5b | C++ | KausihanBrem/Python_Pybind11 | /source/app/app.cpp | UTF-8 | 837 | 2.640625 | 3 | [] | no_license | #if defined(_DEBUG)
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
#include <pybind11/embed.h>
#include <stdio.h>
void say_something ()
{
printf ("Say Something\n");
}
static int COUNTER = 0;
void set_counter (int count)
{
COUNTER = count;
}
struct MyData
{
float x;
};
PYBIND11_EMBEDDED_MODULE (embeddedmodule, module)
{
module.doc () = "Embedded Module";
module.def ("say_something", &say_something);
module.def ("set_counter", &set_counter);
pybind11::class_<MyData>(module, "MyData")
.def_readwrite ("x", &MyData::x);
}
int main ()
{
pybind11::scoped_interpreter guard{};
auto sys = pybind11::module::import ("sys");
pybind11::print (sys.attr ("path"));
MyData data {};
data.x = 33.0f;
printf ("end\n");
return 0;
}
| true |
9b1553b862b42d65bb4121029f78de34fa4cf696 | C++ | pquiring/QSharp | /classlib/src/Map.hpp | UTF-8 | 551 | 2.640625 | 3 | [] | no_license | template <class K, class V>
Qt::QSharp::FixedArray<K>* std::Map<K,V>::keys() {
int size = pairs.size();
Qt::QSharp::FixedArray<K>* ks = new Qt::QSharp::FixedArray<K>(size);
for(int a=0;a<size;a++) {
Pair *p = pairs.get(a);
ks->at(a) = p->k;
}
return ks;
}
template <class K, class V>
Qt::QSharp::FixedArray<V>* std::Map<K,V>::values() {
int size = pairs.size();
Qt::QSharp::FixedArray<V>* vs = new Qt::QSharp::FixedArray<V>(size);
for(int a=0;a<size;a++) {
Pair *p = pairs.get(a);
vs->at(a) = p->v;
}
return vs;
}
| true |
7a7926a07f14b658eb80a2c1a92c0a595e604434 | C++ | tl32rodan/UVA10482 | /原始碼.cpp | UTF-8 | 1,557 | 2.765625 | 3 | [] | no_license | #include<iostream>
#define N 32*20+1
using namespace std;
int dp[N][N];
void dp_init(){
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
dp[i][j]=0;
}
int find_diff(int a,int b,int c){
int max_num = a,min_num = a;
if(b>max_num)max_num=b;
if(b<min_num)min_num=b;
if(c>max_num)max_num=c;
if(c<min_num)min_num=c;
return max_num-min_num;
}
int main(){
int caseNum;
cin>>caseNum;
for(int h=1;h<=caseNum;h++){
int num_of_candies;
cin>>num_of_candies;
int candy[num_of_candies],total=0;
for(int i=0;i<num_of_candies;i++){
cin>>candy[i];
total+=candy[i];
}
dp_init();
dp[0][0]=1;
//cout<<"1"<<endl;
for(int k=0;k<num_of_candies;k++)
for(int i=total;i>=0;i--)
for(int j=total;j>=0;j--)
if(dp[i][j]==1){
dp[i+candy[k]][j]=1;
dp[i][j+candy[k]]=1;
//cout<<i<<" "<<j<<" "<<candy[k]<<endl;
}
int min_w = total;
//
for(int i=0;i<=total;i++)
for(int j=0;j<=total;j++)
if(dp[i][j]==1){
int c = total-i-j;
int d = find_diff(i,j,c);
if(d<min_w){
min_w =d;
}
}
cout<<"Case "<<h<<": "<<min_w<<endl;
}
return 0;
}
| true |
489feaf370cb7140fe0cc528423a2796c1b72ca9 | C++ | pure-xiaojie/acmCode | /大三/PAT练习/数字分类.cpp | UTF-8 | 914 | 2.734375 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int a1=0,a2=0,a3=0,a4=0,a5=0;
int n,m,t = 1,k = 0;
scanf("%d",&n);
while(n--)
{
scanf("%d",&m);
if(m % 5 == 0 && m % 2 == 0)
a1 += m;
if(m % 5 == 1)
{
a2 += m*t;
t *= -1;
}
if(m % 5 == 2)
a3++;
if(m % 5 == 3)
{
a4 += m;
k++;
}
if(m % 5 == 4)
a5 = max(a5,m);
}
if(a1 != 0)
printf("%d ",a1);
else
printf("N ");
if(a2 != 0)
printf("%d ",a2);
else
printf("N ");
if(a3 != 0)
printf("%d ",a3);
else
printf("N ");
if(a4 != 0)
printf("%.1f ",a4*1.0/k);
else
printf("N ");
if(a5 != 0)
printf("%d",a5);
else
printf("N");
return 0;
}
| true |
679248df6e7cf9f8bb91ae2dbb9ec8205c216029 | C++ | cashgithubs/my-crawler-engine | /src/crawler/complete_process/file_storage.cpp | UTF-8 | 2,386 | 2.71875 | 3 | [] | no_license | #include "file_storage.hpp"
#include <cassert>
#include <fstream>
#include "Utility/utility.h"
#include "Unicode/string.hpp"
#include "Win32/FileSystem/filesystem.hpp"
namespace crawler
{
namespace storage
{
namespace
{
const std::wstring directory_name = L"files";
const std::wstring path = utility::GetAppPath() + directory_name;
void replace(std::wstring &val)
{
std::replace_if(val.begin(), val.end(), [](wchar_t c)->bool
{
if( c == '\\' || c == '/' ||
c == '*' || c == '?' ||
c == ':' || c == '|' ||
c == '<' || c == '>' ||
c == '\"'|| c == '\'' ||
c == '.' )
return true;
return false;
}, '_');
}
}
void file::start()
{
static const win32::file::wpath dir(path);
if( !win32::file::is_directory(dir) )
win32::file::create_directories(dir);
}
void file::stop()
{
}
void file::save(const url_ptr &url, const buffer_type &buffer, const handle_error_type &handle_error)
{
const std::wstring &ori_url = url->get_url();
// construct domain
size_t start_pos = ori_url.find(L'.') + 1;
assert(start_pos != std::wstring::npos);
size_t stop_pos = ori_url.find(L'/', start_pos);
if( stop_pos == std::wstring::npos )
stop_pos = ori_url.length();
std::wstring file_folder = ori_url.substr(start_pos, stop_pos - start_pos);
replace(file_folder);
// construct folder
win32::file::wpath foler_path(path + L"/" + file_folder);
if( !win32::file::is_directory(foler_path) )
win32::file::create_directories(foler_path);
// construct file
size_t f_start = ori_url.find(L'/', start_pos) + 1;
assert(start_pos != std::wstring::npos);
size_t f_stop = ori_url.find(L'?', f_start);
f_stop = f_stop == std::wstring::npos ? ori_url.length() : f_stop;
std::wstring file_name = ori_url.substr(f_start, f_stop);
replace(file_name);
file_name += L".html";
std::wstring file_path = foler_path / win32::file::wpath(file_name);
std::ofstream out(file_path.c_str(), std::ios::binary);
if( !out )
{
std::wostringstream os;
os << L"open file " << file_path << L" error" << std::endl;
handle_error(unicode::to_a(os.str()));
}
else
{
out.write(buffer.first.get(), buffer.second);
}
}
}
} | true |
63c018e4e8f1b14832c6e21d46864841a00d8277 | C++ | blizmax/gpugi | /bvhmake/processing/tesselate.cpp | UTF-8 | 5,690 | 3.09375 | 3 | [
"MIT"
] | permissive | #include "tesselate.hpp"
#include "bvhmake.hpp"
void TesselateNone(const FileDecl::Triangle& _triangle, BVHBuilder* _manager)
{
_manager->AddTriangle(_triangle);
}
static FileDecl::Vertex AvgVertex(const BVHBuilder* _manager, uint32 i0, uint32 i1)
{
const FileDecl::Vertex& v0 = _manager->GetVertex(i0);
const FileDecl::Vertex& v1 = _manager->GetVertex(i1);
FileDecl::Vertex v;
v.position = (v0.position + v1.position) * 0.5f;
v.normal = normalize(v0.normal + v1.normal);
v.texcoord = (v0.texcoord + v1.texcoord) * 0.5f;
return v;
}
void TesselateSimple(const FileDecl::Triangle& _triangle, BVHBuilder* _manager, float _maxEdgeLen)
{
// Get edges which violate the threshold
ε::Triangle tr = _manager->GetTriangle(_triangle);
float e0 = lensq(tr.v2 - tr.v1);
float e1 = lensq(tr.v0 - tr.v2);
float e2 = lensq(tr.v0 - tr.v1);
float thresholdSq = _maxEdgeLen * _maxEdgeLen;
bool s0 = e0 > thresholdSq;
bool s1 = e1 > thresholdSq;
bool s2 = e2 > thresholdSq;
if(!s0 && !s1 && !s2)
{
// Stop recursion and add final small triangle
_manager->AddTriangle(_triangle);
return;
}
// Find out which sides to tesselate for an optimal regular refined triangle.
// The smaller the ratio the faster a triangle counts as extreme. It must be larger than
// sqrt(2) (otherwise the triangle gets worse) and smaller 2 (can never be reached due to
// the triangle equation a+b>c).
const float RATIO = 1.45f;
// If one side is much larger then the others split only this.
if(e0 > e1 * RATIO && e0 > e2 * RATIO) s1 = s2 = false;
if(e1 > e0 * RATIO && e1 > e2 * RATIO) s0 = s2 = false;
if(e2 > e0 * RATIO && e2 > e1 * RATIO) s0 = s1 = false;
// If one side is significantly shorter then all others don't split it
if(e0 * 1.8f < e1 && e0 * 1.8f < e2) s0 = false;
if(e1 * 1.8f < e0 && e1 * 1.8f < e2) s1 = false;
if(e2 * 1.8f < e0 && e2 * 1.8f < e1) s2 = false;
// Create new vertices
uint32 i0 = 0, i1 = 0, i2 = 0;
if(s0) i0 = _manager->AddVertex(AvgVertex(_manager, _triangle.vertices[1], _triangle.vertices[2]));
if(s1) i1 = _manager->AddVertex(AvgVertex(_manager, _triangle.vertices[0], _triangle.vertices[2]));
if(s2) i2 = _manager->AddVertex(AvgVertex(_manager, _triangle.vertices[0], _triangle.vertices[1]));
// Split by pattern
if(s0 && s1 && s2)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], i2, i1, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], i0, i2, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], i1, i0, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({i0, i1, i2, _triangle.material}), _manager, _maxEdgeLen);
} else if(s0 && s1)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], i1, i0, _triangle.material}), _manager, _maxEdgeLen);
if(e0 > e1)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], _triangle.vertices[1], i0, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], i0, i1, _triangle.material}), _manager, _maxEdgeLen);
} else {
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], _triangle.vertices[1], i1, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], i0, i1, _triangle.material}), _manager, _maxEdgeLen);
}
} else if(s0 && s2)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], i0, i2, _triangle.material}), _manager, _maxEdgeLen);
if(e0 > e2)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], _triangle.vertices[0], i0, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], i2, i0, _triangle.material}), _manager, _maxEdgeLen);
} else {
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], _triangle.vertices[0], i2, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], i2, i0, _triangle.material}), _manager, _maxEdgeLen);
}
} else if(s1 && s2)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], i2, i1, _triangle.material}), _manager, _maxEdgeLen);
if(e1 > e2)
{
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], _triangle.vertices[2], i1, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], i1, i2, _triangle.material}), _manager, _maxEdgeLen);
} else {
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], _triangle.vertices[2], i2, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], i1, i2, _triangle.material}), _manager, _maxEdgeLen);
}
} else if(s0) {
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], _triangle.vertices[1], i0, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], _triangle.vertices[0], i0, _triangle.material}), _manager, _maxEdgeLen);
} else if(s1) {
TesselateSimple(FileDecl::Triangle({_triangle.vertices[0], _triangle.vertices[1], i1, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], _triangle.vertices[2], i1, _triangle.material}), _manager, _maxEdgeLen);
} else if(s2) {
TesselateSimple(FileDecl::Triangle({_triangle.vertices[2], _triangle.vertices[0], i2, _triangle.material}), _manager, _maxEdgeLen);
TesselateSimple(FileDecl::Triangle({_triangle.vertices[1], _triangle.vertices[2], i2, _triangle.material}), _manager, _maxEdgeLen);
} else Assert(false, "Impossible condition - at least one side must be split.");
} | true |
953612bd1b64ad3c69d2d99c8047390bb2731c32 | C++ | suwitsaengkaew/arduino-project | /Arduino_EthernetRelay/Arduino_EthernetRelay.ino | UTF-8 | 1,870 | 3 | 3 | [] | no_license | /*
Chat Server
A simple server that distributes any incoming messages to all
connected clients. To use, telnet to your device's IP address and type.
You can see the client's input in the serial monitor as well.
Using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
*/
#include <SPI.h>
#include <Ethernet2.h>
byte mac[] = {
0x90, 0xA2, 0xDA, 0x10, 0x16, 0xA9
};
IPAddress ip(10, 102, 4, 8);
IPAddress mydns(10, 102, 1, 21);
IPAddress gateway(10, 102, 4, 1);
IPAddress subnet(255, 255, 255, 0);
EthernetServer server = EthernetServer(10000);
boolean alreadyConnected = false; // whether or not the client was connected previously
void setup() {
// initialize the ethernet device
Ethernet.begin(mac, ip, mydns, gateway, subnet);
// start listening for clients
server.begin();
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Chat server address:");
Serial.println(Ethernet.localIP());
}
void loop() {
// wait for a new client:
EthernetClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clear out the input buffer:
client.flush();
Serial.println("We have a new client");
client.println("Hello, client!");
alreadyConnected = true;
client.stop();
}
if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
client.stop();
}
}
}
| true |
0bc5a10b92b61a56a3e204e37f4d08014435b6e9 | C++ | epixelse/AssaultCubeHack | /src/Console.hpp | UTF-8 | 473 | 3.09375 | 3 | [] | no_license | #pragma once
#include <string>
#include <iostream>
namespace NConsole
{
bool Initiate();
void Terminate();
template<class ... Args>
void Print(Args&& ... args);
template<class ... Args>
void Println(Args&& ... args);
}
template<class ... Args>
void NConsole::Print(Args&& ... args)
{
(std::cout << ... << std::forward<Args>(args));
}
template<class ... Args>
void NConsole::Println(Args&& ... args)
{
(std::cout << ... << std::forward<Args>(args)) << "\n";
} | true |
4204b74dfd5938222cd86003ad91378315c5158d | C++ | ArshP01/Sem-2_Object_Oriented_Programming_Lab | /EXP-6.cpp | UTF-8 | 1,422 | 4.03125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time(){
this->hours = 0;
this->minutes = 0;
this->seconds = 0;
};
Time(int hours, int minutes, int seconds) {
this->hours = hours;
this->minutes = minutes;
this->seconds = seconds;
};
int getHours(){
return this->hours;
};
int getMinutes(){
return this->minutes;
};
int getSeconds() {
return this->seconds;
};
void display(){
cout << hours << ":" << minutes << ":" << seconds << endl;
};
Time add(Time time1, Time time2) {
int hoursAdd = time1.getHours() + time2.getHours();
if (hoursAdd > 23) {
hoursAdd -= 24;
}
int minutesAdd = time1.getMinutes() + time2.getMinutes();
if (minutesAdd > 59) {
minutesAdd -= 60;
hoursAdd += 1;
}
int secondsAdd = time1.getSeconds() + time2.getSeconds();
if (secondsAdd > 59) {
secondsAdd -= 60;
minutesAdd += 1;
}
Time time3(hoursAdd, minutesAdd, secondsAdd);
return time3;
};
};
int main() {
Time time1(06, 35, 24);
Time time2(18, 58, 32);
Time time3;
time3 = time3.add(time1, time2);
time1.display();
time2.display();
time3.display();
return 0;
} | true |
2db9914e9a14eea8c2b6df9c4e256871656283d5 | C++ | aidandan/algorithm | /leetcode/cpp/344. 反转字符串.cpp | UTF-8 | 410 | 3.140625 | 3 | [] | no_license | #include <securec.h>
#include <bits/stdc++.h>
using namespace std;
void reverseString(vector<char>& s)
{
int n = s.size();
for (int i = 0; i < (n + 1) / 2; i++) {
char t = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = t;
}
}
int main()
{
vector<char> a = { 'h', 'e', 'l', 'l', 'o' };
reverseString(a);
for (char e : a) {
cout << e;
}
return 0;
}
| true |
ed7f9059133d0bf8701ff91b3219036a4cd9cffa | C++ | Property404/ElfStream | /Merchant.cpp | UTF-8 | 2,520 | 2.84375 | 3 | [] | no_license | #include "Merchant.h"
#include "Socket.h"
#include <list>
#include <vector>
#include <sstream>
#include <cassert>
#include <iostream>
// Temporary implementation while we build full structure
// Sucks information out of a local elf file
struct Merchant::Impl
{
Socket client;
};
Merchant::Merchant(const std::string& host, const std::string& elf_path, int port):pimpl(std::make_unique<Impl>())
{
pimpl->client.connect(host, port);
pimpl->client.send(elf_path);
pimpl->client.receive();
}
void Merchant::fetchPatches(const void* exact_address, Merchant::PatchList& patches)
{
std::stringstream ss;
ss<<"fetch ";
ss<<exact_address;
pimpl->client.send(ss.str());
std::string response = pimpl->client.receive();
auto toNumeric = [](std::string s){
std::stringstream ss;
ss<<s;
size_t res;
ss>>res;
return res;
};
for(unsigned i=0;i<response.size();i++)
{
Patch patch;
// Get start
std::string start_string = "";
while(response[i] != ' '){start_string+=response[i];i++;}
patch.start = toNumeric(start_string);
i++;
// Get size
std::string size_string = "";
while(response[i] != ' '){size_string+=response[i];i++;}
patch.size = toNumeric(size_string);
i++;
for(unsigned j=0;j<patch.size;j++,i++)
{
patch.content+=response[i];
}
i--;
patches.push_back(patch);
}
}
void* Merchant::entryPoint()
{
pimpl->client.send("get_text_start");
auto response = pimpl->client.receive();
std::stringstream ss;
ss<<response;
void* address;
ss>>address;
return address;
}
void* Merchant::memoryStart()
{
pimpl->client.send("get_memory_start");
auto response = pimpl->client.receive();
std::stringstream ss;
ss<<response;
void* address;
ss>>address;
return address;
}
size_t Merchant::memorySize()
{
pimpl->client.send("get_memory_size");
auto response = pimpl->client.receive();
std::stringstream ss;
ss<<response;
size_t address;
ss>>address;
return address;
}
std::string Merchant::getBlankElf(std::vector<Range>& ranges)
{
pimpl->client.send("get_blank_elf");
const auto blank_elf = pimpl->client.receive();
pimpl->client.send("get_wiped_ranges");
auto ranges_serialized = pimpl->client.receive();
// Deserialize ranges
std::stringstream ss;
size_t num_ranges;
ss<<ranges_serialized;
ss>>num_ranges;
for(unsigned i=0;i<num_ranges;i++)
{
size_t start, size;
ss<<ranges_serialized;
ss>>start;
ss<<ranges_serialized;
ss>>size;
ranges.emplace_back(start, size);
}
return blank_elf;
}
Merchant::~Merchant() = default;
| true |
e7e4299b753b546f2856ea0f825d363dbeb0fbc9 | C++ | yexuechao/leetcode | /string/DecodeWays91.cpp | UTF-8 | 1,071 | 3 | 3 | [] | no_license | #include <vector>
using namespace std;
class Solution {
public:
int numDecodings(string s) {
if (s.empty() || s[0] == '0') {
return 0;
}
vector<int> results(s.size() + 1, 0);
results[0] = 1;
results[1] = 1; // s[0]
for (int i = 2; i <= s.size(); i++) {
// 前一个不能组合在一起的情况
if (s[i - 1] == '0') {
results[i] = results[i - 2];
} else if (s[i - 2] == '0' || s[i - 2] >= '3') {
results[i] = results[i - 1];
} else if (s[i - 2] == 2) {
// 如果s[i] <= 6 就可以组合在一起
// = 0 也不能独立
if (s[i - 1] <= 6) {
results[i] = results[i - 1] + results[i - 2];
} else {
results[i] = results[i - 1];
}
} else {
// s[i - 2] == 1
results[i] = results[i - 1] + results[i - 2];
}
}
return results.back();
}
}; | true |
ca1bdb49681316531a37b3567f79cb79d885b65f | C++ | Breush/evilly-evil-villains | /src/nui/tablelayout.cpp | UTF-8 | 9,929 | 2.53125 | 3 | [] | no_license | #include "nui/tablelayout.hpp"
#include "tools/tools.hpp"
#include "tools/debug.hpp"
#include "tools/vector.hpp"
#include "config/nuiguides.hpp"
using namespace nui;
TableLayout::TableLayout()
: m_hPaddingAuto(true)
, m_vPaddingAuto(true)
{
setDetectable(false);
}
//-------------------//
//----- Routine -----//
void TableLayout::onSizeChanges()
{
refreshRowsSize();
refreshColsSize();
refreshDimensions();
refreshChildrenPosition();
}
void TableLayout::onChildSizeChanges(scene::Entity&)
{
// Note: It's not possible to detect which entity it is, and just refresh this one,
// because it might change the position dimensions of other rows/cols.
refreshRowsSize();
refreshColsSize();
refreshChildrenPosition();
}
void TableLayout::refreshNUI(const config::NUIGuides& cNUI)
{
// Be sure all children have there definitive size
baseClass::refreshNUI(cNUI);
m_hRefPadding = cNUI.hPadding;
m_vRefPadding = cNUI.vPadding;
refreshPaddingAuto();
refreshRowsSize();
refreshColsSize();
refreshDimensions();
refreshChildrenPosition();
}
//---------------------//
//----- Structure -----//
void TableLayout::setDimensions(uint rows, uint cols, float rowsStep, float colsStep)
{
m_rowsDimension = rows;
m_colsDimension = cols;
m_rowsStep = rowsStep;
m_colsStep = colsStep;
refreshDimensions();
}
void TableLayout::setRowAdapt(uint row, Adapt adapt, float param)
{
assert(row < m_rows.size());
if (m_autoSize && adapt != Adapt::FIT)
mquit("AutoSize forces all adapt to be FIT.");
m_rows[row].adapt = adapt;
if (adapt == Adapt::FIXED) m_rows[row].height = param;
refreshChildrenPosition();
}
void TableLayout::setColAdapt(uint col, Adapt adapt, float param)
{
assert(col < m_cols.size());
if (m_autoSize && adapt != Adapt::FIT)
mquit("AutoSize forces all adapt to be FIT.");
m_cols[col].adapt = adapt;
if (adapt == Adapt::FIXED) m_cols[col].width = param;
refreshChildrenPosition();
}
void TableLayout::overridePadding(float hPadding, float vPadding)
{
m_hPaddingAuto = hPadding < 0.f;
m_vPaddingAuto = vPadding < 0.f;
if (!m_hPaddingAuto) m_hPadding = hPadding;
if (!m_vPaddingAuto) m_vPadding = vPadding;
refreshPaddingAuto();
}
float TableLayout::colOffset(uint col)
{
if (col == -1u) col = m_cols.size();
assert(col < m_cols.size() + 1u);
float offset = 0.f;
for (uint c = 0u; c < col; ++c)
offset += m_cols[c].width;
return offset;
}
float TableLayout::rowOffset(uint row)
{
if (row == -1u) row = m_rows.size();
assert(row < m_rows.size() + 1u);
float offset = 0.f;
for (uint r = 0u; r < row; ++r)
offset += m_rows[r].height;
return offset;
}
float TableLayout::maxChildHeightInRow(uint row)
{
float maxHeight = 0.f;
for (uint c = 0u; c < m_cols.size(); ++c)
if (m_children.count({row, c}) != 0u)
maxHeight = std::max(maxHeight, m_children.at({row, c}).entity.size().y + 2.f * m_vPadding);
return maxHeight;
}
float TableLayout::maxChildWidthInCol(uint col)
{
float maxWidth = 0.f;
for (uint r = 0u; r < m_rows.size(); ++r)
if (m_children.count({r, col}) != 0u)
maxWidth = std::max(maxWidth, m_children.at({r, col}).entity.size().x + 2.f * m_hPadding);
return maxWidth;
}
void TableLayout::positionChild(uint row, uint col, float x, float y)
{
returnif (m_children.count({row, col}) == 0u);
auto& child = m_children.at({row, col});
float ox = 0.f, oy = 0.f;
// x coordinates
float dx = m_cols[col].width - child.entity.size().x;
if (child.hAlign == Align::STANDARD) ox = m_hPadding;
else if (child.hAlign == Align::CENTER) ox = dx / 2.f;
else if (child.hAlign == Align::OPPOSITE) ox = dx - m_hPadding;
// y coordinates
float dy = m_rows[row].height - child.entity.size().y;
if (child.vAlign == Align::STANDARD) oy = m_vPadding;
else if (child.vAlign == Align::CENTER) oy = dy / 2.f;
else if (child.vAlign == Align::OPPOSITE) oy = dy - m_vPadding;
child.entity.setLocalPosition({x + ox, y + oy});
// Clip child if too big
if (m_childrenClipping) {
sf::FloatRect clipArea{0.f, 0.f, -1.f, -1.f};
if (ox + m_hPadding > dx) clipArea.width = m_cols[col].width - (ox + m_hPadding);
if (oy + m_vPadding > dy) clipArea.height = m_rows[row].height - (oy + m_vPadding);
if (clipArea.width >= 0.f && clipArea.height < 0.f) clipArea.height = child.entity.size().y;
if (clipArea.width < 0.f && clipArea.height >= 0.f) clipArea.width = child.entity.size().x;
child.entity.setClipArea(clipArea);
}
}
void TableLayout::setAutoSize(bool autoSize)
{
m_autoSize = autoSize;
updateSize();
}
//--------------------//
//----- Children -----//
void TableLayout::setChild(uint row, uint col, scene::Entity& child, Align hAlign, Align vAlign)
{
assert(row < m_rows.size());
assert(col < m_cols.size());
// Remove there was another child here
removeChild(row, col);
// Add new child
attachChild(child);
ChildInfo childInfo{child, hAlign, vAlign};
m_children.insert({{row, col}, childInfo});
// If and only if we have a fit adapt column
refreshDimensions();
refreshChildrenPosition();
}
void TableLayout::setChildAlign(uint row, uint col, Align hAlign, Align vAlign)
{
returnif (m_children.count({row, col}) == 0u);
m_children.at({row, col}).hAlign = hAlign;
m_children.at({row, col}).vAlign = vAlign;
refreshChildrenPosition();
}
void TableLayout::removeChildren()
{
for (uint r = 0u; r < m_rows.size(); ++r)
for (uint c = 0u; c < m_cols.size(); ++c)
removeChild(r, c);
}
void TableLayout::removeChild(uint row, uint col)
{
returnif (m_children.count({row, col}) == 0u);
detachChild(m_children.at({row, col}).entity);
m_children.erase({row, col});
refreshChildrenPosition();
}
//-----------------------------------//
//----- Internal change updates -----//
void TableLayout::updateSize()
{
returnif (!m_autoSize);
sf::Vector2f currentSize;
for (const auto& col : m_cols)
currentSize.x += col.width;
for (const auto& row : m_rows)
currentSize.y += row.height;
setSize(currentSize);
}
void TableLayout::refreshChildrenPosition()
{
returnif (m_rowsDimension == 0u && m_rowsStep < 0.f);
returnif (m_colsDimension == 0u && m_colsStep < 0.f);
// Refresh size
refreshRowsSize();
refreshColsSize();
// Set new positions
float y = 0.f;
for (uint r = 0u; r < m_rows.size(); ++r) {
float x = 0.f;
for (uint c = 0u; c < m_cols.size(); ++c) {
positionChild(r, c, x, y);
x += m_cols[c].width;
}
y += m_rows[r].height;
}
}
void TableLayout::refreshRowsSize()
{
float heightLeft = size().y;
uint fillRowsCount = 0u;
// Set size for all non-fill rows
for (uint r = 0u; r < m_rows.size(); ++r) {
auto& row = m_rows[r];
switch (row.adapt) {
case Adapt::FILL:
++fillRowsCount;
break;
case Adapt::FIT:
row.height = maxChildHeightInRow(r);
heightLeft -= row.height;
break;
case Adapt::FIXED:
heightLeft -= row.height;
break;
}
}
// Set size for all fill rows
float heightHint = heightLeft / fillRowsCount;
for (auto& row : m_rows)
if (row.adapt == Adapt::FILL)
row.height = heightHint;
updateSize();
}
void TableLayout::refreshColsSize()
{
float widthLeft = size().x;
uint fillColsCount = 0u;
// Set size for all non-fill columns
for (uint c = 0u; c < m_cols.size(); ++c) {
auto& col = m_cols[c];
switch (col.adapt) {
case Adapt::FILL:
++fillColsCount;
break;
case Adapt::FIT:
col.width = maxChildWidthInCol(c);
widthLeft -= col.width;
break;
case Adapt::FIXED:
widthLeft -= col.width;
break;
}
}
// Set size for all fill columns
float widthHint = widthLeft / fillColsCount;
for (auto& col : m_cols)
if (col.adapt == Adapt::FILL)
col.width = widthHint;
updateSize();
}
void TableLayout::refreshDimensions()
{
if ((m_rowsDimension == 0u && m_rowsStep < 0.f)
|| (m_colsDimension == 0u && m_colsStep < 0.f)) {
m_rows.clear();
m_cols.clear();
return;
}
if (m_autoSize && (m_rowsDimension == 0u || m_colsDimension == 0u))
mquit("AutoSize demands precise table dimensions.");
// Estimating from step
uint rows = (m_rowsDimension == 0u)? size().y / m_rowsStep : m_rowsDimension;
uint cols = (m_colsDimension == 0u)? size().x / m_colsStep : m_colsDimension;
// Detach the children to be lost
for (uint r = rows; r < m_rows.size(); ++r)
for (uint c = cols; c < m_cols.size(); ++c)
removeChild(r, c);
// Do the actual resize
m_rows.resize(rows);
m_cols.resize(cols);
// Auto-adapt if fixed
if (m_rowsDimension == 0u) {
for (auto& row : m_rows) {
row.adapt = Adapt::FIXED;
row.height = m_rowsStep;
}
}
if (m_colsDimension == 0u) {
for (auto& col : m_cols) {
col.adapt = Adapt::FIXED;
col.width = m_colsStep;
}
}
// Remove Adapt::FILL if auto-size
if (m_autoSize) {
for (auto& row : m_rows)
row.adapt = Adapt::FIT;
for (auto& col : m_cols)
col.adapt = Adapt::FIT;
}
}
void TableLayout::refreshPaddingAuto()
{
if (m_hPaddingAuto) m_hPadding = m_hRefPadding;
if (m_vPaddingAuto) m_vPadding = m_vRefPadding;
}
| true |
f75be2fbeb51aeb3394f4dce89bf48a2eba9b7ea | C++ | michaeleisel/PathKitCExt | /Sources/PathKitCExt/PATPathKit.cpp | UTF-8 | 3,813 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "PATPathKit.h"
#include <string>
#include <vector>
#include <string>
#include <dirent.h>
using namespace std;
static inline void PATFillPathComponentsVector(vector<string> &strings, const char *path) {
size_t curPos = 0;
size_t endPos = strlen(path);
if (path[curPos] == '/') {
strings.push_back("/");
}
while (curPos < endPos) {
while (curPos < endPos && path[curPos] == '/') {
curPos++;
}
if (curPos == endPos) {
break;
}
auto curEnd = curPos;
while (curEnd < endPos && path[curEnd] != '/') {
curEnd++;
}
string str(path + curPos, curEnd - curPos);
strings.push_back(str);
curPos = curEnd;
}
if (endPos > 1 && path[endPos - 1] == '/') {
strings.push_back("/");
}
}
const char **PATPathComponents(const char *path, size_t *count, void **temp) {
if (!*path) {
*count = 0;
return new const char *[1];
}
vector<string> *strings = new vector<string>();
PATFillPathComponentsVector(*strings, path);
const char **components = new const char *[strings->size()];
for (int i = 0; i < strings->size(); i++) {
components[i] = (*strings)[i].c_str();
}
*count = strings->size();
return components;
}
static inline const char *PATPathFromComponents(const vector<string> &comps) {
if (comps.empty()) {
return strdup(".");
}
int i = 0;
int sum = 0;
string path;
for (const auto &comp : comps) {
sum += comp.size() + 1;
}
path.reserve(sum);
for (; i < comps.size(); i++) {
path.append(comps[i]);
if (i != comps.size() - 1) {
path.append("/");
}
}
if (comps.front() == "/" && comps.size() > 1) {
return strdup(path.c_str() + 1);
} else {
return strdup(path.c_str());
}
}
const char *PATAppend(const char *lhs, const char *rhs) {
vector<string> lSlice;
vector<string> rSlice;
PATFillPathComponentsVector(lSlice, lhs);
PATFillPathComponentsVector(rSlice, rhs);
// Get rid of trailing "/" at the left side
if (lSlice.size() > 1 && lSlice.back() == "/") {
lSlice.pop_back();
}
// Advance after the first relevant "."
lSlice.erase(remove(lSlice.begin(), lSlice.end(), "."), lSlice.end());
rSlice.erase(remove(rSlice.begin(), rSlice.end(), "."), rSlice.end());
// Eats up trailing components of the left and leading ".." of the right side
while (!lSlice.empty() && lSlice.back() != ".." && !rSlice.empty() && rSlice.front() == "..") {
if (lSlice.size() > 1 || lSlice.front() != "/") {
// A leading "/" is never popped
lSlice.pop_back();
}
rSlice.erase(rSlice.begin());
}
lSlice.insert(lSlice.end(), rSlice.begin(), rSlice.end());
return PATPathFromComponents(lSlice);
}
const char **PATContentsAt(const char *path, size_t *count, void **temp) {
vector<string> *paths = new vector<string>;
*temp = paths;
DIR *d;
struct dirent *dir;
d = opendir(path);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if (dir->d_name[0] == '.' && (dir->d_name[1] == '\0' || (dir->d_name[1] == '.' && dir->d_name[2] == '\0'))) {
continue;
}
paths->push_back(dir->d_name);
}
closedir(d);
}
const char **components = new const char *[paths->size()];
for (int i = 0; i < paths->size(); i++) {
components[i] = (*paths)[i].c_str();
}
*count = paths->size();
return components;
}
void PATFreePathComponents(const char **components, void *temp) {
delete components;
vector<string> *array = (vector<string> *)temp;
delete array;
}
| true |
b95f2f4a7cd18ff2b444705d8e73fa843aa1f973 | C++ | zerix/Cavium-SDK-2.0 | /linux/embedded_rootfs/source/lockstat/cond.h | UTF-8 | 3,425 | 2.78125 | 3 | [] | no_license | /* -*-C++-*- */
#include "stat-time.h"
#include "stats.h"
#include "mutex.h"
#include "errno.h"
class Cond_stat : public Stat<pthread_cond_t>
{
typedef __gnu_cxx::hash_map<pthread_mutex_t*, int> pthread_mutex_map;
public:
Cond_stat(lock_type* lock)
: Stat<pthread_cond_t>(lock), current_mutex_(0)
{}
std::string
misc(void) const
{
std::ostringstream os;
os << " mutex";
for (pthread_mutex_map::const_iterator i = mutexes_.begin();
i != mutexes_.end();
++i)
os << " " << i->first;
return os.str();
}
std::string
print(Stat_time total) const
{
std::ostringstream os;
os << "wait " << wait_time_.str(total)
<< " signal " << signal_time_.str(total);
return os.str();
}
void
operator+=(const Cond_stat& other)
{
wait_time_ += other.wait_time_;
signal_time_ += other.signal_time_;
if (!current_mutex_)
current_mutex_ = other.current_mutex_;
mutexes_.insert(other.mutexes_.begin(), other.mutexes_.end());
}
friend bool
operator<(const Cond_stat& a, const Cond_stat& b)
{ return a.signal_time_ < b.signal_time_; }
void
used_with(pthread_mutex_t *m)
{
current_mutex_ = m;
mutexes_[m] = 1;
}
enum signal_type { signal, broadcast };
private:
Stat_time wait_time_;
Stat_time signal_time_;
pthread_mutex_t *current_mutex_;
pthread_mutex_map mutexes_;
public:
static int
common_wait(pthread_cond_t*, pthread_mutex_t*, const struct timespec*);
static int
common_signal(pthread_cond_t*, signal_type);
static Stats<Cond_stat> stats;
};
int
Cond_stat::common_wait(pthread_cond_t* c, pthread_mutex_t* m,
const struct timespec* t)
{
if (!initialized || filter_out(c))
{
if (t)
return Wrapper::pthread_cond_timedwait(c, m, t);
else
return Wrapper::pthread_cond_wait(c, m);
}
Cond_stat& cs = Cond_stat::stats.lookup(c);
Mutex_stat* ms;
cs.used_with(m);
if (!Mutex_stat::filter_out(m))
ms = &Mutex_stat::stats.lookup(m);
Stat_time t0 = Stat_time::now();
int ret;
if (t)
ret = Wrapper::pthread_cond_timedwait(c, m, t);
else
ret = Wrapper::pthread_cond_wait(c, m);
if (ret != 0
&& ret != ETIMEDOUT)
return ret;
Stat_time waited = Stat_time::now() - t0;
cs.wait_time_ += waited;
// Mutex is unlocked while waiting for the condition.
if (ms)
ms->remove_hold_time(waited);
return ret;
}
extern "C" int
pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m)
{ return Cond_stat::common_wait(c, m, 0); }
extern "C" int
pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m,
const struct timespec *t)
{ return Cond_stat::common_wait(c, m, t); }
int
Cond_stat::common_signal(pthread_cond_t *c, signal_type s)
{
if (!initialized || filter_out(c))
{
if (s == signal)
return Wrapper::pthread_cond_signal(c);
else
return Wrapper::pthread_cond_broadcast(c);
}
Cond_stat& cs = Cond_stat::stats.lookup(c);
Stat_time t0 = Stat_time::now();
int ret;
if (s == signal)
ret = Wrapper::pthread_cond_signal(c);
else
ret = Wrapper::pthread_cond_broadcast(c);
cs.signal_time_ += Stat_time::now() - t0;
return ret;
}
extern "C" int
pthread_cond_signal(pthread_cond_t *c)
{ return Cond_stat::common_signal(c, Cond_stat::signal); }
extern "C" int
pthread_cond_broadcast(pthread_cond_t *c)
{ return Cond_stat::common_signal(c, Cond_stat::broadcast); }
| true |
774c188ae8040c3d47f962715cf569a182860b86 | C++ | rbwsok/3dfx-OpenGL-ICD-update | /src/oglcontrol/dynarray.cpp | WINDOWS-1251 | 1,022 | 2.984375 | 3 | [
"Unlicense"
] | permissive | #include "stdafx.h"
DYNARRAY::DYNARRAY(int basesize, int sizeelement)
{
currentsize = basesize;
DYNARRAY::basesize = basesize;
elementsize = sizeelement;
baseadress = GlobalAllocPtr(GPTR,basesize*sizeelement);
currentfree = 0;
}
DYNARRAY::~DYNARRAY()
{
if (baseadress != NULL) GlobalFree(baseadress);
}
int DYNARRAY::AddElement(void *adr)
{
if (currentfree < currentsize)
{
//
memcpy(((char*)baseadress + currentfree*elementsize),adr,elementsize);
}
else
{
// -
baseadress = GlobalReAllocPtr(baseadress,(currentsize + basesize)*elementsize,GMEM_ZEROINIT);
currentsize += basesize;
memcpy(((char*)baseadress + currentfree*elementsize),adr,elementsize);
}
currentfree++;
return currentfree - 1;
}
void* DYNARRAY::GetElement(int element)
{
if (element >= currentsize) return NULL; //
return (void*)(((char*)baseadress) + element*elementsize);
} | true |
7d7a3600ffd564afde30e83f2cbf7456e9d7c0ef | C++ | zoteva/oop-kn-5-2021 | /11/Templates Separation/Definitions in the .h file/TemplateObjectTests.cpp | UTF-8 | 164 | 2.625 | 3 | [] | no_license | #include "TemplateObject.h"
#include <iostream>
int main()
{
TemplateObject<int> intObject(2);
std::cout << intObject.data << std::endl;
return 0;
} | true |
853cc97c1013c2ef0b287d382228e336e8efe1fe | C++ | yuebinyun/google_test_sample | /sample4.cpp | UTF-8 | 281 | 2.59375 | 3 | [] | no_license | #include <stdio.h>
#include "sample4.h"
int Counter::Increment() {
return counter_++;
}
int Counter::Decrement() {
if (counter_ == 0) {
return counter_;
} else {
return counter_--;
}
}
void Counter::Print() const {
printf("%d\n", counter_);
} | true |
9e1fea0030daec57cde33f454348377d559d114b | C++ | Submitty/Submitty | /more_autograding_examples/cpp_cats/submissions/cat.h | UTF-8 | 586 | 3.0625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | #ifndef _cat_h_
#define _cat_h_
#include <string>
class Cat
{
public:
Cat();
Cat(std::string n, float av_size, float av_lifeSpan, std::string interesting);
//get functions
std::string getBreed() const { return name; }
float getAverageSize() const { return average_size; }
float getAverageLifeSpan() const { return average_lifeSpan; }
std::string getInterestingFact() const { return interestingFact; }
private:
std::string name;
float average_size;
float average_lifeSpan;
std::string interestingFact;
};
bool sortCats(const Cat& c1, const Cat& c2);
#endif | true |
7f66e2d70d655f819df93663c11216bd35fddef5 | C++ | tanhtm/Competitive-Programming | /OnlineJudge/UVa/146_IDCodes.cpp | UTF-8 | 327 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
#include <string.h>
#include <bitset>
using namespace std;
string s,stop("#");
void run(){
string t = s;
if (next_permutation(s.begin(),s.end()))
cout<<s;
else cout<<"No Successor";
cout<<endl;
}
int main(){
while(cin>>s && s != stop ){
run();
}
return 0;
} | true |
8dff82d0c72a59623de9ca6d60cffdffbc6a6e9a | C++ | eubr-atmosphere/a-GPUBench | /apps/tf_deepspeech/deepspeech/native_client/kenlm/lm/common/print.hh | UTF-8 | 1,471 | 2.671875 | 3 | [
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only",
"LGPL-3.0-only",
"GPL-3.0-only",
"Apache-2.0",
"MPL-2.0"
] | permissive | #ifndef LM_COMMON_PRINT_H
#define LM_COMMON_PRINT_H
#include "lm/word_index.hh"
#include "util/mmap.hh"
#include "util/string_piece.hh"
#include <cassert>
#include <vector>
namespace util { namespace stream { class ChainPositions; }}
// Warning: PrintARPA routines read all unigrams before all bigrams before all
// trigrams etc. So if other parts of the chain move jointly, you'll have to
// buffer.
namespace lm {
class VocabReconstitute {
public:
// fd must be alive for life of this object; does not take ownership.
explicit VocabReconstitute(int fd);
const char *Lookup(WordIndex index) const {
assert(index < map_.size() - 1);
return map_[index];
}
StringPiece LookupPiece(WordIndex index) const {
return StringPiece(map_[index], map_[index + 1] - 1 - map_[index]);
}
std::size_t Size() const {
// There's an extra entry to support StringPiece lengths.
return map_.size() - 1;
}
private:
util::scoped_memory memory_;
std::vector<const char*> map_;
};
class PrintARPA {
public:
// Does not take ownership of vocab_fd or out_fd.
explicit PrintARPA(int vocab_fd, int out_fd, const std::vector<uint64_t> &counts)
: vocab_fd_(vocab_fd), out_fd_(out_fd), counts_(counts) {}
void Run(const util::stream::ChainPositions &positions);
private:
int vocab_fd_;
int out_fd_;
std::vector<uint64_t> counts_;
};
} // namespace lm
#endif // LM_COMMON_PRINT_H
| true |
f7f28640029a537e4a18f9409d7a423962d23561 | C++ | danieljsharpe/cpp_primer | /brief_examples/copy_2dpointer.cpp | UTF-8 | 2,545 | 4.4375 | 4 | [] | no_license | /* Using std::copy to copy a 2d array via pointers */
#include <iostream>
using namespace std;
int main () {
// ONE DIMENSIONAL CASE
std::cout << "Example: 1D array\n\n";
const int cols = 3;
const int rows = 4;
double * foo = new double[cols];
double * bar = new double[cols];
double * baz = new double[cols];
int i, j;
for (i=0;i<cols;i++) {
*(foo+i) = double(i); }
std::copy(foo,foo+cols,bar);
for (i=0;i<cols;i++) {
std::cout << *(bar+i) << " "; }
std::cout << "\n\n";
// alternative
std::copy(&foo[0],&foo[0]+cols,&baz[0]);
for (i=0;i<cols;i++) {
std::cout << baz[i] << " "; }
std::cout << "\n\n";
delete [] foo;
delete [] bar;
delete [] baz;
// TWO DIMENSIONAL CASE
std::cout << "Example: 2D array\n\n";
double (*ham)[cols] = new double[rows][cols]; // only works if cols is const
double (*spam)[cols] = new double[rows][cols];
for (i=0;i<rows;i++) {
for (j=0;j<cols;j++) {
ham[i][j] = double(j) + (double(cols)*double(i));
}
}
std::copy(&ham[0][0],&ham[0][0]+(rows*cols),&spam[0][0]);
for (i=0;i<rows;i++) {
for (j=0;j<cols;j++) {
std::cout << spam[i][j] << " ";
}
std::cout << "\n";
}
std::cout << "\n";
delete [] ham;
delete [] spam;
// Note: the same std::copy syntax as above, for the 1D and 2D array case, can be used
// for the case of arrays declared as arrays (and not as pointers to arrays)
/* The above strictly deals with pointers to a 2D array. It is the correct way to create
a double[rows][cols] array and where all the memory is contiguous. If cols is not
a const, then our only other option is to create a dynamic 2D array that is essentially
an array of pointers to (1D) arrays. Note that this is more expensive in memory, and
more complicated to cleanup, because a memory block is allocated to each row (i.e.
memory is *not* contiguous. */
std::cout << "Example: '2D array' (non-contiguous)\n";
double ** eggs = new double*[rows];
for (i=0;i<rows;i++) {
eggs[i] = new double[cols]; }
for (i=0;i<rows;i++) {
std::copy(ham[i],ham[i]+cols,eggs[i]); }
for (i=0;i<rows;i++) {
for (j=0;j<cols;j++) {
std::cout << eggs[i][j] << " ";
}
std::cout << "\n";
}
std::cout << "\n";
for (i=0;i<rows;i++) {
delete [] eggs[i]; }
delete [] eggs;
return 0;
}
| true |
b52fa939dd464130d4d51ab1da7ea24938d35ad9 | C++ | abhay1432/FIU_TCN_5080 | /des.cpp | UTF-8 | 13,121 | 2.703125 | 3 | [
"MIT"
] | permissive | //============================================================================
// Name : TCN 5080 Secure Telecom Transaction. Project 1
// Author : Abhaykumar Kumbhar 5115320
// Version :
// File name: : des.cpp
// Description : Class file for simplified DES
//============================================================================
//system header includes
//user define includes
#include "defs.h"
#include "des.h"
#include "utility.h"
// Globals
// This permutation table combination is picked from the C-3 page of the handout
const int des::m_permutationTable[PERMUTE_TABLE_SIZE] = {2,6,3,1,4,8,5,7};
const int des::m_inversePermutationTable[PERMUTE_TABLE_SIZE] = {4,1,3,5,7,2,8,6};
const int des::m_p10Table[P10] = {3,5,2,7,4,10,1,9,8,6};
const int des::m_p08Table[P08] = {6,3,7,4,8,5,10,9};
const int des::m_p04Table[P04] = {2,4,3,1};
const int des::m_expandAndPermuteOp[EBOX] = {4,1,2,3,2,3,4,1};
extern utility* myUtility;
//=============================================
//Function: des::des
//Varibles: None
//Return Value: None
//Description: Contructor for des class
//=============================================
des::des()
{
m_subKey0 = string("");
m_subKey1 = string("");
}
//=============================================
//Function: des::~des
//Varibles: None
//Return Value: None
//Description: destructor for des class
//=============================================
des::~des()
{
}
//=============================================
//Function: des::initialPermutation
//input Variables: string inputStr ( string to permute)
//Return Value: string outputStr (permutated string)
//Description: based on the permutation table rearrange the input string.
// used in encrption
//=============================================
string des::initialPermutation(string inputStr)
{
string outputStr = string("");
for(unsigned int i = 0; i < PERMUTE_TABLE_SIZE; ++i)
{
outputStr += inputStr[des::m_permutationTable[i]-1 ];
}
// clog << "DEBUG: des::initialPermutation: input string: " << inputStr << endl;
// clog << "DEBUG: des::initialPermutation: permutated/output string: " << outputStr << endl;
return outputStr;
}
//=============================================
//Function: des::generateRoundKeys
//input Variables: string inputStr ( init key)
//Return Value: string outputStr (round key
//Description: Generate the round key
//=============================================
void des::generateRoundKeys(string key)
{
if(key.size() == DES_KEY_SIZE)
{
//perform permutation 10 on this key
key = p10(key);
//Split the key and shift
string keyLeft = myUtility->leftShift(key.substr(0,(DES_KEY_SIZE/2)));
string keyRight = myUtility->leftShift(key.substr((DES_KEY_SIZE/2), DES_KEY_SIZE));
//generate subkey 0 with permuatation 8
m_subKey0 = p08(keyLeft + keyRight);
cout <<"RESULT: des:generateRoundKeys: k1 " << m_subKey0 << endl;
//Left shift the bits again by 2
keyLeft = myUtility->leftShift(keyLeft);
keyRight = myUtility->leftShift(keyRight);
keyLeft = myUtility->leftShift(keyLeft);
keyRight = myUtility->leftShift(keyRight);
//Generate subkey 1 with permutation 8
m_subKey1 = p08(keyLeft + keyRight);
cout <<"RESULT: des:generateRoundKeys: k2 " << m_subKey1 << endl;
}
else
{
cerr<< "ERROR: des::generateRoundKeys: wrong key size. " << endl;
}
}
//=============================================
//Function: des::inversePermutation
//input Variables: string inputStr ( string to permute)
//Return Value: string outputStr (permutated string)
//Description: based on the permutation table rearrange the input string.
// used in decryption
//=============================================
string des::inversePermutation(string inputStr)
{
string outputStr = string("");
for(unsigned int i = 0; i < PERMUTE_TABLE_SIZE; ++i)
{
outputStr += inputStr[des::m_inversePermutationTable[i]-1 ];
}
// clog << "DEBUG: des::inverse Permutation: input string: " << inputStr << endl;
// clog << "DEBUG: des::inverse Permutation: permutated/output string: " << outputStr << endl;
return outputStr;
}
//=============================================
//Function: des::p10
//input Variables: string inputStr
//Return Value: string outputStr
//Description: Permutation 10 table
//=============================================
string des::p10(string inputStr)
{
string outputStr = string("");
for(unsigned int i = 0; i < P10; ++i)
{
outputStr += inputStr[des::m_p10Table[i]-1 ];
}
// clog << "DEBUG: des::p10 input string for P10: " << inputStr << endl;
// clog << "DEBUG: des::p10 output string after p10: " << outputStr << endl;
return outputStr;
}
//=============================================
//Function: des::p08
//input Variables: string inputStr
//Return Value: string outputStr
//Description: Permutation 08 table
//=============================================
string des::p08(string inputStr)
{
string outputStr = string("");
for(unsigned int i = 0; i < P08; ++i)
{
outputStr += inputStr[des::m_p08Table[i]-1 ];
}
// clog << "DEBUG: des::p08 input string for P08: " << inputStr << endl;
// clog << "DEBUG: des::p08 output string after P08: " << outputStr << endl;
return outputStr;
}
//=============================================
//Function: des::p04
//input Variables: string inputStr
//Return Value: string outputStr
//Description: Permutation 4 table
//=============================================
string des::p04(string inputStr)
{
string outputStr = string("");
for(unsigned int i = 0; i < P04; ++i)
{
outputStr += inputStr[des::m_p04Table[i]-1 ];
}
return outputStr;
}
//=============================================
//Function: des::eBox
//input Variables: string inputStr
//Return Value: string outputStr
//Description: Map an input with the expansion and
// permutation table and return the result
// Will expand a 4-bit string to 8-bits
//=============================================
string des::eBox(string inputStr)
{
string outputStr = string("");
for(unsigned int i = 0; i < EBOX; ++i)
{
outputStr += inputStr[ m_expandAndPermuteOp[i]-1 ];
}
// clog << "DEBUG: des::eBox: output " <<outputStr <<endl;
return outputStr;
}
//=============================================
//Function: des::createSbox0
//input Variables: None
//Return Value: none
//Description: creates S box 0 as show on C-5
//=============================================
void des::createSbox0(void)
{
//Fill the s box 0
vector<string> row;
row.push_back("01");
row.push_back("00");
row.push_back("11");
row.push_back("10");
m_sBox0.push_back(row);
row.clear();
row.push_back("11");
row.push_back("10");
row.push_back("01");
row.push_back("00");
m_sBox0.push_back(row);
row.clear();
row.push_back("00");
row.push_back("10");
row.push_back("01");
row.push_back("11");
m_sBox0.push_back(row);
row.clear();
row.push_back("11");
row.push_back("01");
row.push_back("11");
row.push_back("10");
m_sBox0.push_back(row);
}
//=============================================
//Function: des::createSbox1
//input Variables: None
//Return Value: none
//Description: creates S box 1 as show on C-5
//=============================================
void des::createSbox1(void)
{
vector<string> row;
row.push_back("00");
row.push_back("01");
row.push_back("10");
row.push_back("11");
m_sBox1.push_back(row);
row.clear();
row.push_back("10");
row.push_back("00");
row.push_back("01");
row.push_back("11");
m_sBox1.push_back(row);
row.clear();
row.push_back("11");
row.push_back("00");
row.push_back("01");
row.push_back("00");
m_sBox1.push_back(row);
row.clear();
row.push_back("10");
row.push_back("01");
row.push_back("00");
row.push_back("10");
m_sBox1.push_back(row);
}
//=============================================
//Function: des::perfomSboxColOp
//input Variables: string inputStr
//Return Value: string outputStr
//Description: Sbox column manipulation
//=============================================
int des::perfomSboxColOp(string inputStr)
{
//Use Bit-2 and Bit-3 for column
string colBin = string("");
colBin += inputStr[1];
colBin += inputStr[2];
int col = myUtility->BinToDec(colBin);
return col;
}
//=============================================
//Function: des::perfomSboxRowOp
//input Variables: string inputStr
//Return Value: string outputStr
//Description: Sbox row manipulation
//=============================================
int des::perfomSboxRowOp(string inputStr)
{
//Use Bit-1 and Bit-4 for row
string rowBin = string("");
rowBin += inputStr[0];
rowBin += inputStr[3];
int row = myUtility->BinToDec(rowBin);
return row;
}
//=============================================
//Function: des::sBox
//input Variables: string inputStr and int box number
//Return Value: string outputStr
//Description: Sbox manipulation
//=============================================
string des::sBox(string inputStr, short int box)
{
string outputStr = string("");
if (box == SBOX0)
{
createSbox0();
return m_sBox0[perfomSboxRowOp(inputStr)][perfomSboxColOp(inputStr)];
}
else if (box == SBOX1)
{
createSbox1();
return m_sBox1[perfomSboxRowOp(inputStr)][perfomSboxColOp(inputStr)];
}
else
{
return outputStr;
}
}
//=============================================
//Function: des::fBox
//input Variables: string inputStr and int round number
//Return Value: string outputStr
//Description: Permutation 4 table
//=============================================
string des::fBox(string inputStr, int round)
{
string outputStr = string("");
//Expand the input from 4-bits to 8-bits using ebox
inputStr = eBox(inputStr);
//XOR the input with the key for this round
if(round == ROUND0)
{
inputStr = myUtility->XOR(inputStr, m_subKey0);
}
else if (round == ROUND1)
{
inputStr = myUtility->XOR(inputStr, m_subKey1);
}
//Left half goes to sBox 0
string left = inputStr.substr(0,(inputStr.length()/2));
left = sBox(left, SBOX0);
//Right half goes to sBox 1
string right = inputStr.substr((inputStr.length()/2), inputStr.length());
right = sBox(right, SBOX1);
outputStr = left + right;
outputStr = p04(outputStr);
// clog <<"DEBUG: des:fBox: output " <<outputStr <<endl;
return outputStr;
}
//=============================================
//Function: des::verifyKeyAndTextSize
//input Variables: string key, string plainText
//Return Value: bool
//Description: returns true if the key and plain text are of right size
// else false
//=============================================
bool des::verifyKeyAndTextSize(string key, string plainText)
{
bool retValue = false; //default value
if ((key.size() == DES_KEY_SIZE) and (plainText.size() == BLOCK_SIZE))
{
retValue = true;
}
else
{
cerr <<"ERROR: des::verifyKeyAndTextSize " <<endl;
}
return retValue;
}
//=============================================
//Function: des::encrypt
//input Variables: None
//Return Value: string outputStr
//Description: des encryption
//=============================================
string des::encrypt(string plainText)
{
string outputStr = string("");
string permutatedString = string("");
string left = string("");
string right = string("");
//Do the initial permutation
permutatedString = initialPermutation(plainText);
//split the string
left = permutatedString.substr(0,(permutatedString.size()/2));
right = permutatedString.substr((permutatedString.size()/2), permutatedString.size());
//Apply XOR to the left half and fBox to the right half
left = myUtility->XOR(left, fBox(right, ROUND0));
//Swap left and right
left.swap(right);
//Apply XOR of left half and fBox of right half
left = myUtility->XOR(left, fBox(right, ROUND1));
//Do inverse initial permutation to get the cipher text
outputStr = inversePermutation((left+right));
// cout << "RESULT: des::encryt: cipher text "<< outputStr << endl;
return outputStr;
}
//=============================================
//Function: des::decrypt
//input Variables: None
//Return Value: string outputStr
//Description: des decryption
//=============================================
string des::decrypt(string cipherText)
{
string outputStr = string("");
string permutatedString = string("");
string left = string("");
string right = string("");
//Do the initial permutation
permutatedString = initialPermutation(cipherText);
//split the string
left = permutatedString.substr(0,(permutatedString.size()/2));
right = permutatedString.substr((permutatedString.size()/2), permutatedString.size());
//Apply XOR of left half and fBox of right half
left = myUtility->XOR(left, fBox(right, ROUND1));
//Swap left and right
left.swap(right);
//Apply XOR to the left half and fBox to the right half
left = myUtility->XOR(left, fBox(right, ROUND0));
//Do inverse initial permutation to get the cipher text
outputStr = inversePermutation((left+right));
// cout << "RESULT: des::decryt: plain text "<< outputStr << endl;
return outputStr;
}
| true |
48998ec9215f9231c77c4c9b632ffceaf57da51a | C++ | nqriver/Binary_Search_Tree | /BinarySearchTree.tpp | UTF-8 | 2,031 | 3.296875 | 3 | [] | no_license | #include "BinarySearchTree.h"
template<typename data_t>
BinarySearchTree<data_t>::BinarySearchTree(BinarySearchTree &&otherBST) noexcept :
_root{ std::move(otherBST._root) }
{
}
template<typename data_t>
BinarySearchTree<data_t> &BinarySearchTree<data_t>::operator=(BinarySearchTree&& otherBST) noexcept {
if (&otherBST == this)
return *this;
_root = std::move(otherBST._root);
return *this;
}
template<typename data_t>
template<typename InputIterator>
BinarySearchTree<data_t>::BinarySearchTree(InputIterator first, InputIterator last) {
while(first != last){
insert( *first );
++first;
}
}
template<typename data_t>
void BinarySearchTree<data_t>::insert(const data_t& key) {
_insert(key, _root);
}
template<typename data_t>
void BinarySearchTree<data_t>::insert(data_t&& key) {
_insert(std::forward<data_t>(key), _root);
}
template<typename data_t>
void BinarySearchTree<data_t>::remove(const data_t& key) {
_remove(key, _root);
}
template<typename data_t>
void BinarySearchTree<data_t>::remove(data_t&& key) {
_remove(std::forward<data_t>(key), _root);
}
template<typename data_t>
void BinarySearchTree<data_t>::print(std::ostream& out) {
_print(out, ">", _root, false);
}
template<typename data_t>
void BinarySearchTree<data_t>::traverse(std::function<void(data_t)> action) {
_traverse(action, _root);
}
template<typename data_t>
bool BinarySearchTree<data_t>::empty() const {
return (_root == nullptr);
}
template<typename data_t>
data_t BinarySearchTree<data_t>::maxElement() {
return _maxElement(_root);
}
template<typename data_t>
data_t BinarySearchTree<data_t>::minElement() {
return _minElement(_root);
}
template<typename data_t>
bool BinarySearchTree<data_t>::contains(const data_t& key) {
return _contains(key, _root);
}
template<typename data_t>
void BinarySearchTree<data_t>::clear() {
_clear(_root);
}
template<typename data_t>
std::size_t BinarySearchTree<data_t>::depth() {
return _depth(_root);
}
| true |
4304eebde9d1ab294d090f74dad94a32c23c3e21 | C++ | kyvauneb/CISC2200- | /LinkedList/student.h | UTF-8 | 626 | 2.953125 | 3 | [] | no_license | /*
* Kyvaune Brammer
*
* Linked List Lab Part 1 - Papadakis
*
* 10/5/2016
*
* Student Class header file
*
*/
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
using namespace std;
class Student {
public:
Student();
Student( string fN, char m, string lN, int s, int age);
void setFName( string fN);
string getFName();
void setMInit( char m);
char getMInit();
void setLName ( string lN);
string getLName();
void setSocial( int s);
int getSocial();
void setAge( int a);
int getAge();
void displayStudent();
private:
string fName;
char mInit;
string lName;
int social;
int age;
};
#endif
| true |
e09ddee9ed42aae294ac70ba379c5d2970aa4aa3 | C++ | constanreedjohn/Algorithms_and_Data_Structures | /Sorting_Algoritms_Time_Compare.cpp | UTF-8 | 5,615 | 3.296875 | 3 | [] | no_license | #include<iostream>
#include<time.h>
#include<algorithm>
using namespace std;
#define MAX1 10e6
#define MAX2 100000
double A[(int)MAX1];
double B[(int)MAX1];
double C[(int)MAX1];
double D[(int)MAX1];
void Random_Thuc(double a[],int &n)
{
int Max_Rand=rand()%MAX2;
for(int i=0;i<n;i++)
{
a[i]=rand()+(rand()/(double)Max_Rand);
}
}
void OutPut(double a[],int n)
{
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
}
void Convert(double a[],double b[],int &n)
{
double temp;
for(int i=0;i<n;i++)
{
temp=a[i];
b[i]=temp;
}
}
int Partition(double x[],int low,int high)
{
int pivot=x[high];
int left=low;
int right=high-1;
while(true){
while(left<=right && x[left]<pivot)
left++;
while(right>=left && x[right]>pivot)
right--;
if(left>=right)
break;
swap(x[left],x[right]);
left++;
right--;
}
swap(x[left],x[high]);
return left;
}
void QuickSort(double x[], int low, int high)
{
if(low<high)
{
int pi=Partition(x,low,high);
QuickSort(x,low,pi-1);
QuickSort(x,pi+1,high);
}
}
void Merge(double a[],int l,int m,int r)
{
int i,j,k;
int n1=m-l+1;
int n2=r-m;
// Create 2 halves arrays
int L[n1],R[n2];
// Copy data into 2 arrays L[] and R[]
for(i=0;i<n1;i++)
L[i]=a[l+i];
for(j=0;j<n2;j++)
R[j]=a[m+1+j];
// Merge both arrays into 1 array
i=0; // First Subarray S1[i]
j=0; // Second Subarray S2[j]
k=l; // Merge Subarray a[k]
while(i<n1 && j<n2)
{
if(L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while(i<n1)
{
a[k]=L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while(j<n2)
{
a[k]=R[j];
j++;
k++;
}
}
void MergeSort(double a[],int l,int r)
{
if(l<r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m=l+(r-l)/2;
// Sort first and second halves
MergeSort(a,l,m);
MergeSort(a,m+1,r);
Merge(a, l, m, r);
}
}
void Heapify(double a[],int n,int i)
{
int largest=i; // Initialize largest as root
int l=2*i+1; // left = 2*i + 1
int r=2*i+2; // right = 2*i + 2
// If left child is larger than root
if(l<n && a[l]>a[largest])
largest=l;
// If right child is larger than largest so far
if(r<n && a[r]>a[largest])
largest=r;
// If largest is not root
if(largest!=i)
{
swap(a[i],a[largest]);
// Recursively heapify the affected sub-tree
Heapify(a,n,largest);
}
}
// main function to do heap sort
void HeapSort(double a[],int n)
{
// Build heap (rearrange array)
for(int i=n/2-1;i>=0;i--)
Heapify(a,n,i);
// One by one extract an element from heap
for(int i=n-1;i>0;i--)
{
// Move current root to end
swap(a[0],a[i]);
// call max heapify on the reduced heap
Heapify(a,i,0);
}
}
float Time_Process_HS(double a[],int n)
{
clock_t Start,End;
double cpu_time_used;
Start=clock();
HeapSort(a,n);
End=clock();
cpu_time_used=((double) (End - Start)) / CLOCKS_PER_SEC;
return cpu_time_used;
}
float Time_Process_MS(double a[],int n)
{
clock_t Start,End;
double cpu_time_used;
Start=clock();
MergeSort(a,0,n-1);
End=clock();
cpu_time_used=((double) (End - Start)) / CLOCKS_PER_SEC;
return cpu_time_used;
}
float Time_Process_QS(double a[],int n)
{
clock_t Start,End;
double cpu_time_used;
Start=clock();
QuickSort(a,0,n-1);
End=clock();
cpu_time_used=((double) (End - Start)) / CLOCKS_PER_SEC;
return cpu_time_used;
}
float Time_Process_CSort(double a[],int n)
{
clock_t Start,End;
double cpu_time_used;
Start=clock();
std::sort(a,a+n);
End=clock();
cpu_time_used=((double) (End - Start)) / CLOCKS_PER_SEC;
return cpu_time_used;
}
int main()
{
int n=100000;
cout<<"19521587_Tran Tien Hung_ BTLon"<<endl;
cout<<"Khao sat thoi gian cua tung giai thuat Sort"<<endl<<endl;
cout<<"|=============================================================================================|"<<endl;
cout<<"| Database | QuickSort | HeapSort | MergeSort | CSort |"<<endl;
cout<<"|=============================================================================================|"<<endl;
for(int i=0;i<15;i++)
{
Random_Thuc(A,n);
Random_Thuc(B,n);
Random_Thuc(C,n);
Random_Thuc(D,n);
QuickSort(A,0,n-1);
HeapSort(B,n);
MergeSort(C,0,n-1);
std::sort(D,D+n);
cout<<"| Database "<<i+1<<" | "<<Time_Process_QS(A,n)<<" | "<<Time_Process_HS(B,n)<<" | "<<Time_Process_MS(C,n)<<" | |"<<Time_Process_CSort(D,n)<<" |"<<endl;
}
cout<<"|=============================================================================================|"<<endl;
}
| true |
486af9ab6db20f80beb2c84e3f30a2a01c4017ee | C++ | TycheLaughs/xmlToJSON | /Attribute.h | UTF-8 | 2,023 | 3.65625 | 4 | [] | no_license | /**
* File: Attribute.h
* Author: Uzi sksouza.art@gmail.com
* Assignment 04: Building a Tree Struture from an XML File
* Created on October 20, 2014 for use in Assignment 04.
*/
#ifndef ATTRIBUTE_H
#define ATTRIBUTE_H
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Attribute{
private:
/**
* Attribute name
*/
string name;
/**
* Attribute value
*/
string value;
public:
/** Attribute default contructor
* sets name and value strings to empty string
*@return returns an Attribute object
*/
Attribute();
/** Attribute contructor
* sets name and value strings to empty string
*@param n holds the value to be stored in the name member of Attribute
*@param v holds the value to be stored in the value member of Attribute
*/
Attribute(string n, string v);
/**Attribute copy constructor
*@param orig is the Attribute whose member values are to be copied
*@return returns an Attribute object
*/
Attribute(const Attribute& orig);
/** Attribute Destructor
*Destroys Attribute object
*/
virtual ~Attribute();
/**Sets the value of the name member of Attribute object
*@param attr value to which the string should be set
*@return nothing
*/
void setName(string attr);
/**Sets the value of the value member of Attribute object
*@param val value to which the string should be set
*@return nothing
*/
void setValue(string val);
/** Gets the value of the value member of the Attribute
*@return the value stores in the value member of the Attribute object
*/
string getValue();
/**Gets value of name member of Attribute
*@return the value stored in the name member of Attribute object
*/
string getAttrName();
/**Overloaded operator <<, used for outputting member values of the Attribute objects
*@param out ostream object: stream used for output
*@param attr Attribute object whose data is being output
*@return
*/
friend ostream& operator <<(ostream& out, Attribute& attr);
};
#endif //Attribute.h | true |
1aaeb703426849de06141febc3d381502c9ebdab | C++ | JamesMillerDev/EcceSimulacrum | /fonts.cpp | UTF-8 | 7,889 | 2.75 | 3 | [] | no_license | //#include <Windows.h>
#include "fonts.h"
#include "GameParams.h"
#include "Computer.h"
using namespace std;
struct GlyphStruct
{
FT_Bitmap bitmap;
FT_Int bitmap_left;
FT_Int bitmap_top;
FT_Vector advance;
};
FT_Library library;
FT_Face face, face1, face2, face3;
int font_number = 1;
map<string, GlyphStruct*> glyphs;
void init_fonts()
{
FT_Error error = FT_Init_FreeType( &library ); //TODO FREE THIS
if (error)
{
exit(1);
}
error = FT_New_Face(library, "Lato-Regular.ttf", 0, &face); //AND THIS
if (error)
{
exit(1);
}
face1 = face;
error = FT_New_Face(library, "LiberationMono-Bold.ttf", 0, &face2); //AND THIS
if (error)
{
exit(1);
}
error = FT_New_Face(library, "Audiowide-Regular.ttf", 0, &face3); //AND THIS
if (error)
{
exit(1);
}
}
void change_font(string name)
{
if (name == "Lato-Regular.ttf")
{
face = face1;
font_number = 1;
}
if (name == "LiberationMono-Bold.ttf")
{
face = face2;
font_number = 2;
}
if (name == "Audiowide-Regular.ttf")
{
face = face3;
font_number = 3;
}
}
void right_justify(TextureManager* texture_manager, int size, std::string c, int x, int y, bool display, bool highlight, int box_height, bool no_scale, bool load, bool give_widths)
{
auto widths = draw_string(texture_manager, size, c, x, y, false, highlight, box_height, no_scale, load, give_widths);
float width = widths.back();
draw_string(texture_manager, size, c, (int)(x - width), y, display, highlight, box_height, no_scale, load, give_widths);
}
void get_string_widths(int points, std::string str, float* arr)
{
FT_Set_Char_Size(face, 0, points * 30, 0, 0);
float pen = 0;
int previous = 0;
int i = 0;
for (i = 0; i < str.length(); ++i)
{
char chr = str[i];
FT_UInt glyph_index = FT_Get_Char_Index(face, (int)chr);
if (previous)
{
FT_Vector delta;
FT_Get_Kerning(face, previous, glyph_index, FT_KERNING_DEFAULT, &delta);
pen += delta.x >> 6;
}
string key = to_string(font_number) + to_string(points);
GlyphStruct glyph = glyphs[key][(int)chr];
arr[i] = pen;
pen += glyph.advance.x >> 6;
previous = glyph_index;
}
arr[i] = pen;
}
vector<float> draw_string(TextureManager* texture_manager, int points, std::string str, int x, int y, bool display, bool highlight, int box_height, bool no_scale, bool load, bool give_widths, bool give_height)
{
FT_Set_Char_Size(face, 0, points * 30, 0, 0); //TODO: get real DPI
vector<float> string_widths;
if (highlight && str != "" && box_height != 0)
{
vector<float> widths = draw_string(texture_manager, points, str, x, y, false, false);
float xend = widths[widths.size() - 1];
glDisable(GL_TEXTURE_2D);
glColor4f(0.0, 120.0 / 255.0, 215.0 / 255.0, 1.0);
if (!no_scale)
{
glBegin(GL_QUADS);
glVertex2f(scalex(x), scaley(y - 5));
glVertex2f(scalex(x), scaley(y - 5 + box_height));
glVertex2f(scalex(x + xend), scaley(y - 5 + box_height));
glVertex2f(scalex(x + xend), scaley(y - 5));
glEnd();
}
else
{
glBegin(GL_QUADS);
glVertex2f(x, y - 5);
glVertex2f(x, y - 5 + box_height);
glVertex2f(x + xend, y - 5 + box_height);
glVertex2f(x + xend, y - 5);
glEnd();
}
glEnable(GL_TEXTURE_2D);
glColor4f(1.0, 1.0, 1.0, 1.0);
}
float pen = x;
int previous = 0;
for (int i = 0; i < str.length(); ++i)
{
char chr = str[i];
if (chr == '\n')
continue;
GlyphStruct glyph;
FT_UInt glyph_index = FT_Get_Char_Index(face, (int)chr);
string key = to_string(font_number) + to_string(points);
if (load)
{
if (glyphs[key] == 0)
glyphs[key] = (GlyphStruct*)malloc(128 * sizeof(GlyphStruct));
FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
int index = (int)chr;
GlyphStruct glyph_struct;
glyph_struct.advance = face->glyph->advance;
glyph_struct.bitmap = face->glyph->bitmap;
glyph_struct.bitmap_left = face->glyph->bitmap_left;
glyph_struct.bitmap_top = face->glyph->bitmap_top;
glyphs[key][index] = glyph_struct;
glyph = glyph_struct;
}
else
{
glyph = glyphs[key][(int)chr];
}
int yoffset = 0;
if (chr == -107)
{
str[i] = '.';
yoffset = 5;
}
if (previous)
{
FT_Vector delta;
FT_Get_Kerning(face, previous, glyph_index, FT_KERNING_DEFAULT, &delta);
pen += delta.x >> 6;
}
FT_Bitmap bitmap = glyph.bitmap;
float start_x = pen + glyph.bitmap_left;
float start_y = y - (bitmap.rows - glyph.bitmap_top) + yoffset;
if (give_widths)
string_widths.push_back(pen - x);
if (give_height)
{
if (string_widths.empty() || glyph.bitmap_top > string_widths[0])
{
string_widths.clear();
string_widths.push_back(glyph.bitmap_top);
}
}
int array_num = 0;
if (font_number == 1 && points == 32 && !highlight)
array_num = 0;
else if (font_number == 1 && points == 32 && highlight)
array_num = 1;
else if (font_number == 1 && points == 64 && highlight)
array_num = 2;
else if (font_number == 1 && points == 64 && !highlight)
array_num = 3;
else if (font_number == 2)
array_num = 4;
else if (font_number == 3 && points == 90)
array_num = 5;
else array_num = 6;
if (display || load)
texture_manager->change_character(bitmap, chr, highlight, array_num, load);
if (display)
{
if (!no_scale)
{
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex2f(scalex(start_x), scaley(start_y));
glTexCoord2f(0.0, 1.0); glVertex2f(scalex(start_x), scaley(start_y + bitmap.rows));
glTexCoord2f(1.0, 1.0); glVertex2f(scalex(start_x + bitmap.width), scaley(start_y + bitmap.rows));
glTexCoord2f(1.0, 0.0); glVertex2f(scalex(start_x + bitmap.width), scaley(start_y));
glEnd();
}
else
{
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex2f(start_x, start_y);
glTexCoord2f(0.0, 1.0); glVertex2f(start_x, start_y + bitmap.rows);
glTexCoord2f(1.0, 1.0); glVertex2f(start_x + bitmap.width, start_y + bitmap.rows);
glTexCoord2f(1.0, 0.0); glVertex2f(start_x + bitmap.width, start_y);
glEnd();
}
}
pen += glyph.advance.x >> 6;
previous = glyph_index;
}
if (give_widths)
string_widths.push_back(pen - x);
return string_widths;
}
void draw_string_bounded(TextureManager* texture_manager, int size, std::string str, int x, int y, int end_x, int spacing)
{
int current_y = y;
while (str.length() != 0)
{
vector<float> string_widths = draw_string(texture_manager, size, str, x, current_y, false);
int last_space = 0;
int i;
for (i = 0; i < str.length(); ++i)
{
if (str[i] == '\n')
{
last_space = i;
break;
}
if (str[i] == ' ')
last_space = i;
if (string_widths[i] >= end_x - x)
break;
}
if (last_space == 0)
last_space = i;
if (i == str.length())
last_space = i;
string line = str.substr(0, last_space + 1);
draw_string(texture_manager, size, line, x, current_y);
str.erase(0, last_space + 1);
current_y -= spacing;
}
}
pair<int, int> get_top_and_bottom(string str, int points)
{
int top = 0;
int bottom = 0;
FT_Error error = FT_Set_Char_Size(face, 0, points * 30, 0, 0);
for (int i = 0; i < str.length(); ++i)
{
FT_UInt glyph_index = FT_Get_Char_Index(face, (int)str[i]);
FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
FT_Bitmap bitmap = face->glyph->bitmap;
if (face->glyph->bitmap_top > top)
top = face->glyph->bitmap_top;
if (bitmap.rows - face->glyph->bitmap_top < bottom)
bottom = bitmap.rows - face->glyph->bitmap_top;
}
return pair<int, int>(top, bottom);
} | true |
886c232d3786841602ca84ae2abeab1a62cca53d | C++ | BilhaqAD07/AlgoritmaPemrograman | /SEMESTER 2/PRAKTIKUM/Minggu 1/Catur.cpp | UTF-8 | 465 | 2.734375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int X;
cin>>X;
cin.ignore();
string peserta[X];
int total;
int count=0;
if(X<=0){
cout<<"Error";
exit(0);
}
for(int i=0;i<X;i++){
cin>>peserta[i];
}
for(int i=0;i<X;i++){
for(int j=i;j<X;j++){
if(j>X-2){
goto quit;
}
for(int k=j+1;k<X;k++){
cout<<peserta[j]<<"-"<<peserta[k]<<endl;
count++;
}
}
}
quit:
total=count*3;
cout<<"USD "<<total;
return 0;
} | true |
e440d4b15718b2268d907aad4034614451eddcd6 | C++ | Arios39/Object-Oriented-Programming | /SpaceProject/Lab6/App.cpp | UTF-8 | 5,161 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include "App.h"
App* singleton;
void draw();
void timer(int id){
// This will get called every 16 milliseconds after
// you call it once
float amount;
float back = singleton->background1->getY();
float back2 = singleton-> background2->getY();
float back3 = singleton->background3->getY();
float rocky1 = singleton->rock1->getY();
float rocky2 = singleton->rock1->getY();
float rocky3 = singleton->rock1->getY();
if(!singleton->running){
singleton->redraw();
}
if(singleton->running){
if(rocky1<=-1){
rocky1=5;
}
if(rocky2<=-1){
rocky2=5;
}
if(rocky3<=-1){
rocky3=5;
}
else{
if (rocky1 >= 2){
rocky1 = rocky1-3;
}
if (rocky2 >= 2){
rocky2 = rocky2-3;
}
if (rocky2 >= 2){
rocky2 = rocky2-3;
}
}
amount=-singleton->inc;
singleton->rock1->setY(rocky1+ amount);
singleton->rock2->setY(rocky2+ amount);
singleton->rock3->setY(rocky3+ amount);
singleton->redraw();
}
if (singleton->running) { //Moving BackGround
if (back <= -1) {
back = 5;
}
if (back2 <= -1) {
back2 = 5;
}
if (back3 <= -1) {
back3 = 5;
}
else {
if (back >= 2) {
back = back - 3;
}
if (back2 >= 2) {
back2 = back2 - 3;
}
if (back3 >= 2) {
back3 = back3 - 3;
}
}
amount = -singleton->Binc;
singleton->background1->setY(back + amount);
singleton->background2->setY(back2 + amount);
singleton->background3->setY(back3 + amount);
singleton->redraw();
}
if (singleton->up&&singleton->running){
float ypos = singleton->projectile->getY();
ypos +=0.05;
singleton->projectile->setY(ypos);
singleton->redraw();
singleton->up= false;
}
if(singleton->left&&singleton->running){
float xneg = singleton->projectile->getX();
xneg-=0.25;
singleton->projectile->setX(xneg);
singleton->redraw();
singleton->left= false;
}
if(singleton->right&&singleton->running){
float xpos = singleton->projectile->getX();
xpos+=0.25;
singleton->projectile->setX(xpos);
singleton->redraw();
singleton->right= false;
}
if(singleton->shoot&&singleton->running){
float ypos = singleton->blaster->getY();
ypos +=0.02;
singleton->blaster->setY(ypos);
singleton->redraw();
}
if (singleton->down && singleton->running) { //Stuff to go down
float ypos = singleton->projectile->getY();
ypos -= 0.05;
singleton->projectile->setY(ypos);
singleton->redraw();
singleton->down = false;
}
glutTimerFunc(16, timer, id);
}
App::App(int argc, char** argv, int width, int height, const char* title): GlutApp(argc, argv, width, height, title){
rock1 = new TexRect("/Users/andresrios/SpaceProject/Lab6/rock.png", -0.3, 0.9, 0.5, 0.5);
rock2 =new TexRect("/Users/andresrios/SpaceProject/Lab6/rock.png", -.96, 0.9, 0.3, 0.3);
rock3 =new TexRect("/Users/andresrios/SpaceProject/Lab6/rock.png", 0.5, 0.9, 0.8, 0.7);
blaster = new TexRect("/Users/andresrios/SpaceProject/Lab6/blaster.png", 0.5, 0.9, 0.5, 0.5);
projectile =new TexRect("/Users/andresrios/SpaceProject/Lab6/ship.png", -0.5, -0.8, 0.3, 0.3);
gameover =new TexRect("/Users/andresrios/SpaceProject/Lab6/download.png", -1.0, 1.0, 2, 2);
background1 =new TexRect("/Users/andresrios/SpaceProject/Lab6/stars.png", -1.0, 1.0, 2, 2);
background2 =new TexRect("/Users/andresrios/SpaceProject/Lab6/stars.png", -1.0, 3.0, 2, 2);
background3 = new TexRect("/Users/andresrios/SpaceProject/Lab6/stars.png", -1.0, 5.0, 2, 2); //Added third BackGround
explosion = new AnimatedRect("/Users/andresrios/SpaceProject/Lab6/fireball.bmp", 6, 6, 150, true, true, rock1->getX(), rock1->getY(), 0.5, 0.5);
up = false;
inc=0.04;
Binc = 0.02; //Incrememnt for Backgrounds
left = false;
move = true;
running = true;
singleton = this;
shoot= false;
timer(1);
}
void App::draw() {
background1->draw(0.0);
background2->draw(0.0);
background3->draw(0.0);
projectile->draw(0.1);
rock1->draw(0.1);
rock2-> draw(0.1);
rock3->draw(0.1);
if (projectile->getY() >= (rock1->getY() + 0.0) && projectile->getX() >= (rock1->getX() + 0.0) ) {
running = false;
up = false;
singleton->gameover->draw(0.1);
singleton->explosion->draw(0.1);
}
}
void App::idle(){
}
void App::keyDown(unsigned char key, float x, float y){
if (key == 27){
exit(0);
}
if (key == ' '){
shoot = true;
}
if(key == 'a'){
left =true;
}
if(key == 'w'){
up= true;
}
if(key=='d'){
right = true;
}
if (key == 's') { //Added Down Button
down = true;
}
}
App::~App(){
delete rock1;
std::cout << "Exiting..." << std::endl;
}
| true |
45c6badf150b5cbde4ed9411bb9761e893c4f450 | C++ | shreysingla11/ssl-project | /Backend/Parser/submissions/Assignment 7/28.cpp | UTF-8 | 2,532 | 3.4375 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<iterator>
using namespace std;
class bank
{
public:
map<string,int> m;
map<int,set<string> >p;
map<int,set<string> >::iterator it1;
map<string,int>::iterator it;
int error;
bank()
{
error=0;
}
void open(string s);
void deposit(string s,int n);
void withdraw(string s,int n);
void close(string s);
void print(int min,int max);
};
struct ltstr
{
bool operator()(int s1, int s2)
{
return (s1<=s2);
}
};
int main()
{
bank b;
char ch;
string name;
int bal,min,max;
while(true)
{
cin>>ch;
switch (ch)
{
case 'O' :cin>>name;
b.open(name);
break;
case 'C' :cin>>name;
b.close(name);
break;
case 'D' :cin>>name>>bal;
b.deposit(name,bal);
break;
case 'W' :cin>>name>>bal;
b.withdraw(name,bal);
break;
case 'P' :cin>>min>>max;
b.print(min,max);
break;
case 'E' :cout<<b.error;
return 0;
break;
}
}
}
void bank::open(string s)
{
if (m.find(s)==m.end()) //if not already present add account
{
m[s]=0;
p[0].insert(s);
}
else
{
error++;
}
}
void bank::close(string s)
{
it = m.find(s);
if (it != m.end()) //if present
{
if(m[s]==0)
{
m.erase (it);
p[0].erase(s);
if(p[0].size()==0)
p.erase(m[s]);
}
else //Balance !=0
{
error++;
}
}
else //Not present
{
error++;
}
}
void bank::deposit(string s,int n)
{
if(m.find(s)!=m.end()) //Account already exists
{
p[m[s]].erase(s);
if(p[m[s]].size()==0)
p.erase(m[s]);
m[s]=m[s]+n;
p[m[s]].insert(s);
}
else
{
error++;
}
}
void bank::withdraw(string s,int n)
{
if(m.find(s)!=m.end()) //Account exists
{
if(m[s]>=n)
{
p[m[s]].erase(s);
if(p[m[s]].size()==0)
p.erase(m[s]);
m[s]=m[s]-n;
p[m[s]].insert(s);
}
else //Balance not sufficient
{
error++;
}
}
else //Account not present
{
error++;
}
}
void bank::print(int min,int max)
{
it1=p.begin();
while(it1!=p.end())
{
if(it1->first >=min&& it1->first<=max)
{
cout<<it1->first<<" ";
copy(it1->second.begin(), it1->second.end(), ostream_iterator<string>(cout, " "));
cout<<endl;
it1++;
}
}
}
| true |
eb4bed8c19033f45c1a03e512523782b883c0f95 | C++ | ankan-ekansh/Competitive-Programming | /Codeforces practice/427C.cpp | UTF-8 | 1,648 | 2.640625 | 3 | [] | no_license | /*
Stay motivated and keep working hard
*/
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod = 1e9+7;
const ll N = 3e5+7;
ll n, m;
vector<ll> G[N];
vector<ll> G_rev[N];
vector<ll> cost(N);
vector<bool> vis_f(N), vis_b(N);
stack<ll> dfsorder;
void dfs_f(ll u){
vis_f[u] = true;
for(ll v : G[u]){
if(!vis_f[v]){
dfs_f(v);
}
}
dfsorder.push(u);
}
pair<ll, ll> dfs_b(multiset<ll> &s, ll u){
vis_b[u] = true;
s.insert(cost[u]);
for(ll v : G_rev[u]){
if(!vis_b[v]){
dfs_b(s, v);
}
}
return {*s.begin(), s.count(*s.begin())};
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
// freopen("output.txt", "wt", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
for(ll i=1;i<=n;i++){
cin >> cost[i];
}
cin >> m;
for(ll i=1;i<=m;i++){
ll u, v;
cin >> u >> v;
G[u].push_back(v);
G_rev[v].push_back(u);
}
for(ll i=1;i<=n;i++){
if(!vis_f[i]){
dfs_f(i);
}
}
ll cost = 0, ways = 1;
while(!dfsorder.empty()){
ll s = dfsorder.top();
dfsorder.pop();
if(vis_b[s]){
continue;
}
multiset<ll> st;
pair<ll, ll> x;
x = dfs_b(st, s);
cost += x.first;
ways = (ways * x.second)%mod;
}
cout << cost << " " << ways << "\n";
#ifndef ONLINE_JUDGE
cout<<"\nTime Elapsed : " << 1.0*clock() / CLOCKS_PER_SEC << " s\n";
#endif
return 0;
} | true |
0d598c4080e85b17ca2c823efbdf8b2f519bcf47 | C++ | reineydays/reine-performing-robots | /code/agnus-gyroscope/agnus-gyroscope.ino | UTF-8 | 1,588 | 2.609375 | 3 | [] | no_license | #include <Wire.h>
#include <L3G.h>
L3G gyro;
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6
#define NUMPIXELS 1
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int red = 0;
int green = 0;
int blue = 0;
int r;
int g;
int b;
int zaxis;
long xcal = 0;
long ycal = 0;
long zcal = 0;
long xavg, yavg, zavg;
long counter = 0;
void setup() {
pixels.begin();
Serial.begin(9600);
Wire.begin();
if (!gyro.init())
{
Serial.println("Failed to autodetect gyro type!");
while (1);
}
gyro.enableDefault();
int numberofreads = 100;
Serial.println("Initialising calibration");
while(counter < numberofreads){
xcal += (int)gyro.g.x;
ycal += (int)gyro.g.y;
zcal += (int)gyro.g.z;
counter ++;
delay(10);
}
xavg = xcal / numberofreads;
yavg = ycal / numberofreads;
zavg = zcal / numberofreads;
}
void loop() {
gyro.read();
//
// Serial.print("G ");
// Serial.print("X: ");
// Serial.print(xavg - (int)gyro.g.x / 100);
// Serial.print(" Y: ");
// Serial.print(yavg - (int)gyro.g.y / 100);
// Serial.print(" Z: ");
// Serial.println(zavg - (int)gyro.g.z / 100);
delay(30);
int zaxis = (zavg - (int)gyro.g.z) / 100;
g = map(constrain(zaxis, -327, 0), -327, 0, 255, 0);
b = map(constrain(zaxis, 0, 327), 0, 327, 0, 255);
r = map(constrain(zaxis, -327, 0), -327, 0, 255, 0);
Serial.print(zaxis);
Serial.print(" :: ");
Serial.println(r);
pixels.setPixelColor(0, pixels.Color(g,g,b));
pixels.show();
}
| true |
314f2809e94b6b1b896ff89d50158fe43800dfd8 | C++ | EnzoFerrari430/datastructurealgorithm | /algorithm/KMP/KMP/main.cpp | GB18030 | 432 | 2.953125 | 3 | [] | no_license | /*
TƥPַ
T = a,b,a,a,c,a,b,c,a,c
p = a,b,a,b,c
㷨ƥ-
KMP㷨:
1.ǰ
һַ
P = a,b,a,b,c ַ5ǰ
a
a,b
a,b,a
a,b,a,b
a,b,a,b,c
5ǰַҵǵǰ
a,b,a,bǰΪ
a,b,a,bǰa,b,a b,a,b
*/ | true |
6a0629016bfdfeee3d5d99adc09811fddc083978 | C++ | alwayssmile11a1/Metroid.Game | /Metroid/FrameWork/src/drawable/Sprite.h | UTF-8 | 2,435 | 3.15625 | 3 | [
"MIT"
] | permissive | #ifndef SPRITE_H
#define SPRITE_H
#include "..\math\Vector2.h"
#include "Texture.h"
#include "TextureRegion.h"
#include "GameObject.h"
//Texture + Texture Region
class Sprite :public GameObject
{
private:
Vector2 _Position; //the position of this sprite
Vector2 _ScaleFactor; //scale
Vector2 _Size;
Vector2 _RotationOrigin; //the position that will be used as origin for rotating
float _Rotation;
float _IsCenterOrigin; //
Vector2 _RectSize; //the width and height of the rectangle portion in the image
Vector2 _RectPosition; //the top left position of portion we want to draw
Texture *_Texture; //we don't initialize this variable by default, just use this to hold the reference to a texture
//if you do want to allocate a new memory for this texture, consider use _CreateNewTexture variable
//bool _CreateNewTexture; //if true, allocate a new memory for the texture
bool _FlipX;
bool _FlipY;
public:
Sprite();
//if create new is true, allocate a new memory for the texture
//but may affect the performance
Sprite(Texture *texture);
//draw a portion of image, stretch it to width and height
Sprite(Texture *texture, float x, float y, float rectLeft, float rectTop, float rectWidth, float rectHeight);
~Sprite();
/*Sprite(const Sprite &sprite);
Sprite& operator=(const Sprite &texture);*/
//all get functions
const Vector2& GetRotationOrigin() const;
const Vector2& GetPosition() const;
const Vector2& GetSize() const;
float GetRotation() const;
const Vector2& GetScale() const;
Texture* GetTexture() const;
const Vector2& GetRectSize() const;
const Vector2& GetRectPosition() const;
//all set functions
void SetRotationOrigin(float centerX, float centerY);
void SetRotation(float rotation);
void SetPosition(float x, float y);
void SetSize(float width, float height);
void SetTexture(Texture *texture);
void SetRegion(const TextureRegion &textureRegion);
void SetRectPosition(float rectX, float rectY);
void SetRectSize(float rectWidth, float rectHeight);
//if true, set the origin of this sprite to be always in the center of this texture
void SetCenterRotationOrigin(bool center);
bool IsCenterOrigin() const;
//Flip the texture. This function is done by multiplying the scale x or y with -1.
void Flip(bool flipX, bool flipY);
bool IsFlipX();
bool IsFlipY();
//Reset the size of this sprite to the actual size of the texture
void ResetToWhole();
};
#endif
| true |
970af0cdebe3f5e8d59e6311e4214c2c34f69a84 | C++ | 3DPIT/finalAlgorithm2021 | /Project2/Algorithm2021/Algorithm2021/가비아1.cpp | UHC | 765 | 3.265625 | 3 | [] | no_license | #include <string>
#include <vector>
#include<iostream>
#include <map>
using namespace std;
bool fine_chk(string fineS) {
int alphabetChk[27] = { 0, };
for (int i = 0; i < fineS.size(); i++) {
if (alphabetChk[fineS[i]-'a'] == 0) {// ڿ üũ
alphabetChk[fineS[i]-'a'] = 1;
}
else return false;//ߺ ڿ ־ ڿ
}
return true;
}
int solution(string s) {
int answer = 0;
map<string, int>string_chk;
for (int i = 0; i < s.size(); i++) {
string copy_s="";
for (int j = i; j < s.size(); j++) {
copy_s += s[j];
if (string_chk[copy_s] == 0&&fine_chk(copy_s)) {
string_chk[copy_s] = 1;
}
}
}
answer = string_chk.size();
return answer;
}
int main(void) {
cout<<solution("zxzxz");
return 0;
} | true |
86beb06fc2e476d14d44e2e720ef4bd872a1ee8a | C++ | hrithik20007/DSA_For_CP | /ApniKaksha/BitManipulations/updateBit.cpp | UTF-8 | 917 | 4.125 | 4 | [] | no_license | //This program will update the bit at a given position. To update means simply to unset a bit and then sit the bit, all at the same position.
#include<iostream>
using namespace std;
int main(){
//UnsetBit
int n=5; //The number whose bit we are checking. Binary is 0101.
int i=2; //The position from right at which we will unset the bit (starts from 0).
int b=~(1<<i); //Complement of left shifted 1. After left shifting 1, we get 0100, then after complementing we get, 1011.
int s=b&n; //'AND' operation for making the bit 0 at i's position.
cout<<"After unsetting bit : "<<s<<endl;
//SetBit
int a=1<<i; //1 is left shifted by i places. Here 1 after left shifting becomes 0100 from 0001,
int r=a|s; //'OR' operation is performed. Except the i position, the rest remains same. i will become 1.
cout<<"After setting bit : "<<r<<endl; //Becomes 0101 or 5.
return 0;
}
| true |
dd846c3faddbfc708b66dac1b976371e051a6bb3 | C++ | rokm/guio_esp8266 | /guio_esp8266/program_base.cpp | UTF-8 | 6,056 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* GUI-O ESP8266 bridge
* Base program class.
*
* Copyright (C) 2020, Rok Mandeljc
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "program_base.h"
#include <EEPROM.h>
#include <FunctionalInterrupt.h>
Program::Program (parameters_t ¶meters)
: parameters(parameters), // store reference to parameters struct
statusCode(STATUS_UNKNOWN), // reset status
scheduler(),
// Task for blinking the built-in LED. Used as a signalling mechanism
taskBlinkLed(
250*TASK_MILLISECOND, // this will be later adjusted within the program
TASK_FOREVER,
std::bind(&Program::taskBlinkLedFcn, this),
&scheduler,
false,
[this] () {
// OnEnable
toggleLed(false); // turn off
return true;
},
[this] () {
// OnDisable
toggleLed(false); // turn off
}
),
// Task for checking the button state (for debounce).
taskCheckButton(
100*TASK_MILLISECOND,
TASK_ONCE,
std::bind(&Program::taskCheckButtonFcn, this),
&scheduler,
false,
nullptr,
nullptr
),
buttonStateChanged(false),
buttonPressTime(0)
{
}
void Program::setup ()
{
// LED
pinMode(_GUIO_LED_MAIN, OUTPUT);
// Button pin (force AP mode, reset EEPROM data)
pinMode(_GUIO_AP_BUTTON, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(_GUIO_AP_BUTTON), std::bind(&Program::buttonPressIsr, this), CHANGE);
// Initialize device ID (guio_ + MAC); used as
// - SSID in AP mode
// - pairing device name in AP mode
// - hostname in STA mode
// - mqtt client ID in STA mode
uint8_t macAddr[6];
WiFi.softAPmacAddress(macAddr);
snprintf_P(deviceId, sizeof(deviceId), PSTR("guio_%02x%02x%02x%02x%02x%02x"), macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
}
void Program::loop ()
{
// Check button state
if (buttonStateChanged) {
taskCheckButton.restartDelayed();
buttonStateChanged = false;
}
// Schedule tasks
scheduler.execute();
// Serial input
// Read in small batches to avoid potential flood from starving
// task scheduler...
if (Serial.available()) {
serialBatch = 0; // Reset batch counter
while (Serial.available() && serialBatch < 32) {
char c = Serial.read();
serialBatch++;
if (c == '\n') {
// NULL terminate the buffer
serialBuffer[serialLen] = 0;
// Check if preceding character was \r; if it was, strip
// it away
if (serialLen > 0 && serialBuffer[serialLen-1] == '\r') {
serialBuffer[--serialLen] = 0;
}
// Process the line
serialInputHandler();
// Reset buffer length
serialLen = 0;
} else {
// Read into buffer, truncate on overflow
if (serialLen < sizeof(serialBuffer) - 1) {
serialBuffer[serialLen++] = c;
}
}
}
}
}
void Program::toggleLed (bool on)
{
// LOW = on, HIGH = off
digitalWrite(_GUIO_LED_MAIN, on ? LOW : HIGH);
}
void Program::buttonPressIsr ()
{
buttonStateChanged = true;
}
void Program::taskBlinkLedFcn ()
{
if (scheduler.currentTask().getRunCounter() % 2) {
toggleLed(true); // turn on
} else {
toggleLed(false); // turn off
}
}
void Program::clearParametersInEeprom () const
{
for (int i = 0 ; i < EEPROM.length() ; i++) {
EEPROM.write(i, 0);
}
EEPROM.commit();
}
void Program::writeParametersToEeprom () const
{
EEPROM.put(0, parameters);
EEPROM.commit();
}
void Program::restartSystem () const
{
ESP.restart();
}
void Program::buttonPressHandler (unsigned int duration)
{
GDBG_print(F("Button press lasted "));
GDBG_print(duration);
GDBG_println(F(" ms..."));
if (duration > 15*TASK_SECOND) {
GDBG_println(F("Long press! Clearing EEPROM and rebooting!"));
clearParametersInEeprom(); // clear EEPROM
restartSystem(); // restart
} else if (duration > 1*TASK_SECOND) {
GDBG_println(F("Short press! Rebooting into AP!"));
parameters.force_ap = true; // set forced AP flag
writeParametersToEeprom(); // write to EEPROM
restartSystem(); // restart
}
}
void Program::taskCheckButtonFcn ()
{
// Pull-up; HIGH = no contact, LOW = contact
byte state = digitalRead(_GUIO_AP_BUTTON);
if (state == LOW) {
// Store press time, but only if it is invalid; if it is valid, we're likely observing bounce
if (!buttonPressTime) {
buttonPressTime = millis();
}
} else {
if (buttonPressTime) {
buttonPressHandler(millis() - buttonPressTime);
buttonPressTime = 0;
}
}
}
bool Program::serialInputHandler ()
{
GDBG_print(F("Received line: "));
GDBG_println(serialBuffer);
if (serialBuffer[0] == '!') {
// Protocol commands
if (strcmp_P(serialBuffer, PSTR("!PING")) == 0) {
// Ping - FIXME: add state code
Serial.print(F("!PONG "));
Serial.println(statusCode);
return true;
} else if (strcmp_P(serialBuffer, PSTR("!REBOOT")) == 0) {
// Reboot in preferred mode
restartSystem();
return true;
} else if (strcmp_P(serialBuffer, PSTR("!REBOOT_AP")) == 0) {
parameters.force_ap = true; // set forced AP flag
writeParametersToEeprom(); // write to EEPROM
restartSystem(); // restart
return true;
} else if (strcmp_P(serialBuffer, PSTR("!CLEAR_PARAMS")) == 0) {
clearParametersInEeprom(); // clear EEPROM
restartSystem(); // restart
return true;
}
}
return false; // Line not processed
}
| true |
f04ad21a097a63364073ef496d3b21ba61c09525 | C++ | pateldevang/coursera-Fundamentals-of-Parallelism-on-Intel-Architecture | /WEEK3/threads-filter/main.cc | UTF-8 | 2,285 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <cstdlib>
#include <cstdio>
#include <omp.h>
#include <mkl.h>
#include <vector>
#include <algorithm>
void filter(const long n, const long m, float *data, const float threshold, std::vector<long> &result_row_ind);
//reference function to verify data
void filter_ref(const long n, const long m, float *data, const float threshold, std::vector<long> &result_row_ind) {
float sum;
for(long i = 0; i < n; i++){
sum = 0.0f;
for(long j = 0; j < m; j++) {
sum+=data[i*m+j];
}
if(sum > threshold)
result_row_ind.push_back(i);
}
std::sort(result_row_ind.begin(),result_row_ind.end());
}
int main(int argc, char** argv) {
float threshold = 0.5;
if(argc < 2) {
threshold = 0.5;
} else {
threshold = atof(argv[1]);
}
const long n = 1<<15; //rows
const long m = 1<<18; //columns
float *data = (float *) malloc((long)sizeof(float)*n*m);
long random_seed = (long)(omp_get_wtime()*1000.0) % 1000L;
VSLStreamStatePtr rnStream;
vslNewStream( &rnStream, VSL_BRNG_MT19937, random_seed);
//initialize 2D data
#pragma omp parallel for
for(long i =0; i < n; i++)
vsRngUniform(VSL_RNG_METHOD_UNIFORM_STD, rnStream, m, &data[m*i], -1.0, 1.0);
std::vector<long> ref_result_row_ind;
//compute the refernce data using unoptimized refernce function defined above
filter_ref(n, m, data, threshold, ref_result_row_ind);
//compute actual data using the function defined in worker.cc and get the timing
std::vector<long> result_row_ind;
const double t0 = omp_get_wtime();
filter(n, m, data, threshold, result_row_ind);
const double t1 = omp_get_wtime();
//verify the actual data and the refernce data
if(ref_result_row_ind.size() != result_row_ind.size()) {
// Result sizes did not match
printf("Error: The reference and result vectors have different sizes: %ld %ld",ref_result_row_ind.size(), result_row_ind.size());
} else {
bool passed = true;
for(long i = 0; i < ref_result_row_ind.size(); i++) {
passed &= (ref_result_row_ind[i] == result_row_ind[i]);
}
if(passed) {
// Printing perf
printf("Time: %f\n", t1-t0);
} else {
// Results did not match
printf("Error: The reference and result vectors did not match");
}
}
} | true |
dfbf69a77316b14614e94fe92c8f8ac915196aae | C++ | daniel-dennis/Game-Engine | /hierarchy.hpp | UTF-8 | 4,303 | 3.234375 | 3 | [] | no_license | // (c) Daniel Dennis 2018
// Implements and manages an object hierarchy, provides methods
// To message individual nodes in hierarchy and its children
// Object heirarchy type and packet in which data is sent
// needs to be specified, (hierarchy_implementation) does this
// Everything in this class is my own work
#ifndef HIERARCHY_HPP
#define HIERARCHY_HPP
#include <vector>
#include <stack>
#include <iostream>
#include <cstdint>
namespace dd
{
typedef uint16_t id_t; // Node ID is array of 16 bit unsigned integers
typedef std::stack<id_t> traverse_id_t; // Node ID for internal use
typedef std::vector<id_t> node_id_t; // Node ID for external use
template<class T, typename packet> class hierarchy
{
private:
// Variables and objects
id_t this_id, this_depth;
std::vector<class hierarchy*> children;
protected:
// Methods
void propogate_to_children(packet data)
{
for(int i = 0; i < children.size(); i++)
{
children[i]->node.set_parent(data);
children[i]->propogate_to_children(data);
}
}
traverse_id_t traverse(traverse_id_t current_layer)
{
current_layer.pop();
id_t child_id;
traverse_id_t return_id;
if(current_layer.size())
{
child_id = current_layer.top();
return_id = children[child_id]->traverse(current_layer);
return_id.push(this_id);
return return_id;
}
else
{
child_id = children.size();
class hierarchy* new_child = new class hierarchy(child_id);
children.push_back(new_child);
return_id.push(child_id);
return_id.push(this_id);
return return_id;
}
}
void set_element_internal(traverse_id_t address, packet data)
{
address.pop();
if(address.size())
{
return children[address.top()]->set_element_internal(address, data);
}
else
{
broadcast_internal(data);
return;
}
}
void broadcast_internal(packet data)
{
node.set(data);
data = node.get(data);
for(int i = 0; i < children.size(); i++)
{
children[i]->broadcast_internal(data);
}
return;
}
public:
// Variables and objects
T node;
// Constructors
hierarchy(){}
hierarchy(id_t id){this_id = id;}
~hierarchy(){for(int i = 0; i < children.size(); i++) delete children[i];}
// Methods
node_id_t insert_element(node_id_t address)
{
traverse_id_t new_id, traverse_return;
for(int i = (address.size() - 1); i >= 0; i--)
{
new_id.push(address[i]);
}
address.clear();
traverse_return = traverse(new_id);
node_id_t return_id;
while(traverse_return.size())
{
return_id.push_back(traverse_return.top());
traverse_return.pop();
}
return return_id;
}
node_id_t create_family(int id = 0)
{
node_id_t return_id;
this_id = id;
if(children.empty() == false)
{
std::cerr << "Error: family already initialised\n"; // throw exception here?
return return_id;
}
else
{
return_id.push_back(0);
return return_id;
}
}
void set_element(node_id_t address, packet data)
{
traverse_id_t traverse_id;
for(int i = (address.size() - 1); i >= 0; i--)
{
traverse_id.push(address[i]);
}
set_element_internal(traverse_id, data);
return;
}
void broadcast(packet data)
{
broadcast_internal(data);
return;
}
};
}
#endif | true |
3cbc0e6c2120c2dd815762793214f5f83a50ca89 | C++ | kyliau/playground | /codility/09-1_CountNonDivisible.cpp | UTF-8 | 1,185 | 3.78125 | 4 | [] | no_license |
// Lesson 9 - Sieve of Eratosthenes
// CountNonDivisible
// Calculate the number of elements of an array that are not divisors of each element.
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
// this solution is not O(n log n), but it passes the all test cases
// it is O(sqrt(n) * n) thus O(n ^ 1.5)
int count_divisors_in_array(int x, const vector<int>& B) {
unordered_set<int> divisors {1, x};
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) {
divisors.insert(i);
divisors.insert(x / i);
}
}
int result = 0;
for (const int& d : divisors) {
result += B[d];
}
return result;
}
vector<int> solution(vector<int> &A) {
vector<int> B(*max_element(A.begin(), A.end()) + 1, 0);
for (const int& a : A) {
++B[a];
}
int N = A.size();
vector<int> result(N);
unordered_map<int, int> cache;
for (int i = 0; i < N; ++i) {
auto it = cache.find(A[i]);
if (it != cache.end()) {
result[i] = it->second;
} else {
result[i] = N - count_divisors_in_array(A[i], B);
cache[A[i]] = result[i];
}
}
return result;
}
| true |
70aff041918258c72338ef0b91fff545c0a971c7 | C++ | xiaotdl/Sandbox | /cpp/test/tutorial/main.cpp | UTF-8 | 2,951 | 3.984375 | 4 | [] | no_license | #include <iostream>
using namespace std;
// &: ampersand
// Type:
// int, float, MyClass
// T
// T&: reference to Type
// T*: pointer to Type
//
// Operation:
// &O: get pointer/address from object
// *P: get object by deref pointer/address
// pointer/address size
// int64_t == 8 bytes
// T** var; declares a pointer to a pointer
// **var; references the content of a pointer, which in itself points to a pointer
// pointer
void f2(int* x) {
*x = 1;
cout << "f2:" << *x << endl;
}
void f1() {
int x = 0;
f2(&x);
cout << "f1:" << x << endl;
}
// reference
void f4(int& x) {
x = 1;
cout << "f4:" << x << endl;
}
void f3() {
int x = 0;
f4(x);
cout << "f3:" << x << endl;
}
// big objects
// struct == class with every func/fields public
struct BigData {
BigData() {}; // constructor
~BigData() {}; // destructor
int data[100] = {};
int size = 100; // member variable
int getSize() { // member function
return size;
};
};
void f5(BigData bd) {
cout << "f5: " << &bd << endl;
cout << bd.size << endl;
cout << bd.getSize() << endl;
}
void f6(BigData& bd) {
cout << "f6: " << &bd << endl;
cout << bd.size << endl;
cout << bd.getSize() << endl;
}
void f7(BigData* bd) {
cout << "f7: " << bd << endl;
cout << (*bd).size << endl;
cout << (*bd).getSize() << endl;
cout << bd->size << endl; // same as above, just a syntactic sugar
cout << bd->getSize() << endl;
}
// To Run: !g++ -std=c++14 -Wall % && ./a.out
int main() {
{
// pointer example
f1();
}
{
// reference example
f3();
}
{
// big data pass by value, by ref, by pointer
BigData bd; // create instance in current stack
cout << "&bd:" << &bd << endl;
f5(bd); // pass by value; make copy
f6(bd); // pass by ref; no copy
f7(&bd); // pass by ptr; no copy
}
{
BigData bd;
bd.size = 99; // addr = &bd | val = {}
BigData** p1; // addr = p1 | val = ?
BigData* p2; // addr = p2 | val = ?
p2 = &bd; // addr = p2 | val = &bd
p1 = &p2; // addr = p1 | val = &p2
cout << "bd.size: " << bd.size << endl;
cout << "(**p1).size: " << (**p1).size << endl;
cout << "(*p1)->size: " << (*p1)->size << endl;
}
{
// BigData* bdPtr = new BigData(); // create instance in heap
// free(bdPtr);
// smart pointer: unique ptr, shared ptr
// unique_ptr<BigData> bdUptr = make_unique<BigData>();
auto bdUptr = make_unique<BigData>(); // same as above
}
{
// int main(int argc, char* argv[]);
// is equivalent to:
// int main(int argc, char** argv);
//
// argv is a pointer to an array of char*
//
// the index operator [] is just another way of performing pointer arithmetic
// foo[i]
// is equivalent to:
// *(foo + i)
//
// T**: It might be a matrix (an array of arrays) or an array of strings (a char array), etc.
}
cout << "EOP" << endl;
}
| true |
cf9b1b2fd3c9363c7b2a29a3cd066f87910ba2e0 | C++ | kanishkcoe/c-lecture-codes | /currencyCount.cpp | UTF-8 | 528 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int count = 0;
int countPresest = 0;
int currency[] = {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
int amount;
cout << "Enter amount : "; cin >> amount;
for(int i = 0; i < 10; i++)
{
countPresest = amount / currency[i];
count += amount / currency[i];
if(countPresest != 0)
cout << currency[i] << " notes : " << countPresest << endl;
amount %= currency[i];
}
cout << "Currency notes required = " << count << endl;
return 0;
}
| true |
ece2ad11fe4e3343684f6cf1ef7237d8c99061fe | C++ | edasinar/Complex-Number | /Complex Number/main.cpp | UTF-8 | 1,304 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include "KarmasikSayi.h"
int main()
{
KarmasikSayi a(2, 5);
std::cout << a;
std::cout << "-------------------------------------------------------------------" << std::endl;
KarmasikSayi b(2, -5);
std::cout << b;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << a + b;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << a - b;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << a * b;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << a / b;
std::cout << "-------------------------------------------------------------------" << std::endl;
std::cout << ((a == b) ? "esit" : "esit degil");
std::cout << std::endl;
std::cout << "-------------------------------------------------------------------" << std::endl;
KarmasikSayi f(6, -19);
KarmasikSayi C(f);
std::cout << C;
std::cout << "-------------------------------------------------------------------" << std::endl;
KarmasikSayi e(std::move(f));
std::cout << e;
std::cout << "-------------------------------------------------------------------" << std::endl;
return 0;
} | true |
a54c5849f39807cd2f807b9e8afe9e8175ccb7ea | C++ | GigaFlopsis/Omni_robot_ROS | /arduino_omni_wheel/MyEncoder.cpp | UTF-8 | 698 | 2.78125 | 3 | [] | no_license | //
// Created by op on 16.11.2020.
//
#include "MyEncoder.h"
MyEncoder::MyEncoder(int _outputA, int _outputB, float _radius, int _rate = 10.) : Enc(_outputA, _outputB)
{
rate = _rate;
period = 1.0 / _rate * 1000.;
outputA = _outputA;
outputB = _outputB;
dt = 1. / _rate;
}
void MyEncoder::Init()
{
my_timer = millis(); // "сбросить" таймер
}
void MyEncoder::Update()
{
if ((millis() - my_timer) >= period)
{
counter_period = Enc.read();
velocity = radius * (counter_period * RAD_CICLE) / dt;
my_timer = millis();
counter_period = 0;
Enc.write(0);
}
}
float MyEncoder::GetVel()
{
return velocity;
}
| true |
1d5ab516c92ecf516b343f41c9025f491a26c9b7 | C++ | pgoodman/Grail-Plus | /fltl/include/tdop/Rule.hpp | UTF-8 | 3,849 | 3.0625 | 3 | [
"MIT"
] | permissive | /*
* Rule.hpp
*
* Created on: May 10, 2012
* Author: petergoodman
* Version: $Id$
*/
#ifndef Grail_Plus_TDOP_RULE_HPP_
#define Grail_Plus_TDOP_RULE_HPP_
namespace fltl { namespace tdop {
/// represents a parser rule. This encompasses both initial and extension
/// rules. An initial rule is has a termina/symbol left corner. An extension
/// rule has as its left corner another rule. The extenstion rule is
/// anchored by a symbol, or a symbol predicate.
template <typename AlphaT>
class Rule {
private:
typedef Rule<AlphaT> self_type;
typedef helper::BlockAllocator<self_type> allocator_type;
friend class TDOP<AlphaT>;
friend class OpaqueRule<AlphaT>;
friend class helper::BlockAllocator<self_type>;
friend class detail::CategoryGenerator<AlphaT>;
friend class detail::SymbolGenerator<AlphaT>;
friend class detail::RuleGenerator<AlphaT>;
friend class detail::PatternGenerator<AlphaT,true>;
friend class detail::PatternGenerator<AlphaT,false>;
enum {
INITIAL_RULE_UPPER_BOUND = -1,
UNINITIALIZED = -2
};
uint32_t ref_count;
bool is_deleted;
/// the category this rule belongs to
Category<AlphaT> *category;
/// rule chain of a category
self_type *prev;
self_type *next;
/// upper bound for continuation rules, otherwise
/// INITIAL_RULE_UPPER_BOUND for initial rules.
int32_t upper_bound;
/// sequence of operators
OperatorString<AlphaT> str;
/// reference counting, allocation
static allocator_type rule_allocator;
static void incref(self_type *ptr) throw() {
if(0 != ptr) {
++(ptr->ref_count);
}
}
static void decref(self_type *ptr) throw() {
if(0 != ptr) {
--(ptr->ref_count);
if(0 == ptr->ref_count) {
rule_allocator.deallocate(ptr);
}
}
}
static self_type *allocate(void) throw() {
return rule_allocator.allocate();
}
/// lexicograpgically compare two rules
bool is_less_than(const self_type *that) const throw() {
if(that == this) {
return false;
}
// both extension rules
if(0 <= upper_bound
&& 0 <= that->upper_bound) {
if(str < that->str) {
return true;
} else if(that->str < str) {
return false;
} else {
return upper_bound < that->upper_bound;
}
// both initial rules
} else if(INITIAL_RULE_UPPER_BOUND == upper_bound
&& INITIAL_RULE_UPPER_BOUND == that->upper_bound) {
return str < that->str;
// 'that' is an initial rule
} else if(0 <= upper_bound) {
return false;
// 'this' is an initial rule
} else {
return true;
}
}
public:
/// constructor
Rule(void) throw()
: ref_count(1U)
, is_deleted(false)
, category(0)
, prev(0)
, next(0)
, upper_bound(UNINITIALIZED)
, str()
{ }
/// destructor
~Rule(void) throw() {
category = 0;
prev = 0;
next = 0;
upper_bound = UNINITIALIZED;
}
};
/// static initialization of rule allocator
template <typename AlphaT>
typename Rule<AlphaT>::allocator_type Rule<AlphaT>::rule_allocator;
}}
#endif /* Grail_Plus_TDOP_RULE_HPP_ */
| true |
d24d58ed6b19943f25d3a196d9b2e2b932819d25 | C++ | kingst/bixer | /src/lib/include/HTTPResponse.h | UTF-8 | 530 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef HTTP_RESPONSE_H_
#define HTTP_RESPONSE_H_
#include <map>
#include <string>
class HTTPResponse {
public:
HTTPResponse();
void withStreaming();
void setHeader(std::string name, std::string value);
void setBody(std::string data);
void setContentType(std::string contentType);
void setStatus(int status);
std::string response();
private:
std::string statusToString();
int status;
bool streaming;
std::map<std::string, std::string> headers;
std::string body;
std::string contentType;
};
#endif
| true |
bbb70c0de2e10094985f8030ce0f0370b52a4265 | C++ | nafischonchol/Algorithms | /Graph Representation - Adjacency Matrix C++ Implementation.cpp | UTF-8 | 824 | 2.875 | 3 | [] | no_license | /* Sample Input:
5 6
0 1 1 1 0
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
0 1 1 1 0 */
/*Smaple Output:
0----1 2 3
1----0 4
2----0 4
3----0 4
4----1 2 3
*/
#include <bits/stdc++.h>
using namespace std;
int vertex,edges;
void printGraph(int a[][100])
{
for(int i=0;i<vertex;i++)
{
cout<<i<<"----"; //source
for(int j=0;j<vertex;j++)
{
if(a[i][j]==1)
{
cout<<j<<" ";
}
}
cout<<endl;
}
cout<<endl;
}
void createGraph(int a[][100])
{
for(int i=0;i<vertex;i++)
{
for(int j=0;j<vertex;j++)
{
cin>>a[i][j];
}
}
}
int main()
{
cin>>vertex>>edges;
int a[100][100];
createGraph(a);
printGraph(a);
return 0;
}
| true |
790099e04fd4e8736e74fefbf88e011f78598aa0 | C++ | minhmax098/EmbeddedSystem_Exercise | /Chuong6inra34/Chuong6inra34.ino | UTF-8 | 826 | 2.828125 | 3 | [] | no_license | #include <EEPROMex.h>
int address = 0;
String input = " 3 4 ";
byte output = 3;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
for(int i=0; i<input.length(); i++)
{
address++;
EEPROM.write(address, input[i]);
}
Serial.begin(9600);
for(int i =0; i<input.length(); i++){
address--;
EEPROM.write(address, input[i]);
}
address = 1;
for(int i= 0; i<input.length(); i++)
{
address++;
output = EEPROM.read(address);
char a = output;
Serial.print(a);
}
// for(int i= 0; i<output.length(); i--)
// {
// address--;
// input = EEPROM.write(address);
// char b = input;
// Serial.print(b);
// }
Serial.println("Chuoi sau khi read la: ");
Serial.println("\t");
}
void loop() {
// put your main code here, to run repeatedly:
}
| true |
769fe19ae8242b9f27235c6c47c9ac113b16d073 | C++ | TAPATOP/Data-Structures-and-Algorithms-Homeworks | /SpamFilter New/Trie.cpp | UTF-8 | 8,762 | 3.375 | 3 | [] | no_license | /**
*
* Solution to homework task
* Data Structures Course
* Faculty of Mathematics and Informatics of Sofia University
* Winter semester 2016/2017
*
* @author Hristo Hristov
* @idnumber 61917
* @task 3
* @compiler VC
*
*/
#include "Trie.h"
const short letterError = 69;
Trie::Trie()
{
rootNode = new Node;
numberOfWorkingHeads = 0;
}
// adds words to the dictionary
// whatever is passed for "entry" must be a legit word/phrase composited of spaces and small Latin letters only
void Trie::insert(char* entry, int value)
{
Node* currentNode = rootNode;
unsigned short index;
for (int i = 0; entry[i]; i++)
{
if (entry[i] == ' ')
{
index = 0;
}
else
{
index = entry[i] - 96;
}
//
// decides which letter we're checking for( 0th position of array next is ' ', 1 = 'a', 2 = 'b'...)
//
if (currentNode->next[index] == nullptr)
{
currentNode->next[index] = new Node();// creates new node if one hasn't already been created
}
currentNode = currentNode->next[index];
}
currentNode->endOfWord = true;
currentNode->value = value;
}
// enriches the vocabulary using a >>> properly formatted <<< file
void Trie::insert_via_file(std::ifstream& file)
{
// reason for this const is to easily make changes in case they are needed,
// hopefully we won't need more than 1024 character long dictionary entries
unsigned const int maxSizeOfLine = 1024;
char input[maxSizeOfLine];
char word[maxSizeOfLine];
char value[20];
unsigned int wordSize = 0;
unsigned int valueSize = 0;
while (true)
{
file.getline(input, maxSizeOfLine);
input[file.gcount()] = '\0';
for (int i = 0; input[i]; i++)
{
if (input[i] != ' ') // by definition the vocabulary will not have anything different from ' ', letters and numbers
{
if (input[i] >= 'a' && input[i] <= 'z')
{
word[wordSize] = input[i];
wordSize++;
if (input[i + 1] == ' ')
{
word[wordSize] = ' ';
wordSize++;
}
}
else
{
value[valueSize] = input[i];
valueSize++;
}
}
}
// entire part above is responsible for separating words from values
if(wordSize > 0) word[wordSize - 1] = '\0';
value[valueSize] = '\0';
wordSize = 0;
valueSize = 0;
insert(word, charArrToInt(value));
input[0] = 0;
word[0] = 0;
value[0] = 0;
// the above 4 lines are responsible for resetting the buffers
if (file.eof()) break;
file.clear();
}
}
// searches for vocabulary words into the files
float Trie::search_in_file(std::ifstream& file)
{
collectedValue = 0;
const int readSize = 1024;
char text[readSize + 1];
int textIndex = 0;
unsigned int textWordCount = 0;
bool previousSymbolWasDelimeter = 0;
char firstLetterOfText = file.get();
file.seekg(0, std::ios::beg);
if (decapitalize(firstLetterOfText))
{
textWordCount++;
}
activate_head();
while (!file.eof())
{
// READING PART //
text[0] = '\0';
textIndex = 0;
file.read(text, readSize);
text[file.gcount()] = '\0';
// HEAD WORK PART //
// iterates all the letters
while (text[textIndex] != '\0')
{
// responsible for counting words: if a delimeter is followed by a letter => it's a word
char currentSymbol = decapitalize(text[textIndex]);
if ( currentSymbol == 0)
{
previousSymbolWasDelimeter = 1;
}
else
{
if (previousSymbolWasDelimeter)
{
previousSymbolWasDelimeter = 0;
textWordCount++;
}
}
// gives the current letter to all heads
for (int i = 0; i < numberOfWorkingHeads; i++)
{
// no reason to pass a letter to a non- working head
if (heads[i].isWorking)
{
if (isWhitespace(text[textIndex]))
{
pass_letter_to_head(i, ' ');
}
else
{
pass_letter_to_head(i, decapitalize(text[textIndex]));
}
}
}
if (currentSymbol == 0)
{
activate_head();
}
textIndex++;
}
}
for (int i = 0; i < numberOfWorkingHeads; i++)
{
// passes a letter that is sure to be invalid so the algorithm makes
// the nodes with values to deactivate and send their result back
pass_letter_to_head(i, 0);
}
if (textWordCount == 0) return 0;
return collectedValue / (float)textWordCount;
}
Trie::~Trie()
{
}
// passes letter to heads[headIndex] and kills heads based on what happens next
void Trie::pass_letter_to_head(int headIndex, char letter)
{
// i'd rather copy an address instead of the object itself
head* currentHead = &heads[headIndex];
// the index used to address the letters in Nodes
short letterIndexInNode = transform_letter_to_index(letter);
if (currentHead->isWorking && (letter == ' ' || letter == 0) )
{
// if the current Node is an ending; we do this check only now cause letter is a delimeter
if (currentHead->nodeOfHead->endOfWord)
{
// sets value according to dictionary entry
currentHead->lastValue = currentHead->nodeOfHead->value;
// has recognized a word
currentHead->hasRecognizedAWord = 1;
// deactivates all heads to the right because this head has already found a match of all the
// current letters
for (int i = headIndex + 1; i < numberOfWorkingHeads; i++)
{
deactivate_head(i);
}
// sets the number of working heads
numberOfWorkingHeads = headIndex + 1;
}
}
// if there is an entry of the current sequence of letters and the head is still working
if (currentHead->nodeOfHead->next[letterIndexInNode] != nullptr && currentHead->isWorking && letter != 0)
{
// move to the next node
currentHead->nodeOfHead = currentHead->nodeOfHead->next[letterIndexInNode];
}
// events that occur when the head stops working
else
{
// stop the head from working since there is no valid entry of the letter
currentHead->isWorking = 0;
// eject the value the head has stored so far if it has recognized a word and is first in the array
if (currentHead->hasRecognizedAWord && headIndex == 0)
{
// collects the value
collectedValue += currentHead->lastValue;
// plays the role of "value is collected" -> 0 = "is collected" and we can now destroy the head
currentHead->hasRecognizedAWord = 0;
}
if (!currentHead->hasRecognizedAWord)
{
// move all of the nodes after the current one to the left by copying them one. by. one. It's retarded
// but it will do the job, for now at least
for (int i = headIndex; i < numberOfWorkingHeads - 1; i++)
{
copy_head(i, i + 1);
}
// reduce the number of working heads since the current one got overwritten and the last one
// can be found twice in the heads array now
numberOfWorkingHeads--;
// deactivates the last head, which has a copy right before it
deactivate_head(numberOfWorkingHeads);
// if there is an active head on( or after) the location of the recently overwritten head
if (numberOfWorkingHeads > headIndex)
{
// pass the command to the head on the current place, because search_in_file() will skip it
pass_letter_to_head(headIndex, letter);
}
}
}
}
// prepares another head for work
void Trie::activate_head()
{
head* currentHead = &heads[numberOfWorkingHeads];
currentHead->isWorking = 1;
currentHead->nodeOfHead = rootNode;
currentHead->lastValue = 0;
currentHead->hasRecognizedAWord = 0;
numberOfWorkingHeads++;
}
// stops the head from working
void Trie::deactivate_head(int index)
{
heads[index].isWorking = 0;
heads[index].hasRecognizedAWord = 0;
}
// [a-z] and ' ' only; letterError otherwise
short Trie::transform_letter_to_index(char letter)
{
if (letter == ' ') return 0;
if (letter >= 'a' && letter <= 'z') return letter - 96;
return letterError;
}
// copies heads[index2] to heads[index1]
void Trie::copy_head(int index1, int index2)
{
head* head1 = &heads[index1];
head* head2 = &heads[index2];
head1->isWorking = head2->isWorking;
head1->nodeOfHead = head2->nodeOfHead;
head1->lastValue = head2->lastValue;
head1->hasRecognizedAWord = head2->hasRecognizedAWord;
}
// decapitalizes letter if needed; returns 0 if it letter is not a letter
char decapitalize(char letter)
{
if (letter >= 'A' && letter <= 'Z')
{
return letter + 32;
}
if (letter >= 'a' && letter <= 'z')
{
return letter;
}
return 0; // error
}
// returns true if letter is ' ', newline or tab
bool isWhitespace(char letter)
{
if (letter == ' ' || letter == '\n' || letter == '\t') return 1;
return 0;
}
//
// delimeters are whatever ' ' can be replaced by and still match a dictionary word
//
int charArrToInt(char* word)//please dont try anything different than numbers here
{
int number = 0;
bool amNegative = 0;
int i = 0;
if (word[0] == '-')
{
amNegative = 1;
i++;
}
for (; word[i]; i++)
{
number = number * 10 + (word[i] - 48);
}
if (amNegative)
{
number *= -1;
}
return number;
}
| true |
ccc469bd3008b9838cb0059e6acb217ca91f99d8 | C++ | pratikbhd/lfs | /src/log/loglayer.cpp | UTF-8 | 887 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | /*
============================================================================
Name : loglayer.cpp
Author : Rahul Roy Mattam
Version : 1.0
Description : The log layer for LFS Project
============================================================================
** Usage *****************************************************************
loglayer file
where file is the name of the virtual flash file to create
*/
#include "flash.h"
#include <string>
#include <iostream>
int main(int argc, char** argv)
{
// Initializing the default values for the parameters
long sector = 1024;
long segment_size = 32;
int block_size = 2;
long wear_limit = 1000;
char* file_name;
// Get the flash file name
file_name = argv[argc-1];
unsigned int blocks;
auto flash = Flash_Open(file_name, 0,&blocks);
std::cout << blocks;
Flash_Close(flash);
} | true |
ffad6bd8f783d05b4e5e75d47691bfe18bc62159 | C++ | n-inja/kyoupro | /src/atc/011/atc11b.cpp | UTF-8 | 1,298 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<vector>
#include<map>
#include<math.h>
#include<algorithm>
#include<iomanip>
#include<set>
#include<utility>
#define P 1000000007
using namespace std;
class Union {
public:
vector<int> parent;
int n;
Union(int _) {
n = _;
parent.resize(n);
for(int i = 0; i < n; i++) parent[i] = i;
}
void link(int i, int j) {
if(j < i) swap(i, j);
int ip = i, jp = j;
for(; ip != parent[ip]; ip = parent[ip]);
for(; jp != parent[jp]; jp = parent[jp]);
int par = min(ip, jp);
for(ip = i; ip != parent[ip]; ) {
int p = parent[ip];
parent[ip] = par;
ip = p;
}
for(jp = j; jp != parent[jp]; ) {
int p = parent[jp];
parent[jp] = par;
jp = p;
}
parent[i] = par;
parent[j] = par;
}
bool isLink(int i, int j) {
if(j < i) swap(i, j);
int ip = i, jp = j;
for(; ip != parent[ip]; ip = parent[ip]);
for(; jp != parent[jp]; jp = parent[jp]);
return parent[ip] == parent[jp];
}
};
int main() {
int n, q;
cin >> n >> q;
Union u(n);
for(int i = 0; i < q; i++) {
int p, a, b;
cin >> p >> a >> b;
if(p == 0) u.link(a, b);
else cout << (u.isLink(a, b) ? "Yes" : "No") << endl;
}
return 0;
}
| true |
5f0b58098594ddfb9a246a315454fdf5a2fda881 | C++ | Matheuscs787/computacaoGrafica | /atividade2.2CG.cpp | UTF-8 | 2,266 | 2.984375 | 3 | [] | no_license | #include<stdio.h>
#include<GL/glut.h>
#include<vector>
#include<math.h>
//#include<windows.h>
#include<iostream>
//#include<conio.h>
void mouse(int button, int state, int mouseX, int mouseY);
void teclado(unsigned char key, int mouseX, int mouseY);
void calcular(int posX, int posY);
void desenhar(void);
void init();
using namespace std;
vector<int> x;
vector<int> y;
int width = 800; //largura
int height = 600; //altura
int pos;
int main(int argc, char **argv){
glutInit(&argc, argv); //inicia o glut
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //um monitor e usando rgb
glutInitWindowSize(width, height); //tamanho da janela
glutCreateWindow("Atividade 2"); //cria a janela e passa o nome da janela
init(); //funcao pra iniciar os valores da glut
glutKeyboardFunc(teclado);
glutMouseFunc(mouse);
glutDisplayFunc(desenhar); //funcao pra desenhar
glClearColor(1.0, 1.0, 1.0, 0.0); //cor do fundo
glutMainLoop(); //loop do glut que chama o loop do display func
}
void mouse(int button, int state, int mouseX, int mouseY){
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
x.push_back(mouseX);
y.push_back(mouseY);
}
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){
calcular(mouseX, mouseY);
}
}
void teclado(unsigned char key, int mouseX, int mouseY){
switch(key){
case 'w':
y.at(pos)-=1;
break;
case 'd':
x.at(pos)+=1;
break;
case 's':
y.at(pos)+=1;
break;
case 'a':
x.at(pos)-=1;
break;
}
desenhar();
}
void calcular(int posX, int posY){
int menor=1000;
int calc;
for(int i=0;i<x.size();i++){
int posX1 = x.at(i);
int posY1 = y.at(i);
calc = sqrt(((posX1-posX)*(posX1-posX))+((posY1-posY)*(posY1-posY)));
if(calc<menor){
menor=calc;
pos = i;
}
}
}
void desenhar(void){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0, 0, 0);//PRETO
glBegin(GL_POINTS); //inicia o desenho
for(int a=0;a<x.size();a++){
if(a>-1){
glVertex2i(x.at(a),y.at(a)); //pontos
}
}
glEnd();
glFlush();
}
void init() { //funcao que inicializa o openGL
gluOrtho2D(0,width,height,0); //proporcao da tela
glPointSize(35);
}
//Matheus Cezar de Souza
| true |
600121bec6bde6a79e9c1bc24364c8842df425b1 | C++ | Magnarus/LO21 | /headers/tache_unitaire.h | UTF-8 | 2,064 | 3.15625 | 3 | [] | no_license | #ifndef TACHE_UNITAIRE_H
#define TACHE_UNITAIRE_H
#include"tache.h"
#include<QTime>
/**
* \class Tache_Unitaire tache_Unitaire.h "headers/tache_unitaire.h"
* \author DELAUNAY Grégory et NEVEUX Anaïs
* \version 1.0
* \date 04 juin 2015
* \brief Implémente la classe Tache Unitaire
* \details Une tâche Unitaire est un évènement qui doit être réalisé durant un interval de dates donné.
* Elle peut être préemptive ou non.
*/
class Tache_Unitaire : public Tache
{
protected:
QTime duree; /** durée de la tâche*/
/**
* \brief Tache_Unitaire
* constructeur par recopie interdit
*/
Tache_Unitaire(const Tache_Unitaire&);
/**
* \brief operator =
* recopie par opérateur interdite
* \return copie du paramètre passé
*/
Tache_Unitaire& operator=(const Tache_Unitaire&);
public:
/**
* \brief Tache_Unitaire
* constructeur par défaut
*/
Tache_Unitaire():Tache(){}
/**
* \brief Tache_Unitaire
* constructeur
* \param id
* id de la tâche
* \param titre
* titre de la tâche
* \param dispo
* date disponibilité de la tâche
* \param deadline
* date d'échéance de la tâche
* \param dur
* durée de la tâche
*/
Tache_Unitaire(const int id, const QString& titre, const QDate&
dispo, const QDate& deadline, const QTime& dur):
Tache(id,titre,dispo,deadline),duree(dur)
{
//setType(UNITAIRE);
typeT= UNITAIRE;
}
/**
* \brief afficher
* fonction de service
*/
virtual void afficher()const = 0;
/**
* \brief getDuree
* accesseur sur la durée
* \return durée de la tâche
*/
inline QTime getDuree()const {return duree;}
/**
* \brief setDuree
* mutateur sur la durée
* \param d
* la nouvelle durée
*/
inline virtual void setDuree(QTime& d){duree=d;}
};
#include<QVariant>
Q_DECLARE_METATYPE(Tache_Unitaire*)
#endif // TACHE_UNITAIRE_H
| true |
0ca1543aacf9d13e7e276e454be975fb03d362a9 | C++ | t-fi/SpherePacking | /main.cpp | UTF-8 | 2,217 | 2.75 | 3 | [] | no_license | #include "simulator.h"
#include "renderer.h"
#include <iostream>
#include <limits>
#include <iomanip>
#include <cmath>
#define PI 3.14159265359
int main(int argc, char * argv[])
{
// argument parsing
int numPoints, seed;
long int steps;
double lambda, sigma;
// reading arguments
for(int i=0; i<argc; i++){
if(i==1) numPoints = atoi(argv[i]);
if(i==2) steps = atol(argv[i]);
if(i==3) lambda = atof(argv[i]);
if(i==4) sigma = atof(argv[i]);
if(i==5) seed = atof(argv[i]);
}
// setting defaults for unspecified args
for(int i=5; i>=argc; i--){
if(i==1) numPoints = 12;
if(i==2) steps = 1000000;
if(i==3) lambda = 1.;
if(i==4) sigma = 1.;
if(i==5) seed = 0;
}
// error handling
if(numPoints <= 0 ||
steps <= 0 ||
lambda <= 0. ||
sigma <= 0.)
{
std::cout << "An argument was invalid! Program terminated." << std::endl;
return 1;
}
// printing arguments
std::cout << '#' << " numPoints = " << numPoints << std::endl;
std::cout << '#' << " steps = " << steps << std::endl;
std::cout << '#' << " lambda = " << lambda << std::endl;
std::cout << '#' << " sigma = " << sigma << std::endl;
std::cout << '#' << " seed = " << seed << std::endl;
// starting simulator
Simulator simulator(numPoints, lambda, sigma, seed);
//succes rate (SR) counters
double percSRradius = 0.0;
double percSRposition = 0.0;
long int SRradius = 0;
long int SRposition = 0;
long int trials = 0;
// main loop
for(long int i=0; i<steps; i++){
// log every 1000th step
if(i%(steps/1000)==0){
percSRradius = (double)SRradius/(double)(trials*numPoints);
percSRposition = (double)SRposition/(double)trials;
trials = 0;
SRradius = 0;
SRposition = 0;
std::cerr << simulator.elapsedTime() << " " << i << " " << std::fixed << std::setprecision(19) << 2*simulator.radius << " " << std::fixed << std::setprecision(10) << percSRradius << " " << percSRposition << std::endl;
//simulator.saveFiles(i);
}
trials++;
for(long int j = 0; j<numPoints;j++){
SRradius += simulator.increaseRadius();
}
SRposition += simulator.movePoint();
}
simulator.saveFiles(0);
return 0;
}
| true |
1fc7dd45e6ffe6b6eec13a2094537245a2ff3759 | C++ | zero91/algorithm | /leetcode/034_Search_for_a_Range/search_for_a_range.cc | UTF-8 | 897 | 3.40625 | 3 | [] | no_license | // Problem:
//
// Given a sorted array of integers,
// find the starting and ending position of a given target value.
//
// Your algorithm's runtime complexity must be in the order of O(log n).
//
// If the target is not found in the array, return [-1, -1].
//
// For example,
// Given [5, 7, 7, 8, 8, 10] and target value 8,
// return [3, 4].
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto left = lower_bound(nums.begin(), nums.end(), target);
auto right = upper_bound(nums.begin(), nums.end(), target);
vector<int> ans(2, -1);
if (left < nums.end() && *left == target) {
ans[0] = left - nums.begin();
ans[1] = right - nums.begin() - 1;
}
return ans;
}
};
int main() {
return 0;
}
| true |