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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e7a14cc88a3df43770c9b83f466842c88f33f4b4 | C++ | emrah2021/study | /functionChanining.cpp | UTF-8 | 557 | 3.65625 | 4 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
class Base
{
int _a;
int _b;
public:
Base& setA(int a) // Base& yerine Base dönerse kopyası yaratılır
{ _a=a;
return *this;
}
Base& setB(int b)
{ _b=b;
return *this;
}
void print() {std::cout << "a: " << _a << " b: " << _b << endl;}
};
int main()
{
Base b1;
// function chaining; with the help of this feature functions can de called in a strict order
b1.setA(5).setB(15).print();
return 0;
}
| true |
eb8e8d762a9611fccb9f22e81055f7344177c978 | C++ | Svyatoslav559/lab2 | /Header.h | UTF-8 | 692 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
class Circle {
int r;
int xC;
int yC;
public:
Circle();
int getR();
int getxC();
int getyC();
Circle operator+(int ob);
Circle operator-(int ob);
};
class Square {
int a;
int xSlt;
int ySlt;
public:
Square();
int geta();
int getxS1();
int getyS1();
void show();
Square operator+(int ob);
Square operator-(int ob);
Square operator*(int ob);
};
class Rectangle {
int a1;
int b1;
int xR1, yR1, xR2, yR2, xR3, yR3, xR4, yR4;
public:
Rectangle();
int geta1();
int getb1();
int getxR1();
int getyR1
();
void show();
Rectangle operator+(int ob);
Rectangle operator-(int ob);
Rectangle operator*(int ob);
};
| true |
11c74ec8391eafe1b7f969113ae0784fa0bb66fc | C++ | francoisdavid/COMP345 | /A2COMP345/Part 4/Player.cpp | UTF-8 | 5,448 | 3.359375 | 3 | [] | no_license |
#include <iostream>
#include "Player.h"
#include <string>
#include <cmath>
using namespace std;
//Determines player number
int* Player::objCounter = new int(1);
//Constructors
Player::Player()
{
playerNumber = new int(*objCounter);
playerName = "Player "+ to_string(*playerNumber);
playerCoins = new int();
dayOfBirth = new int();
monthOfBirth = new int();
yearOfBirth = new int();
playerAge = new double();
playerHand = new HandObject();
playerBiddingFacility = new BidingFacility();
*objCounter = *objCounter + 1;
}
Player::Player(string name, int coins, int DOB, int MOB, int YOB)
{
playerNumber = new int(*objCounter);
playerName = name;
playerCoins = new int (coins);
dayOfBirth = new int (DOB);
monthOfBirth = new int(MOB);
yearOfBirth = new int(YOB);
playerAge = new double();
playerHand = new HandObject();
playerBiddingFacility = new BidingFacility();
*objCounter = *objCounter + 1;
}
//Destructor
Player::~Player()
{
}
//Getters
string Player::getName()
{
return playerName;
}
int* Player::getPlayerNumber()
{
return playerNumber;
}
int* Player::getPlayerCoins()
{
return playerCoins;
}
int* Player::getDayOfBirth()
{
return dayOfBirth;
}
int* Player::getMonthOfBirth()
{
return monthOfBirth;
}
int* Player::getYearOfBirth()
{
return yearOfBirth;
}
//returns a double made by combining the day, month and year into one "age" value.
double* Player::getPlayerAge()
{
double DOB = *dayOfBirth;
double MOB = *monthOfBirth;
double YOB = *yearOfBirth;
double birthday = (DOB + MOB * 30.44 + YOB * 365.25);
*playerAge = birthday;
return (playerAge);
}
vector<Card*> Player::getCards()
{
return playerCards;
}
vector<Node*> Player::getCountries()
{
return playerCountries;
}
//Setters
void Player::setName(string name)
{
playerName = name;
}
void Player::setDayOfBirth(int DOB)
{
*dayOfBirth = DOB;
}
void Player::setMonthOfBirth(int MOB)
{
*monthOfBirth = MOB;
}
void Player::setYearOfBirth(int YOB)
{
*yearOfBirth = YOB;
}
void Player::setPlayerAge(double age)
{
*playerAge = age;
}
void Player::setPlayerCoins(int coins)
{
*playerCoins = coins;
}
void Player::printInfo()
{
cout << "Name: " + playerName << endl;
cout << "Number: " << *playerNumber << endl;
cout << "Date of Birth: " << *dayOfBirth << "/" << *monthOfBirth << "/" << *yearOfBirth << endl;
cout << "Coins: " << *playerCoins << endl;
cout << endl;
}
//when a player takes control of a country it will be added to the list
void Player::addCountry(Node* country)
{
Node* count = country;
playerCountries.emplace_back(count);
}
//when a player makes a bid at the beginning of the game
void Player::Bid(int bid)
{
while (bid > *playerCoins)
cout << "You don't have enough coins. Please enter another bid." << endl;
if (bid <= *playerCoins)
{
playerBiddingFacility->playerBid(this, bid);
//this->PayCoin(bid);
}
}
//when a player selects a card it will be added to their list of cards
void Player::BuyCard(int index)
{
Card* card = playerHand->exchange(index);
playerCards.emplace_back(card);
int price = ceil(double(index) / 2);
this->PayCoin(price);
}
void Player::PayCoin(int cost)
{
if (cost <= *playerCoins)
*playerCoins = *playerCoins - cost;
else
cout << "You don't have enough coins." << endl;
}
void Player::PlaceNewArmies(Node* location)
{
bool exists = false;
int index;
for (int i = 0; i < location->getArmies().size(); i++)
{
if (*(location->getArmies()[i]->getOwnerNumber()) == *(this->playerNumber))
{
exists = true;
index = i;
}
}
if (exists)
location->getArmies()[index]->setNumberOfSoldiers(*(location->getArmies()[index]->getNumberOfSoldiers()) + 1);
else
{
Army* army = new Army(location, *(this->playerNumber), 1);
playerArmy.emplace_back(army);
}
}
void Player::MoveArmies(Node* startLocation, Node* endLocation)
{
for (int i = 0; i < startLocation->getArmies().size(); i++)
{
if (*(startLocation->getArmies()[i]->getOwnerNumber()) == *(this->playerNumber))
{
startLocation->getArmies()[i]->setNumberOfSoldiers(*(startLocation->getArmies()[i]->getNumberOfSoldiers()) - 1);
PlaceNewArmies(endLocation);
break;
}
}
}
void Player::MoveOverLandOrWater(Node* startLocation, Node* endLocation)
{
MoveArmies(startLocation, endLocation);
}
void Player::BuildCity(Node* location)
{
City* city = new City(location,*(this->playerNumber));
playerCities.emplace_back(city);
}
void Player::DestroyArmy(Node* location, int ownerNumber)
{
for (int i = 0; i < location->getArmies().size(); i++)
if (*(location->getArmies()[i]->getOwnerNumber()) == ownerNumber)
{
location->getArmies()[i]->setNumberOfSoldiers(*(location->getArmies()[i]->getNumberOfSoldiers()) - 1);
break;
}
}
void Player::setPlayerBiddingFacility(BidingFacility* bf){
playerBiddingFacility = bf;
}
BidingFacility* Player::getBuildingFacility() {
return playerBiddingFacility;
}
void Player::playerBid(int coins) {
playerBiddingFacility->playerBid(this, coins);
}
void Player::toString(){
cout <<"Player-" << getName() << "\n\tCoins: " << *getPlayerCoins() << "\n\tDateOfBirth:" << *getDayOfBirth() << "/" << *getMonthOfBirth() << "/" << *getYearOfBirth()<< endl;
}
| true |
438f2e196037a6f7c9ca7e195a1404a6f2b1e6bf | C++ | bmarti/zz2 | /C++/tp5/chaines.hpp | UTF-8 | 332 | 2.53125 | 3 | [] | no_license | #ifndef TPCHAINES
#define TPCHAINES
#include <iostream>
#include <cstring>
class Chaine{
int capa;
char *tab;
public:
Chaine();
~Chaine();
Chaine(int capacity);
Chaine(const char *word);
Chaine(const Chaine &);
int getCapa();
char* getTab();
//Chaine remplacer(char *wordRepl);
//void afficher();
};
#endif
| true |
9c77e250f191913c770d716e55c1042f2c95b89e | C++ | epsilon-0/codechef-solutions | /long/JAN15/gcdq.cpp | UTF-8 | 932 | 2.640625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int gcd(int a, int b){
int t = a;
while(a>0){
t = a;
a = b%a;
b = t;
}
return b;
}
int lgcd[100005], rgcd[100005], a[100005];
#define S(n) scanf("%d", &n)
#define P(n) printf("%d\n", n)
int main(){
int t, n, q, l, r;
S(t);//cin >> t;
while(t--){
cin >> n >> q;
// cout << n << q << endl;;
for(int i = 0; i < n; i++){
S(a[i]);//cin >> a[i];
}
lgcd[0] = a[0];
rgcd[n-1] = a[n-1];
for(int i = 1; i < n; i++){
lgcd[i] = gcd(lgcd[i-1],a[i]);
rgcd[n-i-1] = gcd(rgcd[n-i], a[n-i-1]);
}
for(int i = 0; i < q; i++){
S(l);S(r);//cin >> l >> r;
// cout << l << r << endl;
l--;r--;
if(l>0 && r<n-1){
P(gcd(lgcd[l-1], rgcd[r+1]));// << endl;
}
else if(l==0 && r<n){
P(rgcd[r+1]);// << endl;
}
else{
P(lgcd[l-1]);// << endl;
}
}
}
}
| true |
2073ab19135f048533b24ddad21c303ea289adfa | C++ | przemo509/DistributedFileServer | /DistributedFileServer/server.cpp | UTF-8 | 3,854 | 2.8125 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <string>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/asio.hpp> // must be ater logging (otherwise you get linker error, don't know why)
#include "config.h"
#include "controller.h"
using namespace boost::asio;
using namespace std;
static const int HEADER_LENGTH = 5;
void assertRequestOk(size_t bytesReceived, int assumedLength, boost::system::error_code& errorCode) {
if (errorCode != 0) {
// TODO handle eof when server gets down
throw exception(("Exception while reading request: error: " + errorCode.message()).c_str());
}
if (bytesReceived != assumedLength) {
throw exception(string("Exception while reading request: unexpected length: " + bytesReceived).c_str());
}
}
string getBufAsString(boost::asio::streambuf& buf) {
ostringstream oss;
oss << &buf;
return oss.str();
}
int getRequestLength(boost::asio::streambuf& buf) {
string header = getBufAsString(buf);
int requestLength = atoi(header.c_str());
return requestLength;
}
string makeHeader(int bodySize) {
char h[HEADER_LENGTH + 1];
sprintf_s(h, ("%0" + to_string(HEADER_LENGTH) + "d").c_str(), bodySize);
return h;
}
string addHeader(string& request) {
return makeHeader(request.size()) + request;
}
int main(int argc, char* argv[])
{
// global logging filter
boost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace);
if (argc != 2) {
cout << "Usage: " << argv[0] << " config_file_full_path" << endl;
exit(EXIT_FAILURE);
}
string configFileFullPath = argv[1];
try
{
config config(configFileFullPath);
controller controller(config);
// preparing service
io_service io_service;
ip::tcp::acceptor acceptor(io_service, ip::tcp::endpoint(ip::tcp::v4(), config.getPort()));
int requests = 0;
while(true)
{
try
{
requests++;
// prepaaring socket
ip::tcp::socket socket(io_service);
BOOST_LOG_TRIVIAL(debug) << "###############################################################";
BOOST_LOG_TRIVIAL(debug) << "Waiting for requests on port " << config.getPort();
acceptor.accept(socket);
BOOST_LOG_TRIVIAL(debug) << "(" << requests << ") Request arrived";
// receiving request header (number of remaining bytes)
boost::system::error_code errorCode;
boost::asio::streambuf buf;
BOOST_LOG_TRIVIAL(debug) << "Waiting for request length header...";
size_t bytesReceived = read(socket, buf, detail::transfer_exactly_t(HEADER_LENGTH), errorCode);
assertRequestOk(bytesReceived, HEADER_LENGTH, errorCode);
int requestLength = getRequestLength(buf);
//buf.consume(bytesReceived); // clear buf
BOOST_LOG_TRIVIAL(debug) << "Request length header received: " << requestLength;
// receiving request body
BOOST_LOG_TRIVIAL(debug) << "Waiting for request body...";
bytesReceived = read(socket, buf, detail::transfer_exactly_t(requestLength), errorCode);
assertRequestOk(bytesReceived, requestLength, errorCode);
string request = getBufAsString(buf);
BOOST_LOG_TRIVIAL(debug) << "Request body received:\n" << request;
// sending response
string response = controller.calculateResponse(request);
BOOST_LOG_TRIVIAL(debug) << "Sending response:\n" << response;
write(socket, buffer(addHeader(response)));
BOOST_LOG_TRIVIAL(debug) << "Response sent";
}
catch (exception& e)
{
BOOST_LOG_TRIVIAL(fatal) << "Request processing exception: [" << e.what() << "]";
}
catch (...)
{
BOOST_LOG_TRIVIAL(fatal) << "Unknown request processing exception";
}
}
}
catch (exception& e)
{
BOOST_LOG_TRIVIAL(fatal) << "Global exception: [" << e.what() << "]";
}
catch (...)
{
BOOST_LOG_TRIVIAL(fatal) << "Unknown global exception";
}
return EXIT_SUCCESS;
} | true |
cab1abfe6aa69c7b49f15ec05d561e48d5559fdb | C++ | pce913/Algorithm | /baekjoon/11562.cpp | UTF-8 | 725 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
int dist[255][255];
int main(){
int n, m;
scanf("%d %d",&n,&m);
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (i == j)
continue;
dist[i][j] = 1e9;
}
}
for (int i = 0; i < m; i++){
int x, y, q;
scanf("%d %d %d",&x,&y,&q);
if (q == 0){
dist[x][y] = 0;
dist[y][x] = 1;
}
else{
dist[x][y] = 0;
dist[y][x] = 0;
}
}
for (int k = 1; k <= n; k++){
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (dist[i][j] > dist[i][k] + dist[k][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
int K;
scanf("%d",&K);
for (int qq = 0; qq < K; qq++){
int s, e;
scanf("%d %d",&s,&e);
printf("%d\n",dist[s][e]);
}
return 0;
} | true |
72297758b5d9f158176a5d28f55c12476cba4a65 | C++ | smhi/metlibs-milogger-qt4 | /src/miLogging_log4cpp.cc | UTF-8 | 2,575 | 2.640625 | 3 | [] | no_license |
#include <log4cpp/Category.hh>
#include <log4cpp/CategoryStream.hh>
#include <log4cpp/PropertyConfigurator.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace /* anonymous*/ {
log4cpp::Category& getCategoryL4C(const std::string& name)
{
if (name.empty())
return log4cpp::Category::getRoot();
else
return log4cpp::Category::getInstance(name);
}
log4cpp::Priority::PriorityLevel levelToL4C(::milogger::detail::PriorityLevel pl)
{
switch (pl) {
case ::milogger::detail::VERBOSE: return log4cpp::Priority::DEBUG;
case ::milogger::detail::DEBUG: return log4cpp::Priority::DEBUG;
case ::milogger::detail::INFO : return log4cpp::Priority::INFO;
case ::milogger::detail::WARN : return log4cpp::Priority::WARN;
case ::milogger::detail::ERROR: return log4cpp::Priority::ERROR;
case ::milogger::detail::FATAL: return log4cpp::Priority::FATAL;
}
return log4cpp::Priority::FATAL;
}
} // anonymous namespace
// ########################################################################
namespace milogger {
LoggingConfig::LoggingConfig(const std::string& l4c_p)
{
struct stat sb;
if (stat(l4c_p.c_str(), &sb) == 0) {
log4cpp::PropertyConfigurator::configure(l4c_p);
} else {
log4cpp::Appender *a = new log4cpp::OstreamAppender("rootAppender", &std::cout);
log4cpp::PatternLayout* layout = new log4cpp::PatternLayout();
layout->setConversionPattern("%d %p %c: %m%n");
a->setLayout(layout);
log4cpp::Category& root = log4cpp::Category::getRoot();
root.setPriority(log4cpp::Priority::WARN);
root.addAppender(a);
}
}
LoggingConfig::~LoggingConfig()
{
log4cpp::Category::shutdown();
}
} // namespace milogger
// ########################################################################
namespace milogger {
namespace detail {
struct CategoryPrivate {
CategoryPrivate(log4cpp::Category& c)
: mCategory(c) { }
log4cpp::Category& mCategory;
};
// ------------------------------------------------------------------------
Category::Category(std::string c)
: p(new CategoryPrivate(getCategoryL4C(c)))
{
}
// ------------------------------------------------------------------------
bool Category::isLoggingEnabled(PriorityLevel pl)
{
return p->mCategory.isPriorityEnabled(levelToL4C(pl));
}
void Category::log(PriorityLevel pl, const std::string& message)
{
p->mCategory.getStream(levelToL4C(pl)) << message;
}
} // namespace detail
} // namespace milogger
| true |
7a3918ac4868ef6b720685dd4093d2bc34ae180c | C++ | alanmbennett/NBA-Stats-Database | /Coach.cpp | UTF-8 | 3,571 | 3.234375 | 3 | [] | no_license | //
// Coach.cpp
// NBA_DB
//
// Created by Alan Bennett on 1/18/18.
// Copyright © 2018 Alan Bennett. All rights reserved.
//
#include <sstream>
#include "Coach.h"
Coach::Coach(std::vector<std::string>& parameters)
{
if(!isValidId(parameters[0]))
throw InvalidDataException("Error: ID must consist of less than 7 capital letters and two digits.");
if(parameters.size() < 9)
throw InvalidDataException("Error: Not enough arguments.");
if(parameters.size() > 9)
throw InvalidDataException("Error: Too many arguments.");
if(isNeg(stoi(parameters[1])))
throw InvalidDataException("Error: Season must be non-negative.");
if(parameters[1].length() != 4)
throw InvalidDataException("Error: Season must be a 4-digit number.");
if(isNeg(stoi(parameters[4])))
throw InvalidDataException("Error: Season Win must be non-negative.");
if(isNeg(stoi(parameters[5])))
throw InvalidDataException("Error: Season Loss must be non-negative.");
if(isNeg(stoi(parameters[6])))
throw InvalidDataException("Error: Playoff Win must be non-negative.");
if(isNeg(stoi(parameters[7])))
throw InvalidDataException("Error: Playoff Loss must be non-negative.");
columns = parameters;
}
bool Coach::isValidId(std::string str)
{
int capCount = 0;
int digitCount = 0;
if(!containsAlphaNum(str))
return false;
for(int i = 0; i < str.length(); i++)
{
if(isupper(str[i]))
capCount++;
else if(isdigit(str[i]))
digitCount++;
}
if(capCount <= 7)
if(digitCount <= 2)
return true;
return false;
}
std::string Coach::getAttribute(std::string attribute)
{
std::string str;
if(attribute == "Coach_ID" || attribute == "coach_ID")
return getId();
else if(attribute == "season")
return getYear();
else if(attribute == "first_name")
return getFirstName();
else if(attribute == "last_name" || attribute == "lastname")
return getLastName();
else if(attribute == "season_win")
return getSeasonWin();
else if(attribute == "season_loss")
return getSeasonLoss();
else if(attribute == "playoff_win")
return getPlayoffWin();
else if(attribute == "playoff_loss")
return getPlayoffLoss();
else if(attribute == "team")
return getTeam();
else if(attribute == "net_wins")
return getNetWins();
return "";
}
std::vector<std::string>& Coach::getColumns()
{
return columns;
}
std::string Coach::getId()
{
return columns[0];
}
std::string Coach::getYear()
{
return columns[1];
}
std::string Coach::getFirstName()
{
return columns[2];
}
std::string Coach::getLastName()
{
std::string str = columns[3];
size_t i = str.find_first_of("+");
if(i != std::string::npos)
str[i] = ' ';
return str;
}
std::string Coach::getSeasonWin()
{
return columns[4];
}
std::string Coach::getSeasonLoss()
{
return columns[5];
}
std::string Coach::getPlayoffWin()
{
return columns[6];
}
std::string Coach::getPlayoffLoss()
{
return columns[7];
}
std::string Coach::getTeam()
{
return columns[8];
}
std::string Coach::getNetWins()
{
std::ostringstream oss;
int netWins = (stoi(getSeasonWin())- stoi(getSeasonLoss())) + (stoi(getPlayoffWin()) - stoi(getPlayoffLoss()));
oss << netWins;
return oss.str();
}
| true |
3cc6fe7a1c72fe887729d0751184176ab501ea68 | C++ | vassilismourikis/cpp1942 | /CppAssignment/Enemy.h | UTF-8 | 436 | 2.515625 | 3 | [] | no_license | #pragma once
#include "Plain.h"
#include "Bullet.h"
class Enemy :public Plain{
protected:
float fx, fy,hp;
public:
float lastBulletTime;
static std::vector<Bullet*> bullets;
Enemy(float w, float h, std::string path, const class Game& mygame);
virtual void draw()=0;
virtual void update() =0;
virtual int getPoints() = 0;
virtual int getHp();
virtual void decrHp(float i);
Collider getCollider() const override;
~Enemy();
}; | true |
d6381683c7173674fe332d7199d256ee13259522 | C++ | sohechai/piscine-cpp | /module-08/ex01/span.hpp | UTF-8 | 1,666 | 2.609375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* span.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sohechai <sohechai@student.42lyon.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/06 18:27:16 by sohechai #+# #+# */
/* Updated: 2021/09/14 15:37:39 by sohechai ### ########lyon.fr */
/* */
/* ************************************************************************** */
#ifndef SPAN_HPP
# define SPAN_HPP
# include <iostream>
# include <list>
# include <vector>
# include <algorithm>
class span
{
public:
span();
span(unsigned int N);
span(const span &src);
~span();
span& operator=(span const &rhs);
void addNumber(int n);
void addNumberrange(int range);
int shortestSpan();
int longestSpan();
class ObjectFullException : public std::exception
{
public:
virtual const char* what() const throw()
{
return ("Object is full");
}
};
class NoSpanToFindException : public std::exception
{
public:
virtual const char* what() const throw()
{
return ("There is no span to find");
}
};
private:
unsigned int _size;
unsigned int _place;
std::vector<int> _tab;
};
#endif | true |
a2965359bdfbead7ba701059e35531e15c27a939 | C++ | ZaChizz/cohesion | /Category.h | UTF-8 | 587 | 2.609375 | 3 | [] | no_license | //
// Created by Admin on 28.02.2021.
//
#ifndef CONNECTIVITY_CATEGORY_H
#define CONNECTIVITY_CATEGORY_H
#include <iostream>
#include <set>
#include "Item.h"
#include "template.cpp"
class Item;
class Category {
private:
std::string name;
std::set<std::string>* items;
public:
Category(const std::string& name);
~Category();
std::string& getName();
const std::set<std::string>& getItems() const;
void addItem(Item* ptr);
void deleteItem(Item* ptr);
};
std::ostream& operator<<(std::ostream& out, Category& category);
#endif //CONNECTIVITY_CATEGORY_H
| true |
4109371e5b198c0f3c655c19d577cb3a4e9720dc | C++ | Kochanac/acs-hw1 | /hw1/src/fraction.cpp | UTF-8 | 389 | 3.109375 | 3 | [] | no_license | #include "fraction.h"
void In(fraction &num, std::ifstream &in) {
in >> num.a >> num.b;
}
void InRnd(fraction &num) {
num.a = rand() % 1000;
num.b = rand() % 1000 + 1;
}
// Вывод в поток
void Out(fraction &num, std::ofstream &out) {
out << num.a << " / " << num.b << " ";
}
double RationalRepr(fraction &num) {
return (double) num.a / (double) num.b;
}
| true |
1d2efde299df982f0d0ef88db4c6d930a33d8c7c | C++ | YashAgarwal/HackerRank | /road_1.cpp | UTF-8 | 768 | 2.890625 | 3 | [] | no_license |
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main(){
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
int n;
int m;
int x;
int y;
cin >> n >> m >> x >> y;
//Build a Adjacency List
vector< vector<int> > A(n);
//vector<int> A[10];
for(int a1 = 0; a1 < m; a1++){
int city_1;
int city_2;
cin >> city_1 >> city_2;
cout << city_1;
A[city_1].push_back(city_2);
A[city_2].push_back(city_1);
}
for(int i=0; i<n; i++){
for(int j=0; j<A[i].size(); j++){
cout << A[i][j] << " ";
}
cout << endl;
}
}
return 0;
}
| true |
f88fc29d5ab9dec8dd3db3d0cd22a2b00064a0c8 | C++ | eblade/steps | /src/Output.cpp | UTF-8 | 5,431 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "Output.h"
OutputRouter::OutputRouter() {
for (int i = 0; i < MAX_OUTPUTS; i++) {
output[i] = OutputSettings();
peak[i] = 0;
}
for (int i = 0; i < MAX_OUTPUT_DEVICES; i++) {
midi_output[i] = NULL;
}
ofxMidiOut::listPorts();
active_output = 0;
};
OutputRouter::~OutputRouter() {
for (int i = 0; i < MAX_OUTPUT_DEVICES; i++) {
if (midi_output[i] != NULL) {
ofLogNotice("OutputRouter") << "Closing midi port " << i
<< " \"" << midi_output[i]->getName() << "\"";
midi_output[i]->closePort();
delete midi_output[i];
midi_output[i] = NULL;
}
};
};
bool OutputRouter::install(OutputSettings settings) {
if (output[active_output].used) {
ofLogError("OutputRouter") << "ERROR: Output address " << active_output << " in use";
return true;
}
output[active_output].type = settings.type;
output[active_output].device = settings.device;
output[active_output].channel = settings.channel;
output[active_output].used = true;
if (settings.type == OUTPUT_TYPE_MIDI) {
if (midi_output[settings.device] == NULL) {
midi_output[settings.device] = new ofxMidiOut();
midi_output[settings.device]->openPort(settings.device);
ofLogNotice("OutputRouter") << "Opened midi port " << settings.device
<< " \"" << midi_output[settings.device]->getName() << "\"";
}
}
return false;
}
void OutputRouter::uninstall() {
output[active_output].used = false;
}
int OutputRouter::getChannel() { return output[active_output].channel; }
void OutputRouter::setChannel(int channel) {
if (channel >= 0 && channel <= 16) {
output[active_output].channel = channel;
} else {
ofLogError("OutputRouter") << "WARNING: Bad channel " << channel;
}
}
int OutputRouter::getOutput() { return active_output; }
void OutputRouter::setOutput(int active_output) {
if (active_output >= 0 && active_output < MAX_OUTPUTS) {
this->active_output = active_output;
} else {
ofLogError("OutputRouter") << "WARNING: Bad output " << active_output;
}
}
string OutputRouter::getOutputString(int address) {
string active_marker = (address == active_output) ? ">" : " ";
if (!(address >= 0 && address < MAX_OUTPUTS)) {
return " " + ofToString(address) + ":OUT OF BOUNDS";
} else if (output[address].used == false) {
return active_marker + ofToString(address) + ":-";
} else {
if (output[address].type == OUTPUT_TYPE_DUMMY) {
return active_marker + ofToString(address) + ":D"
+ ofToString(output[address].device) + "/"
+ ofToString(output[address].channel);
} else if (output[address].type == OUTPUT_TYPE_MIDI) {
return active_marker + ofToString(address) + ":M"
+ ofToString(output[address].device) + "/"
+ ofToString(output[address].channel);
}
}
return "?";
}
int OutputRouter::getPeak(int address) {
peak[address]--;
peak[address] = peak[address] >= 0 ? peak[address] : 0;
return peak[address];
}
void OutputRouter::send(int address, OutputEvent event) {
if (!(address >= 0 && address < MAX_OUTPUTS) || output[address].used == false) {
ofLogError("OutputRouter") << "Output " << address << " is not installed";
return;
}
switch (output[address].type) {
case OUTPUT_TYPE_DUMMY:
sendDummy(output[address], event);
break;
case OUTPUT_TYPE_MIDI:
sendMidi(output[address], event);
break;
}
peak[address] = 55;
}
void OutputRouter::sendDummy(OutputSettings settings, OutputEvent event) {
ofLogNotice("OutputRouter")
<< "SEND DUMMY device=" << settings.device
<< " channel=" << settings.channel
<< " note=" << event.note
<< " velocity=" << event.velocity;
}
void OutputRouter::sendMidi(OutputSettings settings, OutputEvent event) {
ofLogNotice("OutputRouter")
<< "SEND MIDI device=" << settings.device
<< " channel=" << settings.channel
<< " note=" << event.note
<< " velocity=" << event.velocity;
if (midi_output[settings.device] == NULL) {
cerr << "ERROR: Device " << settings.device << " is not installed";
return;
}
midi_output[settings.device]->sendNoteOn(settings.channel, event.note, event.velocity);
}
void OutputRouter::write(ofstream& f) {
f << "# OutputRouter\n";
for (int i = 0; i < MAX_OUTPUTS; i++) {
if (output[i].used) {
f << "set-output-select " << i << "\n"
<< "midi-install " << output[i].device << "\n"
<< "set-channel " << output[i].channel << "\n";
}
}
}
const ofColor OutputColors::color[] = {
ofColor(50, 50, 50),
ofColor(100, 50, 50),
ofColor(50, 100, 50),
ofColor(50, 50, 100),
ofColor(100, 100, 50),
ofColor(100, 50, 100),
ofColor(50, 100, 100),
ofColor(200, 100, 50),
ofColor(100, 200, 50),
ofColor(100, 50, 200),
ofColor(50, 100, 200),
ofColor(50, 200, 100),
ofColor(0, 0, 0),
ofColor(20, 50, 100),
ofColor(50, 20, 100),
ofColor(100, 50, 20)
};
| true |
a029b2bb841929961b9035294212346c4a7934d4 | C++ | someblue/ACM | /2014SummerTraining/个人赛/contest2/a.cpp | UTF-8 | 1,539 | 2.671875 | 3 | [] | no_license | /*
* this code is made by scaucontest
* Problem: 1147
* Verdict: Accepted
* Submission Date: 2014-07-17 11:12:14
* Time: 220MS
* Memory: 1676KB
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL dfs(const LL &len, const LL &s, const LL &pos, const LL &dist) {
if (len == 1) {
return s;
}
LL lenR = len >> 1;
LL lenL = len - lenR;
if (pos <= lenL) { // to left
return dfs(lenL, s, pos, dist << 1);
} else { // to right
return dfs(lenR, s + dist, pos - lenL, dist << 1);
}
}
LL dfs(const LL &len, const LL &s, const LL &num, const LL &dist, const LL &pos) {
if (len == 1) {
return pos;
}
LL nth = (num - s) / dist + 1;
LL lenR = len >> 1;
LL lenL = len - lenR;
if (nth & 1) { // to left
return dfs(lenL, s, num, dist << 1, pos);
} else { // to right
return dfs(lenR, s + dist, num, dist << 1, pos + lenL);
}
}
int Run() {
LL n, m;
//while (cin >> n >> m) {
while (~scanf("%lld%lld", &n, &m)) {
LL x, y;
for (int i = 0; i < m; ++i) {
//cin >> x >> y;
scanf("%lld%lld", &x, &y);
if (x == 1) {
//cout << dfs(n, 1, y, 1) << endl;
printf("%lld\n", dfs(n, 1, y, 1));
} else {
//cout << dfs(n, 1, y, 1, 1) << endl;
printf("%lld\n", dfs(n, 1, y, 1, 1));
}
}
}
return 0;
}
int main() {
//ios::sync_with_stdio(0);
return Run();
} | true |
08f81b7868c9f73088a8c45fff9cf9675ad17584 | C++ | angad/algos | /sorting.cpp | UTF-8 | 2,010 | 3.46875 | 3 | [] | no_license | /*
* sorting.cpp
*
* Created on: Oct 21, 2012
* Author: angadsingh
*/
#include <iostream>
using namespace std;
void merge(int *a,int low,int pivot,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=pivot+1;
while((h<=pivot)&&(j<=high)) {
if(a[h]<=a[j]) b[i]=a[h++];
else b[i]=a[j++];
i++;
}
if(h>pivot)
for(k=j; k<=high; k++) b[i++]=a[k];
else
for(k=h; k<=pivot; k++) b[i++]=a[k];
//copy b to a
for(k=low; k<=high; k++) a[k]=b[k];
}
void mergesort(int *a, int low,int high) {
int pivot;
if(low<high) {
pivot = (low + high) / 2;
mergesort(a, low, pivot);
mergesort(a, pivot+1, high);
merge(a, low, pivot, high);
}
}
int partition(int *a, int start, int end) {
//get the position of the pivot
//elements on the left should be less than the pivot
//elements on the right should be more than the pivot
int m = (start + end) / 2;
int pivot = a[m];
int temp;
int i = start; int j = end;
while(i < j) {
while(a[i] <= pivot && i<=end) i++;
while(a[j] >= pivot && j>=start) j--;
if(i < j) {
//swap
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
a[start] = a[j];
a[j] = pivot;
return j;
}
void quicksort(int *a, int start, int end) {
int m;
if(start < end) {
m = partition(a, start, end);
quicksort(a, start, m-1);
quicksort(a, m, end);
}
}
int main() {
int a[] = {12,10,43,23,-78,45,123,56,98,41,90,24,9,8,7,6,5,4,3,2,1};
int num = sizeof(a)/sizeof(int);
int t = clock();
mergesort(a, 0, num-1);
cout<<"Time taken = "<<(clock()-t)<<endl;
for(int i=0; i<num; i++)
cout<<a[i]<<" ";
cout<<endl;
int b[] = {12,10,43,23,-78,45,123,56,98,41,90,24,9,8,7,6,5,4,3,2,1};
num = sizeof(b)/sizeof(int);
cout<<endl<<num<<" ";
t = clock();
quicksort(b, 0, num-1);
cout<<"Time taken = "<<(clock()-t)<<endl;
for(int i=0; i<num; i++)
cout<<b[i]<<" ";
cout<<endl;
return 0;
}
| true |
7631fed2cb553696eb078653010acef94c005669 | C++ | MasterIceZ/Code_CPP | /Code_15/TOI15/lesson3/Barrier TOI12.cpp | UTF-8 | 1,106 | 2.53125 | 3 | [] | no_license | /*
TASK:Barrier TOI12
LANG: CPP
AUTHOR: KersaWC
SCHOOL: REPS
*/
#include<bits/stdc++.h>
using namespace std;
long long a[6000100];
deque<long long> dq;
int main(){
long long n,w,i,len,ma=0,ch=1;
scanf("%lld %lld",&n,&w);
for(i=1;i<=n;i++){
scanf("%lld",&a[i]);
if(a[i]>0)ch=0;
a[i]+=a[i-1];
}
if(ch){
printf("0\n0\n");
return 0;
}
dq.push_back(0);
for(i=1;i<=n;i++){
while(!dq.empty() && i-dq.front()>w)dq.pop_front();
if(a[i]-a[dq.front()]==ma)len=min(len,i-dq.front());
if(a[i]-a[dq.front()]>ma){
ma=a[i]-a[dq.front()];
len=i-dq.front();
}
while(!dq.empty() && a[i]<=a[dq.back()])dq.pop_back();
dq.push_back(i);
}
printf("%lld\n%lld\n",ma,len);
}
/*
ติดกัน k ตัวนึกถึง sliding window deque
เกิน 4 ตัว pop front(i-dq.front()>k) ทิ้ง pop back while (qs[i]<qs[dq.back()]) ถ้าค่าลด
เป็น deque of index
ans=qs[dq.back()]-qs[dq.front()]
len=dq.back()-dq.front();
*/
| true |
f04ea4bbc0f781114608114af2a7f7e240e4680b | C++ | eshasachan18/100DaysofCode | /Leetcode/November/5_Nov.cpp | UTF-8 | 340 | 2.71875 | 3 | [] | no_license | Problem=https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/solution/
class Solution {
public:
int minCostToMoveChips(vector<int>& pos)
{
int e=0,o=0;
for(int i=0;i<pos.size();i++)
{
if(pos[i]%2==0){e++;}
else{o++;}
}
return min(o,e);
}
};
| true |
43c419a1124cebbeb53a97837829dc1a4f0f669e | C++ | bdmarinov/OOP | /Bank Systems/Bank/SavingsAccount.h | UTF-8 | 345 | 2.671875 | 3 | [] | no_license | #pragma once
#include "Account.h"
class SavingsAccount :
public Account
{
public:
SavingsAccount(int, int, double, double = 2);
double getInterestRate() const;
void deposit(double) override;
bool withdraw(double) override;
void display() const override;
~SavingsAccount();
private:
double interestRate = 2;
};
| true |
929bf8f75f3ab0b6a0c8b23e4c19872a10c82a7d | C++ | zikai1/RPCD | /src/final/fit_circle.cpp | UTF-8 | 2,949 | 2.640625 | 3 | [] | no_license | /**
* @file
* @author answeror <answeror@gmail.com>
* @date 2012-01-11
*
* @section DESCRIPTION
*
*
*/
/// http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion
// REMEMBER to update "lu.hpp" header includes from boost-CVS
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace
{
namespace ublas = boost::numeric::ublas;
/* Matrix inversion routine.
Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */
template<class T>
bool InvertMatrix(const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {
using namespace boost::numeric::ublas;
typedef permutation_matrix<std::size_t> pmatrix;
// create a working copy of the input
matrix<T> A(input);
// create a permutation matrix for the LU-factorization
pmatrix pm(A.size1());
// perform LU-factorization
int res = lu_factorize(A,pm);
if( res != 0 ) return false;
// create identity matrix of "inverse"
inverse.assign(ublas::identity_matrix<T>(A.size1()));
// backsubstitute to get the inverse
lu_substitute(A, pm, inverse);
return true;
}
}
#include <cmath>
#include <QDebug>
#include "fit_circle.hpp"
cvcourse::fit_circle::result_type cvcourse::fit_circle::go(const point_container &ps)
{
//qDebug() << "in go";
BOOST_ASSERT(ps.size() > 2);
typedef ublas::matrix<double> mat;
typedef ublas::vector<double> vec;
const int n = ps.size();
mat M(n, 3);
for (int i = 0; i != n; ++i)
{
M(i, 0) = ps[i][0];
M(i, 1) = ps[i][1];
M(i, 2) = 1;
}
vec y(n);
for (int i = 0; i != n; ++i)
{
y(i) = ps[i][0] * ps[i][0] + ps[i][1] * ps[i][1];
}
auto MT = trans(M);
auto B = prod(MT, M);
vec c = prod(MT, y);
mat C(B.size1(), B.size2());
//qDebug() << "b4 inv";
bool ret = InvertMatrix(mat(B), C);
//qDebug() << "aft inv" << ret;
BOOST_ASSERT(ret);
vec z = prod(C, c);
result_type result;
/// calc circle
{
result.center[0] = z(0) * 0.5;
result.center[1] = z(1) * 0.5;
result.radius = std::sqrt(z(2) + result.center[0] * result.center[0] + result.center[1] * result.center[1]);
}
/// calc mse
{
result.mse = 0;
auto sq = [](double x){ return x * x; };
for (int i = 0; i != n; ++i)
{
result.mse += sq(length(ps[i] - result.center) - result.radius);
}
result.mse /= n;
}
//qDebug() << "---";
//qDebug() << "center:" << result.center[0] << result.center[1];
//qDebug() << "radius:" << result.radius;
//qDebug() << "mse" << result.mse;
return result;
}
| true |
42a126317bfd796d42ff8559dfd5c22d27f9d824 | C++ | trunghai95/MyCPCodes | /Codeforces/103B.cpp | UTF-8 | 592 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n, m, p[111], rank[111], u, v, cnt;
int find(int x)
{
return (p[x] == x) ? x : (p[x] = find(p[x]));
}
void join(int x, int y)
{
x = find(x);
y = find(y);
if (x == y)
return;
--cnt;
if (rank[x] > rank[y])
swap(x,y);
p[x] = y;
rank[y] += rank[x];
}
int main()
{
scanf("%d %d", &n, &m);
if (n != m)
{
printf("NO\n");
return 0;
}
for (int i = 1; i <= n; ++i)
p[i] = i;
cnt = n;
while (m--)
{
scanf("%d %d", &u, &v);
join(u, v);
}
if (cnt == 1)
printf("FHTAGN!\n");
else
printf("NO\n");
return 0;
} | true |
efb4d961712270d183b121a799a112b2b0f5683b | C++ | Mesarthim-14/KonishiYuuto | /吉田学園情報ビジネス専門学校_小西優斗/00_2Dシューティングゲーム/00_2Dシューティングゲーム/01_開発環境/2年_2Dシューティングゲーム/2年_2Dシューティングゲーム/flash.h | SHIFT_JIS | 2,768 | 2.796875 | 3 | [] | no_license | #ifndef _FLASH_H_
#define _FLASH_H_
//=============================================================================
//
// tbVNXwb_[ [flash.h]
// Author : Konishi Yuuto
//
//=============================================================================
//=============================================================================
// CN[h
//=============================================================================
#include "effect.h"
//=============================================================================
// }N`
//=============================================================================
#define FLASH_SIZE_X (27) // TCY
#define FLASH_SIZE_Y (27) // TCY
#define FLASH_LIFE (5) // Ct
#define FLASH_NUM (30) //
//=============================================================================
// O錾
//=============================================================================
class CEffect;
//=============================================================================
// tbVNX
//=============================================================================
class CFlash : public CEffect
{
public:
typedef enum
{
FLASH_TYPE_NONE = 0, // l
FLASH_TYPE_TOP, //
FLASH_TYPE_SHOT, // Ԃ
FLASH_TYPE_MAX
}FLASH_TYPE;
typedef enum
{
FLASH_COLOR_NONE = 0, // l
FLASH_COLOR_WHITE, // V[h
FLASH_COLOR_BLACK, // ԂV[h
FLASH_COLOR_MAX
}FLASH_COLOR;
CFlash(); // RXgN^
~CFlash(); // fXgN^
HRESULT Init(D3DXVECTOR3 pos, D3DXVECTOR3 size, TYPE type); //
void Uninit(void); // I
void Update(void); // XV
void Draw(void); // `揈
static CFlash * Create( // |S
D3DXVECTOR3 pos, D3DXVECTOR3 size, TYPE type,
FLASH_COLOR Ctype, FLASH_TYPE Ftype , int nLife);
void SetMove(D3DXVECTOR3 move); // ړʐݒ
void SetColor(FLASH_COLOR Ctype); // F̐ݒ
void InitColor(void); // F̏
void GetPlayerPos(void); // vC[̎擾
void GetLaserTop(void); // [U[̏
void SetFType(FLASH_TYPE Ftype); // [U[̃^Cvݒ
private:
D3DXVECTOR3 m_Pos; // W
D3DXVECTOR3 m_move; // ړ
LPDIRECT3DVERTEXBUFFER9 m_pVtxBuff; // _obt@̃|C^
FLASH_COLOR m_Ctype; // J[^Cv
FLASH_TYPE m_Ftype; // GtFNg^Cv
int m_nLife; // Ct
D3DXVECTOR3 m_TargetOld; // WǏÂW
};
#endif | true |
6fb16b7b5d884e42ecdcebca432a5c8a9ea0f9ff | C++ | x-bin/SuperFlow | /SpaceSaving/hash-map.cpp | UTF-8 | 2,198 | 2.96875 | 3 | [] | no_license | //
// hash-map.cpp
// SpaceSaving
//
// Created by 熊斌 on 2020/2/9.
// Copyright © 2020 熊斌. All rights reserved.
//
#include "hash-map.h"
HashMap::HashMap(const int size) {
size_ = size;
keys_ = new string[size_];
values_ = new Child*[size_];
half_ = size_ / 2;
full = false;
for (int i = 0; i < size_; ++i) {
keys_[i] = "0";
}
}
HashMap::~HashMap() {
delete[] keys_;
delete[] values_;
}
void HashMap::Insert(const string key, Child* value) {
uint32_t fingerprint = CRC::Calculate(key.c_str(), key.length(), hash1);
int i = fingerprint % size_;
while (keys_[i] != "0")
{
i = (i == size_ - 1) ? 0 : i + 1;
}
keys_[i] = key;
values_[i] = value;
}
void HashMap::Remove(const string key) {
if(key == "0")
return;
uint32_t fingerprint = CRC::Calculate(key.c_str(), key.length(), hash1);
int i = fingerprint % size_;
printf("g");
while (keys_[i] != key) {
i = (i == size_ - 1) ? 0 : i + 1;
}
printf("z");
keys_[i] = "0";
if(full)
return;
// Fill in the deletion gap.
int j = (i == size_ - 1) ? 0 : i + 1;
int st = j;
while (keys_[j] != "0") {
uint32_t fingerprint_j = CRC::Calculate(keys_[j].c_str(), keys_[j].length(), hash1);
/*int dis = (fingerprint_j % size_) - i;
if (dis < -half_) dis += size_;
if (dis > half_) dis -= size_;
if (dis <= 0) {
keys_[i] = keys_[j];
values_[i] = values_[j];
keys_[j] = "0";
i = j;
}*/
if(j==st)
{
full = true;
break;
}
if(fingerprint_j != j){
keys_[i] = keys_[j];
values_[i] = values_[j];
keys_[j] = "0";
i = j;
}
//printf("%d\n",j);*/
j = (j == size_ - 1) ? 0 : j + 1;
}
}
bool HashMap::Find(const string key, int* index) {
uint32_t fingerprint = CRC::Calculate(key.c_str(), key.length(), hash1);
int i = fingerprint % size_;
int st = i;
while (true) {
if (keys_[i] == "0") {
return false;
}
if (keys_[i] == key) {
*index = i;
return true;
}
i = (i == size_ - 1) ? 0 : i + 1;
if(st == i)
return false;
}
return false;
}
| true |
f8473bcb4f39f141e1e20851715da52abe8cda1d | C++ | martinasabova/cppMatice | /inverzna.cpp | UTF-8 | 4,533 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include "zlomok.h"
#include "funkcie.h"
#include "inverzna.h"
void inverzna()
{
Zlomok **povodna;
Zlomok **inverzna;
Zlomok **nemeniaca;
std::cout <<"Zadaj rozmer matice: ";
int rozmer=otestujKladneCislo();
alokuj(&povodna, rozmer);
alokuj(&inverzna, rozmer);
alokuj(&nemeniaca, rozmer);
nacitajPovodnu(povodna,nemeniaca,rozmer);
spravJednotkovu(inverzna,rozmer);
std::cout <<"Povodna:" <<std::endl;
//vypis(nemeniaca,rozmer);
if(vypocitajInverznu(povodna, inverzna, rozmer)==1) //aby sa nahodou nedelilo nulou
{
uvolni(povodna,rozmer);
uvolni(inverzna,rozmer);
uvolni(nemeniaca,rozmer);
exit(0);
}
std::cout <<"Inverzna:" <<std::endl;
vypis(inverzna,rozmer);
//vynasob(nemeniaca, inverzna, rozmer);
uvolni(povodna,rozmer);
uvolni(inverzna,rozmer);
uvolni(nemeniaca,rozmer);
}
void inverzna(Zlomok * matica, int rozmer)
{
Zlomok **povodna;
Zlomok **inverzna;
alokuj(&povodna, rozmer);
alokuj(&inverzna, rozmer);
nacitajPovodnu(povodna,rozmer,matica);
spravJednotkovu(inverzna,rozmer);
if(vypocitajInverznu(povodna, inverzna, rozmer)==1) //aby sa nahodou nedelilo nulou
{
uvolni(povodna,rozmer);
uvolni(inverzna,rozmer);
exit(0);
}
std::cout <<"Inverzna:" <<std::endl;
vypis(inverzna,rozmer);
uvolni(povodna,rozmer);
uvolni(inverzna,rozmer);
}
void alokuj (Zlomok ***matica, int hodnost)
{
try
{
*matica=new Zlomok * [hodnost];
for (int i=0; i<hodnost; ++i)
{
*(*matica+i)=new Zlomok [hodnost];
}
}
catch(std::bad_alloc &ba)
{
std::cout <<ba.what() <<std::endl;
exit(EXIT_FAILURE);
}
}
void nacitajPovodnu(Zlomok **maticaMeni, Zlomok ** maticaNemeni, int hodnost)
{
for (int i=0;i<hodnost;++i)
{
std::cout <<i+1 <<" riadok: ";
for (int j=0;j<hodnost;++j)
{
std::cin >>(*((*(maticaMeni+i))+j));
*((*(maticaNemeni+i))+j)=*((*(maticaMeni+i))+j);
}
}
}
void nacitajPovodnu(Zlomok **maticaMeni, int hodnost, Zlomok *maticaRiadok)
{
int k=0; //posun v riadkovej matici
for (int i=0; i<hodnost; ++i)
{
for (int j=0; j<hodnost; ++j)
{
*((*(maticaMeni+i))+j)=*(maticaRiadok+k);
++k;
}
}
}
void spravJednotkovu(Zlomok **matica, int hodnost)
{
for (int i=0;i<hodnost;++i)
{
for(int j=0;j<hodnost;++j)
{
*((*(matica+i))+j)=(j==i)?Zlomok{1}:Zlomok{0,1};
}
}
}
int vypocitajInverznu(Zlomok ** maticaP, Zlomok ** maticaI, int hodnost)
{
for (int i=0;i<hodnost;++i) //vynulovanie pod
{
int dole=i+1;
while (dole<hodnost)
{
Zlomok k=(-1)*(maticaP[dole][i])/maticaP[i][i];
for (int l=i;l<hodnost;++l)
{
maticaP[dole][l]=maticaP[dole][l]+k*maticaP[i][l]; //pre povodnu
}
for(int l=0; l<hodnost; ++l)
{
maticaI[dole][l]+=k*maticaI[i][l]; //pre inverznu
}
++dole;
}
}
for (int i=1;i<hodnost;++i) //vynulovanie nad
{
int hore=0;
while(hore<i)
{
Zlomok k=(-1)*maticaP[hore][i]/maticaP[i][i];
for (int l=i;l<hodnost;++l) //pre povodnu
{
maticaP[hore][l]=maticaP[hore][l]+k*maticaP[i][l];
}
for(int l=0; l<hodnost; ++l) //pre inverznu
{
maticaI[hore][l]+=k*maticaI[i][l];
}
++hore;
}
}
if (skontroluj(maticaP, hodnost)==1)
{
return 1;
}
for (int i=0;i<hodnost; ++i) //spravenie jednotkovej z povodnej
{
Zlomok k=maticaP[i][i];
for (int j=0;j<hodnost;++j)
{
maticaI[i][j]=maticaI[i][j]/k;
maticaP[i][j]=maticaP[i][j]/k;
}
}
return 0;
}
int skontroluj (Zlomok **matica, int kolko)
{
for(int i=0;i<kolko;++i)
{
if(matica[i][i].getCitatel()==0)
{
std::cout <<"Na hlavnej diagonale v povodnej matici je po uprave nula.\nInverzna neexistuje.";
return 1;
}
}
return 0;
}
void vynasob (Zlomok **maticaP, Zlomok ** maticaI, int kolko)
{
Zlomok ** vynasobena;
alokuj(&vynasobena, kolko);
spravVynulovanu(vynasobena,kolko);
for (int i=0;i<kolko;++i)
{
for (int j=0;j<kolko;++j)
{
for(int l=0;l<kolko;++l)
{
vynasobena[i][j]+=(maticaP[i][l]*maticaI[l][j]);
}
}
}
std::cout <<"Vynasobene" <<std::endl;
vypis(vynasobena,kolko);
uvolni(vynasobena,kolko);
}
void spravVynulovanu (Zlomok ** matica, int hodnost)
{
for (int i=0;i<hodnost;++i)
{
for (int j=0;j<hodnost;++j)
{
*(*(matica+i)+j)=Zlomok{0,1};
}
}
}
void uvolni (Zlomok ** matica, int hodnost)
{
for (int i=0;i<hodnost;++i)
{
delete [] *(matica+i);
}
delete [] matica;
}
void vypis(Zlomok ** matica, int hodnost)
{
for (int i = 0; i < hodnost; ++i)
{
for (int j = 0; j < hodnost; ++j)
{
std::cout <<std::setw(6) <<*(*(matica + i) + j);
}
std::cout <<std::endl;
}
}
| true |
d69063761b21fc0ad027d4681914cf75ae78854d | C++ | Soogyung1106/Algorithm-Study | /백준/삼성 SW 역량 테스트 기출 문제/[15684] 사다리 조작/수경.cpp | UTF-8 | 1,476 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
const int INF = 987654321;
int N, M, H, a, b, answer = INF, visited[34][34];
bool check() {
//col 세로선의 결과 col가 나오는지 체크
for (int col = 1; col <= N; col++) { //세로선 기둥.
int start = col; //출발선
for (int row = 1; row <= H; row++) { //가로선
//해당 row에 길이 있다면
if (visited[row][start]) start++; //다음 세로선으로 이동
else if (visited[row][start - 1]) start--; //이전 세로선으로 이동
}
if (start != col) return false;
}
return true;
}
void search(int here, int cnt) {
//기저조건
if (cnt > 3) return;
if (check()) { //i 세로선의 결과 i가 나오는지 체크
answer = min(answer, cnt);
return;
}
for (int row = here; row <= H; row++) { //가로선
for (int col = 1; col <= N; col++) { //세로선
//가로선을 추가할 수 없는 경우
if (visited[row][col] || visited[row][col - 1] || visited[row][col + 1]) continue;
//가로선 새로 추가.
visited[row][col] = 1; //col 세로선 라인의 row 가로선을 추가.
search(row, cnt + 1);
visited[row][col] = 0;
}
}
}
int main() {
//입력
cin >> N >> M >> H;
for (int i = 0; i < M; i++) {
cin >> a >> b;
visited[a][b] = 1;
}
//탐색
search(1, 0); //(1번 가로선부터 추가, 새로 추가한 가로선의 개수)
//출력
cout << ((answer == INF) ? -1 : answer) << "\n";
return 0;
}
| true |
450646a7896d706ee4e70133fb3223912edf018d | C++ | vitorkaio/Agenda-eletronica | /Files/Email.cpp | UTF-8 | 392 | 3.15625 | 3 | [] | no_license | #include "Email.h"
Email::Email(){
uso = '0';
}
Email::Email(string email, char uso){
setEmail(email);
setUso(uso);
}//Email().
string Email::getEmail(){
return email;
}//getEmail().
void Email::setEmail(string email){
this->email = email;
}//setEmail().
char Email::getUso(){
return uso;
}//getEmail().
void Email::setUso(char uso){
this->uso = uso;
}//setUso(). | true |
57aa2797b9be1ef70b70e2852a3ec75e80a0e886 | C++ | MRSurajKumbhar/DS-Algo | /queueUsingStack2.cpp | UTF-8 | 666 | 3.578125 | 4 | [] | no_license | #include<bits\stdc++.h>
using namespace std;
class Queue
{
stack<int> st;
public:
void push(int x)
{
st.push(x);
}
int pop()
{
if(st.empty())
{
cout<<"Queue is empty"<<endl;
return -1;
}
int x = st.top();
st.pop();
if(st.empty())
{
return x;
}
int item = pop();
st.push(x);
return item;
}
bool empty()
{
if(st.empty())
{
return true;
}
return false;
}
};
int main()
{
Queue qu;
qu.push(1);
qu.push(2);
qu.push(3);
qu.push(4);
qu.push(5);
cout<<qu.pop()<<endl;
qu.push(6);
cout<<qu.pop()<<endl;
cout<<qu.pop()<<endl;
cout<<qu.pop()<<endl;
cout<<qu.pop()<<endl;
cout<<qu.pop()<<endl;
return 0;
} | true |
497a8c94b9ccbcd884cb4cdd13ff8138f8f2f240 | C++ | iEternity/xNet | /xnet/base/Condition.h | UTF-8 | 845 | 2.71875 | 3 | [] | no_license | //
// Created by zhangkuo on 17-9-13.
//
#ifndef XNET_CONDITION_H
#define XNET_CONDITION_H
#include <boost/noncopyable.hpp>
#include "Mutex.h"
#include <pthread.h>
namespace xnet
{
class Condition : boost ::noncopyable
{
public:
explicit Condition(MutexLock& mutex)
: mutex_(mutex)
{
::pthread_cond_init(&pcond_, NULL);
}
~Condition()
{
::pthread_cond_destroy(&pcond_);
}
void wait()
{
MutexLock::UnassignGuard ug(mutex_);
::pthread_cond_wait(&pcond_, mutex_.getPthreadMutex());
}
void waitForSeconds(double seconds);
void notify()
{
::pthread_cond_signal(&pcond_);
}
void notifyAll()
{
::pthread_cond_broadcast(&pcond_);
}
private:
MutexLock mutex_;
pthread_cond_t pcond_;
};
}
#endif //XNET_CONDITION_H
| true |
67bacfdf190716a1a0d7662c6bea59aa9ac824bc | C++ | alir14/SampleNetworkApp | /UDPClient/UDPClient/main.cpp | UTF-8 | 633 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include "WindowUDPClient.h"
#include "LinuxUDPClient.h"
void main(int argc, char* argv[]) //int argc, char *argv[]
{
std::cout << "There are " << argc << " arguments:\n";
// Loop through each argument and print its number and value
for (int count{ 0 }; count < argc; ++count)
std::cout << count << " " << argv[count] << '\n';
if (argv[1] != NULL && argv[2] != NULL) {
std::cout << "Type: " << argv[1] << std::endl;
if (*argv[1] == 'w') {
WindowUDPClient w_udpClient;
w_udpClient.RunClient(argv[2]);
}
else
{
LinuxUDPClient l_udpClient;
l_udpClient.RunClient(argv[2]);
}
}
} | true |
c767256d6954aa1d41198ae643528884c526153b | C++ | TheOpenSpaceProgramArchive/osp | /OSPGL/src/util/types/gradients.cpp | UTF-8 | 694 | 3.125 | 3 | [
"MIT"
] | permissive | #include "gradients.h"
static glm::vec4 interp(glm::vec4 p0, glm::vec4 p1, float t)
{
return glm::vec4();
}
glm::vec4 Gradient::evaluate(float t)
{
if (t < 0.0f || t > 1.0f)
{
abort(); // Invalid values given
}
float prev = 0.0f;
glm::vec4 prev_val = keys[0.0f];
for (auto it = keys.begin(); it != keys.end(); it++)
{
if (t > prev && t <= it->first)
{
// Interpolate between prev and first
// prev is at 0 and it->first is at 1
// so we substract prev and divide by (first - prev)
float subval = (t - prev) / (it->first - prev);
return interp(prev_val, it->second, subval);
}
prev = it->first;
prev_val = it->second;
}
return glm::vec4(0, 0, 0, 0);
} | true |
fc3043da330826e3b77b81befa7971cf25e9b004 | C++ | jbji/Programming-Method-and-Practice---2019-CS | /2020ad-problem-b/main.cpp | UTF-8 | 2,861 | 3.203125 | 3 | [] | no_license | #include <iostream>
#define STONE '*'
#define GRASS '.'
using namespace std;
int areaParalell(char **camp, int n);
int nonParalell(char **camp, int n);
int main() {
int n;
cin >> n;
char * camp[n];
for(int i=0;i<n;i++){
camp[i]= new char[n+1];
cin >> camp[i];
}
int ans = areaParalell(camp, n);
int ans2 = nonParalell(camp, n);
cout << (ans>ans2?ans:ans2) << endl;
return 0;
}
bool pvalid(char **camp, int i1,int j1, int i2, int j2){
int gCnt = 0; //grass
if(camp[i1][j1] == GRASS){
gCnt++;
}
if(camp[i2][j2] == GRASS){
gCnt++;
}
if(camp[i1][j2] == GRASS){
gCnt++;
}
if(camp[i2][j1] == GRASS){
gCnt++;
}
if(camp[i1][j1] == STONE || camp[i2][j2] == STONE ||camp[i1][j2] == STONE ||camp[i2][j1] == STONE){
return false;
}
return (gCnt <=1);
}
bool npvalid(char **camp, int n,int i1,int j1,int i2){
/*
* i1 j1
* j2
*
*
* */
int d = i2-(i1+i2)/2;
int x[4][2] = { {i1,j1} , {i2,j1} ,{(i1+i2)/2, j1-d} ,{(i1+i2)/2, j1+d}};
int gCnt = 0; //grass
for(int i=0;i<4;i++){
if(x[i][1] <0 || x[i][1] >=n){
return false;
}
if(camp[x[i][0]][x[i][1]] == GRASS){
gCnt++;
}
if(camp[x[i][0]][x[i][1]] == STONE){
return false;
}
}
return (gCnt <=1);
}
bool npvalid_1(char **camp, int n,int i1,int j1,int i2,int j2){
int dy = i2-i1;
int dx = j1-j2;
int x[4][2] = { {i1,j1} , {i2,j2} ,{i1+dx,j1+dy} ,{i1+dx+dy,j1+dy-dx}};
int gCnt = 0; //grass
// cout << "checking" << endl;
for(int i=0;i<4;i++){
if(x[i][0] <0 || x[i][0] >=n || x[i][1] <0 || x[i][1] >=n){
return false;
}
if(camp[x[i][0]][x[i][1]] == GRASS){
gCnt++;
}
if(camp[x[i][0]][x[i][1]] == STONE){
return false;
}
}
return (gCnt <=1);
}
int areaParalell(char **camp, int n){
int ans = 0;
for(int i1=0;i1<n;i1++){
for(int j1=0;j1<n;j1++){
for(int i2=i1+1,j2=j1+1;i2<n && j2<n;j2++,i2++){
if(pvalid(camp,i1,j1,i2,j2)){
ans = max(ans,(i2-i1)*(j2-j1));
}
}
}
}
return ans;
}
int nonParalell(char **camp, int n){
int ans = 0;
for(int i1=0;i1<n;i1++){
for(int j1=0;j1<n;j1++){
for(int j2=j1-1;j2>=0;j2--){
for(int i2=i1+1;i2<n;i2++){
// cout << "i1: " << i1 << " j1: " << j1<<endl;
// cout << "i2: " << i2 << " j2: " << j2<<endl;
if(npvalid_1(camp,n,i1,j1,i2,j2)){
ans = max(ans,(i2-i1)*(i2-i1)+(j2-j1)*(j2-j1));
}
}
}
}
}
return ans;
} | true |
3b94e5c4f67a0d9d002a14fe2df3f978ac970378 | C++ | curtkim/c-first | /rxcpp-first/31_multi_subscribe.cpp | UTF-8 | 1,696 | 2.71875 | 3 | [] | no_license | #include <memory>
#include <thread>
#include <rxcpp/rx.hpp>
namespace Rx {
using namespace rxcpp;
using namespace rxcpp::sources;
using namespace rxcpp::operators;
using namespace rxcpp::util;
}
using namespace Rx;
using namespace std;
#include <chrono>
using namespace std::chrono_literals;
int main() {
std::cout << "main thread " << std::this_thread::get_id() << endl;
auto coordination = rxcpp::observe_on_new_thread();
auto values = rxcpp::observable<>::interval(std::chrono::milliseconds(50), coordination)
.take(5)
.publish();
// Subscribe from the beginning
values.subscribe(
[](long v) {
std::cout << "[1] OnNext: " << std::this_thread::get_id() << " " << v << endl;
},
[]() {
printf("[1] OnCompleted ");
std::cout << this_thread::get_id() << endl;
});
// Another subscription from the beginning
values.subscribe(
[](long v) {
std::cout << "[2] OnNext: " << std::this_thread::get_id() << " " << v << endl;
},
[]() {
printf("[2] OnCompleted ");
std::cout << this_thread::get_id() << endl;
});
// Start emitting
values.connect();
// Wait before subscribing
rxcpp::observable<>::timer(std::chrono::milliseconds(75)).subscribe([&](long) {
values.subscribe(
[](long v) {
std::cout << "[3] OnNext: " << std::this_thread::get_id() << " " << v << endl;
},
[]() {
printf("[3] OnCompleted ");
std::cout << this_thread::get_id() << endl;
});
});
// Add blocking subscription to see results
values.as_blocking().subscribe();
std::cout << "end " << this_thread::get_id() << endl;
return 0;
}
| true |
7abd78be465d3ce9e44ed2870fe40ad134ec9d96 | C++ | HongfeiXu/CplusplusPrimer | /ch17/ex17_3/StrVec.h | GB18030 | 2,013 | 3.734375 | 4 | [] | no_license | #pragma once
#include <memory>
#include <string>
#include <initializer_list>
// vector ڴԵļʵ֡
class StrVec {
private:
std::allocator<std::string> alloc; // ԪأԪصĺʹ
std::string *elements;
std::string *first_free;
std::string *cap;
public:
StrVec():
elements(nullptr), first_free(nullptr), cap(nullptr) { }
StrVec(std::initializer_list<std::string> il);
StrVec(const StrVec &s);
StrVec(StrVec &&s) noexcept;
~StrVec();
StrVec& operator= (const StrVec &rhs);
StrVec& operator= (StrVec &&rhs) noexcept;
void push_back(const std::string& s);
void push_back(std::string&& s); // ֵò push_back
size_t size() const { return first_free - elements; }
size_t capacity() const { return cap - elements; }
std::string *begin() { return elements; }
std::string *end() { return first_free; }
void reserve(size_t new_cap);
void resize(size_t new_size);
void resize(size_t new_size, const std::string& s);
private:
// ֤ StrVec һԪصĿռ䡣ûпռԪأchk_n_alloc reallocate ڴʱΪ StrVec ڴ档
void chk_n_alloc();
// ڴ棬һΧеԪ
std::pair<std::string*, std::string*> alloc_n_copy(const std::string *b, const std::string *e);
void free();
void reallocate();
// ǰ StrVec ƶ·ڴУ·ڴɵǰеԪأڴ new_cap Ԫ
void alloc_n_move(size_t new_cap);
};
/*
#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include "StrVec.h"
using namespace std;
int main()
{
StrVec vec;
string s = "some string or another";
vec.push_back(s);
vec.push_back("done");
return 0;
}
push_back(const string&)
push_back(string&&)
밴. . .
*/
| true |
ef23f19defec24c3fb3c75b003dbda956112343d | C++ | Gerold31/Streifenprojektion | /prototype1/src/rotatescancontroller.cpp | UTF-8 | 1,902 | 2.53125 | 3 | [] | no_license | #include "rotatescancontroller.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.h"
#include "configuration.h"
#include "laser.h"
#include "servo.h"
using cv::namedWindow;
#define MIN_ANGLE (-20)
#define MAX_ANGLE (5)
const char WINDOW_DEBUG_CAMERA[] = "Debug: Camera";
RotateScanController::RotateScanController()
{
}
RotateScanController::~RotateScanController()
{
}
void RotateScanController::main()
{
// get device configuration from arguments
updateDevice(Configuration::deviceConfiguration);
// setup hardware
Camera c(Configuration::captureDevice);
Laser::getSingleton()->toggle(false);
//make sure the servo rotates in positive direction to reduce inaccuracies caused by backlash
Servo::getSingleton()->setAngle(MIN_ANGLE-5);
// create debug window for camera if required
if (Configuration::debugCamera) {
namedWindow(WINDOW_DEBUG_CAMERA);
}
// create reference image
cv::Mat reference;
//std::this_thread::sleep_for(std::chrono::milliseconds(1000));
cv::waitKey(2000);
for(int a=MIN_ANGLE; a<=MAX_ANGLE; a++)
{
imageNumber = a;
Configuration::deviceConfiguration.projectorPitch = -a * M_PI/180;
updateDevice(Configuration::deviceConfiguration);
Laser::getSingleton()->toggle(false);
Servo::getSingleton()->setAngle(a);
// wait for servo to be in position
//std::this_thread::sleep_for(std::chrono::milliseconds(100));
cv::waitKey(1000);
c.capture().copyTo(reference);
updateReference(reference);
Laser::getSingleton()->toggle(true);
// wait 1 frame in case the laser was turned on while this frame was captured
c.capture();
cv::Mat img = c.capture();
if(Configuration::debugCamera)
{
cv::imshow(WINDOW_DEBUG_CAMERA, img);
}
processImage(img);
//std::this_thread::sleep_for(std::chrono::milliseconds(400));
cv::waitKey(1);
}
Laser::getSingleton()->toggle(false);
}
| true |
d850050aa75b29d124d80040f11a6b4105a40999 | C++ | abhisingh192/o.s. | /deletingazombie.cpp | UTF-8 | 358 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<cstdio>
using namespace std;
int main()
{
int child_pid = fork();
if(child_pid>0)
{
cout<<"parent will sleep"<<endl;
sleep(2);
}
else
{
cout<<"child is zombie. parent id is "<<getpid()<<endl;
}
if(child_pid!=0)
{
wait(0);
system("ps -lax > 1.txt");
}
return 0;
}
| true |
276b29115abaab3d89198c985d8a32cd56981c83 | C++ | sammhicks/prolog-esp32 | /wam/main/serial-stream.cpp | UTF-8 | 667 | 2.875 | 3 | [
"MIT"
] | permissive | #include "serial-stream.h"
NewLine endl;
Print &operator<<(Print &os, const NewLine &) {
os.println();
return os;
}
Print &operator<<(Print &os, const char *str) {
os.print(str);
return os;
}
Print &operator<<(Print &os, uint8_t n) {
os.print(n, HEX);
return os;
}
Print &operator<<(Print &os, uint16_t n) {
os.print(n, HEX);
return os;
}
Print &operator<<(Print &os, uint32_t n) {
os.print(n, HEX);
return os;
}
Print &operator<<(Print &os, int16_t n) {
os.print(n, DEC);
return os;
}
Print &operator<<(Print &os, int32_t n) {
os.print(n, DEC);
return os;
}
Print &operator<<(Print &os, double n) {
os.print(n);
return os;
}
| true |
7bc43be9c0968d76e6eed245d679c2469fe91c99 | C++ | Bastian-Reul/SmartHome | /JSON_Parser/JSON_Parser/Aktor.h | UTF-8 | 444 | 2.515625 | 3 | [] | no_license | /*
* Aktor.h
*
* Created: 30.04.2019 12:26:22
* Author: Basti
*/
#ifndef __AKTOR_H__
#define __AKTOR_H__
class Aktor
{
//variables
public:
const char *_Topic;
bool _status = false;
int _schaltvorgaenge = 0;
bool _toggle_trigger = false;
int Adresse = 739;
protected:
private:
//functions
public:
Aktor();
~Aktor();
protected:
private:
Aktor( const Aktor &c );
Aktor& operator=( const Aktor &c );
}; //Aktor
#endif //__AKTOR_H__
| true |
d73951f36e32737c132b95172279260e04711b48 | C++ | Guiltybaby/makeprj | /testproject/testcpp/src/time.cpp | UTF-8 | 541 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
#include <test1.h>
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
void Time::AddMin(int m)
{
minutes += m;
hours = minutes / 60;
minutes = minutes % 60;
}
void Time::AddHr(int h)
{
hours += h;
}
Time Time::Sum(const Time t) const
{
Time sum;
sum.minutes += minutes + t.minutes;
sum.hours += hours + t.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
void Time::Show() const
{
printf("hours = %d \n",hours);
printf("minutes = %d \n",minutes);
}
| true |
47f75468a0038b8b9180c5badad36d9179c870a7 | C++ | Akua1919/CS171 | /cs171-assignment5-Katou-Megumi/src/interpolator.h | UTF-8 | 4,427 | 2.890625 | 3 | [] | no_license | #pragma once
#include "volumeData.h"
#include "Eigen/Dense"
//ref https://en.wikipedia.org/wiki/Trilinear_interpolation
class Interpolator
{
public:
virtual volumeData interpolate(Eigen::Vector3f &p, const voxel &voxel) = 0;
};
class NearestNeighbourInterpolator : public Interpolator
{
inline volumeData interpolate(Eigen::Vector3f &p, const voxel &voxel)
{
//Here your NNInterpolator code
volumeData v;
v.position = p;
float l = (p - voxel.c000.position).norm();
v.density = voxel.c000.density;
v.gradient = voxel.c000.gradient;
if ((p - voxel.c001.position).norm() < l)
{
v.density = voxel.c001.density;
v.gradient = voxel.c001.gradient;
l = (p - voxel.c001.position).norm();
}
if ((p - voxel.c010.position).norm() < l)
{
v.density = voxel.c010.density;
v.gradient = voxel.c010.gradient;
l = (p - voxel.c010.position).norm();
}
if ((p - voxel.c100.position).norm() < l)
{
v.density = voxel.c100.density;
v.gradient = voxel.c100.gradient;
l = (p - voxel.c100.position).norm();
}
if ((p - voxel.c011.position).norm() < l)
{
v.density = voxel.c011.density;
v.gradient = voxel.c011.gradient;
l = (p - voxel.c011.position).norm();
}
if ((p - voxel.c110.position).norm() < l)
{
v.density = voxel.c110.density;
v.gradient = voxel.c110.gradient;
l = (p - voxel.c110.position).norm();
}
if ((p - voxel.c101.position).norm() < l)
{
v.density = voxel.c101.density;
v.gradient = voxel.c101.gradient;
l = (p - voxel.c101.position).norm();
}
if ((p - voxel.c111.position).norm() < l)
{
v.density = voxel.c111.density;
v.gradient = voxel.c111.gradient;
l = (p - voxel.c111.position).norm();
}
return v;
};
};
class TrilinearInterpolator : public Interpolator
{
inline volumeData interpolate(Eigen::Vector3f &p, const voxel &voxel)
{
volumeData v;
v.position = p;
//Here your TrilinearInterpolator code
float x0 = voxel.c000.position[0];
float x1 = voxel.c111.position[0];
float y0 = voxel.c000.position[1];
float y1 = voxel.c111.position[1];
float z0 = voxel.c000.position[2];
float z1 = voxel.c111.position[2];
/*
std::cout<<"c0="<<voxel.c000.density<<std::endl;
std::cout<<"c1="<<voxel.c001.density<<std::endl;
std::cout<<"c2="<<voxel.c010.density<<std::endl;
std::cout<<"c3="<<voxel.c011.density<<std::endl;
std::cout<<"c4="<<voxel.c100.density<<std::endl;
std::cout<<"c5="<<voxel.c101.density<<std::endl;
std::cout<<"c6="<<voxel.c110.density<<std::endl;
std::cout<<"c7="<<voxel.c111.density<<std::endl;
*/
float xd = (p[0]-x0)/(x1-x0);
float yd = (p[1]-y0)/(y1-y0);
float zd = (p[2]-z0)/(z1-z0);
/*
std::cout<<"xd="<<xd<<std::endl;
std::cout<<"yd="<<yd<<std::endl;
std::cout<<"zd="<<zd<<std::endl;
*/
float d00 = voxel.c000.density*(1-xd) + voxel.c100.density*xd;
float d01 = voxel.c001.density*(1-xd) + voxel.c101.density*xd;
float d10 = voxel.c010.density*(1-xd) + voxel.c110.density*xd;
float d11 = voxel.c011.density*(1-xd) + voxel.c111.density*xd;
float d0 = d00*(1-yd) + d10*yd;
float d1 = d01*(1-yd) + d11*yd;
float d = d0*(1-zd) + d1*zd;
v.density = d;
Eigen::Vector3f g00 = voxel.c000.gradient*(1-xd) + voxel.c100.gradient*xd;
Eigen::Vector3f g01 = voxel.c001.gradient*(1-xd) + voxel.c101.gradient*xd;
Eigen::Vector3f g10 = voxel.c010.gradient*(1-xd) + voxel.c110.gradient*xd;
Eigen::Vector3f g11 = voxel.c011.gradient*(1-xd) + voxel.c111.gradient*xd;
Eigen::Vector3f g0 = g00*(1-yd) + g10*yd;
Eigen::Vector3f g1 = g01*(1-yd) + g11*yd;
Eigen::Vector3f g = g0*(1-zd) + g1*zd;
v.gradient = g;
//printf("d = %f\n",d);
return v;
};
}; | true |
d2c22a9014dd1d90248f5e1d8988c9df02a3a666 | C++ | ko-ohno/GameComponentSystem | /Project/GameComponentSystem/SourceFiles/GameObjects/Component/ColliderComponent.h | SHIFT_JIS | 1,320 | 2.5625 | 3 | [] | no_license | /*=============================================================================
/*-----------------------------------------------------------------------------
/* [ColliderComponent.h] AIrwCrÃx[XR|[lg
/* AuthorFKousuke,Ohno.
/*-----------------------------------------------------------------------------
/* FAIrwCrAR|[lg̃x[XɂȂNX`
=============================================================================*/
#ifndef COLLIDER_COMPONENT_H_
#define COLLIDER_COMPONENT_H_
/*--- CN[ht@C ---*/
#include "../Component.h"
/*--- \̒` ---*/
/*--- NX̑O錾 ---*/
/*-------------------------------------
/* AIrwCrAR|[lg̃x[XNX
-------------------------------------*/
class ColliderComponent : public Component
{
public:
ColliderComponent(class GameObject* owner, int updateOrder = 100);
~ColliderComponent(void);
virtual TypeID GetComponentType() const override { return TypeID::ColliderComponent; };
private:
protected:
};
#endif //COLLIDER_COMPONENT_H_
/*=============================================================================
/* End of File
=============================================================================*/ | true |
b95e852154c6d0ebbb846ab37875d337aeca8132 | C++ | Orion545/OI-Record | /Grade 10-12/2018 autumn/NOIP/NOIP2018提高组Day1程序包/GD-Senior/answers/GD-0540/money/money.cpp | UTF-8 | 1,929 | 2.5625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
int read()
{
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
int num[25005][105];
bool used[25005][105];
const int N = 105;
int n;
int a[N];
int del[N];
int mx;
void solve()
{
n = read();
for (int i = 1; i <= n; i++)
{
a[i] = read();
mx = std::max(mx, a[i]);
}
std::sort(a + 1, a + n + 1);
for (int i = 1;i <= n; i++)
{
num[a[i]][++num[a[i]][0]] = i;
used[a[i]][i] = 1;
}
for (int i = 1; i <= n; i++)
{
if (del[i])
continue;
int now = i + 1;
for (int k = 1; k * a[i] <= mx; k++)
{
int u = k * a[i];
for (int j = u; j <= mx; j++)
{
if (num[j][0] == 0)
continue;
for (int p = 1; p <= num[j][0]; p++)
{
if (used[j - u][num[j][p]])
continue;
used[j - u][num[j][p]] = 1;
num[j - u][++num[j - u][0]] = num[j][p];
}
}
for (int j = n; j >= 1; j--)
{
if (a[j] < u)
break;
if (del[j])
continue;
if (a[j] == u && j != i)
del[j] = 1;
if (used[a[j] - u][j])
continue;
used[a[j] - u][j] = 1;
num[a[j] - u][++num[a[j] - u][0]] = j;
}
if (num[u][0] > 0)
{
for (int j = 1; j <= num[u][0]; j++)
if (num[u][j] != i)
del[num[u][j]] = 1;
num[u][0] = 0;
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
if (!del[i])
{
// printf("%d\n",a[i]);
ans++;
}
}
printf("%d\n",ans);
}
void init()
{
for (int i = 0; i <= 100; i++)
for (int j = 1; j <= mx; j++)
used[j][i] = 0;
for (int i = 1; i <= mx; i++)
num[i][0] = 0;
for (int i = 1; i <= 100; i++)
del[i] = 0, a[i] = 0;
n = mx = 0;
}
int main()
{
freopen("money.in","r",stdin);
freopen("money.out","w",stdout);
int T = read();
while (T--)
{
init();
solve();
}
}
| true |
4e41400b4459ad1a30d42a20b2446b46041f4083 | C++ | Xpl0itU/qtwitgui-plus | /wiitdb.cpp | UTF-8 | 21,362 | 2.640625 | 3 | [] | no_license | #include "wiitdb.h"
#ifndef Q_OS_MAC
#include "unzip/unzip.h"
#endif
#include "includes.h"
#include <QIODevice>
WiiTDB *wiiTDB;
WiiTDB::WiiTDB( QObject *parent ) : QObject( parent )
{
//grab the language code to use for localized text
localeStr = QLocale::system().name();
if( localeStr.startsWith( "zh" ) )//some sort of chinese
{
if( localeStr == "zh_TW" )//taiwan
localeStr = "ZHTW";
else// make all other chinese use the china version
localeStr = "ZHCH";
}
else // all other languages
{
localeStr.resize( 2 );
localeStr = localeStr.toUpper();
}
//load the default wiitdb.xml
//LoadFile( ":/wiitdb.xml" );
}
WiiTDB::~WiiTDB()
{
if( file.isOpen() )
file.close();
if( buf.isOpen() )
buf.close();
}
//load the wiitdb.xml file
bool WiiTDB::LoadFile( const QString &name )
{
//qDebug() << "WiiTDB::LoadFile" << name;
if( file.isOpen() )
file.close();
if( buf.isOpen() )
buf.close();
QString errorStr;
int errorLine;
int errorColumn;
title = tr( "No WiiTDB available" );
if( name.endsWith( ".xml", Qt::CaseInsensitive ) )
{
//open the file
file.setFileName( name );
if( !file.open(QFile::ReadOnly | QFile::Text ) )
{
emit SendError( tr("WiiTDB Error"), tr("Cannot read file.") );
return false;
}
//point the dom to the file
if( !domDocument.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
{
emit SendError( tr("WiiTDB Error"), tr("Parse error at line %1, column %2:\n%3").arg( errorLine ).arg( errorColumn ).arg( errorStr ) );
return false;
}
}
else if( name.endsWith( ".zip", Qt::CaseInsensitive ) )
{
#ifdef Q_OS_MAC
emit SendError( tr("WiiTDB Error"), tr("Zip files are not supported in the OSx version of this program yet") );
return false;
#else
if( !QFile::exists( name ) )
{
emit SendError( tr("WiiTDB Error"), tr("Cannot find %1.").arg( name ) );
return false;
}
UnZip::ErrorCode ec;
UnZip uz;
//try to open the zip archize
ec = uz.openArchive( name );
if (ec != UnZip::Ok)
{
emit SendError( tr("WiiTDB Error"), QString( "Failed to open archive: " ) + uz.formatError(ec).toLatin1() );
return false;
}
//see if it contains the correct file
if( !uz.contains( "wiitdb.xml" ) )
{
emit SendError( tr("WiiTDB Error"), tr( "wiitdb.xml not found in the archive." ) );
return false;
}
//open the memory oidevice
if( !buf.open( QIODevice::ReadWrite ) )
{
emit SendError( tr("WiiTDB Error"), tr( "Memory error." ) );
return false;
}
//extract that file to our memory buffer
ec = uz.extractFile( "wiitdb.xml", &buf);
if (ec != UnZip::Ok)
{
emit SendError( tr("WiiTDB Error"), QString( "Extraction failed: " ) + uz.formatError(ec).toLatin1() );
uz.closeArchive();
return false;
}
//rewind back to the beginning
buf.seek( 0 );
//point the dom to the buffer
if( !domDocument.setContent( &buf, true, &errorStr, &errorLine, &errorColumn ) )
{
emit SendError( tr("WiiTDB Error"), tr("Parse error at line %1, column %2:\n%3").arg( errorLine ).arg( errorColumn ).arg( errorStr ) );
return false;
}
#endif
}
else
{
qDebug() << name;
emit SendError( tr("WiiTDB Error"), tr("Only .zip and .xml files are supported.") );
return false;
}
//find and check root tag
QDomElement root = domDocument.documentElement();
if( root.tagName() != "datafile" )
{
emit SendError( tr("WiiTDB Error"), tr("The file is missing the \"datafile\" root tag.") );
return false;
}
QDomElement child = root.firstChildElement( "WiiTDB" );
if( child.isNull() || !child.hasAttribute( "version" ) || !child.hasAttribute( "games" ) )
{
emit SendError( tr("WiiTDB Error"), tr("Invalid \"WiiTDB\" tag.") );
return false;
}
bool ok;
xmlGameNum = child.attribute( "games" ).toInt( &ok );
if( !ok )
{
emit SendError( tr("WiiTDB Error"), tr("Invalid attribute in the \"WiiTDB\" tag.") );
return false;
}
title.clear();
ClearGame();
QString ver = child.attribute( "version" );
ver.resize( 8 );
xmlDate = QDate::fromString( ver, "yyyyMMdd");
ver = child.attribute( "version" );
ver.remove( 0, 8 );
xmlTime = QTime::fromString( ver, "hhmmss" );
return true;
}
bool WiiTDB::LoadGameFromID( const QString &id )
{
if( !file.isOpen() && !buf.isOpen() )
return false;
if( id == id_loaded )
return true;
ClearGame();
QDomElement e = GameFromID( id );
if( e.isNull() )
{
if( id.at( 0 ) == QChar( '0' ) || id.at( 0 ) == QChar( '1' ) )//if this game starts with 0 or 1 then it is an autoboot game. try to change it to R or S and see if the game exists
{
QString i = id;
i[ 0 ] = QChar( 'R' );
e = GameFromID( i );
if( e.isNull() )
{
i[ 0 ] = QChar( 'S' );
e = GameFromID( i );
if( e.isNull() )
{
return false;
}
return false;
}
}
return false;
}
id_loaded = id;
title = NameFromGameElement( e );
synopsis = SynopsisFromGameElement( e );
type = TypeFromGameElement( e );
region = RegionFromGameElement( e );
languages = LanguagesFromGameElement( e );
developer = DeveloperFromGameElement( e );
publisher = PublisherFromGameElement( e );
releaseDate = DateFromGameElement( e );
genre = GenreFromGameElement( e );
ratingType = RatingTypeFromGameElement( e );
ratingValue = RatingValueFromGameElement( e );
wifiPlayers = WifiPlayersGameElement( e );
wifiFeatures = WifiFeaturesFromGameElement( e );
inputPlayers = InputPlayersFromGameElement( e );
inputControlers = InputControllersFromGameElement( e );
return true;
}
void WiiTDB::ClearGame()
{
id_loaded.clear();
title.clear();
synopsis.clear();
type.clear();
region.clear();
languages.clear();
developer.clear();
publisher.clear();
releaseDate = QDate();
genre.clear();
ratingType.clear();
ratingValue.clear();
wifiPlayers = 0;
wifiFeatures.clear();
inputPlayers = 0;
inputControlers.clear();
}
//get the "<game>" tag for a give ID
QDomElement WiiTDB::GameFromID( const QString &id )
{
QDomElement root = domDocument.documentElement();
QDomElement child = root.firstChildElement( "game" );
if( child.isNull() )
{
emit SendError( tr("WiiTDB Error"), tr("No \"game\" tag found.") );
return QDomElement();
}
while( !child.isNull() )
{
QDomElement idNode = child.firstChildElement( "id" );
if( !idNode.isNull() )
{
if( idNode.text() == id )
return child;
}
child = child.nextSiblingElement( "game" );
}
return QDomElement();
}
//get a game from an ID
QString WiiTDB::NameFromID( const QString &id )
{
if( !file.isOpen() )
return QString();
QDomElement e = GameFromID( id );
if( e.isNull() )
return QString();
return NameFromGameElement( e );
}
//find shit from the game element
QString WiiTDB::NameFromGameElement( const QDomElement &parent )
{
QDomElement localeElement = parent.firstChildElement( "locale" );
while( !localeElement.isNull() )
{
if( localeElement.hasAttribute( "lang" ) && localeElement.attribute( "lang" ) == localeStr )
{
QDomElement titleElement = localeElement.firstChildElement( "title" );
if( !titleElement.isNull() && !titleElement.text().isEmpty() )
{
return titleElement.text();
}
}
localeElement = localeElement.nextSiblingElement( "locale" );
}
//localized language not found. look for generic one
if( parent.hasAttribute( "name") && !parent.attribute( "name" ).isEmpty() )
return parent.attribute( "name" );
return QString();
}
QString WiiTDB::SynopsisFromGameElement( const QDomElement &parent, const QString &locale )
{
QDomElement localeElement = parent.firstChildElement( "locale" );
QString enSynopsis;
QString loc = locale.isEmpty() ? localeStr : locale; //if no language is given, use the one set in this PC settings
while( !localeElement.isNull() )
{
if( localeElement.hasAttribute( "lang" ) )
{
if( localeElement.attribute( "lang" ) == loc )
{
QDomElement titleElement = localeElement.firstChildElement( "synopsis" );
if( !titleElement.isNull() && !titleElement.text().isEmpty() )
{
return titleElement.text();
}
}
if( localeElement.attribute( "lang" ) == "EN" )
{
QDomElement titleElement = localeElement.firstChildElement( "synopsis" );
if( !titleElement.isNull() && !titleElement.text().isEmpty() )
{
enSynopsis = titleElement.text();
}
}
}
localeElement = localeElement.nextSiblingElement( "locale" );
}
//localized language not found. return the english one
return enSynopsis;
}
QString WiiTDB::TypeFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "type" );
if( !e.isNull() )
ret = e.text();
//as of nov-9-2010, wii games dont have a type string. they have an empty tag
return ret;
}
QString WiiTDB::RegionFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "region" );
if( !e.isNull() )
ret = e.text();
return ret;
}
QString WiiTDB::LanguagesFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "languages" );
if( !e.isNull() )
ret = e.text();
return ret;
}
QString WiiTDB::DeveloperFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "developer" );
if( !e.isNull() )
ret = e.text();
return ret;
}
QString WiiTDB::PublisherFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "publisher" );
if( !e.isNull() )
ret = e.text();
return ret;
}
QDate WiiTDB::DateFromGameElement( const QDomElement &parent )
{
QDate ret;
QString str;
QDomElement e = parent.firstChildElement( "date" );
if( !e.isNull() )
{
if( e.hasAttribute( "year" ) )
str += e.attribute( "year" );
else// no release year, just bail out
return ret;
if( e.hasAttribute( "month" ) )
str += e.attribute( "month" ).rightJustified( 2, '0' );
else//no month. just make it january
str += "01";
if( e.hasAttribute( "day" ) )
str += e.attribute( "day" ).rightJustified( 2, '0' );
else//no day. default to the first of the month
str += "01";
}
ret = QDate::fromString( str, "yyyyMMdd" );
return ret;
}
QString WiiTDB::GenreFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "genre" );
if( !e.isNull() )
ret = e.text();
return ret;
}
QString WiiTDB::RatingTypeFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "rating" );
if( !e.isNull() && e.hasAttribute( "type" ) )
ret = e.attribute( "type" );
return ret;
}
QString WiiTDB::RatingValueFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "rating" );
if( !e.isNull() && e.hasAttribute( "value" ) )
ret = e.attribute( "value" );
return ret;
}
int WiiTDB::WifiPlayersGameElement( const QDomElement &parent )
{
int ret = 0;
bool ok;
QString str;
QDomElement e = parent.firstChildElement( "wi-fi" );
if( !e.isNull() && e.hasAttribute( "players" ) )
{
str = e.attribute( "players" );
ret = str.toInt( &ok, 10 );
if( ok )
return ret;
}
return 0;
}
QString WiiTDB::WifiFeaturesFromGameElement( const QDomElement &parent )
{
QString ret;
QDomElement e = parent.firstChildElement( "wi-fi" );
if( !e.isNull() )
{
QDomElement f = e.firstChildElement( "feature" );
while( 1 )
{
ret += f.text();
f = f.nextSiblingElement( "feature" );
if( !f.isNull() )
ret += ", ";
else
break;
}
}
return ret;
}
int WiiTDB::InputPlayersFromGameElement( const QDomElement &parent )
{
int ret = 0;
bool ok;
QString str;
QDomElement e = parent.firstChildElement( "input" );
if( !e.isNull() && e.hasAttribute( "players" ) )
{
str = e.attribute( "players" );
ret = str.toInt( &ok, 10 );
if( ok )
return ret;
}
return 1;
}
QMap<QString, bool> WiiTDB::InputControllersFromGameElement( const QDomElement &parent )
{
QMap<QString, bool> ret;
QDomElement e = parent.firstChildElement( "input" );
if( !e.isNull() )
{
QDomElement c = e.firstChildElement( "control" );
while( !c.isNull() )
{
bool required = false;
QString type;
if( c.hasAttribute( "type") )
{
type = c.attribute( "type" );
if( c.hasAttribute( "required" ) )
required = c.attribute( "required" ) == "true";
ret.insert( type, required );
}
c = c.nextSiblingElement( "control" );
}
}
return ret;
}
QList< QTreeWidgetItem * >WiiTDB::Search( const QString &id, const QString &name, const QString &players, int playerCmpType, \
const QString &wifiPlayers, int wifiCmpType, const QString &type, const QStringList &accessories, const QStringList &required,\
const QString &ratingType, int ratingCmp, const QString &ratingVal, const QString &synopsisFilter, const QString &synopsisLang )
{
QDomElement root = domDocument.documentElement();
QDomElement child = root.firstChildElement( "game" );
if( child.isNull() )
{
emit SendError( tr("WiiTDB Error"), tr("No \"game\" tag found.") );
return QList< QTreeWidgetItem * >();
}
QList< QTreeWidgetItem * >ret;
//only do these conversions 1 time
QRegularExpression rxTitle( name, QRegularExpression::CaseInsensitiveOption );
QRegularExpression rxID( id, QRegularExpression::CaseInsensitiveOption );
QRegularExpression rxSynopsis( synopsisFilter, QRegularExpression::CaseInsensitiveOption );
bool okPlr = true;
int plr = -1;
if( !players.isEmpty() )
plr = players.toInt( &okPlr );
if( !okPlr )
return ret;
int plrWiFi = -1;
if( !wifiPlayers.isEmpty() )
plrWiFi = wifiPlayers.toInt( &okPlr );
if( !okPlr )
return ret;
while( !child.isNull() )
{
QDomElement c = child;
child = child.nextSiblingElement( "game" );
QDomElement idNode = c.firstChildElement( "id" );
if( idNode.isNull() )
continue;
int curPly = InputPlayersFromGameElement( c );//check the int stuff first as it is quicker and move on to the slower checks
if( !( players.isEmpty() || CheckPlayerRule( curPly, playerCmpType, plr ) ) )
continue;
int curWPly = WifiPlayersGameElement( c );
if( !( wifiPlayers.isEmpty() || CheckPlayerRule( curWPly, wifiCmpType, plrWiFi ) ) )
continue;
QString curType = TypeFromGameElement( c );
if( !( type.isEmpty() || type == curType ) )
continue;
QString curID = idNode.text();
if( !( id.isEmpty() || CheckRegEx( curID, rxID ) ) )
continue;
QString title = NameFromGameElement( c );
if( !( name.isEmpty() || CheckRegEx( title, rxTitle ) ) )
continue;
QMap<QString, bool>acc = InputControllersFromGameElement( c );
if( !CheckAccessories( acc, accessories, required ) )
continue;
QString rType = RatingTypeFromGameElement( c );
QString rVal = RatingValueFromGameElement( c );
if( !( ratingType.isEmpty() || CheckRating( rType, rVal, ratingCmp, ratingType, ratingVal ) ) )
continue;
if( !( synopsisLang.isEmpty() || CheckRegEx( SynopsisFromGameElement( c, synopsisLang ), rxSynopsis ) ) )//the synopsis should probably be the last check. it is a regex check done on the longest string on every game
continue;
QString plyStr = QString( "%1" ).arg( curPly );
QString plyWStr = QString( "%1" ).arg( curWPly );
QString accStr;
QMapIterator<QString, bool> i( acc );//turn all the accessories into a string
while( i.hasNext() )
{
i.next();
accStr += i.key();
if( i.hasNext() )
accStr += ", ";
}
//make a new item and add all the text to it
QTreeWidgetItem *item = new QTreeWidgetItem( QStringList() << curID << title << plyStr << plyWStr );
if( !rType.isEmpty() && !rVal.isEmpty())
item->setText( 4, rType + " : " + rVal );
item->setText( 5, curType );
item->setText( 6, accStr );
ret << item;
}
return ret;
}
bool WiiTDB::CheckRegEx( const QString &text, const QRegularExpression &rx )
{
if( text.isEmpty() )
return false;
if( !rx.isValid() )
return text.contains( rx.pattern(), Qt::CaseInsensitive );
return text.contains(rx.pattern());
}
bool WiiTDB::CheckPlayerRule( int num, int cmpType, int cmpval )
{
switch( cmpType )
{
case 0:
return num < cmpval;
break;
case 1:
return num <= cmpval;
break;
case 2:
return num == cmpval;
break;
case 3:
return num >= cmpval;
break;
case 4:
return num > cmpval;
break;
case 5:
return num != cmpval;
break;
}
//shouldnt happen
return false;
}
bool WiiTDB::CheckAccessories( const QMap<QString, bool> &tags, const QStringList &acc, const QStringList &accReq )
{
//check the supported accessories first
foreach( QString str, acc )
{
if( tags.constFind( str ) == tags.constEnd() )//game doesnt support this accessory
return false;
}
//check the required accessories
foreach( QString str, accReq )
{
QMap<QString, bool>::const_iterator it = tags.constFind( str );
if( it == tags.constEnd() )//game doesnt support this accessory
return false;
if( !it.value() )//accessory is not required to play this game
return false;
}
return true;
}
static int ConvertRatingToIndex( const QString &ratingtext )
{
if( ratingtext == "CERO" )
return 0;
if( ratingtext == "ESRB" )
return 1;
if( ratingtext == "PEGI" )
return 2;
if( ratingtext == "GRB" )
return 3;
return -1;
}
QString WiiTDB::ConvertRating( const QString &fromType, const QString &fromVal, const QString &toType )
{
if( fromType == toType )
{
return fromVal;
}
//set a default return value
QString ret;
if( toType == "CERO" )
ret = "A";
else if( toType == "ESRB" )
ret = "E";
else if( toType == "GRB" )
ret = "ALL";
else ret = "3";
int type = -1;
int desttype = -1;
type = ConvertRatingToIndex( fromType );
desttype = ConvertRatingToIndex( toType );
if( type == -1 || desttype == -1 )
return ret;
/* rating conversion table */
/* the list is ordered to pick the most likely value first: */
/* EC and AO are less likely to be used so they are moved down to only be picked up when converting ESRB to PEGI or CERO */
/* the conversion can never be perfect because ratings can differ between regions for the same game */
char ratingtable[ 12 ][ 4 ][ 5 ] =
{ { { "A" }, { "E" }, { "3" }, { "ALL" } },
{ { "A" }, { "E" }, { "4" }, { "ALL" } },
{ { "A" }, { "E" }, { "6" }, { "ALL" } },
{ { "A" }, { "E" }, { "7" }, { "ALL" } },
{ { "A" }, { "EC" }, { "3" }, { "ALL" } },
{ { "A" }, { "E10+" }, { "7" }, { "ALL" } },
{ { "B" }, { "T" }, { "12" }, { "12" } },
{ { "D" }, { "M" }, { "18" }, { "18" } },
{ { "D" }, { "M" }, { "16" }, { "18" } },
{ { "C" }, { "T" }, { "16" }, { "15" } },
{ { "C" }, { "T" }, { "15" }, { "15" } },
{ { "Z" }, { "AO" }, { "18" }, { "18" } } };
for( int i = 0; i < 12; i++ )
{
if( fromVal == ratingtable[ i ][ type ] )
{
return ratingtable[ i ][ desttype ];
}
}
return ret;
}
bool WiiTDB::CheckRating( const QString &testType, const QString &testVal, int oper, const QString &cmpType, const QString &cmpVal )
{
if( ( testType.isEmpty() || testVal.isEmpty() ) && oper != 2 )
{
return true;
}
QString convVal = ConvertRating( testType, testVal, cmpType );
//test "==" and "!=" here before bothering to do any un-necessary stuff
if( oper == 2 )
{
return convVal == cmpVal;
}
if( oper == 5 )
{
return convVal != cmpVal;
}
QStringList cmpVals;
if( cmpType == "CERO" )
cmpVals << "A" << "B" << "C" << "D" << "Z";
else if( cmpType == "ESRB" )
cmpVals << "EC" << "E" << "E10+" << "T" << "M" << "AO";
else if( cmpType == "PEGI" )
cmpVals << "3" << "4" << "5" << "6" << "7" << "12" << "15" << "16" << "18";
else if( cmpType == "GRB" )
cmpVals << "ALL" << "12" << "15" << "18";
else
return false;
int size = cmpVals.size();
switch( oper )
{
case 0:// <
{
for( int i = 0; i < size; i++ )
{
if( cmpVals.at( i ) == cmpVal )
return false;
if( cmpVals.at( i ) == convVal )
return true;
}
}
break;
case 1:// <=
{
if( convVal == cmpVal )
return true;
for( int i = 0; i < size; i++ )
{
if( cmpVals.at( i ) == cmpVal )
return false;
if( cmpVals.at( i ) == convVal )
return true;
}
}
break;
case 3:// >=
{
if( convVal == cmpVal )
return true;
for( int i = size - 1 ; i >= 0; i-- )
{
if( cmpVals.at( i ) == cmpVal )
return false;
if( cmpVals.at( i ) == convVal )
return true;
}
}
break;
case 4:// >
{
for( int i = size - 1; i >= 0; i-- )
{
if( cmpVals.at( i ) == cmpVal )
return false;
if( cmpVals.at( i ) == convVal )
return true;
}
}
break;
default:
return false;
}
return false;
}
| true |
aa2933e0e7b26698b6abc91d773fbbaa93f9691c | C++ | hleclerc/Stela | /old/src/Stela/Interpreter/PRef.cpp | UTF-8 | 754 | 2.5625 | 3 | [] | no_license | #include "Var.h"
PI64 PRef::cur_date = 0;
struct VRF {
Var var;
int off; ///< offset in bits
};
PRef::~PRef() {
delete refs;
}
void PRef::add_ref_from( const PRef *var ) {
if ( var->refs )
for( const VRF &ref : *var->refs )
add_ref( ref.off, ref.var );
}
void PRef::add_ref( int offset, const Var &var ) {
get_vrf( offset )->var = var;
}
Var PRef::get_ref( int offset ) {
return get_vrf( offset )->var;
}
VRF *PRef::get_vrf( int offset ) {
if ( not refs )
refs = new Vec<VRF>;
for( int i = 0; i < refs->size(); ++i )
if ( refs->operator[]( i ).off == offset )
return &refs->operator[]( i );
VRF *res = refs->push_back();
res->off = offset;
return res;
}
| true |
e24bfa2024573233d2b6f551cc2788fca2eb903d | C++ | hxghhhh/COP3530 | /Turnin/PA3/Miles_Hugh_78686913/main.cpp | UTF-8 | 3,523 | 3.328125 | 3 | [] | no_license | //
// main.cpp
// Assignment_3
//
// Created by Hugh A. Miles on 10/23/15.
// Copyright © 2015 HAM. All rights reserved.
//
#include <ctime>
#include <iostream>
#include <math.h>
#include "minHeap_HAM.h"
//protoTypes///////////////
void bubbleSort(int a[], int n);
int main(int argc, const char * argv[]) {
int numOfJobs;
int numOfMachines;
cout << "Enter number of job(s)" << endl;
cin >> numOfJobs;
cout << "Enter number of machine(s)" << endl;
cin >> numOfMachines;
cout << "Enter Processing Time(s)" << endl;
int jobs[numOfJobs];
for (int i = 0; i < numOfJobs; i++){
cin >> jobs[i];
}
//sort jobs in desceneding order
bubbleSort(jobs, numOfJobs);
arrayHeap* array = new arrayHeap(numOfMachines); //instantiate structs
treeHeap<Machine*> tree = *new ::treeHeap<Machine*>();
//Array Heap
clock_t start = clock();
for (int i = 0; i < numOfMachines; i++){ //create machines
Machine* t = new Machine(numOfJobs); // create new Machine
array->push(t); // push newMachine in Heap
}
for (int i = 0; i < numOfJobs; i++) {
Machine* readyToWork = array->top(); // get top machine
readyToWork->insert(jobs[i]); // add job to it
array->pop(); //pop it off
array->push(readyToWork); // push it back in
}
cout << "Min Heap Finshing Time: " << array->getMax() << endl;
cout << "Schedule:" << endl;
array->print();
clock_t end = clock();
float time = (float) (end-start) / CLOCKS_PER_SEC;
cout << "Time Elapsed: " << time << endl;
cout << endl;
//HeightBiased Leftist Tree
start = clock();
for (int i = 0; i < numOfMachines; i++){ //create machines
Machine* t = new Machine(numOfJobs); // create new Machine
tree.push(t); // push newMachine in Heap
}
for (int i = 0; i < numOfJobs; i++) {
Machine* readyToWork = tree.top(); // get top machine
readyToWork->insert(jobs[i]); // add job to it
tree.pop(); //pop it off
tree.push(readyToWork); // push it back in
}
//get max sum in tree
treeHeap<Machine*> tempTree = *new ::treeHeap<Machine*>();
int sum[numOfMachines];
cout << "Height Biased Leftist Tree Finshing Time: ";
for (int i = 0; i < numOfMachines; i++) {
Machine* readyToWork = tree.top(); // get top machine
tree.pop(); //pop it off
sum[i] = readyToWork->sum; // save sum
tempTree.push(readyToWork); // push it back in
}
//Get max sum in tree
int max = sum[0];
for(int i = 1; i < numOfMachines; i++){
if(sum[i] > max){
max = sum[i];
}
}
cout << max << endl;
//print Machines in tree
cout << "Schedule:" << endl;
for (int i = 0; i < numOfMachines; i++) {
Machine* readyToWork = tempTree.top(); // get top machine
tempTree.pop(); //pop it off
cout << "Machine " << i+1 << ": ";
readyToWork->print();
tree.push(readyToWork); // push it back in
}
end = clock();
time = (float) (end-start) / CLOCKS_PER_SEC;
cout << "Time Elapsed: " << time << endl;
}
void bubbleSort(int a[], int n){
int temp;
for(int i=0;i<n;i++) {
for(int j=0;j<n-i-1;j++){
if(a[j]<a[j+1]){
temp=a[j];
a[j]=a[j+1]; /*Swap have been done here*/
a[j+1]=temp;
}
}
}
}
| true |
82fd6c2fd4dd99f75e9d264e25facb781fa69b17 | C++ | walkerWx/leetcode | /UniquePaths/Solution.cc | UTF-8 | 371 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Solution {
public:
int uniquePaths(int m, int n) {
if (m > n) {
return uniquePaths(n, m);
}
if (m <= 0) {
return 0;
}
long int numPaths = 1;
for (int i = 1; i <=m; ++i) {
numPaths *= (i + n);
numPaths /= i;
}
return numPaths;
}
}
| true |
83ccef9af35fd2ecd027630702d6d373b1af1d15 | C++ | GreatHorizon/ood | /lab7/Composite/Slide/GroupOutlineStyle.h | UTF-8 | 667 | 2.578125 | 3 | [] | no_license | #pragma once
#include <memory>
#include <functional>
#include "IStyle.h"
#include "IStyleEnumerator.h"
#include "IOutlineStyle.h"
typedef std::function<void(std::function<void(IOutlineStyle&)>)> OutlineStyleEnumerator;
class CGroupOutlineStyle : public IOutlineStyle
{
public:
CGroupOutlineStyle(OutlineStyleEnumerator function);
std::optional<bool> IsEnabled() const override;
void Enable(bool enable) override;
std::optional<RGBAColor> GetColor() const override;
void SetColor(RGBAColor color) override;
std::optional<float> GetThickness() const override;
void SetThickness(float thickness) override;
private:
OutlineStyleEnumerator m_enumerator;
};
| true |
d000d9058e907ba44967aae57c85eed0d77a3315 | C++ | jeremyroy/projects | /374_Assembler/assembler.cpp | UTF-8 | 3,978 | 3.09375 | 3 | [] | no_license | /*
* The project in my ELEC 374 course was to make a mini SRC RISC processor.
* For fun I decided to make an assembler for my processor.
*
*********IN PROGRESS*********
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string>
#include <ctype.h>
int lineNum = 1;
using namespace std;
int main(int argc, char *argv[]){
FILE *stream;
char name[64];
char ch;
string firstToken, secondToken, ThirdToken, FourthToken;
int tokenCount = 1; int lineLength = 0;
//const char *table = argv[1];
strncpy(name, argv[1], 64);
strcat(name, ".txt");
stream = fopen(name, "r");
//check that the file had information
if (stream == NULL){
fprintf(stderr,"Could not open %s\n",name);
exit(-1);
}
printf("Starting to assemble %s\n", argv[1]);
while (!feof(stream)){
ch = fgetc(stream);
if (ch = '\n'){
//new instruction
string binOpCode, hexOpCode;
tokenCount = 1;
binOpCode = computeBinOpCode(firstToken, secondToken, thirdToken, fourthToken, tokenCount);
hexOpCode = bin32ToHex(binOpCode);
lineNum ++;
}
else if (ch = '\t' || ch = ','){
tokenCount++;
if (tokenCount > 4){
perror("Invalid Instruction at line %d", lineNum)
exit 1;
}
}
else{
switch(tokenCount){
case 1: firstToken += ch;
case 2: secondToklen += ch;
case 3: thirdToken += ch;
case 4: fourthToken += ch;
}
}
}
printf("\');");
}
string computeOpCode(const string firstToken, const string secondToken, const string thirdToken, const string fourthToken, const int tokenCount){
string opCode;
opCode += computeFirstToken(firtToken);
if (tokenCount >= 2)
opCode += computeSecondToken(firstToken, secondToken);
if (tokenCount >= 3)
opCode += computeThirdToken(firstToken, thirdToken);
if (tokenCount >= 4)
opCode += computeFourthToken(fourthToken);
return opCode;
}
string computeFirstToken(const string firstToken){
string instCode;
switch (firstToken){
case "ld" : instCode = "00000";
case "ldi" : instCode = "00001";
case "st" : instCode = "00010";
case "ldr" : instCode = "00011";
case "str" : instCode = "00100";
case "add" : instCode = "00101";
case "sub" : instCode = "00110";
case "and" : instCode = "00111";
case "or" : instCode = "01000";
case "shr" : instCode = "01001";
case "shl" : instCode = "01010";
case "ror" : instCode = "01011";
case "rol" : instCode = "01100";
case "addi" : instCode = "01101";
case "andi" : instCode = "01110";
case "ori" : instCode = "01111";
case "mul" : instCode = "10000";
case "div" : instCode = "10001";
case "neg" : instCode = "10010";
case "not" : instCode = "10011";
case "brzr" : instCode = "10100"; //Difference in branch instructions comes at end of opCode
case "brnz" : instCode = "10100";
case "brmi" : instCode = "10100";
case "brpl" : instCode = "10100";
case "jr" : instCode = "10101";
case "jal" : instCode = "10110";
case "in" : instCode = "10111";
case "out" : instCode = "11000";
case "mfhi" : instCode = "11001";
case "mflo" : instCode = "11010";
case "nop" : instCode = "11011";
case "halt" : instCode = "11100";
default:
perror("Invalid instruction at line %d", lineNum);
}
return instCode;
}
string computeSecondToken(const string firstToken, const string secondToken){
if (firstToken = "st" || firstToken = "str"){ //could be constant or constant plus rb
}
else{ //could only be ra
return computeReg(secondToken);
}
}
string computeReg(const string regNum){
string reg;
switch(regNum){
case "r0" : reg = "0000";
case "r1" : reg = "0001";
case "r2" : reg = "0010";
case "r3" : reg = "0011";
case "r4" : reg = "0100";
case "r5" : reg = "0101";
case "r6" : reg = "0110";
case "r7" : reg = "0111";
case "r8" : reg = "1000";
case "r9" : reg = "1001";
case "r10" : reg = "1010";
case "r11" : reg = "1011";
case "r12" : reg = "1100";
case "r13" : reg = "1101";
case "r14" : reg = "1110";
case "r15" : reg = "1111";
}
return reg;
}
| true |
edb1d31f31e1a6f0b39183a0a8dd91ff218a4763 | C++ | jbosboom/pushfight-solver | /src/interpolation.hpp | UTF-8 | 781 | 3 | 3 | [] | no_license | /*
* File: interpolation.hpp
* Author: jbosboom
*
* Created on April 28, 2020, 12:41 PM
*/
#ifndef INTERPOLATION_HPP
#define INTERPOLATION_HPP
#include <algorithm>
namespace interp {
template<typename Iterator, typename T>
Iterator upper_bound(Iterator first, Iterator last, const T& needle) {
while (first != last) {
if (needle < *first)
return first;
if (*(last-1) <= needle)
return last;
std::ptrdiff_t idx = ((double)(needle - *first) / (double)(*(last-1) - *first)) * std::distance(first, last);
assert(0 <= idx && idx < std::distance(first, last));
Iterator it = first;
std::advance(it, idx);
if (needle == *it)
return it+1;
if (needle < *it)
last = it;
else
first = it+1;
}
return last;
}
}
#endif /* INTERPOLATION_HPP */
| true |
e48007120322a97812b2cc696f197c1d9942b8df | C++ | sunrinthon/develop | /Weapon.h | UTF-8 | 420 | 2.5625 | 3 | [] | no_license | #pragma once
#include "Entity.h"
#include "Animation.h"
#include "Unit.h"
class Weapon :
public Entity
{
public:
Weapon(WeaponType type);
~Weapon();
void update(float dt);
void attackUpdate();
void changeState(State state);
bool checkAttack(Unit* unit);
Animation* attack;
State state;
WeaponType type;
float attackDelay;
float attackDelayOrigin;
bool isAttacked;
int damage;
float attackRange;
};
| true |
8f5656f341462ecdc610ec7db5ddf6b88ddfe783 | C++ | mouleja/SmileFridge | /Fridge.cpp | UTF-8 | 15,863 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <algorithm>
#include "Fridge.hpp"
#include "Supplier.hpp"
#include "iohelper.hpp"
#define PERPAGE 10 // Number of records to show per page when editing
using std::cout;
using std::endl;
using std::fstream;
using std::istringstream;
Fridge::Fridge(User* user)
{
_user = user;
_supplier = new Supplier();
_items = Items().GetAll();
getInventoryFromCsv(INVFILE);
}
void Fridge::getInventoryFromCsv(string filename)
{
// Note: partially adapted from https://stackoverflow.com/questions/19936483/c-reading-csv-file
std::ifstream inFile(filename);
if (inFile.bad()) // Check for error opening file
{
std::cout << "FATAL Error reading file: " << filename << std::endl;
exit(1);
}
string line, sku, dateYearStr, dateDayStr, quantStr, qooStr;
int dy, dd, quant, qoo;
while (getline(inFile, line)) // Get line from file
{
std::istringstream ss(line); // Split into fields
getline(ss, sku, ',');
getline(ss, quantStr, ',');
getline(ss, qooStr, ',');
getline(ss, dateYearStr, ',');
getline(ss, dateDayStr, ',');
dy = std::stoi(dateYearStr);
dd = std::stoi(dateDayStr);
quant = std::stoi(quantStr);
qoo = std::stoi(qooStr);
ItemInfo *item = _items.at(sku); // This will throw an error if sku not in _items!!
Date ds(dy, dd);
_contents.push_back(new FridgeItem(item, quant, qoo, ds));
}
inFile.close();
}
// Remove some amount(default = 1) from item by sku. Removes item from contents if quantity < 0.
void Fridge::Use(string sku, int amount)
{
FridgeItem* item = GetInfoBySku(sku);
if (item)
{
item->quantity -= amount;
if (item->quantity < 1 && item->quantOnOrder < 1)
{
int index = GetIndexBySku(sku);
_contents.erase(_contents.begin() + index);
cout << "You have run out of that item" << endl;
}
else
{
cout << "You have " << item->quantity << " of " << item->itemInfo->displayName << "(s) left in your fridge" << endl;
}
}
else
{
cout << "That item does not exist in your Fridge" << endl;
}
}
void Fridge::ViewQuantity(string sku)
{
FridgeItem* item = GetInfoBySku(sku);
if (item)
{
cout << "You have " << item->quantity << " of " << item->itemInfo->displayName << "(s) left in your fridge" << endl;
}
else
{
cout << "That item does not exist in your Fridge" << endl;
}
}
// Remove some amount(default = 1) from item by sku. Removes item from contents if quantity < 0.
void Fridge::Update(string sku, int amount)
{
FridgeItem* item = GetInfoBySku(sku);
if (item)
{
item->quantity = amount;
if (item->quantity < 1)
{
int index = GetIndexBySku(sku);
_contents.erase(_contents.begin() + index);
cout << "You have run out of that item" << endl;
//UpdateQuantityInCSV(sku, 0);
}
else
{
cout << "You have " << item->quantity << " of " << item->itemInfo->displayName << "(s) left in your fridge" << endl;
//UpdateQuantityInCSV(sku, item->quantity);
}
updateInventory();
}
else
{
cout << "That item does not exist in your Fridge" << endl;
}
}
void Fridge::UpdateQuantityInCSV(string sku, int amount)
{
//Opening accounts file that contains all user information
fstream fridgeFile(to_string(_user->GetAccount()) + ".csv");
fstream newFridgeFile("temp.csv");
if (!fridgeFile.is_open()) // Check if file exists
{
//if user account file file doesn't exist, then we can't update anything
return;
}
else
{
//Creating variables for searching file
string nextItemLine;
string SKU;
string quantity;
string year;
string day;
string goodFor;
string nextString;
vector<string> row;
//Searching account specific file for a matching SKU
while (!fridgeFile.eof())
{
row.clear();
//Getting each line of csv and adding separated values to vector
getline(fridgeFile, nextItemLine);
istringstream ss(nextItemLine);
while (getline(ss, nextString, ','))
{
row.push_back(nextString);
}
//Storing item information to variables
SKU = row[0];
quantity = row[1];
year = row[2];
day = row[3];
goodFor = row[4];
if (SKU == sku)
{
quantity = to_string(amount);
}
newFridgeFile << SKU << "," << quantity << "," << year << "," << day << "," << goodFor << "\n";
}
}
newFridgeFile.close();
fridgeFile.close();
}
int Fridge::GetIndexBySku(string sku)
{
for (unsigned i = 0; i < _contents.size(); ++i)
{
if (_contents[i]->itemInfo->sku == sku)
{
return i;
}
}
return -1;
}
FridgeItem* Fridge::GetInfoBySku(string sku)
{
for (unsigned i = 0; i < _contents.size(); ++i)
{
if (_contents[i]->itemInfo->sku == sku)
{
return _contents[i];
}
}
return nullptr;
}
// returns all favorites regardless of current stock
vector<ItemInfo*> Fridge::GetFavorites()
{
vector<ItemInfo*> favorites;
map<string, ItemInfo*>::iterator it = _items.begin();
while (it != _items.end())
{
ItemInfo* item = it->second;
if (item->favorite)
{
favorites.push_back(item);
}
++it;
}
return favorites;
}
//Adds an item to the list of contents. Runs the "CreateNewItem" function
//if the item is not in contents already. Needs to be adjusted to track
//items that are already known but not in contents
void Fridge::AddItem(string sku, int quantity, int quantOnOrder) {
//Will return -1 if item was not found
int place = this->GetIndexBySku(sku);
if (place < 0) {
ItemInfo* new_item = GetItemInfoBySku(sku);
if (new_item == nullptr)
{
new_item = Items().CreateNewItem(sku);
}
this->_contents.push_back(new FridgeItem(new_item, quantity, quantOnOrder, GetCurrentDate()));
_items[sku] = new_item;
}
else
{
this->_contents[place]->quantity += quantity;
}
updateInventory();
}
void Fridge::orderLowItems() {
for (std::map<string, ItemInfo*>::iterator it = _items.begin(); it != _items.end(); it++) {
//only add the item to the order list if it has a designated minimum quantity threshold
if (it->second->minQuantity > 0) {
int index = GetIndexBySku(it->first);
//if the fridge is not currently stocked with the item
if (index == -1) {
int orderMultiple = 1;
//ensure amount to be ordered is greater than the designated minimum quantity for the item
while (orderMultiple * it->second->orderQuantity < it->second->minQuantity) orderMultiple++;
//add item to order list
orderList.insert({ it->first, orderMultiple });
/* No need to worry about adding too many items to the orderList if orderLowItems() is called multiple times
before an order is received since the orderList is a map and the appropriate quantity will be overwritten
at the corresponding sku key rather than indexed multiple times as a {key, value} element in the map */
}//end if
//if the fridge has a current quantity for the item and it's below minQuantity
else if ((_contents[index]->quantity+_contents[index]->quantOnOrder) < it->second->minQuantity) {
int orderMultiple = 1;
int currentQuantity = (_contents[index]->quantity + _contents[index]->quantOnOrder) + it->second->orderQuantity;
while (currentQuantity < it->second->minQuantity) {
currentQuantity += it->second->orderQuantity;
orderMultiple++;
}//end while
//add item and quantity to order list
orderList.insert({ it->first, orderMultiple });
}//end else if
}//end outer if
}//end for loop
}//end orderLowItems
void Fridge::updateInventory() {
std::ofstream outFile(INVFILE, std::ios::trunc);
for (FridgeItem* fridgeItem : _contents) {
ItemInfo* item = fridgeItem->itemInfo;
outFile << item->sku << "," << fridgeItem->quantity << "," << fridgeItem->quantOnOrder << ','
<< fridgeItem->dateStocked.Year << "," << fridgeItem->dateStocked.Days << std::endl;
}
outFile.close();
}
void Fridge::printOrderList() {
if (orderList.size() == 0)
{
std::cout << "You are not low on any items at this time." << std::endl;
return;
}
std::cout << "Item name | Order Units | Quantity Ordered" << std::endl << std::endl;
for (std::map<string, int>::iterator it = orderList.begin(); it != orderList.end(); it++) {
ItemInfo* orderItem = _items.at(it->first);
std::cout << orderItem->displayName << " | " << it->second
<< " | " << (orderItem->orderQuantity * it->second) << std::endl;
}
string output = _supplier->PrettyPrintJson(_supplier->GetOrderListJson(orderList));
std::cout << output << std::endl;
}
void Fridge::SubmitOrder()
{
//don't submit an order if the orderList is empty
if (orderList.empty()) return;
_supplier->CreateOrder(_user, orderList);
std::cout << std::endl << "Order placed!" << std::endl;
//loops through order items and finds matching items in fridge contents to update their 'quantOnOrder' field
//or if ordered item is not in fridge contents, it is added with a quantity of 0 and appropriate 'quantOnOrder' value
for (std::map<string, int>::iterator it = orderList.begin(); it != orderList.end(); it++) {
if (GetIndexBySku(it->first) != -1)
GetInfoBySku(it->first)->quantOnOrder = it->second * GetItemInfoBySku(it->first)->orderQuantity;
else
AddItem(it->first, 0, it->second * GetItemInfoBySku(it->first)->orderQuantity);
}
updateInventory();
std::cout << "Current fridge items 'On-Order Quantity' successfully updated" << std::endl << std::endl;
orderList.clear(); // Order placed and added to log
}
void Fridge::ReceiveOrder(string orderJson)
{
vector<FridgeItem*> receivedItems = _supplier->ProcessReceivedOrder(orderJson);
for (FridgeItem* recvdItem : receivedItems) {
FridgeItem* currFridgeItem = GetInfoBySku(recvdItem->itemInfo->sku);
currFridgeItem->quantity += recvdItem->quantity;
currFridgeItem->quantOnOrder -= recvdItem->quantity;
}
updateInventory();
}
// Takes sku string and returns ItemInfo pointer (or nullptr if sku not in items map)
ItemInfo* Fridge::GetItemInfoBySku(string sku)
{
if (_items.find(sku) != _items.end())
{
return _items[sku];
}
else
{
return nullptr;
}
}
string Fridge::stringifyContents() {
string retString = "";
for (FridgeItem* i : _contents)
{
ItemInfo* item = i->itemInfo;
retString += (item->displayName + "| " + item->fullName + "| " + item->sku + "| ");
retString += (GetDateString(i->dateStocked) + "| " + std::to_string(i->quantity) + "| " + std::to_string(i->quantOnOrder));
if (item->favorite) retString += "| Favorite";
retString += '\n';
}
return retString;
}
string Fridge::stringifyFavorites() {
string retString = "";
vector<ItemInfo*> favorites = GetFavorites();
if (favorites.empty()) {
retString += "No items have been favorited.\n";
return retString;
}
for (ItemInfo* item : favorites)
{
retString += ( item->displayName + "| (" + item->sku + ")| " );
FridgeItem* current = GetInfoBySku(item->sku);
if (current != nullptr && current->quantity > 0)
{
retString += std::to_string(current->quantity);
}
else
{
retString += "None";
}
retString += " in the fridge.\n";
}
return retString;
}
// Presents a list of all items (PERPAGE at a time) to select for editing
void Fridge::EditItemMenu()
{
int page = 0; // Page number, items listed in 'pages' of ten items
bool done = false, changes = false;
// Too messy to iterate through map in chunks, using vector of skus instead
vector<string> skus;
// ref: https://stackoverflow.com/questions/110157/
for (auto const& item : _items) skus.push_back(item.first);
//sort the vector so that items are appear alphabetically according to their display name
std::sort(skus.begin(), skus.end(), [&](const string i, const string j) {
return GetItemInfoBySku(i)->displayName < GetItemInfoBySku(j)->displayName;
});
int maxPages = (int)skus.size() / PERPAGE + ((int)skus.size() % PERPAGE > 0 ? 1 : 0);
while (!done)
{
printEmptyLines();
printString("** Edit Item Information **\n\n"
"Choose an item to edit:\n\n"
"0 - Return to Main Menu\n"
"1 - Move Forward One Page\n"
"2 - Move Backward One Page\n"
);
for (int i = 3; i < PERPAGE + 3; ++i)
{
int index = (page * PERPAGE) + i - 3;
if (index >= (int)skus.size()) break;
ItemInfo* current = GetItemInfoBySku(skus[index]);
if (current == nullptr) perror("Invalid sku in EditItemMenu");
else
{
std::cout << i << (i < 10 ? " " : "") << " - " << current->sku << " : " << current->displayName
<< std::endl;
}
}
int choice = getInt(0, PERPAGE + 2, "\nEnter Choice: ");
switch (choice)
{
case 0:
done = true;
break;
case 1:
++page;
if (page >= maxPages) page = maxPages - 1;
break;
case 2:
--page;
if (page < 0) page = 0;
break;
default:
int index = (page * PERPAGE) + choice - 3;
if (!changes) changes = EditItemInfo(skus[index]);
else EditItemInfo(skus[index]); // Once changes is true, don't make it false later
break;
}
}
if (changes) SaveItemsToFile(); // Only rewrite file if an item was actually changed
}
// From EditItemMenu - Edit selected item values (return true if any changes made)
bool Fridge::EditItemInfo(string sku)
{
bool done = false, changes = false;
char yesNo[2] = { 'y', 'n' };
char isFav;
ItemInfo* item = GetItemInfoBySku(sku);
if (item == nullptr) perror("Invalid sku in EditItemInfo");
while (!done)
{
printEmptyLines();
printString("** Edit Item Information **\n\n"
"Choose information to edit:\n\n"
"0 - Done - Return to Items List\n"
"1 - Display (short) name [" + item->displayName + "] :\n"
"2 - Amazon description [" + item->fullName + "] :\n"
"3 - Minimum amount to have on hand (0 to not auto-order) [" + std::to_string(item->minQuantity) + "] :\n"
"4 - Order quantity (number of items in each box) [" + std::to_string(item->orderQuantity) + "] :\n"
"5 - Mark item as favorite? [" + (item->favorite ? "Yes" : "No") + "] :\n"
);
int choice = getInt(0, 5, "\nEnter choice:");
switch (choice)
{
case 0:
done = true;
break;
case 1:
item->displayName = getString("Enter new display name:");
changes = true;
break;
case 2:
item->fullName = getString("Enter new description:");
changes = true;
break;
case 3:
item->minQuantity = getInt(0, 9999, "Enter new minimum amount:");
changes = true;
break;
case 4:
item->orderQuantity = getInt(1, 9999, "Enter new order quantity:");
changes = true;
break;
case 5:
isFav = getChar("Mark item as favorite? (y/n):", yesNo, 2);
item->favorite = (isFav == 'y');
changes = true;
break;
default:
break;
}
}
return changes;
}
// Replace items file with current values
void Fridge::SaveItemsToFile()
{
// NOTE: this can't be done in Items because Items reads values from file in constructor
// which would overwrite the new values we just updated
std::ofstream outfile(ITEMSFILE, std::ios::trunc);
for (auto const& item : _items)
{
outfile << item.second->displayName << ','
<< item.second->fullName << ','
<< item.second->sku << ','
<< item.second->minQuantity << ','
<< item.second->orderQuantity << ','
<< (item.second->favorite ? "true" : "false") << std::endl;
}
outfile.close();
}
//Function to list all current fridge contents.
void Fridge::ListContents(){
cout << "Current fridge inventory:" << endl;
cout << "Item Amount" << endl;
for(unsigned int i = 0; i < this->_contents.size(); i++){
FridgeItem* item = this->_contents[i];
cout << item->itemInfo->displayName << ": " << item->quantity << endl;
}
}
void Fridge::LowStockCallback(){
int lowCount = 0;
for(unsigned int i = 0; i < this->_contents.size(); i++){
FridgeItem* item = this->_contents[i];
if(item->quantity < item->itemInfo->minQuantity){
if(lowCount == 0){
cout << "Warning: You are running low on the following items: " << endl;
}
lowCount++;
cout << item->itemInfo->displayName << ". Only " << item->quantity << " Remaining!" << endl;
}
}
}
| true |
8d744dcabbc1dbda5b68aaa8081e18c050dcf5a1 | C++ | sjbaines/belaCycleCountProfileTest | /cycleCounter.h | UTF-8 | 2,864 | 2.90625 | 3 | [] | no_license | /***** cycleCounter.h *****/
#ifndef CYCLE_COUNTER_H__
#define CYCLE_COUNTER_H__
#include <Bela.h>
#include <utility> // For 'std::pair'
#include <vector>
typedef void (*funcPtr)(void);
// To call any of these, need to have enabled user mode access to Cycle Count (CCNT) register via e.g. a kernel module,
// otherwise an Illegal Instruction error will be generated.
// Simple wrapper to profile the function 'codeToProfile' and return the number of cycles it took.
unsigned int getCycleCountForPrimaryExecution(funcPtr codeToProfile, AuxiliaryTask& auxTask);
// Run code 'numRun' times and return the full set of cycle times as a vector
std::vector<unsigned int> getCycleCountsForPrimaryExecution(unsigned int numRuns, funcPtr codeToProfile, AuxiliaryTask& auxTask);
// Run code 'numRun' times and return the min and max cycle counts
std::pair<unsigned int, unsigned int> getMinMaxCycleCountForPrimaryExecution(unsigned int numRuns, funcPtr codeToProfile, AuxiliaryTask& auxTask);
// AuxTask which executes the function at *profileFuncPtr,
// and stores the number of cycles it took in codeBeingProfiled_cycles
void auxTask_rtCodeProfiler(void* dummy);
// ====================================================================================
// The following code is largely taken from https://stackoverflow.com/q/3247373
inline unsigned int get_cyclecount (void)
{
unsigned int value;
asm volatile ("MRC p15, 0, %0, c9, c13, 0\t\n": "=r"(value)); // Reads CCNT Register into value
return value;
}
// Simple counter init - no reset, no divider
inline void init_cyclecounter()
{
unsigned int value = 17;
// program the performance-counter control-register:
asm volatile ("MCR p15, 0, %0, c9, c12, 0\t\n" :: "r"(value));
// enable all counters:
asm volatile ("MCR p15, 0, %0, c9, c12, 1\t\n" :: "r"(0x8000000f));
// clear overflows:
asm volatile ("MCR p15, 0, %0, c9, c12, 3\t\n" :: "r"(0x8000000f));
}
// do_reset resets counter to zero.
// enable_divider counts every 64 cycles instead of every cycle - to allow longer measurements without overflow
inline void init_perfcounters (bool do_reset = false, bool enable_divider = false)
{
// in general enable all counters (including cycle counter)
unsigned int value = 1;
// peform reset:
if (do_reset)
{
value |= 2; // reset all counters to zero.
value |= 4; // reset cycle counter to zero.
}
if (enable_divider)
value |= 8; // enable "by 64" divider for CCNT.
value |= 16;
// program the performance-counter control-register:
asm volatile ("MCR p15, 0, %0, c9, c12, 0\t\n" :: "r"(value));
// enable all counters:
asm volatile ("MCR p15, 0, %0, c9, c12, 1\t\n" :: "r"(0x8000000f));
// clear overflows:
asm volatile ("MCR p15, 0, %0, c9, c12, 3\t\n" :: "r"(0x8000000f));
}
#endif // CYCLE_COUNTER_H__
| true |
8c48e8c9f8744aebe2f957853f5d78458a7ef8ee | C++ | Divyaansh313/pointer-function | /file_2.cpp | UTF-8 | 791 | 3.375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int *p,*q;
int a=10,b=20;
p=&a;
q=&b;
cout<<"*p+*q :"<<*p+*q<<endl; //pointer value addition//
cout<<"*p**q :"<<*p**q<<endl; //pointer value multiplication//
cout<<"*p-*q :"<<*p-*q<<endl;
/*cout<<"*p/*q"<<*p/*q<<endl;*/
cout<<"*p++ :"<<*p++<<endl;
cout<<"*p-- :"<<*p--<<endl;
cout<<"*q++ :"<<*q++<<endl; //pointer value decrement//
cout<<"*q-- :"<<*q--<<endl; //pointer value decrement//
/*cout<<"p+q :"<<p+q<<endl;*/
/*cout<<"p*q :"<<p*q<<endl;*/
cout<<"p-q :"<<p-q<<endl; //pointer substraction//
/*cout<<"p/q"<<p/q<<endl;*/
cout<<"p++ :"<<p++<<endl; //pointer increment//
cout<<"p-- :"<<p--<<endl;
cout<<"q++ :"<<q++<<endl;
cout<<"q-- :"<<q--<<endl;
}
| true |
a3aefb5d64c519b4311f0ba1022f7a014d9dcab5 | C++ | spencerGallant/TestPrograms | /moveToDirection/moveToDirection.ino | UTF-8 | 1,235 | 3.1875 | 3 | [] | no_license | //Created: Spencer Gallant
//Date last working: August 3rd
//Description: Enter in angle and moves in that direction
//Libraries for Motors
#include <math.h>
#include <SoftwareSerial.h>
#include <PololuQik.h>
PololuQik2s12v10 qik(10, 8, 11); //qik's: (TX, RX. RSET), don't have to have
PololuQik2s12v10 qik1(49, 53, 42);//reset pin is not necessary
float percentSpeed = 75; //base speed (0%-100%)
void setup() {
Serial.begin(115200); //baud rate. Only used for printing in this program so can change
qik.init(); //initalizing qiks
qik1.init();
}
void loop() {
angle(90); //function: angle(degree u want it to go) 0 = forward; counterclockwise going up;
}
double angle(double angle) {
int s = (percentSpeed/100)*127; //changes percent speed no number
double LF = (sin((angle+270+45)*0.0174532925))*s; //left front motor speed
double LB = (sin((angle+180+45)*0.0174532925))*s; //left back
double RB = (sin((angle+90+45)*0.0174532925))*s; //right back
double RF = (sin((angle+45)*0.0174532925))*s; //right front
qik1.setM1Speed(LF); // returns sine of angle; // left front
qik1.setM0Speed(LB); // left back
qik.setM1Speed(RB); //right back ; >0 is forwad
qik.setM0Speed(RF); // right front >0 is forward
}
| true |
da209705813ff9f71d5e5724a7384e4e88faa535 | C++ | bertolinocastro/pfc1_opencv | /face_detection_own_creation/criacao_positivos_cascade.cpp | UTF-8 | 1,349 | 2.84375 | 3 | [] | no_license | #include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <opencv2/opencv.hpp>
using namespace cv;
string const window_name = "Take a pic";
char const diretorio[] = "imagens_camera/";
void imprimeFoto(Mat image, std::vector<int> ¶meters);
int main(int argc, char const *argv[])
{
VideoCapture camera(0);
unsigned int conta_nome=0;
if(!camera.isOpened()){
printf("Failed to open device\n");
return -1;
}
namedWindow(window_name);
Mat frame;
std::vector<int> parameters;
parameters.push_back( CV_IMWRITE_JPEG_QUALITY );
parameters.push_back( 100 );
while(1){
camera >> frame;
if(frame.empty()){
printf("Whitout more frames in Device\n");
return -1;
}
imshow(window_name, frame);
char btn = (char) waitKey(10);
if( 27 == btn ){
printf("Esc pressionado\n");
break;
}
if( ' ' == btn ){
char file_name[50];
sprintf( file_name, "%s%u.jpeg", diretorio, conta_nome );
printf("%s\n",file_name );
if( access( diretorio, F_OK ) ){
printf("Diretorio nao existe\n");
mkdir( diretorio, 0764 );
}
while( !access( file_name, F_OK ) ){
printf("Arquivo já existe\n");
sprintf( file_name, "%s%u.jpeg", diretorio, ++conta_nome );
}
imwrite( file_name, frame, parameters);
}
}
destroyWindow(window_name);
return 0;
}
| true |
d9544da37aee4a55ebdc5b5285ee267dcd92033c | C++ | vladrus13/ITMO | /TranslationsMethods/03/src/main/resources/matlog_labas/ExpressionParser_ideal.h | UTF-8 | 393 | 2.546875 | 3 | [] | no_license | #include <map>
using namespace std;
class ExpressionParser
{
string parsed;
int iterator;
int proofed;
int counter = 0;
bool is_any();
void skip_spaces();
string parse_token();
string parse_and();
string parse_or();
string parse_implication();
string parse(string s);
void add_pair(string s, int h);
void inc_counter();
vector getProofed();
int getCounter();
}
| true |
06002fb176c6453d3c543cbe76cc0ca2292faf67 | C++ | niuliu222/CGAlgorithm | /CGAlgorithm/src/Application.cpp | UTF-8 | 2,209 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "VertexBuffer.h"
#include "IndexBuffer.h"
#include "VertexArray.h"
#include "VertexBufferLayout.h"
#include "Shader.h"
#include "Render.h"
#include "Texture.h"
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cout << "Glew init failed" << std::endl;
}
std::cout << glGetString(GL_VERSION) << std::endl;
/* Loop until the user closes the window */
float positions[] = {
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f
};
/*float positions[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.5f, 0.5f, 0.0f,
-0.5f, 0.5f, 0.0f
};*/
unsigned int index[] = {
0,1,2,
2,3,0
};
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
VertexArray va;
VertexBuffer vbo(positions, sizeof(positions));
IndexBuffer ibo(index, sizeof(index) / sizeof(unsigned int));
VertexBufferLayout layout;
Renderer renderer;
layout.Push<float>(3);
layout.Push<float>(2);
va.AddBuffer(vbo, layout);
Shader shader("res/shaders/Basic.shader");
shader.Bind();
Texture texture("res/textures/texture.png");
texture.Bind();
shader.SetUniform4f("u_Color", 0.5f, 0.7f, 0.1f, 1.0f);
shader.SetUniform1i("u_Texture", 0);
vbo.Unbind();
ibo.Unbind();
va.Unbind();
shader.Unbind();
float r = 0.0f, g = 0.54f, b = 0.79f, delta = 0.01f;
while (!glfwWindowShouldClose(window))
{
renderer.Clear();
shader.Bind();
//shader.SetUniform4f("u_Color", r, g, b, 1.0);
renderer.Draw(va, ibo, shader);
/* Swap front and back buffers */
glfwSwapBuffers(window);
if (r > 1.0f || r < 0.0f)
{
delta *= -1;
}
r += delta;
g += delta;
b += delta;
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
} | true |
d3d9848801b954b821fb31db46e7c40c3cc7edbe | C++ | ternence-li/rive-cpp | /skia/recorder/test/src/extracter.cpp | UTF-8 | 4,416 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "catch.hpp"
#include "extractor.hpp"
TEST_CASE("Test extractor source not found")
{
REQUIRE_THROWS_WITH(new RiveFrameExtractor("missing.riv", "", "", "", 0, 0),
"Failed to open file missing.riv");
}
TEST_CASE("Test extractor no animation")
{
REQUIRE_THROWS_WITH(
new RiveFrameExtractor("./static/no_animation.riv", "", "", "", 0, 0),
"Artboard doesn't contain a default animation.");
}
TEST_CASE("Test extractor no artboard")
{
REQUIRE_THROWS_WITH(
new RiveFrameExtractor("./static/no_artboard.riv", "", "", "", 0, 0),
"File doesn't contain a default artboard.");
}
TEST_CASE("Test extractor odd width")
{
auto rive = new RiveFrameExtractor("./static/51x50.riv", "", "", "", 0, 0);
REQUIRE(rive->width() == 52);
REQUIRE(rive->height() == 50);
}
TEST_CASE("Test extractor odd height")
{
auto rive = new RiveFrameExtractor("./static/50x51.riv", "", "", "", 0, 0);
REQUIRE(rive->width() == 50);
REQUIRE(rive->height() == 52);
}
TEST_CASE("Test extractor width override")
{
auto rive =
new RiveFrameExtractor("./static/50x51.riv", "", "", "", 100, 0);
REQUIRE(rive->width() == 100);
REQUIRE(rive->height() == 52);
}
TEST_CASE("Test extractor height override")
{
auto rive =
new RiveFrameExtractor("./static/50x51.riv", "", "", "", 0, 100);
REQUIRE(rive->width() == 50);
REQUIRE(rive->height() == 100);
}
TEST_CASE("Test small extent target (width)")
{
auto rive =
new RiveFrameExtractor("./static/50x51.riv", "", "", "", 50, 100, 720);
REQUIRE(rive->width() == 720);
REQUIRE(rive->height() == 1440);
}
TEST_CASE("Test small extent target maxed (width)")
{
auto rive = new RiveFrameExtractor(
"./static/50x51.riv", "", "", "", 50, 100, 720, 1080, 1080);
REQUIRE(rive->width() == 540);
REQUIRE(rive->height() == 1080);
}
TEST_CASE("Test small extent target (height)")
{
auto rive =
new RiveFrameExtractor("./static/50x51.riv", "", "", "", 100, 50, 720);
REQUIRE(rive->height() == 720);
REQUIRE(rive->width() == 1440);
}
TEST_CASE("Test small extent target maxed (height)")
{
auto rive = new RiveFrameExtractor(
"./static/50x51.riv", "", "", "", 100, 50, 720, 1080, 1080);
REQUIRE(rive->height() == 540);
REQUIRE(rive->width() == 1080);
}
TEST_CASE("Test 1s_oneShot min 10s")
{
auto rive = new RiveFrameExtractor(
"./static/animations.riv", "", "1s_oneShot", "", 0, 0, 0, 0, 0, 10);
REQUIRE(rive->totalFrames() == 600);
}
TEST_CASE("Test 2s_loop min 5s")
{
auto rive = new RiveFrameExtractor(
"./static/animations.riv", "", "2s_loop", "", 0, 0, 0, 0, 0, 5);
REQUIRE(rive->totalFrames() == 360);
}
TEST_CASE("Test 2s_loop min 5s max 5s")
{
// give it something dumb, it'll do something dumb.
auto rive = new RiveFrameExtractor(
"./static/animations.riv", "", "2s_loop", "", 0, 0, 0, 0, 0, 5, 5);
REQUIRE(rive->totalFrames() == 300);
}
TEST_CASE("Test 2s_pingpong min 5s")
{
auto rive = new RiveFrameExtractor(
"./static/animations.riv", "", "2s_pingpong", "", 0, 0, 0, 0, 0, 5);
REQUIRE(rive->totalFrames() == 480);
}
TEST_CASE("Test 100s_oneshot animation min duration 10s")
{
auto rive = new RiveFrameExtractor("./static/animations.riv",
"",
"100s_oneShot",
"",
0,
0,
0,
0,
0,
0,
10);
REQUIRE(rive->totalFrames() == 600);
}
TEST_CASE("Test 100s_loop animation min duration 10s")
{
auto rive = new RiveFrameExtractor(
"./static/animations.riv", "", "100s_loop", "", 0, 0, 0, 0, 0, 0, 10);
REQUIRE(rive->totalFrames() == 600);
}
TEST_CASE("Test 100s_pingpong animation min duration 10s")
{
auto rive = new RiveFrameExtractor("./static/animations.riv",
"",
"100s_pingpong",
"",
0,
0,
0,
0,
0,
0,
10);
REQUIRE(rive->totalFrames() == 600);
}
| true |
7136c26a13e8b869c6a078e8504a58becc366a57 | C++ | IrinaZagaynova/ood-labs | /lab8/state/state/GumballMachine.h | UTF-8 | 1,629 | 2.90625 | 3 | [] | no_license | #pragma once
#include "IGumballMachine.h"
#include "SoldState.h"
#include "SoldOutState.h"
#include "NoQuarterState.h"
#include "HasQuarterState.h"
#include <string>
#include <boost/format.hpp>
class CGumballMachine : private IGumballMachine
{
public:
CGumballMachine(unsigned numBalls)
: m_soldState(*this)
, m_soldOutState(*this)
, m_noQuarterState(*this)
, m_hasQuarterState(*this)
, m_state(&m_soldOutState)
, m_count(numBalls)
{
if (m_count > 0)
{
m_state = &m_noQuarterState;
}
}
void EjectQuarter()
{
m_state->EjectQuarter();
}
void InsertQuarter()
{
m_state->InsertQuarter();
}
void TurnCrank()
{
m_state->TurnCrank();
m_state->Dispense();
}
std::string ToString()const
{
auto fmt = boost::format(R"(
Mighty Gumball, Inc.
C++-enabled Standing Gumball Model #2016 (with state)
Inventory: %1% gumball%2%
Machine is %3%
)");
return (fmt % m_count % (m_count != 1 ? "s" : "") % m_state->ToString()).str();
}
private:
unsigned GetBallCount() const override
{
return m_count;
}
virtual void ReleaseBall() override
{
if (m_count != 0)
{
std::cout << "A gumball comes rolling out the slot...\n";
--m_count;
}
}
void SetSoldOutState() override
{
m_state = &m_soldOutState;
}
void SetNoQuarterState() override
{
m_state = &m_noQuarterState;
}
void SetSoldState() override
{
m_state = &m_soldState;
}
void SetHasQuarterState() override
{
m_state = &m_hasQuarterState;
}
private:
unsigned m_count = 0;
CSoldState m_soldState;
CSoldOutState m_soldOutState;
CNoQuarterState m_noQuarterState;
CHasQuarterState m_hasQuarterState;
IState* m_state;
}; | true |
1d2122d7e541806c31c4ae35d58ea0373bf6ca2f | C++ | elgips/HeteroSoil | /space.hpp | UTF-8 | 1,478 | 3.046875 | 3 | [] | no_license | /*
* space.hpp
*
* Created on: 3 Nov 2021
* Author: zvias
*/
#ifndef SRC_SPACE_HPP_
#define SRC_SPACE_HPP_
#include <iostream>
#include "point3D.h"
class space{
public:
double xd,xu,yd,yu,zd,zu;
friend std::ostream& operator<< (std::ostream& out, const space& s);
space(){
xd=-1;
xu=-1;
yd=-1;
yu=-1;
zd=-1;
zu=-1;
}
space(double _xd,double _xu,double _yd,double _yu,double _zd,double _zu){
this->xd=_xd;
this->xu=_xu;
this->yd=_yd;
this->yu=_yu;
this->zd=_zd;
this->zu=_zu;
}
static space* newSpace(){
space* temp=new space;
return temp;
}
void operator =(const space &_s){
this->xd=_s.xd;
this->xu=_s.xu;
this->yd=_s.yd;
this->yu=_s.yu;
this->zd=_s.zd;
this->zu=_s.zu;
}
void set(double _xd,double _xu,double _yd,double _yu,double _zd,double _zu){
this->xd=_xd;
this->xu=_xu;
this->yd=_yd;
this->yu=_yu;
this->zd=_zd;
this->zu=_zu;
}
bool PointInSpace(const point3D& _p){
bool x=(_p.x>this->xd)&&(_p.x<this->xu)&&(_p.y>this->yd)&&(_p.y<this->yu)&&(_p.z>this->zd)&&(_p.z<this->zu);
return x;
}
// }
// bool operator<(const point3D& P){
// bool x=P.x<this.xd&&P.y<this.yd&&P.z<this.zd;
// return x;
// }
};
ostream& operator<<(ostream& os, const space& s)
{
os << "(xd,xu)=("<<s.xd<< ","<<s.xu<< ");(yd,yu)=("<<s.yd<< ","<<s.yu<< ");(zd,zu)=("<<s.zd<< ","<<s.zu<<");" ;
return os;
}
#endif /* SRC_SPACE_HPP_ */
| true |
763b37831d8c2bd6b2a649025d5f79eea386b44a | C++ | Svengali/cblib | /Frame3.cpp | UTF-8 | 1,911 | 2.96875 | 3 | [
"Zlib"
] | permissive | #include "Base.h"
#include "Frame3.h"
#include "Vec3U.h"
START_CB
//////////////////////////////////////////
// NOTEZ : IMPORTANT WARNING
// the order of initialization of static class variables is
// undefined !!
// that means you CANNOT use things like Vec3::zero to initialize here !!
const Frame3 Frame3::identity(Frame3::eIdentity);
const Frame3 Frame3::zero(Frame3::eZero);
//--------------------------------------------------------------------------------
/*static*/ bool Frame3::Equals(const Frame3 &a,const Frame3 &b,const float tolerance /*= EPSILON*/)
{
return Mat3::Equals( a.GetMatrix(), b.GetMatrix(), tolerance) &&
Vec3::Equals( a.GetTranslation(), b.GetTranslation(), tolerance );
}
//--------------------------------------------------------------------------------
bool Frame3::IsValid() const
{
ASSERT( m_mat.IsValid() && m_t.IsValid() );
return true;
}
bool Frame3::IsIdentity(const float tolerance /*= EPSILON*/) const
{
return ( m_mat.IsIdentity(tolerance) && Vec3::Equals(m_t,Vec3::zero,tolerance) );
}
//--------------------------------------------------------------------------------
void Frame3::SetAverage(const Frame3 &v1,const Frame3 &v2)
{
ASSERT( v1.IsValid() && v2.IsValid() );
m_mat.SetAverage(v1.GetMatrix(),v2.GetMatrix());
m_t = MakeAverage(v1.m_t,v2.m_t);
}
void Frame3::SetLerp(const Frame3 &v1,const Frame3 &v2,const float t)
{
ASSERT( v1.IsValid() && v2.IsValid() && fisvalid(t) );
m_mat.SetLerp(v1.GetMatrix(),v2.GetMatrix(),t);
m_t = MakeLerp(v1.m_t,v2.m_t,t);
}
//-------------------------------------------------------------------
#pragma warning(disable : 4505) // unreferenced static removed
static void Frame3Test()
{
Frame3 xf(Frame3::eIdentity);
Vec3 v = xf.GetMatrix().GetRowX();
xf.MutableMatrix().SetRowY(v);
xf.MutableMatrix().SetRowZ(0,1,2);
}
//-------------------------------------------------------------------
END_CB
| true |
8dd2d0b1951b483205ef3dfe97c2ae228020c4f4 | C++ | StevenDunn/CodeEval | /GuessNum/cpp/gn.cpp | UTF-8 | 1,702 | 3.484375 | 3 | [] | no_license | // guess the number cpp soln for code eval by steven a dunn
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::ifstream;
using std::istringstream;
using std::string;
using std::vector;
vector<string> parse(string);
void guess(int*, int*, string);
int get_midpoint(int, int);
int main (int argc, char* const argv[])
{
ifstream input_file(argv[1]);
string line;
if (input_file)
{
while (getline(input_file, line))
{
vector<string> tokens = parse(line);
int lower_bound = 0;
int upper_bound = atoi(tokens[0].c_str());
for (int guess_index = 1; guess_index < tokens.size(); ++guess_index)
guess(&lower_bound, &upper_bound, tokens[guess_index]);
cout << upper_bound << endl;
}
input_file.close();
}
return 0;
}
vector<string> parse(string line)
{
vector<string> tokens;
istringstream iss(line);
string token;
while (getline(iss, token, ' '))
tokens.push_back(token);
return tokens;
}
void guess(int* lower_bound, int* upper_bound, string guess_update)
{
int midpoint = get_midpoint(*lower_bound, *upper_bound);
if (guess_update == "Lower")
*upper_bound = midpoint - 1;
else if (guess_update == "Higher")
*lower_bound = midpoint + 1;
else
*upper_bound = midpoint;
}
int get_midpoint(int lower_bound, int upper_bound)
{
int midpoint = (upper_bound - lower_bound);
if (midpoint % 2 == 0)
midpoint /= 2;
else
midpoint = (midpoint + 1)/2;
return lower_bound + midpoint;
} | true |
8598cebf12f8d262693514feeabee6703fb15ad2 | C++ | sumant10/LeetCode | /Sliding Window/862.Shortest-Subarray-with-Sum-at-Least-K/862.Shortest_Subarray_with_Sum_at_Least_K.cpp | UTF-8 | 684 | 2.75 | 3 | [] | no_license | class Solution {
public:
int shortestSubarray(vector<int>& A, int K) {
vector<int> B(A.size()+1);
B[0]=A[0];
for(int i=1;i<A.size();i++){
B[i]=B[i-1]+A[i];
}
deque<int> d;
int res = INT_MAX;
for(int i=0;i<B.size();i++){
if(B[i]>=K)
res = min(res, i+1);
while(!d.empty() && B[i] <= B[d.back()]){
d.pop_back();
}
while(!d.empty() && B[i] - B[d.front()]>=K){
res = min(res,i-d.front());
d.pop_front();
}
d.push_back(i);
}
return res==INT_MAX ? -1 : res;
}
};
| true |
2b84bbf454eeed1ea0a458b77c53c46fc3be5dc0 | C++ | AubinCheD/IDM_TP3 | /Random/q2.cpp | UTF-8 | 1,628 | 3.046875 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <thread>
#include <iostream>
#include <fstream>
#include "CLHEP/Random/MTwistEngine.h"
void createStatusFile(int size){
CLHEP::MTwistEngine * mt = new CLHEP::MTwistEngine();
double randomNumber;
for(int i = 1; i <= size; i++)
{
std::stringstream ss;
ss << "status" << i << ".txt";
const char *s = (ss.str()).c_str();
mt->saveStatus(s);
//std::cout << s << " : " << std::endl;
for(int j=0;j<1000000000;++j){
randomNumber = mt->flat();
//std::cout << "Number :" << randomNumber << "; ";
}
//std::cout << std::endl<<std::endl;
}
delete mt;
}
void restoreStatusFile(std::string fileName, int size){
CLHEP::MTwistEngine * mt = new CLHEP::MTwistEngine();
double randomNumber;
std::stringstream ss;
ss << "tirage_" << fileName;
std::ofstream file;
file.open (ss.str());
//std::cout<<"Create : " << ss.str() << std::endl;
mt->restoreStatus(fileName.c_str());
for(int i=0;i<10;++i){
randomNumber = mt->flat();
file << "Number :" << randomNumber << std::endl;
}
file.close();
delete mt;
}
int main ()
{
int size = 10;
createStatusFile(size);
std::vector<std::thread *> threads(size);
for(int i=0;i<size;++i){
std::stringstream ss;
ss << "status" << i+1 << ".txt";
std::string fileName = ss.str();
threads[i] = new std::thread(restoreStatusFile, fileName, size);
}
for(int i=0;i<size;++i){
threads[i]->join();
}
return 0;
}
| true |
0acb8c424286e9ba587b17a0adc9f499e9bce669 | C++ | ajmir-github/Cpp_history | /Basics/10-multi-files.cpp | UTF-8 | 750 | 3.4375 | 3 | [] | no_license | // -------------------------------------------------------
// filename = math_funs.cpp
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
// -------------------------------------------------------
// filename = math_funs.h
// if not defined if for avoid dublication of this module
// have the default function argument here
#ifndef MATH_FUNS
#define MATH_FUNS
int add(int a, int b = 1);
double add(double a, double b = 0.1);
#endif
// -------------------------------------------------------
// filename = source.cpp
#include <iostream>
#include "math_funs.h";
using namespace std;
int main() {
int sNum = add(1, 2);
cout << sNum << endl;
double cNum = add(2.2222, 3.333);
cout << cNum << endl;
} | true |
401dbf7f2d5f99be9253d8dcc5241dcd02ec92a2 | C++ | v4if/yarpc | /test/asio_timer_test/asio_timer_test.cpp | UTF-8 | 1,814 | 3.40625 | 3 | [] | no_license | /**
Boost::asio io_service 实现分析 io_service的作用 io_servie 实现了一个任务队列,这里的任务就是void(void)的函数。
Io_servie最常用的两个接口是post和run,post向任务队列中投递任务,run是执行队列中的任务,直到全部执行完毕,并且run可以被N个线程调用。
*/
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <unistd.h>
#include <ctime>
#include <ratio>
#include <chrono>
void timenow(std::string&& desc) {
using namespace std::chrono;
duration<int,std::ratio<60*60*24> > one_day (1);
system_clock::time_point now = system_clock::now();
time_t tt;
tt = system_clock::to_time_t ( now );
std::cout << desc << " : " << ctime(&tt);
}
void handler1(const boost::system::error_code &ec)
{
timenow(std::string{"handler1"});
std::cout << "handler1 thread id : " << boost::this_thread::get_id() << std::endl;
}
void handler2(const boost::system::error_code &ec)
{
timenow(std::string{"handler2"});
// sleep(3);
std::cout << "handler2 thread id : " << boost::this_thread::get_id() << std::endl;
}
boost::asio::io_service io_service;
void run()
{
io_service.run();
}
int main()
{
boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(2));
timer1.async_wait(handler1);
boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(2));
timer2.async_wait(handler2);
timenow(std::string{"run"});
// 多个线程对同一个资源对象 std::cout 进行操作,会出现串流,需要加同步
boost::thread thread1(run);
boost::thread thread2(run);
thread1.join();
thread2.join();
timenow(std::string{"done"});
}
| true |
fb79556fa98a9a8f1eaf3e715cc20b68c3a107bb | C++ | proxycase/Pulse-Sensor-Leonardo-to-SamplerBox | /MIDI.ino | UTF-8 | 1,419 | 2.71875 | 3 | [
"MIT"
] | permissive | //int[] notesArray;
//// could have a velocity array here if I wanted...
//
//void midiSetup() {
// notesArray = new int[2];
// for (int i = 0; i < notesArray.length; i++) {
// notesArray[i] = (60 + i); // Starts MIDI channel assignment from note 60
// }
//}
void noteOn(byte channel, byte pitch, byte velocity) {
midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
MidiUSB.sendMIDI(noteOn);
}
void noteOff(byte channel, byte pitch, byte velocity) {
midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
MidiUSB.sendMIDI(noteOff);
}
//void controlChange(byte channel, byte control, byte value) {
// midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
// MidiUSB.sendMIDI(event);
//}
void midiUpdate() {
Serial.println("Sending note on");
noteOn(0, 48, 64); // Channel 0, middle C, normal velocity
MidiUSB.flush();
delay(500);
Serial.println("Sending note off");
noteOff(0, 48, 64); // Channel 0, middle C, normal velocity
MidiUSB.flush();
delay(1500);
// controlChange(0, 10, 65); // Set the value of controller 10 on channel 0 to 65
}
// These will be heartbeats regardless
void sendBeatOn() {
midiEventPacket_t noteOn = {0x09, 0x90 | (byte) 0, (byte) 60, (byte) 64};
MidiUSB.sendMIDI(noteOn);
}
void sendBeatOff() {
midiEventPacket_t noteOff = {0x08, 0x80 | (byte) 0, (byte) 60, (byte) 64};
MidiUSB.sendMIDI(noteOff);
}
| true |
d2a9297573daff5124b129f96bd3348706565266 | C++ | adityanjr/code-DS-ALGO | /CodeForces/Complete/400-499/467A-GeorgeAndAccomodation.cpp | UTF-8 | 237 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <cstdio>
int main(){
int n; scanf("%d\n", &n);
int output(0);
while(n--){
int p, q; scanf("%d %d\n", &p, &q);
if(q - p >= 2){++output;}
}
printf("%d\n", output);
return 0;
}
| true |
f162147ad2e0ab784b4a99b58d50a347729e341e | C++ | andrew2015/ooxmlpp | /Libooxml/trunk/Libooxml/ST_Guid.cpp | UTF-8 | 1,144 | 2.546875 | 3 | [] | no_license | #include "core.h"
#include "shared-commonSimpleTypes.h"
#include <regex>
using namespace officeDocument::sharedTypes;
bool ST_Guid::checkpattern(std::wstring input) {
std::wregex rx(L"\\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\\}");
return std::regex_match(input,rx);
}
ST_Guid::ST_Guid() {
guid = L"{00000000-0000-0000-0000-000000000000}";
}
ST_Guid::ST_Guid(ST_Guid &b) {
if (checkpattern(b))
guid = b.guid;
else
guid = L"{00000000-0000-0000-0000-000000000000}";
}
ST_Guid::ST_Guid(std::wstring b) {
if (checkpattern(b))
guid = b;
else
guid = L"{00000000-0000-0000-0000-000000000000}";
}
ST_Guid& ST_Guid::operator =(const ST_Guid& b) {
if (checkpattern(b))
guid = b.guid;
else
guid = L"{00000000-0000-0000-0000-000000000000}";
return *this;
}
ST_Guid& ST_Guid::operator =(std::wstring b) {
if (checkpattern(b))
guid = b;
else
guid = L"{00000000-0000-0000-0000-000000000000}";
return *this;
}
ST_Guid::operator const wchar_t*() const {
return guid.c_str();
}
ST_Guid::operator std::wstring() const {
return guid;
}
ST_Guid::~ST_Guid() {
} | true |
43c1e9b8039dc41f9f402f6a8a8ca55b507926c0 | C++ | vibgyor98/dsalgocp | /Tree/Binary Search Tree/inst_Build.cpp | UTF-8 | 1,278 | 3.484375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node *left;
node *right;
node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
//modified BFS for Vertical way of Output
void bfs(node* root) {
queue<node*>q;
q.push(root);
q.push(NULL);
while(!q.empty()) {
node* f = q.front();
if(f==NULL) {
cout<<endl;
q.pop();
if(!q.empty()) {
q.push(NULL);
}
} else {
cout<<f->data<<" ";
q.pop();
if(f->left) {
q.push(f->left);
}
if(f -> right) {
q.push(f -> right);
}
}
}
return;
}
void inorder(node* root) {
if(root==NULL) {
return;
}
inorder(root->left);
cout<<root->data<<" , ";
inorder(root->right);
}
node* insertInBst(node* root, int data) {
if(root==NULL) {
return new node(data);
}
if(data <= root->data) {
root->left = insertInBst(root->left,data);
} else {
root->right = insertInBst(root->right,data);
}
return root;
}
node* build() {
int d;
cin>>d;
node* root = NULL;
while(d!=-1) {
root = insertInBst(root, d);
cin>>d;
}
return root;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
node* root = build();
inorder(root);
cout<<"\n\n";
bfs(root);
return 0;
} | true |
c3143090aea2abf9d875a41dfe647e8a4c5a00c8 | C++ | mpoullet/NumCSE | /CppTutorial/lambdatransform.cpp | UTF-8 | 1,403 | 3.265625 | 3 | [] | no_license | /***********************************************************************
* *
* Demo code *
* (Prof. Dr. R. Hiptmair) *
* Author: R.H. *
* Date: May 2018 *
* (C) Seminar for Applied Mathematics, ETH Zurich *
* This code can be freely used for non-commercial purposes as long *
* as this header is left intact. *
***********************************************************************/
// Header for basic IO
#include <iostream>
// Provides random acccess container class
#include <vector>
// Provides algorithms operating on generic containers
#include <algorithm>
using namespace std;
int main() {
// initialize a vector from an initializer list
std::vector<double> v({1.2,2.3,3.4,4.5,5.6,6.7,7.8});
// A vector of the same length
std::vector<double> w(v.size());
// Do cumulative summation of v and store result in w
double sum = 0;
std::transform(v.begin(),v.end(),w.begin(),
[&sum] (double x) { sum += x; return sum;});
cout << "sum = " << sum << ", w = [ ";
for(auto x: w) cout << x << ' '; cout << ']' << endl;
return(0);
}
| true |
233d3717278457b261f14c82fdbf82b1beddcce6 | C++ | abrennec/sose20_cc2 | /05_interact_mem/code/02_screen_grab_img_balls_solution/src/cgObjectManager.h | UTF-8 | 720 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
// Any computer generated objects (CG objects) generation and management
// should be executed in this class. This includes the generation and
// management of the Balls objects and any additional cg object that
// might be added.
#include "Ball.h"
class CGObjectManager {
public:
enum ballType {
RGB_COL_BALLS,
RANDOM_COL_BALLS
};
CGObjectManager();
CGObjectManager(ballType type);
~CGObjectManager();
//void setup();
void update();
void draw();
void keyPressedEvent(int key);
private:
void setupRGBColorBalls();
void setupRandomColorBalls();
std::vector<Ball> balls;
bool drawRGBColorBalls{true};
};
| true |
fd06bf044e4d17c3c3b89e4edbc430ba44712315 | C++ | eyaldouwma/TetrisC- | /Tetris/Tetris/theGame.cpp | UTF-8 | 8,675 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
#include "Joker.h"
#include "Square.h"
#include "Snake.h"
#include "Plus.h"
#include "Zshape.h"
#include "Lshape.h"
#include "theGame.h"
#include "Bomb.h"
#include "Gotoxy.h"
#include "Utils.h"
#include <typeinfo>
using namespace std;
void theGame::run(bool& newGame)
{
GameBoard board;
bool exitGame = false;
char keyPressed;
int whichObject, moveCounter;
bool exploded = false;
score = 0;
pieces = 0;
updateScore(score);
while (exitGame == false)
{
Shape* pShape = nullptr;
SpecialShape *pSpecShape = nullptr;
whichObject = rand() % numOfShapes;
updatePieces(pieces);
moveCounter = 0;
if (board.checkIfGameIsOver((eBlock)whichObject) == true)
{
exitGame = true;
}
else
{
if (((eBlock)whichObject >= SquareBlock) && ((eBlock)whichObject <= LshapeBlock))//Regular Shapes Scenario
{
if ((eBlock)whichObject == SquareBlock)
{
pShape = new Square;
pShape->setBody();
}
else if ((eBlock)whichObject == SnakeBlock)
{
pShape = new Snake;
pShape->setBody();
}
else if ((eBlock)whichObject == PlusBlock)
{
pShape = new Plus;
pShape->setBody();
}
else if ((eBlock)whichObject == ZshapeBlock)
{
pShape = new Zshape;
pShape->setBody();
}
else if ((eBlock)whichObject == LshapeBlock)
{
pShape = new Lshape;
pShape->setBody({6,5});
}
pShape->draw();
while (pShape->checkIfDownAvailable(board))
{
Sleep(sleepMode);
if (moveCounter < 3)
{
if (_kbhit()) //if there is an input
{
keyPressed = _getch();
checkGlobalKeyPressed(keyPressed, exitGame, newGame);
if (exitGame == true || newGame == true)
{
break;
}
if (keyPressed == Rotate) //rotate was pressed
{
pShape->rotate(board, moveCounter);
}
else
{
pShape->move(keyPressed, board, moveCounter);
}
}
else //if there was no input specified, just go down
{
pShape->goDown(moveCounter);
}
}
else //if the user pressed 3 times left & right on the same height level, we force the object to go down
{
pShape->goDown(moveCounter);
}
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
}
board.updateShape(pShape->getBody(), pShape->getSymbol());
}
else //Special Shapes Scenario - Bomb / Joker
{
if ((eBlock)whichObject == JokerBlock)
{
pSpecShape = new Joker;
pSpecShape->setBody();
}
else if ((eBlock)whichObject == BombBlock)
{
pSpecShape = new Bomb;
pSpecShape->setBody();
}
exploded = false;
pSpecShape->draw();
while (pSpecShape->checkIfDownAvailable(board))
{
Sleep(sleepMode);
if (moveCounter < 3)
{
if (_kbhit())
{
keyPressed = _getch();
checkGlobalKeyPressed(keyPressed, exitGame, newGame);
if (exitGame == true || newGame == true)
{
break;
}
if (keyPressed == Stop && typeid(*pSpecShape) == typeid(Joker))
{
break;
}
pSpecShape->move(keyPressed,board,moveCounter,exploded);
if (exploded == true)
{
score = score - (50 * ((Bomb*)pSpecShape)->explode(board));
updateScore(score);
break;
}
}
else
{
pSpecShape->goDown(board, moveCounter);
}
}
else
{
pSpecShape->goDown(board, moveCounter);
}
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
}
if (typeid(*pSpecShape) == typeid(Joker))
{
board.updateJoker(pSpecShape->getBody(), pSpecShape->getSymbol());
}
}
if (exitGame == false)
{
pieces++;
if ((eBlock)whichObject != BombBlock)
{
if (board.checkAndUpdateBoard(score) == true)
{
updateScore(score);
}
}
else
{
if (exploded == false)
{
pieces++;
score = score - (50 * ((Bomb*)pSpecShape)->explode(board));
updateScore(score);
}
}
}
}
}
//gotoxy(0, 20);
//board.printAllValues();
}
void theGame::drawBoard() const
{
int y, x;
gotoxy(0, 0);
cout << "Score: " << endl << "Pieces: " << endl;
for (x = 0; x < 12; x++) //ceiling
{
gotoxy(x, 3);
cout << "~";
}
for (y = 4; y < 19; y++) //left wall
{
gotoxy(0, y);
cout << "|";
}
for (y = 4; y < 19; y++) //right wall
{
gotoxy(11, y);
cout << "|";
}
for (x = 0; x < 12;x++) //floor
{
gotoxy(x, 19);
cout << "~";
}
}
void theGame::updatePieces(int pieces)
{
gotoxy(8, 1);
for (int i = 0; i < 12; i++)
{
cout << ' ';
}
gotoxy(8, 1);
cout << pieces;
}
void theGame::updateScore(int score)
{
gotoxy(7, 0);
for (int i = 0; i < 12; i++)
{
cout << ' ';
}
gotoxy(7, 0);
cout << score;
}
void theGame::printGameOver() const
{
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
SetConsoleTextAttribute(hstdout, FOREGROUND_INTENSITY | BACKGROUND_BLUE);
gotoxy(1, 10);
cout << "GAME OVER" << endl;
SetConsoleTextAttribute(hstdout, csbi.wAttributes);
gotoxy(0, 21);
}
void theGame::printMenu() const
{
//prints the menu
gotoxy(20, 0);
cout << "For new game press:";
gotoxy(54, 0);
cout << "<1>" << endl;
gotoxy(20, 1);
cout << "For Pause / Resume press:";
gotoxy(54, 1);
cout << "<2>" << endl;
gotoxy(20, 2);
cout << "To Increase the game speed press: <3>" << endl;
gotoxy(20, 3);
cout << "To Decrease the game speed press: <4>" << endl;
gotoxy(20, 4);
cout << "To Quit the game press:";
gotoxy(54, 4);
cout << "<9>";
gotoxy(30, 10);
cout << "--------------";
gotoxy(30, 11);
cout << "| SPEED: " << MID_SPEED << " |";
gotoxy(30, 12);
cout << "--------------";
}
void theGame::pauseGame(bool &exitGame, bool& newGame) const
{
char keyPressed = 0;
while (keyPressed != PauseResume)
{
if (_kbhit())
{
keyPressed = _getch();
if (keyPressed == New)
{
newGame = true;
exitGame = true;
break;
}
else if (keyPressed == Quit)
{
exitGame = true;
break;
}
}
}
}
void theGame::runWithMenuOptions()
{
bool quitGame = false;
bool newGame = true;
bool isGameOver = false;
printMenu();
drawBoard();
initialUserInput(quitGame); //the user can choose to start the game, or quit before starting
if (quitGame == false)//if the user pressed '1' for playing the game
{
while (isGameOver == false)//after the game is over, the user can decide to play again
{
while (newGame == true)//if the user entered '1' while in game play, the game will restart
{
newGame = false;
run(newGame);
}
printGameOver();
startNewGameAfterGameOver(newGame, isGameOver);//present the user the option to renew the game after the game is over
}
}
else //the user decided to quit before even starting the game pressing '9'
{
printGameOver();
}
cout << endl;
}
void theGame::speedUp()
{
if (sleepMode != MIN_SPEED)
{
sleepMode -= 50;
gotoxy(39, 11);
cout << " ";
gotoxy(39, 11);
cout << (MAX_SPEED-sleepMode); // the more the sleep is long, the speed we show the user is lower
}
}
void theGame::speedDown()
{
if (sleepMode != MAX_SPEED)
{
sleepMode += 50;
gotoxy(39, 11);
cout << " ";
gotoxy(39, 11);
cout << (MAX_SPEED-sleepMode); // the more the sleep is short, the speed we show the user is higher
}
}
int theGame::getSleepMode() const
{
return sleepMode;
}
void theGame::initialUserInput(bool&quitGame)
{
char key = 0;
while (key != New)
{
if (_kbhit())
{
key = _getch();
if (key == Quit)
{
quitGame = true;
key = New;
}
}
}
}
void theGame::startNewGameAfterGameOver(bool&newGame, bool&isGameOver)
{
cout << "Press 1 for new game, 9 to exit";
char key = 0;
while (key != New && key != Quit)
{
if (_kbhit())
{
key = _getch();
if (key == Quit)
{
isGameOver = true;
}
if (key == New)
{
newGame = true;
}
}
}
gotoxy(0, 21);
for (int i = 0; i <= 30; i++)
{
cout << ' ';
}
}
void theGame::checkGlobalKeyPressed(char key, bool& exitGame, bool& newGame)
{
if (key == Quit)
{
exitGame = true;
}
else if (key == New)
{
newGame = true;
exitGame = true;
}
else if (key == PauseResume)
{
pauseGame(exitGame, newGame);
}
else if (key == IncreaseSpeed)
{
speedUp();
}
else if (key == DecreaseSpeed)
{
speedDown();
}
}
| true |
d79880183efecf0aebe04f1dfd0a558fadace97b | C++ | NCAR/lrose-core | /codebase/libs/rapmath/src/mathparse/LogicalArgs.cc | UTF-8 | 1,582 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file LogicalArgs.cc
*/
#include <rapmath/LogicalArgs.hh>
#include <toolsa/LogStream.hh>
LogicalArg::LogicalArg(const std::string &name, double value, bool missingValue,
const MathFindSimple::Compare_t &test) :
_variableName(name), _value(value), _valueIsMissing(missingValue), _op(test),
_data(NULL)
{
}
bool LogicalArg::satisfiesCondition(int index) const
{
double v;
if (_valueIsMissing)
{
return !_data->getVal(index, v);
}
else
{
if (_data->getVal(index, v))
{
switch (_op)
{
case MathFindSimple::GT:
return v > _value;
case MathFindSimple::GE:
return v >= _value;
case MathFindSimple::EQ:
return v == _value;
case MathFindSimple::LE:
return v <= _value;
case MathFindSimple::LT:
return v < _value;
default:
return false;
}
}
else
{
return false;
}
}
}
bool LogicalArg::synch(MathData *rdata)
{
MathLoopData *ldata = rdata->dataPtr(_variableName);
if (ldata == NULL)
{
LOG(ERROR) << "No data for " << _variableName;
return false;
}
_data = ldata;
if (_valueIsMissing)
{
if (_op != MathFindSimple::EQ)
{
LOG(ERROR) << "Only equality for missing comparison";
return false;
}
_value = ldata->getMissingValue();
}
return true;
}
void LogicalArgs::updateStatus(bool bi, int opIndex, bool &ret) const
{
switch (_ops[opIndex])
{
case Find::AND:
ret = ret && bi;
break;
case Find::OR:
ret = ret || bi;
break;
case Find::NONE:
default:
ret = false;
break;
}
}
| true |
2886f4938abae8b246b07b7f3cdd4cea17b077d7 | C++ | JicLotus/Dropbox-source | /Servidor/testing/TestUserHandler.cpp | UTF-8 | 1,897 | 2.734375 | 3 | [] | no_license | /*
* TestUsers.cpp
*
* Created on: 21 de set. de 2015
* Author: kevin
*/
#include <gtest/gtest.h>
#include "TestUserHandler.h"
TestUserHandler::TestUserHandler() {
// TODO Auto-generated constructor stub
}
void TestUserHandler::testGenerateUser() {
RocksdbHandler::Delete("user_testunit", PATH_DB_USERS);
UserHandler userHandler;
string response = userHandler.Insert("{\"identifier\": \"testunit\", \"name\": \"name1\", \"md5\": \"passwd1\", \"email\" : \"test@test.com\"}");
ASSERT_STREQ(response.c_str(), "{ \"result\" : \"OK\" , \"message\" : \"\" }");
}
void TestUserHandler::testLoadUser() {
UserHandler userHandler;
string jsonResponse = userHandler.Auth("testunit","passwd1");
Json::Value root;
Json::Reader reader;
reader.parse(jsonResponse, root, false);
string token = root["token"].asString();
jsonResponse = userHandler.Get("testunit", token);
ASSERT_STRNE(jsonResponse.c_str(), "{ \"result\" : \"ERROR\" , \"message\" : \"Invalid identifier\" }");
}
void TestUserHandler::testUpdateUser() {
UserHandler userHandler;
string jsonResponse = userHandler.Auth("testunit","passwd1");
Json::Value root;
Json::Reader reader;
reader.parse(jsonResponse, root, false);
string token = root["token"].asString();
jsonResponse = userHandler.Update("testunit", "{\"token\": \"" + token + "\", \"identifier\": \"testunit\", \"name\": \"name1\", \"email\" : \"test@test.com\"}");
ASSERT_STREQ(jsonResponse.c_str(), "{ \"result\" : \"OK\" , \"message\" : \"\" }");
}
void TestUserHandler::testDeleteUser(){
UserHandler userHandler;
string jsonResponse = userHandler.Auth("testunit","passwd1");
Json::Value root;
Json::Reader reader;
reader.parse(jsonResponse, root, false);
string token = root["token"].asString();
jsonResponse = userHandler.Delete("testunit", token);
ASSERT_STREQ(jsonResponse.c_str(), "{ \"result\" : \"OK\" , \"message\" : \"\" }");
}
| true |
70c2d76afc9e8e59c4cf96006f85e92488b56a09 | C++ | bharad6/arm_hab_controller | /InterruptEvent/InterruptEvent.cpp | UTF-8 | 560 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | #include "InterruptEvent.h"
/*
* Constructor
*/
InterruptEvent::InterruptEvent(TaskManager *_task_manager,
SerialTask _task,
void *_context,
void *_serial) {
/* Setting up the task manager who to add the context and task to
periodically. */
task_manager = _task_manager;
task = _task;
context = _context;
serial = _serial;
}
/*
* Schedule the task and context into the task manager
*/
void InterruptEvent::handle() {
task(serial, context);
}
| true |
1f0c46d72cf4dbb887baddc2b8b2af9eac6ed0a0 | C++ | Manzood/CodeForces | /Educational/Educational-Round-90/test.cpp | UTF-8 | 779 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void Init ()
{
const string FileINP = "A" + (string)".INP";
const string FileOUT = "A. Donut Shops" + (string)".OUT";
freopen (FileINP.c_str(), "r", stdin);
freopen (FileOUT.c_str(), "w", stdout);
}
long long t, a, b, c;
void Solve (long long &a, long long &b, long long &c)
{
if (a*b == c) printf ("%lld", b + 1);
else if (a < c)
{
printf ("1");
}
else printf ("-1");
printf (" ");
if (a * b > c)
{
printf ("%lld", b);
}
else printf ("-1");
printf ("\n");
}
int main ()
{
//Init();
scanf ("%lld", &t);
for (long long i = 0; i < t; ++i)
{
scanf ("%lld %lld %lld", &a, &b, &c);
Solve (a, b, c);
}
return 0;
} | true |
e511ef3bc37dd9750b89345d0e657528fc70b357 | C++ | alexandraback/datacollection | /solutions_5709773144064000_1/C++/Lexarx/main.cpp | UTF-8 | 583 | 2.859375 | 3 | [] | no_license | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include "math.h"
using namespace std;
const double EPSILON = 1e-7;
int main() {
int nt;
cin >> nt;
for (int t = 1; t <= nt; t++) {
double c, f, x;
cin >> c >> f >> x;
double s = 0;
if (x <= c) {
s = x / 2;
} else {
int k = 0;
while (true) {
double r = (x - c) / (2 + k * f) - x / (2 + (k + 1) * f);
if (r < EPSILON) {
break;
}
s += c / (2 + k * f);
k++;
}
s += x / (2 + k * f);
}
cout << "Case #" << t << ": ";
printf("%.7f", s);
cout << endl;
}
return 0;
}
| true |
358fc44dd05cd000679696674cae472058549b34 | C++ | UniqueZHY/ZHY | /algorithm/566_上网统计.cpp | UTF-8 | 1,160 | 3.125 | 3 | [] | no_license | /*************************************************************************
> File Name: 566_上网统计.cpp
> Author:
> Mail:
> Created Time: 2020年03月08日 星期日 15时13分26秒
************************************************************************/
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct node {
string id;
vector <string> web;
};
int main() {
vector <node> v;
int n, m;
string id, str;
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> id >> str;
bool flag = 0;
for (int j = 0; j < v.size(); j++) {
if (v[j].id == id) {
v[j].web.push_back(str);
flag = 1;
break;
}
}
if (!flag) {
node temp;
temp.id = id;
temp.web.clear();
temp.web.push_back(str);
v.push_back(temp);
}
}
for(int i = 0;i < v.size();i++){
cout << v[i].id;
for(int j = 0; j < v[i].web.size(); j++) {
cout << " " << v[i].web[j];
}
cout <<endl;
}
return 0;
}
| true |
70725b98723a5dad1dc23c69055d36e02e4733f7 | C++ | opopi123/Laghima | /Desktop/CSE250/assignment7/StackPairRYJ.h | UTF-8 | 1,462 | 3.5625 | 4 | [] | no_license | #ifndef STACKPAIRRYJ_h_
#define STACKPAIRRYJ_h_
#include <vector>
#include <iostream>
using namespace std;
template<class T>
class StackPair{
int front, rear, bound;
vector <T>* elements;
public:
~StackPair();
StackPair(int cell);
int size() const;
bool isFull() const;
bool isEmpty() const;
T popA();
T popB();
void pushA(T A);
void pushB(T B);
};
template<class T>
StackPair<T>::StackPair(int cell):
elements( new vector <T>(cell)),
front(-1),
rear(cell),
bound(cell){}
template<class T> StackPair<T>::~StackPair(){delete elements;}
template<class T>
int StackPair<T>::size() const{
return bound-rear+front;}
template<class T>
bool StackPair<T>::isFull() const{
return front==rear || rear==0 ||front==bound ;}
template<class T>
bool StackPair<T>::isEmpty() const{
return front ==-1 && rear== bound;}
template<class T>
T StackPair<T>::popA(){
if(isEmpty()){
cerr<<"error Stack is empty"<<endl;
return ' ';}
else{return elements->at(front--);
} }
template<class T>
T StackPair<T>::popB(){
if(isEmpty()){
cerr<<"error Stack is empty"<<endl;
return ' ';}
else{ return elements->at(rear++);
}
}
template<class T>
void StackPair<T>::pushA(T A){
if(isFull()){
cerr<< "error Stack is full"<<endl;
}
else{
elements->at(++front)=A;
} }
template<class T>
void StackPair<T>::pushB(T B){
if(isFull()){
cerr<<"error Stack is full"<<endl;}
else{
elements-> at(--rear)=B;
}
}
#endif
| true |
f6f41065b0452732f9f6ffb30d53ebaa85b54c7e | C++ | LoydChen/Cplusplus | /20160420/io1.cc | UTF-8 | 637 | 2.609375 | 3 | [] | no_license | ///
/// @file io1.cc
/// @author loydchen(loydchen729@gmail.com)
/// @date 2016-04-20 20:10:09
///
#include <iostream>
#include <limits>
#include <string>
using namespace std;
void printbit(){
cout << "bad = " << cin.bad() << endl;
cout << "fail = " << cin.fail() << endl;
cout << "eof = " << cin.eof() << endl;
cout << "good = " << cin.good() << endl;
}
int main(){
printbit();
int inum;
while(cin >> inum){
cout << "inum = " << inum << endl;
}
printbit();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << endl;
printbit();
string str;
getline(cin,str);
cout << str << endl;
return 0;
}
| true |
8ae8d37780d1e7f957d00f859de9ec10de7a0450 | C++ | quanghm/UVA-online-judge | /11470.cpp | UTF-8 | 631 | 2.53125 | 3 | [] | no_license | /*
* 11470.cpp
*
* Created on: May 24, 2015
* Author: quanghoang
*/
#include<cstdio>
using namespace std;
int main(){
int c=0,n,s,m;
int a[10][10];
while (scanf("%d",&n)!=EOF&&n){
printf("Case %d:",++c);
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
scanf("%d ",&(a[i][j]));
}
}
m=n/2;
for (int i=0;i<m;i++){
s=0;
for (int j=i;j<n-i-1;j++){
s+=(a[i][j]+a[j][n-1-i]+a[n-1-i][n-1-j]+a[n-1-j][i]);
// printf("%d+%d+%d+%d\n",a[i][j],a[j][n-1-i],a[n-1-i][n-1-j],a[n-1-j][i]);
}
printf(" %d",s);
//s+=(a[])
}
if (n%2){
printf(" %d",a[m][m]);
}
printf("\n");
}
}
| true |
5468e7398e8325c9719af0f43b02e160a36ec47b | C++ | RiffLord/data-structures | /list/linked/doubly/list.h | UTF-8 | 5,320 | 3.421875 | 3 | [] | no_license | /**
* @file list.h
* @author Bruno Pezer (bruno.pezer@tutanota.com)
* @brief Generic doubly linked array-based list class definition.
* @version 0.5
* @date 2022-08-15
*
* @copyright NO COPYRIGHT !(c) 2022
*
*/
#ifndef LIST_H
#define LIST_H
#include <iostream>
#include "node.h"
// TODO: fix double free detected error
template <typename T>
class List {
friend std::ostream &operator<<(std::ostream &out, const List &list) {
for (int i = 0; i < list.length; i++)
out << list.contents[i].getData() << '\n';
return out;
}
public:
typedef unsigned int position;
List(unsigned int = 10);
List(const List &);
~List();
bool isEmpty() const;
bool endOfList(position) const;
position first() const;
position last() const;
position next(position) const;
position previous(position) const;
T read(position) const;
void write(T, position);
void insert(T, position);
void remove(position);
// Utility functions & overloaded operators
unsigned int getCapacity() const;
unsigned int getLength() const;
void setCapacity(unsigned int);
bool isValid(position) const;
void removeDuplicates();
void range(position);
bool operator==(const List &) const;
bool operator!=(const List &) const;
private:
Node<T> *contents;
unsigned int length, capacity;
};
template <typename T>
List<T>::List(unsigned int c) {
capacity = c;
length = 0;
contents = new Node<T>[capacity];
}
template <typename T>
List<T>::List(const List<T> &rval) {
capacity = rval.capacity;
length = rval.length;
contents = new Node<T>[capacity];
for (int i = 0; i < length; i++)
contents[i].setData(rval.contents[i].getData());
}
template <typename T>
List<T>::~List() { delete [] contents; }
template <typename T>
bool List<T>::isEmpty() const { return length == 0; }
template <typename T>
bool List<T>::endOfList(position p) const {
if (0 < p && p <= length + 1)
return (p == length + 1);
else
return false;
}
template <typename T>
bool List<T>::isValid(position p) const { return (0 < p && p < length + 1); }
template <typename T>
typename List<T>::position List<T>::first() const { return 1; }
template <typename T>
typename List<T>::position List<T>::last() const { return length; }
template <typename T>
typename List<T>::position List<T>::next(position p) const {
if (isValid(p))
return p + 1;
else
return p;
}
template <typename T>
typename List<T>::position List<T>::previous(position p) const {
if (isValid(p))
return p - 1;
else
return p;
}
template <typename T>
T List<T>::read(position p) const {
if (!isValid(p))
throw std::out_of_range{"List::read()"};
return contents[p - 1].getData();
}
template <typename T>
void List<T>::write(T t, position p) {
if (!isValid(p))
throw std::out_of_range{"List::write()"};
contents[p - 1].setData(t);
}
template <typename T>
void List<T>::insert(T t, position p) {
if (length == capacity) { // TODO: add setCapacity method
}
if (0 < p && p <= length + 1) {
for (int i = length; i >= p; i--) {
contents[i].setData(contents[i - 1].getData());
}
contents[p - 1].setData(t);
++length;
}
}
template <typename T>
void List<T>::remove(position p) {
if (!isValid(p))
throw std::out_of_range{"List::remove()"};
if (!isEmpty()) {
for (int i = p - 1; i < length - 1; i++) {
contents[i].setData(contents[i + 1].getData());
}
--length;
}
}
template <typename T>
unsigned int List<T>::getCapacity() const { return capacity; }
template <typename T>
unsigned int List<T>::getLength() const { return length; }
template <typename T>
void List<T>::setCapacity(unsigned int c) {
capacity = c;
Node<T> *n = new Node<T>[capacity];
for (int i = 0; i < length; i++)
n[i].setData(contents[i].getData());
delete [] contents;
contents = n;
}
template <typename T>
bool List<T>::operator==(const List<T> &rval) const {
if (length != rval.length)
return false;
for (int i = 0; i < length; i++) {
if (contents[i].getData() != rval.contents[i].getData())
return false;
}
return true;
}
template <typename T>
bool List<T>::operator!=(const List<T> &rval) const { return !(*this == rval); }
template <typename T>
void List<T>::removeDuplicates() {
position p = first(), q = next(p);
while (!endOfList(p)) {
while (!endOfList(q)) {
if (read(p) == read(q))
remove(q);
else
q = next(q);
}
p = next(p);
q = next(p);
}
}
template <typename T>
void List<T>::range(position p) {
if (!isValid(p))
throw std::out_of_range{"List::range()"};
if (!isEmpty()) {
position q = next(p);
if (!endOfList(q)) {
range(q);
int a = read(p) + read(q);
write(a, p);
}
}
}
#endif // LIST_H | true |
f6c793e7b1b3675cacc8691fe283412faa030b28 | C++ | Anderson688/CS204 | /Lab_post-mid_4/Odd_Weight.cpp | UTF-8 | 1,216 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool isBipartite(vector <vector<int> > v, int src , int* color)
{
bool flag = true;
for(int i = 0; i < v[src].size(); i++)
{
if(color[v[src][i]] == 0)
{
color[v[src][i]] = 0-color[src];
flag = flag & isBipartite(v, i, color);
}
else
{
if((color[v[src][i]] == 1 && color[src] == 1) || (color[v[src][i]] == -1 && color[src] == -1))
{
return false;
}
}
}
return flag;
}
int main()
{
long long n, m;
cin >> n >> m;
vector <vector<int> > adj(n+m);
int t = 0;
for(int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
if(c%2 == 1)
{
adj[a-1].push_back(b-1);
adj[b-1].push_back(a-1);
}
else
{
adj[n+t].push_back(a-1);
adj[n+t].push_back(b-1);
adj[a-1].push_back(n+t);
adj[b-1].push_back(n+t);
t++;
}
}
int color[n] = {0};
bool is_bipartite = true;
for(int i = 0; i < n+t; i++)
{
if(color[i] == 0)
{
color[i] = 1;
is_bipartite = isBipartite(adj, i, color);
}
if(is_bipartite == false)
break;
}
if(is_bipartite == true)
cout << "NO";
else
cout << "YES";
return 0;
}
| true |
657fb41d33e8a4e8fce34c2ea50b57ed50ce2461 | C++ | irajgreenberg/Protobyte_0.1.7_quark | /Protobyte/Projects/splineTest02/splineTest02/ProtoController.cpp | UTF-8 | 4,374 | 2.9375 | 3 | [] | no_license | /*
Protobyte Library 0.1.6
Ira Greenberg 2016
*/
//https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline
#include "ProtoController.h"
//void ProtoController::catmulRom() {
// //newPts.clear();
// Vec3f p0{};
// Vec3f p1{};
// Vec3f p2{};
// Vec3f p3{};
// for (int i = 0; i < pts.size()-3; i++) {
// /* if (isClosed) {
// }
// else {
// }*/
// p0 = pts[i];
// p1 = pts[i + 1];
// p2 = pts[i + 2];
// p3 = pts[i + 3];
//
//
// float t0 = 0.0f;
// float t1 = getT(t0, p0, p1);
// float t2 = getT(t1, p1, p2);
// float t3 = getT(t2, p2, p3);
//
// for (float t = t1; t < t2; t += ((t2 - t1) / ptCount)) {
// Vec3f a1 = (t1 - t) / (t1 - t0) * p0 + (t - t0) / (t1 - t0) * p1;
// Vec3f a2 = (t2 - t) / (t2 - t1) * p1 + (t - t1) / (t2 - t1) * p2;
// Vec3f a3 = (t3 - t) / (t3 - t2) * p2 + (t - t2) / (t3 - t2) * p3;
//
// Vec3f b1 = (t2 - t) / (t2 - t0) * a1 + (t - t0) / (t2 - t0) * a2;
// Vec3f b2 = (t3 - t) / (t3 - t1) * a2 + (t - t1) / (t3 - t1) * a3;
//
// Vec3f c = (t2 - t) / (t2 - t1) * b1 + (t - t1) / (t2 - t1) * b2;
//
// newPts.push_back(c);
// }
// }
//}
//
//float ProtoController::getT(float t, Vec3f p0, Vec3f p1) {
// float a = pow((p1.x - p0.x), 2.0f) + pow((p1.y - p0.y), 2.0f) + pow((p1.z - p0.z), 2.0f);
// float b = pow(a, 0.5f);
// float c = pow(b, alpha);
//
// return (c + t);
//}
void ProtoController::init() {
Col4f c;
c[0] = .3f;
// Closed loop test 1
float circleRadius{ 200.0f };
float theta{ 0.0f };
for (int i{ 0 }; i < ptCount; ++i) {
float x = cos(theta) * circleRadius;
float y = sin(theta) * circleRadius;
float z = -ptCount*40/2 + i*40;
vecs.push_back({x, y, z});
theta += TWO_PI / (ptCount/4);
}
// Closed loop test 2
//for (int i = 0; i < ptCount; ++i) {
// vecs.push_back({ random(-400, 400),
// random(-300, 300),
// random(-400, 400) });
//}
s = Spline3(vecs, 5, 0, ProtoSpline3::UNIFORM);
s.setAreTerminalPtsIncluded(0);
//trace("s.getAreTerminalPtsIncluded() =",s.getAreTerminalPtsIncluded());
//s2 = Spline3(vecs, 5, 1, ProtoSpline3::CENTRIPETAL);
//s3 = Spline3(vecs, 5, 1, ProtoSpline3::CHORDAL);
//s.set
tendril = Tube(s, 4, 23, ProtoTransformFunction(ProtoTransformFunction::LINEAR, Tup2(20, 20), 1), true, "corroded_red.jpg");
tendril.setDiffuseMaterial({ 1.0f, 1, 1 });
tendril.setAmbientMaterial(0.05f);
tendril.setBumpMap("corroded_red.jpg", 1.0f);
////tube.loadBumpMapTexture("vascular3_normal2.jpg");
tendril.setTextureScale({ 1.1, .1f });
tendril.setSpecularMaterial({ 1, 1, 1 });
tendril.setShininess(12);
// Enables curves to be drawn to terminasl and closed
// default is terminal drawing
//if (areTerminalsReached) {
// pts.push_back(pts.at(0));
// pts.push_back(pts.at(1));
// // draw smooth closed curve
// if (isCurveClosed) {
// pts.push_back(pts.at(2));
// }
//}
//catmulRom();
// print pts
/*for (Vec3f v : newPts) {
trace("v = ", v);
}*/
//for (int i = 0; i < s.getFrenetFrames().size(); ++i) {
// trace(s.getFrenetFrames().at(i).getT());
// trace(s.getFrenetFrames().at(i).getN());
// trace(s.getFrenetFrames().at(i).getB());
//}
}
void ProtoController::run() {
}
void ProtoController::display() {
/*scale(.5);
beginArcBall();
fill(0);
strokeWeight(6);
for (Vec3f v : newPts) {
point(v.x, v.y, v.z);
}
fill(1, .5, 0, 1);
strokeWeight(7);
int i = 0;
for (Vec3f v : pts) {
if (i == 0) {
strokeWeight(16);
fill(0, 0, 1, 1);
}
else if (i == pts.size()-1) {
strokeWeight(16);
fill(1, 0, 0, 1);
}
else {
strokeWeight(9);
fill(1, .5, 0, 1);
}
point(v.x, v.y, v.z);
i++;
}
endArcBall();*/
scale(.55);
beginArcBall();
s.display(2);
s.displayControlPts();
//s.displayInterpolatedPts(6);
s.displayFrenetFrames();
//translate(100, 0, 0);
//s2.display(2);
//s2.displayInterpolatedPts(6);
////translate(100, 0, 0);
//s3.display(2);
//s3.displayInterpolatedPts(6);
//tendril.display(WIREFRAME);
tendril.display();
endArcBall();
}
// Key and Mouse Events
void ProtoController::keyPressed() {
}
void ProtoController::mousePressed() {
}
void ProtoController::mouseRightPressed() {
}
void ProtoController::mouseReleased() {
}
void ProtoController::mouseRightReleased() {
}
void ProtoController::mouseMoved() {
}
void ProtoController::mouseDragged() {
}
// Window Events
void ProtoController::onResized() {
}
void ProtoController::onClosed() {
} | true |
9c04bb32d92aee94a6a9bc07e08163c2601a7a20 | C++ | jeffreymu/ssrg-hyflow-cpp | /src/core/context/AbstractLock.h | UTF-8 | 1,776 | 2.515625 | 3 | [] | no_license | /*
* AbstractLock.h
*
* Created on: Dec 14, 2012
* Author: mishras[at]vt.edu
*/
#ifndef ABSTRACTLOCK_H_
#define ABSTRACTLOCK_H_
#include <string>
#include <set>
#include <boost/serialization/set.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
namespace vt_dstm {
class AbstractLock {
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
std::string highestObjectName;
std::string lockName;
// Shared lock for current
int absLock;
bool fetched;
unsigned long long requesterTxnId;
std::set<unsigned long long > txnIds;
public:
AbstractLock();
AbstractLock(std::string highestObjectName, std::string lockName, unsigned long long txnId);
virtual ~AbstractLock();
bool isWriteLockable(unsigned long long txnId);
bool isReadLockable(unsigned long long txnId);
void readlock();
void readlock(unsigned long long txnId);
void writelock();
void writelock(unsigned long long txnId);
void unlock(bool isRead, unsigned long long txnId);
int getTracker();
std::string getLockName() const
{
return lockName;
}
void getClone(AbstractLock** abl)
{
AbstractLock* absLockCopy = new AbstractLock();
absLockCopy->highestObjectName = highestObjectName;
absLockCopy->lockName = lockName;
absLockCopy->absLock = absLock;
absLockCopy->txnIds = txnIds;
absLockCopy->requesterTxnId = requesterTxnId;
*abl = absLockCopy;
}
static void serializationTest();
bool isFetchted() const
{
return fetched;
}
void setFetchted(bool fetchted)
{
this->fetched = fetchted;
}
unsigned long long getRequesterTxnId() const
{
return requesterTxnId;
}
};
} /* namespace vt_dstm */
#endif /* ABSTRACTLOCK_H_ */
| true |
17094ef43cd1ca88a0c3006239c401e8fce07091 | C++ | JonasBr68/moderncpp_samples | /Features/CPP11Features/MultiThreading.cpp | UTF-8 | 4,607 | 3.09375 | 3 | [] | no_license | #include "stdafx.h"
#include "MultiThreading.h"
#if CPP_VER > 98
#include <atomic>
#include <mutex>
#endif
#include <memory>
std::once_flag flag;
void do_something() {
int captured = 4;
std::call_once(flag, [&captured]() {std::cout << "Called once " << captured << std::endl; });
std::cout << "Called each time" << std::endl;
}
void callOnce() {
for (int i = 0; i < 5; i++)
{
do_something();
}
}
#if CPP_VER > 98
//http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/
class Singleton {
//Not possible making it a unique_ptr
//see https://stackoverflow.com/questions/13866743/thread-safe-unique-ptr-move
//static std::atomic<std::unique_ptr<Singleton>> s_instance;
static std::atomic<Singleton*> s_instance;
static std::mutex s_mutex;
friend class ThreadCleanup;
static std::atomic<int> s_counter;
public:
Singleton()
{
cout << "Singleton()" << el;
s_counter++;
assert(s_counter.load() < 3);
}
~Singleton()
{
cout << "~Singleton()" << el;
assert(s_counter > 0);
s_counter--;
}
//Avoid copying by accident, delete or remove compiler generated defaults
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
//DCLP - Double Check Locking Pattern now safe in C++ 11
static Singleton* getInstance() {
Singleton* tmp = s_instance.load();
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(s_mutex);
tmp = s_instance.load();
if (tmp == nullptr) {
tmp = new Singleton;
s_instance.store(tmp);
}
}
return tmp;
}
//Even better, now with C++ 11 static initializers
static Singleton& getSingleton() {
static Singleton instance;
return instance;
}
};
std::mutex Singleton::s_mutex;
std::atomic<int> Singleton::s_counter;
std::atomic<Singleton*> Singleton::s_instance = nullptr;
class ThreadCleanup {
public:
//Only ever called on thread exit cleanup
~ThreadCleanup() {
cout << "~ThreadCleanup()" << el;
Singleton* tmp = Singleton::s_instance.load();
if (tmp)
{
delete tmp;
Singleton::s_instance.store(nullptr);
}
}
};
static std::unique_ptr<ThreadCleanup> clean_up_program = std::make_unique<ThreadCleanup>();
#endif
#if CPP_VER > 110
//thread_local is in C++ 11 but only implemented in VS 2015
thread_local static std::unique_ptr<ThreadCleanup> clean_up_thread = std::make_unique<ThreadCleanup>();
#endif
// C++ 20 built in support http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic2
//class SingletonShared {
// static std::atomic<std::shared_ptr<SingletonShared>> s_sharedInstance;
//public:
// ~SingletonShared()
// {
// cout << "~SingletonShared()" << el;
// }
// static std::shared_ptr<SingletonShared> getInstance() {
// std::shared_ptr<SingletonShared>tmp = s_sharedInstance.load();
// if (tmp == nullptr) {
// std::shared_ptr<SingletonShared> potentialSingleton = std::make_shared<SingletonShared>();
// tmp = s_sharedInstance.exchange(potentialSingleton);
// }
// return s_sharedInstance;
// }
//};
//
//std::atomic<std::shared_ptr<SingletonShared>> SingletonShared::s_sharedInstance;
//Example from https://baptiste-wicht.com/posts/2012/03/cp11-concurrency-tutorial-part-2-protect-shared-data.html
struct Counter {
int value;
Counter() : value(0) {}
void increment() {
++value;
}
void decrement() {
if (value == 0) {
throw "Value cannot be less than 0";
}
--value;
}
};
struct ConcurrentSafeCounter {
std::mutex mutex;
Counter counter;
void increment() {
std::lock_guard<std::mutex> guard(mutex); //Exception safe, scope resolves lifetime
counter.increment();
}
void decrement() {
std::lock_guard<std::mutex> guard(mutex); //Exception safe, scope resolves lifetime
counter.decrement();
}
};
void safeCounter() {
ConcurrentSafeCounter counter{};
counter.increment();
counter.decrement();
}
void atomicSingleton() {
#if CPP_VER > 98
std::atomic<int> i = 23;
i += 2;
cout << i << el;
auto instance = Singleton::getInstance();
auto instance2 = Singleton::getInstance();
assert(instance == instance2);
//below same as auto&
decltype(Singleton::getSingleton()) instanceStatic = Singleton::getSingleton();
//Dont forget the & it will make a copy if not...
//deleting copy constructor protects
//auto instanceStatic2 = Singleton::getSingleton();
auto& instanceStatic2 = Singleton::getSingleton();
// C++ 20 built in support http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic2
//auto sharedSingleton = SingletonShared::getInstance();
//auto sharedSingleton2 = SingletonShared::getInstance();
//assert(sharedSingleton.get() == sharedSingleton2.get());
#endif
}
| true |
a1972cb8eaddc28be242842ae1812230b5d1c819 | C++ | Busiu/ProblemSolving | /Hackerrank/Kruskal 2/main.cpp | UTF-8 | 1,858 | 3.09375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct edge{
int waga;
int x;
int y;
};
int partition(edge t[], int pocz, int kon){
int j = pocz;
for(int i = pocz; i <= kon; i++){
if(t[i].waga < t[kon].waga){
swap(t[i], t[j]);
j++;
}
else if(t[i].waga == t[kon].waga){
if(t[i].waga + t[i].x + t[i].y < t[kon].waga + t[kon].x + t[kon].y){
swap(t[i], t[j]);
j++;
}
}
}
swap(t[kon], t[j]);
return j;
}
void quicksort(edge t[], int pocz, int kon){
int pivot = partition(t, pocz, kon);
if(pivot > pocz + 1){
quicksort(t, pocz, pivot - 1);
}
if(pivot + 1 < kon){
quicksort(t, pivot + 1, kon);
}
}
void makeSet(int tab[], int i) {
tab[i] = i;
}
int findSet(int tab[], int i) {
return tab[i];
}
void unionSets(int tab[], int x, int y, int liczba_wierzcholkow) {
int rx = findSet(tab, x);
int ry = findSet(tab, y);
if (rx != ry) {
for (int i = 1; i <= liczba_wierzcholkow; i++) {
if (tab[i] == ry)
tab[i] = rx;
}
}
}
int main() {
int Nodes, Edges;
long long int suma = 0;
cin >> Nodes >> Edges;
edge * t = new edge[Edges + 1];
int * set = new int[Nodes + 1];
for(int i = 1; i <= Edges; i++){
cin >> t[i].x >> t[i].y >> t[i].waga;
}
for(int i = 1; i <= Nodes; i++){
makeSet(set, i);
}
quicksort(t, 1, Edges);
int j = 1;
for(int i = 1; j < Nodes; i++){
if(findSet(set, t[i].x) != findSet(set, t[i].y)){
suma += t[i].waga;
j++;
unionSets(set, t[i].x, t[i].y, Nodes);
}
}
cout << suma;
delete [] t;
delete [] set;
cin >> Nodes;
return 0;
}
| true |
055ce0003af280d9699cec1a3883f8ea22549b33 | C++ | Codeurs2020/graphs | /test/src/test_adjacencyList.h | UTF-8 | 7,411 | 3.140625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../../src/graphs.h"
#include "gtest/gtest.h"
TEST(adjList, add_remove_edge_directed) {
adjacencyList adjacencyList(true);
int num_nodes = 11;
for (int i = 0; i < num_nodes; i++) {
for (int j = 0; j < num_nodes; j++) {
auto added = adjacencyList.add_edge({i, j});
EXPECT_EQ(added, i != j);
}
}
EXPECT_EQ(num_nodes, adjacencyList.get_num_nodes());
auto actual_indegree = adjacencyList.get_indegree();
int expected_indegree[num_nodes];
std::fill(expected_indegree, expected_indegree + num_nodes, num_nodes - 1);
auto res = std::equal(expected_indegree, expected_indegree + num_nodes, actual_indegree);
EXPECT_EQ(res, true);
for (int i = 0; i < num_nodes; i++) {
for (int j = 0; j < num_nodes; j++) {
auto removed = adjacencyList.remove_edge({i, j});
EXPECT_EQ(removed, i != j);
}
}
EXPECT_EQ(0, adjacencyList.get_num_nodes());
delete[] actual_indegree;
}
TEST(adjList, add_remove_edge_undirected) {
adjacencyList adjacencyList(false);
int num_nodes = 10;
for (int i = 0; i < num_nodes; i++) {
for (int j = i + 1; j < num_nodes; j++) {
auto added = adjacencyList.add_edge({i, j});
EXPECT_EQ(added, true);
}
}
EXPECT_EQ(num_nodes, adjacencyList.get_num_nodes());
for (int i = 0; i < num_nodes; i++) {
for (int j = i + 1; j < num_nodes; j++) {
auto removed = adjacencyList.remove_edge({i, j});
EXPECT_EQ(removed, true);
}
}
EXPECT_EQ(0, adjacencyList.get_num_nodes());
}
TEST(adjList, cant_add_edge) {
adjacencyList adjacencyList;
EXPECT_THROW(adjacencyList.add_edge({1}), std::invalid_argument);
EXPECT_THROW(adjacencyList.add_edge({2}), std::invalid_argument);
}
TEST(adjList_indegree, undirected_linear_graph) {
adjacencyList adjacencyList(false);
int num_nodes = 10;
for (int i = 0; i < num_nodes - 1; i++) {
adjacencyList.add_edge({i, i + 1});
}
int expected_indegree[num_nodes];
std::fill(expected_indegree, expected_indegree + num_nodes, 2);
expected_indegree[0] = 1;
expected_indegree[num_nodes - 1] = 1;
auto actual_indegree = adjacencyList.get_indegree();
bool res = std::equal(expected_indegree, expected_indegree + num_nodes, actual_indegree);
EXPECT_EQ(res, true);
delete[] actual_indegree;
}
TEST(adjList_indegree, directed_linear_graph) {
adjacencyList adjacencyList(true);
int num_nodes = 10;
for (int i = 0; i < num_nodes - 1; i++) {
adjacencyList.add_edge({i, i + 1});
}
int expected_indegree[num_nodes];
std::fill(expected_indegree, expected_indegree + num_nodes, 1);
expected_indegree[0] = 0;
auto actual_indegree = adjacencyList.get_indegree();
bool res = std::equal(expected_indegree, expected_indegree + num_nodes, actual_indegree);
EXPECT_EQ(res, true);
delete[] actual_indegree;
}
TEST(adjList_indegree, directed_all_pair_graph) {
adjacencyList adjacencyList(true);
int num_nodes = 10;
for (int i = 0; i < num_nodes; i++) {
for (int j = 0; j < num_nodes; j++) {
auto added = adjacencyList.add_edge({i, j});
EXPECT_EQ(added, i != j);
}
}
int expected_indegree[num_nodes];
std::fill(expected_indegree, expected_indegree + num_nodes, num_nodes - 1);
auto actual_indegree = adjacencyList.get_indegree();
bool res = std::equal(expected_indegree, expected_indegree + num_nodes, actual_indegree);
EXPECT_EQ(res, true);
delete[] actual_indegree;
}
TEST(adjList_indegree, undirected_all_pair_graph) {
adjacencyList adjacencyList(false);
int num_nodes = 10;
for (int i = 0; i < num_nodes; i++) {
for (int j = i + 1; j < num_nodes; j++) {
auto added = adjacencyList.add_edge({i, j});
EXPECT_EQ(added, i != j);
}
}
int expected_indegree[num_nodes];
std::fill(expected_indegree, expected_indegree + num_nodes, num_nodes - 1);
auto actual_indegree = adjacencyList.get_indegree();
bool res = std::equal(expected_indegree, expected_indegree + num_nodes, actual_indegree);
EXPECT_EQ(res, true);
delete[] actual_indegree;
}
TEST(adjList_adjMatrix, directed_all_pair_graph) {
adjacencyList adjacencyList(true);
int num_nodes = 10;
int expected_adjMatrix[num_nodes][num_nodes];
for (int i = 0; i < num_nodes; i++) {
for (int j = 0; j < num_nodes; j++) {
auto added = adjacencyList.add_edge({i, j});
EXPECT_EQ(added, i != j);
expected_adjMatrix[i][j] = i != j;
}
}
EXPECT_EQ(num_nodes, adjacencyList.get_num_nodes());
auto actual_adjMatrix = adjacencyList.get_adjacentMatrix();
for (int r = 0; r < num_nodes; r++) {
for (int c = 0; c < num_nodes; c++) {
EXPECT_EQ(actual_adjMatrix[r][c], expected_adjMatrix[r][c]);
EXPECT_EQ(actual_adjMatrix[r][c], r != c);
}
}
}
TEST(adjList_adjMatrix, undirected_all_pair_graph) {
adjacencyList adjacencyList(false);
int num_nodes = 10;
int expected_adjMatrix[num_nodes][num_nodes];
std::fill(*expected_adjMatrix, *expected_adjMatrix + num_nodes * num_nodes, 0);
for (int i = 0; i < num_nodes; i++) {
for (int j = i + 1; j < num_nodes; j++) {
auto added = adjacencyList.add_edge({i, j});
expected_adjMatrix[i][j] = i != j;
expected_adjMatrix[j][i] = i != j;
EXPECT_EQ(added, i != j);
}
}
EXPECT_EQ(num_nodes, adjacencyList.get_num_nodes());
auto actual_adjMatrix = adjacencyList.get_adjacentMatrix();
for (int r = 0; r < num_nodes; r++) {
for (int c = 0; c < num_nodes; c++) {
EXPECT_EQ(actual_adjMatrix[r][c], expected_adjMatrix[r][c]);
EXPECT_EQ(actual_adjMatrix[r][c], r != c);
}
}
}
TEST(adjList_adjMatrix, undirected_linear_graph) {
adjacencyList adjacencyList(false);
int num_nodes = 10;
int expected_adjMatrix[num_nodes][num_nodes];
std::fill(*expected_adjMatrix, *expected_adjMatrix + num_nodes * num_nodes, 0);
for (int i = 0; i < num_nodes - 1; i++) {
adjacencyList.add_edge({i, i + 1});
expected_adjMatrix[i][i + 1] = 1;
expected_adjMatrix[i + 1][i] = 1;
}
auto actual_adjMatrix = adjacencyList.get_adjacentMatrix();
for (int r = 0; r < num_nodes; r++) {
for (int c = 0; c < num_nodes; c++) {
EXPECT_EQ(actual_adjMatrix[r][c], expected_adjMatrix[r][c]);
EXPECT_EQ(actual_adjMatrix[r][c], abs(r - c) == 1);
}
}
}
TEST(adjList_adjMatrix, directed_linear_graph) {
adjacencyList adjacencyList(true);
int num_nodes = 10;
int expected_adjMatrix[num_nodes][num_nodes];
std::fill(*expected_adjMatrix, *expected_adjMatrix + num_nodes * num_nodes, 0);
for (int i = 0; i < num_nodes - 1; i++) {
adjacencyList.add_edge({i, i + 1});
expected_adjMatrix[i][i + 1] = 1;
}
auto actual_adjMatrix = adjacencyList.get_adjacentMatrix();
for (int r = 0; r < num_nodes; r++) {
for (int c = 0; c < num_nodes; c++) {
EXPECT_EQ(actual_adjMatrix[r][c], expected_adjMatrix[r][c]);
EXPECT_EQ(actual_adjMatrix[r][c], c - r == 1);
}
}
} | true |
d8d2584ce6dca2715eae1c0bc0ef01d197edfb2c | C++ | Dawidsoni/programming-competitions | /MIA/2018/SIR/wzo.cpp | UTF-8 | 2,152 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long int LType;
typedef pair<int, int> IPair;
const int MAX_NODE = 10000010;
const int MAX_NODE_COUNT = 1000010;
class Node {
int rank;
Node* parent;
public:
Node() {
rank = 1;
parent = this;
}
Node* find() {
if(parent == this) {
return this;
}
parent = parent->find();
return parent;
}
static void nodeUnion(Node* node1, Node* node2) {
node1 = node1->find();
node2 = node2->find();
if(node1->rank > node2->rank) {
node2->parent = node1;
}else {
node1->parent = node2;
if(node1->rank == node2->rank) {
node2->rank++;
}
}
}
};
int nodeCount, node;
set<int> nodeSet;
vector<IPair> edgeList;
Node nodeList[MAX_NODE];
vector<IPair> cArr[MAX_NODE];
LType result;
int nodeWeight(IPair node) {
if(node.first < node.second) {
return (node.second % node.first);
}
return (node.first % node.second);
}
void fillEdgeList(int node) {
for(int i = node; i <= MAX_NODE; i += node) {
set<int>::iterator nodeIt = nodeSet.lower_bound(max(i, node + 1));
if(nodeIt == nodeSet.end()) {
break;
}
if(*nodeIt >= i + node) {
continue;
}
edgeList.push_back(IPair(node, *nodeIt));
}
}
void fillEdgeList() {
for(set<int>::iterator nodeIt = nodeSet.begin(); nodeIt != nodeSet.end(); nodeIt++) {
fillEdgeList(*nodeIt);
}
}
void sortEdgeList() {
for(int i = 0; i < (int)edgeList.size(); i++) {
cArr[nodeWeight(edgeList[i])].push_back(edgeList[i]);
}
edgeList.clear();
for(int i = 0; i < MAX_NODE; i++) {
for(int j = 0; j < (int)cArr[i].size(); j++) {
edgeList.push_back(cArr[i][j]);
}
}
}
void buildTree() {
for(int i = 0; i < (int)edgeList.size(); i++) {
IPair edge = edgeList[i];
if(nodeList[edge.first].find() != nodeList[edge.second].find()) {
Node::nodeUnion(&nodeList[edge.first], &nodeList[edge.second]);
result += nodeWeight(edge);
}
}
}
int main() {
cin >> nodeCount;
for(int i = 0; i < nodeCount; i++) {
cin >> node;
nodeSet.insert(node);
}
fillEdgeList();
sortEdgeList();
buildTree();
cout << result << "\n";
return 0;
}
| true |
3c15a6843e433d002a7ff5055595b5afec984c65 | C++ | bracket/circles | /machine_graph/SoundMachineFactory.hpp | UTF-8 | 1,097 | 3.28125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <map>
#include <string>
#include <utility>
class SoundMachine;
class MachineGraph;
class SoundMachineFactory {
public:
typedef SoundMachine * (*MachineConstructor)(MachineGraph *);
private:
typedef std::map<std::string, MachineConstructor> ConstructorMap;
typedef ConstructorMap::iterator iterator;
typedef ConstructorMap::const_iterator const_iterator;
public:
static SoundMachineFactory & get() {
static SoundMachineFactory factory;
return factory;
}
bool register_constructor(
std::string const & name, MachineConstructor constructor, bool force = false
)
{
std::pair<iterator, bool> p = constructors_.insert(std::make_pair(name, constructor));
if (p.second) { return true; }
if (!force) { return false; }
p.first->second = constructor;
return false;
}
SoundMachine * construct(std::string const & name, MachineGraph * graph) const {
const_iterator it = constructors_.find(name);
if (it == constructors_.end()) { return 0; }
return (*it->second)(graph);
}
private:
ConstructorMap constructors_;
};
| true |
fa2581b307dc293aa688ad5b2c344d5a015f45eb | C++ | syawacha/AtCoder | /ABC/D/D_045.cpp | UTF-8 | 959 | 2.515625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
typedef long long ll;
using namespace std;
typedef pair<int,int> P;
int dx[3] = {-1,0,1};
int dy[3] = {-1,0,1};
int main(){
ll H,W,N;
cin >> H >> W >> N;
map<P,int> mp;
for(int i=0;i<N;i++){
int a,b;
cin >> a >> b;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
mp[P(a+dx[i],b+dy[j])]++;
}
}
}
ll cnt[10] = {};
for(auto it = mp.begin() ; it!=mp.end() ; it++){
int x = it->first.first;
int y = it->first.second;
if(2 <= x && x <= H-1 && 2 <= y && y <= W - 1){
cnt[it->second]++;
}
}
cnt[0] = (H - 2) * (W - 2);
for(int i=1;i<10;i++){
cnt[0] -= cnt[i];
}
for(int i=0;i<10;i++){
cout << cnt[i] << endl;
}
return 0;
}
| true |
0db65d4222141149c847e3a6df2118ca6204484b | C++ | MohamedFathi45/Competitive-programming | /UVA/UVA 11495.cpp | UTF-8 | 1,938 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<math.h>
#include<set>
#include<iomanip>
#include<queue>
#include<deque>
#include<bitset>
#include<stack>
#include<list>
#define Mohamed_Fathi ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long long ll;
using namespace std;
unsigned long long c = 0;
void MergeSort(vector<int>& v)
{
if (v.size() <= 1)
return;
vector<int>left;
for (int i = 0; i < v.size() / 2; i++)
left.push_back(v[i]);
vector<int>right;
for (int i = v.size() / 2; i < v.size(); i++)
right.push_back(v[i]);
MergeSort(left);
MergeSort(right);
int ind1 = 0, ind2 = 0;
for (int i = 0; i < v.size(); i++)
{
if (ind2 >= right.size()){
v[i] = left[ind1];
ind1++;
}
else if (ind1 >= left.size()){
v[i] = right[ind2];
ind2++;
}
else if (left[ind1] <= right[ind2]){
v[i] = left[ind1];
ind1++;
}
else {
c += (left.size() - ind1);
v[i] = right[ind2];
ind2++;
}
}
}
int main()
{
Mohamed_Fathi
vector<int>v;
int temp;
while ( cin>>temp && temp )
{
v.clear();
int x;
c = 0;
for (int i = 0; i < temp; i++)
{
cin >> x;
v.push_back(x);
}
MergeSort(v);
if( c & 1 )
cout<<"Marcelo"<<endl;
else
cout<<"Carlos"<<endl;
}
return 0;
}
| true |
47ac620f4c4262fe2a03f2aa88d970551f9dc668 | C++ | stir001/DirectX12Library | /DirectX12/Util/CharToWChar.cpp | UTF-8 | 624 | 2.75 | 3 | [] | no_license | #include "stdafx.h"
#include "CharToWChar.h"
#include <wpframework.h>
#include <locale.h>
#include <stdlib.h>
size_t ToWChar(std::wstring& wstr, std::string cstr)
{
size_t rtn = 0;
cstr.push_back('\0');
wchar_t* buf = new wchar_t[cstr.size()];
mbstowcs_s(&rtn, buf, cstr.size(), cstr.data(), _TRUNCATE);
wstr.resize(rtn);
wstr = buf;
delete buf;
return rtn;
}
size_t ToChar(std::string& cstr, std::wstring wstr)
{
size_t rtn = 0;
wstr.push_back('\0');
char* buf = new char[wstr.size()];
wcstombs_s(&rtn, buf, wstr.size(), wstr.data(), _TRUNCATE);
cstr.resize(rtn);
cstr = buf;
delete buf;
return rtn;
}
| true |
5b6c546d7e46229e912c04f604a2c4f75ac2cdeb | C++ | prakash1895/ros_packages | /kinect_camera/src/GPS_pub_string.cpp | UTF-8 | 783 | 2.609375 | 3 | [] | no_license | #include"ros/ros.h"
#include"std_msgs/String.h"
#include<sstream>
#include<unistd.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "GPS_pub_string");
ros::NodeHandle n;
ros::Publisher pub_lat = n.advertise<std_msgs::String>("LatLng",1000);
ros::Rate loop_rate(10);
int count=1;
while(ros::ok())
{
std_msgs::String msg_latlng;
std::stringstream ss_latlng;
if (count== 1)
ss_latlng << "11.46,79.49";
else if (count == 2)
ss_latlng << "10.46,78.49";
else if (count == 3)
ss_latlng << "9.46,77.49";
else if (count == 4)
ss_latlng << "8.46,76.49";
msg_latlng.data = ss_latlng.str();
pub_lat.publish(msg_latlng);
usleep(5000000);
count++;
if (count == 5)
count = 1;
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| true |
4b69bcae43146e41c05dab01e03781490f6b99d4 | C++ | johnny6464/UVA | /UVA11000-11999/UVA11608.cpp | UTF-8 | 722 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int main() {
int problem, cases = 0;
int produce[12], consume[12];
while (cin >> problem && problem >= 0) {
for (int i = 0; i < 12; i++) {
cin >> produce[i];
}
for (int i = 0; i < 12; i++) {
cin >> consume[i];
}
cout << "Case " << ++cases << ":" << endl;
for (int i = 0; i < 12; i++) {
if (problem >= consume[i]) {
cout << "No problem! :D" << endl;
problem -= consume[i];
}
else {
cout << "No problem. :(" << endl;
}
problem += produce[i];
}
}
return 0;
} | true |
16d18962c8c44eff26a4bd2825267063ecf21f48 | C++ | Megaxela/HGEngineReloaded | /src/Tools/ToolsCore/include/HG/ToolsCore/CommandLineArguments.hpp | UTF-8 | 5,829 | 3.21875 | 3 | [
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | #pragma once
// C++ STL
#include <list>
#include <string>
#include <unordered_map>
#include <variant>
#include <vector>
namespace HG::ToolsCore
{
/**
* @brief Class, that describes command line
* arguments definition and parser.
*/
class CommandLineArguments
{
public:
using ArgumentType = std::variant<int, bool, std::string>;
using ArgumentsMap = std::unordered_map<std::string, ArgumentType>;
/**
* @brief Argument actions.
*/
enum class Action
{
Store,
StoreConst,
StoreTrue,
StoreFalse,
Help,
Version
};
enum class Type
{
Integer,
String,
Boolean
};
private:
/**
* @brief Argument, required in CommandLineArgument.
*/
struct Argument
{
std::vector<std::string> keys;
Action action = Action::Store;
std::size_t numberOfArguments = 0;
ArgumentType constantValue;
ArgumentType defaultVaue;
Type type = Type::String;
std::vector<ArgumentType> choices;
bool required = false;
std::string meta;
std::string destination;
std::string help;
std::string version;
};
public:
/**
* @brief Builder class, that's used by CommandLineArguments::addArgument
*/
class ArgumentBuilder
{
public:
/**
* @brief Constructor.
* @param arg Reference to object to setup.
*/
explicit ArgumentBuilder(Argument& arg);
/**
* @brief Method for setting argument action.
* Store by-default.
* @param action Action.
* @return Reference to builder.
*/
ArgumentBuilder& action(Action action);
/**
* @brief The number of command-line arguments that should be consumed.
* after this one.
* 0 by-default.
* @param number
* @return Reference to builder.
*/
ArgumentBuilder& numberOfArguments(std::size_t number);
/**
* @brief A constant value required by some actions and number of arguments
* selections.
* Empty value by-default.
* @param value Value.
* @return Reference to builder.
*/
ArgumentBuilder& constantValue(ArgumentType argument);
/**
* @brief The value produced if the argument is absent from the command line.
* Empty value by-default.
* @param value Value.
* @return Reference to builder.
*/
ArgumentBuilder& defaultValue(ArgumentType value);
/**
* @brief The type to which the command-line argument should be converted.
* String by-default.
* @param type Type.
* @return Reference to builder.
*/
ArgumentBuilder& type(Type type);
/**
* @brief A container of the allowable values for the argument.
* Empty by-default.
* @param choices Available choices.
* @return Reference to builder.
*/
ArgumentBuilder& choices(std::vector<ArgumentType> choices);
/**
* @brief Whether or not the command-line option may be omitted (optionals only).
* Not required by-default.
* @param required Is required.
* @return Reference to builder.
*/
ArgumentBuilder& required(bool required);
/**
* @brief A name for the argument in usage messages.
* Empty by-default.
* @param meta Meta value.
* @return Reference to builder.
*/
ArgumentBuilder& metavar(std::string meta);
/**
* @brief The name of the attribute to be added to the object returned
* by CommandLineArguments::parse.
* @param name Field name.
* @return Reference to builder.
*/
ArgumentBuilder& destination(std::string name);
/**
* @brief A brief description of what the argument does.
* @param help String.
* @return Reference to builder.
*/
ArgumentBuilder& help(std::string help);
/**
* @brief Version information.
* @param version String version information.
* @return Reference to builder.
*/
ArgumentBuilder& version(std::string version);
private:
Argument& m_ref;
};
/**
* @brief Arguments constructor.
* @param name Descriptions.
*/
explicit CommandLineArguments(std::string name);
/**
* @brief Method for adding argument.
* @param namesOrFlags Name or flags. Example: {"--name", "-n", "-N"}
* @return Builder for argument setup.
*/
ArgumentBuilder addArgument(std::vector<std::string> namesOrFlags);
/**
* @brief Method for parsing argc/argv.
* @param argc Count of arguments.
* @param argv Pointer to arguments.
* @return Parsing result.
*/
ArgumentsMap parse(int argc, char** argv);
/**
* @brief Method, that will show version text to stdout.
*/
void showVersion();
/**
* @brief Method, that will show help text to stdout.
*/
void showHelp();
/**
* @brief Method, that dispays help usage line.
*/
void showUsageLine();
private:
std::string getValueReplacer(const Argument* arg) const;
ArgumentsMap internalParsing(int numberOfArguments, char** arguments);
void showArguments(const std::vector<const Argument*>& arguments);
std::string nameFromKey(const std::string& s) const;
ArgumentType parseValue(const char* value, Type t);
std::string m_name;
std::unordered_map<std::string, Argument*> m_argumentsMap;
std::list<Argument> m_argumentsList;
};
} // namespace HG::ToolsCore
| true |
f25f34a459b685ec55dd9322ff2208d2f1c12e0d | C++ | Steven-Wright1/Beginner-Codes | /SwapVector1sand0s.cpp | UTF-8 | 1,516 | 3.8125 | 4 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
int vectsize_x;
int vectsize_y;
// The vect is passed by reference (simply by using &vect) and changes made here reflect in main()
void func(vector<vector<int>> &vect)
{
// calcs x and y dimensions of vector
vectsize_x = vect.size();
vectsize_y = vect[0].size();
// iterates through both vector dimensions swapping zeros for ones and vice versa
for (int i = 0; i < vectsize_x; i++)
{
for (int j = 0; j < vectsize_y; j++)
{
if(vect[i][j] == 1) vect[i][j] = 0;
else if (vect[i][j] == 0) vect[i][j] = 1;
}
}
}
int main()
{
// Create Vector ones and zeros are to be changed
vector<vector<int>> vect = {{0,1,0,0,0,1,0,1,1,0,1},{0,1,1,1,0,0,1,1,0,1,0}};
// calcs x and y dimensions of vector
vectsize_x = vect.size();
vectsize_y = vect[0].size();
// Print Original Vector
for (int i = 0; i < vectsize_x; i++)
{
for (int j = 0; j < vectsize_y; j++)
{
cout << vect[i][j];
}
cout << endl;
}
// Call function that swaps ones and zeros
func(vect);
// Print Edited Vector
cout << endl;
for (int i = 0; i < vectsize_x; i++) {
for (int j = 0; j < vectsize_y; j++) {
cout << vect[i][j];
}
cout << endl;
}
return 0;
} | true |
8f4040f76878b45f7566cbda68a9f78cac342b44 | C++ | zyhu13/Voronoi-Cell-cpu | /VoronoiProject/ray.h | UTF-8 | 535 | 3.046875 | 3 | [] | no_license | #ifndef _RAY_H
#define _RAY_H
#include "vector.h"
class Ray
{
private:
Vect ori,dir;
//double lowest_dist;
public:
Ray();
Ray(Vect, Vect);
Vect getRayOrigin(){return ori;}
Vect getRayDirection(){return dir;}
//double getRayDistance(){return lowest_dist;}
void setRayOrigin(Vect o){ori=o;}
void setRayDirection(Vect v){dir=v;}
//void setRayDistance(double d){lowest_dist=d;}
};
Ray::Ray()
{
ori=Vect(0,0,0);
dir=Vect(1,0,0);
//lowest_dist=0;
}
Ray::Ray(Vect o, Vect d)
{
ori=o;
dir=d;
//lowest_dist=dist;
}
#endif | true |
b25485fcd0f0d1ba022f61a6696892fbd525a600 | C++ | rahulgoyal911/UCA2017 | /sumOfDigits.cpp | UTF-8 | 245 | 3.34375 | 3 | [] | no_license | //sum of digits using recursion
using namespace std;
#include<iostream>
int a=0;
int sum(int n){
if(n==0)
return a;
//int a;
a = n%10;
a+=sum(n/10);
}
int main()
{
int n;
cin>>n;
int ans = sum(n);
cout<<ans;
} | true |