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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a47a121841e885ec7044419b24fa64080951e4c4 | C++ | andrew4356/oop | /lw2/Encode/ConsoleApplication1/Encode_test.cpp | UTF-8 | 1,388 | 2.65625 | 3 | [] | no_license |
#include "stdafx.h"
#include "../Encode/unitForEncode.h"
BOOST_AUTO_TEST_SUITE(HtmlEncode_function)
BOOST_AUTO_TEST_CASE(replacement_the_symbol_apostrophe)
{
const string expectedResult = "'";
string symbol = "\'";
string encode = HtmlEncode(symbol);
BOOST_CHECK(encode == expectedResult);
}
BOOST_AUTO_TEST_CASE(replaces_the_symbol_ampersand)
{
const string expectedResult = "&";
string symbol = "&";
string encode = HtmlEncode(symbol);
BOOST_CHECK(encode == expectedResult);
}
BOOST_AUTO_TEST_CASE(replacement_the_symbol_quote)
{
const string expectedResult = """;
string symbol = "\"";
string encode = HtmlEncode(symbol);
BOOST_CHECK(encode == expectedResult);
}
BOOST_AUTO_TEST_CASE(replacement_the_symbol_less_than)
{
const string expectedResult = "<";
string symbol = "<";
string encode = HtmlEncode(symbol);
BOOST_CHECK(encode == expectedResult);
}
BOOST_AUTO_TEST_CASE(replacement_the_symbol_greater_than)
{
const string expectedResult = ">";
string symbol = ">";
string encode = HtmlEncode(symbol);
BOOST_CHECK(encode == expectedResult);
}
BOOST_AUTO_TEST_CASE(replacement_the_symbol_char)
{
const string expectedResult = "a b c abc ab bc";
string symbol = "a b c abc ab bc";
string encode = HtmlEncode(symbol);
BOOST_CHECK(encode == expectedResult);
}
BOOST_AUTO_TEST_SUITE_END()
| true |
5172d8c21645d96d763f3682d429bc5f1f3f1d16 | C++ | Yurickh/UnBanco | /src/UserUnit.cpp | UTF-8 | 12,067 | 2.78125 | 3 | [] | no_license | #include "UserUnit.h"
#include <iostream>
extern list<TableClass> PersUnit::returnList;
//===============CtrlUserLogin=====================
ManType CtrlUserLogin::autent(UsrMatric* usrMatric, UsrPassword* usrPassword) throw (invalid_argument, PersError)
{
PersGetManager getManager;
getManager.execute(usrMatric);
Manager man(getManager.getResult());
if(man.getPassword().getValue() != usrPassword->getValue())
throw invalid_argument("Login ou Senha incorretos");
return man.getManType();
}
void CtrlUserLogin :: autent(AccNumber* accNumber, UsrPassword* usrPassword) throw (invalid_argument, PersError)
{
PersGetAccount getAccount;
PersGetCustomer getCustomer;
getAccount.execute(accNumber);
Account acc(getAccount.getResult());
getCustomer.execute(acc.getUsrId());
Customer cus(getCustomer.getResult());
if(cus.getPassword().getValue() != usrPassword->getValue())
throw invalid_argument("Login ou Senha incorretos");
}
//===============StubUserLogin=====================
ManType StubUserLogin::autent(UsrMatric* usrMatric, UsrPassword* usrPassword) throw (invalid_argument, PersError)
{
ManType manType(NORMAL);
if(usrMatric->getValue() == 1)
throw invalid_argument("Login ou Senha incorretos");
if(usrMatric->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
if(usrMatric->getValue() == 3)
manType.setValue(ADMIN);
return manType;
}
void StubUserLogin::autent(AccNumber* accNumber, UsrPassword* usrPassword) throw (invalid_argument, PersError)
{
if(accNumber->getValue() == 1)
throw invalid_argument("Login ou Senha incorretos");
if(accNumber->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
//=================CtrlUserAccAdm======================
void CtrlUserAccAdm :: createAccount( AccType* accType, Money* limit, Money* balance, UsrId usrId) throw (PersError)
{
PersGetLatestNum getLatestNum;
PersNewAccount newAccount;
Account* acc;
getLatestNum.execute();
AccNumber accNumber(getLatestNum.getResult());
acc = new Account(accNumber, *accType, *limit, *balance, usrId);
newAccount.execute(acc);
delete acc;
}
void CtrlUserAccAdm :: deleteAccount( AccNumber* accNumber ) throw (invalid_argument, PersError)
{
PersDelAccount delAccount;
PersGetAccount getAccount;
getAccount.execute(accNumber);
delAccount.execute(accNumber);
}
void CtrlUserAccAdm :: blockAccount(AccNumber* accNumber) throw (invalid_argument, PersError)
{
PersBlkAccount blkAccount;
PersGetAccount getAccount;
getAccount.execute(accNumber);
blkAccount.execute(accNumber);
}
list<Account> CtrlUserAccAdm :: fetchAccount() throw (PersError)
{
PersFetchAccount fetchAccount;
fetchAccount.execute();
return fetchAccount.getResult();
}
Account CtrlUserAccAdm :: fetchAccount(AccNumber number) throw (PersError)
{
PersGetAccount getAccount;
getAccount.execute(&number);
return getAccount.getResult();
}
void CtrlUserAccAdm :: unblockAccount( AccNumber* accNumber ) throw (invalid_argument, PersError)
{
PersUblkAccount ublkAccount;
PersGetAccount getAccount;
getAccount.execute(accNumber);
ublkAccount.execute(accNumber);
}
void CtrlUserAccAdm :: editAccType( AccNumber* accNumber, AccType* accType ) throw (invalid_argument, PersError )
{
PersGetAccount getAccount;
PersEdtAccount edtAccount;
getAccount.execute(accNumber);
edtAccount.execute(accNumber, accType);
}
void CtrlUserAccAdm :: editAccLimit( AccNumber* accNumber, Money* accLimit ) throw (invalid_argument, PersError )
{
PersGetAccount getAccount;
PersEdtAccount edtAccount;
getAccount.execute(accNumber);
edtAccount.execute(accNumber, accLimit);
}
//=================StubUserAccAdm======================
void StubUserAccAdm :: createAccount( AccType* accType, Money* limit, Money* balance, UsrId usrId) throw (PersError)
{
if(limit->getValue() <= 100)
throw PersError(PERS_ERROR_MSG);
}
void StubUserAccAdm :: deleteAccount( AccNumber* accNumber ) throw (invalid_argument, PersError)
{
if(accNumber->getValue() == 1)
throw invalid_argument("A conta requisitada nao existe");
if(accNumber->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
void StubUserAccAdm :: blockAccount( AccNumber* accNumber ) throw (invalid_argument, PersError)
{
if(accNumber->getValue() == 1)
throw invalid_argument("A conta requisitada nao existe");
if(accNumber->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
if(accNumber->getValue() == 3)
throw invalid_argument("A conta requisitada ja esta bloqueada");
}
list<Account> StubUserAccAdm :: fetchAccount() throw (PersError)
{
list<Account> accList;
AccNumber accNum1(1), accNum2(2), accNum3(3);
AccType accType1(NORMAL), accType2(SPECIAL), accType3(NORMAL);
Money accLimit1(10), accLimit2(20), accLimit3(-1);
Money accBal1(5), accBal2(20), accBal3(15);
UsrId accUsrId1(1), accUsrId2(2), accUsrId3(24);
Account n1(accNum1, accType1, accLimit1, accBal1, accUsrId1);
Account n2(accNum2, accType2, accLimit2, accBal2, accUsrId2);
Account n3(accNum3, accType3, accLimit3, accBal3, accUsrId3);
if(!(rand()%2))
throw PersError(PERS_ERROR_MSG);
accList.push_back(n1);
accList.push_back(n2);
accList.push_back(n3);
return accList;
}
Account StubUserAccAdm :: fetchAccount(AccNumber number) throw (PersError)
{
AccNumber accNumber(number);
AccType accType(NORMAL);
Money limit(400.0);
Money balance(20.0);
UsrId usrId(number.getValue()+1);
if(number.getValue() == 2)
throw PersError(PERS_ERROR_MSG);
Account acc(accNumber, accType, limit, balance, usrId);
return acc;
}
void StubUserAccAdm :: unblockAccount( AccNumber* accNumber ) throw (invalid_argument, PersError)
{
if(accNumber->getValue() == 1)
throw invalid_argument("A conta requisitada nao existe");
if(accNumber->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
if(accNumber->getValue() == 3)
throw invalid_argument("A conta requisitada ja esta desbloqueada");
}
void StubUserAccAdm :: editAccType( AccNumber* accNumber, AccType* accType ) throw (invalid_argument, PersError )
{
if(accNumber->getValue() == 1)
throw invalid_argument("A conta requisitada nao existe");
if(accNumber->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
void StubUserAccAdm :: editAccLimit( AccNumber* accNumber, Money* accLimit ) throw (invalid_argument, PersError )
{
if(accNumber->getValue() == 1)
throw invalid_argument("A conta requisitada nao existe");
if(accNumber->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
//=================CtrlUserManAdm======================
void CtrlUserManAdm :: changePassword(UsrMatric usrMatric, UsrPassword* newPassword) throw (PersError)
{
PersEdtManager edtManager;
edtManager.execute(&usrMatric, newPassword);
}
void CtrlUserManAdm :: createManager(UsrName* usrName, UsrPassword* usrPassword) throw (PersError)
{
PersGetLatestMatric getLatestMatric;
PersNewManager newManager;
Manager* man;
ManType manType(NORMAL);
getLatestMatric.execute();
UsrMatric usrMatric(getLatestMatric.getResult());
man = new Manager(*usrName, *usrPassword, manType, usrMatric);
newManager.execute(man);
delete man;
}
list<Manager> CtrlUserManAdm :: fetchManager() throw (PersError)
{
PersFetchManager fetchManager;
fetchManager.execute();
return fetchManager.getResult();
}
Manager CtrlUserManAdm :: fetchManager(UsrMatric matric) throw (PersError)
{
PersGetManager getManager;
getManager.execute(&matric);
return getManager.getResult();
}
void CtrlUserManAdm :: editManName(UsrMatric* usrMatric, UsrName* usrName) throw (invalid_argument, PersError)
{
PersGetManager getManager;
PersEdtManager edtManager;
getManager.execute(usrMatric);
edtManager.execute(usrMatric, usrName);
}
void CtrlUserManAdm :: deleteManager(UsrMatric* usrMatric) throw (invalid_argument, PersError)
{
PersGetManager getManager;
PersDelManager delManager;
getManager.execute(usrMatric);
delManager.execute(usrMatric);
}
//=================StubUserManAdm======================
void StubUserManAdm::changePassword(UsrMatric usrMatric, UsrPassword* newPassword) throw (PersError)
{
if(newPassword->getValue() == "2")
throw PersError(PERS_ERROR_MSG);
}
void StubUserManAdm :: createManager(UsrName* usrName, UsrPassword* usrPassword) throw (PersError)
{
if(usrPassword->getValue() == "2")
throw PersError(PERS_ERROR_MSG);
}
list<Manager> StubUserManAdm :: fetchManager() throw (PersError)
{
list<Manager> manList;
UsrName n1Name("Giovana"), n2Name("Yurick"), n3Name("Andre");
UsrPassword n1Password("s2"), n2Password("eu"), n3Password("outro");
UsrMatric n1Matric(1), n2Matric(2), n3Matric(24);
ManType n1Type(NORMAL), n2Type(NORMAL), n3Type(NORMAL);
Manager n1(n1Name, n1Password, n1Type, n1Matric);
Manager n2(n2Name, n2Password, n2Type, n2Matric);
Manager n3(n3Name, n3Password, n3Type, n3Matric);
if(!(rand()%2))
throw PersError(PERS_ERROR_MSG);
manList.push_back(n1);
manList.push_back(n2);
manList.push_back(n3);
return manList;
}
Manager StubUserManAdm :: fetchManager(UsrMatric matric) throw (PersError)
{
UsrName usrName("Yurick");
UsrPassword usrPassword("eu");
UsrMatric usrMatric(matric);
ManType manType(NORMAL);
if(matric.getValue() == 2)
throw PersError(PERS_ERROR_MSG);
Manager man(usrName, usrPassword, manType, usrMatric);
return man;
}
void StubUserManAdm :: editManName(UsrMatric* usrMatric, UsrName* usrName) throw (invalid_argument, PersError)
{
if(usrMatric->getValue() == 1)
throw invalid_argument("O Gerente requisitado nao existe");
if(usrMatric->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
void StubUserManAdm :: deleteManager(UsrMatric* usrMatric) throw (invalid_argument, PersError)
{
if(usrMatric->getValue() == 1)
throw invalid_argument("O Gerente requisitado nao existe");
if(usrMatric->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
//================CtrlUserCusAdm============================
void CtrlUserCusAdm :: changePassword(UsrId usrId, UsrPassword* newPassword) throw (PersError)
{
PersEdtCustomer edtCustomer;
edtCustomer.execute(usrId, *newPassword);
}
UsrId CtrlUserCusAdm :: createCustomer(UsrName* name, UsrPassword* pass) throw (invalid_argument, PersError)
{
PersGetCustomer getCustomer;
PersNewCustomer newCustomer;
PersGetLatestId getLatestId;
Customer* cus;
try
{
getCustomer.execute(name);
throw PersError("temp");
} catch(invalid_argument except) {}
catch (PersError except)
{
throw invalid_argument("A conta requisitada ja existe");
}
getLatestId.execute();
UsrId usrId (getLatestId.getResult());
cus = new Customer(*name, *pass, usrId);
newCustomer.execute(cus);
delete cus;
return usrId;
}
void CtrlUserCusAdm :: editCusName(UsrId* usrId, UsrName* usrName) throw (invalid_argument, PersError)
{
PersGetCustomer getCustomer;
PersEdtCustomer edtCustomer;
getCustomer.execute(*usrId);
edtCustomer.execute(usrId, usrName);
}
Customer CtrlUserCusAdm :: fetchCustomer(UsrId id) throw (PersError)
{
PersGetCustomer getCustomer;
getCustomer.execute(id);
return getCustomer.getResult();
}
//================StubUserCusAdm============================
void StubUserCusAdm :: changePassword(UsrId usrId, UsrPassword* newPassword) throw (PersError)
{
if(newPassword->getValue() == "2")
throw PersError(PERS_ERROR_MSG);
}
UsrId StubUserCusAdm :: createCustomer(UsrName* name, UsrPassword* pass) throw (invalid_argument, PersError)
{
if(name->getValue() == "A")
throw invalid_argument("Este nome de usuario ja esta em uso");
if(name->getValue() == "B")
throw PersError(PERS_ERROR_MSG);
UsrId usrId(5);
return usrId;
}
void StubUserCusAdm :: editCusName(UsrId* usrId, UsrName* usrName) throw (invalid_argument, PersError)
{
if(usrId->getValue() == 1)
throw invalid_argument("A conta requisitada nao existe");
if(usrId->getValue() == 2)
throw PersError(PERS_ERROR_MSG);
}
Customer StubUserCusAdm :: fetchCustomer(UsrId id) throw (PersError)
{
UsrName usrName("Yurick");
UsrPassword usrPassword("eu");
UsrId usrId(id);
if(id.getValue() == 2)
throw PersError(PERS_ERROR_MSG);
Customer cus(usrName, usrPassword, usrId);
return cus;
}
| true |
ca98a5b44f6ca89d68c83891614b9f15cecd0680 | C++ | jhrotko/dynamic_k2tree | /include/dktree/DKtreeNodeIterator.hpp | UTF-8 | 2,137 | 3.09375 | 3 | [] | no_license | #ifndef __D_K_ITERATOR_VERTICE__
#define __D_K_ITERATOR_VERTICE__
#include <iterator>
#include <memory>
#include "../graph/Graph.hpp"
using namespace std;
namespace dynamic_ktree {
template<class dktree>
class DKtreeNodeIterator : public GraphIterator<DKtreeNodeIterator<dktree>> {
public:
using value_type = int;
using pointer = shared_ptr<int>;
using reference = int &;
using iterator_category = forward_iterator_tag;
DKtreeNodeIterator() {
_ptr = -1;
end();
}
DKtreeNodeIterator(const dktree *tree) {
tree_size = tree->get_number_nodes();
if (tree_size > 0) {
_ptr = 0;
} else {
_ptr = -1;
}
}
DKtreeNodeIterator(DKtreeNodeIterator<dktree> &other) {
_ptr = other._ptr;
tree_size = other.tree_size;
}
value_type operator*() const {
return _ptr;
}
DKtreeNodeIterator<dktree> end() {
DKtreeNodeIterator<dktree> tmp(*this);
tmp._ptr = -1;
return tmp;
}
virtual bool operator==(const DKtreeNodeIterator<dktree> &rhs) const {
return _ptr == rhs._ptr;
}
virtual bool operator!=(const DKtreeNodeIterator<dktree> &rhs) const {
return !(*this == rhs);
}
virtual DKtreeNodeIterator<dktree> &operator++() {
if (_ptr >= tree_size - 1 || _ptr == -1)
_ptr = -1;
else
_ptr += 1;
return *this;
}
virtual DKtreeNodeIterator<dktree> &operator++(int) {
operator++(); // pre-increment
return *this;
}
virtual DKtreeNodeIterator<dktree> &operator=(const DKtreeNodeIterator<dktree> &other) {
if (this != &other) {
_ptr = other._ptr;
tree_size = other.tree_size;
}
return *this;
}
private:
//state
value_type _ptr;
int tree_size = 0;
};
}
#endif
| true |
2cae84e239d87397c8987cad4944b0d3202235cb | C++ | ameerj/nxgpucatch | /src/tests/shader/lop3.cpp | UTF-8 | 2,448 | 2.828125 | 3 | [] | no_license | #include <catch2/catch_test_macros.hpp>
#include "eval_util.h"
namespace {
struct Tuple {
uint32_t a, b, c;
};
} // Anonymous namespace
uint32_t Run(Tuple value, std::string code) {
return EvalUtil::Run(".dksh compute\n"
"main:\n"
"MOV R0, c[0x0][0x140];\n"
"MOV R1, c[0x0][0x144];\n"
"MOV R2, c[2][0];"
"MOV R3, c[2][4];"
"MOV R4, c[2][8];" +
code +
"STG.E [R0], R2;\n"
"EXIT;\n",
value);
}
// https://forums.developer.nvidia.com/t/reverse-lut-for-lop3-lut/110651
// Emulate GPU's LOP3.LUT (three-input logic op with 8-bit truth table)
static uint32_t lop3_fast(uint32_t a, uint32_t b, uint32_t c, unsigned ttbl) {
uint32_t r = 0;
if (ttbl & 0x01) {
r |= ~a & ~b & ~c;
}
if (ttbl & 0x02) {
r |= ~a & ~b & c;
}
if (ttbl & 0x04) {
r |= ~a & b & ~c;
}
if (ttbl & 0x08) {
r |= ~a & b & c;
}
if (ttbl & 0x10) {
r |= a & ~b & ~c;
}
if (ttbl & 0x20) {
r |= a & ~b & c;
}
if (ttbl & 0x40) {
r |= a & b & ~c;
}
if (ttbl & 0x80) {
r |= a & b & c;
}
return r;
}
TEST_CASE("LOP3 Simple", "[shader]") {
static constexpr std::array TUPLES{
Tuple{0x81293021u, 0x12839145u, 0xde92c1a8u},
Tuple{0xa821838du, 0xccccccccu, 0x00000000u},
};
for (unsigned table = 0; table <= 0xff; ++table) {
for (const Tuple tuple : TUPLES) {
REQUIRE(Run(tuple, "LOP3.LUT R2, R2, R3, R4, " + std::to_string(table) + ';') ==
lop3_fast(tuple.a, tuple.b, tuple.c, table));
}
}
const Tuple cbuf{0x0fff, 0xff00, 0x0ff};
REQUIRE(Run(cbuf, "LOP3.LUT R2, R2, c[2][4], R4, 0x80;") ==
lop3_fast(cbuf.a, cbuf.b, cbuf.c, 0x80));
REQUIRE(Run(cbuf, "LOP3.LUT R2, R2, 0xff00, R4, 0x80;") ==
lop3_fast(cbuf.a, cbuf.b, cbuf.c, 0x80));
}
TEST_CASE("LOP3 Predicate", "[shader]") {
const Tuple value{1, 3, 5};
REQUIRE(Run(value, "LOP3.LUT.T P0, R2, R2, R3, R4, 0xff; @P0 MOV R2, 13;") == 13);
REQUIRE(Run(value, "LOP3.LUT.Z P0, R2, R2, R3, R4, 0; @P0 MOV R2, 14;") == 14);
REQUIRE(Run(value, "LOP3.LUT.NZ P0, R2, R2, R3, R4, 0xff; @P0 MOV R2, 15;") == 15);
}
| true |
1ba99af28b7bd30367b6af07d5042d538b6ca5dd | C++ | dendibakh/Algorithm-Tasks | /Coursera class/ComplexDataStructures/Graphs/ShortestPath/ShortestPath/TopologicalSort.h | UTF-8 | 558 | 2.640625 | 3 | [] | no_license | #pragma once
#include <queue>
#include <stack>
#include <vector>
#include "EWDiGraph.h"
namespace TpgSort
{
class TopologicalSort
{
void dfs(const EWDiGraph& graph, int v);
public:
typedef std::queue<int> ReversePostOrderContainer;
typedef std::stack<int> PostOrderContainer;
TopologicalSort(const EWDiGraph& graph);
ReversePostOrderContainer getReversePostOrder();
PostOrderContainer getPostOrder();
private:
const EWDiGraph& graph;
std::vector<bool> marked;
ReversePostOrderContainer rPostOrder;
PostOrderContainer PostOrder;
};
} | true |
484a281e600c12c0c692a80101c778dca985e0be | C++ | TIS2018-FMFI/visionlab-meraky | /Odčítavanie/Roi.cpp | UTF-8 | 4,068 | 2.75 | 3 | [] | no_license |
#include "Roi.h"
using namespace std;
Roi::Roi()
{
}
Roi::Roi(string roi_name, double& pos_x, double& pos_y, double& width, double& height, int PDM, string units, string typ)
{
name = roi_name;
x = pos_x;
y = pos_y;
this->width = width;
this->height = height;
this->PDM = PDM;
this->units = units;
this->typ = typ;
//values.reserve(100);
}
Roi::Roi(string roi_name, double& pos_x, double& pos_y, double& width, double& height, int PDM, string units, string typ, vector<double> points)
{
name = roi_name;
x = pos_x;
y = pos_y;
this->width = width;
this->height = height;
this->PDM = PDM;
this->units = units;
this->typ = typ;
int pom_poc = 0;
for (int i = 0; i < 6; i += 2) {
double pom_x = points.at(i);
double pom_y = points.at(i + 1);
addPoint(pom_x, pom_y, "bod"+ to_string(pom_poc));
pom_poc++;
}
//values.reserve(100);
cout << to_string(this->points.size()) + " body" << endl;
for (AnalogPoint p : this->points) {
cout << "X: " + to_string(p.getX()) + " Y:" + to_string(p.getY()) + " name: " + p.getName() << endl;
}
}
string Roi::getName() {
return name;
}
void Roi::setName(string new_name) {
this->name = new_name;
}
double Roi::getX()
{
return x;
}
double Roi::getY()
{
return y;
}
double Roi::getWidth()
{
return width;
}
double Roi::getHeight()
{
return height;
}
void Roi::setX(double x)
{
this->x = x;
}
void Roi::setY(double y)
{
this->y = y;
}
void Roi::setWidth(double width)
{
this->width = width;
}
void Roi::setHeight(double height)
{
this->height = height;
}
int Roi::getPDM()
{
return PDM;
}
void Roi::setPDM(int new_pdm)
{
this->PDM = new_pdm;
}
string Roi::getUnits()
{
return units;
}
void Roi::setUnits(string units)
{
this->units = units;
}
string Roi::getType()
{
return typ;
}
void Roi::setType(string type)
{
this->typ = type;
}
vector<AnalogPoint> Roi::getPoints()
{
return points;
}
void Roi::addPoint(double x, double y, string which)
{
points.push_back(AnalogPoint(x, y, which));
}
void Roi::removePoint(string ktory)
{
//po dohode ako sa urcity Point bude oznacovat
}
void Roi::removePoint(AnalogPoint bod)
{
//po dohode ako sa urcity Point bude oznacovat
}
void Roi::addValue(double& val)
{
this->values.push_back(val);
}
void Roi::writeToFile(ostream &ofile)
{
ofile << "[ROI]" << endl;
ofile << "roi_name: " + name << endl;
ofile << "x: " + to_string(x) << endl;
ofile << "y: " + to_string(y) << endl;
ofile << "width: " + to_string(width) << endl;
ofile << "height: " + to_string(height) << endl;
ofile << "pocet_desatinnych_miest: " + to_string(PDM) << endl;
ofile << "jednotky: " + units << endl;
ofile << "typ: " + typ << endl;
if (typ == "analog") {
ofile << "body: ";
ofile << "[";
int pom = 0;
for (AnalogPoint p : points) {
ofile << to_string(p.getX());
ofile << ",";
ofile << to_string(p.getY());
if (pom < 2) {
ofile << ",";
}
pom++;
}
ofile << "]" << endl;
}
ofile << endl;
}
double Roi::getMedian()
{
if (values.size() > 0) {
if (values.size() % 2 == 0) {
const auto median_it1 = values.begin() + values.size() / 2 - 1;
const auto median_it2 = values.begin() + values.size() / 2;
std::nth_element(values.begin(), median_it1, values.end());
const auto e1 = *median_it1;
std::nth_element(values.begin(), median_it2, values.end());
const auto e2 = *median_it2;
return (e1 + e2) / 2;
}
else {
const auto median_it = values.begin() + values.size() / 2;
std::nth_element(values.begin(), median_it, values.end());
return *median_it;
}
}
else return 0;
}
double Roi::getAverage()
{
double sum = 0;
for (double val : this->values) {
sum += val;
}
if (this->values.size() > 0) return sum / this->values.size();
else return 0;
}
void Roi::eraseValues()
{
values.clear();
}
| true |
5c4ca461fb6d2ed5b2948ce0136ddd9e274983ac | C++ | Ph0en1xGSeek/ACM | /TOJ/Vector.cpp | UTF-8 | 495 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int arr1[11], arr2[11];
int ca, d, ans;
scanf("%d", &ca);
while(ca--)
{
ans = 0;
scanf("%d", &d);
for(int i = 0; i < d; i++)
scanf("%d", &arr1[i]);
for(int i = 0; i < d; i++)
scanf("%d", &arr2[i]);
for(int i = 0; i < d; i++)
ans += arr1[i]*arr2[i];
printf("%d\n", ans);
}
return 0;
}
| true |
31f48a48a19ce07424c6ec3f84e576f1d7016a1a | C++ | avast/retdec | /src/fileinfo/file_information/file_information_types/dotnet_info.h | UTF-8 | 4,587 | 2.59375 | 3 | [
"MIT",
"Zlib",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"NCSA",
"WTFPL",
"BSL-1.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | /**
* @file src/fileinfo/file_information/file_information_types/dotnet_info.h
* @brief Information about .NET.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef FILEINFO_FILE_INFORMATION_FILE_INFORMATION_TYPES_DOTNET_INFO_H
#define FILEINFO_FILE_INFORMATION_FILE_INFORMATION_TYPES_DOTNET_INFO_H
#include <memory>
#include <string>
#include <vector>
#include "retdec/fileformat/types/dotnet_types/dotnet_class.h"
namespace retdec {
namespace fileinfo {
struct StreamInfo
{
std::uint64_t offset;
std::uint64_t size;
};
/**
* Class for information about .NET
*/
class DotnetInfo
{
private:
bool used;
std::string runtimeVersion;
std::uint64_t metadataHeaderAddress;
StreamInfo metadataStream;
StreamInfo stringStream;
StreamInfo blobStream;
StreamInfo guidStream;
StreamInfo userStringStream;
std::string moduleVersionId;
std::string typeLibId;
std::vector<std::shared_ptr<retdec::fileformat::DotnetClass>> definedClassList;
std::vector<std::shared_ptr<retdec::fileformat::DotnetClass>> importedClassList;
std::string typeRefHashCrc32;
std::string typeRefHashMd5;
std::string typeRefHashSha256;
public:
DotnetInfo();
/// @name Getters
/// @{
const std::string& getRuntimeVersion() const;
std::size_t getNumberOfImportedClasses() const;
std::string getImportedClassName(std::size_t position) const;
std::string getImportedClassNestedName(std::size_t position) const;
std::string getImportedClassNameWithParentClassIndex(std::size_t position) const;
std::string getImportedClassLibName(std::size_t position) const;
std::string getImportedClassNameSpace(std::size_t position) const;
bool getImportedClassIndex(std::size_t position, std::size_t &result) const;
const std::string& getTypeRefhashCrc32() const;
const std::string& getTypeRefhashMd5() const;
const std::string& getTypeRefhashSha256() const;
std::string getMetadataHeaderAddressStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getMetadataStreamOffsetStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getMetadataStreamSizeStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getStringStreamOffsetStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getStringStreamSizeStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getBlobStreamOffsetStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getBlobStreamSizeStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getGuidStreamOffsetStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getGuidStreamSizeStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getUserStringStreamOffsetStr(std::ios_base &(* format)(std::ios_base &)) const;
std::string getUserStringStreamSizeStr(std::ios_base &(* format)(std::ios_base &)) const;
const std::string& getModuleVersionId() const;
const std::string& getTypeLibId() const;
const std::vector<std::shared_ptr<retdec::fileformat::DotnetClass>>& getDefinedClassList() const;
const std::vector<std::shared_ptr<retdec::fileformat::DotnetClass>>& getImportedClassList() const;
/// @}
/// @name Setters
/// @{
void setUsed(bool set);
void setRuntimeVersion(std::uint64_t majorVersion, std::uint64_t minorVersion);
void setMetadataHeaderAddress(std::uint64_t address);
void setMetadataStreamInfo(std::uint64_t offset, std::uint64_t size);
void setStringStreamInfo(std::uint64_t offset, std::uint64_t size);
void setBlobStreamInfo(std::uint64_t offset, std::uint64_t size);
void setGuidStreamInfo(std::uint64_t offset, std::uint64_t size);
void setUserStringStreamInfo(std::uint64_t offset, std::uint64_t size);
void setModuleVersionId(const std::string& id);
void setTypeLibId(const std::string& id);
void setDefinedClassList(const std::vector<std::shared_ptr<retdec::fileformat::DotnetClass>>& dotnetClassList);
void setImportedClassList(const std::vector<std::shared_ptr<retdec::fileformat::DotnetClass>>& dotnetClassList);
void setTypeRefhashCrc32(const std::string& crc32);
void setTypeRefhashMd5(const std::string& md5);
void setTypeRefhashSha256(const std::string& sha256);
/// @}
/// @name Detection
/// @{
bool isUsed() const;
bool hasMetadataStream() const;
bool hasStringStream() const;
bool hasBlobStream() const;
bool hasGuidStream() const;
bool hasUserStringStream() const;
bool hasTypeLibId() const;
bool hasImportedClassListRecords() const;
/// @}
};
} // namespace fileinfo
} // namespace retdec
#endif
| true |
80920ded499482678ab49e0888949dc9175546f0 | C++ | xingfeT/c-practice | /day-001-100/day-016/problem-2/main.cpp | UTF-8 | 1,599 | 4.09375 | 4 | [] | no_license | /*
* Write a C program that displays the following prompts:
* "Enter the length of the swimming pool:"
* "Enter the width of the swimming pool:"
* "Enter the average depth of the swimming pool:"
*
* After each prompt is displayed, your program should use a scanf()
* function call to accept data from the keyboard for the displayed
* prompt. After the depth of the swimming pool is entered, your
* program should calculate and display the volume of the pool. The
* volumne should be included in an appropriate message and calcualated
* using the equation volume = length * width * average depth
*/
#include <stdio.h>
struct Pool
{
float Length;
float Width;
float AverageDepth;
float Volume;
};
inline Pool
CreatePool();
inline void
ComputePoolVolume(Pool *);
inline void
PrettyPrint(Pool *);
int
main(void)
{
Pool P = CreatePool();
ComputePoolVolume(&P);
PrettyPrint(&P);
return 0;
}
inline Pool
CreatePool()
{
float l = 0.0f, w = 0.0f, ad = 0.0f;
printf("Enter the length of the swimming pool:\n");
scanf("%f", &l);
printf("Enter the width of the swimming pool:\n");
scanf("%f", &w);
printf("Enter the average depth of the swimming pool:\n");
scanf("%f", &ad);
return Pool
{
l,
w,
ad,
0.0f,
};
}
inline void
ComputePoolVolume(Pool *p)
{
p->Volume = (p->Length * p->Width * p->AverageDepth);
}
inline void
PrettyPrint(Pool *p)
{
int x = 0;
printf("Pool Length: %.2f\n", p->Length);
printf("Pool Width: %.2f\n", p->Width);
printf("Pool Average Depth: %.2f\n", p->AverageDepth);
printf("Pool Volume: %.2f\n", p->Volume);
scanf("%d", &x);
}
| true |
9d1d8decf1291e05f63bc14e8454351ddc855c4e | C++ | julkifli/microbot_v12.2 | /microbot_v12.2_MOTORTEST/microbot_v12.2_Motor_Test.ino | UTF-8 | 1,226 | 2.640625 | 3 | [] | no_license | /*
MiCROBOT V12.2
Julkifli Awang Besar
C0d3 for Motor Test
Suite with MiCROBOT PCB.
*/
// Motor L
int dir1A = 4;
int dir2A = 9;
int pwmA = 5;
// Motor R
int dir1B = 7;
int dir2B = 8;
int pwmB = 6;
int sw = 12;
void setup()
{
pinMode(dir1A, OUTPUT);
pinMode(dir2A, OUTPUT);
pinMode(pwmA, OUTPUT);
pinMode(dir1B, OUTPUT);
pinMode(dir2B, OUTPUT);
pinMode(pwmB, OUTPUT);
pinMode(sw, INPUT_PULLUP);
}
void loop()
{
if (digitalRead(sw) == HIGH)
{
while (1)
{
digitalWrite(dir1A, LOW);
digitalWrite(dir2A, HIGH);
analogWrite(pwmA, 0);//0-255 for maxspeed
digitalWrite(dir1B, LOW);
digitalWrite(dir2B, HIGH);
analogWrite(pwmB, 0);//0-255 for maxspeed
delay(5000);
digitalWrite(dir1A, HIGH);
digitalWrite(dir2A, LOW);
analogWrite(pwmA, 0);//0-255 for maxspeed
digitalWrite(dir1B, HIGH);
digitalWrite(dir2B, LOW);
analogWrite(pwmB, 0);//0-255 for maxspeed
delay(5000);
digitalWrite(dir1A, LOW);
digitalWrite(dir2A, LOW);
analogWrite(pwmA, 0);//0-255 for maxspeed
digitalWrite(dir1B, LOW);
digitalWrite(dir2B, LOW);
analogWrite(pwmB, 0);//0-255 for maxspeed
while (1);
}
}
}
| true |
a436966cd2373f7874d02f79ea349fa96ab4c5e8 | C++ | rikigigi/sokoban-solver | /boxbomb.cpp | UTF-8 | 3,084 | 2.671875 | 3 | [] | no_license | #include "boxbomb.h"
#include <stack>
std::vector<BoxBombMove> BoxBombFrame::get_possible_moves(){
if (possible_moves_calculated)
return possible_moves;
possible_moves.clear();
std::stack<std::pair<ssize_t,ssize_t> > to_check;
to_check.push(pos);
aux.assign(lx*ly,false);
aux[idx(pos)]=true;
while (!to_check.empty()) {
auto posc = to_check.top();
to_check.pop();
for (auto & delta : move_list ){
std::pair<ssize_t,ssize_t> newpos{posc.first+delta.first,posc.second+delta.second};
if (newpos.first>=0&& newpos.first<lx && newpos.second>=0 && newpos.second<ly){
auto i=idx(newpos.first,newpos.second);
if (is_free(i) && !aux[i]){
aux[i]=true;
to_check.push(newpos);
} else if (!is_free(i)) {
//check if a move is possible
if (boxes[i] && !walls[i]) {
//check the next cell
std::pair<ssize_t,ssize_t> boxmovepos{newpos.first+delta.first, newpos.second+delta.second};
if (is_free(boxmovepos)) {
//this is a possible move
possible_moves.push_back({newpos,boxmovepos});
}
}
}
}
}
}
possible_moves_calculated=true;
return possible_moves;
}
std::vector<BoxBombFrame> BoxBombFrame::generate_possible_frames(){
std::vector<BoxBombFrame> res;
auto moves=get_possible_moves();
for (auto & m : moves) {
res.push_back(BoxBombFrame(*this));
res.back().apply_move(m);
}
return res;
}
std::vector<BoxBombFrame> BoxBombFrame::get_frames(const BoxBombFrame & initial)const {
std::vector<BoxBombFrame> res{initial};
for (auto & m : history) {
res.push_back(res.back());
res.back().apply_move(m);
}
return res;
}
void BoxBombFrame::print(std::ostream & out) const {
for (size_t y=0;y<ly;++y){
for (size_t x=0;x<lx;++x){
auto i = idx(x,y);
if (walls[i]) {
out << "# ";
} else if (idx(pos)==i) {
if (bombs[i]) {
out <<"X ";
} else {
out << "% ";
}
} else if (boxes[i]) {
if (bombs[i]) {
out << "O ";
} else {
out << "o ";
}
} else if (bombs[i]) {
out << "x ";
} else {
out << " ";
}
}
out << std::endl;
}
}
void BoxBombFrame::read(std::istream & in) {
for (size_t y=0;y<ly;++y){
for (size_t x=0;x<lx;++x){
auto i = idx(x,y);
bool t1,t2,t3;
in >> t1 >> t2 >> t3;
walls[i]=t1; bombs[i]=t2; boxes[i]=t3;
}
}
in >> pos.first >> pos.second;
invalidate();
get_possible_moves();
}
| true |
abb4ecd7b8823f404055ca24133bf387b45957a5 | C++ | STEllAR-GROUP/hpxla | /tests/std_complex_cblas_compatibility.cpp | UTF-8 | 1,080 | 2.9375 | 3 | [
"BSL-1.0"
] | permissive | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2012 Bryce Adelstein-Lelbach
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
#include <hpx/util/lightweight_test.hpp>
#include <complex>
/// The C interface for BLAS require complex numbers to be represented by
/// two floating point numbers of the same type that reside in a contiguous
/// block of memory, with the real part first and the imaginary second. This
/// test verifies that std::complex<> fulfills those requirements.
template <
typename T
>
void test()
{
std::complex<T> x(17.0, 42.0);
T* real = (T*) &x;
T* imag = ((T*) &x) + 1;
HPX_SANITY(real);
if (real)
HPX_TEST_EQ(17.0, *real);
HPX_SANITY(imag);
if (imag)
HPX_TEST_EQ(42.0, *imag);
}
int main()
{
test<float>();
test<double>();
return hpx::util::report_errors();
}
| true |
f5d8a9289e68e4d9d4eb79d2d5b50a057976d488 | C++ | swgeek/MacOpenGL | /02_redWindow/02_redWindow.cpp | UTF-8 | 712 | 2.828125 | 3 | [] | no_license |
// complile using: g++ 02_redWindow.cpp -o 02_redWindow -framework OpenGL -framework GLUT
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
void render(void)
{
// clear color buffer to the value set by glClearColor
glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
}
int main(int argc, char ** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500, 500);
glutCreateWindow("Simple Window");
glutDisplayFunc(render);
// glClearColor only sets state, does not actually clear anything
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
glutMainLoop();
return 1;
}
| true |
5ac1ba79b8670d985469a54b11b83cf80a3d9e05 | C++ | Adil-sc/Zoo-Tycoon | /Zoo.cpp | UTF-8 | 24,340 | 3.421875 | 3 | [] | no_license | /*********************************************************************
** Program Name: Project 2
** Author: Adil Chaudhry
** Date: 1/26/2019
** Description: Zoo.cpp holds the class functions for the Zoo class
*********************************************************************/
#include "Zoo.h"
/*********************************************************************
** Zoo Constructor
*********************************************************************/
Zoo::Zoo() {
//Sets current day to 1
currentDay = 1;
//Sets the bank balance to $100,000
bankBalance = 100000;
//Tigers dynamic array
tigerArray = new Tiger[tigerArraySize];
//Pengin dynamic array
penguinArray = new Penguin[penguinArraySize];
//Turtle dynamic array
turtleArray = new Turtle[turtleArraySize];
}
/*********************************************************************
** Destructor, deallocates memmory for the tiger, penguin, and turtle objects
*********************************************************************/
Zoo::~Zoo() {
delete[] tigerArray;
delete[] penguinArray;
delete[] turtleArray;
}
/*********************************************************************
** Starts the simulation, the majority of the simulation occurs here
*********************************************************************/
void Zoo::zooStart() {
cout << "---------------------------------------------------------------------------------------------"
<< std::endl;
cout << " ** Welcome to the Zoo game ** "
<< std::endl;
cout << "---------------------------------------------------------------------------------------------"
<< std::endl;
cout << "Bonus Extra Credit Implemented:" << std::endl;
cout << "1. Status messages: All random events are written and read from a file called RandomEvent.txt"
<< std::endl;
cout << "2. Different Feed Types: User is able to select different feed types" << std::endl;
cout << "---------------------------------------------------------------------------------------------"
<< std::endl;
cout << " " << std::endl;
//Variable to track if the user has quit the simulation
bool quitZoo = false;
//Variable to track the users choice of quitting or playing the game
int quitZooAnswer = 0;
//Variable to track if the choice of the user wanting to purchase an adult animal at the end of the day
int buyAdultAnimalChoice = 0;
//While loop that runs whole the game has not been quit AND the user has not run out of money
while (quitZoo == false && bankBalance >= 0) {
cout << "You have $" << bankBalance << " in the bank" << std::endl;
cout << "The Zoo has been open for " << currentDay << " day(s)" << std::endl;
//Function that calls the Zoo menu
zooMenu();
//Function that ages the animals
ageAnimals();
//Function that aks the user to select a feed type (Bonus)
bonusFeed();
//Function that handles calculating the feeding costs for the animals
feedAnimals();
//Function that decides on a random event to occur
randomEventOccurs();
//Profit calculation and summary happens here
cout << "--------------------------------------------------" << std::endl;
cout << "| Zoo Inventory Summary |" << std::endl;
cout << "--------------------------------------------------" << std::endl;
cout << "Number of tigers:" << numberOfTigers << std::endl;
cout << "Profit from tigers:" << numberOfTigers * tigerArray->getPayoff() << std::endl;
cout << "Number of penguins:" << numberOfPenguins << std::endl;
cout << "Profit from penguins:" << numberOfPenguins * penguinArray->getPayoff() << std::endl;
cout << "Number of turtles:" << numberOfTurtles << std::endl;
cout << "Profit from turtles:" << numberOfTurtles * turtleArray->getPayoff() << std::endl;
cout << " " << std::endl;
cout << "Food cost for the Zoo: " << foodCost << ", Feed Type: " << bonusFeedModifierType() << std::endl;
//Function that calcualts and displays the profit for the end of day
profitCalculation();
//If the bank balance is less than 0, the game ends
if (bankBalance < 0) {
cout << "Out of funds. The game is over" << std::endl;
quitZoo = true;
return;
}
//Asks the user if they want to buy an adult animal at the end of the day
cout << "Would you like to buy an Adult animal?" << std::endl;
cout << "1. Yes" << std::endl;
cout << "2. No" << std::endl;
cin >> buyAdultAnimalChoice;
isValidIntRange(buyAdultAnimalChoice, 1, 2, "");
switch (buyAdultAnimalChoice) {
case 1:
cout << "Which Animal would you like to buy?" << std::endl;
cout << "1. Tiger" << std::endl;
cout << "2. Penguin" << std::endl;
cout << "3. Turtle" << std::endl;
cin >> buyAdultAnimalChoice;
isValidIntRange(buyAdultAnimalChoice, 1, 3, "");
switch (buyAdultAnimalChoice) {
case 1:
numberOfTigers++;
resizeTigerArray();
tigerArray[numberOfTigers].setAge(3);
bankBalance -= tigerArray->getCost();
if (bankBalance < 0) {
cout << "Out of funds. The game is over" << std::endl;
quitZoo = true;
return;
}
break;
case 2:
numberOfPenguins++;
resizePenguinArray();
penguinArray[numberOfPenguins].setAge(3);
bankBalance -= penguinArray->getCost();
if (bankBalance < 0) {
cout << "Out of funds. The game is over" << std::endl;
quitZoo = true;
return;
}
break;
case 3:
numberOfTurtles++;
resizeTurtleArray();
turtleArray[numberOfTurtles].setAge(3);
bankBalance -= turtleArray->getCost();
if (bankBalance < 0) {
cout << "Out of funds. The game is over" << std::endl;
quitZoo = true;
return;
}
break;
}
break;
case 2:
break;
}
//Asks the user if they want to keep playing once the day is over
cout << "Do you want to keep playing?" << std::endl;
cout << "1. Yes" << std::endl;
cout << "2. No, quit game" << std::endl;
cin >> quitZooAnswer;
isValidIntRange(quitZooAnswer, 1, 2, "");
switch (quitZooAnswer) {
case 1:
quitZoo = false;
break;
case 2:
quitZoo = true;
break;
}
currentDay++;
}
}
/*********************************************************************
** Displays the initial menu asking users to buy animals
*********************************************************************/
void Zoo::zooMenu() {
cout << "How many Tigers do you want to buy [choose 1 to 2] [cost:$10,000]" << std::endl;
cin >> numberOfTigersBought;
isValidIntRange(numberOfTigersBought, 1, 2, "How many Tigers do you want to buy [choose 1 or 2] [cost:$10,000]");
//function to add tigers bought to array
addTiger(numberOfTigersBought);
cout << "How many Penguins do you want to buy [choose 1 to 2] [cost:$1000]" << std::endl;
cin >> numberOfPenguinsBought;
isValidIntRange(numberOfPenguinsBought, 1, 2, "How many Penguins do you want to buy [choose 1 to 2] [cost:$1000]");
//function to add penguiins bought to array
addPenguin(numberOfPenguinsBought);
cout << "How many Tutrles do you want to buy [choose 1 to 2] [cost:$100]" << std::endl;
cin >> numberOfTurtlesBought;
isValidIntRange(numberOfTurtlesBought, 1, 2, "\"How many Tutrles do you want to buy [choose 1 to 2] [cost:$100]");
//function to add tutrles bought to array
addTurtle(numberOfTurtlesBought);
}
/*********************************************************************
** Function that deals with aging the animals
*********************************************************************/
void Zoo::ageAnimals() {
//Age tiger
for (int i = 0; i < numberOfTigers; i++) {
tigerArray[i].setAge(tigerArray[i].getAge() + 1);
}
//Age Penguines
for (int i = 0; i < numberOfPenguins; i++) {
penguinArray[i].setAge(penguinArray[i].getAge() + 1);
}
//Age for Turtles
for (int i = 0; i < numberOfTurtles; i++) {
turtleArray[i].setAge(turtleArray[i].getAge() + 1);
}
}
/*********************************************************************
** Function that deals with calculating the feed cost for each animal and subtracting it from the bank balance
*********************************************************************/
void Zoo::feedAnimals() {
//If the number of tigers in the zoo are greater than 0, feed them.
if (numberOfTigers > 0) {
foodCost += (tigerArray->getBaseFoodCost() * bonusFeedModifier) * numberOfTigers;
}
if (numberOfPenguins > 0) {
foodCost += (penguinArray->getBaseFoodCost() * bonusFeedModifier) * numberOfPenguins;
}
if (numberOfTurtles > 0) {
foodCost += (turtleArray->getBaseFoodCost() * bonusFeedModifier) * numberOfTurtles;
}
// cout<<"Food cost for the zoo: "<<foodCost<<std::endl;
bankBalance -= foodCost;
}
/*********************************************************************
** Bonus Function that allows a user to select a varifty of feed choices
*********************************************************************/
void Zoo::bonusFeed() {
int feedSelection = 0;
cout << "Select the quality of Feed you want to give to your animals" << std::endl;
cout << "1. Cheap" << std::endl;
cout << "2. Generic" << std::endl;
cout << "3. Premium" << std::endl;
cin >> feedSelection;
isValidIntRange(feedSelection, 1, 3, "");
switch (feedSelection) {
case 1:
//Sets food cost to be half the base food cost
bonusFeedModifier = 0.5;
break;
case 2:
//Sets food cost to be the normal base food cost
bonusFeedModifier = 1;
break;
case 3:
//Sets the food cost to be twice as expensive as the base food cost
bonusFeedModifier = 2;
break;
}
}
/*********************************************************************
** Function that returns the current selected Feed varity
*********************************************************************/
string Zoo::bonusFeedModifierType() {
string st;
if (bonusFeedModifier == 0.5) {
st = "Cheap";
} else if (bonusFeedModifier == 1) {
st = "Generic";
} else if (bonusFeedModifier == 2) {
st = "Premium";
}
return st;
}
/*********************************************************************
** addTiger, addPenguin, addTurtle functions deal with addign new animals to the Zoo and resizing the array accordingly
*********************************************************************/
//Adds the number of tigers bought to the numberOfTigers variable to keep track of them. Then subtracts the current bank balance by the cost of the tigers purchased.
void Zoo::addTiger(int tigers_bought) {
setNumerOfTigers(getNumberOfTigers() + tigers_bought);
resizeTigerArray();
bankBalance -= tigerArray->getCost() * tigers_bought;
}
//Adds the number of penguins bought to the numberOfPenguins variable to keep track of them. Then subtracts the current bank balance by the cost of the penguins purchased.
void Zoo::addPenguin(int penguins_bought) {
setNumberOfPenguins(getNumberOfPenguins() + penguins_bought);
resizePenguinArray();
bankBalance -= penguinArray->getCost() * penguins_bought;
}
//Adds the number of turtles bought to the numberOfTurtles variable to keep track of them. Then subtracts the current bank balance by the cost of the turtles purchased.
void Zoo::addTurtle(int turtles_bought) {
setNumberOfTurtles(getNumberOfTurtles() + turtles_bought);
resizeTurtleArray();
bankBalance -= turtleArray->getCost() * turtles_bought;
}
/*********************************************************************
** Function to resize Tiger Array
*********************************************************************/
void Zoo::resizeTigerArray() {
if (getNumberOfTigers() > (tigerArraySize - 1)) {
//Make temp array to hold new array
Tiger *tempArray = new Tiger[2 * tigerArraySize];
memcpy(tempArray, tigerArray, tigerArraySize * 2);
delete[]tigerArray;
tigerArraySize *= 2;
tigerArray = tempArray;
}
}
/*********************************************************************
** Function to resize Penguin Array
*********************************************************************/
void Zoo::resizePenguinArray() {
if (getNumberOfPenguins() > (penguinArraySize - 1)) {
//Make temp array to hold new array
Penguin *tempArray = new Penguin[2 * penguinArraySize];
memcpy(tempArray, penguinArray, penguinArraySize * 2);
delete[]penguinArray;
penguinArraySize *= 2;
penguinArray = tempArray;
}
}
/*********************************************************************
** Function to resize Turtle Array
*********************************************************************/
void Zoo::resizeTurtleArray() {
if (getNumberOfTurtles() > (turtleArraySize - 1)) {
//Make temp array to hold new array
Turtle *tempArray = new Turtle[2 * turtleArraySize];
std::memcpy(tempArray, turtleArray, turtleArraySize * 2);
delete[]turtleArray;
turtleArraySize *= 2;
turtleArray = tempArray;
}
}
/*********************************************************************
** Function that generats a random event in which one animal gets sick
*********************************************************************/
void Zoo::randomEventSickness() {
//Randomly select a value from 1-3, which represetns the 3 animals we have.
int randomAnimalToKill = rand() % 3 + 1;
switch (randomAnimalToKill) {
case 1:
//Find the last element in the tiger array, and set its age to 0;
tigerArray[numberOfTigers - 1].setAge(0);
numberOfTigers--;
bonusWriteRandomEventToFile("Oh dear! One of your tigers has gotten sick and has died");
bonusReadRandomEventFromFile();
break;
case 2:
penguinArray[numberOfPenguins - 1].setAge(0);
numberOfPenguins--;
bonusWriteRandomEventToFile("Oh dear! One of your penguins has gotten sick and has died");
bonusReadRandomEventFromFile();
break;
case 3:
turtleArray[numberOfTurtles - 1].setAge(0);
numberOfTurtles--;
bonusWriteRandomEventToFile("Oh dear! One of your turtles has gotten sick and has died");
bonusReadRandomEventFromFile();
break;
}
}
/*********************************************************************
** Function that generates a random event in which the Zoo experiences a boom
*********************************************************************/
void Zoo::randomEventBoomAttendance() {
double randomBonus = rand() % 500 + 250;
for (int i = 0; i < numberOfTigers; i++) {
zooBoomPayoff += randomBonus;
}
bonusWriteRandomEventToFile(
"Attendance boom at the Zoo! Each tiger gets a bonus of $" + std::to_string(randomBonus) + "\n" +
"You've earned an additional $" + std::to_string(zooBoomPayoff) + " dollars");
bonusReadRandomEventFromFile();
bankBalance += zooBoomPayoff;
}
/*********************************************************************
** Function that generates a random event in which a new animal is born
*********************************************************************/
void Zoo::randomEventBirth() {
int randomAnimalIsBorn = rand() % 3 + 1;
bool animalIsAdult = false;
int counter = 0;
switch (randomAnimalIsBorn) {
case 1:
while ((animalIsAdult == false && counter < numberOfTigers)) {
//Check if the animal is over the age of 3, if so, add it to the Zoo
if (tigerArray[0].getAge() >= 3) {
addTiger(tigerArray->getNumberOfBabies());
bonusWriteRandomEventToFile("A baby Tiger was born!");
bonusReadRandomEventFromFile();
animalIsAdult = true;
}
counter++;
}
break;
case 2:
while (animalIsAdult == false && counter < numberOfPenguins) {
if (penguinArray[0].getAge() >= 3) {
addPenguin(penguinArray->getNumberOfBabies());
bonusWriteRandomEventToFile("5 baby Penguins were born!");
bonusReadRandomEventFromFile();
animalIsAdult = true;
}
counter++;
}
break;
case 3:
while (animalIsAdult == false && counter < numberOfTurtles) {
if (turtleArray[0].getAge() >= 3) {
addTurtle(turtleArray->getNumberOfBabies());
bonusWriteRandomEventToFile("10 baby Turtles were born!");
bonusReadRandomEventFromFile();
animalIsAdult = true;
}
counter++;
}
break;
default:
cout << "No animal old enough to give birth" << std::endl;
break;
}
if (animalIsAdult == false) {
// cout << "No animals old enough to give birth" << std::endl;
bonusWriteRandomEventToFile("No animals old enough to give birth");
bonusReadRandomEventFromFile();
}
}
/*********************************************************************
** Function that randomly determins which event will occur
*********************************************************************/
void Zoo::randomEventOccurs() {
//Random seed
srand((time(0)));
//Randomly select a random event to conduct
int randomEventArray[4] = {1, 2, 3, 4};
int randIndex = rand() % 4;
int randomEvent = randomEventArray[randIndex];
//Sickness twice as likely to occur. Original chance of sickness occuring is 25%, now it will be 50%
if (bonusFeedModifier == 0.5) {
int randomEventArray[6] = {1, 1, 1, 2, 3, 4};
int randIndex = rand() % 6;
int randomEvent = randomEventArray[randIndex];
}
//Sickness half as likely to occur. Originally chance of sickness occuring is 25%, now it will be 12.5%. Slight increase in the chance of nothing happening is one drawback here
if (bonusFeedModifier == 2) {
int randomEventArray[8] = {1, 2, 2, 3, 3, 4, 4, 4};
int randIndex = rand() % 8;
int randomEvent = randomEventArray[randIndex];
}
switch (randomEvent) {
case 1:
cout << "--------------------------------------------------" << std::endl;
cout << "| Random event: SICKNESS OCCURS |" << std::endl;
cout << "--------------------------------------------------" << std::endl;
randomEventSickness();
break;
case 2:
cout << "--------------------------------------------------" << std::endl;
cout << "| Random event: BOOM IN ZOO ATTENDENCE |" << std::endl;
cout << "--------------------------------------------------" << std::endl;
randomEventBoomAttendance();
break;
case 3:
cout << "--------------------------------------------------" << std::endl;
cout << "| Random event: BABY IS BORN |" << std::endl;
cout << "--------------------------------------------------" << std::endl;
randomEventBirth();
break;
case 4:
cout << "--------------------------------------------------" << std::endl;
cout << "| Random event: NONE |" << std::endl;
cout << "--------------------------------------------------" << std::endl;
bonusWriteRandomEventToFile(" ");
bonusReadRandomEventFromFile();
break;
}
}
/*********************************************************************
** Function that calculates and summarizes the profit at the end of the day
*********************************************************************/
void Zoo::profitCalculation() {
newProfit = (numberOfTigers * tigerArray->getPayoff() + numberOfPenguins * penguinArray->getPayoff() +
numberOfTurtles * turtleArray->getPayoff());
double endOfDayBalance = bankBalance + newProfit;
cout << "--------------------------------------------------" << std::endl;
cout << "| END OF DAY PROFIT SUMMARY |" << std::endl;
cout << "--------------------------------------------------" << std::endl;
cout << "Total profit at end of day: " << newProfit + zooBoomPayoff << std::endl;
cout << "Balance before new profit:" << bankBalance << std::endl;
cout << "Balance with new profit: " << endOfDayBalance << std::endl;
cout << " " << std::endl;
bankBalance = endOfDayBalance;
zooBoomPayoff = 0;
}
/*********************************************************************
** Function that deals with writing the random event to a file
*********************************************************************/
void Zoo::bonusWriteRandomEventToFile(string s) {
ofstream outf("RandomEvent.txt", std::ios::trunc);
if (!outf) {
cout << "Unable to open or find RandomEvent.txt" << std::endl;
return;
}
outf << s << std::endl;
outf.close();
}
/*********************************************************************
** Function that deals with reading the random event from a file
*********************************************************************/
void Zoo::bonusReadRandomEventFromFile() {
ifstream inf("RandomEvent.txt");
if (!inf) {
cout << "Could not open or read file RandomEvent.txt" << std::endl;
return;
}
while (inf) {
string strInput;
getline(inf, strInput);
cout << strInput << std::endl;
}
inf.close();
}
/*********************************************************************
** Setters
*********************************************************************/
void Zoo::setNumerOfTigers(int numberOfTigers) {
this->numberOfTigers = numberOfTigers;
}
void Zoo::setNumberOfPenguins(int numberOfPenguins) {
this->numberOfPenguins = numberOfPenguins;
}
void Zoo::setNumberOfTurtles(int numberOfTurtles) {
this->numberOfTurtles = numberOfTurtles;
}
void Zoo::setBankBalance(double bankBalance) {
this->bankBalance = bankBalance;
}
/*********************************************************************
** Getters
*********************************************************************/
int Zoo::getNumberOfTigers() {
return numberOfTigers;
}
int Zoo::getNumberOfPenguins() {
return numberOfPenguins;
}
int Zoo::getNumberOfTurtles() {
return numberOfTurtles;
}
int Zoo::getBankBalance() {
return bankBalance;
}
| true |
6346c38896bd753d9b73333b4b2ff4012f0a8bd2 | C++ | its-sachin/InterviewBit | /Linkedlist/revList.cpp | UTF-8 | 592 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
//typedef long long int;
#define inf 1e18
#define mod 1000000007
#define pb push_back
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* A) {
ListNode* c = A;
if(c==nullptr)
return nullptr;
ListNode* next = c->next;
c->next = nullptr;
while(next!=nullptr){
ListNode* temp = next->next;
next->next = c;
c= next;
next = temp;
}
return c;
}
int main(int argc, char const *argv[])
{
return 0;
} | true |
92683c66fc6cdef9acc0f4c7d91b8c86bb044ebf | C++ | turfnima/cppPractice | /hitEffect.cpp | WINDOWS-1252 | 3,435 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<random>
#include<string>
//Xiaozhi Li
// 2017/11/5
//code for fun...
//my cousin was playing a game Onmyouji
// he asks if anyone can calculate the hit effect of a char.
//so the char casts a snow storm, apply on hit effects three times,
//each time,there is freeze, slow, and additional freeze from item.
//the freeze rate was 8 percent, slow rate was 16 percent, and additional freeze rate from item is 12 percent.
//if an enemy is slowed, the chance of him or her getting frozen raises 10% (multiply)
//his char has a 102% hit ratio, which means all the on hit effect will apply to this.
//so my cousin wants to know for 5 enemies getting hit, what are the chances of 1, 2 ,3,4 ,and 5 enemies getting frozen.
//I hate to calculate it with binomial distribution, so I wrote this code.
using namespace std;
class enemy {
public:
bool frozen;
bool slowed;
//constructor
enemy() {
frozen = false;
slowed = false;
}
//initialize
void initialize() {
frozen = false;
slowed = false;
}
bool testFrozen(int frate, bool slowed) {
return false;
}
bool testSlowed(int srate) {
return false;
}
void printCondition() {
cout << "slowed:" << slowed;
cout << " frozen: " << frozen << endl;
}
enemy& operator=(const enemy& b) {
frozen = b.frozen;
slowed = b.slowed;
}
};
//functions:
bool freezeOrNot(enemy &e, int frate) ;
bool slowOrNot(enemy &e, int srate);
// ~functions
int main() {
//first we set the freeze rate, slow rate, armor effect:
int frate = 8;
int srate = 16;
int aeffect = 12;
int hits = 3;
double hitRatio = 1.02;
//then we create an enemy
cout << "slow rate:";
cout << srate;
cout << " freeze rate: ";
cout << frate;
cout << " armor effect: ";
cout << aeffect;
enemy ass[5];
//then we do tests
int tests = 1000000;
double sum[6];
for (int i = 0; i < 6; i++) sum[i] = 0;
for (int i = 0; i < tests; i++) {
//we initialize ass
for(int i=0;i<5;i++) ass[i].initialize();
//every 3 strikes
for(int j=0; j<hits; j++){
//calculate for each person
for(int p=0;p<5;p++){
//first apply freeze chance
freezeOrNot(ass[p], frate);
//then apply armor freeze chance
freezeOrNot(ass[p], aeffect);
// then apply slow
slowOrNot(ass[p], srate);
}
}
//calculate how many was frozen:
int nums = 0;
for (int i = 0; i < 5; i++) {
if (ass[i].frozen) nums += 1;
}
sum[nums]++;
}
for(int i=0;i<6;i++){
double k = sum[i] / tests * 100;
cout <<endl<< i << "˱ʣ ";
cout<< k;
cout << "/100" << endl;
}
getchar();
getchar();
return 0;
}
bool freezeOrNot(enemy &e, int frate) {
//if enemy is already frozen, return
if (e.frozen) { return true; }
else {
//if enemy is slowed, apply additional frate namely 10%
if (e.slowed) {
int k = rand() % 101;
if (k <= frate*1.1*1.02) {
//cout << "slowed, freezed "<<endl;
e.frozen = true;
return true;
}
else return false;
}
//if enemy is not slowed, apply normal freeze rate
else {
int k = rand() % 101;
if (k <= frate*1.02) {
//cout << "not slowed, freezed"<<endl;
e.frozen = true;
return true;
}
else return false;
}
}
return false;
}
bool slowOrNot(enemy &e, int srate) {
if (e.slowed) { return true; }
else {
int k = rand() % 101;
if (k <= srate) {
//cout << "slowed" << endl;
e.slowed = true;
return true;
}
}
return false;
} | true |
e797fea75cade9b4ed2f9ee3fc187b0236496436 | C++ | RaoMiao/freestyle | /RakNet/Include/InternalPacketPool.h | UTF-8 | 2,488 | 2.65625 | 3 | [] | no_license | /* -*- mode: c++; c-file-style: raknet; tab-always-indent: nil; -*- */
/**
* @file
* @brief Internal Packet Pool Class Declaration.
*
* This file is part of RakNet Copyright 2003, 2004
* Rakkarsoft LLC and Kevin Jenkins.
*
* Usage of Raknet is subject to the appropriate licence agreement.
* "Shareware" Licensees with Rakkarsoft LLC are subject to the
* shareware license found at
* http://www.rakkarsoft.com/shareWareLicense.html which you agreed to
* upon purchase of a "Shareware license" "Commercial" Licensees with
* Rakkarsoft LLC are subject to the commercial license found at
* http://www.rakkarsoft.com/sourceCodeLicense.html which you agreed
* to upon purchase of a "Commercial license" All other users are
* subject to the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Refer to the appropriate license agreement for distribution,
* modification, and warranty rights.
*/
#ifndef __INTERNAL_PACKET_POOL
#define __INTERNAL_PACKET_POOL
#include "SimpleMutex.h"
#include "Queue.h"
#include "InternalPacket.h"
/**
* @brief Manage Internal Packet using pools.
*
* This class provide memory management for packets used internaly in RakNet.
* @see PacketPool
*
* @note Implement Singleton Pattern
*
*/
class InternalPacketPool
{
public:
/**
* Constructor
*/
InternalPacketPool();
/**
* Destructor
*/
~InternalPacketPool();
/**
* Retrieve a new InternalPacket instance.
* @return a pointer to an InternalPacket structure.
*/
InternalPacket* GetPointer( void );
/**
* Free am InternalPacket instance
* @param p a pointer to the InternalPacket instance.
*/
void ReleasePointer( InternalPacket *p );
/**
* Clear the pool
*/
void ClearPool( void );
/**
* static function because only static functions can access static members
* @return the unique instance of the class InternalPacketPool.
*
* @note Singleton pattern unique instance access function.
*
*/
static inline InternalPacketPool* Instance()
{
return & I;
}
private:
/**
* Unique Instance
*/
static InternalPacketPool I;
/**
* InternalPacket pool
*/
BasicDataStructures::Queue<InternalPacket*> pool;
/**
* Multithread access management
*/
SimpleMutex poolMutex;
#ifdef _DEBUG
/**
* Used in debugging stage to monitor the number of internal packet released.
*/
int packetsReleased;
#endif
};
#endif
| true |
3e3116d8ea0563f2ed6ab0c0f9481c382e35ccbd | C++ | xhdhr10000/alg | /2/heap.h | UTF-8 | 930 | 3.5625 | 4 | [] | no_license | class Heap {
protected:
int *h;
int s;
int p;
public:
Heap(int size) {
this->h = (int*)malloc(sizeof(int)*(size+1));
this->s = size;
this->p = 0;
}
~Heap() {
free(this->h);
}
void push(int item) {
if (this->p + 1 > this->s) {
this->s *= 2;
this->h = (int*)realloc(this->h, sizeof(int)*this->s);
}
this->h[++this->p] = item;
int p = this->p;
while (p > 1 && this->h[p] < this->h[p/2]) {
this->swap(p, p/2);
p /= 2;
}
}
int pop() {
int ret = this->h[1];
this->h[1] = this->h[this->p--];
int p = 1;
while (p*2+1 < this->p && (this->h[p] > this->h[p*2] || this->h[p] > this->h[p*2+1])) {
if (p*2+1 >= this->p || this->h[p*2] < this->h[p*2+1]) {
this->swap(p, p*2);
p *= 2;
} else {
this->swap(p, p*2+1);
p = p*2+1;
}
}
return ret;
}
protected:
void swap(int x, int y) {
int c;
c = this->h[x];
this->h[x] = this->h[y];
this->h[y] = c;
}
};
| true |
fac1dabc60fc1f640b0d0b970d64098ea24e720f | C++ | HxTenshi/GraduationProject | /engine/TenshiEngine/Source/Library/easing.h | SHIFT_JIS | 5,387 | 3.46875 | 3 | [] | no_license | #pragma once
//http://easings.net/ja
//C[WO
namespace Easing
{
inline double InQuad(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
return max*t*t + min;
}
inline double OutQuad(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
return -max*t*(t - 2) + min;
}
inline double InOutQuad(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
if (t / 2 < 1)
return max / 2 * t * t + min;
--t;
return -max * (t * (t - 2) - 1) + min;
}
inline double InCubic(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
return max * t*t*t + min;
}
inline double OutCubic(double t, double totaltime, double max, double min)
{
max -= min;
t = t / totaltime - 1;
return max * (t*t*t + 1) + min;
}
inline double InOutCubic(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
if (t / 2 < 1)
return max / 2 * t*t*t + min;
t -= 2;
return max / 2 * (t*t*t + 2) + min;
}
inline double InQuart(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
return max * t*t*t*t + min;
}
inline double OutQuart(double t, double totaltime, double max, double min)
{
max -= min;
t = t / totaltime - 1;
return -max*(t*t*t*t - 1) + min;
}
inline double InOutQuart(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
if (t / 2 < 1)
return max / 2 * t*t*t*t + min;
t -= 2;
return -max / 2 * (t*t*t*t - 2) + min;
}
inline double InQuint(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
return max*t*t*t*t*t + min;
}
inline double OutQuint(double t, double totaltime, double max, double min)
{
max -= min;
t = t / totaltime - 1;
return max*(t*t*t*t*t + 1) + min;
}
inline double InOutQuint(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
if (t / 2 < 1)
return max / 2 * t*t*t*t*t + min;
t -= 2;
return max / 2 * (t*t*t*t*t + 2) + min;
}
inline double InSine(double t, double totaltime, double max, double min)
{
max -= min;
return -max*cos(t*1.570796326794896 / totaltime) + max + min;
}
inline double OutSine(double t, double totaltime, double max, double min)
{
max -= min;
return max * sin(t*1.570796326794896 / totaltime) + min;
}
inline double InOutSine(double t, double totaltime, double max, double min)
{
max -= min;
return -max / 2 * (cos(t*3.141592653589793 / totaltime) - 1) + min;
}
inline double InExp(double t, double totaltime, double max, double min)
{
max -= min;
return t == 0.0 ? min : max*pow(2, 10 * (t / totaltime - 1)) + min;
}
inline double OutExp(double t, double totaltime, double max, double min)
{
max -= min;
return t == totaltime ? max + min : max*(-pow(2, -10 * t / totaltime) + 1) + min;
}
inline double InOutExp(double t, double totaltime, double max, double min)
{
if (t == 0) return min;
if (t == totaltime) return max;
totaltime /= 2;
t /= totaltime;
max -= min;
if (t < 1) return max/2 * pow(2, 10 * (t - 1)) + min;
return max/2 * (-pow(2, -10 * --t) + 2) + min;
}
inline double InCirc(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
return -max*(sqrt(1 - t*t) - 1) + min;
}
inline double OutCirc(double t, double totaltime, double max, double min)
{
max -= min;
t = t / totaltime - 1;
return max*sqrt(1 - t*t) + min;
}
inline double InOutCirc(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
if (t / 2 < 1)
return -max / 2 * (sqrt(1 - t*t) - 1) + min;
t -= 2;
return max / 2 * (sqrt(1 - t*t) + 1) + min;
}
inline double InBack(double t, double totaltime, double max, double min, double s)
{
max -= min;
t /= totaltime;
return max*t*t*((s + 1)*t - s) + min;
}
inline double OutBack(double t, double totaltime, double max, double min, double s)
{
max -= min;
t = t / totaltime - 1;
return max*(t*t*((s + 1)*t*s) + 1) + min;
}
inline double InOutBack(double t, double totaltime, double max, double min, double s)
{
(void)totaltime;
max -= min;
s *= 1.525;
if (t / 2 < 1)
{
return max*(t*t*((s + 1)*t - s)) + min;
}
t -= 2;
return max / 2 * (t*t*((s + 1)*t + s) + 2) + min;
}
inline double OutBounce(double t, double totaltime, double max, double min)
{
max -= min;
t /= totaltime;
if (t < 1 / 2.75)
return max*(7.5625*t*t) + min;
else if (t < 2 / 2.75)
{
t -= 1.5 / 2.75;
return max*(7.5625*t*t + 0.75) + min;
}
else if (t< 2.5 / 2.75)
{
t -= 2.25 / 2.75;
return max*(7.5625*t*t + 0.9375) + min;
}
else
{
t -= 2.625 / 2.75;
return max*(7.5625*t*t + 0.984375) + min;
}
}
inline double InBounce(double t, double totaltime, double max, double min)
{
return max - OutBounce(totaltime - t, totaltime, max - min, 0) + min;
}
inline double InOutBounce(double t, double totaltime, double max, double min)
{
if (t < totaltime / 2)
return InBounce(t * 2, totaltime, max - min, max)*0.5 + min;
else
return OutBounce(t * 2 - totaltime, totaltime, max - min, 0)*0.5 + min + (max - min)*0.5;
}
inline double Linear(double t, double totaltime, double max, double min)
{
return (max - min)*t / totaltime + min;
}
} | true |
6a3e018847aaa992712e2afb58cb88209b36b21c | C++ | springtiger/GraphicsRoi | /GraphicsRoiLib/graphicsRoiPolygon.cpp | UTF-8 | 11,102 | 2.609375 | 3 | [] | no_license | #include "graphicsRoiPolygon.h"
#include <QEvent>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include <QGraphicsScene>
GraphicsRoiPolygon::GraphicsRoiPolygon(QGraphicsObject *parent)
: GraphicsItemPolygon(parent)
, IRoi(this)
{
init();
}
GraphicsRoiPolygon::GraphicsRoiPolygon(const QPolygonF &polygon, QGraphicsObject *parent)
: GraphicsItemPolygon(polygon, parent)
, IRoi(this)
{
init();
setPolygon(polygon);
}
void GraphicsRoiPolygon::setPolygon(const QPolygonF &polygon)
{
GraphicsItemPolygon::setPolygon(polygon);
}
void GraphicsRoiPolygon::append(const QPointF &p)
{
if(polygon().size() != 1 && polygon().isClosed()) // 已封闭的轮廓不可再添加。一个点时,必然是Closed所以必须去掉这种情况
return;
if(polygon().size() > 0 && polygon().last() == p) // 忽略重复点
return;
// 先将数据添加到QPolygonF
GraphicsItemPolygon::append(p);
// 完成Line,设置P2
if (m_lineItems.size() > 0)
m_lineItems.last()->setP2(p);
if (polygon().size() == 1 || !polygon().isClosed()) // 第一个点必然添加;polygon不封闭才添加Line
{
// 添加Line
m_lineItems.append(new GraphicsPolyLine(this)); // 添加Line时,设置P1
// 注册事件处理
m_lineItems.last()->installSceneEventFilter(this);
// 设置Line点
m_lineItems.last()->setP1(p);
m_lineItems.last()->setP2(p);
// 添加Anchor
m_anchors.append(new GraphicsAnchor(this, m_anchors.size()));
m_anchors.last()->setPenColor(m_anchors.size() == 1 ? m_firstAnchorBordeColor : m_colorAnchorBorde);
m_anchors.last()->setBrushColor(m_anchors.size() == 1 ? m_firstAnchorFillColor : m_colorAnchorFill);
}
if (polygon().isClosed() && polygon().size() != 1)
emit polygonClosed();
// 设置变换原点
setTransformOriginPoint(this->boundingRect().center());
}
void GraphicsRoiPolygon::insert(int i, const QPointF &p)
{
if (!polygon().isClosed()) // 没有封闭的polygon不可以insert
return;
qDebug() << "GraphicsPolygonItem::insert";
// 在封闭轮廓的末尾追加
if (i < 0 || i >= polygon().size())
{
qDebug() << "GraphicsPolygonItem::insert out of range" << i << polygon().size();
return;
}
// 先将数据添加到QPolygonF
GraphicsItemPolygon::insert(i+1, p);
// 修改前一条Line的P2
QPointF p2 = m_lineItems[i]->line().p2();
m_lineItems[i]->setP2(p);
// 添加Line
m_lineItems.insert(i+1, new GraphicsPolyLine(QLineF(p, p2), this));
// 注册事件处理
m_lineItems[i+1]->installSceneEventFilter(this);
// 添加Anchor
m_anchors.insert(i+1, new GraphicsAnchor(this, i+1));
m_anchors[i+1]->setPenColor(m_colorAnchorBorde);
m_anchors[i+1]->setBrushColor (m_colorAnchorFill );
// 使Anchor调整编号
for (int j = i+2; j < m_anchors.size(); j++)
{
m_anchors[j]->setPolyIndex(j);
}
// 设置变换原点
setTransformOriginPoint(this->boundingRect().center());
}
void GraphicsRoiPolygon::updatePos(int i, const QPointF &p)
{
// qDebug() << "GraphicsPolygonRoi::updatePos";
if (!polygon().isClosed()) // 没有封闭的polygon不可以更新位置
return;
//
GraphicsItemPolygon::updatePos(i, p);
if (i == 0)
GraphicsItemPolygon::updatePos(polygon().size()-1, p);
// 更新Line位置
m_lineItems[(i-1+m_lineItems.size())%m_lineItems.size()]->setP2(p);
m_lineItems[i]->setP1(p);
// Anchor自身会更新位置,再次无需设置
// 设置变换原点
setTransformOriginPoint(this->boundingRect().center());
}
void GraphicsRoiPolygon::remove(int i)
{
if (!polygon().isClosed()) // 没有封闭的polygon不可以
return;
if (polygon().size() <= 4) // 最少4个点,否则不允许删除
return;
if (i < 0 || i >= polygon().size()) // 索引超出范围
return;
if (i == 0 || i == polygon().size()-1)
{
GraphicsItemPolygon::remove(0);
GraphicsItemPolygon::remove(polygon().size()-1);
GraphicsItemPolygon::append(polygon().first());
}
else
{
GraphicsItemPolygon::remove(i);
}
delete m_anchors[i];
m_anchors.remove(i);
for (int j = i; j < m_anchors.size(); j++)
{
m_anchors[j]->setPolyIndex(j);
}
m_lineItems[(i-1+m_lineItems.size())%m_lineItems.size()]->setP2(m_lineItems[i]->line().p2());
delete m_lineItems[i];
m_lineItems.remove(i);
}
void GraphicsRoiPolygon::setAnchorBordeColor(const QColor &color)
{
m_colorAnchorBorde = color;
foreach (GraphicsAnchor* anchor, m_anchors) {
anchor->setPenColor(!polygon().isClosed() && anchor->polyIndex() ==0 ? m_firstAnchorBordeColor : color);
}
}
void GraphicsRoiPolygon::setAnchorFillColor(const QColor &color)
{
m_colorAnchorFill = color;
foreach (GraphicsAnchor* anchor, m_anchors) {
anchor->setBrushColor(!polygon().isClosed() && anchor->polyIndex() ==0 ? m_firstAnchorFillColor : color);
}
}
void GraphicsRoiPolygon::setRotatable(bool set)
{
m_bRotatable = set;
}
void GraphicsRoiPolygon::setResizable(bool set)
{
if (set == false && !polygon().isClosed())
return;
m_bRotatable = set;
foreach (GraphicsAnchor* anchor, m_anchors) {
anchor->setVisible(set);
}
}
void GraphicsRoiPolygon::setFirstAnchorBordeColor(const QColor &color)
{
m_firstAnchorBordeColor = color;
if (!polygon().isClosed() && m_anchors.size() > 0)
{
m_anchors.first()->setPenColor(color);
}
}
void GraphicsRoiPolygon::setFirstAnchorFillColor(const QColor &color)
{
m_firstAnchorFillColor = color;
if (!polygon().isClosed() && m_anchors.size() > 0)
{
m_anchors.first()->setBrushColor(color);
}
}
int GraphicsRoiPolygon::type() const
{
return Type;
}
void GraphicsRoiPolygon::anchorPressed()
{
if (polygon().isClosed())
return;
GraphicsAnchor* anchor = qobject_cast<GraphicsAnchor*>(sender());
if (polygon().size() > 1 && anchor->polyIndex() == 0)
{// 使封闭
append(polygon().first());
}
}
void GraphicsRoiPolygon::anchorDoubleClicked()
{
// 删除
}
void GraphicsRoiPolygon::init()
{
this->setFlag(ItemIsMovable);
this->setFlag(ItemIsSelectable);
this->setFlag(ItemIsFocusable);
this->setCosmetic(true);
this->setFiltersChildEvents(true);
this->setPenColor(Qt::transparent);
this->setBrushColor(QColor(153, 204, 255, 200));
m_colorAnchorBorde = QColor(Qt::black);
m_colorAnchorFill = QColor(153, 204, 255, 200);
m_firstAnchorBordeColor = QColor(Qt::black);
m_firstAnchorFillColor = QColor(255, 204, 255, 200);
//
setAcceptHoverEvents(true);
// 注册事件处理,点击图片时,添加节点。
parentObject()->installSceneEventFilter(this);
// hover
static bool acceptHover = parentObject()->acceptHoverEvents();
parentObject()->setAcceptHoverEvents(true);
parentObject()->setFiltersChildEvents(true);
// 多边形已封闭时,移除事件处理,不可再添加
connect(this, &GraphicsRoiPolygon::polygonClosed, this, [this]()
{
qDebug() << "polygon closed.";
setAcceptHoverEvents(false);
parentObject()->removeSceneEventFilter(this);
parentObject()->setAcceptHoverEvents(acceptHover);
parentObject()->setFiltersChildEvents(false);
m_anchors.first()->setPenColor(m_colorAnchorBorde);
m_anchors.first()->setBrushColor(m_colorAnchorFill);
});
connect(parentObject(), &QGraphicsObject::scaleChanged, this, [=](){
QList<QGraphicsItem*> items = this->childItems();
foreach (QGraphicsItem *item, items) {
GraphicsShapeItem *shapeItem = qgraphicsitem_cast<GraphicsShapeItem *>(item);
if (shapeItem)
shapeItem->updateShape();
}
});
}
bool GraphicsRoiPolygon::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
if (event->type() == QEvent::GraphicsSceneMousePress)
{
QGraphicsSceneMouseEvent *sceneEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
if (polygon().size() > 1 && polygon().isClosed())
{ // 插入
if (watched->type() == GraphicsPolyLine::Type)
{
GraphicsPolyLine* line = qgraphicsitem_cast<GraphicsPolyLine*>(watched);
int index = m_lineItems.indexOf(line);
this->insert(index, watched->mapToItem(this, sceneEvent->pos()));
return true;
}
}
else
{ // 添加
QGraphicsSceneMouseEvent *sceneEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
if (polygon().size() > 1 && !polygon().isClosed() && m_anchors.first()->boundingRect().contains(watched->mapToItem(m_anchors.first(), sceneEvent->pos())))
{
append(polygon().first());
}
else
{
append(watched->mapToItem(this, sceneEvent->pos()));
}
return true;
}
}
else if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
{
if (polygon().size() > 1 && polygon().isClosed())
{
GraphicsAnchor* anchor = qgraphicsitem_cast<GraphicsAnchor*>(watched);
if (m_anchors.contains(anchor))
{
this->remove(anchor->polyIndex());
return true;
}
}
}
else if (event->type() == QEvent::GraphicsSceneHoverMove)
{
QGraphicsSceneMouseEvent *sceneEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
if (m_lineItems.size() > 0 && polygon().size() > 0 && (!polygon().isClosed() || polygon().size() == 1))
m_lineItems.last()->setP2(watched->mapToItem(this, sceneEvent->pos()));
}
return GraphicsItemPolygon::sceneEventFilter(watched, event);
}
void GraphicsRoiPolygon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
GraphicsItemPolygon::paint(painter, option, widget);
if (m_anchors.count() > 2)
paintCenter(painter, option, widget);
}
void GraphicsRoiPolygon::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
return GraphicsItemPolygon::mouseMoveEvent(event);
}
void GraphicsRoiPolygon::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
//qDebug() << "GraphicsPolygonRoi::hoverEnterEvent";
return GraphicsItemPolygon::hoverEnterEvent(event);
}
void GraphicsRoiPolygon::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
//qDebug() << "GraphicsPolygonRoi::hoverLeaveEvent";
return GraphicsItemPolygon::hoverLeaveEvent(event);
}
void GraphicsRoiPolygon::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
// qDebug() << "GraphicsPolygonRoi::hoverMoveEvent";
// if (polygon().size() > 1 && !polygon().isClosed())
// m_lineItems.last()->setP2(event->pos());
return GraphicsItemPolygon::hoverMoveEvent(event);
}
| true |
1f3a66258b41b674449cb573021a0567a43f0c96 | C++ | ChanceXuan/Connect4 | /Strategy.cpp | GB18030 | 5,378 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include "Point.h"
#include "Strategy.h"
#include "UCT.h"
#include <conio.h>
#include <atlstr.h>
Node* root;
bool rootCreated = false;
using namespace std;
const double timeLimit = 2.5; //ʱΪ3s
/*
Ժӿ,úԿƽ̨,ÿδ뵱ǰ״̬,Ҫӵ,ӵһϷӵ,ȻԿƽֱ̨Ϊij
input:
Ϊ˷ֹԶԿƽ̨άɸģдIJΪconst
M, N : ̴С M - N - 0ʼƣ ϽΪԭ㣬xǣy
top : ǰÿһжʵλ. e.g. iΪ,_top[i] == M, i,_top[i] == 0
_board : ̵һάʾ, Ϊ˷ʹãڸúտʼѾתΪ˶άboard
ֱֻʹboardɣϽΪԭ㣬[0][0]ʼ([1][1])
board[x][y]ʾxСyеĵ(0ʼ)
board[x][y] == 0/1/2 ֱӦ(x,y) /û/г,ӵ㴦ֵҲΪ0
lastX, lastY : Էһӵλ, ܲҪòҲҪIJǶԷһ
λãʱԼijм¼ԷಽλãȫȡԼIJ
noX, noY : ϵIJӵ(ע:ʵtopѾ㴦˲ӵ㣬Ҳ˵ijһ
ӵǡDzӵ㣬ôUIеĴѾеtopֵֽһμһ
ĴҲԸʹnoXnoYȫΪtopǵǰÿеĶ,
ȻʹlastX,lastYпܾҪͬʱnoXnoY)
ϲʵϰ˵ǰ״̬(M N _top _board)ԼʷϢ(lastX lastY),ҪľЩϢ¸ǵӵ
output:
ӵPoint
*/
extern "C" __declspec(dllexport) Point* getPoint(const int M, const int N, const int* top, const int* _board,
const int lastX, const int lastY, const int noX, const int noY)
{
AllocConsole();
_cprintf("=====call Strategy=====\n");
/*
Ҫδ
*/
int x = -1, y = -1;//սӵ浽x,y
int** board = new int*[M];
for(int i = 0; i < M; i++)
{
board[i] = new int[N];
for(int j = 0; j < N; j++)
board[i][j] = _board[i * N + j];
}
int* topVariable = new int[N];
for(int i = 0;i < N;i++)
topVariable[i] = top[i];
/*
ԼIJӵ,ҲǸIJɶx,yĸֵ
òֶԲʹûƣΪ˷ʵ֣ԶԼµࡢ.hļ.cppļ
*/
int startTime = clock();//ʱʼ
int chessNumber;
initConst(topVariable, M, N, noX, noY); //UCT㷨
State* rootState = new State(board, topVariable, lastX, lastY, machineGo, M, N);
int presentChessNumber = countChess(board, M, N);
if (presentChessNumber <= 1)
chessNumber = 0;
if (!rootCreated)
{
_cprintf("root is not created\n");
root = new Node(M, N); //ڵ
rootCreated = true;
}
if(presentChessNumber <= chessNumber) //ϷտʼлôӸȻ٣¿ʼ
{
chessNumber = presentChessNumber;
rootState->boardState = initBoard(); //ʼ
rootState->_whosTurn = machineGo; //AIʼ
}
while ((clock() - startTime)/CLOCKS_PER_SEC < timeLimit) //δľʱ
{
Node* expandedNode = TreePolicy(root, rootState); //ѡѽڵ
State* expandedState = new State(rootState->boardState, rootState->topState, rootState->_lastX, rootState->_lastY, userGo, M, N);
int profit = DefaultPolicy(expandedState); //Ĭϲģ
Node* tempNode = expandedNode;
while (tempNode)
{
tempNode->_visitedNum++; //ʴ+1
tempNode->_profit += profit; //delta
profit = -profit; //Сԭ
tempNode = tempNode->parent;
}
}
root = bestChild(root, rootState, 0);
getMove(x, y);
root->clear();
chessNumber = countChess(board, M, N);
/*
//a naive example
for (int i = N-1; i >= 0; i--) {
if (top[i] > 0) {
x = top[i] - 1;
y = i;
break;
}
}
*/
delete root;
/*
Ҫδ
*/
clearArray(M, N, board);
return new Point(x, y);
}
/*
getPointصPointָڱdllģģΪѴӦⲿñdllе
ͷſռ䣬Ӧⲿֱdelete
*/
extern "C" __declspec(dllexport) void clearPoint(Point* p){
delete p;
return;
}
/*
topboard
*/
void clearArray(int M, int N, int** board){
for(int i = 0; i < M; i++){
delete[] board[i];
}
delete[] board;
}
/*
ԼĸԼࡢµ.h .cppļʵ뷨
*/ | true |
a0f9d15b5c96b590ccc934aa8f17c018fe61d022 | C++ | jamboree/niji | /include/niji/support/box.hpp | UTF-8 | 8,594 | 2.671875 | 3 | [
"BSL-1.0"
] | permissive | /*//////////////////////////////////////////////////////////////////////////////
Copyright (c) 2015 Jamboree
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////*/
#ifndef NIJI_SUPPORT_BOX_HPP_INCLUDED
#define NIJI_SUPPORT_BOX_HPP_INCLUDED
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/algorithms/make.hpp>
#include <niji/support/traits.hpp>
#include <niji/support/vector.hpp>
#include <niji/support/convert_geometry.hpp>
namespace niji
{
template<class Point>
struct box
{
using coordinate_type =
typename boost::geometry::traits::coordinate_type<Point>::type;
using point_type = Point;
using coord_t = coordinate_type;
Point min_corner, max_corner;
box() {}
box(coord_t x1, coord_t y1, coord_t x2, coord_t y2)
: min_corner(boost::geometry::make<Point>(x1, y1))
, max_corner(boost::geometry::make<Point>(x2, y2))
{}
box(Point const& min_corner, Point const& max_corner)
: min_corner(min_corner)
, max_corner(max_corner)
{}
template<class Pt>
box(box<Pt> const& other)
: min_corner(convert_geometry<Point>(other.min_corner))
, max_corner(convert_geometry<Point>(other.max_corner))
{}
template<class Box, std::enable_if_t<is_box<Box>::value, bool> = true>
box(Box const& other)
{
boost::geometry::convert(other, *this);
}
void reset(coord_t x1, coord_t y1, coord_t x2, coord_t y2)
{
min_corner = boost::geometry::make<Point>(x1, y1);
max_corner = boost::geometry::make<Point>(x2, y2);
}
void reset(Point const& min, Point const& max)
{
min_corner = min;
max_corner = max;
}
template<class Pt>
void reset(Pt const& min, Pt const& max)
{
min_corner = convert_geometry<Point>(min);
max_corner = convert_geometry<Point>(max);
}
coordinate_type width() const
{
return length<0>();
}
coordinate_type height() const
{
return length<1>();
}
template<std::size_t N>
coordinate_type length() const
{
using boost::geometry::get;
return get<N>(max_corner) - get<N>(min_corner);
}
bool empty() const
{
using boost::geometry::get;
return get<0>(max_corner) == get<0>(min_corner) ||
get<1>(max_corner) == get<1>(min_corner);
}
bool invalid()
{
using boost::geometry::get;
return get<0>(min_corner) > get<0>(max_corner) ||
get<1>(min_corner) > get<1>(max_corner);
}
void clear()
{
max_corner = Point();
min_corner = Point();
}
void translate(vector<coord_t> const& v)
{
translate(v.x, v.y);
}
void translate(coord_t x, coord_t y)
{
using boost::geometry::get;
using boost::geometry::set;
set<0>(min_corner, get<0>(min_corner) + x);
set<1>(min_corner, get<1>(min_corner) + y);
set<0>(max_corner, get<0>(max_corner) + x);
set<1>(max_corner, get<1>(max_corner) + y);
}
void correct()
{
using boost::geometry::get;
using boost::geometry::set;
if (get<0>(max_corner) < get<0>(min_corner))
{
coordinate_type tmp(get<0>(min_corner));
set<0>(min_corner, get<0>(max_corner));
set<0>(max_corner, tmp);
}
if (get<1>(max_corner) < get<1>(min_corner))
{
coordinate_type tmp(get<1>(min_corner));
set<1>(min_corner, get<1>(max_corner));
set<1>(max_corner, tmp);
}
}
template<class F>
box transformed(F&& f) const
{
box ret(f(min_corner), f(max_corner));
ret.correct();
return ret;
}
void offset(vector<coord_t> const& v)
{
offset(v.x, v.y);
}
void offset(coord_t x, coord_t y)
{
using boost::geometry::get;
using boost::geometry::set;
set<0>(min_corner, get<0>(min_corner) - x);
set<1>(min_corner, get<1>(min_corner) - y);
set<0>(max_corner, get<0>(max_corner) + x);
set<1>(max_corner, get<1>(max_corner) + y);
}
void expand(box const& other)
{
using boost::geometry::get;
expand_coord<0>(get<0>(other.min_corner), get<0>(other.max_corner));
expand_coord<1>(get<1>(other.min_corner), get<1>(other.max_corner));
}
template<std::size_t N>
void expand_coord(coord_t min, coord_t max)
{
using boost::geometry::get;
using boost::geometry::set;
auto min_ = get<N>(min_corner);
auto max_ = get<N>(max_corner);
if (min_ == max_)
{
set<N>(min_corner, min);
set<N>(max_corner, max);
return;
}
if (min < min_)
set<N>(min_corner, min);
if (max > max_)
set<N>(max_corner, max);
}
bool clip(box const& other)
{
using boost::geometry::get;
return
clip_coord<0>(get<0>(other.min_corner), get<0>(other.max_corner))
&& clip_coord<1>(get<1>(other.min_corner), get<1>(other.max_corner));
}
template<std::size_t N>
bool clip_coord(coord_t min, coord_t max)
{
using boost::geometry::get;
using boost::geometry::set;
auto min_ = get<N>(min_corner);
auto max_ = get<N>(max_corner);
if (min_ >= max)
{
set<N>(max_corner, min_);
return false;
}
if (max_ <= min)
{
set<N>(min_corner, max_);
return false;
}
if (min_ < min)
set<N>(min_corner, min);
if (max < max_)
set<N>(max_corner, max);
return true;
}
template<std::size_t N>
Point const& corner() const
{
return *(&min_corner + N);
}
template<std::size_t N>
Point& corner()
{
return *(&min_corner + N);
}
Point center() const
{
using boost::geometry::get;
using boost::geometry::set;
Point pt;
set<0>(pt, (get<0>(min_corner) + get<0>(max_corner)) / 2);
set<1>(pt, (get<1>(min_corner) + get<1>(max_corner)) / 2);
return pt;
}
template<class Archive>
void serialize(Archive& ar, unsigned version)
{
ar & min_corner & max_corner;
}
};
}
namespace boost { namespace geometry { namespace traits
{
template<class Point>
struct tag<niji::box<Point>>
{
using type = box_tag;
};
template<class Point>
struct point_type<niji::box<Point>>
{
using type = Point;
};
template<class Point, std::size_t Index, std::size_t Dimension>
struct indexed_access<niji::box<Point>, Index, Dimension>
{
using coordinate_type = typename boost::geometry::coordinate_type<Point>::type;
static inline coordinate_type get(niji::box<Point> const& b)
{
return boost::geometry::get<Dimension>(b.template corner<Index>());
}
static inline void set(niji::box<Point>& b, coordinate_type value)
{
boost::geometry::set<Dimension>(b.template corner<Index>(), value);
}
};
}}}
#endif
| true |
da3f797f96f34b413a10d10f99cdf905f9dc10b0 | C++ | MYTE21/Competitive-Programming-Problems | /Codeforces_A, B/Codeforces - 448 (A. Rewards).cpp | UTF-8 | 583 | 3.015625 | 3 | [] | no_license | /*input
1 0 0
1 0 0
1
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<math.h>
using namespace std ;
int main()
{
int cup ;
int totalCup = 0 ;
int medal ;
int totalMedal = 0 ;
int shelfNumber ;
int neededShelf = 0 ;
for(int i=0;i<3;i++)
{
cin>>cup ;
totalCup += cup ;
}
for(int i=0;i<3;i++)
{
cin>>medal ;
totalMedal += medal ;
}
cin>>shelfNumber ;
neededShelf = ceil((double)totalCup/5) + ceil((double)totalMedal/10) ;
neededShelf <= shelfNumber ? cout<<"YES"<<endl : cout<<"NO"<<endl ;
return 0 ;
} | true |
391e78d5a6667729cef92639882c9bd8108c0c2a | C++ | thomasmainguy/Echec_Game_Mainguy_Thomas | /SDL_Template/Game.h | UTF-8 | 1,073 | 2.96875 | 3 | [] | no_license | #pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <string>
// forward declaration
class Board;
class Game
{
public:
Game();
~Game();
///<summary>Cree la SDL(window)</summary>
void InitSDL();
///<summary>Creer un new board </summary>
void InitGame();
///<summary>Appelle du event de board</summary>
void handleEvent(SDL_Event &e);
///<summary>draw le board en updatant la window et le rect de la screen surface<summary>
void Draw();
///<summary>permet l'update de l'event </summary>
void Update();
private:
//Screen dimension constants
///<param name = "SCREEN_WIDTH">Constante de la screen width</param>
const int SCREEN_WIDTH = 800;
///<param name = "SCREEN_HEIGHT">Constante de la screen height</param>
const int SCREEN_HEIGHT = 800;
///<param name = "m_Window">Pointeur sur la Window</param>
SDL_Window* m_Window;
///<param name = "m_ScreenSurface">Pointeur sur la surface de la screen</param>
SDL_Surface* m_ScreenSurface;
///<param name = "m_Board">Pointeur sur le board(pour le init dans la game)</param>
Board* m_Board;
}; | true |
883730a085a66b27afb61f7b03c82d75720dab8c | C++ | green-fox-academy/zolnay | /week_5/exercise/tasks/main.cpp | UTF-8 | 2,302 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> shoppingList = {
{"Eggs", 200},
{"Milk", 200},
{"Fish", 400},
{"Apples", 150},
{"Bread", 50},
{"Chicken", 550}
};
std::cout << "The fish's price is: " << shoppingList["Fish"] << std::endl;
int price = 0;
for (auto it = shoppingList.begin(); it != shoppingList.end(); it++) {
if (price < it->second) {
price = it->second;
}
}
for (auto it2 = shoppingList.begin(); it2 != shoppingList.end(); it2++) {
if (price == it2->second) {
std::cout << "Most expensive item on the list: " << it2->first << std::endl;
}
}
int sumPrice = 0;
int sizeOfList = shoppingList.size();
for (auto it = shoppingList.begin(); it != shoppingList.end(); it++) {
sumPrice += it->second;
}
float avaragePrice = static_cast<float>(sumPrice) / sizeOfList;
std::cout << "The avarage price on the list is: " << avaragePrice << std::endl;
int productBelowThreeHundred = 0;
for (auto it = shoppingList.begin(); it != shoppingList.end(); it++) {
if (it->second < 300) {
productBelowThreeHundred += 1;
}
}
std::cout << "There is " << productBelowThreeHundred << " Products thats price is under 300" << std::endl;
bool productExactly125 = false;
for (auto it = shoppingList.begin(); it != shoppingList.end(); it++) {
if (it->second == 125) {
productExactly125 = true;
}
}
if (productExactly125 == true) {
std::cout << "There is a product with the exact price of 125" << std::endl;
} else {
std::cout << "There is no product exactly 125 " << std::endl;
}
int cheapest;
std::string cheapestProduct;
for (auto it = shoppingList.begin(); it != shoppingList.end(); it++) {
cheapestProduct = it->second;
}
for (auto it = shoppingList.begin(); it != shoppingList.end(); it++) {
if (it->second < cheapest) {
cheapest = it->second;
cheapestProduct = it->first;
}
}
std::cout << "The cheapest product is " << cheapestProduct << std::endl;
return 0;
} | true |
1e9a2c35ac0d5b4705c01702f3bce726dceb0dd5 | C++ | mchchiang/senescence | /analysis/src/BeadsInSphere.cpp | UTF-8 | 4,500 | 2.890625 | 3 | [] | no_license | /* BeadsInSphere.cpp
*
* A program that reads the position file and counts
* the average number of heterochromatin baeds within
* a cutoff radius from a heterochromatin bead
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <fstream>
#include <sstream>
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::istringstream;
double distance(double x, double y, double z);
int main(int argc, char* argv[]){
if (argc < 12){
cout << "Not enough arguments! Process aborted." << endl;
return 1;
}
int numOfBeads {stoi(string(argv[1]), nullptr, 10)};
int lx {stoi(string(argv[2]), nullptr, 10)};
int ly {stoi(string(argv[3]), nullptr, 10)};
int lz {stoi(string(argv[4]), nullptr, 10)};
double cutoff {stod(string(argv[5]), nullptr)};
int localDist {stoi(string(argv[6]), nullptr, 10)};
int startTime {stoi(string(argv[7]), nullptr, 10)};
int endTime {stoi(string(argv[8]), nullptr, 10)};
int timeInc {stoi(string(argv[9]), nullptr, 10)};
string posFile (argv[10]);
string outFile (argv[11]);
const int dimension {3};
const int headerLines {2};
vector<double> zeroVector (dimension,0.0);
vector< vector<double> >* position =
new vector< vector<double> >(numOfBeads, zeroVector);
vector<int>* type = new vector<int>(numOfBeads, 0);
// Beads in sphere
vector<double>* localBeadsInSphere = new vector<double>(numOfBeads,0.0);
vector<double>* distalBeadsInSphere = new vector<double>(numOfBeads,0.0);
ifstream reader;
reader.open(posFile);
if (!reader){
cout << "Problem in reading position file! Process aborted." << endl;
return 1;
}
string line {}, sym {};
istringstream iss {};
double x {}, y {}, z {};
int ix {}, iy {}, iz {};
int t {}, count {};
long time {};
while (!reader.eof()){
// Ignore header lines
for (int i {}; i < headerLines; i++){
getline(reader, line);
}
if (time >= startTime && time <= endTime){
// Read bead position data - only store position of polymer beads
for (int i {}; i < numOfBeads; i++){
getline(reader, line);
iss.clear();
iss.str(line);
iss >> sym >> x >> y >> z >> ix >> iy >> iz >> t;
(*position)[i][0] = x + ix*lx;
(*position)[i][1] = y + iy*ly;
(*position)[i][2] = z + iz*lz;
(*type)[i] = t;
}
// Compute contact
double dx {}, dy {}, dz {};
for (int i {0}; i < numOfBeads; i++){
// Don't count self-interaction
for (int j {}; j < i; j++){
dx = (*position)[i][0] - (*position)[j][0];
dy = (*position)[i][1] - (*position)[j][1];
dz = (*position)[i][2] - (*position)[j][2];
if (distance(dx, dy, dz) <= cutoff){
if (abs(i-j) < localDist){
(*localBeadsInSphere)[i] += 1.0;
(*localBeadsInSphere)[j] += 1.0;
} else {
(*distalBeadsInSphere)[i] += 1.0;
(*distalBeadsInSphere)[j] += 1.0;
}
}
}
}
count++;
} else if (time < startTime) {
for (int i {}; i < numOfBeads; i++){
getline(reader, line);
}
} else {
break;
}
time += timeInc;
}
reader.close();
double avgLocalBeadsInSphere {};
double avgDistalBeadsInSphere {};
double avgBeadsInSphere {};
int numOfHetBeads {};
// Get the average beads in sphere count
for (int i {}; i < numOfBeads; i++){
(*localBeadsInSphere)[i] /= static_cast<double>(count);
(*distalBeadsInSphere)[i] /= static_cast<double>(count);
if ((*type)[i] == 2){
avgLocalBeadsInSphere += (*localBeadsInSphere)[i];
avgDistalBeadsInSphere += (*distalBeadsInSphere)[i];
numOfHetBeads++;
}
}
avgLocalBeadsInSphere /= static_cast<double>(numOfHetBeads);
avgDistalBeadsInSphere /= static_cast<double>(numOfHetBeads);
avgBeadsInSphere = avgLocalBeadsInSphere + avgDistalBeadsInSphere;
double fracOfLocalBeads {avgLocalBeadsInSphere / avgBeadsInSphere};
double fracOfDistalBeads {avgDistalBeadsInSphere / avgBeadsInSphere};
ofstream writer;
writer.open(outFile);
if (!writer){
cout << "Problem with opening the output file!" << endl;
return 1;
}
writer << std::setprecision(10) << std::fixed;
writer << fracOfLocalBeads << endl;
writer.close();
// Delete resources
delete position;
delete type;
delete localBeadsInSphere;
delete distalBeadsInSphere;
}
double distance(double x, double y, double z){
return sqrt(x*x+y*y+z*z);
}
| true |
124d98ad24ef63cac492d4fa9adfc377bf55b834 | C++ | cpenny42/juce-spotify | /models/spotify_CursorPager.h | UTF-8 | 1,772 | 2.78125 | 3 | [] | no_license | namespace spotify {
template <class T> class CursorPager
{
public:
CursorPager<T>();
CursorPager<T> (const juce::var& pagerJson);
CursorPager<T> (const CursorPager<T>& other);
const juce::String& GetHref() const;
const juce::Array<T>& GetItems() const;
int GetLimit() const;
const juce::String& GetNext() const;
Cursor GetCursors() const;
int GetTotal() const;
private:
juce::String href;
juce::Array<T> items;
int limit;
juce::String next;
Cursor cursors;
int total;
};
template <typename T> CursorPager<T>::CursorPager() = default;
template <typename T> CursorPager<T>::CursorPager(const juce::var& pagerJson)
: cursors (pagerJson["cursors"])
{
href = pagerJson["href"].toString();
limit = pagerJson["limit"];
total = pagerJson["total"];
for (auto json : * pagerJson["items"].getArray()) {
items.add (T(json));
}
if(!pagerJson["next"].isVoid()) {
next = pagerJson["next"].toString();
}
}
template <typename T> CursorPager<T>::CursorPager(const CursorPager<T>& other)
: href (other.href)
, items (other.items)
, limit (other.limit)
, next (other.next)
, cursors (other.cursors)
, total (other.total)
{}
template <typename T> const juce::String& CursorPager<T>::GetHref() const
{
return href;
}
template <typename T> const juce::Array<T>& CursorPager<T>::GetItems() const
{
return items;
}
template <typename T> int CursorPager<T>::GetLimit() const
{
return limit;
}
template <typename T> const juce::String& CursorPager<T>::GetNext() const
{
return next;
}
template <typename T> Cursor CursorPager<T>::GetCursors() const
{
return cursors;
}
template <typename T> int CursorPager<T>::GetTotal() const
{
return total;
}
}
| true |
deb9f656ec92dc994d536c7a6316832807b25aa1 | C++ | SakiAkizuki/ChessGame | /bishop.cc | UTF-8 | 2,255 | 2.953125 | 3 | [] | no_license | #include "bishop.h"
#include "board.h"
#include <vector>
#include <algorithm>
using namespace std;
Bishop::Bishop(int row, int col, char type, Board *board) : Piece(row, col, type, board) {}
bool Bishop::legalMove(int drow, int dcol) {
int row = getRow();
int col = getCol();
Piece *dest = board->getBoard()[drow][dcol].getPiece();
if ((drow >= 0) && (drow <= 7) && (dcol >= 0) && (dcol <= 7) && !((drow == row) && (dcol == col))) {
if ((dest == nullptr) || (dest->getColour() != getColour())) {
if ((row - drow) == (col - dcol)) {
int i = min(row,drow) + 1;
int j = min(col,dcol) + 1;
int k = max(row,drow);
int l = max(col,dcol);
while (i < k) {
if (board->getBoard()[i][j].getPiece() != nullptr) break;
i++;
j++;
}
return ((i == k) && (j == l));
}
else if ((row - drow) == -(col - dcol)) {
int i = min(row,drow) + 1;
int j = max(col,dcol) - 1;
int k = max(row,drow);
int l = min(col,dcol);
while (i < k) {
if (board->getBoard()[i][j].getPiece() != nullptr) break;
i++;
j--;
}
return ((i == k) && (j == l));
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
vector<vector<int>> Bishop::attackArea() {
int row = getRow();
int col = getCol();
vector<vector<int>> retval;
for (int i = row + 1, j = col + 1; ((i <= 7) && (j <= 7)); i++, j++) {
vector<int> tmp = {i, j};
retval.push_back(tmp);
if (board->getBoard()[i][j].getPiece() != nullptr) break;
}
for (int i = row + 1, j = col - 1; ((i <= 7) && (j >= 0)); i++, j--) {
vector<int> tmp = {i, j};
retval.push_back(tmp);
if (board->getBoard()[i][j].getPiece() != nullptr) break;
}
for (int i = row - 1, j = col + 1; ((i >= 0) && (j <= 7)); i--, j++) {
vector<int> tmp = {i, j};
retval.push_back(tmp);
if (board->getBoard()[i][j].getPiece() != nullptr) break;
}
for (int i = row - 1, j = col - 1; ((i >= 0) && (j >= 0)); i--, j--) {
vector<int> tmp = {i, j};
retval.push_back(tmp);
if (board->getBoard()[i][j].getPiece() != nullptr) break;
}
return retval;
}
| true |
e317cf168db76e64f682e9a12a0b5418783d85fb | C++ | phoopies/DesdeoInterface | /desdeo_interface/ArduinoFiles/Components/Component/Component.cpp | UTF-8 | 814 | 3.078125 | 3 | [] | no_license | /*
Component.cpp - Library for a base component
*/
#include "Arduino.h"
#include "Component.h"
Component::Component(uint8_t id, char type) {
_hasChanged = false;
_type = type;
_id = id;
}
/*
* Function: hasChanged
* --------------------
* Has the component value changed. _hasChanged is mainly updated in
* getValue() methods.
*
*
* returns: True if the value has changed else false
*/
bool Component::hasChanged() {
return _hasChanged;
}
/*
* Function: getId
* --------------------
* Get the id of the component
*
* returns: Id of the component
*/
uint8_t Component::getId() {
return _id;
}
/*
* Function: getType
* --------------------
* Get the type of the component
*
* returns: type of the component
*/
char Component::getType() {
return _type;
} | true |
c2d2011f1f09260626910e60bc224d39dfbe698f | C++ | decelj/trichoplax | /src/transform_stack.h | UTF-8 | 625 | 2.640625 | 3 | [] | no_license | #ifndef __TRANSFORM_STACK_H__
#define __TRANSFORM_STACK_H__
#include <glm/glm.hpp>
#include <stack>
class TransformStack {
public:
TransformStack();
void push();
void pop();
void transform(const glm::mat4& m);
glm::vec3 transformPoint(const glm::vec3& p) const;
glm::vec3 transformNormal(const glm::vec3& n) const;
void translate(const float x, const float y, const float z);
void rotate(const glm::vec3& axis, const float degrees);
void scale(const float x, const float y, const float z);
glm::mat4& top();
private:
std::stack<glm::mat4> mStack;
};
#endif
| true |
3e9fbd8b8cc61b1eb98751a7e32a8747f9e8b6cf | C++ | hjmjohnson/XEParallelProg | /HelloWorld/HelloWorld.cpp | UTF-8 | 389 | 2.609375 | 3 | [] | no_license | #include <stdlib.h>
#include <iostream>
#include <omp.h>
int main()
{
// Add first
//#pragma omp parallel default(none) shared(std::cout)
{
// Add second
//#pragma omp critical
{
#if defined(_OPENMP)
int id = omp_get_thread_num();
#else
int id = 0;
#endif
std::cout << "HelloWorld(" << id << ")"
<< std::flush << std::endl;
}
}
return EXIT_SUCCESS;
}
| true |
b63c4184a57ec3b305ba25d58d54e35eb6792751 | C++ | strange-hawk/data_structure_algorithms | /tree/count_nodes_in_complete_bintree.cpp | UTF-8 | 959 | 3.359375 | 3 | [] | no_license | // complete binary tree - a tree in which all the levels are completely filled except the last level
// the filling of the last level are done from left to right
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
struct Node{
int key;
Node* left;
Node* right;
Node(int k){
key = k;
left= right = NULL;
}
};
// save time in calculating no. of nodes if it is perfect binary tree
// skip traversal in the inner nodes if it is complete binary tree
int count_nodes(Node *root){
int lh=0,rh=0;
Node *curr= root;
while(curr!=NULL){
lh++;
curr = curr->left;
}
Node *curr= root;
while(curr!=NULL){
rh++;
curr=curr->right;
}
if (lh==rh){
return pow(2,lh)-1;
}
return 1+count_nodes(root->left)+count_nodes(curr->right);
}
// T(n) < T(2n/3) + theta(h)
// O(log(n)/log(3/2) * log(n)/log(2))
// O(log(n) *log(n)) | true |
3cfc4d1947c4bfd38fcfc7f2286f7da4209374e0 | C++ | igorternyuk/TeQtMineSweeper | /rightclickedbutton.cpp | UTF-8 | 477 | 2.75 | 3 | [] | no_license | #include "rightclickedbutton.h"
RightClickedButton::RightClickedButton(int rowNumber, int columnNumber, QWidget* parent) :
QPushButton(parent), rowNumber_(rowNumber), columnNumber_(columnNumber)
{}
void RightClickedButton::mousePressEvent(QMouseEvent* event)
{
if(event->button() == Qt::LeftButton)
emit onLeftButtonClicked(rowNumber_, columnNumber_);
if(event->button() == Qt::RightButton)
emit onRightButtonClicked(rowNumber_, columnNumber_);
}
| true |
53cfdb4e88d3addf6ade3a31c5079e288fff37f6 | C++ | libSDL2pp/libSDL2pp | /tests/test_pointrect.cc | UTF-8 | 13,447 | 3.125 | 3 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <SDL_main.h>
#include <SDL2pp/Point.hh>
#include <SDL2pp/Rect.hh>
#include "testing.h"
using namespace SDL2pp;
BEGIN_TEST(int, char*[])
{
// Point basic ops
Point p(1,2);
EXPECT_TRUE(p.GetX() == 1 && p.GetY() == 2);
EXPECT_TRUE(p == Point(1,2));
EXPECT_TRUE(p != Point(1,1));
EXPECT_TRUE(p != Point(2,2));
EXPECT_TRUE(p.x == 1);
EXPECT_TRUE(p.y == 2);
p.SetX(4);
p.SetY(5);
EXPECT_TRUE(p.GetX() == 4 && p.GetY() == 5);
EXPECT_TRUE(p == Point(4,5));
EXPECT_TRUE(p.x == 4);
EXPECT_TRUE(p.y == 5);
p = Point(6,7);
EXPECT_TRUE(p.GetX() == 6 && p.GetY() == 7);
EXPECT_TRUE(p == Point(6,7));
EXPECT_TRUE(p.x == 6);
EXPECT_TRUE(p.y == 7);
}
{
// Point self assignment
Point p(8,9);
p = Point(10,11);
p = p;
EXPECT_TRUE(p.GetX() == 10 && p.GetY() == 11);
}
{
// Point self move-assignment
Point p(12,13);
p = Point(14,15);
Point& pref = p;
p = std::move(pref);
EXPECT_TRUE(p.GetX() == 14 && p.GetY() == 15);
}
{
// Point arith
// Unary
EXPECT_EQUAL(-Point(1, 2), Point(-1, -2));
// Binary
EXPECT_EQUAL(Point(1, 2) + Point(10, 20), Point(11, 22));
EXPECT_EQUAL(Point(-1, -2) - Point(10, 20), Point(-11, -22));
EXPECT_EQUAL(Point(20, 60) / 5, Point(4, 12));
EXPECT_EQUAL(Point(20, 60) / Point(5, 10), Point(4, 6));
EXPECT_EQUAL(Point(20, 60) % 11, Point(9, 5));
EXPECT_EQUAL(Point(20, 60) % Point(11, 13), Point(9, 8));
EXPECT_EQUAL(Point(2, 3) * 5, Point(10, 15));
EXPECT_EQUAL(Point(2, 3) * Point(10, 20), Point(20, 60));
// Assignments
Point p(1, 2);
EXPECT_EQUAL(p += Point(10, 20), Point(11, 22));
EXPECT_EQUAL(p -= Point(1, 2), Point(10, 20));
EXPECT_EQUAL(p /= 2, Point(5, 10));
EXPECT_EQUAL(p %= 7, Point(5, 3));
EXPECT_EQUAL(p *= 3, Point(15, 9));
EXPECT_EQUAL(p /= Point(5, 3), Point(3, 3));
EXPECT_EQUAL(p *= Point(10, 20), Point(30, 60));
EXPECT_EQUAL(p %= Point(7, 11), Point(2, 5));
// Less-than
EXPECT_TRUE(Point(0, 0) < Point(1, 0));
EXPECT_TRUE(Point(0, 1) < Point(1, 0));
EXPECT_TRUE(Point(0, 1) < Point(1, 1));
EXPECT_TRUE(Point(0, 0) < Point(0, 1));
EXPECT_TRUE(!(Point(1, 0) < Point(0, 0)));
EXPECT_TRUE(!(Point(1, 0) < Point(0, 1)));
EXPECT_TRUE(!(Point(1, 1) < Point(0, 1)));
EXPECT_TRUE(!(Point(0, 1) < Point(0, 0)));
EXPECT_TRUE(!(Point(1, 1) < Point(1, 1)));
// Hashes
EXPECT_TRUE(std::hash<Point>()(Point(123, 456)) == std::hash<Point>()(Point(123, 456)));
EXPECT_TRUE(std::hash<Point>()(Point(0, 0)) != std::hash<Point>()(Point(0, 1)));
EXPECT_TRUE(std::hash<Point>()(Point(0, 0)) != std::hash<Point>()(Point(1, 0)));
EXPECT_TRUE(std::hash<Point>()(Point(1, 0)) != std::hash<Point>()(Point(0, 1)));
}
{
// Rect basic ops
Rect r(1,2,3,4);
EXPECT_TRUE(r.GetX() == 1 && r.GetY() == 2 && r.GetW() == 3 && r.GetH() == 4);
EXPECT_TRUE(r == Rect(1,2,3,4));
EXPECT_TRUE(r != Rect(2,2,3,4));
EXPECT_TRUE(r != Rect(1,3,3,4));
EXPECT_TRUE(r != Rect(1,2,4,4));
EXPECT_TRUE(r != Rect(1,2,3,5));
EXPECT_TRUE(r.x == 1 && r.y == 2 && r.w == 3 && r.h == 4);
r.SetX(5);
r.SetY(6);
r.SetW(7);
r.SetH(8);
EXPECT_TRUE(r.GetX() == 5 && r.GetY() == 6 && r.GetW() == 7 && r.GetH() == 8);
EXPECT_TRUE(r == Rect(5,6,7,8));
EXPECT_TRUE(r.x == 5 && r.y == 6 && r.w == 7 && r.h == 8);
r = Rect(9,10,11,12);
EXPECT_TRUE(r.GetX() == 9 && r.GetY() == 10 && r.GetW() == 11 && r.GetH() == 12);
EXPECT_TRUE(r == Rect(9,10,11,12));
EXPECT_TRUE(r.x == 9 && r.y == 10 && r.w == 11 && r.h == 12);
}
{
// Rect self assignment
Rect r(13,14,15,16);
r = Rect(17,18,19,20);
r = r;
EXPECT_TRUE(r.GetX() == 17 && r.GetY() == 18 && r.GetW() == 19 && r.GetH() == 20);
}
{
// Rect self move assignment
Rect r(21,22,23,24);
r = Rect(25,26,27,28);
Rect& rref = r;
r = std::move(rref);
EXPECT_TRUE(r.GetX() == 25 && r.GetY() == 26 && r.GetW() == 27 && r.GetH() == 28);
}
{
// Rect second point stuff
Rect r(50,100,5,10);
EXPECT_TRUE(r.GetX2() == 54 && r.GetY2() == 109);
r.SetX2(50+15);
r.SetY2(100+30);
EXPECT_TRUE(r.GetW() == 16 && r.GetH() == 31);
}
{
// Constructors
EXPECT_EQUAL(Rect::FromCenter(100, 100, 5, 7), Rect(98, 97, 5, 7));
EXPECT_EQUAL(Rect::FromCenter(Point(100, 100), Point(5, 7)), Rect(98, 97, 5, 7));
EXPECT_EQUAL(Rect::FromCorners(10, 20, 30, 40), Rect(10, 20, 21, 21));
EXPECT_EQUAL(Rect::FromCorners(Point(10, 20), Point(30, 40)), Rect(10, 20, 21, 21));
}
{
// Rect contains point
Rect r(10, 20, 5, 5);
EXPECT_TRUE(r.Contains(Point(10, 20)));
EXPECT_TRUE(r.Contains(Point(14, 24)));
EXPECT_TRUE(!r.Contains(Point(9, 20)));
EXPECT_TRUE(!r.Contains(Point(10, 19)));
EXPECT_TRUE(!r.Contains(Point(15, 20)));
EXPECT_TRUE(!r.Contains(Point(10, 25)));
EXPECT_TRUE(r.Contains(10, 20));
EXPECT_TRUE(r.Contains(14, 24));
EXPECT_TRUE(!r.Contains(9, 20));
EXPECT_TRUE(!r.Contains(10, 19));
EXPECT_TRUE(!r.Contains(15, 20));
EXPECT_TRUE(!r.Contains(10, 25));
// Rect contains rect
EXPECT_TRUE(r.Contains(r));
EXPECT_TRUE(r.Contains(Rect(11, 21, 3, 3)));
EXPECT_TRUE(!r.Contains(Rect(9, 20, 5, 5)));
EXPECT_TRUE(!r.Contains(Rect(10, 19, 5, 5)));
EXPECT_TRUE(!r.Contains(Rect(10, 20, 6, 5)));
EXPECT_TRUE(!r.Contains(Rect(10, 20, 5, 6)));
}
{
// Rect intersections
// test both GetIntersection() and Intersects() as the former uses the latter
Rect rect(10, 20, 30, 40);
EXPECT_TRUE(rect.Intersects(rect));
EXPECT_TRUE(rect.GetIntersection(rect) == rect);
// simple intersection
EXPECT_TRUE(rect.GetIntersection(Rect(5, 15, 30, 40)) == Rect(10, 20, 25, 35));
EXPECT_TRUE(rect.GetIntersection(Rect(15, 25, 30, 40)) == Rect(15, 25, 25, 35));
// larger at left
EXPECT_TRUE(rect.GetIntersection(Rect(0, 0, 10, 80)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(0, 0, 11, 80)) == Rect(10, 20, 1, 40));
// larger at top
EXPECT_TRUE(rect.GetIntersection(Rect(0, 0, 50, 20)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(0, 0, 50, 21)) == Rect(10, 20, 30, 1));
// larger at bottom
EXPECT_TRUE(rect.GetIntersection(Rect(0, 60, 50, 20)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(0, 59, 50, 20)) == Rect(10, 59, 30, 1));
// larger at right
EXPECT_TRUE(rect.GetIntersection(Rect(40, 0, 20, 80)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(39, 0, 20, 80)) == Rect(39, 20, 1, 40));
// smaller at left
EXPECT_TRUE(rect.GetIntersection(Rect(0, 30, 10, 20)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(0, 30, 20, 20)) == Rect(10, 30, 10, 20));
// smaller at top
EXPECT_TRUE(rect.GetIntersection(Rect(20, 10, 10, 10)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(20, 10, 10, 20)) == Rect(20, 20, 10, 10));
// smaller at bottom
EXPECT_TRUE(rect.GetIntersection(Rect(20, 60, 10, 10)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(20, 50, 10, 20)) == Rect(20, 50, 10, 10));
// smaller at right
EXPECT_TRUE(rect.GetIntersection(Rect(40, 30, 10, 20)) == NullOpt);
EXPECT_TRUE(rect.GetIntersection(Rect(30, 30, 20, 20)) == Rect(30, 30, 10, 20));
// smaller
EXPECT_TRUE(rect.GetIntersection(Rect(20, 30, 10, 20)) == Rect(20, 30, 10, 20));
// larger
EXPECT_TRUE(rect.GetIntersection(Rect(0, 0, 100, 100)) == rect);
}
{
// Rect unions
EXPECT_EQUAL(Rect(10, 20, 1, 1).GetUnion(Rect(30, 40, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(30, 20, 1, 1).GetUnion(Rect(10, 40, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(10, 40, 1, 1).GetUnion(Rect(30, 20, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(30, 40, 1, 1).GetUnion(Rect(10, 20, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(10, 20, 1, 1).Union(Rect(30, 40, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(30, 20, 1, 1).Union(Rect(10, 40, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(10, 40, 1, 1).Union(Rect(30, 20, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
EXPECT_EQUAL(Rect(30, 40, 1, 1).Union(Rect(10, 20, 1, 1)), Rect::FromCorners(10, 20, 30, 40));
}
{
// Rect/line intersections
Rect rect = Rect::FromCorners(10, 10, 20, 20);
Point p1(0, 0), p2(30, 30);
EXPECT_TRUE(rect.IntersectLine(p1, p2));
EXPECT_EQUAL(p1, Point(10, 10));
EXPECT_EQUAL(p2, Point(20, 20));
int x1 = 30, y1 = 0, x2 = 0, y2 = 30;
EXPECT_TRUE(rect.IntersectLine(x1, y1, x2, y2));
EXPECT_EQUAL(x1, 20);
EXPECT_EQUAL(y1, 10);
EXPECT_EQUAL(x2, 10);
EXPECT_EQUAL(y2, 20);
}
{
// Rect extend
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetExtension(0), Rect(10, 20, 30, 40));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetExtension(10), Rect(0, 10, 50, 60));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetExtension(10, 20), Rect(0, 0, 50, 80));
EXPECT_EQUAL(Rect(10, 20, 30, 40).Extend(0), Rect(10, 20, 30, 40));
EXPECT_EQUAL(Rect(10, 20, 30, 40).Extend(10), Rect(0, 10, 50, 60));
EXPECT_EQUAL(Rect(10, 20, 30, 40).Extend(10, 20), Rect(0, 0, 50, 80));
}
{
// Rect point getters
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetTopLeft(), Point(10, 20));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetTopRight(), Point(39, 20));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetBottomLeft(), Point(10, 59));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetBottomRight(), Point(39, 59));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetSize(), Point(30, 40));
EXPECT_EQUAL(Rect(10, 20, 30, 40).GetCentroid(), Point(25, 40));
}
{
// Rect offset
Rect r(1, 2, 3, 4);
EXPECT_EQUAL(r + Point(10, 20), Rect(11, 22, 3, 4));
EXPECT_EQUAL(r - Point(10, 20), Rect(-9, -18, 3, 4));
r += Point(10, 20);
EXPECT_EQUAL(r, Rect(11, 22, 3, 4));
r -= Point(20, 40);
EXPECT_EQUAL(r, Rect(-9, -18, 3, 4));
}
{
// Less-than
EXPECT_TRUE(!(Rect(0, 0, 0, 0) < Rect(0, 0, 0, 0)));
EXPECT_TRUE(Rect(0, 0, 0, 0) < Rect(0, 0, 0, 1));
EXPECT_TRUE(Rect(0, 0, 0, 0) < Rect(0, 0, 1, 0));
EXPECT_TRUE(Rect(0, 0, 0, 0) < Rect(0, 1, 0, 0));
EXPECT_TRUE(Rect(0, 0, 0, 0) < Rect(1, 0, 0, 0));
EXPECT_TRUE(!(Rect(0, 0, 0, 1) < Rect(0, 0, 0, 0)));
EXPECT_TRUE(!(Rect(0, 0, 0, 1) < Rect(0, 0, 0, 1)));
EXPECT_TRUE(Rect(0, 0, 0, 1) < Rect(0, 0, 1, 0));
EXPECT_TRUE(Rect(0, 0, 0, 1) < Rect(0, 1, 0, 0));
EXPECT_TRUE(Rect(0, 0, 0, 1) < Rect(1, 0, 0, 0));
EXPECT_TRUE(!(Rect(0, 0, 1, 0) < Rect(0, 0, 0, 0)));
EXPECT_TRUE(!(Rect(0, 0, 1, 0) < Rect(0, 0, 0, 1)));
EXPECT_TRUE(!(Rect(0, 0, 1, 0) < Rect(0, 0, 1, 0)));
EXPECT_TRUE(Rect(0, 0, 1, 0) < Rect(0, 1, 0, 0));
EXPECT_TRUE(Rect(0, 0, 1, 0) < Rect(1, 0, 0, 0));
EXPECT_TRUE(!(Rect(0, 1, 0, 0) < Rect(0, 0, 0, 0)));
EXPECT_TRUE(!(Rect(0, 1, 0, 0) < Rect(0, 0, 0, 1)));
EXPECT_TRUE(!(Rect(0, 1, 0, 0) < Rect(0, 0, 1, 0)));
EXPECT_TRUE(!(Rect(0, 1, 0, 0) < Rect(0, 1, 0, 0)));
EXPECT_TRUE(Rect(0, 1, 0, 0) < Rect(1, 0, 0, 0));
EXPECT_TRUE(!(Rect(1, 0, 0, 0) < Rect(0, 0, 0, 0)));
EXPECT_TRUE(!(Rect(1, 0, 0, 0) < Rect(0, 0, 0, 1)));
EXPECT_TRUE(!(Rect(1, 0, 0, 0) < Rect(0, 0, 1, 0)));
EXPECT_TRUE(!(Rect(1, 0, 0, 0) < Rect(0, 1, 0, 0)));
EXPECT_TRUE(!(Rect(1, 0, 0, 0) < Rect(1, 0, 0, 0)));
}
{
// Hashes
EXPECT_TRUE(std::hash<Rect>()(Rect(1, 2, 3, 4)) == std::hash<Rect>()(Rect(1, 2, 3, 4)));
EXPECT_TRUE(std::hash<Rect>()(Rect(1, 2, 3, 4)) != std::hash<Rect>()(Rect(2, 1, 3, 4)));
EXPECT_TRUE(std::hash<Rect>()(Rect(1, 2, 3, 4)) != std::hash<Rect>()(Rect(1, 2, 4, 3)));
}
{
// Construction from and comparison with SDL objects
SDL_Rect sdlrect = { 1, 2, 3, 4 };
SDL_Point sdlpoint = { 6, 7 };
EXPECT_TRUE(Rect(sdlrect) == Rect(1, 2, 3, 4));
EXPECT_TRUE(Point(sdlpoint) == Point(6, 7));
EXPECT_TRUE(Rect(sdlrect) != Rect(0, 2, 3, 4));
EXPECT_TRUE(Point(sdlpoint) != Point(0, 7));
EXPECT_TRUE(Rect(1, 2, 3, 4) == sdlrect);
EXPECT_TRUE(Point(6, 7) == sdlpoint);
EXPECT_TRUE(Rect(0, 2, 3, 4) != sdlrect);
EXPECT_TRUE(Point(0, 7) != sdlpoint);
}
{
// clamp
Rect rect(1, 2, 3, 4);
EXPECT_EQUAL(Point(0, 0).GetClamped(rect), Point(1, 2));
EXPECT_EQUAL(Point(0, 0).Clamp(rect), Point(1, 2));
EXPECT_EQUAL(Point(10, 10).GetClamped(rect), Point(3, 5));
EXPECT_EQUAL(Point(10, 10).Clamp(rect), Point(3, 5));
}
{
// wrap
EXPECT_EQUAL(Point(10, 20).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(39, 59).GetWrapped(Rect(10, 20, 30, 40)), Point(39, 59));
EXPECT_EQUAL(Point(9, 20).GetWrapped(Rect(10, 20, 30, 40)), Point(39, 20));
EXPECT_EQUAL(Point(40, 20).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(10, 19).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 59));
EXPECT_EQUAL(Point(10, 60).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(-50, -60).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(-20, -20).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(10, 20).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(40, 60).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(70, 100).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(100, 140).GetWrapped(Rect(10, 20, 30, 40)), Point(10, 20));
EXPECT_EQUAL(Point(-19, -19).GetWrapped(Rect(10, 20, 30, 40)), Point(11, 21));
EXPECT_EQUAL(Point(-21, -21).GetWrapped(Rect(10, 20, 30, 40)), Point(39, 59));
}
{
// streams
std::stringstream stream;
stream << Point(1, 2);
EXPECT_EQUAL(stream.str(), "[x:1,y:2]");
stream.str("");
stream << Rect(1, 2, 3, 4);
EXPECT_EQUAL(stream.str(), "[x:1,y:2,w:3,h:4]");
}
END_TEST()
| true |
bf7cae275dbbdf605a0cb8af5812e93508f45e4b | C++ | SydneyDimitra/ASEexamples | /ImageRandom/src/main.cpp | UTF-8 | 784 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include "Image.h"
#include <random>
int main()
{
constexpr size_t width=200;
constexpr size_t height=200;
std::cout<<"testing image\n";
Image test(width,height);
std::random_device rd;
std::default_random_engine re(rd());
std::uniform_int_distribution<> colour (0,255);
std::uniform_int_distribution<> posx(0,width-1);
std::uniform_int_distribution<> posy(0,height-1);
test.clearScreen(255,255,255);
for (int i=0; i<123243346; ++i)
{
test.setPixel(posx(re), posy(re),
(unsigned char)colour(re),
(unsigned char)colour(re),
(unsigned char)colour(re));
}
test.save("random.png");
return EXIT_SUCCESS;
}
| true |
74766d375ea4aa96ca9db7685be4c595dec43df4 | C++ | Vakondzoli/Arduino-MeArm | /Testing - code samples for sensors and display/keypad_working/keypad_working.ino | UTF-8 | 1,516 | 2.921875 | 3 | [] | no_license | /* @file CustomKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates changing the keypad size and key values.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char* password ="1234"; //create a password
int pozisyon = 0; //keypad position
int setLocked;
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'},
};
byte rowPins[ROWS] = {35, 37, 39, 41}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {43, 45, 47, 49}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup(){
Serial.begin(9600);
setLocked =0;; //state of the password
}
void loop(){
char whichKey = customKeypad.getKey();
if (whichKey){
Serial.println(whichKey);
if(whichKey == '*'){
Serial.println("reset");
}
if(whichKey == '#' || whichKey == 'A' || //define invalid keys
whichKey == 'B' || whichKey == 'C' || whichKey == 'D'){
Serial.println("invalid key");
pozisyon=0;
setLocked =0;
}
if(whichKey == password [pozisyon]){
pozisyon ++;
}
if(pozisyon == 4){
setLocked =1;
Serial.println("Valid key");
}
delay(100);
}
}
| true |
41d58dcc72d1720a90749d7b78bbec4253b94832 | C++ | inaniwa3/test | /explicit/c.cpp | UTF-8 | 572 | 3.4375 | 3 | [] | no_license | #include <cstdio>
class Hoge
{
public:
Hoge(int a) {}
};
class Fuga
{
public:
explicit Fuga(int a) {}
};
void FuncHoge (Hoge hoge) {}
void FuncFuga (Fuga fuga) {}
int main()
{
//// https://ja.cppreference.com/w/cpp/language/copy_initialization
// T object = other; (1)
Hoge hogeA = 1;
// Fuga fugaA = 1;
// f(other) (3)
FuncHoge(1); // ? difficult to read
// FuncFuga(1);
//// https://ja.cppreference.com/w/cpp/language/direct_initialization
// T object ( arg ); (1)
Hoge hogeB(1);
Fuga fugaB(1);
}
| true |
b40fdbf78cbb50d8ff2b99a7e589d76626fe826b | C++ | doantue/CS594_Project | /IRC/HandleMessages.cpp | UTF-8 | 8,362 | 2.671875 | 3 | [] | no_license | #include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <istream>
#include <vector>
#include <queue>
#include <thread>
#include <sstream>
#include <iomanip>
#include "SendRecvMsg.h"
#include "Common.h"
#include "SharedTask.h"
#include "MessageStorage.h"
#include "HandleMessages.h"
HandleMessages::HandleMessages(SOCKET* sock, SendRecvMsg* sr, MessageStorage* _storage, string _username)
{
ConnectSocket = sock;
srObj = sr;
storage = _storage;
username = _username;
}
int HandleMessages::execute() {
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
while (1) {
int iResult;
cout << endl;
std::cout << " 1. Create a room." << std::endl;
std::cout << " 2. List all rooms." << std::endl;
std::cout << " 3. Join a room." << std::endl;
std::cout << " 4. Leave a room." << std::endl;
std::cout << " 5. List members of a room." << std::endl;
std::cout << " 6. Send a message to a room." << std::endl;
std::cout << " 7. Disconnect from the server." << std::endl;
std::cout << ">>> Select next command: ";
int num;
while (std::cin >> num) {
if (std::cin.get() == '\n') break;
}
switch (num)
{
case 1: {
this->createRoom();
break;
}
case 2: {
auto result = this->listRoom();
if (!result.first) {
cout << "===== List of Rooms =====" << std::endl;
for each (string room in result.second){
std::cout << " " << room << std::endl;
}
}
else {
std::cout << "===> ERROR: "<< result.second[0] << std::endl;
}
break;
}
case 3: {
this->joinRoom();
break;
}
case 5: {
this->listMembers();
break;
}
case 6: {
this->sendMessage();
break;
}
case 7: {
string strsend = DISCONNECT_REQ "@" + username + " ";
int len = strsend.size() + PAYLOAD_LENGTH_DIGIT + 1;
strsend = strsend + SharedTask::intToStr(len, PAYLOAD_LENGTH_DIGIT) + " ";
srObj->_payload = strsend;
srObj->_payloadLength = srObj->_payload.size();
srObj->sendMsg();
//shutdown the connection since no more data will be sent
iResult = shutdown(*ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
std::cout << "Shutdown failed with error: " << WSAGetLastError() << std::endl;
return 1;
}
closesocket(*ConnectSocket);
WSACleanup();
return 0;
break;
}
default:
break;
}
}
}
void HandleMessages::createRoom() {
std::string roomName;
do {
std::cout << ">>> Enter room name to create: ";
std::getline(std::cin, roomName, '\n');
auto result = SharedTask::validateName(roomName);
if (result.first == 0) break;
std::cout << "===> ERROR: " << result.second << std::endl;
roomName = "";
} while (1);
string strsend = CREATE_ROOM_REQ "@" + username + " ";
string rstr = roomName + " ";
int len = strsend.size() + PAYLOAD_LENGTH_DIGIT + 1 + rstr.size();
strsend = strsend + SharedTask::intToStr(len, PAYLOAD_LENGTH_DIGIT) + " " + rstr;
srObj->_payload = strsend;
srObj->_payloadLength = srObj->_payload.size();
srObj->sendMsg();
//Timeout receive msg
if (SharedTask::checkQueue(&storage->msgBuf, MSG_RECV_TIMEOUT)) {
auto data = storage->msgBuf.front();
storage->msgBuf.pop();
if (data.first == SUCCESS_RES)
std::cout << "===> INFO: The room was created." << std::endl;
else {
vector<string> codes = SharedTask::parseParams(data.second, username, 1);
std::cout << "===> ERROR, code: " << codes[0] << std::endl;
}
}
else {
//close connection
}
}
pair<int, vector<string>> HandleMessages::listRoom() {
string strsend = LIST_ROOM_REQ "@" + username + " ";
int len = strsend.size() + PAYLOAD_LENGTH_DIGIT + 1;
strsend = strsend + SharedTask::intToStr(len, PAYLOAD_LENGTH_DIGIT);
srObj->_payload = strsend;
srObj->_payloadLength = srObj->_payload.size();
srObj->sendMsg();
if (SharedTask::checkQueue(&storage->msgBuf, MSG_RECV_TIMEOUT)) {
auto data = storage->msgBuf.front();
storage->msgBuf.pop();
if (data.first == LIST_ROOMS_RES) {
vector<std::string> list = SharedTask::parseList(data.second, username);
return{ 0, list };
}
else {
return{ 1, {"unknown error happens."} };
}
}
else {
//close connection
}
}
void HandleMessages::joinRoom() {
std::string roomName;
do {
std::cout << ">>> Enter room name to join: ";
std::getline(std::cin, roomName, '\n');
auto result = SharedTask::validateName(roomName);
if (result.first == 0) break;
std::cout << "===> ERROR: " << result.second << std::endl;
roomName = "";
} while (1);
string strsend = JOIN_ROOM_REQ "@" + username + " ";
string rstr = roomName + " ";
int len = strsend.size() + PAYLOAD_LENGTH_DIGIT + 1 + rstr.size();
strsend = strsend + SharedTask::intToStr(len, PAYLOAD_LENGTH_DIGIT) + " " + rstr;
srObj->_payload = strsend;
srObj->_payloadLength = srObj->_payload.size();
srObj->sendMsg();
if (SharedTask::checkQueue(&storage->msgBuf, MSG_RECV_TIMEOUT)) {
auto data = storage->msgBuf.front();
storage->msgBuf.pop();
if (data.first == SUCCESS_RES)
std::cout << "===> INFO: You've joined the room " << roomName << "." << std::endl;
else {
vector<string> codes = SharedTask::parseParams(data.second, username, 1);
std::cout << "===> ERROR, code: " << codes[0] << std::endl;
}
}
else {
//close connection
}
}
void HandleMessages::sendMessage() {
auto roomList = this->listRoom();
if (roomList.first) {
std::cout << "===> ERROR: " << roomList.second[0] << std::endl;
}
else {
if (roomList.second.size() == 0) {
cout << "===> ERROR: No room existed. " << endl;
}
else {
cout << "===== List of Rooms =====" << std::endl;
for (int i = 0; i < roomList.second.size(); i++) {
std::cout << " "<< i+1 <<". " << roomList.second[i] << std::endl;
}
}
}
string rooms;
static pair<int, string> result;
do {
std::cout << ">>> Enter room number(s), seperated by space char: ";
std::getline(std::cin, rooms, '\n');
result = SharedTask::validateRoomList(rooms, roomList.second);
if (result.first != 0) {
rooms = result.second;
break;
}
std::cout << "===> ERROR: " << result.second << std::endl;
rooms = "";
} while (1);
string content = "";
cout << ">>> Message content: ";
std::getline(std::cin, content, '\n');
std::string numRooms = SharedTask::intToStr(++result.first, NUM_LIST_LENGTH_DIGIT);
string strsend = SEND_MSG_REQ "@" + username + " ";
string rstr = numRooms + " " + rooms + " " + content + " ";
int len = strsend.size() + PAYLOAD_LENGTH_DIGIT + 1 + rstr.size();
strsend = strsend + SharedTask::intToStr(len, PAYLOAD_LENGTH_DIGIT) + " " + rstr;
srObj->_payload = strsend;
srObj->_payloadLength = srObj->_payload.size();
srObj->sendMsg();
if (SharedTask::checkQueue(&storage->msgBuf, MSG_RECV_TIMEOUT)) {
auto data = storage->msgBuf.front();
storage->msgBuf.pop();
if (data.first == SUCCESS_RES)
std::cout << "===> INFO: Your message was sent " << std::endl;
else {
vector<string> codes = SharedTask::parseParams(data.second, username, 1);
std::cout << "===> ERROR, code: " << codes[0] << std::endl;
}
}
else {
//close connection
}
}
void HandleMessages::listMembers() {
std::string roomName;
do {
std::cout << ">>> Enter a room name to list: ";
std::getline(std::cin, roomName, '\n');
auto result = SharedTask::validateName(roomName);
if (result.first == 0) break;
std::cout << "===> ERROR: " << result.second << std::endl;
roomName = "";
} while (1);
string strsend = LIST_MEMBER_REQ "@" + username + " ";
string rstr = roomName + " ";
int len = strsend.size() + PAYLOAD_LENGTH_DIGIT + 1 + rstr.size();
strsend = strsend + SharedTask::intToStr(len, PAYLOAD_LENGTH_DIGIT) + " " + rstr;
srObj->_payload = strsend;
srObj->_payloadLength = srObj->_payload.size();
srObj->sendMsg();
if (SharedTask::checkQueue(&storage->msgBuf, MSG_RECV_TIMEOUT)) {
auto data = storage->msgBuf.front();
storage->msgBuf.pop();
if (data.first == LIST_MEMBERS_RES) {
vector<std::string> list = SharedTask::parseList(data.second, username);
std::cout << "===== List of Members =====" << std::endl;
for each (auto mem in list){
std::cout << " " << mem << std::endl;
}
}
else {
vector<string> codes = SharedTask::parseParams(data.second, username, 1);
std::cout << "===> ERROR, code: " << codes[0] << std::endl;
}
}
else {
//close connection
}
} | true |
931660ebf5499d45e2eeaaf70494aaff51742ab4 | C++ | chorizou/Chess-game | /Queen.cpp | UTF-8 | 679 | 3.125 | 3 | [] | no_license | // Anna Hu
// ahu13, czou9, rmurato2
// Section 02
#include "Queen.h"
/* Defines the legal moves for Queen
* @param start: the starting coordinates
* @param end: the ending coordinates
* @return whether move is legal
*/
bool Queen::legal_move_shape(std::pair<char, char> start, std::pair<char, char> end) const{
int first_diff = start.first - end.first;
int second_diff = start.second - end.second;
if(!((start.first == end.first) && (start.second == end.second))){
if((start.first == end.first) || (start.second == end.second)){
return true;
}
if(first_diff * first_diff == second_diff * second_diff){
return true;
}
}
return false;
}
| true |
0e35220a13030dd39da7039dcb1fa4564d4b2f19 | C++ | eric-jacobson/AddressBook | /Contact.cpp | UTF-8 | 3,676 | 3.203125 | 3 | [] | no_license | // Contact.cpp Contact class implementation
#include "Contact.h"
// Constructors
Contact::Contact()
{
phoneNumber = "Unknown";
emailAddress = "Unknown";
birthday = "Unknown";
pictureFile = "Unknown";
}
Contact::Contact(Field phoneIn, Field emailIn, Field birthdayIn, Field pictureIn)
{
phoneNumber = phoneIn;
emailAddress = emailIn;
birthday = birthdayIn;
pictureFile = pictureIn;
}
Contact::Contact(Address fullAddrIn, Name fullNameIn)
{
fullAddress = fullAddrIn;
fullName = fullNameIn;
}
// Access functions
Field Contact::getPhoneNumber() const
{
return phoneNumber;
}
Field Contact::getEmail() const
{
return emailAddress;
}
Field Contact::getBirthday() const
{
return birthday;
}
Field Contact::getPictureFile() const
{
return pictureFile;
}
Name Contact::getFullName() const
{
return fullName;
}
Address Contact::getFullAddress()const
{
return fullAddress;
}
// Set functions
void Contact::setPhoneNumber(Field phoneIn)
{
phoneNumber = phoneIn;
}
void Contact::setEmail(Field emailIn)
{
emailAddress = emailIn;
}
void Contact::setBirthday(Field birthdayIn)
{
birthday = birthdayIn;
}
void Contact::setPictureFile(Field pictureIn)
{
pictureFile = pictureIn;
}
void Contact::setFullName(Name fullNameIn)
{
fullName = fullNameIn;
}
void Contact::setFullAddress(Address fullAddressIn)
{
fullAddress = fullAddressIn;
}
Field Contact::toString() const
{
Field contact;
contact = " Name: " + fullName.toString() + "\n Address: " + fullAddress.toString() + "\n Phone: "
+ phoneNumber + "\n Email: " + emailAddress + "\nBirthday: " + birthday + "\nPictFile: " + pictureFile + "\n";
return contact;
}
Field Contact::toFileString() const
{
Field contact;
contact = fullName.toFileString() + fullAddress.toFileString() + phoneNumber + ","
+ emailAddress + "," + birthday + "," + pictureFile + ",";
return contact;
}
// Operator overloaded functions
bool operator==(const Contact& contact1, const Contact& contact2)
{
if (contact1.fullName == contact2.fullName)
return(true);
return(false);
}
bool operator!=(const Contact& contact1, const Contact& contact2)
{
return!(contact1.fullName == contact2.fullName);
}
bool operator<(const Contact& contact1, const Contact& contact2)
{
if (contact1.fullName < contact2.fullName)
return(true);
return(false);
}
bool operator<=(const Contact& contact1, const Contact& contact2)
{
return(contact1.fullName < contact2.fullName || contact1.fullName == contact2.fullName);
}
bool operator>(const Contact& contact1, const Contact& contact2)
{
if (contact1.fullName > contact2.fullName)
return(true);
return(false);
}
bool operator>=(const Contact& contact1, const Contact& contact2)
{
return(contact1.fullName > contact2.fullName || contact1.fullName == contact2.fullName);
}
ostream &operator << (ostream &os, const Contact &out_contact)
{
os << out_contact.toString() << endl;
return (os);
}
istream &operator >> (istream &is, Contact &in_contact)
{
Field tmp;
is >> in_contact.fullName;
is >> in_contact.fullAddress;
is >> tmp;
in_contact.setPhoneNumber(tmp);
is >> tmp;
in_contact.setEmail(tmp);
is >> tmp;
in_contact.setBirthday(tmp);
is >> tmp;
in_contact.setPictureFile(tmp);
return (is);
}
ofstream &operator << (ofstream &os, const Contact &out_contact)
{
os << out_contact.toFileString() << endl;
return (os);
}
ifstream &operator >> (ifstream &is, Contact &in_contact)
{
Field tmp;
is >> in_contact.fullName;
is >> in_contact.fullAddress;
is >> tmp;
in_contact.setPhoneNumber(tmp);
is >> tmp;
in_contact.setEmail(tmp);
is >> tmp;
in_contact.setBirthday(tmp);
is >> tmp;
in_contact.setPictureFile(tmp);
return (is);
} | true |
3508df4bde2fa71d1a99e4cb49d04c6b919e5cb3 | C++ | tangzhanran/LeetCodes | /BestTimetoBuyandSellStockwithCooldown.cpp | UTF-8 | 1,445 | 3.875 | 4 | [] | no_license | // 309. Best Time to Buy and Sell Stock with Cooldown
//
// Say you have an array for which the ith element is the price of a given stock on day i.
//
// Design an algorithm to find the maximum profit.
// You may complete as many transactions as you like
// (ie, buy one and sell one share of the stock multiple times) with the following restrictions :
// 1. You may not engage in multiple transactions at the same time(ie, you must sell the stock before you buy again).
// 2. After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
//
// Example :
// prices = [1, 2, 3, 0, 2]
// maxProfit = 3
// transactions = [buy, sell, cooldown, buy, sell]
//
// Written by Zhanran Tang @ 7/21/2017
//
// Idea: DP solution. sell[i] means the profit when selling at day i. keep[i] means the profit when keeping at day i.
// sell[i] has 2 case: 1. sell at day i-1 then buy on day i-1 and sell at day i. 2. keep at day i-1.
// Complexity: O(n) in time, O(1) in space.
#include "Header.h"
using namespace std;
int maxProfit(vector<int>& prices)
{
int n = prices.size();
int sell = 0, presell = 0, keep = 0, prekeep = 0;
for (int i = 1; i<n; i++)
{
prekeep = keep;
presell = sell;
sell = max(presell + prices[i] - prices[i - 1], prekeep);
keep = max(presell, prekeep);
}
return max(sell, keep);
}
int main()
{
vector<int> prices = { 6,1,6,4,3,0,2 };
cout << maxProfit(prices) << endl;
system("pause");
return 0;
} | true |
3b8a897fba0fcd89362ccb2bd7c1657e7afa97f1 | C++ | Nechrito/s0009d-lab-env | /projects/Resource/code/MaterialResource.cpp | UTF-8 | 2,064 | 2.875 | 3 | [
"MIT"
] | permissive | // Copyright © 2020 Philip Lindh
// All rights reserved
#include "MaterialResource.h"
#include <fstream>
#include "CString.h"
bool MaterialResource::Load(const std::string& path, const std::string& name)
{
std::ifstream file(path);
if (!file.is_open())
{
std::cout << "Failed to open " << path << "\n";
return false;
}
std::cout << "Loading: " << path << "\n";
Material ref;
ref.Name = name;
ref.Path = path;
std::string line;
while (getline(file, line))
{
auto lineSplit = CString::Split(line, ' ');
if (lineSplit.size() <= 1)
continue;
if (lineSplit[0] == "Ka")
{
ref.Ambient.X = stof(CString::Split(lineSplit[1], ' ')[0]);
ref.Ambient.Y = stof(CString::Split(lineSplit[2], ' ')[0]);
ref.Ambient.Z = stof(CString::Split(lineSplit[3], ' ')[0]);
}
else if (lineSplit[0] == "Kd")
{
ref.Diffuse.X = stof(CString::Split(lineSplit[1], ' ')[0]);
ref.Diffuse.Y = stof(CString::Split(lineSplit[2], ' ')[0]);
ref.Diffuse.Z = stof(CString::Split(lineSplit[3], ' ')[0]);
}
else if (lineSplit[0] == "Ks")
{
ref.Specular.X = stof(CString::Split(lineSplit[1], ' ')[0]);
ref.Specular.Y = stof(CString::Split(lineSplit[2], ' ')[0]);
ref.Specular.Z = stof(CString::Split(lineSplit[3], ' ')[0]);
}
else if (lineSplit[0] == "Ns")
ref.SpecularExponent = stof(lineSplit[1]);
else if (lineSplit[0] == "Ni")
ref.OpticalDensity = stof(lineSplit[1]);
else if (lineSplit[0] == "d")
ref.Dissolve = stof(lineSplit[1]);
else if (lineSplit[0] == "illum")
ref.Illumination = stof(lineSplit[1]);
}
Materials.push_back(ref);
file.close();
return true;
}
void MaterialResource::Draw(Shader& shader)
{
for (const Material& material : Materials)
{
shader.SetValue("material.AmbientColor", material.Ambient);
shader.SetValue("material.DiffuseColor", material.Diffuse);
shader.SetValue("material.SpecularColor", material.Specular);
shader.SetValue("material.SpecularExponent", material.SpecularExponent);
}
}
| true |
a46539a3011e34fda4a3dc45ff0f0ca99ce3ca8f | C++ | andreasfertig/cppinsights | /tests/Issue81.cpp | UTF-8 | 182 | 3.015625 | 3 | [
"MIT"
] | permissive | auto f(int i)
{ // also `decltype(auto) f(int i)` and `int(*f(int i))[3]`
static int arr[5][3];
return &arr[i];
}
auto *ff(int i)
{
static int arr[5][3];
return &arr[i];
}
| true |
d01f192ff6ff8cade5b1c2bafdd1e97af0862caa | C++ | Sadat97/SuperMarket | /src/Item.cpp | UTF-8 | 905 | 3.25 | 3 | [] | no_license | #include "../include/Item.h"
Item::Item()
{
}
Item::Item(string N,string T,int I,int A,int P)
{
Name=N;
Type=T;
ID=I;
Avamount=A;
Price=P;
}
void Item :: display_items(int s)
{
cout<<"- "<<setw(12)<<this->get_Name()<<" | "<<setw(10)<<this->get_Type()<<" | "<<setw(8)<<this->get_ID()
<<" | "<<setw(2)<<this->get_Avamount()<<" | "<<setw(2)<<this->get_Price()<<"\n";
}
void Item :: set_Name(string n) {Name=n;}
void Item :: set_Type(string t) {Type=t;}
void Item :: set_ID(int i) {ID=i;}
void Item :: set_Avamount(int a){Avamount = a;}
void Item :: set_Price(int p) {Price =p;}
string Item :: get_Name() {return Name;}
string Item :: get_Type() {return Type;}
int Item :: get_ID() {return ID;}
int Item :: get_Avamount(){return Avamount;}
int Item :: get_Price() {return Price;}
| true |
0206dcc39cb5a31479c04a45a0d2f01149b724cc | C++ | BatFace/Hangman | /CompleteBots/Connect4.CPP/Api.cpp | UTF-8 | 5,826 | 2.703125 | 3 | [] | no_license | #include "Api.h"
#include "rest/Response.hpp"
#include "rest/UrlRequest.hpp"
#include "json.hpp"
using json = nlohmann::json;
namespace Api
{
const std::string site("yorkdojoconnect4.azurewebsites.net");
bool Init()
{
#ifdef WIN32
auto wVersionRequested = MAKEWORD(2, 2);
WSAData wsaData;
int ret = WSAStartup(wVersionRequested, &wsaData);
return ret == 0;
#else
return true;
#endif
}
std::string RegisterTeam(const std::string& teamName, const std::string& password)
{
UrlRequest request;
request.host(site.c_str());
request.uri(registerApi.c_str(),
{
{teamNameParam.c_str(), teamName.c_str()},
{passwordParam.c_str(), password.c_str()}
});
request.method("POST");
request.addHeader("Content-Type: application/json\nContent-Length: 0");
try
{
auto response = std::move(request.perform());
if (response.statusCode() == 200)
{
std::string body = response.body();
// Unquote the response
body = body.erase(0, 1);
body = body.erase(body.size() - 1);
return body;
}
else
{
cout << "status code = " << response.statusCode() << ", description = " << response.statusDescription() << endl;
return "";
}
}
catch (std::exception&)
{
return "";
}
}
bool GameState(const std::string& playerID, Game& game)
{
UrlRequest request;
request.host(site.c_str());
request.uri(getGameApi.c_str(),
{
{playerIDParam.c_str(), playerID}
});
request.addHeader("Content-Type: application/json\nContent-Length: 0");
try
{
auto response = std::move(request.perform());
if (response.statusCode() == 200)
{
std::string body = response.body();
auto gameData = json::parse(body);
game.PlayerID = playerID;
game.CurrentState = CurrentGameState(gameData["CurrentState"].get<int>());
game.YellowPlayerID = gameData["YellowPlayerID"].get<std::string>();
game.RedPlayerID = gameData["RedPlayerID"].get<std::string>();
game.ID = gameData["ID"].get<std::string>();
auto cells = gameData["Cells"];
for (int column = 0; column < Game::NUMBER_OF_COLUMNS; column++)
{
for (int row = 0; row < Game::NUMBER_OF_ROWS; row++)
{
game.Cells[column][row] = CellContent(cells[column][row].get<int>());
}
}
return true;
}
else
{
cout << "status code = " << response.statusCode() << ", description = " << response.statusDescription() << endl;
return "";
}
}
catch (std::exception&)
{
return "";
}
}
bool MakeMove(const std::string& playerID, const std::string& password, int column)
{
UrlRequest request;
request.host(site.c_str());
request.uri(makeMoveApi.c_str(),
{
{playerIDParam.c_str(), playerID},
{passwordParam.c_str(), password},
{columnNumberParam.c_str(), column},
});
request.method("POST");
request.addHeader("Content-Type: application/json\nContent-Length: 0");
try
{
auto response = std::move(request.perform());
if (response.statusCode() == 200)
{
return true;
}
else
{
cout << "status code = " << response.statusCode() << ", description = " << response.statusDescription() << endl;
return false;
}
}
catch (std::exception&)
{
return "";
}
}
bool NewGame(const std::string& playerID)
{
UrlRequest request;
request.host(site.c_str());
request.uri(newGameApi.c_str(),
{
{playerIDParam.c_str(), playerID}
});
request.method("POST");
request.addHeader("Content-Type: application/json\nContent-Length: 0");
try
{
auto response = std::move(request.perform());
if (response.statusCode() == 200)
{
return true;
}
else
{
cout << "status code = " << response.statusCode() << ", description = " << response.statusDescription() << endl;
return false;
}
}
catch (std::exception&)
{
return false;
}
}
std::string GetStatusString(Api::Game& game, bool& finished)
{
switch (game.CurrentState)
{
case Api::CurrentGameState::YellowToPlay:
finished = false;
if (game.PlayerID == game.YellowPlayerID)
{
return "Our move (Yellow)";
}
else
{
return "Their move (Yellow)";
}
break;
case Api::CurrentGameState::RedToPlay:
finished = false;
if (game.PlayerID == game.RedPlayerID)
{
return "Our move (Red)";
}
else
{
return "Their move (Red)";
}
break;
case Api::CurrentGameState::Draw:
finished = true;
return "Draw";
break;
case Api::CurrentGameState::GameNotStarted:
finished = false;
return "Not Started";
break;
case Api::CurrentGameState::RedWon:
finished = true;
if (game.PlayerID == game.RedPlayerID)
{
return "We Won (Red)";
}
else
{
return "We Lost (Yellow)";
}
break;
case Api::CurrentGameState::YellowWon:
finished = true;
if (game.PlayerID == game.YellowPlayerID)
{
return "We Won (Yellow)";
}
else
{
return "We Lost (Red)";
}
break;
default:
break;
}
finished = true;
return "";
}
}
| true |
5a9d8344efd3bd41d8989e41369af0ce78d75442 | C++ | tinased95/Principles-of-computers-and-programming | /binary search.cpp | UTF-8 | 694 | 3.125 | 3 | [] | no_license | #include<stdio.h>
#define SIZE 5
int main(){
int a[100],i,n,m,c=0,f,e,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
f=0,e=n-1;
while(f<=e){
mid=(f+e)/2;
if(m==a[mid]){
c=1;
break;
}
else if(m<a[mid]){
e=mid-1;
}
else
f=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
return 0;
} | true |
61db81774d7e95ee506aec3ff0a0108a43a44072 | C++ | kuangr5950/ga_fcnpr | /lib/mockturtle/include/mockturtle/utils/progress_bar.hpp | UTF-8 | 3,845 | 2.765625 | 3 | [
"MIT"
] | permissive | /* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
\file progress_bar.hpp
\brief Progress bar
\author Mathias Soeken
*/
#pragma once
#include <cstdint>
#include <iostream>
#include <string>
#include <fmt/format.h>
namespace mockturtle
{
/*! \brief Prints progress bars.
*
\verbatim embed:rst
Example
.. code-block:: c++
{ // some block
progress_bar bar( 100, "|{0}| neg. index = {1}, index squared = {2}" );
for ( auto i = 0; i < 100; ++i )
{
bar( i, -i, i * i );
}
} // progress bar is deleted at exit of this block
\endverbatim
*/
class progress_bar
{
public:
/*! \brief Constructor.
*
* \param size Number of iterations (for progress bar)
* \param fmt Format strind; used with `fmt::format`, first placeholder `{0}`
* is used for progress bar, the others for the parameters passed
* to `operator()`
* \param enable If true, output is printed, otherwise not
* \param os Output stream
*/
progress_bar( uint32_t size, std::string const& fmt, bool enable = true, std::ostream& os = std::cout )
: _size( size ),
_fmt( fmt ),
_enable( enable ),
_os( os ) {}
/*! \brief Deconstructor
*
* Will remove the last printed line and restore the cursor.
*/
~progress_bar()
{
done();
}
/*! \brief Prints and updates the progress bar status.
*
* This updates the progress to `pos` and re-prints the progress line. The
* previous print of the line is removed. All arguments for the format string
* except for the first one `{0}` are passed as variadic arguments after
* `pos`.
*
* \param pos Progress position (must be smaller than `size`)
* \param args Vardiadic argument pack with values for format string
*/
template<typename... Args>
void operator()( uint32_t pos, Args... args )
{
if ( !_enable )
return;
int spidx = static_cast<int>( ( 6.0 * pos ) / _size );
_os << "\u001B[G" << fmt::format( _fmt, spinner.substr( spidx * 5, 5 ), args... ) << std::flush;
}
/*! \brief Removes the progress bar.
*
* This method is automatically invoked when the progress bar is deleted. In
* some cases, one may wish to invoke this method manually.
*/
void done()
{
if ( _enable )
{
_os << "\u001B[G" << std::string( 79, ' ' ) << "\u001B[G\u001B[?25h" << std::flush;
}
}
private:
uint32_t _size;
std::string _fmt;
bool _enable;
std::ostream& _os;
std::string spinner{" . .. ... .... ....."};
};
} // namespace mockturtle
| true |
aec37c2cf1b16c95c460df1b2e35f7dc31874f72 | C++ | kristofleroux/uh-ogp1-project | /Stone Age/Stone Age - Qt Application/model/Cards/RangedResourceBuildingCard.cpp | UTF-8 | 1,034 | 2.828125 | 3 | [] | no_license | #include "RangedResourceBuildingCard.h"
#include "../Game.h"
#include "../PlayerBoardItems/Resource.h"
// Constructor
RangedResourceBuildingCard::RangedResourceBuildingCard(int returnPoints, QString imagePath, Game* game, int min, int max) :
BuildingCard{returnPoints, imagePath, game}, m_minimumResources{min}, m_maximumResources{max} {}
// Getters
int RangedResourceBuildingCard::getMinimumResources() const {
return m_minimumResources;
}
int RangedResourceBuildingCard::getMaximumResources() const {
return m_maximumResources;
}
bool RangedResourceBuildingCard::checkValidResources() const {
return m_givenResources.size() >= m_minimumResources && m_givenResources.size() <= m_maximumResources;
}
int RangedResourceBuildingCard::getReturnPoints() const {
int returnPoints{0};
for(int i{0}; i < m_givenResources.size(); ++i) {
Resource* resource{m_givenResources.at(i)};
returnPoints += resource->getCalculationValue() * resource->getCurrentAmount();
}
return returnPoints;
}
| true |
59e0031aab375674b6f8f5789ec2dc3576ecbe69 | C++ | everett1224/mytest | /Curiously_Recurring_Template_Pattern.cc | UTF-8 | 2,551 | 3.609375 | 4 | [] | no_license | ////
//this is Curiously_Recurring_Template_Pattern test
// Q1: static_cast syntax : static_cast<type>(expression)
// Q2: keyword "this" in different scope means different type
// n3376 9.3.2/1
// In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called.
//
// The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
//http://stackoverflow.com/questions/17146497/type-of-this-in-c
//
// Q3: menber function hide.
// member function is not virtual and the child has the same function name the father function is hided
// http://www.jb51.net/article/41357.htm
#include <stdio.h>
//group 1 : Q2 this type in the non-const function test
template <class T>
class Base
{
public:
void sayHi();
void print() ;
};
template <class T>
void Base<T>::sayHi()
{
}
template <class T>
void Base<T>::print()
{
//sstatic_cast<T*>this -> sayHi(); // compile error : this --> (this) static_cast<new_type>(expression). Different with the C - language (char*)p or (char)(a+b).
static_cast<T*>(this) -> sayHi();
static_cast<T*>(this) -> print(); // this is OK; because of the function hide
}
class Woo : public Base<Woo>
{
public:
void sayHi()
{
printf("hi Im Woo\n");
}
//void print()
void print()
{
printf("this is test\n");
}
};
//group 2 compare with the group 1
template <class T>
class Base2
{
public:
void sayHi();
void print() const;// this is different with the group1
};
template <class T>
void Base2<T>::sayHi()
{
}
template <class T>
void Base2<T>::print() const
{
//sstatic_cast<T*>this -> sayHi(); // compile error : this --> (this) static_cast<new_type>(expression). Different with the C - language (char*)p or (char)(a+b).
static_cast<const T*>(this) -> sayHi();
static_cast<const T*>(this) -> print(); // this is OK; because of the function hide
}
class Woo2 : public Base2<Woo2>
{
public:
//
// void sayHi() // with out "const" : compile error with default gcc argument. if using -fpermissive complie will warning
void sayHi() const
{
printf("hi Im Woo\n");
}
// void print()
void print() const
{
printf("this is test\n");
}
};
int main()
{
Base<Woo> oB;
oB.print();
Woo wB;
wB.print();
Base2<Woo2> oB2;
oB2.print();
return 0;
}
| true |
ce4a2eaa6fc17753246127c2bbf5356810a5ed06 | C++ | codingsf/tcpproxy_libevent | /lev-master/include/levhttp.h | UTF-8 | 4,484 | 2.5625 | 3 | [
"MIT",
"BSL-1.0"
] | permissive | // Copyright (c) 2014 Yasser Asmi
// Released under the MIT License (http://opensource.org/licenses/MIT)
#ifndef _LEVHTTP_H
#define _LEVHTTP_H
#include <iostream>
namespace lev
{
class EvHttpRequest;
class EvHttpServer;
class EvHttpRequest
{
public:
EvHttpRequest(struct evhttp_request* req)
{
mReq = req;
}
~EvHttpRequest()
{
}
inline void sendError(int error, const char* reason)
{
evhttp_send_error(mReq, error, reason);
}
inline void sendReply(int responsecode, const char* responsemsg)
{
evhttp_send_reply(mReq, responsecode, responsemsg, NULL);
}
inline void sendReply(int responsecode, const char* responsemsg, EvBuffer& body)
{
evhttp_send_reply(mReq, responsecode, responsemsg, body.ptr());
}
//TODO: add chunk API
inline void cancel()
{
evhttp_cancel_request(mReq);
}
inline struct evhttp_connection* connection()
{
return evhttp_request_get_connection(mReq);
}
// uri
inline const char* uriStr()
{
return evhttp_request_get_uri(mReq);
}
inline EvHttpUri uri()
{
EvHttpUri u(evhttp_request_get_evhttp_uri(mReq));
return u;
}
inline const char* host()
{
return evhttp_request_get_host(mReq);
}
inline enum evhttp_cmd_type cmd()
{
return evhttp_request_get_command(mReq);
}
inline int responseCode()
{
return evhttp_request_get_response_code(mReq);
}
inline struct evkeyvalq* inputHdrs()
{
return evhttp_request_get_input_headers(mReq);
}
inline struct evkeyvalq* outputHdrs()
{
return evhttp_request_get_output_headers(mReq);
}
inline EvBuffer input()
{
return EvBuffer(evhttp_request_get_input_buffer(mReq));
}
inline EvBuffer output()
{
return EvBuffer(evhttp_request_get_output_buffer(mReq));
}
protected:
struct evhttp_request* mReq;
private:
EvHttpRequest();
};
class EvHttpServer
{
public:
typedef void (*RouteCallback)(struct evhttp_request*, void*);
EvHttpServer(struct event_base* base)
{
mServer = evhttp_new(base);
if (mServer == NULL)
{
std::cerr << "Can't create http server" << std::endl;
}
}
~EvHttpServer()
{
if (mServer)
{
evhttp_free(mServer);
}
}
void setDefaultRoute(RouteCallback callback, void* cbarg = NULL)
{
evhttp_set_gencb(mServer, callback, cbarg);
}
bool addRoute(const char* path, RouteCallback callback, void* cbarg = NULL)
{
int ret = evhttp_set_cb(mServer, path, callback, cbarg);
if (ret == -2)
{
std::cerr << "Path " << path << "already exists" << std::endl;
}
return ret == 0;
}
bool deleteRoute(const char* path)
{
int ret = evhttp_del_cb(mServer, path);
return ret == 0;
}
bool bind(const char* address, short port, EvConnListener* connout = NULL)
{
// can be called multiple times
struct evhttp_bound_socket* ret;
ret = evhttp_bind_socket_with_handle(mServer, address, port);
if (ret)
{
if (connout)
{
connout->assign(evhttp_bound_socket_get_listener(ret));
}
return true;
}
return false;
}
inline bool bind(const IpAddr& sa)
{
return bind(sa.toString().c_str(), sa.port());
}
static
std::string encodeUriString(const char* src)
{
std::string s;
char* temp = evhttp_encode_uri(src);
if (temp)
{
s.assign(temp);
free(temp);
}
return s;
}
static
std::string decodeUriString(const char* src)
{
std::string s;
char* temp = evhttp_decode_uri(src);
if (temp)
{
s.assign(temp);
free(temp);
}
return s;
}
static
std::string htmlEscape(const char* src)
{
// Replaces <, >, ", ' and & with <, >, ", ' and &
std::string s;
char* temp = evhttp_htmlescape(src);
if (temp)
{
s.assign(temp);
free(temp);
}
return s;
}
protected:
struct evhttp* mServer;
private:
EvHttpServer();
};
} // namespace lev
#endif // _LEVHTTP_H
| true |
767ed27b62a55be7da5e982a48d38032a21f17b8 | C++ | Joann3a/noi | /Noi-OpenJudge/1.编程基础/1.05编程基础之循环控制/CH010506-2.cpp | UTF-8 | 276 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int n, x, maxv=0, minv=10000;
cin >>n; //n=6
for (int i=1; i<=n; i++)
{
cin >> x;
if (x > maxv) maxv = x;
if (x < minv) minv = x;
}
cout << maxv - minv <<endl;
return 0;
}
| true |
7e44e1d96c8ef394ae37328c3934a1d04c2eb026 | C++ | ITAbits/documentacao | /treinamento-c/2016/aula-05/turma-01/Exemplo_002.cpp | UTF-8 | 492 | 3.515625 | 4 | [] | no_license | ///Resolver Flavius Josephus por recursividade com funcoes
#include <stdio.h>
int flaviusJosephus(int n, int k)
{
if (n == 1)
return 1;
return ((flaviusJosephus(n-1,k) + k-1) % n + 1);
}
int main()
{
int n, k, sobrevivente;
printf("PROBLEMA DO FLAVIUS JOSEPHUS\n\n");
printf("Digite o numero de pessoas no circulo e o passo em que elas pulam: ");
scanf("%d %d", &n, &k);
sobrevivente = flaviusJosephus(n,k);
printf("Sobrevivente = %d\n", sobrevivente);
return 0;
}
| true |
6a9ea433a1506a1ef39d4a188756624cb108eff6 | C++ | cchadwickk/Labs | /CD/LexicalAnalyser/comment/comment.h | UTF-8 | 1,735 | 3.046875 | 3 | [] | no_license | #include<fstream>
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class charFileManager{
protected:
ifstream ifile;
ofstream ofile;
char infile[20],oufile[20];
int line;
char ch;
public:
charFileManager(){
line=1;
}
void openfiles(char in[], char out[]){ //(input file, temporary output file)
strcpy(infile,in);
strcpy(oufile,out);
ifile.open(in);
ofile.open(out);
if(!ifile.good())
{
cout<<"Error opening read file.\n";
exit(1);
}
if(!ofile.good())
{
cout<<"Error opening write file.\n";
exit(1);
}
}
void filechange(){ //rename files, create backup files
remove("backup.txt");
if(rename(infile,"backup.txt"))
cout<<"error renaming file";
if(rename(oufile,infile))
cout<<"Error renaming file";
}
void closefiles(){ //close files and call filechange()
ifile.close();
ofile.close();
filechange();
}
char read(int wryte){ //read character and return(bool value=write to file ?)
ifile.get(ch);
if(ch=='\n')
line++;
if(wryte)
ofile.put(ch);
if(ifile.eof())
return -1;
return ch;
}
void write(){ //write char to output file
ofile.put(ch);
}
void write(char cha){ //write explicitly sent char(to be written)
ofile.put(cha);
}
char c(){ //return char read
return ch;
}
int retLineCnt()
{
return line;
}
};
| true |
caa90b7fbba620c6526036dc14c66dee1024b469 | C++ | gameofmachine/C-for-Financial-Engineering | /homework_level_5/3.6/3.6.1/3.6.1/test.cpp | UTF-8 | 286 | 2.5625 | 3 | [] | no_license | #include"array.h"
#include<iostream>
using namespace XIANGZOU;
void main()
{
Containers::Array a(10);
//cout << a[10] << endl; //runtime error occurs
try
{
cout << a[10] << endl;
}
catch (int err)
{
if (err == -1) cout << "index out of bound" << endl;
}
}
| true |
42841094cdee3c40b8c6b850deddfa77f043a686 | C++ | pepesoriagarcia99/C--_2017-2018 | /repaso/3/main.cpp | UTF-8 | 1,132 | 3.671875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float valor_producto;
char tipo_iva;
float iva;
float valor_con_iva;
cout<<"Introduce valor del producto: ";
cin>>valor_producto;
cout<<"tipo de iva (<a>iva general, <b>iva reducido, <c>iva superreducido): ";
cin>>tipo_iva;
if(tipo_iva=='a' || tipo_iva=='A')
{
cout<<"Iva general(21%)"<<endl;
iva=(valor_producto*21)/100;
cout<<"valor sumado: "<<iva<<endl;
valor_con_iva=valor_producto+iva;
cout<<"valor final: "<<valor_con_iva<<endl;
}
if(tipo_iva=='b' || tipo_iva=='B')
{
cout<<"Iva reducido(10%)"<<endl;
iva=(valor_producto*10)/100;
cout<<"valor sumado: "<<iva<<endl;
valor_con_iva=valor_producto+iva;
cout<<"valor final: "<<valor_con_iva<<endl;
}
if(tipo_iva=='b' || tipo_iva=='B')
{
cout<<"Iva superreducido(4%)"<<endl;
iva=(valor_producto*4)/100;
cout<<"valor sumado: "<<iva<<endl;
valor_con_iva=valor_producto+iva;
cout<<"valor final: "<<valor_con_iva<<endl;
}
return 0;
}
| true |
ccb5dd449e61543799d326fe0bf9a4e38e240985 | C++ | FennelFetish/InfinityCube | /animations/Rainbow.h | UTF-8 | 1,290 | 2.6875 | 3 | [] | no_license | #pragma once
#include "../Animation.h"
class AnimRainbow : public Animation
{
private:
float t;
public:
AnimRainbow() : t(0) {}
virtual void update(AnimationContext& ctx, long tpf, bool beat) override
{
t += tpf / 1000000.0f;
int colorVHigh = ctx.brightnessFactor * 255; //20; // 80, 70
int colorVLow = colorVHigh / 5; //3; // 20, 50
int colorVDiff = colorVHigh - colorVLow;
float vFactor = ctx.timeSinceBeat / 200000.0f;
vFactor = pow(vFactor, 0.33);
int colorV = colorVHigh - constrain(vFactor * colorVDiff, 0, colorVDiff);
for(int i=0; i<ctx.numLeds; ++i) {
double val = 0.5 * ( 1.0 + sin(-t*1.0 + (2.0 * i / ctx.numLeds * 3.1415926)) );
ctx.leds[i].h = 255.0 * val;
//h[i] = round(h[i]/30.0) * 30.0;
//s[i] = 55.0 + 200.0 * val;
//v[i] = 3.0 + 47.0 * val;
//h[i] += 3;
ctx.leds[i].s = 255;
if(ctx.leds[i].h > 80)
ctx.leds[i].b = colorV;
else
ctx.leds[i].b = 0;
}
}
}; | true |
bcb6bbd8c97abeb21478058f755a62cac80023f4 | C++ | sanskriti12/arrays | /array33.cpp | UTF-8 | 281 | 3.34375 | 3 | [] | no_license | //product of two elements in an array..
# include<stdio.h>
# include<stdlib.h>
int main()
{
int n,i,j;
int x=6;
int a[]={1,2,3,4,5,6};
n=sizeof(a)/sizeof(a[0]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]*a[j]==x)
printf("elements are %d and %d",a[i],a[j]);
}
| true |
bc8b8820c7886f78f1df245e2df20018bef1e1c2 | C++ | erhemdiputra/codeforces | /problemset/i-wanna-be-the-guy/main.cpp | UTF-8 | 621 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool checkLvl(int arr[], int n) {
for(int i = 1; i <= n; i++) {
if(arr[i] == 0) {
return false;
}
}
return true;
}
int main() {
int n, p, q, lvl, arr[105];
bool isPass;
memset(arr, 0, sizeof(arr));
cin>>n;
cin>>p;
for(int i = 0; i < p; i++) {
cin>>lvl;
arr[lvl]++;
}
cin>>q;
for(int i = 0; i < q; i++) {
cin>>lvl;
arr[lvl]++;
}
if(checkLvl(arr, n)) {
cout<<"I become the guy."<<endl;
} else {
cout<<"Oh, my keyboard!"<<endl;
}
} | true |
97a92fe35c7ddfc6300feb0f811a1fc35470c19f | C++ | ucsd-cse-125-spring-2019/cse125-sp19-group2 | /Shared/Timer.hpp | UTF-8 | 1,776 | 3.578125 | 4 | [] | no_license | #pragma once
#include <functional>
#include <chrono>
/** Utility class for use on the server or client. These are "fake" timers in
* that they are synchronous and the update() function needs to be called on
* them frequently. This is enough for our needs in this case, because we
* have very fast loops on both the server and client.
*/
class Timer {
public:
// Constructs a timer object with a duration and an optional lambda to be
// executed when the duration is reached. Duration is in milliseconds.
// Timer is started immediately upon construction.
Timer(long durationMilliseconds, std::function<void()> f = 0)
{
// Convert milliseconds to nanoseconds
_duration = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::milliseconds(durationMilliseconds));
_onComplete = f;
_durationReached = false;
// Start the timer
_startTime = std::chrono::steady_clock::now();
}
// Must be called every tick
void update()
{
if (!_durationReached)
{
auto elapsed = std::chrono::steady_clock::now() - _startTime;
if (elapsed >= _duration)
{
_durationReached = true;
// Call lambda
_onComplete();
}
}
}
// Stops and marks the timer for deletion
void abort()
{
_durationReached = true;
}
// Has the timer reached its duration?
bool isComplete()
{
update();
return _durationReached;
}
// Returns elapsed time in milliseconds
long getElapsed()
{
update();
auto elapsed = std::chrono::steady_clock::now() - _startTime;
return (long)std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
}
private:
std::chrono::time_point<std::chrono::steady_clock> _startTime;
std::chrono::nanoseconds _duration;
std::function<void()> _onComplete;
bool _durationReached;
};
| true |
f1fd7830b78cb31289b4aa197d6dbaa0f697c3d0 | C++ | Amaterasu90/Runner | /Source/Runner/Private/OrbitalActor.cpp | UTF-8 | 2,232 | 2.5625 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "Runner.h"
#include "OrbitalActor.h"
// Sets default values
AOrbitalActor::AOrbitalActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
TArray<UStaticMeshComponent* > Components;
GetComponents<UStaticMeshComponent>(Components);
static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereVisualAsset(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
if (SphereVisualAsset.Succeeded()) {
Components[0]->SetStaticMesh(SphereVisualAsset.Object);
}
SetMobility(EComponentMobility::Movable);
}
// Called when the game starts or when spawned
void AOrbitalActor::BeginPlay()
{
StartPosition = GetActorLocation();
Super::BeginPlay();
}
// Called every frame
void AOrbitalActor::Tick( float DeltaTime )
{
FVector NewLoaction = StartPosition;
float x = NewLoaction.X;
float y = NewLoaction.Y;
float z = NewLoaction.Z;
float dX = Radius * (FMath::Sin(ChangeToRadians(Alfa))*FMath::Sin(ChangeToRadians(Gamma)) - FMath::Cos(ChangeToRadians(Alfa))*FMath::Cos(ChangeToRadians(Beta))*FMath::Sin(ChangeToRadians(Gamma))+ FMath::Sin(ChangeToRadians(Beta))*FMath::Sin(ChangeToRadians(Gamma)));
float dY = Radius * (FMath::Sin(ChangeToRadians(Alfa))*FMath::Sin(ChangeToRadians(Gamma)) + FMath::Cos(ChangeToRadians(Alfa))*FMath::Cos(ChangeToRadians(Beta))*FMath::Cos(ChangeToRadians(Gamma)) - FMath::Sin(ChangeToRadians(Beta))*FMath::Cos(ChangeToRadians(Gamma)));
float dZ = Radius * (FMath::Cos(ChangeToRadians(Beta)) + FMath::Cos(ChangeToRadians(Alfa))*FMath::Sin(ChangeToRadians(Beta)));
Alfa = Mod(Alfa + DeltaTime * SpeedFactor,360.0f);
if (Alfa + DeltaTime * SpeedFactor > 360.0f){
Beta = Mod(Beta + 3, 360.0f);
Alfa = 0;
}
NewLoaction.X = x + dX;
NewLoaction.Y = y + dY;
NewLoaction.Z = z + dZ;
SetActorLocation(NewLoaction);
Super::Tick(DeltaTime);
}
float AOrbitalActor::ChangeToRadians(float degrees)
{
return degrees * PI / 180.0f;
}
float AOrbitalActor::Mod(float data, float boundary)
{
if (boundary > 0 && data / boundary > 1)
return data - boundary;
else
return data;
}
| true |
a05a74deb7de691102b3d729b5ff87bf4674365f | C++ | Datta2901/Algorithmic-Implementations | /Advanced DS/Policy Based DS/Problem - 1.cpp | UTF-8 | 5,838 | 2.8125 | 3 | [
"MIT"
] | permissive | // Source(s): https://atcoder.jp/contests/abc190/editorial/639
// NOTE: I tried to the problem using Method 1 (based on similar concept of Merge Sort), but it gave
// TLE on some of the cases, but when I calculated inversions using Method 2 (PBDS), it passed all cases.
// Don't know why it happened as both methods to find #inversion counts work in O(n x log2(n)) time.
/************************************************************************************************************/
// Method 1
// Problem: F - Shift and Inversions
// Contest: AtCoder - AtCoder Beginner Contest 190
// URL: https://atcoder.jp/contests/abc190/tasks/abc190_f
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// Parsed on: 01-02-2021 14:26:11 IST (UTC+05:30)
// Author: Kapil Choudhary
// ********************************************************************
// कर्मण्येवाधिकारस्ते मा फलेषु कदाचन |
// मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि || १.४७ ||
// ********************************************************************
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
vi v;
int n;
ll cross_inv(int l, int h) {
int mid = l + ((h - l) >> 1);
vi tmp(n);
ll cnt = 0;
int i = l, j = mid + 1, k = l;
while(i <= mid && j <= h) {
if(v[i] <= v[j]) tmp[k++] = v[i++];
else {
cnt += (mid - i + 1);
tmp[k++] = v[j++];
}
}
while(i <= mid) tmp[k++] = v[i++];
while(j <= h) tmp[k++] = v[j++];
for(int ii = l; ii <= h; ii++) v[ii] = tmp[ii];
return cnt;
}
ll inv_cnt(int l, int h) {
if(l >= h) return 0LL;
int mid = l + ((h - l) >> 1);
ll res = inv_cnt(l, mid) + inv_cnt(mid + 1, h);
res += cross_inv(l, h);
return res;
}
void solve()
{
cin >> n;
v.resize(n);
for(int i = 0; i < n; i++) cin >> v[i];
vi t = v;
ll inv = inv_cnt(0, n - 1);
for(int k = 0; k < n; k++) {
cout << inv << "\n";
inv -= t[k];
inv += (n - 1 - t[k]);
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// cin >> t;
while(t--) {
solve();
}
return 0;
}
/**********************************************************************************************************/
// Method 2
// Problem: F - Shift and Inversions
// Contest: AtCoder - AtCoder Beginner Contest 190
// URL: https://atcoder.jp/contests/abc190/tasks/abc190_f
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// Parsed on: 01-02-2021 15:12:23 IST (UTC+05:30)
// Author: Kapil Choudhary
// ********************************************************************
// कर्मण्येवाधिकारस्ते मा फलेषु कदाचन |
// मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि || १.४७ ||
// ********************************************************************
#include<bits/stdc++.h>
using namespace std;
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
// pair<int, int> is taken so as to take care of array containing
// duplicate elements
typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag,
tree_order_statistics_node_update> PBDS;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
PBDS st;
ll inv = 0; // for storing the result
for(int i = 0; i < n; i++){
inv += (st.size() - st.order_of_key({v[i], i}));
st.insert({v[i], i});
}
for(int k = 0; k < n; k++) {
cout << inv << "\n";
inv -= v[k];
inv += (n - 1 - v[k]);
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// cin >> t;
while(t--) {
solve();
}
return 0;
} | true |
e3726eaf5b33bbbf1ee976cb28d98b2000306b49 | C++ | bixcoito/ExerciseList | /Q4.cpp | ISO-8859-1 | 949 | 3.6875 | 4 | [] | no_license | #include <iostream>
using namespace std;
float calcular_area(float base, float altura);
int main()
{
/*
Programa AREA DO TRIANGULO
Calcula a rea de um Tringulo.
A rea do Tringulo dada por: (base * altura) / 2.
Dicas: Voc precisa enviar alguma informao para a funo?
Dicas: Quais informaes precisam ser passadas? (No use variveis globais!)
Dicas: A funo retorna alguma informao para voc?
Dicas: Se sim, ento a funo deve ter um tipo de retorno e um 'return' ao final.
*/
float area;
float base = 5, altura = 6;
// ----- CALCULA A AREA DE UM TRIANGULO -----
area = calcular_area(base, altura);
cout.precision(3);
cout << "Triangulo possui Base " << fixed << base << endl;
cout << "Triangulo possui Altura " << fixed << altura << endl;
cout << "Area do Triangulo: " << fixed << area << endl;
}
float calcular_area(float base, float altura){
return (base * altura) / 2;
}
| true |
3f0e933b64b11b67e443db3f1ce7b725aac1faa0 | C++ | ericksonalves/questions | /erickson/tree-top-view/tree-top-view.cpp | UTF-8 | 612 | 3.46875 | 3 | [] | no_license | #include <deque>
void go_left(node* root, std::deque<int>& deque)
{
if (root != nullptr) {
deque.push_front(root->data);
go_left(root->left, deque);
}
}
void go_right(node* root, std::deque<int>& deque)
{
if (root != nullptr) {
deque.push_back(root->data);
go_right(root->right, deque);
}
}
void top_view(node* root)
{
std::deque<int> deque;
if (root != nullptr) {
go_left(root->left, deque);
deque.push_back(root->data);
go_right(root->right, deque);
}
for (const auto& data : deque)
std::cout << data << " ";
}
| true |
6103101047ad243695df68b44c8bab984fc325ad | C++ | seflopod/InstructorMemory | /InstructorMemory/titlebutton.cpp | UTF-8 | 1,604 | 2.765625 | 3 | [] | no_license | #ifndef _TITLEBUTTON_H_
#include "titlebutton.h"
#endif
#include "game.h"
TitleButton::TitleButton()
{
_canDraw = false;
_drawPriority = 0;
//_texId = -1;
_text = "";
_position = Vector3();
_height = 0.0f;
_width = 0.0f;
}
void TitleButton::init(string text, Vector3 position, float height, float width)
{
_text = text;
_position = position;
_height = height;
_width = width;
_drawPriority = 12;
Game::instance()->registerDrawable((IDrawable*)this);
}
Vector3 TitleButton::getPosition() { return _position; }
void TitleButton::setPosition(Vector3 newPosition) { _position = newPosition; }
float TitleButton::getHeight() { return _height; }
void TitleButton::setHeight(float height) { _height = height; } //note no check for positive
float TitleButton::getWidth() { return _width; }
void TitleButton::setWidth(float width) { _width = width; }
bool TitleButton::collidesWithPoint(float x, float y)
{
float left = _position.x - _width;
float right = _position.x + _width;
float top = _position.y + _height;
float bottom = _position.y - _height;
return (x >= left && x <= right &&
y >= bottom && y <= top);
}
void TitleButton::enable() { _canDraw = true; }
void TitleButton::disable() { _canDraw = false; }
bool TitleButton::isEnabled() { return _canDraw; }
int TitleButton::getPriority() { return _drawPriority; }
void TitleButton::setPriority(int drawPriority) { _drawPriority = drawPriority; }
void TitleButton::draw()
{
if(!_canDraw)
return;
glRasterPos2f(_position.x, _position.y);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, (const unsigned char*)_text.c_str());
} | true |
b3416dc23083dbd6b2ef04edec266a82d5305219 | C++ | inatel-codetroopers/notebook | /code/matematica/gcd.cpp | UTF-8 | 246 | 3.34375 | 3 | [] | no_license | // Calcula o maior divisor comum entre A e B
ll A, B;
cin >> A >> B;
cout << __gcd(A, B);
// Calcula o menor multiplo comum entre A e B
ll lcm(ll A, ll B) {
if (A and B)
return abs(A) / __gcd(A, B) * abs(B);
else
return abs(A | B);
} | true |
78431159637c7f730091f24eb6de7a912fe5c644 | C++ | bulacu-magda/Alemia | /data/raw/train/student_3/1188/1185/Wallnut.cpp | UTF-8 | 558 | 2.640625 | 3 | [] | no_license | #include "Wallnut.h"
using namespace GameMechanics;
Wallnut::Wallnut(int rowUp, int colLeft) : Plant(rowUp, colLeft)
{
this->ID = EntityID::WALLNUT;
auto index = getIndex(PLANTS_ID, this->ID);
this->HP = PLANTS_HP[index];
this->cost = PLANTS_COST[index];
this->width = UserInterface::WALLNUT_WIDTH;
}
Wallnut::~Wallnut()
{
}
std::string Wallnut::serialize()
{
using namespace std;
string s = "Wallnut\n";
s += to_string(this->rowUp);
s += " ";
s += to_string(this->colLeft);
s += " ";
s += to_string(this->HP);
s += "\n";
return s;
} | true |
ee4fe18e7938c4dfda96f4f9d6618c2578568404 | C++ | SyedTabishAzam/portfolio | /Others/Games/Making of games - Allegro/Ass 5/Striker/Explosion.cpp | UTF-8 | 2,054 | 3.328125 | 3 | [] | no_license | #include "Explosion.h"
Explosion::Explosion(BITMAP* image, int frame_width, int frame_height, Point position) : Plane(image, frame_width, frame_height, position)
{ //Constructor the calls the constructor of Plane (just like bullet)
type=-1; //Type of explosion is Exclusive, that is a negative number
sp=0; //an explosion counter used to delaw the frames of explosion
explodeSound = load_sample("Sounds/ImpactSound.wav"); //loads sound
}
Explosion::Explosion(BITMAP* image, int frame_width, int frame_height, int x, int y) : Plane(image, frame_width, frame_height, x, y)
{
type=-1;
sp=0;
explodeSound = load_sample("Sounds/ImpactSound.wav");
}
Explosion::~Explosion()
{
std::cout<<"Explosion class destroyed";
}
void Explosion::Draw(BITMAP* buffer,bool debug)
{
if (sp==1)
{
play_sample(explodeSound, 255, 128, 1000, 0); //this check ensures that the sound is played only once in the beginning of collision
}
if(sp<=5) //for every sp count uptil +5, one frame is displayed. this ensures frames doesnt run too fast
masked_blit(image, buffer, 0, 688, position.x, position.y,46 ,46);
else if(sp<=10)
masked_blit(image, buffer, 46, 688,position.x, position.y,46 ,46);
else if(sp<=15)
masked_blit(image, buffer, 92, 688, position.x, position.y,46 ,46);
else if(sp<=20)
masked_blit(image, buffer, 138, 688,position.x, position.y,46 ,46);
else if(sp<=25)
masked_blit(image, buffer, 184, 688,position.x, position.y,46 ,46);
else if(sp<=30)
masked_blit(image, buffer, 230, 688,position.x, position.y,46 ,46);
}
void Explosion::Move()
{
sp++; //on every loop, whenever MOVE is called through linked list, an sp counter is increased
if(sp>30) //if the counter reaches 30, it is reset to 0
{
sp=0;
alive=false; //and the alive value is set to false
}
}
| true |
a1f7f81ca4ec6a2dab5d4af8ce8df3bdf59ecc33 | C++ | peterekepeter/vulkan | /vulkan/VulkanShader.cpp | UTF-8 | 1,182 | 2.84375 | 3 | [] | no_license | #include "pch.h"
#include "VulkanShaderModule.h"
VulkanShaderModule::VulkanShaderModule(VkDevice device, const char* data, size_t size) : device(device) {
Init(data, size);
}
VulkanShaderModule::VulkanShaderModule(VkDevice device, const std::vector<char>& binary) : device(device) {
Init(binary.data(), binary.size());
}
void VulkanShaderModule::Init(const char* binaryData, size_t size) {
VkShaderModuleCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = size;
createInfo.pCode = reinterpret_cast<const uint32_t*>(binaryData);
// actually create it
if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
throw std::runtime_error("failed to create shader module!");
}
}
VulkanShaderModule& VulkanShaderModule::Steal(VulkanShaderModule& other) {
this->shaderModule = other.shaderModule;
this->device = other.device;
other.shaderModule = VK_NULL_HANDLE;
other.device = VK_NULL_HANDLE;
return *this;
}
void VulkanShaderModule::Free() {
if (shaderModule != VK_NULL_HANDLE) {
vkDestroyShaderModule(device, shaderModule, nullptr);
shaderModule = VK_NULL_HANDLE;
}
}
| true |
b6d01c41394a56a4f7686061afbc2f5190a778c6 | C++ | nopanderer/ps | /star/2446.cpp | UTF-8 | 438 | 3.015625 | 3 | [] | no_license | /**
* Star 9
* 2446
*/
#include <cstdio>
int main(){
int n;
int i,j;
scanf("%d",&n);
for(i=0;i<n-1;i++){
for(j=0;j<i;j++){
printf(" ");
}
for(j=0;j<2*n-1-2*i;j++)
printf("*");
printf("\n");
}
for(i=0;i<n-1;i++){
printf(" ");
}
printf("*\n");
for(i=1;i<n;i++){
for(j=0;j<n-1-i;j++)
printf(" ");
for(j=0;j<2*i+1;j++)
printf("*");
printf("\n");
}
return 0;
}
| true |
54adb9310c8380b1ef5a483d31d88c02bc0e89c1 | C++ | Ra1nWarden/Online-Judges | /UVa/948.cpp | UTF-8 | 701 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstdio>
int fib[41];
using namespace std;
int main() {
fib[0] = 1;
fib[1] = 2;
for(int i = 2; i < 41; i++)
fib[i] = fib[i-1] + fib[i-2];
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int x;
cin >> x;
int xc = x;
string result(41, '0');
int last = -1;
while(xc != 0) {
int* bound = lower_bound(fib, fib + 41, xc);
if(*bound > xc)
bound--;
if(last == -1)
last = bound - fib;
xc -= *bound;
result[bound - fib] = '1';
}
result = result.substr(0, last + 1);
reverse(result.begin(), result.end());
printf("%d = %s (fib)\n", x, result.c_str());
}
return 0;
}
| true |
6a1b672b09cf169348170179a2180c13b68a501e | C++ | kunyuan/FeynCalc | /src/utility/vector.h | UTF-8 | 4,144 | 3.140625 | 3 | [] | no_license |
#ifndef __FeynCalc__vector__
#define __FeynCalc__vector__
#include <initializer_list>
#include <iosfwd>
#include <math.h>
#include <sstream>
#include <vector>
using namespace std;
template <typename T, int D> class Vec {
private:
T _Array[D];
public:
Vec() {}
Vec(std::initializer_list<T> list) {
int i = 0;
for (auto p = list.begin(); p < list.end() && i < D; ++p) {
_Array[i] = *p;
i++;
}
}
Vec(T value) {
for (int j = 0; j < D; ++j)
_Array[j] = value;
}
Vec(T *value) {
for (int j = 0; j < D; ++j)
_Array[j] = value[j];
}
// Vec(Vec &&tmp) { _Array = tmp.begin(); } // move constructor
void CopyToArray(T *target) const {
for (int i = 0; i < D; ++i)
target[i] = _Array[i];
}
T *data() { return _Array; }
const T *begin() const { return _Array; }
const T *end() const { return _Array + D; }
uint size() const { return D; }
T &operator[](int index) { return _Array[index]; }
const T &operator[](int index) const { return _Array[index]; }
Vec operator*(int i) const {
Vec v;
for (int j = 0; j < D; ++j)
v[j] = _Array[j] * i;
return v;
}
Vec operator*(const double &i) const {
Vec v;
for (int j = 0; j < D; ++j)
v[j] = _Array[j] * i;
return v;
}
Vec operator+(const Vec &v2) const {
Vec v;
for (int j = 0; j < D; j++)
v[j] = _Array[j] + v2._Array[j];
return v;
}
Vec operator-(const Vec &v2) const {
Vec v;
for (int j = 0; j < D; ++j)
v[j] = _Array[j] - v2._Array[j];
return v;
}
Vec &operator+=(const Vec &v2) {
for (int j = 0; j < D; ++j)
_Array[j] += v2._Array[j];
return *this;
}
Vec &operator-=(const Vec &v2) {
for (int j = 0; j < D; ++j)
_Array[j] -= v2._Array[j];
return *this;
}
// string PrettyString(){
// std::ostringstream oss;
// oss << *this;
// return "(" + oss.str() + ")";
// }
// template <typename TT>
// friend std::ostream& operator<<(std::ostream& os, const Vec<TT, D>&){
// for (int i = 0; i < D - 1; i++)
// os << v[i] << " ";
// os << v[D - 1];
// return os;
// }
// template <typename TT>
// friend std::istream& operator>>(std::istream& is, Vec<TT, D>&){
// is >> v[0];
// char sep;
// for (int i = 1; i < D; i++) {
// is >> sep >> v[i];
// if (sep != " ")
// is.setstate(ios::failbit);
// }
// return is;
// }
// friend bool operator==(const Vec<int>&, const Vec<int>&);
// friend bool operator==(const Vec<real>&, const Vec<real>&);
double dot(const Vec &v2) const {
double sum = _Array[0] * v2[0];
for (int i = 1; i < D; ++i) {
sum += _Array[i] * v2[i];
}
return sum;
}
double squaredNorm() const {
double sum = _Array[0] * _Array[0];
for (int i = 1; i < D; ++i) {
sum += _Array[i] * _Array[i];
}
return sum;
}
double norm() const {
double sum = _Array[0] * _Array[0];
for (int i = 1; i < D; ++i) {
sum += _Array[i] * _Array[i];
}
return sqrt(sum);
}
};
// bool operator!=(const Vec<int, D>& v1, const Vec<int, D>& v2);
// bool operator!=(const Vec<double, D>& v1, const Vec<double, D>& v2);
// template <typename T, int D>
// double dot(const Vec<T, D> &v1, const Vec<T, D> &v2) {
// double sum = v1[0] * v2[0];
// for (int i = 1; i < D; i++) {
// sum += v1[i] * v2[i];
// }
// return sum;
// }
// template <typename T, int D> double Sum2(const Vec<T, D> &v1) {
// double sum = v1[0] * v1[0];
// for (int i = 1; i < D; i++) {
// sum += v1[i] * v1[i];
// }
// return sum;
// }
// template <typename T, int D> double Norm2(const Vec<T, D> &v1) {
// double sum = v1[0] * v1[0];
// for (int i = 1; i < D; i++) {
// sum += v1[i] * v1[i];
// }
// return sqrt(sum);
// }
template <typename T, int D> std::string ToString(Vec<T, D> value) {
std::ostringstream oss;
oss << "(";
for (int i = 0; i < D; i++) {
oss << value[i] << ", ";
}
oss << ")";
return oss.str();
}
#endif /* defined(__Feynman_Simulator__vector__) */
| true |
02a5199587f208721337750309a331dc9b40b760 | C++ | hernanrocha/opengl | /src/Obj.h | UTF-8 | 5,066 | 2.875 | 3 | [] | no_license | #ifndef _OBJ_H
#define _OBJ_H
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include <vector>
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <gl\glaux.h>
using namespace std;
struct tMaterialInfo
{
char strName[255]; // The texture name
char strFile[255]; // The texture file name (If this is set it's a texture map)
BYTE color[3]; // The color of the object (R, G, B)
int texureId; // the texture ID
float uTile; // u tiling of texture (Currently not used)
float vTile; // v tiling of texture (Currently not used)
float uOffset; // u offset of texture (Currently not used)
float vOffset; // v offset of texture (Currently not used)
} ;
class CVector3
{
public:
float x, y, z;
};
// This is our 2D point class. This will be used to store the UV coordinates.
class CVector2
{
public:
float x, y;
};
// This is our face structure. This is is used for indexing into the vertex
// and texture coordinate arrays. From this information we know which vertices
// from our vertex array go to which face, along with the correct texture coordinates.
struct tFace
{
int vertIndex[3]; // indicies for the verts that make up this triangle
int coordIndex[3]; // indicies for the tex coords to texture this face
};
struct t3DObject
{
int numOfVerts; // The number of verts in the model
int numOfFaces; // The number of faces in the model
int numTexVertex; // The number of texture coordinates
int materialID; // The texture ID to use, which is the index into our texture array
bool bHasTexture; // This is TRUE if there is a texture map for this object
char strName[255]; // The name of the object
CVector3 *pVerts; // The object's vertices
CVector3 *pNormals; // The object's normals
CVector2 *pTexVerts; // The texture's UV coordinates
tFace *pFaces; // The faces information of the object
};
struct t3DModel
{
int numOfObjects; // The number of objects in the model
int numOfMaterials; // The number of materials for the model
vector<tMaterialInfo> pMaterials; // The list of material information (Textures and colors)
vector<t3DObject> pObject; // The object list for our model
};
// This class can be used to load a .Obj file. You will need the grab the
// structures in main.h as well if you want to use this, or create your own.
// I added a couple functions at the end of this class to help with the material
// problem that a .obj file has. Obj files do not save material information, like
// the color, material name or the texture map file assigned to it. Though the .obj
// file format isn't the best used for games, I thought I would help out a little.
// To be honest, it would be better to just add the information to the .obj and
// modify my code to read it in. For instance, put a : c 255 0 255 for the color.
// This is our class for loading .obj files
class CLoadObj {
public:
// This will be the only function that needs to be called by you.
// Just pass in your model that will hold the information and the file name.
bool ImportObj(t3DModel *pModel, char *strFileName);
// This is the main loading loop that gets called in ImportObj()
void ReadObjFile(t3DModel *pModel);
// This is called in ReadObjFile() if we find a line starting with 'v'
void ReadVertexInfo();
// This is called in ReadObjFile() if we find a line starting with 'f'
void ReadFaceInfo();
// This is called when we are finished loading in the face information
void FillInObjectInfo(t3DModel *pModel);
// This isn't necessary for the loader, but it's nice to have vertex normals for lighting
void ComputeNormals(t3DModel *pModel);
// Since .obj files don't have texture/material names, we create a function to set them manually.
// The materialID is the index into the pMaterial array for our model.
void SetObjectMaterial(t3DModel *pModel, int whichObject, int materialID);
// To make it easier to assign a material to a .obj object we create a funtion to do so.
// We can pass in the model, the material name, the texture file name and the RGB colors.
// If we just want a color, pass in NULL for strFile.
void AddMaterial(t3DModel *pModel, char *strName, char *strFile,
int r = 255, int g = 255, int b = 255);
private:
// This holds our file pointer for reading in the file
FILE *m_FilePointer;
// This is an STL (Standard Template Library) vector that holds a list of vertices
vector<CVector3> m_pVertices;
// This is an STL (Standard Template Library) vector that holds a list of faces
vector<tFace> m_pFaces;
// This is an STL (Standard Template Library) vector that holds a list of UV Coordinates
vector<CVector2> m_pTextureCoords;
// This tells us if the current object has texture coordinates
bool m_bObjectHasUV;
// This tells us if we just read in face data so we can keep track of multiple objects
bool m_bJustReadAFace;
};
#endif
| true |
a99abbc9f9789655bf518bc954234c2610b76a0c | C++ | strncat/competitive-programming | /hacker-rank/graph-theory/kruskal-mst-really-special-subtree.cpp | UTF-8 | 2,741 | 3.34375 | 3 | [] | no_license | //
// Hacker Rank
// Kruskal (MST): Really Special Subtree
//
// Created by Fatima B on 12/30/15.
// Copyright © 2015 Fatima B. All rights reserved.
//
#include <iostream>
#include <vector>
#include <queue>
#include <assert.h>
#include <algorithm>
class Edge {
public:
int x;
int y;
int weight;
Edge(int x, int y, int weight) {
this->x = x;
this->y = y;
this->weight = weight;
}
bool operator<(const Edge &e) const { return weight < e.weight; }
};
class Graph {
public:
std::vector<Edge> edges;
int nvertices;
Graph(int nvertices) {
this->nvertices = nvertices;
}
void insertEdge(int x, int y, int weight) {
edges.push_back(Edge(x, y, weight));
}
};
class UnionByRank {
public:
int *leader;
int *rank;
int n;
int count;
UnionByRank(int n) {
this->n = n;
count = n; // initially the number of components is n
leader = new int[n];
rank = new int[n];
for (int i = 1; i <= n; i++) {
leader[i] = i; // each item is in its own component
rank[i] = 0;
}
}
int findOP(int x) { // O(log(n))
while (leader[x] != x) { // go up the tree
leader[x] = leader[leader[x]]; // path compression
x = leader[x];
}
return x;
}
int connected(int x, int y) {
return findOP(x) == findOP(y);
}
void combine(int x, int y) {
int rootX = findOP(x);
int rootY = findOP(y);
if (rootX == rootY) { return; }
// both have the same size, you're putting one under the other so the rank goes up by one
if (rank[rootX] == rank[rootY]) {
leader[rootX] = rootY;
rank[rootY]++;
} else if (rank[rootX] < rank[rootY]) { // otherwise rank doesn't change
leader[rootX] = rootY;
} else {
leader[rootY] = rootX;
}
count--;
}
};
int kruskal(Graph g, int start) {
std::sort(g.edges.begin(), g.edges.end());
UnionByRank ur = UnionByRank(g.nvertices);
// consider each edge
int sum = 0;
for (std::vector<Edge>::iterator i = g.edges.begin(); i != g.edges.end(); i++) {
// if they are not in the same set, we combine them
if (ur.findOP(i->x) != ur.findOP(i->y)) {
ur.combine(i->x, i->y);
sum += i->weight;
}
}
return sum;
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
Graph g(n);
int x, y, weight, start;
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &x, &y, &weight);
g.insertEdge(x, y, weight);
}
scanf("%d", &start);
printf("%d\n", kruskal(g, start));
return 0;
}
| true |
0623bfb900208fdc7e2c72a207317901c7427981 | C++ | HongfeiXu/LeetCode | /project/src/IntersectionOfTwoArraysII.h | UTF-8 | 2,375 | 3.9375 | 4 | [] | no_license | #pragma once
/*
350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Approach:
使用两个 unordered_map 来分别记录 nums1、nums2 中数字及出现次数
对于那些共同存在的数字,出现次数较小的即为相交的部分。
Approach Follow up1:
What if the given array is already sorted? How would you optimize your algorithm?
见 Solution_v2。很nice的分类讨论方式。
What if nums1's size is small compared to nums2's size? Which algorithm is better?
显然,此时 Solution_v2 更合适,此方法中 nums2访问完后,就会结束运行。而Solution则需要构建完整的 unordered_map
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
*/
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2)
{
unordered_map<int, int> um_nums1;
unordered_map<int, int> um_nums2;
for (auto &item : nums1)
++um_nums1[item];
for (auto &item : nums2)
++um_nums2[item];
vector<int> result;
for (auto &item : um_nums1)
{
if (um_nums2.find(item.first) != um_nums2.end())
{
int cnt = min(um_nums2[item.first], item.second);
for (int i = 0; i < cnt; ++i)
result.push_back(item.first);
}
}
return result;
}
};
class Solution_v2 {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2)
{
vector<int> result;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
for (int i = 0, j = 0; i < nums1.size() && j < nums2.size();)
{
if (nums1[i] < nums2[j])
++i;
else if (nums1[i] > nums2[j])
++j;
else
{
result.push_back(nums1[i]);
++i;
++j;
}
}
return result;
}
};
| true |
346eba512915865b8c748088d7a20acc5e6ac286 | C++ | vasta88/CYOE---Zombies | /main.cpp | UTF-8 | 9,135 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
char whilstAB(char); //validates input for ab menus
char whilstABC(char); //validates input for abc menus
#include <iostream>
using namespace std;
int main() {
char choice;
cout<<"This program lets you choose the actions you take in a story."<<endl;
cout<<"Read the story, then read your choices and enter the letter\n";
cout<<"which corresponds with your choice."<<endl;
do {
cout<<"\nYou wake up this morning and go to the kitchen to make some breakfast.\n";
cout<<"What do you make?"<<endl;
cout<<"A - an omelette\n";
cout<<"B - toast\n";
cin>>choice;
choice = whilstAB(choice);
if (choice == 'a' || choice == 'A') {
cout<<"\nYou undercook the eggs and miss school to be sick.\n";
cout<<"You decide to spend the day in bed. What do you do?\n";
cout<<"A - check the news\n";
cout<<"B - watch some tv shows\n";
cout<<"C - read a book\n";
cin>>choice;
choice = whilstABC(choice);
if (choice == 'a' || choice == 'A') {
cout<<"\nYou catch the beginning of the zombie apocalypse on the news\n";
cout<<"just in time to find your friends and flee.\n";
cout<<"You spend the next few months in hiding and fall in love\n";
cout<<"with another survivor. But then the food runs out.\n";
cout<<"Do you: \n";
cout<<"A - Resort to cannibalism and eat your partner\n";
cout<<"B - Kill yourself so you partner can eat you and live longer\n";
cout<<"C - Opt not to become cannibals and take your chances\n";
cin>>choice;
choice = whilstABC(choice);
if (choice == 'a' || choice == 'A') {
cout<<"\nYou eat the love of your life and manage to live a few more\n";
cout<<"weeks. Then the zombies find your hideout and devour you.\n";
}
else if (choice == 'b' || choice == 'B') {
cout<<"Tragically, you are now dead. But your body lets your partner\n";
cout<<"live long enough for rescue to come. They live and remarry\n";
cout<<"and name their first child after you.\n";
}
else {
cout<<"You get a few more days to spend together before you both\n";
cout<<"starve to death a day before you would have been rescued.\n";
}
}
else if (choice == 'b' || choice == 'B'){
cout<<"\nYou stayed home to watch TV and so are unaware that the zombie\n";
cout<<"Apocalypse has begun. They enter your home halfway through\n";
cout<<"a rerun of the simpsons and bite you. Do you: \n";
cout<<"A - kill yourself before you can become one of them\n";
cout<<"B - let yourself become a zombie\n";
cin>>choice;
choice = whilstAB(choice);
if (choice == 'a' || choice == 'A'){
cout<<"\nYou commit suicide. The world as you know it ends.\n";
}
else {
cout<<"\nYou become a zombie and spend the next few days eating\n";
cout<<"people before someone shoots you and ends your killing spree.\n";
}
}
else {
cout<<"\nYou go to pick out a book. Which do you pick? "<<endl;
cout<<"A - How to Survive the Zombie Apocalypse\n";
cout<<"B - How to Grow Your Own Garden\n";
cout<<"C - Shakespeare's Sonnets\n";
cin>>choice;
choice = whilstABC(choice);
if (choice == 'a' || choice == 'A') {
cout<<"\nZombies break down the door to your house. Luckily, you are\n";
cout<<"prepared. You kill them all and go on the run. Do you: \n";
cout<<"A - Find your friends to help them survive\n";
cout<<"B - Put yourself first and try to make it on your own\n";
cin>>choice;
choice = whilstAB(choice);
if (choice == 'a' || choice == 'A') {
cout<<"\nYour bad-ass zombie killing skills keep most of your\n";
cout<<"friends alive. You are elected the new president after\n";
cout<<"the apocalypse. You are granted the power to rebuild\n";
cout<<"the world exactly the way you think it should be.\n";
}
else {
cout<<"You manage to survive the apocalypse, but are shunned\n";
cout<<"by the other survivors for your heartlessness. You build\n";
cout<<"a cabin in the woods and live out the rest of your days\n";
cout<<"as a hermit.\n";
}
}
else if (choice == 'b' || choice == 'B') {
cout<<"The zombies break down your door and you barely manage to\n";
cout<<"escape. You hide in the mountains and survive by growing\n";
cout<<"your own food. Unfortunately, without contact from the outside\n";
cout<<"world you have not way of knowing when the apocalypse ends.\n";
cout<<"you spend the rest of your days hiding, too scared to leave.\n";
}
else {
cout<<"the zombies come into your house. You try to soothe them by\n";
cout<<"reading them sonnets. It hypnotizes them for a few moments.\n";
cout<<"you use this trick to survive the apocalypse, but all that\n";
cout<<"poetry drives you mad, and afterwards you are placed in a\n";
cout<<"mental asylum where you stage productions of A Midsummer\n";
cout<<"Night's Dream over and over again with your fellow patients.\n";
}
}
}
else {
cout<<"You catch the bus to school. Your friend, Joe, who you usually sit\n";
cout<<"with looks sick, so you sit next to someone you've had a crush on all\n";
cout<<"year. Do you: \n";
cout<<"A - Ask them out\n";
cout<<"B - Wait for a better time\n";
cout<<"C - Decide not to ask and hope they ask you\n";
cin>>choice;
choice = whilstABC(choice);
if (choice == 'a' || choice == 'A') {
cout<<"You pluck up the courage to ask if they want to grab a movie with\n";
cout<<"you Monday. They say yes and you hold hands on the way to class\n";
cout<<"Joe comes out of the bathroom a zombie and is headed towards\n";
cout<<"your date. Do you: \n";
cout<<"A - run away\n";
cout<<"B - try to save your date\n";
cin>>choice;
choice = whilstAB(choice);
if (choice == 'a' || choice == 'A') {
cout<<"You flee, your date screams behind you as Joe catches them.\n";
cout<<"Another zombie catches you at the door and devours you.\n";
}
else {
cout<<"You use your backpack to beat Joe the Zombie to the ground,\n";
cout<<"then grab your date and run. You make it out of the school\n";
cout<<"Do you:\n";
cout<<"A - Go home\n";
cout<<"B - Call the cops\n";
cout<<"C - rob a local store for supplies\n";
cin>>choice;
choice = whilstABC(choice);
if (choice == 'a' || choice == 'A'){
cout<<"You make it home, but your parents are already zombies.\n";
cout<<"You and your date are both killed.\n";
}
else if (choice =='b' || choice == 'B'){
cout<<"You call the cops but no one picks up. You stayed too long\n";
cout<<"at the pay phone and a zombie catches you. It turns you\n";
cout<<"into a zombie as well and you kill your date.\n";
}
else {
cout<<"You run to the nearest store to grab food, water, and\n";
cout<<"anything you could use as a weapon. The two of you find\n";
cout<<"a safe place to lay low until help comes a few weeks\n";
cout<<"later.\n";
}
}
}
else if (choice == 'b' || choice == 'B'){
cout<<"You decide to wait for a more opportune moment, but on the way to\n";
cout<<"school joe turns into a zombie and if headed for you. Do you:\n";
cout<<"A - try to fight\n";
cout<<"B - try to run\n";
cin>>choice;
choice = whilstAB(choice);
if (choice == 'a' || choice == 'A'){
cout<<"You manage to fight them off and grab your crush, but friends\n";
cout<<"around you are dying. Do you:\n";
cout<<"A - stay to help them\n";
cout<<"B - take your crush and leave while you can\n";
cin>>choice;
choice = whilstAB(choice);
if (choice == 'a' || choice == 'A') {
cout<<"You stay to help. You and a few other classmates barricade\n";
cout<<"yourselves in the lunch room, fighting off zombies as you\n";
cout<<"go. Some of you starve, but a few of your survive and begin\n";
cout<<"new lives post apocalypse. You marry your school crush.\n";
}
else {
cout<<"You try to run, but you're surrounded. You tell your crush\n";
cout<<"how you feel right before you are both eaten by zombies\n";
}
}
else {
cout<<"You run out, leaving your crush and your classmates to fend\n";
cout<<"for themselves. You survive the apocalypse but everyone you\n";
cout<<"knew is dead. You kill yourself out of shame a year later.\n";
}
}
else {
cout<<"You hope they'll make the first move, but Joe turns into a zombie\n";
cout<<"at school that day, and turns your crush into a zombie as well.\n";
cout<<"you waited too long to tell them. Your crush turns you into a zombie\n";
cout<<"right before a would-be school shooter kills you both and ends up\n";
cout<<"saving the rest of the school and becoming a hero.\n";
}
}
cout<<"Press Q to quit, press any other key to play again: ";
cin>>choice;
}while (choice != 'q' && choice != 'Q');
return 0;
}
//input validation functions
char whilstAB(char choose){
while(choose != 'a' && choose != 'B' && choose != 'b' && choose != 'A'){
cout<<"Please type A or B: ";
cin>>choose;
}
return choose;
}
char whilstABC(char choose){
while(choose != 'a' && choose != 'B' && choose != 'b' && choose != 'A' && choose != 'c' && choose != 'C'){
cout<<"Please type A, B, or C: ";
cin>>choose;
}
return choose;
}
| true |
0a8be8f2b294c1cab8898dd53236d2da65ab26d6 | C++ | mustafamengutay/Basic-Projects-with-Cpp | /SimpleEmployeeProject/src/EmployeeSystem.cpp | UTF-8 | 3,038 | 3.9375 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
const int MAX = 10000;
string names[MAX];
int ages[MAX];
double salaries[MAX];
char genders[MAX];
int added = 0; // number of emloyees
int menu() {
// This function provides to see a process which we will use.
int choice = -1;
while(choice == -1) {
cout << "1) Add a new employee" << endl;
cout << "2) Print all employees" << endl;
cout << "3) Delete by age" << endl;
cout << "4) Update Salary by name" << endl;
cout << "5) Exit" << endl;
cin >> choice;
if (choice == 5)
abort();
if (!(1 <= choice && choice <=5)) {
cout << "Invalid choice. Please try again!" << endl;
choice = -1;
}
}
return choice;
}
void addEmployee() {
// This function provides to add new users.
cout << "Enter a name:";
cin >> names[added];
cout << endl;
cout << "Enter an age:";
cin >> ages[added];
cout << endl;
cout << "Enter salary:";
cin >> salaries[added];
cout << endl;
cout << "Enter a gender (M/F):";
cin >> genders[added];
cout << endl;
added++;
}
void printEmployees() {
// This function provides to see all users.
for (int i = 0; i < added; i++) {
if (ages[i] != -1) {
cout << names[i] <<" "<< ages[i] <<" "<< salaries[i] <<" "<< genders[i] << endl;
}
}
}
void deleteByAge() {
/*
This function provides to delete the user by age.
we enter the starting age and the ending age to delete an user.
*/
int start, end;
cout << "Enter start and end age: " << endl;
cin >> start >> end;
for (int i = 0; i < added; i++) {
if (start <= ages[i] && ages[i] <= end)
ages[i] = -1;
}
}
void updateSalary() {
// This function provides to update the user salary.
string name;
int salary;
cout << "Enter the name and salary: ";
cin >> name >> salary;
cout << endl;
bool found = false;
for (int i = 0; i < added; i++) {
if (ages[i] != -1 && names[i] == name) {
found = true;
salaries[i] = salary;
break;
}
}
if (!found)
cout << "No employee with this name" << endl;
}
void employeeSystem() {
// This function provides to select a process which we will use.
while (true) {
switch(menu()) {
case 1:
addEmployee();
break;
case 2:
printEmployees();
break;
case 3:
deleteByAge();
break;
case 4:
updateSalary();
break;
default:
cout << "Invalid Value. Try Again!" << endl;
}
}
}
int main() {
employeeSystem();
return 0;
} | true |
fe945550843911c052c6638b85bd952ab270d6c3 | C++ | pankajkumar9797/hangMan | /hangMan.cpp | UTF-8 | 2,603 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <random>
#include <algorithm>
using namespace std;
class hangMan{
private:
string word;
string update_word;
int chances_left;
bool game_over;
string select_word();
void update_game_status(char user_input);
void printF();
public:
hangMan(string word = "anonymous", int chances_left = 5, bool game_over = false):
word(word), chances_left(chances_left), game_over(game_over){
select_word() ;
}
void play();
};
string hangMan::select_word() {
ifstream inputFile;
vector<string> temp;
string temp_string;
string randomWord;
string temp_word;
unsigned int MIN = 0;
unsigned int randomNumber;
unsigned int i = 0;
inputFile.open("inputFile.dat");
while(inputFile >> temp_string){
temp.push_back(temp_string);
i++;
}
inputFile.close();
srand(static_cast<unsigned int>(time(0)));
random_shuffle(temp.begin(), temp.end());
randomWord = temp[0];
string::iterator iterator1;
for (iterator1 = randomWord.begin(); iterator1 != randomWord.end(); ++iterator1) {
temp_word += "#";
}
word = randomWord;
update_word = temp_word;
return word;
}
void hangMan::update_game_status(char user_input) {
string answer;
answer = word;
string::iterator it;
int i;
char temp_char;
for (it = answer.begin(), i = 0; it != answer.end(); ++it, ++i) {
if(user_input == *it){
update_word[i] = answer[i];
temp_char = *it;
}
}
if(temp_char != user_input){
chances_left = this->chances_left - 1 ;
}
cout << "update game status word: "<< update_word << endl;
}
void hangMan::printF(){
cout << "Chances left: " << chances_left << endl;
cout << "updated word: "<< update_word << endl;
}
void hangMan::play(){
char user_input;
while(chances_left > 0){
cout << "Word is: " << update_word <<", ";
cout << "Please enter the character: " << endl;
cin >> user_input;
update_game_status(user_input);
printF();
if (update_word == word){
cout << "Congratulations! you've won the game!" << endl;
exit(1);
}
else if (chances_left == 0){
cout << "Word was: " << word << endl;
}
}
}
int main() {
cout << "game starts now: ";
vector<string> word;
hangMan hangman("anonymous", 5, false);
hangman.play();
return 0;
} | true |
8030ff39030c540b766db59e5a473a63b7a601d8 | C++ | Delaunay/Kiwi | /src/TaskRunner/main.cpp | UTF-8 | 3,326 | 3.453125 | 3 | [] | no_license | /*#include <vector>
#include <cassert>
template <typename E>
class MatrixExpression {
public:
typedef typename E::Scalar Scalar;
Scalar operator()(size_t x, size_t y) const { return static_cast<E const&>(*this)(x, y); }
size_t cols() const { return static_cast<E const&>(*this).cols(); }
size_t rows() const { return static_cast<E const&>(*this).rows(); }
size_t size() const { return cols() * size(); }
// The following overload conversions to E, the template argument type;
// e.g., for VecExpression<VecSum>, this is a conversion to VecSum.
operator E& () { return static_cast<E&>(*this); }
operator const E& () const { return static_cast<const E&>(*this); }
};
template <typename T>
class Matrix: public MatrixExpression<Matrix<T>> {
size_t _rows;
size_t _cols;
std::vector<T> _elems;
public:
typedef typename T Scalar;
Matrix(size_t n, size_t m):
_rows(n), _cols(m), _elems(n * m)
{}
// A Vec can be constructed from any VecExpression, forcing its evaluation.
template <typename E>
Matrix(MatrixExpression<E> const& vec):
_rows(vec.rows()), _cols(vec.cols()), _elems(vec.size())
{
for (size_t i = 0; i < _rows; ++i) {
for (size_t j = 0; j < _cols; ++j) {
_elems[i + j * _rows] = vec(i, j);
}
}
}
T operator ()(size_t x, size_t y) const { return _elems[x + y * _rows]; }
T &operator()(size_t x, size_t y) { return _elems[x + y * _rows]; }
size_t cols() const { return _cols; }
size_t rows() const { return _rows; }
size_t size() const { return _elems.size(); }
};
template <typename E1, typename E2>
class MatrixSum: public MatrixExpression<MatrixSum<E1, E2> > {
E1 const& _u;
E2 const& _v;
public:
typedef typename E1::Scalar Scalar;
MatrixSum(E1 const& u, E2 const& v):
_u(u), _v(v)
{
std::cout << "SUM" << std::endl;
assert(u.cols() == v.cols() && u.rows() == v.rows());
}
Scalar operator ()(size_t x, size_t y) const { return _u(x, y) + _v(x, y); }
size_t cols() const { return _v.cols(); }
size_t rows() const { return _v.rows(); }
size_t size() const { return _v.size(); }
};
template <typename E1, typename E2>
class MatrixMult : public MatrixExpression<MatrixMult<E1, E2> > {
E1 const& _u;
E2 const& _v;
public:
typedef typename E1::Scalar Scalar;
MatrixMult(E1 const& u, E2 const& v) : _u(u), _v(v) {
assert(u.cols() == u.rows());
}
Scalar operator ()(size_t x, size_t y) const {
T value = 0;
for (size_t i = 0; i < _u.cols(); ++i)
value += _u(x, i) * _v(i, y);
return value;
}
size_t cols() const { return _u.cols(); }
size_t rows() const { return _v.rows(); }
size_t size() const { return _u.size(); }
};
template<typename E1, typename E2>
MatrixMult<E1, E2> const operator*(E1 const& u, E2 const& v) {
return MatrixMult<E1, E2>(u, v);
}
template<typename E1, typename E2>
MatrixSum<E1, E2> const operator+(E1 const& u, E2 const& v) {
return MatrixSum<E1, E2>(u, v);
}
#include<iostream>
int main(){
Matrix<double> a(10, 10);
Matrix<double> b(10, 10);
Matrix<double>::Scalar g;
for (int i = 0; i < 10; ++i){
for (int j = 0; j < 10; ++j) {
a(i, j) = i + j;
b(i, j) = i * j;
}
}
auto c = b + a + b;
//Matrix<double> c = a + b;
for (int i = 0; i < 10; ++i){
for (int j = 0; j < 10; ++j) {
std::cout << c(i, j) << "\t";
}
std::cout << "\n";
}
return 0;
}*/
| true |
442a23df06c44a777771393d278b44d8bfbf53ad | C++ | corn-eliu/runsepprun | /RunServerRun/ConnectionSender.cpp | UTF-8 | 1,196 | 2.515625 | 3 | [] | no_license | #include "ConnectionSender.h"
#include "Globals.h"
#include "Server.h"
#include "LogicEngine.h"
/*!
* the thread is contructed
*/
ConnectionSender::ConnectionSender(Server *s)
{
running = false;
server = s;
udpSocket = new QUdpSocket();
udpSocket->moveToThread(this);
}
//! Closes the socket and destroyes the object.
ConnectionSender::~ConnectionSender()
{
stopSend();
udpSocket->close();
delete udpSocket;
udpSocket = NULL;
}
//! Stops the thread.
void ConnectionSender::stopSend()
{
running = false;
sleep(4);
}
/*!
* The thread starts, the threads sleeps for a time seconds
*/
void ConnectionSender::run()
{
running = true;
while(running)
{
msleep(SEND_INT);
send();
}
}
void ConnectionSender::send()
{
QByteArray* packet = server->getLogic()->getActualPositions();
packet->prepend(ITEM_PACKET);
for(int i = 0; i < server->getClientList()->size(); i++)
{
if(udpSocket->writeDatagram(*packet, server->getClientList()->at(i)->ip, CLIENT_INCOMING_PORT_UDP + server->getClientList()->at(i)->id) == -1)
qDebug() << "Could not send update packet";
}
delete packet;
}
| true |
c51bd22e16d08b88f2ed4c4d02e61790c3e6710b | C++ | aratalin/write_more_code | /174_dungeon_game_H_dp.cpp | UTF-8 | 801 | 2.515625 | 3 | [] | no_license | class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
if (dungeon.size() == 0) return 0;
int n = dungeon.size(), m = dungeon[0].size();
vector<vector<int>>dp(n, vector<int>(m, INT_MAX));
if(dungeon[n-1][m-1] >= 0) dp[n-1][m-1] = 0;
else dp[n-1][m-1] = - dungeon[n-1][m-1];
for(int i = n - 1; i >= 0; i--){
for(int j = m - 1; j >= 0; j--){
if(i < n - 1){
dp[i][j] = dp[i+1][j] - dungeon[i][j];
}
if(j < m - 1){
dp[i][j] = min(dp[i][j], dp[i][j+1] - dungeon[i][j]);
}
dp[i][j] = max(0, dp[i][j]);
}
}
return dp[0][0] +1;
}
}; | true |
1038154ff0ca81a0d3061de56921bd27869bf8e6 | C++ | RodicaMihaelaVasilescu/AdventOfCode2018 | /#11/day11.cpp | UTF-8 | 2,071 | 3.0625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define N 301
using namespace std;
tuple<int, int, int, int> Solve(vector<vector<int>> matrix, int k)
{
int topLeftCornerX, topLeftCornerY, squareLength, sumMax = INT_MIN;
vector<vector<int>> partialSum(N,vector<int>(N)) ;
for (int j = 0; j < N; j++)
{
int sum = 0;
for (int i = 0; i < k; i++)
{
sum += matrix[i][j];
}
for (int i = 1; i < N - k + 1; i++)
{
sum += matrix[i+k-1][j] - matrix[i-1][j];
partialSum[i][j] = sum;
}
}
for (int i = 0; i < N - k + 1; i++)
{
int sum = accumulate(partialSum[i].begin(), partialSum[i].begin() + k, 0);
for (int j = 1; j < N-k+1; j++)
{
sum += partialSum[i][j+k-1] - partialSum[i][j-1];
if (sum > sumMax)
{
topLeftCornerX = i;
topLeftCornerY = j;
squareLength = k;
sumMax = sum;
}
}
}
return make_tuple( topLeftCornerX, topLeftCornerY, squareLength, sumMax);
}
int main()
{
ifstream cin("in.txt");
//ofstream cout("out.txt");
vector<vector<int>> matrix(N,vector<int>(N)) ;
int input;
cin >> input;
for(int i = 1; i < N; i++)
{
for(int j = 1; j < N; j++)
{
matrix[i][j] = (((i+10)*j + input)*(i+10))/100%10-5;
}
}
///Part1
auto largest3x3Square = Solve(matrix, 3);
cout << "Part1: " << get<0>(largest3x3Square) << "," << get<1>(largest3x3Square) <<endl;
///Part2
tuple<int, int, int, int> largestSquare;
for(int k = 1; k < N; k++)
{
auto largestKxKSquare = Solve(matrix, k);
if(get<3> (largestKxKSquare) > get<3>(largestSquare))
{
largestSquare = largestKxKSquare;
}
}
cout << "Part2: " << get<0>(largestSquare) << "," << get<1>(largestSquare) << "," << get<2>(largestSquare);
return 0;
}
| true |
e31208081ad6bfdddfd653bc08002f6458fba095 | C++ | harem123/Git | /Sensado celdas/AtomSensado/AtomSensado.ino | UTF-8 | 2,369 | 2.671875 | 3 | [] | no_license |
const int En_WrRd_RS485 = 2;
const int Led_1 = 13;
const int Led_2 = 6;
const int Led_3 = 5;
// ++ pines de sensado my pins y pin de salida
int myPins[] = {7, 8,9};
int sN=00;
boolean flag;
// ++++++++++++++++++++++++++++++
// variables de buffering
char VarChar = ' ';
String BufferIn = "";
boolean StringCompleta = false;
// variables temporizador
unsigned long currentSec;
unsigned long previousSec;
void setup()
{
//++ defino pines de entrada
for(int j= 0 ; j <2; j++){
pinMode(myPins[j],INPUT);}
// +++
Serial.begin(9600);
BufferIn.reserve(6);
pinMode(En_WrRd_RS485, OUTPUT);
pinMode(Led_1, OUTPUT);
pinMode(Led_2, OUTPUT);
pinMode(Led_3, OUTPUT);
digitalWrite(En_WrRd_RS485, LOW);
digitalWrite(Led_1, LOW);
digitalWrite(Led_2, LOW);
digitalWrite(Led_3, LOW);
}
void loop()
{
if (StringCompleta)
{
delay(50);
digitalWrite(En_WrRd_RS485, LOW); // pongo pin en LOW para habilitar RS 485
Serial.print(BufferIn);
if ((BufferIn.indexOf('C')) >= 0) // leo el identificador de la placa sensores
{
if (BufferIn.indexOf('1' ) >= 0) // leo el comando de inicio de sensado
{
flag = true; // permito ingresar al while
Serial.println("OK");
delay(100);
currentSec = millis();
previousSec = currentSec; // inicio temporizadores
while(flag == true && (currentSec - previousSec) < 5000)
{
digitalWrite(Led_2, HIGH);
for(int i = 0; i<3; i++) // ciclo de 5 ms para 32 celdas
{
if (digitalRead(myPins[i]) == HIGH)
{
sN = i;
Serial.println(sN);
flag = false;
}
}
currentSec = millis();
}
delay(500);
digitalWrite(Led_2, LOW);
Serial.println("C");
Serial.println(sN);
Serial.println("#");
}
}
StringCompleta = false;
BufferIn = "";
}
}
void serialEvent() {
while (Serial.available())
{
VarChar = (char)Serial.read();
BufferIn += VarChar;
if (VarChar == 'Z') { StringCompleta = true; }
}
}
| true |
e93e9066ac5f476496baca2bc5b1a17726078e5c | C++ | endurodave/StateMachine | /SelfTest.cpp | UTF-8 | 1,869 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "SelfTest.h"
#include <iostream>
using namespace std;
SelfTest::SelfTest(INT maxStates) :
StateMachine(maxStates)
{
}
void SelfTest::Cancel()
{
#if 1
// External event functions in a state machine base class may use a partial transition
// map if preceded by PARENT_TRANSITION. The partial transition map only includes
// entries up to the number of states known at the current level within the
// hierarchy. PARENT_TRANSITION must be used in anything but the most-derived
// state machine class. The macro is as a catch-all used to capture the transition
// to use when the state machine current state is in a parent state. The statement
// below is read "If the Cancel event is generated when the state machine is not in
// ST_IDLE, ST_COMPLETE, or ST_FAILED then transition to the ST_FAILED state".
// If the base Cancel event is not appropriate for some parent classes, make Cancel()
// virtual and define Cancel() in the derived class with a full transition map.
PARENT_TRANSITION (ST_FAILED)
BEGIN_TRANSITION_MAP // - Current State -
TRANSITION_MAP_ENTRY (EVENT_IGNORED) // ST_IDLE
TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_COMPLETED
TRANSITION_MAP_ENTRY (CANNOT_HAPPEN) // ST_FAILED
END_TRANSITION_MAP(NULL)
#else
// Alternatively external events can be generated manually without a
// transition map.
if (GetCurrentState() != ST_IDLE)
ExternalEvent(ST_FAILED);
#endif
}
STATE_DEFINE(SelfTest, Idle, NoEventData)
{
cout << "SelfTest::ST_Idle" << endl;
}
ENTRY_DEFINE(SelfTest, EntryIdle, NoEventData)
{
cout << "SelfTest::EN_EntryIdle" << endl;
}
STATE_DEFINE(SelfTest, Completed, NoEventData)
{
cout << "SelfTest::ST_Completed" << endl;
InternalEvent(ST_IDLE);
}
STATE_DEFINE(SelfTest, Failed, NoEventData)
{
cout << "SelfTest::ST_Failed" << endl;
InternalEvent(ST_IDLE);
}
| true |
13e67e2a890c9c74b858f4cf566121199aa0724a | C++ | chaoaero/leetcode_answers | /valid_parentheses.cc | UTF-8 | 1,174 | 3.3125 | 3 | [] | no_license | /*==================================================================
* Copyright (C) 2015 All rights reserved.
*
* filename: valid_parentheses.cc
* author: Meng Weichao
* created: 2015/11/10
* description:
*
================================================================*/
#include<iostream>
#include<string>
#include<vector>
#include<stdint.h>
#include <climits>
#include<algorithm>
#include<stack>
using namespace std;
bool isMatch(char s, char t) {
if((s == '(' && t == ')') || (s == '[' && t == ']') || ( s == '{' && t == '}'))
return true;
return false;
}
bool isValid(string s) {
int str_size = s.size();
if(str_size % 2 != 0)
return false;
stack<char> stk;
for(int i = 0; i< str_size ; i++) {
cout<<s[i]<<endl;
if(stk.empty())
stk.push(s[i]);
else {
char t = stk.top();
if(isMatch(t, s[i]))
stk.pop();
else
stk.push(s[i]);
}
}
if(stk.empty())
return true;
return false;
}
int main() {
string s;
cin>>s;
cout<<isValid(s)<<endl;
return 0;
}
| true |
673dda9395ade5e61ba9cdcb1498d351c14a5a0d | C++ | evelyn-plee/leetcode | /547_FriendCircles/solution3.cpp | UTF-8 | 1,534 | 3.453125 | 3 | [] | no_license | /**
Union-find
time complexity:O(n^3). Traverse the complete matrix once. Union and find operations take O(n) time in worst case.
space complexity: O(n). Parent array of size n is used.
**/
#include <vector>
#include <unordered_set>
using namespace std;
class UnionFindSet {
public:
UnionFindSet(int n) {
parents_ = vector<int>(n + 1, 0);
ranks_ = vector<int>(n + 1, 0);
for (int i = 0; i < parents_.size(); ++i)
parents_[i] = i;
}
bool Union(int u, int v) {
int pu = Find(u);
int pv = Find(v);
if (pu == pv) return false;
if (ranks_[pu] > ranks_[pv]) {
parents_[pv] = pu;
} else if (ranks_[pv] > ranks_[pu]) {
parents_[pu] = pv;
} else {
parents_[pu] = pv;
++ranks_[pv];
}
return true;
}
int Find(int id) {
if (id != parents_[id])
parents_[id] = Find(parents_[id]);
return parents_[id];
}
private:
vector<int> parents_;
vector<int> ranks_;
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
int n = M.size();
UnionFindSet s(n);
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
if (M[i][j] == 1) s.Union(i, j);
unordered_set<int> circles;
for (int i = 0; i < n; ++i)
circles.insert(s.Find(i));
return circles.size();
}
};
| true |
ab2d194e36832ef931ba465f4b60b770b1857a47 | C++ | RedXtreme99/utd_projects | /Unix_C++/Project2/Program2Turnin/program2.cpp | UTF-8 | 1,623 | 3.328125 | 3 | [] | no_license | /*
Filename program2.cpp
Date 2/7/2019
Author Basil Elhindi
Email bae170000
Course CS 3377.502 Spring 2019
Version 1.0
Copyright 2019, All Rights Reserved
Description
File containing main that calls the command line parser and reads the input file and writes it to an output file in the correct case.
*/
#include <iostream>
#include <fstream>
#include "header.h"
#include <cctype>
using namespace std;
//define map in just one place
map<int, string> myMap;
int main(int argc, char* argv[])
{
//send the command line arguments to be parsed
parseCommandLine(argc, argv);
//take the input and output file from the map and open the streams to be read from and wrote to
ifstream inputfile (myMap[INFILENAME]);
ofstream outputfile (myMap[OUTFILENAME]);
//check for u or l flag and capitalize appropriately. traverse the entire input file and print the output to the output file
char c;
if(inputfile.is_open())
{
if(myMap[UFLAG] == "true")
{
while(inputfile.get(c))
{
if(c == '\n')
outputfile << endl;
else outputfile << static_cast<char>(toupper(c));
}
}
else if(myMap[LFLAG] == "true")
{
while(inputfile.get(c))
{
if(c == '\n')
outputfile << endl;
else outputfile << static_cast<char>(tolower(c));
}
}
else
{
while(inputfile.get(c))
{
if(c == '\n')
outputfile << endl;
else outputfile << c;
}
}
}
else {cerr << "error"; return 1;}
//close the input and output streams and exit the code
outputfile.close();
inputfile.close();
return 0;
}
| true |
57ce53ca9e217fcbd3b1d5b13d2740ed0c4cabf0 | C++ | lutfulrafi/190041210-CSE-4302 | /Lab4/190041210_Task3.cpp | UTF-8 | 1,036 | 3.890625 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
class Employee
{
private:
string EmpName;
int ID;
int age;
float salary;
public:
void FeedInfo(string name,int i,int a,float sal)
{
EmpName=name;
ID=i;
age=a;
salary=sal;
}
string getStatus()
{
string status;
if(age<=25 && salary<=20000)
status="Low";
if(age<=25 && salary>20000)
status="Moderate";
if(age>25 && salary<=21000)
status="Low";
if(age>25 && (salary>21000 && salary<=60000))
status="Moderate";
if(age>25 && salary>60000)
status="High";
return status;
}
void ShowInfo()
{
cout<<"Employee Name: "<<EmpName<<endl;
cout<<"ID: "<<ID<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Salary: "<<salary<<endl;
cout<<"Status: "<<getStatus()<<endl;
}
};
int main()
{
Employee e;
e.FeedInfo("Rafi",10,21,21000);
e.ShowInfo();
}
| true |
b9b7b2ad8472536b64d0aedcc87a694afb8debc3 | C++ | MaksShizo/19 | /Stack_c.h | UTF-8 | 195 | 2.640625 | 3 | [] | no_license | #pragma once
class Stack_c
{
private:
struct Stack
{
char data[20];
Stack* next;
};
Stack* stack;
int n;
Stack* make_stack();
public:
void add_to_stack();
void print_stack();
};
| true |
6270903724cbe46a38bd7042cfc1ce6a198d64cf | C++ | AMJAeioLuz/Personal | /Sensores_y_Modulos/Mandar_lectura_temperatura_por_SERIAL/Mandar_lectura_temperatura_por_SERIAL.ino | UTF-8 | 1,746 | 3.03125 | 3 | [] | no_license | #include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
inline size_t LiquidCrystal_I2C::write(uint8_t value) {
send(value, Rs);
return 1;
}
const int sensor = A0; //entrada del sensor LM35-1
const int sensor1 = A1; //entrada del sensor LM35-2
long miliVolts;
long temperatura;
long miliVolts1;
long temperatura1;
byte simGrad[8] = {
B00110,
B01001,
B01001,
B00110,
B00000,
B00000,
B00000,
B00000,
};
void setup() {
Serial.begin(9600); //Iniciamos comunicación serial
// initialize the LCD
lcd.begin();
// Turn on the blacklight and print a message.
lcd.backlight();
lcd.createChar(1, simGrad);
}
void loop() {
miliVolts = (analogRead(sensor) * 5000L) / 1023; //Calculamos los Mv en la entrada
temperatura = miliVolts / 10; //Calculamos la temperatura
miliVolts1 = (analogRead(sensor1) * 5000L) / 1023; //Calculamos los Mv en la entrada
temperatura1 = miliVolts1 / 10; //Calculamos la temperatura
Serial.print("Temperatura: "); //mandamos la temperatura por
Serial.print(temperatura1); //serial
Serial.println(" grados");
delay(300); //Esperamos para no saturar la consola
lcd.setCursor(1,0);
lcd.print("Temperatura S1");
lcd.setCursor(6,1);
lcd.print(temperatura);
lcd.write(byte(1));
lcd.print("C");
delay(2000);
lcd.clear();
lcd.setCursor(1,0);
lcd.print("Temperatura S2");
lcd.setCursor(6,1);
lcd.print(temperatura1);
lcd.write(byte(1));
lcd.print("C");
delay(2000);
}
| true |
0b2203cce9d7116a48e2d28f2119797aedee204d | C++ | qliu67/compiler | /compiler/LivenessAnalysis.cpp | UTF-8 | 6,952 | 2.609375 | 3 | [] | no_license | #include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/InstIterator.h"
#include "231DFA.h"
#include <set>
#include <algorithm>
using namespace llvm;
using namespace std;
namespace llvm{
class LiveInfo : public Info{
public:
~LiveInfo() {}
/*
* Print out the information
*
* Direction:
* In your subclass you should implement this function according to the project specifications.
*/
void print(){
for(auto def : definedInstructions){
errs() << def << "|";
}
errs() << "\n";
}
/*
* Compare two pieces of information
*
* Direction:
* In your subclass you need to implement this function.
*/
static bool equals(LiveInfo * info1, LiveInfo * info2){
return info1->definedInstructions == info2->definedInstructions;
}
/*
* Join two pieces of information.
* The third parameter points to the result.
*
* Direction:
* In your subclass you need to implement this function.
*/
static LiveInfo* join(LiveInfo * info1, LiveInfo * info2, LiveInfo * result){
result->definedInstructions.insert(info1->definedInstructions.begin(), info1->definedInstructions.end());
result->definedInstructions.insert(info2->definedInstructions.begin(), info2->definedInstructions.end());
return result;
}
static void join(LiveInfo * info1, LiveInfo * result){
result->definedInstructions.insert(info1->definedInstructions.begin(), info1->definedInstructions.end());
}
set<unsigned> definedInstructions;
};
class LivenessAnalysis : public DataFlowAnalysis<LiveInfo, false>{
public:
LivenessAnalysis(LiveInfo info):
DataFlowAnalysis<LiveInfo, false>(info, info){}
void flowfunction(Instruction * I,
std::vector<unsigned> & IncomingEdges,
std::vector<unsigned> & OutgoingEdges,
std::vector<LiveInfo *> & Infos) {
unsigned instrIdx = InstrToIndex[I];
LiveInfo* tempInfo = new LiveInfo();
Infos.resize(OutgoingEdges.size());
for (auto incoming : IncomingEdges){
Edge edge = Edge(incoming, instrIdx);
LiveInfo* incomingInfo = EdgeToInfo[edge];
LiveInfo::join(incomingInfo, tempInfo);
}
unsigned opcode = I->getOpcode();
// alloca, load, getelementptr
// icmp, fcmp, select, call
if(opcode == 29 || opcode == 30 || opcode == 32 ||
opcode == 51 || opcode == 52 || opcode == 55 ||
I->isBinaryOp() ){
for (Use &U : I->operands()) {
Value *v = U.get();
if(InstrToIndex.find((Instruction*) v) != InstrToIndex.end()){
tempInfo->definedInstructions.insert(InstrToIndex[llvm::cast<llvm::Instruction>(v)]);
}
}
tempInfo->definedInstructions.erase(instrIdx);
for(int i = 0 , size = OutgoingEdges.size() ; i < size ; i++){
LiveInfo* newInfo = new LiveInfo();
newInfo->definedInstructions = tempInfo->definedInstructions;
Infos[i] = newInfo;
}
}else if (opcode == 54){ //Call
CallInst* callInst = (CallInst*) I;
for (unsigned i = 0, ie = callInst->getNumArgOperands() ; i < ie ; i++) {
Value *v = callInst->getArgOperand(i);
if(InstrToIndex.find((Instruction*) v) != InstrToIndex.end()){
tempInfo->definedInstructions.insert(InstrToIndex[llvm::cast<llvm::Instruction>(v)]);
}
}
for(int i = 0 , size = OutgoingEdges.size() ; i < size ; i++){
LiveInfo* newInfo = new LiveInfo();
newInfo->definedInstructions = tempInfo->definedInstructions;
Infos[i] = newInfo;
}
}else if(opcode == 2 || opcode == 3 || opcode == 31 || opcode == 1
){ // br, switch, store, ret
for (Use &U : I->operands()) {
Value *v = U.get();
if(InstrToIndex.find((Instruction*) v) != InstrToIndex.end()){
tempInfo->definedInstructions.insert(InstrToIndex[llvm::cast<llvm::Instruction>(v)]);
}
}
for(int i = 0 , size = OutgoingEdges.size() ; i < size ; i++){
LiveInfo* newInfo = new LiveInfo();
newInfo->definedInstructions = tempInfo->definedInstructions;
Infos[i] = newInfo;
}
}else if(opcode == 53){ //Phi
// tempInfo->definedInstructions.erase(InstrToIndex[llvm::cast<llvm::Instruction>(I->getOperand(0))]);
// tempInfo->definedInstructions.erase(InstrToIndex[llvm::cast<llvm::Instruction>(I->getOperand(1))]);
// tempInfo->definedInstructions.insert(instrIdx);
BasicBlock* block = I->getParent();
for (auto ii = block->begin(), ie = block->end(); ii != ie; ++ii) {
Instruction * instr = &*ii;
if (isa<PHINode>(instr)){
tempInfo->definedInstructions.erase(InstrToIndex[instr]);
}
}
for(int j = 0, je = OutgoingEdges.size() ; j < je ; j++){
Infos[j] = new LiveInfo();
Infos[j]->definedInstructions = tempInfo->definedInstructions;
}
for (auto ii = block->begin(), ie = block->end(); ii != ie ; ++ii) {
Instruction * instr = &*ii;
if (isa<PHINode>(instr)){
PHINode* phiInstr = (PHINode*) instr;
for(unsigned i = 0, ie = phiInstr->getNumIncomingValues() ;
i < ie ; i++){
Instruction* phiValue = (Instruction*)(phiInstr->getIncomingValue(i));
if(InstrToIndex.find((Instruction*) phiValue) == InstrToIndex.end()){
continue;
}
BasicBlock* phiLabel = phiInstr->getIncomingBlock(i);
Instruction* prevInstr = (Instruction *)phiLabel->getTerminator();
unsigned prevInstrIndex = InstrToIndex[prevInstr];
for(int j = 0, je = OutgoingEdges.size() ; j < je ; j++){
if(OutgoingEdges[j] == prevInstrIndex){
Infos[j]->definedInstructions.insert(InstrToIndex[phiValue]);
}
}
}
}
}
}else{
for(int i = 0 , size = OutgoingEdges.size() ; i < size ; i++){
LiveInfo* newInfo = new LiveInfo();
newInfo->definedInstructions = tempInfo->definedInstructions;
Infos[i] = newInfo;
}
}
delete tempInfo;
}
};
struct LivenessAnalysisPass : public FunctionPass {
static char ID;
LivenessAnalysisPass() : FunctionPass(ID) {
}
bool runOnFunction(Function &F) override {
LiveInfo baseInfo;
LivenessAnalysis analysis(baseInfo);
analysis.runWorklistAlgorithm(&F);
analysis.print();
return false;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
}; // end of struct Hello
} // end of anonymous namespace
char LivenessAnalysisPass::ID = 0;
static RegisterPass<LivenessAnalysisPass> X("cse231-liveness", "LivenessAnalysis",
false /* Only looks at CFG */,
false /* Analysis Pass */); | true |
c32005a12312b612f784088554cf397f75c6517b | C++ | MadMuck/fk | /Games/20189004_潮汕麻将/GameCode/Server/majiang/PatternFinder/PatternResultCards.cpp | UTF-8 | 782 | 2.796875 | 3 | [] | no_license | #include "PatternResultCards.h"
PatternResultCardsImpl::PatternResultCardsImpl(int type, const CardList &cards):m_Type(type), m_Cards(cards)
{
for(int i = 0; i < m_Cards.size(); ++i)
{
m_IsJoker.push_back(0);
}
}
PatternResultCardsImpl::PatternResultCardsImpl(int type, const CardList &cards, const CardList &isJoker):m_Type(type), m_Cards(cards), m_IsJoker(isJoker)
{
}
int PatternResultCardsImpl::Type() const
{
return m_Type;
}
void PatternResultCardsImpl::Consume(CardStatistic &stat) const
{
stat.Sub(m_Cards);
}
void PatternResultCardsImpl::Recover(CardStatistic &stat) const
{
stat.Add(m_Cards);
}
const CardList &PatternResultCardsImpl::GetCards() const
{
return m_Cards;
}
const CardList &PatternResultCardsImpl::GetIsJoker() const
{
return m_IsJoker;
}
| true |
48413125774e62239f86a71a95d8a4c603b88763 | C++ | samsank06/my-learnings | /oops-c++/constructors1.cpp | UTF-8 | 543 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class constr{
private:
int a,b;
public:
constr()
{
a=30;
b=40;
}
void display()
{
cout<<"a= "<<a<<endl<<"b="<<b<<endl;
}
~constr()
{
cout<<"a= "<<a<<" "<<"b= "<<b<<endl;
}
};
int main()
{
constr con1; //if n objects are created then constructor is called n times;
// con1.display();
return 0;
} | true |
4d38a93b1445e5d3cca376a398ccee0265f4c8ae | C++ | mguillemot/kamaku.foliage | /foliage/leaf_graphic/graphic_types.hpp | UTF-8 | 2,345 | 3.109375 | 3 | [] | no_license | #ifndef __FOLIAGE_GRAPHIC_TYPES
#define __FOLIAGE_GRAPHIC_TYPES
#include <iostream>
#include "../basic_types.hpp"
#include "../settings.hpp"
#include "../fastmath.hpp"
namespace Foliage
{
typedef Uint16 Color;
enum ScreenMode { YOKO, TATE };
struct Size
{
Sint16 w, h;
Size() : w(0), h(0)
{
}
Size(const Sint16 sw, const Sint16 sh)
: w(sw), h(sh)
{
}
Size inverted() const
{
return Size(h, w);
}
};
struct Point
{
Sint16 x, y;
Point() : x(0), y(0)
{
}
Point(const Sint16 px, const Sint16 py)
: x(px), y(py)
{
}
static Fixed angleBetween(const Point from, const Point to)
{
const Sint16 dx = to.x - from.x;
const Sint16 dy = to.y - from.y;
Fixed angle;
if (dx != 0)
{
angle = FastMath::atan(Foliage::Fixed(dy) / Foliage::Fixed(dx));
}
else if (dy > 0)
{
angle = F_PI_2;
}
else
{
angle = F_MINUS_PI_2;
}
if (dx < 0)
{
angle += F_PI;
}
return angle;
}
const Point operator+(const Point s) const
{
return Point(x + s.x, y + s.y);
}
const Point operator-(const Point s) const
{
return Point(x - s.x, y - s.y);
}
};
struct Speed
{
Fixed x, y;
Speed() : x(), y()
{
}
Speed(const Fixed &sx, const Fixed &sy)
: x(sx), y(sy)
{
}
};
struct Rect
{
Sint16 x, y;
Sint16 w, h;
Rect() : x(0), y(0), w(0), h(0)
{
}
Rect(const Sint16 rx, const Sint16 ry, const Sint16 rw, const Sint16 rh)
: x(rx), y(ry), w(rw), h(rh)
{
}
Rect(const Point p, const Size s)
: x(p.x), y(p.y), w(s.w), h(s.h)
{
}
void shift(const Point shift)
{
x += shift.x;
y += shift.y;
}
Size size() const
{
return Size(w, h);
}
Point center() const
{
Point p(x, y);
p.x += w >> 1;
p.y += h >> 1;
return p;
}
static bool intersects(const Rect &a, const Rect &b)
{
return !(b.x > a.x + a.w || b.x + b.w < a.x || b.y > a.y + a.h || b.y + b.h < a.y);
}
friend std::ostream & operator<<(std::ostream &s, const Rect &r)
{
s << "((" << r.x << ", " << r.y << ") => (" << (r.x + r.w) << ", " << (r.y + r.h) << "))";
return s;
}
friend std::ostream & operator<<(std::ostream &s, const Size &size)
{
s << "(" << size.w << "x" << size.h << ")";
return s;
}
};
}
#endif //__FOLIAGE_GRAPHIC_TYPES
| true |
d3425f347ba187bd6a6db062b4b71cc7fd581bf3 | C++ | Flovln/42-abstractVm | /includes/Instruction.hpp | UTF-8 | 2,235 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include <vector>
#include <list>
#include <string>
#include <string.h>
#include <algorithm>
#include <iterator>
#include "Infos.hpp"
#ifndef INSTRUCTION_HPP
# define INSTRUCTION_HPP
struct Token {
enum Type {
Instruction,
Operand,
/* Errors */
LexicalError,
UnknownInstruction
};
int line;
Type type;
std::string valueType;
std::string value;
};
class Instruction {
public:
Instruction(void);
Instruction(Instruction const &obj);
~Instruction(void);
Instruction &operator=(Instruction const &rhs);
int getLine(void) const;
std::vector<std::string> getErrors(void) const;
std::vector<std::string> getChunks(void) const;
std::vector<Token> getTokens(void) const;
std::vector<Content> getInstructions(void) const;
bool getMarkedAsComment(void) const;
bool getMarkAsLexicalError(void) const;
bool getMarkedAsUnknownInstruction(void) const;
void setLine(int nb);
/* LEXER */
void lexer(std::vector<std::string> buff);
void createChunks(std::string str);
void removeComments(void);
void tokenizer(void);
void tokenizeSimple(std::string chunk);
void tokenizeComplex(std::string chunk);
/* PARSER */
std::vector<Content> parser(void);
void checkInstructions(Token iterator, Token *next, int line);
void checkOperands(Token iterator, int line);
private:
int _line;
std::vector<std::string> _errors;
std::vector<std::string> _chunks;
std::vector<std::string> _commentsRemoved;
std::vector<Token> _tokens;
std::vector<Content> _instructions;
bool _markedAsComment;
bool _markAsLexicalError;
bool _markAsUnknownInstruction;
};
std::ostream & operator<<(std::ostream & o, Instruction const &obj);
#endif
| true |
f2af1a3f881344d1f53e894539c6ccb8e7713bdd | C++ | BenSeawalker/EntityFramework | /EntityFramework2/EntityManager.cpp | UTF-8 | 3,880 | 3.0625 | 3 | [] | no_license | #include "EntityManager.h"
#include "System.h"
#include "Components.h"
#include <time.h>
#include <thread>
using std::thread;
typedef EntityManager::EID EID;
//void UpdateSystems(EntityManager * _this);
EntityManager::EntityManager()
: m_running(true)
{
thread system_loop(&EntityManager::UpdateSystems, *this, this);
system_loop.detach();
}
EntityManager::~EntityManager()
{
for each (auto iter_entity in m_entities)
{
auto components = iter_entity.second;
for (UINT i = 0; i < components.size(); ++i)
delete components[i];
}
for each (System * system in m_systems)
{
delete system;
}
}
EID EntityManager::CreateEntity()
{
EID eid = GetValidID();
m_entities[eid] = {};
return eid;
}
EID EntityManager::CreateEntity(ComponentList _components)
{
EID eid = GetValidID();
m_entities[eid] = _components;
return eid;
}
void EntityManager::DestroyEntity(EID &_entity)
{
auto iter_entity = m_entities.find(_entity);
if (iter_entity != m_entities.end())
{
m_entities.erase(m_entities.find(_entity));
_entity = 0;
}
}
void EntityManager::AddComponent(EID _entity, Component * _component)
{
auto iter_entity = m_entities.find(_entity);
if (iter_entity != m_entities.end())
{
DestroyComponent(_entity, _component->type); // replace existing component...
iter_entity->second.push_back(_component);
}
}
void EntityManager::AddComponents(EID _entity, ComponentList _components)
{
for each (auto component in _components)
AddComponent(_entity, component);
}
void EntityManager::DestroyComponent(EID _entity, CType _type)
{
auto iter_entity = m_entities.find(_entity);
if (iter_entity != m_entities.end())
{
int component_index = GetComponentIndex(_entity, _type);
if (component_index >= 0)
{
auto components = iter_entity->second;
delete components[component_index];
components.erase(components.begin() + component_index);
}
}
}
int EntityManager::GetComponentIndex(EID _entity, CType _type)
{
int component_index = -1;
auto iter_entity = m_entities.find(_entity);
if (iter_entity != m_entities.end())
{
auto components = iter_entity->second;
bool found = false;
for (UINT c = 0; c < components.size() && !found; ++c)
{
if (components[c]->type == _type)
{
found = true;
component_index = c;
}
}
}
return component_index;
}
vector<EID> EntityManager::GetEntitiesWithComponent(CType _type)
{
vector<EID> entities;
for each (auto iter_entity in m_entities)
{
EID entity = iter_entity.first;
if (GetComponentIndex(entity, _type) >= 0)
entities.push_back(entity);
}
return entities;
}
vector<EID> EntityManager::GetEntitiesWithComponents(vector<CType> _types)
{
vector<EID> entities;
for each (auto iter_entity in m_entities)
{
EID entity = iter_entity.first;
bool has_components = true;
for (UINT i = 0; i < _types.size() && has_components; ++i)
has_components = (GetComponentIndex(entity, _types[i]) >= 0);
if (has_components)
entities.push_back(entity);
}
return entities;
}
void EntityManager::AddSystem(System * _system)
{
m_systems.push_back(_system);
//_system->Update(*this);
}
void EntityManager::AddSystems(SystemList _systems)
{
for each (auto system in _systems)
AddSystem(system);
}
EID EntityManager::GetValidID()
{
EID eid = 1;
while (m_entities.find(eid) != m_entities.end())
++eid;
return eid;
}
bool EntityManager::Running()
{
return m_running;
}
void EntityManager::Running(bool _running)
{
m_running = _running;
}
void EntityManager::UpdateSystems(EntityManager * _this)
{
time_t last_time;
time_t current_time;
time(&last_time);
time(¤t_time);
while (_this->m_running)
{
time(¤t_time);
if (difftime(current_time, last_time) >= (1.0f / 1.0f))
{
time(&last_time);
for each (auto system in _this->m_systems)
system->Update(*_this);
}
}
}
| true |
727dc107b39f6b4e83dd50a444c5a22293b68f82 | C++ | 0xJacky/dataStruct-oj | /DS二叉树/DS二叉树--二叉树的中后序遍历及操作/main.cpp | UTF-8 | 3,563 | 3.25 | 3 | [] | no_license | //
// main.cpp
// DS二叉树--二叉树的中后序遍历及操作
//
// Created by Jacky on 2021/5/9.
//
#include <iostream>
using namespace std;
class BiTreeNode {
public:
int data;
BiTreeNode *LeftChild;
BiTreeNode *RightChild;
BiTreeNode *parent;
BiTreeNode() : LeftChild(NULL), RightChild(NULL), parent(NULL) {}
~BiTreeNode() {}
};
class BiTree {
BiTreeNode *Root;
int len;
int *pastorder;
int *inorder;
void *CreateTree(BiTreeNode *&p, int *pastorder, int *inorder, int l, BiTreeNode *parent) {
BiTreeNode *t;
int i, j;
if (l) {
int temp = pastorder[l - 1]; //后序遍历最后一位数为根节点
p = new BiTreeNode();
p->data = temp;
p->parent = parent;
for (i = 0; i < l; i++)
if (inorder[i] ==
temp) //在中序遍历中找到根结点,其左边的为左子树,右边为右子树
break;
int num1 = i; //左子树个数
int num2 = l - i - 1; //右子树个数
int in1[num1], in2[num2];
for (j = 0; j < l; j++) {
if (j < i)
in1[j] = inorder[j];
else if (j > i)
in2[j - i - 1] = inorder[j];
}
int post1[num1], post2[num2];
for (j = 0; j < l; j++) {
if (j < i)
post1[j] = pastorder[j];
else if (j >= i && j < l - 1)
post2[j - i] = pastorder[j];
}
CreateTree(p->LeftChild, post1, in1, num1, p);
CreateTree(p->RightChild, post2, in2, num2, p);
} else
t = NULL;
return t;
}
public:
BiTree(int n, int *s1, int *s2);
~BiTree(){};
void CreateTree() {
CreateTree(Root, pastorder, inorder, len, NULL);
}
void UPDATE(int &a, int &b) {
update(Root, a, b);
}
void update(BiTreeNode *p, int &a, int &b) {
if (p) {
update(p->LeftChild, a, b);
a--;
if (a == 0) p->data = b;
update(p->RightChild, a, b);
}
}
void QUERY() {
query(Root);
}
int count(BiTreeNode *p) {
int s = 0;
while (p) {
s = p->data + s;
p = p->parent;
}
return s;
}
void query(BiTreeNode *p) {
if (p) {
query(p->LeftChild);
cout << p->data << ' ' << count(p) << endl;
query(p->RightChild);
}
}
};
BiTree::BiTree(int n, int *past, int *in) {
len = n;
pastorder = new int[len];
inorder = new int[len];
for (int i = 0; i < len; i++) {
pastorder[i] = past[i];
inorder[i] = in[i];
}
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int in[n], past[n];
for (int i = 0; i < n; i++) {
cin >> in[i];
}
for (int i = 0; i < n; i++) {
cin >> past[i];
}
BiTree mytree(n, past, in);
mytree.CreateTree();
while (1) {
string s;
cin >> s;
if (s == "UPDATE") {
int a, b;
cin >> a >> b;
mytree.UPDATE(a, b);
} else if (s == "QUERY") {
mytree.QUERY();
} else if (s == "STOP") {
break;
}
}
cout << endl;
}
return 0;
}
| true |
10a70ed598fae5532110e6b29c5889359c9c4021 | C++ | LukasKnd/SlimeShooter | /src/GameEngine.h | UTF-8 | 909 | 2.59375 | 3 | [] | no_license | #ifndef GAMEENGINE_H_INCLUDED
#define GAMEENGINE_H_INCLUDED
#include <vector>
#include <SFML/Graphics.hpp>
#include "./GameState.h"
#include "./Constants.h"
namespace sg {
class GameEngine {
private:
std::vector<GameState*> states;
bool isRunning;
public:
GameEngine();
GameEngine(const GameEngine &other) = delete;
GameEngine& operator=(const GameEngine &other) = delete;
sf::RenderWindow* window;
void ChangeState(GameState* state);
void PushState(GameState* state);
void PopState();
bool IsRunning() const;
void Quit();
void Initialize(unsigned width, unsigned height);
void ProcessInput();
void Update();
void Render();
void Cleanup();
};
}
#endif // GAMEENGINE_H_INCLUDED
| true |
df4f8bc4a68f2aeab09142229b61b68859b82d29 | C++ | xorazmiy1996/wargaming-test-task | /cpp/test/test-cyclic-queue.cpp | UTF-8 | 2,601 | 3.375 | 3 | [
"MIT"
] | permissive | #include <gtest/gtest.h>
#include "simple_class.h"
#include "../src/second/cyclic_queue.h"
TEST(test_cyclic_queue, test_cyclic_queue_with_pod)
{
test_tasks::impl_on_array::statically::cyclic_queue<int, 5> queue1;
// queue is empty, so throw exception
EXPECT_ANY_THROW(queue1.pop());
queue1.push(100);
auto res = queue1.pop();
EXPECT_EQ(res, 100);
queue1.push(1);
queue1.push(2);
queue1.push(3);
queue1.push(4);
queue1.push(5);
// queue is full, so throw exception
EXPECT_ANY_THROW(queue1.push(100));
res = queue1.pop();
EXPECT_EQ(res, 1);
res = queue1.pop();
EXPECT_EQ(res, 2);
res = queue1.pop();
EXPECT_EQ(res, 3);
res = queue1.pop();
EXPECT_EQ(res, 4);
res = queue1.pop();
EXPECT_EQ(res, 5);
EXPECT_TRUE(queue1.empty());
queue1.push(1);
queue1.push(2);
queue1.push(3);
queue1.pop();
queue1.pop();
queue1.pop();
queue1.push(4);
queue1.pop();
queue1.push(5);
queue1.push(1);
queue1.pop();
queue1.push(2);
queue1.pop();
queue1.push(3);
res = queue1.pop();
EXPECT_EQ(res, 2);
res = queue1.pop();
EXPECT_EQ(res, 3);
queue1.push(1);
queue1.push(2);
queue1.push(3);
EXPECT_EQ(queue1.count(), 3);
}
TEST(test_cyclic_queue, test_cyclic_queue_with_class_object)
{
test_tasks::impl_on_array::statically::cyclic_queue<SimpleClass, 5> queue1;
SimpleClass el("Ivan");
SimpleClass el1("Alexey");
SimpleClass el2("Olga");
queue1.push(el);
queue1.push(el1);
queue1.push(el);
queue1.push(el2);
EXPECT_EQ(queue1.count(), 4);
auto res = queue1.pop();
EXPECT_EQ(res.name(), "Ivan");
res = queue1.pop();
EXPECT_EQ(res.name(), "Alexey");
res = queue1.pop();
EXPECT_EQ(res.name(), "Ivan");
res = queue1.pop();
EXPECT_EQ(res.name(), "Olga");
queue1.push(SimpleClass("Evgeniy"));
res = queue1.pop();
EXPECT_EQ(res.name(), "Evgeniy");
EXPECT_TRUE(queue1.empty());
// copy constructor
queue1.push(el);
queue1.push(el1);
queue1.push(el);
queue1.push(el2);
test_tasks::impl_on_array::statically::cyclic_queue<SimpleClass, 5> queue2(queue1);
EXPECT_EQ(queue1.pop().name(), queue2.pop().name());
EXPECT_EQ(queue1.pop().name(), queue2.pop().name());
// move constructor
test_tasks::impl_on_array::statically::cyclic_queue<SimpleClass, 5> queue3(std::move(queue1));
// queue1 was moved, so pop throw exception
EXPECT_ANY_THROW(queue1.pop());
EXPECT_EQ(queue1.count(), 0);
}
| true |
2918c0a6ecab73e97778c6b224836a2786a2478b | C++ | potpath/algo-class | /exercise/ex02/e1_fibo/solution/main.cpp | UTF-8 | 543 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
// read input from keyboard and store in n
int n;
scanf("%d",&n);
int curr; // current fibonacci number
int next; // the next fibonacci number
// compute n-th fibo number
curr = 0;
next = 1;
for (int i = 0;i < n;i++) {
int tmp = next + curr;
curr = next;
next = tmp;
}
//display output
printf("%d\n",curr);
}
| true |
8cd3c559dc65eb698d6dcd2a4584970d20c59766 | C++ | cogito666/Autonomous-Air-Boat-Controller | /BoatController2/PWMWidthCounterI2C.h | UTF-8 | 875 | 2.578125 | 3 | [] | no_license | // PWMWidthCounterI2C.h
#ifndef _PWMWIDTHCOUNTERI2C_h
#define _PWMWIDTHCOUNTERI2C_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
#include "PWMWidthCounterIface.h"
#include <Wire.h>
class PWMWidthCounterI2C : public PWMWidthCounterIface{
protected:
union PulseWidth{
uint32_t width;
uint8_t _raw[4];
};
public:
PWMWidthCounterI2C(TwoWire* i2c, int slave_addr, uint8_t channel_idx)
:_i2c(i2c), _slave_addr(slave_addr), _channel_idx(channel_idx), _updated(false){
}
void poll();
bool updated() const {
return _updated;
}
void clearUpdated() {
_updated = false;
}
uint32_t width() const{
return _width.width;
}
/*
This method is irrelevant in i2c
*/
void attach(int, Modes){}
protected:
TwoWire* _i2c;
int _slave_addr;
uint8_t _channel_idx;
PulseWidth _width;
bool _updated;
};
#endif
| true |