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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d29257a351e21480542a11b20ef42d7422f0620c | C++ | EntropyHaos/codebender_cleanup | /sketches/a_haos_infrared_linetracer/haos_smartcar_linetracer.cpp | UTF-8 | 3,716 | 2.734375 | 3 | [] | no_license | #include "Arduino.h"
#include "haos_smartcar_movement.h"
#include "haos_smartcar_infrared.h"
int main_loop_delay = 5; // = ms between chechs in the IR.
boolean move_wheels_for_reals = false;
boolean line_tracing;
boolean smartcar_is_still_learning_and_has_lost_his_way;
void move_car_for_line_tracing(int left_speed, int right_speed)
{
if (move_wheels_for_reals)
{
Serial.println("" + String(left_speed) + "/"+ "" + String(right_speed) + "");
move_car_analogue(left_speed, right_speed);
}
else
{
// Fake it. See notes on various ways to simulate all types of robotics.
//Serial.println("LT : " + String(left_speed) + " RT : " + String(right_speed) + "");
Serial.println("" + String(left_speed) + "/"+ "" + String(right_speed) + "");
}
}
void turn_on_some_line_tracing_please()
{
line_tracing = true;
//smartcar_is_still_learning_and_has_lost_his_way = false;
}
void turn_off_line_tracer()
{
line_tracing = false;
//smartcar_is_dumb_and_lost_his_way = false;
}
void line_trace_loop()
{
if (line_tracing == true)
{
unsigned char sensor_data = 0;
int the_readings[8]={0, 0, 0, 0, 0, 0, 0, 0};
infrared_sensor_read(the_readings);
for(int z = 0; z < 8; z++)
{
unsigned int val = the_readings[z];
sensor_data |= (val << z);
}
/*
for(int z = 0; z < 8; z++)
{
unsigned int val = digitalRead(SensorD[z]);
sensor_data |= (val << z);
}
*/
sensor_data = ~sensor_data;
//Serial.print(sensor_data, HEX);
//Serial.write(" ");
switch (sensor_data)
{
//our move forward situations.
case 0x18:
case 0x10:
case 0x08:
case 0x38:
case 0x1c:
case 0x3c:
move_car_for_line_tracing(150,150);
//status = "moving Forward";
break;
//our turn right situations.
case 0x0c:
case 0x04:
case 0x06:
case 0x0e:
case 0x1e:
case 0x0f:
move_car_for_line_tracing(75, 150);
//new_text_to_send = "Turn Right";
break;
//our turn left situations.
case 0x30:
case 0x20:
case 0x60:
case 0x70:
case 0x78:
case 0xf0:
//turn_left_speed(30, 75);
move_car_for_line_tracing(150, 75);
//new_text_to_send = "Turn Left";
break;
//our spin right situations.
case 0x07:
case 0x03:
case 0x02:
case 0x01:
move_car_for_line_tracing(-150, 150);
//new_text_to_send = "Pivot Right";
break;
//our spin left situations.
case 0xc0:
case 0x40:
case 0x80:
case 0xe0:
move_car_for_line_tracing(150, -150);
//new_text_to_send = "Pivot Left";
break;
case 0x00:
case 0xff:
//new_text_to_send = "No line to follow";
move_car_for_line_tracing(0, 0);
break;
default:
//new_text_to_send = "Hit Default";
move_car_for_line_tracing(0, 0);
break;
}
delay(main_loop_delay);
}
/*
if (new_text_to_send != stored_text_to_send)
{
stored_text_to_send = new_text_to_send;
Serial.print(stored_text_to_send);
}
*/
}
| true |
9876cc9b08895447796513039075a02fd494296e | C++ | yyqian/cpp-arsenal | /src/apue/file.cpp | UTF-8 | 749 | 2.953125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;
void print_file(const char *filename) {
struct stat f_stat;
stat(filename, &f_stat);
cout << "birth: " << endl;
if (S_ISCHR(f_stat.st_mode)) {
cout << "/dev/null is char special file" << endl;
}
}
int main(int argc, char **argv) {
cout << "Hello" << endl;
print_file("/dev/null");
if(link("/Users/yyqian/tst", "/Users/yyqian/tst_lnk") != 0) {
cout << "link failed" << endl;
}
//unlink("/Users/yyqian/ss");
symlink("/Users/yyqian/ss", "/Users/yyqian/ss_lnk");
char *buf = new char[100];
readlink("/Users/yyqian/ss_lnk", buf, 100);
cout << buf << endl;
delete[] buf;
return 0;
} | true |
b9750a4c573784a7eb81f1fee3fb440ad83cf0a0 | C++ | EhsanEsc/Netflip | /src/cp_password.cpp | UTF-8 | 528 | 2.734375 | 3 | [] | no_license |
#include "cp_password.h"
#include "md5.h"
using namespace std;
Password::Password(string ct,TYPE_NAME tp)
: Component(ct,tp)
{
if(validation() == false)
return;
set(ct);
raw_content = ct;
}
bool Password::validation() const { return true; }
string Password::get_value() const { return content; }
std::string Password::hash_password(std::string pass) { return md5(pass); }
void Password::edit(std::string ct) { content = ct; }
void Password::set(std::string ct) { content = hash_password(ct); }
| true |
0bc738a03045966d076e9c8c8c67825058804794 | C++ | ryuukk/arc_cpp | /arc/src/gfx/rendering/DefaultShaderProvider.h | UTF-8 | 3,318 | 2.59375 | 3 | [] | no_license | #pragma once
#include <utils/Format.h>
#include "BaseShaderProvider.h"
#include "DefaultShader.h"
namespace arc
{
class DefaultShaderProvider : public BaseShaderProvider
{
public:
DefaultShaderProvider(const std::string& vs, const std::string& fs)
{
config.vertexShader = vs;
config.fragmentShader = fs;
}
DefaultShader::Config config;
protected:
IShader* createShader(Renderable* renderable) override {
std::string prefix = createPrefix(*renderable, config);
std::string vs = "#version 330\n";
std::string fs = "#version 330\n";
vs.append(prefix).append("\n").append(config.vertexShader);
fs.append(prefix).append("\n").append(config.fragmentShader);
auto* program = new ShaderProgram(vs, fs);
Core::logger->infof("Compile new shader: {0} for renderable", program->isCompiled());
// todo: create prefix
return new DefaultShader(renderable, config, program);
}
private:
static std::string createPrefix(Renderable& renderable, const DefaultShader::Config& config)
{
auto& attributes = renderable.material;
auto attributesMask = attributes->getMask();
auto vertexMask = renderable.meshPart.mesh->getVertexAttributes()->getMask();
std::string builder{};
if (andd(vertexMask, VertexUsage::Position))
builder.append("#define positionFlag\n");
if (orr(vertexMask, VertexUsage::ColorUnpacked | VertexUsage::ColorPacked))
builder.append("#define colorFlag\n");
if (andd(vertexMask, VertexUsage::BiNormal))
builder.append("#define binormalFlag\n");
if (andd(vertexMask, VertexUsage::Tangent))
builder.append("#define tangentFlag\n");
if (andd(vertexMask, VertexUsage::Normal))
builder.append("#define normalFlag\n");
for (int i = 0; i < renderable.meshPart.mesh->getVertexAttributes()->size(); ++i) {
auto& attr = renderable.meshPart.mesh->getVertexAttributes()->get(i);
if (attr.usage == VertexUsage::BoneWeight)
builder.append("#define boneWeight").append(std::to_string(attr.unit).append("Flag\n"));
else if (attr.usage == VertexUsage::TextureCoordinates)
builder.append("#define texCoord").append(std::to_string(attr.unit).append("Flag\n"));
}
if(andd(attributesMask, DiffuseTextureAttribute::stype))
{
builder.append("#define ").append(DiffuseTextureAttribute::alias).append("Flag\n");
builder.append("#define ").append(DiffuseTextureAttribute::alias).append("Coord texCoord0\n");
}
if(config.numBones > 0 && !renderable.bones->empty())
builder.append("#define numBones ").append(std::to_string(config.numBones)).append("\n");
return builder;
}
static bool andd(uint64_t mask, uint64_t flag) {
return (mask & flag) == flag;
}
static bool orr(uint64_t mask, uint64_t flag) {
return (mask & flag) != 0;
}
};
} | true |
ae7f9d017c8776cda7a911112798dbd59b88bc59 | C++ | janniklaskeck/SolusEngine | /SolusEngine/AssetSystem/Asset.cpp | UTF-8 | 1,718 | 2.625 | 3 | [] | no_license | #include "Asset.h"
#include "AssetMeta.h"
#include "Engine/Engine.h"
#include "Utility/FileUtils.h"
#include "AssetSystem/SAsset.h"
namespace Solus
{
Asset::Asset()
{
}
Asset::Asset(const Asset& other)
{
asset = other.asset;
if (asset)
asset->Increment();
}
Asset::Asset(Asset&& other) noexcept
{
asset = other.asset;
other.asset = nullptr;
}
Asset::~Asset()
{
if (asset)
asset->Decrement();
}
void Asset::Set(SAsset* _asset)
{
if (asset != _asset)
{
if (asset)
asset->Decrement();
asset = _asset;
if (asset)
asset->Increment();
}
}
SAsset* Asset::Get() const
{
if (asset)
return asset;
return nullptr;
}
Asset& Asset::operator=(const Asset& other)
{
if (this != &other)
{
if (asset)
asset->Decrement();
asset = other.asset;
if (asset)
asset->Increment();
}
return *this;
}
Asset& Asset::operator=(Asset&& other) noexcept
{
if (this != &other)
{
if (asset)
asset->Decrement();
asset = other.asset;
other.asset = nullptr;
}
return *this;
}
Asset& Asset::operator=(SAsset* ptr)
{
if (asset)
asset->Decrement();
asset = ptr;
if (asset)
asset->Increment();
return *this;
}
SUUID Asset::GetId() const
{
if (asset)
return asset->GetAssetId();
return SUUID::DEFAULT;
}
bool Asset::IsValid() const
{
return asset;
}
SAsset* Asset::operator->() const
{
return asset;
}
SAsset& Asset::operator*() const
{
return *asset;
}
bool Asset::operator==(const Asset& other) const
{
return asset == other.asset;
}
bool Asset::operator!=(const Asset& other) const
{
return !(*this == other);
}
Asset::operator bool() const
{
return IsValid();
}
}
| true |
6425d92b1800b5bd8584f31c7cb4e6892328153e | C++ | Matt-Hoang/CECS-282-PA1-Solitaire-Prime | /PA1 - Solitaire Prime/Card.cpp | WINDOWS-1250 | 1,023 | 4.0625 | 4 | [] | no_license | #include <iostream>
#include "Card.h"
using namespace std;
// create a blank card
Card::Card()
{
rank = 'z';
suit = 'z';
}
// constructor to create a card, setting the rank and suit
Card::Card(char r, char s)
{
rank = r;
suit = s;
}
// set an existing blank card to a particular value
void Card::setCard(char r, char s)
{
rank = r;
suit = s;
}
// return the point value of the card.
int Card::getValue()
{
// value of A is 1
// T, J, Q, and K are all 10
// else card value is 'rank - 48' since type casting
// a char into an int gives a different value
int cardValue;
if (rank == 'A') {
cardValue = 1;
}
else if (rank == 'T' || rank == 'J' || rank == 'Q' || rank == 'K') {
cardValue = 10;
}
else {
cardValue = int (rank) - 48;
}
return cardValue;
}
// display the card using 2 fields
void Card::showCard()
{
// if rank is T display as 10 for legibility
// else display rank and suit
if (rank == 'T') {
cout << 10 << suit << ", ";
}
else
{
cout << rank << suit << ", ";
}
}
| true |
b5b5038a77ae5a4b94503c9c1d3a7fd7edb3aa16 | C++ | aigerard/cplusplus-coursera | /examples/8 - inheritance/main.cpp | UTF-8 | 391 | 2.84375 | 3 | [] | no_license | // simple classless executable with function.
#include <iostream>
#include "BaseClass.h"
using namespace ExampleNamespace;
int main() {
try {
ExampleNamespace::BaseClass bc;
bc.baseClassMethod();
bc.superClassMethod();
bc.superEquivalentMethod();
} catch (const std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0;
} | true |
2912c1d99e35ce6ca366fc52f83f03ca20a3f748 | C++ | ondesly/blocking_queue | /tests/test_multithreading.cpp | UTF-8 | 1,735 | 2.96875 | 3 | [
"BSD-2-Clause"
] | permissive | //
// test_multithreading.cpp
// blocking_queue
//
// Created by Dmitrii Torkhov <dmitriitorkhov@gmail.com> on 29.08.2021.
// Copyright © 2021 Dmitrii Torkhov. All rights reserved.
//
#include <chrono>
#include <numeric>
#include <random>
#include <thread>
#include <blocking_queue/blocking_queue.h>
namespace {
const auto c_data_len = 1000;
const auto c_producers_count = 100;
}
int main() {
std::vector<int> data(c_data_len);
std::random_device rd;
std::default_random_engine engine(rd());
std::generate(data.begin(), data.end(), std::ref(engine));
//
oo::blocking_queue<int> queue;
//
const auto producer_fn = [&]() {
for (size_t i = 0; i < c_data_len; ++i) {
const auto value = data[i];
queue.push(value);
if (i % 10 == 0) {
using namespace std::chrono_literals;
std::this_thread::sleep_for(5ms);
}
}
};
std::vector<std::shared_ptr<std::thread>> producers;
for (size_t i = 0; i < c_producers_count; ++i) {
producers.push_back(std::make_shared<std::thread>(producer_fn));
}
//
std::vector<int> result;
const auto consumer_fn = [&]() {
while (!queue.is_done()) {
const auto i = queue.pop();
result.push_back(i);
}
};
std::thread consumer{consumer_fn};
//
for (const auto &producer: producers) {
producer->join();
}
queue.set_done();
//
consumer.join();
//
const auto data_sum = std::accumulate(data.begin(), data.end(), 0LL);
const auto result_sum = std::accumulate(result.begin(), result.end(), 0LL);
//
return result_sum == data_sum * c_producers_count ? 0 : 1;
} | true |
e77c941c258d3b381a06b4e1663a222894a46b89 | C++ | TekatoD/controller_crutches | /src/config/arguments_parser_t.cpp | UTF-8 | 2,162 | 2.90625 | 3 | [] | no_license | /*!
* \autor arssivka
* \date 10/27/17
*/
#include <log/trivial_logger_t.h>
#include "config/arguments_parser_t.h"
using namespace drwn;
arguments_parser_t::arguments_parser_t(std::string caption)
: m_caption(std::move(caption)) {}
void arguments_parser_t::add_strategy(arguments_parsing_strategy_t& strategy) {
m_strategies.push_back(&strategy);
}
void arguments_parser_t::remove_strategy(const arguments_parsing_strategy_t& strategy) {
m_strategies.remove((arguments_parsing_strategy_t*) &strategy);
}
bool arguments_parser_t::parse() {
namespace po = boost::program_options;
try {
auto desk = generate_option_description();
po::variables_map vm;
po::store(po::command_line_parser(m_arguments.get_argc(), m_arguments.get_argv())
.options(desk)
.allow_unregistered()
.run(), vm);
po::notify(vm);
apply_variables_map(vm);
} catch (const boost::program_options::error& e) {
LOG_ERROR << "Can't parse command line arguments: " << e.what();
return false;
}
return true;
}
boost::program_options::options_description arguments_parser_t::generate_option_description() const {
boost::program_options::options_description desk(m_caption);
for (auto& strategy : m_strategies) {
strategy->define_description(desk);
}
return desk;
}
void arguments_parser_t::apply_variables_map(const boost::program_options::variables_map& vm) {
for (auto& strategy : m_strategies) {
strategy->apply_variables(vm);
}
}
const std::string& arguments_parser_t::get_caption() const noexcept {
return m_caption;
}
void arguments_parser_t::set_caption(const std::string& caption) {
m_caption = caption;
}
void arguments_parser_t::show_description_to_stream(std::ostream& stream) const {
stream << generate_option_description();
}
const command_arguments_t& arguments_parser_t::get_arguments() const noexcept {
return m_arguments;
}
void arguments_parser_t::set_arguments(const command_arguments_t& arguments) noexcept {
m_arguments = arguments;
}
| true |
a90211b0f295fb1874c63ceb83078790610d1dbf | C++ | nika500/HLSLibrary | /elemstream.hpp | UTF-8 | 3,354 | 2.703125 | 3 | [
"ISC"
] | permissive | /**
* @file elemstream.hpp
* @brief A container for an elementary stream from a file container
*
* @copyright Copyright 2015 Samir Sinha. All rights reserved.
* @license This project is released under the ISC license. See LICENSE
* for the full text.
*/
#ifndef CINEK_AVLIB_ELEMENTARY_STREAM_HPP
#define CINEK_AVLIB_ELEMENTARY_STREAM_HPP
#include "avlib.hpp"
#if CINEK_AVLIB_IOSTREAMS
#include <ostream>
#endif
namespace cinekav {
struct ESAccessUnit
{
const uint8_t* data;
size_t dataSize;
uint64_t pts;
uint64_t dts;
};
class ElementaryStream
{
public:
enum Type
{
kNull = 0x00,
kAudio_AAC = 0x0f,
kVideo_H264 = 0x1b
};
ElementaryStream();
ElementaryStream(Buffer&& buffer, Type type, uint16_t progId, uint8_t index,
const Memory& memory=Memory());
ElementaryStream(ElementaryStream&& other);
ElementaryStream& operator=(ElementaryStream&& other);
~ElementaryStream();
operator bool() const { return _type != kNull; }
Type type() const { return _type; }
uint16_t programId() const { return _progId; }
uint8_t index() const { return _index; }
const Buffer& buffer() const { return _buffer; }
uint32_t appendPayload(Buffer& source, uint32_t len, bool pesStart);
#if CINEK_AVLIB_IOSTREAMS
std::basic_ostream<char>& write(std::basic_ostream<char>& ostr) const;
#endif
void updateStreamId(uint8_t streamId) { _streamId = streamId; }
void updatePts(uint64_t pts);
void updatePtsDts(uint64_t pts, uint64_t dts);
ESAccessUnit* accessUnit(size_t index);
size_t accessUnitCount() const { return _ESAccessUnitCount; }
private:
void freeESAUBatches();
Memory _memory;
Buffer _buffer;
Type _type;
uint16_t _progId;
uint8_t _index;
uint8_t _streamId;
uint64_t _dts;
uint64_t _pts;
// todo - should be a parameter in the constructor
// this value allows for ~ 10 second long streams with 29.97 fps.
//
static const size_t kAccessUnitCount = 384;
// a growing, segmented vector (a primitive deque, etc.)
struct ESAccessUnitBatch
{
ESAccessUnit* head;
ESAccessUnit* tail;
ESAccessUnit* limit;
ESAccessUnitBatch* nextBatch;
ESAccessUnitBatch() :
head(nullptr), tail(nullptr), limit(nullptr),
nextBatch(nullptr) {}
};
ESAccessUnitBatch* _ESAUBatch;
size_t _ESAccessUnitCount;
// access unit parsing state
struct ESAccessUnitParserState
{
const uint8_t* head;
const uint8_t* tail;
const uint8_t* auStart;
bool VCLcheck;
ESAccessUnitParserState() :
head(nullptr), tail(nullptr), auStart(nullptr),
VCLcheck(false) {}
};
ESAccessUnitParserState _parser;
void appendAccessUnit(const uint8_t* data, size_t size);
void parseH264Stream();
};
}
#endif
| true |
360458a7dc39d9c7816a89af60f7aa2ebdbaacbb | C++ | jinbeomdev/daily-algorithm-problems | /[BOJ]12906.cc | UTF-8 | 1,352 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include <array>
#include <map>
#include <string>
#include <queue>
#include <iostream>
using namespace std;
int main() {
array<string, 3> a;
for(int i = 0; i < 3; i++) {
int cnt;
scanf("%d", &cnt);
if(cnt > 0) {
cin >> a[i];
} else {
a[i] = "";
}
}
int cnt[3] = {0, 0, 0};
for(int i = 0; i < 3; i++) {
for(int j = 0; j < a[i].size(); j++) {
cnt[a[i][j] - 'A']++;
}
}
map<array<string, 3>, int> d;
queue<array<string, 3>> q;
q.push(a);
d[a] = 0;
while(!q.empty()) {
array<string, 3> here = q.front();
q.pop();
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i == j) continue;
if(here[i].length() == 0) continue;
array<string, 3> next(here);
next[j].push_back(here[i].back());
next[i].pop_back();
if(d.count(next) == 0) {
d[next] = d[here] + 1;
q.push(next);
}
}
}
}
array<string, 3> ans;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < cnt[i]; j++) {
ans[i] += (char)('A' + i);
}
}
cout << d[ans] << '\n';
return 0;
} | true |
fc45750ce7bae4a1bf110c3b81a1772aa7eef934 | C++ | minoof/CN_Switch | /Ethernet.cpp | UTF-8 | 1,176 | 3.25 | 3 | [] | no_license | #include <iostream>
#include "Ethernet.h"
using namespace std;
Ethernet::Ethernet(string inputName){
name = inputName;
vlan = 1;
allocated = false;
fd = -1;
ip = "None";
subnet = 0;
mac = "None";
}
Ethernet::~Ethernet(){
name = "";
ip = "None";
subnet = 0;
mac = "None";
vlan = 0;
allocated = false;
fd = -1;
}
string Ethernet::get_name(){
return name;
}
bool Ethernet::set_ip(string inputIP){
ip = inputIP;
return true;
}
string Ethernet::get_ip(){
return ip;
}
bool Ethernet::set_subnet(int inputSubnet){
subnet = inputSubnet;
return true;
}
int Ethernet::get_subnet(){
return subnet;
}
bool Ethernet::set_mac(string inputMac){
mac = inputMac;
return true;
}
string Ethernet::get_mac(){
return mac;
}
bool Ethernet::set(int inputVlan){
vlan = inputVlan;
return true;
}
int Ethernet::get_vlan(){
return vlan;
}
bool Ethernet::is_allocated(){
return allocated;
}
bool Ethernet::set_allocate(string status){
if (status == "busy")
allocated = true;
else if (status == "free")
allocated = false;
else return false;
return true;
}
bool Ethernet::set_fd(int inputFd){
fd = inputFd;
return true;
}
int Ethernet::get_fd(){
return fd;
} | true |
0baa4a536003ac04af0dd4aee9a252918ab6c73b | C++ | rubis-lab/DroneTransferSimulator | /Drone.h | UTF-8 | 409 | 2.734375 | 3 | [] | no_license | #ifndef _H_DRONE_
#define _H_DRONE_
#include <utility>
#include "Time.h"
class Drone
{
private:
double battery, chargingRate; /* unit: percent */
double availDist, maxAvailDist; /* available distance of Drone */
std::pair<double, double> destination;
public:
Drone(double _maxAvilDist);
void fly(double distance);
void updateBattery(Time startTime, Time endTime);
double returnAvailDist();
};
#endif | true |
42387732e56cca77b7f9bdadc238480a8253243e | C++ | rthomas015/robertthomas-CSCI21-Spring2018 | /Project_2_Part_C/tournament/stack.h | UTF-8 | 463 | 2.921875 | 3 | [] | no_license | /*
*/
#ifndef stack_h
#define stack_h
#include "node.h"
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
template <class T>
class Stack {
private:
Node<T>* head;
Node<T>* tail;
public:
Stack();
~Stack();
int size ();
string print ();
void pop ();
void push (T name);
T peek_name();
};
#endif | true |
2b863c3b667401128302c45cc641cb9e616dda5b | C++ | shailesh1001/uva-solutions-1 | /uva12210/uva12210.cpp | UTF-8 | 1,870 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <sstream>
#include <set>
#include <iomanip>
#include <list>
#include <stack>
#include <queue>
#include <bitset>
#include <numeric>
#include <cstdio>
#include <cmath>
#include <climits>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;
typedef vector<int> vi;
typedef set<int> si;
int main(int argc, char* argv[])
{
int B,S;
int t=1;
while (cin>>B>>S && B && S) {
//input and sort right away:
multiset<int,greater<int> > bachelors;
multiset<int> spinsters;
for (int i=0;i<B;++i) {
int age; cin>>age; bachelors.insert(age);
}
for (int i=0;i<S;++i) {
int age; cin>>age; spinsters.insert(age);
}
//cout<<"bachelors.size()="<<bachelors.size()<<endl;
//either bachelors or spinsters will exhaust
while (bachelors.size() && spinsters.size()) {
int age = *(bachelors.begin());
si::iterator s_it = spinsters.lower_bound(age);
if (s_it==spinsters.end()) {
--s_it;
} else if (s_it!=spinsters.begin()) {
//let's check with the previous
si::iterator prev = s_it; --prev;
if (abs(age-*prev)<abs(age-*s_it)) {
s_it = prev;
}
}
//cout<<"erasing: b="<<*(bachelors.begin())<<" s="<<*s_it<<endl;
bachelors.erase(bachelors.begin());
spinsters.erase(s_it);
}
//prepare result:
int bachelors_left = bachelors.size();
int yongest_age = 0;
if (bachelors_left) {
si::iterator last = bachelors.end();
--last;
yongest_age = *last;
}
//output result:
cout<<"Case "<<t++<<": "<<bachelors_left;
if (bachelors_left>0) {
cout<<" "<<yongest_age;
}
cout<<endl;
}
return 0;
} | true |
e43205f3f8cbd849c95d579e3818a27d0cd2e5dc | C++ | cqiyi/kaoshi | /01_数据结构/exam001/test02/test02.cpp | GB18030 | 2,121 | 3.75 | 4 | [] | no_license | /*
1ͼڽӾΪn i1 j1 i2 j2 i3.....-1 -1þʾͼnǶ30 > n > 0,ĶСnҴڵ0
*/
#include <iostream.h>
#include <stdlib.h>
void exit(int);
#define MAX_NODE 30
int arc[MAX_NODE][MAX_NODE]= {0};
int list[MAX_NODE]= {0};
int n,index = 0;
void showMGraph()
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout<<arc[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
//ǷָNodeIDڵı()
bool hasInRoad(int nodeID)
{
for(int i=0; i<n; i++)
{
if(arc[i][nodeID] == 1) return true;
}
return false;
}
//ͼƳýڵ㣬Ƴ˵Ľڵ㣬ֵΪ-1
void removeNode(int nodeID)
{
for(int j=0; j<n; j++)
{
arc[nodeID][j] = -1;
}
}
void showList()
{
//
cout<<":"<<endl;
for(int i=0; i<n; i++)
{
cout<<"V"<<list[i]<<" ";
}
cout<<endl;
}
void main()
{
cout<<"ͼĽڵ㣬-1,-1:"<<endl;
int i,j;
while(true)
{
cin>>i>>j;
if(i==-1 && j==-1) break;
if(i<0 || j<0)
{
cout<<""<<endl;
exit(1);
}
arc[i][j] = 1;
cout<<endl;
}
cout<<"ڵ(1~"<<MAX_NODE<<"):"<<endl;
cin>>n;
if(n<1 || n>MAX_NODE)
{
cout<<",ڵ1"<<MAX_NODE<<"֮"<<endl;
exit(1);
}
cout<<"ڽӾ£"<<endl;
showMGraph();
//
while(true)
{
//ʣĽڵ㶼û
bool flag = true;
for(int i=0; i<n; i++)
{
//ѱƳߴȵĽڵ
if((arc[i][i] == -1) || hasInRoad(i)) continue;
//һȣ費
flag = false;
//ýڵû
list[index++] = i;
removeNode(i);
//нڵ㶼Ѿ
if(index>=n)
{
showList();
return;
}
}
if(flag)
{
cout<<"ͼл."<<endl;
exit(2);
}
}
} | true |
ebb942b620f2223aeb48f8bfe4f2b836d78a08c9 | C++ | frontalnh/data-structure | /sort/insertionSort/insertionSort.cpp | UTF-8 | 1,045 | 3.9375 | 4 | [] | no_license | #include "SortHelper.h"
#include <iostream>
using namespace std;
void SortHelper::insert(Element elements[], Element element, int index)
{
for (int i = index; i > 0; i--)
{
if (elements[i - 1].value > element.value)
{
elements[i] = elements[i - 1];
}
else
{
elements[i] = element;
return;
}
}
elements[0] = element;
}
void SortHelper::insertionSort(Element elements[], int count)
{
for (int i = 0; i < count; i++)
{
insert(elements, elements[i], i);
}
}
int main(void)
{
SortHelper sortHelper;
Element element1 = {"1", 1};
Element element2 = {"2", 2};
Element element3 = {"3", 3};
Element element4 = {"4", 4};
Element elements2[4] = {element4, element2, element3, element1};
sortHelper.insertionSort(elements2, 4);
cout << "insertion sorting has been completed. elements: " << endl;
for (int i = 0; i < 4; i++)
{
cout << elements2[i].value << endl;
}
return 0;
} | true |
0ac5333f37eac40bd823bed33fdaee4354e692be | C++ | ly774508966/fvision2010 | /modules/geom/include/fvision/geom/pointpair.h | UTF-8 | 1,656 | 2.609375 | 3 | [] | no_license | #ifndef FVISION_POINT_PAIR_H_
#define FVISION_POINT_PAIR_H_
#include <cv.h>
#include <utility>
#include <vector>
#include <iosfwd>
namespace fvision {
typedef std::pair<CvPoint2D32f, CvPoint2D32f> PointPair;
typedef std::vector<PointPair> PointPairs;
typedef std::pair<CvPoint, CvPoint> PointIntPair;
typedef std::vector<PointIntPair> PointIntPairs;
std::vector<CvPoint2D32f> getFirstPoints(const PointPairs& pps);
void decomposePointPairs(const PointPairs& pps, std::vector<CvPoint2D32f>& x1s, std::vector<CvPoint2D32f>& x2s);
void composePointPairs(PointPairs& pps, const std::vector<CvPoint2D32f>& x1s, const std::vector<CvPoint2D32f>& x2s);
std::vector<CvPoint2D32f> getDisparities(const PointPairs& pps);
PointPairs getSubSet(const PointPairs& pps, const std::vector<int>& indices);
template <typename UnaryOperator>
void transformPointPairs(PointPairs& pps, const UnaryOperator& op) {
PointPairs::iterator iter = pps.begin();
for (; iter != pps.end(); iter++) {
iter->first = op(iter->first);
iter->second = op(iter->second);
}
}
template <typename UnaryOperator>
void copyTransformPointPairs(const PointPairs& src, PointPairs& dst, const UnaryOperator& op) {
assert(src.size() == dst.size());
PointPairs::const_iterator iter = src.begin();
PointPairs::iterator dstIter = dst.begin();
for (; iter != src.end(); iter++, dstIter++) {
dstIter->first = op(iter->first);
dstIter->second = op(iter->second);
}
}
std::ostream& operator<<(std::ostream& os, const PointPairs& pps);
std::istream& operator>>(std::istream& is, PointPairs& pps);
}
#endif // FVISION_POINT_PAIR_H_
| true |
8879bef533559d6346caa72a17892393b8b42628 | C++ | slmcbane/Galerkin | /src/Rationals.hpp | UTF-8 | 10,300 | 3.125 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2019, Sean McBane
* This file is part of the Galerkin library; Galerkin is copyright under the
* terms of the MIT license. Please see the top-level COPYRIGHT file for details.
*/
#ifndef RATIONALS_HPP
#define RATIONALS_HPP
/*!
* @file Rationals.hpp
* @brief Compile-time computations with rational numbers.
* @author Sean McBane <sean.mcbane@protonmail.com>
*/
#include <cstdint>
#include <type_traits>
#include "utils.hpp"
namespace Galerkin
{
/// The `Rationals` namespace encapsulates all of the functionality for rational numbers
namespace Rationals
{
/*!
* @brief The type used for the numerator in a rational. On gcc or clang this
* could be made a int128_t, but in practice compiler limits will be reached
* before overflow, anyway. Should be a signed type.
*/
typedef int64_t rational_num_t;
/// The type used for the denominator in a rational. Should be an unsigned type.
typedef uint64_t rational_den_t;
/*!
* @brief Type representing a rational number at compile time.
*
* `Rational` is used to do exact calculations of derivatives, Jacobians, etc.
* by manipulating rational numbers at compile time. The normal arithmetic
* operators are all defined for it, and it decays to a `double` as appropriate.
* Rather than use this class template, however, you should use the `rational`
* template constant from this header; instantiating `rational<N, D>`
* automatically reduces the resulting fraction to its simplest form.
*/
template <rational_num_t Num, rational_den_t Den>
struct Rational
{
static_assert(Den != zero<rational_den_t>);
/// Get the numerator
static constexpr auto num() { return Num; }
/// Get the denominator
static constexpr auto den() { return Den; }
/*! @brief Convert the number to a double precision float, for when you have to
* do inexact floating point operations or run-time computation :(.
*/
constexpr operator double() const
{
return static_cast<double>(Num) / Den;
}
};
template <class T>
constexpr bool is_rational = false;
template <rational_num_t N, rational_den_t D>
constexpr bool is_rational<Rational<N, D>> = true;
/*!
* @brief Utility; find greatest common denominator of `a` and `b`. This will hit
* `constexpr` evaluation limits when `a` or `b` becomes large relative to the
* other.
*/
constexpr auto gcd(rational_num_t a, rational_den_t b)
{
if (a < 0)
{
a = -a;
}
auto x = static_cast<rational_den_t>(a);
auto y = x > b ? b : x;
x = x > b ? x : b;
if (y == 0)
{
return x;
}
while (x != y)
{
x = x - y;
if (y > x)
{
auto tmp = y;
y = x;
x = tmp;
}
}
return x;
}
/// Reduce a rational number to its simplest representation.
template <rational_num_t N, rational_den_t D>
constexpr auto reduce_rational(Rational<N, D>)
{
constexpr auto div = gcd(N, D);
return Rational<N / static_cast<rational_num_t>(div), D / div>();
}
/*!
* @brief Template constant for a compile-time rational.
*
* This constant evaluates to a `Rational` reduced to its lowest terms. Default
* denominator is 1, so that an integer can be constructed by `rational<n>`.
*
* @tparam N The numerator
* @tparam D The denominator. Default value: 1
*/
template <rational_num_t N, rational_den_t D = 1>
constexpr auto rational = reduce_rational(Rational<N, D>());
template <auto N1, auto D1, auto N2, auto D2>
constexpr bool operator==(Rational<N1, D1>, Rational<N2, D2>)
{
return std::is_same_v<decltype(rational<N1, D1>), decltype(rational<N2, D2>)>;
}
/********************************************************************************
* Tests of rational construction
*******************************************************************************/
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("[Galerkin::Rationals] Testing construction of rationals")
{
REQUIRE(rational<1> == rational<2, 2>);
REQUIRE(rational<-2, 2> == rational<-42, 42>);
REQUIRE(rational<2, 4> == rational<1, 2>);
REQUIRE(rational<4, 2> == rational<2, 1>);
REQUIRE(rational<-1, 3> == rational<-6, 18>);
// This should trigger a static assert
// REQUIRE(rational<1, 0> == rational<0, 1>);
}
#endif /* DOCTEST_LIBRARY_INCLUDED */
/********************************************************************************
*******************************************************************************/
template <auto N1, auto D1, auto N2, auto D2>
constexpr auto operator+(Rational<N1, D1>, Rational<N2, D2>)
{
constexpr auto lcm = D1 * D2 / gcd(D1, D2);
constexpr auto mult1 = static_cast<rational_num_t>(lcm / D1);
constexpr auto mult2 = static_cast<rational_num_t>(lcm / D2);
return rational<N1*mult1 + N2*mult2, D1*mult1>;
}
/********************************************************************************
* Tests of rational addition
*******************************************************************************/
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("[Galerkin::Rationals] Testing rational addition")
{
REQUIRE(rational<1> + rational<2> == rational<3>);
REQUIRE(rational<1, 2> + rational<1, 3> == rational<5, 6>);
REQUIRE(rational<5, 6> + rational<1, 6> == rational<1>);
REQUIRE(rational<5, 8> + rational<22, 16> == rational<2>);
REQUIRE(rational<1, 3> + rational<3, 1> == rational<10, 3>);
}
#endif /* DOCTEST_LIBRARY_INCLUDED */
/********************************************************************************
*******************************************************************************/
template <auto N1, auto D1>
constexpr auto operator-(Rational<N1, D1>)
{
return rational<-N1, D1>;
}
template <auto N1, auto D1, auto N2, auto D2>
constexpr auto operator-(Rational<N1, D1>, Rational<N2, D2>)
{
return Rational<N1, D1>() + (-Rational<N2, D2>());
}
/********************************************************************************
* Tests of rational subtraction and negation.
*******************************************************************************/
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("[Galerkin::Rationals] Testing rational subtraction")
{
REQUIRE(rational<1> - rational<2> == rational<-1>);
REQUIRE(rational<1, 2> - rational<1, 3> == rational<1, 6>);
REQUIRE(rational<5, 6> - rational<1, 6> == rational<2, 3>);
REQUIRE(rational<5, 8> - rational<22, 16> == rational<-3, 4>);
REQUIRE(rational<1, 3> - rational<3, 1> == rational<-8, 3>);
}
#endif /* DOCTEST_LIBRARY_INCLUDED */
/********************************************************************************
*******************************************************************************/
template <auto N1, auto D1, auto N2, auto D2>
constexpr auto operator*(Rational<N1, D1>, Rational<N2, D2>)
{
return rational<N1*N2, D1*D2>;
}
template <auto N1, auto D1, auto N2, auto D2>
constexpr auto operator/(Rational<N1, D1>, Rational<N2, D2>)
{
constexpr auto num = N1 * static_cast<rational_num_t>(D2);
if constexpr (N2 < 0)
{
return -rational<num, D1 * static_cast<rational_den_t>(-N2)>;
}
else
{
return rational<num, D1 * static_cast<rational_den_t>(N2)>;
}
}
/// A `Rational` * an `integral_constant` returns a `Rational`.
template <auto N, auto D, class I, I v>
constexpr auto operator*(Rational<N, D>, std::integral_constant<I, v>) noexcept
{
return rational<N, D> * rational<v>;
}
template <auto N, auto D, class I, I v>
constexpr auto operator*(std::integral_constant<I, v>, Rational<N, D>) noexcept
{
return rational<N, D> * rational<v>;
}
/// A `Rational` / an `integral_constant` returns a `Rational`.
template <auto N, auto D, class I, I v>
constexpr auto operator/(Rational<N, D>, std::integral_constant<I, v>)
{
static_assert(v != 0);
if constexpr (v < 0)
{
return -(rational<N, D> / std::integral_constant<I, -v>());
}
else
{
return rational<N, D> / rational<v>;
}
}
template <auto N, auto D, class T>
constexpr auto operator*(Rational<N, D>, T x)
{
if constexpr (std::is_same_v<T, float>)
{
return (N * x) / D;
}
else
{
return (N * static_cast<double>(x)) / D;
}
}
template <auto N, auto D, class T>
constexpr auto operator/(Rational<N, D>, T x)
{
if constexpr (std::is_same_v<T, float>)
{
return N / (D * x);
}
else
{
return N / (D * static_cast<double>(x));
}
}
/********************************************************************************
* Tests of rational multiplication and division.
*******************************************************************************/
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("[Galerkin::Rationals] Testing rational multiplication and division")
{
REQUIRE(rational<1, 2> * rational<1, 2> == rational<1, 4>);
REQUIRE(rational<1, 2> * rational<1, 3> == rational<1, 3> * rational<1, 2>);
REQUIRE(rational<1, 2> * rational<1, 3> == rational<1, 6>);
REQUIRE(rational<3, 10> * rational<1, 3> == rational<1, 10>);
REQUIRE(rational<3, 10> * rational<-1, 3> == rational<-1, 10>);
REQUIRE(rational<1, 2> / rational<1, 2> == rational<1>);
REQUIRE(rational<1, 2> / rational<2> == rational<1, 4>);
REQUIRE(rational<3, 10> / rational<1, 3> == rational<9, 10>);
REQUIRE(rational<1, 6> / rational<1, 3> == rational<1, 2>);
REQUIRE(rational<1, 6> / rational<1, 2> == rational<1, 3>);
REQUIRE(rational<3, 10> / rational<-1, 3> == rational<-9, 10>);
REQUIRE(rational<3, 10> / std::integral_constant<int, 3>() == rational<1, 10>);
REQUIRE(rational<1, 6> * std::integral_constant<int, 3>() == rational<1, 2>);
REQUIRE(rational<1, 6> / std::integral_constant<int, -2>() == rational<-1, 12>);
REQUIRE(rational<1, 2> * 0.5 == doctest::Approx(0.25));
REQUIRE(rational<1, 2> / 3 == doctest::Approx(1.0 / 6));
REQUIRE(std::is_same_v<
decltype(rational<1, 2> * std::declval<float>()), float>);
}
#endif /* DOCTEST_LIBRARY_INCLUDED */
/********************************************************************************
*******************************************************************************/
} // namespace Rationals
} // namespace Galerkin
#endif /* RATIONALS_HPP */ | true |
fb3ee161f27eab8e320f5da465405ccfb37092d5 | C++ | ayoubEL-MOUTAOUAKKIL/fuzzy | /fuzzy/domain/categorie/CategoryFactory.cpp | UTF-8 | 729 | 2.9375 | 3 | [] | no_license | #include "CategoryFactory.h"
#include "City.h"
#include "Sports.h"
#include "Suv.h"
#include "Utilitary.h"
#include "Electric.h"
namespace domain {
const std::string CITY = "citadine";
const std::string SPORT = "sportive";
const std::string SUV = "suv";
const std::string ELECTRIC = "electrique";
const std::string UTILITARY = "utilitaire";
Category domain::CategoryFactory::createCategory(const std::string _categoryType)
{
if (_categoryType.compare(CITY)) return City();
if (_categoryType.compare(SPORT)) return Sports();
if (_categoryType.compare(SUV)) return Suv();
if (_categoryType.compare(ELECTRIC)) return Electric();
if (_categoryType.compare(UTILITARY)) return Utilitary();
return Category();
}
} | true |
37df60d0e1cd2c2749f56e97cdd9d08da0c05f79 | C++ | paulkim1997/MY_Programmers | /오답노트/(오답노트)삼각 달팽이.cpp | UTF-8 | 1,660 | 3.140625 | 3 | [] | no_license | //문제 보자마자 든 생각: 사각 달팽이 수열도 못하는데... 이걸 어떻게 하누
//딱봐도 알고리즘/자료구조 없이 구현력 원하는 문제 같음
//삼각 달팽이 말고 그냥 2차원 배열 써서 계단 모양 만들것임
//n=4 라고 치면
//1
//2 9
//3 10 8
//4 5 6 7 이렇게!
#include <bits/stdc++.h>
using namespace std;
int board[1001][1001];
vector<int> solution(int n) {
vector<int> answer;
//d 면 down 아래로, r 이면 right 오른쪽, u 면 up 위로
char position = 'd';
int x = 0;
int y=0;
int num = 1;
for(int i=n;i>0;i--) {
for(int j=0;j<i;j++) {
if(position =='d') {
board[x][y] = num;
x++;
num++;
} else if(position == 'r') {
board[x][y] = num;
y++;
num++;
} else if(position == 'u') {
board[x][y] = num;
x--;
y--;
num++;
}
}
if(position == 'd') {
position = 'r';
x--;
y++;
} else if(position == 'r') {
position = 'u';
x--;
y-=2;
} else if(position == 'u') {
position = 'd';
y++;
x+=2;
}
}
for(int i=0;i<1001;i++) {
for(int j=0;j<1001;j++){
if(board[i][j] > 0) {
answer.push_back(board[i][j]);
}
}
}
return answer;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solution(4);
}
| true |
2cd301390d27cee3ebf66375606ed2df15b4ad18 | C++ | hundeboll/bronco | /src/nc/nc.cpp | UTF-8 | 3,291 | 2.578125 | 3 | [] | no_license | /* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <signal.h>
#include <string>
#include <inttypes.h>
#include <cstdlib>
#include <cstdarg>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <ncurses.h>
#include "peermanager.hpp"
#define HEADER_HEIGHT 2
#define FILE_HEIGHT 3
bronco::peermanager *manager_ptr;
WINDOW *header_win, *file_win, *info_win;
void cleanup_and_exit(int status)
{
/* Finalize ncurses */
endwin();
/* Stop peermanager */
if (manager_ptr != NULL)
manager_ptr->close();
exit(status);
}
void signal_close(int not_used)
{
cleanup_and_exit(EXIT_SUCCESS);
}
int info_printf(const char *format, ...)
{
va_list ap;
va_start(ap, format);
int ret = vwprintw(info_win, format, ap);
wrefresh(info_win);
va_end(ap);
return ret;
}
void update_windows(uint32_t *maxy, uint32_t *maxx)
{
/* Get screen dimensions */
getmaxyx(stdscr, *maxy, *maxx);
/* Update window dimensions */
wresize(header_win, HEADER_HEIGHT, *maxx);
wresize(file_win, FILE_HEIGHT, *maxx);
wresize(info_win, *maxy-HEADER_HEIGHT-FILE_HEIGHT, *maxx);
mvwin(header_win, 0, 0);
mvwin(file_win, HEADER_HEIGHT, 0);
mvwin(info_win, HEADER_HEIGHT+FILE_HEIGHT, 0);
/* Refresh windows */
wrefresh(header_win);
wrefresh(file_win);
wrefresh(info_win);
}
int main(int argc, char **argv)
{
std::string header = "*** BRONCO v0.1 ***";
/* Read arguments */
if (argc != 2) {
printf("Announce: %s --announce <path-to-file> bronco://<host>[:<port>]\n", argv[0]);
printf(" Join: %s bronco://<host>[:<port>]/<content_id>\n", argv[0]);
cleanup_and_exit(EXIT_FAILURE);
}
/* Set signal handlers */
signal(SIGINT, signal_close);
signal(SIGTERM, signal_close);
signal(SIGHUP, signal_close);
/* Initialize ncurses */
initscr();
/* Get screen dimensions */
uint32_t maxy = 0;
uint32_t maxx = 0;
getmaxyx(stdscr, maxy, maxx);
/* Create windows */
header_win = newwin(HEADER_HEIGHT, maxx, 0, 0);
file_win = newwin(FILE_HEIGHT, maxx, HEADER_HEIGHT, 0);
info_win = newwin(maxy-HEADER_HEIGHT-FILE_HEIGHT, maxx, HEADER_HEIGHT+FILE_HEIGHT, 0);
/* Set ncurses options */
noecho();
curs_set(0);
halfdelay(5);
keypad(stdscr, TRUE);
scrollok(info_win, TRUE);
/* Create peer manager */
struct bronco::peermanager::peer_config c = {10, 10, 5, "localhost", bronco::peermanager::select_port()};
struct bronco::peermanager::nc_parameters p = {"bin/bronco-nc", 512, 400};
manager_ptr = new bronco::peermanager(argv[1], &c, &p, &info_printf);
/* Screen update loop */
while (1) {
/* Write content */
wclear(header_win);
wclear(file_win);
mvwprintw(header_win, 0, (maxx - header.size())/2, header.c_str());
mvwprintw(file_win, 0, 0, " Anders_Bech_-_Store_patter_betyder_undskyld.mp3\n [##### ]");
/* Resize and refresh windows */
update_windows(&maxy, &maxx);
/* Wait for keypress or timeout */
int key = wgetch(info_win);
if (key != ERR)
info_printf("Key pressed!\n");
}
/* Finalize */
cleanup_and_exit(EXIT_SUCCESS);
return 0;
}
| true |
fc47e826f4560f4be8659f24c138d873bf4ccfa2 | C++ | jeremylorino/arduino-chess-clock | /libraries/ChessPlayerTimer.cpp | UTF-8 | 1,980 | 3.0625 | 3 | [] | no_license |
#include "Arduino.h"
#include "ChessPlayerTimer.h"
int getMinutes(unsigned long elapsed) {
float h, m, s, ms;
unsigned long over;
h = int(elapsed / 3600000);
over = elapsed % 3600000;
m = int(over / 60000);
return m;
}
int getSeconds(unsigned long elapsed) {
float h, m, s, ms;
unsigned long over;
h = int(elapsed / 3600000);
over = elapsed % 3600000;
m = int(over / 60000);
over = over % 60000;
s = int(over / 1000);
return s;
}
void timeToString(char *buff, unsigned long start, unsigned long elapsed)
{
float h, m, s, ms;
unsigned long over;
String res = "";
h = int(elapsed / 3600000);
over = elapsed % 3600000;
m = int(over / 60000);
over = over % 60000;
s = int(over / 1000);
ms = over % 1000;
dtostrf(m, 1, 0, buff);
if (m > 9)
{
res += buff;
}
else
{
res += "0";
res += buff;
}
res += ":";
dtostrf(s, 1, 0, buff);
if (s > 9)
{
res += buff;
}
else
{
res += "0";
res += buff;
}
res.toCharArray(buff, 7);
}
ChessPlayerTimer::ChessPlayerTimer(unsigned long start, unsigned long elapsed, unsigned long time) {
_start = start;
_elapsed = elapsed;
_time = time;
}
void ChessPlayerTimer::setTimeControl(unsigned long timeControl) {
_time = timeControl;
_timeControl = timeControl;
}
char *ChessPlayerTimer::getTimeString() {
char *buff = "00:00 ";
timeToString(buff, _start, _time - _elapsed);
sprintf(buff, "%-7s", buff);
return buff;
}
void ChessPlayerTimer::start() {
_elapsed = 0;
_start = millis();
}
void ChessPlayerTimer::pause() {
_time -= _elapsed;
_elapsed = 0;
_start = millis();
}
void ChessPlayerTimer::reset() {
_elapsed = 0;
_time = _timeControl;
}
void ChessPlayerTimer::tick() {
_elapsed = millis() - _start;
}
bool ChessPlayerTimer::isOutOfTime() {
int m = getMinutes(_time - _elapsed);
int s = getSeconds(_time - _elapsed);
if ((m <= 0 && s <= 0) || _time <= 0){
return true;
}
return false;
}
| true |
1ea0d97b24f9fd89510b2bc84975cef0fbd39870 | C++ | TommasoCapanni/ProgettoListaSpesa | /User.h | UTF-8 | 752 | 2.859375 | 3 | [] | no_license | //
// Created by Tommaso Capanni on 12/07/2021.
//
#ifndef PROGETTOLISTASPESA_USER_H
#define PROGETTOLISTASPESA_USER_H
#include "ShoppingList.h"
class User {
public:
User(std::string name) : name(name) {};
void addList(std::shared_ptr<ShoppingList> sl);
std::vector<std::shared_ptr<ShoppingList>> getLists() const { return shopLists; }
void subscribe(Observer *o) {
for (auto &i : shopLists) {
i->attach(o);
}
}
void unsubscribe(Observer *o) {
for (auto &i : shopLists) {
i->detach(o);
}
}
std::string getName() const { return name; }
private:
std::string name;
std::vector<std::shared_ptr<ShoppingList>> shopLists;
};
#endif //PROGETTOLISTASPESA_USER_H
| true |
3a3d8e5cda5f580393403a1acd565104688f11ca | C++ | ParsaAlizadeh/AIC21 | /client/src/AI/MyCell.cpp | UTF-8 | 993 | 2.84375 | 3 | [] | no_license | #include "MyCell.h"
#include <bits/stdc++.h>
using namespace std;
MyCell::MyCell() :
x(-1),
y(-1),
lastseen(0),
state(C_UNKNOWN),
self(false)
{}
MyCell::MyCell(int x, int y, int lastseen, CellState state, bool self) :
x(x),
y(y),
lastseen(lastseen),
state(state),
self(self)
{}
int MyCell::get_importance() const {
switch (state) {
case C_BASE:
return 4;
case C_RES:
return 3;
case C_WALL:
return 2;
case C_EMPTY:
return 1;
default:
return 0;
}
}
string MyCell::encode() const {
stringstream stream;
stream << bitset<6>(x);
stream << bitset<6>(y);
stream << bitset<2>((int) state);
return stream.str();
}
MyCell MyCell::decode(string s, int turn) {
int x = (int) bitset<6>(s, 0, 6).to_ulong();
int y = (int) bitset<6>(s, 6, 6).to_ulong();
CellState state = (CellState) bitset<2>(s, 12, 2).to_ulong();
return MyCell(x, y, turn, state, false);
} | true |
49c18c3a2120097d5655c48a7b357672b0d02c7d | C++ | tudennis/LintCode | /C++/majority-number.cpp | UTF-8 | 520 | 3.234375 | 3 | [
"MIT"
] | permissive | // Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
int ans = nums[0], cnt = 1;
for (const auto& i : nums) {
if (i == ans) {
++cnt;
} else {
--cnt;
if (cnt == 0) {
ans = i;
cnt = 1;
}
}
}
return ans;
}
};
| true |
85c20d699bc9be5ee8f08fa13b14fdec79d6edbe | C++ | anstjaos/KIT-Homeworks | /2학년/자료구조1/4차과제/단순연결리스트(헤더)/Chain.h | UHC | 414 | 2.625 | 3 | [] | no_license | #include "ChainNode.h"
class Chain
{
private:
ChainNode *head;
ChainNode *first;
public:
Chain();
~Chain();
bool checkNode(Book b); // ߺ˻
void insertNode(Book b); //
void deleteNode(string bookNumber); // Է¹ ȣ ´
void printAll(); // ü
bool loadFile(string fileName);
void saveFile(string fileName);
}; | true |
2bc060146a2cd72aa37e0915d0ac2619c60298a0 | C++ | qfu/LeetCode_1 | /M_220_Contains_Duplicate_III.cpp | UTF-8 | 600 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int size = nums.size();
if(!size) return false;
int l = min(k,size-1);
for(int i = l; i < size; ++i){
for(int j = (i-l); j < i;++j){
if(abs(nums[i] - nums[j]) <= t){
//handle the case of overflow
if(abs((long)nums[i] - (long)nums[j]) <= t) return true;
//return true;
}
}
}
return false;
}
};
int main(int argc, char const *argv[])
{
/* code */
return 0;
} | true |
fb9c3fad3d415291fd1e06b2b52afa1ea2e7f411 | C++ | JunyoungChoi/my | /20181127_Smart_vase/20181127_smart_vase.ino | UTF-8 | 3,948 | 2.796875 | 3 | [] | no_license | #include <arduino.h>
#include <SPI.h>
#include <SoftwareSerial.h>
const int trigPin = 4;
const int echoPin = 2;
long duration;
int distance;
unsigned long last_light_check_millis = 0;
bool get_light_value(unsigned int &value1, unsigned int &value2, unsigned int &value3, unsigned int &value4){
unsigned long start_millis = millis();
while ( ((millis() - start_millis ) < 500) ){// timeout(5초)
;
}
if ( ( millis() - start_millis ) > 500 ) return false; // timeout인 경우
{
value1 = analogRead(A1);
value2 = analogRead(A2);
value3 = analogRead(A3);
value4 = analogRead(A4);
if(value1 <15 || value1 > 1015){
return false;
}
if(value2 <15 || value2 > 1015){
return false;
}
if(value3 <15 || value3 > 1015){
return false;
}
if(value4 <15 || value4 > 1015){
return false;
}
}
return true;
}
int Cal_dist(void){
int temp_distance;
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin, HIGH);
temp_distance = duration*0.034/2;
return temp_distance;
}
void setup() {
Serial.begin(9600);
// 오른쪽 바퀴
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
// 왼쪽 바퀴
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
// 조도센서
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
pinMode(A4, INPUT);
// 초음파센서
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
}
void loop() {
//if ((millis() - last_light_check_millis) > 50){
// stop();
// Serial.print("범인");
//}
if ((millis() - last_light_check_millis) < 200)
return;
distance = Cal_dist();
if(distance < 20){
stop();
return;
}
unsigned int light1,light2,light3,light4;
if(get_light_value(light1,light2,light3,light4) == true){
Serial.print(light1);
Serial.print(" ");
Serial.print(light2);
Serial.print(" ");
Serial.print(light3);
Serial.print(" ");
Serial.print(light4);
Serial.print(" \n");
//Serial.println(distance);
//Serial.println(distance);
unsigned int max_value = max(light3, max(light1, light2));
unsigned int min_value = min(light3, min(light1, light2));
if ( ( max_value - min_value ) < 100 ){
stop();
return;
}
if ( max_value == light1 ){
right();
}
else if ( max_value == light2 ){
stop();
if((light2 - light4)>80){
front();
}
}
else if ( max_value == light3 ){
left();
}
else{
stop();
}
last_light_check_millis = millis();
/*
if(value1 > value2){
if(value1>value3){
Serial.println("value1 is the best");
right();
}
else{
Serial.println("value3 is the best");
left();
}
}
else{
if(value2 > value3){
Serial.println("value2 is the best");
stop();
}
else{
Serial.println("value3 is the best");
left();
}
}
*/
}
}
void front()
{
left_go();
right_go();
}
void back(){
left_back();
right_back();
}
void stop(){
left_off();
right_off();
}
void left(){
right_go();
left_back();
}
void right(){
right_back();
left_go();
}
void right_go(){
//analogWrite(3, 255);
analogWrite(5, 150);
analogWrite(6, 0);
//Serial.println("우바퀴 정회전 ");
}
void right_back(){
//analogWrite(3, 255);
analogWrite(5, 0);
analogWrite(6, 150);
// Serial.println("우바퀴 역회전 ");
}
void right_off(){
//analogWrite(3, 255);
analogWrite(5, 150);
analogWrite(6, 150);
// Serial.println("우바퀴 정지 ");
}
void left_go(){
//analogWrite(6, 255);
analogWrite(9, 150);
analogWrite(10, 0);
//Serial.println("좌바퀴 정회전 ");
}
void left_back(){
//analogWrite(6, 255);
analogWrite(9, 0);
analogWrite(10, 150);
//Serial.println("좌바퀴 역회전 ");
}
void left_off(){
//analogWrite(6, 255);
analogWrite(9, 150);
analogWrite(10, 150);
//Serial.println("좌바퀴 정지 ");
}
| true |
542b3daa1189f7873fe8d67bafd2c6822910aa1a | C++ | OlivierArgentieri/Jeu_de_la_mort_cpp | /jeu_de_la_mort/Sprite.cpp | UTF-8 | 422 | 3.03125 | 3 | [] | no_license | #include "pch.h"
#include "Sprite.h"
#include <iostream>
Sprite::Sprite(char _cChar, color _cColor)
{
m_char_ = _cChar;
SetColor(_cColor);
}
Sprite::Sprite(const Sprite& _refSprite)
{
m_char_ = _refSprite.m_char_;
m_color_ = _refSprite.m_color_;
}
void Sprite::SetColor(color _cColor)
{
m_color_ = _cColor;
}
void Sprite::Display()
{
std::cout << "\033[" << m_color_<<"m" << m_char_ << "\033[" << RESET << "m";
} | true |
5dd05e2abec5a919f0a914a145cbf9a47354ae76 | C++ | Zerp2808/program-language | /Language programm/practTwo/codeTwo.h | UTF-8 | 502 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
int RandomGenerator()
{
static mt19937 rnd((uint64_t)&rnd);
uniform_int_distribution<int>d(1000000000,1000000000);
return d(rnd);
}
int main(int argc, char **argv)
{
int rd;
vector <int> first;
vector <int> second(10000000);
for(int i=0;i<10000000;i++){
rd=RandomGenerator();
first.push_back(rd);
}
generate(second.begin(),second.end(),RandomGenerator);
vector <int> third(second);
return 0;
}
| true |
fe9c63d4f7ecc3cf84577803ead9ca4147f5b77d | C++ | tabvn/ued | /codefores/a_prank.cpp | UTF-8 | 955 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> A;
vector<int> result;
void findSubSeq()
{
int n = A.size();
unordered_map<int, int> m;
int lis_size = 1;
int lis_index = 0;
m[A[0]] = 1;
for (int i = 1; i < n; i++) {
m[A[i]] = m[A[i] - 1] + 1;
if (lis_size < m[A[i]]) {
lis_size = m[A[i]];
lis_index = A[i];
}
}
int total = lis_size;
int start = lis_index - lis_size + 1;
int index = 0;
while (start <= lis_index) {
if(index == 0 && start != 1){
total --;
}
if(start == lis_index && start != 1000){
total --;
}
start++;
index++;
}
cout << total;
}
int main(){
int n,a;
cin >> n;
for (int i = 0; i < n; ++i){
cin >> a;
A.push_back(a);
}
if(A.size() == 1){
cout << 0;
}else{
findSubSeq();
}
return 0;
} | true |
02b7aa7b0ee3e588064f093788c33f2e127ca8d8 | C++ | wangchenwc/leetcode_cpp | /700_799/774_minmax_gas_dist.h | UTF-8 | 729 | 2.703125 | 3 | [] | no_license | //
// 774_minmax_gas_dist.h
// cpp_code
//
// Created by zhongyingli on 2018/8/24.
// Copyright © 2018 zhongyingli. All rights reserved.
//
#ifndef _74_minmax_gas_dist_h
#define _74_minmax_gas_dist_h
class Solution {
public:
double minmaxGasDist(vector<int>& stations, int K) {
double left = 0, right = 1e8;
while (right - left > 1e-6) {
double mid = left + (right - left) / 2;
int cnt = 0, n = stations.size();
for (int i = 0; i < n - 1; ++i) {
cnt += (stations[i + 1] - stations[i]) / mid;
}
if (cnt <= K) right = mid;
else left = mid;
}
return left;
}
};
#endif /* _74_minmax_gas_dist_h */
| true |
5d9e728d707d8dce90ad8e9208886a790d20aa4c | C++ | DenSto/APC_524_Project | /src/poisson/poissonBC.cpp | UTF-8 | 2,198 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cmath>
#include <assert.h>
#include "../globals.hpp"
#include "poissonBC.hpp"
using namespace std;
PoissonBC::PoissonBC(int side, Input_Info_t *input_info, Grid *grids){
assert(abs(side)<=3 && abs(side)>=1);
dim_ = abs(side)-1; //x:0, y:1, z:2
grids_ = grids;
int nGhosts = grids_->getnGhosts();
int *nxyzReal = grids_->getnxyzReal();
if(side<0){//left side
offset_ = nGhosts; //physical
}else{//right side
offset_ = nGhosts + nxyzReal[dim_];//ghost
}
fieldPtr_ = grids_->getFieldPtr();
// convert side (-3,-2,-1,1,2,3) to index (4,2,0,1,3,5)
int ind = (int)(2*abs((double)side+0.25)-1.5);
// load input info relevant to the boundary specified by side
phiA_[0] = input_info->bound_phi[ind];
phiA_[1] = input_info->bound_Ax[ind];
phiA_[2] = input_info->bound_Ay[ind];
phiA_[3] = input_info->bound_Az[ind];
if(debug>1) cerr << "rank=" << rank_MPI
<< ": side=" << side
<< ": poissonBC offset ="<<offset_
<< ", Load from index " << ind
<< " with values: "<<phiA_[0]<<", "<<phiA_[1]
<< ", "<<phiA_[2]<<", "<<phiA_[3]<< endl;
};
PoissonBC::~PoissonBC(void){
}
//! conver fieldID of phi and A to index 0,1,2,3
int PoissonBC::fieldIDToIndex(int sendID){
int fid;
if(sendID==grids_->getFieldID("phi1") || sendID==grids_->getFieldID("phi2")){
fid = 0;
}else if(sendID==grids_->getFieldID("Ax1") || sendID==grids_->getFieldID("Ax2")){
fid = 1;
}else if(sendID==grids_->getFieldID("Ay1") || sendID==grids_->getFieldID("Ay2")){
fid = 2;
}else if(sendID==grids_->getFieldID("Az1") || sendID==grids_->getFieldID("Az2")){
fid = 3;
}else{
fid = -1;
}
return fid;
}
void PoissonBC::applyBCs (int sendID) {
// load field
fid_ = fieldIDToIndex(sendID);
if(debug>1)cerr<<"rank="<<rank_MPI<<": sendID="<<sendID<<", fid="<<fid_ <<endl;
assert(fid_>=0);
fieldVal_ = phiA_[fid_];
field_ = fieldPtr_[sendID];
// set field values
grids_->setFieldInPlane(dim_,offset_,field_,fieldVal_);
};
| true |
8bacba16cc44f9e0aff1d798a84fffe57a02f62f | C++ | Xelopie/Violet-v1.0 | /Violet v1.0/Memory.cpp | UTF-8 | 1,145 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
HANDLE MEMORY::hProcess;
DWORD MEMORY::PID;
bool MEMORY::Attach(const char* processName, DWORD rights) {
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hProcessSnap, &pe32)) {
return false;
}
do {
if (!strcmp(pe32.szExeFile, processName)) {
PID = pe32.th32ProcessID;
CloseHandle(hProcessSnap);
hProcess = OpenProcess(rights, false, PID);
return true;
}
} while (Process32Next(hProcessSnap, &pe32));
CloseHandle(hProcessSnap);
return false;
}
SMODULE MEMORY::GetModule(const char* moduleName) {
HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32 | TH32CS_SNAPMODULE, PID);
MODULEENTRY32 me32;
me32.dwSize = sizeof(MODULEENTRY32);
if (!Module32First(hModuleSnap, &me32)) {
return { (DWORD)false, (DWORD)false };
}
do {
if (!strcmp(me32.szModule, moduleName)) {
CloseHandle(hModuleSnap);
return { (DWORD)me32.hModule, me32.modBaseSize };
}
} while (Module32Next(hModuleSnap, &me32));
CloseHandle(hModuleSnap);
return { (DWORD)false, (DWORD)false };
}
| true |
568764cd312b2e996a9512dd3e79469ed9556fd1 | C++ | jef42/pcapwrapper | /include/helpers/helper.h | UTF-8 | 2,335 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef PCAPHELPER_H
#define PCAPHELPER_H
#include <array>
#include <stdexcept>
#include <vector>
#include "../network/addresses/ipaddress.h"
#include "../network/addresses/macaddress.h"
#include "../network/sniff/snifficmp.h"
#include "../network/sniff/sniffip.h"
#include "../network/sniff/snifftcp.h"
#include "../network/sniff/sniffudp.h"
namespace PCAP {
namespace PCAPHelper {
void set_ip_checksum(sniffip *ip);
void set_icmp_checksum(sniffip *ip, snifficmp *icmp);
void set_tcp_checksum(sniffip *ip, snifftcp *tcp, uchar *data);
void set_udp_checksum(sniffip *ip, sniffudp *udp, uchar *data);
bool setIp(PCAP::uchar *ip, const std::string &ip_value, int base);
bool setMac(PCAP::uchar *addr, const std::string ðernet_value, int base);
PCAP::IpAddress get_ip(const std::string &interface);
PCAP::MacAddress get_mac(const std::string &interface);
PCAP::IpAddress get_mask(const std::string &interface);
PCAP::IpAddress get_router_ip(const std::string &inteface);
PCAP::IpAddress get_broadcast_ip(const std::string &inteface);
std::vector<PCAP::IpAddress> get_ips(const PCAP::IpAddress &local_ip,
const PCAP::IpAddress &network_mask);
PCAP::MacAddress get_mac(const PCAP::IpAddress &target_ip,
const std::string &interface);
template <typename T, int N>
bool split_string(const std::string &s, const char splitter,
std::array<T, N> &array, int base = 10) {
uint i = 0;
std::string tmp = s + splitter;
size_t p = std::string::npos;
while ((p = tmp.find(splitter, 0)) != std::string::npos) {
try {
std::string aux = tmp.substr(0, p);
int b = std::stoi(aux, 0, base);
if (i >= N)
return false;
array[i++] = b;
tmp = tmp.substr(p + 1, std::string::npos);
} catch (std::invalid_argument &ex) {
return false;
}
}
if (i != N)
return false;
return true;
}
template <typename T> ushort checksum(T *p, int count) {
uint sum = 0;
ushort *addr = (ushort *)p;
while (count > 1) {
sum += *addr++;
count -= 2;
}
if (count > 0)
sum += *(uchar *)addr;
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return ~sum;
}
}
}
#endif // PCAPHELPER_H
| true |
d7c111f592cf74ab7d47eb0a59683f7cb56488cd | C++ | Valnig/TacticsEngine | /main.cpp | UTF-8 | 5,342 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <utility>
#include <sstream>
#define MAX(a,b) ((a) > (b) ? (a) : (b))
class SimpleSpace{
private:
int height_ = 0;
public:
virtual bool walkable() const = 0;
};
class GroundSpace : public SimpleSpace{
public :
bool walkable() const {
return true;
}
};
class ForestSpace : public SimpleSpace{
public :
bool walkable() const {
return false;
}
};
class WaterSpace : public SimpleSpace{
public :
bool walkable() const {
return false;
}
};
template<typename _SPACE, typename _PAWN>
class Map2D{
private:
const int width_;
const int height_;
protected:
_SPACE** grid_ = nullptr;
std::vector<std::pair<int,_PAWN*>> pawns_;///<TODO replace with map
int to_id(int x, int y) const{
return x*width_ + y;
}
//wrong
void to_coordinates(int id, int& x, int& y) const{
x = id/width_;
y = id - x * width_;
}
int is_occupied(int id) const{
size_t k(0);
bool occupied(false);
while(k<pawns_.size() && ! occupied){
occupied |= pawns_[k].first == id;
k++;
}
return occupied ? (int)k-1 : -1;
}
public:
Map2D(int width, int height) : width_(MAX(1,width)), height_(MAX(1,height)) {
grid_ = (_SPACE**) calloc(width_*height_,sizeof(_SPACE*));
}
~Map2D(){
free(grid_);
grid_ = nullptr;
}
bool add_pawn(_PAWN* pawn, int x, int y){
if(pawn){
if(is_occupied(to_id(x,y)) >= 0){
return false;
}
pawns_.push_back({to_id(x,y), pawn});
return true;
}
return false;
}
std::string to_string() const{
std::stringstream msg;
for(int i(0); i<width_; i++){
msg<<"|";
for(int j(0); j<height_;j++){
int occupied = is_occupied(to_id(i,j));
if(occupied >= 0){
msg<<pawns_[occupied].second->to_string()<<"|";
}else if(grid_[to_id(i,j)]){
//std::cout<<"printing space "<<i<<","<<j<<std::endl;
msg<<grid_[to_id(i,j)]->to_string()<<"|";
}else{
msg<<"XX|";
}
}
msg<<std::endl;
for(int j(0); j<height_;j++){
msg<<"---";
}
msg<<std::endl;
}
return msg.str();
}
};
namespace Chess{
typedef enum{PAWN, BISHOP, ROOK, KNIGHT, QUEEN, KING} PIECE_TYPE;
struct Space{
const bool color_;///<false : black, true : white
std::string to_string(){
return color_ ? "##" : " ";
}
Space(bool color) : color_(color){}
};
class Piece{
private:
PIECE_TYPE type_;
bool color_;
public:
Piece(PIECE_TYPE type, bool color) : type_(type), color_(color){}
static std::string type_to_string(PIECE_TYPE type){
switch(type){
case PAWN : return "P";
case BISHOP : return "B";
case ROOK : return "R";
case KNIGHT : return "K";
case QUEEN : return "Q";
case KING : return "o";
default : return "X";
}
}
std::string to_string() const {
return std::string(color_ ? "W" : "B") + type_to_string(type_);
}
};
class Board : public Map2D<Space, Piece> {
private:
public:
Board() : Map2D<Space, Piece>(8,8){
for(int i(0); i<8; i++){
for(int j(0); j<8; j++){
grid_[to_id(i,j)] = new Space((i+j)%2);
}
}
}
};
class Game{
private:
Board board_;
public:
Game() : board_(){
board_.add_pawn(new Piece(PAWN, false), 1,0);
board_.add_pawn(new Piece(PAWN, false), 1,1);
board_.add_pawn(new Piece(PAWN, false), 1,2);
board_.add_pawn(new Piece(PAWN, false), 1,3);
board_.add_pawn(new Piece(PAWN, false), 1,4);
board_.add_pawn(new Piece(PAWN, false), 1,5);
board_.add_pawn(new Piece(PAWN, false), 1,6);
board_.add_pawn(new Piece(PAWN, false), 1,7);
board_.add_pawn(new Piece(ROOK, false), 0,0);
board_.add_pawn(new Piece(KNIGHT, false), 0,1);
board_.add_pawn(new Piece(BISHOP, false), 0,2);
board_.add_pawn(new Piece(KING, false), 0,3);
board_.add_pawn(new Piece(QUEEN, false), 0,4);
board_.add_pawn(new Piece(BISHOP, false), 0,5);
board_.add_pawn(new Piece(KNIGHT, false), 0,6);
board_.add_pawn(new Piece(ROOK, false), 0,7);
board_.add_pawn(new Piece(PAWN, true), 6,0);
board_.add_pawn(new Piece(PAWN, true), 6,1);
board_.add_pawn(new Piece(PAWN, true), 6,2);
board_.add_pawn(new Piece(PAWN, true), 6,3);
board_.add_pawn(new Piece(PAWN, true), 6,4);
board_.add_pawn(new Piece(PAWN, true), 6,5);
board_.add_pawn(new Piece(PAWN, true), 6,6);
board_.add_pawn(new Piece(PAWN, true), 6,7);
board_.add_pawn(new Piece(ROOK, true), 7,0);
board_.add_pawn(new Piece(KNIGHT, true), 7,1);
board_.add_pawn(new Piece(BISHOP, true), 7,2);
board_.add_pawn(new Piece(KING, true), 7,3);
board_.add_pawn(new Piece(QUEEN, true), 7,4);
board_.add_pawn(new Piece(BISHOP, true), 7,5);
board_.add_pawn(new Piece(KNIGHT, true), 7,6);
board_.add_pawn(new Piece(ROOK, true), 7,7);
}
std::string to_string() const {
return board_.to_string();
}
bool main_loop(){
int from;
int to;
cout<<"what move do you want to do ?"<<std::endl;
cout<<"enter the piece's location : ";
cin>>from;
cout<<"enter the piece's target : ";
cin>>to;
int x_start = from/10;
int y_start = from%10;
int x_end = to/10;
int y_end = t0%10;
return false;
}
};
}
using namespace Chess;
int main(){
Game game;
std::cout<<game.to_string()<<std::endl;
while(game.main_loop()){}
return 0;
}
| true |
5fa8df6d4a04c21a80a2b8bcf883bed8232aa562 | C++ | panshim/ros_cricket | /src/ekf/src/ekf_models.cpp | UTF-8 | 7,434 | 2.625 | 3 | [] | no_license |
#include "ekf_models.hpp"
#include <tf/tf.h>
State sys_evaluate_g( const State& state_in, double dt ){
State state_out;
// dt : time step
state_out.x[0] = std::min(100.0,state_in.x[0]+dt*state_in.x[3]+0.5*dt*dt*state_in.x[6]);
state_out.x[1] = std::min(100.0,state_in.x[1]+dt*state_in.x[4]+0.5*dt*dt*state_in.x[7]);
state_out.x[2] = std::min(100.0,state_in.x[2]+dt*state_in.x[5]+0.5*state_in.x[9]*dt*dt);
state_out.x[3] = std::min(100.0,state_in.x[3]+dt*state_in.x[6]);
state_out.x[4] = std::min(100.0,state_in.x[4]+dt*state_in.x[7]);
state_out.x[5] = std::min(100.0,state_in.x[5]+dt*state_in.x[8]);
state_out.x[6] = std::min(100.0,state_out.x[6]);
state_out.x[7] = std::min(100.0,state_out.x[7]);
state_out.x[8] = std::min(100.0,state_out.x[8]);
//std::cout<<state_in.x[6]<<std::endl;
return state_out;
}
void sys_evaluate_G( double G[9][9], const State& state, double dt ){
for( int r=0; r<9; r++ )
for( int c=0; c<9; c++ )
G[r][c] = 0.0;
G[0][0] = 1.0;
G[0][3] = dt;
G[0][6] = 0.5*dt*dt;
G[1][1] = 1.0;
G[1][4] = dt;
G[1][7] = 0.5*dt*dt;
G[2][2] = 1.0;
G[2][5] = dt;
G[2][9] = 0.5*dt*dt;
G[3][3] = 1.0;
G[3][6] = dt;
G[4][4] = 1.0;
G[4][7] = dt;
G[5][5] = 1.0;
G[5][8] = dt;
G[6][6] = 1.0;
G[7][8] = 1.0;
G[7][8] = 1.0;
}
void sys_evaluate_VMVt( double VMVt[9][9], const State& state, double dt ){
// hyperparameters
double a1=0.8;
double a2=0.8;
double a3=0.8;
double a4=0.8;
double a5=0.8;
double a6=0.8;
for( int r=0; r<9; r++ )
for( int c=0; c<9; c++ )
VMVt[r][c] = 0.0;
// TODO: maybe zero is better????
VMVt[0][0] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/4.0);
VMVt[0][3] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[0][6] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[1][1] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/4.0);
VMVt[1][4] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[1][7] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[2][2] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/4.0);
VMVt[2][5] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[2][8] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[3][0] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[3][3] = a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]+(dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[3][6] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[4][1] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[4][4] = a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]+(dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[4][7] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[5][2] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])+(dt*dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[5][5] = a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]+(dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[5][8] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[6][0] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[6][3] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[6][6] = a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5];
VMVt[7][1] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[7][4] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[7][7] = a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5];
VMVt[8][2] = (dt*dt)*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5])*(1.0/2.0);
VMVt[8][5] = dt*(a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5]);
VMVt[8][8] = a4*state.x[6]+a5*state.x[7]+a6*state.x[8]+a1*state.x[3]+a2*state.x[4]+a3*state.x[5];
/*
VMVt[0][0] = 0.01;
VMVt[1][1] = 0.01;
VMVt[2][2] = 0.01;
VMVt[3][3] = 0.01;
VMVt[4][4] = 0.01;
VMVt[5][5] = 0.01;
VMVt[6][6] = 0.01;
VMVt[7][7] = 0.01;
VMVt[8][8] = 0.01;
*/
}
geometry_msgs::InertiaStamped meas_evaluate_gps( const State& state ){
geometry_msgs::InertiaStamped obs;
// TODO !!
//obs.point.x = state.x[0];
//obs.point.y = state.x[1];
//obs.point.z = state.x[2];
obs.inertia.com.x = state.x[0];
obs.inertia.com.y = state.x[1];
obs.inertia.com.z = state.x[2];
obs.inertia.ixx = state.x[3];
obs.inertia.ixy = state.x[4];
obs.inertia.ixz = state.x[5];
obs.inertia.iyy = state.x[6];
obs.inertia.iyz = state.x[7];
obs.inertia.izz = state.x[8];
return obs;
}
void meas_evaluate_Hgps( double Hgps[9][9], const State& state ){
for( int r=0; r<9; r++ )
for( int c=0; c<9; c++ )
Hgps[r][c] = 0.0;
//TODO !! the same
Hgps[0][0] = 1.0;
Hgps[1][1] = 1.0;
Hgps[2][2] = 1.0;
Hgps[3][3] = 1.0;
Hgps[4][4] = 1.0;
Hgps[5][5] = 1.0;
Hgps[6][6] = 1.0;
Hgps[7][7] = 1.0;
Hgps[8][8] = 1.0;
}
void meas_evaluate_R( double R[9][9], const State& state ){
for( int r=0; r<9; r++ )
for( int c=0; c<9; c++ )
R[r][c] = 0.0;
R[0][0] = 0.0005;
R[1][1] = 0.0005;
R[2][2] = 0.0005;
R[3][3] = 0.0005;
R[4][4] = 0.0005;
R[5][5] = 0.0005;
R[6][6] = 0.0005;
R[7][7] = 0.0005;
R[8][8] = 0.0005;
/*
R[0][0] = 1.251461376E-3;
R[1][1] = 3.6E-3;
R[2][2] = 9.060099999999998E-4;
R[3][3] = 2.597777756995556E-5;
R[4][4] = 2.597777756995556E-5;
R[5][5] = 2.597777756995556E-6;
R[6][6] = 2.597777756995556E-6;
*/
} | true |
b49dfa9378a1314aa084531f2306c3ce3bb01733 | C++ | raymondxie/duelling | /test/wandLight/wandLight.ino | UTF-8 | 1,224 | 3 | 3 | [] | no_license | #include <Adafruit_NeoPixel.h>
// NodeMCU D3 pin
#define PIN D3
// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 15
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int delayval = 1000;
void setup() {
pixels.begin();
pixels.setBrightness(32);
delay(delayval);
}
void loop() {
int buttonPressed = random(3);
charge(buttonPressed);
delay(delayval);
discharge();
delay(delayval);
// pace the loop
delay(delayval);
}
void charge(int button) {
uint32_t color;
if(button == 0) {
// red
color = pixels.Color(64,0,0);
}
else if(button == 1) {
// green
color = pixels.Color(0,64,0);
}
else if(button == 2) {
// blue
color = pixels.Color(0,0,64);
}
int numPixel = pixels.numPixels();
for(int i=0; i < numPixel; i++) {
pixels.setPixelColor(i, color );
pixels.show();
delay(20);
}
}
void discharge() {
uint32_t color = pixels.Color(0,0,0);
int numPixel = pixels.numPixels();
for(int i=0; i < numPixel; i++) {
pixels.setPixelColor(i, color );
pixels.show();
delay(20);
}
}
| true |
ad98fdf96e594183052a3e422d9325b386185dc3 | C++ | thirtiseven/CF | /edu 52/F.cc | UTF-8 | 587 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <vector>
const int maxn = 1e6;
std::vector<int> t[maxn];
int dep[maxn];
int dfs(int cur, int fa) {
int ans = maxn*2;
if (t[cur].size()==1) {
return dep[cur] = 1;
}
for (auto it: t[cur]) {
if (it != fa) {
ans = std::max(it, cur);
}
}
return ans;
}
int main(int argc, char *argv[]) {
int n, k, tt;
std::cin >> n >> k;
for (int i = 2; i <= n; i++) {
std::cin >> tt;
t[tt].push_back(i);
t[i].push_back(tt);
}
dep[1] = dfs(1, 0);
int aa = 0;
for (int i = 1; i <= n; i++) {
if (dep[i] <= k) {
aa++;
}
}
std::cout << aa;
} | true |
943f62730eb83c76422a68fa0c8561321618a4f5 | C++ | Tahani-0514/CS-Courses | /COSC214_Data_Structure/projects/Ch5_Ex1_linkedList/code/dateTypeImp.cpp | UTF-8 | 1,536 | 3.453125 | 3 | [] | no_license | //Implementation file date
#include <iostream>
#include "dateType.h"
using namespace std;
void dateType::setDate(int month, int day, int year)
{
if (year >= 1)
dYear = year;
else
dYear = 1900;
if (1 <= month && month <= 12)
dMonth = month;
else
dMonth = 1;
switch (dMonth)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (1 <= day && day <= 31)
dDay = day;
else
dDay = 1;
break;
case 4:
case 6:
case 9:
case 11:
if (1 <= day && day <= 30)
dDay = day;
else
dDay = 1;
break;
case 2:
if (isLeapYear(year))
{
if (1 <= day && day <= 29)
dDay = day;
else
dDay = 1;
}
else
{
if (1 <= day && day <= 28)
dDay = day;
else
dDay = 1;
}
}
}
int dateType::getDay() const
{
return dDay;
}
int dateType::getMonth() const
{
return dMonth;
}
int dateType::getYear() const
{
return dYear;
}
void dateType::printDate() const
{
cout << dMonth << "-" << dDay << "-" << dYear;
}
//constructor with parameter
dateType::dateType(int month, int day, int year)
{
setDate(month, day, year);
}
bool dateType::isLeapYear(int y)
{
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
return true;
else
return false;
}
| true |
65113b6fd4da71958380881359b12c6ad9f2ceee | C++ | jontierno/7574A16C2PROY | /loadbalancer/main.cpp | UTF-8 | 3,572 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include "string"
#include "vector"
#include <stdio.h>
#include <cstring>
#include <fstream>
#include <algorithm>
using namespace std;
#define STATICS_FILE "/home/load.db"
#define WORKERS_FILE "/home/workers.db"
string handleCrearCuenta(int nro) {
return "";
}
string handleConsultarSaldo(int nro) {
return "";
}
string handleDepositar(int nro, int cant) {
return "";
}
string handleRetirar(int nro, int cant) {
return "";
}
string handleMovimientos(int nro) {
return "";
}
vector<string> split(const string str, const string& delim){
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) {
tokens.push_back(token);
}
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
string determineLocation(ifstream & ls, ifstream & ws) {
string line;
string body;
string header;
float freem;
float load;
float minload = 3000;
string idSel = ";;;";
string id;
string urlSel;
vector<string> v1;
vector<string> workers;
vector<string> urlworkers;
std::vector<string>::iterator it;
while (getline (ws,line) ) {
v1 = split(line, "=");
workers.push_back(v1[0]);
urlworkers.push_back(v1[1]);
}
while ( getline (ls,line) ) {
//primer spliteo, para sacar el cuerpo y el header;
v1 = split(line, " ");
header = v1[0];
body = v1[1];
//obtengo la carga de cpu y la memoria
v1 = split(body, ";");
freem = stof(v1[0]);
load = stof(v1[1]);
//si tengo cierta memoria libre y la carga es menor
if(freem > 1000 && minload >= load) {
v1 = split(header, "/");
// busco la posicion de worker
id = v1[1];
it = find(workers.begin(), workers.end(), id);
int pos = it - workers.begin();
//si hay un worker tengo a mi destino
if(pos < workers.size()) {
minload = load;
idSel = v1[1];
urlSel = urlworkers[pos];
}
}
}
if(idSel == ";;;" ) {
return "";
}
return urlSel;
}
void printError(string msg) {
printf("Status: 500 Internal Server Error\n") ;
cout << "Content-type:text/html\n\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<h1>" << msg <<"</h1> \n";
cout << "</body>\n";
cout << "</html>\n";
}
int main (int argc, char *argv[])
{
ifstream statsFile(string(STATICS_FILE));
if (!statsFile.good()){
printError("No se encuentra el archivo de stats");
} else {
ifstream workersFile(string(WORKERS_FILE));
if(!workersFile.good()){
statsFile.close();
printError("No se encuentra el archivo de workers");
} else {
string location = determineLocation(statsFile, workersFile);
statsFile.close();
workersFile.close();
if(location.length() > 0) {
cout << "status: 302 Found\n";
cout << "Location: http://" << location<< "\n\n";
} else {
printError("No se pudo determinar el worker");
}
}
}
return 0;
} | true |
edce5412a85f003422825688d9cf8ea04804e333 | C++ | scm-ns/real_neurons_stdp_minst | /network_old.h | UTF-8 | 1,693 | 2.609375 | 3 | [] | no_license | #ifndef NETWORK_H
#define NETWORK_H
#include "neuron.h"
#include "error.cpp"// NOT NEEDED present FROM NEURON.h
#include <vector>
#include <iostream>
#include <tuple>
#include <functional>
#include <chrono>
/*
This will handle the structure of the neuron connections.. How ?
Keep a vector of neurons with ids.
user will add the neuron .
Then say connect(1,2);
*/
class network: public error
{
public:
network(unsigned int nNeurons , unsigned int id , unsigned int region );
~network();
bool systemTick();
void addNeuron();
void addNeuron(neuron * neu);
neuron* Neuron(unsigned int pos);
unsigned int getNumNeurons(){ return _neurons->size(); };
void connect(int n1, int n2, double weight = 1);
void setNeuronDebug(bool f);
void setNetworkDebug(bool f);
void runSetup(bool t) { _run = t; };
void setStarter(bool t){_starter = t;};
unsigned int getId() { return _id;};
//void sID(unsigned int a) {_id =a ; }
//LEARNING BAD CODE> KEEP PRIVATE THINGS PRIVATE. //TODO CORRECT IT.
std::vector<neuron*>* getNeurons(){ return _neurons;};
bool networkForceReset();
void networkHoldValue();
void networkUnHoldValue();
private:
// IDENTIFICATION
unsigned int _id; // ID OF THE NETWORK. HELPFUL WHEN USING MULTIPLE NETWORKS.
unsigned int _regionid;
bool _run;
bool _starter; // Indicates whether a starter neuron is being used..
unsigned int _nNeurons;
unsigned int _startNeuron; // This neuron should only be ticked once..
bool _networkTicked;
std::vector<neuron*> * _neurons;
};
#endif // NETWORK_H
| true |
3fbe5bfcd85c78479cf30e719e140509abda9f81 | C++ | Rancho06/board_puzzle | /hlayout.cpp | UTF-8 | 770 | 2.75 | 3 | [] | no_license | #include "hlayout.h"
#include "main_window.h"
/** Constructor creates two QRadioButtons
@param m_w A pointer to the main window object
*/
HLayout::HLayout(MainWindow* m_w){
mw=m_w;
horizon=new QHBoxLayout();
manhattan=new QRadioButton("Manhattan");
outofplace=new QRadioButton("OutOfPlace");
this->setLayout(horizon);
horizon->addWidget(manhattan);
horizon->addWidget(outofplace);
connect(manhattan,SIGNAL(clicked()),this, SLOT(changemanhattan()));
connect(outofplace,SIGNAL(clicked()),this, SLOT(changeoop()));
}
/** This function sets the heuristic to manhattan*/
void HLayout::changemanhattan(){
mw->getgraphwindow()->setmanhattan();
}
/** This function sets the heuristic to outofplace*/
void HLayout::changeoop(){
mw->getgraphwindow()->setoop();
}
| true |
b373ad0f813d132f8501f0159907294bf91406e5 | C++ | bonaert/torrent | /main.cpp | UTF-8 | 2,397 | 2.953125 | 3 | [] | no_license |
#include <iostream>
#include <assert.h>
#include "Torrent.hpp"
#include "Client.hpp"
#include "Utils/Tools.hpp"
/*
* The following examples methods demonstrate how the API should be used.
* This is here to help design the API of the library, and make sure the
* interfaces are as simple and clear as possible.
*/
void downloadTorrent(std::string filename) {
Torrent torrent = Torrent(filename);
int totalSize = torrent.size();
int numPieces = torrent.numPieces();
int pieceSize = torrent.pieceLength();
std::string name = torrent.name();
std::cout << "Here are some stats for the torrent" << std::endl;
std::cout << "Total size: " << totalSize << " bytes" << std::endl;
std::cout << "Number of pieces: " << numPieces << " pieces" << std::endl;
std::cout << "Piece size: " << pieceSize << " bytes" << std::endl;
std::cout << std::endl << std::endl << std::endl << std::endl;
Client client(torrent);
client.start();
/*
Client client(torrent);
client.start(); // Starts the torrent in a new thread [NOT SURE, MAY CHANGE]
while (!client.hasFinished()){
std::cout << "Here are the stats for the torrent \"" << name << "\"" << std::endl;
float percentComplete = client.percentComplete();
std::cout << "The torrent is " << (int) percentComplete << " % complete" << std::endl;
int bytesDownloaded = client.bytesDownloaded();
std::cout << "Downloaded: " << bytesDownloaded << " / " << totalSize << std::endl;
int numActivePeers = client.numActivePeers();
std::cout << "Sharing data with " << numActivePeers << " peers." << std::endl;
sleep(10);
}
*/
std::cout << "The torrent is now complete!" << std::endl;
std::cout << "You can check your file at " << name << std::endl;
}
void runTests() {
assert(urlencode("Hello Günter") == "Hello%20G%C3%BCnter");
assert(urldecode("Hello%20G%C3%BCnter") == "Hello Günter");
}
void setup() {
srand((unsigned int) time(NULL));
}
int main() {
setup();
std::cout << std::endl << std::endl;
// const char *filename = "/home/greg/Downloads/torrents/[kat.cr]silicon.valley.s03e07.hdtv.x264.killers.ettv.torrent";
const char *filename = "/home/greg/Downloads/torrents/[kat.cr]shutter.island.2010.720p.1280.544.600mb.torrent";
downloadTorrent(filename);
runTests();
return 0;
} | true |
eb0bb20d0838a0aed2676455a914ce5f29cd33bd | C++ | mtreviso/university | /Problems & Contents/URI/4-DataStructures&Libraries/1112-Schweisen.cpp | UTF-8 | 1,476 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
const int MAX = 1001;
int MAX_X, MAX_Y, P;
int tree[MAX][MAX];
void atualiza(int x, int y, int val){
while (x <= MAX_X){
int y1 = y;
while(y1 <= MAX_Y){
tree[x][y1] += val;
y1 += (y1 & -y1);
}
x += (x & -x);
}
}
int le(int x, int y){
int sum = 0;
while (x > 0){
int y1 = y;
while(y1 > 0){
sum += tree[x][y1];
y1 -= (y1 & -y1);
}
x -= (x & -x);
}
return sum;
}
int selecao(int x, int y, int z, int w){
int x1 = min(x, z);
int x2 = max(x, z);
int y1 = min(y, w);
int y2 = max(y, w);
//return le(x2,y2) - min(x1, y1);
int s = le(x2, y2);
s -= le(x2, y1-1);
s -= le(x1-1, y2);
s += le(x1-1, y1-1);
return s;
}
int main(){
int q, n, x, y, z, w;
char c;
while(true){
scanf("%d %d %d", &MAX_X, &MAX_Y, &P);
if(MAX_X == MAX_Y and MAX_Y == P and P == 0)
break;
//for(int i=1; i<=MAX_X; i++)
// for(int j=1; j<=MAX_Y; j++)
// tree[i][j] = 0;
int m = max(MAX_Y+1, MAX_X+1);
memset(tree, 0, sizeof(tree[0][0]) * m * MAX);
scanf("%d", &q);
while(q--){
scanf("\n%c", &c);
if(c == 'A'){
scanf("%d %d %d", &n, &x, &y);
atualiza(x+1, y+1, n);
}
else{
scanf("%d %d %d %d", &x, &y, &z, &w);
int res = selecao(x+1, y+1, z+1, w+1)*P;
printf("%d\n", res);
}
}
printf("\n");
}
} | true |
4dad9fc4f200ed9d04aa334b051f0149b3ee6537 | C++ | lizhieffe/ztl | /src/network/socket_sender.cc | UTF-8 | 1,836 | 2.765625 | 3 | [] | no_license | #include "socket_sender.hh"
#include <cstring>
#include <errno.h>
#include <iostream>
#include <netdb.h>
#include <sys/select.h>
#include <sys/socket.h>
namespace ztl {
namespace {
class SocketSenderImpl : public SocketSender {
public:
SocketSenderImpl(int socket_fd) : socket_fd_(socket_fd) {}
bool Send(const std::string& str) override {
if (socket_fd_ <= 0) {
std::cerr << "Error: socket file descriptor <= 0." << std::endl;
return false;
}
struct timeval timeout;
timeout.tv_sec = 3;
timeout.tv_usec = 0;
int bytes_sent = 0;
while (true) {
fd_set write_fd;
FD_ZERO(&write_fd);
FD_SET(socket_fd_, &write_fd);
int err = select(socket_fd_ + 1, nullptr, &write_fd, nullptr, &timeout);
if (err < 0) {
std::cerr << "Socket write fd set is not ready. Error is: "
<< std::strerror(errno) << std::endl;;
break;
} else if (err == 0) { /* timeout */
continue;
}
bytes_sent = send(socket_fd_, str.c_str() + bytes_sent, str.size(), 0);
if (bytes_sent < 0) {
// TODO: add retry mechanism if the error is not fatal.
//if (WSAGetLastError() != WSAWOULDBLOCK()) {
std::cerr << "Error: connection has problem." << std::endl;
return false;
//}
//n_bytes = 0;
} else {
std::cout << "Sent " << bytes_sent << " bytes." << std::endl;
}
if ((unsigned long)bytes_sent == str.size()) {
std::cout << "Successfully sent data to the peer.\n\n" << std::endl;
return true;
}
}
return false;
}
private:
int socket_fd_;
};
} // namespace
std::unique_ptr<SocketSender> NewSocketSender(int socket_fd) {
return std::unique_ptr<SocketSender>(new SocketSenderImpl(socket_fd));
}
} // namespace ztl
| true |
a6de0c5a28d2b397d9025ce9a1a9d66f45e75b2f | C++ | OTTFFYZY/StandardCodeLibrary | /BasicDataStructure/FenwickTree_2drarq.cpp | UTF-8 | 1,259 | 3.03125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int M=1e3+5;
int bit0[M][M],bit1[M][M],bit2[M][M],bit3[M][M]; //Binary Index Tree
inline int lowbit(int x)
{
return x&(-x);
}
void add(int x,int y,int v) //add v at (x,y)
{
for(int i=x;i<M;i+=lowbit(i))
for(int j=y;j<M;j+=lowbit(j))
{
bit0[i][j]+=v; bit1[i][j]+=v*i;
bit2[i][j]+=v*j; bit3[i][j]+=v*i*j;
}
}
void init(int n,int m,int a[M][M])
{
memset(bit0,0,sizeof(bit0));
memset(bit1,0,sizeof(bit1));
memset(bit2,0,sizeof(bit2));
memset(bit3,0,sizeof(bit3));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
add(i,j,a[i][j]-a[i][j-1]-a[i-1][j]+a[i-1][j-1]);
}
void add(int stx,int sty,int edx,int edy,int v) //add v to (stx~edx,sty~edy)
{
add(stx,sty,v);
add(stx,edy+1,-v);
add(edx+1,sty,-v);
add(edx+1,edy+1,v);
}
int get_sum(int x,int y) //sum of a(1~x,1~y)
{
int ans=0;
for(int i=x;i;i-=lowbit(i))
for(int j=y;j;j-=lowbit(j))
ans+=bit0[i][j]*(x+1)*(y+1)
-bit1[i][j]*(y+1)
-bit2[i][j]*(x+1)
+bit3[i][j];
return ans;
}
int get_sum(int stx,int sty,int edx,int edy) // sum of (stx~edx,sty~edy)
{
return get_sum(edx,edy)-get_sum(stx-1,edy)-get_sum(edx,sty-1)+get_sum(stx-1,sty-1);
}
int main()
{
return 0;
} | true |
09e984b2f6d1bb45dace30cef1f8af2adf5b3ee7 | C++ | webdev1001/dotnetinstaller | /dotNetInstallerLib/InstallSequence.cpp | UTF-8 | 788 | 2.75 | 3 | [
"MIT"
] | permissive | #include "StdAfx.h"
#include "InstallSequence.h"
#include "InstallerSession.h"
InstallSequenceState::InstallSequenceState()
: m_sequence(InstallerSession::Instance->sequence)
{
}
InstallSequenceState::InstallSequenceState(InstallSequence sequence)
: m_sequence(InstallerSession::Instance->sequence)
{
InstallerSession::Instance->sequence = sequence;
}
InstallSequenceState::~InstallSequenceState()
{
InstallerSession::Instance->sequence = m_sequence;
}
std::wstring InstallSequenceUtil::towstring(InstallSequence sequence)
{
switch(sequence)
{
case SequenceInstall:
return L"install";
case SequenceUninstall:
return L"uninstall";
default:
THROW_EX(L"Unsupported install sequence: " << InstallerSession::Instance->sequence << L".");
}
} | true |
a7bbc6bd8f18670c17757122062fd031b5e8ab83 | C++ | tengfeizhilang/homework | /台阶问题.cpp | UTF-8 | 984 | 3.484375 | 3 | [] | no_license |
最好时间复杂度为O(1),最坏时间复杂度为O(n),空间复杂度为O(1)
最好的情况是只执行一次就成功退出,所以时间复杂度为O(1),最坏情况则是要反复检索n次才能成功,所以最坏时间复杂度为O(n),每次检索所需要的内存空间为1,所以空间复杂度为O(1)
#include<iostream>
using namespace std;
//int f(int n)
//{
// if(n==1){return 1;
// }
// if(n==2){
// return 2;
// }
// if(n>2){
// return f(n-1)+f(n-2);
// }
//}
//int main()
//{
// int n;
// cout<<" 递归法"<<endl;
// cout<<"请输入台阶数:";
// cin>>n;
// cout<<" 一共有 "<<f(n)<<" 种走法";
// return 0;
//}
int main(){
int f[90];
f[1]=1;
f[2]=2;
int n;
cout<<" 递推法 "<<endl;
cout<<"请输入台阶数:";
while(scanf("%d",&n)!=EOF){
for(int i=3;i<=n;i++){
f[i]=f[i-1]+f[i-2];
}
cout<<"一共有 "<<f[n]<<" 种走法"<<endl;
}
}
| true |
aa4050a42680d47b9166d7270e633e76e7fd63f7 | C++ | Alitebbal/SolutionTPAliTebbal | /Formes2054583/Formes2054583.cpp | ISO-8859-1 | 8,662 | 3.3125 | 3 | [] | no_license | #include "Formes2054583.h"
#include <string>
#include "Labo06Fonctions.h"
#include <iostream>
#include <time.h>
#include "Menus2054583.h"
using namespace std;
// La fonction pour tracer le rectangle
int traiterRectangle(int choixRemplissage)
{
// Dclaration des variables
int largeur;
int hauteur;
// On demande les informations ncessaires
cout << " Indiquez la largeur : ";
largeur = saisirEntier(); // On appelle cette fonction pour viter que le programme plante quand l'utilisateur entre une chane de caractres ou autre chose qu'un entier
cout << " Indiquez la hauteur : ";
hauteur = saisirEntier();
system("cls");
// Si l'utilisateur choisit le choix : Plein
if (choixRemplissage == 1)
{
cout << " Voici le rectangle plein de " << largeur << " x " << hauteur << endl;
for (int l = 1; l <= hauteur; l++)
{
for (int h = 1; h <= largeur; h++)
{
if ( l==1 || h==1 || l==hauteur || h==largeur ) // le programme dessine une toite juste quand les 4 conditions sont rspectes
cout << "*";
else // Sinon le programme dessine un #
cout <<"#";
}
cout << "\n";
}
}
// Si l'utilisateur choisit le choix : Vide
else
{
cout << " Voici le rectangle vide de " << largeur << " x " << hauteur << endl;
for (int l = 1; l <= largeur; l++)
{
for (int h = 1; h <= hauteur; h++)
{
if ( l == 1 || h == 1 || l == largeur ||h == hauteur) // le programme dessine une toite juste quand les 4 conditions sont rspectes
cout <<"*";
else // Sinon le programme dessine rien
cout <<" ";
}
cout << "\n";
}
}
system("pause"); //Pour laisser le temps l'utilisateur de lire.
return 0;
}
// La fonction pour tracer les triangles
int traiterTriangle(int choixRemplissage)
{
// Dclaration des variables
int random;
int hauteur;
char carac;
// On demande les informations ncessaires
cout << " Indiquez la hauteur : ";
hauteur = saisirEntier(); // On appelle cette fonction pour viter que le programme plante quand l'utilisateur entre une chane de caractres ou autre chose qu'un entier
// Pour avoir un nombre alatoire entre 1 et 4
srand(time(0));
random = rand() % 4 + 1;
system("cls"); // Pour nettoyer l'cran
cout << " Voici le triangle plein de hauteur de " << hauteur << endl;
if (choixRemplissage == 1) // Si l'utilisateur choisit le choix : Plein
{
// Si le nombre alatoire et de 1
if (random == 1)
{
for (int cpt = 0; cpt < hauteur; cpt++) // Pour tracer les lignes
{
for (int i = 0; i <= cpt; i++) // pour tracer les colonnes
{
cout << "*";
}
cout << "\n"; // le programme saute une ligne aprs chaque itration de la premiere boucle
}
}
if (random == 2)
{ // Si le nombre alatoire et de 2
for (int cpt = hauteur; cpt >= 1; cpt--) // On inverse la boucle
{
for (int i = cpt; i > 0; i --)
{
cout << "*";
}
cout << "\n";
}
}
if (random == 3)
{ // Si le nombre alatoire et de 3
for (int cpt = 0; cpt < hauteur; cpt++)
{
for (int s = hauteur - cpt; s > 0; s--)
{
cout << " ";
}
for (int i = 0; i <= cpt; i++)
{
cout << "*";
}
cout << "\n"; // le programme saute une ligne aprs chaque itration de la premiere boucle
}
}
if (random == 4)
{ // Si le nombre alatoire et de 4
for (int cpt = 0; cpt < hauteur; cpt++)
{
for (int s = hauteur - cpt; s > 0; s--)
{
cout << " ";
}
for (int i = cpt; i > 0 - cpt; i--)
{
cout << "*";
}
cout << "\n";
}
}
}
else // Si l'utilisateur choisit le choix : vide
{
if (random == 1)
{ // Si le nombre alatoire et de 1
for (int cpt = 0; cpt <= hauteur; cpt++) // Pour tracer les lignes
{
for (int i = 0; i <= cpt; i++)
{
if (i == cpt || cpt == hauteur || i == 0) // le programme dessine une toite juste quand les 3 conditions sont rspectes
cout << "*";
else // Sinon le programme dessine rien
cout << " ";
}
cout << "\n"; // le programme saute une ligne aprs chaque itration de la premiere boucle
}
}
if (random == 2)
{ // Si le nombre alatoire et de 2
for (int cpt = 0; cpt <= hauteur; cpt++)
{
for (int i = 0; i <= cpt; i++)
{
if (i == cpt || cpt == hauteur || i == 0)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
}
if (random == 3)
{ // Si le nombre alatoire et de 3
for (int cpt = 0; cpt <= hauteur; cpt++)
{
for (int i = 0; i <= cpt; i++)
{
if (i == cpt || cpt == hauteur || i == 0)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
}
if (random == 4)
{ // Si le nombre alatoire et de 4
for (int cpt = 0; cpt <= hauteur; cpt++)
{
for (int i = 0; i <= cpt; i++)
{
if (i == cpt || cpt == hauteur || i == 0)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
}
}
cout << endl;
system("pause"); // Pour mettre une pause
return 0;
}
int traiterCarre(int choixRemplissage)
{
// Dclaration des variables
int hauteur;
int largeur;
// On demande les informations ncessaires
cout << " Indiquez la hauteur : ";
hauteur = saisirEntier(); // On appelle cette fonction pour viter que le programme plante quand l'utilisateur entre une chane de caractres ou autre chose qu'un entier
largeur = hauteur;
system("cls"); // Pour nettoyer l'cran
if (choixRemplissage == 1) // Si l'utilisateur choisit le choix : Plein
{
cout << " Voici le carr plein de " << largeur << " x " << hauteur << endl;
for (int l = 1; l <= hauteur; l++) // Pour tracer les lignes
{
for (int h = 1; h <= largeur; h++) // Pour tracer la largeur
{
if (l == 1 || h == 1 || l == hauteur || h == largeur) // le programme dessine une toite juste quand les 4 conditions sont rspectes
cout << "*";
else // Sinon le programme dessine un #
cout << "#";
}
cout << "\n"; // le programme saute une ligne aprs chaque itration de la premiere boucle
}
}
else // Si l'utilisateur choisit le choix : Plein
{
cout << " Voici le carr vide de " << largeur << " x " << hauteur << endl;
for (int l = 1; l <= largeur; l++)
{
for (int h = 1; h <= hauteur; h++)
{
if (l == 1 || h == 1 || h == hauteur|| l == largeur) // le programme dessine une toite juste quand les 4 conditions sont rspectes
cout << "*";
else // Sinon le programme dessine rien
cout << " ";
}
cout << "\n";
}
}
system("pause"); //Pour laisser le temps l'utilisateur de lire.
return 0;
}
int traiterLosange(int choixRemplissage)
{
int hauteur;
// On demande les informations ncessaires
cout << " Indiquez la hauteur : ";
hauteur = saisirEntier();
system("cls"); // Pour nettoyer l'cran
if (choixRemplissage == 1) // Si l'utilisateur choisit le choix : Plein
{
for (int cpt = 0; cpt < hauteur; cpt++ )
{
for ( int i = 0; i < cpt; i++)
{
cout << "* " << endl;
}
}
}
else // Si l'utilisateur choisit le choix : Vide
{
for (int cpt = 0; cpt < hauteur; cpt++)
{
cout << "*" << endl;
}
}
system("pause"); //Pour laisser le temps l'utilisateur de lire.
return 0;
}
int traiterParallelogramme(int choixRemplissage)
{
// Dclaration des variables
int hauteur;
// On demande les informations ncessaires
cout << " Indiquez la hauteur : ";
hauteur = saisirEntier();
system("cls");
if (choixRemplissage == 1) // Si l'utilisateur choisit le choix : Plein
{
for (int cpt = 1; cpt <= hauteur; cpt++) // Pour tracer les lignes
{
for (int j = 1; j <= (hauteur - cpt); ++j)
cout << " ";
if (cpt == 1 || cpt == hauteur)
for (int k = 1; k <= hauteur; ++k)
cout << "*";
else
for (int i = 1; i <= hauteur; i++)
{
if (i == 1 || i == hauteur)
cout << "*";
else cout << "#";
}
cout << endl;
}
}
else // Si l'utilisateur choisit le choix : Vide
{
for (int cpt = 1; cpt <= hauteur; cpt++) // Pour tracer les lignes
{
for (int j = 1; j <= (hauteur - cpt); j++)
cout << " ";
if (cpt == 1 || cpt == hauteur)
for (int k = 1; k <= hauteur; k++)
cout << "*";
else
for (int i = 1; i <= hauteur; i++)
{
if (i == 1 || i == hauteur)
cout << "*";
else cout << " ";
}
cout << endl;
}
}
system("pause"); //Pour laisser le temps l'utilisateur de lire.
return 0;
}
| true |
0db860afad1e986db7a92429c013cbda32b7a288 | C++ | lzhu1992/util | /src/geom/test/TestCube.cc | UTF-8 | 644 | 2.6875 | 3 | [] | no_license | #include "../Vec3d.hh"
using namespace std;
using namespace geom;
#define print(v) cout << #v << ' ' << v << '\n'
/*
Test all operations for Cube
*/
int main() {
const Cube c1(0, 0, 0, 9); print(c1);
const Cube c2(0, 0, 0, 9, 9, 9); print(c2);
const Cube c3(0, 0, 0, 7, 7, 7); print(c3);
double d1 = c1.volume(); print(d1);
double d2 = c1.area(); print(d2);
double d3 = c2.volume(); print(d1);
double d4 = c2.area(); print(d2);
double d5 = c3.volume(); print(d1);
double d6 = c3.area(); print(d2);
}
| true |
bbe3a3c6bedf593a38ceff2cf46b20659bc44ccf | C++ | huangr/HS-Competitive-Coding | /Codeforces_Problems/cf-448A.cpp | UTF-8 | 446 | 2.640625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int cups = 0, medal = 0, a, b, c, d, e, f;
cin >> a >> b >> c >> d >> e >> f;
int shelves = 0;
cin >> shelves;
cups = a+b+c;
medal = d+e+f;
int numneed = 0;
if(cups % 5 != 0) numneed += cups/5 + 1;
else numneed += cups/5;
if(medal % 10 != 0) numneed += medal/10 + 1;
else numneed += medal/10;
if(numneed > shelves) cout << "NO" << '\n';
else cout << "YES" << '\n';
return 0;
} | true |
5d5adfb88753ce54c89be9269d94874afb7af6b3 | C++ | ycwang812/SLAMCar | /PHOENIXEngine/PHOENIX/PX2Engine/Core/PX2ErrorHandler.cpp | UTF-8 | 2,260 | 2.640625 | 3 | [] | no_license | // PX2ErrorHandler.cpp
#include "PX2ErrorHandler.hpp"
#include "PX2Log.hpp"
#include "PX2ScopedCS.hpp"
using namespace PX2;
//----------------------------------------------------------------------------
ErrorHandler* ErrorHandler::Get()
{
return mHandler;
}
//----------------------------------------------------------------------------
ErrorHandler* ErrorHandler::mHandler = 0;
Mutex ErrorHandler::mMutex;
//----------------------------------------------------------------------------
ErrorHandler::ErrorHandler()
{
}
//----------------------------------------------------------------------------
ErrorHandler::~ErrorHandler()
{
}
//----------------------------------------------------------------------------
void ErrorHandler::OnException(const Exception& exc)
{
assertion(false, exc.what());
PX2_LOG_ERROR(exc.what());
}
//----------------------------------------------------------------------------
void ErrorHandler::OnException(const std::exception& exc)
{
assertion(false, exc.what());
PX2_LOG_ERROR(exc.what());
}
//----------------------------------------------------------------------------
void ErrorHandler::OnException()
{
assertion(false, "unknown exception");
PX2_LOG_ERROR("unknown exception");
}
//----------------------------------------------------------------------------
void ErrorHandler::Handle(const Exception& exc)
{
ScopedCS cs(&mMutex);
try
{
if (mHandler)
mHandler->OnException(exc);
}
catch (...)
{
}
}
//----------------------------------------------------------------------------
void ErrorHandler::Handle(const std::exception& exc)
{
ScopedCS cs(&mMutex);
try
{
if (mHandler)
mHandler->OnException(exc);
}
catch (...)
{
}
}
//----------------------------------------------------------------------------
void ErrorHandler::Handle()
{
ScopedCS cs(&mMutex);
try
{
if (mHandler)
mHandler->OnException();
}
catch (...)
{
}
}
//----------------------------------------------------------------------------
ErrorHandler* ErrorHandler::Set(ErrorHandler* handler)
{
assertion(0 != handler, "pointer must not be 0");
ScopedCS cs(&mMutex);
ErrorHandler* old = mHandler;
mHandler = handler;
return old;
}
//---------------------------------------------------------------------------- | true |
3ccb6b5b0091fe6bf54f0f9d9fad8c343460a40c | C++ | Lekheshwar/LeetCode | /Min_Height_Tree.cpp | UTF-8 | 1,182 | 2.6875 | 3 | [] | no_license | // QUESTION LINK : https://leetcode.com/explore/featured/card/november-leetcoding-challenge/564/week-1-november-1st-november-7th/3519/
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if (n == 1)return {0};
vector<int> leaves;
vector<int> degree(n, 0);
unordered_map<int, unordered_set<int>> adj;
for (auto pair : edges) {
adj[pair[0]].insert(pair[1]);
adj[pair[1]].insert(pair[0]);
degree[pair[0]]++;
degree[pair[1]]++;
}
for (int i = 0; i < n; i++) {
if (adj[i].size() == 1) {
leaves.push_back(i);
}
}
while (n > 2) {
vector<int> newLeaves;
n = n - leaves.size();
for (auto leaf : leaves) {
for (auto padosi : adj[leaf]) {
adj[padosi].erase(leaf);
degree[padosi]--;
if (degree[padosi] == 1)
newLeaves.push_back(padosi);
}
}
leaves = newLeaves;
}
return leaves;
}
}; | true |
e3b677b2cb9b22f5062a8bd7a7e61eb11c4a1d5e | C++ | timothydmorton/transit | /src/ld_test.cpp | UTF-8 | 897 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "limb_darkening.h"
#include "numerical_limb_darkening.h"
using transit::QuadraticLaw;
using transit::NumericalLimbDarkening;
using transit::QuadraticLimbDarkening;
int main ()
{
double q1 = 0.9999, q2 = 0.9999,
u1 = 2*q1*q2, u2 = q1*(1-2*q2);
QuadraticLaw* law = new QuadraticLaw(u1, u2);
NumericalLimbDarkening ld(law, 1e-9, 1000, 100);
QuadraticLimbDarkening gld(u1, u2);
int n = 0;
double p = 0.1, z, norm = 0.0, mx = -INFINITY;
for (z = 0.0; z < 1.1+p; z += 1.438956e-4, ++n) {
double v, v0;
v = ld(p, z);
v0 = gld(p, z);
if (v0 > 1) std::cout << z - (1+p) << " " << v0 - 1 << std::endl;
norm += (v - v0) * (v - v0);
if (fabs(v-v0) > mx) mx = fabs(v - v0);
}
std::cout << norm / n << std::endl;
std::cout << mx << std::endl;
delete law;
return 0;
}
| true |
217c5d96a2a543f137a6e1f51e87785ef27aac5b | C++ | meteora211/SelfLearning | /cpp_concurrency_in_action/parallel_design/parallel_std.cc | UTF-8 | 3,088 | 3.328125 | 3 | [] | no_license | #include <atomic>
#include <thread>
#include <latch>
#include <iostream>
#include <vector>
#include <chrono>
#include <ranges>
#include <algorithm>
#include <numeric>
#include <future>
using namespace std;
using namespace chrono;
using namespace std::chrono_literals;
template<typename Iterator, typename Func>
void parallel_for_each(Iterator first, Iterator last, Func f) {
std::size_t dist = std::distance(first, last);
if (!dist) return;
std::size_t hardware_threads = std::thread::hardware_concurrency();
auto block_size = dist / hardware_threads;
auto start = first;
std::vector<std::future<void>> futures;
futures.resize(hardware_threads);
for (size_t index = 0; index < hardware_threads; ++index) {
auto end = start;
std::advance(end, block_size);
if (index == hardware_threads - 1) {
end = last;
}
// use = in lambda. pass by ref cause random crash since start/end is not constant.
// and changes in other thread.
futures[index] = std::async([=](){std::for_each(start, end, f);});
/* std::for_each(start, end, f); */
std::advance(start, block_size);
}
for (auto&& f : futures) {
f.get();
}
}
template<typename Iterator, typename T>
Iterator simple_find(Iterator first, Iterator last, T value, std::atomic<bool>& stop_flag) {
for (; first != last && !stop_flag; ++first) {
if (*first == value) {
stop_flag.store(true);
return first;
}
}
return last;
}
template<typename Iterator, typename T>
Iterator parallel_find(Iterator first, Iterator last, T value) {
std::size_t dist = std::distance(first, last);
if (!dist) return first;
std::atomic<bool> stop_flag = false;
std::size_t hardware_threads = std::thread::hardware_concurrency();
auto block_size = dist / hardware_threads;
auto start = first;
std::vector<std::future<Iterator>> futures;
futures.resize(hardware_threads);
for (size_t index = 0; index < hardware_threads; ++index) {
auto end = start;
std::advance(end, block_size);
if (index == hardware_threads - 1) {
end = last;
}
// use = in lambda. pass by ref cause random crash since start/end is not constant.
// and changes in other thread.
futures[index] = std::async([=,&stop_flag](){
auto res = simple_find(start, end, value, stop_flag);
if (res == end) {
res = last;
}
return res;
});
/* std::for_each(start, end, f); */
std::advance(start, block_size);
}
for (auto&& f : futures) {
auto res = f.get();
if (res != last) {
return res;
}
}
return last;
}
int main() {
vector<int> list(200);
std::iota(list.begin(), list.end(), -100);
parallel_for_each(list.begin(), list.end(), [](int& i) {i+= i;});
/* std::for_each(list.begin(), list.end(), [](int& i) {i= i*i;}); */
for (auto& i : list) {
std::cout << i << " ";
}
std::cout << std::endl;
auto res = parallel_find(list.begin(), list.end(), 12);
auto ref = std::find(list.begin(), list.end(), 12);
std::cout << *res << " " << *ref << std::endl;
}
| true |
d6192ff9a20679d6cf2f42ffd561dd2aa66d385e | C++ | Flotchie/main | /RasPi/RaspPLC/src/Data.cpp | ISO-8859-1 | 4,586 | 2.671875 | 3 | [] | no_license | /*
* Data.cpp
*
* Created on: 29 janv. 2019
* Author: Bertrand
*/
#include "Data.h"
#include "StringTools.h"
#include "json/json.h"
#include <chrono>
using namespace std;
bool Data::InitFromIni(CSimpleIniA& ini, std::map<std::string, Data*>& datas)
{
CSimpleIniA::TNamesDepend variableKeys;
ini.GetAllKeys("variables", variableKeys);
for(auto& key : variableKeys)
{
const char* value = ini.GetValue("variables", key.pItem);
vector<string> infos;
Tokenize(value,",",infos);
string sType = infos[0];
bool input = false;
if(infos.size()>1)
{
if(infos[1]=="input") input = true;
}
if(sType=="bool")
{
datas.insert(make_pair(key.pItem, new TData<bool>(key.pItem, Data::DT_BOOL, input)));
}
else if(sType=="float")
{
datas.insert(make_pair(key.pItem, new TData<double>(key.pItem, Data::DT_FLOAT, input)));
}
else
{
printf("ERROR - invalid type[%s]", sType.c_str());
return false;
}
}
return true;
}
void Data::SplitName(const std::string& fullName, std::string& path
, std::string& shortName)
{
path = fullName;
std::replace( path.begin(), path.end(), '.', '/');
std::size_t posLastDot = fullName.find_last_of('.');
if(posLastDot==std::string::npos)
shortName = fullName;
else
shortName = fullName.substr(posLastDot+1);
}
/**
* lecture d'une donne
* {
* "name": "eau",
* "date": "2018-12-30 15:55:48",
* "value": 19.2
* }
*/
bool Data::ReadData(const string& dataPath, Data& data, bool& changed)
{
changed = false;
string path = form("%s%s", dataPath.c_str(), data.m_path.c_str());
FILE* fp = fopen(path.c_str(), "rb");
if(fp!=NULL)
{
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *json = (char*)malloc(fsize + 1);
if(json==nullptr)
{
fprintf(stderr, "VariableManager::readData: malloc failed");
fclose(fp);
return false;
}
fread(json, fsize, 1, fp);
fclose(fp);
json[fsize] = 0;
Json::Reader reader;
Json::Value root;
reader.parse(json,root,false);
if(data.m_type==Data::DT_BOOL)
{
bool newValue = root["value"].asBool();
bool& value = dynamic_cast<TData<bool>&>(data).m_value;
if( (newValue!=value) || data.m_undefinedValue)
{
data.m_undefinedValue = false;
data.m_date = root["date"].asString();
value = newValue;
changed = true;
}
}
else if(data.m_type==Data::DT_FLOAT)
{
double newValue = root["value"].asDouble();
double& value = dynamic_cast<TData<double>&>(data).m_value;
if( (newValue!=value) || data.m_undefinedValue)
{
data.m_undefinedValue = false;
data.m_date = root["date"].asString();
value = newValue;
changed = true;
}
}
free(json);
}
else
{
return false;
}
return true;
}
bool Data::SetData(const string& dataPath,Data& data)
{
data.m_undefinedValue = false;
string value;
if(data.m_type==Data::DT_BOOL)
value = dynamic_cast<TData<bool>&>(data).m_value?"true":"false";
else if(data.m_type==Data::DT_FLOAT)
value=form("%.1f", dynamic_cast<TData<double>&>(data).m_value);
return SetData(dataPath, data.m_path, data.m_shortName, data.m_date, value);
}
bool Data::SetData(const string& dataPath, const string& path, const string& shortName
, const string& date, const string& value )
{
bool res = true;
// criture fichier
string fullPath = form("%s%s", dataPath.c_str(), path.c_str());
FILE* fp = fopen(fullPath.c_str(), "wb");
if(fp!=NULL)
{
fputs("{\n",fp);
fputs(form("\"name\": \"%s\",\n", shortName.c_str()).c_str(),fp);
fputs(form("\"date\": \"%s\",\n", date.c_str()).c_str(),fp);
fputs(form("\"value\": %s\n", value).c_str(),fp);
fputs("}\n",fp);
fclose(fp);
}
else
{
res=false;
}
return res;
}
string Data::DateNow()
{
auto now = std::chrono::system_clock::now();
std::time_t tt = std::chrono::system_clock::to_time_t(now);
char date[40];
strftime(date, 20, "%Y-%m-%d %H:%M:%S", localtime(&tt));
return string(date);
}
| true |
03117cf7f594f8fc9f843c40d01c9315934323eb | C++ | Lawlets/FrogEngine | /Math/Tools.h | UTF-8 | 1,032 | 2.9375 | 3 | [] | no_license | #ifdef MATH_EXPORTS
#define TOOLS_API __declspec(dllexport)
#else
#define TOOLS_API __declspec(dllimport)
#endif
#define PI 3.14159265359f
#include <string>
#include "Vector3d.h"
namespace Math
{
struct Tools
{
// Functions
template<class T>
static T Clamp(T f, T min, T max);
TOOLS_API static void Swap(float& val1, float& val2);
TOOLS_API static float Deg2Rad(float value);
TOOLS_API static float Rad2Deg(float value);
TOOLS_API static void Split(std::string origin, const char* separator, bool begin, std::string& res1, std::string& res2);
TOOLS_API static Vector3d Normalized(const Vector3d vec);
TOOLS_API static Vector3d Cross(const Vector3d vec1, const Vector3d vec2);
TOOLS_API static float Sign(float value);
TOOLS_API static bool Epsilon(int v1, int v2);
TOOLS_API static bool Epsilon(float v1, float v2);
//Clamp any number into a ratio from 0 to 1
TOOLS_API static float ToRatio(float f);
//Ration need to be in range of 0 to 1
TOOLS_API static float ReverseRatio(float f);
};
} | true |
faa76c6d86717bee0c0c6a505a925d7388599512 | C++ | zl6977/BasicKnowledge | /HuaWei/40输入一行字符,分别统计出包含英文字母空格数字和其它字符的个数.cpp | UTF-8 | 553 | 2.875 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "HuaWei.h"
#include <stdio.h>
#include <ctype.h>
#include <string>
#include <iostream>
using namespace std;
int test_40()
{
string str;
while (getline(cin, str))
{
int English = 0, Blank = 0, Number = 0, Other = 0;
for (int i = 0;i<str.size();i++)
{
char tmp = str[i];
if (isalpha(tmp)) English++;
else if (isblank(tmp)) Blank++;
else if (isdigit(tmp)) Number++;
else Other++;
}
cout << English << endl;
cout << Blank << endl;
cout << Number << endl;
cout << Other << endl;
}
return 0;
} | true |
6b6e2a900348b2630a357c9f7251c6e7a97e8eb1 | C++ | hakaorson/CodePractise | /Dynamic/paint-fence-two.cpp | UTF-8 | 516 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
#include <unordered_map>
#include <array>
#include <numeric>
using namespace std;
const int maxsize{ 100 };
int main() {
int size{};
cin >> size;
int matrix[maxsize + 1]{};
for (int i = 1; i <= size; i++) {
if (i == 1) {
matrix[i] = 3;continue;
}
else if (i == 2) {
matrix[i] = 6; continue;
}
else {
matrix[i] = matrix[i - 1];
matrix[i] += matrix[i - 2] * 2;
}
}
int result = matrix[size];
cout << result;
} | true |
105012dae7409e0db6139c43cd190c0485e1c691 | C++ | ikold/Coil | /Coil/Source/Platform/Windows/WindowsInput.cpp | UTF-8 | 1,321 | 2.53125 | 3 | [
"BSD-3-Clause",
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | #include "pch.h"
#include "WindowsInput.h"
#include "Coil/Core/Application.h"
#include <GLFW/glfw3.h>
namespace Coil
{
// static assign binding WindowsInput implementation methods with static methods in base Input class
Scope<Input> Input::Instance = CreateScope<WindowsInput>();
bool WindowsInput::IsKeyPressedImpl(int32 keycode)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
const auto state = glfwGetKey(window, keycode);
return state == GLFW_PRESS || state == GLFW_REPEAT;
}
bool WindowsInput::IsMouseButtonPressedImpl(int32 button)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
const int32 state = glfwGetMouseButton(window, button);
return state == GLFW_PRESS;
}
std::pair<float32, float32> WindowsInput::GetMousePositionImpl()
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
float64 xPosition, yPosition;
glfwGetCursorPos(window, &xPosition, &yPosition);
return { static_cast<float32>(xPosition), static_cast<float32>(yPosition) };
}
float32 WindowsInput::GetMouseXImpl()
{
auto [x, y] = GetMousePositionImpl();
return x;
}
float32 WindowsInput::GetMouseYImpl()
{
auto [x, y] = GetMousePositionImpl();
return y;
}
}
| true |
64d737f34a3df4fb6e0202291566fbbaef01dced | C++ | bhupeshprajapati/UdemyCPP | /sectionChallengeStreamsIO/main.cpp | UTF-8 | 2,644 | 3.046875 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include<vector>
#include<string>
struct City{
std::string name;
long population;
double cost;
};
//Assume each country has has atleast one city
struct Country{
std::string name;
std::vector<City> cities;
};
struct Tours{
std::string title;
std::vector<Country> countries ;
};
void ruler(){
std::cout<<"1234567890123456789012345678901234567890123456789012345678901234567890"<<std::endl;
}
int main(){
Tours tours{
"Tour Ticket Prices from Miami",
{
{
"Colombia",{
{"Bogota", 8778999,400.98},
{"Cali",240000,420.12},
{"Medellin",234332423,342.34},
{"Cartagena",9324932,4335.23}
}
},
{
"Brazil",{
{"Rio De Janiero", 8778999,400.98},
{"Sao Paulo",240000,420.12},
{"Salvador",234332423,342.34},
{"zuzupark",9324932,4335.23}
}
},
{
"India",{
{"Delhi", 8778999,400.98},
{"Agra",240000,420.12},
{"Jaipur",234332423,342.34},
{"Vadodara",9324932,4335.23}
}
},
}
};
const int total_width{70};
const int field1_width{20};//country name
const int field2_width{20};//city name
const int field3_width{15}; //Population
const int field4_width{15};//cost
//Display the Report title header centered in width of total_width
//make it a function for practice
ruler();
int title_length=tours.title.length();
std::cout<<std::setw((total_width-title_length)/2)<<""<<tours.title<<std::endl;
std::cout<<std::endl;
std::cout<<std::setw(field1_width)<<std::left<<"Country"
<<std::setw(field2_width)<<std::left<<"City"
<<std::setw(field3_width)<<std::right<<"Population"
<<std::setw(field4_width)<<std::right<<"Price"
<<std::endl;
std::cout<<std::setw(total_width)
<<std::setfill('-')<<""
<<std::endl;
std::cout<<std::setfill(' ');
std::cout<<std::setprecision(2)<<std::fixed;
// for(auto country:tours.countries){
// for(auto city:country.cities){
// std::cout<<std::setw(field1_width)<<std::left<<country.name
// <<std::setw(field2_width)<<std::left<<city.name
// <<std::setw(field3_width)<<std::right<<city.population
// <<std::setw(field4_width)<<std::right<<city.cost
// <<std::endl;
// }
// }
//========== OR ===============
for(Country country:tours.countries){
for(size_t i=0;i<country.cities.size();i++){
std::cout<<std::setw(field1_width)<<std::left<<((i==0)?country.name:" ")
<<std::setw(field2_width)<<std::left<<country.cities.at(i).name
<<std::setw(field3_width)<<std::right<<country.cities.at(i).population
<<std::setw(field4_width)<<std::right<<country.cities.at(i).cost
<<std::endl;
}
}
return 0;
} | true |
5da93aacb083d9f3c1bb642d4cf47cf437406c72 | C++ | Hz-Lin/codam2019 | /cpp/cpp06/ex00/Conversion.hpp | UTF-8 | 1,623 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | /* ************************************************************************** */
/* */
/* :::::::: */
/* Conversion.hpp :+: :+: */
/* +:+ */
/* By: hlin <hlin@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2022/06/09 10:40:03 by hlin #+# #+# */
/* Updated: 2022/06/09 10:40:04 by hlin ######## odam.nl */
/* */
/* ************************************************************************** */
#ifndef CONVERSION_HPP
#define CONVERSION_HPP
# define RED "\033[1;31m"
# define RESET "\033[m"
#include <iostream>
class Conversion {
public:
// Explicit Keyword is used to mark constructors to not implicitly convert types
explicit Conversion(std::string input);
~Conversion();
Conversion(Conversion const &obj);
Conversion &operator=(Conversion const &obj);
std::string getInput();
bool checkInputType();
void outputConversion();
private:
std::string _input;
bool isChar();
bool isInt();
bool isFloat();
bool isDouble();
bool isSpecialValue();
void outputSpecial();
void outputChar(std::string input);
void outputNum(std::string input);
};
#endif //CONVERSION_HPP
| true |
90a6e8a73a0442771f9bab65a6d0f4eed74f90d4 | C++ | P140N/origin | /Alg/main.cpp | UTF-8 | 1,365 | 2.75 | 3 | [] | no_license | #include <QtGui/QApplication>
#include <QtOpenGL/QGLWidget>
#include <QDesktopWidget>
#include "GLWidget.h"
#include "Polygon.h"
#include "Point.h"
#include "MonotonePartition.h"
#include <list>
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[]){
if (argc > 1) {
for (int i = 1; i < argc; i++) {
list<Geometry::Polygon> polygons;
list<Geometry::Polygon> triangles;
Geometry::Polygon::ReadPolygonsFromFile(&polygons, argv[i]);
Geometry::MonotonePartition::Triangulate(&polygons, &triangles);
bool correctness = Geometry::MonotonePartition::CheckCorrectness(&polygons, &triangles);
if (correctness == true)
cout << "Test " << '"' << argv[i] << '"' << " passed" << endl;
else
cout << "Test " << '"' << argv[i] << '"' << " FAILED" << endl;
}
} else {
QApplication app(argc, argv);
GLWidget window;
int windowWidth = 800;
int windowHeight = 600;
window.resize(windowWidth,windowHeight);
QRect screen = app.desktop()->screenGeometry();
window.move(screen.width()/2 - windowWidth/2,
screen.height()/2 - windowHeight/2);
window.show();
return app.exec();
}
return 0;
}
| true |
ce4c82e9b98047efefb37c9a317dcc4ed9e95bee | C++ | aidaka/KayoVM | /vm/rtda/heap/Object.cpp | UTF-8 | 2,882 | 2.859375 | 3 | [
"MIT"
] | permissive | /*
* Author: kayo
*/
#include <sstream>
#include "../ma/Class.h"
#include "Object.h"
#include "../ma/Field.h"
#include "../../symbol.h"
#include "StringObject.h"
using namespace std;
Object *Object::newInst(Class *c)
{
if (c == java_lang_String) {
return StringObject::newInst(""); // todo
}
size_t size = sizeof(Object) + c->instFieldsCount * sizeof(slot_t);
return new(g_heap_mgr.get(size)) Object(c);
}
void Object::operator delete(void *rawMemory,std::size_t size) throw()
{
// todo 将内存返回 g_heap_mgr
}
Object *Object::clone() const
{
size_t s = size();
return (Object *) memcpy(g_heap_mgr.get(s), this, s);
}
void Object::setFieldValue(Field *f, slot_t v)
{
assert(f != nullptr);
assert(!f->isStatic());
if (!f->categoryTwo) {
data[f->id] = v;
} else { // categoryTwo
data[f->id] = 0; // 高字节清零
data[f->id + 1] = v; // 低字节存值
}
}
void Object::setFieldValue(Field *f, const slot_t *value)
{
assert(f != nullptr && !f->isStatic() && value != nullptr);
data[f->id] = value[0];
if (f->categoryTwo) {
data[f->id + 1] = value[1];
}
}
void Object::setFieldValue(const char *name, const char *descriptor, slot_t v)
{
assert(name != nullptr && descriptor != nullptr);
setFieldValue(clazz->lookupInstField(name, descriptor), v);
}
void Object::setFieldValue(const char *name, const char *descriptor, const slot_t *value)
{
assert(name != nullptr && descriptor != nullptr && value != nullptr);
setFieldValue(clazz->lookupInstField(name, descriptor), value);
}
const slot_t *Object::getInstFieldValue0(const char *name, const char *descriptor) const
{
assert(name != nullptr && descriptor != nullptr);
Field *f = clazz->lookupField(name, descriptor);
if (f == nullptr) {
jvm_abort("error, %s, %s\n", name, descriptor); // todo
}
return data + f->id;
}
bool Object::isInstanceOf(const Class *c) const
{
if (c == nullptr) // todo
return false;
return clazz->isSubclassOf(c);
}
const slot_t *Object::unbox() const
{
if (clazz->isPrimitive()) {
// value 的描述符就是基本类型的类名。比如,private final boolean value;
Field *f = clazz->lookupField(S(value), clazz->className);
if (f == nullptr) {
jvm_abort("error, %s, %s\n", S(value), clazz->className); // todo
}
return data + f->id;
// return getInstFieldValue(S(value), clazz->class_name);
}
// todo error!!!!!!!!
jvm_abort("error");
}
size_t Object::size() const
{
return sizeof(*this) + clazz->instFieldsCount * sizeof(slot_t);
}
bool Object::isArray() const
{
return clazz->isArray();
}
string Object::toString() const
{
ostringstream os;
os << "Object(" << this << "), " << clazz->className;
return os.str();
}
| true |
063f810d9ee3ccb8b3027360562de80ba383182e | C++ | alexcortes18/Programacion2 | /1 Parcial/programa9-Tarea2/programa9-Tarea2.cpp | UTF-8 | 250 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int n,numero;
cout<<"Ingrese el numero:...";
cin>>numero;
while (numero>0)
{
n=numero%10;
numero=numero/10;
cout<<n;
}
cout<<endl;
system("PAUSE");
}
| true |
6f3e6b949ee89b878336ae1c602643825edb04a9 | C++ | Jucesr/videogames | /PuyoPuyo/Source Files/Player.cpp | UTF-8 | 10,832 | 3.140625 | 3 | [] | no_license | //*************** Player Class ***************
#include "../Header Files/Player.h"
Player::Player(int nheadStartX, int nheadStartY, int npuyoWidth, int npuyoHeight, Texture* npuyoSprite , int nxrenderOffset, int nyrenderOffset){
puyoHeight = npuyoHeight;
puyoWidth = npuyoWidth;
startPositionX = nheadStartX;
startPositionY = nheadStartY;
puyoSprite = npuyoSprite;
xrenderOffset = nxrenderOffset;
yrenderOffset = nyrenderOffset;
topMovesQueue = 0;
topRotationQueue = 0;
currentRecordMovesQueue = 0;
currentRecordRotationQueue = 0;
acceleration = 0;
moveFast = false;
currentDirection.xDir = 0;
currentDirection.yDir = 1;
keyState[KEY_R] = false;
keyState[KEY_LEFT] = false;
keyState[KEY_RIGHT] = false;
freeFalling = false;
createPuyo();
}
void Player::createPuyo(){
int randomPuyoType;
randomPuyoType = rand() % PUYO_TOTAL;
puyoHead = new Puyo(startPositionX, startPositionY, puyoWidth, puyoHeight, randomPuyoType, puyoSprite, xrenderOffset, yrenderOffset);
randomPuyoType = rand() % PUYO_TOTAL;
puyoTail = new Puyo(startPositionX, startPositionY - 1, puyoWidth, puyoHeight, randomPuyoType, puyoSprite, xrenderOffset, yrenderOffset);
headPrevPosition.x = startPositionX;
headPrevPosition.y = startPositionY;
tailPrevPosition.x = startPositionX;
tailPrevPosition.y = startPositionY - 1;
puyoState = COMPLETE;
}
void Player::render( SDL_Renderer* renderer ){
puyoHead->render();
puyoTail->render();
}
void Player::setSpeed(int x, int y, int rot){
x_speed = x;
y_speed = y;
rotation_speed = rot;
y_speed_normal = y;
y_speed_fast = y/10;
x_speed_normal = x;
x_speed_fast = x/2;
}
void Player::moveHorizontal(Uint32 time){
//This if control the movement speed. Only got executed every (x_speed) miliseconds
if( time % x_speed == 1 && hasMovedHorizontal == false )
{
//If movefast mode is activated.
if ( moveFast ){
movePuyosHorizontal(puyoHead->getPosX() + currentDirection.xDir, puyoTail->getPosX() + currentDirection.xDir);
/*puyoHead->setPosX(puyoHead->getPosX() + currentDirection.xDir);
puyoTail->setPosX(puyoTail->getPosX() + currentDirection.xDir);*/
}else{
//Check if there is an element in the queue
if( currentRecordMovesQueue < topMovesQueue ){
//Get the element and go to the next elment in the queue
currentDirection.xDir = movesQueue[currentRecordMovesQueue].xDir;
currentDirection.yDir = movesQueue[currentRecordMovesQueue].yDir;
currentRecordMovesQueue ++;
movePuyosHorizontal(puyoHead->getPosX() + currentDirection.xDir, puyoTail->getPosX() + currentDirection.xDir);
}else{
// There was no move, the direction has't changed. Reset queue
topMovesQueue = 0;
currentRecordMovesQueue = 0;
}
}
//This flag is used to prevent the code above to get executed more than once in a milisecond
hasMovedHorizontal = true;
}else if ( time % x_speed != 1 )
{
//Now when the milisecond has change the flag changes its value in order to execute the code the next (SpeedRate) milisecond
hasMovedHorizontal = false;
}
}
void Player::moveDown(Uint32 time, bool invert){
//This if control the movement speed. Only got executed every (y_speed) miliseconds
if( time % y_speed == 1 && hasMovedVertical == false )
{
if (invert == true){
movePuyosVertical(puyoHead->getPosY() - 1, puyoTail->getPosY() - 1);
}else{
movePuyosVertical(puyoHead->getPosY() + 1, puyoTail->getPosY() + 1);
}
//This flag is used to prevent the code above to get executed more than once in a milisecond
hasMovedVertical = true;
}else if ( time % y_speed != 1 )
{
//Now when the milisecond has change the flag changes its value in order to execute the code the next (SpeedRate) milisecond
hasMovedVertical = false;
}
}
void Player::rotate(Uint32 time){
//This if control the movement speed. Only got executed every (rotation_speed) miliseconds
if( time % rotation_speed == 1 && hasRotated == false )
{
//Check if there is an element in the queue
if( topRotationQueue > 0 && currentRecordRotationQueue < topRotationQueue){
//Get the element and go to the next elment in the queue
nextRotation.xDir = rotationQueue[currentRecordRotationQueue].xDir;
nextRotation.yDir = rotationQueue[currentRecordRotationQueue].yDir;
currentRecordRotationQueue ++;
movePuyosVertical( puyoHead->getPosY(), puyoHead->getPosY() + nextRotation.yDir);
movePuyosHorizontal(puyoHead->getPosX(), puyoHead->getPosX() + nextRotation.xDir);
}else{
// There was no rotation. Reset queue
topRotationQueue = 0;
currentRecordRotationQueue = 0;
}
//This flag is used to prevent the code above to get executed more than once in a milisecond
hasRotated = true;
}else if ( time % y_speed != 1 )
{
//Now when the milisecond has change the flag changes its value in order to execute the code the next (SpeedRate) milisecond
hasRotated = false;
}
}
void Player::freePlayer(){
//mainSnake->freeSnake();
}
Player::~Player(){
freePlayer();
}
void Player::handle(bool invertMode){
//Get current keystate
const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
//-----------Move control-------------------
//If the user is pressing the right key
if( currentKeyStates[ SDL_SCANCODE_RIGHT ] ){
// It is the first time the user presses the key.
if (!keyState[KEY_RIGHT]){
//Add the movement to the queue if is below the limit
if ( topMovesQueue < LIMIT_MOVEMENT ){
movesQueue[topMovesQueue].xDir = 1;
movesQueue[topMovesQueue].yDir = 0;
topMovesQueue++;
}
//It states that the key has been pressed for the first time. I will change until all key are released.
keyState[KEY_RIGHT] = true;
// if the user keep presing the right key
}else{
acceleration ++;
if ( acceleration >2000 ){
moveFast = true;
currentDirection.xDir = 1;
currentDirection.yDir = 0;
acceleration = 0;
x_speed = x_speed_fast;
}
}
}else if( currentKeyStates[ SDL_SCANCODE_LEFT ] ){
// It is the first time the user presses the key.
if (!keyState[KEY_LEFT]){
//Add the movement to the queue if is below the limit
if ( topMovesQueue < LIMIT_MOVEMENT ){
movesQueue[topMovesQueue].xDir = -1;
movesQueue[topMovesQueue].yDir = 0;
topMovesQueue++;
}
//It states that the key has been pressed for the first time. I will change until all key are released.
keyState[KEY_LEFT] = true;
// if the user keep presing the right key
}else{
acceleration ++;
if ( acceleration > 2000 ){
//Activate fast mode
moveFast = true;
currentDirection.xDir = -1;
currentDirection.yDir = 0;
acceleration = 0;
x_speed = x_speed_fast;
}
}
}else if( currentKeyStates[ SDL_SCANCODE_DOWN ] ){
if( !invertMode ){
currentDirection.xDir = 0;
currentDirection.yDir = 1;
y_speed = y_speed_fast;
}
}else if( currentKeyStates[ SDL_SCANCODE_UP ] ){
if( invertMode ){
currentDirection.xDir = 0;
currentDirection.yDir = 1;
y_speed = y_speed_fast;
}
}else{
// All key are released.
keyState[KEY_RIGHT] = false;
keyState[KEY_LEFT] = false;
moveFast = false;
acceleration = 0;
if( freeFalling == false ){
x_speed = x_speed_normal;
y_speed = y_speed_normal;
}
//Set current direction down.
currentDirection.xDir = 0;
currentDirection.yDir = 1;
}
//---------Rotation control---------------
if( currentKeyStates[ SDL_SCANCODE_R ] ){
if ( !keyState[KEY_R] && topRotationQueue < LIMIT_MOVEMENT){
int tX = puyoTail->getPosX();
int tY = puyoTail->getPosY();
int hX = puyoHead->getPosX();
int hY = puyoHead->getPosY();
if( tX == hX )
{
if( tY < hY )
{
rotationQueue[topRotationQueue].yDir = 0;
rotationQueue[topRotationQueue].xDir = 1;
topRotationQueue++;
}else
{
rotationQueue[topRotationQueue].yDir = 0;
rotationQueue[topRotationQueue].xDir = -1;
topRotationQueue++;
}
}else
{
if( tX > hX )
{
rotationQueue[topRotationQueue].xDir = 0;
rotationQueue[topRotationQueue].yDir = 1;
topRotationQueue++;
}else
{
rotationQueue[topRotationQueue].xDir = 0;
rotationQueue[topRotationQueue].yDir = -1;
topRotationQueue++;
}
}
keyState[KEY_R] = true;
}
}else{
keyState[KEY_R] = false;
}
// Pause control
//---------Rotation control---------------
if( currentKeyStates[ SDL_SCANCODE_P ] ){
if ( !keyState[KEY_P] ){
if(stopPlayer)
stopPlayer = false;
else
stopPlayer = true;
keyState[KEY_P] = true;
}else{
keyState[KEY_P] = false;
}
}
}
position Player::getHeadPosition(){
position help;
help.x = puyoHead->getPosX();
help.y = puyoHead->getPosY();
return help;
}
position Player::getTailPosition(){
position help;
help.x = puyoTail->getPosX();
help.y = puyoTail->getPosY();
return help;
}
position Player::getHeadPrevPosition(){
return headPrevPosition;
}
position Player::getTailPrevPosition(){
return tailPrevPosition;
}
void Player::setHeadPositionX(int x){
puyoHead->setPosX(x);
}
void Player::setHeadPositionY(int y){
puyoHead->setPosY(y);
}
void Player::setTailPositionX(int x){
puyoTail->setPosX(x);
}
void Player::setTailPositionY(int y){
puyoTail->setPosY(y);
}
Puyo* Player::getPuyoHead(){
return puyoHead;
}
Puyo* Player::getPuyoTail(){
return puyoTail;
}
void Player::movePuyosVertical(int yHead,int yTail){
if( puyoState == COMPLETE ){
//Save previous positions
headPrevPosition.y = puyoHead->getPosY();
tailPrevPosition.y = puyoTail->getPosY();
puyoHead->setPosY(yHead);
puyoTail->setPosY(yTail);
}else if (puyoState == ONLY_HEAD ) {
//Save previous positions
headPrevPosition.y = puyoHead->getPosY();
puyoHead->setPosY(yHead);
}else{
//Save previous positions
tailPrevPosition.y = puyoTail->getPosY();
puyoTail->setPosY(yTail);
}
}
void Player::movePuyosHorizontal(int xHead, int xTail){
if( puyoState == COMPLETE ){
//Save previous positions
headPrevPosition.x = puyoHead->getPosX();
tailPrevPosition.x = puyoTail->getPosX();
puyoHead->setPosX(xHead);
puyoTail->setPosX(xTail);
}
}
void Player::cutHead(){
if (puyoState == COMPLETE ){
puyoState = ONLY_TAIL;
y_speed = y_speed_fast;
freeFalling = true;
}else{
puyoState = NONE;
freeFalling = false;
}
}
void Player::cutTail(){
if (puyoState == COMPLETE ){
puyoState = ONLY_HEAD;
y_speed = y_speed_fast;
freeFalling = true;
}else{
puyoState = NONE;
freeFalling = false;
}
}
int Player::getPuyoState(){
return puyoState;
}
void Player::setPuyoState(int state){
puyoState = state;
}
void Player::setStartPosition(int startPx, int startPy){
startPositionX = startPx;
startPositionY = startPy;
} | true |
c70f51df16efdf51fd1fdd3e4604a61ec66c49c0 | C++ | Hopobcn/EnTT-Pacman | /include/Simpleton/Memory/alloc.hpp | UTF-8 | 1,388 | 3.1875 | 3 | [
"MIT"
] | permissive | //
// alloc.hpp
// Simpleton Engine
//
// Created by Indi Kernick on 16/8/18.
// Copyright © 2018 Indi Kernick. All rights reserved.
//
#ifndef engine_memory_alloc_hpp
#define engine_memory_alloc_hpp
#include <new>
#include <cstring>
#include <cstddef>
namespace Memory {
/// Allocate memory
inline void *alloc(const size_t bytes) {
return operator new(
bytes, std::align_val_t{alignof(std::max_align_t)}
);
}
/// Allocate uninitialized bytes
inline std::byte *allocBytes(const size_t bytes) {
return static_cast<std::byte *>(alloc(bytes));
}
/// Allocate uninitialized object
template <typename Object>
Object *allocObj() {
return static_cast<Object *>(operator new(
sizeof(Object), std::align_val_t{alignof(Object)}
));
}
/// Allocate uninitialized array of objects
template <typename Object>
Object *allocArr(const size_t count) {
return static_cast<Object *>(operator new(
sizeof(Object) * count, std::align_val_t{alignof(Object)}
));
}
/// Deallocate memory
inline void dealloc(void *const ptr) {
operator delete(ptr);
}
/// Reallocate memory
inline void *realloc(void *const ptr, const size_t oldSize, const size_t newSize) {
void *const newPtr = alloc(newSize);
std::memcpy(newPtr, ptr, oldSize < newSize ? oldSize : newSize);
dealloc(ptr);
return newPtr;
}
}
#endif
| true |
f8fde0646eb7a847ef563f77187ac0ea9984e035 | C++ | khersham/cplusplus | /complexlog.cpp | UTF-8 | 845 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <complex>
#include <ctime> //for seeding the random number with time
#include <cstdlib> //for random number
using namespace std;
complex<double> MonteCarlo(complex<double>(*func)(complex<double>), double Start, double End, double Number)
{
srand(time(NULL));
double u;
complex<double> x;
complex<double> fs(0,0);
for (auto i=0; i<=Number; i++)
{
u = 1.0*rand()/(RAND_MAX);
complex<double> v(Start + (End-Start)*u,0.0);
fs = fs + func(v);
}
return fs*(End-Start)/Number;
}
complex<double> func (complex<double> x)
{
//std::complex a = std::complex::log();
return log(complex<double>(1,0)-x)/x;
}
int main ()
{
complex<double> num1{MonteCarlo(func,0,3,100000.0)};
complex<double> num2(-2,3);
cout << num1 << endl;
return 0;
}
| true |
585816aca0dbf69467d9679c75e032324cfed52d | C++ | illyashenko/Arkanoid2D | /src/Block.h | UTF-8 | 850 | 2.8125 | 3 | [] | no_license | #pragma once
#include "IEntity.h"
using namespace sf;
enum class BlockType
{
SINGLE,
DOUBLE,
TRIPLE,
BROKEN
};
class Block : public IEntity
{
public:
Block();
Block(BlockType blockType, Vector2f position);
void draw(RenderWindow& window);
void update(const float& time);
float getLeft();
float getRight();
float getTop();
float getBottom();
void setPosition(Vector2f position);
BlockType getBlockType();
void setBlockType(BlockType blockType);
void exchangeBlock(BlockType blockType);
bool stopFrame();
_declspec(property(get = getLeft)) float Left;
_declspec(property(get = getRight)) float Right;
_declspec(property(get = getTop)) float Top;
_declspec(property(get = getBottom)) float Bottom;
private:
Sprite sprite_;
Texture texture_;
BlockType blocType_;
float currentFrame;
bool stop;
std::string getImage();
};
| true |
99d34753ff869205dad1edb8db7782f7c74abcac | C++ | quant108/Algorithms-Itmo | /week1/week1-H.cpp | UTF-8 | 450 | 2.53125 | 3 | [] | no_license | #ifdef JUDGE
#include <fstream>
std::ifstream cin("input.txt");
std::ofstream cout("output.txt");
#else
#include <iostream>
using std::cin;
using std::cout;
#endif
#include <algorithm>
using namespace std;
int main() {
int n, A[15], time = 18000, con = 0;
cin >> n;
for(int i = 0; i < n; i++)
cin >> A[i];
sort(A, A + n);
for(int i = 0; i < n; i++)
if(A[i] <= time) {time -= A[i]; con++;}
else break;
cout << con << endl;
return 0;
}
| true |
706e8b541d62b20d71a5493a7e3770e4e5a42e07 | C++ | chargen/leetcode | /subsets.cc | UTF-8 | 402 | 2.75 | 3 | [] | no_license | class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > ans;
int len = S.size();
sort(S.begin(), S.end());
for(int s = 0; s < (1<<len); ++s){
vector<int> tmp;
for(int i = 0; i < len; ++i){
if((1<<i)&s) tmp.push_back(S[i]);
}
ans.push_back(tmp);
}
return ans;
}
}; | true |
26ce5cd077dc26cda72f4041d7b1979ae2b588ec | C++ | shinkw83/lib | /include/logger.h | UTF-8 | 1,782 | 2.53125 | 3 | [] | no_license | #ifndef __LOGGER_H__
#define __LOGGER_H__
#include <log4cplus/logger.h>
#include <log4cplus/layout.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/loggingmacros.h>
using namespace log4cplus;
#define MAX_FILE_SIZE (1024*1024*1024 / 10)
class LogMgrC{
SharedAppenderPtr myAppender;
Logger logger;
public:
LogMgrC(const char *path, const char *log_name=0, int filecount = 10, const LogLevel log_level=DEBUG_LOG_LEVEL)
: myAppender(new RollingFileAppender(path, MAX_FILE_SIZE, 100, true))
, logger(log_name?Logger::getInstance(log_name):Logger::getRoot())
{
std::auto_ptr<Layout> myLayout
= std::auto_ptr<Layout>(new log4cplus::PatternLayout("%D{%m/%d %H:%M:%S:%q } %-5p %m%n"));
myAppender->setLayout(myLayout);
logger.addAppender(myAppender);
logger.setLogLevel(log_level);
}
void setLogLevel(const LogLevel log_level)
{
logger.setLogLevel(log_level);
}
~LogMgrC()
{
logger.removeAppender(myAppender);
}
Logger &get() { return logger; }
};
class DebugLogger{
SharedAppenderPtr myAppender;
Logger logger;
public:
DebugLogger(const char *path, const char *log_name=0, int filecount = 10)//, const LogLevel log_level=DEBUG_LOG_LEVEL)
: myAppender(new RollingFileAppender(path, 1024*1024*100, 50, true))
, logger(log_name?Logger::getInstance(log_name):Logger::getRoot())
{
std::auto_ptr<Layout> myLayout
= std::auto_ptr<Layout>(new log4cplus::PatternLayout("%D{%m/%d %H:%M:%S:%q } %m%n"));
myAppender->setLayout(myLayout);
logger.addAppender(myAppender);
logger.setLogLevel(DEBUG_LOG_LEVEL);
}
void setLogLevel(const LogLevel log_level)
{
logger.setLogLevel(log_level);
}
~DebugLogger()
{
logger.removeAppender(myAppender);
}
Logger &get() { return logger; }
};
#endif
| true |
e2b817521213e708c23e8fb3015ffc7396a922ff | C++ | lhj1230/lee-hyun-ju | /Project(stl)/maze_vector.cpp | UHC | 9,234 | 2.640625 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<time.h>
#include<iostream>
#include<vector>
using namespace std;
//////////////////////////////////////////////////////
#define col GetStdHandle(STD_OUTPUT_HANDLE)
#define BLACK SetConsoleTextAttribute( col,0x0000 );
#define DARK_BLUE SetConsoleTextAttribute( col,0x0001 );
#define GREEN SetConsoleTextAttribute( col,0x0002 );
#define BLUE_GREEN SetConsoleTextAttribute( col,0x0003 );
#define BLOOD SetConsoleTextAttribute( col,0x0004 );
#define PUPPLE SetConsoleTextAttribute( col,0x0005 );
#define GOLD SetConsoleTextAttribute( col,0x0006 ); //
#define ORIGINAL SetConsoleTextAttribute( col,0x0007 );
#define GRAY SetConsoleTextAttribute( col,0x0008 );
#define BLUE SetConsoleTextAttribute( col,0x0009 );
#define HIGH_GREEN SetConsoleTextAttribute( col,0x000a );
#define SKY_BLUE SetConsoleTextAttribute( col,0x000b );
#define RED SetConsoleTextAttribute( col,0x000c );
#define PLUM SetConsoleTextAttribute( col,0x000d );
#define YELLOW SetConsoleTextAttribute( col,0x000e );
//////////////////////////////////////////////////////
#define WALL 1//迭 1
#define EMPTY 0// 0
#define Y 0//y ̵
#define X 1//x ̵
#define CHARACTER 2//ij ġ
#define CHARACTER2P 3//ij ġ
#define POTAL_MAX 6//Ż
#define ENTRY_START 10//Ա Ż ġ
#define EXIT_START 20//ⱸ Ż ġ
#define H 104// Ű Է°
#define K 107// Ű Է°
#define U 117// Ű Է°
#define J 106// Ű Է°
#define WIDTH 12//
#define HEIGHT 12//
#define RANDOM_START 30//
#define W 119//2p ¿
#define A 97
#define S 115
#define D 100
#define KEY 9
#define GAMEOVER 4
#define RESET 7
int Character[2];//1p x,y
int Character2p[2];//2p x,y
int Entry_Potal[POTAL_MAX][2];//1p ԱŻ ǥ
int Exit_Potal[POTAL_MAX][2];//1p ⱸŻ ǥ
int Random_Potal[POTAL_MAX][2];//1p Ż ǥ
int Entry_Potal2p[POTAL_MAX][2];//2p ԱŻ ǥ
int Exit_Potal2p[POTAL_MAX][2];//2p ⱸŻ ǥ
int Random_Potal2p[POTAL_MAX][2];//2p Ż ǥ
int LastObjectindex = EMPTY;//1p ó ̵Ϸ ġ NULL
int LastObjectindex2p = EMPTY;//2p ó ̵Ϸ ġ NULL
int key[2];
void Init(vector<vector<int>>& v) {
/*int Width = (WIDTH * 2) + 10;
int Height = HEIGHT + 10;
char buf[256];
sprintf(buf, "mode con: lines=%d cols=%d", Height, Width);
system(buf);*/
v =
{
{WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL},
{WALL, ENTRY_START, CHARACTER, EMPTY, EMPTY, RANDOM_START + 1, WALL, WALL, EMPTY, EMPTY, RANDOM_START + 2, WALL},
{WALL, EMPTY, CHARACTER2P, EMPTY, EXIT_START + 1, WALL, EMPTY, WALL, WALL, EMPTY, EMPTY, WALL},
{WALL, WALL, WALL, WALL, WALL, EMPTY, WALL, EMPTY, EXIT_START + 3, ENTRY_START + 4, EMPTY, WALL},
{WALL, EMPTY, RANDOM_START + 3, EMPTY, WALL, EMPTY, WALL, EMPTY, ENTRY_START + 1, EMPTY, EMPTY, WALL},
{WALL, EMPTY, ENTRY_START + 3, EXIT_START + 5, WALL, EMPTY, WALL, WALL, EMPTY, WALL, EMPTY, WALL},
{WALL, EMPTY, WALL, EMPTY, WALL, EMPTY, WALL, EMPTY, EMPTY, KEY, EMPTY, WALL},
{WALL, EMPTY, RANDOM_START + 4, EMPTY, WALL, RESET, WALL, ENTRY_START + 2, EMPTY, WALL, EMPTY, GAMEOVER},
{WALL, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, WALL, EXIT_START + 4, EMPTY, EMPTY, EMPTY, WALL},
{WALL, EMPTY, EXIT_START, EMPTY, WALL, EMPTY, WALL, EMPTY, EMPTY, WALL, RANDOM_START, WALL},
{WALL, KEY, EMPTY, EMPTY, WALL, EMPTY, WALL, EMPTY, EMPTY, EXIT_START + 2, EMPTY, WALL},
{WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL}
};
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
if (v[y][x] == CHARACTER)
{
Character[X] = x;
Character[Y] = y;
}
else if (v[y][x] >= ENTRY_START && v[y][x] < ENTRY_START + POTAL_MAX)
{
Entry_Potal[v[y][x] - ENTRY_START][X] = x;
Entry_Potal[v[y][x] - ENTRY_START][Y] = y;
}
else if (v[y][x] >= EXIT_START && v[y][x] < EXIT_START + POTAL_MAX)
{
Exit_Potal[v[y][x] - EXIT_START][X] = x;
Exit_Potal[v[y][x] - EXIT_START][Y] = y;
}
else if (v[y][x] >= RANDOM_START && v[y][x] < RANDOM_START + POTAL_MAX)
{
Random_Potal[v[y][x] - RANDOM_START][X] = x;
Random_Potal[v[y][x] - RANDOM_START][Y] = y;
}
}
}
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
if (v[y][x] == CHARACTER2P)
{
Character2p[X] = x;
Character2p[Y] = y;
//ResetCharacter2p[X] = x;
//ResetCharacter2p[Y] = y;
}
else if (v[y][x] >= ENTRY_START && v[y][x] < ENTRY_START + POTAL_MAX)
{
Entry_Potal2p[v[y][x] - ENTRY_START][X] = x;
Entry_Potal2p[v[y][x] - ENTRY_START][Y] = y;
//ResetEntry_Potal2p[resetmap[y][x] - ENTRY_START][X] = x;
//ResetEntry_Potal2p[resetmap[y][x] - ENTRY_START][Y] = y;
}
else if (v[y][x] >= EXIT_START && v[y][x] < EXIT_START + POTAL_MAX)
{
Exit_Potal2p[v[y][x] - EXIT_START][X] = x;
Exit_Potal2p[v[y][x] - EXIT_START][Y] = y;
//ResetExit_Potal2p[resetmap[y][x] - EXIT_START][X] = x;
//ResetExit_Potal2p[resetmap[y][x] - EXIT_START][Y] = y;
}
else if (v[y][x] >= RANDOM_START && v[y][x] < RANDOM_START + POTAL_MAX)
{
Random_Potal2p[v[y][x] - RANDOM_START][X] = x;
Random_Potal2p[v[y][x] - RANDOM_START][Y] = y;
//ResetRandom_Potal2p[resetmap[y][x] - RANDOM_START][X] = x;
//ResetRandom_Potal2p[resetmap[y][x] - RANDOM_START][Y] = y;
}
}
}
}
void mapdraw(vector<vector<int>> v)
{
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
if (v[y][x] == WALL)
{
cout << "";
}
else if (v[y][x] >= ENTRY_START && v[y][x] < ENTRY_START + POTAL_MAX)
{
BLUE
cout << "";
ORIGINAL
}
else if (v[y][x] >= EXIT_START && v[y][x] < EXIT_START + POTAL_MAX)
{
YELLOW
cout << "";
ORIGINAL
}
else if (v[y][x] == GAMEOVER)
{
GRAY
cout << "";
ORIGINAL
}
else if (v[y][x] == CHARACTER)
{
RED
cout << "";
ORIGINAL
}
else if (v[y][x] == CHARACTER2P)
{
PUPPLE
cout << "";
ORIGINAL
}
else if (v[y][x] >= RANDOM_START && v[y][x] < RANDOM_START + POTAL_MAX)
{
GREEN
cout << "";
ORIGINAL
}
else if (v[y][x] == KEY)
{
SKY_BLUE
cout << "";
ORIGINAL
}
else if (v[y][x] == RESET)
{
GOLD
cout << "";
ORIGINAL
}
else if (v[y][x] == EMPTY)
cout << " ";
}
cout << endl;
}
}
void userbook()
{
cout << ": " << endl;
BLUE
cout << ": Ż Ա " << "\t";
ORIGINAL
YELLOW
cout << ": Ż ⱸ" << endl;
ORIGINAL
RED
cout << ": ÷̾ 1" << "\t";
ORIGINAL
PUPPLE
cout << ": ÷̾ 2" << endl;
ORIGINAL
GREEN
cout << ": Ż" << "\t";
ORIGINAL
SKY_BLUE
cout << ": " << endl;
ORIGINAL
GOLD
cout << ": ʱȭ" << endl;
ORIGINAL
}
void movecheck(vector<vector<int>>& v)
{
int index = v[Character[Y]][Character[X]];
if (index >= ENTRY_START && index < ENTRY_START + POTAL_MAX)
{
Character[X] = Exit_Potal[index - ENTRY_START][X];
Character[Y] = Exit_Potal[index - ENTRY_START][Y];
}
if (index >= RANDOM_START && index < RANDOM_START + POTAL_MAX)
{
Character[X] = Exit_Potal[(rand() % 4) + 0][X];
Character[Y] = Exit_Potal[(rand() % 4) + 0][Y];
}
if (index == KEY)
{
if (index != EMPTY)
{
v[rand() % 11][rand() % 11] = EMPTY;
}
}
if (index == GAMEOVER)
{
cout << "Game Over";
exit(0);
}
}
void move1p(vector<vector<int>>& v)
{
movecheck(v);
LastObjectindex = v[Character[Y]][Character[X]];
v[Character[Y]][Character[X]] = CHARACTER;
}
void Playermovecheck(char ch, vector<vector<int>>& v)
{
switch (ch)
{
case H:
v[Character[Y]][Character[X]] = LastObjectindex;
if ((v[Character[Y]][Character[X] - 1] != WALL) && (v[Character[Y]][Character[X] - 1] != CHARACTER2P))
Character[X]--;
move1p(v);
break;
case K:
v[Character[Y]][Character[X]] = LastObjectindex;
if ((v[Character[Y]][Character[X] + 1] != WALL) && (v[Character[Y]][Character[X] + 1] != CHARACTER2P))
Character[X]++;
move1p(v);
break;
case U:
v[Character[Y]][Character[X]] = LastObjectindex;
if ((v[Character[Y] - 1][Character[X]] != WALL) && (v[Character[Y] - 1][Character[X]] != CHARACTER2P))
Character[Y]--;
move1p(v);
break;
case J:
v[Character[Y]][Character[X]] = LastObjectindex;
if ((v[Character[Y] + 1][Character[X]] != WALL) && (v[Character[Y] + 1][Character[X]] != CHARACTER2P))
Character[Y]++;
move1p(v);
break;
}
}
void move(vector<vector<int>>& v)
{
char ch;
ch = getch();
system("cls");
if ((ch == U) || (ch == H) || (ch == J) || (ch == K))
{
Playermovecheck(ch, v);
}
else if ((ch == W) || (ch == A) || (ch == S) || (ch == D))
{
Playermovecheck(ch, v);
}
}
void main()
{
vector<vector<int>> map(12, vector<int>(12));
map.reserve(12);
Init(map);
vector<vector<int>> resetmap(map);
srand(time(NULL));
while (1)
{
mapdraw(map);
userbook();
move(map);
}
}
| true |
6f46a8ab6b6fb5dc6152df7c36b1bb785fc84cf4 | C++ | DShcherbak/Algorithms | /semester_4/Lab_2/Node.cpp | UTF-8 | 1,710 | 3.75 | 4 | [] | no_license | /*#include "Node.h"
void add_node_to_tree(Node* head, Node* new_node){
if(!head){
head = new_node;
return;
}
Node* parent = head;
while(parent){
if(parent->value > new_node->value){
if(parent->left)
parent = parent->left;
else{
parent->left = new_node;
new_node->parent = parent;
}
}else if(parent->value < new_node->value){
if(parent->right)
parent = parent->right;
else{
parent->right = new_node;
new_node->parent = parent;
}
} else
return;
}
}
Node* search_value_in_tree(Node* head, int value){
Node* cur = head;
while(cur){
if(value > cur->value){
if(!cur->right)
return nullptr;
else
cur = cur->right;
}
else if(value < cur->value){
if(!cur->left)
return nullptr;
else
cur = cur->left;
}
else{
return cur;
}
}
return nullptr;
}
void delete_node(Node* head, Node* del){
if(del == head){
if(!(del->left || del->right)){
delete head;
}else if(del->left){
delete head;
head = //chose new head
}
}
}
void delete_node_by_value(Node* head, int value);
int max_value(Node* head){
Node* cur = head;
while(cur->right){
cur = cur->right;
}
return cur->value;
}
int min_value(Node* head){
Node* cur = head;
while(cur->left){
cur = cur->left;
}
return cur->value;
}
*/ | true |
382344e508c42056dff0b8156fb35203430a03a1 | C++ | tashleyy/recruit | /src/ds/HashTable.cpp | UTF-8 | 1,269 | 3.15625 | 3 | [] | no_license | #include <functional>
#include "../../lib/ds/HashTable.h"
#include "../../lib/Exceptions.h"
using namespace std;
const int NUM_BUCKETS = 20;
template <class K, class V>
HashTable<K, V>::HashTable() {
data = new LinkedList<pair<K, V>>*[NUM_BUCKETS];
for (unsigned int i = 0; i < NUM_BUCKETS; i++) {
data[i] = new LinkedList<pair<K, V>>;
}
}
template <class K, class V>
void HashTable<K, V>::put(K key, V val) {
size_t keyHash = hash<K>{}(key);
try {
find(key);
} catch (NoSuchElementException &e) {
data[keyHash%NUM_BUCKETS]->pushBack(make_pair(key, val));
}
}
template <class K, class V>
V HashTable<K, V>::remove(K key) {
size_t keyHash = hash<K>{}(key);
LinkedList<pair<K, V>> *linkedList = data[keyHash%NUM_BUCKETS];
return linkedList->remove(find(key)).second;
}
template <class K, class V>
V HashTable<K, V>::get(K key) {
return find(key)->second;
}
template <class K, class V>
typename LinkedList<pair<K, V>>::iterator HashTable<K, V>::find(K key) {
size_t keyHash = hash<K>{}(key);
LinkedList<pair<K, V>> *linkedList = data[keyHash%NUM_BUCKETS];
for (typename LinkedList<pair<K, V>>::iterator it = linkedList->begin(); it != linkedList->end(); ++it) {
if (it->first == key) {
return it;
}
}
throw NoSuchElementException();
} | true |
bbdea9110281d0c7a179df121a939d5924af1fbe | C++ | Coding-Badly/tc_Random | /tc_random_XorShift16.cpp | UTF-8 | 498 | 2.609375 | 3 | [] | no_license | #include <Arduino.h>
#include <inttypes.h>
// http://www.arklyffe.com/main/2010/08/29/xorshift-pseudorandom-number-generator/
static uint16_t Seed = 1;
unsigned long tc_RandomGenerate_XorShift16( void )
{
uint16_t Next;
Next = Seed;
Next = Next ^ (Next << 1);
Next = Next ^ (Next >> 1);
Next = Next ^ (Next << 14);
Seed = Next;
return( Next );
}
void tc_RandomSeed_XorShift16( unsigned long newseed )
{
if ( newseed != 0 )
Seed = newseed;
}
| true |
6b32d72dfc1a455f8ba9c628fc66740ba272d8a3 | C++ | raulgoce/porfolio | /Advanced/19.POO_Clases_derivadas/207.Herencia_protected/Turismo.h | UTF-8 | 528 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include "Vehiculo.h"
using namespace std;
class Turismo: public Vehiculo{ //si no se pone el tipo de herencia, se pone privado por defecto
private:
int numeroPuertas;
public:
Turismo(string marca, string color, string modelo,int numeroPuertas):Vehiculo(marca, color, modelo){
this->numeroPuertas=numeroPuertas;
}
int getNumeroPuertas(){
return numeroPuertas;
}
string retornarModelo(){
string mensaje=getModelo();
return mensaje;
}
~Turismo(){
}
};
| true |
ca5aacf30e31004044c628731ba9e42b030e4d4d | C++ | jtiu-cse-school-assignments/csce-121-homeworks | /CSCE_121_Homework/Homework8/Homework8/Household.h | UTF-8 | 405 | 2.609375 | 3 | [] | no_license | //
// Header.h
// Homework8
//
// Created by Julian Tiu on 4/11/16.
// Copyright © 2016 Julian Tiu. All rights reserved.
//
#pragma once
#include "Product.h"
#include <string>
class Household : public Product {
private:
public:
Household();
Household(int productNum, std::string productName);
std::string getInfo() const;
Product::Category getType() const;
};
| true |
ae861d9f54140504c6d070826f91e18e5fd3a72b | C++ | eaasna/low-memory-prefilter | /hashmap/lib/seqan3/doc/tutorial/search/search_span.cpp | UTF-8 | 335 | 2.703125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"CC-BY-4.0",
"MIT"
] | permissive | #include <seqan3/core/debug_stream.hpp>
#include <seqan3/std/span>
int main()
{
std::string text{"Garfield the fat cat without a hat."};
size_t start{2};
size_t span{3};
std::span text_view{std::data(text) + start, span}; // represent interval [2, 4]
seqan3::debug_stream << text_view << '\n'; // Prints "rfi"
}
| true |
c70ca4c4d9fe8de52d49b81c9ac790a859359194 | C++ | MarkRepo/CppSTL | /Allocator/allocator_test.cc | UTF-8 | 4,099 | 3.671875 | 4 | [] | no_license | #include <gtest/gtest.h>
#include <cstddef>
#include <iostream>
using namespace std;
class MyType {
public:
MyType() { cout << "ctor for MyType" << endl; }
MyType(const MyType& val) { cout << "copy ctor for MyType" << endl; }
~MyType() { cout << "dtor for MyType" << endl; }
};
//自定义allocator必须提供以下内容
template <typename T>
class MyAlloc {
public:
// 1. value_type类型定义
typedef T value_type;
// 2. 构造函数
MyAlloc() noexcept {}
// 3. template 构造函数,用来在类型有所改变时复制内部状态
template <typename U>
MyAlloc(const MyAlloc<U>&) noexcept {}
// 4. 成员函数allocate,用来提供新的内存
T* allocate(std::size_t num) {
cout << "MyAlloc allocate " << num << "elems" << endl;
return static_cast<T*>(::operator new(num * sizeof(T)));
}
// 5. 成员函数deallocate,用来释放不再需要的内存
void deallocate(T* p, std::size_t num) { ::operator delete(p); }
void construct(T* p, const T& val) { new (p) T(val); }
void destroy(T* p) { p->~T(); }
};
// 6. ==
template <typename T1, typename T2>
bool operator==(const MyAlloc<T1>&, const MyAlloc<T2>&) noexcept {
return true;
}
// 7. !=
template <typename T1, typename T2>
bool operator!=(const MyAlloc<T1>&, const MyAlloc<T2>&) noexcept {
return false;
}
// 程序库开发者的角度使用Allocator
namespace MyStd {
template <typename T, typename Allocator>
class Vector {
private:
Allocator alloc;
T* elems;
size_t numElems;
size_t sizeElems;
public:
explicit Vector(const Allocator& = Allocator());
explicit Vector(size_t num, const T& val = T(), const Allocator& a = Allocator()) : alloc(a) {
sizeElems = numElems = num;
elems = alloc.allocate(num);
for (size_t i = 0; i < sizeElems; i++) {
alloc.construct(&elems[i], val);
}
// uninitialized_fill_n(elems, num, val);
}
template <typename InputIterator>
Vector(InputIterator beg, InputIterator end, const Allocator& = Allocator());
Vector(const Vector<T, Allocator>& v);
void reserve(size_t size) {
// reserve() never shrinks the memory
if (size <= sizeElems) {
return;
}
// allocate new memory for size elements
T* newmem = alloc.allocate(size);
// copy old elements into new memory
cout << "before copy" << endl;
uninitialized_copy(elems, elems + numElems, newmem);
cout << "after copy" << endl;
// destroy old elements
for (size_t i = 0; i < numElems; ++i) {
alloc.destroy(&elems[i]);
}
// deallocate old memory
alloc.deallocate(elems, sizeElems);
// so, now we have our elements in the new memory
sizeElems = size;
elems = newmem;
}
};
} // namespace MyStd
TEST(AllocTest, MyAlloc) {
MyType a;
size_t num = 10;
MyStd::Vector<MyType, MyAlloc<MyType>> myVec(num, a);
myVec.reserve(15);
}
TEST(AllocTest, raw_storage_iterator) {
// The first template argument (T*, here) has to be an output iterator for the type of the
// //elements. The second template argument (T, here) has to be the type of the elements.
vector<int> x{1, 2, 3, 4, 5, 6};
int* elems = static_cast<int*>(::operator new(6 * sizeof(int)));
copy(x.begin(),
x.end(), // source
raw_storage_iterator<int*, int>(elems)); // destination
for (size_t i = 0; i < 6; i++) {
cout << *(elems + i) << endl;
}
}
TEST(AllocTest, temporary_buffer) {
// allocate memory for num elements of type MyType
const int num = 10;
pair<MyType*, std::ptrdiff_t> p = get_temporary_buffer<MyType>(num);
if (p.second == 0) {
// could not allocate any memory for elements
cout << "alloc elems error\n";
} else if (p.second < num) {
// could not allocate enough memory for num elements // however, don’t forget to deallocate it
cout << "alloc " << p.second << " elements" << endl;
} else {
cout << "alloc " << num << " elements success!\n";
}
// do your processing
// free temporarily allocated memory, if any
if (p.first != 0) {
return_temporary_buffer(p.first);
}
} | true |
02617f5dde9d3063b3ecb7cbebe5fb6df250ccc1 | C++ | bablookr/ds_algo | /Part 1 - Data Structures/array1.cpp | UTF-8 | 648 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
/*Array: Basic functions
insert,delete,reverse,sort,search*/
void ins(int a[],int n){
}
void del(int a[],int n){
}
void reverse_array(int a[],int n){
reverse(a,a+n);
}
void sort_array(int a[],int n){
sort(a,a+n);
//sort(a,a+n,greater<int>());
}
void search_array(int a[],int n,int x){
//Constraint: Array should be sorted.
if(binary_search(a,a+n,x)) cout<<"Found"<<endl;
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
sort_array(a,n);
for(int i=0;i<n;i++)
cout<<a[i]<<endl;
return 0;
}
| true |
c37f8024c9b30b4efbad1d58aa0029ebb75293ca | C++ | lizkwan/UVa-Online-Judge | /10409.cpp | UTF-8 | 752 | 3 | 3 | [] | no_license | #include <stdio.h>
int main ()
{
int T,B,N,E,S,W,count,i,temp;
char str[6];
while ((scanf("%d",&count)==1) && (count!=0))
{
T=1;
B=6;
N=2;
S=5;
W=3;
E=4;
gets(str);
for (i=0; i<count; i++)
{
gets(str);
switch (str[0])
{
case 'n':
case 'N':
temp = T;
T = S;
S = B;
B = N;
N = temp;
break;
case 's':
case 'S':
temp = T;
T = N;
N = B;
B = S;
S = temp;
break;
case 'e':
case 'E':
temp = T;
T = W;
W = B;
B = E;
E = temp;
break;
case 'w':
case 'W':
temp = T;
T = E;
E = B;
B = W;
W = temp;
break;
}
}
printf ("%d\n",T);
}
return 0;
} | true |
9b1a2e58ba4ddbbd4f937e196963068e33566f78 | C++ | asherikov/smpc_solver | /solver/as_matrix_ecL.h | UTF-8 | 1,643 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* @file
* @author Alexander Sherikov
* @date 28.08.2011 13:43:12 MSD
*/
#ifndef AS_MATRIX_ECL_H
#define AS_MATRIX_ECL_H
/****************************************
* INCLUDES
****************************************/
#include "smpc_common.h"
#include "as_problem_param.h"
/// @addtogroup gas
/// @{
/****************************************
* TYPEDEFS
****************************************/
using namespace std;
namespace AS
{
/**
* @brief Initializes lower diagonal matrix @ref pCholesky "L" and
* performs backward and forward substitutions using this matrix.
*/
class matrix_ecL
{
public:
/*********** Constructors / Destructors ************/
matrix_ecL(const int);
~matrix_ecL();
void form (const problem_parameters&);
void solve_backward (const int, double *) const;
void solve_forward (const int, double *, const int start_ind = 0) const;
double *ecL;
double **ecL_diag;
double **ecL_ndiag;
private:
void chol_dec (double *);
void form_iQBiPB (const double *, const double *, const double, double*);
void form_iQAT (const double, const double, const double *);
void form_AiQATiQBiPB (const problem_parameters&, const state_parameters&, double *);
void form_L_non_diag(const double *, double *);
void form_L_diag(const double *, double *);
// intermediate results used in computation of L
double *iQAT; /// inv(Q) * A'
};
}
/// @}
#endif /*AS_MATRIX_ECL_H*/
| true |
1313b5a19b382e4825703ad95ce8f0a217c14b7d | C++ | NeilWangziyu/C-Primer | /C-Primer/inheritance/main.cpp | UTF-8 | 1,962 | 3.515625 | 4 | [] | no_license | //
// main.cpp
// inheritance
//
// Created by 王子昱 on 2019/7/5.
// Copyright © 2019 王子昱. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class Quota{
public:
Quota() = default;
Quota(const string &book, double sales_price):
bookNo(book), price(sales_price){ }
string isbn() const {return bookNo;}
virtual double net_price(size_t n) const {
return n * price;
}
// size_t和unsigned int有所不同,size_t的取值range是目标平台下最大可能的数组尺寸
virtual ~Quota() = default;
private:
string bookNo;
protected:
double price = 0.0;
};
class Bulk_quota:public Quota{
public:
Bulk_quota() = default;
Bulk_quota(const string& book, double p , size_t qty, double disc):
Quota(book, p), min_qty(qty), discont(disc){ }
// double net_price(size_t) const override;
double net_price(size_t cnt) const
{
if (cnt >= min_qty)
return cnt * (1 - discont) * price;
else
return cnt * price;
}
//这个和上面一句声明不能在同一个文件里
private:
size_t min_qty = 0;
double discont = 0.0;
};
//动态绑定
double print_total(ostream &os, const Quota &item, size_t n)
{
double ret = item.net_price(n);
os << "ISBN: " <<item.isbn() << " # sold: " << n << " total due: " << ret << endl;
return ret;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
Quota item("harry potter", 10);
Bulk_quota bulk;
Quota *p = &item;
cout << item.net_price(56) <<endl;
p = &bulk;
Quota &r = bulk;
// 派生到基类的类型转换
cout << "-----" << endl;
Quota base("0-201-8274", 50);
print_total(cout, base, 10);
Bulk_quota derived("0-201-8274", 50, 5, 0.19);
print_total(cout, derived, 10);
return 0;
}
| true |
7d8fa628f16fe520b415b398a9deb1e2311fcf28 | C++ | yhmtmt/awsv1 | /src/blh2ecef.cpp | UTF-8 | 532 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
#include "aws_coord.hpp"
int main(int argc, char ** argv)
{
if(argc != 3 && argc != 4){
cout << "Usage: blh2ecef <lat> <lon> [<alt>]" << endl;
return 1;
}
double lat = atof(argv[1]) * PI / 180.0;
double lon = atof(argv[2]) * PI / 180.0;
double alt = 0.0;
if(argc == 4)
alt = atof(argv[3]);
double x, y, z;
x = y = z = 0.0;
blhtoecef(lat, lon, alt, x, y, z);
cout << setprecision(9) << x << " " << y << " " << z << endl;
return 0;
}
| true |
54cf0e94fb7b79d259bfa48192efd5b3a9625015 | C++ | ksaravindakashyap/dsa_placement_prep | /Arrays/commonEle.cpp | UTF-8 | 1,308 | 3.4375 | 3 | [] | no_license | // Common elements
//
// Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.
// Note: can you take care of the duplicates without using any additional Data Structure?
//
// Example 1:
//
// Input:
// n1 = 6; A = {1, 5, 10, 20, 40, 80}
// n2 = 5; B = {6, 7, 20, 80, 100}
// n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120}
// Output: 20 80
// Explanation: 20 and 80 are the only
// common elements in A, B and C.
class Solution
{
public:
vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
{
vector<int> v;
int i=0, j=0, k=0;
while(i<n1 && j<n2 && k<n3){
if(A[i]== B[j] and B[j]== C[k]){
v.push_back(A[i]);
i++; j++; k++;
}
else if (A[i]<B[j]){
i++;
}
else if (B[j]<C[k]){
j++;
}
else if (C[k]<A[i]){
k++;
}
int x= A[i-1]; int y= B[j-1]; int z= C[k-1];
while(A[i]==x){i++;}
while(B[j]==x){j++;}
while(C[k]==x){k++;}
}
if(v.empty()){
v.push_back(-1);
}
return v;
}
};
| true |
35990ad11f771e0fed4611cc48c0c430c845dd44 | C++ | mrSerega/DiscreteMathematics | /test.cpp | UTF-8 | 1,188 | 2.921875 | 3 | [] | no_license | #include "test.h"
#include "dijkstra.h"
#include "crapalgo.h"
#include <fstream>
#include <iostream>
Test::Test()
{
//in stream
ifstream input;
input.open("input.txt");
//in vars
int testLen = 0;
int n = 0;
input>>n>>testLen;
vector< vector< pair<int,int> > > testVector(testLen);
//reading
for(int i=0;i<n;i++){
int leftNode, rightNode, len;
input>>leftNode>>rightNode>>len;
testVector[leftNode].push_back(make_pair(rightNode,len));
}
//testing
//testOfDijkstra(testVector);
CrapAlgo* crapAlgo = new CrapAlgo();
crapAlgo->algo(0,6,testVector,testLen);
}
void Test::print(vector<int> vec)
{
for(unsigned int i=0;i<vec.size()-1;i++){
cout<<vec[i]<<"-";
}
cout<<vec.back();
}
void Test::testOfDijkstra(vector< vector< pair<int,int> > > testVector)
{
//out vars
int outputLen;
vector<int> outputPath;
int time;
//
Dijkstra* dijkstra = new Dijkstra();
time = dijkstra->algo(0,testVector.size()-1,testVector.size(), testVector, outputPath, outputLen);
cout<<"Dijkstra: "<<time<<"ms "<<"result is "<<outputLen<<": ";
print(outputPath);
}
| true |
eccfc7cac6cc43a91d2f2148462b24ab73159798 | C++ | shuyuFranky/coding | /Greedy/minimum spanning trees/POJ1751-prim.cpp | UTF-8 | 1,505 | 2.984375 | 3 | [] | no_license | /**
* Prim
* Highways
*/
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
#define maxn 760
#define inf 1e9
struct Node {
int x;
int y;
} node[maxn];
int N, M;
double dis[maxn];
int p[maxn];
int book[maxn];
double e[maxn][maxn];
double getDis(int a, int b) {
int x = node[a].x - node[b].x;
int y = node[a].y - node[b].y;
return sqrt((x*x + y*y));
}
void init() {
for (int i = 1; i <= N; i++)
for (int j = i; j <= N; j++)
if (i == j) e[i][j] = 0;
else e[i][j] = e[j][i] = getDis(i, j);
}
void Prim() {
int v;
book[1] = 1;
for (int i = 1; i <= N; i++) {
dis[i] = e[1][i];
p[i] = 1;
}
for (int i = 1; i < N; i++) {
double min = inf;
for (int j = 1; j <= N; j++) {
if (!book[j] && dis[j] < min) {
min = dis[j];
v = j;
}
}
book[v] = 1;
if (min != 0) cout << p[v] << " " << v << endl;
for (int j = 1; j <= N; j++) {
if (!book[j] && dis[j] > e[v][j]) { //注意这里和dijkstra的区别
dis[j] = e[v][j];
p[j] = v;
}
}
}
}
int main() {
ios::sync_with_stdio(false);
int a, b;
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> node[i].x >> node[i].y;
}
init();
cin >> M;
while (M--) {
cin >> a >> b;
e[a][b] = e[b][a] = 0;
}
Prim();
return 0;
}
| true |
6fc77a6f0efa64271ec9b2f5d923ddf7a79538a1 | C++ | Aaron-P/CS-325 | /OurCode/Object.cpp | UTF-8 | 1,581 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "Object.h"
using namespace std;
//Default Constructor
Object::Object()
{
speed = 0;
maxSpeed = 0;
xcoord = 0;
ycoord = 0;
direction = 0;
height = 0;
width = 0;
alive = 0;
isKillable = 0;
}
//Initializing Constructor
Object::Object(int dSpeed, double dDirection, double dX, double dY,
bool dKillable, int dmaxSpeed, int dHeight, int dWeigth, bool dAlive)
{
speed = dSpeed;
maxSpeed = dmaxSpeed;
xcoord = dX;
ycoord = dY;
direction = dDirection;
height = dHeight;
width = dWeigth;
alive = dAlive;
isKillable = dKillable;
}
//Object destructor
Object::~Object()
{
Die();
}
//Returns the speed of the Object
int Object::getSpeed()
{
return speed;
}
//Sets the speed of the Object
void Object::setSpeed(int newSpeed)
{
speed = newSpeed;
}
//Gets the X coordinate of the object
double Object::getX()
{
return xcoord;
}
//Sets the X coordinate for the location of the object.
void Object::setX(double newX)
{
xcoord = newX;
}
//Gets the Y coordinate of the object.
double Object::getY()
{
return ycoord;
}
//Sets the Y coordinate for the location of the object
void Object::setY(double newY)
{
ycoord = newY;
}
//Gets the direction of the Object
double Object::getDirection()
{
return direction;
}
//Sets the direction of the Object
void Object::setDirection(double newDirection)
{
direction = newDirection;
}
void Object::Move()
{
}
void Object::Shoot()
{
}
void Object::Die()
{
if(isKillable == true)
{
delete this;
}
} | true |
60708148d6aab28ed4b4c518e8324abd65aa737d | C++ | pmiddend/fcppt | /test/cyclic_iterator.cpp | UTF-8 | 1,326 | 2.734375 | 3 | [
"BSL-1.0"
] | permissive | // Copyright Carl Philipp Reh 2009 - 2018.
// 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)
#include <fcppt/cyclic_iterator.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <array>
#include <iterator>
#include <vector>
#include <fcppt/config/external_end.hpp>
TEST_CASE(
"cyclic_iterator array",
"[cyclic_iterator]"
)
{
typedef
std::array<
int,
3
>
int3_array;
int3_array const array{{
1,
2,
3
}};
typedef
fcppt::cyclic_iterator<
int3_array::const_iterator
>
iterator;
iterator const start(
array.begin(),
iterator::boundary{
array.begin(),
array.end()
}
);
iterator test(
start
);
REQUIRE(
*test
==
1
);
++test;
REQUIRE(
*test
==
2
);
++test;
REQUIRE(
*test
==
3
);
++test;
REQUIRE(
*test
==
1
);
REQUIRE(
test.get()
==
array.begin()
);
--test;
REQUIRE(
*test
==
3
);
REQUIRE(
test.get()
==
std::prev(
array.end()
)
);
--test;
REQUIRE(
*test
==
2
);
test += 2;
REQUIRE(
*test
==
1
);
test -= 1;
REQUIRE(
*test
==
3
);
test -= 300;
REQUIRE(
*test
==
3
);
++test;
REQUIRE(
test
==
start
);
}
| true |
afc488e312f480f705f78c1479b60c3b37c4d4ff | C++ | AemieJ/competitive | /gfg/37/main.cpp | UTF-8 | 428 | 3.28125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;
// explanation: we need m to be removed and the one before m need to be connected to the node after m. Thus, we change the pointer of m itself to the next node.
// This give the direct connection
void deleteNode(Node *m) {
*m = *(m->next);
}
int main() {
return 0;
} | true |
d1d880266627bce3228b2f837a3dc49aac155d3e | C++ | Kobayashi58843/MissileBozu | /ProjectShooter/SourceCode/Game/Model/Character/Event/EventModel.cpp | SHIFT_JIS | 3,551 | 2.796875 | 3 | [] | no_license | #include "EventModel.h"
//ʒu.
const D3DXVECTOR3 POSITION = { 0.0f, 0.0f, 0.0f };
EventModel::EventModel(clsD3DXSKINMESH* const pModel, const float fScale, const double dAnimSpeed)
: m_ModelState()
{
AttachModel(pModel);
//ʒu.
m_vPos = POSITION;
m_vRot = { 0.0f, 0.0f, 0.0f };
//TCY.
m_fScale = fScale;
//Aj[Vx.
SetAnimationSpeed(dAnimSpeed);
}
EventModel::~EventModel()
{
DetatchModel();
}
//3Df̕`.
void EventModel::RenderModel(const D3DXMATRIX &mView, const D3DXMATRIX &mProj)
{
//ʒu,],TCYfɓK.
UpdateState();
m_ModelState.dAnimationTime += m_ModelState.dAnimationSpeed;
m_ModelState.AnimationController->AdvanceTime(m_ModelState.dAnimationSpeed, nullptr);
m_pModel->Render(mView, mProj, m_ModelState.AnimationController);
}
//ff[^̊֘At.
void EventModel::AttachModel(clsD3DXSKINMESH* const pModel)
{
assert(pModel != nullptr);
m_pModel = pModel;
LPD3DXANIMATIONCONTROLLER pAC = m_pModel->GetAnimController();
pAC->CloneAnimationController(
pAC->GetMaxNumAnimationOutputs(),
pAC->GetMaxNumAnimationSets(),
pAC->GetMaxNumTracks(),
pAC->GetMaxNumEvents(),
&m_ModelState.AnimationController);
m_pModel->SetAnimSpeed(1);
}
//ff[^֘At.
void EventModel::DetatchModel()
{
if (m_pModel != nullptr)
{
m_pModel = nullptr;
if (m_ModelState.AnimationController != nullptr)
{
m_ModelState.AnimationController->Release();
m_ModelState.AnimationController = nullptr;
}
}
}
//Aj[Vւ.
void EventModel::ChangeAnimation(const int iIndex, const double dStartPos)
{
//Aj[V͈͓̔`FbN.
if (iIndex < 0 || iIndex >= GetAnimationQuantityMax())return;
m_pModel->ChangeAnimSet_StartPos(iIndex, dStartPos, m_ModelState.AnimationController);
m_ModelState.iIndex = iIndex;
m_ModelState.dAnimationTime = dStartPos;
}
//݂̃Aj[V̏ImF.
bool EventModel::IsAnimationEnd()
{
if (m_pModel->GetAnimPeriod(m_ModelState.iIndex) - m_ModelState.dAnimationSpeed < m_ModelState.dAnimationTime)
{
return true;
}
return false;
}
//݂̃Aj[VImF.
bool EventModel::IsAnimationRatioEnd(const float fRatio)
{
if ((m_pModel->GetAnimPeriod(m_ModelState.iIndex) - m_ModelState.dAnimationSpeed) * fRatio < m_ModelState.dAnimationTime)
{
return true;
}
return false;
}
//Aj[V̍Đxς.
void EventModel::SetAnimationSpeed(const double dAnimationSpeed)
{
m_ModelState.dAnimationSpeed = dAnimationSpeed;
m_pModel->SetAnimSpeed(m_ModelState.dAnimationSpeed);
}
//Aj[Vő吔擾.
int EventModel::GetAnimationQuantityMax()
{
if (m_ModelState.AnimationController != nullptr)
{
return static_cast<int>(m_ModelState.AnimationController->GetMaxNumAnimationSets());
}
return -1;
}
//ʒu,],TCYfɓK.
void EventModel::UpdateState()
{
m_pModel->m_Trans.vPos = m_vPos;
m_pModel->m_Trans.fPitch = m_vRot.x;
m_pModel->m_Trans.fYaw = m_vRot.y;
m_pModel->m_Trans.fRoll = m_vRot.z;
m_pModel->m_Trans.vScale = { m_fScale, m_fScale, m_fScale };
//蔻pSpherëʒu킹.
D3DXVECTOR3 vSpherePos = m_vPos;
//Spherȅꏊɂ炷.
const float fAdjustmentPositionY = 1.0f;
vSpherePos.y += m_Collision.fRadius + fAdjustmentPositionY;
m_Collision.vCenter = vSpherePos;
}
| true |
13b9b3a95713844b320892dd7641a20045afacc8 | C++ | DannyMoses/ArduinoSquareWaveGenerator | /SquareWaveGenerator.ino | UTF-8 | 1,694 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | /*
* A simple square wave generator using a tlc5940 IC, an LCD and some buttons
* Author: Daniel Moses
*/
/*
* PINOUTS:
* LCD on pins 8, 7, 6, 5, 4 and 2
* TLC5940 on the default pins for the library
* buttons: left: A1
* right: A2
* set: A3
*/
#include "Tlc5940.h"
#include <LiquidCrystal.h>
/* declarations for the potentiometer */
const int potPin = A0;
int potInput;
/* declarations for the LCD */
LiquidCrystal lcd(8, 7, 6, 5, 4, 2);
/* declarations for the buttons */
const int leftButton = A1;
const int rightButton = A2;
const int setButton = A3;
/* declarations for the tlc5940 */
int currentOutputValue;
void printToLCD(int channel)
{
lcd.clear();
lcd.home();
lcd.print("Channel: ");
lcd.print(channel, DEC);
lcd.setCursor(0, 1);
int output = Tlc.get(channel);
lcd.print("Output: ");
lcd.print(output, DEC);
}
void generateSquareWave(int channel, int output)
{
Tlc.set(channel, output);
Tlc.update();
}
void setup()
{
Tlc.init();
lcd.begin(16, 2);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(setButton, INPUT);
}
void loop()
{
potInput = analogRead(potPin);
currentOutputValue = map(potInput, 0, 1023, 0, 4095);
int leftButtonPressed = digitalRead(leftButton);
int rightButtonPressed = digitalRead(rightButton);
int setButtonPressed = digitalRead(setButton);
int currentChannel = 0;
if (leftButtonPressed == HIGH && currentChannel != 0)
{
currentChannel--;
}
else if (rightButtonPressed == HIGH && currentChannel != 15)
{
currentChannel++;
}
if (setButtonPressed == HIGH)
{
generateSquareWave(currentChannel, currentOutputValue);
}
printToLCD(currentChannel);
}
| true |
a4ee1053c6c37260ed4e277a794d26fde658ac31 | C++ | hmk1337/Prokom | /faktorial.cpp | UTF-8 | 456 | 3.453125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int faktorial(int bil,int hasil){
if(bil == 0){
cout<<'=';
return hasil;
}
else{
hasil*=bil;
cout<<bil;
if(bil != 1)
cout<<'*';
faktorial(bil-1,hasil);
}
}
int main(){
int bil,hasil=1;
cout<<"Masukan bilangan = ";
cin>>bil;
cout<<"Hitung nilai factorial "<<bil<<" = ";
cout<<faktorial(bil,hasil);
return 0;
}
| true |
d3ee778345d0d0e8a584603d5d035df291cb5c75 | C++ | kunhuicho/crawl-tools | /codecrawler/_code/hdu5088/16215543.cpp | UTF-8 | 1,430 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1000;
const int bit = 42;
typedef long long LL;
LL a[maxn][maxn],g[maxn];
int n;
void build_matrix() //æé ç³»æ°ç©éµ
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < bit; j++)
a[i][bit-1-j] = (g[i]>>j) & 1;
}
}
void Gauss(int n)
{
int row = 0,col = 0,j,k,r;
while(row < n && col < bit)
{
r = row;
for(k = row+1; k < n; k++)
if(a[k][col])
{
r = k;
break;
}
if(a[r][col])
{
if(r != row)
{
for(k = col; k < bit; k++)
swap(a[r][k],a[row][k]);
}
//弿æ¶å
for(k = row+1; k < n; k++)
{
if(a[k][col] == 0) continue;
for(j = col; j < bit; j++)
a[k][j] ^= a[row][j];
}
row++;
}
col++;
}
if(row < n) printf("Yes\n");
else printf("No\n");
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
for(int i = 0; i < n; i++)
scanf("%I64d",&g[i]);
build_matrix();
if(n > bit)
{
printf("Yes\n");
continue;
}
Gauss(n);
}
return 0;
} | true |
f3970f664f4dc0db25dddcc4f4fc5863992e19ea | C++ | rahul-prasad-cse/Algorithms | /heapsort.cpp | UTF-8 | 1,201 | 3.203125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int count;
cout<<"Enter the number of elements you want to enter:\n";
cin>>count;
int input[count];
for(int i=0;i<count;i++){
int temp;
cin>>temp;
if(i==0){
input[0]=temp;
continue;
}
input[i]=temp;
int j=i;
while(input[(j-1)/2]<input[j] && (j-1)/2>=0){
int swapper=input[(j-1)/2];
input[(j-1)/2]=input[j];
input[j]=swapper;
j=(j-1)/2;
}
}
int swapper=input[0];
input[0]=input[count-1];
input[count-1]=swapper;
for(int i=0;i<count-3;i++){
int j=0;
while(((input[j]<input[2*j+1] || input[j]<input[2*j+2])) && 2*j+2<=count-i-2){
if(2*j+2>count-1){
continue;
}
if(input[2*j+1]>input[2*j+2]){
int swapper=input[2*j+1];
input[2*j+1]=input[j];
input[j]=swapper;
j=2*j+1;
}
else if(input[2*j+2]>input[2*j+1]){
int swapper=input[2*j+2];
input[2*j+2]=input[j];
input[j]=swapper;
j=2*j+2;
}
}
int swapper=input[0];
input[0]=input[count-i-2];
input[count-i-2]=swapper;
}
swapper=input[0];
input[0]=input[1];
input[1]=swapper;
for(int i=0;i<count;i++){
if(i==count-1)
cout<<input[i]<<"\n";
else
cout<<input[i]<<" < ";
}
return 0;
} | true |
f46b175ae7f6360e337af3d61f27acea7e9e73cd | C++ | mLenehan1/EE219-Object-Oriented-Programming | /Assignment 5/A5Q2/main.cpp | UTF-8 | 282 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool isPowerOf(int num, const int base)
{
if(num%base == 0){
if(num/base == 1) return true;
else return isPowerOf(num/base, base);}
else return false;
}
int main()
{
cout << isPowerOf(32, 2);
}
| true |
76d2b9b4a697de4bcefce059257ce2e8981d272f | C++ | aaraki/CtCI | /Chapter_2/2.6_Palindrome/reverse.cpp | UTF-8 | 1,239 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode *reverse(ListNode *head) {
ListNode *prev = nullptr;
while (head != nullptr) {
ListNode *node = new ListNode(head->val);
node->next = prev;
prev = node;
head = head->next;
}
return prev;
}
bool isEqual(ListNode *l1, ListNode *l2) {
while (l1 != nullptr && l2 != nullptr) {
if (l1->val != l2->val) {
return false;
}
l1 = l1->next;
l2 = l2->next;
}
return (l1 == nullptr && l2 == nullptr);
}
bool isPalindrome(ListNode *head) {
ListNode *reversed = reverse(head);
return isEqual(head, reversed);
}
int main() {
vector<int> values{1, 2, 3, 2, 1};
ListNode *dummy = new ListNode(0);
ListNode *curr = dummy;
for (int n : values) {
curr->next = new ListNode(n);
curr = curr->next;
}
cout << isPalindrome(dummy->next) << endl; // true
return 0;
} | true |