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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1ef0f311a7e622aebd6694cf0f6b33207cbae75d | C++ | Muril-o/UV_RP | /UV_RP/project_esp/esp.ino | UTF-8 | 6,216 | 2.578125 | 3 | [] | no_license | #include <Arduino.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
/* Definições pinos do ML8511 */
#define PIN_GPIO34 34
#define PIN_GPIO35 35
/* Definições do Telegram */
#define TELEGRAM_TIME_CHECK_MESSAGE 250 //Em ms
#define TELEGRAM_TOKEN "1474488007:AAFMnESRAA0qbyfSKGNxJRsvpK4EqxLazkw"
/* Definições das mensagens possíveis de serem recebidas */
#define CMD_UV "UV"
/* Credenciais do Wi-Fi */
#define WIFI_SSID " "
#define WIFI_PASSWORD " "
/* Variáveis globais de saída para os pinos do ML8511 */
int UVOUT = analogRead(PIN_GPIO34); //Output from the sensor (GPIO34)
int REF_3V3 = analogRead(PIN_GPIO35); //3.3V power on the Arduino board (GPIO35)
/* Variáveis e objetos globais para o Wi-Fi */
WiFiClientSecure client;
/* Variáveis e objetos globais para o Telegram */
UniversalTelegramBot bot(TELEGRAM_TOKEN, client);
unsigned long timestamp_checagem_msg_telegram = 0;
int num_mensagens_recebidas_telegram = 0;
String resposta_msg_recebida;
/* Prototypes para Wi-Fi*/
void wifi_init(void);
void wifi_conecta(void);
void wifi_verifica_conexao(void);
/* Prototypes para o Telegram */
unsigned long diferenca_tempo(unsigned long timestamp_referencia);
String trata_mensagem_recebida(String msg_recebida);
/*
* Implementações
*/
/* Função: Inicializa Wi-Fi
* Parâmetros: Nenhum
* Retorno: Nenhum
*/
void wifi_init(void) {
Serial.println("----- Wi-Fi -----");
Serial.print("Conectando-se à rede: ");
Serial.println(WIFI_SSID);
Serial.println("Aguarde...");
wifi_conecta();
}
/* Função: Conecta-se a rede Wi-Fi
* Parâmetros: Nenhum
* Retorno: Nenhum
*/
void wifi_conecta(void) {
/* Se ja estiver conectado, nada é feito. */
if (WiFi.status() == WL_CONNECTED)
return;
/* Refaz a conexão */
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
vTaskDelay(100 / portTICK_PERIOD_MS);
Serial.print(".");
}
Serial.println();
Serial.print("Conectado com sucesso a rede Wi-Fi ");
Serial.println(WIFI_SSID);
Serial.print("IP: ");
Serial.println(WiFi.localIP());
}
/* Função: Verifica se a conexao Wi-Fi está ativa
* (e, em caso negativo, refaz a conexão)
* Parâmetros: Nenhum
* Retorno: Nenhum
*/
void wifi_verifica_conexao(void) {
wifi_conecta();
}
/* Função: Calcula a diferença de tempo entre o timestamp
* de referência e o timestamp atual
* Parâmetros: Timestamp de referência
* Retorno: Diferença de tempo
*/
unsigned long diferenca_tempo(unsigned long timestamp_referencia) {
return (millis() - timestamp_referencia);
}
/* Função: trata mensagens recebidas via Telegram
* Parametros: mensagem recebida
* Retorno: resposta da mensagem recebida
*/
String trata_mensagem_recebida(String msg_recebida) {
String resposta = "";
bool comando_valido = false;
float uv_lido = 0.0;
/* Faz tratamento da mensagem recebida */
if (msg_recebida.equals(CMD_UV)) {
uv_lido = read_uv_value();
resposta = "Intensidade UV: " + String(uv_lido);
comando_valido = true;
}
if (comando_valido == false)
resposta = "Comando invalido: "+msg_recebida;
return resposta;
}
float read_uv_value() {
int uvLevel = averageAnalogRead(UVOUT);
int refLevel = averageAnalogRead(REF_3V3);
//Use the 3.3V power pin as a reference to get a very accurate output value from sensor
float outputVoltage = 3.3 / refLevel * uvLevel;
float uvIntensity = mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0); //Convert the voltage to a UV intensity level
Serial.print("Referencia: ");
Serial.print(refLevel);
Serial.print("ML8511 output: ");
Serial.print(uvLevel);
Serial.print(" / ML8511 voltage: ");
Serial.print(outputVoltage);
Serial.print(" / UV Intensity (mW/cm^2): ");
Serial.print(uvIntensity);
Serial.println();
return uvIntensity;
}
void setup() {
Serial.begin(9600);
/* Inicializa a conexão Wi-Fi */
wifi_init();
/* Inicializa timestamp de checagem de mensagens recebidas via Telegram */
timestamp_checagem_msg_telegram = millis();
}
void loop() {
int i;
/* Garante que o Wi-Fi está conectado */
wifi_verifica_conexao();
/* Verifica se é hora de checar por mensagens enviadas ao bot Telegram */
if (diferenca_tempo(timestamp_checagem_msg_telegram) >= TELEGRAM_TIME_CHECK_MESSAGE) {
/* Verifica se há mensagens a serem recebidas */
num_mensagens_recebidas_telegram = bot.getUpdates(bot.last_message_received + 1);
if (num_mensagens_recebidas_telegram > 0) {
Serial.print("[BOT] Mensagens recebidas: ");
Serial.println(num_mensagens_recebidas_telegram);
}
/* Recebe mensagem a mensagem, faz tratamento e envia resposta */
while(num_mensagens_recebidas_telegram) {
for (i=0; i<num_mensagens_recebidas_telegram; i++) {
resposta_msg_recebida = "";
resposta_msg_recebida = trata_mensagem_recebida(bot.messages[i].text);
bot.sendMessage(bot.messages[i].chat_id, resposta_msg_recebida, "");
}
num_mensagens_recebidas_telegram = bot.getUpdates(bot.last_message_received + 1);
}
/* Reinicializa timestamp de checagem de mensagens recebidas via Telegram */
timestamp_checagem_msg_telegram = millis();
}
}
//Recebe os valores de leitura de um determinado pin
//Retorna o valor medio
int averageAnalogRead(int pinToRead) {
byte numberOfReadings = 8;
unsigned int runningValue = 0;
for(int x = 0 ; x < numberOfReadings ; x++)
runningValue += analogRead(pinToRead);
runningValue /= numberOfReadings;
return(runningValue);
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
| true |
e2ab52c577c61d918e1209a180762f1b090be380 | C++ | Pinkii-/LD48 | /Object.hpp | UTF-8 | 568 | 2.53125 | 3 | [] | no_license | #ifndef OBJECT_HPP
#define OBJECT_HPP
#include "utils.hpp"
class LD48;
class Object
{
public:
Object(LD48* game, sf::Vector2f size, sf::Texture& tex, sf::Vector2i spriteCount );
LD48* game;
sf::Vector2f position;
sf::Vector2f size;
sf::Texture& tex;
sf::Vector2i spriteCount;
sf::Vector2i spriteNum;
sf::Sprite sprite;
virtual void update(float deltaTime);
virtual void draw();
bool receivesCollisions;
bool dead;
virtual void collidedWith(Object* b);
bool collidesWith(Object* b);
};
#endif // OBJECT_HPP
| true |
16f40c6685f363858964a6f44e213383d6bfdd6a | C++ | Gystre/HaloCE-internal | /haloCE-internal/matrix.cpp | UTF-8 | 1,857 | 2.796875 | 3 | [] | no_license | #include "pch.h"
#include "matrix.h"
#include "vector4d.h"
mat4_t::mat4_t() {
m11 = m12 = m13 = m14 = m21 = m22 = m23 = m24 = m31 = m32 = m33 = m34 = m41 = m42 = m43 = m44 = 0;
}
mat4_t::mat4_t(float x1, float x2, float x3, float x4,
float y1, float y2, float y3, float y4,
float z1, float z2, float z3, float z4,
float w1, float w2, float w3, float w4) {
m11 = x1; m12 = x2; m13 = x3; m14 = x4;
m21 = y1; m22 = y2; m23 = y3; m24 = y4;
m31 = z1; m32 = z2; m33 = z3; m34 = z4;
m41 = w1; m42 = w2; m43 = w3; m44 = w4;
}
mat4_t::~mat4_t() { }
//w2s specifically for directx
bool mat4_t::worldToScreen(vec3_t pos, int windowWidth, int windowHeight, vec2_t& screen) {
vec4_t clipCoords;
clipCoords.x = pos.x * m11 + pos.y * m12 + pos.z * m13 + m14;
clipCoords.y = pos.x * m21 + pos.y * m22 + pos.z * m23 + m24;
clipCoords.z = pos.x * m31 + pos.y * m33 + pos.z * m33 + m34;
clipCoords.w = pos.x * m41 + pos.y * m44 + pos.z * m43 + m44;
if (clipCoords.w < 0.1f)
return false;
vec3_t NDC;
NDC.x = clipCoords.x / clipCoords.w;
NDC.y = clipCoords.y / clipCoords.w;
NDC.z = clipCoords.z / clipCoords.w;
screen.x = (windowWidth / 2 * NDC.x) + (NDC.x + windowWidth / 2);
screen.y = -(windowHeight / 2 * NDC.y) + (NDC.y + windowHeight / 2);
return true;
}
std::string mat4_t::toString() {
return "[ " + std::to_string(m11) + " " + std::to_string(m12) + " " + std::to_string(m13) + " " + std::to_string(m14) + " ]\n" +
"[ " + std::to_string(m21) + " " + std::to_string(m22) + " " + std::to_string(m23) + " " + std::to_string(m24) + " ]\n" +
"[ " + std::to_string(m31) + " " + std::to_string(m32) + " " + std::to_string(m33) + " " + std::to_string(m34) + " ]\n" +
"[ " + std::to_string(m41) + " " + std::to_string(m42) + " " + std::to_string(m43) + " " + std::to_string(m44) + " ]";
} | true |
a37e847f0bb3d84e90919b9f36c1b5d72620ac32 | C++ | JaviVinnas/Proyecto-final-de-COGA | /ProyectoFinalCOGA/LocalizadorShader.h | UTF-8 | 2,326 | 2.734375 | 3 | [] | no_license | #pragma once
#ifndef GLAD_H
#include <glad.h>
#endif // !GLAD_H
#ifndef GLM_HPP
#include <glm/glm.hpp>
#endif // !GLM_HPP
#ifndef MATRIX_TRANSFORM_HPP
#include <glm/gtc/matrix_transform.hpp>
#endif // !MATRIX_TRANSFORM_HPP
#ifndef TYPE_PTR_HPP
#include <glm/gtc/type_ptr.hpp>
#endif // !TYPE_PTR_HPP
#ifndef CMATH
#include <cmath>
#endif // !CMATH
using namespace glm;
class LocalizadorShader;
class LocalizadorVertexShader;
class LocalizadorFragmentShader;
class LocalizadorShader
{
private:
//vertex shader
class LocalizadorVertexShader
{
private:
unsigned view;
unsigned projection;
unsigned model;
public:
LocalizadorVertexShader();
LocalizadorVertexShader(GLuint shaderProgram);
void cargarView(mat4 const &matrix);
void cargarProjection(mat4 const &matrix);
void cargarModel(mat4 const &matrix);
void cargarObjetoyDibujar(GLuint vaoObjeto);
};
//fragment shader
class LocalizadorFragmentShader
{
private:
//color de la luz
unsigned lightColor;
//posición de la luz
unsigned lightPos;
//posición del observador
unsigned viewPos;
//2texturas (2 unsigned ints)
uvec2 texturas;
//color de la luz actual
vec3 lightColorActual;
public:
LocalizadorFragmentShader();
LocalizadorFragmentShader(GLuint const &shaderProgram);
void cargarColorLuz(vec3 const &lightColor);
void cargarPosiciónLuz(vec3 const &lightPos);
void cargarPosicionEspectador(vec3 const &viewPos);
void cargarTexturas(uvec2 const &texturas);
vec3 getLightColorActual();
};
LocalizadorVertexShader locVertexShader;
LocalizadorFragmentShader locFragmentShader;
public:
LocalizadorShader();
LocalizadorShader(GLuint shaderProgram);
//vertex
void cargarView(mat4 const &matrix);
void cargarProjection(mat4 const &matrix);
void cargarModel(mat4 const &matrix);
void cargarObjetoyDibujar(GLuint vaoObjeto);
//fragment
void cargarColorLuz(vec3 const &lightColor);
void cargarPosicionLuz(vec3 const &lightPos);
void cargarPosicionEspectador(vec3 const &viewPos);
void cargarTexturas(uvec2 const &texturas);
vec3 getLightColorActual();
};
| true |
b37e278b71ed6dbc2264974185ba43205e4c0506 | C++ | chenfan2014/CFgit | /LeetCode/numberToTitle.cpp | UTF-8 | 874 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
const int SIZE = 1024;
string numberToTitle(int number)
{
if(number == 0){
return "";
}
char s[SIZE] = "";
int i = 0;
while(number)
{
int n = number % 26;
if(n == 0){
s[i] = 'Z';
number -= 26;
}else{
s[i] = (char)(n - 1 + 'A');
number -= n;
}
i ++;
number /= 26;
}
i = 0;
int size = strlen(s) - 1;
while(i < (size + 1)/2)
{
char c = s[i];
s[i] = s[size - i];
s[size - i] = c;
i ++;
}
return s;
}
int main(int argc, const char *argv[])
{
//706 AAD 1457 BDA
int n;
while(1)
{
cin >> n;
cout << numberToTitle(n) << endl;
}
return 0;
}
| true |
20586d4fe1b6e5bebf8afb9d56d1df75fc646bd2 | C++ | eooomji/StudyCPP | /Chap05/예제 5-11.cpp | UHC | 1,935 | 4.1875 | 4 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
class Person { // Person Ŭ
char* name;
int id;
public:
Person(int id, const char* name); //
Person(const Person& person); //
~Person(); // Ҹ
void changeName(const char* name);
void show() { cout << id << ',' << name << endl; }
};
Person::Person(int id, const char* name) { //
this->id = id;
int len = strlen(name); // name
this->name = new char[len + 1]; // name ڿ Ҵ
strcpy(this->name, name); // name ڿ
}
Person::Person(const Person& person) { //
this->id = person.id; // id
int len = strlen(person.name); // name
this->name = new char[len + 1]; // name Ҵ
strcpy(this->name, person.name); // name ڿ
cout << " . ü ̸" << this->name << endl;
}
Person::~Person() { // Ҹ
if (name) // name Ҵ 迭
delete[] name; // Ҵ Ҹ
}
void Person::changeName(const char* name) { // ̸
if (strlen(name) > strlen(this->name))
return; // name Ҵ ̸ ٲ
strcpy(this->name, name);
}
int main() {
Person father(1, "Kitae"); // (1) father ü
Person daughter(father); // (2) daughter ü . ȣ
cout << "daughter ü ----" << endl;
father.show(); // (3) father ü
daughter.show(); // (3) father ü
daughter.changeName("Grace"); // (4) daughter ̸ "Grace"
cout << "daughter ̸ Grace ----" << endl;
father.show(); // (5) father ü
daughter.show(); // (5) daughter ü
return 0; // (6), (7) daughter, father ü Ҹ
}
| true |
09847827f64d901c684a86d8d3ab09ccd2ca8dd7 | C++ | SetsunaChyan/OI_source_code | /Luogu/P1019.cpp | UTF-8 | 1,019 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
char s[20][255], head;
int n, maxn = 0, ans, vis[20];
inline int min(int a, int b)
{
return a < b ? a : b;
}
int min_cover(int sa, int sb)
{
int la = strlen(s[sa]);
int lb = strlen(s[sb]);
for(int i = 1; i < min(la, lb); i++)
{
int flag = 0;
for(int j = la - i, k = 0; j < la; j++, k++)
{
if(s[sa][j] != s[sb][k])
{
flag = 1;
break;
}
}
if(flag == 0) return i;
}
return 0;
}
void dfs(int last)
{
for(int i = 0; i < n; i++)
{
if(vis[i] == 2) continue;
int cov = min_cover(last, i);
if(cov == 0) continue;
vis[i]++;
ans += strlen(s[i]) - cov;
if(ans > maxn) maxn = ans;
dfs(i);
vis[i]--;
ans -= strlen(s[i]) - cov;
}
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", s[i]);
vis[i] = 0;
}
scanf(" %c", &head);
for(int i = 0; i < n; i++)
if(s[i][0] == head)
{
ans = strlen(s[i]);
vis[i]++;
if(ans > maxn) maxn = ans;
dfs(i);
vis[i]--;
}
printf("%d\n", maxn);
return 0;
} | true |
ff1a5469f4555c52ccab10bbee0e97bbea854104 | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/boost/random/xor_combine.hpp | UTF-8 | 7,118 | 2.84375 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | /* boost random/xor_combine.hpp header file
*
* Copyright Jens Maurer 2002
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org for most recent version including documentation.
*
* $Id$
*
*/
#ifndef BOOST_RANDOM_XOR_COMBINE_HPP
#define BOOST_RANDOM_XOR_COMBINE_HPP
#include <istream>
#include <iosfwd>
#include <cassert>
#include <algorithm> // for std::min and std::max
#include <boost/config.hpp>
#include <boost/limits.hpp>
#include <boost/cstdint.hpp> // uint32_t
#include <boost/random/detail/config.hpp>
#include <boost/random/detail/seed.hpp>
#include <boost/random/detail/seed_impl.hpp>
#include <boost/random/detail/operators.hpp>
namespace boost {
namespace random {
/**
* Instantiations of @c xor_combine_engine model a
* \pseudo_random_number_generator. To produce its output it
* invokes each of the base generators, shifts their results
* and xors them together.
*/
template<class URNG1, int s1, class URNG2, int s2>
class xor_combine_engine
{
public:
typedef URNG1 base1_type;
typedef URNG2 base2_type;
typedef typename base1_type::result_type result_type;
BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
BOOST_STATIC_CONSTANT(int, shift1 = s1);
BOOST_STATIC_CONSTANT(int, shift2 = s2);
/**
* Constructors a @c xor_combine_engine by default constructing
* both base generators.
*/
xor_combine_engine() : _rng1(), _rng2() { }
/** Constructs a @c xor_combine by copying two base generators. */
xor_combine_engine(const base1_type & rng1, const base2_type & rng2)
: _rng1(rng1), _rng2(rng2) { }
/**
* Constructs a @c xor_combine_engine, seeding both base generators
* with @c v.
*
* @xmlwarning
* The exact algorithm used by this function may change in the future.
* @endxmlwarning
*/
BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(xor_combine_engine,
result_type, v)
{ seed(v); }
/**
* Constructs a @c xor_combine_engine, seeding both base generators
* with values produced by @c seq.
*/
BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(xor_combine_engine,
SeedSeq, seq)
{ seed(seq); }
/**
* Constructs a @c xor_combine_engine, seeding both base generators
* with values from the iterator range [first, last) and changes
* first to point to the element after the last one used. If there
* are not enough elements in the range to seed both generators,
* throws @c std::invalid_argument.
*/
template<class It> xor_combine_engine(It& first, It last)
: _rng1(first, last), _rng2( /* advanced by other call */ first, last) { }
/** Calls @c seed() for both base generators. */
void seed() { _rng1.seed(); _rng2.seed(); }
/** @c seeds both base generators with @c v. */
BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(xor_combine_engine, result_type, v)
{ _rng1.seed(v); _rng2.seed(v); }
/** @c seeds both base generators with values produced by @c seq. */
BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(xor_combine_engine, SeedSeq, seq)
{ _rng1.seed(seq); _rng2.seed(seq); }
/**
* seeds both base generators with values from the iterator
* range [first, last) and changes first to point to the element
* after the last one used. If there are not enough elements in
* the range to seed both generators, throws @c std::invalid_argument.
*/
template<class It> void seed(It& first, It last)
{
_rng1.seed(first, last);
_rng2.seed(first, last);
}
/** Returns the first base generator. */
const base1_type& base1() const { return _rng1; }
/** Returns the second base generator. */
const base2_type& base2() const { return _rng2; }
/** Returns the next value of the generator. */
result_type operator()()
{
return (_rng1() << s1) ^ (_rng2() << s2);
}
/** Fills a range with random values */
template<class Iter>
void generate(Iter first, Iter last)
{ detail::generate_from_int(*this, first, last); }
/** Advances the state of the generator by @c z. */
void discard(boost::uintmax_t z)
{
_rng1.discard(z);
_rng2.discard(z);
}
/** Returns the smallest value that the generator can produce. */
static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
{ return (URNG1::min)()<(URNG2::min)()?(URNG1::min)():(URNG2::min)(); }
/** Returns the largest value that the generator can produce. */
static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
{ return (URNG1::max)()>(URNG2::max)()?(URNG1::max)():(URNG2::max)(); }
/**
* Writes the textual representation of the generator to a @c std::ostream.
*/
BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, xor_combine_engine, s)
{
os << s._rng1 << ' ' << s._rng2;
return os;
}
/**
* Reads the textual representation of the generator from a @c std::istream.
*/
BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, xor_combine_engine, s)
{
is >> s._rng1 >> std::ws >> s._rng2;
return is;
}
/** Returns true if the two generators will produce identical sequences. */
BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(xor_combine_engine, x, y)
{ return x._rng1 == y._rng1 && x._rng2 == y._rng2; }
/** Returns true if the two generators will produce different sequences. */
BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(xor_combine_engine)
private:
base1_type _rng1;
base2_type _rng2;
};
#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
// A definition is required even for integral static constants
template<class URNG1, int s1, class URNG2, int s2>
const bool xor_combine_engine<URNG1, s1, URNG2, s2>::has_fixed_range;
template<class URNG1, int s1, class URNG2, int s2>
const int xor_combine_engine<URNG1, s1, URNG2, s2>::shift1;
template<class URNG1, int s1, class URNG2, int s2>
const int xor_combine_engine<URNG1, s1, URNG2, s2>::shift2;
#endif
/// \cond show_private
/** Provided for backwards compatibility. */
template<class URNG1, int s1, class URNG2, int s2,
typename URNG1::result_type v = 0>
class xor_combine : public xor_combine_engine<URNG1, s1, URNG2, s2>
{
typedef xor_combine_engine<URNG1, s1, URNG2, s2> base_type;
public:
typedef typename base_type::result_type result_type;
xor_combine() {}
xor_combine(result_type val) : base_type(val) {}
template<class It>
xor_combine(It& first, It last) : base_type(first, last) {}
xor_combine(const URNG1 & rng1, const URNG2 & rng2)
: base_type(rng1, rng2) { }
result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return (std::min)((this->base1().min)(), (this->base2().min)()); }
result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return (std::max)((this->base1().min)(), (this->base2().max)()); }
};
/// \endcond
} // namespace random
} // namespace boost
#endif // BOOST_RANDOM_XOR_COMBINE_HPP
| true |
b4b85cbcdaa911b6054e804b1353093eb1fade9c | C++ | cjawahar/wssaLab3 | /I2C_1/I2C_1.ino | UTF-8 | 2,664 | 2.6875 | 3 | [] | no_license | // This file is ConfigureExample -- overwritten.
// I2C interface by default
#include "Wire.h"
#include "SparkFunIMU.h"
#include "SparkFunLSM303C.h"
#include "LSM303CTypes.h"
#include "DebugMacros.h"
#include "FreeRTOS_ARM.h"
/*
define DEBUG 1 in SparkFunLSM303C.cpp turns on debugging statements.
Redefine to 0 to turn them off.
*/
/*
SPI pins defined in SparkFunLSM303C.h for Pro Mini
D10 -> SDI/SDO
D11 -> SCLK
D12 -> CS_XL
D13 -> CS_MAG
*/
LSM303C myIMU;
float magX, magY, magZ;
SemaphoreHandle_t Read, Write;
static void Read_Val(void* arg){
while(1){
xSemaphoreTake(Read, portMAX_DELAY);
magX = myIMU.readMagX();
magY = myIMU.readMagY();
magZ = myIMU.readMagZ();
xSemaphoreGive(Write);
}
}
static void Write_Val(void* arg){
while(1){
xSemaphoreTake(Write, portMAX_DELAY);
SerialUSB.println("Magnetometer X: ");
SerialUSB.println(magX, 4);
SerialUSB.println("Magnetometer Y: ");
SerialUSB.println(magY, 4);
SerialUSB.println("Magnetometer Z: ");
SerialUSB.println(magZ, 4);
xSemaphoreGive(Read);
SerialUSB.println("");
delay(2000);
}
}
/* Answers to Part 1 Questions.
*
* 1. The default I2C clockspeed is 100 kHz for the standard mode.
* 2. The LSM303C's maximum clock speed is 400 kHz.
* 3. The code is using a 400000 Hz frequency, as seen in Wire.setClock.
* 4. Looks like 3 bytes are required. 2 to denote the address of device/receiver
* and then 1 bytes for the data itself.
* 5.
*
*/
uint8_t mag_id;
void setup() {
// Commented out as we are using Wire1 instead of Wire.
//Wire.begin();//set up I2C bus, comment out if using SPI mode
//Wire.setClock(400000L);//clock stretching, comment out if using SPI mode
portBASE_TYPE s1, s2;
while(!SerialUSB);
Serial.begin(115200);//initialize serial monitor, maximum reliable baud for 3.3V/8Mhz ATmega328P is 57600
Wire1.begin();
Wire1.setClock(400000L);
if (myIMU.begin() != IMU_SUCCESS)
{
SerialUSB.println("Failed setup.");
while (1);
}
// WHO_AM_I Section
if (myIMU.mag_whoami() != IMU_SUCCESS) {
SerialUSB.println("Failure to read: MAG_WHO_AM_I");
}
else {
SerialUSB.println("MAG WHO AM I id = ");
SerialUSB.println(mag_id, 1);
}
//Semaphores
Read = xSemaphoreCreateCounting(1, 1);
Write = xSemaphoreCreateCounting(1, 0);
s1 = xTaskCreate(Read_Val, NULL, configMINIMAL_STACK_SIZE, NULL, 1, NULL);
s2 = xTaskCreate(Write_Val, NULL, configMINIMAL_STACK_SIZE, NULL, 1, NULL);
vTaskStartScheduler();
while(1);
}
void loop()
{
// Removed everything that was present here from ConfigureExample.
}
| true |
67611f2b827d3326cc13b7d571a8fee01e4ec84c | C++ | sgadrat/super-tilt-bro-server | /src/server/StatisticsSink.hpp | UTF-8 | 1,915 | 2.578125 | 3 | [] | no_license | #pragma once
#include "GameState.hpp"
#include "network.hpp"
#include "src/utils.hpp"
#include <chrono>
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <uuid/uuid.h>
/** Component processing reports from the rest of the game, outputing statistics */
class StatisticsSink {
public:
struct GameLog {
struct Entry {
std::chrono::steady_clock::time_point time;
std::shared_ptr<network::IncommingUdpMessage> datagram;
bool new_batch;
};
std::array<Entry, 1000> log;
size_t next_log = 0;
void new_net_message(
std::chrono::steady_clock::time_point const& time,
std::shared_ptr<network::IncommingUdpMessage> datagram,
bool new_batch
);
};
struct GameInfo {
uuid_t game_id;
GameLog game_log;
std::chrono::system_clock::time_point game_begin;
std::chrono::system_clock::time_point game_end;
std::shared_ptr<std::map<uint32_t, GameState::ControllerState>> controller_a_history;
std::shared_ptr<std::map<uint32_t, GameState::ControllerState>> controller_b_history;
size_t num_ticks_in_game;
uint32_t client_a_id;
uint32_t client_b_id;
bool player_a_ranked;
bool player_b_ranked;
uint8_t character_a;
uint8_t character_b;
uint8_t character_a_palette;
uint8_t character_b_palette;
uint8_t stage;
uint8_t video_system;
uint8_t winner;
};
StatisticsSink(
std::string game_info_path,
std::shared_ptr<ThreadSafeFifo<GameInfo>> in_messages
);
void run();
void stop();
private:
std::shared_ptr<ThreadSafeFifo<GameInfo>> in_messages;
std::string game_info_path;
};
inline void StatisticsSink::GameLog::new_net_message(
std::chrono::steady_clock::time_point const& time,
std::shared_ptr<network::IncommingUdpMessage> datagram,
bool new_batch
)
{
if (this->next_log < this->log.size()) {
this->log[this->next_log] = {
.time = time, .datagram = datagram, .new_batch = new_batch
};
++this->next_log;
}
}
| true |
4ade6a8040bde0b99973abcd621cf85813268ba1 | C++ | jorgerodrigar/Sistema-de-Integracion-Continua | /ProyectosSDL/Tracker/src/TrackerEvents.cpp | ISO-8859-1 | 4,439 | 2.8125 | 3 | [] | no_license | #include "TrackerEvents.h"
#include "json.hpp"
using namespace nlohmann;
const string TrackerEvent::toJson() const
{
json j;
//Elementos comunes del evento
j["userID"] = id_;
j["time"] = timeStamp_;
j["type"] = eventTypes[type_]; // escribe el tipo de forma legible
string result = j.dump();
return result;
}
const string TrackerEvent::toCSV() const
{
string timeStamp = to_string(timeStamp_);
string type = eventTypes[type_]; // escribe el tipo de forma legible
string result = "user id: " + id_ + ",time: " + timeStamp + ",type: " + type;
//Tambin se puede usar append y sstream, pero de momento lo dejo as que es lo mismo
return result;
}
const string TestEvent::toJson() const
{
//Aqu se meteran los atributos especificos del evento en el json
string head = TrackerEvent::toJson();
json j;
//Elementos comunes del evento
j["userID"] = id_;
j["time"] = timeStamp_;
string info = j.dump();
string result = head + info;
return result;
}
const string TestEvent::toCSV() const
{
//Aqu iran los atributos especficos del evento en csv
string head = TrackerEvent::toCSV();
string timeStamp = to_string(timeStamp_);
string result = head + ",user id: " + id_ + ",time: " + timeStamp;
return result;
}
TrackerEvent* TestEvent::clone() const
{
return new TestEvent(timeStamp_, id_);
}
const string SceneEvent::toJson() const
{
//Habra que mirar la legibilidad
string head = TrackerEvent::toJson();
json j;
j["Number scene"] = numScene_;
j["Action"] = eventActions[action_];
string info = j.dump();
string result = head + info;
return result;
}
const string SceneEvent::toCSV() const
{
//Revisar
string head = TrackerEvent::toCSV();
string result = head + ",Number scene: " + to_string(numScene_) + ",Action: " + eventActions[action_];
return result;
}
TrackerEvent* SceneEvent::clone() const
{
SceneEvent* aux = new SceneEvent(timeStamp_, id_);
aux->setParameters(numScene_, action_);
return aux;
}
const string PuzzleEvent::toJson() const
{
string head = TrackerEvent::toJson();
json j;
j["Number puzzle"] = numPuzzle_;
j["Action"] = eventActions[action_];
string info = j.dump();
string result = head + info;
return result;
}
const string PuzzleEvent::toCSV() const
{
string head = TrackerEvent::toCSV();
string result = head + ",Number puzzle: " + to_string(numPuzzle_) + ",Action: " + eventActions[action_];
return result;
}
const string ClickEvent::toJson() const
{
string head = TrackerEvent::toJson();
json j;
j["Position_X"] = pos_.first;
j["Position_Y"] = pos_.second;
string info = j.dump();
string result = head + info;
return result;
}
const string ClickEvent::toCSV() const
{
string head = TrackerEvent::toCSV();
string result = head + ",Position_X: " + to_string(pos_.first) +
",Position_Y: " + to_string(pos_.second);
return result;
}
const string ClickSceneEvent::toJson() const
{
string head = ClickEvent::toJson();
json j;
j["Number scene"] = numScene_;
string info = j.dump();
string result = head + info;
return result;
}
const string ClickSceneEvent::toCSV() const
{
string head = ClickEvent::toCSV();
string result = head + ",Number scene: " + to_string(numScene_);
return result;
}
TrackerEvent* ClickSceneEvent::clone() const
{
ClickSceneEvent* aux = new ClickSceneEvent(timeStamp_, id_);
aux->setParameters(numScene_, pos_);
return aux;
}
const string ClickPuzzleEvent::toJson() const
{
string head = ClickEvent::toJson();
json j;
j["Number puzzle"] = numPuzzle_;
string info = j.dump();
string result = head + info;
return result;
}
const string ClickPuzzleEvent::toCSV() const
{
string head = ClickEvent::toCSV();
string result = head + ",Number puzzle: " + to_string(numPuzzle_);
return result;
}
TrackerEvent* ClickPuzzleEvent::clone() const
{
ClickPuzzleEvent* aux = new ClickPuzzleEvent(timeStamp_, id_);
aux->setParameters(numPuzzle_, pos_);
return aux;
}
TrackerEvent* SessionStartEvent::clone() const
{
return new SessionStartEvent(timeStamp_, id_);
}
TrackerEvent* SessionEndEvent::clone() const
{
return new SessionEndEvent(timeStamp_, id_);
}
TrackerEvent* Connect4Event::clone() const
{
Connect4Event* aux = new Connect4Event(timeStamp_, id_);
aux->setParameters(numPuzzle_, action_);
return aux;
}
TrackerEvent* LightPuzzleEvent::clone() const
{
LightPuzzleEvent* aux = new LightPuzzleEvent(timeStamp_, id_);
aux->setParameters(numPuzzle_, action_);
return aux;
}
| true |
bc55c59d01d666b0842877ba74666fa82ba23abe | C++ | Lee-W/ACM | /POJ/1125/1125.cpp | UTF-8 | 1,639 | 2.84375 | 3 | [] | no_license | #include <cstdio>
#include <climits>
#include <numeric>
#include <algorithm>
#define maxStockholderNum 105
int dis[maxStockholderNum][maxStockholderNum];
void Floyd(int n) {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (dis[i][k] + dis[k][j] < dis[i][j])
dis[i][j] = dis[i][k] + dis[k][j];
}
main()
{
int stockholderNum, pairNum, contact, time;
while(scanf("%d", &stockholderNum) && stockholderNum) {
//initial dis
for (int i = 1; i <= stockholderNum; i++) {
for (int j = 1; j <= stockholderNum; j++)
dis[i][j] = INT_MAX/2;
dis[i][i] = 0;
scanf("%d", &pairNum);
while(pairNum--) {
scanf("%d%d", &contact, &time);
dis[i][contact] = time;
}
}
Floyd(stockholderNum);
int sum = INT_MAX, tmpSum;
int source, max = 0;
for (int i = 1; i <= stockholderNum; i++) {
if (std::find(dis[i]+1, dis[i]+stockholderNum+1, INT_MAX/2) != dis[i]+stockholderNum+1) {
continue;
} else
tmpSum = std::accumulate(dis[i]+1, dis[i]+stockholderNum+1, 0);
if (tmpSum < sum) {
source = i;
sum = tmpSum;
}
}
if (sum != INT_MAX) {
max = *std::max_element(dis[source]+1, dis[source]+stockholderNum+1);
printf("%d %d\n", source, max);
}
else
printf("disjoint\n"); //測資好像沒這個也會AC@@
}
}
| true |
533e2daf173e079773e83aa7780d5545ba107732 | C++ | iangrigiani/tpdatos2daentrega | /sadfghjkl/src/Arbol/ArbolBMas.h | UTF-8 | 3,874 | 2.703125 | 3 | [] | no_license |
#ifndef _ARBOLBMAS_H_
#define _ARBOLBMAS_H_
#include "../EstructurasArbol/Elementos.h"
#include "NodoInterior.h"
#include "../Persistencia/PersistorArbol.h"
#include "../EstructurasArbol/Solucion.h"
#include <fstream>
#include <vector>
#include <list>
using namespace std;
class ArbolBMas {
friend class Nodo;
friend class NodoInterior;
friend class NodoHoja;
private:
Nodo* raiz;
int primeraHoja;
int cantidadNodos;
string pathId;
int tipoDeArbol; // 1 es arbol primario, 2 es secundario
vector<int> nodosLibres;
PersistorArbol* persistor;
Clave ultimaClave;
enum enumReturn {RESULTADO_OK = 0, NO_ENCONTRADO = 1, ACTUALIZAR_ULTIMA_CLAVE = 2, FUSION = 4} flags;
public:
ArbolBMas(string ruta_archivo,string ruta_Contador, int tipoDeArbol);
~ArbolBMas();
int insertar(Elementos* registro, bool incrementarID);
bool modificar(Elementos* registro);
bool incrementarID(Elementos* elemento, int& frecuencia);
bool decrementarID(Elementos* elemento);
// IteradorArbolBMas* begin();
/*
* Primitiva que va a buscar una clave o cadena de caracteres en la estructura o archivo
* Pre: Recibo la clave del registro a buscar.
* Pos: Si lo encontro, devuelve el registro, sino, devuelve NULL.
*/
// pair<Elementos*, IteradorArbolBMas*> buscar(Clave clave);
bool borrar(Elementos* elemento);
void mostrar();
Nodo* leerNodo(int numeroDeNodo);
int getCantidadBloques();
void buscar(list<Elementos*>* listaElementos, Clave* clave);
private:
void llenarListadeBusqueda(list<Elementos*>* listaElementos, NodoHoja* nodo, int posicion, Clave* clave);
bool claveMenor(Clave clave1, Clave clave2);
bool claveMenorIgual(Clave clave1, Clave clave2);
bool claveIgual(Clave clave1, Clave clave2);
NodoHoja* crearNodoHoja();
NodoInterior* crearNodoInterior(int nivel);
void liberarMemoriaNodo(Nodo *unNodo);
int obtenerPosicion(Nodo *unNodo, Clave clave);
bool insertarRecursivo(Nodo* nodoCorriente, Clave clave, Persistencia dato, Persistencia id, Clave* clavePromocion, Nodo** nuevoNodo, Persistencia* idInsertado, bool incrementarID);
void dividirNodoHoja(NodoHoja* unNodoHoja, Clave* clavePromocion, Nodo** nuevoNodoHoja);
void dividirNodoInterior(NodoInterior* unNodoInterior, Clave* clavePromocion, Nodo** nuevoNodoInterior, int nuevaPosicion);
int borrarRecursivo(Elementos* elem, Clave clave, Nodo *nodoCorriente, Nodo *nodoIzquierda, Nodo *nodoDerecha,
NodoInterior *nodoPadreIzquierda, NodoInterior *nodoPadreDerecha, NodoInterior *nodoPadre, int posicionPadre);
int fusionarHojas(NodoHoja* hojaIzquierda, NodoHoja* hojaDerecha);
int fusionarNodosInteriores(NodoInterior* nodoIzquierda, NodoInterior* nodoDerecha, NodoInterior* nodoPadre, int posicionPadre);
int pasarElementosHojaIzquierda(NodoHoja *hojaIzquierda, NodoHoja *hojaDerecha, NodoInterior *nodoPadre, int posicionPadre);
void pasarElementosNodoInteriorIzquierdo(NodoInterior *nodoIzquierda, NodoInterior *nodoDerecha, NodoInterior *nodoPadre, int posicionPadre);
void pasarElementosHojaDerecha(NodoHoja *hojaIzquierda, NodoHoja *hojaDerecha, NodoInterior *nodoPadre, int posicionPadre);
void pasarElementosNodoInteriorDerecho(NodoInterior *nodoIzquierda, NodoInterior *nodoDerecha, NodoInterior *nodoPadre, int posicionPadre);
void persistirNodo(Nodo* unNodo);
Nodo* hidratarNodo(int numeroDeNodo);
int obtenerNumeroDeNodo();
void persistirDatosConfiguracion();
void hidratarDatosConfiguracion();
void toString(Nodo* nodoAmostrar, int tab, ofstream& fo);
void refactorizarNodoFrontCoding(NodoHoja** nodoHojaCorriente);
void refactorizarNodoNoHojaFrontCoding(Nodo** nodo);
void sacarFrontCodingNodo (Nodo ** nodo);
void sacarFrontCodingNodoHoja (NodoHoja ** nodo);
Solucion buscarSecuencialClave(int nodo, Elementos* elemento, int posicion);
Persistencia obtenerNuevoId(string path);
};
#endif // _ARBOLBMAS_H_
| true |
95646c154a43e8cdc5ff8620dad3eb626fb9115a | C++ | sk2282/ECE3400_Team8 | /code/milestone1/milestone1.ino | UTF-8 | 2,971 | 2.828125 | 3 | [] | no_license | /* MILESTONE 1
* Team 8: The Resistance
* Monday Night Lab
*/
#include <Servo.h>
Servo left;
Servo right;
// GLOBAL VARIABLES //
int leftLine = 0; // Pin for left line detector
int rightLine = 1; // Pin for right line detector
int leftWide = 2; // Pin for left intersection detector
int rightWide = 3; // Pin for right intersection detector
int thresh = 800; // Threshold for black line detection
int intsec = 0; // Number of intersections detected
int detectCooldown = 0;
int DETECT_COOLDOWN = 50;
int roboStop = 0; // robot stops moving
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
left.attach(5); // above 90 is forward - THESE ARE DIGITAL PINS
right.attach(6); // below 90 is forward
}
void loop() {
int lRead = analogRead(leftLine);
int rRead = analogRead(rightLine);
int lwRead = analogRead(leftWide);
int rwRead = analogRead(rightWide);
// INTERSECTION DETECTION
if((lwRead >= thresh || rwRead >= thresh) && detectCooldown == 0){
switch (intsec){
case 0:
Serial.println("Case0");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
goStraight();
break;
case 1:
Serial.println("Case1");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
leftTurn();
break;
case 2:
Serial.println("Case2");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
leftTurn();
break;
case 3:
Serial.println("Case3");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
leftTurn();
break;
case 4:
Serial.println("Case4");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
goStraight();
break;
case 5:
Serial.println("Case5");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
rightTurn();
break;
case 6:
Serial.println("Case6");
intsec++;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
rightTurn();
break;
case 7:
Serial.println("Case7");
intsec = 0;
detectCooldown = DETECT_COOLDOWN;
roboStop = 0;
rightTurn();
break;
default:
Serial.println("Default");
roboStop = 0;
break;
}
}
else{
detectCooldown--;
if (detectCooldown < 0) detectCooldown = 0;
}
if(lRead<=thresh && rRead<=thresh || roboStop){ // stop
left.write(90);
right.write(90);
}
else{
if(lRead<thresh){ // left side is out of line
left.write(170);
right.write(86);
}
else if(rRead<thresh){ // right side is out of line
left.write(94);
right.write(10);
}
else{ // go straight
left.write(100);
right.write(80);
}
}
}
| true |
83cdd5af04ca7d329758cc38f648e416541c6569 | C++ | vedant-jad99/DSA-450 | /Linked List/Reverse a linked list/reverse_ll.cc | UTF-8 | 865 | 3.765625 | 4 | [] | no_license | /*
Link to the question - https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1
Approach 1 - Recursive
Approach 2 - Iterative
*/
class Solution
{
public:
//Function to reverse a linked list.
struct Node* reverseList(struct Node *head)
{
//Common for both
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
//Aprroach - 1
// struct Node *temp = reverseList(head->next);
// head->next->next = head;
// head->next = NULL;
// return temp;
//Approach - 2
struct Node *p = head->next, *q = head->next;
head->next = NULL;
while(q != NULL) {
q = q->next;
p->next = head;
head = p;
p = q;
}
return head;
}
};
| true |
3cee0b0c78db747eeab29d782760036a4804647a | C++ | Yangjiaxi/leetcode | /0001-0200/0173-binary-search-tree-iterator/main_morris.cpp | UTF-8 | 1,520 | 3.65625 | 4 | [] | no_license | /**
* time: 92ms, 33.90%
* mem: 26.2MB, 6.67%
*
* BUTT WHY ?? :(
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
TreeNode *current;
public:
BSTIterator(TreeNode *root) : current(root) {}
/** @return the next smallest number */
int next() {
int res = 0;
while (1) {
if (!current->left) {
res = current->val;
current = current->right;
return res;
} else {
auto rightmost = current->left;
while (rightmost->right && rightmost->right != current) {
rightmost = rightmost->right;
}
if (!rightmost->right) {
rightmost->right = current;
current = current->left;
} else {
rightmost->right = nullptr; // remove temp link
res = current->val;
current = current->right;
return res;
}
}
}
}
/** @return whether we have a next smallest number */
bool hasNext() { return current; }
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/ | true |
42e0b9a917e2d9155d34bf75b44750d204ebff59 | C++ | FelixOON/DOIT_ESP32_DevKit-v1_30P | /Examples/DigitalOutput/DigitalOutput.ino | UTF-8 | 3,631 | 2.875 | 3 | [] | no_license | /********************************************* ESP32 GPIO OUTPUT PINS *************************************************
The ESP32 chip comes with 48 pins with multiple functions. Not all pins are exposed in all ESP32 development boards,
and there are some pins that cannot be used. ESP32 devkit has 36 pins and 18 on each side of the board. It has 34 GPIO
pins and each pin has multiple functionalities which can be configured using specific registers.
As it said, GPIO’s cannot be used freely, as they are already assigned to module peripherals or have special functions
during booting:
GPIO 0 pin is used as a bootstrapping pin, and should be low to enter UART download mode. Make sure it is not pulled
low by a peripheral device during boot or the firmware will not start!
GPIO 2 pin is used as a bootstrapping pin, and should be low to enter UART download mode. Make sure it is not pulled
high by a peripheral device during boot or you will not be able to flash a firmware to the module!
GPIO 12 is used as a bootstrapping pin to select output voltage of an internal regulator which powers the flash chip (VDD_SDIO).
This pin has an internal pulldown so if left unconnected it will read low at reset (selecting default 3.3V operation).
Make sure it is not pulled high by a peripheral device during boot or the module might not be able to start!
GPIO 15 can be used to stop debug output on Serial during boot. If pulled low there will be no output on the Serial port during
the boot process. This can be helpful in battery powered applications where you do not want to use the Serial port at all
to reduce power consumption.
GPIO 34-39 pins which can be used as digital input pins only. They cannot be configured as digital output pins.
They do not have internally connected push pull resistors. They can only be used as digital input pins:
GPIO 34
GPIO 35
GPIO 36
GPIO 37 and 38 are not available on most boards
GPIO 39
GPIO 6 to GPIO 11 are exposed in some ESP32 development boards. However, these pins are connected to the integrated SPI
flash on the ESP-WROOM-32 chip and are not recommended for other uses. So, don’t use these pins in your projects:
GPIO 6 (SCK/CLK)
GPIO 7 (SDO/SD0)
GPIO 8 (SDI/SD1)
GPIO 9 (SHD/SD2)
GPIO 10 (SWP/SD3)
GPIO 11 (CSC/CMD)
Some GPIOs change its state to HIGH or output PWM signals at boot or reset. This means that if you have outputs
connected to these GPIOs you may get unexpected results when the ESP32 resets or boots:
GPIO 1
GPIO 3
GPIO 5
GPIO 6 to GPIO 11 (connected to the ESP32 integrated SPI flash memory – not recommended to use).
GPIO 14
GPIO 15
*Note:
Connect LED to GPIO subject for testing
***********************************************************************************************************************/
int GPIO_pins[] = {2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33};
int GPIO_count = (sizeof(GPIO_pins) / sizeof(GPIO_pins[0]));
bool GPIOstate = false;
void setup() {
Serial.begin(115200);
for (int thisPin = 0; thisPin < GPIO_count; thisPin++) {
pinMode(GPIO_pins[thisPin], OUTPUT);
}
}
void loop() {
static unsigned long timer = millis();
if (millis() - timer > 1000) {
timer = millis();
GPIOstate = !(GPIOstate);
for (int thisPin = 0; thisPin < GPIO_count; thisPin++) {
Serial.println("GPIO: " + String(GPIO_pins[thisPin]) + " Logic State: " + String(GPIOstate));
digitalWrite(GPIO_pins[thisPin], GPIOstate);
}
}
}
| true |
2bbd34916ad2bf5009b01bf5a596a576ad0e21d2 | C++ | prokarius/hello-world | /C/SumOfTheOthers.cpp | UTF-8 | 406 | 3.328125 | 3 | [] | no_license | #include<iostream>
int sum (int N) {
return (N*(N+1))/2;
}
int main(){
std::ios::sync_with_stdio(false);
int numcases, N, testcase;
std::cin >> numcases;
while (numcases > 0){
std::cin >> testcase >> N;
std::cout << testcase << ' ' << sum(N) << ' ' << sum(N)*2 - N << ' ' << sum(N)*2 << std::endl;
numcases -= 1;
}
return 0;
}
| true |
b24aee8a3ddd5dc3706aa1d018dc12e641668bc7 | C++ | IvanHalim/sort-search | /test.cpp | UTF-8 | 1,640 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include "sort.hpp"
using std::cout;
using std::endl;
using std::srand;
using std::time;
void display(vector<int> vect) {
for (int i = 0; i < vect.size(); i++) {
cout << vect[i] << " ";
}
cout << endl;
}
int main() {
// Initialize the seed for the random number generator
srand(time(0));
// Create an array of size 10 with random numbers between 1 and 10
vector<int> arr;
for (int i = 0; i < 10; i++) {
arr.push_back(rand() % 10 + 1);
}
// Create copies of array arr
vector<int> mergesort(arr.begin(), arr.end());
vector<int> quicksort(arr.begin(), arr.end());
vector<int> heapsort(arr.begin(), arr.end());
// Sort the arrays
sort::mergesort(mergesort, 0, mergesort.size()-1);
sort::quicksort(quicksort, 0, quicksort.size()-1);
sort::heapsort(heapsort, 0, heapsort.size()-1);
// Display the arrays
display(arr);
display(mergesort);
display(quicksort);
display(heapsort);
// Test the binary search function
cout << sort::binary_search(quicksort, 0, arr.size()-1, 7) << endl;
// Test the insert_sorted function
sort::insert_sorted(quicksort, 7);
display(quicksort);
// Test the set_union function
display(sort::set_union(quicksort, mergesort));
// Test the intersection function
display(sort::intersection(quicksort, mergesort));
// Test the symmetric difference function
display(sort::symm_diff(quicksort, mergesort));
// Test the remove function
sort::remove(quicksort, 7);
display(quicksort);
return 0;
} | true |
343dd97cab62265de99f76c72636329f388ce473 | C++ | AkiLotus/AkikazeCP | /Vault/UVa Online Judge/10300.cpp | UTF-8 | 513 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
long long strtoll(string z) {
long long result = 0, sign = 1, i = 0;
if (z[0] == '-') {
i = 1; sign = -1;
}
for (; i<z.size(); i++) {
result *= 10;
result += (z[i] - '0');
}
return result * sign;
}
int main() {
int t; cin >> t;
while (t-- > 0) {
int p; cin >> p;
long long ans = 0;
while (p-- > 0) {
long long x, y, z; cin >> x >> y >> z;
ans += x * z;
}
cout << ans << endl;
}
return 0;
}
| true |
0061e27feadb3719053f851853124247f3701e73 | C++ | wjwzju/pat | /advanced/1012.cpp | UTF-8 | 3,101 | 3.203125 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
const int MAXN = 2000;
struct student{
int id;
int score_c, score_m, score_e;
double score_a;
int rank_a, rank_c, rank_m, rank_e;
int rank, rank_class;
student(){
score_c = -1;
score_e = -1;
score_m = -1;
score_a = -1;
}
}stu[MAXN];
map<int, student> stu2;
bool cmp1(student a, student b) { return a.score_a > b.score_a;}
bool cmp2(student a, student b) { return a.score_c > b.score_c;}
bool cmp3(student a, student b) { return a.score_m > b.score_m;}
bool cmp4(student a, student b) { return a.score_e > b.score_e;}
//寻找最小值
void find_min(student &s){
int min = MAXN + 1;
if(s.rank_e <= min){
s.rank = s.rank_e;
s.rank_class = 3;
min = s.rank_e;
}
if(s.rank_m <= min){
s.rank = s.rank_m;
s.rank_class = 2;
min = s.rank_m;
}
if(s.rank_c <= min){
s.rank = s.rank_c;
s.rank_class = 1;
min = s.rank_c;
}
if(s.rank_a <= min){
s.rank = s.rank_a;
s.rank_class = 0;
}
return;
}
int main(){
int i, m, n;
char c[5] = "ACME";
int s[2000];
scanf("%d %d", &n, &m);
for(i = 0; i < n; i++){
scanf("%d %d %d %d", &stu[i].id, &stu[i].score_c, &stu[i].score_m, &stu[i].score_e);
stu[i].score_a = (stu[i].score_c + stu[i].score_m + stu[i].score_e) / 3;
//printf("%d %d %d %d %lf\n", stu[i].id, stu[i].score_c, stu[i].score_m, stu[i].score_e, stu[i].score_a);
}
for(i = 0; i < m; i++){
scanf("%d", &s[i]);
}
//按平均分排序;
sort(stu, stu + n, cmp1);
stu[0].rank_a = 1;
for(i = 1; i < n; i++){
if(stu[i].score_a == stu[i - 1].score_a) stu[i].rank_a = stu[i - 1].rank_a;
else stu[i].rank_a = i + 1;
}
//按科目c
sort(stu, stu + n, cmp2);
stu[0].rank_c = 1;
for(i = 1; i < n; i++){
if(stu[i].score_c == stu[i - 1].score_c) stu[i].rank_c = stu[i - 1].rank_c;
else stu[i].rank_c = i + 1;
}
//按科目m
sort(stu, stu + n, cmp3); stu[0].rank_m = 1;
for(i = 1; i < n; i++){
if(stu[i].score_m == stu[i - 1].score_m) stu[i].rank_m = stu[i - 1].rank_m;
else stu[i].rank_m = i + 1;
}
//按科目e
sort(stu, stu + n, cmp4);
stu[0].rank_e = 1;
for(i = 1; i < n; i++){
if(stu[i].score_e == stu[i - 1].score_e) stu[i].rank_e = stu[i - 1].rank_e;
else stu[i].rank_e = i + 1;
}
//确定最终排名
for(i = 0; i < n; i++){
stu2[stu[i].id] = stu[i];
find_min(stu2[stu[i].id]);
}
if(stu2[s[0]].score_c != -1){
printf("%d %c", stu2[s[0]].rank, c[stu2[s[0]].rank_class]);
}else{
printf("N/A");
}
for(i = 1; i < m; i++){
if(stu2[s[i]].score_c != -1){
printf("\n%d %c", stu2[s[i]].rank, c[stu2[s[i]].rank_class]);
}else{
printf("\nN/A");
}
}
return 0;
}
//其实map可以只存id与stu索引的对应就可以。 | true |
4287125c4556aeb38982c1752286b3bf7ae7be4e | C++ | Msudyc/LeetCodePartCpp | /LeetCodeTestSolutions/Ex022-MergekSortedLists-Test.cpp | UTF-8 | 3,794 | 3.0625 | 3 | [] | no_license | #include "CppUnitTest.h"
#include "Ex022-MergekSortedLists.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace LeetCodeTestSolutions
{
TEST_CLASS(Ex22Test)
{
public:
TEST_METHOD(Ex022_Test_mergeKLists)
{
Ex22 ex;
vector<ListNode *> t;
ListNode h1(1); ListNode h2(2); ListNode h3(3);
ListNode h4(4); ListNode h5(5); ListNode h6(6);
ListNode h7(7); ListNode h8(8); ListNode h9(9);
h1.next = &h4; h4.next = &h7;
h2.next = &h5; h5.next = &h8;
h3.next = &h6; h6.next = &h9;
t.push_back(&h1);
t.push_back(&h2);
t.push_back(&h3);
ListNode *r = ex.mergeKLists(t);
Assert::AreEqual(1, r->val);
r = r->next;
Assert::AreEqual(2, r->val);
r = r->next;
Assert::AreEqual(3, r->val);
r = r->next;
Assert::AreEqual(4, r->val);
r = r->next;
Assert::AreEqual(5, r->val);
r = r->next;
Assert::AreEqual(6, r->val);
r = r->next;
Assert::AreEqual(7, r->val);
r = r->next;
Assert::AreEqual(8, r->val);
r = r->next;
Assert::AreEqual(9, r->val);
r = r->next;
Assert::IsNull(r);
}
TEST_METHOD(Ex022_Test_mergeKLists1)
{
Ex22 ex;
vector<ListNode *> t;
ListNode h1(1); ListNode h2(2); ListNode h3(3);
ListNode h4(4); ListNode h5(5); ListNode h6(6);
ListNode h7(7); ListNode h8(8); ListNode h9(9);
h1.next = &h4; h4.next = &h7; h7.next = &h8;
h2.next = &h5;
h3.next = &h6; h6.next = &h9;
t.push_back(&h1);
t.push_back(&h2);
t.push_back(&h3);
ListNode *r = ex.mergeKLists(t);
Assert::AreEqual(1, r->val);
r = r->next;
Assert::AreEqual(2, r->val);
r = r->next;
Assert::AreEqual(3, r->val);
r = r->next;
Assert::AreEqual(4, r->val);
r = r->next;
Assert::AreEqual(5, r->val);
r = r->next;
Assert::AreEqual(6, r->val);
r = r->next;
Assert::AreEqual(7, r->val);
r = r->next;
Assert::AreEqual(8, r->val);
r = r->next;
Assert::AreEqual(9, r->val);
r = r->next;
Assert::IsNull(r);
}
TEST_METHOD(Ex022_Test_mergeKLists2)
{
Ex22 ex;
vector<ListNode *> t;
ListNode h1(1); ListNode h2(2); ListNode h3(3);
ListNode h4(4); ListNode h5(5); ListNode h6(6);
ListNode h7(7); ListNode h8(8); ListNode h9(9);
h2.next = &h4; h4.next = &h5; h5.next = &h7; h7.next = &h8;
h3.next = &h6; h6.next = &h9;
t.push_back(&h1);
t.push_back(&h2);
t.push_back(&h3);
ListNode *r = ex.mergeKLists(t);
Assert::AreEqual(1, r->val);
r = r->next;
Assert::AreEqual(2, r->val);
r = r->next;
Assert::AreEqual(3, r->val);
r = r->next;
Assert::AreEqual(4, r->val);
r = r->next;
Assert::AreEqual(5, r->val);
r = r->next;
Assert::AreEqual(6, r->val);
r = r->next;
Assert::AreEqual(7, r->val);
r = r->next;
Assert::AreEqual(8, r->val);
r = r->next;
Assert::AreEqual(9, r->val);
r = r->next;
Assert::IsNull(r);
}
};
} | true |
d978afb77bc3e4b23f78de6227902215dfa4cebc | C++ | UVMCS120BS2020/GF-SC-Project3 | /main.cpp | UTF-8 | 14,797 | 3.421875 | 3 | [] | no_license | // George Fafard and Sean Cosgrove
// Lisa Dion
// CS 120
// Project 3: Battleship
#include <string>
#include <iostream>
#include <optional>
#include <memory>
#include "battleship.h"
#include "destroyer.h"
#include "torpedoes.h"
#include "board.h"
using namespace std;
/********** Global functions declarations **********/
// start game
// Requires: nothing
// Modifies: nothing
// Effects: gets user input for battleship or destroyer battle, calls respective game function
void startGame();
// battleship game
// Requires: nothing
// Modifies: battleship object
// Effects: calls make user battleship and battle functions
void battleshipGame();
// destroyer game
// Requires: nothing
// Modifies: destroyer object
// Effects: calls make user destroyer and destroyer battle function
void destroyerGame();
// make user battleship
// Requires: nothing
// Modifies: creates a new battleship with user input values
// Effects: returns a new battleship
Battleship makeUserBattleship();
// make user destroyer
// Requires: nothing
// Modifies: creates a new destroyer with user input values
// Effects: returns a new destroyer
Destroyer makeUserDestroyer();
// battle
// Requires: two battleships
// Modifies: hitpoints of the battleships
// Effects: fires until one is destroyed (takes turns, battleship one goes first). returns the winner.
Battleship battle(Battleship &pOne, Battleship &pTwo);
// destroyer battle
// Requires: two destroyers
// Modifies: hitpoints of the battleships
// Effects: fires until one is destroyed (takes turns, destroyer one goes first). returns the winner.
Destroyer destroyerBattle(Destroyer &pOne, Destroyer &pTwo);
// MAIN
int main() {
startGame();
return 0;
}
/********** Global function definitions **********/
// startGame function
void startGame() {
// get user input
char choice;
cout << "Battleship or Destroyer battle? (B/D) ";
cin >> choice;
while (tolower(choice) != 'b' && tolower(choice) != 'd') {
cout << "Please enter a 'B' or 'D' ";
cin >> choice;
}
// user wants to fight with destroyers
if (tolower(choice) == 'D') {
destroyerGame(); // call destroyerGame function
// user wants to fight with battleships
} else if (tolower(choice) == 'B') {
battleshipGame(); // call battleshipGame function
} else {
battleshipGame();
}
}
// battleshipGame function
void battleshipGame() {
// initialize variables
Battleship userShip = makeUserBattleship();
Board board = Board();
int userX;
int userY;
int counter = 0;
bool forward;
char choice;
// while loop until game is over
while (userShip.getDestroyed() == false){
// if initial position
if (userShip.getX()) {
// if they want to move on X
choice = 'a';
cout << "Do you want to move on the X axis (y/n)? ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
// move forward?
choice = 'a';
cout << "Do you want to move forward? (y/n) ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
forward = true;
cout << "your new X position is: " << board.moveX(userShip, forward) << endl;
} else if (choice == 'n' || choice != 'N') {
forward = false;
cout << "your new X position is: " << board.moveX(userShip, forward) << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else if (choice == 'n' || choice != 'N') {
cout << "Ok, you did not move." << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else{
cout << "Enter your starting X position between 0 and " << board.getSizeX() << ": ";
cin >> userX;
while (userX > board.getSizeX() || userX < 0){
cout << "Enter a valid X: ";
cin >> userX;
}
userShip.setX(userX);
}
if (userShip.getY()){
// move on Y
choice = 'a';
cout << "Do you want to move on the Y axis (y/n)? ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
// move up?
choice = 'a';
cout << "Do you want to move up? (y/n) ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
forward = true;
cout << "your new Y position is: " << board.moveY(userShip, forward) << endl;
} else if (choice == 'n' || choice != 'N') {
forward = false;
cout << "your new Y position is: " << board.moveY(userShip, forward) << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else if (choice == 'n' || choice != 'N') {
cout << "Ok, you did not move." << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else {
cout << "Enter your starting Y position between 0 and " << board.getSizeY() << ": ";
cin >> userY;
while (userY > board.getSizeY() || userY < 0){
cout << "Enter a valid Y: ";
cin >> userY;
}
userShip.setY(userY);
}
cout << "Battle enemy ship? (Y/N) ";
// battle the enemy
cin >> choice;
if (choice == 'Y' || choice == 'y' ){
// count how many ships
++counter;
unique_ptr<Battleship> computerPtr = make_unique<Battleship>("Computer " + to_string(counter));
// computer position
computerPtr->setX(0);
computerPtr->setY(0);
cout << "Your distance from " << computerPtr->getName() << " is " << board.calcDistance(userShip, *computerPtr) << endl;
// call battle function
battle(userShip, *computerPtr);
} else if(choice == 'n' || choice != 'N') {
cout << "you're a wimp" << endl;
} else {
cout << "thats not a y or an n" << endl;
}
}
cout << "You were destroyed. Game Over." << endl;
}
// destroyerGame function
void destroyerGame() {
// initialize variables
Destroyer userShip = makeUserDestroyer();
Board board = Board();
int userX;
int userY;
int counter = 0;
bool forward;
char choice;
// while loop until game is over
while (userShip.getDestroyed() == false){
// if initial position
if (userShip.getX()) {
// if they want to move on X
choice = 'a';
cout << "Do you want to move on the X axis (y/n)? ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
// move forward?
choice = 'a';
cout << "Do you want to move forward? (y/n) ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
forward = true;
cout << "your new X position is: " << board.moveX(userShip, forward) << endl;
} else if (choice == 'n' || choice != 'N') {
forward = false;
cout << "your new X position is: " << board.moveX(userShip, forward) << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else if (choice == 'n' || choice != 'N') {
cout << "Ok, you did not move." << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else{
cout << "Enter your starting X position between 0 and " << board.getSizeX() << ": ";
cin >> userX;
while (userX > board.getSizeX() || userX < 0){
cout << "Enter a valid X: ";
cin >> userX;
}
userShip.setX(userX);
}
if (userShip.getY()){
// move on Y
choice = 'a';
cout << "Do you want to move on the Y axis (y/n)? ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
// move up?
choice = 'a';
cout << "Do you want to move up? (y/n) ";
cin >> choice;
if (choice == 'Y' || choice == 'y') {
forward = true;
cout << "your new Y position is: " << board.moveY(userShip, forward) << endl;
} else if (choice == 'n' || choice != 'N') {
forward = false;
cout << "your new Y position is: " << board.moveY(userShip, forward) << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else if (choice == 'n' || choice != 'N') {
cout << "Ok, you did not move." << endl;
} else {
cout << "thats not a y or an n" << endl;
}
} else {
cout << "Enter your starting Y position between 0 and " << board.getSizeY() << ": ";
cin >> userY;
while (userY > board.getSizeY() || userY < 0){
cout << "Enter a valid Y: ";
cin >> userY;
}
userShip.setY(userY);
}
cout << "Battle enemy ship? (Y/N) ";
// battle the enemy
cin >> choice;
if (choice == 'Y' || choice == 'y' ){
// count how many ships
++counter;
unique_ptr<Destroyer> computerPtr = make_unique<Destroyer>("Computer " + to_string(counter));
// computer position
computerPtr->setX(0);
computerPtr->setY(0);
cout << "Your distance from " << computerPtr->getName() << " is " << board.calcDistance(userShip, *computerPtr) << endl;
// call destroyerBattle function
destroyerBattle(userShip, *computerPtr);
} else if(choice == 'n' || choice != 'N') {
cout << "you're a wimp" << endl;
} else {
cout << "thats not a y or an n" << endl;
}
}
cout << "You were destroyed. Game Over." << endl;
}
// make user battleship function
Battleship makeUserBattleship() {
string name;
int hitPoints;
int firePower;
int accuracy;
int speed;
cout << "Enter the name of your Battleship: ";
cin >> name;
cout << "Enter the Hitpoints of your Battleship (Integer Between 100-30,000): ";
cin >> hitPoints;
if (hitPoints < 100 || hitPoints > 30000) {
cout << "Invalid hit points, set to default (1,000)" << endl;
hitPoints = 1000;
}
cout << "Enter the Fire Power of your Battleship (Between 50,000-1,000,000): ";
cin >> firePower;
if (firePower < 50000 || firePower > 1000000) {
cout << "Invalid fire power, set to default (50,000)" << endl;
firePower = 50000;
}
cout << "Enter the Accuracy of your Battleship (Between 1-100): ";
cin >> accuracy;
if (accuracy < 0 || accuracy > 100) {
cout << "Invalid pAccuracy, set to default (75)" << endl;
accuracy = 75;
}
cout << "Enter the Speed of your Battleship (Between 1-100): ";
cin >> speed;
if (speed < 0 || speed > 100){
cout << "Invalid pSpeed, set to default (50)" << endl;
speed = 50;
}
// make Battleship a unique pointer and return it to battleshipGame function
unique_ptr<Battleship> userShip = make_unique<Battleship>(name, hitPoints, firePower, accuracy, speed);
return *userShip;
}
// make user destroyer function
Destroyer makeUserDestroyer() {
string name;
int hitPoints;
int firePower;
int accuracy;
int speed;
cout << "Enter the name of your Battleship: ";
cin >> name;
cout << "Enter the Hitpoints of your Battleship (Integer Between 100-30,000): ";
cin >> hitPoints;
if (hitPoints < 100 || hitPoints > 30000) {
cout << "Invalid hit points, set to default (1,000)" << endl;
hitPoints = 1000;
}
cout << "Enter the Fire Power of your Battleship (Between 50,000-1,000,000): ";
cin >> firePower;
if (firePower < 50000 || firePower > 1000000) {
cout << "Invalid fire power, set to default (50,000)" << endl;
firePower = 50000;
}
cout << "Enter the Accuracy of your Battleship (Between 1-100): ";
cin >> accuracy;
if (accuracy < 0 || accuracy > 100) {
cout << "Invalid pAccuracy, set to default (75)" << endl;
accuracy = 75;
}
cout << "Enter the Speed of your Battleship (Between 1-100): ";
cin >> speed;
if (speed < 0 || speed > 100){
cout << "Invalid pSpeed, set to default (50)" << endl;
speed = 50;
}
// make Destroyer a unique pointer and return it to destroyerGame function
unique_ptr<Destroyer> userShip = make_unique<Destroyer>(name, hitPoints, firePower, accuracy, speed);
return *userShip;
}
// battle function
Battleship battle(Battleship &pOne, Battleship &pTwo){
if (pOne.getDestroyed() == false && pTwo.getDestroyed() == false) {
while (pOne.getDestroyed() == false && pTwo.getDestroyed() == false) {
pOne.fire(pTwo);
if (pTwo.getDestroyed() == false) {
pTwo.fire(pOne);
}
}
if (pOne.getDestroyed() == false) {
return pOne;
} else {
return pTwo;
}
} else{
if (pOne.getDestroyed()){
cout << "cannot battle, " << pOne.getName() << " is destroyed" << endl;
return pTwo;
} else{
cout << "cannot battle, " << pTwo.getName() << " is destroyed" << endl;
return pOne;
}
}
}
// destroyerBattle function
Destroyer destroyerBattle(Destroyer &pOne, Destroyer &pTwo){
if (pOne.getDestroyed() == false && pTwo.getDestroyed() == false) {
while (pOne.getDestroyed() == false && pTwo.getDestroyed() == false) {
pOne.fire(pTwo);
if (pTwo.getDestroyed() == false) {
pTwo.fire(pOne);
}
}
if (pOne.getDestroyed() == false) {
return pOne;
} else {
return pTwo;
}
} else{
if (pOne.getDestroyed()){
cout << "cannot battle, " << pOne.getName() << " is destroyed" << endl;
return pTwo;
} else{
cout << "cannot battle, " << pTwo.getName() << " is destroyed" << endl;
return pOne;
}
}
} | true |
c2ceaaf9f63fbeee94648076f4da83ef8bbdba18 | C++ | smartboyathome/something-lang | /IdentTypes/VariableType.cpp | UTF-8 | 4,582 | 3.203125 | 3 | [] | no_license | // VariableType.cpp
#include "VariableType.h"
string VarTypes::ToString(Type type)
{
string StringTypes[] = {
"NIL",
"INTEGER",
"BOOLEAN",
"REAL",
"STRING",
"ARRAY",
"POINTER",
"RECORD"
};
if((int)type >= 0 && (int)type <= 7)
return StringTypes[type];
else
{
stringstream ss;
ss << (int)type;
return ss.str();
}
}
// Constructor
VariableType::VariableType(string name, const VarTypes::Type varType) : MetaType(name, VARIABLE_TYPE) {
this->var_type = varType;
}
VariableType::~VariableType() {}
VarTypes::Type VariableType::GetEnumType() {return var_type;}
// IntegerType ----------------------------------------------------------------
IntegerType::IntegerType(string name) : VariableType(name, VarTypes::INTEGER)
{
value = 0;
}
IntegerType::IntegerType(string name, int value) : VariableType(name, VarTypes::INTEGER)
{
this->value = value;
}
int IntegerType::GetValue() {return value;}
void IntegerType::SetValue(int value) {this->value = value;}
string IntegerType::ToString() const {
stringstream ss;
ss << value;
return ss.str();
}
string IntegerType::CString() const {
return "int";
}
string IntegerType::CString(string var_name) const {
stringstream ss;
ss << "int " << var_name << " = " << value << ";";
return ss.str();
}
// BooleanType ----------------------------------------------------------------
BooleanType::BooleanType() : VariableType("", VarTypes::BOOLEAN) {
value = true; // defaults to true
}
BooleanType::BooleanType(string name) : VariableType(name, VarTypes::BOOLEAN) {
value = true; // defaults to true
}
// String for 'true' and 'false'
BooleanType::BooleanType(string name, string input) : VariableType(name, VarTypes::BOOLEAN) {
SetValue(input);
}
// for 0 and 1 defined boolean values
BooleanType::BooleanType(string name, int input) : VariableType(name, VarTypes::BOOLEAN) {
SetValue(input);
}
bool BooleanType::GetValue() {return value;}
void BooleanType::SetValue(int input) {
if (input == 0)
value = false;
else // Going by C++ standards, anything other than zero equals true
value = true;
}
void BooleanType::SetValue(string input) {
if (input == "false")
value = false;
else // We'll set the value to true with any other string value
value = true;
}
string BooleanType::ToString() const {
stringstream ss;
ss << boolalpha << value;
return ss.str();
}
string BooleanType::CString() const {
return "bool";
}
string BooleanType::CString(string var_name) const {
stringstream ss;
ss << "bool " << var_name << " = " << boolalpha << value << ";";
return "bool ";
}
// RealType -------------------------------------------------------------------
RealType::RealType() : VariableType("", VarTypes::REAL) {
value = 0;
}
RealType::RealType(string name) : VariableType(name, VarTypes::REAL) {
value = 0;
}
RealType::RealType(string name, double value) : VariableType(name, VarTypes::REAL) {
this->value = value;
}
double RealType::GetValue() {return value;}
void RealType::SetValue(double value) {this->value = value;}
string RealType::ToString() const {
stringstream ss;
ss << value;
return ss.str();
}
string RealType::CString() const {
return "double";
}
string RealType::CString(string var_name) const {
stringstream ss;
ss << "double " << var_name << " = " << value << ";";
return ss.str();
}
// StringType -----------------------------------------------------------------
StringType::StringType() : VariableType("", VarTypes::STRING) {
value = "";
}
StringType::StringType(string name) : VariableType(name, VarTypes::STRING) {
value = "";
}
StringType::StringType(string name, string value) : VariableType(name, VarTypes::STRING) {
this->value = value;
}
string StringType::GetValue() {return value;}
void StringType::SetValue(string value) {this->value = value;}
string StringType::ToString() const {
stringstream ss;
ss << "\"" << value << "\"";
return ss.str();
}
string StringType::CString() const {
return "string";
}
string StringType::CString(string var_name) const {
stringstream ss;
ss << "string " << var_name << " = \"" << value << "\";";
return ss.str();
}
| true |
048e462647e626d403868915bf57e7d41ab63093 | C++ | cc-yyyy/C-_STL | /06 vector容器-互换容器.cpp | GB18030 | 1,359 | 3.953125 | 4 | [] | no_license | #include<iostream>
using namespace std;
#include<vector>
//swap(vec); // vec뱾Ԫػ
void printVector6(vector<int> &v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//1ʹ
void test06()
{
vector<int>v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
cout << "ǰ" << endl;
printVector6(v1);
vector<int>v2;
for (int i = 10; i > 0; i--)
{
v2.push_back(i);
}
printVector6(v2);
cout << "" << endl;
v1.swap(v2);
printVector6(v1);
printVector6(v2);
}
//2ʵ; swapڴռ
void test07()
{
vector<int>v;
for (int i = 0; i < 100000; i++)
{
v.push_back(i);
}
cout << "vΪ" << v.capacity() << endl;
cout << "vĴСΪ" << v.size() << endl;
v.resize(3);
cout << "vΪ" << v.capacity() << endl;
cout << "vĴСΪ" << v.size() << endl;
//swapڴ
vector<int>(v).swap(v); //ԭǰִԶ
cout << "vΪ" << v.capacity() << endl;
cout << "vĴСΪ" << v.size() << endl;
}
int main6()
{
//test06();
test07();
system("pause");
return 0;
} | true |
2c15ff8e88cf523211bf2c8ba1ba8a68bd074bb8 | C++ | pearlescen7/code-stash | /djikstra.cpp | UTF-8 | 9,468 | 3.625 | 4 | [] | no_license | /****************************
* Author: Uzay Uysal *
* Student Number: 150180039 *
****************************/
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <sstream>
#include <stack>
#include <climits>
using namespace std;
//////////////////////////////////////////////////////////////////////////////////
//Simple min heap without templates. //
//Uses a vector to cope with dynamic allocation and keep track of the size etc. //
//The indexing that is used with this implementation is as the following //
// //
// PARENT(i/2) //
// // //
// NODE(i) //
// // \\ //
// LCHILD(2*i) RCHILD(2*i+1) //
//////////////////////////////////////////////////////////////////////////////////
struct MinHeap
{
std::vector<pair<string, int> > v;
void insert_key(pair<string, int>);
void update_key(string, int);
void extract_min();
void min_heapify(int index);
bool in_heap(string);
};
//Main function of min heap, min_heapify
//Works in a top-down manner, goes down from the element which it's called
void MinHeap::min_heapify(int index)
{
if(v.size() <= 1) return; //If the size is 1 or smaller there is nothing to fix
int l = 2 * index, r = 2 * index + 1; //Calculate children indexes using the formula above
int smallest = index; //Set the smallest as current index for now
if((size_t)l < v.size() && v[l].second < v[index].second) smallest = l; //Check if left child is smaller
if((size_t)r < v.size() && v[r].second < v[smallest].second) smallest = r; //Check if the right child is smaller
if(smallest != index) //If the current node is bigger than one of its children
{
std::swap(v[smallest], v[index]); //Swap with that child
min_heapify(smallest); //Call heapify for the child to check the heap property
}
}
//Inserts an element to the heap
void MinHeap::insert_key(pair<string, int> val)
{
v.push_back(val); //Add the element to the end
int index = v.size()-1; //Set the index to the last element which is the element that we just added
while(index != 0 && v[index].second < v[index/2].second) //Check if we have to carry the element to the upper nodes
{
std::swap(v[index], v[index/2]); //If we have to, swap with the parent
index /= 2; //Set the new index as parent index, if we reach the root then it is done.
}
}
//Update the node value
void MinHeap::update_key(string node, int val)
{
if(v.size() < 1) return; //Check if there is a key to decrease
int index;
for(size_t i = 0; i < v.size(); i++)
{
if(v[i].first == node)
{
index = i; break;
}
}
v[index].second = val;
while(index != 0 && v[index].second < v[index/2].second) //Do the same checks in the insert_heap function to carry the element to the right place.
{
std::swap(v[index], v[index/2]);
index /= 2;
}
}
//Extract the smallest element from the heap which is always the root
void MinHeap::extract_min()
{
if(v.size() < 1) return; //Check if there is anything to extract
std::swap(v[v.size()-1], v[0]); //Swap the root to the last element
v.erase(v.end()-1); //Delete the last element which is the element we just swapped
min_heapify(0); //Call heapify for the root to fix the heap property
}
bool MinHeap::in_heap(string node)
{
for(size_t i = 0; i < v.size(); i++)
{
if(v[i].first == node) return true;
}
return false;
}
void printMa(string, string, unordered_map<string, string>);
typedef pair<string, pair<string, int> > g_edge;
//typedef pair<unordered_map<string,int>, unordered_map<string, string> > s_dist;
//set<string> vertices;
//bool set_vertices = true;
struct Graph
{
multimap<string, pair<string, int> > adj_list;
void add_edge(string, string, int);
void djikstra_spt(string);
private:
bool check_edge(g_edge);
};
void Graph::add_edge(string n1, string n2, int d)
{
adj_list.insert({ n1, {n2, d}});
adj_list.insert({ n2, {n1, d}});
}
bool Graph::check_edge(g_edge e)
{
if(e.first[0] == 'E') return false;
if(e.second.first[0] == 'E' && e.second.second < 5) return false;
return true;
};
void Graph::djikstra_spt(string src)
{
MinHeap h;
unordered_map<string, int> dist;
unordered_map<string, bool> flag;
unordered_map<string, string> parent;
set<string> seen;
//Find unique nodes
//Set starting node distance as 0 and push to heap, set others as inf.
for(auto it = adj_list.begin(); it != adj_list.end(); it++)
{
if(seen.find(it->first) == seen.end())
{
if(it->first == src)
{
seen.insert(src);
h.insert_key({src, 0});
dist[src] = 0;
flag[src] = false;
parent[src] = "-";
}
else
{
seen.insert(it->first);
dist[it->first] = INT_MAX;
flag[it->first] = false;
parent[it->first] = "-";
}
}
}
/*if(set_vertices)
{
vertices = seen;
set_vertices = false;
}*/
seen.clear();
while(h.v.size() > 0)
{
auto u_node = h.v[0];
string u = u_node.first;
h.extract_min();
flag[u] = true;
bool e_node = false;
auto trange = adj_list.equal_range(u);
for(; trange.first != trange.second; trange.first++)
{
g_edge curr = *trange.first;
if(!check_edge(curr)){ e_node = true; break;}
}
if(!e_node)
{
auto range = adj_list.equal_range(u);
for(; range.first != range.second; range.first++)
{
g_edge curr = *range.first;
int weight = curr.second.second;
string v = curr.second.first;
if(flag[v] == false && (dist[v] > dist[u] + weight))
{
dist[v] = dist[u] + weight;
h.insert_key({v, dist[v]});
parent[v] = u;
}
}
}
}
/*cout << "Distance from " << src << endl;
for(auto it : dist)
{
cout << it.first << ":" << it.second << ":" << parent[it.first] << endl;
}*/
printMa("Ma", "Mo", parent);
cout << dist["Mo"] << endl;
}
void printMa(string dest, string src, unordered_map<string, string> parent)
{
cout << dest << " ";
stack<string> s;
while(src != dest)
{
s.push(src);
src = parent[src];
}
while(!s.empty())
{
cout << s.top() << " ";
s.pop();
}
}
/*void printMo(string dest, string src, unordered_map<string, string> parent)
{
src = parent[src];
while(src != dest)
{
cout << src << " ";
src = parent[src];
}
cout << dest << " ";
}*/
int main(int argc, const char** argv) {
string fname;
cin >> fname;
ifstream city_plan(fname);
Graph g;
string temp;
while(getline(city_plan, temp))
{
stringstream ss(temp);
string n1, n2; int d;
getline(ss, n1, ',');
getline(ss, n2, ',');
ss >> d;
g.add_edge(n1, n2, d);
}
/*for(auto i : g.adj_list)
{
cout << i.first << " " << i.second.first << " " << i.second.second << endl;
}*/
g.djikstra_spt("Ma");
/*unordered_map<string, s_dist> s_path_list;
vector<string> rest_list;
s_path_list["Ma"] = g.djikstra_spt("Ma");
for(auto it : vertices)
{
if(it[0] != 'R') continue;
//s_path_list[it] = g.djikstra_spt(it);
rest_list.push_back(it);
}
s_path_list["Mo"] = g.djikstra_spt("Mo");
long long int best_cost = INT_MAX;
int best_rest = -1;
for(size_t i = 0; i < rest_list.size(); i++)
{
//cout << s_path_list["Ma"].first[rest_list[i]] << " " << s_path_list[rest_list[i]].first["Mo"];
long long int curr_cost = (long long int)s_path_list["Ma"].first[rest_list[i]] + (long long int)s_path_list["Mo"].first[rest_list[i]];
//cout << curr_cost << " " << rest_list[i] << endl;
if(best_cost > curr_cost) { best_cost = curr_cost; best_rest = i; }
}
printMa("Ma", rest_list[best_rest], s_path_list["Ma"].second);
printMo("Mo", rest_list[best_rest], s_path_list["Mo"].second);
cout << best_cost << endl;*/
return 0;
} | true |
0ebbb73552fe5848150075755633f84595a38af7 | C++ | CGCL-codes/FJoin | /src/util/logger.cpp | UTF-8 | 2,416 | 2.671875 | 3 | [
"MIT"
] | permissive | /*
Modified from https://github.com/bmoscon/Logger
*/
/*
* logger.hpp
*
*
* Logger Library Header
*
*
* Copyright (C) 2013-2017 Bryant Moscon - bmoscon@gmail.com
*
* Please see the LICENSE file for the terms and conditions
* associated with this software.
*
*/
#include"../head.hpp"
#ifndef __LOGGER__
#define __LOGGER__
Logger::Logger(const char *f) : _file(f, std::ios::out | std::ios::app),
_log(_file),
_level(VERBOSE),
_line_level(VERBOSE),
_default_line_level(VERBOSE)
{
assert(_file.is_open());
*this << DEBUG <<"Logger Start."<<std::endl;
}
Logger::Logger(const std::string& f) : _file(f.c_str(), std::ios::out | std::ios::app),
_log(_file),
_level(VERBOSE),
_line_level(VERBOSE),
_default_line_level(VERBOSE)
{
assert(_file.is_open());
*this << DEBUG <<"Logger Start."<<std::endl;
}
Logger::~Logger()
{
if (_file.is_open()) {
*this << DEBUG <<"Logger Close."<<std::endl;
_log.flush();
_file.close();
}
}
void Logger::set_level(const logger_level& level)
{
_level = level;
}
void Logger::set_default_line_level(const logger_level& level)
{
_default_line_level = level;
}
void Logger::flush()
{
if (_line_level >= _level) {
_log << get_time() << " -- [" << level_str(_line_level) << "] -- " << str();
_log.flush();
}
str("");
_line_level = _default_line_level;
}
Logger& Logger::operator<<(const logger_level& level)
{
_line_level = level;
return (*this);
}
Logger& Logger::operator<<(LoggerManip m)
{
return m(*this);
}
std::string Logger::get_time() const
{
struct tm *timeinfo;
time_t rawtime;
char *time_buf;
time(&rawtime);
timeinfo = localtime(&rawtime);
time_buf = asctime(timeinfo);
std::string ret(time_buf);
if (!ret.empty() && ret[ret.length() - 1] == '\n') {
ret.erase(ret.length()-1);
}
return (ret);
}
inline const char* Logger::level_str(const logger_level& level)
{
switch (level) {
case VERBOSE:
return ("VRB");
case DEBUG:
return ("DBG");
case INFO:
return ("INF");
case WARNING:
return ("WRN");
case ERROR:
return ("ERR");
case CRITICAL:
return ("CRT");
default:
assert(false);
}
return ("");
}
#endif | true |
19451cd95eef7daa5aa0dd54c86fe6d1cebcbc81 | C++ | crashdemons/BLAKE-wasm | /blake_easy_stub.cpp | UTF-8 | 2,241 | 2.875 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | #include "blake_easy_stub.hpp"
#include <iostream>
/*
void* mallocz(size_t size){
void* p = malloc(size);
memset(p, 0, size);
return p;
}
*/
blake_state_easy* blake_init_easy(unsigned int digestBits){
blake_state_easy* ctx = (blake_state_easy*) malloc(sizeof(blake_state_easy));
ctx->bitlength = digestBits;
switch(ctx->bitlength){
case 224:
ctx->internal_state = malloc(sizeof(state224));
blake224_init((state224*) ctx->internal_state);
break;
case 256:
ctx->internal_state = malloc(sizeof(state256));
blake256_init((state256*) ctx->internal_state);
break;
case 384:
ctx->internal_state = malloc(sizeof(state384));
blake384_init((state384*) ctx->internal_state);
break;
case 512:
default:
ctx->bitlength = 512;//if it wasn't already set to this
ctx->internal_state = malloc(sizeof(state512));
blake512_init((state512*) ctx->internal_state);
break;
}
// std::cout<<"init-easy "<< (ctx) << " " << (ctx->bitlength) << " " << (ctx->internal_state) <<std::endl;
return ctx;
}
void blake_update_easy(blake_state_easy* ctx, const uint8_t *in, uint64_t inlen){
// std::cout<<"update-easy "<< ctx <<" "<< (ctx->bitlength) << " " << in << " " << inlen <<std::endl;
switch(ctx->bitlength){
case 224:
return blake224_update((state224*)ctx->internal_state,in,inlen);
case 256:
return blake256_update((state256*)ctx->internal_state,in,inlen);
case 384:
return blake384_update((state384*)ctx->internal_state,in,inlen);
case 512:
return blake512_update((state512*)ctx->internal_state,in,inlen);
}
}
void blake_final_easy(blake_state_easy* ctx, uint8_t *out){
// std::cout<<"final-easy "<< ctx <<" "<< (ctx->bitlength)<< " " << out <<std::endl;
switch(ctx->bitlength){
case 224:
return blake224_final((state224*)ctx->internal_state,out);
case 256:
return blake256_final((state256*)ctx->internal_state,out);
case 384:
return blake384_final((state384*)ctx->internal_state,out);
case 512:
return blake512_final((state512*)ctx->internal_state,out);
}
}
void blake_cleanup_easy(blake_state_easy* ctx){
// std::cout<<"cleanup-easy "<< ctx <<" "<< (ctx->bitlength) <<std::endl;
free(ctx->internal_state);
free(ctx);
}
int version(){
return 2021030604;
}
| true |
caec15d9ad198734ba8b0b59beaae81eeaead0f0 | C++ | nuharahman9/factory-pattern | /add.hpp | UTF-8 | 365 | 2.734375 | 3 | [] | no_license | #ifndef __ADD_HPP__
#define __ADD_HPP__
#include "base.hpp"
#include "op.hpp"
#include "Operator.hpp"
class Add: public Operator{
public:
Add(Base* left,Base* right ):Operator(left,right){ }
double evaluate() {return value1->evaluate()+value2->evaluate();}
std::string stringify() {return value1->stringify()+" + "+value2->stringify();}
};
#endif
| true |
8f90654ab7641359baa574429e4ef044af15519e | C++ | royertiago/porrinha-wagner | /Zero2.cpp | UTF-8 | 755 | 2.703125 | 3 | [] | no_license | #include "Zero2.h"
#include "core/util.h"
#include "stdlib.h"
namespace wagner {
Zero2::Zero2( std::string name ) :
_name(name)
{}
int Zero2::hand() {
if( rand() % 100 < 5 )
return rand() % core::chopsticks(core::index(this)) + 1;
return 0;
}
int Zero2::guess() {
int half = core::chopstick_count()/2;
int guess = core::chopstick_count()/2;
while( !core::valid_guess(guess) ) {
guess++;
if( guess > core::chopstick_count() ) {
guess = half;
break;
}
}
while( !core::valid_guess(guess) )
guess--;
return guess;
}
std::string Zero2::name() const {
return "zero2";
}
}
| true |
4068d2b9c434191c6b537d36f8066e5b6820d721 | C++ | Ecole-INRA-Test/INRA-Test.cpp | /src/RoadBookCalculator.h | UTF-8 | 1,003 | 2.515625 | 3 | [] | no_license | /*
* File: RoadBook.h
* Author: cjoffro2
*
* Created on 27 novembre 2013, 13:14
*/
#ifndef ROADBOOKCALCULATOR_H
#define ROADBOOKCALCULATOR_H
#include <algorithm>
#include <vector>
#include "Instruction.h"
#include "Error.h"
#include "Direction.h"
#include "RoadBook.h"
#include "MapTools.h"
#include "LandSensor.h"
#include "InstructionListTool.h"
class RoadBookCalculator {
public:
static RoadBook* calculateRoadBook(Direction::Directions direction, Coordinates* position, Coordinates* destination, std::vector<Instruction>* instructions);
static RoadBook* calculateRoadBook(LandSensor* sensor, Direction::Directions direction, Coordinates* position, Coordinates* destination, std::vector<Instruction>* instructions, std::vector<Coordinates*>* trace);
private:
static int lastIndex(std::vector<Instruction>* v, Instruction elem, int pos=-1);
static void eraseElement(std::vector<Direction::Directions>* v, Direction::Directions d);
};
#endif /* ROADBOOKCALCULATOR_H */
| true |
22d7094a88975543d5b448b25ea4895424e2977b | C++ | kirkosyn/C-project | /GeographicArea.cpp | UTF-8 | 808 | 2.984375 | 3 | [] | no_license | #include "GeographicArea.h"
GeographicArea::GeographicArea()
{
#ifdef _DEBUG
std::cout << "GeographicArea class default constructor fired.\n";
#endif // _DEBUG
}
void GeographicArea::setLandform(int i)
{
landform = i;
}
void GeographicArea::setLatitude(int number)
{
latitude = number;
}
void GeographicArea::setLongitude(int number)
{
longitude = number;
}
void GeographicArea::setHemisphere(std::string h)
{
hemisphere = h;
}
std::string GeographicArea::randomHemisphere()
{
srand((unsigned int)time(NULL));
switch (rand() % 4)
{
case 0:
return "NW";
case 1:
return "SW";
case 2:
return "SE";
case 3:
return "NE";
default:
return "undefined";
}
}
GeographicArea::~GeographicArea()
{
#ifdef _DEBUG
std::cout << "GeographicArea class destructor fired.\n";
#endif // _DEBUG
}
| true |
c08472128c604d430ac93b0221967bc0e068020a | C++ | JannLee/c_plus_plus_lab | /kaka22/Study_1/Source.cpp | TIS-620 | 940 | 2.859375 | 3 | [] | no_license | #include <string>
#include <iostream>
int main()
{
std::string input1;
std::string input2;
std::string input3;
std::string input4;
std::string grape("");
std::cin >> input1;
std::cin >> input2;
std::cin >> input3;
std::cin >> input4;
int iInput1 = 0;
int iInput2 = 0;
int iInput3 = 0;
char buf[10] = { 0, };
int exit = 0;
while (buf[0] != '0')
{
std::cin.getline(buf, 2);
if (buf[0] == '1')
iInput1++;
else if (buf[0] == '2')
iInput2++;
else if (buf[0] == '3')
iInput3++;
else
{
exit++;
if (exit == 5)
break;
}
}
std::cout << input2 << ':';
for (int i = 0; i < iInput1; i++)
{
std::cout << grape;
}
std::cout << std::endl;
std::cout << input3 << ':';
for (int i = 0; i < iInput2; i++)
{
std::cout << grape;
}
std::cout << std::endl;
std::cout << input4 << ':';
for (int i = 0; i < iInput3; i++)
{
std::cout << grape;
}
std::cout << std::endl;
return 0;
} | true |
495d1af9f06530c6ad51e5c92f964372ac5174c9 | C++ | dringakn/ROSExamples | /src/example_template.cpp | UTF-8 | 284 | 2.609375 | 3 | [
"MIT"
] | permissive | #include <stdc++.h>
// The base template for the standard (non-array) case, the dimension is 0.
template<typename T>
struct dimof{
static constexpr int value = 0;
};
/*
A partial specialization for type
*/
int main(int argc, char const *argv[])
{
return 0;
}
| true |
2d47e054868ef9907df65a230798219a0e5a5a55 | C++ | Yashika1305/CppPrograms | /palindrome.cpp | UTF-8 | 419 | 3.421875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int num,n,n1,rev=0;
cout<<"Enter the number to check for palindrome";
cin>>num;
n=num;
while(num!=0)
{
n1=num%10;
rev=(rev*10)+n1;
num=num/10;
}
cout<<"Reverse is:"<<rev;
if(n==rev)
cout<<"Number is palindrome";
else
cout<<"Number is not palindrome";
return 0;
} | true |
9faadad953648f3a8d783d83926db319e8547d76 | C++ | emewinchester/RV_Star3D | /estrellaRv/Projects/Project6/Project6/Scene3D.cpp | ISO-8859-1 | 2,229 | 2.640625 | 3 | [] | no_license | #include "stdafx.h"
#include <glew.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Scene3D.h"
#include "ShaderProgram.h"
#include "Figure3D.h"
#include "Ground3D.h"
#include "Star3D.h"
//
// FUNCIN: Scene3D::Scene3D()
//
// PROPSITO: Construye el objeto que representa la escena
//
Scene3D::Scene3D()
{
glm::vec3 Ldir = glm::vec3(1.0f, -0.8f, -1.0f);
Ldir = glm::normalize(Ldir);
light = new Light();
light->SetLightDirection(Ldir);
light->SetAmbientLight(glm::vec3(0.2f, 0.2f, 0.2f));
light->SetDifusseLight(glm::vec3(0.8f, 0.8f, 0.8f));
light->SetSpecularLight(glm::vec3(1.0f, 1.0f, 1.0f));
matg = new Material();
matg->SetAmbientReflect(0.0f, 0.6f, 0.0f);
matg->SetDifusseReflect(0.0f, 0.6f, 0.0f);
matg->SetSpecularReflect(0.8f, 0.8f, 0.8f);
matg->SetShininess(16.0f);
matg->InitTexture("textures/stone.jpg");
GLuint textureId = matg->GetTexture();
ground = new Ground3D(50.0f, 50.0f);
//ground->Rotate(90.0f, glm::vec3(1.0f, 0.0f, 0.0f));
//ground->Translate(glm::vec3(0.0f, -300.0f, -20.0f));
ground->SetMaterial(matg);
matEstrella = new Material();
matEstrella->SetAmbientReflect(0.917f, 0.745f, 0.247f); // afecta al color
matEstrella->SetDifusseReflect(0.917f, 0.745f, 0.247f); //
matEstrella->SetSpecularReflect(0.8f, 0.8f, 0.8f); // el especular no modifica el color
matEstrella->SetShininess(16.0f);
matEstrella->InitTexture("textures/dorado512.jpg");
textureId = matEstrella->GetTexture();
estrella = new Star3D(5, 4.0f, 12.5f, 2.0f);
estrella->SetMaterial(matEstrella);
estrella->Translate(glm::vec3(0.0f, 12.0f, -0.0f));
//estrella->Rotate(90.0f, glm::vec3(0.0f, 1.0f, 0.0f));
}
//
// FUNCIN: Scene3D::~Scene3D()
//
// PROPSITO: Destruye el objeto que representa la escena
//
Scene3D::~Scene3D()
{
delete ground;
delete matg;
delete light;
delete estrella;
delete matEstrella;
}
//
// FUNCIN: Scene3D::Draw()
//
// PROPSITO: Dibuja la escena
//
void Scene3D::Draw(ShaderProgram* program, glm::mat4 proj, glm::mat4 view)
{
light->SetUniforms(program);
ground->Draw(program, proj, view);
estrella->Rotate(2.4f, glm::vec3(0.0f, 1.0f, 0.0f));
estrella->Draw(program, proj, view);
}
| true |
01a3c408131c4420f6cc44215fa5a23d90c32282 | C++ | kbc16b15/game | /GameTemplate/game/Sea.cpp | SHIFT_JIS | 1,353 | 2.59375 | 3 | [] | no_license | #include "stdafx.h"
#include "Sea.h"
Sea::Sea()
{
}
Sea::~Sea()
{
m_modelData.Release();
}
void Sea::Init(const char* modelName, D3DXVECTOR3 pos, D3DXQUATERNION rot)
{
//ǂݍރf̃t@CpX쐬B
char modelPath[256];
sprintf(modelPath, "Assets/modelData/%s.x",modelName);
//f[hB
m_modelData.LoadModelData(modelPath, NULL);
//[hff[^gSkinModelB
m_model.Init(&m_modelData);
//CgB
//m_light.SetAmbientLight(D3DXVECTOR4(0.8f, 0.8f, 0.8f, 1.0f));
m_model.SetLight(&Game::GetInstance().GetLight());
m_position = pos;
m_rotation = rot;
m_model.UpdateWorldMatrix(m_position, m_rotation, { 1.0f, 1.0f, 1.0f });
//L[u}bv̍쐬
/*D3DXCreateCubeTextureFromFile(g_pd3dDevice, "Assets/modelData/skyCubeMap.dds", &m_cubeTex);
if (m_cubeTex != NULL)
{
model.SetcubeMap(m_cubeTex);
}
*/
D3DXCreateTextureFromFileA(g_pd3dDevice,
"Assets/modelData/NormalMap.png",
&m_normalMap);
if (m_normalMap != NULL)
{
m_model.SetnormalMap(m_normalMap);
}
}
void Sea::Update()
{
m_model.UpdateWorldMatrix(m_position, m_rotation, { 1.0f,1.0f,1.0f, });
}
void Sea::Draw()
{
m_model.Draw(&Game::GetInstance().GetCamera()->GetViewMatrix(), &Game::GetInstance().GetCamera()->GetProjectionMatrix());
} | true |
33477e82324991b1aa954980a655e6186e4a6516 | C++ | geewizz246/COMP_NOTES | /C++/Class_Tutorial/Main_BMI.cpp | UTF-8 | 1,095 | 3.078125 | 3 | [] | no_license | //Client File
//Main_BMI.cpp
#include <iostream>
#include <string>
#include<vector>
#include "BMI.h"
using namespace std;
int main() {
vector<BMI> patients;
BMI patient_1{ 0015, "George", 68, 150.4 }; //using overload constructor
BMI patient_2; //using default constructor
BMI patient_3{ 0264, "Conor", 65, 170.45 };
patients.push_back(patient_1);
patients.push_back(patient_3);
int ID;
string name;
int height;
double weight;
cout << "Enter your ID: ";
cin >> ID;
cin.ignore();
patient_2.setID(ID);
cout << "Enter your name: ";
getline(cin,name);
patient_2.setName(name);
cout << "Enter your height (in inches): ";
cin >> height;
patient_2.setHeight(height);
cout << "Enter your weight (in pounds): ";
cin >> weight;
patient_2.setWeight(weight);
patients.push_back(patient_2);
//cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//used to flush the newline character out of the buffer
//useful when using cin or getline for strings when an input comes before
for (int i = 0; i < patients.size(); i++)
patients[i].printInfo();
return 0;
} | true |
0c46da07414875640e089b0fb38239404d3bba93 | C++ | dangbert/raytracer | /seamcarving/code.cpp | UTF-8 | 12,432 | 3.078125 | 3 | [] | no_license | #define cimg_display 0
#include "CImg.h"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <limits>
using namespace cimg_library;
using std::string;
using std::cout;
using std::endl;
/* function prototypes */
int getIndex(int col, int row, int width, int height);
Eigen::Vector3d *removeVerticalSeam(Eigen::Vector3d *image, int width, int height);
Eigen::Vector3d *transposeImage(Eigen::Vector3d *image, int width, int height);
double getEnergy(Eigen::Vector3d *image, int col, int row, int width, int height);
double getDx(Eigen::Vector3d *image, int col, int row, int width, int height);
double getDy(Eigen::Vector3d *image, int col, int row, int width, int height);
void viewEnergy(Eigen::Vector3d *image, int width, int height, char* output_image, int* seam=NULL);
/**
*
* USAGE:
* ./seamcarving <input_image> <output_image> <output_width> <output_height>
*/
int main(int argc, char *argv[]) {
char* input_image = argv[1];
char* output_image = argv[2];
int output_width = atoi(argv[3]);
int output_height = atoi(argv[4]);
CImg<double> input(argv[1]);
CImg<double> lab = input.RGBtoLab();
/* convert input image to LAB color space */
/* one dimensional array of 3D vectors */
Eigen::Vector3d *image = new Eigen::Vector3d[input.width()*input.height()];
for (unsigned int i=0; i<input.width(); i++) {
for (unsigned int j=0; j<input.height(); j++) {
int index = getIndex(i, j, input.width(), input.height());
image[index][0] = lab(i, j, 0);
image[index][1] = lab(i, j, 1);
image[index][2] = lab(i, j, 2);
}
}
/******************************************/
/* display the energy of the original image */
///viewEnergy(image, input.width(), input.height(), output_image);
/* remove vertial seams */
int curWidth = input.width(), curHeight = input.height();
for (; curWidth > output_width; curWidth--) {
image = removeVerticalSeam(image, curWidth, input.height());
}
/* remove horizontal seams */
image = transposeImage(image, curWidth, curHeight);
for (; curHeight > output_height; curHeight--) {
// note that we reverse the params for width, height here (b/c image was tranposed)
image = removeVerticalSeam(image, curHeight, curWidth);
}
image = transposeImage(image, curHeight, curWidth);
/******************************************/
/* output image to file */
CImg<double> output(output_width, output_height, input.depth(), input.spectrum(), 0);
for (unsigned int i=0; i<output.width(); i++) {
for (unsigned int j=0; j<output.height(); j++) {
int index = getIndex(i, j, output_width, output_height);
output(i, j, 0) = image[index][0];
output(i, j, 1) = image[index][1];
output(i, j, 2) = image[index][2];
}
}
CImg<double> rgb = output.LabtoRGB();
if (strstr(output_image, ".png") || strstr(output_image, ".PNG"))
rgb.save_png(output_image);
else if (strstr(output_image, ".jpg") || strstr(output_image, ".JPG"))
rgb.save_jpeg(output_image);
delete [] image;
return 0;
}
/*
* get the corresponding index in a 1-D array for (col, row) in image (width x height)
*/
int getIndex(int col, int row, int width, int height) {
return col * height + row;
}
/*
* removes one vertical seam from @image
* deallocates the memory for @image
* and returns a pointer to a newly allocated image with (width is shrunk by 1)
*
* @image: image of pixel values
* @width: width of @image
* @height: height of @image
*/
Eigen::Vector3d *removeVerticalSeam(Eigen::Vector3d *image, int width, int height) {
/* populate energy matrix (with energy of each pixel) */
double *energy = new double[width * height];
double max = 0.0;
for (unsigned int row=0; row<height; row++) {
for (unsigned int col=0; col<width; col++) {
int index = getIndex(col, row, width, height);
energy[index] = getEnergy(image, col, row, width, height);
max = std::max<double>(max, energy[index]);
}
}
/* compute cumulative minimum energy (cost at each pixel) */
double *M = new double[width * height];
// first row is trivial
for (unsigned int col=0; col<width; col++) {
int index = getIndex(col, 0, width, height);
M[index] = energy[index];
}
// compute M for rest of rows (note that row traversal must be the outer loop)
for (unsigned int row=1; row<height; row++) {
for (unsigned int col=0; col<width; col++) {
int index = getIndex(col, row, width, height);
// compute the cost of the possible connections above (up to three)
double C[3] = {std::numeric_limits<double>::max(),
std::numeric_limits<double>::max(), std::numeric_limits<double>::max()};
if (0 != col)
C[0] = M[getIndex(col-1, row-1, width, height)]; // diagonally up left
C[1] = M[getIndex(col, row-1, width, height)]; // straight up
if (width-1 != col)
C[2] = M[getIndex(col+1, row-1, width, height)]; // diagonally up right
// store the cumulative min energy for this pixel
M[index] = energy[index] + std::min<double>(std::min<double>(C[0], C[1]), C[2]);
}
}
/* find the cheapest connected path (the seam to remove) */
// start from bottom row, find the pixel with min seam cost, and trace
// a path up from there (choosing the min of the 2 to 3 options each time)
int *seam = new int[height]; // stores selected col index for each row of image
int leftCol = 0, rightCol = width-1; // range of columns to search
for (int row=height-1; row>=0; row--) {
seam[row] = leftCol; // column with smallest M value in this row
for (unsigned int col=leftCol; col<=rightCol; col++) {
int index = getIndex(col, row, width, height);
if (M[index] < M[getIndex(seam[row], row, width, height)])
seam[row] = col;
}
// update leftCol and rightCol for next row's search
leftCol = std::max(0, seam[row]-1);
rightCol = std::min(width-1, seam[row]+1);
}
/* return a new image (remove seam from original) */
/* create new image and return it */
std::string fname = std::to_string(width) + ".jpg";
char *outName = &fname[0u];
///viewEnergy(image, width, height, outName, seam); // for debugging
Eigen::Vector3d *newImage = new Eigen::Vector3d[(width-1)*height];
for (unsigned int row=0; row<height; row++) {
double minCost = std::numeric_limits<double>::max();
int offset = 0; // column offset (once seam location in row is passed)
for (unsigned int col=0; col<width-1; col++) {
if (col == seam[row]) {
// we hit the pixel in the seam (use the offset to skip it)
offset++;
}
for (unsigned int k=0; k<3; k++) {
newImage[getIndex(col, row, width, height)][k] = image[getIndex(col+offset, row, width, height)][k];
}
}
}
delete[] image;
delete[] energy;
delete[] M;
delete[] seam;
return newImage;
}
/**
* returns an image that is the transpose of @image
* (deallocates @image and returns a pointer to the new image)
* ///transposes @image in place (works because it's really 1D array)
* ///afterwards treat the new width as @height, and the new height as @width
*
* @image: image of pixel values
* @width: width of @image
* @height: height of @image
*/
Eigen::Vector3d *transposeImage(Eigen::Vector3d *image, int width, int height) {
Eigen::Vector3d *newImage = new Eigen::Vector3d[width * height];
int origIndex, newIndex;
//Eigen::Vector3d tmp;
for (unsigned int row=0; row<height; row++) {
for (unsigned int col=0; col<width; col++) {
origIndex = getIndex(col, row, width, height);
newIndex = getIndex(row, col, height, width);
// swap the 2 pixels
//tmp = image[origIndex];
//image[origIndex] = image[newIndex];
//image[origIndex] = tmp;
newImage[newIndex] = image[origIndex];
}
}
delete[] image;
return newImage;
}
/**
* returns the energy at a specified pixel in an image
*
* @image: image of pixel values
* @col: column index of target pixel
* @row: row index of target pixel
* @width: width of @image
* @height: height of @image
*/
double getEnergy(Eigen::Vector3d *image, int col, int row, int width, int height) {
return getDx(image, col, row, width, height) + getDy(image, col, row, width, height);
}
/**
* get the x-derivatve of the pixel in the image at point (col, row)
* @Image: image in LAB color space
* @col: column index of target pixel
* @row: row index of target pixel
* @width: width of @image
* @height: height of @image
*/
double getDx(Eigen::Vector3d *image, int col, int row, int width, int height) {
/* edge cases */
int divide = 1, index1, index2;
if (0 == col) {
index1 = getIndex(col, row, width, height);
index2 = getIndex(col+1, row, width, height);
}
else if (width-1 == col) {
index1 = getIndex(col-1, row, width, height);
index2 = getIndex(col, row, width, height);
}
else {
index1 = getIndex(col-1, row, width, height);
index2 = getIndex(col+1, row, width, height);
divide = 2.0;
}
// use component 0 because that is the "lightness" value
return abs(image[index2][0] - image[index1][0]) / (double) divide;
}
/**
*
* get the y-derivatve of the pixel in the image at point (col, row)
* @Image: image in LAB color space
* @col: column index of target pixel
* @row: row index of target pixel
* @width: width of @image
* @height: height of @image
*/
double getDy(Eigen::Vector3d *image, int col, int row, int width, int height) {
/* edge cases */
int divide = 1, index1, index2;
if (0 == row) {
index1 = getIndex(col, row, width, height);
index2 = getIndex(col, row+1, width, height);
}
else if (height-1 == row) {
index1 = getIndex(col, row-1, width, height);
index2 = getIndex(col, row, width, height);
}
else {
index1 = getIndex(col, row-1, width, height);
index2 = getIndex(col, row+1, width, height);
divide = 2.0;
}
// use component 0 because that is the "lightness" value
return abs(image[index2][0] - image[index1][0]) / (double) divide;
}
/**
* create an image showing the energy of the pixels in the provided image
* and write it to a file.
* If @seam is not NULL, then the seam will be drawn on the output image in yellow
*
* @image: image of pixel values
* @width: width of @image
* @height: height of @image
* @output_image: name of the file to output ("out-energy-" will be prepended to it)
* @seam: array of length @height (or NULL
*/
void viewEnergy(Eigen::Vector3d *image, int width, int height, char* output_image, int* seam) {
string fname(output_image);
if (seam == NULL)
fname.insert(0, "out-energy-");
else
fname.insert(0, "out-seam-");
/* populate energy matrix */
double *energy = new double[width * height];
double max = 0.0;
for (unsigned int i=0; i<width; i++) {
for (unsigned int j=0; j<height; j++) {
int index = getIndex(i, j, width, height);
energy[index] = getEnergy(image, i, j, width, height);
max = std::max<double>(max, energy[index]);
}
}
/* write to output image */
CImg<float> output(width, height, 1, 3);
for (unsigned int i=0; i<output.width(); i++) {
for (unsigned int j=0; j<output.height(); j++) {
int index = getIndex(i, j, output.width(), output.height());
output(i, j, 0) = 255.0*pow(energy[index]/max, 1/3.0);
output(i, j, 1) = 255.0*pow(energy[index]/max, 1/3.0);
output(i, j, 2) = 255.0*pow(energy[index]/max, 1/3.0);
if (seam != NULL && i == seam[j]) {
output(i, j, 0) = 255.0;
output(i, j, 1) = 255.0;
output(i, j, 2) = 0;
}
}
}
output.save_png(fname.c_str());
delete[] energy;
}
| true |
26b579eb9c69d736d11876cd0d57bf615e3c5dbc | C++ | mverde/Random | /Random/Euler7.cpp | UTF-8 | 448 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void not7main()
{
int primeCount = 0, i = 2;
bool isPrime = true;
while (primeCount < 10001)
{
if ((i - 5) % 10 != 0 || i == 5)
{
for (long long int j = 2; j <= i / 2; j++)
{
if (i%j == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
primeCount++;
}
if (primeCount == 10001)
{
cout << i << endl;
}
isPrime = true;
}
i++;
}
} | true |
794da19dc6c0e84392410dbe93a2156b596045c8 | C++ | enitink/prj | /generic/codes/googleJam/codeChef/Crafts02/simulator/soln.cpp | UTF-8 | 869 | 2.84375 | 3 | [] | no_license | #include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cstring>
#include <cmath>
#ifndef PI
#define PI 3.14159265358979323846
#endif
#define DEG_CIRCLE 360
//#define DEG_TO_RAD (M_PI / (DEG_CIRCLE / 2))
#define RAD_TO_DEG ((DEG_CIRCLE / 2) / M_PI)
/*inline double deg2rad(double degrees)
{
return degrees * DEG_TO_RAD;
}*/
inline double rad2deg(double radians)
{
return radians * RAD_TO_DEG;
}
int main(){
int i, time;
float D, n, cald;
float arr[25][25];
while(true){
cin >> D >> n;
time = -1;
memset(arr, 0, sizeof(arr));
if((D == -1) && (n == -1))
break;
for(i = 0; i < n; ++i){
cin >> a[i][0] >> a[i][1];
}
cald = sqrt((a[0][0] * a[0][0]) - (a[n][0] * a[n][0]) + (a[0][1] * a[0][1]) - (a[n][1] * a[n][1]));
if(cald >= D){
time = D;
}
if(time > 0)
cout << "impossible" << endl;
}
}
| true |
bd4c9e933d18233e054c1375a595904662741673 | C++ | teemusallyla/smart-curtains | /curtain_main/curtain_server.cpp | UTF-8 | 6,470 | 2.6875 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include "Arduino.h"
#include "curtain_server.h"
#include "curtain_led.h"
cServer::cServer(int http_port, cStepper* stpr)
: _led(0), _server(http_port) {
_stepper = stpr;
}
void cServer::begin() {
const char* ssid = "";
const char* password = "";
Serial.print("\n\nConnecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
_led.toggle();
}
Serial.println("\nWiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
_server.begin();
}
void cServer::send200(WiFiClient client, String body) {
client.print("HTTP/1.1 200 OK\r\n");
client.print("Access-Control-Allow-Origin: *\r\n");
client.print("\r\n");
client.println(body);
}
void cServer::send404(WiFiClient client) {
client.print("HTTP/1.1 404 Not Found\r\n");
client.print("Access-Control-Allow-Origin: *\r\n");
client.print("\r\n");
}
void cServer::handle(){
WiFiClient client = _server.available();
if (client) {
if (client.connected()) {
Serial.println("Connected to client");
while (!client.available());
String line = client.readStringUntil('\r');
Serial.println(line);
while (client.available()) client.read();
String path = line.substring(
line.indexOf(' ') + 1,
line.lastIndexOf(' ')
);
String major_path = path, minor_path = "";
if (path.indexOf('/', 1) != -1) {
major_path = path.substring(
0,
path.indexOf('/', 1)
);
minor_path = path.substring(
path.indexOf('/', 1)
);
}
Serial.print("Major path: ");
Serial.println(major_path);
Serial.print("Minor path: ");
Serial.println(minor_path);
if (path.equals("/on")){
_led.turnOn();
send200(client, "LED is on!");
} else if (path.equals("/off")){
_led.turnOff();
send200(client, "LED is off!");
} else if (path.equals("/toggle")){
_led.toggle();
String statusText = _led.status == LOW ? "ON" : "OFF";
String msg = "LED toggled " + statusText;
send200(client, msg);
} else if (major_path.equals("/rotate")) {
float deg = minor_path.substring(1).toFloat();
if (deg != 0) _stepper->rotateDeg(deg, 0.3);
send200(client, "Rotated");
} else if (major_path.equals("/setTarget")) {
int target = minor_path.substring(1).toInt();
target = _stepper->setTargetPos(target);
send200(client, "Targeting " + String(target));
} else if (major_path.equals("/setPercentage")) {
int target = minor_path.substring(1).toInt();
int min = _stepper->_min_pos;
int max = _stepper->_max_pos;
target = (max - min) * target / 100 + min;
target = _stepper->setTargetPos(target);
send200(client, "Targeting " + String(target));
} else if (path.equals("/close")) {
_stepper->_target_pos = _stepper->_max_pos;
send200(client, "Closing the curtains");
} else if (path.equals("/open")) {
_stepper->_target_pos = _stepper->_min_pos;
send200(client, "Opening the curtains");
} else if (path.equals("/stop")) {
int pos = _stepper->_cur_pos;
_stepper->_target_pos = pos;
send200(client, "Stopping the curtains at position " + String(pos));
} else if (major_path.equals("/setMax")) {
int max = minor_path.substring(1).toInt();
_stepper->_max_pos = max;
send200(client, "Setting the maximum position to " + String(max));
} else if (major_path.equals("/setMin")) {
int min = minor_path.substring(1).toInt();
_stepper->_min_pos = min;
send200(client, "Setting the minimum position to " + String(min));
} else if (path.equals("/setThisMax")) {
int max = _stepper->_cur_pos;
_stepper->_max_pos = max;
send200(client, "Setting the maximum position to " + String(max));
} else if (path.equals("/setThisMin")) {
int min = _stepper->_cur_pos;
_stepper->_min_pos = min;
send200(client, "Setting the minimum position to " + String(min));
} else if (major_path.equals("/setSpeed")) {
int spd = minor_path.substring(1).toInt();
spd = _stepper->setSpeed(spd);
send200(client, "Setting the speed to " + String(spd));
} else if (path.equals("/getSpeed")) {
int spd = _stepper->getSpeed();
send200(client, String(spd));
} else if (path.equals("/getPos")) {
int pos = _stepper->_cur_pos;
send200(client, String(pos));
} else if (path.equals("/getMax")) {
int max = _stepper->_max_pos;
send200(client, String(max));
} else if (path.equals("/getMin")) {
int min = _stepper->_min_pos;
send200(client, String(min));
} else if (path.equals("/getAll")) {
String resp = String(_stepper->_cur_pos) + ",";
resp += String(_stepper->_min_pos) + ",";
resp += String(_stepper->_max_pos) + ",";
resp += String(_stepper->getSpeed());
send200(client, resp);
} else if (path.equals("/enable")) {
_stepper->enable();
send200(client, "Stepper enabled");
} else if (path.equals("/disable")) {
_stepper->disable();
send200(client, "Stepper disabled");
} else {
send404(client);
}
Serial.println("Response sent");
}
client.stop();
Serial.println("client stopped");
}
}
| true |
37c7339f164612073b39c29bf1b4d06388cfd908 | C++ | GPUOpen-LibrariesAndSDKs/RadeonProRenderSharedComponents | /OpenVDB/include/openvdb/cmd/openvdb_lod.cc | UTF-8 | 13,254 | 2.640625 | 3 | [
"MPL-2.0",
"MIT",
"LicenseRef-scancode-khronos",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0"
] | permissive | // Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include <openvdb/openvdb.h>
#include <openvdb/tools/MultiResGrid.h>
#include <openvdb/util/CpuTimer.h>
#include <openvdb/util/logging.h>
#include <boost/algorithm/string/classification.hpp> // for boost::is_any_of()
#include <boost/algorithm/string/split.hpp>
#include <cstdlib> // for std::atof()
#include <iomanip> // for std::setprecision()
#include <iostream>
#include <set>
#include <sstream>
#include <stdexcept> // for std::runtime_error
#include <string>
namespace {
const char* gProgName = "";
inline void
usage [[noreturn]] (int exitStatus = EXIT_FAILURE)
{
std::cerr <<
"Usage: " << gProgName << " in.vdb out.vdb -range FROM[-TO[:STEP]] [options]\n" <<
"Which: generates a volume mipmap from an OpenVDB grid\n" <<
"Where:\n" <<
" FROM is the highest-resolution mip level to be generated\n" <<
" TO is the lowest-resolution mip level to be generated (default: FROM)\n" <<
" STEP is the mip level step size (default: 1)\n" <<
"Options:\n" <<
" -name S[,S,S,...] name(s) of the grid(s) to be processed\n" <<
" (default: process all grids of supported types)\n" <<
" -keep pass through grids that were not processed\n" <<
" (default: discard grids that were not processed)\n" <<
" -nokeep cancel an earlier -keep option\n" <<
" -p, -preserve if only one mip level is generated, give it the same\n" <<
" name as the original grid (default: name each level\n" <<
" \"NAME_level_N\", where NAME is the original grid name\n" <<
" and N is the level number, e.g., \"density_level_0\")\n" <<
" -nopreserve cancel an earlier -p or -preserve option\n" <<
" -version print version information\n" <<
"\n" <<
"Mip level 0 is the input grid. Each successive integer level is half\n" <<
"the resolution of the previous level. Fractional levels are supported.\n" <<
"\n" <<
"Examples:\n" <<
" Generate levels 0, 1, and 2 (full resolution, half resolution,\n" <<
" and quarter resolution, respectively) for all grids of supported types\n" <<
" and ignore all other grids:\n" <<
"\n" <<
" " << gProgName << " in.vdb out.vdb -range 0-2\n" <<
"\n" <<
" Generate levels 0, 0.5, and 1 for all grids of supported types\n" <<
" and pass through all other grids:\n" <<
"\n" <<
" " << gProgName << " in.vdb out.vdb -range 0-1:0.5 -keep\n" <<
"\n" <<
" Generate level 3 for the first of multiple grids named \"density\":\n" <<
"\n" <<
" " << gProgName << " in.vdb out.vdb -range 3 -name 'density[0]'\n" <<
"\n" <<
" Generate level 1.5 for the second of multiple unnamed grids and for\n" <<
" the grid named \"velocity\" and give the resulting grids the same names\n"<<
" as the original grids:\n" <<
"\n" <<
" " << gProgName << " in.vdb out.vdb -range 1.5 -name '[1],velocity' -p\n" <<
"\n";
exit(exitStatus);
}
struct Options
{
Options(): from(0.0), to(0.0), step(1.0), keep(false), preserve(false) {}
double from, to, step;
bool keep, preserve;
};
/// @brief Parse a string of the form "from-to:step" and populate the given @a opts
/// with the resulting values.
/// @throw std::runtime_error if parsing fails for any reason
inline void
parseRangeSpec(const std::string& rangeSpec, Options& opts)
{
// Split on the "-" character, of which there should be at most one.
std::vector<std::string> rangeItems;
boost::split(rangeItems, rangeSpec, boost::is_any_of("-"));
if (rangeItems.empty() || rangeItems.size() > 2) throw std::runtime_error("");
// Extract the "from" value, and default "to" to "from" and "step" to 1.
opts.from = opts.to = std::atof(rangeItems[0].c_str());
opts.step = 1.0;
if (rangeItems.size() > 1) {
// Split on the ":" character, of which there should be at most one.
const std::string item = rangeItems[1];
boost::split(rangeItems, item, boost::is_any_of(":"));
if (rangeItems.empty() || rangeItems.size() > 2) throw std::runtime_error("");
// Extract the "to" value.
opts.to = std::atof(rangeItems[0].c_str());
if (rangeItems.size() > 1) {
// Extract the "step" value.
opts.step = std::atof(rangeItems[1].c_str());
}
}
if (opts.from < 0.0 || opts.to < opts.from || opts.step <= 0.0) throw std::runtime_error("");
}
/// @brief Mipmap a single grid of a fully-resolved type.
/// @return a vector of pointers to the member grids of the mipmap
template<typename GridType>
inline openvdb::GridPtrVec
mip(const GridType& inGrid, const Options& opts)
{
OPENVDB_LOG_INFO("processing grid \"" << inGrid.getName() << "\"");
// MultiResGrid requires at least two mipmap levels, starting from level 0.
const int levels = std::max(2, openvdb::math::Ceil(opts.to) + 1);
openvdb::util::CpuTimer timer;
timer.start();
// Initialize the mipmap.
typedef typename GridType::TreeType TreeT;
openvdb::tools::MultiResGrid<TreeT> mrg(levels, inGrid);
openvdb::GridPtrVec outGrids;
for (double level = opts.from; level <= opts.to; level += opts.step) {
// Request a level from the mipmap.
if (openvdb::GridBase::Ptr levelGrid =
mrg.template createGrid</*sampling order=*/1>(static_cast<float>(level)))
{
outGrids.push_back(levelGrid);
}
}
if (outGrids.size() == 1 && opts.preserve) {
// If -preserve is in effect and there is only one output grid,
// give it the same name as the input grid.
outGrids[0]->setName(inGrid.getName());
}
OPENVDB_LOG_INFO("processed grid \"" << inGrid.getName() << "\" in "
<< std::setprecision(3) << timer.seconds() << " sec");
return outGrids;
}
/// @brief Mipmap a single grid and append the resulting grids to @a outGrids.
inline void
process(const openvdb::GridBase::Ptr& baseGrid, openvdb::GridPtrVec& outGrids, const Options& opts)
{
using namespace openvdb;
if (!baseGrid) return;
GridPtrVec mipmap;
if (FloatGrid::Ptr g0 = GridBase::grid<FloatGrid>(baseGrid)) { mipmap = mip(*g0, opts); }
else if (DoubleGrid::Ptr g1 = GridBase::grid<DoubleGrid>(baseGrid)) { mipmap = mip(*g1, opts); }
else if (Vec3SGrid::Ptr g2 = GridBase::grid<Vec3SGrid>(baseGrid)) { mipmap = mip(*g2, opts); }
else if (Vec3DGrid::Ptr g3 = GridBase::grid<Vec3DGrid>(baseGrid)) { mipmap = mip(*g3, opts); }
else if (Vec3IGrid::Ptr g4 = GridBase::grid<Vec3IGrid>(baseGrid)) { mipmap = mip(*g4, opts); }
else if (Int32Grid::Ptr g5 = GridBase::grid<Int32Grid>(baseGrid)) { mipmap = mip(*g5, opts); }
else if (Int64Grid::Ptr g6 = GridBase::grid<Int64Grid>(baseGrid)) { mipmap = mip(*g6, opts); }
else if (BoolGrid::Ptr g7 = GridBase::grid<BoolGrid>(baseGrid)) { mipmap = mip(*g7, opts); }
else if (MaskGrid::Ptr g8 = GridBase::grid<MaskGrid>(baseGrid)) { mipmap = mip(*g8, opts); }
else {
std::string operation = "skipped";
if (opts.keep) {
operation = "passed through";
outGrids.push_back(baseGrid);
};
OPENVDB_LOG_WARN(operation << " grid \"" << baseGrid->getName()
<< "\" of unsupported type " << baseGrid->type());
}
outGrids.insert(outGrids.end(), mipmap.begin(), mipmap.end());
}
} // unnamed namespace
int
main(int argc, char *argv[])
{
OPENVDB_START_THREADSAFE_STATIC_WRITE
gProgName = argv[0];
if (const char* ptr = ::strrchr(gProgName, '/')) gProgName = ptr + 1;
OPENVDB_FINISH_THREADSAFE_STATIC_WRITE
int exitStatus = EXIT_SUCCESS;
if (argc == 1) usage();
openvdb::logging::initialize(argc, argv);
openvdb::initialize();
// Parse command-line arguments.
Options opts;
bool version = false;
std::string inFilename, outFilename, gridNameStr, rangeSpec;
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
if (arg[0] == '-') {
if (arg == "-name") {
if (i + 1 < argc && argv[i + 1]) {
gridNameStr = argv[i + 1];
++i;
} else {
OPENVDB_LOG_FATAL("missing grid name(s) after -name");
usage();
}
} else if (arg == "-keep") {
opts.keep = true;
} else if (arg == "-nokeep") {
opts.keep = false;
} else if (arg == "-p" || arg == "-preserve") {
opts.preserve = true;
} else if (arg == "-nopreserve") {
opts.preserve = false;
} else if (arg == "-range") {
if (i + 1 < argc && argv[i + 1]) {
rangeSpec = argv[i + 1];
++i;
} else {
OPENVDB_LOG_FATAL("missing level range specification after -range");
usage();
}
} else if (arg == "-h" || arg == "-help" || arg == "--help") {
usage(EXIT_SUCCESS);
} else if (arg == "-version" || arg == "--version") {
version = true;
} else {
OPENVDB_LOG_FATAL("\"" << arg << "\" is not a valid option");
usage();
}
} else if (!arg.empty()) {
if (inFilename.empty()) {
inFilename = arg;
} else if (outFilename.empty()) {
outFilename = arg;
} else {
OPENVDB_LOG_FATAL("unrecognized argument \"" << arg << "\"");
usage();
}
}
}
if (version) {
std::cout << "OpenVDB library version: "
<< openvdb::getLibraryAbiVersionString() << "\n";
std::cout << "OpenVDB file format version: "
<< openvdb::OPENVDB_FILE_VERSION << std::endl;
if (outFilename.empty()) return EXIT_SUCCESS;
}
if (inFilename.empty()) {
OPENVDB_LOG_FATAL("missing input OpenVDB filename");
usage();
}
if (outFilename.empty()) {
OPENVDB_LOG_FATAL("missing output OpenVDB filename");
usage();
}
if (rangeSpec.empty()) {
OPENVDB_LOG_FATAL("missing level range specification");
usage();
}
try {
parseRangeSpec(rangeSpec, opts);
} catch (...) {
OPENVDB_LOG_FATAL("invalid level range specification \"" << rangeSpec << "\"");
usage();
}
// If -name was specified, generate a white list of names of grids to be processed.
// Otherwise (if the white list is empty), process all grids of supported types.
std::set<std::string> whitelist;
if (!gridNameStr.empty()) {
boost::split(whitelist, gridNameStr, boost::is_any_of(","));
}
// Process the input file.
try {
openvdb::io::File file(inFilename);
file.open();
const openvdb::MetaMap::ConstPtr fileMetadata = file.getMetadata();
openvdb::GridPtrVec outGrids;
// For each input grid...
for (openvdb::io::File::NameIterator nameIter = file.beginName();
nameIter != file.endName(); ++nameIter)
{
const std::string& name = nameIter.gridName();
// If there is a white list, check if the grid is on the list.
const bool skip = (!whitelist.empty() && (whitelist.find(name) == whitelist.end()));
if (skip && !opts.keep) {
OPENVDB_LOG_INFO("skipped grid \"" << name << "\"");
} else {
// If the grid's name is on the white list or if -keep is in effect, read the grid.
openvdb::GridBase::Ptr baseGrid = file.readGrid(name);
if (!baseGrid) {
OPENVDB_LOG_WARN("failed to read grid \"" << name << "\"");
} else {
if (skip) {
OPENVDB_LOG_INFO("passed through grid \"" << name << "\"");
outGrids.push_back(baseGrid);
} else {
process(baseGrid, outGrids, opts);
}
}
}
}
file.close();
openvdb::util::CpuTimer timer;
timer.start();
openvdb::io::File outFile(outFilename);
if (fileMetadata) {
outFile.write(outGrids, *fileMetadata);
} else {
outFile.write(outGrids);
}
const double msec = timer.milliseconds(); // elapsed time
if (outGrids.empty()) {
OPENVDB_LOG_WARN("wrote empty file " << outFilename << " in "
<< std::setprecision(3) << (msec / 1000.0) << " sec");
} else {
OPENVDB_LOG_INFO("wrote file " << outFilename << " in "
<< std::setprecision(3) << (msec / 1000.0) << " sec");
}
}
catch (const std::exception& e) {
OPENVDB_LOG_FATAL(e.what());
exitStatus = EXIT_FAILURE;
}
catch (...) {
OPENVDB_LOG_FATAL("Exception caught (unexpected type)");
std::unexpected();
}
return exitStatus;
}
| true |
2015bb1f8789501809361220347405f9ac6db5ec | C++ | Dark90lab/university-projects | /Labs_C++/Lab11-Geometry/Polynomial.cpp | UTF-8 | 2,880 | 3.203125 | 3 | [] | no_license | #include "Polynomial.h"
#include <cmath>
//define missing constructor(s)
Polynomial::Polynomial(int _deg , int* _coef)
{
if (_deg > 0 && _coef == nullptr)
{
this->degree = -1;
return;
}
this->degree = _deg;
this->size = degree + 1;
this->init(size, _coef);
}
//Polynomial::~Polynomial()
//{
// this->degree = 0;
//}
ostream& operator<<(ostream& out, const Polynomial& w)
{
//fill missing code
if (w.degree == 0)
out << "Empty polynomial";
else if (w.degree == -1)
{
out << " ";
}
else
{
int k = w.degree;
for (int j = w.size - 1; j >=0;j--,k--)
{
if (j > 0 && k>0)
{
out << showpos << w.tab[j] << "x^" << noshowpos << k;
}
else
{
if(w.tab[j]!=0)
out << showpos << w.tab[j];
}
}
}
return out;
}
Polynomial::Polynomial(const Polynomial& p)
{
//(*this).Array::operator=(p);
this->~Polynomial();
if (p.degree > 0)
this->degree = p.degree;
this->init(p.size, p.tab);
}
Polynomial& Polynomial::operator=(const Polynomial& p)
{
if (this == &p)
return *this;
this->~Polynomial();
if (p.degree > 0)
this->degree = p.degree;
this->init(p.size, p.tab);
return *this;
}
Polynomial& Polynomial::operator*=(int val)
{
if (!tab)
return *this;
for (int i = 0; i < size; i++)
tab[i] *= val;
return *this;
}
Polynomial operator+(const Polynomial&p1, const Polynomial&p2)
{
Polynomial result;
if (p1.size != p2.size)
return result;
result.degree = p1.degree;
result.init(p1.size, p1.tab);
for (int i = 0; i < p1.size; i++)
result.tab[i] += p2.tab[i];
return result;
}
Polynomial operator-(const Polynomial&p1, const Polynomial&p2)
{
if (p2.degree<0)
return p1;
Polynomial result;
if (p1.size != p2.size)
return result;
result.degree = p1.degree;
result.init(p1.size, p1.tab);
for (int i = 0; i < p1.size; i++)
result.tab[i] = result.tab[i]- p2.tab[i];
return result;
}
Polynomial Polynomial::derivtive() const
{
//add missing code
Polynomial tmp=*this;
int count = degree;
for (int i = count; i >=0; i--)
{
tmp.tab[i] *= count;
count--;
}
tmp.degree = this->degree - 1;
return tmp;
}
double Polynomial::operator()(double x) const
{
/*cout << "Degree: " << degree <<" Szie: "<<size<<" ";
for (int i = 0; i < size; i++)
cout << tab[i] << " ";*/
double result = tab[size-1]*x+tab[size-2];
if (degree > 1)
{
for (int i = size - 3; i >= 0; i--)
result = result * x + tab[i];
}
return result;
}
double poly_root(const Polynomial& w, double x, int& it)
{
double eps = 1e-3; // epsilon value
int max_it = 100; // maximum iteration count
for (it = 0; it < max_it; it++) // actual number of iterations
{
//implement Newton's method
Polynomial tmp = w.derivtive();
double prev = x;
x-=(w(x)/tmp(x));
if (abs(x - prev) < eps || abs(tmp(x)) < eps)
return x;
tmp.~Polynomial();
}
cout << "not convergent" << endl;
return x;
}
| true |
a78d6ca6b493d8144ac31428895105b9d3486f70 | C++ | sinsheep/dateStructures | /leetcode/Cpp/lcofer-cha-de-shen-du.cpp | UTF-8 | 789 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// * Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root) return 0;
queue<pair<TreeNode*,int>> q;
int ans = 0;
q.push(make_pair(root,0));
while(!q.empty()){
TreeNode* tmp = q.front().first;
int t = q.front().second;
ans = max(t,ans);
if(tmp->left) q.push(make_pair(tmp->left,t+1));
if(tmp->right) q.push(make_pair(tmp->right,t+1));
q.pop();
}
return ans + 1;
}
};
int main(){
Solution* s = new Solution();
return 0;
}
| true |
22353b5042c91bc0611dbf0656fdda320640d443 | C++ | TailonR/PartC372Final | /Headers/Mazda.h | UTF-8 | 331 | 2.53125 | 3 | [] | no_license | //Tailon Russell
// Created by renew on 4/30/2020.
//
#include "Car.h"
#ifndef UNTITLED1_MAZDA_H
#define UNTITLED1_MAZDA_H
class Mazda: public Car{
public:
Mazda(std::string model, int year);
std::string getModel() override;
int getYear() override;
private:
std::string _model;
int _year;
};
#endif //UNTITLED1_MAZDA_H
| true |
cb7c72236730bac7584e37ea58a0f33271c373aa | C++ | DamirNabiull/ITP_CPP | /UniversityAccessSystem/generator.cpp | UTF-8 | 26,693 | 3.125 | 3 | [] | no_license | //
// Created by dale on 06.03.2021.
//
#include <iostream>
#include <string>
#include <vector>
#include "persons.h"
#include "rooms.h"
#include "generator.h"
using namespace std;
void generator::generate_data(vector<Guest> &guests, vector<Student> &students, vector<LabEmployee> &labs, vector<Professor> &profs, vector<Director> &directors, vector<Admin> &admins, vector<rooms> &rooms_vector){
string Access;
string Room_Name;
string Name_Surname;
string Date;
string Pet;
string cabinet;
Access = "No level";
Room_Name = "Class room";
rooms class_room(Access, Room_Name);
rooms_vector.push_back(class_room);
Access = "Green";
Room_Name = "108 - Lecture room";
rooms lecture_room108(Access, Room_Name);
rooms_vector.push_back(lecture_room108);
Access = "Green";
Room_Name = "107 - Lecture room";
rooms lecture_room107(Access, Room_Name);
rooms_vector.push_back(lecture_room107);
Access = "Yellow";
Room_Name = "111 - Conference room";
rooms conference_room111(Access, Room_Name);
rooms_vector.push_back(conference_room111);
Access = "Yellow";
Room_Name = "211 - Conference room";
rooms conference_room211(Access, Room_Name);
rooms_vector.push_back(conference_room211);
Access = "Special";
Room_Name = "Alexander Tormasov's cabinet";
rooms director_room(Access, Room_Name);
rooms_vector.push_back(director_room);
Access = "Special";
Room_Name = "Robo Lab";
rooms Robo_Lab(Access, Room_Name);
rooms_vector.push_back(Robo_Lab);
Access = "Special";
Room_Name = "GameDev Lab";
rooms GameDev_Lab(Access, Room_Name);
rooms_vector.push_back(GameDev_Lab);
Name_Surname = "Posetitel Guestovich";
Date = "02.09.2002";
Pet = "No pet";
Guest g1(Name_Surname, Date, Pet);
guests.push_back(g1);
Name_Surname = "Damir Nabiullin";
Date = "02.09.2002";
Pet = "No pet";
Student s1(Name_Surname, Date, Pet);
students.push_back(s1);
Name_Surname = "Dinar Shamsutdinov";
Date = "01.08.2002";
Pet = "Dog";
Student s2(Name_Surname, Date, Pet);
students.push_back(s2);
Name_Surname = "Ann Dluzhinskaya";
Date = "22.09.2002";
Pet = "Unicorn";
Student s3(Name_Surname, Date, Pet);
students.push_back(s3);
Name_Surname = "Lev Kozlov";
Date = "23.10.2002";
Pet = "Cat";
Student s4(Name_Surname, Date, Pet);
students.push_back(s4);
Name_Surname = "Alex Strijnev";
Date = "11.05.2002";
Pet = "No pet";
Student s5(Name_Surname, Date, Pet);
students.push_back(s5);
Name_Surname = "Egor Vlasov";
Date = "04.10.2002";
Pet = "Dog";
Student s6(Name_Surname, Date, Pet);
students.push_back(s6);
Name_Surname = "Vadim Makarov";
Date = "05.10.2002";
Pet = "Frog";
Student s7(Name_Surname, Date, Pet);
students.push_back(s7);
Name_Surname = "Renata Shakirova";
Date = "13.11.2002";
Pet = "Lion";
Student s8(Name_Surname, Date, Pet);
students.push_back(s8);
Name_Surname = "Zamira Kholmatova";
Date = "04.10.2000";
Pet = "No pet";
Student s9(Name_Surname, Date, Pet);
students.push_back(s9);
Name_Surname = "Danil Usmanov";
Date = "14.01.2000";
Pet = "Dog";
Student s10(Name_Surname, Date, Pet);
students.push_back(s10);
Name_Surname = "Daler Zakirov";
Date = "17.02.2002";
Pet = "No pet";
Student s11(Name_Surname, Date, Pet);
students.push_back(s11);
Name_Surname = "Ruslan Gilvanov";
Date = "16.12.2002";
Pet = "No pet";
Student s12(Name_Surname, Date, Pet);
students.push_back(s12);
Name_Surname = "Egor Osokin";
Date = "21.10.2000";
Pet = "No pet";
Student s13(Name_Surname, Date, Pet);
students.push_back(s13);
Name_Surname = "Roman Voronov";
Date = "14.01.2002";
Pet = "No pet";
Student s14(Name_Surname, Date, Pet);
students.push_back(s14);
Name_Surname = "Artem Usmanov";
Date = "14.01.2002";
Pet = "No pet";
Student s15(Name_Surname, Date, Pet);
students.push_back(s15);
Name_Surname = "Alina Paukova";
Date = "24.08.2000";
Pet = "No pet";
Student s16(Name_Surname, Date, Pet);
students.push_back(s16);
Name_Surname = "Nikolai Adminovich";
Date = "29.02.2020";
Pet = "Unicorn";
cabinet = "510";
Admin a1(Name_Surname, cabinet, Date, Pet);
admins.push_back(a1);
Access = "Special";
Room_Name = "510";
rooms room_510(Access, Room_Name);
rooms_vector.push_back(room_510);
Name_Surname = "Alexander Adminovich";
Date = "29.02.2020";
Pet = "Unicorn";
cabinet = "511";
Admin a2(Name_Surname, cabinet, Date, Pet);
admins.push_back(a2);
Access = "Special";
Room_Name = "511";
rooms room_511(Access, Room_Name);
rooms_vector.push_back(room_511);
Name_Surname = "Alexander Tormasov";
Date = "12.12.1970";
Pet = "No pet";
cabinet = "Alexander Tormasov's cabinet";
Director d(Name_Surname, cabinet, Date, Pet);
directors.push_back(d);
Name_Surname = "Eugenie Zuev";
Date = "25.10.1973";
Pet = "No pet";
cabinet = "436";
Professor p1(Name_Surname, cabinet, Date, Pet);
profs.push_back(p1);
Access = "Special";
Room_Name = "436";
rooms room_436(Access, Room_Name);
rooms_vector.push_back(room_436);
Name_Surname = "Nikolai Shilov";
Date = "20.10.1973";
Pet = "No pet";
cabinet = "437";
Professor p2(Name_Surname, cabinet, Date, Pet);
profs.push_back(p2);
Access = "Special";
Room_Name = "437";
rooms room_437(Access, Room_Name);
rooms_vector.push_back(room_437);
Name_Surname = "Manuel Mazzara";
Date = "22.05.1985";
Pet = "No pet";
cabinet = "438";
Professor p3(Name_Surname, cabinet, Date, Pet);
profs.push_back(p3);
Access = "Special";
Room_Name = "438";
rooms room_438(Access, Room_Name);
rooms_vector.push_back(room_438);
Name_Surname = "Artem Burmyakov";
Date = "11.07.1989";
Pet = "No pet";
cabinet = "439";
Professor p4(Name_Surname, cabinet, Date, Pet);
profs.push_back(p4);
Access = "Special";
Room_Name = "439";
rooms room_439(Access, Room_Name);
rooms_vector.push_back(room_439);
Name_Surname = "Oleg Bulichev";
Date = "11.07.1989";
Pet = "No pet";
cabinet = "Robo Lab";
LabEmployee l1(Name_Surname, cabinet, Date, Pet);
labs.push_back(l1);
Name_Surname = "Kostya Bulichev";
Date = "13.06.1985";
Pet = "No pet";
cabinet = "Robo Lab";
LabEmployee l2(Name_Surname, cabinet, Date, Pet);
labs.push_back(l2);
Name_Surname = "Roman Voronov";
Date = "14.01.2002";
Pet = "No pet";
cabinet = "Robo Lab";
LabEmployee l3(Name_Surname, cabinet, Date, Pet);
labs.push_back(l3);
Name_Surname = "Artem Voronov";
Date = "14.01.2002";
Pet = "No pet";
cabinet = "Robo Lab";
LabEmployee l4(Name_Surname, cabinet, Date, Pet);
labs.push_back(l4);
Name_Surname = "Ann Kopeikina";
Date = "17.06.2002";
Pet = "No pet";
cabinet = "GameDev Lab";
LabEmployee l5(Name_Surname, cabinet, Date, Pet);
labs.push_back(l5);
Name_Surname = "Danya Kakoito";
Date = "25.12.1996";
Pet = "No pet";
cabinet = "GameDev Lab";
LabEmployee l6(Name_Surname, cabinet, Date, Pet);
labs.push_back(l6);
Name_Surname = "Danila Kochan";
Date = "26.07.1999";
Pet = "No pet";
cabinet = "GameDev Lab";
LabEmployee l7(Name_Surname, cabinet, Date, Pet);
labs.push_back(l7);
Name_Surname = "Artem Horoshiy";
Date = "26.01.2000";
Pet = "No pet";
cabinet = "GameDev Lab";
LabEmployee l8(Name_Surname, cabinet, Date, Pet);
labs.push_back(l8);
}
void generator::print_data(vector<Guest> &guests, vector<Student> &students, vector<LabEmployee> &labs, vector<Professor> &profs, vector<Director> &directors, vector<Admin> &admins, vector<rooms> &rooms_vector) {
cout << "List of rooms: \n ";
for (int i = 0; i < rooms_vector.size(); i++) {
cout << rooms_vector[i].getName();
if (i == rooms_vector.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
cout << "Directors(Amount = " << directors.size() << "):\n ";
for (int i = 0; i < directors.size(); i++) {
cout << directors[i].getName();
if (i == directors.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
cout << "Admins(Amount = " << admins.size() << "):\n ";
for (int i = 0; i < admins.size(); i++) {
cout << admins[i].getName();
if (i == admins.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
cout << "Professors(Amount = " << profs.size() << "):\n ";
for (int i = 0; i < profs.size(); i++) {
cout << profs[i].getName();
if (i == profs.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
cout << "Employees(Amount = " << labs.size() << "):\n ";
for (int i = 0; i < labs.size(); i++) {
cout << labs[i].getName();
if (i == labs.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
cout << "Students(Amount = " << students.size() << "):\n ";
for (int i = 0; i < students.size(); i++) {
cout << students[i].getName();
if (i == students.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
cout << "Guests(Amount = " << guests.size() << "):\n ";
for (int i = 0; i < guests.size(); i++) {
cout << guests[i].getName();
if (i == guests.size() - 1) {
cout << " ";
}
else {
cout << "; ";
}
}
cout << "\n\n";
}
void generator::add_data(string &class_of_person, bool &t, string &Name, string &Surname, string &Name_Surname, string &cabinet, string &Date, string &Pet, std::string &password, string &Access, string &Room_Name, vector<Guest> &guests, vector<Student> &students, vector<LabEmployee> &labs, vector<Professor> &profs, vector<Director> &directors, vector<Admin> &admins, vector<rooms> &rooms_vector) {
if (class_of_person == "Guest") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
cout << "Date: ";
cin >> Date;
cout << "Pet: ";
getline(cin, Pet);
getline(cin, Pet);
Guest g(Name_Surname, Date, Pet);
guests.push_back(g);
cout << class_of_person << " added\n";
}
else if (class_of_person == "Student") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
cout << "Date: ";
cin >> Date;
cout << "Pet: ";
getline(cin, Pet);
getline(cin, Pet);
Student s(Name_Surname, Date, Pet);
students.push_back(s);
cout << class_of_person << " added\n";
}
else if (class_of_person == "Employee") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
cout << "Lab: ";
getline(cin, cabinet);
getline(cin, cabinet);
cout << "Date: ";
cin >> Date;
cout << "Pet: ";
getline(cin, Pet);
getline(cin, Pet);
t = false;
for (auto & i : rooms_vector) {
if (i.getName() == cabinet) {
t = true;
break;
}
}
if (!t) {
cout << "We have not this lab in our university, therefore we can't add this " << class_of_person << "\n";
}
else {
LabEmployee l(Name_Surname, cabinet, Date, Pet);
labs.push_back(l);
cout << class_of_person << " added\n";
}
}
else if (class_of_person == "Professor") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
cout << "Cabinet: ";
getline(cin, cabinet);
getline(cin, cabinet);
cout << "Date: ";
cin >> Date;
cout << "Pet: ";
getline(cin, Pet);
getline(cin, Pet);
t = false;
for (auto & i : rooms_vector) {
if (i.getName() == cabinet) {
t = true;
break;
}
}
if (!t) {
Access = "Special";
Room_Name = cabinet;
rooms room(Access, Room_Name);
rooms_vector.push_back(room);
}
Professor p(Name_Surname, cabinet, Date, Pet);
profs.push_back(p);
cout << class_of_person << " added\n";
}
else if (class_of_person == "Admin") {
cout << "Password: ";
cin >> password;
if (password == "9876") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
cout << "Cabinet: ";
getline(cin, cabinet);
getline(cin, cabinet);
cout << "Date: ";
cin >> Date;
cout << "Pet: ";
getline(cin, Pet);
getline(cin, Pet);
t = false;
for (auto & i : rooms_vector) {
if (i.getName() == cabinet) {
t = true;
break;
}
}
if (!t) {
Access = "Special";
Room_Name = cabinet;
rooms room(Access, Room_Name);
rooms_vector.push_back(room);
}
Admin a(Name_Surname, cabinet, Date, Pet);
admins.push_back(a);
cout << class_of_person << " added\n";
}
else {
cout << "Incorrect password, therefore we can't add this " << class_of_person << "\n";
}
}
else if (class_of_person == "Director") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
cout << "Cabinet: ";
getline(cin, cabinet);
getline(cin, cabinet);
cout << "Date: ";
cin >> Date;
cout << "Pet: ";
getline(cin, Pet);
getline(cin, Pet);
t = false;
for (auto & i : rooms_vector) {
if (i.getName() == cabinet) {
t = true;
break;
}
}
if (!t) {
Access = "Special";
Room_Name = cabinet;
rooms room(Access, Room_Name);
rooms_vector.push_back(room);
}
Director d(Name_Surname, cabinet, Date, Pet);
directors.push_back(d);
cout << class_of_person << " added\n";
}
else {
cout << "Incorrect class, try again\n";
}
}
void generator::info_data(string &class_of_person, bool &t, string &Name, string &Surname, string &Name_Surname, vector<Guest> &guests, vector<Student> &students, vector<LabEmployee> &labs, vector<Professor> &profs, vector<Director> &directors, vector<Admin> &admins, vector<rooms> &rooms_vector) {
if (class_of_person == "Guest") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : guests) {
if (i.getName() == Name_Surname) {
cout << "Access level: " << i.getAccess() << "\n";
cout << "Date: " << i.getDate() << "\n";
cout << "Pet: " << i.getPet() << "\n";
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Student") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : students) {
if (i.getName() == Name_Surname) {
cout << "Access level: " << i.getAccess() << "\n";
cout << "Date: " << i.getDate() << "\n";
cout << "Pet: " << i.getPet() << "\n";
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Employee") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : labs) {
if (i.getName() == Name_Surname) {
cout << "Access level: " << i.getAccess() << "\n";
cout << "Lab: " << i.getCabinet() << "\n";
cout << "Date: " << i.getDate() << "\n";
cout << "Pet: " << i.getPet() << "\n";
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Professor") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : profs) {
if (i.getName() == Name_Surname) {
cout << "Access level: " << i.getAccess() << "\n";
cout << "Cabinet: " << i.getCabinet() << "\n";
cout << "Date: " << i.getDate() << "\n";
cout << "Pet: " << i.getPet() << "\n";
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Admin") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : admins) {
if (i.getName() == Name_Surname) {
cout << "Access level: " << i.getAccess() << "\n";
cout << "Cabinet: " << i.getCabinet() << "\n";
cout << "Date: " << i.getDate() << "\n";
cout << "Pet: " << i.getPet() << "\n";
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Director") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : directors) {
if (i.getName() == Name_Surname) {
cout << "Access level: " << i.getAccess() << "\n";
cout << "Cabinet: " << i.getCabinet() << "\n";
cout << "Date: " << i.getDate() << "\n";
cout << "Pet: " << i.getPet() << "\n";
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else {
cout << "Incorrect class, try again\n";
}
}
void generator::change_data(string &class_of_person, bool &t, string &Name, string &Surname, string &Name_Surname, string &password, string &Access, vector<Guest> &guests, vector<Student> &students, vector<LabEmployee> &labs, vector<Professor> &profs, vector<Director> &directors, vector<Admin> &admins, vector<rooms> &rooms_vector) {
cout << "Password: ";
cin >> password;
if (password == "9876") {
if (class_of_person == "Guest") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : guests) {
if (i.getName() == Name_Surname) {
admins[0].changeAccess(i, Access);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Student") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : students) {
if (i.getName() == Name_Surname) {
admins[0].changeAccess(i, Access);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Employee") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : labs) {
if (i.getName() == Name_Surname) {
admins[0].changeAccess(i, Access);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Professor") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : profs) {
if (i.getName() == Name_Surname) {
admins[0].changeAccess(i, Access);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Admin") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : admins) {
if (i.getName() == Name_Surname) {
admins[0].changeAccess(i, Access);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Director") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : directors) {
if (i.getName() == Name_Surname) {
admins[0].changeAccess(i, Access);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else {
cout << "Incorrect class, try again\n";
}
}
else {
cout << "Incorrect password, therefore we can't change access level\n";
}
}
void generator::add_room_data(string &class_of_person, bool &t, string &Name, string &Surname, string &Name_Surname, string &password, rooms &room, vector<Guest> &guests, vector<Student> &students, vector<LabEmployee> &labs, vector<Professor> &profs, vector<Director> &directors, vector<Admin> &admins, vector<rooms> &rooms_vector) {
cout << "Password: ";
cin >> password;
if (password == "9876") {
if (class_of_person == "Guest") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : guests) {
if (i.getName() == Name_Surname) {
admins[0].giveAccesToRoom(i, room);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Student") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : students) {
if (i.getName() == Name_Surname) {
admins[0].giveAccesToRoom(i, room);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Employee") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : labs) {
if (i.getName() == Name_Surname) {
admins[0].giveAccesToRoom(i, room);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Professor") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : profs) {
if (i.getName() == Name_Surname) {
admins[0].giveAccesToRoom(i, room);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Admin") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : admins) {
if (i.getName() == Name_Surname) {
admins[0].giveAccesToRoom(i, room);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else if (class_of_person == "Director") {
cout << "Name and Surname: ";
cin >> Name >> Surname;
Name_Surname = Name + " " + Surname;
t = true;
for (auto &i : directors) {
if (i.getName() == Name_Surname) {
admins[0].giveAccesToRoom(i, room);
t = false;
break;
}
}
if (t) {
cout << "No person with this name\n";
}
}
else {
cout << "Incorrect class, try again\n";
}
}
else {
cout << "Incorrect password, therefore we can't change access level\n";
}
}
| true |
8109fea1c3bb892b7934bd8417abf65747a40053 | C++ | PHANTOM0122/Learning_OpenCV | /Class/Mat/MatOp4.cpp | UTF-8 | 520 | 2.90625 | 3 | [] | no_license | #include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main() {
Mat mat1 = Mat::zeros(3, 4, CV_8UC1);
// op1
for (int j = 0; j < mat1.rows; j++) {
for (int i = 0; i < mat1.cols; i++)
mat1.at<uchar>(j,i)++;
}
// op2
for (int j = 0; j < mat1.rows; j++) {
uchar* p = mat1.ptr<uchar>(j);
for (int i = 0; i < mat1.cols; i++)
p[i]++;
}
// op3
for (MatIterator_<uchar>it = mat1.begin<uchar>(); it != mat1.end<uchar>(); ++it) {
(*it)++;
}
cout << "mat1 : \n" << mat1 << endl;
} | true |
accb186de011968a31b527b9bb33742ef7cab7c2 | C++ | ahwxz123/ITKLearning | /Demo1_itkImageReader/ITKImageReader.cpp | UTF-8 | 1,352 | 2.703125 | 3 | [] | no_license | #include <itkImage.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
int main(int argc, char* argv[])
{
const unsigned int Dimension = 2; //定义图像维数
//typedef unsigned char PixelType; //定义像素类型
typedef itk::RGBPixel< unsigned char > PixelType; // RGBPixel相当于是类模板的继承,这里的PiexlType相当于是一种数据类型
typedef itk::Image< PixelType, 2 > ImageType; // 定义一个图像类型
typedef itk::ImageFileReader< ImageType > ReaderType; // 定义一个读取类型
typedef itk::ImageFileWriter< ImageType > WriterType; // 定义一个写入图像类型
ReaderType::Pointer reader = ReaderType::New(); // 创建一个文件读指针
WriterType::Pointer writer = WriterType::New(); // 创建一个文件写指针
reader->SetFileName("E:\\XC\\itk\\Examples\\Demo1_itkImageReader\\bin\\hua.jpg"); // 文件读路径
writer->SetFileName( "E:\\XC\\itk\\Examples\\Demo1_itkImageReader\\bin\\hua2.jpg"); // 文件写路径
ImageType::Pointer image = reader->GetOutput(); // 将数据读取进来
writer->SetInput( image ); // 写入读取的对象
writer->Update(); // Aliased to the Write() method to be consistent with the rest of the pipeline.
return 0;
} | true |
8af72db5d9450e71808e55d522acd092638fcad3 | C++ | looooj/testxx | /common/mgserver.cpp | UTF-8 | 2,179 | 2.703125 | 3 | [] | no_license | #include <string.h>
#include "mgserver.h"
void* MgServerThread(void* arg)
{
if ( arg )
{
((MgServer*)arg)->loop();
}
}
int MgServerHandler(struct mg_connection* conn, enum mg_event evt)
{
if ( conn->server_param )
{
return ((MgServer*)conn->server_param)->handler( conn, evt );
}
return MG_FALSE;
}
MgServer::MgServer()
{
mMainThread = 0;
mPort = 8080;
mStopFlag = 0;
strcpy( mBindIp, "0.0.0.0" );
}
MgServer::~MgServer()
{
}
int MgServer::getPort()
{
return mPort;
}
void MgServer::setPort(int port)
{
mPort = port;
}
void MgServer::setBindIp(const char* ip)
{
strcpy( mBindIp, ip );
}
void MgServer::loop()
{
while(1)
{
if ( mStopFlag )
break;
mg_poll_server(mServer, 1000);
Sleep(1);
}
mg_destroy_server(&mServer);
mServer = 0;
}
bool MgServer::start()
{
mStopFlag = 0;
struct mg_server *server = mg_create_server(this, MgServerHandler);
mg_set_option(server, "document_root", ".");
char tmp_port[16];
sprintf( tmp_port, "%s:%d", mBindIp, mPort );
const char* result = mg_set_option(server, "listening_port", tmp_port );
if ( result != NULL )
return false;
mServer = server;
pthread_create( &mMainThread, NULL, MgServerThread, this );
return true;
}
void MgServer::stop()
{
mStopFlag = 1;
pthread_join( mMainThread, NULL );
}
void MgServer::setStop()
{
mStopFlag = 1;
}
bool MgServer::isStop()
{
//if ( !mMainThread )
// return !mMainThread->IsRun();
return false;
}
int MgServer::handler(struct mg_connection* conn, enum mg_event evt)
{
if (evt == MG_AUTH)
{
return MG_TRUE;
}
else
if (evt == MG_REQUEST )
{
doRequest(conn);
//mg_printf_data(conn, "%s", "Hello");
return MG_TRUE;
}
else
{
return MG_FALSE; // Rest of the events are not processed
}
}
void MgServer::doRequest(struct mg_connection* conn)
{
if ( mRequestHandler )
mRequestHandler(conn);
}
//---------------------------------------------------------------------------
| true |
e8c5c60dc6d6fd8de6e8f0ecdea4adbd48301aa6 | C++ | OmriMan/ZoomSys-Rooms-and-students | /Student.cpp | UTF-8 | 1,379 | 3.25 | 3 | [] | no_license | /*
* Student.cpp
*
* Created on: Jan 2, 2021
* Author: ise
*/
#include "Student.h"
Student::Student(string first , string last , int id , int avg):m_first_name(first),m_last_name(last)
{
if (id < 0 || avg < 0 || avg > 100)
{
throw Invalid_details();
}
m_id = id;
m_avg = avg;
m_curr_room = nullptr;
m_room_id = -1;
}
ostream& operator<<(ostream& out, const Student& other)
{
out << other.m_first_name << " " << other.m_last_name << " " << other.m_id << " " << other.m_avg << " " << other.m_room_id<< endl;
/* if (other.m_msg.size()>0)
{
out << "---Messages---"<< endl;
for (int i = 0 ; i < (int)other.m_msg.size();i++)
{
out << other.m_first_name << " " << other.m_last_name << ":" << other.m_msg[i] << endl;
}
}*/
return out;
}
Student* Student::operator=(const Student& other)
{
m_first_name=other.m_first_name;
m_last_name=other.m_last_name;
m_id = other.m_id;
m_avg = other.m_avg;
m_curr_room = other.m_curr_room;
m_room_id = other.m_room_id;
m_msg=other.m_msg;
return this;
}
void Student::MoveRoom(Room* to_room)
{
m_room_id = to_room->GetID();
m_curr_room = to_room;
}
void Student::removeRoom()
{
m_room_id = -1;
m_curr_room = nullptr;
}
Student::~Student()
{
m_msg.clear();
m_msg.shrink_to_fit();
m_first_name.clear();
m_last_name.clear();
}
void Student::Get_Msg_Str(string m)
{
m_msg.push_back(m);
}
| true |
548d1419c7269f26c17ab26d72f9633759ce8060 | C++ | ktran050/Portfolio | /plusplus/csCourseWork/cs12_labs/lab09/main.cpp | UTF-8 | 1,399 | 2.875 | 3 | [] | no_license | // =============== BEGIN ASSESSMENT HEADER ================
/// @file main.cpp
/// @brief Lab 9 for CS 12 Winter 2015
///
/// @author Kevin Tran [ktran050@ucr.edu]
/// @date March 2nd, 2015
///
/// @par Enrollment Notes
/// Lecture Section: 002
/// @par
/// Lab Section: 023
/// @par
/// TA: Brian
///
/// @par Plagiarism Section
/// I hereby certify that the code in this file
/// is ENTIRELY my own original work.
// ================== END ASSESSMENT HEADER ===============
// Implement functions given in Prompt.txt
/// Create necessary files
/// Copy class and class member declarations
/// Write Tune class
/// Write Constructors/Deconstructor for MuCol
/// Write the other functions
/// Brainstorm edge cases
/// Test for edge cases
/// Fix cases
#include <iostream>
#include "Music_collection.h"
using namespace std;
void somefunction(Music_collection p){
Tune aa("wowee");
p.add_tune(aa);
}
int main(){
Tune qq;
Tune aa("wowee");
Tune bb("Test");
Music_collection cc;
cc.add_tune(aa);
cout << cc;
cout << "-------------------------" << endl;
Music_collection dd(4);
dd.add_tune(bb);
dd.add_tune(bb);
dd.add_tune(bb);
dd.add_tune(bb);
cout << dd;
cout << "-------------------------" << endl;
cc.set_tune(0, bb);
cout << cc;
cout << "-------------------------" << endl;
return 0;
} | true |
a8f4c167b97ed4541d5fec8adbdac3998b3ed2ac | C++ | dgpalmieri/Flow | /flow_main.cpp | UTF-8 | 3,172 | 3.34375 | 3 | [] | no_license | // flow_main.cpp
// Dylan Palmieri
// 2020-12-12
// Test Suite for flow module
#include"flow.hpp"
#include<iostream>
using std::cout;
using std::endl;
int main() {
Flow test;
test.hello();
{ // test case with example from
// https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/
// ( Also from the class final lol )
// The format for the graph input is:
// index = node number
// pair.first = node the edge connectes to
// pair.second = edge weight
Flow gfg_test( {
{ { 1, 16 }, { 2, 13 } }, // We have an edge 0->1 with weight 16, etc.
{ { 2, 10 }, { 3, 12 } },
{ { 1, 4 }, { 4, 14 } },
{ { 2, 9 }, { 5, 20 } },
{ { 3, 7 }, { 5, 4 } },
{ }
} );
gfg_test.calculate();
int tFlow = gfg_test.getMaxFlow();
cout << "Test Case: graph from GeeksForGeeks example" << endl;
gfg_test.printGraph();
if ( tFlow != 23 ){
cout << " TEST FAILED" << endl;
cout << " Max Flow value calculated: " << tFlow << endl;
cout << " Expected value: 23" << endl;
}
else
cout << " Test Passed!" << endl;
} // end test case
{ // test case
// example from https://www.geeksforgeeks.org/max-flow-problem-introduction/
Flow basic_backwards_test( {
{ { 1, 3 }, { 2, 2 } },
{ { 2, 5 }, { 3, 2 } },
{ { 3, 3 } },
{ }
} );
basic_backwards_test.calculate();
int tFlow = basic_backwards_test.getMaxFlow();
cout << "Test Case: graph from Geeks For Geeks small example" << endl;
basic_backwards_test.printGraph();
if ( tFlow != 5 ){
cout << " TEST FAILED" << endl;
cout << " Max Flow value calculated: " << tFlow << endl;
cout << " Expected value: 6" << endl;
}
else
cout << " Test Passed!" << endl;
} // end test case
{ // test case
// From the course textbook, Introduction to the Design and Analysis of
// Algorithms, Levitin
// Figure 10.7, page 368
// NOTE: all node values are decreased by one, because in the book, the
// source is labeled as one, and here it is zero
Flow textbook_test( {
{ { 1, 2 }, { 3, 3 } },
{ { 4, 3 }, { 2, 5 } },
{ { 5, 2 } },
{ { 2, 1 } },
{ { 5, 4 } },
{ }
} );
textbook_test.calculate();
int tFlow = textbook_test.getMaxFlow();
cout << "Test Case: graph from textbook example" << endl;
textbook_test.printGraph();
if ( tFlow != 3 ){
cout << " TEST FAILED" << endl;
cout << " Max Flow value calculated: " << tFlow << endl;
cout << " Expected value: 6" << endl;
}
else
cout << " Test Passed!" << endl;
}
return 0;
}
| true |
b876aeff7cc50498b377dfb57c1b52ae10fbf58a | C++ | xgraph/XGLCD | /LittleVGL_examples/lv_test_tileview/lv_test_tileview.ino | UTF-8 | 4,032 | 2.59375 | 3 | [] | no_license | /**
* Create a tileview to test their functionalities
*/
#include "lv_xg.h"
#include "lvgl.h"
void setup() {
Serial.begin(38400); // Debugging info via Arduino Terminal = Serial debugging port
lv_xg_init(); // Init X-Graph LCD, LittleVGL library and the LittleVGL to X-Graph driver
static const lv_point_t vp[] = {
{1,0}, /*First row: only the middle tile*/
{0,1}, {1,1}, {1,2}, /*Second row: all tree tiles */
{2,1}, {2,2}, /*Third row: middle and right tile*/
{LV_COORD_MIN, LV_COORD_MIN}};
lv_obj_t * t;
t = lv_tileview_create(lv_scr_act(), NULL);
lv_tileview_set_valid_positions(t, vp);
lv_tileview_set_edge_flash(t, true);
lv_obj_t * label;
/*x0, y1 container*/
lv_obj_t * p01 = lv_obj_create(t, NULL);
lv_obj_set_click(p01, true);
lv_obj_set_style(p01, &lv_style_pretty_color);
lv_obj_set_size(p01, lv_obj_get_width(t), lv_obj_get_height(t));
lv_tileview_add_element(p01);
/*Add a button at x0, y1*/
lv_obj_t * b01 = lv_btn_create(p01, NULL);
lv_tileview_add_element(b01);
lv_obj_align(b01, NULL, LV_ALIGN_CENTER, 0, 50);
label = lv_label_create(b01, NULL);
lv_label_set_text(label, "Button");
/*Add a label to indicate the position*/
label = lv_label_create(p01, NULL);
lv_label_set_text(label, "x0, y1");
lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
/*x1, y1 container*/
lv_obj_t * p11 = lv_obj_create(t, p01);
lv_obj_align(p11, p01, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
lv_tileview_add_element(p11);
/*Add a label to indicate the position*/
label = lv_label_create(p11, NULL);
lv_label_set_text(label, "x1, y1");
lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
/*x1, y2 list*/
lv_obj_t * list12 = lv_list_create(t, NULL);
lv_obj_set_size(list12, LV_HOR_RES, LV_VER_RES);
lv_obj_align(list12, p11, LV_ALIGN_OUT_BOTTOM_MID, 0, 0);
lv_list_set_scroll_propagation(list12, true);
lv_tileview_add_element(list12);
lv_obj_t * list_btn;
list_btn = lv_list_add(list12, NULL, "One", NULL);
lv_tileview_add_element(list_btn);
list_btn = lv_list_add(list12, NULL, "Two", NULL);
lv_tileview_add_element(list_btn);
list_btn = lv_list_add(list12, NULL, "Three", NULL);
lv_tileview_add_element(list_btn);
list_btn = lv_list_add(list12, NULL, "Four", NULL);
lv_tileview_add_element(list_btn);
list_btn = lv_list_add(list12, NULL, "Five", NULL);
lv_tileview_add_element(list_btn);
list_btn = lv_list_add(list12, NULL, "Six", NULL);
lv_tileview_add_element(list_btn);
list_btn = lv_list_add(list12, NULL, "Seven", NULL);
lv_tileview_add_element(list_btn);
/*x1, y0 container*/
lv_obj_t * p10 = lv_obj_create(t, p01);
lv_tileview_add_element(p10);
/*Add a label to indicate the position*/
label = lv_label_create(p10, NULL);
lv_label_set_text(label, "x1, y0");
lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
lv_obj_align(p10, p11, LV_ALIGN_OUT_TOP_MID, 0, 0);
/*x2, y1 container*/
lv_obj_t * p21 = lv_obj_create(t, p01);
lv_tileview_add_element(p21);
lv_obj_align(p21, p11, LV_ALIGN_OUT_RIGHT_MID, 0, 0);
/*Add a label to indicate the position*/
label = lv_label_create(p21, NULL);
lv_label_set_text(label, "x2, y1");
lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
/*x2, y1 container*/
lv_obj_t * p22 = lv_obj_create(t, p01);
lv_tileview_add_element(p22);
lv_obj_align(p22, p21, LV_ALIGN_OUT_BOTTOM_MID, 0, 0);
/*Add a label to indicate the position*/
label = lv_label_create(p22, NULL);
lv_label_set_text(label, "x2, y2");
lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
/*Focus on a tile (the list)*/
lv_tileview_set_tile_act(t, 1, 2, true);
}
void loop() {
lv_task_handler(); // Handle the GUI
delay(5); // Just wait a little
}
| true |
c0b3bf03519eecfd94f9af3237d73c9b15b4d4a9 | C++ | JCiroR/Competitive-programming | /Problems/JTS/CF-B/10077TheSternBrotcotNS.cpp | UTF-8 | 990 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <utility>
#include <string>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> frac;
bool above(frac f1, frac f2) {
if(f1.second == 0 || f2.first == 0) return true;
else if(f1.first == 0 || f2.second == 0) return false;
else return ((double)f1.first)/((double)f1.second) > ((double)f2.first)/((double)f2.second);
}
int main() {
ll n, d;
while(cin >> n >> d) {
if(n == 1 && d == 1) break;
frac left(0, 1), right(1, 0), curr(1, 1), target(n, d);
string ans = "";
while(target != curr) {
if(above(curr, target)) {
ans += 'L';
right = curr;
curr.first += left.first;
curr.second += left.second;
} else {
ans += 'R';
left = curr;
curr.first += right.first;
curr.second += right.second;
}
}
cout << ans << endl;
}
} | true |
02c819ad7f619afbefd64b09d9c38995d3417285 | C++ | iridium-browser/iridium-browser | /buildtools/third_party/libc++/trunk/test/std/time/time.cal/time.cal.weekday/time.cal.weekday.nonmembers/plus.pass.cpp | UTF-8 | 2,473 | 2.84375 | 3 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17
// <chrono>
// class weekday;
// constexpr weekday operator+(const days& x, const weekday& y) noexcept;
// Returns: weekday(int{x} + y.count()).
//
// constexpr weekday operator+(const weekday& x, const days& y) noexcept;
// Returns:
// weekday{modulo(static_cast<long long>(unsigned{x}) + y.count(), 7)}
// where modulo(n, 7) computes the remainder of n divided by 7 using Euclidean division.
// [Note: Given a divisor of 12, Euclidean division truncates towards negative infinity
// and always produces a remainder in the range of [0, 6].
// Assuming no overflow in the signed summation, this operation results in a weekday
// holding a value in the range [0, 6] even if !x.ok(). -end note]
// [Example: Monday + days{6} == Sunday. -end example]
#include <chrono>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
#include "../../euclidian.h"
template <typename M, typename Ms>
constexpr bool testConstexpr()
{
M m{1};
Ms offset{4};
assert(m + offset == M{5});
assert(offset + m == M{5});
// Check the example
assert(M{1} + Ms{6} == M{0});
return true;
}
int main(int, char**)
{
using weekday = std::chrono::weekday;
using days = std::chrono::days;
ASSERT_NOEXCEPT( std::declval<weekday>() + std::declval<days>());
ASSERT_SAME_TYPE(weekday, decltype(std::declval<weekday>() + std::declval<days>()));
ASSERT_NOEXCEPT( std::declval<days>() + std::declval<weekday>());
ASSERT_SAME_TYPE(weekday, decltype(std::declval<days>() + std::declval<weekday>()));
static_assert(testConstexpr<weekday, days>(), "");
for (unsigned i = 0; i <= 6; ++i)
for (unsigned j = 0; j <= 6; ++j)
{
weekday wd1 = weekday{i} + days{j};
weekday wd2 = days{j} + weekday{i};
assert(wd1 == wd2);
assert((wd1.c_encoding() == euclidian_addition<unsigned, 0, 6>(i, j)));
assert((wd2.c_encoding() == euclidian_addition<unsigned, 0, 6>(i, j)));
}
return 0;
}
| true |
be40147bab9099f927112453dbead57294983edc | C++ | raima20/C_Programming | /prime factor.cpp | UTF-8 | 262 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
int main()
{
int i,n;
printf("Enter the numnber:");
scanf("%d",&n);
while(n%2==0){
printf("%d",2);
n=n/2;
}
for(i=3;i<=sqrt(n);i=i+2)
while(n%i==0){
printf("%d\t",i);
n=n/i;
}
if(n>2)
printf("%d",n);
return 0;
}
| true |
912aca5ec4e39f2c32c4667d2cc5e9ef5db56a0b | C++ | kwh1108/WenhuiKuang | /CS32/Project4/Project4/DiskMultiMap.h | UTF-8 | 2,238 | 2.796875 | 3 | [] | no_license | #ifndef DISKMULTIMAP_H_
#define DISKMULTIMAP_H_
#include <string>
#include <iostream>
#include "MultiMapTuple.h"
#include "BinaryFile.h"
using namespace std;
class DiskMultiMap
{
public:
class Iterator
{
public:
Iterator();
Iterator(BinaryFile *bf, BinaryFile::Offset off);
bool isValid() const;
Iterator& operator++();
MultiMapTuple operator*();
private:
BinaryFile *bf;
BinaryFile::Offset off_set;
bool Valid;
void setValid(bool x){Valid = x;}
};
DiskMultiMap();
~DiskMultiMap();
bool createNew(const std::string& filename, unsigned int numBuckets);
bool openExisting(const std::string& filename);
void close();
bool insert(const std::string& key, const std::string& value, const std::string& context);
Iterator search(const std::string& key);
int erase(const std::string& key, const std::string& value, const std::string& context);
void print(const string &key)
{
bucket b;
unsigned int position = hashFuction(key) % head.numOfBuckets;
m_bf.read(b,sizeof(head)+sizeof(bucket)*position);
BinaryFile::Offset next = b.next;
DiskNode node;
while (next != 0)
{
m_bf.read(node, next);
cout << node.m_tuple.key << endl;
cout << node.m_tuple.value << endl;
cout << node.m_tuple.context << endl;
next = node.next;
}
}
private:
struct header
{
unsigned int numOfBuckets;
BinaryFile::Offset emptyList;
int numOfEmptyNodes;
};
struct MapTuple
{
char key[121];
char value[121];
char context[121];
};
struct DiskNode {
MapTuple m_tuple;
BinaryFile::Offset next;
};
struct bucket
{
int position;
BinaryFile::Offset next;
};
string filename;
BinaryFile m_bf;
header head;
unsigned int hashFuction(const string &str)
{
unsigned int h = 2166136261U;
for (int k = 0; k < str.size(); k++)
{
h += str[k];
h *= 16777619;
}
return h;
}
};
#endif // DISKMULTIMAP_H_ | true |
9bf8da0f5127b464761f40450f74f64fca5dcc28 | C++ | yuuta-h/-GamePrize2019 | /GameProtType.ver.0.00/textDX.cpp | SHIFT_JIS | 2,696 | 2.71875 | 3 | [] | no_license | #include "textDX.h"
TextDX debugFont;
struct {
const int m_TOP = 100, m_SIZE = 25;//Jnʒu/sԊu
int m_y = m_TOP;
}TxtLine;// 0.02
void initializeTextDX()
{
createTextDX(&debugFont, 24, false, false, "Arial");
}
void unInitializeTextDX()
{
safeRelease(debugFont.dxFont);
};
bool createTextDX(TextDX* text,int height,bool bold,bool italic,const std::string &fontName ) {
text->color = SETCOLOR_ARGB(255, 255, 255, 255); // FŃftHg
// tHgʒuݒ肷
text->fontRect.top = 0;
text->fontRect.left = 0;
text->fontRect.right = WINDOW_WIDTH;
text->fontRect.bottom= WINDOW_HEIGHT;
text->dxFont = NULL;
text->angle = 0;
UINT weight = FW_NORMAL;
if (bold)
{
weight = FW_BOLD;
}
// DirectXtHg쐬
if (FAILED(D3DXCreateFont(getDevice(), height, 0, weight, 1, italic,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, fontName.c_str(), &text->dxFont)))
{
return false;
}
// ϊs쐬
D3DXMatrixTransformation2D(&text->matrix, NULL, 0.0f, NULL, NULL, 0.0f, NULL);
return true;
};
int printTextDX(TextDX* text,const std::string &str, int x,int y) {
if (text->dxFont == NULL)
{
return 0;
}
// tHgʒuݒ
text->fontRect.top = y;
text->fontRect.left = x;
// ]S
D3DXVECTOR2 rCenter = D3DXVECTOR2((float)x, (float)y);
// eLXg̊pxʼn]s
D3DXMatrixTransformation2D(&text->matrix, NULL, 0.0f, NULL, &rCenter, text->angle, NULL);
// sXvCgɓKp
getSprite()->SetTransform(&text->matrix);
return text->dxFont->DrawTextA(getSprite(), str.c_str(), -1, &text->fontRect, DT_LEFT, text->color);
};
int printTextDX(TextDX* text,const std::string &str, int x, int y, float value)
{
const int BUF_SIZE = 255;
static char buffer[BUF_SIZE];
// floatCstringɕϊ
_snprintf_s(buffer, BUF_SIZE, "%f", value);
return printTextDX(text,str + buffer, x, y);
}
int printTextDX(TextDX* text,const std::string &str, int x, int y, int value)
{
const int BUF_SIZE = 255;
static char buffer[BUF_SIZE];
// floatCstringɕϊ
_snprintf_s(buffer, BUF_SIZE, "%d", value);
return printTextDX(text,str + buffer, x, y);
}
TextDX* getDebugFont()
{
return &debugFont;
}
int txtLineReset(int newtop) {// 0.02
TxtLine.m_y = newtop;//sʒuZbg(t[ŏ)
return TxtLine.m_TOP;//̏l擾
// txtLineReset(txtLineReset(0));//ƏƏlŃZbg
}
int txtLineBreak() {// 0.02
TxtLine.m_y += TxtLine.m_SIZE;//s
return TxtLine.m_y - TxtLine.m_SIZE;
} | true |
a13ac5f06a37fb4a4379bf9cea5947105a41807c | C++ | Pikecillo/ninety-nine-problems | /leetcode/102_binary_tree_level_order_traversal.cpp | UTF-8 | 801 | 3.3125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode *> nodes;
vector<vector<int>> levels;
if(root)
nodes.push(root);
while(!nodes.empty()) {
levels.push_back(vector<int>());
const int level_size = nodes.size();
for(int i = 0; i < level_size; i++) {
TreeNode *node = nodes.front();
nodes.pop();
levels.back().push_back(node->val);
if(node->left)
nodes.push(node->left);
if(node->right)
nodes.push(node->right);
}
}
return levels;
}
};
| true |
786e5c3c3b59ecf3971b11b72d65cbb5e5d2077a | C++ | chenbq83/CodeLab | /c++0x/thread_pool/thread_pool_1/ThreadPool.cpp | UTF-8 | 1,904 | 3.28125 | 3 | [] | no_license | #include "ThreadPool.h"
#include <iostream>
#include <algorithm>
using namespace netlib;
ThreadPool::ThreadPool(int theThreadNumber)
:threadNumber_(theThreadNumber),
isRunning_(false)
{
std::cout << "ThreadPool constructor" << std::endl;
}
ThreadPool::~ThreadPool()
{
std::cout << "ThreadPool destructor" << std::endl;
if (isRunning_)
stop();
}
bool ThreadPool::start(void)
{
for (int i = 0; i < threadNumber_; i++)
threadList_.push_back(std::thread(&ThreadPool::threadFunc, this));
std::cout << "Thread pool begins to work" << std::endl;
isRunning_ = true;
return true;
}
bool ThreadPool::stop(void)
{
if (isRunning_)
{
std::cout << "Thread pool begins to stop" << std::endl;
isRunning_ = false;
conditionEmpty_.notify_all();
for_each(threadList_.begin(), threadList_.end(), [](std::thread& t) -> void {
if (t.joinable())
t.join();
});
}
return true;
}
bool ThreadPool::addTask(Task task)
{
std::cout << "Add a task to ThreadPool" << std::endl;
std::lock_guard<std::mutex> guard(mutex_);
taskList_.push_front(task);
conditionEmpty_.notify_one();
return true;
}
void ThreadPool::threadFunc(void)
{
std::cout << "Thread " << std::this_thread::get_id() << " begins to work" << std::endl;
Task task = NULL;
while (isRunning_)
{
{
std::lock_guard<std::mutex> guard(mutex_);
if (taskList_.empty())
conditionEmpty_.wait(mutex_);
if (!taskList_.empty())
{
std::cout << "Thread " << std::this_thread::get_id() << " Take one task from queue" << std::endl;
task = taskList_.front();
taskList_.pop_front();
}
else
continue;
}
task();
}
std::cout << "Thread " << std::this_thread::get_id() << " stops" << std::endl;
}
| true |
0549e58cf93e211c9217e28d67d18af929dfbad5 | C++ | rohan-shah/residualConnectivity | /RPackage/src/residualConnectivity/igraphInterface.cpp | UTF-8 | 1,000 | 2.5625 | 3 | [] | no_license | #include "igraphInterface.h"
void igraphConvert(SEXP graph_sexp, residualConnectivity::context::inputGraph& outputGraph)
{
//Convert graph object
Rcpp::List graph;
try
{
graph = Rcpp::as<Rcpp::List>(graph_sexp);
}
catch(Rcpp::not_compatible&)
{
throw std::runtime_error("Unable to convert input graph to a list");
}
Rcpp::Environment igraphEnv("package:igraph");
Rcpp::Function length("length"), as_edgelist = igraphEnv["as_edgelist"], is_directed = igraphEnv["is_directed"], V = igraphEnv["V"];
int nVertices = Rcpp::as<int>(length(V(graph_sexp)));
bool directed = Rcpp::as<bool>(is_directed(graph_sexp));
Rcpp::NumericMatrix edgeList = Rcpp::as<Rcpp::NumericMatrix>(as_edgelist(graph_sexp));
if(directed)
{
throw std::runtime_error("Input graph must be undirected");
}
//Construct graph
outputGraph = residualConnectivity::context::inputGraph(nVertices);
for(int i = 0; i < edgeList.nrow(); i++)
{
boost::add_edge(edgeList(i, 0)-1, edgeList(i, 1)-1, outputGraph);
}
}
| true |
6f44adf9fddf0868f34297cd4dcaf6bbbef4b40f | C++ | flajann2/cwrap | /example/Po7/Po7_socket.h | UTF-8 | 9,173 | 2.734375 | 3 | [] | no_license | #pragma once
//
// Po7_socket.h
// cwrap
//
// Created by Lisa Lippincott on 8/30/14.
// Released into the public domain by Lisa Lippincott, 2014.
//
#include "Po7_Basics.h"
#include "Po7_is_sockaddr.h"
#include "bufferlike.h"
#include <type_traits>
#include <unistd.h>
#include <sys/socket.h>
namespace Po7
{
// socket_t represents a socket in any domain
struct SocketTag
{
constexpr int operator()() const { return -1; }
static const bool hasEquality = true;
static const bool hasComparison = true;
};
using socket_t = cwrap::Boxed< SocketTag >;
// socket_in_domain represents a socket in a specific domain
template < socket_domain_t >
struct SocketInDomainTag
{
constexpr int operator()() const { return -1; }
static const bool hasEquality = true;
static const bool hasComparison = true;
constexpr operator SocketTag() const { return SocketTag(); }
};
template < socket_domain_t domain >
using socket_in_domain = cwrap::Boxed< SocketInDomainTag<domain> >;
template < socket_domain_t domain >
socket_in_domain< domain > domain_cast( socket_t s )
{
return Wrap< socket_in_domain< domain > >( Unwrap( s ) );
}
// unique_socket refers to a socket, and represents the obligation to close it
struct SocketDeleter
{
using pointer = cwrap::PointerToValue< socket_t >;
void operator()( pointer s ) const;
};
using unique_socket = std::unique_ptr< const socket_t, SocketDeleter >;
// unique_socket_in_domain refers to a socket with a domain, and represents the obligation to close it
template < socket_domain_t domain >
struct SocketInDomainDeleter
{
using pointer = cwrap::PointerToValue< socket_in_domain<domain> >;
void operator()( pointer s ) const { SocketDeleter()( s ); }
operator SocketDeleter() const { return SocketDeleter(); }
};
template < socket_domain_t domain >
using unique_socket_in_domain = std::unique_ptr< const socket_in_domain<domain>, SocketInDomainDeleter<domain> >;
template < socket_domain_t domain >
unique_socket_in_domain< domain > domain_cast( unique_socket s )
{
return Seize< unique_socket_in_domain< domain > >( domain_cast<domain>( Release( s ) ) );
}
// socket_type_t is the second paremeter to socket()
enum class socket_type_t: int {};
template <> struct Wrapper< socket_type_t >: cwrap::EnumWrapper< socket_type_t > {};
const socket_type_t sock_stream = socket_type_t( SOCK_STREAM );
const socket_type_t sock_dgram = socket_type_t( SOCK_DGRAM );
const socket_type_t sock_seqpacket = socket_type_t( SOCK_SEQPACKET );
#ifdef SOCK_RAW
const socket_type_t sock_raw = socket_type_t( SOCK_RAW );
// socket_protocol_t is the third paremeter to socket()
enum class socket_protocol_t: int;
template <> struct Wrapper< socket_protocol_t >: cwrap::EnumWrapper< socket_protocol_t > {};
// socket() creates sockets, and close() gets rid of them.
// Calling close allows any final errors to be thrown.
unique_socket socket( socket_domain_t domain,
socket_type_t type,
socket_protocol_t protocol );
void close( unique_socket s );
// The template form of socket produces a socket typed to its domain, making address operations easier.
template < socket_domain_t domain >
unique_socket_in_domain< domain > socket( socket_type_t type, socket_protocol_t protocol )
{
return domain_cast< domain >( socket( domain, type, protocol ) );
}
// Listen is surprisingly simple
void listen( socket_t, int backlog );
// socklen_t is a perfectly cromulent integral type
using ::socklen_t;
// bind, connect, accept, getsockname, and
// getpeername are callable with a sockaddr and a
// length in their basic form.
void bind( socket_t, const sockaddr&, socklen_t );
void connect( socket_t, const sockaddr&, socklen_t );
unique_socket accept( socket_t );
unique_socket accept( socket_t, sockaddr&, socklen_t& );
void getsockname( socket_t, sockaddr&, socklen_t& );
void getpeername( socket_t, sockaddr&, socklen_t& );
// bind, connect, accept, getsockname, and
// getpeername are also callable with domain-typed
// sockets and addresses.
template < socket_domain_t domain >
void bind( socket_in_domain<domain> s, const sockaddr_type<domain>& a )
{
bind( s, sockaddr_cast< const sockaddr& >( a ), sizeof( a ) );
}
template < socket_domain_t domain >
void connect( socket_in_domain<domain> s, const sockaddr_type<domain>& a )
{
connect( s, sockaddr_cast< const sockaddr& >( a ), sizeof( a ) );
}
template < socket_domain_t domain >
auto accept( socket_in_domain<domain> s )
-> std::tuple< unique_socket_in_domain<domain>, sockaddr_type<domain> >
{
sockaddr_type< domain > address;
socklen_t addressLength = sizeof( address );
sockaddr& genericAddress = sockaddr_cast< sockaddr& >( address );
unique_socket accepted = accept( s, genericAddress, addressLength );
if ( Wrap<socket_domain_t>( genericAddress.sa_family ) != domain )
throw std::domain_error( "Socket not in the expected domain" );
return std::make_tuple( domain_cast<domain>( std::move( accepted ) ), address );
}
template < socket_domain_t domain >
auto getsockname( socket_in_domain<domain> s )
-> sockaddr_type< domain >
{
sockaddr_type< domain > address;
socklen_t addressLength = sizeof( address );
sockaddr& genericAddress = sockaddr_cast< sockaddr& >( address );
getsockname( s, genericAddress, addressLength );
if ( Wrap<socket_domain_t>( genericAddress.sa_family ) != domain )
throw std::domain_error( "Socket not in the expected domain" );
return address;
}
template < socket_domain_t domain >
auto getpeername( socket_in_domain<domain> s )
-> sockaddr_type< domain >
{
sockaddr_type< domain > address;
socklen_t addressLength = sizeof( address );
sockaddr& genericAddress = sockaddr_cast< sockaddr& >( address );
getpeername( s, genericAddress, addressLength );
if ( Wrap<socket_domain_t>( genericAddress.sa_family ) != domain )
throw std::domain_error( "Socket not in the expected domain" );
return address;
}
// msg_flags_t is a parameter to send() and recv()
struct MessageFlagsTag
{
constexpr int operator()() const { return 0; }
static const bool hasEquality = true;
static const bool hasComparison = true;
static const bool hasBitwise = true;
};
using msg_flags_t = cwrap::Boxed< MessageFlagsTag >;
const msg_flags_t msg_eor = msg_flags_t( MSG_EOR );
const msg_flags_t msg_oob = msg_flags_t( MSG_OOB );
const msg_flags_t msg_peek = msg_flags_t( MSG_PEEK );
const msg_flags_t msg_waitall = msg_flags_t( MSG_WAITALL );
// send and recv send and receive the data
std::size_t send( socket_t, const void *buffer, std::size_t length, msg_flags_t = msg_flags_t() );
std::size_t recv( socket_t, void *buffer, std::size_t length, msg_flags_t = msg_flags_t() );
template < class Buffer >
auto send( socket_t s, const Buffer& b, msg_flags_t f = msg_flags_t() )
-> typename std::enable_if< cwrap::stdish::is_bufferlike<Buffer>::value, std::size_t >::type
{
return send( s, cwrap::stdish::bufferlike_data( b ), cwrap::stdish::bufferlike_size( b ), f );
}
template < class Buffer >
auto recv( socket_t s, Buffer& b, msg_flags_t f = msg_flags_t() )
-> typename std::enable_if< cwrap::stdish::is_bufferlike<Buffer>::value, std::size_t >::type
{
return recv( s, cwrap::stdish::bufferlike_data( b ), cwrap::stdish::bufferlike_size( b ), f );
}
// shutdown_how_t is a parameter to shutdown()
enum class shutdown_how_t: int {};
template <> struct Wrapper< shutdown_how_t >: cwrap::EnumWrapper< shutdown_how_t > {};
const shutdown_how_t shut_rd = shutdown_how_t( SHUT_RD );
const shutdown_how_t shut_wr = shutdown_how_t( SHUT_WR );
const shutdown_how_t shut_rdwr = shutdown_how_t( SHUT_RDWR );
// shutdown ends communication on a socket
void shutdown( socket_t, shutdown_how_t );
}
| true |
8f5f5423c2921e51af0e75aada46676a0bd48980 | C++ | rishirajsurti/uva | /10004.cpp | UTF-8 | 955 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
vector<vi> adj;
vi bfs_col;
map<int, bool> vis;
bool bfs(int u, int color){
bfs_col[u] = color;
bool ans=true;
int i,v;
queue<int> q;
q.push(u);
while(!q.empty() && ans){
v = q.front(); q.pop();
// printf("%d-> ",v );
for(i=0; i<adj[v].size(); i++){
if(bfs_col[adj[v][i]] == bfs_col[v]){
ans = false;
break;
}
else if(!vis[adj[v][i]]){
bfs_col[adj[v][i]] = 1 - bfs_col[v];
vis[adj[v][i]] = true;
q.push(adj[v][i]);
}
}
}
return ans;
}
int main(){
int n;
while(scanf("%d",&n), n){
adj.clear();
adj.assign(n, vi());
bfs_col.clear();
bfs_col.assign(n, -1);
vis.clear();
int l; scanf("%d", &l);
int i,j,x,y;
for(i=0; i<l; i++){
scanf("%d %d", &x, &y);
adj[x].push_back(y);
adj[y].push_back(x);
}
if(bfs(0, 0))
printf("BICOLORABLE.\n");
else
printf("NOT BICOLORABLE.\n");
}
return 0;
} | true |
47ee327404ed246ba102f9457abcd916665012ce | C++ | SyromyatnikovAlexander/msu_cpp_autumn_2020 | /07/vector.h | UTF-8 | 2,528 | 3.15625 | 3 | [] | no_license | #ifndef VECTOR_H
#define VECTOR_H
#include <cstddef>
template<class T>
class MyAllocator {
T * pointer = nullptr;
size_t mySize = 0;
public:
MyAllocator() { }
T * allocate(size_t size);
void deallocate(T* ptr, size_t size);
size_t maxSize() const noexcept;
};
template<class T, class Container>
class MyIterator {
size_t current = 0;
Container vec;
public:
MyIterator() { }
MyIterator(size_t cur, Container& myVec) : current(cur), vec(myVec) { }
MyIterator(const MyIterator& other) : current(other.current), vec(other.vec) { }
MyIterator(MyIterator&& other);
MyIterator& operator=(const MyIterator& other);
MyIterator& operator=(MyIterator&& other);
~MyIterator() { }
void operator++();
T operator*() const;
bool operator==(const MyIterator& other) const;
bool operator!=(const MyIterator& other) const;
};
template<class T, class Container>
class MyRIterator : public MyIterator<T, Container> {
size_t current;
public:
MyRIterator(size_t cur, Container& myVec) { }
MyRIterator(const MyRIterator& other) { }
MyRIterator(MyRIterator&& other) { }
void operator++() {
current--;
}
};
template<class T, class A = MyAllocator<T>>
class MyVector {
using value_type = T;
using Allocator = A;
value_type *myValues = nullptr;
size_t mySize = 0;
size_t myCapacity = 0;
Allocator myAllocator;
void setCapacity(size_t capacity);
public:
MyVector() { };
MyVector(size_t count);
MyVector(size_t count, const value_type& defaultValue);
MyVector(const MyVector& other);
MyVector(MyVector&& other);
~MyVector();
MyVector& operator=(const MyVector& other);
MyVector& operator=(MyVector&& other);
bool operator==(const MyVector& other) const;
bool operator!=(const MyVector& other) const;
size_t capacity() const noexcept;
size_t size() const noexcept;
bool empty() const noexcept;
void clear();
void resize(size_t count);
void push_back(const value_type& value);
void push_back(value_type&& value);
value_type pop_back();
void reserve(size_t capacity);
template<class... ArgsT>
void emplace_back(ArgsT&&... args);
value_type operator[](size_t pos) const;
value_type& operator[](size_t pos);
MyIterator<T, MyVector> begin();
MyIterator<T, MyVector> end();
MyRIterator<T, MyVector> rbegin();
MyRIterator<T, MyVector> rend();
};
#include "vector_fromcpp.h"
#endif
| true |
e8d2b4cad1b6b77af51e63fcb5d541dccf93f38a | C++ | Radu-Lucian/pianify | /include/Client/DataMappingTools.hpp | UTF-8 | 2,212 | 3.4375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include <sstream>
#include <type_traits>
#include <iterator>
class DataMapper
{
public:
template <typename T>
std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, std::string> convertToString(const std::vector<std::vector<T>>& data);
template <typename T>
std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, std::string> convertToString(const std::vector<T>& data);
template <typename T>
std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, std::vector<T>> convertFromString(std::string_view data);
private:
static constexpr std::string_view kElementsDelimiter{ "," };
static constexpr std::string_view kEmptyString{ "" };
static constexpr char kSequenceDelimiter{ ';' };
private:
std::ostringstream m_outputStringStream;
std::istringstream m_inputStringStream;
};
template<typename T>
inline std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, std::string> DataMapper::convertToString(const std::vector<std::vector<T>>& data)
{
static std::string result;
result.clear();
for (const auto& vector : data)
{
std::copy(std::cbegin(vector), std::cend(vector), std::ostream_iterator<T>(m_outputStringStream, kElementsDelimiter.data()));
}
result = m_outputStringStream.str();
result.pop_back();
return result;
}
template<typename T>
inline std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, std::string> DataMapper::convertToString(const std::vector<T>& data)
{
static std::string result;
result.clear();
std::copy(std::begin(data), std::end(data), std::ostream_iterator<T>(m_outputStringStream, kElementsDelimiter.data()));
result = m_outputStringStream.str();
result.pop_back();
m_outputStringStream.str(kEmptyString.data());
return result;
}
template<typename T>
inline std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, std::vector<T>> DataMapper::convertFromString(std::string_view data)
{
static std::vector<T> result;
result.clear();
m_inputStringStream.clear();
m_inputStringStream.str(data.data());
for (T value; m_inputStringStream >> value;)
{
result.emplace_back(value);
}
return result;
}
| true |
bdde60bb67aa7ad86c00052a54d9cbaa6fa0535a | C++ | Argo15/Aggro-Engine | /AggroEngine/src/Subsystem/Graphics/Impl/OpenGL/CommandTree/GBuffer/InitializeGBufferCommand.cpp | UTF-8 | 1,947 | 2.765625 | 3 | [] | no_license | #include "InitializeGBufferCommand.hpp"
#include "Texture.hpp"
InitializeGBufferCommand::InitializeGBufferCommand(GLuint framebuffer, GLuint program, GLsizei width, GLsizei height)
: Command()
, m_framebuffer(framebuffer)
, m_program(program)
, m_width(width)
, m_height(height)
{
m_hash = CommandType::INIT_GBUFFER;
}
void InitializeGBufferCommand::executeCommand()
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_framebuffer);
glUseProgram(m_program);
GLenum mrt[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT };
glDrawBuffers(4, mrt);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, m_width, m_height);
glLineWidth(1);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glBindFragDataLocation(m_program, 0, "normalBuffer");
glBindFragDataLocation(m_program, 1, "albedoBuffer");
glBindFragDataLocation(m_program, 2, "selectionBuffer");
glBindFragDataLocation(m_program, 3, "glowBuffer");
glBindAttribLocation(m_program, 0, "v_vertex");
glBindAttribLocation(m_program, 1, "v_texcoord");
glBindAttribLocation(m_program, 2, "v_normal");
glBindAttribLocation(m_program, 3, "v_tangent");
glBindAttribLocation(m_program, 4, "v_bitangent");
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
}
void InitializeGBufferCommand::end()
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
glDisableVertexAttribArray(4);
glUseProgram(0);
glPopAttrib();
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
Texture::unbind();
}
bool InitializeGBufferCommand::equals(shared_ptr<Command> other)
{
InitializeGBufferCommand *cmd = static_cast<InitializeGBufferCommand *>(other.get());
return cmd->m_type == CommandType::INIT_GBUFFER;
} | true |
8ee922ce7c7fc10c4f2288b7f0630fc86093880e | C++ | gokcedemir/Object-Oriented-Homeworks | /hw5/ConnectFourDiag.h | UTF-8 | 851 | 2.8125 | 3 | [] | no_license | /* File: ConnectFourDiag.h
* Author: Gökçe Demir
* Student ID: 141044067
* CSE241 - HWO5
* Created on November 22, 2017, 12:41 AM
*/
#ifndef CONNECTFOURDIAG_H
#define CONNECTFOURDIAG_H
#include <iostream>
#include <string>
#include "ConnectFourAbstract.h"
using namespace std;
namespace Game
{
class ConnectFourDiag: public ConnectFourAbstract
{
public:
ConnectFourDiag(); //no parameter constructor
ConnectFourDiag(int theRow, int theCol);
/* This function that returns if the game ended. */
/* Return Value: bool if game ends return true */
virtual bool gameEnded(char ch, char typeGame) override;
private:
/*This function checks the cross four X or O for user.*/
bool crossCheck(char ch, const char& type);
};
}
#endif /* CONNECTFOURDIAG_H */
| true |
92c57739d12e2765dcf731b2901e63be04a052c0 | C++ | BaranovMykola/Parallel-Computing | /MatrixComputing/SymplexMethod.cpp | UTF-8 | 3,856 | 3.0625 | 3 | [] | no_license | #include "SymplexMethod.h"
#include <iostream>
#include <algorithm>
#include <numeric>
#include <thread>
#include <future>
using std::cout;
using std::endl;
double symplexMethod(Mat C, Mat a, int n, int m)
{
Vec P0 = extractVecB(a, n, m);
Vec b = P0;
Mat _Cb = createMat(1, m);
generateMatrix(_Cb, 1, m, 0);
Vec Cb = _Cb[0];
Vec delta = createMat(1, n)[0];
updateDelta(delta, Cb, C, a, m, n);
try
{
do
{
int minDeltaIndex = findMinDeltaIndex(delta, n);
int k = minDeltaIndex;
int r = findMainIndex(P0, a, m, k);
Cb[r] = C[0][k];
if (delta[k] >= 0)
{
break;
}
double max = a[0][k];
for (int i = 0; i < m; i++)
{
if (a[i][k] > max)
{
max = a[i][k];
}
}
if (max <= 0)
{
return INT_MAX;
}
updateB(&P0, a, r, k, m);
updateA(&a, m, n, r, k);
updateDelta(delta, Cb, C, a, m, n);
}
while (true);
}
catch (int) {}
Vec functSeries = createMat(1, m)[0];
std::transform(Cb, Cb + m, P0, functSeries, [](double a, double b) { return a*b; });
return std::accumulate(functSeries, functSeries + m, 0.0);
}
double symplexMethodParallel(Mat C, Mat a, int n, int m, int p)
{
Vec P0 = extractVecB(a, n, m);
Vec b = P0;
Mat _Cb = createMat(1, m);
generateMatrix(_Cb, 1, m, 0);
Vec Cb = _Cb[0];
Vec delta = createMat(1, n)[0];
updateDelta(delta, Cb, C, a, m, n);
try
{
do
{
int minDeltaIndex = findMinDeltaIndex(delta, n);
int k = minDeltaIndex;
int r = findMainIndex(P0, a, m, k);
Cb[r] = C[0][k];
if (delta[k] >= 0)
{
break;
};
updateB(&P0, a, r, k, m);
updateAParallel(&a, m, n, r, k, p);
updateDelta(delta, Cb, C, a, m, n);
}
while (true);
}
catch (int) {}
Vec functSeries = createMat(1, m)[0];
std::transform(Cb, Cb + m, P0, functSeries, [](double a, double b) { return a*b; });
return std::accumulate(functSeries, functSeries + m, 0.0);
}
Vec extractVecB(Mat a, int n, int m)
{
Vec b = new double[m];
for (int i = 0; i < m; i++)
{
b[i] = a[i][n];
}
return b;
}
void updateDelta(Vec delta, Vec Cb, Mat C, Mat a, int m, int n)
{
for (int j = 0; j < n; j++)
{
delta[j] = 0;
for (int i = 0; i < m; i++)
{
delta[j] += Cb[i] * a[i][j];
}
delta[j] -= C[0][j];
}
}
int findMinDeltaIndex(Vec delta, int n)
{
auto minIter = std::min_element(delta, delta + n);
int index = std::distance(delta, minIter);
return index;
}
int findMainIndex(Vec Cb, Mat a, int m, int k)
{
Vec ratio = createMat(1, m)[0];
for (int i = 0; i < m; i++)
{
if (a[i][k] == 0)
{
ratio[i] = INT_MAX;
continue;
}
ratio[i] = Cb[i] / a[i][k];
}
auto minIter = std::min_element(ratio, ratio + m);
int index = std::distance(ratio, minIter);
return index;
}
void updateB(Vec* P0, Mat a, int r, int k, int m)
{
Vec b = *P0;
Vec _b = createMat(1, m)[0];
for (int i = 0; i < m; i++)
{
if (a[r][k] == 0)
{
throw 0;
}
_b[i] = i == r ? b[r] / a[r][k] : b[i] - (b[r] / a[r][k])*a[i][k];
}
*P0 = _b;
delete[] _b;
}
bool updateA(Mat* a, int m, int n, int r, int k, int from, int to)
{
if (from == to)
{
from = 0;
to = m;
}
Mat _a = createMat(m, n);
for (int i = from; i < to; i++)
{
if ((*a)[r][k] == 0)
{
if (from != to)
{
return false;
}
throw 0;
}
for (int j = 0; j < n; j++)
{
_a[i][j] = i == r ? (*a)[r][j] / (*a)[r][k] : (*a)[i][j] - ((*a)[r][j] / (*a)[r][k])*(*a)[i][k];
}
}
if (from == to)
{
deallocate(*a, m, n);
*a = _a;
}
return true;
}
void updateAParallel(Mat* a, int m, int n, int r, int k, int p)
{
std::vector<std::future<bool>> thrs;
for (int i = 0; i < p; i++)
{
int from = (m / p)*i;
int to = (m / p)*(i + 1);
if (i + 1 == p)
{
to = p;
}
thrs.push_back(std::async(updateA,a, m, n, r, k, from, to));
}
bool t = false;
for (auto& i : thrs)
{
if(!i.get());
{
t = true;
}
}
if (t) { throw 0; }
} | true |
b306fc3e2d2bc147cb6c8470cdfc0ccee9615185 | C++ | eagletmt/contests | /source/code/poj/3771.cc | UTF-8 | 1,843 | 3.03125 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
using namespace std;
typedef complex<double> P;
struct edge
{
int u, v;
double d;
edge(int a, int b, double c) : u(a), v(b), d(c) {}
bool operator<(const edge& e) const { return d < e.d; }
};
struct DisjointSet/*{{{*/
{
vector<int> parent;
int root(int x)
{
if (parent[x] < 0) {
return x;
} else {
parent[x] = root(parent[x]);
return parent[x];
}
}
explicit DisjointSet(int n) : parent(n, -1) {}
bool unite(int x, int y)
{
const int a = root(x);
const int b = root(y);
if (a != b) {
if (parent[a] < parent[b]) {
parent[a] += parent[b];
parent[b] = a;
} else {
parent[b] += parent[a];
parent[a] = b;
}
return true;
} else {
return false;
}
}
bool find(int x, int y) { return root(x) == root(y); }
int size(int x) { return -parent[root(x)]; }
};/*}}}*/
double kruskal(const vector<edge>& g, int N, int bill)
{
double c = 0;
DisjointSet s(N);
for (vector<edge>::const_iterator it = g.begin(); it != g.end(); ++it) {
if (it->u == bill || it->v == bill) {
continue;
}
if (s.unite(it->u, it->v)) {
c += it->d;
}
}
return c;
}
int main()
{
int T;
scanf("%d", &T);
while (T-- > 0) {
int N;
scanf("%d", &N);
vector<P> v;
for (int i = 0; i < N; i++) {
int x, y;
scanf("%d %d", &x, &y);
v.push_back(P(x, y));
}
vector<edge> g;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
g.push_back(edge(i, j, abs(v[i] - v[j])));
}
}
sort(g.begin(), g.end());
double ans = 1e10;
for (int i = 0; i < N; i++) {
ans = min(ans, kruskal(g, N, i));
}
printf("%.2f\n", ans);
}
return 0;
}
| true |
99b60dac55c634432988223ba35a1123b7f6e7ab | C++ | CODARcode/MGARD | /tests/src/test_TensorQuantityOfInterest.cpp | UTF-8 | 5,218 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | #include "catch2/catch_approx.hpp"
#include "catch2/catch_test_macros.hpp"
#include <cstdlib>
#include <algorithm>
#include <limits>
#include <random>
#include <stdexcept>
#include "TensorMeshHierarchy.hpp"
#include "TensorNorms.hpp"
#include "TensorQuantityOfInterest.hpp"
#include "blas.hpp"
#include "testing_random.hpp"
namespace {
//! Functional given by an inner product with a function.
template <std::size_t N, typename Real> class RieszRepresentative {
public:
//! Constructor.
//!
//! IMPORTANT: `representative` must be shuffled.
//!
//!\param hierarchy Mesh hierarchy associated to the function space.
//!\param representative Function φ such that the functional is given by
//! (φ, ·).
RieszRepresentative(const mgard::TensorMeshHierarchy<N, Real> &hierarchy,
Real const *const representative);
//! Destructor.
~RieszRepresentative();
//! Apply the functional to a function.
//!
//! IMPORTANT: `u` must be unshuffled.
//!
//!\param hierarchy Mesh hierarchy on which the function is defined.
//!\param u Input to the functional.
Real operator()(const mgard::TensorMeshHierarchy<N, Real> &hierarchy,
Real const *const u) const;
private:
//! Associated mesh hierarchy.
const mgard::TensorMeshHierarchy<N, Real> &hierarchy;
//! Size of the finest mesh in the hierarchy.
std::size_t ndof;
//! Buffer in which to store shuffled inputs.
Real *u;
//! Product of the mass matrix and the Riesz representative.
Real *f;
};
template <std::size_t N, typename Real>
RieszRepresentative<N, Real>::RieszRepresentative(
const mgard::TensorMeshHierarchy<N, Real> &hierarchy,
Real const *const representative)
: hierarchy(hierarchy), ndof(hierarchy.ndof()), u(new Real[ndof]),
f(new Real[ndof]) {
std::copy(representative, representative + ndof, f);
const mgard::TensorMassMatrix<N, Real> M(hierarchy, hierarchy.L);
M(f);
}
template <std::size_t N, typename Real>
RieszRepresentative<N, Real>::~RieszRepresentative() {
delete[] f;
delete[] u;
}
template <std::size_t N, typename Real>
Real RieszRepresentative<N, Real>::operator()(
const mgard::TensorMeshHierarchy<N, Real> &hierarchy,
Real const *const u) const {
if (hierarchy != this->hierarchy) {
throw std::domain_error(
"construction and calling hierarchies must be equal");
}
mgard::shuffle(hierarchy, u, this->u);
return blas::dotu(hierarchy.ndof(), f, this->u);
}
template <std::size_t N, typename Real>
void test_qoi_norm_equality(std::default_random_engine &generator,
std::uniform_real_distribution<Real> &distribution,
const std::array<std::size_t, N> shape,
const Real s) {
const mgard::TensorMeshHierarchy<N, Real> hierarchy =
hierarchy_with_random_spacing(generator, distribution, shape);
Real *const representative = new Real[hierarchy.ndof()];
generate_reasonable_function<N, Real>(hierarchy, static_cast<Real>(1),
generator, representative);
const Real representative_norm = mgard::norm(hierarchy, representative, -s);
const RieszRepresentative<N, Real> functional(hierarchy, representative);
const mgard::TensorQuantityOfInterest<N, Real> Q(hierarchy, functional);
delete[] representative;
REQUIRE(Q.norm(s) == Catch::Approx(representative_norm));
}
} // namespace
TEST_CASE("Riesz representative norm equality", "[qoi]") {
std::default_random_engine gen;
// Node spacing distribution.
std::uniform_real_distribution<double> dis(0.05, 0.075);
test_qoi_norm_equality<1, double>(gen, dis, {5}, 0);
test_qoi_norm_equality<1, double>(gen, dis, {18}, -0.25);
test_qoi_norm_equality<2, double>(gen, dis, {13, 13}, 0.5);
test_qoi_norm_equality<2, double>(gen, dis, {40, 7}, -0.75);
test_qoi_norm_equality<3, double>(gen, dis, {4, 4, 5}, 1.0);
test_qoi_norm_equality<3, double>(gen, dis, {9, 5, 6}, -1.25);
}
namespace {
template <std::size_t N, typename Real>
void test_average_norms(const std::array<std::size_t, N> shape) {
const mgard::TensorMeshHierarchy<N, Real> hierarchy(shape);
Real *const ones = new Real[hierarchy.ndof()];
std::fill(ones, ones + hierarchy.ndof(), static_cast<Real>(1));
const RieszRepresentative<N, Real> functional(hierarchy, ones);
delete[] ones;
const mgard::TensorQuantityOfInterest<N, Real> Q(hierarchy, functional);
const std::vector<Real> smoothness_parameters = {-1.5, -0.5, 0, 0.5, 1.5};
Real minimum_norm = std::numeric_limits<Real>::max();
Real maximum_norm = std::numeric_limits<Real>::min();
for (const Real s : smoothness_parameters) {
const Real norm = Q.norm(s);
minimum_norm = std::min(minimum_norm, norm);
maximum_norm = std::max(maximum_norm, norm);
}
REQUIRE(minimum_norm == Catch::Approx(maximum_norm).epsilon(1e-3));
}
} // namespace
TEST_CASE("average quantity of interest", "[qoi]") {
// Could be any function contained in the coarsest function space here.
test_average_norms<1, float>({25});
test_average_norms<2, double>({12, 14});
test_average_norms<3, float>({10, 11, 4});
test_average_norms<4, double>({6, 3, 3, 5});
}
| true |
32064f91e92063f0a3eb144d0cc45aaca39e0aa1 | C++ | zhongjianhua163/BlackMoonKernelStaticLib | /krnln/krnln_GetHDiskCode.cpp | GB18030 | 950 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "stdafx.h"
/*
øʽ ͡ ȡӲ - ϵͳֿ֧->
ӢƣGetHDiskCode
صеһӲ̵֣ǽӲصģҲ˵κϵͳأϵͳûʹôԼijijһ̨УԱԼİȨκ Windows ϵͳ汾Сִк 0 ʾ˴ȡӲʧܡпΪʱ I/O ͻɣʧܺԵȴһʱԣԲο̣ظκȻʧܣӲȡ֡Ϊ
*/
extern DWORD __cdecl krnln_GetHD___Code(int *a1);
LIBAPI(DWORD, krnln_GetHDiskCode)
{
return krnln_GetHD___Code(NULL);
} | true |
fce7d4937df1e6b17ce056fb7b004b0b79fc4f74 | C++ | mrdylan123/LinalgEindopdracht | /LinalgEindopdracht/World.cpp | UTF-8 | 1,539 | 2.515625 | 3 | [] | no_license | #include "World.h"
#define _USE_MATH_DEFINES
#include "Vector.h"
#include "Shapes/Shape.h"
#include "Shapes/SpaceShip.h"
World::World() : camera_{ this }
{
}
World::~World()
{
}
void World::update(SDL_Renderer& renderer)
{
SDL_SetRenderDrawColor(&renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
if (shapes_.size() > 10)
shapes_.erase(shapes_.begin() + 1);
// Get all vectors and draw them aswell
for (auto& shape : shapes_)
{
shape->update(renderer, camera_);
}
for (auto& asteroid : asteroids_)
{
asteroid->update(renderer, camera_);
}
if (planet_ != nullptr)
planet_->update(renderer, camera_);
if (planet_ != nullptr && planet_->collidesWith(*shapes_[0]))
{
auto spaceship = dynamic_cast<SpaceShip*>(shapes_[0].get());
spaceship->setDestroyed(true);
}
for(auto& asteroid : asteroids_)
{
if(asteroid->collidesWith(*shapes_[0]))
{
auto spaceship = dynamic_cast<SpaceShip*>(shapes_[0].get());
spaceship->setDestroyed(true);
}
}
std::vector<std::vector<std::unique_ptr<Shape>>::const_iterator> deleteProjectilesList{};
// Loop through all projectiles and see if it's near a collision sphere
for (auto i = shapes_.begin() + 1; i < shapes_.end(); ++i)
{
if (planet_ != nullptr && planet_->collidesWith(**i))
{
deleteProjectilesList.emplace_back(i);
if (planet_->hits() >= 10)
planet_.reset();
}
}
for (auto i = deleteProjectilesList.rbegin(); i < deleteProjectilesList.rend(); ++i)
{
shapes_.erase(*i);
}
}
void World::initializeCamera()
{
camera_.lookatMatrix();
}
| true |
e02a994e1202054cbf87e02b87222dcf47e50cd4 | C++ | luisSalher/Sistemas-Distribuidos | /Practica12/Cliente.cpp | UTF-8 | 1,941 | 2.90625 | 3 | [] | no_license | #include "SocketDatagrama.h"
#include <iostream>
#define PUERTO 7200
#define PUERTO1 7201
#define PUERTO2 7202
int main(int argc, char const *argv[]) {
char *server_ip = "127.0.0.1";
char *server_ip2 = "127.0.0.10";
char *server_ip3 = "127.0.0.20";
unsigned int mensaje1[3];
unsigned int mensaje2[3];
unsigned int mensaje3[3];
unsigned int n=4294967291;
printf("%s\n", "CLIENTE");
SocketDatagrama socketCliente(6666);
printf("%s\n", "ENVIANDO PAQUETE...");
mensaje1[0] = n;
mensaje1[1] = 1;
mensaje1[2] = n/3;
mensaje2[0] = n;
mensaje2[1] = mensaje1[2] + 1;
mensaje2[2] = (n/3) * 2;
mensaje3[0] = n;
mensaje3[1] = mensaje2[2] + 1;
mensaje3[2] = n - 1;
PaqueteDatagrama paquete1((char *)mensaje1, sizeof(mensaje1) * sizeof(int), server_ip, PUERTO);
PaqueteDatagrama paquete2((char *)mensaje2, sizeof(mensaje2) * sizeof(int), server_ip, PUERTO1);
PaqueteDatagrama paquete3((char *)mensaje3, sizeof(mensaje3) * sizeof(int), server_ip, PUERTO2);
printf("Mandando paquete a: %s:%d\n", paquete1.obtieneDireccion(), paquete1.obtienePuerto());
socketCliente.envia(paquete1);
socketCliente.envia(paquete2);
socketCliente.envia(paquete3);
printf("%s\n", "PAQUETE ENVIADO");
socketCliente.recibe(paquete1);
socketCliente.recibe(paquete2);
socketCliente.recibe(paquete3);
printf("\nPaquete recibido de: %s:%d \n", paquete1.obtieneDireccion(), PUERTO);
printf("\nPaquete recibido de: %s:%d \n", paquete2.obtieneDireccion(), PUERTO1);
printf("\nPaquete recibido de: %s:%d \n", paquete3.obtieneDireccion(), PUERTO2);
unsigned int *num1 = (unsigned int *)paquete1.obtieneDatos();
unsigned int *num2 = (unsigned int *)paquete2.obtieneDatos();
unsigned int *num3 = (unsigned int *)paquete3.obtieneDatos();
printf("%d,%d,%d\n",num1[0],num2[0],num3[0]);
return 0;
}
| true |
e09824f63629c50ea4e8942dace0b3599693110f | C++ | snowyuki31/competitive-programming-library | /snow/monoids/plus-size.hpp | UTF-8 | 1,404 | 2.890625 | 3 | [] | no_license | #pragma once
namespace snow {
template < typename T >
struct plus_size_monoid {
struct value_type {
T val;
int size;
};
static value_type e() { return value_type{0, 0}; };
static value_type op(value_type l, value_type r) { return {l.val + r.val, l.size + r.size}; };
struct add {
using f_type = T;
static value_type mapping(f_type f, value_type x) { return {f * x.size + x.val, x.size}; }
static f_type composition(f_type f, f_type g) { return f + g; }
static f_type id(){ return T(); }
};
struct update {
struct f_type{
T val;
bool flag;
};
static value_type mapping(f_type f, value_type x) { return {(f.flag ? f.val * x.size : x.val), x.size}; }
static f_type composition(f_type f, f_type g) { return f.flag ? f : g; }
static f_type id(){ return {T(), false}; }
};
struct affine {
using f_type = std::pair<T, T>;
static value_type mapping(f_type f, value_type x) { return {x.val * f.first + x.size * f.second, x.size}; }
static f_type composition(f_type f, f_type g) { return {g.first * f.first, g.second * f.first + f.second}; }
static f_type id(){ return {1, 0}; }
};
};
} // namespace snow | true |
bdd8bbbd7abb75cca6f41285dede9d9541f930be | C++ | HarryLong/StatisticalAnalysisTool | /reproducer/distribution_factory.h | UTF-8 | 1,489 | 2.515625 | 3 | [] | no_license | #ifndef DISTRIBUTION_FACTORY_H
#define DISTRIBUTION_FACTORY_H
#include "../utils/dice_roller.h"
#include <QPoint>
class AnalysisPoint;
class DistributionFactory
{
public:
DistributionFactory();
std::vector<AnalysisPoint> generateRandomDistribution(int category_id, int p_number_of_points, int width, int height,
int min_height, int max_height, float canopy_r_multiplier, float root_size_multiplier);
std::vector<AnalysisPoint> generateGriddedDistribution(int category_id, int p_grid_seperation, int width, int height,
int min_height, int max_height, float canopy_r_multiplier, float root_size_multiplier);
std::vector<AnalysisPoint> generateSeededDistribution(int category_id, int n_seeds, int n_seeding_iterations, int max_seeding_distance,
int width, int height, int min_height, int max_height, float canopy_r_multiplier, float root_size_multiplier,
bool equidistant = false);
private:
QPoint get_random_position(int max_width, int max_height);
AnalysisPoint generate_analysis_point(int category_id, QPoint position, int min_height, int max_height, float canopy_radius_multiplier, float root_size_multiplier);
int get_random_value(int min, int max);
DiceRoller m_dice_roller;
};
#endif // DISTRIBUTION_FACTORY_H
| true |
b2e96228f26152662fcf173968986ad29ba25a31 | C++ | gratus907/Gratus_PS | /BOJ Originals/[BOJ Steps] BOJ 단계별로 풀어보기/[20] 스택/09012 괄호.java | UTF-8 | 372 | 2.796875 | 3 | [] | no_license | #include <cstdio>
#pragma warning (disable:4996)
using namespace std;
int stack[100000];
int main()
{
int n;
scanf("%d", &n);
int ptr = 0;
long long int sum = 0;
while (n--)
{
int x;
scanf("%d", &x);
if (x != 0)
{
stack[ptr] = x;
ptr++;
}
else
{
ptr--;
}
}
for (int i = 0; i < ptr; i++)
{
sum += stack[i];
}
printf("%lld", sum);
} | true |
63c1a6c4d4dd540baf2bf23fa09fb4e36ec385c6 | C++ | Bonayy/Competitive-Programming | /SnackDown2019/TYPING.cpp | UTF-8 | 1,701 | 2.640625 | 3 | [] | no_license | /*
Author: Dung Tuan Le
University of Rochester
*/
#include <bits/stdc++.h>
#define fio ios_base::sync_with_stdio(false); cin.tie(NULL)
#define FOR(i, l, r) for (int i=l; i<=r; i++)
#define REP(i, r, l) for (int i=r; i>=l; i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define eps 1e-9
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<long, long> pll;
typedef pair<ll, ll> pllll;
typedef pair<ld, ld> Point;
typedef pair<Point, Point> line;
struct strLine { ld a, b, c; };
typedef vector<int> vi;
typedef vector<long> vl;
typedef vector<ll> vll;
const double pi = 3.141592653589793;
ll gcd(ll a, ll b) { return (b==0)?a:gcd(b, a%b); }
ll lcm(ll a, ll b) { return (a*b)/gcd(a, b); }
ll max(ll a, ll b) { return (a>=b)?a:b; }
ll min(ll a, ll b) { return (a<=b)?a:b; }
long hand(char c) {
if (c == 'd' || c == 'f') return 1;//left hand
return 2;
}
int main() {
fio;
long test_cases, n;
double time, totalTime;
string word;
cin >> test_cases;
map<string, double> Map;
FOR(current_test, 1, test_cases) {
cin >> n;
totalTime = 0;
Map.clear();
FOR(i, 1, n) {
cin >> word;
if (Map[word] != 0) {
totalTime += (Map[word] / 2);
continue;
}
time = 0;
FOR(j, 0, int(word.length()) - 1) {
if (j == 0) {
time += 0.2;
continue;
}
if (hand(word[j]) == hand(word[j - 1])) time += 0.4;
else time += 0.2;
}
Map[word] = time;
totalTime += time;
}
cout << totalTime * 10 << "\n";
}
return 0;
}
| true |
a4c2344cfa09ab19b9eebd99135f2c95c5e7a9b7 | C++ | ivilab/src | /lib/l_mt_cpp/l_mt_pt_attr.h | UTF-8 | 3,227 | 3.109375 | 3 | [] | no_license | /**
* @file
* @author Andrew Predoehl
* @brief def of RAII class to control a pthread attr object
*/
/*
* $Id: l_mt_pt_attr.h 25499 2020-06-14 13:26:04Z kobus $
*/
#ifndef PT_ATTR_H_INCLUDED_IVILAB
#define PT_ATTR_H_INCLUDED_IVILAB
#include <l_mt/l_mt_pthread.h>
#include <l_cpp/l_exception.h>
namespace ivi
{
/**
* @addtogroup iviThreads Thread support
* @{
*/
/**
* @brief RAII class to manage an object of type ivi_pthread_attr_t
*
* The ivi_pthread sublibrary, which wraps the Posix pthread library,
* uses an object of type ivi_pthread_attr_t to describe the attributes
* of a thread. Thread attributes are its "detach state," its stack
* size, and other things. See pthread_attr_init(3).
* A single attribute object may be used on multiple threads.
*
* The attribute object must be created and destroyed, thus this RAII
* class exists to manage those tasks.
* Objects of this class are not copyable or assignable.
*
* Currently this class does not support all thread attribute options,
* but a developer is welcome to add new ones to the C library wrapper
* (l_mt) and add WRAPPED calls through this class. Please do not call
* pthreads functions directly -- use the wrapped calls in ivi_c.
*
* Example.
* @code
* void* ha(void*) { for(int i=100; i--; ) puts("lol"); }
* main() {
* ivi_c::ivi_pthread_t tid;
* ivi::Pthread_attr a;
* a.set_detached();
* ivi_c::ivi_pthread_create(*tid, a, ha, NULL);
* // no need to join
* return 0;
* }
* @endcode
*/
class Pthread_attr
{
// private attribute object
ivi_c::ivi_pthread_attr_t m_attr;
Pthread_attr(const Pthread_attr&); // teaser: do not copy
Pthread_attr& operator=(const Pthread_attr&); // teaser: do not assign
public:
/// @brief initialize a generic attribute object.
Pthread_attr()
{
ETX(ivi_c::ivi_pthread_attr_init(&m_attr));
}
/// @brief destroy an attribute object.
~Pthread_attr()
{
ivi_c::ivi_pthread_attr_destroy(&m_attr);
}
/**
* @brief set the detach flag.
* @param flag IVI_PTHREAD_CREATE_JOINABLE, IVI_PTHREAD_CREATE_DETACHED
* are the two valid values.
* @return ERROR or NO_ERROR as appropriate
* @see set_detached as a possibly more readable alternative
*/
int setdetachstate(int state)
{
return ivi_c::ivi_pthread_attr_setdetachstate(&m_attr, state);
}
/// @brief convenience synonym setdetachstate(IVI_PTHREAD_CREATE_DETACHED)
int set_detached()
{
return setdetachstate(IVI_PTHREAD_CREATE_DETACHED);
}
/**
* @brief obtain the detach setting of this object.
* @param[out] state Pointer to int into which the state is written
* @return ERROR or NO_ERROR
* @post *state contains IVI_PTHREAD_CREATE_JOINABLE if the thread is
* joinable, or IVI_PTHREAD_CREATE_DETACHED if not.
*/
int getdetachstate(int* state)
{
return ivi_c::ivi_pthread_attr_getdetachstate(&m_attr, state);
}
/// @brief access thread attribute as const pointer.
operator const ivi_c::ivi_pthread_attr_t*()
{
return &m_attr;
}
};
/// @}
} // end ns ivi
#endif /* PT_ATTR_H_INCLUDED_IVILAB */
| true |
bc550477b3b188be3910e0da82a351788a7a8b72 | C++ | Vegtam/Roguelike | /src/TitleView.cpp | UTF-8 | 1,424 | 2.671875 | 3 | [] | no_license | #include <vector>
#include <string>
#include <allegro5/allegro.h>
#include "Image.hpp"
#include "TitleView.hpp"
#include "World.hpp"
bool TitleView::init()
{
int result = false;
if( model && imageset)
{
Image& title = imageset->get(titlescreen);
title.init(0, 0, 1024, 768); /* probably need a better way of specifying this*/
drawList.push_back(&title);
result = is_init = true;
}
return result;
}
DefinedViews TitleView::handleKeyPress(ALLEGRO_EVENT* ev)
{
DefinedViews dv = DefinedViews::TITLE_VIEW;
switch(ev->keyboard.keycode)
{
case ALLEGRO_KEY_N: /* New Game*/
dv = DefinedViews::CHARACTER_CREATION_NAME_VIEW;
model->init();
break;
case ALLEGRO_KEY_R: /* Credits */
dv = DefinedViews::CREDITS_VIEW;
break;
case ALLEGRO_KEY_C: /* Continue */
if (model->isInit())
{
dv = DefinedViews::WORLD_VIEW;
}
break;
case ALLEGRO_KEY_S: /* Settings */
/* not supported yet */
break;
case ALLEGRO_KEY_Q: /* Quit */
dv = DefinedViews::QUIT_VIEW;
break;
default:
break;
}
return dv;
}
DefinedViews TitleView::handleEvent(ALLEGRO_EVENT* ev)
{
/* for now just handle start and quit */
DefinedViews dv = DefinedViews::TITLE_VIEW;
if( ev )
{
switch (ev->type)
{
case ALLEGRO_EVENT_KEY_CHAR:
dv = handleKeyPress(ev);
break;
default:
break;
}
}
return dv;
}
std::vector<Displayable*>& TitleView::draw()
{
return drawList;
} | true |
94814eb9a3ca11df4a2866741a4307de4168c535 | C++ | yushiyaogg/backup | /practice/STL/find.cpp | UTF-8 | 508 | 3 | 3 | [] | no_license | #include <vector>
#include <list>
#include <deque>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
const int arraySize = 7;
int ia[arraySize] = {0,1,2,3,4,5,6};
vector<int> ivect(ia, ia+arraySize);
list<int> ilist(ia,ia+arraySize);
deque<int> ideque(ia, ia+arraySize);
vector<int>::iterator it1 = find(ivect.begin(),ivect.end(),4);
if(it1 == ivect.end())
cout << "4 not found"<<endl;
else
cout << "4 found"<<endl;
return 0;
}
| true |
f638be4b42013a4870bb3ef724db51cc733ead48 | C++ | jonathanleemn/Program_Design_And_Development | /HW01/point2.cc | UTF-8 | 539 | 3.203125 | 3 | [] | no_license | // Copyright 2018 <Jonathan Lee>
#include "HW/HW01/point2.h"
#include <math.h>
#include <iostream>
Point2::Point2(float x, float y) {
XCoord = x;
YCoord = y;
}
Point2::Point2() {
XCoord = 0;
YCoord = 0;
}
Point2::~Point2() {
std::cout << "Destructor" << std::endl;
}
float Point2::get_X_Coord() {
return XCoord;
}
float Point2::get_Y_Coord() {
return YCoord;
}
float Point2::DistanceBetween(Point2 p) {
return sqrt(pow(p.get_X_Coord()-XCoord, 2.0) +
pow(p.get_Y_Coord() - YCoord, 2.0));
}
| true |
a36fec163fc1fb10e54301f6040982eb436d086c | C++ | rjtsdl/CPlusPlus | /Interview Play CPP/a1388PizzaWith3nSlices.cpp | UTF-8 | 954 | 2.71875 | 3 | [] | no_license | //
// a1388PizzaWith3nSlices.cpp
// Interview Play CPP
//
// Created by jingtao ren on 9/6/20.
// Copyright © 2020 Jingtao Ren. All rights reserved.
//
#include <stdio.h>
#include <vector>
using namespace std;
class Solution {
public:
const int inf = 1e9;
int solve(vector<int>& a, int k) {
if (a.empty()) return 0;
int n = a.size();
vector<vector<int> > dp(n + 1, vector<int>(k + 1, -inf));
for (int i = 0; i < n + 1; i++) dp[i][0] = 0;
dp[1][1] = a[0];
for (int i = 2; i < n + 1; i++)
for (int j = 1; j < k + 1; j++)
dp[i][j] = max(dp[i - 1][j], dp[i - 2][j - 1] + a[i - 1]);
return dp[n][k];
}
int maxSizeSlices(vector<int>& slices) {
int n = slices.size();
vector<int> a(slices.begin(), slices.end() - 1);
vector<int> b(slices.begin() + 1, slices.end());
return max(solve(a, n / 3), solve(b, n / 3));
}
};
| true |
50e05a6c3bfb7a61872bc701a209ff667c6b29f3 | C++ | jxu103/denchgrade | /src/menu.h | UTF-8 | 2,106 | 3.25 | 3 | [] | no_license | #ifndef MENU_H
#define MENU_H
#include "account.h"
#include <iostream>
#include <string>
using namespace std;
class Menu {
private:
Account* account;
public:
bool run() {
bool exitcall;
this->loginMenu();
exitcall = this->mainMenu();
return exitcall;
}
void loginMenu() {
this->account = new Account();
bool userLogin = 0;
bool exitCall = 0;
while(exitCall == 0) {
cout << "Please choose an option from the menu" << endl;
cout << "1. Login" << endl;
cout << "2. Create Account" << endl;
cout << "3. Exit" << endl;
//Prompting User
string userInput;
cin >> userInput;
if(userInput == "1") {
//calls login function
bool status = account->login();
if(!status) {
// Should not end program here, loop to menu
cout << "The username or password you've entered is incorrect" << endl;
}
else {
// Unimplemented
cout << "Correct login!" << endl;
cout << "Welcome back: " << account->getUsername() << "!" << endl;
exitCall = 1;
}
}
else if(userInput == "2") {
account->signup();
cout << "Signup successful!" << endl;
// Unimplemented
exitCall = 0;
}
else if(userInput == "3") {
cout <<"Thanking for using Dench Grading System" << endl;
exit(-1);
}
else {
cout <<"Invalid selection" << endl;
}
}
}
bool mainMenu() {
return 1;
}
};
#endif | true |
80f535104c3dffc64f196ee4c5d8a60d63d2d508 | C++ | Sokakaoh/CameraRP_PTut | /func.cpp | UTF-8 | 5,027 | 2.703125 | 3 | [] | no_license | /*
* func.cpp
*
* Created on: 15 févr. 2018
* Author: pi
*/
#include "func.hpp"
void error(const char *msg)
{
perror(msg);
exit(0);
}
Conf* menu(Conf* setRP)
{
int numb = -1;
while(numb < 1 || numb > 3)
{
cout << "Configuration de la capture d'images :" << endl;
cout << "1. Modification taille image." << endl;
cout << "2. Démarrer capture." << endl;
cout << "3. Choix méthode de comparaison." << endl;
cin.clear();
cin >> numb;
}
switch(numb) {
case 1:
setSize(setRP);
break;
case 2:
cout << "Lancement capture ('q' pour quitter)." << endl;
break;
case 3:
compChoice(setRP);
break;
default :
menu(setRP);
break;
}
return setRP;
}
void setSize(Conf* setRP)
{
//bool valide = false;
cout << "Configuration de la taille (minimum 200px) :" << endl;
cout << "Configuration largeur (min : 200px , max : 1920px) : " << endl;
cout << "Largeur :";
cin >> setRP->width;
while(setRP->width < 200 || setRP->width > 1920)
{
cout << "Largeur :";
cin >> setRP->width;
}
cout << "Configuration hauteur (min : 200px , max : 1080px) : " << endl;
cout << "Hauteur :";
cin >> setRP->height;
while(setRP->height < 200 || setRP->width > 1080)
{
cout << "Hauteur :";
cin >> setRP->height;
}
menu(setRP);
}
void compChoice(Conf* setRP)
{
int choix;
cout <<"Méthode de comparaison :"<< endl;
cout <<"1. Comparaison par pixels: Compare chaque pixel de deux images. (par défaut)" << endl;
cout <<"2. Comparaison par contours: Compare les contours (des formes) dans les images (en noir et blanc)." << endl;
cout <<"3. Comparaison par suppression de fond : Supprime les éléments statiques d'une image et détecte les changements." << endl;
cout <<"4. Retour menu principal." << endl;
cin >> choix;
switch(choix) {
case 1 :
setRP->comp_method = 1;
menu(setRP);
break;
case 2 :
setRP->comp_method = 2;
menu(setRP);
break;
case 3 :
setRP->comp_method = 3;
menu(setRP);
break;
case 4 :
menu(setRP);
break;
default :
compChoice(setRP);
break;
}
}
void createSocket(int argc, char *argv[] ,Conf* setRP )
{
int sockfd, portno;
struct sockaddr_in serv_addr;
struct hostent *server;
if (argc < 3) {
fprintf(stderr,"Utilisation %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERREUR ouverture socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERREUR, hôte inconnu\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERREUR connection");
setRP->sock = sockfd;
}
void sendParameters(Conf* setRP)
{
int numReq = 1;
if(send(setRP->sock, &numReq, sizeof ( int), 0 ) < 0)
error("Erreur envoi numéro requête paramètre");
else {
if( send(setRP->sock, &setRP->width, sizeof (unsigned int), 0 ) < 0 )
error("Erreur envoi taille");
else
{
if( send(setRP->sock, &setRP->height, sizeof (unsigned int), 0 ) < 0 )
error("Erreur envoi taille");
else
cout <<"Envoi taille :" << setRP->width << "x" << setRP->height << endl;
}
}
}
void sendInit(Conf* setRP)
{
int init = -1;
if( send(setRP->sock, &init, sizeof (int), 0 ) < 0 )
error("Erreur envoi initialisation");
}
Mat compare_contours(Mat image, Mat image2)
{
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
int thresh = 30;
/// Détection de bords avec filtre de Canny
Canny( image, canny_output, thresh, thresh*2, 3 );// tresh*3
/// Détection de contours
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
/// On dessine les contours
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC1 );
Mat drawing2 = Mat::zeros( canny_output.size(), CV_8UC1 );
for( unsigned int i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( 255, 255, 255 );
drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
}
/// On fait la même chose pour la deuxième image
Canny( image2, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
for( unsigned int i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( 255, 255, 255 );
drawContours( drawing2, contours, i, color, 2, 8, hierarchy, 0, Point() );
}
/// On soustrait les deux images pour avoir les différences
Mat diff;
compare(drawing, drawing2, diff, cv::CMP_EQ);
return diff;
}
/*void apply_bgs(Conf_bgs* bgs)
{
bgs->pMOG2 = createBackgroundSubtractorMOG2();
}
*/
| true |
7334390b397f22b888bf2095607988bd08b679f1 | C++ | joerocklin/pdes | /warped/simulationmodels/adaptTest/AdaptTestObject.cpp | UTF-8 | 8,141 | 2.515625 | 3 | [] | no_license | // See copyright notice in file Copyright in the root directory of this archive.
#include <string>
#include <utils/StringUtilities.h>
#include "AdaptTestEvent.h"
#include "AdaptTestObject.h"
#include "AdaptTestObjectState.h"
#include <warped/SimulationManager.h>
#include <warped/warped.h>
#include <warped/IntVTime.h>
using namespace std;
const unsigned int numAdaptObjects = 6;
AdaptTestObject::AdaptTestObject( int myId,
const string &initDestObjectName,
const int initNumberOfStragglers,
bool initAdaptiveState,
string initOutputMode ):
myObjectName( getName( myId )),
myDestObjectName( initDestObjectName ),
numStragglers( initNumberOfStragglers ),
sendTo( 0 ),
rollbackOccurred( false ),
rollbackCount( 0 ),
adaptiveState( initAdaptiveState ),
outputMode( initOutputMode){}
AdaptTestObject::~AdaptTestObject(){
deallocateState(getState());
}
void
AdaptTestObject::initialize(){
sendTo = getObjectHandle(myDestObjectName);
IntVTime initTime = dynamic_cast<const IntVTime&> (getSimulationTime());
// Setup the objects vector. The index into the vector returns the object id
// of the object with name "Object#" where "#" is the object number and the index.
string objName;
objects.resize(numAdaptObjects);
for(int i = 0; i < numAdaptObjects; i++){
stringstream out;
out << i;
objName = "Object" + out.str();
objects[i] = *(getObjectHandle(objName)->getObjectID());
}
if( *getObjectID() == objects[0]){
startEvent();
}
else if( *getObjectID() == objects[3]){
// Object3 starts the first event for the mini-pingpong ring.
// This event will continue to circle around the ring for the duration
// of the simulation.
AdaptTestObjectState* myState = static_cast<AdaptTestObjectState*>(getState());
Event *startNewEvent = new AdaptTestEvent( initTime,
initTime + 5,
this,
sendTo );
sendTo->receiveEvent( startNewEvent );
myState->eventSent();
myState->eventStarted();
}
}
void
AdaptTestObject::startEvent(){
IntVTime sendTime = dynamic_cast<const IntVTime&> (getSimulationTime());
AdaptTestObjectState* myState = static_cast<AdaptTestObjectState*>(getState());
Event *startNewEvent = new AdaptTestEvent( sendTime,
sendTime + 20,
this,
sendTo );
sendTo->receiveEvent( startNewEvent );
myState->eventStarted();
myState->eventSent();
// Send an event back to itself that this object continues to
// generate events.
Event *repeatEvent = new AdaptTestEvent( sendTime,
sendTime + 20,
this,
this );
receiveEvent( repeatEvent );
}
void
AdaptTestObject::executeProcess(){
AdaptTestObjectState *myState = static_cast<AdaptTestObjectState*>(getState());
ASSERT(myState != 0);
IntVTime sendTime = dynamic_cast<const IntVTime&> (getSimulationTime());
ASSERT( haveMoreEvents() == true );
while(haveMoreEvents() == true){
const AdaptTestEvent *eventReceived = dynamic_cast<const AdaptTestEvent *>(getEvent());
ASSERT( eventReceived != 0 );
// This delay is used to test the adaptive state manager.
if( adaptiveState ){
double x = 35.39453234857;
for(long double wait = -123456789.1234567890; wait < 4000000; wait = wait + 10000){
x = wait / x;
}
}
ObjectID senderObject = eventReceived->getSender();
if( myState->getNumStragglersSent() < numStragglers ){
if( *getObjectID() == objects[0] && myState->getNumSent() < 10000 ){
// Object0 will generate 10000 events
startEvent();
}
else if( *getObjectID() == objects[1] ){
myState->eventReceived();
// When the event is from Object3, it is the straggler event.
// Do not send a new event for this event. Object1 is the main
// object in this simulation. There are 3 modes that occur after
// a rollback:
// 1. Regenerate all the same events. (LAZY)
// 2. Generate entirely different events. (AGGR)
// 3. Generate the same events for half the simualtion, then
// different events for the second half of the simulation. (ADAPT)
if(senderObject == objects[3]){
rollbackCount++;
if( outputMode == "lazy" ){
rollbackOccurred = false;
}
else if( outputMode == "aggr" ){
rollbackOccurred = !rollbackOccurred;
}
else if( outputMode == "adapt" ){
if( rollbackCount <= numStragglers/2 ){
rollbackOccurred = false;
}
else{
rollbackOccurred = !rollbackOccurred;
}
}
else{
std::cerr << "Improper output mode. Must be lazy, aggr, or adapt.\n";
abort();
}
}
if(senderObject == objects[0]){
if( !rollbackOccurred ){
Event *sameEvent = new AdaptTestEvent( sendTime,
sendTime + 20,
this,
sendTo );
sendTo->receiveEvent( sameEvent );
myState->eventSent();
}
else{
Event *differentEvent = new AdaptTestEvent( sendTime,
sendTime + 19,
this,
sendTo );
sendTo->receiveEvent( differentEvent );
myState->eventSent();
}
}
}
else if( *getObjectID() == objects[2] ){
// Do nothing for Object2. This is a sink object.
myState->eventReceived();
}
else if( *getObjectID() == objects[3] || *getObjectID() == objects[4] || *getObjectID() == objects[5] ){
myState->eventReceived();
// Send a straggler for every 100 events sent.
if( *getObjectID() == objects[3] && myState->getNumSent() % 100 == 0 && sendTime > 0 ){
SimulationObject *recv = getObjectHandle("Object1");
Event *secondEvent = new AdaptTestEvent( sendTime,
sendTime + 1,
this,
recv );
recv->receiveEvent( secondEvent );
myState->eventSent();
myState->stragglerSent();
}
Event *shortEvent = new AdaptTestEvent( sendTime,
sendTime + 1,
this,
sendTo );
sendTo->receiveEvent( shortEvent );
myState->eventSent();
}
}
}
}
void
AdaptTestObject::finalize(){
SEVERITY severity = NOTE;
//simulation is over
//let's see how we did
AdaptTestObjectState* myState = static_cast<AdaptTestObjectState*>(getState());
ASSERT(myState != NULL);
string msg = myObjectName + " " + myState->getSummaryString() + "\n";
reportError( msg, severity );
}
State*
AdaptTestObject::allocateState() {
return new AdaptTestObjectState( adaptiveState );
}
void
AdaptTestObject::deallocateState( const State *state ){
// delete state
// HINT: you could insert this in a free pool of states
delete state;
}
void
AdaptTestObject::reclaimEvent(const Event *event){
// delete event
// HINT: you could insert this in a free pool of event
delete event;
}
string
AdaptTestObject::getName( int forId ){
return "Object" + intToString(forId);
}
| true |
6a83d5b7411f17bb42a0cb9ca9e5afd7210c1263 | C++ | garinrk/MonsterEngine | /MonsterGame_WithEngine/MonsterChase/MonsterGame.cpp | UTF-8 | 8,862 | 3.21875 | 3 | [] | no_license | #include "MonsterGame.h"
#include "Player.h"
#include "Monster.h"
#include "MonsterEngine.h"
#include "MonsterDebug.h"
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
MonsterGame::MonsterGame(int boardSize, MonsterPoint2D &playerStartPos)
{
boardSizeX = boardSize;
boardSizeY = boardSize;
main_player = new Player("PlayerOne");
main_player->SetPosition(playerStartPos);
}
MonsterGame::~MonsterGame()
{
delete[] masterMonsterList;
}
void MonsterGame::Start()
{
printf("%s", "=======================================\n");
printf("%s", "==============MONSTER CHASE============\n");
printf("%s", "=======================================\n");
GetAndDisplayUserName();
GetAndSetNumberOfMonsters();
InitializeMonsters(numberOfMonsters);
PlayGame();
printf("%s", "=======================================\n");
printf("%s", "==============EXITING GAME=============\n");
printf("%s", "=======================================\n");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Check for number validity, specifically if
/// the user inputted a number less than 100 </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
///
/// <param name="input"> [in,out] If non-null, the input. </param>
///
/// <returns> true if it succeeds, false if it fails. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
bool MonsterGame::CheckForNumberValidity(char* input) const
{
size_t result = strlen(input);
int userNumber = atoi(input);
if (userNumber > 100 || result == 0 || userNumber == 0)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets user name using printf a </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
void MonsterGame::GetAndDisplayUserName() {
while (askingForPlayerInfo) {
printf("%s", "\nWhat is your name [Max length of 80]: ");
fgets(userNameInput, sizeof(userNameInput), stdin);
if (userNameInput != 0) {
askingForPlayerInfo = false;
}
else
printf("%s", "Invalid");
}
main_player->SetName(userNameInput);
printf("%s%s\n", "Accepted!\n\tWelcome ", userNameInput);
DEBUGLOG("%s\nLine: %d \n%s: %s", __FILE__, __LINE__, "Username: ", userNameInput);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets number of monsters via scanf </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
void MonsterGame::GetAndSetNumberOfMonsters()
{
while (askingForNumberOfMonsters) {
printf("\nHow many monsters would you like to create? [100 Max]: ");
fgets(numberInput, sizeof(numberInput), stdin);
assert(strtol(numberInput, NULL, 0) != 0 && "Non-Numerical Integer detected!");
size_t result = strlen(numberInput);
int userNumber = atoi(numberInput);
assert(userNumber <= 100 && "You can only have 100 monsters or less!");
if (userNumber == 0) {
printf("You either supplied 0 or a non numerical integer, please try again\n");
continue;
}
numberOfMonsters = userNumber;
askingForNumberOfMonsters = false;
}
DEBUGLOG("%s\nLine: %d \n%s: %d\n", __FILE__, __LINE__, "Number of Monsters: ", numberOfMonsters);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Main gameplay function. </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
void MonsterGame::PlayGame()
{
printf("=======================================\n");
printf("==============GAME START===============\n");
printf("=======================================\n\n\n");
while (inMainGameplayLoop) {
DisplayGameState();
main_player->Update();
bool game_over = reinterpret_cast<PlayerController*>(main_player->GetController())->GetGameOverState();
if (game_over)
return;
/*Main Loop :
Query user for Player movement directory or quit request.
If quit condition has been satisfied quit the game.Otherwise :
Update Monster positions based on their AI.
Determine if any Monsters need to be created or destroyed and do so.
Update Player position based on user input.
Go to step 1.
*/
//kill a monster randomly.
killMonsterCounter--;
if (killMonsterCounter == 0) {
killMonsterCounter = killMonstersEvery;
int monsterToKill = MMEngine::MMath::GetRandomIntInBounds(0, numberOfMonsters - 1);
KillMonster(monsterToKill);
}
for (int i = 0; i < numberOfMonsters; i++) {
masterMonsterList[i].Update();
}
//add a monster randomly
if (MonsterEngine::RandomTrueOrFalse())
AddMonster();
timeStep += 1;
}
}
void MonsterGame::DisplayGameState() const
{
printf("\n\n=======================================\n");
printf("==============Day Number %d=============\n", timeStep);
printf("=======================================\n");
printf("\n\n%s%d%s\n", "There are ", numberOfMonsters, " monster(s) in the dungeon");
for (int i = 0; i < numberOfMonsters; i++) {
if (masterMonsterList[i].is_zombie_) {
printf("Zombie Monster %s is at %.1f, %.1f and is %d day(s) old\n", masterMonsterList[i].GetName().c_str(), masterMonsterList[i].GetPosition().x(), masterMonsterList[i].GetPosition().y(), masterMonsterList[i].GetAge());
}
else {
printf("Monster %s is at %.1f, %.1f and is %d day(s) old\n", masterMonsterList[i].GetName().c_str(), masterMonsterList[i].GetPosition().x(), masterMonsterList[i].GetPosition().y(), masterMonsterList[i].GetAge());
}
}
printf("You are at (%.1f, %.1f)\n\n", main_player->GetPosition().x(),main_player->GetPosition().y());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Initializes the monsters based on the amount of monsters
/// specified </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
///
/// <param name="n"> The int to process. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void MonsterGame::InitializeMonsters(const int numberOfMonsters)
{
masterMonsterList = new Monster[numberOfMonsters];
for (int i = 0; i < numberOfMonsters; i++) {
Monster *tempMon = new Monster(std::to_string(i + 1),boardSizeX,boardSizeY);
if (i % 5 == 0) {
tempMon->Zombify(main_player);
}
masterMonsterList[i] = *tempMon;
DEBUGLOG("%s\nLine: %d \n%s: %d\n", __FILE__, __LINE__, "Creating Monster: ", i + 1);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Kills a monster based on its given index in the
/// master monster list. Does this by copying over it and
/// shifting the array over. </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
///
/// <param name="monsterPos"> The monster position. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
void MonsterGame::KillMonster(const int monsterPos)
{
printf("\n\n=======================================\n");
printf("===========A MONSTER HAS DIED==========\n");
printf("=======================================\n\n");
numberOfMonsters--;
for (int i = monsterPos; i < numberOfMonsters - 1; i++) {
masterMonsterList[i] = masterMonsterList[i + 1];
masterMonsterList[i].SetName(std::to_string(i + 1));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Adds a new monster to the master monster list. </summary>
///
/// <remarks> Garin, 9/4/2016. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
void MonsterGame::AddMonster() {
numberOfMonsters++;
printf("\n\n=======================================\n");
printf("===========A MONSTER HAS APPEARED======\n");
printf("=======================================\n\n");
//create new array
Monster *newMon = new Monster(std::to_string(numberOfMonsters),boardSizeX,boardSizeY);
Monster *newArray = new Monster[numberOfMonsters];
for (int i = 0; i < numberOfMonsters; i++) {
if (i < numberOfMonsters - 1) {
newArray[i] = masterMonsterList[i];
}
if (i == numberOfMonsters - 1)
newArray[i] = *newMon;
}
delete[] masterMonsterList;
/*
Monster *tempMon = new Monster(std::to_string(i + 1), boardSizeX, boardSizeY);
if (i % 5 == 0) {
tempMon->Zombify(main_player);
}
masterMonsterList[i] = *tempMon;*/
masterMonsterList = newArray;
}
| true |
42084760b1dc5acce71694e06d94b51eafe63917 | C++ | palmsnipe/cppsharing | /shared/mylib.cpp | UTF-8 | 1,050 | 2.578125 | 3 | [] | no_license | //
// shared.cpp for cppsharing in /Users/cyrilmorales/Documents/Projects/perso-cppsharing/shared
//
// Made by Cyril Morales
// Email <palmsnipe@hotmail.com>
//
// Started on Wed Nov 18 00:10:30 2015 Cyril Morales
// Last update Wed Nov 18 22:42:57 2015 Cyril Morales
//
#include <fstream>
// #include <iostream>
// #include <vector>
#include "mylib.h"
const std::string helloworld() {
return std::string("Bonjour le monde !!");
}
const std::vector<std::string> getDays() {
std::vector<std::string> list;
list.push_back(std::string("lundi"));
list.push_back(std::string("mardi"));
list.push_back(std::string("mercredi"));
list.push_back(std::string("jeudi"));
list.push_back(std::string("vendredi"));
list.push_back(std::string("samedi"));
list.push_back(std::string("dimanche"));
return list;
}
const std::string getFile() {
std::ifstream file;
std::string line;
file.open("toto.txt");
if (file.is_open()) {
while (getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
}
return std::string("fffff");
}
| true |
9f8a516865d0c79dae9ee78acadde89f3577e45e | C++ | banach-space/cpp-tutor | /include/strings_pool.hpp | UTF-8 | 2,170 | 3.609375 | 4 | [
"MIT"
] | permissive | //==============================================================================
// FILE:
// strings_pool.hpp
//
// AUTHOR:
// banach-space@github
//
// DESCRIPTION:
//
// License: MIT
//==============================================================================
#ifndef _STRINGS_POOL_
#define _STRINGS_POOL_
#include <string>
//==============================================================================
// StringsPool class
//
// A basic memory manager/container for std::string. It stores strings inside a
// preallocated memory pool using `placement new`. It is assumes that only
// small strings are stored [1], so that no dynamic memory allocation within
// string's constructor is used.
//
// [1] Strings that fit into the static internal buffer. See also SSO.
//==============================================================================
class StringsPool {
public:
StringsPool();
StringsPool(char const *const *c_strings, size_t n);
~StringsPool();
// Since a non-default destructor was declared, the following special
// functions need to be either defined or deleted. Otherwise they will be
// auto-generated.
StringsPool(const StringsPool &) = delete;
StringsPool(StringsPool &&) = delete;
StringsPool operator=(StringsPool) = delete;
StringsPool operator=(StringsPool &&) = delete;
// Get the string at index `idx`
std::string const &at(size_t idx) const { return memory_[idx]; }
// Reserve space for `request` strings
void reserve(size_t request);
// Add `new_str` to the memory pool
void append(std::string const &new_str);
// Get the number of strings currently stored
size_t size() const { return size_; }
private:
// Allocates a new memory for capacity_ strings. All currently stored strings
// are copied into the new memory pool. Old memory pool is deallocated.
void reserve();
// Destroys all strings stored in memory_ and frees the memory.
void destroy();
// Number of strings currently stored
size_t size_ = 0;
// Number of strings that can be stored inside memory_
size_t capacity_ = 0;
// The raw memory pool used for storing strings
std::string *memory_ = nullptr;
};
#endif
| true |
74fb0dc0c636710b752cfe36dff6a2f039dee0cd | C++ | Yee172/SHY_ACM_Template | /Codes/cpp/Yee_172/math/fast_Walsh_Hadamard_transform.cpp | UTF-8 | 1,691 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
namespace FWT
{
const int MOD = 0x3b9aca07;
const int inv2 = MOD + 1 >> 1;
inline void FWT_OR(int * x, int len, int mode=1)
{
for (int step = 1; step < len; step <<= 1)
for (int d = step << 1, i = 0; i < len; i += d)
for (int j = i; j < i + step; ++j)
{
int a = x[j], b = x[j + step];
if (mode == -1) x[j + step] = (b - a + MOD) % MOD;
else x[j + step] = (a + b) % MOD;
}
}
inline void FWT_AND(int * x, int len, int mode=1)
{
for (int step = 1; step < len; step <<= 1)
for (int d = step << 1, i = 0; i < len; i += d)
for (int j = i; j < i + step; ++j)
{
int a = x[j], b = x[j + step];
if (mode == -1) x[j] = (a - b + MOD) % MOD;
else x[j] = (a + b) % MOD;
}
}
inline void FWT_XOR(int * x, int len, int mode=1)
{
for (int step = 1; step < len; step <<= 1)
for (int d = step << 1, i = 0; i < len; i += d)
for (int j = i; j < i + step; ++j)
{
int a = x[j], b = x[j + step];
x[j] = (a + b) % MOD;
x[j + step] = (a - b + MOD) % MOD;
if (mode == -1)
{
x[j] = (int)(1ll * x[j] * inv2 % MOD);
x[j + step] = (int)(1ll * x[j + step] * inv2 % MOD);
}
}
}
}
using FWT::FWT_OR;
using FWT::FWT_AND;
using FWT::FWT_XOR;
| true |
42bffa6a29fb52e08bf68a2f09522bf728c9a515 | C++ | MyunghunSeong/CExample | /Example9.cpp | UHC | 1,056 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void copyArray(int* pArr, int* arr, int size)
{
int i = 0;
for(i = 0; i < size; i++)
*(pArr + i) = arr[i];
}
void printArray(int* pArr, int start, int size)
{
int i = 0;
for(i = start; i < size; i++)
printf("Number[%d] : %d\n", i+1, pArr[i]);
}
void InputArray(int* pArr, int pre, int size)
{
int i = 0;
for(i = pre; i < size; i++)
{
printf(" Է : ");
scanf("%d", &pArr[i]);
}
}
int main()
{
int num, i = 0;
int count = 0;
int arr[5] = {0,};
int* pArr = NULL;
int size = sizeof(arr) / sizeof(int);
for(i = 0; i < size; i++)
{
printf(" Է : ");
scanf("%d", &num);
arr[i] = num;
count++;
}
pArr = (int*)malloc(count);
copyArray(pArr, arr, count);
printArray(pArr, 0, count);
while(num != -1)
{
int now = 0;
now = count + now;
if(count >= now)
{
free(pArr);
count = now + 3;
pArr = (int*)malloc(count);
}
InputArray(pArr, size, count);
printArray(pArr, size, count);
}
return 0;
} | true |
c8266aaff2a68eb3bc33e3f66a2449b0711e0f2e | C++ | kass1693/Baekjoon | /2775.cpp | UTF-8 | 400 | 2.546875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int arr[15][15];
int main() {
int T, k, n;
for (int i = 1; i <= 14; i++)
arr[0][i] = i;
for (int i = 1; i <= 14; i++)
arr[i][1] = 1;
for (int i = 1; i <= 14; i++) {
for (int j = 2; j <= 14; j++) {
arr[i][j] = arr[i - 1][j] + arr[i][j - 1];
}
}
scanf("%d", &T);
while (T--) {
scanf("%d %d", &k, &n);
printf("%d\n", arr[k][n]);
}
}
| true |
d349272ed6685de529f3c1c391b4c8f342fbad4c | C++ | evanJensengit/problems | /twoSum.cpp | UTF-8 | 1,686 | 3.484375 | 3 | [] | no_license | //
// main.cpp
// TwoSumProblem
//
// Created by Evan Jensen on 8/5/20.
// Copyright © 2020 Evan Jensen. All rights reserved.
//
using namespace std;
#include <iostream>
#include <vector>
vector<int> twoSum(vector<int>& nums, int target) {
bool solutionNotFound = true;
int indexBase = 0;
int baseAndCurrentSum;
int currentElement;
int currentElementBase;
while (solutionNotFound) {
for (int i = indexBase; i < nums.size(); i++) {
baseAndCurrentSum = nums[i] + nums[indexBase];
//cout << baseAndCurrentSum << endl;
if (baseAndCurrentSum == target) {
solutionNotFound = false;
currentElementBase = nums[indexBase];
currentElement = nums[i];
nums.erase(nums.begin(), nums.end());
nums.push_back (currentElement);
nums.push_back (currentElementBase);
break;
}
}
if (indexBase == nums.size()) {
break;
}
indexBase++;
}
return nums;
}
int main(int argc, const char * argv[]) {
vector<int> myInts {12, 14, 22, 7, 8, 13 };
for (auto i = myInts.begin(); i != myInts.end(); ++i) {
cout << *i << endl;
}
int target = 21;
myInts = twoSum(myInts, target);
cout << "New vector after twoSum: " << endl;
for (auto i = myInts.begin(); i != myInts.end(); ++i) {
cout << *i << endl;
}
// cout << myInts.size();
// for (int i = 0; i <= 20; i++) {
// myInts.push_back(i);
// }
// for (int i = 0; i <= 20; i++) {
// cout << myInts[i] << endl;
// }
}
| true |
62b30d612641b16e18d846b4c11e82125491024a | C++ | abista7/DatabaseSystem | /projects/FinalProject/Library.h | UTF-8 | 5,205 | 3.015625 | 3 | [] | no_license | #pragma once
#include "Database.h"
class Library
{
Database db;
string host = "tcp://127.0.0.1:3306";
string userName = "root";
string password = "0987654321";
string database = "Library";
public:
Library()
{
db.connect(host, userName, password);
if (db.getIsConnected())
{
if (db.ConnectDB(database) == 0)
{
db.createDatabase(database);
db.ConnectDB(database);
db.createTable("users", vector<string> {"id", "user_name", "user_password"}, vector<string> {"int auto_increment not null", "nvarchar(50) not null", "nvarchar(100) not null"}, "constraint pk_user_id primary key (id)");
db.createTable("Author", vector<string> {"id", "author_name", "details"}, vector<string> {"int auto_increment not null", "nvarchar(50) not null", "nvarchar(100) not null"}, "constraint pk_author_id primary key (id)");
db.createTable("Books", vector<string> {"id", "ISBN", "title", "publisher", "author_id"}, vector<string> {"int auto_increment not null", "bigint not null", "nvarchar(100) not null", "nvarchar(100) not null", "int not null"}, "constraint pk_book_id primary key (id), constraint fk_book_author foreign key (author_id) references Author (id) on update cascade on delete cascade");
}
}
}
void CreateAccount()
{
string name;
string password;
string rechkPassword;
do {
system("cls");
cin.ignore();
cout << "Enter name : ";
getline(cin, name);
cout << "Enter password : ";
getline(cin, password);
cout << "Re-Enter password : ";
getline(cin, rechkPassword);
} while (password != rechkPassword);
if (!isUserExist(name, password))
db.insert("users", vector<string> {"user_name", "user_password"}, vector<string> {name, password});
else
cout << "User already exist ..." << endl;
}
bool LogIn()
{
string name;
string password;
system("cls");
cin.ignore();
cout << "Enter name : ";
getline(cin, name);
cout << "Enter password : ";
getline(cin, password);
return isUserExist(name, password);
}
void Search()
{
string query;
cout << "Enter Book by ISBN or title : ";
cin.ignore();
getline(cin, query);
if (db.getIsConnected())
{
vector<vector<string>> res = db.select("Books as b join Author as a on a.id = b.author_id","b.title, b.ISBN, b.publisher, a.author_name, a.details","b.ISBN = '"+ query +"' or b.title ='" + query + "'");
if (res.size() != 0)
{
for (size_t i = 0; i < res.size(); i++)
{
cout << "Title : " << res[i][0] << endl;
cout << "ISBN : " << res[i][1] << endl;
cout << "Publisher : " << res[i][2] << endl;
cout << "Author Name : " << res[i][3] << endl;
cout << "About author : " << res[i][4] << endl;
}
}
else
{
cout << "No result Found ..." << endl;
}
}
}
void Insert()
{
if (db.getIsConnected())
{
string title;
string ISBN;
string author;
string author_details;
string publisher;
cin.ignore();
cout << "Enter Book title : ";
getline(cin, title);
cout << "Enter Book ISBN : ";
getline(cin, ISBN);
cout << "Enter Author Name : ";
getline(cin, author);
cout << "Enter about Author : ";
getline(cin, author_details);
cout << "Enter publisher : ";
getline(cin, publisher);
db.insert("Author", vector<string> {"author_name", "details"}, vector<string> {author, author_details});
vector<vector<string>> id = db.select("Author", "id", " author_name = '" + author + "'");
db.insert("Books", vector<string> {"ISBN", "title", "publisher","author_id"}, vector<string> {ISBN, title, publisher,id[0][0]});
}
}
void Update()
{
if (db.getIsConnected())
{
string toUpdate;
string title;
string ISBN;
string author;
string author_details;
string publisher;
cin.ignore();
cout << "Enter Book title or ISBN for update : ";
getline(cin, toUpdate);
cout << "Enter Book title : ";
getline(cin, title);
cout << "Enter Book ISBN : ";
getline(cin, ISBN);
cout << "Enter Author Name : ";
getline(cin, author);
cout << "Enter about Author : ";
getline(cin, author_details);
cout << "Enter publisher : ";
getline(cin, publisher);
db.update("Author join Books on Books.author_id = Author.id", vector<string> {"Books.ISBN", "Books.title", "Books.publisher", "Author.author_name", "Author.details"}, vector<string> {ISBN, title, publisher, author, author_details}, "Books.title = '" + toUpdate + "' or Books.ISBN = '" + toUpdate + "'");
}
}
void Remove()
{
string query;
cin.ignore();
cout << "Enter Book title or ISBN : ";
getline(cin, query);
db.Delete("Author", "Author join Books on Books.author_id = Author.id", "Books.title = '" + query + "' or Books.ISBN = '" + query + "'");
}
void Exit()
{
exit(0);
}
private:
bool isUserExist(string name, string password)
{
vector<vector<string>> res = db.select("users", "user_name, user_password");
for (size_t i = 0; i < res.size(); i++)
{
if (res[i][0] == name && res[i][1] == password)
return true;
}
return false;
}
};
| true |
273a5692fec9c9b21cc44c7655b18a6b7fc60023 | C++ | cristiano-xw/c-homework | /sixth/第四题.cpp | GB18030 | 2,326 | 3.1875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<math.h>
int main(void)
{
int a=0;
int b=0;
int c=0; //ֱ洢ʱ
//һʱַʽΪAA/BB/CC
//:MM/DD/YYYY/MM/DD.
scanf("%d/%d/%d",&a,&b,&c);//ÿִ洢ʡȥ0
//January, February, March, April, May, June, July, August, September, October, November December
if(a>=13) //ֻǵڶ YY/MM/DD.
{
if(b==1)
{
printf("January ");
}
if(b==2)
{
printf("February ");
}
if(b==3)
{
printf("March ");
}
if(b==4)
{
printf("April ");
}
if(b==5)
{
printf("May ");
}
if(b==6)
{
printf("June ");
}
if(b==7)
{
printf("July ");
}
if(b==8)
{
printf("August ");
}
if(b==9)
{
printf(" September ");
}
if(b==10)
{
printf("October ");
}
if(b==11)
{
printf("November ");
}
if(b==12)
{
printf("December ");
}
printf("%d",c);
printf(", ");
printf("20%d",a);
}
//:MM/DD/YYYY/MM/DD.
if(b>=13)
{
if(a==1)
{
printf("January ");
}
if(a==2)
{
printf("February ");
}
if(a==3)
{
printf("March ");
}
if(a==4)
{
printf("April ");
}
if(a==5)
{
printf("May ");
}
if(a==6)
{
printf("June ");
}
if(a==7)
{
printf("July ");
}
if(a==8)
{
printf("August ");
}
if(a==9)
{
printf(" September ");
}
if(a==10)
{
printf("October ");
}
if(a==11)
{
printf("November ");
}
if(a==12)
{
printf("December ");
}
printf("%d",b);
printf(", ");
printf("20%d",c);
}
if(a<=12&&b<=12) //ֶ
{
if(c==a)//ͬһ
{
if(a==b)//ͬһ
{
printf("%d",abs(b-c));
return 0;
}
}
int sum=0;
int max=0;
int min=0;
if(a>c)
{
max=a;
min=c;
}
if(a<c)
{
max=c;
min=a;
}
int j=0;int k=0; // ֻʼֹ֮
for(j=min+1;j<max;j++)
{
int v=0;
v=2000+j;
if(v%4==0)
{
k++;
}
}
if((max-min-1)>=0)
{
sum=(max-min-1)*365+k;//ݵʱֻꡣ
}
}
return 0;
}
| true |
3281d015be9674491358d4068ffaf985e1161e6e | C++ | RoshniPande/Competitive-Programming | /pset2/prob14_grains.cpp | UTF-8 | 437 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
long long int n,m;
cin>>n>>m;
if (n<=m)
{
cout<<n<<endl;
return 0;
}
else
{
long long int low=0,high=1e10;
while(low<high)
{
long long int mid=low+(high-low)/2,x=(mid*(mid+1))/2;
if (n-x > m)
{
low=mid+1;
}
else
{
high=mid;
}
}
cout<<m+low<<endl;
}
return 0;
} | true |
5d24a40b4147c3247e51829f4ee50efe1ff45dbf | C++ | Le0nRoy/StepicCppCourse | /src/headers/ScopedPtr.h | UTF-8 | 902 | 2.90625 | 3 | [] | no_license | //
// Created by lap on 9/25/20.
//
#ifndef TESTS_SCOPED_PTR_H
#define TESTS_SCOPED_PTR_H
#include "Expression.h"
struct Expression;
struct Number;
struct BinaryOperation;
struct ScopedPtr {
explicit ScopedPtr(Expression *ptr = 0) {
ptr_ = ptr;
}
~ScopedPtr() {
delete ptr_;
}
Expression *get() const {
return ptr_;
}
Expression *release() {
Expression *ptr = ptr_;
ptr_ = nullptr;
return ptr;
}
void reset(Expression *ptr = 0) {
delete ptr_;
ptr_ = ptr;
}
Expression &operator*() const {
return *ptr_;
}
Expression *operator->() const {
return ptr_;
}
private:
// запрещаем копирование ScopedPtr
ScopedPtr(const ScopedPtr &);
ScopedPtr &operator=(const ScopedPtr &);
Expression *ptr_;
};
#endif //TESTS_SCOPED_PTR_H
| true |
cd6cbf63b1c1dd370dbcbb6b6ab9a626fb040e8a | C++ | marcphilippebeaujean-abertay/archaic-arena | /projectile.h | UTF-8 | 801 | 2.703125 | 3 | [] | no_license | #pragma once
#include "game_object.h"
class projectile : public game_object
{
public:
projectile(sf::Vector2f colliderSize, LOOK_DIR initDir, int firedPlayerID, sf::Texture* fireTexture, sf::Vector2f boundryInfo, sf::Vector2f initPosition);
~projectile();
// functions
void update(float& delta_time) override;
// getters
bool isActive() { return active; }
int getOwner() { return ownerID; }
// setters
void deactivate() { active = false; }
private:
// speed that the projectile moves
const float speed = 100.0f;
// variable that indicates which player the projectile should ignore
int ownerID;
// variable used to determine whether the projectile should be rendered and updated
bool active;
// rate at which the fire animation should be played
const float fireAnimTime = 0.4f;
};
| true |
85750839189de32917dc8cd921aba14dc8b47a82 | C++ | hsj278/Scientific-Computing-Coursework | /lab04/fact.cpp | UTF-8 | 503 | 3.984375 | 4 | [] | no_license | #include <stdio.h>
long factorial(int n);
int main(){
int n;
printf("Enter an integer\n");
scanf("%i",&n);
printf("%i! = %ld\n",n,factorial(n));
return 0;
}
// recursive implementation of factorial algorithm
long factorial(int n){
long answer;
printf("factorial called w/ n = %i\n",n);
if (n < 2 ) answer = 1;
else {
printf("calling factorial(n-1)\n");
answer = (long)n * factorial(n-1);
}
printf("return value %ld from factorial(%i)\n", answer, n);
return answer;
}
| true |
ee500f9f1faa1261ac30a1b0f2d7af3726ec19f5 | C++ | suhyunch/shalstd | /BOJ/5000~/5622/src.cpp | UTF-8 | 386 | 2.9375 | 3 | [] | no_license | //https://www.acmicpc.net/problem/5622
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num;
cin >> num;
int x;
int l=num.size();
int sum=0;
for(int i=0; i<l; i++)
{
if(num[i]=='1') x=2;
else if(num[i]=='Z' ) x= 10;
else if((int)num[i]>='S') x= (num[i]-'A'-1)/3+3;
else x= (num[i]-'A')/3+3;
sum+=x;
}
cout << sum;
}
| true |