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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2b1e917e92936518046a114950856f391c6a8053 | C++ | PacktPublishing/CPP-Reactive-Programming | /Chapter10/Source_Code/RxCpp-master/Rx/v2/test/operators/skip_until.cpp | UTF-8 | 19,227 | 2.609375 | 3 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | permissive | #include "../test.h"
#include <rxcpp/operators/rx-skip_until.hpp>
SCENARIO("skip_until, some data next", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.next(220, 3),
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.next(225, 99),
on.completed(230)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
| rxo::skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
| rxo::as_dynamic();
}
);
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 250)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, some data error", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
std::runtime_error ex("skip_until on_error from source");
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.next(220, 3),
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.error(225, ex)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output only contains error message"){
auto required = rxu::to_vector({
on.error(225, ex)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, error some data", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
std::runtime_error ex("skip_until on_error from source");
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.error(220, ex)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.next(230, 3),
on.completed(250)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output only contains error message"){
auto required = rxu::to_vector({
on.error(220, ex)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 220)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 220)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, some data empty", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.next(220, 3),
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.completed(225)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output is empty"){
auto required = std::vector<rxsc::test::messages<int>::recorded_type>();
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 250)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, never next", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.next(225, 2),
on.completed(250)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output is empty"){
auto required = std::vector<rxsc::test::messages<int>::recorded_type>();
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 1000)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, never error", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
std::runtime_error ex("skip_until on_error from source");
auto l = sc.make_hot_observable({
on.next(150, 1)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.error(225, ex)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output only contains error message"){
auto required = rxu::to_vector({
on.error(225, ex)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, some data error after completed", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
std::runtime_error ex("skip_until on_error from source");
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.next(220, 3),
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.error(300, ex)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output only contains error message"){
auto required = rxu::to_vector({
on.error(300, ex)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 250)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 300)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, some data never", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.next(220, 3),
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto r = sc.make_hot_observable({
on.next(150, 1)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output is empty"){
auto required = std::vector<rxsc::test::messages<int>::recorded_type>();
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 250)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 1000)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, never empty", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1)
});
auto r = sc.make_hot_observable({
on.next(150, 1),
on.completed(225)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output is empty"){
auto required = std::vector<rxsc::test::messages<int>::recorded_type>();
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 1000)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 225)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until, never never", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1)
});
auto r = sc.make_hot_observable({
on.next(150, 1)
});
WHEN("one is taken until the other emits a marble"){
auto res = w.start(
[&]() {
return l
.skip_until(r)
// forget type to workaround lambda deduction bug on msvc 2013
.as_dynamic();
}
);
THEN("the output is empty"){
auto required = std::vector<rxsc::test::messages<int>::recorded_type>();
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 1000)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the trigger"){
auto required = rxu::to_vector({
on.subscribe(200, 1000)
});
auto actual = r.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("skip_until time point, some data next", "[skip_until][skip][operators]"){
GIVEN("2 sources"){
auto sc = rxsc::make_test();
auto so = rx::synchronize_in_one_worker(sc);
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto l = sc.make_hot_observable({
on.next(150, 1),
on.next(210, 2),
on.next(220, 3),
on.next(230, 4),
on.next(240, 5),
on.completed(250)
});
auto t = sc.to_time_point(225);
WHEN("invoked with a time point"){
auto res = w.start(
[&]() {
return l
| rxo::skip_until(t, so)
// forget type to workaround lambda deduction bug on msvc 2013
| rxo::as_dynamic();
}
);
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(231, 4),
on.next(241, 5),
on.completed(251)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there was 1 subscription/unsubscription to the source"){
auto required = rxu::to_vector({
on.subscribe(200, 250)
});
auto actual = l.subscriptions();
REQUIRE(required == actual);
}
}
}
} | true |
753a94a0b1fba6fc4fff8ed9b147a55664fdb03d | C++ | sarahtattersall/Snake | /Board.cpp | UTF-8 | 4,056 | 3.234375 | 3 | [] | no_license | #include "Board.hpp"
#include "Cell.hpp"
#include "SnakeException.hpp"
#include <map>
#include <vector>
#include <boost/scoped_ptr.hpp>
using std::multimap;
using std::vector;
using std::pair;
using boost::scoped_ptr;
class CellOccupier;
//This is the only current implementation of Board
class SquareBoard : public Board {
public:
SquareBoard(const int size);
virtual int get_height();
virtual int get_width();
virtual void insert(CellOccupier* occupier, Coord coord);
virtual void move(const CellOccupier* occupier, Coord coord);
virtual void remove(const CellOccupier* occupier);
virtual Coord find(const CellOccupier* occupier);
virtual vector<Coord> find_all(const CellOccupier* occupier);
virtual const CellOccupier* lookup(const Coord coord);
virtual void clear();
private:
int m_size;
vector<vector<Cell> > m_cells;
shared_ptr<EmptyOccupier> m_empty;
// Stores occupiers to coordinates
multimap<const CellOccupier*, Coord> m_occupiers;
// Initializes the board with empty cells.
void initialize_board();
};
BoardBuilder::BoardBuilder(){
m_size = 0;
}
BoardBuilder& BoardBuilder::set_size(int size){
m_size = size;
return *this;
}
shared_ptr<Board> BoardBuilder::create(){
if(m_size == 0){
throw BoardBuilderException();
}
return shared_ptr<Board> (new SquareBoard(m_size));
}
SquareBoard::SquareBoard(const int size) : m_empty(new EmptyOccupier()){
m_size = size;
initialize_board();
}
int SquareBoard::get_height(){
return m_size;
}
int SquareBoard::get_width(){
return m_size;
}
void SquareBoard::insert(CellOccupier* occupier, const Coord coord){
m_cells[coord.get_y()][coord.get_x()].set_occupier(occupier);
m_occupiers.insert(pair<CellOccupier*,Coord>(occupier, coord));
}
void SquareBoard::move(const CellOccupier* occupier, const Coord coord){
Coord old_coord = m_occupiers.find(occupier)->second;
m_cells[old_coord.get_y()][old_coord.get_x()].set_occupier(m_empty.get());
m_cells[coord.get_y()][coord.get_x()].set_occupier(occupier);
if( m_occupiers.find(occupier) != m_occupiers.end() ){
m_occupiers.erase(m_occupiers.find(occupier));
}
m_occupiers.insert(pair<const CellOccupier*,Coord>(occupier, coord));
}
void SquareBoard::remove(const CellOccupier* occupier){
Coord coord = m_occupiers.find(occupier)->second;
m_cells[coord.get_y()][coord.get_x()].set_occupier(m_empty.get());
m_occupiers.erase(m_occupiers.find(occupier));
}
Coord SquareBoard::find(const CellOccupier* occupier){
return m_occupiers.find(occupier)->second;
}
// TODO would it have been better to return a pointer and delete when finished?
vector<Coord> SquareBoard::find_all(const CellOccupier* occupier){
vector<Coord> coords;
pair<multimap<const CellOccupier*, Coord>::iterator,multimap<const CellOccupier*, Coord>::iterator> ret;
ret = m_occupiers.equal_range(occupier);
for (multimap<const CellOccupier*, Coord>::iterator itr = ret.first; itr != ret.second; ++itr){
coords.push_back((*itr).second);
}
return coords;
}
const CellOccupier* SquareBoard::lookup(const Coord coord){
return m_cells[coord.get_y()][coord.get_x()].get_occupier();
}
void SquareBoard::initialize_board(){
m_cells.resize(m_size);
for (int i = 0; i < m_size; ++i){
for( int j = 0; j < m_size; ++j){
m_cells[i].push_back(Cell(m_empty.get()));
m_occupiers.insert(pair<CellOccupier*,Coord>(m_empty.get(), Coord(j,i)));
}
}
}
void SquareBoard::clear(){
for(multimap<const CellOccupier*, Coord>::iterator itr = m_occupiers.begin();
itr != m_occupiers.end(); ++itr ){
m_occupiers.erase(itr);
}
for (int i = 0; i < m_size; ++i){
for( int j = 0; j < m_size; ++j){
Coord coord = Coord(j,i);
m_cells[coord.get_y()][coord.get_x()].set_occupier(m_empty.get());
m_occupiers.insert(pair<CellOccupier*,Coord>(m_empty.get(), coord));
}
}
}
| true |
7f8f189acbf3aa6e76cc6118c0c67a064095dd35 | C++ | BUPT-HeptaQ/LeetCode | /C++/WiggleSubsequence(greedy).cpp | UTF-8 | 947 | 3.609375 | 4 | [] | no_license | // leetcode 376 摇摆序列 (状态机思想)
#include<vector>
class Solution {
public:
int wiggleMaxLength(std::vector<int>& nums) {
if (nums.size() < 2) { //序列个数小于2时直接为摇摆序列
return nums.size();
}
static const int BEGIN = 0; //扫描序列式的三种状态
static const int UP = 1;
static const int DOWN = 2;
int STATE = BEGIN;
int max_length = 1; //摇摆序列最大长度至少是1
for (int i = 1; i < num.size(); i++) { //从第二个元素开始扫描
switch (STATE) {
case BEGIN:
if (nums[i - 1] < nums[i]) {
STATE = UP;
max_length++;
}
else if (nums[i - 1] > nums[i]) {
STATE = DOWN;
max_length++;
}
break;
case UP:
if (nums[i - 1] > nums[i]) {
STATE = DOWN;
max_length++;
}
break;
case DOWN:
if (nums[i - 1] < nums[i]) {
STATE = UP;
max_length++;
}
break;
}
}
return max_length;
}
};
| true |
089beba6ed6c918fd8f8d3e0758bfde63470ba3a | C++ | java9494/AvalosJoel_CSC_17A_Spring_2018 | /Hmwk/Assignment_5/Gaddis_8thEd_Chap14_Prob5_TimeOff/main.cpp | UTF-8 | 1,187 | 3.359375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Joel Avalos
* Created on May 6, 2018, 2:41 PM
* Purpose: Create a program to calculate time off.
*/
//System Libraries
#include <iostream>
#include "NumDays.h"
using namespace std;
//User Libraries
//Global Constants - Math/Physics Constants, Conversions,
// 2-D Array Dimensions
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Declare Variables
float numHrs,numHrs2;
cout<<"Hello, enter in the number of hours worked. I will convert to a number of days."<<endl;
cin>>numHrs;
NumDays num(numHrs);
num.setHr(numHrs);
num.setDay(numHrs);
cin>>numHrs2;
NumDays num2(numHrs2);
num2.setHr(numHrs2);
num2.setDay(numHrs2);
NumDays num3(0.0f);
num3 = num + num2;
num3.setDay(num3.getHr());
//Initialize Variables
cout<<num.getDay()<<" days."<<endl;
cout<<num3.getDay()<<" days."<<endl;
num3++;
num3.setDay(num3.getHr());
cout<<num3.getHr()<<endl;
cout<<num3.getDay()<<" days."<<endl;
//Process/Map inputs to outputs
//output data
//Exit stage right!
return 0;
} | true |
3e6b7a48f5c802a9517219da2af9773e91a9bf68 | C++ | Sharadchandra-Patil/Object_oriented_concepts | /DAY08/day8_4.cpp | UTF-8 | 1,443 | 3.734375 | 4 | [] | no_license | using namespace std;
#include<iostream>
// when we use virtual keyword with function
// virtual function declaration must be done in base class Compulsory
// virtual functions are designed to be called using base class pointer
//LATE BINDING CONCEPT
class Base
{
public:
virtual void show()
{
cout<<"Inside show function of base class"<<endl;
}
};
class Derived : public Base
{
public:
void show()
{
Base :: show();
cout<<"Inside show function of derived class"<<endl;
}
};
int main(void)
{
Base *ptr; // base class pointer
Derived dobj; // created object of derived class
ptr=&dobj; // pointer is holding address of derived class object
ptr->show(); // call to derived class
return 0;
}
/*
class Base
{
public:
void show()
{
cout<<"Inside show function of base class"<<endl;
}
};
class Derived : public Base
{
public:
void show()
{
Base :: show();
cout<<"Inside show function of derived class"<<endl;
}
};
int main(void)
{
Base *ptr; // base class pointer
Derived dobj; // created object of derived class
ptr=&dobj; // pointer is holding address of derived class object
ptr->show(); // call to base class Always
return 0;
}
//If we give a call to overridden function , using base class pointer
// then always base class function gets called
// EARLY BINDING CONCEPT
*/ | true |
da9d1e57b214042fe6373634b4934f8be5f3f6e1 | C++ | ehariz/AutoCell | /AutoCell/matrixrule.cpp | UTF-8 | 3,221 | 3.0625 | 3 | [] | no_license | #include "matrixrule.h"
/** \brief Returns a vector fill of the integers between min and max (all included)
* \return Interval
* \param min Minimal value (included)
* \param max Maximal value (included)
*/
QVector<unsigned int> fillInterval(unsigned int min, unsigned int max)
{
QVector<unsigned int> interval;
for (unsigned int i = min; i <= max ; i++)
interval.push_back(i);
return interval;
}
/** \brief Constructor
* \param finalState Final state if the rule match the cell
* \param currentStates Possibles states of the cell. Nothing means all states
*/
MatrixRule::MatrixRule(unsigned int finalState, QVector<unsigned int> currentStates) :
Rule(currentStates, finalState)
{
}
/** \brief Tells if the cell match the rule
* \param cell Cell to test
* \return True if the cell match the rule
*/
bool MatrixRule::matchCell(const Cell *cell) const
{
// Check cell state
if (!m_currentCellPossibleValues.contains(cell->getState()))
{
return false;
}
// Check neighbours
bool matched = true;
// Rappel : QMap<relativePosition, possibleStates>
for (QMap<QVector<short>, QVector<unsigned int> >::const_iterator it = m_matrix.begin() ; it != m_matrix.end(); ++it)
{
if (cell->getNeighbour(it.key()) != nullptr) // Border management
{
if (! it.value().contains(cell->getNeighbour(it.key())->getState()))
{
matched = false;
break;
}
}
else
{
if (!it.value().contains(0))
{
matched = false;
break;
}
}
}
return matched;
}
/** \brief Add a possible state to a relative position
*/
void MatrixRule::addNeighbourState(QVector<short> relativePosition, unsigned int matchState)
{
m_matrix[relativePosition].push_back(matchState);
}
/** \brief Add multiples possible states to existents states
*/
void MatrixRule::addNeighbourState(QVector<short> relativePosition, QVector<unsigned int> matchStates)
{
for (QVector<unsigned int>::const_iterator it = matchStates.begin(); it != matchStates.end(); ++it)
m_matrix[relativePosition].push_back(*it);
}
/** \brief Return a QJsonObject to save the rule
*/
QJsonObject MatrixRule::toJson() const
{
QJsonObject object(Rule::toJson());
object.insert("type", QJsonValue("matrix"));
QJsonArray neighbours;
for (QMap<QVector<short>, QVector<unsigned int> >::const_iterator it = m_matrix.begin(); it != m_matrix.end(); ++it)
{
QJsonObject aNeighbour;
QJsonArray relativePosition;
for (unsigned int i = 0; i < it.key().size(); i++)
{
relativePosition.append(QJsonValue((int)it.key().at(i)));
}
aNeighbour.insert("relativePosition", relativePosition);
QJsonArray neighbourStates;
for (unsigned int i = 0; i < it.value().size(); i++)
{
neighbourStates.append(QJsonValue((int)it.value().at(i)));
}
aNeighbour.insert("neighbourStates", neighbourStates);
neighbours.append(aNeighbour);
}
object.insert("neighbours", neighbours);
return object;
}
| true |
b5029611b15a8fbb05af105b259bedbb31bfb7ec | C++ | 100156994/Http | /Channel.h | GB18030 | 2,775 | 2.84375 | 3 | [] | no_license |
#pragma once
#include<functional>
#include"noncopyable.h"
#include<string>
class EventLoop;
using std::string;
//һfd¼ַ fdĹر fdĹرSocket
class Channel : noncopyable
{
public:
typedef std::function<void()> EventCallback;
typedef std::function<void(size_t)> ReadEventCallback;
Channel(EventLoop* loop ,int fd);
~Channel();
void handleEvent(size_t receiveTime);
void setReadCallback(ReadEventCallback cb)
{
readCallback_ = std::move(cb);
}
void setWriteCallback(EventCallback cb)
{
writeCallback_ = std::move(cb);
}
void setErrorCallback(EventCallback cb)
{
errorCallback_ = std::move(cb);
}
void setCloseCallback(EventCallback cb)
{
closeCallback_ = std::move(cb);
}
int fd() const { return fd_; }
int events() const { return events_; }
void set_revents(int revt) { revents_ = revt; } // used by pollers
bool isNoneEvent() const { return events_ == kNoneEvent; }
void enableReading() { events_ |= kReadEvent; update(); }
void disableReading() { events_ &= ~kReadEvent; update(); }
void enableWriting() { events_ |= kWriteEvent; update(); }
void disableWriting() { events_ &= ~kWriteEvent; update(); }
void disableAll() { events_ = kNoneEvent; update(); }
bool isWriting() const { return events_ & kWriteEvent; }
bool isReading() const { return events_ & kReadEvent; }
// for Poller
int index(){ return index_; }//channel״̬ -1 1 2
void set_index(int idx){ index_ = idx; }
//for debug
string reventsToString() const;
string eventsToString() const;
EventLoop* ownerLoop()
{
return loop_;
}
void remove();
private:
static string eventsToString(int fd,int ev);
void update();
static const int kNoneEvent;
static const int kReadEvent;
static const int kWriteEvent;
EventLoop* loop_;
const int fd_;
int events_;
int revents_;
int index_;//epollermapkey
bool eventHandling_;
bool addedToLoop_;
ReadEventCallback readCallback_;
EventCallback writeCallback_;
EventCallback errorCallback_;
EventCallback closeCallback_;
//ֹ channelhandʱ conn»صconnĺδ֪
///˸о connptr serverremoveConnгзһͻҲûУ Ȼbind connDestroy
///Ȼqueueloop߳ ŶӻصȫhandleEventý ŻdoPengdingFunc connDestroy doPengdingFunc ʱ
///conn handleEventý Ҫtie
//std::weak_ptr<void> tie_;
//bool tied_;
};
| true |
08c0434151fb5f5ececf28e4ffe9eef806fff051 | C++ | paolosev/cpplinq | /src/cppLinqUnitTest/exceptTest.cpp | UTF-8 | 6,019 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2012 Paolo Severini
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "stdafx.h"
#include "CppUnitTest.h"
#include "testUtils.h"
#include "throwingEnumerable.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest
{
TEST_CLASS(ExceptTest)
{
public:
static void test()
{
fprintf(stdout, "except\n");
ExceptTest t;
t.Except_NullSecondWithoutComparer();
t.Except_NullSecondWithComparer();
t.Except_NoComparerSpecified();
t.Except_CaseInsensitiveComparerSpecified();
t.Except_NoSequencesUsedBeforeIteration();
t.Except_SecondSequenceReadFullyOnFirstResultIteration();
t.Except_FirstSequenceOnlyReadAsResultsAreRead();
}
TEST_METHOD(Except_NullSecondWithoutComparer)
{
int v[] = { 5 };
std::shared_ptr<IEnumerable<int>> first(new Vector<int>(v, ARRAYSIZE(v)));
std::shared_ptr<IEnumerable<int>> second(nullptr);
Assert::ExpectException<ArgumentNullException&>([&first, &second]() {
first->Except(second);
});
}
TEST_METHOD(Except_NullSecondWithComparer)
{
String v0[] = { "A" };
std::shared_ptr<IEnumerable<String>> first(new Vector<String>(v0, ARRAYSIZE(v0)));
std::shared_ptr<IEnumerable<String>> second(nullptr);
Assert::ExpectException<ArgumentNullException&>([&first, &second]() {
first->Except(second, CompareIgnoreCase());
});
}
TEST_METHOD(Except_NoComparerSpecified)
{
String v0[] = { "A", "a", "b", "c", "b", "c" };
std::shared_ptr<IEnumerable<String>> first(new Vector<String>(v0, ARRAYSIZE(v0)));
String v1[] = { "b", "a", "d", "a" };
std::shared_ptr<IEnumerable<String>> second(new Vector<String>(v1, ARRAYSIZE(v1)));
String exp[] = { "A", "c" };
Assert::IsTrue(first->Except(second)->SequenceEqual<String>(exp, ARRAYSIZE(exp)));
}
/*
TEST_METHOD(Except_NullComparerSpecified)
{
String v0[] = { "A", "a", "b", "c", "b", "c" };
std::shared_ptr<IEnumerable<String>> first(new Vector<String>(v0, ARRAYSIZE(v0)));
String v1[] = { "b", "a", "d", "a" };
std::shared_ptr<IEnumerable<String>> second(new Vector<String>(v1, ARRAYSIZE(v1)));
String exp[] = { "A", "c" };
std::function<bool(String, String)> comparer = nullptr;
Assert::IsTrue(first->Except(second, comparer)->SequenceEqual<String>(exp, ARRAYSIZE(exp)));
}
*/
TEST_METHOD(Except_CaseInsensitiveComparerSpecified)
{
String v0[] = { "A", "a", "b", "c", "b" };
std::shared_ptr<IEnumerable<String>> first(new Vector<String>(v0, ARRAYSIZE(v0)));
String v1[] = { "b", "a", "d", "a" };
std::shared_ptr<IEnumerable<String>> second(new Vector<String>(v1, ARRAYSIZE(v1)));
String exp[] = { "c" };
Assert::IsTrue(first->Except(second, CompareIgnoreCase())->SequenceEqual<String>(exp, ARRAYSIZE(exp)));
}
TEST_METHOD(Except_NoSequencesUsedBeforeIteration)
{
std::shared_ptr<IEnumerable<int>> first(new ThrowingEnumerable());
std::shared_ptr<IEnumerable<int>> second(new ThrowingEnumerable());
// No exceptions!
auto query = first->Except(second);
// Still no exceptions... we're not calling MoveNext.
auto iterator = query->GetEnumerator();
}
TEST_METHOD(Except_SecondSequenceReadFullyOnFirstResultIteration)
{
int v0[] = { 1 };
std::shared_ptr<IEnumerable<int>> first(new Vector<int>(v0, ARRAYSIZE(v0)));
int v1[] = { 10, 2, 0 };
std::shared_ptr<IEnumerable<int>> second(new Vector<int>(v1, ARRAYSIZE(v1)));
auto secondQuery = second->Select<int>([](int x) -> int {
return 10 / x;
});
auto query = first->Except(secondQuery);
auto iterator = query->GetEnumerator();
Assert::ExpectException<std::exception&>([iterator]() {
iterator->MoveNext();
});
}
TEST_METHOD(Except_FirstSequenceOnlyReadAsResultsAreRead)
{
int v0[] = { 10, 2, 0, 2 };
std::shared_ptr<IEnumerable<int>> first(new Vector<int>(v0, ARRAYSIZE(v0)));
auto firstQuery = first->Select<int>([](int x) { return 10 / x; });
int v1[] = { 1 };
std::shared_ptr<IEnumerable<int>> second(new Vector<int>(v1, ARRAYSIZE(v1)));
auto query = firstQuery->Except(second);
auto iterator = query->GetEnumerator();
// We can get the first value with no problems
Assert::IsTrue(iterator->MoveNext());
Assert::AreEqual(5, iterator->get_Current());
// Getting at the *second* value of the result sequence requires
// reading from the first input sequence until the "bad" division
Assert::ExpectException<std::exception&>([iterator]() {
iterator->MoveNext();
});
}
};
}
| true |
557eb6db262bd1c0f1481d023352021fc4626343 | C++ | Esrappelt/PAT-AdvancedLevel | /1044Shopping in Mars2 (2)/main.cpp | UTF-8 | 1,661 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct node
{
int s,e,sum;
node(int s,int e) : s(s),e(e) {}
node(int s,int e,int sum) : s(s),e(e),sum(sum) {}
};
int cmp1(node a,node b) {return a.sum != b.sum ? a.sum < b.sum : a.s < b.s;}
int main()
{
int n,target,s,e,minnum = 0x3f3f3f3f;
scanf("%d%d",&n,&target);
vector<int> num(n);
vector<node> ans,res;
for(int i = 0; i < n; ++i) scanf("%d",&num[i]);
for(int i = 0; i < n; ++i)
{
int sum = num[i];
if(sum > target) { res.push_back(node(i+1,i+1,sum)); continue;}
if(sum == target) ans.push_back(node(i+1,i+1));
else
{
for(int j = i + 1; j < n; ++j)
{
if(sum + num[j] == target) ans.push_back(node(i+1,j+1));
else if(sum + num[j] < target) sum += num[j];
else
{
int x = sum + num[j];
if(x - target <= minnum )
{
s = i + 1;
e = j + 1;
minnum = x - target;
res.push_back(node(s,e,minnum));
}
break;
}
}
}
}
if(ans.size() != 0)
for(int i = 0; i < ans.size(); ++i) printf("%d-%d\n",ans[i].s,ans[i].e);
else
{
sort(res.begin(),res.end(),cmp1);
for(int i = 0; i < res.size(); ++i)
{
printf("%d-%d\n",res[i].s,res[i].e);
if(res[i].sum != res[i+1].sum) break;
}
}
return 0;
}
| true |
627318ee82df30a7e42883cfc17d8632504ec01f | C++ | wdomitrz/jnp1 | /starwars2/battle.cc | UTF-8 | 3,691 | 3.375 | 3 | [
"MIT"
] | permissive | /*
* Authors:
* Wojciech Kuźmiński
* Witalis Domitrz
*/
#include <cassert>
#include <iostream>
#include "battle.h"
// Metody SpaceTime
SpaceBattle::SpaceTime::SpaceTime(SpaceBattle::SpaceTime::Time t0, SpaceBattle::SpaceTime::Time t1) : currentTime(t0),
t1(t1) {
assert(t0 <= t1);
}
bool SpaceBattle::SpaceTime::isNowAttackTime() const {
return (currentTime % 2 == 0 || currentTime % 3 == 0) && currentTime % 5 != 0;
}
void SpaceBattle::SpaceTime::moveTime(SpaceBattle::SpaceTime::Time timeStep) {
currentTime += timeStep;
currentTime %= (t1 + 1);
}
// Metody SpaceBattle
SpaceBattle::SpaceBattle(SpaceTime::Time t0, SpaceTime::Time t1,
std::vector<std::shared_ptr<ImperialStarship>> &imperials,
std::vector<std::shared_ptr<RebelStarship>> &rebels) :
spaceTime(t0, t1), imperials(imperials), rebels(rebels) {}
bool SpaceBattle::hasFinished() {
// Sprawdzenie czy już kiedyś bitwa się skończyła. Jeśli tak to nie ma
// sensu nic robić oprócz wypisywania wiadomości.
if (hasFinishedFlag)
return true;
// Zapisanie aktualnych rozmiarów obydwu armi
size_t imperialFleetCounter = countImperialFleet();
size_t rebelFleetCounter = countRebelFleet();
// Sprawdzenie, czy bitwa powinna być dalej kontynuowana
if (imperialFleetCounter == 0 || rebelFleetCounter == 0) {
// Zapisanie informacji o tym, że bitwa się już zakończyła
hasFinishedFlag = true;
// Zapisanie informacji kto wygrał
if (imperialFleetCounter != 0)
resultOfTheBattle = "IMPERIUM WON\n";
else if (rebelFleetCounter != 0)
resultOfTheBattle = "REBELLION WON\n";
else
resultOfTheBattle = "DRAW\n";
// Przejście do wypisania rezultatu bitwy
return true;
}
// Jeśli jest jeszcze wystarczająco statków, to kontynuujemy bitwę
return false;
}
void SpaceBattle::attack() {
// dla każdego statku Imperium
for (auto &imperial : imperials)
// dla każdego statku Rebelii
for (auto &rebel : rebels)
// jeśli oba statki nie nie zostały jeszcze zniszczone,
if (imperial->isAlive() && rebel->isAlive())
// statek Imperium atakuje statek Rebelii.
rebel->reactToAttack(*imperial);
}
size_t SpaceBattle::countImperialFleet() const {
return countShips(imperials);
}
size_t SpaceBattle::countRebelFleet() const {
return countShips(rebels);
}
void SpaceBattle::tick(SpaceTime::Time timeStep) {
// Sprawdzenie, czy bitwa już się skończyła
if (hasFinished()) {
std::cout << resultOfTheBattle;
return;
}
if (spaceTime.isNowAttackTime())
attack();
spaceTime.moveTime(timeStep);
}
// Metody Builder
SpaceBattle::Builder &SpaceBattle::Builder::startTime(SpaceTime::Time t) {
ist0Set = true;
t0 = t;
return *this;
}
SpaceBattle::Builder &SpaceBattle::Builder::maxTime(SpaceTime::Time t) {
ist1Set = true;
t1 = t;
return *this;
}
SpaceBattle::Builder &SpaceBattle::Builder::ship(const std::shared_ptr<RebelStarship> &starship) {
rebels.emplace_back(starship);
return *this;
}
SpaceBattle::Builder &SpaceBattle::Builder::ship(const std::shared_ptr<ImperialStarship> &starship) {
imperials.emplace_back(starship);
return *this;
}
SpaceBattle SpaceBattle::Builder::build() {
if (!ist0Set || !ist1Set)
throw std::logic_error("Both t0 and t1 have to be set!");
return SpaceBattle(t0, t1, imperials, rebels);
}
| true |
2e663a11991447bde56664ca3fa4fec3733dc563 | C++ | bluebambu/Leetcode_cpp | /291. Word Pattern II/291. Word Pattern II/_template2.cpp | UTF-8 | 6,476 | 3.09375 | 3 | [] | no_license | // _template.cpp : Defines the entry point for the console application.
//
#include <stdafx.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <list>
#include <vector>
#include <algorithm> // std::for_each
#include <unordered_map>
#include <queue>
#include <stack>
#include <unordered_set>
#include <set>
#include <map>
#include <utility>
#include <sstream>
#include <string>
#include <chrono>
using namespace std;
inline int exchg(int &a, int &b) { int c = a; a = b; b = c; }
inline int log2(int N){ return log10(N) / log10(2); }
inline float min(float a, float b) { return a < b ? a : b; }
struct TreeNode
{
TreeNode(int a) :val(a), left(nullptr), right(nullptr) {}
TreeNode(int a, TreeNode* x, TreeNode* y) :val(a), left(x), right(y) {}
TreeNode() :val(0), left(nullptr), right(nullptr) {}
int val;
TreeNode *left;
TreeNode *right;
};
void print(TreeNode* root){
queue<TreeNode*> q;
q.push(root);
while (q.size()){
int n = q.size();
for (int i = 0; i < n; ++i){
TreeNode* front = q.front();
q.pop();
if (!front)
cout << "# ";
else{
cout << front->val << " ";
q.push(front->left);
q.push(front->right);
}
}
cout << endl;
}
}
template <typename C>
void prt1Layer(C v){
for (auto i : v)
cout << i << " ";
cout << endl;
}
template <typename C>
void prt2Layer(C v){
for (auto i : v){
for (auto j : i)
cout << j << " ";
cout << endl;
}
cout << endl;
}
template <typename C>
void mapprt(C v){
for (auto i : v)
cout << i.first << " " << i.second << endl;
cout << endl;
}
////////////////////////////////////////////////////////////////
// Given a pattern and a string str, find if str follows the same pattern.
// Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.
// Examples:
// pattern = "abab", str = "redblueredblue" should return true.
// pattern = "aaaa", str = "asdasdasdasd" should return true.
// pattern = "aabb", str = "xyzabcxzyabc" should return false.
class Solution {
public:
bool wordPatternMatch(string pattern, string str) {
unordered_map<string, char> scm;
unordered_map<char, string> csm;
return dfs(pattern, 0, str, 0, scm, csm);
}
bool dfs(string& pattern, int pi, string& str, int si, unordered_map<string, char>& scm, unordered_map<char, string>& csm){
if (pi == pattern.size() && si == str.size()){
return true;
}
else if (pi == pattern.size() || si == str.size()){
return false;
}
bool res = false;
for (int i = si; i < str.size(); ++i){
string substr = str.substr(si, i - si + 1);
char pch = pattern[pi];
if (scm.count(substr) == 0 && csm.count(pch) == 0){
scm[substr] = pch, csm[pch] = substr;
res |= dfs(pattern, pi + 1, str, i + 1, scm, csm);
scm.erase(substr), csm.erase(pch);
}
else if (scm.count(substr) == 0 || csm.count(pch) == 0)
continue;
else if (scm[substr] != pch || csm[pch] != substr)
continue;
else
res |= dfs(pattern, pi + 1, str, i + 1, scm, csm);
}
return res;
}
};
class Solution2 {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> m;
return dfs(pattern, 0, str, 0, m);
}
bool dfs(string& pattern, int pi, string tgt, int ti, unordered_map<char, string>& m){
if (pi == pattern.size() && ti == tgt.size())
return true;
else if (pi == pattern.size() || ti == tgt.size())
return false;
char curp = pattern[pi];
if (m.count(curp)){
string ps = m[curp], cand = tgt.substr(ti, ps.size());
if (cand != ps)
return false;
return dfs(pattern, pi + 1, tgt, ti + ps.size(), m);
}
else{
for (int j = ti + 1; j <= tgt.size(); ++j){
string cand = tgt.substr(ti, j - ti);
m[curp] = cand;
if (dfs(pattern, pi + 1, tgt, j, m))
return true;
else{
m.erase(curp);
}
}
return false;
}
}
};
class Solution3 {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> dict;
return dfs(pattern, 0, str, 0, dict);
}
bool dfs(string& pat, int pi, string& ss, int si, unordered_map<char, string>& dict){
if (pi == pat.size() && si == ss.size())
return true;
if (pi >= pat.size() || si >= ss.size())
return false;
if (pi == pat.size() && si < ss.size())
return false;
char c = pat[pi];
if (dict.count(c)){
int len = dict[c].size();
if (ss.substr(si, len) != dict[c])
return false;
if (dfs(pat, pi + 1, ss, si + len, dict))
return true;
else
return false;
}
else{
for (int j = si; j < ss.size(); ++j){
string subss = ss.substr(si, j - si + 1);
dict[c] = subss;
if (dfs(pat, pi + 1, ss, j + 1, dict))
return true;
else{
dict.erase(c);
continue;
}
}
}
return false;
}
};
// roughly OK, not check.
class Solution4 {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> m;
return dfs(pattern, 0, str, 0, m);
}
bool dfs(string& p, int pi, string& s, int si, unordered_map<char, string>& m){
if (pi == p.size() && si == s.size())
return true;
if (pi >= p.size() || si >= s.size())
return false;
char c = p[pi];
if (m.count(c)){
string w = m[c];
if (s.substr(si, w.size()) == w){
return dfs(p, pi + 1, s, si + w.size(), m);
}
else
return false;
}
else{
for (int sj = si + 1; sj <= s.size(); ++sj){
string potential = s.substr(si, sj - si);
m[c] = potential;
if (dfs(p, pi + 1, s, si + potential.size(), m))
return true;
m.erase(c);
}
}
return false;
}
};
int main(){
Solution a;
Solution4 a2;
vector<int> b = { 4, 1, -9, 0, INT_MAX };
cout << a.wordPatternMatch("aba", "aaaaaaaaa")<<endl;
cout << a2.wordPattern("aba", "aaaaaaaaa")<<endl;
//TreeNode* tree = new TreeNode(6,new TreeNode(3, new TreeNode(1), new TreeNode(4)),new TreeNode(8, new TreeNode(7), new TreeNode(9)));
TreeNode* tree = new TreeNode(6, new TreeNode(3, new TreeNode(1),
new TreeNode(4)),
new TreeNode(8, new TreeNode(7),
new TreeNode(9)));
/* 6
3 8
1 4 7 9
*/
///////////////////////////
auto start = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cout << endl << microseconds << " microseconds elapsed..." << endl;
}
| true |
48df8e21ddab8d45bb959226c45c861595c94f5c | C++ | jerry-peng/CS162-intro-to-cs-2 | /assignment2/Hand.cpp | UTF-8 | 1,133 | 3.328125 | 3 | [] | no_license | #include "./Hand.h"
Hand::Hand(){
num_cards = 2;
cards = new Card [2];
}
int Hand::get_num_cards() const{
return num_cards;
}
Card* Hand::get_cards_pointer() const{
return cards;
}
void Hand::set_num_cards(const int num_cards){
this->num_cards = num_cards;
}
void Hand::add_card(Deck &deck){
Card *temp;
temp = new Card [num_cards + 1];
for(int i = 0; i < num_cards; i++){
temp[i] = cards[i];
}
delete[] cards;
cards = temp;
cards[num_cards] = deck.deal_card();
num_cards++;
}
void Hand::print_hand(){
for(int i = 0; i < num_cards; i++){
cards[i].print_card();
}
}
Hand::Hand(const Hand &obj){
num_cards = obj.num_cards;
cards = new Card [obj.num_cards];
for(int i = 0; i < num_cards; i++){
cards[i] = obj.cards[i];
}
}
void Hand::operator =(const Hand &obj){
delete [] cards;
num_cards = obj.num_cards;
cards = new Card [obj.num_cards];
for(int i = 0; i < num_cards; i++){
cards[i] = obj.cards[i];
}
}
Hand::~Hand(){
delete [] cards;
}
| true |
d57d38d9d9b8ff3b3e5328409d1fec4aa521317e | C++ | ABRG-Models/AttractorScaffolding | /factorial/pascals.cpp | UTF-8 | 745 | 2.765625 | 3 | [] | no_license | // By computing n choose k: n! / (k!(n-k)!) many times, display Pascal's triangle values.
#include <iostream>
#include <sstream>
#include "lmp.h"
using std::cout;
using std::cerr;
using std::endl;
using std::stringstream;
int main(int argc, char** argv)
{
if (argc < 2) {
cerr << "usage: " << argv[0] << " N (N is number of rows in Pascal's triangle to display" << endl;
return 1;
}
ulong N = (ulong)atoi(argv[1]);
Xint nchoosek;
lmp::InitSetUi(nchoosek, 1);
for (ulong n = 0; n < N; ++n) {
for (ulong k = 0; k<n+1; ++k) {
lmp::BinomialUiUi (nchoosek, n, k);
cout << nchoosek << ",";
}
cout << endl;
}
lmp::Clear(nchoosek);
return 0;
}
| true |
279f6a881ac9e6a226a6a45c0d6b32304d2b0a6b | C++ | Kiritow/OJ-Problems-Source | /QUSTOJ/1249.cpp | UTF-8 | 773 | 2.890625 | 3 | [] | no_license | //Memory Time
//240K 0MS
#include<iostream>
#include<math.h>
#include<string>
#include<iomanip>
using namespace std;
int main(void)
{
char alpha;
double t,d,h;
int i;
for(;;)
{
t=d=h=200; //三个参数的范围默认都是在-100 ~ 100
for(i=0;i<2;i++)
{
cin>>alpha;
if(alpha=='E')
return 0;
else if(alpha=='T')
cin>>t;
else if(alpha=='D')
cin>>d;
else if(alpha=='H')
cin>>h;
}
if(h==200)
h=t+0.5555*(6.11*exp(5417.7530*(1/273.16-1/(d+273.16)))-10);
else if(t==200)
t=h-0.5555*(6.11*exp(5417.7530*(1/273.16-1/(d+273.16)))-10);
else if(d==200)
d=1/((1/273.16)-((log((((h-t)/0.5555)+10.0)/6.11))/5417.7530))-273.16;
cout<<setprecision(1)<<fixed<<"T "<<t<<" D "<<d<<" H "<<h<<endl;
}
return 0;
}
| true |
1067d9f628edb60356b8fafc15c5a1470297e921 | C++ | xiajiaonly/XEffect2D | /engine/XEffeEngine/XControl/XSimpleChart.h | GB18030 | 4,656 | 2.609375 | 3 | [] | no_license | #ifndef _JIA_XSIMPLECHART_
#define _JIA_XSIMPLECHART_
//++++++++++++++++++++++++++++++++
//Author: ʤ(JiaShengHua)
//Version: 1.0.0
//Date: 2014.4.2
//--------------------------------
//#include "XMath\XVector2.h"
//#include "XFont\XFontUnicode.h"
#include <deque>
#include "XControlBasic.h"
#include "XResourceManager.h"
//һݱ
//Ż
//1ͳƵǰֵСֵ
//2ͳƵǰı
//3ͳƵǰƽֵ
namespace XE{
enum XSimpleChartType
{
TYPE_0_UP, //0ģʽ
TYPE_0_MIDDLE, //0мģʽ
TYPE_0_BOTTOM, //0ģʽ
};
enum XSimpleChartShowInfo //ʾϢ
{
INFO_NULL, //ûʾϢ
INFO_CUR_VALUE, //ǰֵ
INFO_ALL_RANGLE, //ķΧ
INFO_LOCAL_RANGLE, //ǰķΧ
INFO_LOCAL_AVERAGE, //ǰƽֵ
INFO_LOCAL_SD, //,standard deviation
};
class XSimpleChart:public XControlBasic
{
private:
bool m_isInited;
XVec2 m_size; //С
float m_rateY; //Ŀǰϵ
float m_rateX; //֮ľ룬λΪ
XSimpleChartType m_simpleChartType; //ߵʽδЧ
XSimpleChartShowInfo m_showInfo;
std::deque<float> m_datas;
int m_maxDataSum; //ʾdata
//Ե
bool m_isAutoRateY; //YϵǷʹӦ,trueʱֵ仯ϵ仯falseʱзŴʱ仯
XFontUnicode m_caption; //
bool m_showCaption;
//ǷΧͳƵ
bool m_isFirstPush; //Ƿǵһη
float m_maxData; //ݵֵ
float m_minData; //ݵСֵ
float m_curData; //ǰ
float m_localMaxData;
float m_localMinData;
float m_localAverageData; //ǰƽֵ
float m_localSDData; //ǰı
XFontUnicode m_infoFont;
XFColor m_textColor; //ֵɫ
public:
XSimpleChartType getSimpleChartType()const{return m_simpleChartType;}
void setSimpleChartType(XSimpleChartType type){m_simpleChartType = type;}
XSimpleChartShowInfo getShowInfo()const{return m_showInfo;}
void setShowInfo(XSimpleChartShowInfo info){m_showInfo = info;}
XSimpleChart()
:m_isInited(false)
,m_maxDataSum(0)
,m_rateY(1.0f)
,m_rateX(1.0f)
// ,m_scale(1.0f)
,m_size(128.0f,512.0f)
,m_isAutoRateY(true)
,m_showCaption(false)
,m_isFirstPush(false)
,m_maxData(0.0f)
,m_minData(0.0f)
,m_curData(0.0f)
,m_localMaxData(0.0f)
,m_localMinData(0.0f)
,m_localAverageData(0.0f)
,m_localSDData(0.0f)
,m_simpleChartType(TYPE_0_MIDDLE)
,m_showInfo(INFO_NULL)
{
m_ctrlType = CTRL_OBJ_SIMPLECHART;
}
~XSimpleChart(){release();}
void release();
void setIsAutoRateY(bool flag){m_isAutoRateY = flag;}
bool getIsAutoRateY()const{return m_isAutoRateY;}
XBool init(const XFontUnicode& font,const XVec2& size,float xRate);
XBool init(const XVec2& size,float xRate)
{
return init(getDefaultFont(),size,xRate);
}
void setCaption(const char *p);
XBool isInRect(const XVec2& p); //xyǷϣxyĻľ
XVec2 getBox(int order); //ȡĸ꣬ĿǰȲת
protected:
void draw();
void drawUp(){}
XBool mouseProc(const XVec2& p,XMouseState mouseState); //궯Ӧ
XBool keyboardProc(int keyOrder,XKeyState keyState){return XFalse;} //Ƿ
void insertChar(const char *,int){;}
XBool canGetFocus(const XVec2& p); //жϵǰǷԻý
XBool canLostFocus(const XVec2& ){return XTrue;} //Ӧǿʱʧȥ
// void setLostFocus(); //ʧȥ
public:
void update(float stepTime){}
bool insertAData(float data);
void clearAll();
XBool setACopy(const XButton &temp){return XFalse;}
private://Ϊ˷ֹظֵƹ캯
XSimpleChart(const XSimpleChart &temp);
XSimpleChart& operator = (const XSimpleChart& temp);
private:
void updateInfoStr();
public:
using XObjectBasic::setPosition; //⸲ǵ
void setPosition(const XVec2& p);
using XObjectBasic::setScale; //⸲ǵ
void setScale(const XVec2& s);
using XObjectBasic::setColor; //⸲ǵ
void setColor(const XFColor& c);
void setAlpha(float a);
};
#if WITH_INLINE_FILE
#include "XSimpleChart.inl"
#endif
}
#endif | true |
79afa678dcd570998ebe14e3692f96113cb75013 | C++ | MiroKaku/ucxxrt | /src/ucrt/startup/onexit.cpp | UTF-8 | 7,488 | 2.953125 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | //
// onexit.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The _onexit registry, which stores pointers to functions to be called when
// the program terminates or, when the CRT is statically linked into a DLL, when
// the DLL is unloaded.
//
// When the CRT is statically linked into an EXE or a DLL, this registry is used
// to hold the on-exit functions for the module (EXE or DLL) into which it is
// linked.
//
// When the dynamic CRT is used, this object is part of the AppCRT DLL and this
// registry stores the on-exit functions for the VCRuntime. If the EXE for the
// process uses this VCRuntime, then this registry also stores the on-exit
// functions for that EXE. If a DLL uses the dynamic CRT, then that DLL has its
// own registry, defined in the statically-linked VCStartup library.
//
#include <corecrt_internal.h>
// The global atexit and at_quick_exit registries
extern "C" _onexit_table_t __acrt_atexit_table{};
extern "C" _onexit_table_t __acrt_at_quick_exit_table{};
enum : size_t
{
initial_table_count = 32,
minimum_table_increment = 4,
maximum_table_increment = 512
};
// Registers a function to be executed on exit. This function modifies the global
// onexit table.
extern "C" int __cdecl _crt_atexit(_PVFV const function)
{
return _register_onexit_function(&__acrt_atexit_table, reinterpret_cast<_onexit_t>(function));
}
extern "C" int __cdecl _crt_at_quick_exit(_PVFV const function)
{
return _register_onexit_function(&__acrt_at_quick_exit_table, reinterpret_cast<_onexit_t>(function));
}
extern "C" int __cdecl _initialize_onexit_table(_onexit_table_t* const table)
{
if (!table)
{
return -1;
}
// If the table has already been initialized, do not do anything. Note that
// this handles both the case where the table was value initialized and where
// the table was initialized with encoded null pointers.
if (table->_first != table->_end)
{
return 0;
}
_PVFV* const encoded_nullptr = __crt_fast_encode_pointer(nullptr);
table->_first = encoded_nullptr;
table->_last = encoded_nullptr;
table->_end = encoded_nullptr;
return 0;
}
// Appends the given 'function' to the given onexit 'table'. Returns 0 on
// success; returns -1 on failure. In general, failures are considered fatal
// in calling code.
extern "C" int __cdecl _register_onexit_function(_onexit_table_t* const table, _onexit_t const function)
{
return __acrt_lock_and_call(__acrt_select_exit_lock(), [&]
{
if (!table)
{
return -1;
}
_PVFV* first = __crt_fast_decode_pointer(table->_first);
_PVFV* last = __crt_fast_decode_pointer(table->_last);
_PVFV* end = __crt_fast_decode_pointer(table->_end);
// If there is no room for the new entry, reallocate a larger table:
if (last == end)
{
size_t const old_count = end - first;
size_t const increment = old_count > maximum_table_increment ? maximum_table_increment : old_count;
// First, try to double the capacity of the table:
size_t new_count = old_count + increment;
if (new_count == 0)
{
new_count = initial_table_count;
}
_PVFV* new_first = nullptr;
if (new_count >= old_count)
{
new_first = _recalloc_crt_t(_PVFV, first, new_count).detach();
}
// If that didn't work, try to allocate a smaller increment:
if (new_first == nullptr)
{
new_count = old_count + minimum_table_increment;
new_first = _recalloc_crt_t(_PVFV, first, new_count).detach();
}
if (new_first == nullptr)
{
return -1;
}
first = new_first;
last = new_first + old_count;
end = new_first + new_count;
// The "additional" storage obtained from recalloc is sero-initialized.
// The array holds encoded function pointers, so we need to fill the
// storage with encoded nullptrs:
_PVFV const encoded_nullptr = __crt_fast_encode_pointer(nullptr);
for (auto it = last; it != end; ++it)
{
*it = encoded_nullptr;
}
}
*last++ = reinterpret_cast<_PVFV>(__crt_fast_encode_pointer(function));
table->_first = __crt_fast_encode_pointer(first);
table->_last = __crt_fast_encode_pointer(last);
table->_end = __crt_fast_encode_pointer(end);
return 0;
});
}
// This function executes a table of _onexit()/atexit() functions. The
// terminators are executed in reverse order, to give the required LIFO
// execution order. If the table is uninitialized, this function has no
// effect. After executing the terminators, this function resets the table
// so that it is uninitialized. Returns 0 on success; -1 on failure.
extern "C" int __cdecl _execute_onexit_table(_onexit_table_t* const table)
{
return __acrt_lock_and_call(__acrt_select_exit_lock(), [&]
{
if (!table)
{
return -1;
}
_PVFV* first = __crt_fast_decode_pointer(table->_first);
_PVFV* last = __crt_fast_decode_pointer(table->_last);
if (!first || first == reinterpret_cast<_PVFV*>(-1))
{
return 0;
}
// This loop calls through caller-provided function pointers. We must
// save and reset the global state mode before calling them, to maintain
// proper mode nesting. (These calls to caller-provided function pointers
// are the only non-trivial calls, so we can do this once for the entire
// loop.)
{
_PVFV const encoded_nullptr = __crt_fast_encode_pointer(nullptr);
_PVFV* saved_first = first;
_PVFV* saved_last = last;
for (;;)
{
// Find the last valid function pointer to call:
while (--last >= first && *last == encoded_nullptr)
{
// Keep going backwards
}
if (last < first)
{
// There are no more valid entries in the list; we are done:
break;
}
// Store the function pointer and mark it as visited in the list:
_PVFV const function = __crt_fast_decode_pointer(*last);
*last = encoded_nullptr;
function();
_PVFV* const new_first = __crt_fast_decode_pointer(table->_first);
_PVFV* const new_last = __crt_fast_decode_pointer(table->_last);
// Reset iteration if either the begin or end pointer has changed:
if (new_first != saved_first || new_last != saved_last)
{
first = saved_first = new_first;
last = saved_last = new_last;
}
}
}
if (first != reinterpret_cast<_PVFV*>(-1))
{
free(first);
}
_PVFV* const encoded_nullptr = __crt_fast_encode_pointer(nullptr);
table->_first = encoded_nullptr;
table->_last = encoded_nullptr;
table->_end = encoded_nullptr;
return 0;
});
}
| true |
3173854bcab2118675ac68b8b34501f1554a68fb | C++ | Stolof/IG.2409-Multimedia | /TF1/Student.cc | UTF-8 | 299 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include "Student.h"
using namespace std;
Student::Student(char *sn, int bod){
strcpy(name , sn);
name[127] = 0;
date_of_birth = bod;
}
const char* Student::Name() {
return name;
}
int Student::Birthday() const{
return date_of_birth % 10000;
}
| true |
0887fc96ba8842aaf4ad09375666ca1980ca45bc | C++ | Kaleado/roguelike-engine | /rpg-prototype/src/gmMap.h | UTF-8 | 2,446 | 3.296875 | 3 | [] | no_license | #ifndef GMMAP_H
#define GMMAP_H
#include <stdio.h>
#include <string>
#include "gmTile.h"
#include "gmThing.h"
/*Class for all the maps the player may explore.
*This needs a lot of work:
* - The addition of more tile types would assist in the creation of more diverse maps.
* - The removal of the simple 'wall, floor or door' manner in which the tiles are determined.
* - The spawnlist needs to be segmented into the spawnlist for items and the spawnlist for creatures.
*/
class gmMap
{
public:
bool isOutdoors; //Whether the map is outside or underground / undercover. Determines viewRadius.
std::vector <std::vector<gmTile*>> map;//The tiles on the map.
std::vector <std::vector<bool>> fovMap;//Whether or not the tiles are within the player's FoV.
std::vector <std::vector<bool>> rememberMap;//Whether or not the player has seen the tiles before.
std::string wallPath, floorPath, doorPath;//Paths to the images for the walls, floors, and doors. This HAS to change.
std::vector <gmThing*> spawnList;//Things which may spawn on this level.
std::vector <gmThing*> things;//The things present on this map, also known as the 'thinglist'.
void(*make)(gmMap* owner);//The function to make the map.
void spawnThings()//Randomly spawns things from the spawnList to populate the level. Currently this does not distinguish between enemies and items.
{
struct coords
{
int x, y;
coords(int x, int y){ this->x = x; this->y = y; }
};
std::vector <coords> openSpaces;
for (int dx = 0; dx < map[0].size(); dx++){for (int dy = 0; dy < map.size(); dy++)
{
if (map[dy][dx]->passable){ openSpaces.push_back(coords(dx, dy)); }
}}
if (spawnList.size() > 0)
{
for (int i = 0; i < map.size() * map[0].size() / 100;)
{
for (int j = 0; j < spawnList.size(); j++)
{
if (roll(1, 'd', 100) <= spawnList[j]->rarity)
{
things.push_back(new gmThing(*spawnList[j]));
int a = rand() % openSpaces.size();
things.back()->x = openSpaces[a].x;
things.back()->y = openSpaces[a].y;
things.back()->load();
i++;
}
}
}
}
return;
}
gmMap(int w, int h, bool isOutdoors, void(*make)(gmMap* owner), std::vector <gmThing*> spawnList)
{
this->isOutdoors = isOutdoors;
this->make = make;
map.resize(h, std::vector<gmTile*>(w));
fovMap.resize(h, std::vector<bool>(w));
rememberMap.resize(h, std::vector<bool>(w));
this->spawnList = spawnList;
}
};
#endif | true |
85da7d3cc10acf9af1d9d1bef41b036ac2ab38af | C++ | haampie/project-euler | /027/27.cc | UTF-8 | 1,346 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <tuple>
std::vector<size_t> primes_under(size_t N)
{
std::vector<bool> prime(N, true);
for (size_t x = 3; x * x <= N; x += 2)
if (prime[x])
for (size_t m = x * x; m < N; m += 2 * x)
prime[m] = false;
std::vector<size_t> primes;
primes.push_back(2);
for (size_t x = 3; x < N; x += 2)
if (prime[x])
primes.push_back(x);
return primes;
}
int main()
{
size_t max = 0;
std::pair<int64_t, size_t> maximizer;
auto primes = primes_under(1'000'000);
for (size_t b_idx = 0; primes[b_idx] < 1000; ++b_idx)
{
for (auto p : primes)
{
int64_t a = p - primes[b_idx] - 1;
if (a <= -1000 || a >= 1000)
break;
for (size_t n = 2; n < 1'000'000; ++n) {
int64_t num = n * n + a * n + primes[b_idx];
if (num <= 0 || !std::binary_search(primes.begin(), primes.end(), num)) {
if (n > max) {
max = n;
maximizer = std::make_pair(a, primes[b_idx]);
}
break;
}
}
}
}
std::cout << '(' << maximizer.first << ','
<< maximizer.second << ") = " << max << '\n';
for (size_t n = 0; n != max; ++n)
std::cout << "n = " << n << ": " << (n * n + maximizer.first * n + maximizer.second) << '\n';
} | true |
77a68b6171faeadb6b30a64a75260a2bbccf8fb5 | C++ | sfluo/GSE | /rbfs.h | UTF-8 | 1,817 | 3.21875 | 3 | [] | no_license | /*
* Recursive Best-First Search (RBFS)
*
* A kind of recursive Depth-first search, instead of going down the current path,
* it uses the f_limit variable to keep track of the f-vlaue of the best alternative
* from the ancestor of the current node. If the current node exceeds this limit,
* the recurion unwinds back to the alternative path.
*
* Reference: AIMA page 99.
*
* Author: Shoufu Luo
* Date: Apr. 21, 2015
*/
#ifndef __RBFS_H__
#define __RBFS_H__
#include <stack>
#include "strategy.h"
#include "astar.h"
class RBFSOrder {
public:
/* less then, i.e. x < y (x put after y) */
bool operator()(const NodePtr x, const NodePtr y) const
{
// return x->f > y->f;
return x->getCost() + x->getDistanceToGoal() > y->getCost() + y->getDistanceToGoal();
}
};
typedef std::priority_queue<NodePtr, std::vector<NodePtr>, RBFSOrder> PriorityQueue;
typedef std::shared_ptr<PriorityQueue> PriorityQueuePtr;
class RBFSBlock {
public:
RBFSBlock() : queueptr(PriorityQueuePtr()), alternative(0), pending(false) {}
~RBFSBlock() {}
PriorityQueuePtr queueptr;
/* alternative may inherit from ancestor (parent) or its sibling */
long alternative;
bool pending; /* is this block pending to put to stack */
};
class RBFS : public Strategy {
public:
RBFS() : Strategy("RBFS"), m_current_blk(), m_qsize(0) {}
~RBFS() {}
NodePtr remove();
void insert(NodePtr n);
long qsize();
private:
/*
* We use each prioirty_queue for each layer of the tree, ordered by A*
* use stack to achieve DFS fashion explore
*/
std::stack<RBFSBlock> m_tree;
/* Temporally store the queue for one "layer" (successors of one node)*/
RBFSBlock m_current_blk;
/* The ancestor associated to the current queue (all nodes should be its successors) */
NodePtr m_ancestor;
long m_qsize;
};
#endif
| true |
a050bf84f50828341477d150494ff112370ea700 | C++ | wzzydezy/C-learning | /trees.cpp | UTF-8 | 3,231 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string.h>
#include <unordered_map>
#include <sstream>
#include <stack>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL){}
};
class Solution{
public:
static bool issametrees(TreeNode* root1, TreeNode* root2){
if(!root1 && !root2) return true;
if(!root1 || !root2) return false;
return (root1->val==root2->val) && issametrees(root1->left, root2->right)
&& issametrees(root1->right, root2->left);
}
void scan(TreeNode* root){
if(!root) return;
if(root->left) scan(root->left);
if(root->right) scan(root->right);
cout<<root->val<<" ";
return;
}
};
class scan2{
public:
void midscan(TreeNode* root){
stack<TreeNode*> sta;
while(!sta.empty() || root){
while(root){
sta.push(root);
root = root->left;
}
root = sta.top();
cout<<root->val<<" ";
sta.pop();
root = root -> right;
}
return;
}
void prescan(TreeNode* root){
stack<TreeNode*> sta;
if(root) sta.push(root);
while(!sta.empty()){
TreeNode* root = sta.top();
sta.pop();
cout<<root->val<<" ";
if(root->right) sta.push(root->right);
if(root->left) sta.push(root->left);
}
return;
}
void postscan(TreeNode* root){
stack<TreeNode*> sta;
if(root) sta.push(root);
while(!sta.empty()){
if(root->right) sta.push(root->right);
if(root->left) sta.push(root->left);
}
}
};
int maxpath(TreeNode* root, int& val){
if(!root) return 0;
int left = maxpath(root->left, val);
int right = maxpath(root->right, val);
int v = max(max(left,0), max(right,0)) + root->val;
int mp = max(left,0) + max(right,0) + root->val;
val = max(val, mp);
return v;
}
int maxPathSum(TreeNode* root) {
int val = INT_MIN;
maxpath(root, val);
return val;
}
class Solution129 {
public:
int res = 0;
void dfs(TreeNode* root, int n){
if(!root){
res += n;
return;
}
n = n*10 + root->val;
if(root->left) dfs(root->left, n);
if(root->right) dfs(root->right, n);
return;
}
int sumNumbers(TreeNode* root) {
dfs(root, 0);
return res;
}
};
int main(){
Solution a;
TreeNode* tn_0_0 = new TreeNode(1);
TreeNode* tn_1_0 = new TreeNode(2);
TreeNode* tn_1_1 = new TreeNode(3);
//TreeNode* tn_2_0 = new TreeNode(2);
//TreeNode* tn_2_1 = new TreeNode(3);
TreeNode* tn_2_2 = new TreeNode(15);
TreeNode* tn_2_3 = new TreeNode(7);
tn_0_0->left = tn_1_0;
tn_0_0->right = tn_1_1;
//tn_1_0->left = tn_2_0;
//tn_1_0->right = tn_2_1;
//tn_1_1->left = tn_2_2;
//tn_1_1->right = tn_2_3;
//bool res = Solution::issametrees(tn_0_0, tn_0_0);
//a.scan(tn_0_0);
//int res = maxPathSum(tn_0_0);
Solution129 s129;
int res = s129.sumNumbers(tn_0_0);
return 0;
}
| true |
294e15659879e366fa13d200972fa17dfdabfcf4 | C++ | locker/leetcode | /solutions/isomorphic-strings/solution.cpp | UTF-8 | 1,188 | 3.578125 | 4 | [
"BSD-2-Clause",
"BSD-2-Clause-Views"
] | permissive | #include <iostream>
#include <limits>
#include <string>
#include <utility>
using namespace std;
class Solution {
public:
bool isIsomorphic(const string& s, const string& t) {
if (s.length() != t.length())
return false;
const int map_size = numeric_limits<char>::max() + 1;
char map1[map_size] = { 0, };
char map2[map_size] = { 0, };
for (auto it1 = s.begin(), it2 = t.begin();
it1 != s.end(); ++it1, ++it2) {
int c1 = *it1, c2 = *it2;
if (map1[c1] == 0)
map1[c1] = c2;
if (map2[c2] == 0)
map2[c2] = c1;
if (map1[c1] != c2)
return false;
if (map2[c2] != c1)
return false;
}
return true;
}
};
int main()
{
pair<string, string> input[] = {
{"", ""}, // true
{"a", ""}, // false
{"a", "b"}, // true
{"ab", "aa"}, // false
{"aa", "bb"}, // true
{"aa", "bc"}, // false
{"egg", "add"}, // true
{"foo", "bar"}, // false
{"paper", "title"}, // true
};
Solution solution;
for (const auto& p: input) {
cout << '"' << p.first << "\" and \"" << p.second << '"';
if (solution.isIsomorphic(p.first, p.second))
cout << " are ";
else
cout << " are not ";
cout << "isomorphic strings" << endl;
}
return 0;
}
| true |
24e3ac54bcf41708e1b3005095b9bf6c7c2a86ee | C++ | robotconscience/ofxKinectForWindows2 | /src/ofxKinectForWindows2/Source/Depth.cpp | UTF-8 | 3,655 | 2.625 | 3 | [
"MIT"
] | permissive | #include "Depth.h"
#include "ofMain.h"
namespace ofxKinectForWindows2 {
namespace Source {
//----------
Depth::PointCloudOptions::PointCloudOptions() {
this->stitchFaces = true;
this->textureCoordinates = TextureCoordinates::None;
}
//----------
Depth::PointCloudOptions::PointCloudOptions(bool stitchFaces, bool useColor, TextureCoordinates textureCoordinates) {
this->stitchFaces = stitchFaces;
this->textureCoordinates = textureCoordinates;
}
//----------
string Depth::getTypeName() const {
return "Depth";
}
//----------
void Depth::init(IKinectSensor * sensor) {
this->reader = NULL;
try {
IDepthFrameSource * source = NULL;
if (FAILED(sensor->get_DepthFrameSource(& source))) {
throw(Exception("Failed to initialise Depth source"));
}
if (FAILED(source->OpenReader(& this->reader))) {
throw(Exception("Failed to initialise Depth reader"));
}
SafeRelease(source);
if (FAILED(sensor->get_CoordinateMapper(&this->coordinateMapper))) {
throw(Exception("Failed to acquire coordinate mapper"));
}
} catch (std::exception & e) {
SafeRelease(this->reader);
throw (e);
}
}
//----------
ofMesh Depth::getMesh(bool stitchFaces, PointCloudOptions::TextureCoordinates textureCoordinates) {
const auto frameSize = this->pixels.size();
const int width = this->getWidth();
const int height = this->getHeight();
ofMesh mesh;
mesh.setMode(stitchFaces ? ofPrimitiveMode::OF_PRIMITIVE_TRIANGLES : ofPrimitiveMode::OF_PRIMITIVE_POINTS);
mesh.getVertices().resize(frameSize);
auto vertices = mesh.getVerticesPointer();
this->coordinateMapper->MapDepthFrameToCameraSpace(frameSize, this->pixels.getPixels(), frameSize, (CameraSpacePoint*) mesh.getVerticesPointer());
if (stitchFaces) {
for(int i=0; i<width-1; i++) {
for(int j=0; j<height-1; j++) {
auto topLeft = width * j + i;
auto topRight = topLeft + 1;
auto bottomLeft = topLeft + width;
auto bottomRight = bottomLeft + 1;
//upper left triangle
if (vertices[topLeft].z > 0 && vertices[topRight].z > 0 && vertices[bottomLeft].z > 0) {
const ofIndexType indices[3] = {topLeft, bottomLeft, topRight};
mesh.addIndices(indices, 3);
}
//bottom right triangle
if (vertices[topRight].z > 0 && vertices[bottomRight].z > 0 && vertices[bottomLeft].z > 0) {
const ofIndexType indices[3] = {topRight, bottomRight, bottomLeft};
mesh.addIndices(indices, 3);
}
}
}
}
switch(textureCoordinates) {
case PointCloudOptions::TextureCoordinates::ColorCamera:
{
mesh.getTexCoords().resize(frameSize);
this->coordinateMapper->MapDepthFrameToColorSpace(frameSize, this->pixels.getPixels(), frameSize, (ColorSpacePoint*) mesh.getTexCoordsPointer());
}
break;
case PointCloudOptions::TextureCoordinates::DepthCamera:
{
mesh.getTexCoords().resize(frameSize);
auto texCoords = mesh.getTexCoordsPointer();
for(int i=0; i<frameSize; i++) {
texCoords[i] = ofVec2f(i % width, i / width);
}
}
break;
case PointCloudOptions::TextureCoordinates::None:
default:
break;
}
return mesh;
}
//----------
ofMesh Depth::getMesh(const PointCloudOptions & pointCloudOptions) {
return this->getMesh(pointCloudOptions.stitchFaces, pointCloudOptions.textureCoordinates);
}
//----------
ICoordinateMapper * Depth::getCoordinateMapper(){
return coordinateMapper;
}
}
} | true |
cf3781a275dcd6412d751c6f630bc420e9d09b85 | C++ | JakeMotta/jakemotta | /NinjaDonut/Pages/Students/JakeMotta/CPP/SecondWorld/GoodMorningWorld.cpp | UTF-8 | 296 | 3.03125 | 3 | [
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | #include <iostream>
int main()
{
using namespace std;
cout << "Good Morning World!" << endl;
cout << "Derby at 12! Let me just take a quick shower!" << endl;
cout << "And some quick chores....";
system("pause");
return 0;
}
| true |
791ce7bc8c99fb932e150d481af8e9f06b9e2ce2 | C++ | zhangshuai7/-182- | /201811050996/面向对象.cpp | UTF-8 | 944 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class vehicle
{
protected:
int wheels;
float weight;
public:
vehicle(int w1, float w2)
{
wheels = w1;
weight = w2;
}
void printf()
{
cout << "wheels=" << wheels << "," << "weight=" << "weight" << endl;
}
};
class car :private vehicle
{
int passenger_load;
public:
car(int w1,float w2,int p1):vehicle(w1,w2)
{
passenger_load = p1;
}
void printf()
{
vehicle::printf();
cout << "passenger_load=" << passenger_load << endl;
}
};
class truck :private vehicle
{
int passenger_load;
float payload;
public:
truck(int w1,float w2,int p1,float p2):vehicle(w1,w2)
{
passenger_load = p1;
payload = p2;
}
void printf()
{
vehicle::printf();
cout << "passenger_load=" << passenger_load << "," << "payload=" << payload << endl;
}
};
int main()
{
vehicle v(1000, 842.2);
v.printf();
car c(134, 94.7, 84);
c.printf();
truck t(48,29.6,27,19.8);
t.printf();
}
| true |
5eed74035ed21764cfcca887dbc67b7ede3c020d | C++ | Bencow/Vegetal | /GLFW_EXAMPLE/Vertex.cpp | UTF-8 | 1,968 | 3.1875 | 3 | [] | no_license | //
// Vertex.cpp
//
// Author :
// Quentin Mulliez
// Benoit Coville
//
//
#include "Vertex.hpp"
Vertex::Vertex() :
m_x(0.0f), m_y(0.0f), m_z(0.0f),
m_r(1.0f), m_g(1.0f), m_b(1.0f),
m_nx(0.0f), m_ny(0.0f), m_nz(1.0f),
m_tx(0.0f), m_ty(0.0f)
{}
Vertex::Vertex(float x, float y, float z, int age):
m_x(x), m_y(y), m_z(z),
m_r(1.0f), m_g(1.0f), m_b(1.0f),
m_nx(0.0f), m_ny(0.0f), m_nz(1.0f),
m_tx(0.0f), m_ty(0.0f),
m_born(age)
{}
Vertex::~Vertex(){
}
double Vertex::getAge(){
//to code with all libraries ...
return m_born;
}
std::ostream& operator <<(std::ostream& out, Vertex& v)
{
//setw is just a function which print the value always on the same number of "space" on the screen
//because otherwise if x = 6 (1space) and y = -1234.5 (7 spaces) all the other data are shifted during displaying
out << " x: " << std::setw(4) << v.getX()
<< " y: " << std::setw(4) << v.getY()
<< " z: " << std::setw(4) << v.getZ() << "\n";
return out;
}
int Vertex::fillGfloatArray(GLfloat* arrayGfloat, int offset){
arrayGfloat[offset] = m_x;
offset++;
arrayGfloat[offset] = m_y;
offset++;
arrayGfloat[offset] = m_z;
offset++;
arrayGfloat[offset] = m_r;
offset++;
arrayGfloat[offset] = m_g;
offset++;
arrayGfloat[offset] = m_b;
offset++;
arrayGfloat[offset] = m_nx;
offset++;
arrayGfloat[offset] = m_ny;
offset++;
arrayGfloat[offset] = m_nz;
offset++;
/*
arrayGfloat[offset] = m_tx;
offset++;
arrayGfloat[offset] = m_ty;
offset++;
*/
return offset;
}
void Vertex::fillVectorVertices(std::vector<GLfloat>& vertices)
{
vertices.push_back(m_x);
vertices.push_back(m_y);
vertices.push_back(m_z);
vertices.push_back(m_r);
vertices.push_back(m_g);
vertices.push_back(m_b);
vertices.push_back(m_nx);
vertices.push_back(m_ny);
vertices.push_back(m_nz);
vertices.push_back(m_tx);
vertices.push_back(m_ty);
}
| true |
242f0aa3d2eecbe9bd93390f15d234ff1367984e | C++ | MoonighT/google_code_jam | /store_credit/store_credit.cpp | UTF-8 | 694 | 3 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
// freopen("A-small-practice.in.txt", "r", stdin);
freopen("A-large-practice.in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int N;
int r1, r2;
cin >> N;
unordered_map<int, int> mymap;
for(int i = 0; i < N; ++i)
{
int C, I;
cin >> C >> I;
mymap.clear();
for (int j = 1; j <= I; ++j)
{
int temp;
cin >> temp;
if(mymap.count(C-temp) > 0)
{
//find a solution
r1 = mymap[C-temp];
r2 = j;
}
else
{
if(mymap.count(temp) == 0)
mymap[temp] = j;
}
}
//output
cout << "Case #" << i+1 << ": " << r1 << " " << r2 << endl;
}
return 0;
}
| true |
b6443816b491ffbb768e1926632151eb6e72ff23 | C++ | tranquyenbk173/CodeC_TTUD_20191 | /sinhvien_5_link_loi.cpp | UTF-8 | 5,507 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct sv{
char *ht, *lop, *gt;
int mssv, ns;
float diem;
struct sv *next;
};
struct sinhvien{
char ht[30], lop[30];
int mssv, ns, gt;
float diem;
};
struct sv *pdau, *pcuoi;
struct sinhvien tam;
char f[3] = "Nu", m[4] = "Nam";
void giaiphong()
{
struct sv *p;
if (pdau == NULL) return;
while (pdau != NULL)
{
p = pdau;
pdau = p->next;
delete [] p->ht;
delete [] p->lop;
delete p;
}
pdau = NULL;
pcuoi = NULL;
}
void docfile()
{
FILE *fp = fopen("sinhvien1.dat", "rb");
struct sv *p;
char s[30];
int g;
if (fp == NULL)
{
printf("\n File khong ton tai!"); getch(); return;
}
giaiphong(); rewind(fp);
while (feof(fp)!=0)
{
if (pdau == NULL)
{
pdau = new sv;
p = pdau;
}
else
{
p->next = new sv;
p = p->next;
}
fread(&tam, sizeof(sinhvien), 1, fp);
strcpy(s, tam.ht); p->ht = new char[strlen(s)+1]; strcpy(p->ht, s);
strcpy(s, tam.lop); p->lop = new char[strlen(s)+1]; strcpy(p->lop, s);
if (tam.gt == 1) p->gt = m;
else if (tam.gt == 0) p->gt = f;
p->mssv = tam.mssv;
p->ns = tam.ns;
p->diem = tam.diem;
p->next = NULL;
}
pcuoi = p;
fclose(fp);
printf("\n Doc file thanh cong!"); getch();
}
void ghifile()
{
FILE *fp = fopen("sinhvien1.dat", "wb");
struct sv *p;
system("cls");
if (pdau == NULL)
{
printf("\n Danh sach rong!"); getch(); return;
}
p = pdau;
// Sao chep tu p -> tam; Sau do ghi tam len file. Lan luot cho den khi het danh sach
while (p!= NULL)
{
strcpy(tam.ht, p->ht);
strcpy(tam.lop, p->lop);
if (p->gt == "Nam") tam.gt = 1;
else if (p->gt == "Nu") tam.gt = 0;
tam.mssv = p->mssv;
tam.ns = p->ns;
tam.diem = p->diem;
fwrite(&tam, sizeof(sinhvien), 1, fp);
p = p->next;
}
fclose(fp);
printf("\n Ghi file thanh cong!");
}
void bosung()
{
struct sv *p;
int i = 1, g;
float d;
char s[30];
system("cls");
printf("\n Bo sung them danh sach!");
while (1)
{
printf("\n Sinh vien thu %d", i++);
printf("\n \t- Ho ten (ENTER de dung nhap): "); fflush(stdin); gets(s);
if (s[0] == '\0') break;
if (pdau == NULL)
{
pdau = new sv;
p = pdau;
}
else
{
p = pcuoi;
p ->next = new sv;
p = p->next;
}
p->ht = new char[strlen(s)+1]; strcpy(p->ht, s);
printf("\n \t- Lop: "); fflush(stdin);gets(s);
p->lop = new char[strlen(s)+1]; strcpy(p->lop, s);
printf("\n \t- Gioi tinh (Nam-1, Nu-0): ");
gender: scanf("%d", &g);
if (g != 0 && g!= 1) goto gender;
if (g==1) p->gt = m;
else p->gt = f;
printf("\n \t- MSSV: "); scanf("%d", &g); p->mssv = g;
printf("\n \t- Nam sinh: "); scanf("%d", &g); p->ns = g;
printf("\n \t- Diem: "); scanf("%f", &d); p->diem = d;
p->next = NULL; pcuoi = p;
}
}
void swap(struct sv *p1, struct sv *p2)
{
struct sv *pp1, *pp2, *tg, *p;
/// Sau chuong trinh nay, vi tri tro cua p1 va p2 khong thay doi. Chi co thu tu lien ket trong danh sach moc noi bi thay doi
if (p1 == pdau)
{
// tim pp2, lien truoc p2. Cho no chi toi p1
p = pdau;
while (p->next != p2) p = p->next;
pp2 = p;
pp2 ->next = p1;
// doi cau truc lien sau cua p1 va p2
tg = p1->next;
p1->next = p2 ->next;
p2->next = tg;
}
else
{
// tim pp1 va thay doi
p = pdau;
while (p->next != p1) p = p->next;
pp1 = p; pp1->next = p2;
// tim pp2 va thay doi
p = pdau;
while (p->next != p2) p = p->next;
pp2 = p; pp2 ->next = p1;
// Doi cho cau truc lien sau p1 va p2
tg = p1->next;
p1->next = p2->next;
p2->next = tg;
}
}
int sosanh(char *s1, char *s2)
{
int i, j;
// So sanh firstname roi moi den lastname
i = strlen(s1) - 1; j = strlen(s2) - 1;
while (i>0)
{
if (s1[i]!=' ' && s1[i-1]==' ') break;
i--;
}
while (j>0)
{
if (s2[j]!=' ' && s2[j-1]==' ') break;
j--;
}
if (strcmp(&s1[i], &s2[j])>0) return 1;
else if (strcmp(&s1[i], &s2[j])<0) return -1;
else return strcmp(s1, s2);
}
void sapxep()
{
struct sv *tg, *pi, *pj, *pk;
// Best sort - Thay doi thu tu tro de tao danh sach moi.
if (pdau == NULL)
{
printf("\n Danh sach rong!"); getch(); return;
}
pi = pdau;
while (pi != NULL)
{
pj = pi->next; pk = pi;
while (pj != NULL)
{
if (sosanh(pk->ht, pj->ht)>0) pk = pj;
pj = pj->next;
}
if (pk != pi)
{
tg = pi;
swap(tg, pk);
pi = pk;
}
pi = pi->next;
}
printf("\n Da sap xep xong!");
getch();
}
void inds()
{
struct sv *p;
int i = 1;
if (pdau == NULL)
{
printf("\n Danh sach rong!"); getch(); return;
}
p = pdau;
printf("\n Danh sach sinh vien: ");
printf("\n %5s %30s %13s %13s %13s %25s %15s", "STT", "Ho va ten", "MSSS", "Nam sinh", "Gioitinh", "Lop", "Diem");
while (p!=NULL)
{
printf("\n %5d %30s %13d %13d %13s %25s %15.2f", i++, p->ht, p->mssv, p->ns, p->gt, p->lop, p->diem);
p = p->next;
}
getch();
}
int main()
{
char ch;
while (1)
{
system("cls");
printf("\n Chuong trinh quan li sinh vien!");
printf("\n ===============================");
printf("\n 1. Doc du lieu tu file!");
printf("\n 2. Ghi file!");
printf("\n 3. Bo sung danh sach!");
printf("\n 4. Sap xep danh sach theo ten tieng Viet!");
printf("\n 5. In danh sach ra man hinh!");
printf("\n ===============================");
fflush(stdin); ch = getch();
if (ch == '1') docfile();
else if (ch == '2') ghifile();
else if (ch == '3') bosung();
else if (ch == '4') sapxep();
else if (ch == '5') inds();
else
{
printf("\n Chan roi a? Y/ ... "); fflush(stdin); ch = getch();
if (ch == 'y' || ch == 'Y') break;
}
}
return 0;
}
| true |
f1ebddea63822cb729bbcd64027087f928551a10 | C++ | opendarkeden/server | /src/server/gameserver/Party.h | UHC | 8,573 | 2.640625 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : Party.h
// Written by : excel96
// Description :
//////////////////////////////////////////////////////////////////////////////
#ifndef __PARTY_H__
#define __PARTY_H__
#include "Creature.h"
#include "Mutex.h"
#include "ModifyInfo.h"
#include "Mutex.h"
#include <unordered_map>
#include <list>
// Ƽ ִ ũ
const int PARTY_MAX_SIZE = 6;
//////////////////////////////////////////////////////////////////////////////
// forward declaration
//////////////////////////////////////////////////////////////////////////////
class Packet;
class GCPartyJoined;
class Creature;
class MonsterCorpse;
//////////////////////////////////////////////////////////////////////////////
// class PartyInviteInfo
//////////////////////////////////////////////////////////////////////////////
class PartyInviteInfo
{
public:
PartyInviteInfo() { m_HostName = ""; m_GuestName = ""; }
~PartyInviteInfo() {}
public:
string getHostName(void) const { return m_HostName; }
void setHostName(const string& name) { m_HostName = name; }
string getGuestName(void) const { return m_GuestName; }
void setGuestName(const string& name) { m_GuestName = name; }
public:
string toString(void) const ;
protected:
string m_HostName;
string m_GuestName;
};
//////////////////////////////////////////////////////////////////////////////
// class PartyInviteInfoManager
//////////////////////////////////////////////////////////////////////////////
class PartyInviteInfoManager
{
public:
PartyInviteInfoManager() ;
~PartyInviteInfoManager() ;
public:
bool hasInviteInfo(const string& HostName) ;
bool canInvite(Creature* pHost, Creature* pGuest) ;
bool isInviting(Creature* pHost, Creature* pGuest) ;
void initInviteInfo(Creature* pHost, Creature* pGuest) ;
void cancelInvite(Creature* pHost, Creature* pGuest) ;
void cancelInvite(Creature* pCreature) ;
public:
bool addInviteInfo(PartyInviteInfo* pInfo) ;
void deleteInviteInfo(const string& HostName) ;
PartyInviteInfo* getInviteInfo(const string& HostName) ;
protected:
unordered_map<string, PartyInviteInfo*> m_InfoMap;
Mutex m_Mutex;
};
//////////////////////////////////////////////////////////////////////////////
// class Party
//////////////////////////////////////////////////////////////////////////////
class Party
{
public:
Party(Creature::CreatureClass CClass) ;
~Party() ;
public:
int getID(void) const { return m_ID; }
void setID(int ID) { m_ID = ID; }
Creature::CreatureClass getCreatureClass(void) const { return m_CreatureClass; }
public:
Creature* getMember(const string& name) const ;
void addMember(Creature* pCreature) ;
void deleteMember(const string& name) ;
bool hasMember(const string& name) const ;
// ۷ι Ƽ Ŵ Ѵ.
// Ƽ üϱ Ƽ Ƽ ID 0 ,
// Ƽ Ŵ ش ID Ƽ Ѵ.
void destroyParty(void) ;
public:
// Ƽ 鿡 Ŷ .
void broadcastPacket(Packet* pPacket, Creature* pOwner=NULL) ;
// ο Ƽ ߰Ǿ Ƽ鿡 ư
// GCPartyJoined Ŷ Ѵ.
void makeGCPartyJoined(GCPartyJoined* pGCPartyJoined) const ;
public:
int getSize(void) const ;
unordered_map<string, Creature*> getMemberMap(void) ;
// Ÿ(8Ÿ) ִ ڸ Ѵ.
int getAdjacentMemberSize(Creature* pLeader) const ;
int getAdjacentMemberSize_LOCKED(Creature* pLeader) const ;
// ġ Ǯ .
int shareAttrExp(Creature* pLeader, int amount, int STRMultiplier, int DEXMultiplier, int INTMultiplier, ModifyInfo& LeaderModifyInfo) const ;
int shareVampireExp(Creature* pLeader, int amount, ModifyInfo& LeaderModifyInfo) const ;
int shareOustersExp(Creature* pLeader, int amount, ModifyInfo& LeaderModifyInfo) const ;
public:
void shareRevealer(Creature* pCaster, int Duration) ;
void shareDetectHidden(Creature* pCaster, int Duration) ;
void shareDetectInvisibility(Creature* pCaster, int Duration) ;
void shareExpansion(Creature* pCaster, int Duration, int percent) ;
void shareActivation(Creature* pCaster, int Duration) ;
void shareGnomesWhisper(Creature* pCaster, int Duration, int SkillLevel) ;
void shareHolyArmor(Creature* pCaster, int DefBonus, int SkillLevel) ;
bool shareWaterElementalHeal(Creature* pCaster, int HealPoint) ;
void shareGDRLairEnter(Creature* pLeader) ;
void shareRankExp(Creature* pLeader, int amount) ;
void shareAdvancementExp(Creature* pLeader, int amount) ;
void dissectCorpse(Creature* pDissecter, MonsterCorpse* pCorpse) ;
void eventPartyCrash() ;
public:
bool isFamilyPay() const { return m_bFamilyPay; }
void refreshFamilyPay();
public:
string toString(void) const ;
protected:
int m_ID; // Ƽ ID
Creature::CreatureClass m_CreatureClass; // Ƽ
unordered_map<string, Creature*> m_MemberMap; // Ƽ
mutable Mutex m_Mutex; // ο
bool m_bFamilyPay; // йи Ƽΰ?
};
//////////////////////////////////////////////////////////////////////////////
// class PartyManager
//////////////////////////////////////////////////////////////////////////////
class PartyManager
{
public:
PartyManager() ;
virtual ~PartyManager() ;
public:
virtual bool createParty(int ID, Creature::CreatureClass) ;
virtual bool addPartyMember(int ID, Creature* pCreature) ;
virtual bool deletePartyMember(int ID, Creature* pCreature) ;
virtual Party* getParty(int ID) ;
public:
virtual string toString(void) const = 0;
protected:
unordered_map<int, Party*> m_PartyMap; // Ƽ
mutable Mutex m_Mutex;
};
//////////////////////////////////////////////////////////////////////////////
// class LocalPartyManager
//////////////////////////////////////////////////////////////////////////////
class LocalPartyManager : public PartyManager
{
public:
LocalPartyManager() ;
virtual ~LocalPartyManager() ;
public:
void heartbeat(void) ;
int getAdjacentMemberSize(int PartyID, Creature* pLeader) const ;
int shareAttrExp(int PartyID, Creature* pLeader, int amount, int STRMultiplier, int DEXMultiplier, int INTMultiplier, ModifyInfo& LeaderModifyInfo) const ;
int shareVampireExp(int PartyID, Creature* pLeader, int amount, ModifyInfo& LeaderModifyInfo) const ;
int shareOustersExp(int PartyID, Creature* pLeader, int amount, ModifyInfo& LeaderModifyInfo) const ;
void shareRevealer(int PartyID, Creature* pCaster, int Duration) ;
void shareDetectHidden(int PartyID, Creature* pCaster, int Duration) ;
void shareDetectInvisibility(int PartyID, Creature* pCaster, int Duration) ;
void shareExpansion(int PartyID, Creature* pCaster, int Duration, int Percent) ;
void shareActivation(int PartyID, Creature* pCaster, int Duration) ;
void shareGnomesWhisper(int PartyID, Creature* pCaster, int Duration, int SkillLevel) ;
void shareHolyArmor(int PartyID, Creature* pCaster, int DefBonus, int SkillLevel) ;
bool shareWaterElementalHeal(int PartyID, Creature* pCaster, int HealPoint) ;
void shareGDRLairEnter(int PartyID, Creature* pLeader) ;
int shareRankExp(int PartyID, Creature* pLeader, int amount) const ;
int shareAdvancementExp(int PartyID, Creature* pLeader, int amount) const ;
public:
virtual string toString(void) const ;
};
//////////////////////////////////////////////////////////////////////////////
// class GlobalPartyManager
//////////////////////////////////////////////////////////////////////////////
class GlobalPartyManager : public PartyManager
{
public:
GlobalPartyManager() ;
virtual ~GlobalPartyManager() ;
public:
bool canAddMember(int ID) ;
virtual bool addPartyMember(int ID, Creature* pCreature) ;
virtual bool deletePartyMember(int ID, Creature* pCreature) ;
virtual bool expelPartyMember(int ID, Creature* pExpeller, const string& ExpelleeName) ;
int registerParty(void) ;
void refreshFamilyPay(int ID);
public:
virtual string toString(void) const ;
protected:
int m_PartyIDRegistry; // Ƽ ID
};
extern GlobalPartyManager* g_pGlobalPartyManager;
//////////////////////////////////////////////////////////////////////////////
// Ǹ Լ...
//////////////////////////////////////////////////////////////////////////////
void deleteAllPartyInfo(Creature* pCreature) ;
#endif
| true |
2b773368f9fe601cd90113ba9feca53b9af32839 | C++ | Brightest-Sunshine/Game-Gems-Cpp | /Project_Gems/Project_Gems/Repainting.cpp | UTF-8 | 1,025 | 2.84375 | 3 | [] | no_license | #include "Repainting.h"
Repainting::~Repainting() {}
void Repainting::DrawBonusTexture(std::shared_ptr<sf::RenderWindow> window, std::shared_ptr<Field> field)
{
Sprite painter;
Texture tex;
tex.loadFromFile("images/painter.png");
painter.setTexture(tex);
field->DoTransparent(x, y);
for (int i = 0; i < 25; i++) {
field->DrawField(*window);
window->display();
}
painter.setPosition(field->GetPositionX(x), field->GetPositionY(y));
for (int i = 0; i < 40; i++) {
window->draw(painter);
window->display();
}
}
int Repainting::Actuation(std::shared_ptr<Field> field)
{
int new_color, tmp1, tmp2, tmp_x, tmp_y;
new_color = rand() % 7;
field->ChangeColor(x, y, new_color);
for (int i = 0; i < countPaintedGems; i++) {
tmp1 = rand() % paintingRadius + 1;
tmp2 = rand() % paintingRadius + 1;
if (x + tmp1 <= 7)
tmp_x = x + tmp1;
else
tmp_x = x - tmp1;
if (y - tmp2 >= 0)
tmp_y = y - tmp2;
else
tmp_y = y + tmp2;
field->ChangeColor(tmp_x, tmp_y, new_color);
}
return 0;
}
| true |
6ef22b5f60058b1ec3f3ace9fcf0b9764b4a2f48 | C++ | sean-fisher/SDL-GameEngine | /SimE/SpriteBatch.cpp | UTF-8 | 8,141 | 2.5625 | 3 | [] | no_license | #include "stdafx.h"
#include "SpriteBatch.h"
#include <algorithm>
#include <iostream>
#include "Time.h"
#include "ResourceManager.h"
#include "Camera2D.h"
#define _CRTDBG_MAP_ALLOC
namespace SimE {
SpriteBatch::SpriteBatch() {
}
SpriteBatch::~SpriteBatch() {
}
void SpriteBatch::init(GLuint vao, GLuint vbo, int layerNum) {
m_vao = vao;
m_vbo = vbo;
m_layerNum = layerNum;
}
void SpriteBatch::begin() {
m_sortType = GlyphSortType::TEXTURE;
m_renderBatches.clear();
m_glyphs.clear();
}
void SpriteBatch::end() {
m_glyphPointers.resize(m_glyphs.size());
for (size_t i = 0; i < m_glyphs.size(); i++) {
m_glyphPointers[i] = &m_glyphs[i];
}
// make sure the glyphs are sorted for efficiency
sortGlyphs();
createRenderBatches();
}
void SpriteBatch::draw(const glm::vec4& destRect, const glm::vec4& uvRect, GLuint texture, float depth, const ColorRGBA8& color) {
m_glyphs.emplace_back(destRect, uvRect, texture, depth, color);
}
void SpriteBatch::draw(const glm::vec4& destRect, const glm::vec4& uvRect, GLuint texture, float depth, const ColorRGBA8& color, glm::vec2& scale) {
/* Glyph* newGlyph = new Glyph;
newGlyph->texture = texture;
newGlyph->depth = depth;
newGlyph->topLeft.color = color;
newGlyph->topLeft.setPosition(destRect.x * scale.x, (destRect.y + destRect.w) * scale.y);
newGlyph->topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
newGlyph->bottomLeft.color = color;
newGlyph->bottomLeft.setPosition(destRect.x * scale.x, destRect.y * scale.y);
newGlyph->bottomLeft.setUV(uvRect.x, uvRect.y);
newGlyph->bottomRight.color = color;
newGlyph->bottomRight.setPosition((destRect.x + destRect.z) * scale.x, destRect.y * scale.y);
newGlyph->bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
newGlyph->topRight.color = color;
newGlyph->topRight.setPosition((destRect.x + destRect.z) * scale.x, (destRect.y + destRect.w) * scale.y);
newGlyph->topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
_glyphs.push_back(newGlyph);*/
}
void SpriteBatch::drawAll(Camera2D* cam) {
begin(); // 3 is GlyphSortType::TEXTURE
// pos is xcoor, ycoor, width, height
glm::vec4 pos(0, 0, 100, 100);
glm::vec4 uv(0.0f, 0.0f, 1.0f, 1.0f);
SimE::ColorRGBA8 color;
color.r = 255;
color.g = 255;
color.b = 255;
color.a = 255;
if (m_sprites.size() > 0) {
_currentShaderID = m_sprites[0]->_shaderID;
pos.x = m_sprites[0]->_pos->x - m_sprites[0]->_texture.width / 2;
pos.y = m_sprites[0]->_pos->y - m_sprites[0]->_texture.height / 2;
pos.z = m_sprites[0]->_uv.x;
pos.w = m_sprites[0]->_uv.y;
uv.x = m_sprites[0]->_uv.x;
uv.y = m_sprites[0]->_uv.y;
glm::vec2 aliveDims(/*radius*/ 4);
if (cam->canBeSeen(*m_sprites[0]->_pos, m_sprites[0]->_texture.width, m_sprites[0]->_texture.height)) {
draw(pos, uv, (m_sprites[0])->_texture.id, 0, color);
}
for (size_t i = 1; i < m_sprites.size(); i++) {
// used for occlusion
if (cam->canBeSeen(*m_sprites[i]->_pos, m_sprites[i]->_texture.width, m_sprites[i]->_texture.height)) {
if (m_sprites[i]->_shaderID != _currentShaderID) {
_currentShaderID = m_sprites[i]->_shaderID;
}
pos.x = m_sprites[i]->_pos->x -
m_sprites[i]->_texture.width / 2;
pos.y = m_sprites[i]->_pos->y -
m_sprites[i]->_texture.height / 2;
pos.z = m_sprites[i]->_uv.x;
pos.w = m_sprites[i]->_uv.y;
uv.x = m_sprites[i]->_uv.x;
uv.y = m_sprites[i]->_uv.y;
draw(pos, uv, m_sprites[i]->_texture.id, (float) m_layerNum, color);
}
}
}
}
void SpriteBatch::renderBatch() {
glBindVertexArray(m_vao);
for (size_t i = 0; i < m_renderBatches.size(); i++) {
glBindTexture(GL_TEXTURE_2D, m_renderBatches[i].texture);
glDrawArrays(GL_TRIANGLES, m_renderBatches[i].offset, m_renderBatches[i].numVertices);
}
glBindVertexArray(0);
}
void SpriteBatch::createRenderBatches() {
std::vector<Vertex> vertices;
vertices.resize(m_glyphPointers.size() * 6); // each rectangular glyph has 6 vertices
if (m_glyphPointers.empty()) {
return;
}
int offset = 0;
int currentVertex = 0;
m_renderBatches.emplace_back(offset, 6, m_glyphPointers[0]->texture);
vertices[currentVertex++] = m_glyphPointers[0]->topLeft;
vertices[currentVertex++] = m_glyphPointers[0]->bottomLeft;
vertices[currentVertex++] = m_glyphPointers[0]->bottomRight;
vertices[currentVertex++] = m_glyphPointers[0]->bottomRight;
vertices[currentVertex++] = m_glyphPointers[0]->topRight;
vertices[currentVertex++] = m_glyphPointers[0]->topLeft;
offset += 6;
for (size_t cg = 1; cg < m_glyphPointers.size(); cg++) {
if (m_glyphPointers[cg]->texture != m_glyphPointers[cg - 1]->texture) {
m_renderBatches.emplace_back(offset, 6, m_glyphPointers[cg]->texture);
} else {
m_renderBatches.back().numVertices += 6;
}
vertices[currentVertex++] = m_glyphPointers[cg]->topLeft;
vertices[currentVertex++] = m_glyphPointers[cg]->bottomLeft;
vertices[currentVertex++] = m_glyphPointers[cg]->bottomRight;
vertices[currentVertex++] = m_glyphPointers[cg]->bottomRight;
vertices[currentVertex++] = m_glyphPointers[cg]->topRight;
vertices[currentVertex++] = m_glyphPointers[cg]->topLeft;
offset += 6;
}
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
// orphan the buffer
glBufferData(GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
nullptr,
GL_DYNAMIC_DRAW);
// upload the data
glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(Vertex), vertices.data());
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void SpriteBatch::sortGlyphs() {
switch (m_sortType) {
case GlyphSortType::BACK_TO_FRONT:
std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareBackToFront);
break;
case GlyphSortType::FRONT_TO_BACK:
std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareFrontToBack);
break;
case GlyphSortType::TEXTURE:
std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareTexture);
break;
}
}
bool SpriteBatch::compareBackToFront(Glyph* a, Glyph* b) {
return (a->depth < b->depth);
}
bool SpriteBatch::compareFrontToBack(Glyph* a, Glyph* b) {
return (a->depth > b->depth);
}
bool SpriteBatch::compareTexture(Glyph* a, Glyph* b) {
return (a->texture < b->texture);
}
void SpriteBatch::addSprite(Sprite * sprite) {
m_sprites.emplace_back(sprite);
}
void SpriteBatch::removeSprite(Sprite * sprite) {
size_t i = 0;
while (i < m_sprites.size() && m_sprites[i++] != sprite) {}
if (i <= m_sprites.size()) {
m_sprites.erase(m_sprites.begin() + i - 1);
}
}
void SpriteBatch::clearSprites() {
}
void SpriteBatch::initShaders() {
m_colorProgram.compileShaders("shaders/colorShader.vert", "shaders/colorShader.frag");
m_colorProgram.addAttribute("vertexPosition");
m_colorProgram.addAttribute("vertexColor");
m_colorProgram.addAttribute("vertexUV");
m_colorProgram.linkShaders();
}
void SpriteBatch::beginDrawing() {
// enable the shader
/*_colorProgram.use();
glActiveTexture(GL_TEXTURE0);
GLint textureLocation = _colorProgram.getUniformLocation("spriteSampler");
glUniform1i(textureLocation, 0);
GLuint timeLoc = _colorProgram.getUniformLocation("time");
// send variable to shader
glUniform1f(timeLoc, Time::getTime());*/
}
void SpriteBatch::endDrawing() {
end();
renderBatch();
}
Glyph::Glyph(const glm::vec4 & destRect, const glm::vec4 & uvRect, GLuint Texture, float Depth, const ColorRGBA8 & color) : depth(Depth), texture(Texture)
{
topLeft.color = color;
topLeft.setPosition(destRect.x, destRect.y + destRect.w);
topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
bottomLeft.color = color;
bottomLeft.setPosition(destRect.x, destRect.y);
bottomLeft.setUV(uvRect.x, uvRect.y);
bottomRight.color = color;
bottomRight.setPosition(destRect.x + destRect.z, destRect.y);
bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
topRight.color = color;
topRight.setPosition(destRect.x + destRect.z, destRect.y + destRect.w);
topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
}
} | true |
08f3425c7096a91eec1a38c07598b2f099bbd311 | C++ | oneflyingfish/Class-Helper | /Random.cpp | GB18030 | 1,001 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #include"Random.h"
int Random::random(int max)
{
std::random_device rd;//Ӳ豸ʼ,ϧwindowsΪrand_s
std::default_random_engine e(rd());//
std::uniform_int_distribution<int> u(0,max-1);//ʾȷֲ
return u(e);
/*qsrand(QTime(0, 0, 0).msecsTo(QTime::currentTime()));
return qrand() % max;*/
}
int Random::random(int min, int max)
{
std::random_device rd;//Ӳ豸ʼ,ϧwindowsΪrand_s
std::default_random_engine e(rd());//
std::uniform_int_distribution<int> u(min, max-1);//ʾȷֲ
return u(e);
/*qsrand(QTime(0, 0, 0).msecsTo(QTime::currentTime()));
return qrand() % (max - min) + min;*/
}
QList<StudentInfo> Random::sufferList(QList<StudentInfo>& infoList)
{
QList<StudentInfo> shufferList;
int times= infoList.count();
for (int i = 0; i < times; i++)
{
int index = random(infoList.count());
shufferList.append(infoList[index]);
infoList.removeAt(index);
}
return shufferList;
} | true |
139ab6aa66e0794aa825fdc18d82bc783d520563 | C++ | PSU-LQC-Group/VTK-viz | /IO/FreeFormatOneLine.h | UTF-8 | 928 | 2.640625 | 3 | [] | no_license | #include <string>
#include <SplittableString.h>
#ifndef FreeFormatOneLine_H
#define FreeFormatOneLine_H
using namespace std;
class FreeFormatOneLine{
public:
FreeFormatOneLine();
FreeFormatOneLine(string);
~FreeFormatOneLine();
void setText(string);
void setCommentDeliminator(string);
void setAssignDeliminator(string);
void setSecondLevelDeliminator(string);
void split();
string getFirstLevelIdentifier();
string getSecondLevelIdentifier();
string getValues();
string getComment();
private:
string commentDeliminator="#";
string assignDeliminator="=";
string secondLevelDeliminator=".";
string comment="";
string text;
string firstLevelIdentifier="";
string secondLevelIdentifier="";
string values="";
string trim(const string& str);
};
#endif
| true |
591705fbf5d57f53e7f8421f84cc242ef23a4ca5 | C++ | Souravirus/codechef | /aug17/hilljump.cpp | UTF-8 | 5,253 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int jumparr[17][100001];
//make the update function and query function of segmented tree
void build(int arr[], int n, int logval)
{
//first loop is to traverse to make different arrays from 1 to logval
for(int i=0; i<=logval; i++)
{
int jumpcount=pow(2, i);
//cout<<"for jumpcount "<<jumpcount<<endl;
//second loop is to make different elements of that array
for(int j=1; j<=n; j++)
{
int cnt=0;
int indcnt=j;
int diff=0;
int flag=0;
while(cnt<jumpcount && indcnt<=n )
{
//cout<<"current indcnt "<<indcnt<<endl;
if(diff>=100 || indcnt>n)
{
// cout<<"breaking away"<<endl;
break;
}
else if(arr[j]<arr[indcnt])
{
jumparr[i][j]=indcnt;
//cout<<"in correct if"<<endl;
cnt++;
//cout<<"cnt increased to "<<cnt<<endl;
diff=0;
}
else
{
//cout<<"nothing happened"<<endl;
diff++;
}
indcnt++;
}
if(jumparr[i][j]==0)
{
//cout<<"Putiing some thing here "<<endl;
jumparr[i][j]=j;
}
}
}
}
//update(start, 0, n, value, seg_tree);
int seg_query(int l, int r, int s, int e, int node_num, int seg_tree[])
{
if(s>r|| e<l)
return 0;
else if(s>=l && e<=r)
return seg_tree[node_num];
else
{
int m=(s+e)/2;
return seg_query(l, r, s, m , node_num*2, seg_tree) + seg_query(l, r, m+1, e, node_num*2+1, seg_tree);
}
}
void seg_update(int pos, int s, int e, int value, int seg_tree[], int node_num)
{
if(s==e)
{
seg_tree[node_num]+=value;
return ;
}
int mid=(s+e)/2;
if(mid<pos)
{
seg_update(pos, mid+1, e, value, seg_tree, node_num*2+1);
}
else
seg_update(pos, s, mid, value, seg_tree, node_num*2);
seg_tree[node_num]=seg_tree[node_num*2]+seg_tree[node_num*2+1];
}
void update_jump(int arr[], int upni[], int n, int logval, int s, int e, int seg_tree[]){
int start, end;
//first loop is to traverse to make different arrays from 1 to logval
for(int i=0; i<=logval; i++)
{
int jumpcount=pow(2, i);
start=(s-jumpcount*100);
if(start<1)
{
start=1;
}
cout<<"start"<<start<<endl;
end=e-jumpcount*100;
if(end<s)
{
end=s+1;
}
cout<<"end"<<end<<endl;
//second loop is to make different elements of that array
for(int j=start; j<=s; j++)
{
int numupd=seg_query(0, start, 0, n, 0, seg_tree);
int jupd=seg_query(0, s, 0, n, 0, seg_tree);
int cnt=0;
int indcnt=j;
int diff=0;
int flag=0;
jumparr[i][j]=0;
cout<<"i "<<i<<"j "<<j<<endl;
while(cnt<jumpcount && indcnt<=n )
{
numupd+=upni[indcnt];
cout<<"numupd"<<numupd<<endl;
cout<<"current indcnt "<<indcnt<<endl;
if(diff>=100 || indcnt>n)
{
cout<<"breaking away"<<endl;
break;
}
else if(arr[j]+seg_query(0, j, 0, n, 0, seg_tree)<arr[indcnt]+seg_query(0, indcnt, 0, n, 0, seg_tree))
{
cout<<"Putiing "<<j<<" at"<<"i "<<i<<"j "<<indcnt<<endl;
jumparr[i][j]=indcnt;
cout<<"in correct if"<<endl;
cnt++;
cout<<"cnt increased to "<<cnt<<endl;
diff=0;
}
else
{
cout<<"nothing happened"<<endl;
diff++;
}
indcnt++;
}
if(jumparr[i][j]==0)
{
cout<<"Putiing "<<j<<" at"<<"i "<<i<<"j "<<j<<endl;
jumparr[i][j]=j;
}
}
for(int j=end; j<=e; j++)
{
int numupd=0;
int cnt=0;
int indcnt=j;
int diff=0;
int flag=0;
while(cnt<jumpcount && indcnt<=n )
{
numupd+=upni[indcnt];
//cout<<"current indcnt "<<indcnt<<endl;
if(diff>=100 || indcnt>n)
{
// cout<<"breaking away"<<endl;
break;
}
else if(arr[j]+numupd<arr[indcnt]+numupd)
{
jumparr[i][j]=indcnt;
//cout<<"in correct if"<<endl;
cnt++;
//cout<<"cnt increased to "<<cnt<<endl;
diff=0;
}
else
{
//cout<<"nothing happened"<<endl;
diff++;
}
indcnt++;
}
if(jumparr[i][j]==0)
{
//cout<<"Putiing some thing here "<<endl;
jumparr[i][j]=j;
}
}
}
}
int query(int index, int jump, int n)
{
int count=0;
int ans=index;
while(jump!=0)
{
int rem=jump%2;
if(rem==1)
{
int temp;
// cout<<"count"<<count<<" ans"<<ans<<endl;
temp=jumparr[count][ans];
if(temp==ans || temp==n)
return temp;
else
ans=temp;
}
jump=jump/2;
count++;
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, q, index, type, jump, ans;
cin>>n>>q;
int arr[n+1];
int upni[n+1];
int seg_tree[4*n]={0};
for(int i=1; i<=n; i++)
{
cin>>arr[i];
upni[i]=0;
}
int logval=log2(n);
memset(jumparr, 0, sizeof(jumparr));
build(arr, n, logval);
for(int i=1; i<=q; i++)
{
cin>>type;
if(type==1)
{
cin>>index;
cin>>jump;
ans=query(index, jump, n);
cout<<ans<<endl;
}
else{
int start;
int end, value;
cin>>start>>end>>value;
seg_update(start, 1, n, value, seg_tree, 0);
seg_update(end, 1, n, -1*value, seg_tree, 0);
cout<<"seg tree printing"<<endl;
for(int i=0; i<=n; i++)
{
cout<<seg_tree[i]<<endl;
}
update_jump(arr, upni, n, logval, start, end, seg_tree);
//cout<<"after update"<<endl;
for(int i=0; i<=logval; i++)
{
for(int j=1; j<=n; j++)
cout<<"[ "<<i <<", "<<j<<"]"<<jumparr[i][j]<<" ";
cout<<endl;
}
}
}
return 0;
}
| true |
4d3329a98a21bb70d92066448bcb58ae43e73d64 | C++ | bebyakinb/CPP_Piscine | /d03/ex01/ScavTrap.hpp | UTF-8 | 1,014 | 2.9375 | 3 | [] | no_license | //
// Created by Endell Noelia on 3/11/21.
//
#ifndef D03_SCAVTRAP_HPP
# define D03_SCAVTRAP_HPP
# define CHALLANGECOUNT 3
# include <iostream>
class ScavTrap
{
private:
void printPrefix();
unsigned int _hitPoints;
unsigned int _maxHitPoints;
int _energyPoints;
unsigned int _maxEnergyPoints;
unsigned int _level;
std::string _name;
unsigned int _meleeAttackDamage;
unsigned int _rangedAttackDamage;
unsigned int _armorDamageReduction;
public:
ScavTrap();
ScavTrap(const std::string&);
ScavTrap(const ScavTrap&);
~ScavTrap();
ScavTrap& operator=(const ScavTrap&);
void rangedAttack(std::string const & target);
void meleeAttack(std::string const & target);
void challange1(std::string const & target);
void challange2(std::string const & target);
void challange3(std::string const & target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
void challengeNewcomer(std::string const & target);
};
#endif //D03_SCAVTRAP_HPP
| true |
19a588b166beed624b9ce93511370f4301b96609 | C++ | WangShanyue/X86ToMips | /code/util/fileUtil.cpp | UTF-8 | 928 | 2.890625 | 3 | [] | no_license | //
// Created by cyw35 on 2018/12/25.
//
#include<iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cassert>
#include <string>
#include <map>
#include <vector>
#include <cstring>
#include "fileUtil.h"
using namespace std;
vector<string> readTxt(string file) { //读文件
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
vector<string> res;
string s;
while (getline(infile, s)) {
int len = s.size();
s = s.at(len - 1) == ';' ? s.substr(0, len - 1) : s; //处理句尾的‘;’
res.insert(res.end(), s);
}
infile.close(); //关闭文件输入流
return res;
}
void writeTxt(char *file, string content) { //写文件
ofstream outfile(file);
outfile << content;
outfile.close();
}
| true |
8c3f1ab60c2a138cdd8ee819890358d918f80b57 | C++ | danbinnun1/ex4 | /src/GraphPathService.cpp | UTF-8 | 1,461 | 3.0625 | 3 | [] | no_license | #include "GraphPathService.hpp"
#include "Direction.hpp"
#include <vector>
server_side::GraphPathService::GraphPathService()
: m_path(std::vector<Direction>()), m_pathWeight(0), m_lastWeight(0) {}
void server_side::GraphPathService::addDirection(Direction d, double weight) {
m_path.push_back(d);
m_pathWeight += weight;
m_lastWeight = weight;
}
std::vector<server_side::Direction>
server_side::GraphPathService::getPath() const {
return m_path;
}
double server_side::GraphPathService::getPathWeight() const {
return m_pathWeight;
}
double server_side::GraphPathService::getLastWeight() const {
return m_lastWeight;
}
server_side::GraphElement
server_side::GraphPathService::applyPath(const server_side::FindGraphPathInfo& info) {
uint32_t row = info.getStartRow();
uint32_t col = info.getStartCol();
for (Direction d : m_path) {
if (d == Direction::up) {
row--;
} else if (d == Direction::down) {
row++;
} else if (d == Direction::left) {
col--;
} else if (d == Direction::right) {
col++;
}
}
return GraphElement(row, col);
}
bool server_side::LargerThanByPathWeight::operator()(
const GraphPathService &lhs, const GraphPathService &rhs) const {
return lhs.getPathWeight() > rhs.getPathWeight();
}
bool server_side::LargerThanByLastWeight::operator()(
const GraphPathService &lhs, const GraphPathService &rhs) const {
return lhs.getLastWeight() > rhs.getLastWeight();
}
| true |
52a4d9b34032963d780793cd717f08a96d6e55da | C++ | raghavjajodia/SchoolProgramming | /LISTOFPRACTICALS/Q14.CPP | UTF-8 | 2,168 | 3.890625 | 4 | [] | no_license | /*Q-14) EACH NODE OF A QUEUE CONTAINS BOOKNO,BOOKNAME,PRICE AND SUBJECT IN ADDITION TO THE POINTER FIELD. WRITE FUNCTIONS TO INSERT, DELETE,AND SHOW ALL THE
ELEMENTS. ALSO WRITE A FUNCTION TO COUNT THOSE NODES OF THE QUEUE, WHOSE SUBJECT IS "SCIENCE"*/
#include<iostream.h>
#include<process.h>
#include<conio.h> //header files
#include<stdio.h>
#include<string.h>
struct node
{
int bookno;
float price;
char booknm[20];
char subject[10]; //structure node
node*link;
};
class queue{
node*front,*rear; //class queue
public:
queue()
{
front=rear=NULL;
}
void qins();
void qdel();
void qdisp();
void countsubject();
};
void main() //main func
{
queue s1;
clrscr();
int a;
char ch;
do{
cout<<"\t\t\t\tmain menu \n";
cout<<" \t\t\t\t1.insert into queue\n";
cout<<"\t\t\t\t2.delete from queue\n";
cout<<"\t\t\t\t3.display queue\n";
cout<<"\t\t\t\t4.countsubject\n";
cout<<"\t\t\t\t5.exit\n";
cout<<"enter the choice\n";
cin>>a;
switch(a)
{
case 1: s1.qins();break;
case 2: s1.qdel();break;
case 3: s1.qdisp();break;
case 4: s1.countsubject();break;
case 5: exit(0);break;
default:cout<<"wrong no entered";
}
cout<<"\n do you want to continue\t";
cin>>ch;
}
while(ch=='y');
}
void queue::qins() //insert in queue
{
node*temp;
temp=new node;
if(temp==NULL)
cout<<"no space";
else
{
cout<<"enter bookno";
cin>>temp ->bookno;
cout<<"enter booknm";
gets(temp->booknm);
cout<<"enter price ";
cin>>temp->price;
cout<<"enter subject";
gets(temp->subject);
temp->link=NULL;
}
if(rear==NULL)
front=rear=temp;
else{
rear->link=temp;
rear=temp;
}}
void queue::qdel() //delete from queue
{
node*temp;
if(front==NULL)
cout<<"queue empty";
else
{
temp=front;
front=front->link;
delete temp;
}
}
void queue::qdisp() //displaying the queue
{
node*temp;
for(temp=front;temp!=NULL;temp=temp->link)
{
cout<<temp->bookno<<" ";
puts(temp->booknm);
cout<<temp->price<<" ";
puts(temp->subject);
}
}
void queue::countsubject() //counting no. of subjects
{
node*temp;
int c=0;
for(temp=front;temp!=NULL;temp=temp->link)
if(strcmp(temp->subject,"science")==0)
c++;
cout<<"The no of data related to science subject ="<<c;
}
| true |
62408ea39c159efe436b277757756d37a18f3cf2 | C++ | ngtranminhtuan/Algorithm-Immediately | /14. Prim/Road Construction.cpp | UTF-8 | 3,662 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int MAX = 105;
const int inf = 1e7;
int test;
map <string , int> my_map;
int n, m;
int dist[MAX];
bool visited[MAX];
vector<pair<int, int> > adj[MAX];
void Prim(int source) {
priority_queue<pair<int , int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
for (int i = 1; i <= n; i++) {
dist[i] = inf;
visited[i] = false;
}
pq.push(make_pair(0 , source));
dist[source] = 0;
while (!pq.empty()) {
pair <int , int> tmp = pq.top();
pq.pop();
int u = tmp.second;
visited[u] = true;
for (int i = 0; i < adj[u].size(); i++) {
pair<int , int> neighbor = adj[u][i];
int v = neighbor.first;
int c = neighbor.second;
if (!visited[v] && dist[v] > c) {
dist[v] = c;
pq.push(make_pair(c , v));
}
}
}
int res = 0;
for (int i = 1; i <= n; i++)
res += dist[i];
if (res >= inf) {
cout << "Impossible\n";
}
else {
cout << res << endl;
}
}
int main () {
//freopen("input.txt" , "r" , stdin);
cin >> test;
int t = test;
while (test--) {
cout << "Case " << t - test << ": ";
cin >> m;
my_map.clear();
n = 0;
for (int i = 1; i <= 2*m; i++)
adj[i].clear();
for (int i = 1; i <= m; i++) {
string s1 , s2;
int w;
cin >> s1 >> s2 >> w;
if (my_map.find(s1) == my_map.end()) {
my_map[s1] = ++n;
}
if (my_map.find(s2) == my_map.end()) {
my_map[s2] = ++n;
}
int u = my_map[s1];
int v = my_map[s2];
adj[u].push_back(make_pair(v , w));
adj[v].push_back(make_pair(u , w));
}
Prim(1);
}
return 0;
}
// Py
import queue
class node:
dist = 0
index = 0
def __init__(self, dist, index):
self.dist = dist
self.index = index
def __lt__(self, other):
return self.dist < other.dist
def inp():
return map(int, input().split())
def prim(graph, src):
n = len(graph)
dist = [1e18 for i in range(n)]
visited = [0 for i in range(n)]
total_cost = 0
dist[src] = 0
Q = queue.PriorityQueue()
Q.put(node(0, src))
while not Q.empty():
temp = Q.get()
u = temp.index
visited[u] = True
for item in graph[u]:
v = item.index
if not visited[v] and dist[v] > item.dist:
dist[v] = item.dist
Q.put(node(dist[v], v))
for i in range(n):
if dist[i] >= 1e18:
return "Impossible"
total_cost += dist[i]
return total_cost
def solve():
testcase = int(input())
for t in range(testcase):
input()
m = int(input())
cities = dict()
cnt = 0
graph = []
for i in range(m):
name1, name2, cost = input().split()
if name1 in cities:
u = cities[name1]
else:
u = cnt
cities[name1] = cnt
graph.append([])
cnt+=1
if name2 in cities:
v = cities[name2]
else:
v = cnt
cities[name2] = cnt
graph.append([])
cnt+=1
cost = int(cost)
graph[u].append(node(cost, v))
graph[v].append(node(cost, u))
print("Case {}: {}".format(t + 1, prim(graph, 0)))
solve() | true |
4d118fe282deb5842ae3550cae2129691091d1b2 | C++ | TheRoboticsClub/2019-colab-victor_lucia | /docs/AVANCES/30EN20/led/led/led.ino | UTF-8 | 696 | 3 | 3 | [] | no_license | /*LED */
#include "ParserLib.h"
char demo[] = "LED#1-OFF";
int demoLength = strlen(demo);
Parser parser((byte*)demo, demoLength);
void setup()
{
Serial.begin(9600);
while (!Serial) { ; }
Serial.println("Starting Demo");
}
void loop()
{
Serial.println("--- Demo loop ---");
parser.Compare("LED", 3,
[]() { Serial.print("Received LED N:");
parser.SkipWhile(Parser::IsSeparator);
Serial.print(parser.Read_Uint8());
parser.SkipWhile(Parser::IsSeparator);
parser.Compare("ON", 2, []() {Serial.println(" Action: TURN ON"); });
parser.Compare("OFF", 3, []() {Serial.println(" ACTION: TURN OFF"); });
});
parser.Reset();
delay(2500);
}
| true |
3d4a45030152cbcea805361d1235b0efa8caac88 | C++ | handicraftsman/guosh | /src/guosh.cpp | UTF-8 | 5,139 | 2.671875 | 3 | [
"MIT"
] | permissive | #include <guosh.hpp>
Guosh::LogLevel Guosh::Logger::main_level = Guosh::LogLevel::INFO;
Guosh::LogLevel Guosh::Logger::main_file_level = Guosh::LogLevel::WARNING;
Guosh::Logger::Logger(std::string _name, Guosh::LogLevel _level)
: name(_name)
, level(_level)
, iochars(" IO")
, should_log_to_files(false)
, logging_directory("./")
, fprefix("log")
{}
Guosh::Logger::Logger(Logger& other)
: name(other.name)
, level(other.level)
{}
bool Guosh::Logger::operator==(Guosh::Logger& other) {
return this->name == other.name && this->level == other.level;
}
void Guosh::Logger::write(std::string message, Guosh::LogLevel level, va_list args) {
static std::mutex mtx;
static std::ofstream file;
static std::string filename;
mtx.lock();
time_t now = time(0);
std::string dt = std::string(ctime(&now));
dt.pop_back();
if (level >= Guosh::Logger::main_level) {
std::cerr << this->format(message, dt, level, args, true) << std::endl;
}
if (level >= Guosh::Logger::main_file_level) {
if (should_log_to_files) {
char* raw_new_f = (char*) malloc(sizeof(16 + fprefix.size()));
strftime(raw_new_f, 16 + fprefix.size(), (fprefix + "-%d.%m.%Y.log").c_str(), localtime(&now));
std::string new_filename(raw_new_f);
if (filename != new_filename) {
file.close();
filename = new_filename;
file.open(logging_directory + "/" + filename, std::ios_base::app);
}
std::string dat = this->format(message, dt, level, args, false);
file << dat << std::endl;
file.flush();
free(raw_new_f);
}
}
mtx.unlock();
}
void Guosh::Logger::write(std::string message, Guosh::LogLevel level, ...) {
va_list args;
va_start(args, level);
this->write(message, level, args);
va_end(args);
}
void Guosh::Logger::write(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, this->level, args);
va_end(args);
}
void Guosh::Logger::operator()(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, this->level, args);
va_end(args);
}
void Guosh::Logger::enable_file_logging(std::string directory, std::string prefix) {
logging_directory = directory;
fprefix = prefix;
should_log_to_files = true;
}
void Guosh::Logger::disable_file_logging() {
should_log_to_files = false;
}
std::string Guosh::Logger::format(std::string _message, std::string dt, Guosh::LogLevel level, va_list args, bool colored) {
va_list la;
va_copy(la, args);
char* cmessage = NULL;
vasprintf(&cmessage, _message.c_str(), la);
std::string message = std::string(cmessage);
free(cmessage);
// Get level chars
std::string lvl_chars = "UNK";
std::string lvl_color = "";
std::string c_bold = "\x1b[1m";
std::string c_reset = "\x1b[0m";
std::string c_creset = "\x1b[39m";
switch(level) {
case Guosh::LogLevel::DEBUG:
lvl_chars = "DBG";
lvl_color = "\x1b[32m";
break;
case Guosh::LogLevel::IO:
lvl_chars = iochars;
lvl_color = "\x1b[36m";
break;
case Guosh::LogLevel::INFO:
lvl_chars = "INF";
lvl_color = "\x1b[34m";
break;
case Guosh::LogLevel::WARNING:
lvl_chars = "WRN";
lvl_color = "\x1b[33m";
break;
case Guosh::LogLevel::ERROR:
lvl_chars = "ERR";
lvl_color = "\x1b[31m";
break;
case Guosh::LogLevel::IMPORTANT:
lvl_chars = "IMP";
lvl_color = "\x1b[37m";
break;
case Guosh::LogLevel::CRITICAL:
lvl_chars = "CRT";
lvl_color = "\x1b[35m";
break;
default:
break;
}
// Return
if (colored) {
return
c_bold
+ lvl_color
+ "["
+ c_creset
+ std::string(dt)
+ lvl_color
+ " | "
+ c_creset
+ lvl_chars
+ lvl_color
+ "] "
+ c_reset
+ name
+ c_bold
+ lvl_color
+ "> "
+ c_reset
+ message
;
} else {
return
"["
+ std::string(dt)
+ " | "
+ lvl_chars
+ "] "
+ name
+ "> "
+ message
;
}
}
void Guosh::Logger::debug(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::DEBUG, args);
va_end(args);
}
void Guosh::Logger::io(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::IO, args);
va_end(args);
}
void Guosh::Logger::info(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::INFO, args);
va_end(args);
}
void Guosh::Logger::warning(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::WARNING, args);
va_end(args);
}
void Guosh::Logger::error(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::ERROR, args);
va_end(args);
}
void Guosh::Logger::important(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::IMPORTANT, args);
va_end(args);
}
void Guosh::Logger::critical(std::string message, ...) {
va_list args;
va_start(args, message);
this->write(message, LogLevel::CRITICAL, args);
va_end(args);
}
| true |
e39c74d56d625a9b9eb4db3f96bbecc1c4890dfd | C++ | walterfreeman/picup-workshop | /gas3d.cpp | UTF-8 | 15,292 | 3.25 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include "vector.h"
int ilist_size=1000000; // how much memory to allocate for the list of possible interactions
int N=2000; // default number of particles (probably changed later)
double L=1; // box width
double r0=0.015; // interaction radius
int NG; // number of zones in each direction. Set later
double pad=2; // At what multiple of r0 do we assume the force is small and neglect the interactions?
double timer[10]; // Array shared by starttimer() and stoptimer() for timing things
// the following is a new thing y'all haven't learned yet. Ask me about in person; this is used to make
// "linked lists", which are a way of keeping track of which particles are where.
struct list_el {
int val;
struct list_el *next;
};
typedef struct list_el item;
double myclock(void)
{
return clock()/1e6;
}
// Just a dopey timing function that tells you if n milliseconds have passed since the last time you called it
// "bool" = "boolean", true or false (1 or 0, basically)
bool istime2(int msec)
{
static double lasttime=0;
if (myclock() - lasttime > msec / 1000.0)
{
lasttime=myclock();
return true;
}
else return false;
}
bool istime(int msec)
{
static double lasttime=0;
if (myclock() - lasttime > msec / 1000.0)
{
lasttime=myclock();
return true;
}
else return false;
}
// given a particle's position, which zone is it in?
ivec getzone (vector v)
{
ivec result;
result.x=(int)((v.x+L/2)*NG/L);
result.y=(int)((v.y+L/2)*NG/L);
result.z=(int)((v.z+L/2)*NG/L);
if (result.x>=NG) result.x=NG-1;
if (result.x<0) result.x=0;
if (result.y>=NG) result.y=NG-1;
if (result.y<0) result.y=0;
if (result.z>=NG) result.z=NG-1;
if (result.z<0) result.z=0;
return result;
}
// add/remove an item from linked lists -- will explain this in person
void add(item **list, int v)
{
// printf("!Adding item %d\n",v);
item *curr;
curr=(item *)malloc(sizeof(item));
curr->val = v;
curr->next = *list;
*list=curr;
}
void del (item **list, int v)
{
item *curr;
curr=*list;
if (curr == NULL) {return;}
if (curr->val == v) {*list=curr->next; free(curr);}
else
while (curr -> next != NULL)
{
if (curr->next->val == v)
{
free(curr->next); curr->next=curr->next->next;
break;
}
curr=curr->next;
}
}
// cycle through all the particles and put them in the right zones
int check_zonelist(item **zonelist,ivec zone[], vector pos[])
{
ivec cz; // the correct zone for the particle to be in
for (int i=0;i<N;i++)
{
cz = getzone(pos[i]);
if (cz.x != zone[i].x || cz.y != zone[i].y || cz.z != zone[i].z) // if we're not in the right zone, fix it
{
if (zone[i].x >= 0 && zone[i].x < NG && zone[i].y >= 0 && zone[i].y < NG && zone[i].z >= 0 && zone[i].x < NG) del(&zonelist[zone[i].x*NG*NG + zone[i].y * NG + zone[i].z],i);
add(&zonelist[cz.x*NG*NG + cz.y*NG + cz.z],i);
}
zone[i]=cz;
}
}
// a function for V(r), used only to compute total energy
double V(double r)
{
if (r > r0*pad) return V(r0*pad);
r/=r0;
static double r6;
r6=r*r*r*r*r*r;
return (4*r0*(1/(r6*r6)-1/r6));
}
double V2(double r)
{
if (r*r > r0*r0*pad*pad) return V2(r0*r0*pad*pad);
r/=(r0*r0);
static double r6;
r6=r*r*r;
return (4*r0*(1/(r6*r6)-1/r6));
}
// derpy timing functions: this one starts a timer with index t...
void starttimer(int t)
{
timer[t]=myclock();
}
// and this one stops it, returning how long it's been in microseconds since starttimer was called
double stoptimer(int t)
{
return myclock()-timer[t];
}
// NOTE: Actually returns F/r to avoid having to do a square root in velocity_update
// when dealing with the unit vectors. This is why it's r^14-r^8.
// Square roots are 'spensive.
double force(double r2)
{
static double r8,r14,r6;
r6=r2*r2*r2; // doing this is substantially faster than using pow()
r8=r6*r2;
r14=r6*r8;
return -24.*(2./r14 - 1./r8) / r0; // the factor of 24 is in some canonical form of this. gods know why.
}
double drnd48(void) // just a way to get a centered random number
{
return drand48()-0.5;
}
void draw_box(double L)
{
// baaaaarf.
printf("l3 -%e -%e -%e -%e -%e %e\n",L,L,L,L,L,L);
printf("l3 -%e -%e %e -%e %e %e\n",L,L,L,L,L,L);
printf("l3 -%e %e %e -%e %e -%e\n",L,L,L,L,L,L);
printf("l3 -%e %e -%e -%e -%e -%e\n",L,L,L,L,L,L);
printf("l3 %e -%e -%e %e -%e %e\n",L,L,L,L,L,L);
printf("l3 %e -%e %e %e %e %e\n",L,L,L,L,L,L);
printf("l3 %e %e %e %e %e -%e\n",L,L,L,L,L,L);
printf("l3 %e %e -%e %e -%e -%e\n",L,L,L,L,L,L);
printf("l3 %e -%e -%e -%e -%e -%e\n",L,L,L,L,L,L);
printf("l3 %e %e -%e -%e %e -%e\n",L,L,L,L,L,L);
printf("l3 %e -%e %e -%e -%e %e\n",L,L,L,L,L,L);
printf("l3 %e %e %e -%e %e %e\n",L,L,L,L,L,L);
}
// This is the function I said I'd give you a copy of. What this does:
// * assumes that zonelist is an array of linked lists, one for each zone, that holds the particles in each zone
// * ... and that zone is an array of size N that holds which zone each particle is in
// * For each particle i in the simulation:
// * For its own zone and all adjacent zones:
// * For each particle j in those zones (iterated over with the while loop -- I'll explain this in person)
// * If the distance from i to j is more than r0*pad, do nothing
// * ... otherwise, add that pair of particles to ilist1 and ilist2, and their squared distance to r2list
// When we're done, ilist1 and ilist2 contain paired lists of all the interactions worth thinking about
// ... and r2list contains how far away those particles are, so you don't have to work it out again
// This returns the number of interactions that we found, so we know how far to take the for loops later
int build_interaction_list(vector pos[],item *zonelist[],ivec zone[],int ilist1[],int ilist2[], double r2list[])
{
// need to make some internally-used interaction list arrays for the threads
// starttimer(9);
int num_found=0; // keep track of how many interactions we've found already
{
ivec myzone; //ivec = vector of integers (only used here)
item *curr;
int i, j, k, l, m;
for (i=0; i<N; i++)
{
double r2;
myzone=getzone(pos[i]);
for (k=myzone.x-1; k<=myzone.x+1; k++)
for (l=myzone.y-1; l<=myzone.y+1; l++)
for (m=myzone.z-1; m<=myzone.z+1; m++)
{
// if we've driven off the edge of the simulation region, ignore and move to
// the next zone
if (k<0 || k>=NG || l<0 || l>=NG || m<0 || m>=NG)
continue;
curr=zonelist[k*NG*NG + l*NG + m]; // this awkwardness avoids the issues with passing multidimensional arrays
// while there are particles left in this zone...
while (curr)
{
j=curr->val;
// skip if pair misordered, same particle, or further apart than permitted
// this last condition may seem silly, but it allows us to consistently truncate
// the force so that the physics don't depend on the exact layout of the zone boundaries.
// (it also makes things faster.)
//r2=(pos[i]-pos[j])*(pos[i]-pos[j])/(r0*r0); // squared distance between, in units of r0
r2 = ((pos[i].x - pos[j].x) * (pos[i].x - pos[j].x) +
(pos[i].y - pos[j].y) * (pos[i].y - pos[j].y) +
(pos[i].z - pos[j].z) * (pos[i].z - pos[j].z))/(r0*r0);
if (i<=j || r2 > pad*pad) {curr=curr->next; continue;}
r2list[num_found] = r2; // it is very marginally faster to store a third array, containing the squared
// distances between particles, so we don't have to compute it again.
ilist1[num_found] = i;
ilist2[num_found] = j;
// printf("!Thread %d found interaction between %d and %d, stored in %d (%d this thread so far)\n",tid,i,j,num_found[tid]+iliststride*tid,num_found[tid]);
if (r2 < 0) printf("!ALARM: distance is %e\n",r2);
num_found++;
curr=curr->next;
}
}
}
}
return num_found;
}
void position_step(vector pos[], vector vel[], double dt)
{
for (int i=0; i<N; i++)
pos[i] += vel[i] * dt;
}
void velocity_step(vector *pos, vector *vel, double *m,
int *ilist1, int *ilist2, double *r2list, int nint, double dt)
{
double PE=0;
vector sep;
double r2;
for (int i=0; i<nint; i++) // traverse the interaction list in ilist1 and ilist2
{
vector F;
int j,k;
j=ilist1[i]; k=ilist2[i];
sep=pos[j]-pos[k];
// r2 = sep*sep/r0*r0;
// if (r2 > pad*pad) continue;
// F=(force((sep*sep)/(r0*r0))*dt)*sep; // parentheses not absolutely necessary but may save a few flops
F=(force((r2list[i]))*dt)*sep; // is it faster to look up the radius in the list, or compute it?
// maybe for bigger problems that don't fit into cache the above is better
vel[j] -= F/m[j];
vel[k] += F/m[k];
}
}
double kinetic(vector v[], double m[])
{
double T=0;
for (int i=0;i<N;i++)
T+=0.5*m[i]*v[i]*v[i]; // note that v*v does a dot product
return T;
}
double potential(vector pos[])
{
double U=0;
for (int i=0;i<N;i++)
for (int j=i+1;j<N;j++)
{
U+=V(norm(pos[i]-pos[j]));
}
return U;
}
// dummy space
int main(int argc, char **argv)
{
double time_intlist=0;
double time_velstep=0;
double time_posstep=0;
double time_check=0;
double time_checklist=0;
double time_anim=0;
double lastchecksteps=0;
double time_energy=0; // some variables for timing
double dt=1e-3, vinit;
double P=0, T=0, U, J=0;
int i=0,j=0,k=0,l=0;
int ninttotal=0;
int nint;
int drawn;
int *ilist1=NULL,*ilist2=NULL;
double *r2list=NULL;
double KE, PE,Tnow;
ilist1=(int *)malloc(sizeof(int) * ilist_size);
ilist2=(int *)malloc(sizeof(int) * ilist_size);
r2list=(double *)malloc(sizeof(double) * ilist_size);
double thermo_interval=5;
double next_thermo=thermo_interval;
double Taccum=0;
double rate;
if (argc < 5) // if they didn't give us command line parameters, die and print out the order
{
printf("!Usage: <this> <N> <dt> <vinit> <L>\n");
printf("!Try: gas3d 1000 1e-3 0.25 1\n");
exit(1);
}
// read command line parameters
N=atoi(argv[1]);
dt=atof(argv[2]);
vinit=atof(argv[3]);
L=atof(argv[4]);
int drawms=N*50.0/1000.0;
double smult=0;
NG=L/(r0*pad);
printf("!Read parameters. Drawing every %d ms\n",drawms);
ivec zone[N];
int lastframe=0;
vector pos[N],v[N];
double m[N];
item *zonelist[NG*NG*NG];
for (i=0;i<NG*NG*NG;i++)
{
zonelist[i]=NULL;
}
// set up initial conditions
double interval = r0 * pow(2,1./6.); // how far away to put the particles at the start
for (i=0;i<N;i++)
{
j++;
if (j>pow(N,1./3.)) {j=0;k++;}
if (k>pow(N,1./3.)) {k=0;l++;}
zone[i].x=-1; zone[i].y=-1; zone[i].z=-1; // set these to -1, we'll fix later
pos[i].x=k*interval-interval * pow(N,1./3.)/2;
pos[i].y=l*interval-interval * pow(N,1./3.)/2;
pos[i].z=j*interval-interval * pow(N,1./3.)/2;
v[i].x=drnd48()*vinit;
v[i].y=drnd48()*vinit;
v[i].z=drnd48()*vinit;
m[i]=1;
}
check_zonelist(zonelist,zone,pos); // put particles in the right zones to start
printf("!start main loop\n");
int steps=0;
for (double t=0; 1; t+=dt)
{
starttimer(9);
if (istime2(1000))
{
KE=kinetic(v,m);
PE=potential(pos);
}
time_energy+=stoptimer(9);
if (istime(drawms)) // anim time
{
starttimer(4);
// it's actually super expensive to compute the total energy since we do it
// pairwise to ensure absolute sanity, so do it only every 100 anim updates
printf("C 0.5 1 0.5\n");
// draw particles
for (i=0;i<N;i++)
{
// if (i==0) printf("C 1 1 1\n");
// if (i==1) printf("C 0.5 1 0.5\n");
// if (i<1) printf("ct3 %d %.3e %.3e %.3e %.3e\n",i,pos[i].x,pos[i].y,pos[i].z,r0/4);
printf("c3 %.4e %.4e %.4e %.4e\n",pos[i].x,pos[i].y,pos[i].z,r0/4);
}
printf("C 0.7 0.2 0.2\n");
draw_box(L/2);
printf("C 0.5 0.5 1\n");
printf("T -0.9 0.85\nt=%.3f/%.2f, E=%.5e = %.5e + %.5e\n",t,next_thermo,KE+PE,KE,PE); stoptimer(0);
printf("T -0.9 0.75\nPV = %.4e \t NkT = %.4e \t ratio = %f\n",P*L*L*L,N*T,P*L*L*L/(N*T));
printf("T -0.9 0.65\nsteps/frame: %d\n",steps-lastframe);
starttimer(0); lastframe=steps;
printf("F\n");
// fflush(stdout);
time_anim += stoptimer(4);
}
// start force calculations
// check zonelist
// build list of interactions. pass in pointers
// to interaction lists so it can realloc them
// if need be
position_step(pos,v,dt/2);
starttimer(1);
starttimer(2);
check_zonelist(zonelist,zone,pos);
time_checklist += stoptimer(2);
nint=build_interaction_list(pos,zonelist,zone,ilist1,ilist2,r2list);
time_intlist += stoptimer(1);
// printf("!%d interactions\n",nint);
starttimer(3);
velocity_step(pos,v,m,ilist1,ilist2,r2list,nint,dt);
position_step(pos,v,dt/2);
double eps = 0.1786178958448;
double lam = -0.2123418310626;
double chi = -0.06626458266982;
time_velstep += stoptimer(3);
steps++;
ninttotal+=nint;
// all this code is just here to determine how much time different parts of the calculation are taking
if (myclock() - 1.0 > time_check)
{
double curtime=myclock();
printf("!%.2f force (%.2f ns/int), %.2f anim, %.2f ilist, %.2f checklist, %.2f energy (us/step): %.1f ints/atom, %.1f SPS\n",
1e3*(float)time_velstep / (steps-lastchecksteps),
1e6*(float)time_velstep/ (ninttotal),
1e3*(float)time_anim / (steps-lastchecksteps),
1e3*(float)time_intlist / (steps-lastchecksteps),
1e3*(float)time_checklist / (steps-lastchecksteps),
1e3*(float)time_energy / (steps-lastchecksteps),
(float)ninttotal/N/(steps-lastchecksteps),
(float)(steps-lastchecksteps)/(curtime-time_check));
time_velstep=time_intlist=time_posstep=time_anim=time_energy=time_checklist=0;
lastchecksteps=steps;
time_check=myclock();
ninttotal=0;
}
// do wall collisions and accumulate impulse (pressure calculation not in yet)
for (i=0; i<N; i++)
{
if ( (pos[i].y > L/2 && v[i].y > 0) || ((pos[i].y < -L/2 && v[i].y < 0) ) )
{
v[i].y=-v[i].y;
J=J+2*fabs(v[i].y)*m[i];
}
if ( (pos[i].z > L/2 && v[i].z > 0) || ((pos[i].z < -L/2 && v[i].z < 0) ) )
{
v[i].z=-v[i].z;
J=J+2*fabs(v[i].z)*m[i];
}
if ( (pos[i].x > L/2 && v[i].x > 0) || ((pos[i].x < -L/2 && v[i].x < 0) ) )
{
v[i].x=-v[i].x;
J=J+2*fabs(v[i].x)*m[i];
}
}
Tnow=0;
for (i=0; i<N; i++)
{
Tnow += 0.5 * m[i] * v[i]*v[i] * dt;
}
Taccum+=Tnow;
Tnow/=N;
if (t > next_thermo)
{
P=J/(thermo_interval)/(6*L*L);
T=Taccum * 2.0 / 3.0 / N / thermo_interval;
J=Taccum=0;
next_thermo = t + thermo_interval;
}
}
}
| true |
2511a3f046159190ab229ab5787ba91aecd40ebe | C++ | tr1step2/cbr-history | /interface.cpp | UTF-8 | 1,524 | 2.734375 | 3 | [] | no_license | #include "stdafx.h"
#include "HistoryManager.hpp"
#define CBRHISTAPI __declspec(dllexport)
cbr::HistoryManager manager;
cbr::CurrencyDataContainerSPtr result;
void AllocAndCopy(std::string data, char ** out)
{
if (!out)
return;
*out = new char[data.length() + 1];
std::strcpy(*out, data.c_str());
}
void MakeError(const std::exception & exc, char ** error)
{
if (!error)
return;
AllocAndCopy(exc.what(), error);
}
extern "C"
{
CBRHISTAPI int load_data(const char * char_code, const char * start_date, const char * end_date, char ** error)
{
try
{
const char * name = "forex.xml";
result = manager.get_history(char_code, start_date, end_date, name);
}
catch (const std::exception & exc)
{
MakeError(exc, error);
return -1;
}
return 0;
}
CBRHISTAPI int get_next(char ** date, char ** value, char ** error)
{
if (!result)
{
*error = "Data not loaded";
return -1;
}
static cbr::CurrencyDataContainer::const_iterator iter = result->cbegin();
static cbr::CurrencyDataContainer::const_iterator end = result->cend();
try
{
if (iter == end)
{
return 0;
}
std::string dateStr = boost::lexical_cast<std::string>(iter->first);
std::string valueStr = boost::lexical_cast<std::string>(iter->second->value);
AllocAndCopy(dateStr, date);
AllocAndCopy(valueStr, value);
++iter;
}
catch (const std::exception & exc)
{
MakeError(exc, error);
return -1;
}
return 1;
}
} // extern C
| true |
b5f80bba835b52ca9a0877c21c14dcef0ec9c237 | C++ | KrzysztofJopek/SDL2-Tanks | /src/controls.cpp | UTF-8 | 1,599 | 2.65625 | 3 | [] | no_license | #include "controls.h"
#include "moveable.h"
Controls::Controls(App* app)
{
this->app = app;
}
void Controls::handleEvents()
{
while(SDL_PollEvent(&event)){
handleEvent(event);
}
}
void Controls::handleEvent(SDL_Event& e)
{
if(e.type == SDL_QUIT){
app->quit();
}
else if(e.type == SDL_KEYDOWN && event.key.repeat == 0){
switch(e.key.keysym.sym){
case SDLK_UP:
tank->velocity.stop();
tank->velocity.move(TOP);
break;
case SDLK_DOWN:
tank->velocity.stop();
tank->velocity.move(DOWN);
break;
case SDLK_LEFT:
tank->velocity.stop();
tank->velocity.move(LEFT);
break;
case SDLK_RIGHT:
tank->velocity.stop();
tank->velocity.move(RIGHT);
break;
case SDLK_SPACE:
tank->shoot();
break;
case SDLK_ESCAPE:
app->enterMenu();
break;
}
}
else if(e.type == SDL_KEYUP && event.key.repeat == 0){
switch(e.key.keysym.sym){
case SDLK_UP:
tank->velocity.stop(TOP);
break;
case SDLK_DOWN:
tank->velocity.stop(DOWN);
break;
case SDLK_LEFT:
tank->velocity.stop(LEFT);
break;
case SDLK_RIGHT:
tank->velocity.stop(RIGHT);
break;
}
}
}
| true |
96e2419a89cba42a0b4839302d0cd0facf83d54a | C++ | TashiTee/Seneca-Projects | /oop345(C++)/Labs/w7/athome/DataTable.h | UTF-8 | 7,153 | 3.296875 | 3 | [] | no_license | /*************************************************************************
// week 7 at home
// File: DataTable.h
// Version: 1.0
// Date: 04/01/2019
// Author: Tashi Tsering
// Description: holds and process statistical data
// A short explanation of what the filename is about goes here!
// Revision History
// -----------------------------------------------------------
// Name Date Reason
// Fardad 2019-01-15 created empty filename for workshop
*************************************************************************/
#ifndef SICT_DATA_TABLE_H
#define SICT_DATA_TABLE_H
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <iomanip>
#include <numeric>
#include <algorithm>
#include <cmath>
#include <string>
// External variables coming from w7.cpp
extern int FW;
extern int ND;
namespace sict {
/**
* A class that takes care of holding and processing statistical data
* std::vector<std::pair<T,T>> will be the structure defined using vector container
* to hold pair elemnts in each element of the vector
*/
template<class T>
class DataTable {
std::vector<std::pair<T, T>> m_data;
private:
/**
* Assistance methods
* Methods that assist in the calculation of queries
* Private method that calculates the sum of the X and Y coordinates and returns them both via a pair object
* by using the STL algorithm: accumulate(begin, end, initialValue, [](currentValue - starts with the initialValue, currentValueInVector))
* Explanation:
* begin/end - range of the vector to iterate through
* initialValue - 'static_cast<T>(0)' -> make the initial value 0
* currentValue with init - the value starts with 0 and increases based on the returned value of the lambda
* currentValueInVector - the current element
*/
std::pair<T, T> sum_x_y() const {
T t_x = { 0 };
T t_y = { 0 };
t_x += std::accumulate(m_data.begin(), m_data.end(), static_cast<T>(0), [](auto& a, auto& b) { return a + b.first; });
t_y += std::accumulate(m_data.begin(), m_data.end(), static_cast<T>(0), [](auto& a, auto& b) { return a + b.second; });
return std::make_pair(t_x, t_y);
}
/**
* Private method that returns all the x and y coordinates in a pair of enclosed vectors by using a range-based for loop
*/
std::pair<std::vector<T>, std::vector<T>> xy_collection() const {
std::vector<T> x;
std::vector<T> y;
for (auto& i : m_data) {
x.push_back(std::get<0>(i));
y.push_back(std::get<1>(i));
}
return std::make_pair(x, y);
}
// private method that calculates the mean of all the Y coordinates
T mean() const {
std::pair<T, T> t_xy = sum_x_y();
return std::get<1>(t_xy) / m_data.size();
}
/*
* Private method that calculates the sample standard deviation
* To calculate the sigma:
*/
T sigma() const {
T total = { 0 };
std::pair<std::vector<T>, std::vector<T>> v_xy = xy_collection();
std::vector<T> y = std::get<1>(v_xy);
std::for_each(y.begin(), y.end(), [&](T& n) {
total += std::pow(n - mean(), 2);
});
return std::sqrt(total / (y.size() - 1));
}
/**
* Private method that calculates the median
* The median is described as the value that separates the values right in the middle
* In order to find the median, we can sort the values and then take the middle
*/
T median() const {
std::pair<std::vector<T>, std::vector<T>> xy = xy_collection();
std::vector<T> y = std::get<1>(xy);
std::sort(y.begin(), y.end());
return y[y.size() / 2];
}
/**
* Private method that calculates the slope
* The slope is the ratio of the amount that y increases as x increases
* The slope tells you how much y increases as x increases
*/
T slope() const {
size_t n = m_data.size(); //n - number of elements
std::pair<T, T> sums_xy = sum_x_y();
std::pair<std::vector<T>, std::vector<T>> v_xy = xy_collection();
std::vector<T> x = std::get<0>(v_xy);
T sumOf_x = std::get<0>(sums_xy); //sumOf_x - sum of all the x coordinates
T sumOf_y = std::get<1>(sums_xy); //sumOf_y - sum of all the y coordinates
// prod_xy_sum - sum of the products of each x*y coordinates
T prod_xy_sum = { 0 };
std::for_each(m_data.begin(), m_data.end(), [&](auto& i) { prod_xy_sum += i.first * i.second; });
//sum_squared_x - sum of all x^2
T sum_squared_x = { 0 };
std::for_each(x.begin(), x.end(), [&](auto& i) { sum_squared_x += i * i; });
T numerator = (n * prod_xy_sum) - (sumOf_x * sumOf_y);
T denominator = ((n * sum_squared_x) - (sumOf_x * sumOf_x));
return numerator / denominator;
}
/**
* Private method that calculates the y-intercept of the given coordinates
* The following information is needed in order to calculate the intercept of slope
*/
T intercept() const {
size_t n = m_data.size(); // number of elements
std::pair<T, T> sums_xy = sum_x_y();
T sumOf_x = std::get<0>(sums_xy); // sum of all x coordinates
T sumOf_y = std::get<1>(sums_xy); // sum of all y coordinate
return (sumOf_y - (slope() * sumOf_x)) / n;
}
public:
// One-arg constructor that reads every record from the file, data is stored in a pair then stored in an index within vector
explicit DataTable(std::ifstream& file) {
bool keepReading = true;
if (file) {
T x = { 0 };
T y = { 0 };
do {
if (file >> x >> y)
m_data.push_back(std::make_pair(x, y));
else
keepReading = false;
} while (keepReading);
}
}
/**
* Query function that displays the x-y data within the vector in the following format:
* This can be done by utilizing the FW and ND provided from the main module
* The method iterates element by element through the vector displaying one pair at a time.
* To access first element from a pair: std::get<0>(pair_identifer)
*/
void displayData(std::ostream& os) {
os << "Data Values" << std::endl;
os << "------------" << std::endl;
os << std::setw(FW) << "x" << std::setw(FW) << "y" << std::endl;
for (const auto& i : m_data)
os << std::fixed << std::setprecision(ND) << std::setw(FW) << std::right << std::get<0>(i)
<< std::setprecision(ND) << std::setw(FW) << std::get<1>(i) << std::endl;
}
//Query that displays the statistics for the current object in the following format:
void displayStatistics(std::ostream& os) {
os << "\nStatistics" << std::endl;
os << "----------" << std::endl;
os << std::fixed << std::setprecision(ND) << " y mean = " << std::setw(FW) << mean() << std::endl; //y mean = 11.0000
os << std::fixed << std::setprecision(ND) << " y sigma = " << std::setw(FW) << sigma() << std::endl; //y sigma = 2.5820
os << std::fixed << std::setprecision(ND) << " y median = " << std::setw(FW) << median() << std::endl; //y median = 12.0000
os << std::fixed << std::setprecision(ND) << " slope = " << std::setw(FW) << slope() << std::endl; // slope = 1.9087
os << std::fixed << std::setprecision(ND) << " intercept = " << std::setw(FW) << intercept() << std::endl; // intercept = 5.1784
}
};
}
#endif // !SICT_DATA_TABLE_H | true |
6f760d4a42cd061c83ebdc301834aae1b32ef78f | C++ | kurmasz-assignments/cis263-hashPolynomial | /Polynomial.hpp | UTF-8 | 4,472 | 3.5 | 4 | [] | no_license | /*
* Polynomial.hpp
*
* Author: "Hans Dulimarta <dulimarh@cis.gvsu.edu>"
*/
#ifndef POLYNOM_H_
#define POLYNOM_H_
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <climits>
#include <math.h>
//
namespace cis263 {
using namespace std;
template<typename T>
class Polynomial {
public:
using Term = pair<T, int>;
private:
/* coefficient and exponent of the polynomial are stored as a pair<> */
vector<Term> poly;
public:
/* each term is a pair of coefficient and exponent, the type of
* coefficient is determined by <T>, but exponent is always an integer */
Polynomial() {
}
Polynomial(const string &input) {
load(input);
}
Polynomial(const Polynomial &other) {
poly = other.poly;
}
~Polynomial() {
poly.clear();
}
Polynomial &operator=(const Polynomial &other) {
poly = other.poly;
return *this;
}
/* TODO: complete this function to multiply "this" polynomial (of M
* terms) with the "other" polynomial (of N terms). Use the first
* technique described in question 5.13: (a) store the MN terms of the
* product (b) sort them (c) combine like terms
*/
Polynomial slowMultiply(const Polynomial &other) const {
Polynomial result;
// Place your code here.
return result;
}
/* TODO: complete this function to multiply "this" polynomial (of M
* terms) with the "other" polynomial (of N terms). Use the alternate
* technique described in question 5.13. Hint, use a map (or
* unordered_map) to merge like terms as they are computed.
*/
Polynomial operator*(const Polynomial &other) const {
Polynomial result;
// Place your code here.
return result;
}
/* TODO: Return the highest degree in the polynomial */
int maxDegree() const {
int answer = 0;
// Place your code here.
return answer;
}
Term term(int k) const {
return poly[k];
}
/* TODO evaluate the polynomial at the given value */
T operator()(T arg) const {
T answer = 0;
// Place your code here.
return answer;
}
bool operator==(const Polynomial& other) const {
return this->poly == other.poly;
}
bool operator!=(const Polynomial& other) const {
return this->poly != other.poly;
}
/* The following function "object" is needed for sorting
* the polynomial terms in descending order of the exponent */
struct exponent_comparator {
bool operator()(const pair<T, int> &a, const pair<T, int> &b) {
return a.second > b.second;
}
};
template<typename U>
friend ostream &operator<<(ostream &out, const Polynomial<U> &);
private:
/* The load function reads in a string representation of a polynomial
* and creates a vector of "polynomial terms".
* The input string has the following format:
*
* [coeff int] [coeff int] .....
*
* For instance, 3x^5 - 7x^2 + 11 can be represented as one of
* the following string (whitespaces do not matter)
*
* [3 5] [-7 2] [11 0]
* [3 5] [-7 2] [11 0]
*/
void load(const string &polystring) {
/* use a string input stream */
stringstream input(polystring);
const int L = polystring.length();
T coeff;
int expo = INT_MIN, last_expo;
bool sortNeeded = false;
/* skip the input, upto and including the '[' */
input.ignore(L, '[');
last_expo = expo;
/* our string input stream is like a file, so we can check for
* "end-of-file".... */
while (!input.eof()) {
input >> coeff >> expo;
input.ignore(L, ']');
if (fabs(coeff) > 1e-6) /* include only non-zero coeffs */
{
poly.push_back(make_pair(coeff, expo));
if (expo > last_expo)
sortNeeded = true;
last_expo = expo;
}
input.ignore(L, '[');
}
/* sort the terms in increasing order of exponents */
if (sortNeeded)
sort(poly.begin(), poly.end(), exponent_comparator());
}
};
template<typename T>
ostream &operator<<(ostream &out, const Polynomial<T> &poly) {
for (auto i = poly.poly.end() - 1; i != poly.poly.begin(); --i) {
out << i->first << "x^" << i->second << " + ";
}
return out;
}
}
#endif
| true |
f872ea6d000008f07c17daef1fb6eb80f202049e | C++ | checkmate-bitch/Random-Programs | /HackerRank/twin_arrays.cpp | UTF-8 | 1,177 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int get_min( int a[], int size )
{
int min = a[0], index = 0;
for(int i= 1; i< size; i++)
{
if( a[i] < min )
{
min = a[i];
index = i;
}
}
return index;
}
int get_next_min( int a[], int size, int min_index )
{
int index = 0, next_min = a[0];
for(int i= 1; i< size; i++)
{
if( a[i] < next_min && i != min_index )
{
index = i;
next_min = a[i];
}
}
return index;
}
int main()
{
int n;
cin >> n;
int *a = new int[n];
int *b = new int[n];
for(int i= 0; i< n; i++)
cin >> a[i];
for(int i= 0; i< n; i++)
cin >> b[i];
int min_index_a = get_min(a, n);
int min_index_b = get_min(b, n);
if( min_index_a != min_index_b )
cout << a[min_index_a] + b[min_index_b];
else
{
int next_min_a = get_next_min(a, n, min_index_a);
int next_min_b = get_next_min(b, n, min_index_b);
int min = a[next_min_a] + b[min_index_b] < a[min_index_a] + b[next_min_b]
? a[next_min_a] + b[min_index_b]
: a[min_index_a] + b[next_min_b];
cout << min;
}
return 0;
}
| true |
47e9a10cf9ede53c5b746bc33e218b4e41d9b39e | C++ | KhozmoS/Competitive-Programming-Solutions | /COJ/KhozmoS-p4077-Accepted-s1267284.cc | UTF-8 | 1,557 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;
ll a , b , c , d , e , f;
struct matriz{
ll m[5][5];
matriz()
{
memset(m , 0 , sizeof(m));
m[0][0] = a;
m[0][2] = b;
m[0][3] = 1;
m[1][1] = d;
m[1][2] = e;
m[1][4] = 1;
m[2][1] = 1;
m[3][3] = 1;
m[4][4] = 1;
}
matriz(int x)
{
memset(m , 0 , sizeof(m));
for(int i = 0; i < 5; i++)
m[i][i] = x;
}
matriz operator*(const matriz &X) const{
matriz res;
memset(res.m , 0 , sizeof(res.m));
for(int i = 0 ; i < 5; i++)
for(int j = 0 ; j < 5 ; j++)
for(int k = 0 ; k < 5; k++)
res.m[i][j] = (res.m[i][j] + (m[i][k] * X.m[k][j] % mod)) % mod;
return res;
}
};
matriz exp(matriz m , int b)
{
matriz res = matriz(1);
while(b)
{
if(b&1)
res = res * m;
m = m*m;
b >>= 1;
}
return res;
}
ll recurrence[5];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>a>>b>>c>>d>>e>>f;
recurrence[0] = 1;
recurrence[1] = 1;
recurrence[2] = 0;
recurrence[3] = c;
recurrence[4] = f;
int t;cin>>t;
while(t--){
int n;cin>>n;
matriz ans = exp(matriz() , n-1);
ll solve = 0;
for(int i = 0 ; i < 5 ; i++)
solve = (solve + (ans.m[0][i] * recurrence[i] % mod))%mod;
cout<<solve<<"\n";
}
}
| true |
fd8a220cbf4bc62d91451e045e49750a6e693509 | C++ | PazerOP/stuff | /cpp/include/mh/text/insertion_conversion.hpp | UTF-8 | 1,248 | 3.0625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <string_view>
#include <ostream>
namespace mh
{
namespace detail::insertion_conversion_hpp
{
template<typename T> static constexpr bool is_char_v =
std::is_same_v<T, char> || std::is_same_v<T, wchar_t> || std::is_same_v<T, signed char> || std::is_same_v<T, unsigned char>
#if __cpp_char8_t >= 201811
|| std::is_same_v<T, char8_t> || std::is_same_v<T, char16_t> || std::is_same_v<T, char32_t>
#endif
;
}
}
template<typename CharT, typename Traits, typename CharT2, typename Traits2, typename Alloc,
typename = std::enable_if_t<!std::is_same_v<CharT, CharT2> && mh::detail::insertion_conversion_hpp::is_char_v<CharT2>>>
inline std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::basic_string<CharT2, Traits2, Alloc>& str)
{
return os << str.c_str();
}
template<typename CharT, typename Traits, typename CharT2, typename Traits2,
typename = std::enable_if_t<!std::is_same_v<CharT, CharT2> && mh::detail::insertion_conversion_hpp::is_char_v<CharT2>>>
inline std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::basic_string_view<CharT2, Traits2>& str)
{
for (auto ch : str)
os.put(ch);
return os;
}
| true |
49deb86c4aca9ea615bbc46013ed1c72b80e44fa | C++ | fledge-iot/fledge | /C/common/include/resultset.h | UTF-8 | 4,691 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef _RESULTSET_H
#define _RESULTSET_H
/*
* Fledge storage client.
*
* Copyright (c) 2018 Dianomic Systems
*
* Released under the Apache 2.0 Licence
*
* Author: Mark Riddoch
*/
#include <string>
#include <string.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <rapidjson/document.h>
typedef enum column_type {
INT_COLUMN = 1,
NUMBER_COLUMN,
STRING_COLUMN,
BOOL_COLUMN,
JSON_COLUMN,
NULL_COLUMN
} ColumnType;
/**
* Result set
*/
class ResultSet {
public:
class ColumnValue {
public:
ColumnValue(const std::string& value)
{
m_value.str = (char *)malloc(value.length() + 1);
strncpy(m_value.str, value.c_str(), value.length() + 1);
m_type = STRING_COLUMN;
};
ColumnValue(const int value)
{
m_value.ival = value;
m_type = INT_COLUMN;
};
ColumnValue(const long value)
{
m_value.ival = value;
m_type = INT_COLUMN;
};
ColumnValue(const double value)
{
m_value.fval = value;
m_type = NUMBER_COLUMN;
};
ColumnValue(const rapidjson::Value& value)
{
m_doc = new rapidjson::Document();
rapidjson::Document::AllocatorType& a = m_doc->GetAllocator();
m_value.json = new rapidjson::Value(value, a);
m_type = JSON_COLUMN;
};
~ColumnValue()
{
if (m_type == STRING_COLUMN)
free(m_value.str);
else if (m_type == JSON_COLUMN)
{
delete m_doc;
delete m_value.json;
}
};
ColumnType getType() { return m_type; };
long getInteger() const;
double getNumber() const;
char *getString() const;
const rapidjson::Value *getJSON() const { return m_value.json; };
private:
ColumnValue(const ColumnValue&);
ColumnValue& operator=(ColumnValue const&);
ColumnType m_type;
union {
char *str;
long ival;
double fval;
rapidjson::Value *json;
} m_value;
rapidjson::Document *m_doc;
};
class Row {
public:
Row(ResultSet *resultSet) : m_resultSet(resultSet) {};
~Row()
{
for (auto it = m_values.cbegin();
it != m_values.cend(); it++)
delete *it;
}
void append(ColumnValue *value)
{
m_values.push_back(value);
};
ColumnType getType(unsigned int column);
ColumnType getType(const std::string& name);
ColumnValue *getColumn(unsigned int column) const;
ColumnValue *getColumn(const std::string& name) const;
ColumnValue *operator[] (unsigned long colNo) const {
return m_values[colNo];
};
private:
Row(const Row&);
Row& operator=(Row const&);
std::vector<ResultSet::ColumnValue *> m_values;
const ResultSet *m_resultSet;
};
typedef std::vector<Row *>::iterator RowIterator;
ResultSet(const std::string& json);
~ResultSet();
unsigned int rowCount() const { return m_rowCount; };
unsigned int columnCount() const { return m_columns.size(); };
const std::string& columnName(unsigned int column) const;
ColumnType columnType(unsigned int column) const;
ColumnType columnType(const std::string& name) const;
RowIterator firstRow();
RowIterator nextRow(RowIterator it);
bool isLastRow(RowIterator it) const;
bool hasNextRow(RowIterator it) const;
unsigned int findColumn(const std::string& name) const;
const Row * operator[] (unsigned long rowNo) {
return m_rows[rowNo];
};
private:
ResultSet(const ResultSet &);
ResultSet& operator=(ResultSet const&);
class Column {
public:
Column(const std::string& name, ColumnType type) : m_name(name), m_type(type) {};
const std::string& getName() { return m_name; };
ColumnType getType() { return m_type; };
private:
const std::string m_name;
ColumnType m_type;
};
unsigned int m_rowCount;
std::vector<ResultSet::Column *> m_columns;
std::vector<ResultSet::Row *> m_rows;
};
class ResultException : public std::exception {
public:
ResultException(const char *what)
{
m_what = strdup(what);
};
~ResultException()
{
if (m_what)
free(m_what);
};
virtual const char *what() const throw()
{
return m_what;
};
private:
char *m_what;
};
class ResultNoSuchColumnException : public std::exception {
public:
virtual const char *what() const throw()
{
return "Column does not exist";
}
};
class ResultNoMoreRowsException : public std::exception {
public:
virtual const char *what() const throw()
{
return "No more rows in the result set";
}
};
class ResultIncorrectTypeException : public std::exception {
public:
virtual const char *what() const throw()
{
return "No more rows in the result set";
}
};
#endif
| true |
26e456c3478505c12dd952263902ddf58687fd2c | C++ | jeromelebel/LightJugglingBall | /arduino/JugglingBall/EEPROMControler.cpp | UTF-8 | 3,338 | 3.234375 | 3 | [] | no_license | #include "EEPROMControler.h"
#include <Arduino.h>
#include <avr/eeprom.h>
#define BUFFER_SIZE 1024
#define BUFFER_OFFSET 1
EEPROMControler::EEPROMControler(void)
{
_buffer = NULL;
_usedBufferSize = 0;
}
void EEPROMControler::_readToEeprom(void)
{
unsigned short ii;
for (ii = 0; ii < BUFFER_SIZE; ii++) {
_buffer[ii] = eeprom_read_byte((unsigned char *) ii);
}
}
void EEPROMControler::_writeToEeprom(void)
{
unsigned short ii;
// first write 1 to show it's dirty
_buffer[0] = 1;
for (ii = 0; ii < _usedBufferSize; ii++) {
eeprom_write_byte((unsigned char *) ii, _buffer[ii]);
}
// then write 0 to show that we are finished
eeprom_write_byte(0, 0);
}
unsigned char EEPROMControler::init(void)
{
_buffer = (unsigned char *)malloc(BUFFER_SIZE);
this->_readToEeprom();
return _buffer[0];
}
void EEPROMControler::flush(void)
{
this->_writeToEeprom();
}
void EEPROMControler::writeUChar(unsigned short address, unsigned char value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeChar(unsigned short address, char value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeUShort(unsigned short address, unsigned short value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeShort(unsigned short address, short value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeULong(unsigned short address, unsigned long value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeLong(unsigned short address, long value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeFloat(unsigned short address, float value)
{
this->writeBuffer(address, sizeof(value), &value);
}
void EEPROMControler::writeBuffer(unsigned short address, unsigned short length, void *buffer)
{
memcpy(_buffer + address + BUFFER_OFFSET, buffer, length);
}
unsigned char EEPROMControler::readUChar(unsigned short address)
{
unsigned char value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
char EEPROMControler::readChar(unsigned short address)
{
char value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
unsigned short EEPROMControler::readUShort(unsigned short address)
{
unsigned short value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
short EEPROMControler::readShort(unsigned short address)
{
short value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
unsigned long EEPROMControler::readULong(unsigned short address)
{
unsigned long value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
long EEPROMControler::readLong(unsigned short address)
{
long value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
float EEPROMControler::readFloat(unsigned short address)
{
float value;
this->readBuffer(address, sizeof(value), &value);
return value;
}
void EEPROMControler::readBuffer(unsigned short address, unsigned short length, void *buffer)
{
memcpy(buffer, _buffer + address + BUFFER_OFFSET, length);
}
| true |
aac9e8a96a757214d32ba56ea035e715f9361d9d | C++ | UTEC-PE/binary-tree-201710424-utec | /bk.main.cpp | UTF-8 | 1,106 | 2.921875 | 3 | [] | no_license | //powered by apu.mp
#include <iostream>
#include "btree.h"
int main(int argc, char const *argv[]) {
Btree<int> arbolito;
int test_insert[10] = {35,45,24,35,10,209,34,25,30,90};
for (int i = 0; i < 10; i++) {
arbolito.insert(test_insert[i]);
}
cout <<"InOrderIterator: ";
for (auto i = arbolito.begin(); i != arbolito.end(); ++i) {
cout << *i << ' ';
}
cout<<'\n';
cout <<"weigth: " <<arbolito.weigth() <<'\n';
cout <<"printInOrder: ";
arbolito.printInOrder();
cout <<"printPreOrder: ";
arbolito.printPreOrder();
cout <<"printPostOrder: ";
arbolito.printPostOrder();
cout <<"\nRemove: 24,209 \n";
int test_remove[2] = {24,209};
for (int i = 0; i < 2; i++) {
arbolito.remove(test_remove[i]);
}
cout <<"InOrderIterator: ";
for (auto i = arbolito.begin(); i != arbolito.end(); ++i) {
cout << *i << ' ';
}
cout<<'\n';
cout <<"weigth: " <<arbolito.weigth() <<'\n';
cout <<"printInOrder: ";
arbolito.printInOrder();
cout <<"printPreOrder: ";
arbolito.printPreOrder();
cout <<"printPostOrder: ";
arbolito.printPostOrder();
return 0;
}
| true |
ec2f24a927b8539e6daafec1647957d4a73cc531 | C++ | geloumil/Interprocess-Communications-pipes-signals- | /commands.cpp | UTF-8 | 11,217 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <error.h>
#include <fcntl.h>
#include <cerrno>
#include <sys/stat.h>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <signal.h>
#include "commands.h"
using namespace std;
string buff;
int fd_executor,file_executor;
Executor ex;
int file_commander,fd_commander;
int write_executor( string buffer)
{
char fifo_read[]="fifo_read";
if(( file_executor = open ( fifo_read , O_WRONLY )) <0 )
{
perror("error opening fifo_write 1 " );
return 1;
}
if (( write ( file_executor , buffer.c_str() , SIZE ) ) == -1)
{
perror ( " Error in Writing ") ;
return 1 ;
}
close(file_executor);
return 0;
}
string read_executor( )
{
char msgbuf[SIZE];
memset(msgbuf,0,SIZE);
if ( read ( fd_executor ,msgbuf ,SIZE )< 0 )
{
perror (" problem in reading ") ;
return "";
}
string x(msgbuf);
return x;
}
void signal_read (int signo )
{
buff = read_executor();
}
void signal_open (int signo )
{
char fifo_write[]="fifo_write";
if ( ( fd_executor = open ( fifo_write , O_RDONLY )) < 0)
{
perror (" fifo_write open problem 2 " );
}
}
void close_pipe(int signo)
{
close(fd_executor);
}
void children_handler( int signo)
{
int status;
int pid;
string job_id;
while ((pid = waitpid((pid_t)(-1), &status, WNOHANG )) > 0)
ex.remove_running(&job_id,pid);
}
void run_waiting()
{
int count =1, i=0 , pid,status =0;
string part1,str;
char ** part;
while(1)
{ count=1;
i=0;
status=0;
if((ex.get_running()->size_List() < ex.get_concurrency()) && (ex.get_waiting()->size_List() > 0) )
{
ex.remove_waiting(&part1,-1);
if(part1.empty())
return;
istringstream str_stream(part1);
while(part1[i] != '\0' )
{
if(part1[i] == '#')
count++;
i++;
}
part = new char * [count ];
for(i= 0 ; i < count ; i ++ )
part[i]= new char[15];
i=0;
while(getline(str_stream,str,'#'))
{
strcpy(part[i],str.c_str());
i++;
}
part[count - 1 ]=NULL;
for( i =0 ; i < count -1 ; i ++)
cout <<" thesi " << i << "me timi " << part[i]<<endl;
pid=fork();
if(pid < 0 )
{
cout<<"unable to fork "<<endl;
}
else if (pid == 0 )
{ sleep(2);
char ** part2;
part2 = new char * [count-1 ];
for(i= 0 ; i < count ; i ++ )
part2[i]= new char[15];
for( i=0 ; i< count -2 ; i ++)
{
part2[i]=part[i+1];
}
part2[count -2] =NULL;
sleep(2);
execvp(part[1] ,part2);
perror("exec");
_exit(status);
}
else
{
ex.push_running( pid , part1 );
for( i = 0; i < count;i++)
delete[] part[i];
delete [] part;
}
}
else
{
break;
}
}
return;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void create_server(int * pid)
{
char fifo_write[] = "fifo_write";
char fifo_read[]="fifo_read";
*pid=fork();
if(*pid < 0 )
{
return;
}
else if (*pid == 0 )
{
char str[] = "./executor";
char *buff[2];
buff[1]=NULL;
buff[0]=str;
execvp(str ,buff);
perror("exec");
}
else
{
if(mkfifo(fifo_write , 0666) == -1)
{
if(errno != EEXIST)
{
perror("error while creating fifo_write");
return ;
}
}
if(mkfifo(fifo_read , 0666) == -1)
{
if(errno != EEXIST)
{
perror("error while creating fifo_write");
return ;
}
}
sleep(2);
}
}
string read_commander( )
{
char fifo_read[]="fifo_read";
char msgbuf[SIZE];
memset(msgbuf,0,SIZE);
if ( ( fd_commander = open ( fifo_read , O_RDONLY )) < 0)
{
perror (" fifo_write open problem 2 " );
}
if ( read ( fd_commander ,msgbuf ,SIZE )< 0 )
{
perror (" problem in reading ") ;
return "";
}
string x(msgbuf);
close(fd_commander);
return x;
}
int write_commander( char ** data , int num , int id)
{
char fifo_write[] = "fifo_write";
int c ;
string buffer;
buffer.clear();
for(int i = 1 ; i < num ; i ++ )
{
buffer=buffer+data[i];
buffer=buffer+"#";
}
buffer=buffer+ "\0";
c =kill(id ,SIGRTMIN +1);
if(c ==-1)
cerr<<errno << "(1)" << id <<endl;
if(( file_commander = open ( fifo_write , O_WRONLY )) <0 )
{
perror("error opening fifo_write 1 " );
return 1;
}
c =kill(id ,SIGRTMIN);
if(c ==-1)
cerr<<errno<<"(2)" <<endl;
if (( write ( file_commander , buffer.c_str() ,SIZE ) ) == -1)
{
perror ( " Error in Writing ") ;
return 1 ;
}
c =kill(id , SIGRTMIN +2);
if(c ==-1)
cerr<<errno<<"(3)" <<endl;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Executor:: Executor()
{
concurrency=1;
}
int Executor:: get_concurrency()
{
return concurrency;
}
void Executor:: set_concurrency(int data)
{
concurrency=data;
}
Executor :: List * Executor :: get_waiting()
{
return &waiting;
}
Executor :: List * Executor :: get_running()
{
return &running;
}
void Executor:: push_waiting(int data , string arg )
{
waiting.push_List(data , arg );
}
void Executor:: push_running(int data , string arg )
{
running.push_List(data , arg );
}
string Executor :: print_waiting()
{
return waiting.print_List();
}
string Executor :: print_running()
{
return running.print_List();
}
int Executor :: remove_waiting(string * job_id,int data)
{
return waiting.remove_from_List( job_id,data );
}
int Executor :: remove_running( string * job_id ,int data )
{
return running.remove_from_List( job_id,data );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Executor :: List :: List () //creating list
{
first=NULL;
last=NULL;
size=0;
}
Executor :: List :: ~List() //deleting list
{
Node* t ;
while(size > 0)
{
t=first;
first=first->next;
delete(t);
size--;
}
}
Executor :: List :: Node * Executor :: List :: return_first ()
{
return first;
}
Executor :: List :: Node * Executor :: List :: return_last ()
{
return last;
}
int Executor :: List :: size_List ()
{
return size;
}
void Executor :: List :: push_List (int data , string arguments )
{
if( size == 0) // pushing in an empty list ( first element)
{
first = new Node;
first->next=NULL;
first->pid=data;
first->job=arguments;
last=first;
size++;
}
else
{
Node *t;
t=first; //mpenoun sto first
first= new Node; // ara |first|-> |next| -> ...... -> |last| ( to proto pou mpike )
first->next=t;
first->pid=data;
first->job = arguments;
size++;
}
return;
}
// auto xrisimeuei an theleis na bgeis apo tin oura anamonis
int Executor :: List :: remove_from_List (string * job_id,int pid ) // default timi gia to pid einai -1. Etsi tha to balo na diagrafei ton last
{
// ( ton proto pou mpike ) , allios tha kanei anazitisi tou pid kai tha diagrafei
int i,megethos; // auto
Node* t = first , *temp ;
job_id->clear();
if((size == 0 ) )
return -1; //if list empty or wrong pointer ,error
if(pid == -1 )
{
if((size > 1) ) //if list has more than one nodes
{
while(1)
{
if(t->next==last)
break;
t=t->next;
}
* job_id = last->job;
delete last;
last=t;
}
else // if deleting the only node
{
* job_id = last->job;
delete last;
first=NULL;
last=NULL;
}
size--;
}
else
{//deleting node with specified id
bool found = false;
int count= 1;
while(1)
{
if(count > size )
{
found = false;
break;
}
if(t->pid == pid )
{
found = true;
break;
}
temp=t;
t=t->next;
count++;
}
if(!found)
{
return -1;
}
else
{
if(size =1 )
{
* job_id = first->job;
delete first;
first=NULL;
last=NULL;
size --;
}
else
{
if(t == last)
{
*job_id=last->job;
delete last;
last=temp;
}
else if(t== first)
{
temp=first->next;
* job_id = first->job;
delete first;
first=temp;
}
else
{
Node *n = t->next;
*job_id=t->job;
delete t;
temp->next=n ;
}
size --;
}
}
}
return 0;
}
string Executor :: List :: print_List()
{
Node * t = first;
string str="";
char temp[10];
if(size_List() == 0 )
str= str + "no jobs available\n";
for(int i =0 ;i < ( size_List() ) ; i++)
{
sprintf( temp , "%d ",t->pid);
str = str +t->job + ( (string) temp ) + "\n";
t=t->next;
}
str=str+"\0";
return str;
}
int Executor :: List :: get_pid(Node * node)
{
return node->pid;
}
string Executor :: List :: get_job(Node * node)
{
return node->job;
}
| true |
b666a87ee8095f2217b09bbaba00e9fd57e31ac8 | C++ | andrecaetanov/grafos-grupo-1 | /Componentes/Grafo/Aresta.cpp | UTF-8 | 866 | 2.515625 | 3 | [] | no_license | //
// Created by andre on 10/09/2018.
//
#include "Aresta.h"
Aresta::Aresta() = default;
Aresta::Aresta(Vertice *vertice1, Vertice *vertice2) {
vertice1->arestas.push_back(this);
vertice2->arestas.push_back(this);
vertice1->verticesAdjacentes.push_back(vertice2);
vertice1->grau++;
vertice2->verticesAdjacentes.push_back(vertice1);
vertice2->grau++;
this->vertice1 = vertice1;
this->vertice2 = vertice2;
}
Aresta::Aresta(Vertice *vertice1, Vertice *vertice2, int peso) {
vertice1->arestas.push_back(this);
vertice2->arestas.push_back(this);
vertice1->verticesAdjacentes.push_back(vertice2);
vertice1->grau++;
vertice2->verticesAdjacentes.push_back(vertice1);
vertice2->grau++;
this->vertice1 = vertice1;
this->vertice2 = vertice2;
this->peso = peso;
}
| true |
6d5c13d7fa435f932a490635e898ccd42c8123fe | C++ | ArcFlux/Numerical-Method | /Integration/Trapezoid Method [Function].cpp | UTF-8 | 695 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
double func(double x){
return 1 / (1 + pow (x, 2));
}
int main(){
int n, i;
float sum, h, x1, x2, y, x;
cout<<"Amount of segment: ", cin>>n;
cout<<"xmin: ", cin>>x1;
cout<<"xmax: ", cin>>x2;
h = (x2-x1)/n;
x = x1;
y = func(x);
cout<<"x: "<<x<<endl<<"y: "<<y<<endl<<endl;
sum = y/2;
for(i=1; i<n; i++){
x = x1 + h*i;
y = func(x);
cout<<"x: "<<x<<endl<<"y: "<<y<<endl<<endl;
sum = sum + y;
}
x = x2;
y = func(x);
cout<<"x: "<<x<<endl<<"y: "<<y<<endl<<endl;
sum = sum + y/2;
sum = sum * h;
cout<<"SUM = ", printf("%.5lf",sum);
return 0;
}
| true |
9a2d04760ffac4f25455d13b364324f57aeb5831 | C++ | juan436/MVC-CPLUSPLUS | /Programa9/C.cpp | UTF-8 | 410 | 2.703125 | 3 | [] | no_license | #include "ML.cpp"
#include "VL.cpp"
using namespace std;
class C{
private:
ML m;
VL v;
public:
C();
void ProcesarLlamada();
};
C::C(){
}
void C::ProcesarLlamada(){
int tipo, duracion; float total;
tipo = v.LeerTipo();
duracion = v.LeerDuracion();
m.setTipo(tipo);
m.setDuracion(duracion);
tipo = m.getTipo();
duracion = m.getDuracion();
total = m.CalcularTotal();
v.ImprimirTotal(total);
}
| true |
9c1ddbe959729be488dc595e95fcc8445a4e88fe | C++ | mistermagson/archsoft-training-code | /module-1/extras/JNI/TextCase/TextCase/TextCase/TextCase.cpp | UTF-8 | 1,363 | 3.0625 | 3 | [] | no_license | #include "pch.h"
#include <jni.h>
#include "com_archsoft_TextCase.h"
using namespace std;
JNIEXPORT jstring JNICALL Java_com_archsoft_TextCase_upcase(JNIEnv* env, jobject obj, jstring text)
{
// Step 1: Convert the JNI String (jstring) into C-String (char*)
const char* str = env->GetStringUTFChars(text, nullptr);
if (nullptr == str) return nullptr;
// Step 2: release resources
env->ReleaseStringUTFChars(text, str);
// Step 3: Create a C-Style string with upper case
size_t size = strlen(str) + 1;
char* out = new char[size];
for (unsigned int i = 0; i < size; i++) {
out[i] = toupper(str[i]);
}
// Step 4: Convert the C-string (char*) into JNI String (jstring) and return
return env->NewStringUTF(out);
}
JNIEXPORT jstring JNICALL Java_com_archsoft_TextCase_lowcase(JNIEnv* env, jobject obj, jstring text)
{
// Step 1: Convert the JNI String (jstring) into C-String (char*)
const char* str = env->GetStringUTFChars(text, nullptr);
if (NULL == str) return nullptr;
// Step 2: release resources
env->ReleaseStringUTFChars(text, str);
// Step 3: Create a C-Style string with upper case
size_t size = strlen(str) + 1;
char* out = new char[size];
for (unsigned int i = 0; i < size; i++) {
out[i] = tolower(str[i]);
}
// Step 4: Convert the C-string (char*) into JNI String (jstring) and return
return env->NewStringUTF(out);
}
| true |
3801fb1fb74d5bc4ca810cf2f024504224d6497d | C++ | jffifa/algo-solution | /ural/1330.cpp | UTF-8 | 338 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int N, M;
int sum[16384];
int main()
{
int i, l, r;
scanf("%d", &N);
for (i = 1; i <= N; ++i)
{
scanf("%d", sum+i);
sum[i] += sum[i-1];
}
scanf("%d", &M);
while (M--)
{
scanf("%d%d", &l, &r);
printf("%d\n", sum[r]-sum[l-1]);
}
return 0;
}
| true |
eb6383a3310f9b006007e5e9842885698a677e2e | C++ | Takahashi0213/rengame | /Game/GameObject/Switch.h | SHIFT_JIS | 2,810 | 2.890625 | 3 | [] | no_license | #pragma once
#include "system/CGameObjectManager.h"
#include "graphics/skinModel/SkinModelRender.h"
#include "physics/PhysicsGhostObject.h"
#include "GameObject/Player.h"
/// <summary>
/// XCb`̐Ԃ
/// XCb`yɃAbvf[gE_[ĂłĂ
/// </summary>
class SwitchObj
{
public:
SwitchObj();
~SwitchObj();
void SwitchObj_Init(const CVector3& Pos);
void SwitchUpdate();
void SwitchDraw();
/// <summary>
/// _[[hύX
/// </summary>
void SwitchRenderModeChange(const RenderMode renderMode) {
m_model.SetRenderMode(renderMode);
}
/// <summary>
/// XCb`̃IItԂԂ
/// </summary>
bool GetSwitchState() {
return m_switchState;
}
void SetScale(const CVector3& scale) {
m_scale = scale;
}
private:
void GhostCheck();
//XCb`
enum SwitchState {
On,
Off,
};
SkinModel m_model; //XCb`̃f
Player* m_pl = nullptr; //vC[
PhysicsStaticObject m_physicsStaticObject; //ÓIIuWFNg
PhysicsGhostObject m_ghostObject; //S[XgIuWFNg
CVector3 m_position = CVector3().Zero();
CQuaternion m_rotation = CQuaternion().Identity();
CVector3 m_scale = { 5.0f,5.0f,5.0f }; //g嗦
SwitchState m_switchState = Off; //IIt
//萔
const CVector3 Local = { 0.0f,5.0f,0.0f }; //x[XɂԂ̃[JW
const CVector3 GhostScale = { 140.0f,0.5f,140.0f }; //pS[Xg͈̔
const float GhostY_Up = 15.0f; //pS[XgɎグĂړ
const float SwitchMove = 14.0f; //ꂽƂ߂̈ړ
const int SwitchMoveTime = 12; //ꂽƂ߂̈ړ
};
/// <summary>
/// XCb`̃x[X
/// ɂȂ̂͂ł
/// </summary>
class Switch : public ObjectClass
{
public:
Switch();
~Switch();
void Update()override;
void Render()override;
//ݒ
void SetPosition(const CVector3& pos) {
m_position = pos;
m_switchObj.SwitchObj_Init(m_position);
}
/// <summary>
/// WԂ
/// </summary>
CVector3 GetPosition() {
return m_position;
}
/// <summary>
/// XCb`̃IItԂԂ
/// O猩ƎdltȂ̂Ŗ߂Ă
/// </summary>
bool GetSwitchState() {
if (m_switchObj.GetSwitchState() == false) {
return true;
}
if (m_switchObj.GetSwitchState() == true) {
return false;
}
return false;
}
private:
SkinModel m_model; //XCb`̓y䃂f
SwitchObj m_switchObj; //Ԃ
PhysicsStaticObject m_physicsStaticObject; //ÓIIuWFNg
};
| true |
75caa11a8d6d85f975bf0502a884e7425befb6b3 | C++ | mtcl/ArduinoRobotCar | /robot_car_sketch.ino | UTF-8 | 2,455 | 2.9375 | 3 | [] | no_license |
#define leftMotorPin1 9 //Pin number for left Motor
#define leftMotorPin2 8 //Pin number for left Motor
#define rightMotorPin1 13 // Pin number for right Motor
#define rightMotorPin2 12 // Pin number for right Motor
#define trigPin 2
#define echoPin 4
#define minObjDistInch 6 //set minimum object distance before collision happens
#define scanInterval 100 //scan interval for ultrasonic sensor in 1/1000 of a seconds
long duration, cm, inches;
void setup() {
pinMode(leftMotorPin1, OUTPUT);
pinMode(leftMotorPin2, OUTPUT);
pinMode(rightMotorPin1, OUTPUT);
pinMode(rightMotorPin2, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//built in 3 seconds delay to power on the Car.
delay(3000);
}
void loop()
{
//sets both motors to full speed in the same direction
goForward();
//every scanInterval mili seconds, check for distance in inches
inches = distanceIn();
delay(scanInterval);
//Check for obstacles
if (inches < minObjDistInch) {
//stops both motors
comeToStop();
delay(1000);
//sets both motors to full speed in opposite direction
goBackward();
delay(1000);
//sets only the left motor to rotate so the robot turns
turnRight();
delay(1500);
}//end if statement
}//ends loop
void goForward(){
digitalWrite(leftMotorPin1,HIGH);
digitalWrite(leftMotorPin2,LOW);
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
}
void goBackward(){
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, HIGH);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, HIGH);
}
void turnLeft(){
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
}
void turnRight(){
digitalWrite(leftMotorPin1, HIGH);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, LOW);
}
void comeToStop(){
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, LOW);
}
int distanceIn(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(4);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// converts the time to a distance
inches = (duration / 2) / 74;
return inches;
}
| true |
a120419db151a1e811c122f136cc101372eb773e | C++ | baru64/mpeg2parser | /src/main.cpp | UTF-8 | 2,486 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <cstdlib>
#include "packet.hpp"
#include "pesparser.hpp"
using namespace std;
int arrFindInt(int* arr, int x, int len)
{
for(int i = 0; i < len; i++)
if (arr[i] == x) return i;
return -1;
}
bool arrAppendInt(int* arr, int x, int len) {
for(int i = 0; i < len; i++)
if (arr[i] == 0) {
arr[i] = x;
return false; // no error
}
return true; // error
}
#define MAX_PIDS 8
#define PACKET_SIZE 188
#define BUFFER_LEN 4096
int main(int argc, char* argv[]) {
fstream input_fs;
fstream output_fs;
int pids[MAX_PIDS] = {0};
char packet_buff[PACKET_SIZE];
char input_file[128] = "example.ts";
char output_file[128] = "audio.mp2";
uint16_t pid_to_extract = 0xcb;
if (argc < 4) {
cout << "Usage: mpeg2parser OUTPUT_FILE INPUT_FILE PID_TO_EXTRACT" << endl;
return EXIT_FAILURE;
} else {
strcpy(output_file, argv[1]);
strcpy(input_file, argv[2]);
pid_to_extract = (uint16_t) atoi(argv[3]);
}
cout << "Input: " << input_file
<< " Output: " << output_file
<< " PID: " << pid_to_extract << endl;
input_fs.open(input_file, fstream::in | fstream::binary);
if (!input_fs.good()) {
cout << "Error opening " << input_file << "!" << endl;
return 1;
}
output_fs.open(output_file, fstream::out | fstream::binary);
if (!output_fs.good()) {
cout << "Error opening " << output_file << "!" << endl;
return 1;
}
PES_Parser* parser = new PES_Parser(&output_fs, false);
while(input_fs.read(packet_buff, PACKET_SIZE)) {
if (input_fs.gcount() < 188) {
cout << "Read less than 188 bytes, exiting." << endl;
break;
}
TS_Packet *packet = new TS_Packet(packet_buff);
if (packet->pid == pid_to_extract) {
parser->next_packet(packet);
}
if (arrFindInt(pids, packet->pid, MAX_PIDS) == -1) {
arrAppendInt(pids, packet->pid, MAX_PIDS);
}
if (!output_fs.good()) {
cout << "Output stream error!\n";
break;
}
}
input_fs.close();
parser->close_fs(output_file);
cout << "\n all pids: ";
for(int i = 0; i < MAX_PIDS; i++)
if(pids[i] != 0) cout << pids[i] << " ";
cout << endl;
return EXIT_SUCCESS;
}
| true |
7969066c8b12c4b78a457b4686f329ec460b294e | C++ | yamadashi/ArrowCrash | /ArrowCrash/Scripts/Explain/Explain.cpp | SHIFT_JIS | 1,958 | 2.65625 | 3 | [] | no_license | #include "Explain.h"
Explain::Explain()
:counter(0),
numOfExplain(6)
{}
Explain::~Explain() {
ymds::GamepadManager::get().inactivate();
}
void Explain::init() {
ymds::GamepadManager::get().activate();
//pointer
for (int i = 0; i < 4; i++) {
//|C^̏ʒu
Point pos(Window::Center().movedBy(0, Window::Height() / 6));
const Point tmp(2 * (i % 2) - 1, 2 * (i / 2) - 1); //i == 0 ̂Ƃ (-1, 0), i== ̂Ƃ (0, 1)
pos.moveBy(0.2 * Window::Width() * tmp.x, 0.2 * tmp.y * Window::Height());
pointers.emplace_back(new Pointer(i, pos));
}
const int buttonMargin = Window::Height() / 54;
const int buttonSize = Window::Height() / 5;
targets.emplace_back(new ymds::ClickablePanel(L"back", { buttonMargin, buttonMargin }, Size(buttonSize, buttonSize),
[this](ymds::ClickablePanel&) {
SoundAsset(L"select").playMulti();
if (counter > 0) counter--;
else changeScene(SceneName::Title); }
));
targets.emplace_back(new ymds::ClickablePanel(L"forward", { Window::Width() - buttonSize - buttonMargin, buttonMargin }, Size(buttonSize, buttonSize),
[this](ymds::ClickablePanel&) {
SoundAsset(L"select").playMulti();
if (counter < numOfExplain - 1) counter++;
else changeScene(SceneName::Title); }
));
for (auto& target : targets) {
clickDetector.addTarget(target);
}
for (auto& pointer : pointers) {
clickDetector.addPointer(pointer);
}
}
void Explain::update() {
ymds::GamepadManager::get().update();
clickDetector.update();
for (auto& pointer : pointers) pointer->update();
}
void Explain::draw() const {
TextureAsset(L"background").resize(Window::Size()).draw();
static const Rect clientRect(Window::ClientRect());
clientRect.draw(Alpha(200));
TextureAsset(L"explain" + ToString(counter)).resize(Window::Size()).draw();
PutText(L"explain" + ToString(counter)).from(0 ,0);
for (const auto& target : targets) target->draw();
for (const auto& pointer : pointers) pointer->draw();
} | true |
f8372e7191575ad65b19cf9cd7b58ceb0f173d75 | C++ | macwoj/CtCI-6th-Edition-cpp | /code/Q3_03_Stack_of_Plates.cpp | UTF-8 | 2,067 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <deque>
using namespace std;
template <typename T>
class SetOfStacks {
int capacity_;
vector<deque<T>> stacks_;
void addBack() {
stacks_.push_back({});
}
void leftShift(int index) {
if (index+1 < stacks_.size()) {
stacks_[index].push_back(stacks_[index+1].front());
stacks_[index+1].pop_front();
leftShift(index+1);
}
}
public:
SetOfStacks(int capacity): capacity_(capacity) {
addBack();
}
void push(T val) {
if (stacks_.back().size() == capacity_) {
addBack();
}
stacks_.back().push_back(val);
}
T pop() {
T res = {};
if (!stacks_.empty()) {
auto& back = stacks_.back();
if (!back.empty()) {
res = back.back();
back.pop_back();
}
if (back.empty())
stacks_.pop_back();
}
return res;
}
T popAt(int index) {
if (index < stacks_.size()) {
auto res = stacks_[index].back();
stacks_[index].pop_back();
leftShift(index);
if (stacks_.back().empty())
stacks_.pop_back();
return res;
}
return {};
}
};
int main() {
{
SetOfStacks<int> stack(2);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl << endl;
}
{
SetOfStacks<int> stack(2);
stack.push(1); //1,2 3,4 5
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
cout << stack.popAt(1) << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
}
} | true |
ddb9e57cb967e1b99521d7763599dd986c28ed60 | C++ | kanghuiseon/algorithms | /baekjoon/실버/1449_수리공항승.cpp | UTF-8 | 617 | 2.53125 | 3 | [] | no_license | #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#define MAX 1001
using namespace std;
int pipe[MAX];
bool repair[MAX];
int main(){
int n, l;
scanf("%d %d", &n, &l);
for(int i=0; i<n; i++){
scanf("%d", &pipe[i]);
}
int cnt=0;
sort(pipe, pipe+n);
for(int i=0; i<n; i++){
// 안고쳐졌다면
if(!repair[pipe[i]]){
for(int j=pipe[i]; j<= min(pipe[i]+l-1,MAX); j++){
repair[j] = true;
}
cnt++;
}
}
printf("%d\n", cnt);
return 0;
}
| true |
31fa7c00de14ae18d380b618fff62674e3df09ab | C++ | NicolasBeaudrot/babelconstructor | /Game/Utility/ScoreManager.cpp | UTF-8 | 3,140 | 2.9375 | 3 | [] | no_license | #include "ScoreManager.h"
#include <tinyxml.h>
ScoreManager::ScoreManager() {
}
ScoreManager::~ScoreManager() {
}
void ScoreManager::parse(std::string path) {
bool loaded = false;
TiXmlDocument doc(path.c_str());
if (doc.LoadFile()) {
TiXmlElement *score = doc.FirstChildElement("game");
if (score) {
score = score->FirstChildElement("scores");
if (score) {
score = score->FirstChildElement();
while (score) {
float value;
score->QueryFloatAttribute("value", &value);
_arrScore.insert(std::pair<std::string, float>(score->GetText(), value));
score = score->NextSiblingElement();
}
loaded = true;
}
}
}
Logger::Instance()->log("Score file parsed");
if (!loaded) {
Logger::Instance()->log("Unable to load the score file");
}
}
void ScoreManager::update(std::string map, float score) {
std::map<std::string, float>::iterator it;
it = _arrScore.find(map);
if(it == _arrScore.end()) {
_arrScore.insert(std::pair<std::string, float>(map, score));
} else {
if (it->second > score) {
it->second = score;
}
}
}
void ScoreManager::save(std::string path) {
TiXmlDocument doc(path.c_str());
bool saved = false;
if (doc.LoadFile()) {
TiXmlElement *elements = doc.FirstChildElement("game");
if (elements) {
elements = elements->FirstChildElement("scores");
if (elements) {
std::map<std::string, float>::iterator it;
it = _arrScore.begin();
while (it != _arrScore.end()) {
TiXmlElement *elem = elements->FirstChildElement();
bool create = true;
while (elem) {
if (elem->GetText() == it->first) {
elem->SetDoubleAttribute("value", it->second);
create = false;
break;
}
elem = elem->NextSiblingElement();
}
if (create) {
TiXmlElement *score = new TiXmlElement( "score" );
elements->LinkEndChild(score);
TiXmlText * text = new TiXmlText( it->first.c_str() );
score->LinkEndChild( text );
score->SetDoubleAttribute("value", it->second);
}
it++;
}
saved = true;
}
}
}
if ( saved ) {
doc.SaveFile(path.c_str());
Logger::Instance()->log("Scores saved");
} else {
Logger::Instance()->log("Unable to save scores");
}
}
float ScoreManager::getHightScore(std::string map) {
std::map<std::string, float>::iterator it;
it = _arrScore.find(map);
if(it == _arrScore.end()) {
return 0;
} else {
return it->second;
}
}
| true |
44ee62b21a452d9644c3d634b89e9342933bddab | C++ | sysvinit/littlesat | /main.cc | UTF-8 | 1,186 | 2.640625 | 3 | [
"ISC"
] | permissive | /* see LICENSE.txt file for license details */
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <optional>
#include "solver.hh"
#include "parser.hh"
int main(int argc, char *argv[]) {
std::ifstream inp;
littlesat::formula cnf;
std::optional<littlesat::solution> soln;
bool stdin;
stdin = false;
if (argc == 1) {
stdin = true;
} if (argc == 2) {
inp = std::ifstream(argv[1]);
if (!inp) {
std::cerr << "Could not open " << argv[1] << " for reading"
<< std::endl;
std::exit(EXIT_FAILURE);
}
} else if (argc > 2) {
std::cerr << "Too many arguments" << std::endl;
std::exit(EXIT_FAILURE);
}
if (stdin) {
littlesat::parse(std::cin, cnf);
} else {
littlesat::parse(inp, cnf);
}
soln = littlesat::dpll(cnf);
if (soln) {
std::cout << "SATISFIABLE" << std::endl;
for (auto s: soln.value()) {
std::cout << s.first << ": " << (s.second ? "true" : "false") <<
std::endl;
}
} else {
std::cout << "UNSATISFIABLE" << std::endl;
}
return 0;
}
| true |
edb132e2839679ff1958a945bf82174beea326b6 | C++ | daheeKang/cp2016890002 | /선택정렬 연습/연습.cpp | UHC | 865 | 3.84375 | 4 | [] | no_license | #include <stdio.h>
void printArray (int* arr, int len){
for(int index=0; index<len; index++){
printf("array[%d] = %d \n", index, arr[index]);
}
}
void swapElement(int* arr, int i, int j ){
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
int findMin(int* arr, int length){
int min=arr[0];
for (int count=1; count<length; count++){
if (min > arr[count])
min = arr[count];
}
return min;
}
void selectSort(int* arr, int length){ //find min ϳ ־. start Ʈ ٸǷ.
int i, j;
for( i=0; i<length-1; i++){
int min=arr[i];
int minIndex=i;
for (j=i+1; j<length; j++){
if (arr[j]<min) {
min = arr[j];
minIndex=j;
}
}
if(i!=minIndex)swapElement(arr, minIndex, i);
}
printArray(arr,5);
}
int main() {
int a[] = {3, 623, 1,24,978};
selectSort(a,5);
return 0;
} | true |
3c965910769d261796785f44d3628ce0e4401838 | C++ | mirek190/x86-android-5.0 | /vendor/intel/hardware/audiocomms/utilities/serializer/include/serializer/framework/Child.hpp | UTF-8 | 1,732 | 2.515625 | 3 | [] | no_license | /**
* @section License
*
* Copyright 2013-2014 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "serializer/framework/GetterHelper.hpp"
#include "serializer/framework/SetterHelper.hpp"
namespace audio_comms
{
namespace utilities
{
namespace serializer
{
/** Template used to describe a class child (member). */
template <typename _ChildTrait,
typename _Getter, _Getter _getter,
typename _Setter, _Setter _setter, bool _takeOwnership,
bool _optional = false>
struct Child
{
typedef _ChildTrait ChildTrait;
typedef GetterHelper<_Getter, _getter> Getter;
typedef SetterHelper<_Setter, _setter> Setter;
static const bool takeOwnership = _takeOwnership;
/** @fixme: It would be far better to be optional if the _ChildTrait had a
* specific base class (called Optional).
* Instead of writing : Child<myChildTrait, ... , true>
* you could write : Child<Optional<myChildTrait, ...> >
* with Optional defined as such :
* template <class Base> struct Optional : Base {};
*/
static const bool optional = _optional;
};
} // namespace serializer
} // namespace utilities
} // namespace audio_comms
| true |
dcace1b0483c11ce6a52494b30760bc05f47683a | C++ | duanpfsd/facedet_opennpd | /src/npd_train/LearnGAB.cpp | UTF-8 | 11,061 | 2.65625 | 3 | [] | no_license | #include "common.h"
#include <iostream>
#include "time.h"
using namespace std;
int CalcTreeDepth(vector<int>& leftChild, vector<int>& rightChild, int node = 0) {
int ld, rd;
if (node > int(leftChild.size()) - 1 ) {
return 0;
}
if (leftChild[node] < 0) {
ld = 0;
}
else {
ld = CalcTreeDepth(leftChild, rightChild, leftChild[node]);
}
if (rightChild[node] < 0) {
rd = 0;
}
else {
rd = CalcTreeDepth(leftChild, rightChild, rightChild[node]);
}
return (max(ld, rd) + 1);
}
vector<double> CalcWeight(vector<double>& fx, int flag, double maxW) {
int n = fx.size();
vector<double> weight(n);
double sum = 0;
for (int i = 0; i < n; i++) {
weight[i] = min(exp(-flag * fx[i]), maxW);
sum += weight[i];
}
if (sum == 0) {
for (int i = 0; i < n; i++) {
weight[i] = 1./n;
}
}
else{
for (int i = 0; i < n; i++) {
weight[i] /= sum;
}
}
return weight;
}
//function to test the learned soft cascade and DQT weak classifier based Gentle AdaBoost classifier.
void TestGAB(vector<double>& Fx, vector<int>& passCount, Model& model, cv::Mat& X) {
int n = X.rows;
Fx.clear();
passCount.clear();
Fx.resize(n);
passCount.resize(n);
for (int i = 0; i < n; i++) { //for each image
bool run = true;
for (int j = 0; j < int(model.stages.size()) && run; j++) { //for each weak classifier
double fx = TestDQT(model.stages[j], X.row(i));
Fx[i] += fx;
if (Fx[i] >= model.stages[j].threshold) {
passCount[i]++;
}
else {
run = false;
}
}
}
};
void LearnGAB(Model& model, cv::Mat& faceFea, cv::Mat& nonfaceFea,NpdModel& npdModel, vector<cv::Mat>& nonFaceRects, BoostOpt& option) {
int treeLevel = 4; // the maximal depth of the DQT trees to be learned
int maxNumWeaks = 1000; // maximal number of weak classifiers to be learned
double minDR = 1.0; // minimal detection rate required
double maxFAR = 1e-16; // maximal FAR allowed; stop the training if reached
int minSamples = 1000; // minimal samples required to continue training
double minNegRatio = 0.2; // minimal fraction of negative samples required to remain,
// w.r.t.the total number of negative samples.This is a signal of
// requiring new negative sample bootstrapping.Also used to avoid
// overfitting.
double trimFrac = 0.05; // weight trimming in AdaBoost
double samFrac = 1.0; // the fraction of samples randomly selected in each iteration
// for training; could be used to avoid overfitting.
double minLeafFrac = 0.01; // minimal sample fraction w.r.t.the total number of
// samples required in each leaf node.This is used to avoid overfitting.
int minLeaf = 100; // minimal samples required in each leaf node.This is used to avoid overfitting.
double maxWeight = 100; // maximal sample weight in AdaBoost; used to ensure numerical stability.
int numThreads = 24; // the number of computing threads in tree learning
if (true) {
maxWeight = option.maxWeight;
samFrac = option.samFrac;
treeLevel = option.treeLevel;
minLeafFrac = option.minLeafFrac;
minLeaf = option.minLeaf;
maxNumWeaks = option.maxNumWeak;
maxFAR = option.maxFAR;
minNegRatio = option.minNegRatio;
minSamples = option.minSamples;
trimFrac = option.trimFrac;
numThreads = option.numThreads;
minDR = option.minDR;
}
int nPos = faceFea.rows;
int nNeg = nonfaceFea.rows;
clock_t t0 = clock();
vector<double> posFx, negFx;
vector<int> passCount;
cv::Mat posX(nPos, faceFea.cols, CV_8UC1, faceFea.data);
cv::Mat negX(nNeg, nonfaceFea.cols, CV_8UC1, nonfaceFea.data);
vector<double> newPosFx, newNegFx, posW, negW;
vector<int> posPassIndex, negPassIndex;
int startIter;
if (!model.isEmpty()) {
cout << "Test the current model..." << endl;
int T = model.stages.size();
//test pos samples
TestGAB(posFx, passCount, model, faceFea);
nPos = 0;
for (int i = 0; i < int(passCount.size()); i++) {
if (passCount[i] == T) {
//faceFea.row(i).copyTo(posX.row(nPos++));
posPassIndex.push_back(i);
nPos++;
newPosFx.push_back(posFx[i]);
}
}
if (nPos < faceFea.rows) {
cout << "Warning: some positive samples cannot pass all stages. pass rate is "
<< ((nPos)/(double)(faceFea.rows)) << endl;
}
//test neg samples
passCount.clear();
TestGAB(negFx, passCount, model, nonfaceFea);
nNeg = 0;
for (int i = 0; i < int(passCount.size()); i++) {
if (passCount[i] == T) {
//nonfaceFea.row(i).copyTo(negX.row(nNeg++));
negPassIndex.push_back(i);
nNeg++;
newNegFx.push_back(negFx[i]);
}
}
if (nNeg < nonfaceFea.rows) {
cout << "Warning: some negative samples cannot pass all stages, pass rate is "
<< ((nNeg)/(double)(nonfaceFea.rows)) << endl;
}
vector<double> newPosW = CalcWeight(newPosFx, 1, maxWeight);
vector<double> newNegW = CalcWeight(newNegFx, -1, maxWeight);
posW.resize(faceFea.rows);
for (int i = 0; i < int(newPosW.size()); i++)
{
posW[posPassIndex[i]] = newPosW[i];
}
negW.resize(nonfaceFea.rows);
for (int i = 0; i < int(newNegW.size()); i++)
{
negW[negPassIndex[i]] = newNegW[i];
}
startIter = T;
cout << (clock() - t0) << " seconds." << endl;
}
else {
posW = vector<double>(nPos);
negW = vector<double>(nNeg);
posFx = vector<double>(nPos);
negFx = vector<double>(nNeg);
for (int i = 0; i < nPos; i++) {
posW[i] = 1. / nPos;
posFx[i] = 0;
}
for (int i = 0; i < nNeg; i++) {
negW[i] = 1. / nNeg;
negFx[i] = 0;
}
posPassIndex.resize(nPos);
for (int i = 0; i < nPos; i++) {
posPassIndex[i] = i;
}
negPassIndex.resize(nNeg);
for (int i = 0; i < nNeg; i++) {
negPassIndex[i] = i;
}
startIter = 0;
}
int nNegPass = nNeg;
cout << "\nStart to train adaboost, nPos=" << nPos << ", nNeg=" << nNeg << endl << endl;
int t;
for (t = startIter; t < maxNumWeaks; t++) {
if (nNegPass < minSamples) {
cout << endl << "No enough negative samples. The Adaboost learning terninates at iteration "
<< t << ". nNegPass = " << nNegPass << endl;
break;
}
//posIndex
int nPosSam = max((int)round(nPos*samFrac), minSamples);
vector<int> posIndex(nPos);
for (int i = 0; i < nPos; i++) {
posIndex[i] = posPassIndex[i];
}
random_shuffle(posIndex.begin(), posIndex.end());
posIndex.resize(nPosSam);
//negIndex
int nNegSam = max((int)round(nNegPass*samFrac), minSamples);
vector<int> negIndex(nNegPass);
for (int i = 0; i < nNegPass; i++) {
negIndex[i] = negPassIndex[i];
}
random_shuffle(negIndex.begin(), negIndex.end());
negIndex.resize(nNegSam);
//trim pos weight
vector<int> trimedPosIndex;
vector<int> posIndexSort(posIndex);
IndexSort(posIndexSort, posW);
double cumsum = 0;
int k = 0;
for (int i = 0; i < int(posIndexSort.size()); i++) {
cumsum += posW[posIndexSort[i]];
if (cumsum >= trimFrac) {
k = i;
break;
}
}
k = min(k, nPosSam - minSamples);
double trimWeight = posW[posIndexSort[k]];
for (int i = 0; i < int(posIndex.size()); i++) {
if (posW[posIndex[i]] >= trimWeight)
trimedPosIndex.push_back(posIndex[i]);
}
posIndex.swap(trimedPosIndex);
//trim neg weight
vector<int> trimedNegIndex;
vector<int> negIndexSort(negIndex);
IndexSort(negIndexSort, negW);
cumsum = 0;
//int k;
for (int i = 0; i < int(negIndexSort.size()); i++) {
cumsum += negW[negIndexSort[i]];
if (cumsum >= trimFrac) {
k = i;
break;
}
}
k = min(k, nNegSam - minSamples);
trimWeight = negW[negIndexSort[k]];
for (int i = 0; i < int(negIndex.size()); i++) {
if (negW[negIndex[i]] >= trimWeight)
trimedNegIndex.push_back(negIndex[i]);
}
negIndex.swap(trimedNegIndex);
nPosSam = posIndex.size();
nNegSam = negIndex.size();
int minLeaf_t = max( (int)round((nPosSam+nNegSam)*minLeafFrac), minLeaf);
printf("\nIter %d: nPos=%d, nNeg=%d, ", t, nPosSam, nNegSam);
vector<int> feaId, leftChild, rightChild;
vector< vector<uchar> > cutpoint;
vector<double> fit;
double minCost;
LearnDQT(feaId, leftChild, rightChild, cutpoint, fit, minCost, posX, negX, posW, negW, posFx, negFx, posIndex,
negIndex, treeLevel, minLeaf_t, numThreads);
if (int(feaId.size()) == 0)
{
printf("\n\nNo available features to satisfy the split. The AdaBoost learning terminates.\n");
break;
}
model.stages.push_back(Stage()); //add a new stage
model.stages[t].feaId = feaId;
model.stages[t].cutpoint = cutpoint;
model.stages[t].leftChild = leftChild;
model.stages[t].rightChild = rightChild;
model.stages[t].fit = fit;
model.stages[t].depth = CalcTreeDepth(leftChild, rightChild);
vector<double> v;
for (int i = 0; i < int(posPassIndex.size()); i++) {
posFx[posPassIndex[i]] += TestDQT(model.stages[t], posX.row(posPassIndex[i]));
v.push_back(posFx[posPassIndex[i]]);
}
for (int i = 0; i < int(negPassIndex.size()); i++) {
negFx[negPassIndex[i]] += TestDQT(model.stages[t], negX.row(negPassIndex[i]));
}
sort(v.begin(), v.end());
int index = max((int)floor(nPos*(1-minDR)), 0);
model.stages[t].threshold = v[index];
vector<int> temNegPassIndex;
for (int i = 0; i < int(negPassIndex.size()); i++) {
if (negFx[negPassIndex[i]] >= model.stages[t].threshold) {
temNegPassIndex.push_back(negPassIndex[i]);
}
}
negPassIndex.swap(temNegPassIndex);
model.stages[t].far = negPassIndex.size() / (double)nNegPass;
nNegPass = negPassIndex.size();
double FAR = 1;
for (int i = 0; i < int(model.stages.size()); i++) {
FAR *= model.stages[i].far;
}
//TODO: calc aveEval
printf("FAR(t)=%.2f%%, FAR=%.2g, depth=%d, nFea(t)=%d, nFea=%d, cost=%.3f.\n",
model.stages[t].far * 100, FAR, model.stages[t].depth, int(feaId.size()), int(model.stages[t].feaId.size()), minCost);
printf("\t\tnNegPass=%d, aveEval=%.3f, time=%.0fs, meanT=%.3fs.\n", nNegPass, 0.0/*aveEval*/, double(clock() - t0), double(clock()- t0) / (t - startIter + 1));
if (FAR <= maxFAR) {
printf("\n\nThe training is converged at iteration %d. FAR = %.2f%%\n", t, FAR * 100);
break;
}
if (nNegPass < nNeg * minNegRatio || nNegPass < minSamples) {
printf("\n\nNo enough negative samples. The AdaBoost learning terminates at iteration %d. nNegPass = %d.\n", t, nNegPass);
break;
}
vector<double> temposW;
vector<double> temposFx;
for (int i = 0; i < int(posPassIndex.size()); i++) {
temposFx.push_back(posFx[posPassIndex[i]]);
}
temposW = CalcWeight(temposFx, 1, maxWeight);
for (int i = 0; i < int(posPassIndex.size()); i++) {
posW[posPassIndex[i]] = temposW[i];
}
vector<double> temNegW;
vector<double> temNegFx;
for (int i = 0; i < int(negPassIndex.size()); i++) {
temNegFx.push_back(negFx[negPassIndex[i]]);
}
temNegW = CalcWeight(temNegFx, -1, maxWeight);
for (int i = 0; i < int(negPassIndex.size()); i++) {
negW[negPassIndex[i]] = temNegW[i];
}
}
printf("\n\nThe adaboost training is finished. Total time: %.0f seconds. Mean time: %.3f seconds.\n\n", double(clock() - t0), double(clock() - t0) / (t - startIter + 1));
};
| true |
c9de8723990b3b578e4c1cc8671db2cdc5f1c421 | C++ | huyk18/TinyWebServer | /httpd/http_server/http_server.cc | UTF-8 | 7,223 | 2.765625 | 3 | [] | no_license | /**********************************
* @Author: Soyn
* @Brief: the simple http server
* @CreatedTime: 1/11/15.
* @RefactorTime: Soyn at 30/4/16
*********************************/
#include "http_server.hpp"
#include <iostream>
const int HttpServer::BUFFERSIZE = 8096;
//
// @Brief: the predictor function
bool IsDelimiter(const char &chr)
{
return (chr == '\r' || chr == '\n');
}
//
// @Brief: Open the server
// @Note:
// This part is to open the server for connection.
void HttpServer::OpenServer()
{
InitializeServer();
}
//
// @Brief: Initialize the server including checking the error
void HttpServer::InitializeServer()
{
error_handler_.CheckRequestSupportedOrNot();
error_handler_.CheckRequestDirectoryValidOrNot();
error_handler_.CheckChangeDirectoryValidOrNot();
CreateSocket();
}
//
// @Brief: Get the request from client
void HttpServer::GetRequest(const int& connected_socket_file_descriptor,
int hit)
{
char copy_of_buffer[BUFFERSIZE];
auto bytes_counts_from_socket = read(connected_socket_file_descriptor,
copy_of_buffer, BUFFERSIZE);
buffer_ = copy_of_buffer;
std::replace_if(buffer_.begin(), buffer_.end(), IsDelimiter, '*');
if(bytes_counts_from_socket > 0)
logger_.Logging(Logger::LOG, "request: ", buffer_, hit);
if((bytes_counts_from_socket == 0) || (bytes_counts_from_socket == -1)){
logger_.Logging(Logger::FORBIDDEN, "failed to read browser request",
" ", connected_socket_file_descriptor);
}
if(bytes_counts_from_socket < -1 || bytes_counts_from_socket > BUFFERSIZE){
buffer_.clear();
}
}
//
// @Brief: Handle the request from client
void HttpServer::HandleRequest(const int& connected_socket_file_descriptor,int hit)
{
std::string http_method = buffer_.substr(0, 3);
if(http_method == "GET" && http_method == "get"){
logger_.Logging(Logger::FORBIDDEN, "Only Simple GET operation supported", buffer_,
connected_socket_file_descriptor);
}
std::size_t found = buffer_.find("..");
if(found != std::string::npos){
logger_.Logging(Logger::FORBIDDEN, "Parent directory (..) path names not\
supported", buffer_, connected_socket_file_descriptor);
}
GetTheRequestFileName();
bool supported_file_type = false;
auto iter = SupportFileType.find(request_file_type_);
if(iter != SupportFileType.end()){
supported_file_type = true;
}
if(!supported_file_type){
logger_.Logging(Logger::FORBIDDEN, "file extension type not supported", buffer_,
connected_socket_file_descriptor);
}
request_file_type_ = SupportFileType[request_file_type_];
}
//
// @Brief: Get the resource file name
// @Note: Private method
void HttpServer::GetTheRequestFileName()
{
unsigned int i = 4;
while(i < buffer_.size() && buffer_[i] != ' '){
++i;
}
if(i > 5){
request_resource_file_name_ = buffer_.substr(5, i - 5);
for(i = 0; i < request_resource_file_name_.size() ; ++i){
if(request_resource_file_name_[i] == '.'){
break;
}
}
request_file_type_ = request_resource_file_name_.substr(i + 1,
std::string::npos);
}else{
buffer_.replace(0, 5, "GET /index.html");
request_file_type_ = "html";
request_resource_file_name_ = "index.html";
}
}
//
//
// @Brief: Get the http head information
// @Note: Private member method
void HttpServer::GetHttpHeadInfo(const int& connected_socket_file_descriptor,
const int& hit)
{
std::ifstream request_file_stream(request_resource_file_name_);
auto start_position_of_file = request_file_stream.tellg();
if(!request_file_stream.is_open()){
logger_.Logging(Logger::NOTFOUND, "failed to open file",
request_resource_file_name_,connected_socket_file_descriptor);
}
logger_.Logging(Logger::LOG, "SEND: \n", request_resource_file_name_,
hit);
request_file_stream.seekg(0, request_file_stream.end);
auto end_position_of_file = request_file_stream.tellg();
length_of_request_file_ = end_position_of_file -
start_position_of_file;
request_file_stream.seekg(0, request_file_stream.beg);
}
//
// @Brief: Send http head
void HttpServer::SendHttpHead(const int& connected_socket_file_descriptor)
{
buffer_.clear();
std::string response_string("");
std::ostringstream writting_buffer_stream(response_string);
writting_buffer_stream << "HTTP/1.1 200 OK\nServer: YWeb "<<
ErrorHandler::version_ << "\nContent-Length: " <<
length_of_request_file_<< "\nConnection:close\nContent-Type: "
<< request_file_type_ << "\n\n";
buffer_ = writting_buffer_stream.str();
logger_.Logging(Logger::LOG, "Header: \n", buffer_, 2);
write(connected_socket_file_descriptor, const_cast<char*>(buffer_.c_str()),
buffer_.length());
}
//
// @Brief: Send request file to client
void HttpServer::SendRequestFile(const int& connected_socket_file_descriptor)
{
int file_descriptor = open(request_resource_file_name_.c_str(), O_RDONLY);
int bytes_counts_from_file = 0;
while((bytes_counts_from_file = read(file_descriptor,
const_cast<char*>(buffer_.c_str()),buffer_.length())) > 0){
write(connected_socket_file_descriptor, buffer_.c_str(),
bytes_counts_from_file);
}
}
//
// @Brief: Send the response to client
void HttpServer::SendResponse()
{
int connected_socket_file_descriptor;
int pid;
for(int hit = 1; ; ++hit){
socklen_t connected_client_length = sizeof(client_address_);
if((connected_socket_file_descriptor = accept(
listen_socket_file_descriptor_, (struct sockaddr*)&client_address_,
&connected_client_length)) < 0){
logger_.Logging(Logger::ERROR, "system call", "accept", 0);
}
if((pid = fork()) < 0){
logger_.Logging(Logger::ERROR, "system call", "fork", 0);
}else{
if(pid == 0){
//close(connected_socket_file_descriptor);
// get and handle the request from client
GetRequest(connected_socket_file_descriptor, hit);
HandleRequest(connected_socket_file_descriptor, hit);
// get the http head info and send the info to client
GetHttpHeadInfo(connected_socket_file_descriptor,hit);
SendHttpHead(connected_socket_file_descriptor);
// send the request file
SendRequestFile(connected_socket_file_descriptor);
sleep(1);
close(connected_socket_file_descriptor);
exit(1);
}else{
close(connected_socket_file_descriptor);
}
}
}
}
//
// @Brief: Package all the procedure
void HttpServer::Run()
{
OpenServer();
SendResponse();
}
| true |
b0c0dfa5a0f3607bf98575f685e668dbdf5ddb9a | C++ | VLanvin/ACM_booklet | /code/eulertour.cpp | UTF-8 | 655 | 3.34375 | 3 | [] | no_license | // INPUT a graph G (matrix) of size N
// OUTPUT a vector P of edges forming the eulerian tour
struct Edge {
int from, to;
Edge(int from, int to):from(from),to(to) {}
};
int deg[N];
vector<Edge> P;
void euler(int u) {
for(int v = 0; v < N; v++)
if(G[u][v]) {
G[u][v]--; G[v][u]--; //only G[u][v]--; for directed graph.
euler(v);
P.push_back(Edge(u, v));
}
}
bool solve_euler_path() {
bool solved = true;
for(int i = 0; i < N; i++)
if(deg[i] % 2 == 1) { solved = false; break; }
if(solved) {
P.clear();
euler(start);
if(P.size() != N || P[0].to != P[P.size()-1].from) solved = false;
}
return solved;
}
| true |
19e856d4a4b31421b83483df08e7b586a879d675 | C++ | luoskdev/LeetCode | /BinaryTreeLevelOrderTraversal.h | UTF-8 | 2,433 | 3.5625 | 4 | [] | no_license | /**************************************
* Author : luoshikai
* Version : 1.0
* Date : 2013-11-04
* Email : luoshikai@gmail.com
*************************************/
/**************************************
* Given a binary tree, return the level order traversal of its nodes' values.
* (ie, from left to right, level by level).
*
* For example:
* Given binary tree {3,9,20,#,#,15,7},
* 3
* / \
* 9 20
* / \
* 15 7
* return its level order traversal as:
* [
* [3],
* [9,20],
* [15,7]
* ]
* confused what "{1,#,2,3}" means? > read more on how binary tree is
* serialized on OJ.
*
*
* OJ's Binary Tree Serialization:
* The serialization of a binary tree follows a level order traversal, where
* '#' signifies a path terminator where no node exists below.
*
* Here's an example:
* 1
* / \
* 2 3
* /
* 4
* \
* 5
* The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*************************************/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root)
{
vector<vector<int> > res;
levelOrderRe(root, 0, res);
return res;
}
void levelOrderRe(TreeNode *root, int level, vector<vector<int> > &res)
{
if (root == NULL) return;
if (level >= res.size()) res.push_back(vector<int>());
res[level].push_back(root->val);
levelOrderRe(root->left, level + 1, res);
levelOrderRe(root->right, level + 1, res);
}
vector<vector<int> > levelOrder_1(TreeNode *root)
{
vector<vector<int> > res;
deque<TreeNode*> queue;
queue.push_back(root);
queue.push_back(NULL);
while(queue.front() != NULL)
{
vector<int> v_t;
while (true)
{
TreeNode *temp = queue.front();
queue.pop_front();
if (temp == NULL) break;
v_t.push_back(temp->val);
if (temp->left != NULL) queue.push_back(temp->left);
if (temp->right != NULL) queue.push_back(temp->right);
}
queue.push_back(NULL);
res.push_back(v_t);
}
return res;
}
}; | true |
2a789d32f7f812b5759e2058542636d8a6a4d4a6 | C++ | tranbaohien/TranBaoHien | /_16LedTuanTu.ino | UTF-8 | 2,895 | 3.40625 | 3 | [] | no_license | /*
shiftOut với 8 LED bằng 1 IC HC595
*/
//chân ST_CP của 74HC595
int latchPin = 8;
//chân SH_CP của 74HC595
int clockPin = 12;
//Chân DS của 74HC595
int dataPin = 11;
//Trạng thái của LED, hay chính là byte mà ta sẽ gửi qua shiftOut
const int HC595_COUNT = 2;//Nếu bạn dùng nhiều hơn thì thay bằng một số lớn hơn 2.
byte ledStatus[HC595_COUNT]= {0};
void setup() {
//Bạn BUỘC PHẢI pinMode các chân này là OUTPUT
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void fillValueToArray(byte value) {
for (int i = 0;i < HC595_COUNT; i++) {
ledStatus[i] = value;
}
}
void shiftOutHC595(int dataPin, int clockPin, byte ledStatus[]) {
digitalWrite(latchPin, LOW);
for (int i = 0; i < HC595_COUNT; i++) {
shiftOut(dataPin,clockPin,LSBFIRST,ledStatus[i]);
}
digitalWrite(latchPin, HIGH);
}
void loop() {
/*
Trong tin học, ngoài các phép +, -, *, / hay % mà bạn đã biết trên hệ cơ số 10.
Thì còn có nhiều phép tính khác nữa. Và một trong số đó là Bit Math (toán bit) trên hệ cơ số 2.
Để hiểu những gì tôi viết tiếp theo sau, bạn cần có kiến thức về Bit Math.
Để tìm hiểu về Bit Math, bạn vào mục Tài liệu tham khảo ở bảng chọn nằm phía trên cùng trang web và chạy xuống khi bạn kéo chuột trên trang Arduino.VN
*/
//Sáng tuần tự
//vì ledStatus là một mảng vì vậy để mặc định tất cả đèn tắt thì chúng ta phải for đến từng giá trị của mảng rồi đặt giá trị là 0.
fillValueToArray(0);
//Bật tuần tự
for (int i =HC595_COUNT; i>=0; i--) {
for (byte j=0;j<8;j++) {
ledStatus[i] = (ledStatus[i] >> 1)|128;
shiftOutHC595(dataPin,clockPin,ledStatus);
delay(100); // Dừng chương trình khoảng 500 mili giây để thấy các hiệu ứng của đèn LED
}
}
for (int i =HC595_COUNT; i>=0; i--) {
for (byte j=0;j<8;j++) {
ledStatus[i] = (ledStatus[i] >> 1);
shiftOutHC595(dataPin,clockPin,ledStatus);
delay(100); // Dừng chương trình khoảng 500 mili giây để thấy các hiệu ứng của đèn LED
}
}
for (int i=0; i< HC595_COUNT; i++) {
for (byte j=0;j<8;j++) {
ledStatus[i] = (ledStatus[i] << 1)|1;
shiftOutHC595(dataPin,clockPin,ledStatus);
delay(100); // Dừng chương trình khoảng 500 mili giây để thấy các hiệu ứng của đèn LED
}
}
for (int i = 0; i < HC595_COUNT; i++) {
for (byte j=0;j<8;j++) {
ledStatus[i] = (ledStatus[i] << 1);
shiftOutHC595(dataPin,clockPin,ledStatus);
delay(100); // Dừng chương trình khoảng 500 mili giây để thấy các hiệu ứng của đèn LED
}
}
}
| true |
9f140db6edf0da48e38c5e3552ee979c4ca3cfbb | C++ | yebo92/programming_examples | /boost_python_exports/rocket/include/rocket/rocket.h | UTF-8 | 1,019 | 2.890625 | 3 | [] | no_license | #ifndef _ROCKET_H_
#define _ROCKET_H_
#include <Eigen/Core>
namespace rocket {
class Rocket {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Rocket();
Rocket(double max_speed);
Rocket(double max_speed, const Eigen::Matrix2d& inertia_matrix);
virtual ~Rocket();
double getMaxSpeed() const;
void setMaxSpeed(double max_speed);
void setInertiaMatrix(const Eigen::Matrix2d& inertia_matrix);
Eigen::Matrix2d& getInertiaMatrix();
const Eigen::Matrix2d& getInertiaMatrix() const;
virtual std::string name() const = 0;
private:
double max_speed_;
Eigen::Matrix2d inertia_matrix_;
};
class Booster : public Rocket {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Booster();
Booster(double max_speed,
const Eigen::Matrix2d& inertia_matrix,
unsigned num_boosts);
virtual ~Booster();
unsigned getNumBoosts() const;
void setNumBoosts(unsigned nb);
virtual std::string name() const;
private:
unsigned num_boosts_;
};
} // namespace rocket
#endif /* _ROCKET_H_ */
| true |
1a6705728bb80f58644c0a4bf64286f3783edb37 | C++ | tudasc/MetaCG | /graph/src/MCGReader.cpp | UTF-8 | 7,402 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* File: MCGReader.cpp
* License: Part of the MetaCG project. Licensed under BSD 3 clause license. See LICENSE.txt file at
* https://github.com/tudasc/metacg/LICENSE.txt
*/
#include "MCGReader.h"
#include "MCGBaseInfo.h"
#include "Util.h"
#include "Timing.h"
#include <queue>
namespace metacg {
namespace io {
/**
* Base class
*/
MetaCGReader::FuncMapT::mapped_type &MetaCGReader::getOrInsert(const std::string &key) {
if (functions.find(key) != functions.end()) {
auto &fi = functions[key];
return fi;
} else {
FunctionInfo fi;
fi.functionName = key;
functions.insert({key, fi});
auto &rfi = functions[key];
return rfi;
}
}
void MetaCGReader::buildGraph(metacg::graph::MCGManager &cgManager, MetaCGReader::StrStrMap &potentialTargets) {
metacg::RuntimeTimer rtt("buildGraph");
auto console = metacg::MCGLogger::instance().getConsole();
// Register nodes in the actual graph
for (const auto &[k, fi] : functions) {
console->trace("Inserting MetaCG node for function {}", k);
auto node = cgManager.getCallgraph()->getOrInsertNode(k); // node pointer currently unused
node->setIsVirtual(fi.isVirtual);
node->setHasBody(fi.hasBody);
for (const auto &c : fi.callees) {
auto calleeNode = cgManager.getCallgraph()->getOrInsertNode(c);
cgManager.getCallgraph()->addEdge(node, calleeNode);
auto &potTargets = potentialTargets[c];
for (const auto &pt : potTargets) {
auto potentialCallee = cgManager.getCallgraph()->getOrInsertNode(pt);
cgManager.getCallgraph()->addEdge(node, potentialCallee);
}
}
}
}
MetaCGReader::StrStrMap MetaCGReader::buildVirtualFunctionHierarchy(metacg::graph::MCGManager &cgManager) {
metacg::RuntimeTimer rtt("buildVirtualFunctionHierarchy");
auto console = metacg::MCGLogger::instance().getConsole();
// Now the functions map holds all the information
std::unordered_map<std::string, std::unordered_set<std::string>> potentialTargets;
for (const auto &[k, funcInfo] : functions) {
if (!funcInfo.isVirtual) {
// No virtual function, continue
continue;
}
/*
* The current function can: 1. override a function, or, 2. be overridden by a function
*
* (1) Add this function as potential target for any overridden function
* (2) Add the overriding function as potential target for this function
*
*/
if (funcInfo.doesOverride) {
for (const auto &overriddenFunction : funcInfo.overriddenFunctions) {
// Adds this function as potential target to all overridden functions
potentialTargets[overriddenFunction].insert(k);
// In IPCG files, only the immediate overridden functions are stored currently.
std::queue<std::string> workQ;
std::set<std::string> visited;
workQ.push(overriddenFunction);
// Add this function as a potential target for all overridden functions
while (!workQ.empty()) {
const auto next = workQ.front();
workQ.pop();
const auto fi = functions[next];
visited.insert(next);
console->debug("In while: working on {}", next);
potentialTargets[next].insert(k);
for (const auto &om : fi.overriddenFunctions) {
if (visited.find(om) == visited.end()) {
console->debug("Adding {} to the list to process", om);
workQ.push(om);
}
}
}
}
}
}
for (const auto &[k, s] : potentialTargets) {
std::string targets;
for (const auto t : s) {
targets += t + ", ";
}
console->debug("Potential call targets for {}: {}", k, targets);
}
return potentialTargets;
}
/**
* Version two Reader
*/
void VersionTwoMetaCGReader::read(metacg::graph::MCGManager &cgManager) {
metacg::RuntimeTimer rtt("VersionTwoMetaCGReader::read");
MCGFileFormatInfo ffInfo{2, 0};
auto console = metacg::MCGLogger::instance().getConsole();
auto errConsole = metacg::MCGLogger::instance().getErrConsole();
auto j = source.get();
auto mcgInfo = j[ffInfo.metaInfoFieldName];
if (mcgInfo.is_null()) {
errConsole->error("Could not read version info from metacg file.");
throw std::runtime_error("Could not read version info from metacg file");
}
/// XXX How to make that we can use the MCGGeneratorVersionInfo to access the identifiers
auto mcgVersion = mcgInfo["version"].get<std::string>();
auto generatorName = mcgInfo["generator"]["name"].get<std::string>();
auto generatorVersion = mcgInfo["generator"]["version"].get<std::string>();
MCGGeneratorVersionInfo genVersionInfo{generatorName, metacg::util::getMajorVersionFromString(generatorVersion),
metacg::util::getMinorVersionFromString(generatorVersion), ""};
console->info("The metacg (version {}) file was generated with {} (version: {})", mcgVersion, generatorName,
generatorVersion);
{ // raii
std::string metaReadersStr;
int i = 1;
for (const auto mh : cgManager.getMetaHandlers()) {
metaReadersStr += std::to_string(i) + ") " + mh->toolName() + " ";
++i;
}
console->info("Executing the meta readers: {}", metaReadersStr);
}
MCGFileInfo fileInfo{ffInfo, genVersionInfo};
auto jsonCG = j[ffInfo.cgFieldName];
if (jsonCG.is_null()) {
errConsole->error("The call graph in the metacg file was null.");
throw std::runtime_error("CG in metacg file was null.");
}
for (json::iterator it = jsonCG.begin(); it != jsonCG.end(); ++it) {
auto &fi = getOrInsert(it.key()); // new entry for function it.key
fi.functionName = it.key();
/** Bi-directional graph information */
std::unordered_set<std::string> callees;
setIfNotNull(callees, it, fileInfo.nodeInfo.calleesStr);
fi.callees = callees;
std::unordered_set<std::string> parents;
setIfNotNull(parents, it, fileInfo.nodeInfo.callersStr); // Different name compared to version 1.0
fi.parents = parents;
/** Overriding information */
setIfNotNull(fi.isVirtual, it, fileInfo.nodeInfo.isVirtualStr);
setIfNotNull(fi.doesOverride, it, fileInfo.nodeInfo.doesOverrideStr);
std::unordered_set<std::string> overriddenFunctions;
setIfNotNull(overriddenFunctions, it, fileInfo.nodeInfo.overridesStr);
fi.overriddenFunctions.insert(overriddenFunctions.begin(), overriddenFunctions.end());
std::unordered_set<std::string> overriddenBy;
setIfNotNull(overriddenBy, it, fileInfo.nodeInfo.overriddenByStr);
fi.overriddenBy.insert(overriddenBy.begin(), overriddenBy.end());
/** Information relevant for analysis */
setIfNotNull(fi.hasBody, it, fileInfo.nodeInfo.hasBodyStr);
}
auto potentialTargets = buildVirtualFunctionHierarchy(cgManager);
buildGraph(cgManager, potentialTargets);
for (json::iterator it = jsonCG.begin(); it != jsonCG.end(); ++it) {
/**
* Pass each attached meta reader the current json object, to see if it has meta data
* particular to that reader attached.
*/
auto &jsonElem = it.value()[fileInfo.nodeInfo.metaStr];
if (!jsonElem.is_null()) {
for (const auto metaHandler : cgManager.getMetaHandlers()) {
if (jsonElem.contains(metaHandler->toolName())) {
metaHandler->read(jsonElem, it.key());
}
}
}
}
}
} // namespace io
} // namespace metacg
| true |
3da1ce73b9566be7f9caaf9065f1b16b7311438f | C++ | cavallo5/cpp_scripts | /src/Triangolo tartaglia.cpp | UTF-8 | 891 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
using namespace std;
const int D=20;
typedef int matrice[D][D];
void costruzionetriangolo(matrice t,int r);
void stampatriangolo(matrice t,int r);
int main()
{
int n;
cout<<"Triangolo di Tartaglia"<<endl;
cout<<"Numero di righe"<<endl;
cin>>n;
matrice m;
costruzionetriangolo(m,n);
stampatriangolo(m,n);
system("PAUSE");
return 0;
}
void costruzionetriangolo(matrice t,int r)
{
for(int i=1;i<r;i++)
t[i][i]=0;
for(int i=0;i<r;i++)
t[i][0]=1;
for(int i=2;i<r;i++)
for(int j=0;j<i;j++)
t[i][j]=t[i-1][j-1]+t[i-1][j];
}
void stampatriangolo(matrice t,int r)
{
for(int i=0;i<r;i++)
{for(int j=0;j<r;j++)
{
cout.width(4);
cout<<t[i][j]<<" ";
cout<<endl;
}
}
}
| true |
a58adcecbdb8a38ba3e7a0a197b4e9cb175d9e37 | C++ | mridenti/COVID-19-ITA-WIN | /src/csv_to_input.cpp | ISO-8859-1 | 6,554 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <math.h>
#include <stdbool.h>
#ifndef NEA
#define NEA 16
#endif
#define NUM_FAIXAS NEA
int main(int argc, char** argv) {
FILE *csv;
FILE *output;
char filename[512];
char *input_path = "input\\";
errno_t err;
if (argc == 2)
{
sprintf_s(filename, "%scenarios\\%s\\initial.csv", input_path, argv[1]);
if (fopen_s(&csv, filename, "r") == 1)
{
perror("Abertura de arquivo de entrada initial.csv falhou. \n");
return 1;
}
}
else if (argc == 1)
{
sprintf_s(filename, "%scenarios\\default\\initial.csv", input_path);
if (fopen_s(&csv, filename, "r") != 0)
{
perror("Abertura de arquivo de entrada initial.csv falhou. \n");
return 1;
}
}
else {
printf_s("Uso: \n");
printf_s("\tcsv_to_input [nome do cenrio] \n");
printf_s("\n");
printf_s("Exemplos: \n");
printf_s("1) Usando o cenrio \"Default\":\n");
printf_s("\tcsv_to_input \n");
printf_s("2) Usando um cenrio chamado de \"HardLockdown\":\n");
printf_s("\tcsv_to_input HardLockdown\n");
printf_s("\n");
printf_s("Cenrio: \n");
printf_s("Um cenrio uma pasta dentro de input/cenarios com o nome do cenrio e contendo os arquivos .csv referentes aos parmetros da simulao que sero utilizados");
printf_s("\t\n");
return 0;
}
sprintf_s(filename, "%s\\generated-input.txt", input_path);
if (fopen_s(&output,filename, "w") != 0)
{
perror("Abertura de arquivo de saida generated-input.txt falhou. \n");
return 1;
}
fprintf_s(output, "# ---------------------------------------------------------- \n");
fprintf_s(output, "# INITIAL VALUES PER AGE GROUP \n");
fprintf_s(output, "# ---------------------------------------------------------- \n");
fprintf_s(output, "\n");
char line[4096];
while (fgets(line, 4096, csv) != NULL)
{
char* tmp = _strdup(line);
const char* tok;
char* posn;
for (tok = strtok_s(line, ",", &posn); tok && *tok; tok = strtok_s(NULL, ",\n", &posn))
{
fprintf_s(output, "%-15s\t", tok);
}
fprintf_s(output, "\n");
free(tmp);
}
fclose(csv);
// Open PARAMETERS file
if (argc == 2)
{
sprintf_s(filename, "%scenarios\\%s\\parameters.csv", input_path, argv[1]);
printf_s("Lendo: %s\n", filename);
if(fopen_s(&csv, filename, "r") != 0)
{
perror("Abertura de arquivo de parametros paramenters.csv falhou. \n");
return 1;
}
}
else if(argc == 1)
{
sprintf_s(filename, "%scenarios\\default\\parameters.csv", input_path);
printf_s("Lendo: %s\n", filename);
if((err = fopen_s(&csv, filename, "r")) != 0)
{
perror("Abertura de arquivo de parametros parameters.csv falhou. \n");
return 1;
}
}
else {
printf_s("Uso: \n");
printf_s("csv_to_input [nome do cenrio] \n");
printf_s("\t ou \n");
printf_s("csv_to_input \n");
printf_s("\t (Neste caso usar o cenrio default) \n");
}
fprintf_s(output, "\n\n");
fprintf_s(output, "# ---------------------------------------------------------- \n");
fprintf_s(output, "# PARAMETERS (fixed in time) \n");
fprintf_s(output, "# ---------------------------------------------------------- \n");
fprintf_s(output, "\n");
fgets(line, 4096, csv); // Ignorar header
while (fgets(line, 4096, csv) != NULL)
{
char* tmp = _strdup(line);
const char* tok;
char* posn;
for (tok = strtok_s(line, ",", &posn); tok && *tok; tok = strtok_s(NULL, ",\n", &posn))
{
fprintf_s(output, "%-15s\t", tok);
}
fprintf_s(output, "\n");
free(tmp);
}
fprintf_s(output, "\n");
fclose(csv);
// Print gama, gama_QI, gama_QA and beta by day
FILE *csv_beta_gama;
if (argc == 2)
{
sprintf_s(filename, "%scenarios\\%s\\beta_gama.csv", input_path, argv[1]);
printf_s("Lendo: %s\n", filename);
if (fopen_s(&csv_beta_gama, filename, "r") != 0)
{
perror("Abertura de arquivo de parametros beta_gama.csv falhou. \n");
return 1;
}
}
else if (argc == 1)
{
sprintf_s(filename, "%scenarios\\default\\beta_gama.csv", input_path);
printf_s("Lendo: %s\n", filename);
if (fopen_s(&csv_beta_gama, filename, "r") != 0)
{
perror("Abertura de arquivo de parametros beta_gama.csv falhou. \n");
return 1;
}
sprintf_s(filename, "%scenarios\\default\\beta_gama.csv", input_path);
}
else {
printf_s("Uso: \n");
printf_s("csv_to_input [nome do cenrio] \n");
printf_s("\t ou \n");
printf_s("csv_to_input \n");
printf_s("\t (Neste caso usar o cenrio default) \n");
}
// Print gama, gama_QI, gama_QA and beta by day
fgets(line, 4096, csv_beta_gama); // Ignorar header
int day = -1;
while (fgets(line, 4096, csv_beta_gama) != NULL)
{
char* beta_tmp = _strdup(line);
bool first_tok = true;
const char* tok;
char *posn;
for (tok = strtok_s(line, ",", &posn); tok && *tok; tok = strtok_s(NULL, ",\n", &posn))
{
if (first_tok) {
if (atoi(tok) > day) {
day = atoi(tok);
fprintf_s(output, "# ---------------------------------------------------------- \n");
fprintf_s(output, "DAY %s \n", tok);
// Print GAMA
fprintf_s(output, "GAMA \t\t");
tok = strtok_s(NULL, ",\n", &posn); // Step
for (int ii = 0; ii < NEA; ii++) {
fprintf_s(output, "%-18s ", tok);
tok = strtok_s(NULL, ",\n", &posn); // Step
}
fprintf_s(output, "\n");
// Print xI
fprintf_s(output, "xI \t\t\t");
for (int ii = 0; ii < NEA; ii++) {
fprintf_s(output, "%-18s ", tok);
tok = strtok_s(NULL, ",\n", &posn); // Step
}
fprintf_s(output, "\n");
// Print xA
fprintf_s(output, "xA \t\t\t");
for (int ii = 0; ii < NEA; ii++) {
fprintf_s(output, "%-18s ", tok);
if (ii != (NEA - 1)) tok = strtok_s(NULL, ",\n", &posn); // Step
}
fprintf_s(output, "\n");
// Print BETA
fprintf_s(output, "BETA \t\t");
}
else if (tok[0] != 10) {
// Padding
fprintf(output, " ");
}
first_tok = false;
}
else {
fprintf(output, "%-18s ", tok);
}
}
first_tok = true;
fprintf_s(output, "\n");
free(beta_tmp);
}
fclose(csv_beta_gama);
return 0;
}
| true |
9680546e9cd613add55353fdde22213759f51c0f | C++ | ZhuChaozheng/rover_18 | /rover_cmd_point/src/sub_cmd_vel.cpp | UTF-8 | 2,376 | 2.515625 | 3 | [] | no_license |
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/String.h"
#include "nav_msgs/Odometry.h"
using namespace std;
ros::Publisher velocity_publisher;
ros::Subscriber pose_subscriber;
nav_msgs::Odometry odom;
geometry_msgs::Twist new_vel;
void velCallback(const geometry_msgs::Twist::ConstPtr& vel);
void write_callback(const std_msgs::String::ConstPtr& msg);
void serial_write(void);
int main(int argc, char **argv)
{
// Initiate new ROS node named "rover_garen_node"
ros::init(argc, argv, "rover_garen_node");
ros::NodeHandle np;
pose_subscriber = np.subscribe("/husky_velocity_controller/cmd_vel", 10, velCallback);
velocity_publisher = np.advertise<geometry_msgs::Twist>("/husky_velocity_controller/cmd_vel", 1000);
ros::Rate loop_rate(5);
ROS_INFO("\n\n\n ********START TESTING*********\n");
ros::spin();
return 0;
}
void velCallback(const geometry_msgs::Twist::ConstPtr& vel)
{
new_vel.linear.x=vel->linear.x;
new_vel.linear.y=vel->linear.y;
new_vel.angular.z=vel->angular.z;
ROS_INFO("x : %lf y : %lf thetha : %lf ",new_vel.linear.x,new_vel.linear.y,new_vel.angular.z);
//serial_write();
}
/*
void write_callback(const std_msgs::String::ConstPtr& msg){
ROS_INFO_STREAM("Writing to serial port" << msg->data);
ser.write(msg->data);
}
void serial_write(void)
{
ros::NodeHandle nh;
ros::Subscriber write_sub = nh.subscribe("write", 1000, write_callback);
ros::Publisher read_pub = nh.advertise<std_msgs::String>("read", 1000);
try
{
ser.setPort("/dev/ttyACM0");
ser.setBaudrate(9600);
serial::Timeout to = serial::Timeout::simpleTimeout(1000);
ser.setTimeout(to);
ser.open();
}
catch (serial::IOException& e)
{
ROS_ERROR_STREAM("Unable to open port ");
return -1;
}
if(ser.isOpen()){
ROS_INFO_STREAM("Serial Port initialized");
}else{
return -1;
}
ros::Rate loop_rate(5);
while(ros::ok()){
ros::spinOnce();
if(ser.available()){
ROS_INFO_STREAM("Reading from serial port");
std_msgs::String result;
result.data = ser.read(ser.available());
ROS_INFO_STREAM("Read: " << result.data);
read_pub.publish(result);
}
loop_rate.sleep();
}
}
}
*/
| true |
dc25bb307fa5aedcd8a030e0bcddbcddf57ebc78 | C++ | seeinto/Code | /haizei/1.C语言/16.prime.cpp | UTF-8 | 701 | 2.890625 | 3 | [] | no_license | /*************************************************************************
> File Name: 15.prime.cpp
> Author:
> Mail:
> Created Time: Fri 13 Nov 2020 03:53:12 PM CST
************************************************************************/
#include <stdio.h>
#define max 100
int prime[max + 5];
void init(){
for(int i = 2; i <= max; i++){
if(prime[i])continue;
prime[++prime[0]] = i;
for(int j = i * i ; j <= max;j +=i){
prime[j] = 1;
}
}
return ;
}
int main(){
init();
int sum = 0;
for(int i = 1; i <= prime[0]; i++){
sum += prime[i];
printf("%d\n",prime[i]);
}
printf("%d\n",sum);
return 0;
}
| true |
0476e8e0bfd80b7a7a39655157b686432a2e0a11 | C++ | jessehon/journee | /eosio_docker/contracts/treechain/treechain.cpp | UTF-8 | 3,712 | 3.125 | 3 | [] | no_license | #include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
using namespace eosio;
// Smart Contract Name: treechain
// Table struct:
// treestruct: multi index table to store the trees
// prim_key(uint64): primary key
// user(account_name/uint64): account name for the user
// tree(string): the tree message
// timestamp(uint64): the store the last update block time
// Public method:
// isnewdna => to check if the given dna has tree in table or not
// Public actions:
// update => put the tree into the multi-index table and sign by the given account
// carbon => estimate carbon usage for a particular object
// Replace the contract class name when you start your own project
class treechain : public eosio::contract {
private:
bool isnewdna( std::string dna ) {
treetable treeobj(_self, _self);
// get object by secordary key
auto trees = treeobj.get_index<N(getbydna)>();
auto tree = trees.find(string_to_name(dna.c_str()));
return tree == trees.end();
}
/// @abi table
struct treestruct {
uint64_t prim_key; // primary key
account_name user; // account name for the user
std::string dna; // the tree message
std::string message; // the tree message
uint64_t timestamp; // the store the last update block time
// primary key
auto primary_key() const { return prim_key; }
// secondary key: dna (max length of 12)
uint64_t get_by_dna() const { return string_to_name(dna.c_str()); }
};
// create a multi-index table and support secondary key
typedef eosio::multi_index< N(treestruct), treestruct,
indexed_by< N(getbydna), const_mem_fun<treestruct, uint64_t, &treestruct::get_by_dna> >
> treetable;
public:
using contract::contract;
// This action inserts into a table information about the lineage
// of a botanical item.
// While we are using dna as a demonstration string we will move
// to hashing dna with a public salt that is per account (such as
// the account public key). With this process we will not show
// the actual DNA so an intermediate supplier would not be able
// to say they processed the tree without actually taking a sample
// of DNA. Verification of this process would require the actual
// DNA of the object (tests for this are currently arround $20 but
// decreasing).
/// @abi action
void insert( account_name _user, std::string& _dna, std::string& _message ) {
// to sign the action with the given account
require_auth( _user );
treetable obj(_self, _self); // code, scope
// insert object
obj.emplace( _self, [&]( auto& address ) {
address.prim_key = obj.available_primary_key();
address.user = _user;
address.dna = _dna;
address.message = _message;
address.timestamp = now();
});
}
// This is a simple action for estimating carbo
// We will change this to validate the hash of the DNA with
// a list of authorised parties and additionally
// use the latitude / longitude for estimating real carbon
// usage.
/// @abi action
void carbon(std::string& _dna ) {
treetable obj(_self, _self); // code, scope
float carbon = 0.0;
auto itr = obj.begin();
while (itr != obj.end()) {
if (itr->dna == _dna) {
carbon += 1000;
}
itr++;
}
std::string message = std::string("carbon estimated at ") + std::to_string(carbon) + "\n";
print(message);
}
};
// specify the contract name, and export a public action: update
EOSIO_ABI( treechain, (insert)(carbon) )
| true |
1a45e0e5fb32217ecd56f818e16a792a995d8410 | C++ | SpencerYoungCS/CS-Projects | /CS3A - Object Oriented Programming/CH10DateMonthClass/main.cpp | UTF-8 | 371 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include "month.h"
using namespace std;
int main()
{
Month(5);
Month A;
A.SetNum(30);
cout << "A.SetNum(30): " << A.getNumMonth() << endl;
A.SetChar('f','e','b');
cout << "A.SetChar(f,e,b) :" << A.getcharmonth() << endl;
A.getNextMonth();
cout << "A.getnextmonth(): " << A.getNumMonth() << endl;
return 0;
}
| true |
fe2685563cac0f7a388b1c8f565f3ce0a70faf4f | C++ | WhiZTiM/coliru | /Archive2/4a/d2c64ce30539c6/main.cpp | UTF-8 | 534 | 2.765625 | 3 | [] | no_license | int foo(int i)
{
int res = 0;
if (i % 2) {
if (i % 3) {
goto labelA;
}
// The lack of a goto here is a fallthrough bug case which should not happen.
} else if (i % 3) {
goto labelB;
} else {
goto labelC;
}
goto labelNoReturn; // -- this point should not be reached. --
labelA:
res = 1;
goto final;
labelB:
res = 2;
goto final;
labelC:
res = 3;
goto final;
final:
return res;
labelNoReturn:
{}
} | true |
64ba00f23205ab6bee390a45cadc45f45fae133a | C++ | Hibchibbler/TankGame | /Common/Player.h | UTF-8 | 1,661 | 2.625 | 3 | [] | no_license | #ifndef Player_h_
#define Player_h_
#include <SFML/Graphics.hpp>
#include "Projectile.h"
#include "Tank.h"
namespace tg
{
//This ratified enum is used by both server and client entities
//to identify state. so, some states don't make sense from a client
//perspective, and likewise for server.
//None the less, the state is specific to a Player
struct PlayerState{
enum pstate{
New,/***********/
SendingWhoIs,
SendingWhoIsAck,
WaitingForWhoIsAck,
SendingId,
SendingIdAck,
SendingIdNack,
WaitingForIdAck,
SendingStateOfPlayer,
WaitingForStateOfPlayer,
SendingStateOfUnion,
WaitingForStateOfUnion,
SendingReady,
WaitingForReady,
Ready,/***********/
WaitingForMap,
WaitingForStart,
Running,/***********/
Paused,/***********/
EmitProjectile
};
};
class Player
{
public:
Player(){
playerName = "-empty-";
connectionId = -1;
state = PlayerState::New;
hasHost = false;
slotNum = -1;
nextUid=1;
}
Tank tank;
std::vector<Projectile> prjctls;
sf::Uint32 nextUid;
std::string playerName;
sf::Uint32 connectionId;
sf::Uint32 hasHost;//yes, like, in the alien sense.
sf::Uint32 slotNum;
sf::Uint32 state;
sf::Clock attackClock;
sf::Clock accelerateClock;
sf::Clock turnClock;
};
};
#endif
| true |
ed98a95dc0827f0715b839fcbef631fe7ce39f7b | C++ | bettle123/tokenizer | /Tokenizer.cpp | UTF-8 | 8,633 | 3.296875 | 3 | [] | no_license | /*
This code can be compiled and run ok.
Goal: The goal of this part of the project is to
implement a Tokenizer for the language Core.
(1~11) Reserved words (11 reserved words):
program, begin, end, int, if, then,
else, while, loop, read, write
(12~30) Special symbols (19 special symbols):
; , = ! [ ] && || ( ) + - * != == < > <= >=
(31) Integers (unsigned) (max size of 8 digits).
ex. 25;
(32) Identifiers:
ex. X,Y,z;
(33) for end-of-life
EOF
usage (how to run):
g++ -o test Tokenizer.cpp
input file:
coreProgram.txt
output files:
none
compile (how to compile):
g++ -o Tokenizer Tokenizer.cpp
coded by Su, Ming Yi, OSU_ID: su.672, email: su.672@osu.edu
date: 2017.10.04
LinkedList is learnt from website:
https://github.com/alrightchiu/SecondRound/blob/master/content/Algorithms%20and%20Data%20Structures/BasicDataStructures/ExampleCode/LinkedList.cpp
*/
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdlib.h> /* atoi */
using namespace std;
// List records each word meaning
class LinkedList; // 為了將class LinkedList設成class ListNode的friend,
// 需要先宣告
class ListNode{
private:
int data;
ListNode *next;
public:
ListNode():data(0),next(0){};
ListNode(int a):data(a),next(0){};
friend class LinkedList;
};
class LinkedList{
private:
// int size; // size是用來記錄Linked list的長度, 非必要
ListNode *first; // list的第一個node
public:
LinkedList():first(0){};
void PrintList(); // 印出list的所有資料
void Push_front(int x); // 在list的開頭新增node
void Push_back(int x); // 在list的尾巴新增node
void Delete(int x); // 刪除list中的 int x
void Clear(); // 把整串list刪除
void Reverse(); // 將list反轉: 7->3->14 => 14->3->7
};
// PrintList()的功能就是把Linked list中的所有資料依序印出。
void LinkedList::PrintList(){
if (first == 0) { // 如果first node指向NULL, 表示list沒有資料
cout << "List is empty.\n";
return;
}
ListNode *current = first; // 用pointer *current在list中移動
while (current != 0) { // Traversal
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
// Push_back()的功能是在Linked list的尾巴新增資料
void LinkedList::Push_back(int x){
ListNode *newNode = new ListNode(x); // 配置新的記憶體
if (first == 0) { // 若list沒有node, 令newNode為first
first = newNode;
return;
}
ListNode *current = first;
while (current->next != 0) { // Traversal
current = current->next;
}
current->next = newNode; // 將newNode接在list的尾巴
}
void token_check_int_id (string &x, LinkedList&mytokenizer,int &number){
char uppercase_letter[26]={
'A','B','C','D','E',
'F','G','H','I','J',
'K','L','M','N','O',
'P','Q','R','S','T',
'U','V','W','X','Y','Z'
};
// Integers
char *fff;
int i,j;
fff= new char [x.size()];
for(i = 0; i < x.size(); i++) {
fff[i]=x[i];
}
int value =atoi (fff);
if(value >0||value<0){
mytokenizer.Push_back(31);number =1;
}
if(x=="0"){
mytokenizer.Push_back(31);number =1;
}
//Identifiers
int key=0,letter_value=0,key2=0;
for (i=0;i<26;i++){
if(fff[0]==uppercase_letter[i]){
key2=1;
}
for (j=0; j<x.size();j++){
if(fff[j]==uppercase_letter[i]){
key++;
}
}
}
for(j=0;j<x.size();j++){
letter_value = fff[j]-'0';
if(letter_value>=0&&letter_value<10){
key++;
}
}
if (key==x.size()&&(key2==1)){
mytokenizer.Push_back(32);number =1;
}
if ((key!=x.size())&&(number==0)){
// cout <<x<<" is illegal."<<endl;
}
}
int token_check(string &x, LinkedList&mytokenizer,int &number){
string token[30]= {
"program", "begin", "end", "int",
"if", "then", "else", "while", "loop",
"read","write",
";", ",", "=", "!", "[", "]", "&&",
"||", "(", ")", "+", "-", "*", "!=",
"==", "<", ">", "<=", ">="
};
int token_length[30]={0};
for(int i =0;i<30;i++){
token_length[i]= token[i].size();
}
int i=0,j=0;
// number is the controller that my identifiers won't
// bother my other staff
for(i =0;i<30;i++){
if(x==token[i]){
mytokenizer.Push_back(i+1);number =1;
}
}
token_check_int_id (x,mytokenizer,number);
//solve the problem that "ABC;" is illegal
// it should be "ABC" and ";"
string x_part1,x_part2;
int k1=0,k2=0,part1=0,part2=0;
int x_length= x.size();
if(number==0){
if(x_length>1){
for(i = 1;i<x_length;i++){
x_part1 = x_part1.assign (x,0,i);
x_part2 = x_part2.assign (x,i,x_length-i);
int part1=0,part2=0,k1,k2;
for(j=0;j<30;j++){
if(x_part1==token[j]){
part1=1;
k1 = j+1;
}
if(x_part2==token[j]){
part2=1;
k2 = j+1;
}
}
if ((part1==1)&&(part2==1)){
mytokenizer.Push_back(k1);
mytokenizer.Push_back(k2);
number =1;
}
}
}
}
if((number==0)&&(x_length>1)&&(part1+part2<2)){
string x_part,x_rest,x_rest2;
for(i = 0;i<x_length;i++){
for (j=0;j<30;j++){
if(x_length>token_length[j]){
x_part = x_part.assign (x, i,token_length[j]);
if(x_part==token[j]){
x_rest = x_rest.assign (x, token_length[j],x_length-token_length[j]);
if(i==0){
mytokenizer.Push_back(j+1);
//token_check_int_id (x_rest,mytokenizer,number);
token_check(x_rest,mytokenizer,number);
}
if(i!=0){
x_rest = x_rest.assign (x, 0,i);
//token_check_int_id(x_rest,mytokenizer,number);
token_check(x_rest,mytokenizer,number);
mytokenizer.Push_back(j+1);
if(x_length>(i+token_length[j]))
{
x_rest2 = x_rest2.assign (x,i+token_length[j],x_length);
token_check(x_rest2,mytokenizer,number);
break;
}
}
}
}
}
}
}
return(number);
}
int main(int argc, char* argv[]){
//Tokenizer mytokenizer;
// initialize the tokenizer object
LinkedList mytokenizer; // 建立LinkedList的object
char uppercase_letter[26]={
'A','B','C','D','E',
'F','G','H','I','J',
'K','L','M','N','O',
'P','Q','R','S','T',
'U','V','W','X','Y','Z'
};
cout <<"Please input the test file."<<'\n'
<<"ex. coreProgram.txt"<<endl;
string filename;
cin >>filename;
char *fff;
fff= new char [filename.size()];
for(int i = 0; i < filename.size(); i++) {
fff[i]=filename[i];
}
cout <<"The test filename: "<<filename<<endl;
ifstream file;
file.open( filename.c_str() );
string x;
cout <<"Output:"<<endl;
while (file >>x){
// Reserved words
int number =0;
number = token_check(x, mytokenizer, number);
}
file.close();
// EOF (for end-of-file)
mytokenizer.Push_back(33);
mytokenizer.PrintList();
return 0;
}
| true |
ab74396ef485878c1d0e6ea2da9f66e6d1555059 | C++ | franciscoruivo/isec-material | /POO-2020/Trabalho/ISECTotalWar/tecnologia.h | UTF-8 | 641 | 3 | 3 | [] | no_license | #ifndef TECNOLOGIA_H
#define TECNOLOGIA_H
#include <string>
#include <sstream>
using namespace std;
class Tecnologia {
string nome, descr;
int custo;
bool isBought = false;
public:
Tecnologia(string n, int c, string d) : nome(n), custo(c), descr(d) {}
// Devolve o nome da tecnologia
string getNome() const { return nome; }
// Devolve a descricao da tecnologia
string getDescr() const { return descr; }
// Devolve o custo da tecnologia
int getCusto() const { return custo; }
string getAsString() const;
};
ostream& operator<<(ostream& out, const Tecnologia& a);
#endif /* TECNOLOGIA_H */ | true |
2117983b10dc7b99e1f05a94a38378bbd203a3c4 | C++ | hypercubestart/universal | /include/universal/posit/specialized/posit_8_1.hpp | UTF-8 | 13,909 | 2.65625 | 3 | [
"LicenseRef-scancode-public-domain",
"LGPL-3.0-only",
"MIT"
] | permissive | #pragma once
// posit_8_1.hpp: specialized 8-bit posit using fast implementation specialized for posit<8,1>
//
// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
namespace sw {
namespace unum {
// set the fast specialization variable to indicate that we are running a special template specialization
#if POSIT_FAST_POSIT_8_1
#pragma message("Fast specialization of posit<8,1>")
// injecting the C API into namespace sw::unum
#include "posit_8_1.h"
template<>
class posit<NBITS_IS_8, ES_IS_1> {
public:
static constexpr size_t nbits = NBITS_IS_8;
static constexpr size_t es = ES_IS_1;
static constexpr size_t sbits = 1;
static constexpr size_t rbits = nbits - sbits;
static constexpr size_t ebits = es;
static constexpr size_t fbits = nbits - 3 - es;
static constexpr size_t fhbits = fbits + 1;
static constexpr uint8_t sign_mask = 0x80;
posit() { _bits = 0; }
posit(const posit&) = default;
posit(posit&&) = default;
posit& operator=(const posit&) = default;
posit& operator=(posit&&) = default;
// initializers for native types
explicit posit(const signed char initial_value) { *this = initial_value; }
explicit posit(const short initial_value) { *this = initial_value; }
explicit posit(const int initial_value) { *this = initial_value; }
explicit posit(const long initial_value) { *this = initial_value; }
explicit posit(const long long initial_value) { *this = initial_value; }
explicit posit(const char initial_value) { *this = initial_value; }
explicit posit(const unsigned short initial_value) { *this = initial_value; }
explicit posit(const unsigned int initial_value) { *this = initial_value; }
explicit posit(const unsigned long initial_value) { *this = initial_value; }
explicit posit(const unsigned long long initial_value) { *this = initial_value; }
explicit posit(const float initial_value) { *this = initial_value; }
explicit posit(const double initial_value) { *this = initial_value; }
explicit posit(const long double initial_value) { *this = initial_value; }
// assignment operators for native types
posit& operator=(const signed char rhs) { return operator=((int)(rhs)); }
posit& operator=(const short rhs) { return operator=((int)(rhs)); }
posit& operator=(const int rhs) { return integer_assign(rhs); }
posit& operator=(const long rhs) { return operator=((int)(rhs)); }
posit& operator=(const long long rhs) { return operator=((int)(rhs)); }
posit& operator=(const char rhs) { return operator=((int)(rhs)); }
posit& operator=(const unsigned short rhs) { return operator=((int)(rhs)); }
posit& operator=(const unsigned int rhs) { return operator=((int)(rhs)); }
posit& operator=(const unsigned long rhs) { return operator=((int)(rhs)); }
posit& operator=(const unsigned long long rhs) { return operator=((int)(rhs)); }
posit& operator=(const float rhs) { return float_assign(rhs); }
posit& operator=(const double rhs) { return operator=(float(rhs)); }
posit& operator=(const long double rhs) { return operator=(float(rhs)); }
explicit operator long double() const { return to_long_double(); }
explicit operator double() const { return to_double(); }
explicit operator float() const { return to_float(); }
explicit operator long long() const { return to_long_long(); }
explicit operator long() const { return to_long(); }
explicit operator int() const { return to_int(); }
explicit operator unsigned long long() const { return to_long_long(); }
explicit operator unsigned long() const { return to_long(); }
explicit operator unsigned int() const { return to_int(); }
posit& set(sw::unum::bitblock<NBITS_IS_8>& raw) {
_bits = uint8_t(raw.to_ulong());
return *this;
}
posit& set_raw_bits(uint64_t value) {
_bits = uint8_t(value & 0xff);
return *this;
}
posit operator-() const {
posit negated;
posit8_1_t b = { { _bits } };
return negated.set_raw_bits(posit8_1_negate(b).v);
}
posit& operator+=(const posit& b) {
posit8_1_t lhs = { { _bits } };
posit8_1_t rhs = { { b._bits} };
posit8_1_t add = posit8_1_addp8(lhs, rhs);
_bits = add.v;
return *this;
}
posit& operator-=(const posit& b) {
posit8_1_t lhs = { { _bits } };
posit8_1_t rhs = { { b._bits } };
posit8_1_t sub = posit8_1_subp8(lhs, rhs);
_bits = sub.v;
return *this;
}
posit& operator*=(const posit& b) {
posit8_1_t lhs = { { _bits } };
posit8_1_t rhs = { { b._bits } };
posit8_1_t mul = posit8_1_mulp8(lhs, rhs);
_bits = mul.v;
return *this;
}
posit& operator/=(const posit& b) {
posit8_1_t lhs = { { _bits } };
posit8_1_t rhs = { { b._bits } };
posit8_1_t div = posit8_1_divp8(lhs, rhs);
_bits = div.v;
return *this;
}
posit& operator++() {
++_bits;
return *this;
}
posit operator++(int) {
posit tmp(*this);
operator++();
return tmp;
}
posit& operator--() {
--_bits;
return *this;
}
posit operator--(int) {
posit tmp(*this);
operator--();
return tmp;
}
posit reciprocate() const {
posit p = 1.0 / *this;
return p;
}
// SELECTORS
inline bool isnar() const { return (_bits == 0x80); }
inline bool iszero() const { return (_bits == 0x00); }
inline bool isone() const { return (_bits == 0x40); } // pattern 010000...
inline bool isminusone() const { return (_bits == 0xC0); } // pattern 110000...
inline bool isneg() const { return (_bits & 0x80); }
inline bool ispos() const { return !isneg(); }
inline bool ispowerof2() const { return !(_bits & 0x1); }
inline int sign_value() const { return (_bits & 0x80 ? -1 : 1); }
bitblock<NBITS_IS_8> get() const { bitblock<NBITS_IS_8> bb; bb = int(_bits); return bb; }
unsigned long long encoding() const { return (unsigned long long)(_bits); }
inline void clear() { _bits = 0; }
inline void setzero() { clear(); }
inline void setnar() { _bits = 0x80; }
inline posit twosComplement() const {
posit<NBITS_IS_8, ES_IS_1> p;
int8_t v = -*(int8_t*)&_bits;
p.set_raw_bits(v);
return p;
}
private:
uint8_t _bits;
// Conversion functions
#if POSIT_THROW_ARITHMETIC_EXCEPTION
int to_int() const {
if (iszero()) return 0;
if (isnar()) throw not_a_real{};
return int(to_float());
}
long to_long() const {
if (iszero()) return 0;
if (isnar()) throw not_a_real{};
return long(to_double());
}
long long to_long_long() const {
if (iszero()) return 0;
if (isnar()) throw not_a_real{};
return long(to_long_double());
}
#else
int to_int() const {
if (iszero()) return 0;
if (isnar()) return int(INFINITY);
return int(to_float());
}
long to_long() const {
if (iszero()) return 0;
if (isnar()) return long(INFINITY);
return long(to_double());
}
long long to_long_long() const {
if (iszero()) return 0;
if (isnar()) return (long long)(INFINITY);
return long(to_long_double());
}
#endif
float to_float() const {
posit8_1_t p = { { _bits } };
return posit8_1_tof(p);
}
double to_double() const {
return (double)to_float();
}
long double to_long_double() const {
return (long double)to_float();
}
// helper method
posit& integer_assign(int rhs) {
posit8_1_t p = posit8_1_fromsi(rhs);
_bits = p.v;
return *this;
}
posit& float_assign(float rhs) {
posit8_1_t p = posit8_1_fromf(rhs);
_bits = p.v;
return *this;
}
// I/O operators
friend std::ostream& operator<< (std::ostream& ostr, const posit<NBITS_IS_8, ES_IS_1>& p);
friend std::istream& operator>> (std::istream& istr, posit<NBITS_IS_8, ES_IS_1>& p);
// posit - posit logic functions
friend bool operator==(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs);
friend bool operator!=(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs);
friend bool operator< (const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs);
friend bool operator> (const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs);
friend bool operator<=(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs);
friend bool operator>=(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs);
};
// posit I/O operators
// generate a posit format ASCII format nbits.esxNN...NNp
inline std::ostream& operator<<(std::ostream& ostr, const posit<NBITS_IS_8, ES_IS_1>& p) {
// to make certain that setw and left/right operators work properly
// we need to transform the posit into a string
std::stringstream ss;
#if POSIT_ROUNDING_ERROR_FREE_IO_FORMAT
ss << NBITS_IS_8 << '.' << ES_IS_1 << 'x' << to_hex(p.get()) << 'p';
#else
std::streamsize prec = ostr.precision();
std::streamsize width = ostr.width();
std::ios_base::fmtflags ff;
ff = ostr.flags();
ss.flags(ff);
ss << std::showpos << std::setw(width) << std::setprecision(prec) << (long double)p;
#endif
return ostr << ss.str();
}
// read an ASCII float or posit format: nbits.esxNN...NNp, for example: 32.2x80000000p
inline std::istream& operator>> (std::istream& istr, posit<NBITS_IS_8, ES_IS_1>& p) {
std::string txt;
istr >> txt;
if (!parse(txt, p)) {
std::cerr << "unable to parse -" << txt << "- into a posit value\n";
}
return istr;
}
// convert a posit value to a string using "nar" as designation of NaR
std::string to_string(const posit<NBITS_IS_8, ES_IS_1>& p, std::streamsize precision) {
if (p.isnar()) {
return std::string("nar");
}
std::stringstream ss;
ss << std::setprecision(precision) << float(p);
return ss.str();
}
// posit - posit binary logic operators
inline bool operator==(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return lhs._bits == rhs._bits;
}
inline bool operator!=(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return !operator==(lhs, rhs);
}
inline bool operator< (const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return (signed char)(lhs._bits) < (signed char)(rhs._bits);
}
inline bool operator> (const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return operator< (rhs, lhs);
}
inline bool operator<=(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return operator< (lhs, rhs) || operator==(lhs, rhs);
}
inline bool operator>=(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return !operator< (lhs, rhs);
}
/* base class has these operators: no need to specialize */
inline posit<NBITS_IS_8, ES_IS_1> operator+(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
posit<NBITS_IS_8, ES_IS_1> result = lhs;
return result += rhs;
}
inline posit<NBITS_IS_8, ES_IS_1> operator-(const posit<NBITS_IS_8, ES_IS_1>& lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
posit<NBITS_IS_8, ES_IS_1> result = lhs;
return result -= rhs;
}
// binary operator*() is provided by generic class
#if POSIT_ENABLE_LITERALS
// posit - literal logic functions
// posit - int logic operators
inline bool operator==(const posit<NBITS_IS_8, ES_IS_1>& lhs, int rhs) {
return operator==(lhs, posit<NBITS_IS_8, ES_IS_1>(rhs));
}
inline bool operator!=(const posit<NBITS_IS_8, ES_IS_1>& lhs, int rhs) {
return !operator==(lhs, posit<NBITS_IS_8, ES_IS_1>(rhs));
}
inline bool operator< (const posit<NBITS_IS_8, ES_IS_1>& lhs, int rhs) {
return operator<(lhs, posit<NBITS_IS_8, ES_IS_1>(rhs));
}
inline bool operator> (const posit<NBITS_IS_8, ES_IS_1>& lhs, int rhs) {
return operator< (posit<NBITS_IS_8, ES_IS_1>(rhs), lhs);
}
inline bool operator<=(const posit<NBITS_IS_8, ES_IS_1>& lhs, int rhs) {
return operator< (lhs, posit<NBITS_IS_8, ES_IS_1>(rhs)) || operator==(lhs, posit<NBITS_IS_8, ES_IS_1>(rhs));
}
inline bool operator>=(const posit<NBITS_IS_8, ES_IS_1>& lhs, int rhs) {
return !operator<(lhs, posit<NBITS_IS_8, ES_IS_1>(rhs));
}
// int - posit logic operators
inline bool operator==(int lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return posit<NBITS_IS_8, ES_IS_1>(lhs) == rhs;
}
inline bool operator!=(int lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return !operator==(posit<NBITS_IS_8, ES_IS_1>(lhs), rhs);
}
inline bool operator< (int lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return operator<(posit<NBITS_IS_8, ES_IS_1>(lhs), rhs);
}
inline bool operator> (int lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return operator< (posit<NBITS_IS_8, ES_IS_1>(rhs), lhs);
}
inline bool operator<=(int lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return operator< (posit<NBITS_IS_8, ES_IS_1>(lhs), rhs) || operator==(posit<NBITS_IS_8, ES_IS_1>(lhs), rhs);
}
inline bool operator>=(int lhs, const posit<NBITS_IS_8, ES_IS_1>& rhs) {
return !operator<(posit<NBITS_IS_8, ES_IS_1>(lhs), rhs);
}
#endif // POSIT_ENABLE_LITERALS
#else // POSIT_FAST_POSIT_8_1
// too verbose #pragma message("Special posit<8,1>")
# define POSIT_FAST_POSIT_8_1 0
#endif // POSIT_FAST_POSIT_8_1
}
}
| true |
281484d8e8f3b1e6b98a42ec0c8375a4971a6096 | C++ | tanishq1g/cp_codes | /LeetCode/454. 4Sum II.cpp | UTF-8 | 683 | 2.953125 | 3 | [
"MIT"
] | permissive | // array hashing
class Solution {
public:
int fourSumCount(vector<int>& a, vector<int>& b, vector<int>& c, vector<int>& d) {
int n = a.size();
unordered_map<int, int> umap;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
umap[a[i] + b[j]]++;
}
}
int count = 0;
unordered_map<int, int>::iterator itr;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
itr = umap.find(-(c[i] + d[j]));
if(itr != umap.end()){
count += itr->second;
}
}
}
return count;
}
}; | true |
e23ef4dd6574200ab76230e0bcadf1abe0c3c945 | C++ | norrilsk/SuicidalLollipop | /main.cpp | UTF-8 | 637 | 2.625 | 3 | [] | no_license | #include <iostream>
#include "GLfunc.hpp"
#include "Game.hpp"
#include "Loger.hpp"
using namespace std;
Game game;
Loger logfile;
void DealWithError(Error err)
{
if((err.getType() != NONE) && (err.getType() != QUIT))
cerr << err.getMessage()<< endl;
if(err.getType() != LOGFILE)
logfile << err.getMessage() << endl;
}
int main(int argc, char **argv)
{
try
{
logfile.open("Log/GameLog.txt");
Gl :: init(&argc, argv);
game.start();
Gl :: MainLoop(); //запускаем главный цикл
}
catch (Error err)
{
DealWithError(err);
}
catch (...)
{
DealWithError(newError(OTHER));
}
return 0;
}
| true |
93599f2c97738228b193463eaa8ca899a56fa3bb | C++ | avinashsastry/trimarkov_HMM | /markov_ViewpointHidden.cpp | UTF-8 | 16,460 | 2.671875 | 3 | [] | no_license | /*
* markov_ViewpointHidden.cpp
* markov
*
* Created by Avinash on 10/1/10.
* Copyright 2010 GTCMT. All rights reserved.
*
*/
#include "markov_Gaussian.h"
#include "markov_defines.h"
#include "markov_enums.h"
#include "markov_classes.h"
#include "markov_1DNode.h"
#include "markov_1DList.h"
#include "markov_1DVectorNode.h"
#include "markov_1DVectorList.h"
#include "markov_Bundle2D.h"
#include "markov_2DNode.h"
#include "markov_tracker.h"
#include "markov_Bundle2DHidden.h"
#include "markov_2DNodeHidden.h"
#include "markov_ViewpointHidden.h"
cViewPointHidden :: cViewPointHidden()
{
Stream.SetDim(0);
UseShortTermModel = TRUE;
PrevPDF = new tBundle2DHidden();
}
cViewPointHidden :: cViewPointHidden(unsigned int Dim = 0)
{
Stream.SetDim(Dim);
UseShortTermModel = TRUE;
}
// Wrapper for tBundle2D :: GrowAll(...)
int cViewPointHidden :: GrowAll(tTracker * Tracker, void *x)
{
return Trie.GrowAll(&Stream, &SymbolStream, Tracker, x, &StrokeMeans[0][0], &StrokeVariance[0][0], &StrokeInverse[0][0], &StrokeDeterminant);
}
// Wrapper for tBundle2D :: PredictBest(...)
int cViewPointHidden :: PredictBest(c1DList *Outcome, void *x)
{
return Trie.PredictBest(&Stream, Outcome, x);
}
int cViewPointHidden :: PredictBest(tBundle2DHidden *Outcome, void *x)
{
return Trie.PredictBest(&SearchStream, Outcome, x);
}
void cViewPointHidden :: SetUseShortTermModel(bool TrueOrFalse)
{
UseShortTermModel = TrueOrFalse;
}
int cViewPointHidden :: AddToStream(float input1, void *x)
{
c1DList Vector(NULL,NULL,0);
Vector.Append(input1);
if (Stream.GetDim() == 0)
{
Stream.SetDim(1);
}
// Check for dimensions of the input stream
// Add only if it is a single dimension stream
if (Stream.GetDim() == 1)
{
Stream.Append(&Vector);
// If the tree has a maximum order limit, left shift the input stream
// so that only that part is fed into the tree
if (Stream.GetLength() > MAX_ORDER)
{
Stream.LeftShift();
}
// Grow the tree
Trie.GrowAll(&Stream, &SymbolStream, &Tracker, x, &StrokeMeans[(unsigned int)input1][0], &StrokeVariance[0][0], &StrokeInverse[0][0], &StrokeDeterminant);
Vector.DeleteAll();
return eRETVAL_SUCCESS;
}
else
{
return eRETVAL_FAILURE;
}
}
// This function does the following:
// 1. Add the state to the StateStream
// 2. Add the symbol to the SymbolStream
// 3. Add the state to the Trie
// 4. Add the symbol to the current state in the Trie.
// The function is recursive so it should update each level of the
// trie, until the entire input stream of both states and symbols is
// covered.
int cViewPointHidden :: AddToStream(float InputState, float InputSymbol, void *x)
{
// Add State to the state stream
c1DList Vector(NULL,NULL,0);
Vector.Append(InputState);
if (Stream.GetDim() == 0)
{
Stream.SetDim(1);
}
// Check for dimensions of the input stream
// Add only if it is a single dimension stream
if (Stream.GetDim() == 1)
{
Stream.Append(&Vector);
// If the tree has a maximum order limit, left shift the input stream
// so that only that part is fed into the tree
if (Stream.GetLength() > MAX_ORDER)
{
Stream.LeftShift();
}
}
Vector.DeleteAll();
// Add symbol to the symbol stream
Vector.Append(InputSymbol);
if (SymbolStream.GetDim() == 0)
{
SymbolStream.SetDim(1);
}
if (SymbolStream.GetDim() == 1)
{
SymbolStream.Append(&Vector);
if (SymbolStream.GetLength() > MAX_ORDER)
{
SymbolStream.LeftShift();
}
}
// Grow the tree
Trie.GrowAll(&Stream, &SymbolStream, &Tracker, x, &StrokeMeans[((unsigned int)InputState-1)][0], &StrokeVariance[0][0], &StrokeInverse[0][0], &StrokeDeterminant);
Vector.DeleteAll();
return eRETVAL_SUCCESS;
}
int cViewPointHidden :: AddToSearchStream(float input1, void *x)
{
c1DList Vector(NULL, NULL, 0);
Vector.Append(input1);
// If SearchStream has not been initialized then set dimension
if(SearchStream.GetDim() == 0)
{
SearchStream.SetDim(1);
}
if (SearchStream.GetDim() == 1)
{
// Add the input value to the Search Stream
SearchStream.Append(&Vector);
// Maintain the order
if (SearchStream.GetLength() > MAX_ORDER)
{
SearchStream.LeftShift();
}
}
// If the short term model is active then
// grow the short term trie on the search stream
if (IS_SHORT_TERM_MODEL)
{
// TrieShortTerm.GrowAll(&SearchStream, &TrackerShortTerm, x);
}
//CrossValidate priors
EntropyPrior = Trie.CrossValidate(&Vector, &Tracker, x);
//Crossvalidate long term
if (PrevPDFLongTerm != NULL)
{
EntropyLongTerm = PrevPDFLongTerm->CrossValidate(&Vector, &Tracker, x);
}
else
{
EntropyLongTerm = -log10(Tracker.GetEscapeProb(0))/log10(2);
}
//Crossvalidate the short term
if (PrevPDFShortTerm != NULL)
{
EntropyShortTerm = PrevPDFShortTerm->CrossValidate(&Vector, &TrackerShortTerm, x);
}
else
{
EntropyShortTerm = -log10(TrackerShortTerm.GetEscapeProb(0))/log10(2);
}
//Crossvalidate the merged model
if (PrevPDF != NULL)
{
EntropyCombined = PrevPDF->CrossValidate(&Vector, &Tracker, x);
}
else
{
EntropyCombined = -log10(Tracker.GetEscapeProb(0))/log10(2);
}
Vector.DeleteAll();
return eRETVAL_SUCCESS;
}
int cViewPointHidden :: AddToSearchStream(float input1, float input2, void* x)
{
c1DList Vector(NULL, NULL, 0);
Vector.Append(input1);
Vector.Append(input2);
// If SearchStream has not been initialized then set dimension
if(SearchStream.GetDim() == 0)
{
SearchStream.SetDim(2);
}
// Add the input value to the Search Stream
if (SearchStream.GetDim() == 2)
{
SearchStream.Append(&Vector);
// Maintain the order
if (SearchStream.GetLength() > MAX_ORDER)
{
SearchStream.LeftShift();
}
}
// If the short term model is active then
// grow the short term trie on the search stream
if (IS_SHORT_TERM_MODEL)
{
// TrieShortTerm.GrowAll(&SearchStream, &TrackerShortTerm, x);
}
//CrossValidate priors
EntropyPrior = Trie.CrossValidate(&Vector, &Tracker, x);
//Crossvalidate long term
if (PrevPDFLongTerm != NULL)
{
EntropyLongTerm = PrevPDFLongTerm->CrossValidate(&Vector, &Tracker, x);
}
else
{
EntropyLongTerm = -log10(Tracker.GetEscapeProb(0))/log10(2);
}
//Crossvalidate the short term
if (PrevPDFShortTerm != NULL)
{
EntropyShortTerm = PrevPDFShortTerm->CrossValidate(&Vector, &TrackerShortTerm, x);
}
else
{
EntropyShortTerm = -log10(TrackerShortTerm.GetEscapeProb(0))/log10(2);
}
//Crossvalidate the merged model
if (PrevPDF != NULL)
{
EntropyCombined = PrevPDF->CrossValidate(&Vector, &Tracker, x);
}
else
{
EntropyCombined = -log10(Tracker.GetEscapeProb(0))/log10(2);
}
Vector.DeleteAll();
return eRETVAL_SUCCESS;
}
unsigned int cViewPointHidden :: AddFeaturesToSearchStream(float* FeatureVector, c1DList* DataToken)
{
SearchStream.AddFeatures(FeatureVector, DataToken);
if (SearchStream.GetLength() > MAX_ORDER)
{
SearchStream.LeftShift();
}
return eRETVAL_SUCCESS;
}
int cViewPointHidden :: PredictNext(void *x)
{
tBundle2DHidden* OutcomeLT = new tBundle2DHidden();
tBundle2DHidden* OutcomeST = new tBundle2DHidden();
tBundle2DHidden* OutcomeCT = new tBundle2DHidden();
double TempEntropy1 = 0;
double TempEntropy2 = 0;
unsigned int retval = eRETVAL_UNDEFINED;
// Call the prediction function. This will give out a probability distribution
retval = Trie.PredictSmoothBest(&SearchStream, OutcomeLT, &Tracker, x);
// If the prediction fails, assign NULL to the outcome
if(retval & eRETVAL_FAILURE)
{
PrevPDFLongTerm = NULL;
}
else
{
// Store this probability distribution
OutcomeLT->Normalize();
PrevPDFLongTerm = OutcomeLT;
}
// Call predict on the short term model
retval = TrieShortTerm.PredictSmoothBest(&SearchStream, OutcomeST, &TrackerShortTerm, x);
if(retval & eRETVAL_FAILURE)
{
PrevPDFShortTerm = NULL;
}
else
{
// Store this probability distribution
OutcomeST->Normalize();
PrevPDFShortTerm = OutcomeST;
}
// If the short term model gave prediction, then merge
if (!(retval & eRETVAL_FAILURE))
{
// Combine the two predictions
// Call predict again so that the Combined model is the same as the
// Long term model, then the merge function can be used to combine with
// the short term model
retval = Trie.PredictSmoothBest(&SearchStream, OutcomeCT, &Tracker, x);
if (retval & eRETVAL_FAILURE)
{
PrevPDF = NULL;
}
else
{
// Normalize the model and assign the pointer
OutcomeCT->Normalize();
PrevPDF = OutcomeCT;
//Get the long term entropy
TempEntropy1 = PrevPDFLongTerm->TotalEntropy(&Tracker);
//Get the shortTerm entropy
TempEntropy2 = PrevPDFShortTerm->TotalEntropy(&TrackerShortTerm);
//Merge the PDFs
if (UseShortTermModel)
{
PrevPDF->MergePDF(PrevPDFShortTerm, TempEntropy2, TempEntropy1);
}
}
}
else
{
PrevPDF = NULL;
}
return retval;
}
int cViewPointHidden :: PredictNextKN(void *x)
{
tBundle2DHidden* OutcomeLT = new tBundle2DHidden();
tBundle2DHidden* OutcomeST = new tBundle2DHidden();
tBundle2DHidden* OutcomeCT = new tBundle2DHidden();
double TempEntropy1 = 0;
double TempEntropy2 = 0;
unsigned int retval = eRETVAL_UNDEFINED;
// Call the prediction function. This will give out a probability distribution
retval = Trie.PredictKneserNey(&SearchStream, OutcomeLT, &Tracker, x);
// If the prediction fails, assign NULL to the outcome
if(retval & eRETVAL_FAILURE)
{
PrevPDFLongTerm = NULL;
}
else
{
// Store this probability distribution
OutcomeLT->Normalize();
PrevPDFLongTerm = OutcomeLT;
}
// Call predict on the short term model
retval = TrieShortTerm.PredictKneserNey(&SearchStream, OutcomeST, &TrackerShortTerm, x);
if(retval & eRETVAL_FAILURE)
{
PrevPDFShortTerm = NULL;
}
else
{
// Store this probability distribution
OutcomeST->Normalize();
PrevPDFShortTerm = OutcomeST;
}
// If the short term model gave prediction, then merge
if (!(retval & eRETVAL_FAILURE))
{
// Combine the two predictions
// Call predict again so that the Combined model is the same as the
// Long term model, then the merge function can be used to combine with
// the short term model
retval = Trie.PredictKneserNey(&SearchStream, OutcomeCT, &Tracker, x);
if (retval & eRETVAL_FAILURE)
{
PrevPDF = NULL;
}
else
{
// Normalize the model and assign the pointer
OutcomeCT->Normalize();
PrevPDF = OutcomeCT;
//Get the long term entropy
TempEntropy1 = PrevPDFLongTerm->TotalEntropy(&Tracker);
//Get the shortTerm entropy
TempEntropy2 = PrevPDFShortTerm->TotalEntropy(&TrackerShortTerm);
//Merge the PDFs
PrevPDF->MergePDF(PrevPDFShortTerm, TempEntropy2, TempEntropy1);
}
}
else
{
PrevPDF = NULL;
}
return retval;
}
double cViewPointHidden :: EvaluateStream(void *x)
{
return Trie.EvaluateSearchStream(&SearchStream, x);
}
// This function finds the forward probability of
// every possible stream given the set of features
// and calculates a probability distribution over
// the different possible symbols
double cViewPointHidden :: EvaluateStreamContinuous(void *x)
{
double ForwardProb = 0;
t2DNodeHidden* TempNode = NULL;
// Create a NULL distribution with the initialized
// gaussians and all prior probs set to NULL
UpdateNodesInPDF(0);
for (TempNode = PrevPDF->FirstNode; TempNode != NULL; TempNode = TempNode->Right)
{
ForwardProb = Trie.EvaluateSearchStreamContinuous(&SearchStream, &TempNode->Vector, &Tracker, x);
// Set the forward prob as the prior for the PDF
TempNode->Prob = ForwardProb;
}
return 0;
}
// Calculates the backward probability for the search sequence,
// given that it ended on a particular end-state
double cViewPointHidden :: GetBackwardProbability(c1DList* NodeVector, void * x)
{
// Call GetBackwardProbability() on the top level bundle
// Atleast for now, till I figure out exactly what I need from
// this function
return Trie.GetBackwardProbabilityForNode(&SearchStream, NodeVector, &Tracker, x);
}
// ForwardBackwardAlgorithm()
// Top level function to run the Fwd-Back Algo on
// the entire tree at every time step.
double cViewPointHidden :: ForwardBackwardAlgorithm(void* x)
{
Tracker.SetAllWeights(SearchStream.GetLength());
Tracker.ResetOrder();
return Trie.AdjustProbabilities(&Trie, &SearchStream, 0, &Tracker, x);
}
unsigned int cViewPointHidden :: DecodeStream(c1DVectorList *ResultStream ,void *x)
{
return Trie.DecodeSearchStream(&SearchStream, ResultStream, x);
}
unsigned int cViewPointHidden :: UpdateNodesInPDF(double ForwardProb)
{
t2DNodeHidden* TempNode = NULL;
t2DNodeHidden* TempNode2 = NULL;
float InputStroke = 0;
// Check if PrevPDF exists and create it if it doesn't
if (PrevPDF == NULL)
{
PrevPDF = new tBundle2DHidden();
}
if (Trie.FirstNode != NULL)
{
// For each node in the Trie
for (TempNode = Trie.FirstNode; TempNode != NULL; TempNode = TempNode->Right)
{
// Find the node in the trie in PrevPDF
TempNode2 = PrevPDF->Find(&TempNode->Vector);
// If you find it
if (TempNode2 != NULL)
{
// Set its prob
TempNode2->Prob = ForwardProb;
}
else
{
// If you don't find it, create the node
// and set its probabilty to the forward prob.
// Get the stroke in the vector
InputStroke = TempNode->Vector.GetValue(0);
// Append the node and then update the prob
PrevPDF->Append(&TempNode->Vector, ForwardProb, &StrokeMeans[((unsigned int)InputStroke-1)][0], &StrokeVariance[0][0], &StrokeInverse[0][0], &StrokeDeterminant);
}
}
}
else
{
// Trie does not exist. Do nothing.
}
return eRETVAL_SUCCESS;
}
int cViewPointHidden :: ResetViewpoint(int ResetType)
{
switch(ResetType)
{
// reset input stream
case 1:
Stream.DeleteAll();
break;
// reset tree
case 2:
// Reset both tries
Trie.DeleteBundle();
// Reset tracker
Tracker.DeleteAll();
// Erase the Streams
Stream.DeleteAll();
SearchStream.DeleteAll();
SymbolStream.DeleteAll();
break;
//reset short term tries
case 3:
SearchStream.DeleteAll();
TrieShortTerm.DeleteBundle();
TrackerShortTerm.DeleteAll();
// Set all PDFs to NULL
PrevPDF = NULL;
PrevPDFShortTerm = NULL;
PrevPDFLongTerm = NULL;
break;
case 4:
// reset search streams
SearchStream.DeleteAll();
PrevPDF = NULL;
PrevPDFLongTerm = NULL;
PrevPDFShortTerm = NULL;
break;
default:
break;
}
// Complete reset of the viewpoint
return eRETVAL_SUCCESS;
}
/**********************************************************************
Special Functions - Below are functions that may be specific to some
viewpoints. These functions must be used in the right context so use
carefully.
**********************************************************************/
// PredictStrokePIS()
// Predicts stroke values given the position of the next event in the song
// Works only with StrokePIS viewpoint
// This should use only the ST model otherwise it may end up
// picking up junk that is not consistent with the song
int cViewPointHidden :: PredictStrokePIS(float PositionInSong, void* x)
{
tBundle2DHidden* OutcomeST = new tBundle2DHidden();
t2DNodeHidden* TempNode = NULL;
c1DList Vector(NULL, NULL, 0);
int retval = eRETVAL_UNDEFINED;
Vector.Append(PositionInSong);
// Call predict on the short term model
retval = TrieShortTerm.PredictSmoothBest(&SearchStream, OutcomeST, &TrackerShortTerm, x);
if(retval & eRETVAL_FAILURE)
{
PrevPDFShortTerm = NULL;
}
else
{
// If we made a prediction on the ST,
// then we need to filter the strokes
// based on the position given.
// First reset PrevPDFShortTerm
PrevPDFShortTerm = new tBundle2DHidden();
for (TempNode = OutcomeST->FirstNode; TempNode != NULL; TempNode = TempNode->Right)
{
// if the PIS matches, then
if (TempNode->Vector.GetValue(1) == Vector.GetValue(0))
{
// Append the node to PrevPDFShortTerm
PrevPDFShortTerm->Append(&TempNode->Vector);
// This node will now be the last node
// So set its probability
PrevPDFShortTerm->LastNode->Prob = TempNode->Prob;
}
else
{
// Do absolutely nothing
}
}
if (PrevPDFShortTerm->FirstNode != NULL)
{
// Store this probability distribution
PrevPDFShortTerm->Normalize();
}
else
{
PrevPDFShortTerm = OutcomeST;
PrevPDFShortTerm->Normalize();
}
}
return eRETVAL_SUCCESS;
} | true |
02ee6d20cfc06647c04670329c694c585abce359 | C++ | lynus/sns | /src/eye.cpp | WINDOWS-1252 | 3,033 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include "cinder\Camera.h"
#include "cinder\Vector.h"
#include "cinder\app\AppNative.h"
#include <cmath>
#include <ostream>
#include "eye.h"
#include "cinder\CinderMath.h"
#include "config.h"
using namespace ci;
#define min(x,y) (x)<=(y)?(x):(y)
#define max(x,y) (x)>=(y)?(x):(y)
Matrix44f modelview;
Matrix44f projection;
Area viewport;
Vec3f unproject(const Vec3f &pt)
{
/* find the inverse modelview-projection-matrix */
Matrix44f a = projection * modelview;
a.invert(0.0f);
/* transform to normalized coordinates in the range [-1, 1] */
Vec4f in;
in.x = (pt.x - viewport.getX1())/viewport.getWidth()*2.0f-1.0f;
in.y = (pt.y - viewport.getY1())/viewport.getHeight()*2.0f-1.0f;
in.z = 2.0f * pt.z - 1.0f;
in.w = 1.0f;
/* find the object's coordinates */
Vec4f out = a * in;
if(out.w != 0.0f) out.w = 1.0f / out.w;
/* calculate output */
Vec3f result;
result.x = out.x * out.w;
result.y = out.y * out.w;
result.z = out.z * out.w;
return result;
}
Vec3f screenToWorld(float x, float y, float z)
{
Vec3f p = Vec3f(x, y, z);
/* adjust y (0,0 is lowerleft corner in OpenGL) */
p.y = (viewport.getHeight() - p.y);
/* near plane intersection */
p.z = 0.0f;
Vec3f p0 = unproject(p);
/* far plane intersection */
p.z = 1.0f;
Vec3f p1 = unproject(p);
/* find (x, y) coordinates */
float t = (z - p0.z) / (p1.z - p0.z);
p.x = (p0.x + t * (p1.x - p0.x));
p.y = (p0.y + t * (p1.y - p0.y));
p.z = z;
return p;
}
static void getxy(float _scale, Vec2f p, int &x, int &y)
{
int scale = (int)ceil(_scale);
//ռŴ㿪ʼ
x =(int)( p.x*pow(2.0,scale));
y =(int) (p.y*pow(2.0,scale));
}
void eye::init(Vec3f _pos,float ratio)
{
pos = _pos;
scale= 0;
need_update = true;
}
void eye::reset()
{
pos = ci::Vec3f(0.5f,0.5f,0.0f);
scale = 0.0f;
pos.z = pow(2,-scale-0.5);
need_update = true;
}
void eye::setClose(float z_delta)
{
/*pos.z += z_delta;
float t = sqrt(2.0)* pos.z;
float new_scale = -log(t)/log(2.0);
scale = new_scale;*/
scale +=z_delta;
need_update = true;
}
void eye::update()
{
if (need_update == false)
return;
//glOrtho(0,config::get()->win_width,0,config::get()->win_height,0.0f,1.0f);
}
void eye::setPos(int dir, float delta)
{
if (dir == VERTICAL) {
pos.y += delta/scale;
if (scale >= 0.0f)
pos.y = constrain( pos.y,static_cast<float>(pow(2,-scale)/2),1.0f-static_cast<float>(pow(2,-scale)/2));
else
pos.y = constrain(pos.y,1.0f-static_cast<float>(pow(2,-scale)/2),static_cast<float>(pow(2,-scale)/2));
}
if (dir == HORIZONAL) {
pos.x += delta/scale;
if (scale >= 0.0f)
pos.x = constrain(pos.x,static_cast<float>(pow(2,-scale)/2),1.0f-static_cast<float>(pow(2,-scale)/2));
else
pos.x = constrain(pos.x,1.0f-static_cast<float>(pow(2,-scale)/2),static_cast<float>(pow(2,-scale)/2));
}
need_update = true;
}
void eye::convertMouse(float &mx, float &my)
{
modelview = gl::getModelView();
projection = gl::getProjection();
viewport = gl::getViewport();
Vec3f p = screenToWorld(mx, my);
mx = p.x;
my = p.y;
} | true |
2b70bcb4f12de81d5817667b62ef7120da38ad4b | C++ | FatemaAkter44/C-Projects | /The Painting Project.cpp | UTF-8 | 4,199 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
const double flatpaint = 30, semigloss = 35, gloss = 28;
//const double argent_labour_per_hour = 80, contract_per_hour_labour = 60;
const int gallon = 400; // 400 sqft can cover by 1 gallon
const int one_hour = 150; // 150 sqft can paint in one hour
int main()
{
double L1, W1, H1, room_sqft, num_win, win_L1, win_W1, room_Win_sqft, room_area, paint_cost, labour_cost;
double total_area = 0;
char name[100];
int i, count, total_room, num_coats, paint, paint_type, need_labour, argent_labour;
cout << " Buterfly.inc" << endl;
cout << " 420 7th ave, Brooklyn, NY, 11223" << endl;
cout << " Buterfly@gamil.com" << endl;
cout << " Phone: 347 348 3489" << endl;
cout << endl;
cout << " DATE: " << __DATE__ << endl;
cout << "CUSTOMER NAME: ";
//cin >> name;
cin.get(name, 100);
cout << endl;
cout << " How many room do you have? ";
cin >> total_room;
cout << endl;
count = 1;
for (i = 1; i <= total_room; i++)
{
cout << "Enter the Length, Width, and Height for each wall for the room " << count << " :";
cin >> L1 >> W1 >> H1;
cout << endl;
room_sqft = (W1 * H1 + L1 * H1) * 2;
// cout << room1_sqft;
cout << "How many windows do you have in room" << count << " : ";
cin >> num_win;
cout << endl;
if (num_win >= 1) {
cout << "Enter the length, and width of window(s): ";
cin >> win_L1 >> win_W1;
cout << endl;
room_Win_sqft = win_L1 * win_W1 * num_win;
//cout << "The measurement of the winddow(s) in first bedroom is: " << win_L1 * win_W1 * num_win << endl;
room_area = room_sqft - room_Win_sqft;
cout << "Area to be painted for Room " << count << ": " << room_area << " sqft" << endl;
}
else {
room_area = room_sqft;
cout << "Area to be painted for Room " << count << " : " << room_area << " sqft" << endl;
}
++count;
total_area += room_area;
}
cout << "total_area: " << total_area << endl;
cout << "Please choose paint you like to use from bellow.\n 1 for flatpaint (per galon=$30),\n 2 for semigloss (per galon= $35),\n 3 for gloss (per galon = $28) ";
cout << "Please Enter your number: ";
cin >> paint_type;
cout << "How many coats do you want to apply? ";
cin >> num_coats;
cout << endl;
// 1 gallon can cover 400 sqft
if (paint_type == 1) {
paint = (total_area / gallon) * num_coats;
cout << "Paint need : " << paint << "Galon" << endl;
paint_cost = paint * flatpaint;
cout << "Total cost for using Flatpaint: $ " << paint_cost;
}
else if (paint_type == 2) {
paint = (total_area / gallon) * num_coats;
cout << "Paint need : " << paint << "Galon" << endl;
paint_cost = paint * semigloss;
cout << "Total cost for using Flatpaint: $ " << paint_cost;
}
else if (paint_type == 3) {
paint = (total_area / gallon) * num_coats;
cout << "Paint need : " << paint << "Galon" << endl;
paint_cost = paint * gloss;
cout << "Total cost for using Flatpaint: $ " << paint_cost << endl;
}
else
{
cout << "please Choose a valid option." << endl;
}
cout << " Do you need labour? please, enter 1 for 'yes' or 2 for 'no' : ";
cin >> need_labour;
cout << endl;
if (need_labour == 1)
{
cout << " Do you need argent labour ($80 per hour)?,\n or Contract for the work done in a month ($60 per hour)." << endl;
cout << "please, enter 1 for 'need argent labour' or 2 for 'contract' : ";
cin >> argent_labour;
cout << endl;
if (argent_labour == 1) {
// 150 sqft can cover in 1 hour. total area / 150 = this * labour cost per hour
labour_cost = (total_area / one_hour) * 80;
cout << "Total Argent labour cost will be: " << labour_cost << endl;
cout << " Total due: $ " << paint_cost + labour_cost << endl;
}
else {
labour_cost = (total_area / one_hour) * 60;
cout << "Regular Total labour cost will be: " << labour_cost << endl;
cout << " Total due: $ " << paint_cost + labour_cost << endl;
}
}
else
{
cout << " Total due: $ " << paint_cost * 1 << endl;
}
cout << " Thank you for doing buesness with us";
system("pause");
return 0;
}
| true |
ed558b2727aff78f760d9eae591f365f938f4117 | C++ | GitVishwa/Algorithms_Data-structures | /Algorithms/sorting/Heap_Sort.cpp | UTF-8 | 1,499 | 3.8125 | 4 | [] | no_license | /*
Implementation of Heap sort
@Author Vishwanath Gulabal
*/
#include<iostream>
#include<stdlib.h>
#include<time.h>
#define MAX 1000
using namespace std;
int arr[MAX];
void heapify(int arr[],int num,int i_index) {
int max = i_index;
int l = 2 * i_index + 1; //left nodes
int r = 2 * i_index + 2; //right nodes
if(l < num && arr[l] > arr[max])
max = l;
if(r < num && arr[r] > arr[max])
max = r;
if(max != i_index){
swap(arr[i_index], arr[max]);
heapify(arr, i_index, max);
}
}
void heap_sort(int arr[],int num){
for(int i_index = num / 2 - 1;i_index >= 0 ;i_index--)
heapify(arr,num,i_index);
for(int i_index = num - 1;i_index >= 0;i_index--){
swap(arr[0],arr[i_index]);
heapify(arr,i_index,0);
}
}
int main(void) {
int num;
clock_t start,end;
double cpu_execute_time;
cout << "Enter the number of elements to be executed "<<endl;
cin >> num;
cout << "Enter " << num << " Elements " <<endl;
for(int i_index = 0;i_index < num;i_index++){
cin >> arr[i_index] ;
}
cout << "Entered elements before sorting " <<endl;
for(int i_index = 0;i_index < num;i_index++){
cout << arr[i_index] << endl;
}
//Heap Sort
start = clock();
heap_sort(arr,num);
end = clock();
cpu_execute_time = ((double)(end-start)) / CLOCKS_PER_SEC;
cout << "After sorting the elements are " << endl;
for(int i_index = 0;i_index < num;i_index++) {
cout << arr[i_index] << endl;
}
cout << "The time taken is " << cpu_execute_time << "seconds " << endl;
return 0;
}
| true |
8e175e444865b44431c8148e5a3d165fc4b03b44 | C++ | losvald/algo | /topcoder/CyclicSequence.cpp | UTF-8 | 4,767 | 2.65625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <list>
#include <deque>
#include <set>
#include <functional>
#include <numeric>
#include <algorithm>
#define EPS 1e-9
#define MAX
using namespace std;
typedef long long LL;
class CyclicSequence {
public:
string minimalCycle( string s ) {
string curr="";
bool found;
for(int l = 1; l < s.size(); ++l){
curr = s.substr(0, l);
found = true;
for(int it = 0; it * l < s.size(); ++it){
for(int i = 0; i < l; ++i){
if(s[it*l+i] != curr[i]) found = false;;
}
}
if(found) return curr;
}
return s;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test( int casenum = -1 ) {
if ( casenum != -1 ) {
if ( run_test_case( casenum ) == -1 )
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
return;
}
int correct = 0, total = 0;
for ( int i=0;; ++i ) {
int x = run_test_case(i);
if ( x == -1 ) {
if ( i >= 100 ) break;
continue;
}
correct += x;
++total;
}
if ( total == 0 ) {
cerr << "No test cases run." << endl;
} else if ( correct < total ) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
int verify_case( int casenum, const string &expected, const string &received, clock_t elapsed ) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if ( expected == received ) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: \"" << expected << "\"" << endl;
cerr << " Received: \"" << received << "\"" << endl;
}
return verdict == "PASSED";
}
int run_test_case( int casenum ) {
switch( casenum ) {
case 0: {
string s = "11111";
string expected = "1";
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}
case 1: {
string s = "234234234";
string expected = "234";
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}
case 2: {
string s = "567890";
string expected = "567890";
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}
case 3: {
string s = "0";
string expected = "0";
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}
case 4: {
string s = "678967";
string expected = "678967";
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}
// custom cases
/* case 5: {
string s = ;
string expected = ;
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}*/
/* case 6: {
string s = ;
string expected = ;
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}*/
/* case 7: {
string s = ;
string expected = ;
clock_t start = clock();
string received = CyclicSequence().minimalCycle( s );
return verify_case( casenum, expected, received, clock()-start );
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| true |
3f5bb4750f466c91731fa835be0602d598e20e66 | C++ | mindis/libfuzzymatch | /src/libfuzzymatch/util.h | UTF-8 | 576 | 2.875 | 3 | [
"MIT"
] | permissive | #include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include "../utf8/utf8.h"
/*
* Convert UTF-8 string to std::vector<uint32_t>
*/
void inline utf8to32(const std::string &s, std::vector<uint32_t> &vec) {
vec.assign(utf8::distance(s.cbegin(), s.cend()), 0);
utf8::utf8to32(s.cbegin(), s.cend(), vec.data());
}
/*
* Convert UTF-8 C-string to std::vector<uint32_t>
*/
void inline utf8to32(char* const s, std::vector<uint32_t> &vec) {
const size_t len(strlen(s));
vec.assign(utf8::distance(s, s+len), 0);
utf8::utf8to32(s, s+len, vec.data());
}
| true |
cfa2b479bb59408867ef70f1cc0edf53451d8a2d | C++ | Ali1849/SDS_fall2018 | /SDS392/exercise_6_6.cc | UTF-8 | 905 | 3.28125 | 3 | [] | no_license | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int start_num , current_num, next_num, iteration_count, previous_max_iteration_count;
previous_max_iteration_count = 0;
for (start_num = 1; start_num < 1001; start_num++){
current_num = start_num;
iteration_count = 0;
while (current_num>1){
if (current_num%2 == 0){
next_num = current_num/2;
} else if (current_num%2 == 1){
next_num = 3*current_num+1;
}
current_num = next_num;
iteration_count += 1;
}
if (iteration_count > previous_max_iteration_count){
cout << "start guess: " << start_num << " has "<<iteration_count<<" iterations!"<<endl;
}
if (iteration_count > previous_max_iteration_count){
previous_max_iteration_count = iteration_count;
}
}
cout<<"The longest length is: "<<previous_max_iteration_count<<endl;
return 0;
}
| true |
5d7b75ac27b9de1b30e67b372ab619e118dd8193 | C++ | codenamecpp/carnage3d | /src/TrafficManager.h | UTF-8 | 1,782 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
class DebugRenderer;
// This class generates randomly wander pedestrians and vehicles on currently visible area on map
class TrafficManager final: public cxx::noncopyable
{
friend class GameCheatsWindow;
public:
TrafficManager();
// Start or stop traffic generators
void StartupTraffic();
void CleanupTraffic();
void UpdateFrame();
void DebugDraw(DebugRenderer& debugRender);
int CountTrafficPedestrians() const;
int CountTrafficCars() const;
private:
// traffic pedestrians generation
void GeneratePeds();
void GenerateTrafficPeds(int pedsCount, GameCamera& view);
void RemoveOffscreenPeds();
int GetPedsToGenerateCount(GameCamera& view) const;
// traffic cars generation
void GenerateCars();
void GenerateTrafficCars(int carsCount, GameCamera& view);
void RemoveOffscreenCars();
int GetCarsToGenerateCount(GameCamera& view) const;
// traffic objects generation
Pedestrian* GenerateRandomTrafficCarDriver(Vehicle* vehicle);
Pedestrian* GenerateRandomTrafficPedestrian(int posx, int posy, int posz);
Pedestrian* GenerateHareKrishnas(int posx, int posy, int posz);
Vehicle* GenerateRandomTrafficCar(int posx, int posy, int posz);
// attempt to remove traffic pedestrian or vehicle
bool TryRemoveTrafficPed(Pedestrian* ped);
bool TryRemoveTrafficCar(Vehicle* car);
private:
float mLastGenPedsTime = 0.0;
float mLastGenCarsTime = 0.0f;
float mLastGenHareKrishnasTime = 0.0f;
// buffers
struct CandidatePos
{
int mMapX;
int mMapY;
int mMapLayer;
};
std::vector<CandidatePos> mCandidatePosArray;
};
extern TrafficManager gTrafficManager; | true |
4cd7ecde8a434e089e452034991b40decc85eb82 | C++ | harryQAQ/PAT-Advanced-Level | /a1038.cpp | UTF-8 | 627 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string a, string b){
return (a + b) < (b + a);
}
int main() {
int n, pos = -1;
cin >> n;
vector<string> v(n);
for (int i = 0; i < n; ++i)
cin >> v[i];
sort(v.begin(), v.end(),cmp);
string ans;
for (int i = 0; i < n; ++i)
ans += v[i];
for (int i = 0; i < ans.size(); ++i) {
if(ans[i] == '0')
continue;
pos = i;
break;
}
if(pos == -1){
printf("\n");
return 0;
}
ans = ans.substr(pos);
cout << ans;
return 0;
} | true |
b6a7c98e497fa5240aac7be18fadd781b1eb4458 | C++ | albicilla/- | /atcoder/038d2.cc | UTF-8 | 703 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct segtree{
int n;
vector<int> d;
segtree(int mx){
n = 1;
while(n<mx)n<<=1;
d = vector<int>(n<<1);
}
int getmax(int a,int b,int i=1,int l=0,int r=-1){
if(r==-1)r=n;
if(a<=l&&r<=b)return d[i];
int res=0;
int c=(l+r)>>1;
if(a < c)
}
};
int main(){
int n;
scanf("%d",&n);
vector<pair<int,int>> a(n);
for(int i=0;i<n;i++){
scanf("%d%d",&a[i].first,&a[i].second);
a[i].second *= -1
}
sort(a.begin(),a.end());
segtree t(100005);
for(int i=0;i<n;i++){
int h=a[i].second;
int now=t.getmax(0,h)+1;
ans = max(ans,now);
t.add(h,now);
}
cout<<ans<<endl;
return 0;
} | true |
e1924c419c5b84d9aa06062cbaa45262419c89ef | C++ | T208FOR2/T208FOR2_2016 | /lectures/lecture19_02/main.cpp | UTF-8 | 552 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
namespace mainfile {
int test() {
cout << "Hello!" << endl;
return 0;
}
}
namespace somethingelse {
int test() {
cout << "Hi again!" << endl;
return 0;
}
void prentaeitthvad();
}
int main()
{
using namespace mainfile;
using namespace somethingelse;
int x = mainfile::test();
prentaeitthvad();
cout << x << endl;
return 0;
}
namespace somethingelse {
void prentaeitthvad() {
cout << "eitthvad" << endl;
}
}
| true |
9d708ab1074b4c80306657b8ae49da470fc1f628 | C++ | robclu/fluidity | /tests/container_tests_host.cu | UTF-8 | 2,779 | 3.03125 | 3 | [
"MIT"
] | permissive | //==--- fluidity/tests/container_tests_host.cpp ------------ -*- C++ -*- ---==//
//
// Fluidity
//
// Copyright (c) 2018 Rob Clucas.
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//==------------------------------------------------------------------------==//
//
/// \file container_tests_host.cpp
/// \brief This file defines tests for host side container functionality.
//
//==------------------------------------------------------------------------==//
#include <fluidity/algorithm/fill.hpp>
#include <fluidity/container/array.hpp>
#include <fluidity/container/host_tensor.hpp>
#include <gtest/gtest.h>
using array_t = fluid::Array<int, 3>;
using namespace fluid;
TEST(container_host_tensor, can_create_tensor)
{
host_tensor1d<float> t(20);
EXPECT_EQ(t.size(), static_cast<decltype(t.size())>(20));
}
TEST(container_host_tensor, can_create_and_initialize_tensor)
{
const float v = 3.0f;
host_tensor1d<float> t(20, v);
for (const auto& e : t)
{
EXPECT_EQ(e, v);
}
}
TEST(container_host_tensor, can_fill_tensor)
{
host_tensor1d<int> t(20);
fluid::fill(t.begin(), t.end(), 2);
for (const auto& element : t)
{
EXPECT_EQ(element, 2);
}
}
TEST(container_host_tensor, can_fill_tensor_with_functor)
{
host_tensor1d<int> t(20);
std::size_t count = 0;
fluid::fill(t.begin(), t.end(), [&count] (auto& iterator)
{
iterator = count++;
});
count = 0;
for (const auto& element : t)
{
EXPECT_EQ(element, count++);
}
}
TEST(container_host_tensor, can_resize_tensor)
{
host_tensor1d<int> t;
t.resize(30);
std::size_t count = 0;
fluid::fill(t.begin(), t.end(), [&count] (auto& iterator)
{
iterator = count++;
});
count = 0;
for (const auto& element : t)
{
EXPECT_EQ(element, count++);
}
}
TEST(container_host_tensor, can_convert_to_and_from_device_tensor)
{
host_tensor1d<int> t;
t.resize(30);
std::size_t count = 0;
fluid::fill(t.begin(), t.end(), [&count] (auto& iterator)
{
iterator = count++;
});
auto dt = t.as_device();
auto ht = dt.as_host();
count = 0;
for (const int& element : ht)
{
EXPECT_EQ(element, count++);
}
}
TEST(container_array, can_create_array)
{
array_t a{2};
EXPECT_EQ(a.size(), 3);
EXPECT_EQ(a[0], 2);
EXPECT_EQ(a[1], 2);
EXPECT_EQ(a[2], 2);
}
TEST(container_array, can_copy_array)
{
array_t a{2};
array_t b{a};
auto c = b;
EXPECT_EQ(b.size(), 3);
EXPECT_EQ(b[0], 2);
EXPECT_EQ(b[1], 2);
EXPECT_EQ(b[2], 2);
EXPECT_EQ(c.size(), 3);
EXPECT_EQ(c[0], 2);
EXPECT_EQ(c[1], 2);
EXPECT_EQ(c[2], 2);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |