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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a1a03e68410a0801cb348da44840b6c8f91c5389 | C++ | bmjoy/ZenonEngine | /znEngine/SceneFunctional/SceneNode/MeshComponent.h | UTF-8 | 926 | 2.515625 | 3 | [] | no_license | #pragma once
#include "ComponentBase.h"
class
__declspec(uuid("403E886D-7BD7-438B-868D-AC4380830716"))
CMeshComponent : public CComponentBase
{
public:
typedef std::vector<std::shared_ptr<IMesh>> MeshList;
public:
CMeshComponent(std::shared_ptr<SceneNode3D> OwnerNode);
virtual ~CMeshComponent();
/**
* Add a mesh to this scene node.
* The scene node does not take ownership of a mesh that is set on a mesh
* as it is possible that the same mesh is added to multiple scene nodes.
* Deleting the scene node does not delete the meshes associated with it.
*/
virtual void AddMesh(std::shared_ptr<IMesh> mesh);
virtual void RemoveMesh(std::shared_ptr<IMesh> mesh);
virtual const MeshList& GetMeshes();
// ISceneNodeComponent
virtual bool Accept(IVisitor& visitor) override;
private:
MeshList m_Meshes;
std::mutex m_MeshMutex;
}; | true |
8eef66a4197663c8b81da4510e1ed2b095c41b15 | C++ | sickwiz/ds-algo | /pointers/character_pointer.cpp | UTF-8 | 339 | 3.359375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char c[]="aamir"; //
char *c1=&c[0]; // pointing to a string
cout<<c1<<endl; //1
char c2='a';
char *c3=&c2;
cout<<c3<<endl; //2
// AT 1 AND 2, IT WILL KEEP PRINTING UNTIL A NULL CHARACTER I.E \0 IS FOUND;
// char *ptr="asaad"; THIS IS NOT ALLOWED
} | true |
0c7d6775fff70524f7f3ca571fc2d4da7acafd9e | C++ | JoeDumoulin/CS172 | /Homework/HW6Example/testComplex.cpp | UTF-8 | 1,176 | 3.375 | 3 | [] | no_license | // testComplex.cpp - test the complex number class
// compile with g++ testComplex.cpp Complex.cpp -o test
//
#include <iostream>
#include "Complex.h"
using namespace std;
int main()
{
// Test printing complex numbers
Complex c1(2,5);
Complex c2;
cout << c1.toString() << endl;
cout << c2.toString() << endl;
Complex c3(4,7);
cout << c1.toString() << " + " << c3.toString() << " = " << c1.add(c3).toString() << endl;
cout << c1.toString() << " - " << c3.toString() << " = " << c1.subtract(c3).toString() << endl;
cout << c1.toString() << " * " << c3.toString() << " = " << c1.multiply(c3).toString() << endl;
cout << c1.toString() << " / " << c3.toString() << " = " << c1.divide(c3).toString() << endl;
cout << c1.toString() << " += " << c3.toString() << " = " << (c1 += c3).toString() << endl;
cout << c1.toString() << " -= " << c3.toString() << " = " << (c1 -= c3).toString() << endl;
cout << c1.toString() << " *= " << c3.toString() << " = " << (c1 *= c3).toString() << endl;
cout << c1.toString() << " /= " << c3.toString() << " = " << (c1 /= c3).toString() << endl;
return 0;
}
| true |
17887c31c8b4833fec06bb8f76b3282bb18e5a39 | C++ | elft3r/AlgoLab13 | /problems/w08/Collisions/Collisions2.cpp | UTF-8 | 1,962 | 2.75 | 3 | [] | no_license | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <iostream>
#include <vector>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaunay_triangulation_2<K> Triangulation;
typedef Triangulation::Vertex_iterator Vertex_iterator;
typedef K::Point_2 Point;
typedef CGAL::Segment_2<K> Segment;
int main() {
std::ios_base::sync_with_stdio(false);
int testCases;
std::cin >> testCases;
for(int i=0; i<testCases; i++) {
int numPlanes;
K::FT minDistance;
std::cin >> numPlanes>> minDistance;
std::vector<Point> planes(numPlanes);
Triangulation t;
for(int j=0; j<numPlanes;j++) {
int x, y;
std::cin >> x >> y;
//t.insert(Triangulation::Point(x,y));
planes[j] = Point(x,y);
}
t.insert(planes.begin(), planes.end());
int numEndangered = 0;
K::FT minSquaredDistance = minDistance * minDistance;
for(Vertex_iterator v=t.finite_vertices_begin();
v!=t.finite_vertices_end(); v++) {
// std::cout<<v->point() << std::endl;
Triangulation::Edge_circulator c = t.incident_edges(v);
K::FT minDist;
bool firstEdge = true;
do {
if(!t.is_infinite(c)) {
Triangulation::Vertex_handle v1 = c->first->vertex((c->second+1)%3);
Triangulation::Vertex_handle v2 = c->first->vertex((c->second+2)%3);
K::FT candidateDist = Segment(v1->point(), v2->point()).squared_length();
// std::cout << "candidate min dist for " << v->point() << " between " << v1->point() << " " << v2->point() << " is " << candidateDist << std::endl;
if(firstEdge == true || minDist > candidateDist) {
minDist = candidateDist;
firstEdge = false;
}
}
} while(++c != t.incident_edges(v));
if(!firstEdge && minDist < minSquaredDistance)
numEndangered++;
}
std::cout << numEndangered << std::endl;
}
}
| true |
1d6afd7ff9a94357c81b49a0a478f4f4350028ae | C++ | littleboys/Chairman-Mao | /Chairman Mao/GuardOwnedStates.h | UTF-8 | 1,955 | 2.71875 | 3 | [] | no_license | #ifndef GUARD_OWNED_STATES_H
#define GUARD_OWNED_STATES_H
#include "State.h"
struct Telegram;
class Guard;
class GuardGlobleState : public State<Guard>
{
private:
GuardGlobleState(){}
//copy ctor and assignment should be private
GuardGlobleState(const GuardGlobleState&);
GuardGlobleState& operator=(const GuardGlobleState&);
public:
//this is a singleton
static GuardGlobleState* Instance();
virtual void Enter(Guard* guard);
virtual void Execute(Guard* guard);
virtual void Exit(Guard* guard);
virtual bool OnMessage(Guard* agent, const Telegram& msg);
};
class CollectInformation : public State<Guard>
{
private:
CollectInformation(){}
//copy ctor and assignment should be private
CollectInformation(const CollectInformation&);
CollectInformation& operator=(const CollectInformation&);
public:
//this is a singleton
static CollectInformation* Instance();
virtual void Enter(Guard* guard);
virtual void Execute(Guard* guard);
virtual void Exit(Guard* guard);
virtual bool OnMessage(Guard* agent, const Telegram& msg);
};
//------------------------------------------------------------------------
//
// Entity will go to a bank and deposit any nuggets he is carrying. If the
// Guard is subsequently wealthy enough he'll walk home, otherwise he'll
// keep going to get more gold
//------------------------------------------------------------------------
class ReportToMao : public State<Guard>
{
private:
ReportToMao(){}
//copy ctor and assignment should be private
ReportToMao(const ReportToMao&);
ReportToMao& operator=(const ReportToMao&);
public:
//this is a singleton
static ReportToMao* Instance();
virtual void Enter(Guard* guard);
virtual void Execute(Guard* guard);
virtual void Exit(Guard* guard);
virtual bool OnMessage(Guard* agent, const Telegram& msg);
};
#endif | true |
86c17e6fec87988aeb6d692bda97736b5a229338 | C++ | xjrueda/fixprime | /src/Node.cpp | UTF-8 | 13,088 | 2.890625 | 3 | [] | no_license | /*
* File: Node.cpp
* Author: DeveloperPrime
*
* Created on September 27, 2014, 9:57 PM
*/
#include "Node.h"
#include "Protocol.h"
#include "Component.h"
namespace fprime {
Node::Node() {
}
Node::Node(NodeType t) : _type(t), isRequired(false) {
}
Node::Node(const Node& other) :
_type(other._type),
isRequired(other.isRequired),
field(other.field),
protocolPtr(other.protocolPtr),
componentPtr(other.componentPtr) {
if (other._type == fprime::Node::NodeType::FIELD_NODE || other._type == fprime::Node::NodeType::REPEATING_GROUP) {
fprime::DataHolderFactory factory;
this->value = factory.create(other.field->getDataType());
const string val = other.value->get();
this->value->set(val);
}
childsVector.clear();
childsByFieldId.clear();
for (NodeVector::const_iterator itr = other.childsVector.begin(); itr != other.childsVector.end(); itr++) {
NodePtr newNode(new Node(**itr));
childsVector.push_back(newNode);
if (other._type == fprime::Node::NodeType::ROOT_NODE || other._type == fprime::Node::NodeType::GROUP_INSTANCE)
childsByFieldId[newNode->getField()->getId()] = newNode;
if (other._type == fprime::Node::NodeType::REPEATING_GROUP)
childsByFieldId[childsVector.size()] = newNode;
}
// if (_type != fprime::Node::NodeType::ROOT_NODE)
// cout << "Node " << field->getId() << " copied" << endl;
// else
// cout << "Root Node " << " copied" << endl;
}
Node::~Node() {
}
fprime::Node& Node::operator=(const fprime::Node& other) {
_type = other._type;
value = other.value;
isRequired = other.isRequired;
field = other.field;
protocolPtr = other.protocolPtr;
componentPtr = other.componentPtr;
fprime::DataHolderFactory factory;
if (other._type == fprime::Node::NodeType::FIELD_NODE) {
fprime::DataHolderFactory factory;
value = factory.create(other.field->getDataType());
this->value = factory.create(other.field->getDataType());
const string val = other.value->get();
this->value->set(val);
}
childsVector.clear();
childsByFieldId.clear();
for (NodeVector::const_iterator itr = other.childsVector.begin(); itr != other.childsVector.end(); itr++) {
NodePtr newNode(new Node(**itr));
childsVector.push_back(newNode);
if (other._type == fprime::Node::NodeType::ROOT_NODE || other._type == fprime::Node::NodeType::GROUP_INSTANCE)
childsByFieldId[newNode->getField()->getId()] = newNode;
if (other._type == fprime::Node::NodeType::REPEATING_GROUP)
childsByFieldId[childsVector.size()] = newNode;
}
return *this;
}
// Getters
fprime::Field::FieldPtr Node::getField() {
if (field == nullptr)
throw runtime_error("No field setted for the node");
return field;
}
//
const string Node::getValue() {
return value->get();
}
//
Node::NodeType Node::getType() {
return _type;
}
// // Setters
void Node::setType(NodeType nodeType) {
_type = nodeType;
}
void Node::setField(fprime::Field::FieldPtr fld) {
try {
if (fld == nullptr)
throw runtime_error("Invalid field assigment to node.");
fprime::DataHolderFactory factory;
value = factory.create(fld->getDataType());
if (_type == GROUP_INSTANCE) {
throw runtime_error("The method is not available for groups instances.");
}
if (_type == ROOT_NODE) {
stringstream ss;
ss << "This method is not available for root nodes. setting field " << fld->getId();
throw runtime_error(ss.str());
}
// if (_type == REPEATING_GROUP) {
// value->set("0");
// }
field = fld;
} catch (exception& e) {
throw runtime_error("at Node.setField: " + string(e.what()));
}
}
void Node::setValue(string val) {
if (_type == REPEATING_GROUP)
throw runtime_error("Repeating group values are calculated");
value->set(val);
}
void Node::setRequired(bool reqFlag) {
isRequired = reqFlag;
}
void Node::setProtocol(fprime::Protocol* prot) {
protocolPtr = prot;
}
void Node::setComponent(fprime::Component::ComponentPtr compPtr) {
componentPtr = compPtr;
}
// //Group operations
void Node::appendChild(fprime::Node::NodePtr nodePtr) {
if (!nestingRule(_type, nodePtr->getType())) {
throw InvalidNodeNesting(decodeNodeType(_type), decodeNodeType(nodePtr->getType()));
}
if (nodePtr->getType() == fprime::Node::GROUP_INSTANCE) {
unsigned int instanceId = (this->childsByFieldId.size()) + 1;
childsByFieldId[instanceId] = nodePtr;
}
if ((nodePtr->getType() == fprime::Node::REPEATING_GROUP) || (nodePtr->getType() == fprime::Node::FIELD_NODE)) {
childsByFieldId[nodePtr->field->getId()] = nodePtr;
}
childsVector.push_back(nodePtr);
}
void Node::appendGroupInstance() {
if (_type != Node::NodeType::REPEATING_GROUP) {
throw std::runtime_error("appendGroupInstance is only allowed for BlockRepeating.");
} else {
Node::NodePtr newInstance(new Node(Node::NodeType::GROUP_INSTANCE));
newInstance->resolveComponent(this->componentPtr);
this->appendChild(newInstance);
this->value->set(boost::lexical_cast<string>(childsByFieldId.size()));
}
}
//operators
fprime::Node::NodePtr Node::getChild(unsigned int fieldId) {
if (_type == Node::NodeType::REPEATING_GROUP) {
throw runtime_error("The operator () is not available for repeating groups. Use []");
}
NodeMap::iterator search = childsByFieldId.find(fieldId);
if (search != childsByFieldId.end()) {
return search->second;
} else {
stringstream msg;
msg << "at Node.operator(): Node for field " << fieldId << " does not exists";
throw InvalidField(msg.str());
}
}
fprime::Node::NodePtr Node::getInstance(unsigned int instanceIndex) {
if (_type != Node::NodeType::REPEATING_GROUP) {
throw runtime_error("The operator[] is only available for repeating groups.");
}
NodeMap::iterator search = childsByFieldId.find(instanceIndex);
if (search != childsByFieldId.end())
return search->second;
else
throw runtime_error("at Node.operator[] : Invalid repeating group instance");
}
void Node::stringify(string& outputString, bool& isBody, unsigned int& bodyLength) {
try {
switch (_type) {
case ROOT_NODE:
case GROUP_INSTANCE:
case REPEATING_GROUP:
{
if (_type == REPEATING_GROUP) {
unsigned int id = this->getField()->getId();
this->addValuePair(outputString, id, this->getValue());
}
for (int i = 0; i < childsVector.size(); i++) {
childsVector[i]->stringify(outputString, isBody, bodyLength);
}
break;
}
case FIELD_NODE:
{
if (!isBody) {
if (this->getField()->getId() == 9)
isBody = true;
}
int prelen = outputString.size();
unsigned int id = this->getField()->getId();
this->addValuePair(outputString, id, this->getValue());
if (isBody && this->getField()->getId() != 9)
bodyLength += (outputString.size() - prelen);
break;
}
}
} catch (exception& e) {
cout << "at Node.stringify : " << e.what() << endl;
}
}
void Node::addValuePair(string &s, unsigned int fieldId, string val) {
try {
if (!val.empty()) {
// if (!s.empty())
// s += ";";
s = s + boost::lexical_cast<string>(fieldId) + string("=") + boost::lexical_cast<string>(val) + "\001";
}
} catch (exception& e) {
cout << "exception at Node.addValuePair : " << e.what();
}
}
bool Node::nestingRule(NodeType parentType, NodeType nestedType) {
bool result = false;
switch (parentType) {
case ROOT_NODE:
case GROUP_INSTANCE:
{
if (nestedType == ROOT_NODE || nestedType == GROUP_INSTANCE)
result = false;
else
result = true;
break;
}
case FIELD_NODE:
{
result = false;
break;
}
case REPEATING_GROUP:
{
if (nestedType != GROUP_INSTANCE)
result = false;
else
result = true;
break;
}
}
return result;
}
string Node::decodeNodeType(NodeType t) {
string typeStr;
switch (t) {
case ROOT_NODE:
{
typeStr = "ROOT_NODE";
break;
}
case GROUP_INSTANCE:
{
typeStr = "GROUP_INSTANCE";
break;
}
case FIELD_NODE:
{
typeStr = "FIELD_NODE";
break;
}
case REPEATING_GROUP:
{
typeStr = "REPEATING_GROUP";
break;
}
default:
{
typeStr = "INVALID";
break;
}
}
return typeStr;
}
void Node::resolveComponent(fprime::Component::ComponentPtr componentPtr) {
// process fields
vector<fprime::Component::FieldT> fields = componentPtr->getFields();
vector<fprime::Component::FieldT>::iterator iter;
for (iter = fields.begin(); iter < fields.end(); iter++) {
fprime::Component::FieldT fieldt = *iter;
string fieldType = fieldt.field->getDataType();
fprime::Node::NodePtr child(new Node());
// if (fieldType == "NUMINGROUP") {
// child.setType(fprime::Node::REPEATING_GROUP);
// if (this->componentPtr == nullptr)
// throw runtime_error("at Node.resolveComponent: Component for repeating group " + fieldt.field->getName() + " was not found.");
// else {
// fprime::Field::FieldPtr ctrlFieldPtr = this->componentPtr->getControlField();
// child.setField(ctrlFieldPtr);
// }
// // cout << "Repeating control field resolved " << child.getField()->getId() << endl;
// } else {
//
// };
child->setType(fprime::Node::FIELD_NODE);
child->setField(fieldt.field);
child->setRequired(fieldt.isRequired);
child->setProtocol(protocolPtr);
appendChild(child);
}
// process components
vector<fprime::Component::ComponentPtr> nestedComponents = componentPtr->getNestedComponents();
vector<fprime::Component::ComponentPtr>::iterator cmpIter;
for (cmpIter = nestedComponents.begin(); cmpIter < nestedComponents.end(); cmpIter++) {
fprime::Component::ComponentPtr nestedComponent = *cmpIter;
if (nestedComponent->getType() == "BlockRepeating") {
fprime::Field::FieldPtr ctrlFieldPtr = nestedComponent->getControlField();
fprime::Node::NodePtr child(new Node());
child->setType(fprime::Node::REPEATING_GROUP);
child->setField(ctrlFieldPtr);
//TODO Define required
child->setRequired(false);
child->setProtocol(protocolPtr);
child->setComponent(nestedComponent);
appendChild(child);
} else {
resolveComponent(nestedComponent);
}
}
}
} | true |
100fd3861a05c1e578ad19bc503855b44620e9a8 | C++ | zylzjucn/Leetcode | /1200~1299/1209. Remove All Adjacent Duplicates in String II.cpp | UTF-8 | 547 | 2.796875 | 3 | [] | no_license | class Solution {
public:
string removeDuplicates(string str, int k) {
string res;
stack<pair<char, int>> s;
for (const auto& c : str) {
if (!s.empty() && s.top().first == c)
s.top().second++;
else
s.emplace(c, 1);
if (s.top().second == k)
s.pop();
}
for (; !s.empty(); s.pop())
res.append(s.top().second, s.top().first);
reverse(res.begin(), res.end());
return res;
}
};
| true |
36a9b58924e18fc2d4e1ec0cfb5a14d9a5812ff8 | C++ | StarThinking/MOBBS | /src/ceph-0.72.2-src/common/sharedptr_registry.hpp | UTF-8 | 4,165 | 2.625 | 3 | [] | no_license | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef CEPH_SHAREDPTR_REGISTRY_H
#define CEPH_SHAREDPTR_REGISTRY_H
#include <map>
#include <memory>
#include "common/Mutex.h"
#include "common/Cond.h"
/**
* Provides a registry of shared_ptr<V> indexed by K while
* the references are alive.
*/
template <class K, class V>
class SharedPtrRegistry {
public:
typedef std::tr1::shared_ptr<V> VPtr;
typedef std::tr1::weak_ptr<V> WeakVPtr;
int waiting;
private:
Mutex lock;
Cond cond;
map<K, pair<WeakVPtr, V*> > contents;
class OnRemoval {
SharedPtrRegistry<K,V> *parent;
K key;
public:
OnRemoval(SharedPtrRegistry<K,V> *parent, K key) :
parent(parent), key(key) {}
void operator()(V *to_remove) {
{
Mutex::Locker l(parent->lock);
typename map<K, pair<WeakVPtr, V*> >::iterator i =
parent->contents.find(key);
if (i != parent->contents.end() &&
i->second.second == to_remove) {
parent->contents.erase(i);
parent->cond.Signal();
}
}
delete to_remove;
}
};
friend class OnRemoval;
public:
SharedPtrRegistry() :
waiting(0),
lock("SharedPtrRegistry::lock")
{}
bool empty() {
Mutex::Locker l(lock);
return contents.empty();
}
bool get_next(const K &key, pair<K, VPtr> *next) {
pair<K, VPtr> r;
{
Mutex::Locker l(lock);
VPtr next_val;
typename map<K, pair<WeakVPtr, V*> >::iterator i =
contents.upper_bound(key);
while (i != contents.end() &&
!(next_val = i->second.first.lock()))
++i;
if (i == contents.end())
return false;
if (next)
r = make_pair(i->first, next_val);
}
if (next)
*next = r;
return true;
}
bool get_next(const K &key, pair<K, V> *next) {
VPtr next_val;
Mutex::Locker l(lock);
typename map<K, pair<WeakVPtr, V*> >::iterator i =
contents.upper_bound(key);
while (i != contents.end() &&
!(next_val = i->second.first.lock()))
++i;
if (i == contents.end())
return false;
if (next)
*next = make_pair(i->first, *next_val);
return true;
}
VPtr lookup(const K &key) {
Mutex::Locker l(lock);
waiting++;
while (1) {
typename map<K, pair<WeakVPtr, V*> >::iterator i =
contents.find(key);
if (i != contents.end()) {
VPtr retval = i->second.first.lock();
if (retval) {
waiting--;
return retval;
}
} else {
break;
}
cond.Wait(lock);
}
waiting--;
return VPtr();
}
VPtr lookup_or_create(const K &key) {
Mutex::Locker l(lock);
waiting++;
while (1) {
typename map<K, pair<WeakVPtr, V*> >::iterator i =
contents.find(key);
if (i != contents.end()) {
VPtr retval = i->second.first.lock();
if (retval) {
waiting--;
return retval;
}
} else {
break;
}
cond.Wait(lock);
}
V *ptr = new V();
VPtr retval(ptr, OnRemoval(this, key));
contents.insert(make_pair(key, make_pair(retval, ptr)));
waiting--;
return retval;
}
unsigned size() {
Mutex::Locker l(lock);
return contents.size();
}
void remove(const K &key) {
Mutex::Locker l(lock);
contents.erase(key);
cond.Signal();
}
template<class A>
VPtr lookup_or_create(const K &key, const A &arg) {
Mutex::Locker l(lock);
waiting++;
while (1) {
typename map<K, pair<WeakVPtr, V*> >::iterator i =
contents.find(key);
if (i != contents.end()) {
VPtr retval = i->second.first.lock();
if (retval) {
waiting--;
return retval;
}
} else {
break;
}
cond.Wait(lock);
}
V *ptr = new V(arg);
VPtr retval(ptr, OnRemoval(this, key));
contents.insert(make_pair(key, make_pair(retval, ptr)));
waiting--;
return retval;
}
friend class SharedPtrRegistryTest;
};
#endif
| true |
eb5e0981ea3d4e3c34ee96766bad9dd162d4ee84 | C++ | gd2dg/pat-basic | /code/46.cpp | UTF-8 | 618 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int n;
int num1 = 0, num2 = 0;
cin >> n;
for (size_t i = 0; i < n; i++) {
int aWin = 0, bWin = 0;
int aSay, bSay, aShow, bShow;
cin >> aSay >> aShow >> bSay >> bShow;
int sum = aSay + bSay;
if (aShow == sum) {
aWin = 1;
++num1;
}
if (bShow == sum) {
bWin = 1;
++num2;
}
if (aWin + bWin == 2) {
--num1;
--num2;
}
}
cout << num2 << " " << num1;
return 0;
}
| true |
e7a4ed3fd7c1d3986da99cda2d4593af3d0ec586 | C++ | nyeBaker/MPhys | /Project/Monte_carlo.cpp | UTF-8 | 6,172 | 3.03125 | 3 | [] | no_license | /*
Author: Aneirin John Baker
Date: 23/09/17
Description: The script is where the HMC algorithm will take place. The intergration methods will be
housed here and will be executed here.
*/
#include "Monte_carlo.h"
#define Oscillator_flip 1
void lattice_Evolution(vector<vector<double> > &lattice,unsigned int length,double t_step,unsigned int iterations)
{
FILE * out;
out = fopen("HMC_OUT","w");
// p-0,q-1
vector<double> v1(2,0);
vector<vector<double> > State(length,v1);
vector<double> v(2,0);
vector<vector<double> >temp_State(length,v);
default_random_engine generator(random_device{}());
normal_distribution<double> distribution(0.0,1.0);
double acceptance =0;
for(unsigned int i=0;i<length;i++)
{
State[i][0]=0;
State[i][1]=0;
temp_State[i][0]=0;
temp_State[i][1]=0;
}
unsigned int result_no=0;
//run main algorithm
for(unsigned int i = 0; i<iterations;i++)
{
default_random_engine generator(random_device{}());
for(unsigned int j = 0; j<length;j++)
{
State[j][0] = distribution(generator);
}
acceptance += hmcAlgorithm(length,t_step,State,temp_State);
if(i % 5 == 0)
{
//copy results into results array
for(unsigned int k = 0;k<length;k++)
{
lattice[result_no][k] = State[k][1];
}
//fprintf(out, "%f %f\n", State[5][1],State[5][0]);
//fprintf(out, "--------------------\n");
result_no++;
}
}
printf("The Acceptance Rate is %f percent \n",(acceptance*100)/(double) iterations);
}
int hmcAlgorithm(unsigned int length,double t_step,vector<vector<double> > &old_state,vector<vector<double> > &temp_State)
{
/*
double min=0;
unsigned int steps = 15;
double H_old=0,H_new=0;
H_old=lattice_Hamiltonian(old_state,length,t_step);
//half step in the p
//printf("################\n");
for(unsigned int j = 0;j<length;j++)
{
//printf("%f %f\n",old_state[j][0],old_state[j][1]);
temp_State[j][0] = old_state[j][0] - (0.5*t_step * old_state[j][1]);
temp_State[j][1] = old_state[j][1];
}
//printf("-------------------\n");
//full step in p and q for n steps
for(unsigned int i = 0;i<steps;i++)
{
//update all q's
for(unsigned int j = 0;j<length;j++)
{
temp_State[j][1] = temp_State[j][1] + (t_step * temp_State[j][0]);
}
if(i != steps-1)
{
temp_State[0][0] = temp_State[0][0] - (t_step * temp_State[0][1]);
for(unsigned int j = 1;j<length-1;j++)
{
temp_State[j][0] = temp_State[j][0] - (t_step * temp_State[j][1]);
}
temp_State[length-1][0] = temp_State[length-1][0] - (t_step * temp_State[length-1][1]);
}
}
//half step in the p
for(unsigned int j = 0;j<length;j++)
{
temp_State[j][0] = temp_State[j][0] - (0.5*t_step * temp_State[j][1]);
}
for(unsigned int j=0;j<length;j++)
{
//printf("%f %f\n",temp_State[j][0],temp_State[j][1]);
}
//printf("################\n");
H_new = lattice_Hamiltonian(temp_State,length,t_step);
//metroplis update
double r = ((double) rand() / (RAND_MAX));
min = (1 < exp(H_old - H_new)) ? 1 : exp(H_old - H_new);
//printf("Hamiltonians: %f %f %f %f %f\n",H_old,H_new,exp(H_old-H_new),r,min);
if(r < min)
{
//accept
for(unsigned int i = 0;i<length;i++)
{
old_state[i][1] = temp_State[i][1];
}
//printf("welp\n");
}
*/
double min=0;
unsigned int steps = 25;
double H_old=0,H_new=0;
H_old=lattice_Hamiltonian(old_state,length,t_step);
//half step in the p
temp_State[0][0] = old_state[0][0] - (0.5*t_step * (old_state[0][1] - (old_state[1][1]+old_state[length-1][1]-(2*old_state[0][1]))));
for(unsigned int j = 1;j<length-1;j++)
{
temp_State[j][0] = old_state[j][0] - (0.5*t_step * (old_state[j][1] - (old_state[j+1][1]+old_state[j-1][1]-(2*old_state[j][1]))));
temp_State[j][1] = old_state[j][1];
}
temp_State[length-1][0] = old_state[length-1][0] - (0.5*t_step * (old_state[length-1][1] - (old_state[0][1]+old_state[length-2][1]-(2*old_state[length-1][1]))));
//full step in p and q for n steps
for(unsigned int i = 0;i<steps;i++)
{
//update all q's
for(unsigned int j = 0;j<length;j++)
{
temp_State[j][1] = temp_State[j][1] + (t_step * temp_State[j][0]);
}
if(i != steps-1)
{
temp_State[0][0] = temp_State[0][0] - (t_step * (temp_State[0][1] - ((temp_State[1][1]+temp_State[length-1][1]-(2*temp_State[0][1])))));
for(unsigned int j = 1;j<length-1;j++)
{
temp_State[j][0] = temp_State[j][0] - (t_step * (temp_State[j][1] - ((temp_State[j+1][1]+temp_State[j-1][1]-(2*temp_State[j][1])))));
}
temp_State[length-1][0] = temp_State[length-1][0] - (t_step * (temp_State[length-1][1] - ((temp_State[0][1]+temp_State[length-2][1]-(2*temp_State[length-1][1])))));
}
}
//half step in the p
temp_State[0][0] = temp_State[0][0] - (0.5*t_step * (temp_State[0][1] - (temp_State[1][1]+temp_State[length-1][1]-(2*temp_State[0][1]))));
for(unsigned int j = 1;j<length-1;j++)
{
temp_State[j][0] = temp_State[j][0] - (0.5*t_step * (temp_State[j][1] - (temp_State[j+1][1]+temp_State[j-1][1]-(2*temp_State[j][1]))));
}
temp_State[length-1][0] = temp_State[length-1][0] - (0.5*t_step * (temp_State[length-1][1] - (temp_State[0][1]+temp_State[length-2][1]-(2*temp_State[length-1][1]))));
H_new = lattice_Hamiltonian(temp_State,length,t_step);
//metroplis update
double r = ((double) rand() / (RAND_MAX));
min = (1 < exp(H_old - H_new)) ? 1 : exp(H_old - H_new);
if(r < min)
{
//accept
for(unsigned int i = 0;i<length;i++)
{
old_state[i][1] = temp_State[i][1];
}
return 1;
}
return 0;
}
double lattice_Hamiltonian(vector<vector<double> > state,unsigned int length,double t_step)
{
double H=0;
//loop for all sites which are not effected by periodic BC's
for(unsigned int i=0;i<length-1;i++)
{
H += hamiltonian(state[i][0],state[i][1],state[i+1][1],t_step);
}
//Periodic BC sites
H += hamiltonian(state[length-1][0],state[length-1][1],state[0][1],t_step);
return H;
}
double hamiltonian(double p,double q,double q_plus,double t_step)
{
double h=0;
//h = (p*p*0.5) + (pow((q_plus - q),2)*0.5*(1/t_step*t_step)) + (0.5*q*q);
h = (p*p*0.5) + (pow((q_plus - q),2)*0.5) + (0.5*q*q*t_step);
//h = (p*p*0.5) + (0.5*q*q);
return h;
}
| true |
732b32319fd8a7a8a44f930b4dde7b110355a832 | C++ | systemtwo/CellPhoneEscape | /main.cpp | UTF-8 | 2,716 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <SFML/Graphics.hpp>
#include "ResourceManager.h"
#include "StateManager.h"
#include "TitleState.h"
#include "LoaderState.h"
#include "GameState.h"
#include "GameOverState.h"
#include <typeinfo>
#include <cstdio>
//If you see a white pixel that is supposed to be an image, try looking to see if sprite has image linked
int main(void) {
//Buffer for output stream
//This makes output faster at a cost of being unsure when it is output
//Because the flush to OS function is expensive
char buf[1024];
//setvbuf(stdout, buf, _IOLBF, 1024);
//Main function
//Setup game objs
sf::RenderWindow App(sf::VideoMode(800,600,32), "Satellite Game"); //Make the window
//App.ShowMouseCursor(false); //Hide the cursor
ResourceManager RM; //Make RM
//Make a pointer to the window and RM to pass to StateManager
sf::RenderWindow *AppPointer = &App;
ResourceManager * RMPointer = &RM;
const sf::Input & Input = App.GetInput(); //Make Input
StateManager SM(AppPointer, RMPointer, Input); //Make StateManager
App.SetFramerateLimit(30); //Limit Framerate to standard refresh rate
//Should probably make a loader state for loading resources at beginning
//Then calls switchstate to title
//This doesn't even need to have a display, just make sure it is initialized
// The init() function will load everything
LoaderState LS;
SM.storeState(&LS);
//TitleStateTesting
//Make TitleState
TitleState TS(AppPointer); //This should passed AppPointer instead of input, as input can be found with AppPointer
SM.storeState(&TS);
//Make GameState
GameState GS(AppPointer, RMPointer);
SM.storeState(&GS);
//Make GameOverState
GameOverState GOS(AppPointer, RMPointer);
SM.storeState(&GOS);
try {
SM.switchState("Title");
} catch (int e) {
std::cout << "Could not find state title" << std::endl;
}
std::cout << "Switched States" << std::endl;
//EndTS Testing
//Start game loop
while (App.IsOpened()) {
//Get events
sf::Event Event;
while (App.GetEvent(Event)) { //Iterate thru event queue, store events in Event and process
if (Event.Type == sf::Event::Closed || (Event.Type == sf::Event::KeyPressed && Event.Key.Code == sf::Key::Escape)) {
App.Close();
//std::cout << "I died here?" << std::endl;
exit(0); // Strange... I didn't need this before (this is to prevent crash after closing)
//return 0;
//std::cout << "Nothing here!" << std::endl;
}
//else if (Event.Type == sf::Event::MouseMoved) {
// std::cout << "The mouse moved!" << std::endl;
//}
}
App.Clear(); //Clear screen
//App.Draw(s);
SM.checkSwitchState();
SM.updateState();
SM.drawState();
App.Display(); //Update Screen
}
return 0;
}
| true |
4a83212a4e7f8f22b447c007ceb5610ed9c803f6 | C++ | Jeevz10/kattis-code | /wheresmyinternet.cpp | UTF-8 | 1,001 | 3.109375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void DFS (int i,vector < vector<int> > &AL,vector<int> &visited) {
visited[i] = 1;
for (auto &v: AL[i]) {
if (!visited[v]) {
DFS(v,AL,visited);
}
}
}
int main() {
int houses,num;
cin >> houses >> num;
vector < vector<int> > AL;
AL.assign(houses, vector<int> ());
for (int i = 0;i < num;i++) {
int u,v;
cin >> u >> v;
u--;
v--;
AL[u].push_back(v);
AL[v].push_back(u);
}
vector<int> visited;
int CC = 0;
visited.assign(houses,0);
set<int> rank;
for (int i = 0;i < houses;i++) {
if (visited[i] == 0) {
CC++;
if (CC == 1) {
DFS(i,AL,visited);
}
}
}
int status = 0;
for (int i = 0;i < houses;i++) {
if (visited[i] == 0) {
status = 1;
int num = i;
num++;
// cout << num << endl;
rank.insert(num);
}
}
if (status == 0) {
cout << "Connected\n"; // gotta check if all visited or not
}
else {
for (auto &it: rank) {
cout << it << endl;
}
}
return 0;
}
| true |
ce29fb9d2cca6ade9381d6ee2c2cc0372a6e6928 | C++ | shramov/tll | /src/tll/util/argparse.h | UTF-8 | 4,816 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2021 Pavel Shramov <shramov@mexmat.net>
*
* tll is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*
* Command line parser inspired by python argparse and used an idea from Simon Schneegans
*
* http://schneegans.github.io/tutorials/2019/08/06/commandline
*/
#ifndef _TLL_UTIL_ARGPARSE_H
#define _TLL_UTIL_ARGPARSE_H
#include <fmt/format.h>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
#include <tll/util/result.h>
#include <tll/util/conv.h>
namespace tll::util
{
class ArgumentParser
{
public:
using value_type = std::variant<bool *, int *, unsigned *, std::string *, std::vector<std::string> *>;
ArgumentParser(const ArgumentParser &) = delete;
ArgumentParser(ArgumentParser &&) = delete;
explicit ArgumentParser(std::string_view description) : _description(description)
{
add_argument({"-h", "--help"}, "display help and exit", &help);
}
template <typename T>
void add_argument(const std::vector<std::string> &flags, std::string_view help, T * value)
{
_arguments.emplace_back(argument_type {flags, std::string(help), value});
}
std::string format_help() const;
expected<int, std::string> parse(int argc, char *argv[]) const;
bool help = false;
private:
struct argument_type {
std::vector<std::string> flags;
std::string help;
value_type value;
};
std::string _description;
std::vector<argument_type> _arguments;
};
inline std::string ArgumentParser::format_help() const
{
std::ostringstream os;
os << _description << std::endl;
size_t align = 0;
for (auto &arg : _arguments) {
size_t size = 0;
for (auto &flag : arg.flags)
size += flag.size() + 2;
align = std::max(align, size);
}
for (auto const &arg : _arguments) {
std::string flags;
size_t size = 0;
os << " ";
for (auto &flag : arg.flags) {
if (size) {
os << ", ";
size += 2;
}
os << flag;
size += flag.size();
}
for (; size < align; size++)
os << ' ';
os << arg.help << std::endl;
}
return os.str();
}
inline expected<int, std::string> ArgumentParser::parse(int argc, char *argv[]) const
{
std::map<std::string_view, const argument_type *> flags;
std::vector<const argument_type *> positional;
for (auto &arg : _arguments) {
for (auto &f : arg.flags) {
if (f.size() && f[0] == '-')
flags[f] = &arg;
else
positional.push_back(&arg);
}
}
auto posit = positional.begin();
int i = 1; // argv[0] is program name
while (i < argc) {
std::string_view flag(argv[i++]);
std::optional<std::string_view> value;
if (flag.size() < 1)
return error("Flag size < 2: '" + std::string(flag) + "'");
size_t sep = flag.find('=');
if (flag == "--")
return i;
const argument_type * arg = nullptr;
if (flag.size() > 1 && flag[0] == '-') { // Normal argument
if (flag[1] != '-') {
if (flag.size() > 2) { // Short flag
value = flag.substr(2);
flag = flag.substr(0, 2);
}
} else if (sep != flag.npos) {
value = flag.substr(sep + 1);
flag = flag.substr(0, sep);
}
auto it = flags.find(flag);
if (it == flags.end())
return error("Invalid flag: '" + std::string(flag) + "'");
arg = it->second;
if (!std::holds_alternative<bool *>(arg->value) && !value) {
if (i >= argc)
return error("No value for flag '" + std::string(flag) + "'");
value = argv[i++];
}
} else { // Positional argument
if (posit == positional.end())
return error("No positional arguments defined for '" + std::string(flag) + "'");
arg = *posit;
if (!std::holds_alternative<std::vector<std::string> *>(arg->value))
posit++;
value = flag;
}
if (std::holds_alternative<bool *>(arg->value)) {
auto ptr = std::get<bool *>(arg->value);
if (value)
*ptr = (*value == "true");
else
*ptr = true;
} else if (std::holds_alternative<std::string *>(arg->value)) {
*std::get<std::string *>(arg->value) = std::string(*value);
} else if (std::holds_alternative<int *>(arg->value)) {
auto v = tll::conv::to_any<int>(*value);
if (!v)
return error(fmt::format("Invalid int value '{}' for flag '{}': {} ", *value, flag, v.error()));
*std::get<int *>(arg->value) = *v;
} else if (std::holds_alternative<unsigned *>(arg->value)) {
auto v = tll::conv::to_any<unsigned>(*value);
if (!v)
return error(fmt::format("Invalid unsigned value '{}' for flag '{}': {} ", *value, flag, v.error()));
*std::get<unsigned *>(arg->value) = *v;
} else if (std::holds_alternative<std::vector<std::string> *>(arg->value)) {
std::get<std::vector<std::string> *>(arg->value)->push_back(std::string(*value));
}
}
return i;
}
} // namespace tll::util
#endif // _TLL_UTIL_ARGPARSE_H
| true |
e7e6fe60f2fd1e8e5847edf1bd63f9471a5a9bec | C++ | ferrolho/feup-contests | /USACO/Section 1.3/Prime Cryptarithm/miguelsandim.cpp | UTF-8 | 3,298 | 3.0625 | 3 | [] | no_license | /*
ID: migueel1
PROG: crypt1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int numbers[9];
int subset_number;
unsigned int solution_number;
bool existsInSubSet(int num)
{
for (int i=0; i < subset_number; i++)
if (numbers[i] == num)
return true;
return false;
}
bool validSolution(int top[], int bottom[])
{
//printf("Vou testar com os valores\nTop: %d,%d,%d;\nBot: %d,%d\n\n",top[2],top[1],top[0],
//bottom[1],bottom[0]); getchar();
int partial1[3], partial2[3], sum, carry=0;
for (unsigned int i=0; i < 2; i++)
{
for (unsigned int j=0; j < 3; j++)
{
int mul = bottom[i]*top[j];
//printf("Mul deu %d\n",mul); getchar();
if (carry)
{mul+= carry; carry = 0;}
if (mul >= 10)
carry = mul/10;
//printf("Mul com carry %d\n",mul); getchar();
mul = mul%10;
//printf("Mul final %d\n",mul); getchar();
if (!existsInSubSet(mul))
return false;
//else printf("passou\n");
if (i==0)
partial1[j] = mul;
else
partial2[j] = mul;
if (j == 2 && carry) // se sobrou carry, não pode
return false;
//else printf("passou\n");
}
}
//printf("Agora as somas\npartial1: %d,%d,%d;\npartial2: %d,%d,%d\n\n",partial1[2],partial1[1],partial1[0],
//partial2[2],partial2[1],partial2[0]); getchar();
sum = partial1[1] + partial2[0];
//printf("Soma deu %d\n",sum); getchar();
if (sum >= 10)
carry = 1;
sum = sum%10;
//printf("Soma final deu %d\n",sum); getchar();
if (!existsInSubSet(sum))
return false;
//else printf("passou\n");
sum = partial1[2] + partial2[1];
//printf("Soma deu %d\n",sum); getchar();
if (carry)
{sum+= carry; carry=0;}
//printf("Soma com carry %d\n",sum); getchar();
if (sum >= 10)
carry = sum/10;
sum = sum%10;
//printf("Soma final deu %d\n",sum); getchar();
if (!existsInSubSet(sum))
return false;
//else printf("passou\n");
sum = partial2[2];
//printf("Soma deu %d\n",sum); getchar();
if (carry)
{sum+= carry; carry=0;}
//printf("Soma com carry %d\n",sum); getchar();
if (sum >= 10)
carry = sum/10;
sum = sum%10;
//printf("Soma final deu %d\n",sum); getchar();
if (!existsInSubSet(sum))
return false;
//else printf("passou\n");
return carry==0;
}
int main()
{
// receive input
ifstream input("crypt1.in");
input >> subset_number;
for(int i=0; i < subset_number; i++)
input >> numbers[i];
input.close();
// VARIABLE DECLARATION
int top[3], bottom[2], solution_number=0;
for(int i=0; i < subset_number; i++)
for(int j=0; j < subset_number; j++)
for(int k=0; k < subset_number; k++)
for(int l=0; l < subset_number; l++)
for(int m=0; m < subset_number; m++)
{
top[0] = numbers[i]; top[1] = numbers[j]; top[2] = numbers[k];
bottom[0] = numbers[l]; bottom[1] = numbers[m];
//top[0] = 9; top[1] = 7; top[2] = 2;
//bottom[0] = 8; bottom[1] = 7;
if (validSolution(top,bottom))
solution_number++;
}
//SAVE OUTPUT
ofstream output("crypt1.out");
output << solution_number << endl;
output.close();
return 0;
}
| true |
0fe60fd88c2e5f53540988c8bef77543f8e8101e | C++ | riobun/142nb | /Classes/NetworkManager.h | GB18030 | 8,284 | 2.546875 | 3 | [] | no_license | // NetworkManager: շҪӿ
// οMultiplayer game programming, Joshua Glazer, Sanjay Madhav
// ģõ 2019.06.05
#ifndef _NETWORK_MANAGER_H_
#define _NETWORK_MANAGER_H_
class NetworkManager
{
public:
// Packet Types
//sent when first trying to join
static const uint32_t kHelloCC = 'HELO';
//sent when accepted by master peerӭ
static const uint32_t kWelcomeCC = 'WLCM';
//sent as a reply to HELO if it isn't the master peer
static const uint32_t kNotMasterPeerCC = 'NOMP';
//sent as a reply to HELO if the game can't be joined (either full or already started)ܼ
static const uint32_t kNotJoinableCC = 'NOJN';
//sent by new player to all non-master peers after being accepted
static const uint32_t kIntroCC = 'INTR';
//contains data for a particular turn
static const uint32_t kTurnCC = 'TURN';
//notifies peers that the game will be starting soonϿʼ
static const uint32_t kStartCC = 'STRT';
static const int kMaxPacketsPerFrameCount = 10;//ÿ10
enum NetworkManagerState
{
NMS_Unitialized, //δʼ
NMS_Hello, //
NMS_Lobby, //Ϣ
//everything above this should be the pre-game/lobby/connection
NMS_Starting, //ڿʼϷʼ
NMS_Playing, //ڽϷ
NMS_Delay, //ӳ
};
// Ψһʵ
static unique_ptr< NetworkManager > sInstance;
//ʼΪ
static bool StaticInitAsMasterPeer( uint16_t inPort, const string& inName );
//ʼΪֻ
static bool StaticInitAsPeer( const SocketAddress& inMPAddress, const string& inName );
NetworkManager();
~NetworkManager();
void ProcessIncomingPackets(); //ѭδ
void SendOutgoingPackets(); //ѭδ
private:
void UpdateSayingHello( bool inForce = false ); //ʱHello
void SendHelloPacket(); //Hello
void UpdateStarting(); //Ϸʼ
void UpdateSendTurnPacket(); //ÿݰ
void TryAdvanceTurn(); //ǷӳԼ
public:
//հ:NMS_Hello, Lobby, Playing, Delay
void ProcessPacket( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );
private:
void ProcessPacketsHello( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//Hello״̬
void HandleNotMPPacket( InputMemoryBitStream& inInputStream );//·
void HandleWelcomePacket( InputMemoryBitStream& inInputStream );//õӭid
void ProcessPacketsLobby( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//Ϣ״̬
void HandleHelloPacket( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//Ϣӵhello
void HandleIntroPacket( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//Ϣӵintro
void HandleStartPacket( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//Ϣӵstart
void ProcessPacketsPlaying( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//Ϸ״̬
void HandleTurnPacket( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//
void ProcessPacketsDelay( InputMemoryBitStream& inInputStream, const SocketAddress& inFromAddress );//ڵȴ״̬
public:
void HandleConnectionReset( const SocketAddress& inFromAddress );//ûϿ
void SendPacket( const OutputMemoryBitStream& inOutputStream, const SocketAddress& inToAddress );
void TryStartGame();//ͼʼϷ
const WeightedTimedMovingAverage& GetBytesReceivedPerSecond() const { return mBytesReceivedPerSecond; }
const WeightedTimedMovingAverage& GetBytesSentPerSecond() const { return mBytesSentPerSecond; }
void SetDropPacketChance( float inChance ) { mDropPacketChance = inChance; }
float GetDropPacketChance() const { return mDropPacketChance; }
void SetSimulatedLatency( float inLatency ) { mSimulatedLatency = inLatency; } //ģӳ
float GetSimulatedLatency() const { return mSimulatedLatency; } //ģӳ
bool IsMasterPeer() const { return mIsMasterPeer; }
float GetTimeToStart() const { return mTimeToStart; }
EntityPtr GetGameObject( uint32_t inNetworkId ) const; //idõϷid
EntityPtr RegisterAndReturn( Entity* inGameObject ); //עµϷ
void RegisterGameObject(EntityPtr inGameObject);
void UnregisterGameObject( Entity* inGameObject ); //ȡϷid
NetworkManagerState GetState() const { return mState; }
int GetPlayerCount() const { return mPlayerCount; }
int GetTurnNumber() const { return mTurnNumber; }
int GetSubTurnNumber() const { return mSubTurnNumber; }
uint32_t GetMyPlayerId() const { return mPlayerId; }
private:
void AddToNetworkIdToGameObjectMap( EntityPtr inGameObject );//idϷidmap
void RemoveFromNetworkIdToGameObjectMap( EntityPtr inGameObject );//ƳidϷidmap
uint32_t GetNewNetworkId();
uint32_t ComputeGlobalCRC(); //ѭ
bool InitAsMasterPeer( uint16_t inPort, const string& inName );
bool InitAsPeer( const SocketAddress& inMPAddress, const string& inName );
bool InitSocket( uint16_t inPort );//UDPSocket,,nonblocking
class ReceivedPacket
{
public:
ReceivedPacket( float inReceivedTime, InputMemoryBitStream& inInputMemoryBitStream, const SocketAddress& inAddress );
const SocketAddress& GetFromAddress() const { return mFromAddress; }
float GetReceivedTime() const { return mReceivedTime; }
InputMemoryBitStream& GetPacketBuffer() { return mPacketBuffer; }
private:
float mReceivedTime;
InputMemoryBitStream mPacketBuffer;
SocketAddress mFromAddress;
};
//ProcessIncomingPacket()˳
void ReadIncomingPacketsIntoQueue(); //ȡ
void ProcessQueuedPackets(); //еpackets
void UpdateBytesSentLastFrame(); //״̬
void UpdateHighestPlayerId( uint32_t inId );
void EnterPlayingState();
//these should stay ordered!
typedef map< uint32_t, SocketAddress > IntToSocketAddrMap;
typedef map< uint32_t, string > IntToStrMap;
typedef map< uint32_t, TurnData > IntToTurnDataMap;
typedef map< uint32_t, EntityPtr > IntToGameObjectMap;
typedef unordered_map< SocketAddress, uint32_t > SocketAddrToIntMap;
bool CheckSync( IntToTurnDataMap& inTurnMap );//Ƿڴİ
queue< ReceivedPacket, list< ReceivedPacket > > mPacketQueue;
IntToGameObjectMap mNetworkIdToGameObjectMap; //id -- ʵָ
IntToSocketAddrMap mPlayerToSocketMap; //id -- socketַ
SocketAddrToIntMap mSocketToPlayerMap; //socketַ -- id
public:
IntToStrMap mPlayerNameMap; //id -- ֣Ϊpubllic
private:
//this stores all of our turn information for every turn since game start
vector< IntToTurnDataMap > mTurnData;
UDPSocketPtr mSocket;
SocketAddress mMasterPeerAddr;
WeightedTimedMovingAverage mBytesReceivedPerSecond;
WeightedTimedMovingAverage mBytesSentPerSecond;
NetworkManagerState mState;
int mBytesSentThisFrame;
std::string mName;
float mDropPacketChance;
float mSimulatedLatency;
float mTimeOfLastHello;
float mTimeToStart;
int mPlayerCount;
int mIntroCount;
//we track the highest player id seen in the event
//the master peer d/cs and we need a new master peer
//who can assign ids
uint32_t mHighestPlayerId;
uint32_t mNewNetworkId;
uint32_t mPlayerId;
int mTurnNumber;
int mSubTurnNumber;
bool mIsMasterPeer;
};
#endif // !_NETWORK_MANAGER_H_ | true |
756456a5c8c5599ab28fac042fbcecb039fbf93c | C++ | Fanqingle/- | /Desktop/个人春招/华为/华为机试/051 组成一个偶数最接近的2个质数/051.cpp | UTF-8 | 1,093 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
bool isPrimeNum(int n)
{
if(1 == n || 4 == n)
return false;
if(2 == n || 3 == n || 5 == n)
return true;
int v = (int)sqrt(n) + 1;
bool bOk = true;
for(int i = 2 ; i <= v ; i++)
{
if(n % i == 0)
{
bOk = false;
break;
}
}
return bOk;
}
int main()
{
int n;
while(cin >> n)
{
int a,b;
if(n % 4 == 0)
{
a = n / 2 - 1;
b = n / 2 + 1;
while(a>1&&b<n&&!(isPrimeNum(a)&&isPrimeNum(b)))
{
a -= 2;
b += 2;
}
cout << a << "\n" << b << endl;
}
else
if(n % 2 == 0)
{
a = n / 2;
b = n / 2;
while(a>1&&b<n&&!(isPrimeNum(a)&&isPrimeNum(b)))
{
a -= 2;
b += 2;
}
cout << a << "\n" << b << endl;
}
}
return 0;
} | true |
7b0a7d96e3190fc12fea59be076a8a17a3346efa | C++ | clumpytuna/ABBYY_2018 | /Functor/Functor.h | UTF-8 | 9,340 | 3.359375 | 3 | [] | no_license | // Автор: Михаил Анухин
// Описание: Класс CFunctor<typename T, TYPELIST_N(...) >
#ifndef Functor_h
#define Functor_h
#include "TypeList.h"
// Шаблонный класс реализующий возможности функтора.
// Можно поместить в класс функтор, функцию или метод класса и использовать их стандартным образом,
// вызывая оператор (). Для обертки параметров используются TypeList. Количество аргументов в данной
// реализации ограничено двумя, но может быть расширено.
// Пример использования:
// void function( int i, double d );
// CFunctor<void, TYPELIST_2( int, double )> f( &function );
// f( 4, 4.5 );
template <class ResultType, class TypeList>
class CFunctor {
public:
CFunctor() : callableObject( nullptr ) {}
// Конструктор из функции или функтора
template <typename Callable>
CFunctor( const Callable& f ) : callableObject( new CFunctionHandler<CFunctor, Callable > ( f ) ) {}
// Конструктор из указателя на объект и его метода
template <class ObjectPtr, typename ObjectMethodPtr>
CFunctor( const ObjectPtr& object, ObjectMethodPtr method ) :
callableObject( new CMethodHandler<CFunctor, ObjectPtr, ObjectMethodPtr > ( object, method ) ) {}
~CFunctor() { delete callableObject; }
// Оператор присваивания помещает функцию или функтор в объект.
// Важно! Не стоит его использовать для присваивания метода
template <typename Callable>
void operator = ( const Callable& f );
// Привязывает функцию или функтор
template <typename Callable>
void BindFunction( const Callable& f );
// Привязывет метод класса
template <class ObjectPtr, typename ObjectMethodPtr>
void BindMethod( const ObjectPtr& object, ObjectMethodPtr method );
// Типы параметров функции, метода или функтора
typedef typename GetTypeAt<TypeList, 0, NullType>::Result FirstParameterType;
typedef typename GetTypeAt<TypeList, 1, NullType>::Result SecondParameterType;
// Вызывает функцию, функтор или метод
ResultType operator()() const;
ResultType operator()( FirstParameterType firstParameter ) const;
ResultType operator()( FirstParameterType firstParameter, SecondParameterType secondParameter ) const;
private:
// Интерфейс для вызываемого объекта.
// Определен для каждого из возможных количеств параметров о фиксированного N.
// Данная реализация поддерживает до 2 параметров.
// Количество параметров может быть увеличено до необходимого числа.
template <typename ResType, typename ClassTypeList>
class ICallable;
// Указатель на вызываемый объект
ICallable <ResultType, TypeList>* callableObject;
// Интерфейс для вызываемого объекта без параметров
template <typename ResType>
class ICallable<ResType, NullType> {
public:
virtual ResType operator()() const = 0;
virtual ~ICallable() {};
};
// Интерфейс для вызываемого объекта с 1 параметром
template <typename ResType, typename ParameterType>
class ICallable<ResType, TYPELIST_1( ParameterType )> {
public:
virtual ResType operator()( ParameterType ) const = 0;
virtual ~ICallable() {}
};
// Интерфейс для вызываемого объекта с 2 параметрами
template <typename ResType, typename ParameterTypeFirst, typename ParameterTypeSecond>
class ICallable<ResType, TYPELIST_2( ParameterTypeFirst, ParameterTypeSecond )> {
public:
virtual ResType operator()( ParameterTypeFirst, ParameterTypeSecond ) const = 0;
virtual ~ICallable() {}
};
// Класс вызываемого объекта. Хранит функцию или функтор.
// Определен оператор () для всевозможных количеств параметров до фиксированного N.
// Данная реализация поддерживает до 2 параметров.
// Количество параметров может быть увеличено до необходимого числа.
// Через оператор() происходит вызов функции или функтора.
template <class ParentFunctor, typename Callable>
class CFunctionHandler: public ICallable<ResultType, TypeList> {
public:
CFunctionHandler( const Callable& f ) : callableObject( f ) {}
// Вызывает функцию, функтор или метод для разного числа параметров
ResultType operator()() const
{
return callableObject();
}
ResultType operator()( typename ParentFunctor::FirstParameterType firstParameter ) const
{
return callableObject( firstParameter );
}
ResultType operator()( typename ParentFunctor::FirstParameterType firstParameter,
typename ParentFunctor::SecondParameterType secondParameter ) const
{
return callableObject( firstParameter, secondParameter );
}
private:
// Фунция или функтор, которые мы будем вызывать
Callable callableObject;
};
// Класс вызываемого объекта. Хранит указатель на метод и укзатель на объект, метод которого мы вызываем.
// Определен оператор () для всевозможных количеств параметров до фиксированного N.
// Данная реализация поддерживает до 2 параметров.
// Количество параметров может быть увеличено до необходимого числа.
// Через оператор() происходит вызов метода.
template <class ParentFunctor, typename ObjectPointer, typename ObjectMethodPointer>
class CMethodHandler : public ICallable<ResultType, TypeList> {
public:
CMethodHandler( const ObjectPointer& object_, ObjectMethodPointer method_ ) :
object( object_ ),
method( method_ ) { }
// Вызывает метод для разного числа параметров
ResultType operator()() const
{
return ( ( *object ).*method )();
}
ResultType operator()( typename ParentFunctor::FirstParameterType firstParameter ) const
{
return ( ( *object ).*method )( firstParameter );
}
ResultType operator()( typename ParentFunctor::FirstParameterType firstParameter,
typename ParentFunctor::SecondParameterType secondParameter ) const
{
return ( ( *object ).*method )( firstParameter, secondParameter );
}
private:
// Указатель на класс, метод которого будет вызыван
ObjectPointer object;
// Указатель на метод класса
ObjectMethodPointer method;
};
};
template<class ResultType, class TypeList>
template <typename Callable>
void CFunctor<ResultType, TypeList>::operator = ( const Callable& f )
{
delete callableObject;
callableObject = new CFunctionHandler<CFunctor, Callable>( f );
}
template<class ResultType, class TypeList>
ResultType CFunctor<ResultType, TypeList>::operator()() const
{
return ( *callableObject )();
}
template<class ResultType, class TypeList>
ResultType CFunctor<ResultType, TypeList>::operator()( FirstParameterType firstParameter ) const
{
return ( *callableObject )( firstParameter );
}
template<class ResultType, class TypeList>
ResultType CFunctor<ResultType, TypeList>::operator()( FirstParameterType firstParameter, SecondParameterType secondParameter ) const
{
return ( *callableObject )( firstParameter, secondParameter );
}
template<class ResultType, class TypeList>
template <class ObjectPointer, typename ObjectMethodPointer>
void CFunctor<ResultType, TypeList>::BindMethod( const ObjectPointer& object, ObjectMethodPointer method )
{
delete callableObject;
callableObject = new CMethodHandler<CFunctor, ObjectPointer, ObjectMethodPointer > ( object, method );
}
template<class ResultType, class TypeList>
template <typename Callable>
void CFunctor<ResultType, TypeList>::BindFunction( const Callable& f )
{
delete callableObject;
callableObject = new CFunctionHandler<CFunctor, Callable > ( f );
}
#endif // Functor_h
| true |
733c19019210b80da3f3fa7fa5e1e3c621af4717 | C++ | firewood/topcoder | /atcoder/arc_090/d.cpp | UTF-8 | 1,003 | 3.109375 | 3 | [] | no_license | // D.
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
typedef long long LL;
struct Edge {
int node;
LL dist;
};
struct Node {
LL value;
vector <Edge> edges;
bool vis;
};
vector<Node> nodes;
bool check(int n, LL value) {
if (nodes[n].vis) {
return nodes[n].value == value;
}
nodes[n].value = value;
nodes[n].vis = true;
for (Edge &edge : nodes[n].edges) {
if (!check(edge.node, value + edge.dist)) {
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
int n, m;
cin >> n >> m;
nodes.resize(n);
for (int i = 0; i < m; ++i) {
int l, r;
LL d;
cin >> l >> r >> d;
--l, --r;
nodes[l].edges.push_back({r, d});
nodes[r].edges.push_back({l, -d});
}
bool ans = true;
for (int i = 0; i < n; ++i) {
if (!nodes[i].vis && !check(i, 0)) {
ans = false;
}
}
cout << (ans ? "Yes" : "No") << endl;
return 0;
}
| true |
ccf708a3d9f670c2b02a235857463e21b36d563a | C++ | TheMoira/Semesters_1-4 | /CPP/lab08b/ExceptType.cpp | UTF-8 | 829 | 3.359375 | 3 | [] | no_license | #include "ExceptType.h"
#include <iostream>
ExceptType2::ExceptType2() : ExceptType(2), exp(new ExceptType4())
{
std::cout<<"***konstruktor ExceptType2\n";
}
void ExceptType1::PrzedstawSie() const
{
std::cout<<"Nazywam sie Except1\n";
}
void ExceptType2::PrzedstawSie() const
{
std::cout<<"Nazywam sie Except2\n";
}
void ExceptType3::PrzedstawSie() const
{
std::cout<<"Nazywam sie Except3\n";
}
void ExceptType4::PrzedstawSie() const
{
std::cout<<"Nazywam sie Except4\n";
}
void HandleExcept(ExceptType * exp)
{
std::cout<<"przetworz wyjatek ";
switch(exp->getType())
{
case 1:
std::cout<<" Except1 o adresie: "<<exp;
case 2:
std::cout<<" Except2 o adresie: "<<exp;
default:
std::cout<<" inny: ";
}
throw exp->getExp();
} | true |
cabbd6b0b9457b265e16dd8da80fca6699ca4ee2 | C++ | DingZhan/Data-Structure-and-Algorithm-Chinese-PTA- | /07. 六度空间/a.cpp | UTF-8 | 2,617 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
//Floyd算法,一定要记住中间结点k一定要放在最外层循环
#define MAX_N 10001
//如果结点i,j之间有一条直接的通路,则该元素值为1; 初始时,矩阵全部为0;
//后续扫描时,该矩阵用来存储顶点i,j之间的连通距离
unsigned char mat[MAX_N][MAX_N];
int main()
{
//设置高速I/O
std::ios::sync_with_stdio(false);
int N, M, i, a, b, j, k, v;
cin>>N>>M;
//获得邻接矩阵
for(i=0; i<M; ++i)
{
cin>>a>>b;
mat[a][b] = 1;
mat[b][a] = 1;
}
//Floyd算法,中间结点k一定要放在最外层循环
for(k=1; k<=N; ++k)
{
for(i=1; i<=N; ++i)
{
if(i==k)
continue;
//如果i->k 或 k->j之间目前还没有路径,则忽略本次循环
if(mat[i][k]==0)
continue;
for(j=1; j<=N; ++j)
{
if(i==j||j==k)
continue;
//如果i->k 或 k->j之间目前还没有路径,则忽略本次循环
if(mat[k][j]==0)
continue;
v = (int)mat[i][k] + mat[k][j];
//如果这条累加的路径距离和超过了6,则忽略;这样做也是避免溢出
if(v>6)
continue;
//如果当前i->j之间还没有路径,则用i->k + k->j路径
if(mat[i][j]==0)
mat[i][j] = v;
else if(mat[i][j]>v) //如果当前路径距离超过i->k + k->j路径,则刷新
mat[i][j] = v;
/*
//考虑对称矩阵问题,更新对称元素;貌似这步骤不需要
if(mat[j][i]==0 && mat[i][j]!=0)
mat[j][i] = mat[i][j];
else if(mat[j][i]>mat[i][j] && mat[i][j]!=0)
mat[j][i] = mat[i][j];
*/
}
}
}
//一一打印每个节点度小于等于6的百分比
for(i=1; i<=N; ++i)
{
//初始k=1,因为结点i自己也算在有效的邻接顶点内
k=1;
for(j=1; j<=N; ++j)
{
if(i==j)
continue;
//结点j和结点i之间路径的距离<=6,则是一个有效的邻接顶点
//mat[i][j]==0表示i,j之间没有有效的路
if(mat[i][j]>0 && mat[i][j]<=6)
++k;
}
cout<<i<<": "<<std::fixed<<std::setprecision(2)<<k*100.0/N<<"%\n";
}
}
| true |
4a8ebaa75d34be101c5511fba43e99877407b959 | C++ | andj97/RG165-bethebachelor | /src/camera.cpp | UTF-8 | 1,968 | 2.78125 | 3 | [] | no_license | //
// Created by nikjan on 3/11/19.
//
#include <GL/glut.h>
#include <cmath>
#include "camera.hpp"
#define FIRST_VIEW (1)
#define SECOND_VIEW (2)
#define THIRD_VIEW (3)
#define FOURTH_VIEW (4)
Camera::Camera(double eyeX, double eyeY, double eyeZ, double centerX, double centerY, double centerZ, double upX,
double upY, double upZ) : eyeX(eyeX), eyeY(eyeY), eyeZ(eyeZ), centerX(centerX), centerY(centerY),
centerZ(centerZ), upX(upX), upY(upY), upZ(upZ) {}
extern float z_pos, y_pos, u;
void Camera::setLook(int id) {
switch (id) {
case FIRST_VIEW:
setEyeX(0); setEyeY(0.6 + y_pos); setEyeZ(5 + z_pos);
setCenterX(0); setCenterY(0); setCenterZ(z_pos-2);
break;
case SECOND_VIEW:
setEyeX(0); setEyeY(2.2 + y_pos); setEyeZ(z_pos + 3);
setCenterX(0); setCenterY(0); setCenterZ(z_pos-2);
break;
case THIRD_VIEW:
setEyeX(2); setEyeY(4); setEyeZ(5+z_pos);
setCenterX(0); setCenterY(0); setCenterZ(z_pos + 1.5);
break;
case FOURTH_VIEW:
setEyeX(0); setEyeY(1.6 + 3*sin(u)); setEyeZ(3+z_pos);
setCenterX(0); setCenterY(0); setCenterZ(z_pos-2);
}
setUpX(0); setUpY(1); setUpZ(0);
gluLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
void Camera::setEyeX(double eyeX) {
Camera::eyeX = eyeX;
}
void Camera::setEyeY(double eyeY) {
Camera::eyeY = eyeY;
}
void Camera::setEyeZ(double eyeZ) {
Camera::eyeZ = eyeZ;
}
void Camera::setCenterX(double centerX) {
Camera::centerX = centerX;
}
void Camera::setCenterY(double centerY) {
Camera::centerY = centerY;
}
void Camera::setCenterZ(double centerZ) {
Camera::centerZ = centerZ;
}
void Camera::setUpX(double upX) {
Camera::upX = upX;
}
void Camera::setUpY(double upY) {
Camera::upY = upY;
}
void Camera::setUpZ(double upZ) {
Camera::upZ = upZ;
}
| true |
768cc59252663904d0a0a80ea003ac8e4f49307d | C++ | blorin948/cpp | /day04/ex03/MateriaSource.cpp | UTF-8 | 1,122 | 3.296875 | 3 | [] | no_license | #include "MateriaSource.hpp"
MateriaSource::MateriaSource(void) : _count(0)
{
_save[0] = NULL;
_save[1] = NULL;
_save[2] = NULL;
_save[3] = NULL;
}
MateriaSource::MateriaSource(MateriaSource const &c)
{
*this = c;
}
MateriaSource &MateriaSource::operator=(MateriaSource const &c)
{
deleteAll();
int i = 0;
while (i < c._count)
{
_save[i] = c.getAmateria(i)->clone();
i++;
}
return (*this);
}
MateriaSource::~MateriaSource()
{
deleteAll();
}
Amateria *MateriaSource::getAmateria(int idx) const
{
if (idx < _count)
{
return (_save[idx]);
}
else
return (NULL);
}
void MateriaSource::deleteAll(void)
{
int i = 0;
while (i < _count)
{
delete _save[i];
i++;
}
_count = 0;
}
void MateriaSource::learnMateria(Amateria *c)
{
if (this->_count < 4)
{
_save[_count] = c;
_count++;
}
else
{
std::cout << "Could not learn this Materia, inventory is full" << std::endl;
}
}
Amateria *MateriaSource::createMateria(std::string const & type)
{
int i = 0;
while (i < this->_count)
{
if (_save[i]->getType() == type)
{
return (_save[i]->clone());
}
i++;
}
return (0);
} | true |
84f93a83d795297649a8f4a1d3918404f58f3876 | C++ | Peteef/GFK_Projekt | /main.cpp | UTF-8 | 960 | 2.9375 | 3 | [] | no_license | #include "Figure.h"
#include "FigureArray.h"
#include <iostream>
#include "Line.h"
int main()
{
FigureArray arr;
arr.AddLine(0, 0, 1, 1, 5, 6, 7);
arr.Get()[0]->Get();
arr.AddCircle(5, 7, 5, 1, 4, 5, 7, 8, 65);
arr.Get()[1]->Get();
arr.AddRectangle(3, 4, 5, 26, 4, 6, 43, 3, 6, 6);
arr.Get()[2]->Get();
int coordA[4] = { 1, 2, 3, 4 };
arr.AddPolygon(coordA, 2, 34, 5, 4, 3, 3, 2);
arr.Get()[3]->Get();
arr.AddCPolygon(100, 100, 20, 5, 34, 34, 34, 34, 34, 34);
arr.Get()[4]->Get();
for(int i = 0; i < arr.Size(); i++)
{
std::cout << arr.Get()[i] << std::endl;
}
std::cout << "Wielkosc tablicy: " << arr.Size() << std::endl;
arr.SaveToFile("../vect.txt");
FigureArray arr2;
arr2.LoadFromFile("../vect.txt");
for (int i = 0; i < arr2.Size(); i++)
{
std::cout << arr2.Get()[i] << std::endl;
}
std::cout << "Wielkosc tablicy: " << arr2.Size() << std::endl;
system("PAUSE");
}
| true |
9af741c041a179f24cc22c8933b492e6e27ebc7c | C++ | wook0605/wook0605.github.io | /C++/Phone_Book/test.cpp | UTF-8 | 2,435 | 3.46875 | 3 | [
"MIT"
] | permissive |
//
// main.cpp
// cpptest
//
// the template Created by Jong-Chul Yoon on 13/04/2019.
// Copyright ? 2019 Jong-Chul Yoon. All rights reserved.
// Coder : KiWook Lee
#include "phonebook.h"
using namespace std;
int main() {
int input;
char N_temp[20];
Person P_temp;
Phonebook book;
cout << "전화번호부 V0.2 프로그램을 시작합니다" <<endl;
while(1)
{
cout << "1.사용자입력, 2.사용자검색, 3.정렬후출력, 4.사용자삭제, 5.종료" <<endl;
cin >> input;
switch (input) {
case 1:
cout << "사용자의 이름, 전화번호, 주소, 이메일을 순서대로 입력하시오." <<endl;
cin >> P_temp.m_name >> P_temp.m_phone_number >> P_temp.m_address >> P_temp.m_email;
book.insert_person(P_temp);
break;
case 2:
cout << "검색할 사용자의 이름을 입력하시오." <<endl;
cin >> N_temp;
if (book.search_person(N_temp,&P_temp))
{
cout << "이름이 " << N_temp << "인 사용자는 전화번호가 " << P_temp.m_phone_number << " 입니다" <<endl;
}
else
{
cout << "사용자를 찾지 못하였습니다." << endl;
}
break;
case 3:
cout << "정렬한 상용자를 출력합니다." << endl;
book.sort_and_print();
break;
case 4:
cout << "삭제할 사용자의 이름을 입력하시오." <<endl;
cin >> N_temp;
if (book.delete_person(N_temp))
{
cout << N_temp << " 사용자를 삭제하였습니다" <<endl;
}
else
{
cout << "삭제할 사용자를 찾지 못하였습니다." << endl;
}
break;
case 5:
cout << "프로그램을 종료합니다." <<endl;
return 0;
default:
cout << "잘못된 입력. 다시 입력하세요" <<endl;
break;
}
}
return 0;
}
| true |
7713d9096d556cef5489b99ef7275fd7d8ff3825 | C++ | MarsXiaolei/Design-Patterns | /单例模式.cpp | GB18030 | 1,661 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Singelton {
public:
static Singelton* getInstance()
{
if (instance==NULL)
{
instance = new Singelton;
}
m_count++;
return instance;
}
int getCount()
{
return m_count;
}
private:
Singelton()
{
instance = NULL;
m_count = 0;
cout << "캯 singelton() ִ" << endl;
}
~Singelton() {};
static Singelton *instance;
static int m_count;
};
Singelton* Singelton::instance = NULL;
int Singelton::m_count = 0;
class Singelton2 {
public:
static Singelton2* getInstance()
{
m_count++;
return instance;
}
int getCount()
{
return m_count;
}
private:
Singelton2()
{
instance = NULL;
m_count = 0;
}
~Singelton2() {};
static Singelton2* instance;
static int m_count;
};
Singelton2* Singelton2::instance = NULL;
int Singelton2::m_count = 0;
int main()
{
Singelton *singer = Singelton::getInstance();
cout << singer->getCount() << endl;
Singelton *singer2 = Singelton::getInstance();
cout << singer2->getCount() << endl;
if (singer==singer2)
{
cout << "ͬһʵ" << endl;
}
else
{
cout << "߲ͬһʵ" << endl;
}
cout << "--------------Ƕʽ---------------" << endl;
Singelton2 *singer3 = Singelton2::getInstance();
cout << singer3->getCount() << endl;
Singelton2 *singer4 = Singelton2::getInstance();
cout << singer4->getCount() << endl;
if (singer3==singer4)
{
cout << "ͬһʵ" << endl;
}
else
{
cout << "߲ͬһʵ" << endl;
}
cin.get();
return 0;
} | true |
fa4ae8783c0a4f3e97ece0f67dc2085d1809c25e | C++ | thiagosantos1/Practice_CPlus | /Labs/Lab11/Circle.h | UTF-8 | 284 | 2.640625 | 3 | [] | no_license | #ifndef CIRCLE_H
#define CIRCLE_H
class Circle : public Shape
{
public:
Circle(int);
virtual void setX(int);
virtual void setY(int);
virtual void setGray (float);
virtual void drawOn (sf::RenderWindow &);
private:
int radius;
int x, y;
float colorGrey;
};
#endif | true |
80cb0453ac18dd6c786f44b477add2e77d305543 | C++ | hibamueen/hospital-management-system | /Hospital Management System/Hospital Management System/Doctor.h | UTF-8 | 1,887 | 3.140625 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<string>
#include<conio.h>
#include "Patient.h"
using namespace std;
class Doctor
{
string name, Field;
int age, id, size, index, fees;
char gender;
double contact;
Patient * ptr;
bool slot;
public:
Doctor() { slot = true; ptr = NULL; }
Doctor(Doctor &q)
{
if (size > 10)
size = 10;
else if (size < 5)
size = 5;
this->size = q.size;
this->name = q.name;
this->age = q.age;
this->id = q.id;
this->gender = q.gender;
this->contact = q.contact;
this->Field = q.Field;
this->fees = q.fees;
this->ptr = new Patient[size]();
this->index = 0;
slot = true;
}
Doctor(string name, string Field, int age, int id, int fees, int size, char gender, double contact);
void Set_Field(string val);
string Get_Field();
void print();
void Set_contact(double val);
double Get_contact();
void Set_gender(char val);
char Get_gender();
void Set_id(int val);
int Get_id();
void Set_age(int val);
int Get_age();
void Set_fees(int val);
int Get_fees();
bool Get_Slot() { return slot; }
void Set_Slot(bool x) { slot = x; }
void Set_name(string val);
string Get_name();
void update(int ID)
{
ptr[index - 1].Set_id(ID);
}
void insert_patient(Patient q)
{
if (index < size)
{
ptr[index].Set_name(q.Get_name());
ptr[index].Set_id(q.Get_id());
ptr[index].Set_gender(q.Get_gender());
ptr[index].Set_contact(q.Get_contact());
ptr[index].Set_dep(q.Get_dep());
ptr[index++].Set_age(q.Get_age());
}
else
cout << Field << " Doctor Cannot Handle More Patients. Sorry\n";
}
void delete_patient(int ID)
{
for (int i = 0; i < index ; i++)
{
if (ptr[i].Get_id() == ID)
{
ptr[i].~Patient();
for (int j = i; j < index - 1; j++)
{
Patient temp = ptr[j];
ptr[j] = ptr[j + 1];
ptr[j + 1] = temp;
}
index--;
break;
}
}
}
~Doctor();
}; | true |
b48e88749aaeb4bf42023b28f3d3bdf0fef93f24 | C++ | 93Hong/Algorithms | /9461_waveSequence/Main.cpp | UTF-8 | 345 | 2.625 | 3 | [] | no_license | #include <cstdio>
#pragma warning(disable:4996)
using namespace std;
long long int arr[101];
int main() {
int N;
scanf("%d", &N);
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 2;
arr[5] = 2;
for (int i = 6; i <= 100; i++) {
arr[i] = arr[i-1] + arr[i-5];
}
while (N--) {
int n;
scanf("%d", &n);
printf("%lld\n", arr[n]);
}
} | true |
c93ae15e0e00245eae5589c106925da37ae99793 | C++ | warrenween/fuzzification | /ia.cpp | ISO-8859-1 | 10,277 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <locale.h>
#include <ctype.h>
void layout(){
setlocale(LC_ALL, "Portuguese");
printf("\n");
for(int i =0; i <79; i++)
printf("-");
printf("\n");
printf(" Bem vindo ao bar do Gallo ");
printf("\n");
for(int i =0; i <79; i++)
printf("-");
printf("\n\n");
}
void layout_Final(){
setlocale(LC_ALL, "Portuguese");
printf("\n");
for(int i =0; i <79; i++)
printf("-");
printf("\n");
printf(" Obrigado por usar o Cuba Livre ");
printf("\n");
for(int i =0; i <79; i++)
printf("-");
printf("\n\n");
}
void layout1(){
printf("\n");
for(int i =0; i <79; i++)
printf("-");
printf("\n");
printf(" Cuba Livre ");
printf("\n");
for(int i =0; i <79; i++)
printf("-");
printf("\n\n");
}
bool validarValor(float valor){
if(valor == 0){
printf("\nPor favor digite um numero ou maior que 0. \n");
system("pause");
system("cls");
layout1();
return false;
}
return true;
}
int main (){
setlocale(LC_ALL, "Portuguese");
//variaveis
int tipoRefri, flag;
float mlRefri, mlRun, mlGelo;
float resulRefri, resulRun, resulGelo;
int c,r,p,g;
int resp=0, soma=0, valor=0;
char entradarefri [10];
char entradarun [10];
char entradagelo [10];
do{
//layout
layout();
system("pause");
system("cls");
layout1();
//Entrada de dados
do{
printf("Digite o tipo do seu refrigerante:\n");
printf("1- Coca-cola\n");
printf("2- Pepsi\n");
printf("\n");
printf("Opo: ");
if (scanf("%d", &tipoRefri) != 1) {
printf("\nPor favor digite apenas numeros \n");
tipoRefri = 10;
fflush(stdin);
}
}while(tipoRefri<1 || tipoRefri>2);
system("cls");
layout1();
do{
printf("Digite a quantidade de ml de Refrigerante:\n");
printf("Coca-Cola (50ml a 60ml) ou Pepsi-Cola (60ml a 70ml)\n");
printf("Quantidade: ");
scanf("%s", &entradarefri);
mlRefri = atof (entradarefri);
fflush(stdin);
}while(!validarValor(mlRefri));
do{
printf("\nDigite a quantidade de ml de Run\n");
printf("Run (10ml a 30ml)\n");
printf("Quantidade: ");
scanf("%s", &entradarun);
mlRun = atof (entradarun);
fflush(stdin);
}while(!validarValor(mlRun));
do{
printf("\nDigite a quantidade de ml de Gelo\n");
printf("Gelo (20ml)\n");
printf("Quantidade: ");
scanf("%s", &entradagelo);
mlGelo = atof (entradagelo);
fflush(stdin);
}while(!validarValor(mlGelo));
printf ("\n");
//comea a verificar Coca
if(tipoRefri == 1)
//comea coca forte
if(mlRefri >= 50 && mlRefri < 52 ){
c=1;
printf("Coca-Forte\n");
}else
if(mlRefri >= 52 && mlRefri < 54){
resulRefri = ((54-mlRefri)/(54-52));
c=1;
printf("Coca-forte com o grau de: %.0f\n", resulRefri);
//comea coca suave
}else if(mlRefri >= 54 && mlRefri <56 ){
c=2;
printf("Coca-Suave\n");
}else if(mlRefri >= 56 && mlRefri < 58){
c=2;
resulRefri = ((58-mlRefri)/(58-56));
printf("Coca-suave com o grau de: %.0f\n", resulRefri);
//comea coca fraca
}else if(mlRefri >= 58 && mlRefri <= 60 ){
c=3;
printf("Coca-Fraco\n");
}
//comea verificar Pepsi
if(tipoRefri == 2)
//comecaPepsi forte
if(mlRefri >= 60 && mlRefri < 62 ){
p=1;
printf("Pepsi-Forte\n");
}else
if(mlRefri >= 62 && mlRefri < 64){
p=1;
resulRefri = ((64-mlRefri)/(64-62));
printf("Pepsi-forte com o grau de: %.0f\n", resulRefri);
//comeca Pepsi suave
}else if(mlRefri >= 64 && mlRefri <66 ){
p=2;
printf("Pepsi-Suave\n");
}else if(mlRefri >= 66 && mlRefri < 68){
p=2;
resulRefri = ((68-mlRefri)/(68-66));
printf("Pepsi-suave com o grau de: %.0f\n", resulRefri);
//comeca pepsi fraca
}else if(mlRefri >= 68 && mlRefri < 71 ){
p=3;
printf("Pepsi-Fraco\n");
}
//comea a verficar Run
//comea Run fraco
if(mlRun >= 10 && mlRun < 15 ){
r=3;
printf("Run-Fraco\n");
//comea run suave
}else if(mlRun >= 20 && mlRun <23 ){
r=2;
printf("Run-Suave\n");
}else if(mlRun >= 15 && mlRun < 20){
r=2;
resulRun = ((20-mlRun)/(20-15));
printf("Run-suave com o grau de: %.0f\n", resulRun);
//comea run forte
}else if(mlRun >= 27 && mlRun <= 30 ){
r=1;
printf("Run-Forte\n");
} else
if(mlRun >= 23 && mlRun < 27){
r=1;
resulRun = ((27-mlRun)/(27-23));
printf("Run-forte com o grau de: %.0f\n", mlRun);
}
//comea a verificar o gelo
if(mlGelo == 20){
g=1;
printf("Gelado\n");
}else
printf("Sem gelo\n");
printf("\n\n");
system("pause");
system("cls");
layout_Final();
//Defuzzificao
//comea a verificar com coca-cola
//comea paladar suave com coca
if(tipoRefri == 1) {
if(c==1 && r==3 && g==1){
valor=20;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Suave\n");
printf("Seu preo : R$ 20,00\n");
}else if(c==2 && r==2 && g==1){
valor=20;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Suave\n");
printf("Seu preo : R$ 20,00\n");
}else if(c==3 && r==1 && g==1) {
valor=20;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Suave\n");
printf("Seu preo : R$ 20,00\n");
//comea paladar forte
}else if(c==1 && r==2 && g==1){
valor=25;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Forte\n");
printf("Seu preo : R$ 25,00\n");
}else if(c==1 && r==1 && g==1){
valor=25;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Forte\n");
printf("Seu preo : R$ 25,00\n");
} else if(c==2 && r==1 && g==1){
valor=25;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Forte\n");
printf("Seu preo : R$ 25,00\n");
//comeca paladar fraco
}else if(c==3 && r==3 && g==1){
valor=15;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Fraco\n");
printf("Seu preo : R$ 15,00\n");
}else if(c==3 && r==2 && g==1){
valor=15;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Fraco\n");
printf("Seu preo : R$ 15,00\n");
}else if(c==2 && r==3 && g==1){
valor=15;
printf("\nBebida Com Coca-cola\n");
printf("Paladar: Fraco\n");
printf("Seu preo : R$ 15,00\n");
}
}else if(tipoRefri == 2) {
//Comea a verificar com pepsi
//comea paladar suave
if(p==1 && r==3 && g==1){
valor=20;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Suave\n");
printf("Seu preo : R$ 20,00\n");
}else if(p==2 && r==2 && g==1){
valor=20;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Suave\n");
printf("Seu preo : R$ 20,00\n");
}else if(p==3 && r==1 && g==1) {
valor=20;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Suave\n");
printf("Seu preo : R$ 20,00\n");
//comea paladar forte
}else if(p==1 && r==2 && g==1){
valor=25;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Forte\n");
printf("Seu preo : R$ 25,00\n");
}else if(p==1 && r==1 && g==1){
valor=25;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Forte\n");
printf("Seu preo : R$ 25,00\n");
} else if(p==2 && r==1 && g==1){
valor=25;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Forte\n");
printf("Seu preo : R$ 25,00\n");
//comea paladar fraco
}else if(p==3 && r==3 && g==1){
valor=15;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Fraco\n");
printf("Seu preo : R$ 15,00\n");
}else if(p==3 && r==2 && g==1){
valor=15;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Fraco\n");
printf("Seu preo : R$ 15,00\n");
}else if(p==2 && r==3 && g==1){
valor=15;
printf("\nBebida Com Pepsi\n");
printf("Paladar: Fraco\n");
printf("Seu preo : R$ 15,00\n");
}
}else{
printf("\nSua bebida no Cuba Livre\n");
}
soma=soma+valor;
system("pause");
system("cls");
layout1();
do {
flag = 0;
printf("Deseja continuar?\n");
printf("1-Sim\n");
printf("2-Nao\n");
if (scanf("%d", &resp) != 1) {
printf("\nPor favor digite apenas numeros \n");
flag = 1;
fflush(stdin);
}
}while(flag==1);
}while(resp==1);
layout_Final();
if(soma != 0) {
printf("O valor total da conta : %i\n\n", soma);
}
system("pause");
}
| true |
d2cfeb66154f90ea0e7f1f3614da04dc6807d5ce | C++ | enriquecs095/Ejercicio-Basico-c- | /MiPrimerEjercicioEnC++/Main.cpp | UTF-8 | 2,641 | 3.890625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{ //ejercicio 4.26 , 4.27 y 2.29
int opcion;
int numero1, numero2, numero3, numero4, numero5;
int contador = 0;
double entrada2 = 0;
int entrada;
bool salir = true;
do {
cout << "\nEjercicios Basicos de c++\n" << endl;
cout << "1. Numero palindrome" << endl;
cout << "2. Numero binario a decimal" << endl;
cout << "3. Cuadrados y cubos de numeros" << endl;
cout << "4. Salir" << endl;
cout << "Ingrese una opcion" << endl;
cin >> opcion;
switch (opcion) {
case 1:
do {
cout << "Ingrese el numero de 5 cifras" << endl;
cin >> entrada;
if (entrada >= 100000)
cout << "Numero debe ser de 5 cifras" << endl;
} while (entrada>= 100000);
numero1 = entrada / 10000;
numero2 = (entrada % 10000) / 1000;
numero3 = (entrada % 1000) / 100;
numero4 = (entrada % 100) / 10;
numero5 = entrada % 10;
if (numero1 == numero5 && numero2 == numero4)
cout << "El numero es palindrome" << endl;
else
cout << "El numero no es palindrome" << endl;
break;
case 2:
long numero, dato, valor, decimal;
int exponente;
bool verificar;
do {
cout << "Introduce el numero binario 1 y 0: " << endl;
cin >> entrada2;
verificar = true;
dato= entrada2;
while (dato != 0) {
valor = dato % 10;
if (valor != 0 && valor != 1) {
verificar = false; }
dato = dato / 10;
}
} while (!verificar);
exponente = 0;
decimal = 0;
while (entrada2 != 0) {
valor = (long)entrada2 % 10;
decimal = decimal + valor * (int) pow(2, exponente);
exponente++;
entrada2 = entrada2 / 10;
}
cout<<"El resultado es: " << decimal<<endl;
break;
case 3:
cout << "Tabla de numeros del 0 al 10" << endl;
cout << "Numero" << "\t" << "Cuadrado" << " Cubo" << endl;
cout << 0 << "\t" <<0 << "\t " << 0 << endl;
cout << 1 << "\t" <<1 * 1 << "\t " <<1 * 1 * 1 << endl;
cout << 2 << "\t" <<2 * 2 << "\t " <<2 * 2 * 2 << endl;
cout << 3 << "\t" <<3 * 3 << "\t " <<3 * 3 * 3 << endl;
cout << 4 << "\t" <<4 * 4 << "\t " <<4 * 4 * 4 << endl;
cout << 5 << "\t" <<5 * 5 << "\t " <<5 * 5 * 5 << endl;
cout << 6 << "\t" <<6 * 6 << "\t " <<6 * 6 * 6 << endl;
cout << 7 << "\t" <<7 * 7 << "\t " <<7 * 7 * 7 << endl;
cout << 8 << "\t" <<8 * 8 << "\t " <<8 * 8 * 8 << endl;
cout << 9 << "\t" <<9 * 9 << "\t " <<9 * 9 * 9 << endl;
cout << 10 << "\t" <<10 * 10 << "\t " <<10 * 10 * 10 << endl;
break;
case 4:
salir = false;
break;
default:
cout << "Ingrese una opcion correcta" << endl;
}
} while (salir);
}
| true |
0334798896e57caa4f11892757fc5be7edf86672 | C++ | drbaird2/Restart | /Objects/Sphere.cpp | UTF-8 | 2,584 | 3 | 3 | [] | no_license | #include "Sphere.h"
#include "../Utilities/Constants.h"
Sphere::Sphere() :
center(Point3(0,0,0)),
radius(1.0)
{}
Sphere::Sphere(Point3 cen, double rad) :
center(cen),
radius(rad)
{}
Sphere::Sphere(const Sphere& sphere)
: Object(sphere)
, center(sphere.center)
, radius(sphere.radius)
{
mat = sphere.mat;
}
Sphere::~Sphere()
{}
shared_ptr<Sphere> Sphere::clone() const
{
return make_shared<Sphere>((*this));
}
bool Sphere::intersect(const Ray& ra, double& tMin, Record& recentHits)
{
double t;
Vec3 oc = ra.orig - center; //direction vector for Sphere. (o - c)
auto a = ra.dir * ra.dir; // a = d * d
auto b = 2.0 * oc*ra.dir; // b = 2(o - c) * d
auto c = oc.length_squared() - radius * radius; // c = (o - c) * (o - c) - r * r;
auto disc = b * b - 4.0 * a * c; // discriminant
if (disc < 0.0) // No hit
{
return false;
}
else // one or two hit
{
double sqrtd = sqrt(disc);
double denom = 2.0 * a;
t = (-b - sqrtd) / denom; //smaller root
if (t > kEpsilon)
{
tMin = t;
recentHits.sceneNormal = (oc + t * ra.dir) / radius;
recentHits.localHit = ra.orig + t * ra.dir;
//recentHits.material_ptr = getMaterial();
recentHits.lastObject = this->clone();
return true;
}
t = (-b + sqrtd) / denom; //larger root
if (t > kEpsilon)
{
tMin = t;
recentHits.sceneNormal = (oc + t * ra.orig) / radius;
recentHits.localHit = ra.orig + t * ra.dir;
//recentHits.material_ptr = getMaterial();
recentHits.lastObject = this->clone();
return true;
}
}
return false;
}
bool Sphere::shadowIntersect(const Ray& ra, double& tMin) const
{
double t;
Vec3 oc = ra.orig - center; //direction vector for Sphere. (o - c)
double a = ra.dir * ra.dir; // a = d * d
double b = 2.0 * oc * ra.dir; // b = 2(o - c) * d
double c = oc.length_squared() - radius * radius; // c = (o - c) * (o - c) - r * r;
double disc = b * b - 4.0 * a * c; // discriminant
if (disc < 0.0) // No hit
{
return false;
}
else // one or two hit
{
double e = sqrt(disc);
double denom = 2.0 * a;
t = (-b - e) / denom; //swaller root
if (t > kEpsilon)
{
tMin = t;
return true;
}
t = (-b + e) / denom; //larger root
if (t > kEpsilon)
{
tMin = t;
return true;
}
}
return false;
}
bool Sphere::getBoundingBox(AABB& outputBox) const
{
Point3 p0(center.xPoint - radius, center.yPoint - radius, center.zPoint - radius);
Point3 p1(center.xPoint + radius, center.yPoint + radius, center.zPoint + radius);
outputBox = AABB(p0,p1);
// std::cout << "Bound a sphere: " << this<< endl;
return true;
} | true |
678cf735c62a7fdecf9e6a27c33fbc1bacc4c160 | C++ | DianaGeorgievaa/Data-Structures-and-Algorithms- | /Practice_05/Task4.cpp | UTF-8 | 1,000 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include<vector>
#include<stack>
using namespace std;
int main()
{
long long n;
cin >> n;
vector<long long>numbers;
if (n <= 9)
{
for (int i = 1; i <= n; i++)
{
numbers.push_back(i);
}
}
else
{
for (int i = 1; i <= 9; i++)
{
numbers.push_back(i);
}
long long first = 0;
long long second = 0;
for (long long i = 0; i <= numbers.size(); i++)
{
first = 10 * numbers[i] + numbers[i] % 10 - 2;
second = 10 * numbers[i] + numbers[i] % 10 + 2;
if (first > n && second > n)
{
break;
}
if (first <= n && (numbers[i] % 10) != 1 && (numbers[i] % 10) != 0)
{
numbers.push_back(first);
}
if (second <= n && (numbers[i] % 10) != 9 && (numbers[i] % 10) != 8)
{
numbers.push_back(second);
}
}
}
for (long long i = 0; i < numbers.size(); i++)
{
if (numbers[i] > 1000000)
{
break;
}
cout << numbers[i] << " ";
}
system("pause");
return 0;
} | true |
248c4e41d2e9e2763e96cb33463b41d0c11913c4 | C++ | whguo/LeetCode | /C++/Tree/449.Serialize and Deserialize BST.cpp | UTF-8 | 2,100 | 3.828125 | 4 | [] | no_license | /*
对二叉搜索树进行序列化和反序列化。
*/
/*
思路:由于二叉搜索树的中序遍历是一定的,所以任何相同结点的二叉搜索树中序序列一样。
因此,为了使得序列化后的唯一性,考虑使用前序遍历。
前序遍历的序列中,先是root,然后是root左侧,最后root右侧。
左右侧是靠root结点的值区分开的,左侧的小于root,右侧大于。
反序列化是依据这一特点解开的。
为了方便,这里使用4字节的char直接表示一个int值。
*/
#include <iostream>
#include <cstring>
#include <limits.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec {
public:
string serialize(TreeNode* root) {
string order;
inorderDFS(root, order);
return order;
}
inline void inorderDFS(TreeNode* root, string& order) {
if (!root) return;
char buf[4];
memcpy(buf, &(root->val), sizeof(int));
for (int i=0; i<4; i++) order.push_back(buf[i]);
inorderDFS(root->left, order);
inorderDFS(root->right, order);
}
TreeNode* deserialize(string data) {
int pos = 0;
return reconstruct(data, pos, INT_MIN, INT_MAX);
}
inline TreeNode* reconstruct(const string& buffer, int& pos, int minValue, int maxValue) {
if (pos >= buffer.size()) return NULL;
int value;
memcpy(&value, &buffer[pos], sizeof(int));
if (value < minValue || value > maxValue) return NULL;
TreeNode* node = new TreeNode(value);
pos += sizeof(int);
node->left = reconstruct(buffer, pos, minValue, value);
node->right = reconstruct(buffer, pos, value, maxValue);
return node;
}
};
int main()
{
TreeNode n1(1),n2(2),n3(3),n4(4),n5(5),n6(6);
n4.left = &n3, n4.right = &n5;
n3.left = &n1, n1.right = &n2;
n5.right = &n6;
Codec codec;
TreeNode *root = codec.deserialize(codec.serialize(&n4));
}
| true |
001f416c773218065ef6509659487684eff8395e | C++ | wsmind/leaf | /src/engine/resource/ResourceManager.inline.h | UTF-8 | 3,366 | 2.984375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <algorithm>
#include <engine/resource/Resource.h>
#include <engine/resource/ResourceWatcher.h>
template <class ResourceType>
void ResourceManager::updateResourceData(const std::string &name, const unsigned char *buffer, size_t size)
{
ResourceDescriptor &descriptor = findDescriptor<ResourceType>(name);
if (descriptor.buffer != nullptr)
free(descriptor.buffer);
descriptor.buffer = (unsigned char *)malloc(size);
descriptor.size = size;
memcpy(descriptor.buffer, buffer, size);
// reload if necessary
if ((descriptor.users > 0) || descriptor.pendingUnload)
{
Resource *resource = descriptor.resource;
const unsigned char *newBuffer = descriptor.buffer; // calling unload() could indirectly move descriptors in memory, so we keep a copy of that pointer
resource->unload();
resource->load(newBuffer, size);
this->notifyWatchers(descriptor);
}
}
template <class ResourceType>
ResourceType *ResourceManager::requestResource(const std::string &name, ResourceWatcher *watcher)
{
ResourceDescriptor &descriptor = findDescriptor<ResourceType>(name);
ResourceType *resource = static_cast<ResourceType *>(descriptor.resource);
descriptor.users++;
if (watcher != nullptr)
{
assert(std::find(descriptor.watchers.begin(), descriptor.watchers.end(), watcher) == descriptor.watchers.end());
descriptor.watchers.push_back(watcher);
}
// load if needed
if (descriptor.pendingUnload)
descriptor.pendingUnload = false;
else if (descriptor.users == 1)
resource->load(descriptor.buffer, descriptor.size);
return resource;
}
void ResourceManager::releaseResource(Resource *resource, ResourceWatcher *watcher)
{
auto it = std::find_if(this->descriptors.begin(), this->descriptors.end(), [resource](const std::pair<std::string, ResourceDescriptor> &tuple) -> bool
{
return tuple.second.resource == resource;
});
assert(it != this->descriptors.end());
ResourceDescriptor &descriptor = it->second;
descriptor.users--;
if (watcher != nullptr)
{
auto it = std::find(descriptor.watchers.begin(), descriptor.watchers.end(), watcher);
assert(it != descriptor.watchers.end());
descriptor.watchers.erase(it);
}
// unload if needed
if (descriptor.users == 0)
{
descriptor.pendingUnload = true;
descriptor.ttl = 20; // keep it around for 20 frames
}
}
template <class ResourceType>
ResourceManager::ResourceDescriptor &ResourceManager::findDescriptor(const std::string &name)
{
// resource ID is Type_Name; e.g: Mesh_Door
const std::string resourceId = ResourceType::resourceClassName + "_" + name;
// this will create a new descriptor if not found
ResourceDescriptor &descriptor = this->descriptors[resourceId];
// if it's a new descriptor, we also need to instanciate the actual resource object
if (descriptor.resource == nullptr)
{
descriptor.resource = new ResourceType;
descriptor.buffer = (unsigned char *)malloc(ResourceType::defaultResourceData.size());
descriptor.size = ResourceType::defaultResourceData.size();
memcpy(descriptor.buffer, ResourceType::defaultResourceData.c_str(), descriptor.size);
}
return descriptor;
}
| true |
891b6dcad153f9818436b02b1308e61f5376c929 | C++ | marioandre01/PTC-Projeto1B_ComSerialTunTxRx_Cpp | /ComSerialTunTxRx/Callback.cpp | UTF-8 | 1,060 | 2.640625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Callback.cpp
* Author: marioandre
*
* Created on 1 de Novembro de 2018, 00:12
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Callback.cpp
* Author: msobral
*
* Created on 20 de Setembro de 2018, 13:41
*/
#include "Callback.h"
Callback::Callback(int fd, long tout): fd(fd), base_tout(tout),tout(tout) {}
Callback::Callback(long tout) : fd(-1), base_tout(tout),tout(tout) {}
int Callback::filedesc() const { return fd;}
int Callback::timeout() const { return tout;}
void Callback::reload_timeout() {
tout = base_tout;
}
void Callback::update(long dt) {
tout -= dt;
if (tout < 0) tout = 0;
}
bool Callback::operator==(const Callback & o) const {
return fd == o.fd;
}
| true |
82bfd535fc7e45c81f76a66366f5200715e95df3 | C++ | Chennyben/Data-Science | /PA Excercise/PA Excercise/new randf/main.cpp | UTF-8 | 3,792 | 2.90625 | 3 | [
"MIT"
] | permissive | /*
*
* Compilation line:
g++ -o main main.cpp DensityTree.cpp -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lopencv_ml
*
*/
#include "DensityTree.h"
Mat densityForest(unsigned int D, unsigned int numberOfThreshodls,unsigned int numberOfTrees, Mat X);
Mat generateData();
void plotData(Mat dataMatrix, char const * name);
void plotDensities(Mat data, vector<Mat> densityXY,int dimension,char const * name);
int main(int argc, char** argv)
{
int n_levels=2; //This is a parameter, it can change
int n_thresholds=50;
Mat dataMatrix = generateData();
plotData(dataMatrix,"Data Matrix Plot");
vector<Mat> densityXY;
densityXY.push_back(densityForest(n_levels,n_thresholds,1,dataMatrix));
densityXY.push_back(densityForest(n_levels,n_thresholds,50,dataMatrix));
densityXY.push_back(densityForest(n_levels,n_thresholds,100,dataMatrix));
plotDensities(dataMatrix,densityXY,0,"Densities X");
plotDensities(dataMatrix,densityXY,1,"Densities Y");
waitKey(0);
return 0;
}
Mat generateData()
{
unsigned int dim = 2;
Mat A = Mat(500, dim, CV_64F);;
cv::theRNG().fill(A, cv::RNG::NORMAL, 5, 3);
Mat B = Mat(500, dim, CV_64F);
cv::theRNG().fill(B, cv::RNG::NORMAL, -9, 3);
Mat dataMatrix;
vconcat(A, B, dataMatrix);
return dataMatrix;
}
Mat densityForest(unsigned int D, unsigned int numberOfThreshodls,unsigned int numberOfTrees, Mat X)
{
Mat density=Mat::zeros(1000,2,CV_64F);
for (int i=0;i<numberOfTrees;i++)
{
DensityTree T(D,numberOfThreshodls,X);
T.train();
density+=T.densityXY();
}
return density/(double)numberOfTrees;
}
void plotData(Mat dataMatrix, char const * name)
{
Mat origImage = Mat(1000,1000,CV_8UC3);
origImage.setTo(0.0);
double minValX,maxValX;
minMaxIdx( dataMatrix.col(0), &minValX, &maxValX,NULL,NULL);
double minValY,maxValY;
minMaxIdx( dataMatrix.col(1), &minValY, &maxValY,NULL,NULL);
double v;
double nmin=100,nmax=900;
for (int i = 0; i < 1000; i++)
{
Point p1;
v= dataMatrix.at<double>(i,0);
p1.x = ((v-minValX)/(maxValX-minValX))*(nmax-nmin)+nmin;
v= dataMatrix.at<double>(i,1);
p1.y = ((v-minValY)/(maxValY-minValY))*(nmax-nmin)+nmin;
circle(origImage,p1,3,Scalar( 255, 255, 255 ));
}
namedWindow( name, WINDOW_AUTOSIZE );
imshow( name, origImage );
}
void plotDensities(Mat data, vector<Mat> density, int dim, char const * name)
{
int n_densities=density.size();
Mat origImage = Mat(1000,1000,CV_8UC3);
origImage.setTo(0.0);
double minValX,maxValX;
double minValY,maxValY;
double tempMinY,tempMaxY;
minMaxIdx( data.col(dim), &minValX, &maxValX,NULL,NULL);
minMaxIdx( density[0].col(dim), &minValY, &maxValY,NULL,NULL);
for(int i=1;i<n_densities;i++)
{
minMaxIdx( density[i].col(dim), &tempMinY, &tempMaxY,NULL,NULL);
if(tempMaxY>maxValY) maxValY=tempMaxY;
if(tempMinY<minValY) minValY=tempMinY;
}
double v;
int nmin=100;
int nmax=900;
int r=0,g=0,b=0;
for(int j=0; j< n_densities;j++)
{
if(j==0)r=250;
if(j==1)g=250;
if(j==2)b=250;
for (int i = 0; i < 1000; i++)
{
Point p1;
v= data.at<double>(i,dim);
p1.x = ((v-minValX)/(maxValX-minValX))*(nmax-nmin)+nmin;
v= density[j].at<double>(i,dim);
p1.y = ((v-minValY)/(maxValY-minValY))*(nmax-nmin)+nmin;
circle(origImage,p1,1,Scalar(b,g,r));
}
if(j==0)r=0;
if(j==1)g=0;
if(j==2)b=0;
}
namedWindow( name, WINDOW_AUTOSIZE );
imshow( name, origImage );
imwrite( (String(name) + ".png").c_str(),origImage);
}
| true |
c42213daad3d88cb36ca37fe5e5ad0d6a49fecaf | C++ | ayabdelrahman72/Data-Structures-using-C-Plus-Plus | /Chapter11/Binary Trees/binaryTreeType.h | UTF-8 | 1,443 | 3.15625 | 3 | [] | no_license | #ifndef BINARYTREETYPE_H
#define BINARYTREETYPE_H
#include "stackLinkedList.h"
class binaryTreeType
{
public:
~binaryTreeType();
binaryTreeType();
binaryTreeType(const binaryTreeType &);
const binaryTreeType &operator=(binaryTreeType &);
bool isEmpty()const;
void inorderTraversal()const;
void preorderTraversal()const;
void postorderTraversal()const;
int treeHeight();
int treeNodeCount()const;
int treeLeavesCount()const;
void destroyTree();
void nonRecInorderTraversal()const;
protected:
binaryTreeNode *root; // we defined as protected so we can later derive special binary trees
private:
void copyTree(binaryTreeNode* &copiedTreeRoot,binaryTreeNode * otherTreeNode);
void destroy(binaryTreeNode * &p);//to destroy the binary tree which p points to
void inorder(binaryTreeNode *p)const; //to traverse the binary tree which p points to
void preorder(binaryTreeNode *p)const; //to traverse the binary tree which p points to
void postorder(binaryTreeNode *p)const; //to traverse the binary tree which p points to
int height(binaryTreeNode *p);
int nodeCount(binaryTreeNode *p)const;
int leavesCount(binaryTreeNode *p)const;
void nonRecInorder(binaryTreeNode *p)const;
int max(int x,int y);
};
#endif // BINARYTREETYPE_H
| true |
865e7a507fe74436d19c401617ac8ed96566e347 | C++ | ENgineE777/Atum | /Atum/Services/TaskExecutor/TaskExecutor.h | UTF-8 | 3,803 | 2.9375 | 3 | [
"Zlib"
] | permissive |
#pragma once
#include "Support/Support.h"
#include <vector>
#include <map>
/**
\ingroup gr_code_services_task_executor
*/
/**
\brief TaskExecutor
This class manages execution of tasks. Each task is a callback, i.e. method
of class. Task can be ordered by level of execution and can be combined in single
pool via class TaskExecutor::SingleTaskPool. Severel task pools can be combined into
one group pool via class TaskExecutor::GroupTaskPool.
*/
class TaskExecutor
{
public:
class TaskPool
{
public:
virtual void Execute(float dt) = 0;
};
class GroupTaskPool;
class SingleTaskPool : public TaskPool
{
public:
friend class GroupTaskPool;
struct Task : DelegateObject
{
float freq;
float time;
};
struct TaskList
{
int level;
std::vector<Task> list;
};
private:
std::vector<TaskList*> lists;
bool active;
int changeMark;
TaskList* FindTaskList(int level);
static void ExecuteList(TaskList* list, float dt);
public:
SingleTaskPool();
/**
\brief Set active state
\param[in] set Define active state. Inactive pools are not executed.
*/
void SetActive(bool set);
/**
\brief Execute all tasks in a pool
\param[in] dt Deltatime since last frame.
*/
virtual void Execute(float dt);
/**
\brief Adding task in a pool
\param[in] level Priority level of execution. Lower numbers means earlst execution.
\param[in] entity Pointer to object which method should be executed
\param[in] call Pointer to a method of a owner class
\param[in] freq Frequincy of execution of a method
*/
void AddTask(int level, Object* entity, Object::Delegate call, float freq = -1.0f);
/**
\brief Delete task in a pool
\param[in] level Priority level of execution. Lower numbers means earlst execution.
\param[in] entity Pointer to object which method should be executed
\param[in] new_pool Move task to a new pool
*/
void DelTask(int level, Object* entity, SingleTaskPool* new_pool = nullptr);
/**
\brief Delete all task of a object in a pool
\param[in] entity Pointer to object which method should be executed
\param[in] new_pool Move task to a new pool
*/
void DelAllTasks(Object* entity, SingleTaskPool* new_pool = nullptr);
};
class GroupTaskPool : public TaskPool
{
friend class SingleTaskPool;
struct TaskList
{
SingleTaskPool* pool;
SingleTaskPool::TaskList* list;
};
struct GroupList
{
int level;
std::vector<TaskList> taskLists;
};
std::vector<GroupList> groupLists;
std::vector<SingleTaskPool*> taskPools;
std::vector<int> changeMarks;
std::vector<int> filter;
void FillList();
void Execute(GroupList& groupList, float dt);
public:
/**
\brief Add filter of level executions. Filter is used in a case when needed to call only tasks with particular level if execution.
\param[in] level Level of execution.
*/
void AddFilter(int level);
/**
\brief Create new task pool in a group
\return Pointer to TaskExecutor::SingleTaskPool
*/
SingleTaskPool* AddTaskPool();
/**
\brief Delete pool for a group.
\param[in] pool Pointer to TaskExecutor::SingleTaskPool
*/
void DelTaskPool(SingleTaskPool* pool);
/**
\brief Execute all tasks pool pool for a group.
\param[in] dt Deltatime since last frame.
*/
virtual void Execute(float dt);
/**
\brief Execute all tasks which particular levele of execution
\param[in] level Level of execution
\param[in] dt Deltatime since last frame.
*/
void ExecutePool(int level, float dt);
};
/**
\brief Create new task pool
\return Pointer to TaskExecutor::SingleTaskPool
*/
SingleTaskPool* CreateSingleTaskPool();
/**
\brief Create new group pool
\return Pointer to TaskExecutor::GroupTaskPool
*/
GroupTaskPool* CreateGroupTaskPool();
}; | true |
a93961dc20d8cfc3b405c5fd02695f1d5f06dba4 | C++ | 96scar/UNT_code | /csce4550/project.cpp | UTF-8 | 4,579 | 3.125 | 3 | [] | no_license | #include "header.h"
using namespace std;
//hashtable.push_back("0");
//hashtable.resize(SIZE);
vector<string> hashtable(100, "0");
int main()
{
User myUser;
int logged_in = 0; //whether or not anyone is logged in
int Sinput = 0; //start input
int Uinput = 0; //user input
int start = 1; //start is true
int Use = 1; //Use is true
string username, password, sitename;
string u, s, h;
char answer;
int value;
cout << endl << "Password Manager by Scarlett Jones" << endl << endl;
//open file to read
ifstream htxt("hash.txt");
if((bool) htxt)
{
string line1;
while(getline(htxt, line1))
{
int j=0;
char * pch1;
pch1 = strtok((char*) line1.c_str(), " ");
while(pch1 != NULL)
{
if(j==0)
{
u = pch1;
//cout << u << endl;
}
else if(j==1)
{
s = pch1;
//cout << s << endl;
}
else if(j==2)
{
h = pch1;
//cout << h << endl;
}
else
{
;
}
value = atoi(h.c_str())%SIZE;
hashtable.at(value) = u;
pch1 = strtok(NULL, " ");
//cout << "word: " << j << endl;
j++;
}
//value = atoi(h.c_str())%SIZE;
//cout << "hi" << endl;
}
//cin.ignore();
htxt.close();
}
while(start)
{
StartMenu();
cin >> Sinput;
switch(Sinput)
{
case 1: //create new user
CreateUser(hashtable);
//make new file for user
//add to hash of username/passwords
//tell them to login to use their account now that it's created
break;
case 2: //login
//check if already logged in
if(logged_in == 1)
{
cout << "You are already logged in as " << username << "." << endl;
cout << "Not " << username << "? Log out by selecting option 6." << endl;
}
else
{
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
ifstream input;
input.open("hash.txt");
string line;
while(getline(input, line) && logged_in != 1)
{
int i=0;
char * pch;
pch = strtok((char *) line.c_str(), " ");
while(pch != NULL)
{
if(i==0)
{
if(pch == username)
{
u = pch;
pch = strtok(NULL, " ");
s = pch;
pch = strtok(NULL, " ");
h = pch;
}
}
pch = strtok(NULL, " ");
i++;
}
//value = atoi(h.c_str())%SIZE;
//string compvalstring = password + s;
value = checkHash(username, password, s, SIZE, hashtable);
if(value == 1)
{
cout << "Logged in" << endl;
logged_in = 1;
Use=1;
}
//else
//{
// cout << "Wrong username or password." << endl;
//}
}
//cin.ignore();
//checkHash(username, password, salt, SIZE, hashtable);
//check if password maps to username
//Wrong username or password, try again
//Log in if correct
//logged_in = 1;
//load user info from file named from username, decrypt with password
//cout << "Before menu options" << endl;
if(logged_in == 1)
{
myUser.login(username, password);
remove("temp");
//cout << "made it out of the login function" << endl;
while(Use)
{
UserMenu();
//cout << "Choose a menu option: ";
cin >> Uinput;
switch(Uinput)
{
case 1: //add new account
myUser.addAccount();
break;
case 2: //show account info
myUser.printAccounts();
break;
case 3: //delete specific account
cout << "Which account?" << endl;
myUser.printSitenames();
cin >> sitename;
cout << "Deleting " << sitename << endl;
myUser.deleteOneAccount(sitename);
break;
case 4: //exit
cout << "Logging you out . . ." << endl;
//save user data in temp file
//encrypt into their username file with their password, write over old username file
//delete temp file
myUser.logout(username, password);
remove("temp");
logged_in = 0;
Use = 0; //Use is false, exit loop
break;
default: //incorrect input
cout << "Incorrect input. Only enter numbers 1 through 4." << endl;
break;
}
}
}
else
{
cout << "Wrong username or password" << endl;
}
}
break;
case 3: //exit
cout << "Goodbye!" << endl;
start = 0;
//exit(1);
break;
default: //incorrect input
cout << "Incorrect input. Only enter numbers 1 through 3." << endl;
break;
}
}
return 0;
} | true |
25b0f7168ab1db55aa218e42afaeb4ea1b916a8d | C++ | rashikshrestha/opencv-try1 | /smooth_using_trackbar.cpp | UTF-8 | 2,341 | 3.3125 | 3 | [] | no_license | #include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
char string1[] = "Smooth Type:\n 0: Normal Blur\n 1: Gaussian Blur\n 2: Medial Blur\n 3: Bilateral Filter";
int smooth_type = 0;
int max_type = 3;
char string2[] = "Maximum Kernel size";
int kernel_size = 0;
int max_kernal_size = 20;
cv::Mat src = cv::imread("lena.png", cv::IMREAD_GRAYSCALE);
cv::Mat dest = src.clone();
void trackbar1(int, void *);
void trackbar2(int, void *);
void display(int mode, int max_kernel);
int main(int argc, char **argv)
{
cv::namedWindow("Image Smoothing using various filters", cv::WINDOW_NORMAL);
cv::createTrackbar(string1, "Image Smoothing using various filters", &smooth_type, max_type, trackbar1);
cv::createTrackbar(string2, "Image Smoothing using various filters", &kernel_size, max_kernal_size, trackbar2);
cv::waitKey(0);
return 0;
}
void trackbar1(int, void *)
{
display(smooth_type, kernel_size);
}
void trackbar2(int, void *)
{
display(smooth_type, kernel_size);
}
void display(int mode, int max_kernel)
{
if (max_kernel >= 3)
{
switch (mode)
{
case 0:
for (int i = 1; i < max_kernel; i += 2)
blur(src, dest, cv::Size(i, i), cv::Point(-1, -1));
cv::imshow("Image Smoothing using various filters", dest);
std::cout << "Normal Box Blur Shown" << std::endl;
break;
case 1:
for (int i = 1; i < max_kernel; i += 2)
GaussianBlur(src, dest, cv::Size(i, i), 0, 0);
cv::imshow("Image Smoothing using various filters", dest);
std::cout << "Gaussian Blur Shown" << std::endl;
break;
case 2:
for (int i = 1; i < max_kernel; i += 2)
medianBlur(src, dest, i);
cv::imshow("Image Smoothing using various filters", dest);
std::cout << "Median Blur Shown" << std::endl;
break;
case 3:
for (int i = 1; i < max_kernel; i += 2)
bilateralFilter(src, dest, i, i * 2, i / 2);
cv::imshow("Image Smoothing using various filters", dest);
std::cout << "Bilateral Filter Shown" << std::endl;
break;
}
}
else
{
cv::imshow("Image Smoothing using various filters", src);
}
} | true |
ad03f93429cfb3772ef35c2c0ab8036e92126a8a | C++ | actnet/saedb | /storage/mmap_test.cpp | UTF-8 | 1,258 | 2.953125 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <string>
#include "testing/testharness.hpp"
#include "mmap_file.hpp"
using namespace std;
struct MMapFileTest {
MMapFileTest() {
filepath = saedb::test::TempFileName();
}
~MMapFileTest() {
int ret = remove(filepath.c_str());
ASSERT_TRUE(ret == 0) << "removing temp file: " << filepath;
}
protected:
string filepath;
};
TEST(MMapFileTest, CreateAndRead) {
int COUNT = 17;
// Test Create
{
int count = COUNT;
int size = count * sizeof(int);
MMapFile* f = MMapFile::Create(filepath.c_str(), size);
ASSERT_TRUE(f) << "creating mmap file";
int* d = (int*) f->Data();
for (int i = 0; i < count; i++) {
d[i] = i;
}
f->Close();
delete f;
}
// Test Read
{
MMapFile* f = MMapFile::Open(filepath.c_str());
ASSERT_TRUE(f) << "reading mmap file";
int* d = (int*) f->Data();
int count = f->Size() / sizeof(int);
ASSERT_EQ(count, COUNT);
for (int i = 0; i < count; i++) {
ASSERT_EQ(d[i], i);
}
f->Close();
delete f;
}
}
int main() {
return ::saedb::test::RunAllTests();
}
| true |
eec8d680695c06b5fe7be734f19b7ec232205e01 | C++ | shreysingla11/ssl-project | /Backend/Parser/submissions/Assignment 4/52.cpp | UTF-8 | 2,826 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
using namespace std;
class counter{
private:
long n;
vector<long> page;
long maxAtt;
list< list<long> > order;
vector<list< list<long> >::iterator> point;
vector<list<long>::iterator> position;
public:
counter(long n1){
n=n1;
maxAtt = 0;
for(long i=0;i<n;i++){page.push_back(0);}
list<long> l;
for(long j=0;j<n;j++){
l.push_back(j);
}
for(list<long>::iterator pt = l.begin(); pt!=l.end(); ++pt){
position.push_back(pt);
}
order.push_back(l);
list< list<long> >::iterator it = order.begin();
point.push_back(it);
}
void increment(long i){
(*point[page[i]]).remove(i);
if((*point[page[i]]).size()==0){(*point[page[i]]).clear();}
page[i]++;
if(page[i]>maxAtt){
list<long> l;
l.push_back(i);
order.push_back(l);
list< list<long> >::iterator iit = order.begin();
advance(iit,order.size()-1);
point.push_back(iit);
maxAtt+=1;
}
else{
(*point[page[i]]).push_back(i);
}
list<long>::iterator iitt = (*point[page[i]]).begin();
advance(iitt,(*point[page[i]]).size()-1);
position[i]=iitt;
return;
}
void decrement(long i){
if(page[i]<=0){page[i]=0;}
else{
(*point[page[i]]).remove(i);
if((*point[page[i]]).size()==0){(*point[page[i]]).clear();}
page[i]--;
(*point[page[i]]).push_back(i);
list<long>::iterator idtt = (*point[page[i]]).begin();
advance(idtt,(*point[page[i]]).size()-1);
position[i]=idtt;
}
return;
}
void reset(long i){
if(page[i]<=0){page[i]=0;}
else{
(*point[page[i]]).remove(i);
if((*point[page[i]]).size()==0){(*point[page[i]]).clear();}
(*point[0]).push_back(i);
list<long>::iterator irtt = (*point[0]).begin();
advance(irtt,(*point[0]).size()-1);
position[i]=irtt;
page[i]=0;
}
return;
}
long count(long i){
return page[i];
}
long findMax(){
long maxCount=0;
for(long j=0;j<n;j++){
if(page[j]>maxCount){maxCount=page[j];}
}
return maxCount;
}
long numMax(){
long var = findMax();
return (*point[var]).size();
}
void printMax(){
long var = findMax();
list<long>::iterator ipt2 = (*point[var]).begin();
for (; ipt2 != (*point[var]).end(); ++ipt2)
{cout << ' ' << *ipt2;}
return;
}
};
| true |
c648f2942e5069649e70c6c0e48e99244df2c660 | C++ | WassimHajji10/ComicBookReader | /include/comic_book_reader_contract.h | UTF-8 | 1,041 | 2.609375 | 3 | [] | no_license | #pragma once
#include <string>
#include <map>
#include <opencv2/opencv.hpp>
#include <vector>
class ArchiveInterface
{
// class for archiving file, unzip the image files
// Use OpenCV, format for image: "cv::Mat"
public:
bool virtual loadArchivedFiles(std::string file_path) = 0;
// Use 7z function
//load to private element: archive_loaded.
bool virtual loadOneImage(int num, cv::Mat &a_image) = 0;
// Use OpenCV function
//load one image from archive_loaded
};
class ImageProcessInterface
{
public:
//ImageProcessInterface();
//~ImageProcessInterface();
bool virtual autoAdjustImage(cv::Mat& input_image, cv::Mat& output_image, int image_type_flag) = 0;
// image_type_flags = 0 for image whose the type is text
// image_type_flags = 1 for image whose the type is graphics
// output_image's height in pixels
// output_image's width in pixels
bool virtual getImage(int num, int image_type_flag, cv::Mat& output_image) = 0;
//first step: check if the page exists in cache, if not, processing the images
};
| true |
7966acb60911e52315786e50316027c7947d63bf | C++ | brem-hub/project-2 | /container/container.h | UTF-8 | 3,182 | 3.171875 | 3 | [] | no_license | #ifndef PROJECT_CPP_CONTAINER_CONTAINER_H_
#define PROJECT_CPP_CONTAINER_CONTAINER_H_
#define MAX_CONTAINER_SIZE 10001
#include "../objects/number.h"
#include "../objects/complex.h"
#include "../objects/fraction.h"
#include "../objects/polar.h"
/*
* Класс контейнера, хранящего в себе числа.
*/
class container {
public:
container();
~container();
/*
* Получить текущий размер контейнера.
* @returns: текущий размер контейнера.
*/
int size() const { return _size; }
/*
* Заполнить контейнер из файла.
* @param: in - дескриптор файла, открытого для чтения.
* @returns: код статуса операции.
*/
int fill(FILE* in);
/*
* Случайное заполнение контейнера size элементами.
* @param: size - количество генерируемых элементов.
* @param: out - [optional] дескриптор файла, открытого на вывод для записи сгенерированных элементов.
* @returns: код статуса операции.
*/
int randomFill(int size, FILE* out = NULL);
/*
* Сортировать контейнер по вещественному представлению чисел в порядке возрастания.
*/
void straightSort();
/*
* Вывод содержимого контейнера в файл.
* @param: out - дескриптор файла, открытого на запись.
*/
void out(FILE*);
private:
/*
* Добавить число в контейнер.
* Это внутренний метод контейнера, т.к. мы передаем ссылку на число, следовательно,
* если мы добавим ссылку в контейнер и очистим пямять по некой другой ссылке, то при попытке получить доступ к
* данному элементу мы получим ошибку доступа к памяти. Однако внутри контейнера мы гарантируем,
* что ссылка не будет очищена или объект по этой ссылке не будет изменен.
* Для реализации публичного метода add() необходимо копировать(deep-copy) объект из ссылки,
* т.е. создать виртульный метод в классе number, который будет переопределяться
* в каждом классе-наследнике и копировать объект по значению.
* @param: num - число, которое добавляется.
* @returns: код статуса операции.
*/
int add(number* num);
private:
int _size; // размер контейнера.
number** _array; // динамический массив чисел.
};
#endif //PROJECT_CPP_CONTAINER_CONTAINER_H_
| true |
fc995d7feb6ee4d76a5caf044dd8e52fa16225da | C++ | karnkaul/LittleEngineVk | /engine/src/graphics/animation/animation.cpp | UTF-8 | 1,222 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <le/core/visitor.hpp>
#include <le/graphics/animation/animation.hpp>
namespace le::graphics {
auto Animation::Channel::duration() const -> Duration {
return std::visit([](auto const& s) { return s.duration(); }, storage);
}
void Animation::Channel::update(NodeLocator node_locator, Duration time) const {
auto* joint = node_locator.find(joint_id);
if (joint == nullptr) { return; }
auto const visitor = Visitor{
[time, joint](Animation::Translate const& translate) {
if (auto const p = translate(time)) { joint->transform.set_position(*p); }
},
[time, joint](Animation::Rotate const& rotate) {
if (auto const o = rotate(time)) { joint->transform.set_orientation(*o); }
},
[time, joint](Animation::Scale const& scale) {
if (auto const s = scale(time)) { joint->transform.set_scale(*s); }
},
};
std::visit(visitor, storage);
}
auto Animation::duration() const -> Duration {
auto ret = Duration{};
for (auto const& sampler : channels) { ret = std::max(ret, sampler.duration()); }
return ret;
}
auto Animation::update(NodeLocator node_locator, Duration time) const -> void {
for (auto const& channel : channels) { channel.update(node_locator, time); }
}
} // namespace le::graphics
| true |
ac5e1e517ce90f6ab46446feaf44875b2ce1e36d | C++ | GodOfProgramming/ltt | /c++/test/tag-parser.cpp | UTF-8 | 4,876 | 2.953125 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <unordered_map>
#include <memory>
class Tag;
typedef std::vector<std::string> string_vec;
typedef std::unordered_map<std::string, std::string> AttributeMap;
typedef std::unordered_map<std::string, std::shared_ptr<Tag>> TagMap;
void fill_vector(string_vec& vec, int count);
class Tag {
public:
Tag() = default;
Tag(Tag& other) {
*this = other;
}
Tag& operator=(const Tag& other) {
this->children = std::move(other.children);
this->attributes = std::move(other.attributes);
}
Tag& operator[](const std::string& key) {
return *children[key];
}
std::string& operator()(const std::string& key) {
return attributes[key];
}
TagMap children;
AttributeMap attributes;
};
struct TagData {
std::string tag_name;
size_t open_start_tag_indx = std::string::npos;
size_t close_start_tag_indx = std::string::npos;
size_t open_end_tag_indx = std::string::npos;
size_t close_end_tag_indx = std::string::npos;
size_t next_pos = 0;
};
class TagParser {
public:
TagParser() = default;
Tag getTags(const std::string& src) {
Tag root;
TagMap roots;
TagData tag_data;
do {
tag_data = get_tag_data(src, tag_data.next_pos);
std::string body = src.substr(tag_data.close_start_tag_indx + 1, tag_data.open_end_tag_indx);
Tag current;
if (body.length()) {
Tag inner(getTags(body));
current.children = std::move(inner.children);
}
roots[tag_data.tag_name] = std::make_shared(current);
} while(tag_data.next_pos != std::string::npos);
root.children = std::move(roots);
return root;
}
private:
TagData get_tag_data(const std::string& src, size_t offset) {
size_t open_start_tag_indx = src.find_first_of("<", offset);
size_t close_start_tag_indx = src.find_first_of(">", offset + open_start_tag_indx + 1);
std::string tag_name = src.substr(open_start_tag_indx + 1, offset + close_start_tag_indx);
size_t open_end_tag_indx = src.find_last_of("</" + tag_name + ">", offset);
size_t close_end_tag_indx = src.find_first_of(">", offset + open_end_tag_indx + 1);
TagData retval;
retval.tag_name = tag_name;
retval.open_start_tag_indx = open_start_tag_indx;
retval.close_start_tag_indx = close_start_tag_indx;
retval.open_end_tag_indx = open_end_tag_indx;
retval.close_end_tag_indx = close_end_tag_indx;
retval.next_pos = src.find_first_of("<", close_end_tag_indx + 1);
return retval;
}
};
struct QueryCommand {
bool is_child_access = false;
bool is_attr_access = false;
std::string member_name;
};
class QueryRunner {
public:
QueryRunner(const Tag& root) : mRootTag(root) { }
void runQueries(std::vector<std::string>& cmds) {
for (auto& cmd : cmds) {
std::vector<QueryCommand> queries = parseCommand(cmd);
Tag start = mRootTag;
for(auto& query : queries) {
if (query.is_child_access) {
start = start[query.member_name];
} else if (query.is_attr_access) {
std::cout << start(query.member_name) << '\n';
}
}
}
}
private:
const Tag& mRootTag;
std::vector<QueryCommand> parseCommand(const std::string& line) {
std::vector<QueryCommand> retval;
std::vector<size_t> dot_locations;
size_t next_pos = line.find(".", next_pos);
while (next_pos != std::string::npos) {
dot_locations.push_back(next_pos);
next_pos = line.find(".", next_pos);
}
size_t last_dot_location = 0;
for (auto loc : dot_locations) {
QueryCommand cmd;
cmd.is_child_access = true;
cmd.member_name = line.substr(last_dot_location, loc);
last_dot_location = loc;
retval.push_back(cmd);
}
QueryCommand cmd;
size_t attr_access = line.find("~", last_dot_location);
cmd.is_attr_access = true;
cmd.member_name = line.substr(attr_access);
retval.push_back(cmd);
return retval;
}
};
int main(int argc, char* argv[]) {
std::string input;
std::string src_line_count_arg(argv[1]);
std::string query_line_count_arg(argv[2]);
int src_line_count = std::stoi(src_line_count_arg);
int query_line_count = std::stoi(query_line_count_arg);
std::vector<std::string> src_code;
fill_vector(src_code, src_line_count);
std::vector<std::string> queries;
fill_vector(queries, query_line_count);
std::stringstream ss;
for (const auto& line : src_code) {
ss << line;
}
TagParser parser;
Tag root = parser.getTags(ss.str());
QueryRunner runner(root);
runner.runQueries();
return 0;
}
void fill_vector(string_vec& vec, int count) {
for (int i = 0; i < count; i++) {
std::string line;
std::getline(std::cin, line);
vec.push_back(line);
}
}
| true |
70dcc8c7df069aa71140278bd71c79b1d67b57c3 | C++ | TwentyFiveSeven/Algorithm | /C-Code/Map)위장.cpp | UTF-8 | 459 | 2.578125 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
map<string,vector<string>> M;
int count=0;
int solution(vector<vector<string>> clothes) {
int answer = 1,Fsize = clothes.size();
for(int i=0;i<Fsize;i++)
M[clothes[i][1]].push_back(clothes[i][0]);
int Msize = M.size();
for(auto iter = M.begin();iter != M.end();iter++)
answer = answer*((iter->second).size()+1);
return answer-1;
}
| true |
93b0f7e5ab18e3b705f6a6de6ca57efe80efa8b1 | C++ | opendarkeden/server | /src/server/gameserver/BloodBibleBonusManager.cpp | UTF-8 | 4,266 | 2.734375 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : BloodBibleBonusManager.cpp
// Written By : beowulf
// Description :
//////////////////////////////////////////////////////////////////////////////
#include "BloodBibleBonus.h"
#include "BloodBibleBonusManager.h"
#include "DB.h"
#include "GCHolyLandBonusInfo.h"
//////////////////////////////////////////////////////////////////////////////
// class BloodBibleBonusManager member methods
//////////////////////////////////////////////////////////////////////////////
BloodBibleBonusManager::BloodBibleBonusManager()
{
__BEGIN_TRY
m_Count = 0;
__END_CATCH
}
BloodBibleBonusManager::~BloodBibleBonusManager()
{
__BEGIN_TRY
clear();
__END_CATCH
}
void BloodBibleBonusManager::init()
{
__BEGIN_TRY
load();
__END_CATCH
}
void BloodBibleBonusManager::clear()
{
__BEGIN_TRY
BloodBibleBonusHashMapItor itr = m_BloodBibleBonuses.begin();
for ( ; itr != m_BloodBibleBonuses.end(); itr++ )
{
SAFE_DELETE( itr->second );
}
m_BloodBibleBonuses.clear();
__END_CATCH
}
void BloodBibleBonusManager::load()
{
__BEGIN_TRY
__BEGIN_DEBUG
clear();
Statement* pStmt = NULL;
Result* pResult = NULL;
BEGIN_DB
{
pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement();
pResult = pStmt->executeQuery("SELECT MAX(Type) FROM BloodBibleBonusInfo");
if (pResult->getRowCount() == 0)
{
SAFE_DELETE(pStmt);
throw Error ("There is no data in BloodBibleBonusInfo Table");
}
pResult->next();
m_Count = pResult->getInt(1) + 1;
Assert (m_Count > 0);
pResult = pStmt->executeQuery("SELECT Type, Name, OptionList FROM BloodBibleBonusInfo");
while (pResult->next())
{
BloodBibleBonus* pBloodBibleBonus = new BloodBibleBonus();
int i = 0;
pBloodBibleBonus->setType( pResult->getInt(++i) );
pBloodBibleBonus->setName( pResult->getString(++i) );
pBloodBibleBonus->setOptionTypeList( pResult->getString(++i) );
pBloodBibleBonus->setRace( 0 );
addBloodBibleBonus(pBloodBibleBonus);
}
SAFE_DELETE(pStmt);
}
END_DB(pStmt)
__END_DEBUG
__END_CATCH
}
void BloodBibleBonusManager::save()
{
__BEGIN_TRY
throw UnsupportedError (__PRETTY_FUNCTION__);
__END_CATCH
}
BloodBibleBonus* BloodBibleBonusManager::getBloodBibleBonus( BloodBibleBonusType_t bloodBibleBonusType ) const
{
__BEGIN_TRY
BloodBibleBonusHashMapConstItor itr = m_BloodBibleBonuses.find( bloodBibleBonusType );
if ( itr == m_BloodBibleBonuses.end() )
{
cerr << "BloodBibleBonusManager::getBloodBibleBonus() : no such element" << endl;
throw NoSuchElementException();
}
return itr->second;
__END_CATCH
}
void BloodBibleBonusManager::addBloodBibleBonus(BloodBibleBonus* pBloodBibleBonus)
{
__BEGIN_TRY
Assert (pBloodBibleBonus != NULL);
BloodBibleBonusHashMapConstItor itr = m_BloodBibleBonuses.find( pBloodBibleBonus->getType() );
if ( itr != m_BloodBibleBonuses.end() )
{
throw DuplicatedException ();
}
m_BloodBibleBonuses[pBloodBibleBonus->getType()] = pBloodBibleBonus;
__END_CATCH
}
void BloodBibleBonusManager::setBloodBibleBonusRace( BloodBibleBonusType_t bloodBibleBonusType, Race_t race )
{
__BEGIN_TRY
getBloodBibleBonus( bloodBibleBonusType )->setRace( race );
__END_CATCH
}
void BloodBibleBonusManager::makeHolyLandBonusInfo( GCHolyLandBonusInfo& gcHolyLandBonusInfo )
{
__BEGIN_TRY
/* BloodBibleBonusHashMapConstItor itr = m_BloodBibleBonuses.begin();
for ( ; itr != m_BloodBibleBonuses.end(); itr++ )
{
BloodBibleBonusInfo* pInfo = new BloodBibleBonusInfo();
BloodBibleBonus* pBonus = itr->second;
pInfo->setType( pBonus->getType() );
pInfo->setRace( pBonus->getRace() );
pInfo->setOptionType( pBonus->getOptionTypeList() );
gcHolyLandBonusInfo.addBloodBibleBonusInfo( pInfo );
}*/
__END_CATCH
}
string BloodBibleBonusManager::toString() const
{
__BEGIN_TRY
StringStream msg;
msg << "BloodBibleBonusManager(\n";
BloodBibleBonusHashMapConstItor itr = m_BloodBibleBonuses.begin();
for ( ; itr != m_BloodBibleBonuses.end(); itr++ )
{
msg << itr->second->toString() << ",";
}
return msg.toString();
__END_CATCH
}
// Global Variable definition
BloodBibleBonusManager* g_pBloodBibleBonusManager = NULL;
| true |
7485d941314eadb9caaa6617863924af5022b6f3 | C++ | joelbygger/adventofcode19 | /src/day3/routes.hpp | UTF-8 | 967 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <cstdint>
#include <utility>
#include <vector>
class Routes
{
public:
using rawPoint = std::pair<char, int32_t>;
using rawRoute = std::vector<rawPoint>;
using rawRoutes = std::vector<rawRoute>;
// Route is expected to be on format Rn or Dn or Un or Ln.
void addRoutes(const rawRoutes& inRoutes);
[[nodiscard]] int32_t getClosestIntersectionManhattanDist() const;
[[nodiscard]] int32_t getSmallestManhattanDist() const;
private:
struct point
{
uint64_t xy;
int32_t totDist;
};
using aRoute = std::vector<struct point>;
static aRoute calcRoute(const Routes::rawRoute& inRoute);
static std::vector<aRoute> sortIntersections(const std::vector<Routes::aRoute>& inRoutes);
static aRoute onlyDuplicates(const std::vector<Routes::aRoute>& inRoutes);
static aRoute onlyDuplicatesCombineDist(const std::vector<Routes::aRoute>& inRoutes);
std::vector<aRoute> m_routes;
};
| true |
72da5a86734396e7d5572a002b24dc983f5883ea | C++ | PMSeitzer/openmp-example | /PS5_problem2.cpp | UTF-8 | 1,824 | 3.6875 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct cae_t {
int value;
bool isLocked = false;
int numAttempts = 0;
};
int test_and_set(int* mem);
bool compare_and_exchange(cae_t * mem, int compare_value, int swap_value);
int main(int argc, char *argv[])
{
cae_t mem;
mem.value = 4;
int compare_value = 4;
int exchange_value = 7;
compare_and_exchange(&(mem), compare_value, exchange_value);
//break the lock
mem.isLocked = false;
compare_and_exchange(&(mem), compare_value, exchange_value);
compare_and_exchange(&(mem), compare_value, exchange_value);
}
bool test_and_set(cae_t *mem){
if (mem->isLocked) {
//force break the lock after 100 attempts
mem->numAttempts++;
if (mem->numAttempts >= 100) {
mem->isLocked = false;
cout << "Breaking lock after 100 access attempts." << endl;
}
}
return mem->isLocked;
}
bool compare_and_exchange(cae_t * mem, int compare_value, int swap_value){
cout << "-----------------------" << endl;
cout << "Starting compare_and_exchange()" << endl;
cout << "Comparing cae_t @ " << &(mem) << ": val=" << mem->value << " to " << compare_value << endl;
bool isSwapped = false;
// acquire lock (spin until the lock is released)
while(test_and_set(mem)){}
if (compare_value == mem->value){
mem->value = swap_value;
isSwapped = true;
}
//release lock (set to true)
mem->isLocked = true;
cout << "result for " << "cae_t @ " << &(mem) << ": " << (isSwapped > 0 ? "swapped" : "not swapped") << endl;
cout << "new value for " << "cae_t @ " << &(mem) << ": " << mem->value << endl;
cout << "Finished compare_and_exchange()" << endl;
cout << "-----------------------" << endl;
return isSwapped;
}
| true |
0ae21882ce5671335b5888db1f8be035ee14f6a5 | C++ | cheunkay/carolc-shawnkade-ixd-textile-proj1 | /Sequential_blinking_10_.ino | UTF-8 | 3,040 | 2.9375 | 3 | [] | no_license | /*
Light-up distance sensor
Reading data from the ping/ultrasonic sensor. By measuring arbitrarily
set distance, white light emitting diodes (LEDs) turn on one after the other
when an object comes into close proximity with the sensor. When an object
goes out of the set distance, LEDs turn off one after the other.
The circuit:
- ping/ultrasonic sensor
connected to digital pin 12
- LEDs x 6
anode (long leg) attached to digital pin 2-7
cathode (short leg) attached to ground
available at instructables, posted by jreeve17, March 9, 2013
modified March 1, 2018
By Carol Cheung, Shawn Kadawathage
http://www.instructables.com/id/How-to-make-A-light-up-distance-sensor/
*/
const int pingPin = 12; //setup pingpin as 12
void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT); // set up these pins as outputs
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH); // function to let you know it is ready
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
delay (500);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
}
void loop()
{
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
if (inches < 30) {
digitalWrite(2, HIGH); } //these numbers give the distances needed to turn lights on or off
if (inches > 30) { //change these to chang thedistances
digitalWrite(2, LOW); }
if (inches < 27) {
digitalWrite(3, HIGH);}
if (inches > 27) {
digitalWrite(3, LOW);}
if (inches < 24) {
digitalWrite(4, HIGH);}
if (inches > 24) {
digitalWrite(4, LOW);}
if (inches < 21) {
digitalWrite(5, HIGH);}
if (inches > 21) {
digitalWrite(5, LOW);}
if (inches < 18) {
digitalWrite(6, HIGH);}
if (inches > 18) {
digitalWrite(6, LOW);}
if (inches < 15) {
digitalWrite(7, HIGH);}
if (inches > 15) {
digitalWrite(7, LOW);}
if (inches < 12) {
digitalWrite(8, HIGH);}
if (inches > 12) {
digitalWrite(8, LOW);}
if (inches < 9) {
digitalWrite(9, HIGH);}
if (inches > 9) {
digitalWrite(9, LOW);}
delay(100);
}
long microsecondsToInches(long microseconds)
{
}
| true |
f34cd7aa9d80f625352122cacdbf10eed812cf09 | C++ | Ryednap/Coding-Competition | /Codeforces/Practice/Gym/Tree(Galen_Colin_Mashup)/G.cpp | UTF-8 | 2,528 | 2.625 | 3 | [] | no_license | // include the library code for LCD
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
float value;
int pressureinbar = 0;
String ssid
= "Simulator Wifi"; // SSID to connect to
String password = ""; // Our virtual wifi has no password (so dont do your banking
String host
= "api.thingspeak.com"; // Open Weather Map API
const int httpPort = 80;
String uri
= "/update?api_key=PWVX09BUXSNJ7IGJ&field1=";
int setupESP8266(void) {
// Start our ESP8266 Serial Communication
Serial.begin(115200); // Serial connection over USB to computer
Serial.println("AT"); // Serial connection on Tx / Rx port to ESP8266
delay(10);
// Wait a little for the ESP to respond
if (!Serial.find("OK")) return 1;
// Connect to 123D Circuits Simulator Wifi
Serial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");delay(10);
// Wait a little for the ESP to respond
if (!Serial.find("OK")) return 2;
// Open TCP connection to the host:
Serial.println("AT+CIPSTART=\"TCP\",\"" + host + "\"," + httpPort);
delay(50);
// Wait a little for the ESP to respond
if (!Serial.find("OK")) return 3;
return 0;
}
void anydata(int pressureinbar) {
int temp = map(analogRead(A0),20,358,-40,125);
int tempi = map(pressureinbar,20,358,-40,125);
// Construct our HTTP call
String httpPacket = "GET " + uri + String(temp) + "&field2=" + String(tempi) + "HTTP/1.1\r\nHost: " + host + "\r\n\r\n";
int length = httpPacket.length();
// Send our message length
Serial.print("AT+CIPSEND=");
Serial.println(length);delay(10); // Wait a little for the ESP to respond if (!Serial.find(">")) return -1;
// Send our http request
Serial.print(httpPacket);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find("SEND OK\r\n")) return;
}
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
setupESP8266();
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
value = analogRead(A0)*0.004882814;
value = (value - 0.5) * 100.0;
lcd.setCursor(0,0);
lcd.print("Temp:");
lcd.print(value);
lcd.print("C");
float pressureSensorVal = analogRead(A1);float barVoltage = (pressureSensorVal/1024.0) * 5.0;
if (pressureSensorVal < 102.00 || pressureSensorVal == 102.00){
pressureinbar = 0;
}
else {
float pressureinbarToRound = ((barVoltage * 155.0) / 0.5) * 1.333 ;
pressureinbar = (int)roundf(pressureinbarToRound);
}
lcd.setCursor(0,1);
lcd.print("Pressure:");
lcd.print(pressureinbar);
lcd.print("mb");
anydata(pressureinbar);
delay(10000);
}
| true |
c522a330d949ccee7158d24ce8eeedadcd1499c2 | C++ | imdanielsp/nex | /src/nex_stmt.hpp | UTF-8 | 5,876 | 2.796875 | 3 | [] | no_license | #ifndef NEX_STMT_HPP_
#define NEX_STMT_HPP_
#include "nex_token.hpp"
#include "nex_expr.hpp"
#include <memory>
#include <vector>
namespace nex::ast::stmt {
struct Block;
struct Class;
struct Expression;
struct Function;
struct If;
struct Print;
struct Return;
struct Let;
struct While;
class Visitor {
public:
virtual std::any visitBlockStmt(Block* stmt) = 0;
virtual std::any visitClassStmt(Class* stmt) = 0;
virtual std::any visitExpressionStmt(Expression* stmt) = 0;
virtual std::any visitFunctionStmt(Function* stmt) = 0;
virtual std::any visitIfStmt(If* stmt) = 0;
virtual std::any visitPrintStmt(Print* stmt) = 0;
virtual std::any visitReturnStmt(Return* stmt) = 0;
virtual std::any visitLetStmt(Let* stmt) = 0;
virtual std::any visitWhileStmt(While* stmt) = 0;
};
struct Stmt {
virtual std::any accept(Visitor* visitor) = 0;
};
struct Block : public Stmt {
Block(std::vector<std::shared_ptr<Stmt>> statements) :
m_statements(statements)
{}
virtual ~Block() = default;
std::any accept(Visitor* visitor) {
return visitor->visitBlockStmt(this);
}
const std::vector<std::shared_ptr<Stmt>> m_statements;
};
inline std::shared_ptr<Stmt> make_block(std::vector<std::shared_ptr<Stmt>> statements) {
return std::make_shared<Block>(statements);
}
struct Class : public Stmt {
Class(Token name, std::shared_ptr<expr::Variable> superclass, std::vector<std::shared_ptr<Function>> methods, std::vector<std::shared_ptr<Let>> fields) :
m_name(name),
m_superclass(superclass),
m_methods(methods),
m_fields(fields)
{}
virtual ~Class() = default;
std::any accept(Visitor* visitor) {
return visitor->visitClassStmt(this);
}
const Token m_name;
const std::shared_ptr<expr::Variable> m_superclass;
const std::vector<std::shared_ptr<Function>> m_methods;
const std::vector<std::shared_ptr<Let>> m_fields;
};
inline std::shared_ptr<Stmt> make_class(Token name, std::shared_ptr<expr::Variable> superclass, std::vector<std::shared_ptr<Function>> methods, std::vector<std::shared_ptr<Let>> fields) {
return std::make_shared<Class>(name, superclass, methods, fields);
}
struct Expression : public Stmt {
Expression(std::shared_ptr<expr::Expr> e) :
m_e(e)
{}
virtual ~Expression() = default;
std::any accept(Visitor* visitor) {
return visitor->visitExpressionStmt(this);
}
const std::shared_ptr<expr::Expr> m_e;
};
inline std::shared_ptr<Stmt> make_expression(std::shared_ptr<expr::Expr> e) {
return std::make_shared<Expression>(e);
}
struct Function : public Stmt {
Function(Token name, std::vector<Token> params, std::vector<std::shared_ptr<Stmt>> body) :
m_name(name),
m_params(params),
m_body(body)
{}
virtual ~Function() = default;
std::any accept(Visitor* visitor) {
return visitor->visitFunctionStmt(this);
}
const Token m_name;
const std::vector<Token> m_params;
const std::vector<std::shared_ptr<Stmt>> m_body;
};
inline std::shared_ptr<Stmt> make_function(Token name, std::vector<Token> params, std::vector<std::shared_ptr<Stmt>> body) {
return std::make_shared<Function>(name, params, body);
}
struct If : public Stmt {
If(std::shared_ptr<expr::Expr> cond, std::shared_ptr<Stmt> thenBranch, std::shared_ptr<Stmt> elseBranch) :
m_cond(cond),
m_thenBranch(thenBranch),
m_elseBranch(elseBranch)
{}
virtual ~If() = default;
std::any accept(Visitor* visitor) {
return visitor->visitIfStmt(this);
}
const std::shared_ptr<expr::Expr> m_cond;
const std::shared_ptr<Stmt> m_thenBranch;
const std::shared_ptr<Stmt> m_elseBranch;
};
inline std::shared_ptr<Stmt> make_if(std::shared_ptr<expr::Expr> cond, std::shared_ptr<Stmt> thenBranch, std::shared_ptr<Stmt> elseBranch) {
return std::make_shared<If>(cond, thenBranch, elseBranch);
}
struct Print : public Stmt {
Print(std::shared_ptr<expr::Expr> e) :
m_e(e)
{}
virtual ~Print() = default;
std::any accept(Visitor* visitor) {
return visitor->visitPrintStmt(this);
}
const std::shared_ptr<expr::Expr> m_e;
};
inline std::shared_ptr<Stmt> make_print(std::shared_ptr<expr::Expr> e) {
return std::make_shared<Print>(e);
}
struct Return : public Stmt {
Return(Token keyword, std::shared_ptr<expr::Expr> value) :
m_keyword(keyword),
m_value(value)
{}
virtual ~Return() = default;
std::any accept(Visitor* visitor) {
return visitor->visitReturnStmt(this);
}
const Token m_keyword;
const std::shared_ptr<expr::Expr> m_value;
};
inline std::shared_ptr<Stmt> make_return(Token keyword, std::shared_ptr<expr::Expr> value) {
return std::make_shared<Return>(keyword, value);
}
struct Let : public Stmt {
Let(Token name, std::shared_ptr<expr::Expr> init) :
m_name(name),
m_init(init)
{}
virtual ~Let() = default;
std::any accept(Visitor* visitor) {
return visitor->visitLetStmt(this);
}
const Token m_name;
const std::shared_ptr<expr::Expr> m_init;
};
inline std::shared_ptr<Stmt> make_let(Token name, std::shared_ptr<expr::Expr> init) {
return std::make_shared<Let>(name, init);
}
struct While : public Stmt {
While(std::shared_ptr<expr::Expr> cond, std::shared_ptr<Stmt> body) :
m_cond(cond),
m_body(body)
{}
virtual ~While() = default;
std::any accept(Visitor* visitor) {
return visitor->visitWhileStmt(this);
}
const std::shared_ptr<expr::Expr> m_cond;
const std::shared_ptr<Stmt> m_body;
};
inline std::shared_ptr<Stmt> make_while(std::shared_ptr<expr::Expr> cond, std::shared_ptr<Stmt> body) {
return std::make_shared<While>(cond, body);
}
}
#endif
| true |
f869b4ccc7bd95209d597c7a11af32662fde0725 | C++ | priety33/arrays | /1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.cpp | UTF-8 | 1,356 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
int n=nums.size();
int len=0;
int s=0,e=0;
pair<int,int> low={nums[0],0}, high={nums[0],0};
while(s<n && e<n)
{
if(nums[e]>high.first) high={nums[e], e};
if(nums[e]<low.first) low={nums[e], e};
if(high.first-low.first>limit)
{
if(nums[e]==low.first)
{
int temp=high.second+1;
s=temp;
high={nums[temp], temp};
while(temp<e)
{
if(nums[temp]>high.first) high={nums[temp], temp};
temp++;
}
}
else if(nums[e]==high.first)
{
int temp=low.second+1;
s=temp;
low={nums[temp], temp};
while(temp<e)
{
if(nums[temp]<low.first) low={nums[temp], temp};
temp++;
}
}
}
if(high.first-low.first<=limit)
{
len=max(len, e-s+1);
e++;
}
}
return len;
}
};
| true |
41b82264eca60d3fb290c2d7197e766e002abdb9 | C++ | garrity-patrick/foamy | /include/exp_operator.hpp | UTF-8 | 2,112 | 3.046875 | 3 | [] | no_license | // exp_operator.hpp
// @author Chris Cornelius
// Created 11/07/2011
// An extension of exp_base to represent exp_operator - the set of binary operators
#ifndef _EXP_OPERATOR_HPP_
#define _EXP_OPERATOR_HPP_
#include "exp_base.hpp"
//Temporary fix to get around multiple enum declaration for OperatorType
#include "token_operator.hpp"
class exp_operator : public exp_base
{
protected:
OperatorType _optype;
exp_base* _lexp;
exp_base* _rexp;
public:
// constructors, destructors
exp_operator() : exp_base() {
_exptype = ExpOperator;
_optype = ErrorOperator;
_lexp = _rexp = NULL;
}
exp_operator(exp_base* next, OperatorType op, exp_base* lexp, exp_base* rexp) : exp_base(next) {
_exptype = ExpOperator;
_optype = op; _lexp = lexp; _rexp = rexp;
}
exp_operator(const exp_operator& src) : exp_base(src) {
_optype = src._optype;
_lexp = src._lexp;
_rexp = src._rexp;
}
~exp_operator() {
if(_lexp) delete _lexp;
if(_rexp) delete _rexp;
}
// accessors
OperatorType optype() { return _optype; }
void set_optype(const OperatorType o) { _optype = o; }
exp_base* lexp() { return _lexp; }
exp_base* rexp() { return _rexp; }
void set_lexp(exp_base* l) {
if(_lexp) delete _lexp;
_lexp = l;
}
void set_rexp(exp_base* r) {
if(_rexp) delete _rexp;
_rexp = r;
}
// functions for printing
virtual std::ostream& printExpHead(std::ostream& os) {
os << "exp_operator ";
switch(_optype){
case ErrorOperator: os << "+"; break;
//case ErrorOperator: os << "Operator Type Error"; break;
case OpEquals: os << "=="; break;
case Plus: os << "+"; break;
case Minus: os << "-"; break;
case Greater: os << ">"; break;
case Less: os << "<"; break;
default: os << "Unknown optype"; break;
}
return os;
}
virtual std::ostream& printExpMembers(std::ostream& os, unsigned depth=0) {
os << endl;
if(_lexp) _lexp->printRec(os,depth+1);
if(_rexp) os << endl;
if(_rexp) _rexp->printRec(os, depth+1);
return os;
}
};
#endif // _EXP_OPERATOR_HPP_
| true |
62ce2ef0aecb89edbf4d72983687639d45df3889 | C++ | tarce/Practice_Problems | /CountAndSay.cpp | UTF-8 | 745 | 2.953125 | 3 | [] | no_license | class Solution {
public:
string countAndSay(int n) {
string seq = "1";
int iter = 1;
while (iter < n) {
string newSeq;
char last = seq[0];
int count = 0;
for (int i = 0; i <= seq.size(); i++) {
if(seq[i] ==last) { count ++; }
else {
newSeq.append(to_string(count));
newSeq.push_back(last);
last = seq[i];
count =1;
}
}
seq = newSeq;
iter++;
}
return seq;
}
};
| true |
ebdb06fbd1b4e9a787cde859042a5ccd63502519 | C++ | C0DE-RUNNER/Practice-Questions-DSA | /Arrays/Middle-of-three.cpp | UTF-8 | 1,122 | 3.4375 | 3 | [] | no_license | Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons).
Example 1:
Input:
A = 978, B = 518, C = 300
Output:
518
Explanation:
Since 518>300 and 518<978, so
518 is the middle element.
Example 2:
Input:
A = 162, B = 934, C = 200
Output:
200
Exaplanation:
Since 200>162 && 200<934,
So, 200 is the middle element.
Your Task:
You don't need to read input or print anything.Your task is to complete the function middle() which takes three integers A,B and C as input parameters and returns the number which has middle value.
Expected Time Complexity:O(1)
Expected Auxillary Space:O(1)
Constraints:
1<=A,B,C<=109
A,B,C are distinct.
***************************************************************************************
int middle(int A, int B, int C){
if(A>B && A>C){
if(B>C)
return B;
return C;
}
else if(B>C && B>A){
if(A>C)
return A;
return C;
}
else{
if(B>A)
return B;
return A;
}
}
| true |
f6dabb350c1650b0968e2f179b522e7fa874eec7 | C++ | PeterSansan/job_prepare | /C与CPP语言基础/const关键字/const_c.cpp | UTF-8 | 2,343 | 3.375 | 3 | [] | no_license | /*顺序表示例代码*/
#include<iostream>
#include <fstream>
#include<time.h>
#include<stdlib.h>
#include<math.h>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <sstream> //字符串调用读写
#include <fstream> //文件调用读写
using namespace std;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;//函数结果状态代码,如OK等
typedef int ElemType;
typedef int SElemType;
typedef int QElemType;
#define MAXSIZE 100
int main()
{
string str("Hello the world");
cout << str << endl;
//cnost的使用,引用篇
const int a = 1024;
const int &b = a;
//b = 4; //错误
//int &c = a; //错误,无法从const int 转换为int &,限定符会被丢弃
int d = 43;
const int &e = d;//允许将const int 绑定到一个普通int对象上
const int &f = 32; // 是一个常量引用
const int &g = d * 2; // 是常量引用
//int &h = d * 2; //非常量引用,非常量引用的妆始值必须为左值
double dval = 3.14;
const int &ri = dval;
cout << ri << endl; //结果为3
const int temp = dval; //由双精度浮点数生成一个临时的整型常量
const int &i = temp;
//const,指针篇
const double pi = 3.14;
const double x = 3;
//double *ptr = π //错误:ptr是一个普通指针
const double * cptr = π
cptr = &x;
//所谓指向常量的指针或引用,不过是指针或引用“自以为是”罢了,它们觉得自己指向了常量,
//所以自觉地不去改变所指对象的值
//const 指针
int errNumb = 0;
int *const curErr = &errNumb; //curErr将一直指向errNumb
const double pii = 3.13159;
const double * const pip = &pii;
//顶层const与底层const的概念
//顶层const表示指针本身是个常量,而底层const表示指针所指的对象是一个常量。
int ii = 0;
int *const p1 = ⅈ //不能改变p1的值,这是一个顶层const
const int ci = 42;//不能改变ci的值,这是一个顶层const
const int *p2 = &ci; //允许改变p2的值,这是一个底层const
const int *const p3 = p2; //靠右的const是顶层cosnt,靠左的是底层const
const int &r = ci; //用于声明引用的const都是底层const
return 0;
}
| true |
0ed9c379609cd0d8c7c1986dbe9d3f9292ab50a2 | C++ | AlfaIV/C-plus-plus--Stepic | /sum/sum.cpp | UTF-8 | 914 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
void sum(){
int len;
cin >> len;
//cout << len << "\n";
int a,b;
for(int j = 0; j < len; ++j){
//cout << j << " ";
cin >> a;
cin >> b;
//cout << a << " " << b << "\n";
cout << a + b;
if (j + 1 != len){
cout << "\n";
}
/*string input_str;
getline(cin, input_str);
cout << input_str << "\n";
char sep;
sep = ' ';
string one;
string second;
for (int i = 0; i < input_str.length(); ++i){
if (input_str[i] == sep){
//cout << 0;
one.assign(input_str,0,i);
second.assign(input_str,i+1,input_str.length());
break;
}
//cout << typeid(input_str[i]);
//cout << input_str[i] << "\n";
};
int a = stoi(one);
int b = stoi(second);
cout << a <<endl;
cout << b;*/
}
}
int main()
{
sum();
return 0;
} | true |
78392f122ffb849196aeaebcc533f4a672fc2cea | C++ | JingHuu/BreakoutHit | /GAD173/Main.h | UTF-8 | 4,131 | 3.171875 | 3 | [] | no_license | #pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
constexpr float windowX = { 1000 }; // window width
constexpr float windowY = { 600 }; // window height
const sf::Color colour = sf::Color(255, 255, 0, 255); // custom colour. value between 0-255 for R,G,B,A
class Game // gonna make this a game manager
{
public: // functions to run the game
bool Start();
int Update();
int LossLife();
private:
sf::RenderWindow window;
int score = 0;
int lives = 3;
};
class Rectangle
{
public:
sf::RectangleShape shape;
float x() { return shape.getPosition().x; }
float y() { return shape.getPosition().y; }
float left() { return x() - shape.getSize().x / 2.f; }
float right() { return x() + shape.getSize().x / 2.f; }
float top() { return y() - shape.getSize().y / 2.f; }
float bottom() { return y() + shape.getSize().y / 2.f; } // Rectangle boundaries. The origin would be set to the center of the shape.
};
// class of the Walls
class Wall
{
public:
sf::RectangleShape top;
sf::RectangleShape bottom;
sf::RectangleShape left;
sf::RectangleShape right;
bool SetWall()
{
top.setSize(sf::Vector2f(windowX, 1));
top.setPosition(0, 0);
top.setFillColor(sf::Color::Black);
bottom.setSize(sf::Vector2f(windowX, 1));
bottom.setPosition(sf::Vector2f(0, windowY - 1));
bottom.setFillColor(sf::Color::Black);
left.setSize(sf::Vector2f(1, windowY));
left.setPosition(0, 0);
left.setFillColor(sf::Color::Black);
right.setSize(sf::Vector2f(1, windowY));
right.setPosition(sf::Vector2f(windowX - 1, 0));
right.setFillColor(sf::Color::Black);
return true;
}
/*bool SetWall()
{
shape.setPosition(windowX / 2, windowY / 2);
shape.setSize( sf::Vector2f((windowX - 20.f), (windowY-20.f)));
shape.setOrigin((windowX-20) / 2, (windowY-20) / 2);
shape.setFillColor(sf::Color::Blue);
return true;
}*/
};
// make a class of the Paddle
class Paddle : public Rectangle
{
public:
const int velocity = 10; // paddle speed is constant, unless making powerups or debuff for it later
sf::Vector2f speed;
sf::Vector2f paddleSize = sf::Vector2f(200.f, 50.f); // size of the rectangle
Paddle(float mX, float mY)
{
shape.setPosition(mX, mY);
shape.setSize(paddleSize);
shape.setFillColor(colour);
shape.setOrigin(paddleSize.x / 2.f, paddleSize.y / 2.f); // set origin to the center
}
// Check player input within Update function
void Update()
{
shape.move(speed);
// check if left is pressed
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && left() > 0)
{
speed.x = -velocity;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && right() < windowX)
{
speed.x = velocity;
}
else
{
speed.x = 0;
}
}
};
// make a class of the bricks
class Brick : public Rectangle
{
public:
sf::RectangleShape bShape;
sf::Color bColour;
sf::Vector2f bSize;
sf::Vector2f bPos;
};
// make a class of ball
class Ball
{
public:
int ballRadius = 10; // setup ball size
int ballVelocity = 3;
sf::CircleShape shape;
sf::Vector2f velocity{ ballVelocity, ballVelocity };
Ball(float mX, float mY)
{
shape.setPosition(mX, mY);
shape.setRadius(ballRadius);
shape.setFillColor(sf::Color::Cyan);
shape.setOrigin(ballRadius, ballRadius); // set origin to the center of the ball
}
float x() { return shape.getPosition().x; } // Reminder: Object origin is set to the center.
float y() { return shape.getPosition().y; }
float left() { return x() - shape.getRadius(); }
float right() { return x() + shape.getRadius(); }
float top() { return y() - shape.getRadius(); }
float bottom() { return y() + shape.getRadius(); }
void Update()
{
shape.move(velocity);
// Set the window barrier for the ball. Temporary
/*if (left() < 0)
{
velocity.x = ballVelocity;
}
else if (right() > windowX)
{
velocity.x = -ballVelocity;
}
if (top() < 0)
{
velocity.y = ballVelocity;
}
else if (bottom() > windowY)
{
velocity.y = -ballVelocity;
}*/
}
};
| true |
6f124d0b66ae7caffa163fbf77615a0d359615a5 | C++ | hagego/SmartHome | /FS20ShutterControl/libraries/TinyTime/TinyTime.h | UTF-8 | 22,460 | 2.953125 | 3 | [] | no_license | #ifndef __TINYTIME_H
#define __TINYTIME_H
/**
* This class implements a time base with time based events.
* It only cares about time of day, not about the date.
* Events can be schedules as absolute time or relative to sunraise or sunset
*/
// some constants that cannot be put inside class declaration
const IPAddress NTP_SERVER(129,69,1,153); // rustime01.rus.uni-stuttgart.de
// NTP server used to get time (once per day)
const IPAddress EARTHTOOLS_SERVER(208,113,226,171); // www.earthtools.org
const char* EARTHTOOLS_SERVER_NAME = "www.earthtools.org";
// used to query sunraise/sunset times (once per day)
const char* LONGITUDE = "9.326123"; // longitude to query sunraise/sunset times
const char* LATITUDE = "48.635135"; // latitude to query sunraise/sunset times
class Time {
static const unsigned int UTC_OFFSET = 1; // offset from UTC in hours w/o DST
static const unsigned int NTP_PORT = 123; // port of the NTP protocol
static const unsigned int NTP_PACKET_SIZE = 48; // size of an NTP packet
static const unsigned int UDP_PORT = 8888; // local port to listen for UDP packets
static const unsigned int EEPROM_BASE_ADDR = 0; // EEPROM base adress to store event data
public:
// defines the mode for an event:
// OFF: The event is disabled
// ABSOLUTE: The event is scheduled as absolute time of the day
// SUNRAISE: The event is scheduled relative to sunraise
// SUNSET: The event is scheduled relative to sunset
enum Mode {OFF,ABSOLUTE,SUNRISE,SUNSET};
/**
* constructor
*/
Time(unsigned int parEventCount) : eventCount(parEventCount),dstActive(true),syncSuccess(false),
timeSunrise(0),timeSunset(0), syncDoneToday(false) {
}
/**
* destructor
*/
~Time() {
delete[] events;
}
/**
* initializes the object. Must be called AFTER Ethernet is activated
*/
void init() {
//syncTimestamp[0] = '\0';
// create an array with events according to the specified count and fill with disabled events
events = new Event[eventCount];
for(unsigned int event=0 ; event<eventCount ; event++) {
events[event].time = 0;
events[event].mode = OFF;
events[event].offset = 0;
events[event].fired = false;
events[event].fireOnce = true;
events[event].pFunction = NULL;
}
udp.begin(UDP_PORT);
};
/**
* reads stored event data from EEPROM (if available)
*/
void readEeprom() {
// check if EEPROM looks to be initialized
byte readVal = EEPROM.read(EEPROM_BASE_ADDR);
if(readVal != eventCount) {
//Serial.println("initializing eeprom");
// EEPROM not initialized for this application
EEPROM.write(EEPROM_BASE_ADDR,(byte)eventCount);
for(unsigned int event=0 ; event<eventCount ; event++) {
eepromStoreEventData(event);
}
}
else {
//Serial.println("reading from eeprom");
// EEPROM seems to contain meaningful values
for(unsigned int event=0 ; event<eventCount ; event++) {
eepromReadEventData(event);
}
}
}
void dump() {
//Serial.println("event dump:");
for(unsigned int event=0 ; event<eventCount ; event++) {
//Serial.print(" event ID = ");Serial.println(event);
//Serial.print(" time = ");Serial.println(events[event].time);
//Serial.print(" mode = ");Serial.println(events[event].mode);
//Serial.print(" fired = ");Serial.println(events[event].fired);
//Serial.print(" fireOnce = ");Serial.println(events[event].fireOnce);
}
}
/**
* synchronizes the time from an NTP server, queries todays sunraise and sunset times
* and updates the absolute event time for all relative events.
* It should be enough to do this max. once per day
*/
boolean sync() {
//
// synchronize time from NTP server
//
Serial.println( F("NTP sync started") );
// assume success. Will be set to false in case of any error
syncSuccess = true;
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
packetBuffer[0] = 0b11100011; // LI=3 (unknown), Version=4, Mode=3 (client)
packetBuffer[1] = 0; // Stratum, or type of clock = 0 (unspecified)
packetBuffer[2] = 6; // Polling Interval (default)
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49; // 4 byte reference ID
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all required NTP fields have been given values, nowsend packet requesting a timestamp:
udp.beginPacket(NTP_SERVER, NTP_PORT);
udp.write(packetBuffer,NTP_PACKET_SIZE);
udp.endPacket();
Serial.println( F("NTP package sent") );
delay(500); // wait for answer
unsigned int month,
dayOfMonth;
if ( udp.parsePacket() ) {
//Serial.println("NTP package received");
// We've received a packet, read the data from it
udp.read(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer
// the timestamp starts at byte 40 of the received packet and is four bytes long
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
// now convert NTP time into everyday time:
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// correct timezone
epoch += UTC_OFFSET*3600;
// figure out if DST is active.
// the following is based on time.c - low level time and date functions, (c) Michael Margolis 2009
#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
unsigned long daysSince1970 = epoch/86400;
unsigned int wDay = ((daysSince1970 + 4) % 7) + 1; // Sunday is day 1
unsigned int year = 0; // years after 1970
unsigned int days = 0;
while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= daysSince1970) {
year++;
}
days -= LEAP_YEAR(year) ? 366 : 365;
unsigned int dayOfYear = daysSince1970 - days;
month=0;
for( month=0; month<12; month++) {
unsigned int monthLength = monthDays[month];
if (month==1 && (LEAP_YEAR(year))) { // february
monthLength++;
}
if (dayOfYear >= monthLength) {
dayOfYear -= monthLength;
} else {
break;
}
}
month++; // make Jan month 1
dayOfMonth = dayOfYear+1;
// now determine if DST is active.
// DST starts last Sunday of March and ends last Sunday in October
// (8-wDay)%7 results in days till next Sunday
dstActive = ( (month>3 && month<10) || (month==3 && dayOfMonth+((8-wDay)%7)>31) || (month==10 && dayOfMonth+((8-wDay)%7)<31)) ? true : false;
// correct for DST
if(dstActive) {
// add 1h
epoch += 3600;
}
// for now we only use seconds of the day
lastSync.secondOfDay = epoch%86400UL;
lastSync.millisSinceBoot = millis();
unsigned int h = lastSync.secondOfDay/3600UL,
m = (lastSync.secondOfDay%3600UL)/60UL,
s = lastSync.secondOfDay%60UL;
Serial.println( F("NTP sync success") );
sprintf(syncTimestamp,"%02d.%02d.%02d %02d:%02d:%02d DST=%d",dayOfMonth,month,(1970+year)%100,h,m,s,dstActive);
Serial.println(syncTimestamp);
syncDoneToday = true;
}
else {
// error: no answer from UTP server
syncSuccess = false;
//Serial.println("NTP sync failed");
}
//
// query todays sunraise and sunset time
//
// send http request to www.earthtools.com
char request[100];
//Serial.println("connecting to earthtools");
if( tcpClient.connect(EARTHTOOLS_SERVER,80) ) {
//Serial.println("http connected");
sprintf(request,"GET /sun-1.0/%s/%s/%d/%d/1/0 HTTP/1.1",LATITUDE,LONGITUDE,dayOfMonth,month);
tcpClient.println(request);
sprintf(request,"Host: %s",EARTHTOOLS_SERVER_NAME);
tcpClient.println(request);
tcpClient.println("Connection: close");
tcpClient.println();
//Serial.println("earthtools request sent");
// receive answer and parse XML
const unsigned long timeout = 2000; // timeout 2 seconds
unsigned long timeStart = millis(); // start time
unsigned long timeNow = timeStart;
bool completed = false;
const unsigned int BUFFERSIZE = 10;
char buffer[BUFFERSIZE],
content[BUFFERSIZE];
unsigned int pos = 0;
buffer[0] = '\0';
content[0] = '\0';
while( !completed && timeNow>=timeStart && timeNow-timeStart<timeout ) {
if( tcpClient.available() ) {
char c=tcpClient.read();
if( c=='<' ) {
// start of XML tag. copy buffer into content and reset
//Serial.println("tag start");
buffer[pos] = '\0';
strcpy(content,buffer);
//Serial.println(content);
pos = 0;
}
else if( c=='>' ) {
// end of XML tag
//Serial.println("tag end");
buffer[pos] = '\0';
pos = 0;
if(strcmp(buffer,"/sunrise")==0) {
timeSunrise = 3600UL*atol(content)+60UL*atol(content+3)+atol(content+6);
// correct for DST
if(dstActive) {
// add 1h
timeSunrise += 3600;
}
//Serial.println("sunrise=");Serial.println(content);
}
if(strcmp(buffer,"/sunset")==0) {
timeSunset = 3600UL*atol(content)+60UL*atol(content+3)+atol(content+6);
// correct for DST
if(dstActive) {
// add 1h
timeSunset += 3600;
}
//Serial.println("sunset=");Serial.println(content);
}
if(strcmp(buffer,"/sun")==0) {
completed = true;
}
}
else {
// inside tag
if(pos<BUFFERSIZE-2) {
buffer[pos++] = c;
}
}
}
timeNow = millis();
}
tcpClient.stop();
if(timeSunrise==0 || timeSunset==0) {
// sunrise/sunset time(s) could not be queried
syncSuccess = false;
}
else {
// set absolute event time of all sunrise/sunset relative events
for(unsigned int event=0 ; event<eventCount ; event++) {
if(events[event].mode == SUNRISE) {
events[event].time = timeSunrise + events[event].offset;
}
if(events[event].mode == SUNSET) {
events[event].time = timeSunset + events[event].offset;
}
}
}
}
else {
// query failed
//Serial.println("earthtools connect failed");
syncSuccess = false;
}
//Serial.println("sync end");
return syncSuccess;
};
/**
* Updates the actual time
*/
void update(boolean syncNtp=false) {
unsigned long current = millis(),
delta;
if(current<lastSync.millisSinceBoot) {
// wrap around
delta = (0xFFFFFFFFUL-lastSync.millisSinceBoot+current)/1000UL;
}
else {
delta = (current-lastSync.millisSinceBoot)/1000UL;
}
actualTime.secondOfDay = lastSync.secondOfDay+delta;
boolean newDay = (actualTime.secondOfDay>86400UL);
actualTime.secondOfDay %= 86400UL;
actualTime.millisSinceBoot = current;
// a snc() might reset the time to the very end of the previous day so newDay
// might actually happen twice
if(syncNtp || (!syncDoneToday && actualTime.secondOfDay>3600 && actualTime.secondOfDay<4000)) {
// sync with NTP server and update events with relative time
sync();
syncError = abs(actualTime.secondOfDay-lastSync.secondOfDay);
actualTime = lastSync;
}
// enable events for this day again
if(newDay) {
syncDoneToday = false;
for(unsigned int event=0 ; event<eventCount ; event++) {
events[event].fired = false;
}
}
}
/**
* Check if an event needs to be fired
*/
void checkEvents() {
for(unsigned int event=0 ; event<eventCount ; event++) {
if(events[event].mode != OFF) {
if(!events[event].fired && actualTime.secondOfDay>=events[event].time) {
// fire event
//Serial.print("fire event, ID=");Serial.println(event);
events[event].fired = true;
events[event].pFunction();
// disable event if it should be active only for one day
if(events[event].fireOnce) {
events[event].mode = OFF;
}
}
}
}
}
/**
* returns the time stamp of the last sync
*/
char* getSyncTimestamp() {
//return syncTimestamp;
return "";
}
/**
* returns the time as seconds of the day
*/
unsigned long getSecondsOfDay() {
update();
return actualTime.secondOfDay;
};
/**
* returns the sunrise time as seconds of day
*/
unsigned long getSunriseTime() {
return timeSunrise;
}
/**
* returns the sunset time as seconds of day
*/
unsigned long getSunsetTime() {
return timeSunset;
}
/**
* returns the error offset that was determined at the last sync
*/
unsigned long getSyncError() {
return syncError;
}
/**
* adds an event
* returns the id for this event for further calls dealing with it
*/
unsigned int addEvent(void (*pFunction)()) {
static unsigned int index = 0; // keep track of index for next event
if(index<eventCount) {
// event can be added
events[index].pFunction = pFunction;
}
index++;
return index-1;
}
/**
* enables/disables an event
*/
void setEventMode(unsigned int eventId,Mode mode) {
if(eventId<eventCount) {
events[eventId].mode = mode;
// update EEPROM
eepromStoreEventData(eventId);
// check if event still need to be fired today
if( actualTime.secondOfDay>=events[eventId].time ) {
events[eventId].fired = true;
}
else {
events[eventId].fired = false;
}
}
}
/**
* returns the enabled state of an event
*/
Mode getEventMode(unsigned int eventId) {
if(eventId<eventCount) {
return events[eventId].mode;
}
return OFF;
}
/**
* sets the fireOnce status
*/
void setEventFireOnce(unsigned int eventId,bool fireOnce) {
if(eventId<eventCount) {
events[eventId].fireOnce = fireOnce;
}
}
/**
* returns the fireOnce status
*/
bool getEventFireOnce(unsigned int eventId) {
if(eventId<eventCount) {
return events[eventId].fireOnce;
}
}
/**
* sets the event time
*/
void setEventTime(unsigned int eventId,unsigned long eventTime) {
if(eventId<eventCount) {
events[eventId].time = eventTime;
// update EEPROM
eepromStoreEventData(eventId);
// check if event still needs to happen today
if( actualTime.secondOfDay>=events[eventId].time ) {
events[eventId].fired = true;
}
else {
events[eventId].fired = false;
}
}
}
/**
* returns the event time
*/
unsigned long getEventTime(unsigned int eventId) {
if(eventId<eventCount) {
return events[eventId].time;
}
return 0;
}
/**
* sets the offset for relative events
*/
void setEventOffset(unsigned int eventId,long eventOffset) {
if(eventId<eventCount) {
events[eventId].offset = eventOffset;
if(events[eventId].mode==SUNRISE) {
events[eventId].time = timeSunrise+eventOffset;
}
if(events[eventId].mode==SUNSET) {
events[eventId].time = timeSunset+eventOffset;
}
// update EEPROM
eepromStoreEventData(eventId);
// check if event still needs to happen today
if( actualTime.secondOfDay>=events[eventId].time ) {
events[eventId].fired = true;
}
else {
events[eventId].fired = false;
}
}
}
/**
* returns the event offset for relative events
*/
unsigned long getEventOffset(unsigned int eventId) {
if(eventId<eventCount) {
return events[eventId].offset;
}
return 0;
}
private:
// EEPROM format:
// EEPROM_BASE_ADDR event count
// EEPROM_BASE_ADDR+1 event ID 0 mode (1 byte)
// EEPROM_BASE_ADDR+2 event ID 0 time (4 bytes)
// EEPROM_BASE_ADDR+6 event ID 0 offset (4 bytes)
// EEPROM_BASE_ADDR+10 event ID 1 mode (1 byte)
// ...
// 9 bytes per event
/**
* stores event data (mode,time,offset) in the EEPROM
*/
void eepromStoreEventData(unsigned int eventId) {
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9,events[eventId].mode);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+1,(events[eventId].time/65536)/256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+2,(events[eventId].time/65536)%256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+3,(events[eventId].time%65536)/256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+4,(events[eventId].time%65536)%256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+5,(events[eventId].offset/65536)/256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+6,(events[eventId].offset/65536)%256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+7,(events[eventId].offset%65536)/256);
EEPROM.write(EEPROM_BASE_ADDR+1+eventId*9+8,(events[eventId].offset%65536)%256);
}
/**
* reads event data (mode,time,offset) from EEPROM
*/
void eepromReadEventData(unsigned int eventId) {
events[eventId].mode = (Mode)EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9);
byte b1 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+1);
byte b2 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+2);
byte b3 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+3);
byte b4 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+4);
events[eventId].time = (b1*256+b2)*65536+(b3*256+b4);
b1 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+5);
b2 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+6);
b3 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+7);
b4 = EEPROM.read(EEPROM_BASE_ADDR+1+eventId*9+8);
events[eventId].offset = (b1*256+b2)*65536+(b3*256+b4);
// don't fire event if its time is already gone past today
if(events[eventId].time > actualTime.secondOfDay) {
events[eventId].fired = true;
}
else {
events[eventId].fired = false;
}
}
// maps milliseconds since boot to a time (seconds of day)
struct Timestamp {
unsigned long secondOfDay;
unsigned long millisSinceBoot;
};
// struct to control events
struct Event {
unsigned long time; // absolute time for the event as seconds of day
Mode mode; // event enabled, absolute, or relative to sunraise/sunset ?
long offset; // offset to the reference time for relative events
boolean fired; // true if the event was already fired this day
boolean fireOnce; // if true, the event will be automatically disbaled after it fired
void (*pFunction)(); // pointer to the function that will be called when the event fires
};
// array storing all events
Event *events;
byte packetBuffer[NTP_PACKET_SIZE]; // UDP buffer for NTP protocol
EthernetUDP udp; // UDP object
EthernetClient tcpClient; // TCP client
Timestamp lastSync; // the timestamp of the last synchronization
Timestamp actualTime; // actual time. Only valid after update() or syncIfNeeded()
unsigned long syncError; // offset to real time in seconds before last sync
boolean syncSuccess; // last sync successfull ?
boolean dstActive; // daylight saving time active ?
boolean syncDoneToday; // NTP sync done today already ?
//char syncTimestamp[30]; // time & date of last sync as string
unsigned int eventCount; // numer of time events to handle
unsigned long timeSunrise; // time of sunrise as seconds of day
unsigned long timeSunset; // time of sunset as seconds of day
};
#endif | true |
a2d0ae6b17c7f28b2592a91f722ecfe62c0289d6 | C++ | ras0219/mlcard | /shared/game.h | UTF-8 | 4,905 | 2.71875 | 3 | [] | no_license | #pragma once
#pragma once
#include "vec.h"
#include <fmt/format.h>
#include <string>
#include <vector>
enum class ArtifactType
{
DirectImmune,
CreatureImmune,
DoubleMana,
HealCauseDamage,
LandCauseDamage,
Count,
};
const char* artifact_name(ArtifactType t);
struct Card
{
enum class Type
{
Creature,
Direct,
Heal,
Land,
Draw3,
Artifact,
Count,
};
Type type;
union
{
int value;
ArtifactType artifact;
};
void randomize();
void encode(vec_slice x) const;
static constexpr size_t encoded_size = (size_t)Type::Count + (size_t)ArtifactType::Count;
};
const char* card_name(Card::Type t);
struct Player
{
int health = 20;
int land = 1;
int creature = 0;
ArtifactType artifact = ArtifactType::Count;
std::vector<Card> avail;
static constexpr size_t encoded_size = 4 + (size_t)ArtifactType::Count;
void encode(vec_slice x) const;
void encode_cards(vec_slice x) const;
void init(bool p1);
int cards() const { return (int)avail.size(); }
};
struct Encoded
{
static constexpr size_t board_size = 4 + Player::encoded_size * 2;
static constexpr size_t card_size = Card::encoded_size;
vec data;
vec_slice board() { return data.slice(0, board_size); }
vec_slice me_cards_in() { return data.slice(board_size, me_cards * card_size); }
vec_slice you_cards_in() { return data.slice(board_size + me_cards * card_size, you_cards * card_size); }
vec_slice me_card(int i) { return data.slice(board_size + i * card_size, card_size); }
vec_slice you_card(int i) { return data.slice(board_size + (i + me_cards) * card_size, card_size); }
int me_cards = 0;
int you_cards = 0;
int avail_actions() const { return me_cards + 1; }
};
struct Game
{
Player p1;
Player p2;
bool player2_turn = false;
int turn = 0;
int mana = 0;
bool played_land = false;
Encoded encode() const;
void init();
Player& cur_player() { return player2_turn ? p2 : p1; }
void advance(int action);
std::string format() const;
std::vector<std::string> format_public_lines() const;
static const char* help_html(std::string_view pg);
std::vector<std::string> input_descs();
std::vector<std::string> format_actions();
void serialize(struct RJWriter& w);
void deserialize(const std::string& str);
enum class Result
{
p1_win,
p2_win,
playing,
timeout,
};
Result cur_result() const
{
if (p1.health <= 0) return Result::p2_win;
if (p2.health <= 0) return Result::p1_win;
if (turn > 30) return Result::timeout;
return Result::playing;
}
};
template<>
struct fmt::formatter<vec_slice>
{
constexpr auto parse(format_parse_context& ctx)
{
if (ctx.begin() != ctx.end() && *ctx.begin() != '}') throw format_error("invalid format");
return ctx.begin();
}
template<typename FormatContext>
auto format(vec_slice p, FormatContext& ctx) -> decltype(ctx.out())
{
if (p.size() == 0) return format_to(ctx.out(), "()");
auto out = format_to(ctx.out(), "({: 4.2f}", p[0]);
for (size_t i = 1; i < p.size(); ++i)
out = format_to(out, ", {: 4.2f}", p[i]);
return format_to(out, ")");
}
};
template<>
struct fmt::formatter<std::vector<int>>
{
constexpr auto parse(format_parse_context& ctx)
{
if (ctx.begin() != ctx.end() && *ctx.begin() != '}') throw format_error("invalid format");
return ctx.begin();
}
template<typename FormatContext>
auto format(std::vector<int> const& p, FormatContext& ctx) -> decltype(ctx.out())
{
if (p.size() == 0) return format_to(ctx.out(), "()");
auto out = format_to(ctx.out(), "({}", p[0]);
for (size_t i = 1; i < p.size(); ++i)
out = format_to(out, ", {}", p[i]);
return format_to(out, ")");
}
};
template<>
struct fmt::formatter<std::vector<Card>>
{
constexpr auto parse(format_parse_context& ctx)
{
if (ctx.begin() != ctx.end() && *ctx.begin() != '}') throw format_error("invalid format");
return ctx.begin();
}
template<typename FormatContext>
auto format(std::vector<Card> const& p, FormatContext& ctx) -> decltype(ctx.out())
{
if (p.size() == 0) return format_to(ctx.out(), "()");
auto out = format_to(ctx.out(), "({}.{}", (int)p[0].type, p[0].value);
for (size_t i = 1; i < p.size(); ++i)
out = format_to(out, ", {}.{}", (int)p[i].type, p[i].value);
return format_to(out, ")");
}
};
| true |
1d4265911e1456a2c2b221b2beec3aafa11644c4 | C++ | thomoncik/hexadoku | /src/Model/BoardCell.cpp | UTF-8 | 826 | 2.890625 | 3 | [
"MIT"
] | permissive | //
// Created by Jakub Kiermasz on 2019-05-11.
//
#include <Model/BoardCell.hpp>
const int BoardCell::EMPTY_VALUE = 0;
const int BoardCell::MAX_HEXADOKU_VALUE = 16;
const int BoardCell::MAX_STANDARD_VALUE = 9;
BoardCell::BoardCell() : isSelected(false), isCorrect(true), value(EMPTY_VALUE) {
}
void BoardCell::SetValue(int value) {
this->value = value;
}
int BoardCell::GetValue() const {
return this->value;
}
void BoardCell::SetIsCorrect(bool isCorrect) {
if (value == BoardCell::EMPTY_VALUE) {
this->isCorrect = true;
return;
}
this->isCorrect = isCorrect;
}
void BoardCell::SetSelected(bool isSelected = true) {
this->isSelected = isSelected;
}
bool BoardCell::IsSelected() const {
return this->isSelected;
}
bool BoardCell::IsCorrect() const {
return this->isCorrect;
}
| true |
faa48ad2759121a7183570972d080c5cc24ce157 | C++ | adityanjr/code-DS-ALGO | /GeeksForGeeks/Practice/NDigitNumbersWithDigitsInIncreasingOrder.cpp | UTF-8 | 897 | 3.171875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <queue>
#include <string>
using namespace std;
struct temp{
long long int num;
int last;
int len;
};
int main() {
//code
int test;
cin >> test;
while(test--){
int n;
cin >> n;
queue<temp> q;
for(int i = 1; i <= 9; i++){
temp t;
t.num = i;
t.last = i;
t.len = 1;
q.push(t);
}
while(!q.empty()){
temp t = q.front();
if(t.len == n){
cout << t.num << " ";
}
else if(t.len < n){
for(int i = t.last+1; i <= 9; i++){
temp t1;
t1.num = stoll(to_string(t.num) + to_string(i));
t1.last = i;
t1.len = t.len + 1;
q.push(t1);
}
}
q.pop();
}
cout << endl;
}
return 0;
}
| true |
23c60370ba35739b0a003226e6db1719215acb43 | C++ | lucasbivar/competitive-programming | /competitions/SBC Marathon/SBC_2020/E/e.cpp | UTF-8 | 1,084 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstring>
using namespace std;
vector<int> amgs[100005];
int idades[100005];
int visited[100005];
int qtd[100005];
int anf, l, r;
void DFS(int x){
for(int i = 0; i < amgs[x].size(); i++){
int v = amgs[x][i];
if(visited[v] != -1) continue;
if(idades[v] < l || idades[v] > r) continue;
visited[v] = 1;
qtd[v] += 1;
DFS(v);
}
}
int main(){
cin.tie(NULL);
cout.tie(NULL);
ios::sync_with_stdio(0);
int p, f, a, b;
cin >> p >> f;
for(int i = 1; i <= p; i++){
cin >> a >> b;
idades[i] = a;
amgs[i].push_back(b);
amgs[b].push_back(i);
}
memset(qtd, 0, sizeof(qtd));
for(int i = 0; i < f; i++){
cin >> anf >> l >> r;
memset(visited, -1, sizeof(visited));
visited[anf] = 1;
qtd[anf] += 1;
DFS(anf);
}
cout << qtd[1];
for(int i = 2; i <= p; i++){
cout << " " << qtd[i];
}
cout << endl;
return 0;
} | true |
c0714f425c4ea515530f861fe4a79f213fa4fd3d | C++ | claudiiolima/Prog_III | /Aula06/Car/Car.cpp | UTF-8 | 740 | 3.34375 | 3 | [] | no_license | #include "Car.h"
Car::Car(int year, string brand) : yearModel(year), make(brand), speed(0) {}
int Car::getYearModel() { return yearModel; }
void Car::setYearModel(int year) { yearModel = year; }
string Car::getMake() { return make; }
void Car::setMake(string brand) { make = brand; }
int Car::getSpeed() { return speed; }
void Car::setSpeed(int s) { speed = s; }
void Car::accelerate() { speed += 5; }
void Car::brake() { speed -= 5; }
ostream &operator<<(ostream &out, const Car &C) {
out << C.make << ": " << C.yearModel << endl << C.speed << " km/h" << endl;
return out;
}
istream &operator>>(istream &in, Car &C) {
cout << "Modelo, Marca, Velocidade" << endl;
in >> C.yearModel >> C.make >> C.speed;
return in;
}
| true |
25aaf9cfc7f4fcd40afef6be398b90a1bb089c09 | C++ | RichardKlem/IMS | /main.cpp | UTF-8 | 1,743 | 2.515625 | 3 | [] | no_license | /**
* @author1: Martin Haderka
* @author2: Richard Klem
* @email1: xhader00@stud.fit.vutbr.cz
* @email2: xklemr00@stud.fit.vutbr.cz
* @login1: xhader00
* @login2: xklemr00
* @date: 6.11.2020
*/
#include <iostream>
#include "CellularAutomaton.h"
#include "main.h"
int main(int argc, char *argv[]) {
unsigned int x = 23, y = 23, step = 1000, number = 60, initInfectionRate = 10, initImmuneRate = 20,
forwardP = 20, rightP = 20, leftP = 20, backP = 20, stayP = 20;
string dumpDir = "./";
vector<pair<unsigned int, unsigned int>> walls {{17, 0}, {17, 1}, {17, 2}, {17, 3},
{17, 4}, {17, 5}, {17, 6}, {18, 6},
{19, 6},
{0, 11}, {1, 11}, {2, 11}, {3, 11},
{4, 11}, {5, 11}, {6, 11}, {7, 11},
{8, 11}, {9, 11}, {10, 11}, {11, 11},
{12, 11}, {13, 11}, {14, 11}, {15, 11},
{16, 11}, {17, 11}, {17, 12}, {17, 13},
{17, 14}, {17, 15}, {17, 16}, {17, 17},
{17, 18}};
if (argc > 1)
argParse(argc, argv, &number, &initInfectionRate, &initImmuneRate, &x, &y, &step, &forwardP, &rightP,
&leftP, &backP, &stayP, &dumpDir);
CellularAutomaton CA(x, y, number, &walls);
CA.initWalls(&CA.getMatrix());
CA.initCellPositions();
CA.initPersonPositions();
CA.simulate(step, initInfectionRate, initImmuneRate, forwardP, rightP, leftP, backP, stayP, &dumpDir);
return 0;
}
| true |
0912020094a053f32c3815a09a933b9e9671eb96 | C++ | radtek/Pos | /MenuMate/MenuMate/Source/product-count-down/spinlock.cpp | UTF-8 | 452 | 2.546875 | 3 | [] | no_license | #include <spinlock.hh>
namespace utilities {
namespace locking {
spinlock::spinlock()
: lock_(false)
{
}
spinlock::~spinlock()
{
}
void
spinlock::enter()
{
while (InterlockedCompareExchange(&lock_, true, false))
;
}
void
spinlock::exit()
{
InterlockedExchange(&lock_, false);
}
bool
spinlock::try_enter()
{
return !InterlockedCompareExchange(&lock_, true, false);
}
} /* locking */
} /* utilities */
| true |
a4c56703f900d8c99c759d124737861b83cfb8ec | C++ | virtyaluk/leetcode | /problems/1499/solution.cpp | UTF-8 | 1,283 | 3.03125 | 3 | [] | no_license | // yi + yj + |xi - xj| = yi + xi + yj - xj
class Solution {
public:
int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
int ans = INT_MIN;
deque<pair<int, int>> dq; // xj, yj - xj
for (const vector<int>& point: points) {
int xj = point[0], yj = point[1], dif = yj - xj;
while (not empty(dq) and xj - dq.front().first > k) {
dq.pop_front();
}
if (not empty(dq)) {
ans = max(ans, yj + xj + dq.front().second);
}
while (not empty(dq) and (dq.back().second <= dif or xj - dq.back().first > k)) {
dq.pop_back();
}
dq.push_back({xj, dif});
}
return ans;
}
int findMaxValueOfEquation1(vector<vector<int>>& points, int k) {
int ans = INT_MIN, n = size(points);
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (abs(points[i][0] - points[j][0]) <= k) {
ans = max(ans, points[i][1] + points[j][1] + abs(points[i][0] - points[j][0]));
}
}
}
return ans;
}
}; | true |
5095ffc7ade8684b8ca90e0a2dffb912f1b553b5 | C++ | skeimeier/Arduino | /JEE/JeeBlink/JeeBlink.ino | UTF-8 | 594 | 3.125 | 3 | [] | no_license |
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
#include <Ports.h>
Port led (1);
void setup() {
Serial.begin(57600);
Serial.println("\n[JeeBlink]");
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
led.mode( OUTPUT);
}
void loop() {
led.digiWrite(HIGH); // set the LED on
delay(100); // wait for a second
led.digiWrite(LOW); // set the LED off
delay(100); // wait for a second
}
| true |
8c1f0b83741224e6943bb3aee035b718ae6e2fff | C++ | jiangyinzuo/icpc | /data_structure/segment_tree/yinchuan_g.cpp | UTF-8 | 3,270 | 2.84375 | 3 | [] | no_license | //
// Created by jiang on 2020/8/12.
//
#include <cstdio>
#include <cstring>
#include <array>
long long seq[100008];
std::array<int, 4> seg_tree[400008]; // 本题build初始化
std::array<int, 4> multi_tags[400008];
/**
* 下推懒惰标记
* @param l 左区间端点
* @param r 右区间端点
* @param num 序号
*/
void push_down(int l, int r, int num) {
for (int i = 0; i < 4; ++i)
if (multi_tags[num][i]) {
seg_tree[num << 1][i] += multi_tags[num][i];
seg_tree[num << 1 | 1][i] += multi_tags[num][i];
multi_tags[num << 1][i] += multi_tags[num][i];
multi_tags[num << 1 | 1][i] += multi_tags[num][i];
multi_tags[num][i] = 0;
}
}
/**
* 区间更新
* @param update_l 更新区间左端点
* @param update_r 更新区间右端点
* @param value 更新的值
* @param l 当前搜索区间左端点
* @param r 当前搜索区间右端点
* @param num 线段树序号
*/
void update(int update_l, int update_r, long long value, int l, int r, int num) {
#define ADD(n, v) (multi_tags[num][n] += v, seg_tree[num][n] += v)
if (update_l <= l && r <= update_r) {
if (value == 2) ADD(0, 1);
else if (value == 3) ADD(1, 1);
else if (value == 4) ADD(0, 2);
else if (value == 5) ADD(2, 1);
else if (value == 6) {
ADD(0, 1);
ADD(1, 1);
} else if (value == 7) ADD(3, 1);
else if (value == 8) ADD(0, 3);
else if (value == 9) ADD(1, 2);
else if (value == 10) {
ADD(0, 1);
ADD(2, 1);
}
return;
}
push_down(l, r, num);
int mid = (l + r) / 2;
if (update_l <= mid) {
update(update_l, update_r, value, l, mid, num << 1);
}
if (mid + 1 <= update_r) {
update(update_l, update_r, value, mid + 1, r, num << 1 | 1);
}
for (int i = 0; i < 4; ++i)
seg_tree[num][i] = std::max(seg_tree[num << 1][i], seg_tree[num << 1 | 1][i]);
}
/**
* 区间查询
* @param query_l 查询区间左端点
* @param query_r 查询区间右端点
* @param l 当前搜索区间左端点
* @param r 当前搜索区间右端点
* @param num 线段树序号
* @return 区间查询结果(求区间和)
*/
long long query(int query_l, int query_r, int l, int r, int num) {
if (query_l <= l && r <= query_r) {
int max_value = 0;
for (auto &i : seg_tree[num]) {
max_value = std::max(max_value, i);
}
return max_value;
}
push_down(l, r, num);
long long result = 0;
int mid = (l + r) / 2;
if (query_l <= mid) {
result = std::max(result, query(query_l, query_r, l, mid, num << 1));
}
if (mid + 1 <= query_r) {
result = std::max(result, query(query_l, query_r, mid + 1, r, num << 1 | 1));
}
return result;
}
int main() {
int n, q;
scanf("%d %d", &n, &q);
memset(seq, 1, sizeof(seq));
char op[10];
int n1, n2, n3;
for (int i = 0; i < q; ++i) {
scanf("%s %d %d", op, &n1, &n2);
if (op[1] == 'U') {
scanf("%d", &n3);
update(n1, n2, n3, 1, n, 1);
} else {
printf("ANSWER %lld\n", query(n1, n2, 1, n, 1));
}
}
return 0;
} | true |
d8adaaa36555c136f0b5f3977f7ec1a1856818e1 | C++ | tdcoish/GUNSLINGER_PLAYART_CREATOR | /PlayArtCreator/Structs.h | UTF-8 | 1,566 | 2.78125 | 3 | [] | no_license | #pragma once
#include <string>
#include <list>
struct Vec2 {
int x, y;
Vec2 operator+(const Vec2& v2) {
Vec2 v;
v.x = x + v2.x;
v.y = y + v2.y;
return v;
}
Vec2 operator-(const Vec2& v2) {
Vec2 v;
v.x = x - v2.x;
v.y = y - v2.y;
return v;
}
Vec2 operator*(const int val) {
Vec2 v;
v.x = x * val;
v.y = y * val;
return v;
}
Vec2 operator/(const int val) {
Vec2 v;
v.x = x / val;
v.y = y / val;
return v;
}
};
struct DATA_Zone {
std::string mName;
Vec2 mSpot;
};
struct ZoneHolder{
int numZones;
DATA_Zone* aZones;
};
struct DATA_Route {
std::string mName;
int numSpots;
Vec2* aSpots;
};
struct RouteHolder {
int numRoutes;
DATA_Route* aRoutes;
};
struct DATA_PlayRole {
std::string mTag;
std::string mRole;
std::string mDetail;
Vec2 mStart;
};
struct DATA_Off_Route {
std::string mOwner;
int mNumSpots;
Vec2* mSpots;
};
struct DATA_Off_Play {
std::string mName;
std::string mFormation;
int mNumReceivers;
int mNumPlayers;
std::string* aTags;
std::string* aRoles;
DATA_Off_Route* aRoutes;
};
struct DATA_Off_Formation {
int mNumPlayers;
std::string mName;
std::string* aTags;
Vec2* aSpots;
};
struct DATA_Def_Play {
std::string mName;
int numPlayers;
DATA_PlayRole* pRoles;
};
struct OffPlayHolder {
int mNumPlays;
DATA_Off_Play* aPlays;
};
struct OffFormationHolder {
int numFormations;
DATA_Off_Formation* aFormations;
};
struct DefPlayHolder {
int numPlays;
DATA_Def_Play* aPlays;
}; | true |
f3abacbc91b97ebc29a031fb41da2962cab1dea7 | C++ | busraeskiyurt/arduino | /sunflower.ino | UTF-8 | 804 | 3.0625 | 3 | [] | no_license | #include<Servo.h>
int a =90;
Servo sevro;
void setup() {
Serial.begin(9600);
sevro.attach(8);
sevro.write(90); //we move the servo motor to the 90 position at the start
}
void loop() {
int ldr1 = analogRead(A0);
Serial.println(ldr1);
int ldr2 = analogRead(A1);
Serial.println(ldr2);
delay(100);
if(ldr1 > 650 && ldr2 < 800){ //As long as a is more than 21, we take the servo motor to "a"position by decreasing "a" one at a time.
while(a>21){
a=a-1;
sevro.write(a);
delay(50);
}
}
if(ldr1 < 650 && ldr2 > 800){ //As long as a is less than 151, we take the servo motor to "a"position by increasing "a" one at a time.
while(a<151){
a=a+1;
sevro.write(a);+,
delay(50);
}
}
}
| true |
ad6e70bddd18c4ab57ff65ccf735ea153dd2081e | C++ | ShubhikaBhardwaj/Leetcode-Coding | /journeytoMoon.cpp | UTF-8 | 1,026 | 2.859375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Edge
{ public:
int v;
Edge(int v)
{
this->v=v;
}
};
vector<vector<Edge>> graph;
void addEdge(int v,int u)
{
graph[v].push_back(u);
graph[u].push_back(v);
}
int ConnectedComp(int x,vector<bool>&vis)
{
vis[x]=true;
int c=0;
for(Edge e:graph[x])
{
if(!vis[e.v])
{
c=ConnectedComp(e.v,vis);
}
}
return c+1;
}
vector<string> split_string(string);
int journeyToMoon(int n, vector<vector<int>> astronaut) {
graph.resize(n,vector<Edge>());
for(int i=0;i<astronaut.size();i++)
{
addEdge(astronaut[i][0],astronaut[i][1]);
}
vector<int>cc;
vector<bool>vis(n,false);
for(int i=0;i<n;i++)
{
int x=ConnectedComp(i,vis);
cc.push_back(x);
}
int sum=0;
for(int i=0;i<cc.size();i++)
{
for(int j=i+1;j<cc.size();j++)
{
sum+=(i*j);
}
}
return sum;
} | true |
b250d49dcd947066186df9e53d4675ffdea83a94 | C++ | Matthew-E-Gould/Past-Projects | /IoT Plant Grower Sim/CW1/Source.cpp | UTF-8 | 4,905 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include "Classes.h"
using namespace std;
uint16_t Random16Bit(); // generates a random 16 bit value
void InputCheck(uint16_t &i, uint16_t min, uint16_t max);
void turnOn(Machine &m, Weather &w);
int main() {
const uint16_t PLANTS = 5;
bool running = true;
bool newDay = false;
bool torf;
string tempStr;
uint16_t tempInt = 0;
Plant plant[PLANTS];
Soil soil;
Weather weather(Random16Bit(), Random16Bit(), Random16Bit());
Authenticator authenticator;
Machine machine(authenticator, plant, soil, weather);
DataLoadSave data(machine, plant);
// loading data from a file
cout << "LAST SAVE DATA:\n";
data.readD();
cout << "\n\n";
while (running) {
// generating new day data for soil and weather, consists of a securely randomly generated number being inputted and the soil reacting to that.
weather.nextDay(Random16Bit(), Random16Bit(), Random16Bit());
soil.nextDay(weather.getDownpour(), weather.getRained(), weather.getSunlight());
// user deicdes if they want to turn the machine on, if not a day passes
turnOn(machine, weather);
// running the machines interface
machine.main();
// saving and appending data
data.saveD();
data.appendD();
// watering soil
soil.water(machine.waterSoil(soil.getMoistureValue()));
// growing plants
for (int i = 0; i < PLANTS; i++) {
if (plant[i].isAlive()) {
plant[i].nextDay(soil.getFertilised(), soil.getMoistureValue(), weather.getSunlight(), soil.getFertiliseValue());
}
}
// updating soil moisture and fertilisation
soil.endDay((double)machine.getPlantCount());
// turning off machine if user requested it
if (machine.getOffAfterDay()) {
machine.turnOff();
authenticator.turnedOff();
}
// updating the date in the machine
machine.updateDate();
// asking validator if the want to end the simulation of the plant waterer
cout << "\n\tEND PROGRAM? [Y/N]";
cin >> tempStr;
while (tempStr != "y" && tempStr != "Y" && tempStr != "n" && tempStr != "N") {
cout << "ERROR: Enter either [y/Y/n/N]: ";
cin >> tempStr;
}
if (tempStr == "y" || tempStr == "Y") {
running = false;
}
}
system("pause");
return 0;
}
// generates a random number between 0 and 2^16
uint16_t Random16Bit() {
srand(time(NULL));
uint16_t random = rand() % UINT16_MAX;
return random;
}
// checks if the input is valid
void InputCheck(uint16_t &i, uint16_t min, uint16_t max) {
cin >> i;
while (i < min || i > max || cin.get() != '\n') {
cin.clear();
cin.ignore();
cout << "ERROR: please enter a value between " << min << " and " << max << ": ";
cin >> i;
}
}
// asking if the user wants to turn the machine on or off. and does so.
void turnOn(Machine &m, Weather &w) {
string tempStr;
if (m.isOn()) {
m.rainCheck(w.getRained());
}
else {
cout << "Turn device on? [y/n]: ";
cin >> tempStr;
while (tempStr != "y" && tempStr != "Y" && tempStr != "n" && tempStr != "N") {
cout << "ERROR: Enter either [y/Y/n/N]: ";
cin >> tempStr;
}
if (tempStr == "y" || tempStr == "Y") {
m.changeMachineState(true);
tempStr.clear();
}
}
}
/*
Set up weather
Set up machine
Set up soil
Randomise the initial weather
Make soil affected by weather
//START while loop
//IF machine is off
Ask user if they want to turn on the machine
//IF machine is on
see if it rained
System logs date
//WHILE torf
Machine asks user if they want to plant plants
//IF machine has free spaces left && user says yes
Machine adds plant to lowest vector
//IF machine has no free spaces left && user says yes
Inform user the machine has no spaces left
set torf to false
//IF user says no
set torf to false
//END of WHILE
//FOR each plant
Machine tests soil moisture
Machine measures plant height and informs user
Machine logs height
Machine informs user and asks what they want to do
//IF user wants to change plants desired moisture
Asks user to input desired (water resistivity)
//IF user wants to dig up plant
Remove plant from machine (vector)
//IF user wants to fertilise plant
fertilise plant
Machine waters plant IF it needs it
Machine logs moisture levels whether plant was watered & fertilised
torf = true
ask user if they want to stop
//if yes set running = false
//END while loop if running == false
Return 0;
Weather 1 _ 1 Machine Weather 1 _ * Machine
1 1 1 1 * *
| _____/ | OR (if there are mutiple machines allowed) | _____/ |<== Plant/Machine allocation
1 1 * 1 1 *
Soil 1 ____ * Plant Soil 1 ____ * Plant
*/ | true |
de56b9612b76a753d7c5cc8b0e4ddf4ac238c6a7 | C++ | ChengHsinHan/myOwnPrograms | /CodeWars/C++/8 kyu/#24 Collatz Conjecture (3n+1).cpp | UTF-8 | 1,058 | 4 | 4 | [] | no_license | // The Collatz conjecture (also known as 3n+1 conjecture) is a conjecture that
// applying the following algorithm to any number we will always eventually
// reach one:
//
// [This is writen in pseudocode]
// if(number is even) number = number / 2
// if(number is odd) number = 3*number + 1
// #Task
//
// Your task is to make a function hotpo that takes a positive n as input and
// returns the number of times you need to perform this algorithm to get n = 1.
//
// #Examples
//
// hotpo(1) returns 0
// (1 is already 1)
//
// hotpo(5) returns 5
// 5 -> 16 -> 8 -> 4 -> 2 -> 1
//
// hotpo(6) returns 8
// 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
//
// hotpo(23) returns 15
// 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 ->
// 4 -> 2 -> 1
// #References
//
// Collatz conjecture wikipedia page:
// https://en.wikipedia.org/wiki/Collatz_conjecture
unsigned int hotpo(unsigned int n)
{
unsigned int steps = 0;
while (n != 1)
{
n = (n % 2) ? (3 * n + 1) : n / 2;
++steps;
}
return steps;
}
| true |
c35df17a5062fe3c5dbf58875978322675d57a26 | C++ | buppter/LearnCPP | /struct/04_stuct_nesting_stuct.cpp | UTF-8 | 592 | 3.21875 | 3 | [] | no_license | //
// Created by SXTian on 2019/10/18.
//
#include <iostream>
using namespace std;
//定义学生的结构体
struct Student {
string name;
int age;
int score;
};
//定义老师结构体
struct Teacher {
int id;
string name;
int age;
struct Student stu;
};
int main4(){
Teacher t;
t.id = 100;
t.name = "老王";
t.age = 20;
t.stu.name = "李明";
t.stu.age = 10;
t.stu.score = 100;
cout << t.id << " " << t.name << " " << t.age << endl;
cout << t.stu.name << " " << t.stu.age << " " << t.stu.score << endl;
return 0;
} | true |
b8a91175d213722623e17ce57c0e0573b04e5df7 | C++ | HERECJ/FINISH | /1503 1A.cpp | WINDOWS-1252 | 1,106 | 3.109375 | 3 | [] | no_license | //===1503
#include <iostream>
#include <string.h>
using namespace std;
char Input[100];
char Result[105];
int main(){
string s;
string Out;
int len,c;//cǽλ
int i,j;
memset(Result,0,sizeof(char)*105);
while(cin >> s){
memset(Input,0,sizeof(char)*100);
c = 0;
if(s.compare("0")==0)break;
else{
j=0;
len = s.size();
for(i=len-1;i>=0;i--){
Input[j] = s[i]-'0';
//cout <<s[i]<<""<< Input[j]<<" "<<endl;
j++;
}
//plus
for(i=0;i<105;i++){
Result[i] =Result[i] + Input[i]+c;
c = Result[i]/10;
Result[i]=Result[i]%10;
//cout << Result[i]<< ":";
}
}
}
i = 104;
j = 0 ;
while(Result[i]==0){
//cout <<"loop"<<endl;
i--;
}
for(i;i>=0;i--){
Out[j]=Result[i]+'0';
cout << Out[j];
j++;
}
// cout <<endl<<"next sum"<<endl;
//Out[j]= '\0';
//cout << Out ;
}
| true |
f89915914cfedbb7e35f995b539076ee9cea7a85 | C++ | jairochaves2/Curso-Sertaozinho | /exemplos/Aula 1 e 2/exemplo-06.cpp | UTF-8 | 288 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
float numero,num2,div;
printf("Digite um numero: ");
scanf("%f", &numero);
printf("Digite um numero: ");
scanf("%f", &num2);
div=numero/num2;
printf("seu numero eh: %f\n", div);
return 0;
}
| true |
c183d6849ac0c9322dcb7450490e4b4b1eb3462d | C++ | byreave/Simple2DGameEngine | /Engine/PhysicsSystem.h | UTF-8 | 1,632 | 2.515625 | 3 | [] | no_license | #pragma once
#include "GameObject.h"
#include <vector>
#include "SmartPointer.h"
namespace Engine {
namespace Physics {
class PhysicsSystem {
private:
WeakPointer<GameObject> m_GameObject;
bool isKinematic;
float m_Mass;
float m_DragCoef; //Positive
Point2D<float> m_Force;
//Point2D<float> m_Velocity;
public:
PhysicsSystem(const StrongPointer<GameObject> & i_GameObject)
:
m_GameObject(i_GameObject)
{
m_Mass = 1.0f;
m_DragCoef = 0.02f;
}
PhysicsSystem(const StrongPointer<GameObject> & i_GameObject, float i_Mass, float i_DragCoef, bool i_iskinematic = false)
:
m_GameObject(i_GameObject),
m_Mass(i_Mass),
m_DragCoef(i_DragCoef),
isKinematic(i_iskinematic)
{
}
~PhysicsSystem()
{
}
void SetMass(const float i_Mass)
{
m_Mass = i_Mass;
}
float GetMass() const { return m_Mass; };
WeakPointer<GameObject> GetGameobject() const { return m_GameObject; }
inline void AddForce(Point2D<float> i_Force);
inline void AddForce(float i_xForce, float i_yForce);
void Update(float deltaTime);
bool IsKinematic() const { return isKinematic; }
};
extern std::vector<PhysicsSystem *> PhysicsInfo;
void Update(float deltaTime);
void CleanUp();
PhysicsSystem * GetPhysicsSystem(const StrongPointer<GameObject> & gameObject);
//UnitTest
void PhysicsSystem_UnitTest();
}
}
inline void Engine::Physics::PhysicsSystem::AddForce(Point2D<float> i_Force)
{
m_Force += i_Force;
}
inline void Engine::Physics::PhysicsSystem::AddForce(float i_xForce, float i_yForce)
{
m_Force += Point2D<float>(i_xForce, i_yForce);
} | true |
b4db975928bc0c063f2845be0ca4eb070a3308a8 | C++ | erik-zwart/leetcodeCpp | /LinkedListSerializer.cpp | UTF-8 | 1,608 | 3.453125 | 3 | [] | no_license | using namespace std;
struct EncodedList {
std::string storage;
};
struct Node {
int val;
struct Node* next;
Node(int v) : val(v), next(nullptr) {}
};
EncodedList encode(Node* head) {
EncodedList e;
for(auto it = head; it != nullptr; it = it->next) {
e.storage += to_string(it->val);
if(it->next) e.storage += ",";
}
return e;
}
Node* decode(const EncodedList& e) {
Node* head = nullptr;
Node* last = nullptr;
const auto& str = e.storage;
auto pos = str.find(",", 0);
auto prevPos = 0;
while(pos != string::npos) {
auto val = str.substr(prevPos, pos - prevPos);
auto p = new Node(stoi(val));
if(!head) head = last = p;
else {
last->next = p;
last = p;
}
prevPos = pos + 1;
pos = str.find(",", prevPos);
}
// add the last Node
last->next = new Node(stoi(str.substr(prevPos, str.length() - prevPos)));
return head;
}
Node* insertLast(Node* head, int v) {
auto p = new Node(v);
if(!head) return p;
auto* last = head;
while(last->next) {
last = last->next;
}
last->next = p;
return head;
}
void printList(Node* head) {
for(auto curr = head; curr; curr = curr->next) {
cout << curr->val;
if(curr->next) cout <<", ";
}
cout << "\n";
}
void tester(void) {
vector<int> vec = {10,20,30,40,50};
Node* head = nullptr;
for(auto a : vec) head = insertLast(head, a);
printList(head);
EncodedList e;
e = encode(head);
cout << " Encoded string: " << e.storage <<"\n";
auto decodedList = decode(e);
printList(decodedList);
}
int main()
{
tester();
return 0;
}
| true |
21106dc11bd513554c282a998bb3097f4c3e8b03 | C++ | MakerTakala/ZeroJudge | /a539.cpp | UTF-8 | 385 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n,a[1000];
while(cin>>n){
for(int i=0;i<n;i++)
cin>>a[i];
int sum=0;
for(int i=0;i<n;i++)
for(int j=i-1;j>=0;j--)
if(a[i]<a[j])
sum++;
cout<<"Minimum exchange operations : "<<sum<<endl;
}
return 0;
}
| true |
72783da99dd5306b6c772e8f588b187859bd7c55 | C++ | Leamsy/Fundamentos-de-la-Programacion-2015-2016 | /Sesión 9/III_Intervalo.cpp | ISO-8859-1 | 2,530 | 3.65625 | 4 | [] | no_license | /***************************************************************************/
// FUNDAMENTOS DE PROGRAMACIN
// GRADO EN INGENIERA INFORMTICA
//
// CURSO 2015-2016
// (C) ISMAEL MOYANO ROMERO
// 1B - GRUPO 3
//
// RELACIN DE PROBLEMAS 3
// EJERCICIO 22
/*
Programa que calcula la pertenecia de un nmero a dicho intervalo y si ste
es vaco.
*/
/***************************************************************************/
#include <iostream>
#include <string>
using namespace std;
class Intervalo{
public:
int numero1, numero2, numerox, tipo;
bool contiene, vacio;
Intervalo(int tipo, int numero1, int numero2, int numerox){
Contiene(tipo, numero1, numero2, numerox);
Vacio(numero1, numero2);
}
void Contiene(int tipo, int numero1, int numero2, int numerox) {
if(tipo == 1){
if(numerox >= numero1 && numerox <= numero2){
contiene = true;
}
else{
contiene = false;
}
}
if(tipo == 2){
if(numerox >= numero1 && numerox < numero2){
contiene = true;
}
else{
contiene = false;
}
}
if(tipo == 3){
if(numerox > numero1 && numerox <= numero2){
contiene = true;
}
else{
contiene = false;
}
}
if(tipo == 4){
if(numerox > numero1 && numerox < numero2){
contiene = true;
}
else{
contiene = false;
}
}
}
void Vacio(int numero1, int numero2) {
vacio = false;
if(numero1 >= numero2){
vacio = true;
}
}
};
int main()
{
int tipo, numero1, numero2, numerox;
do{
cout << "Introduce un tipo de intervalo () = 1, (] = 2, [) = 3, [] = 4: ";
cin >> tipo;
}while(tipo < 1 || tipo > 4);
cout << "Introduce el primer nmero del intervalo: ";
cin >> numero1;
cout << "Introduce el segundo nmero del intervalo: ";
cin >> numero2;
cout << "Introduce el nmero a comprobar: ";
cin >> numerox;
Intervalo intervalo(tipo, numero1, numero2, numerox);
if(intervalo.contiene == true){
cout << "\n\nEl intervalo contiene al nmero " <<numerox<< ".";
}
if(intervalo.contiene == false){
cout << "\n\nEl intervalo no contiene al nmero " <<numerox<< ".";
}
if(intervalo.vacio == true){
cout << "\n\nEl intervalo (" <<numero1<< ", " <<numero2<< ") es un "
"intervalo vaco.";
}
return(0);
}
| true |
860e488425afb2e628e10f94a9160ab65f9693c0 | C++ | EdwinJosue16/Proyecto_Integrador_Redes-SO | /src/Green/Log.cpp | UTF-8 | 428 | 2.703125 | 3 | [] | no_license | /// @copyright 2020 ECCI, Universidad de Costa Rica. All rights reserved
/// This code is released under the GNU Public License version 3
/// @author Jeisson Hidalgo-Céspedes <jeisson.hidalgo@ucr.ac.cr>
#include "Log.hpp"
Log &Log::getInstance()
{
static Log log;
return log;
}
void Log::write(const std::string &text, bool addNewLine)
{
this->mutex.lock();
(*this->output) << text;
if (addNewLine)
(*this->output) << std::endl;
this->mutex.unlock();
}
| true |
5ceacdc4d4ed9aee50da445448c304d988742df7 | C++ | fumyparli/problem-solving | /lyricsSearching_binary_search.cpp | UTF-8 | 1,473 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<vector<string>> a(10001);
vector<vector<string>> ra(10001);
int get_iv(string &s1, string &s2, int flag) {
int s_size = s1.size();
if (flag == 0) {
auto ed = lower_bound(a[s_size].begin(), a[s_size].end(), s2);
auto st = upper_bound(a[s_size].begin(), a[s_size].end(), s1);
return ed - st;
} else {
auto ed = lower_bound(ra[s_size].begin(), ra[s_size].end(), s2);
auto st = upper_bound(ra[s_size].begin(), ra[s_size].end(), s1);
return ed - st;
}
}
vector<int> solution(vector<string> words, vector<string> queries) {
vector<int> answer;
for (auto &s : words) {
int s_size = s.size();
a[s_size].push_back(s);
reverse(s.begin(), s.end());
ra[s_size].push_back(s);
}
for (int i = 0; i < 10001; i++) {
sort(a[i].begin(), a[i].end());
sort(ra[i].begin(), ra[i].end());
}
for (auto &s : queries) {
string s1 = "", s2 = "";
int s_size = s.size();
int flag = 0;
if (s[0] == '?') {
flag = 1;
reverse(s.begin(), s.end());
}
for (int i = 0; i < s_size; i++) {
if (s[i] == '?') {
s1 += 'a';
s2 += 'z';
} else {
s1 += s[i];
s2 += s[i];
}
}
answer.push_back(get_iv(s1, s2, flag));
}
return answer;
} | true |
dff6711799096010871728a01056514022c400fb | C++ | wxz879526/UIEngine | /components/skia/src/gpu/gl/GrGLEffect.h | UTF-8 | 4,748 | 2.546875 | 3 | [
"MIT"
] | permissive | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrGLEffect_DEFINED
#define GrGLEffect_DEFINED
#include "GrBackendEffectFactory.h"
#include "GrGLProgramEffects.h"
#include "GrGLShaderVar.h"
#include "GrGLSL.h"
class GrGLShaderBuilder;
/** @file
This file contains specializations for OpenGL of the shader stages declared in
include/gpu/GrEffect.h. Objects of type GrGLEffect are responsible for emitting the
GLSL code that implements a GrEffect and for uploading uniforms at draw time. If they don't
always emit the same GLSL code, they must have a function:
static inline void GenKey(const GrDrawEffect&, const GrGLCaps&, GrEffectKeyBuilder*)
that is used to implement a program cache. When two GrEffects produce the same key this means
that their GrGLEffects would emit the same GLSL code.
The GrGLEffect subclass must also have a constructor of the form:
EffectSubclass::EffectSubclass(const GrBackendEffectFactory&, const GrDrawEffect&)
The effect held by the GrDrawEffect is guaranteed to be of the type that generated the
GrGLEffect subclass instance.
These objects are created by the factory object returned by the GrEffect::getFactory().
*/
class GrDrawEffect;
class GrGLTexture;
class GrGLVertexEffect;
class GrGLEffect {
public:
typedef GrGLProgramEffects::TransformedCoordsArray TransformedCoordsArray;
typedef GrGLProgramEffects::TextureSampler TextureSampler;
typedef GrGLProgramEffects::TextureSamplerArray TextureSamplerArray;
GrGLEffect(const GrBackendEffectFactory& factory)
: fFactory(factory)
, fIsVertexEffect(false) {
}
virtual ~GrGLEffect() {}
/** Called when the program stage should insert its code into the shaders. The code in each
shader will be in its own block ({}) and so locally scoped names will not collide across
stages.
@param builder Interface used to emit code in the shaders.
@param drawEffect A wrapper on the effect that generated this program stage.
@param key The key that was computed by GenKey() from the generating GrEffect.
@param outputColor A predefined vec4 in the FS in which the stage should place its output
color (or coverage).
@param inputColor A vec4 that holds the input color to the stage in the FS. This may be
NULL in which case the implied input is solid white (all ones).
TODO: Better system for communicating optimization info (e.g. input
color is solid white, trans black, known to be opaque, etc.) that allows
the effect to communicate back similar known info about its output.
@param samplers One entry for each GrTextureAccess of the GrEffect that generated the
GrGLEffect. These can be passed to the builder to emit texture
reads in the generated code.
*/
virtual void emitCode(GrGLProgramBuilder* builder,
const GrDrawEffect& drawEffect,
const GrEffectKey& key,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) = 0;
/** A GrGLEffect instance can be reused with any GrEffect that produces the same stage
key; this function reads data from a GrEffect and uploads any uniform variables required
by the shaders created in emitCode(). The GrEffect installed in the GrDrawEffect is
guaranteed to be of the same type that created this GrGLEffect and to have an identical
effect key as the one that created this GrGLEffect. Effects that use local coords have
to consider whether the GrEffectStage's coord change matrix should be used. When explicit
local coordinates are used it can be ignored. */
virtual void setData(const GrGLProgramDataManager&, const GrDrawEffect&) {}
const char* name() const { return fFactory.name(); }
static void GenKey(const GrDrawEffect&, const GrGLCaps&, GrEffectKeyBuilder*) {}
/** Used by the system when generating shader code, to see if this effect can be downcasted to
the internal GrGLVertexEffect type */
bool isVertexEffect() const { return fIsVertexEffect; }
protected:
const GrBackendEffectFactory& fFactory;
private:
friend class GrGLVertexEffect; // to set fIsVertexEffect
bool fIsVertexEffect;
};
#endif
| true |
e4d1b310bfe77fce2037d35fffc76e91a9365544 | C++ | HomuraVehicle/HomuraMachine_Ontake | /hmrM2500_Ontake/hmLib_v3_04/position.hpp | SHIFT_JIS | 9,298 | 2.90625 | 3 | [] | no_license | #ifndef HMLIB_POSITION_INC
#define HMLIB_POSITION_INC 100
#include <cmath>
#include <iostream>
namespace hmLib{
template<class T>
struct di_position{
public:
T x;
T y;
di_position<T>(){
x=0;
y=0;
}
di_position<T>(T _x,T _y){
x=_x;
y=_y;
}
di_position<T>(const di_position<T>& _T){
x=_T.x;
y=_T.y;
}
template<class S>
di_position<T>(S _x,S _y){
x=(T)_x;
y=(T)_y;
}
template<class S>
di_position<T>(const di_position<S>& _S){
x=(T)_S.x;
y=(T)_S.y;
}
void set(T _x,T _y){
x=_x;
y=_y;
}
// void Set(T _x,T _y){set(_x,_y);}
template<class S>
void set(S _x,S _y){
x=(T)_x;
y=(T)_y;
}
// template<class S>
// void Set(S _x,S _y){set(_x,_y);}
bool operator!=(const di_position<T>& _T)const{
if(x!=_T.x || y!=_T.y)return true;
else return false;
}
bool operator==(const di_position<T>& _T)const{
if(x!=_T.x || y!=_T.y)return false;
else return true;
}
bool operator<(const di_position<T>& _T)const{
if(x>=_T.x || y>=_T.y)return false;
else return true;
}
bool operator>(const di_position<T>& _T)const{
if(x<=_T.x || y<=_T.y)return false;
else return true;
}
bool operator<=(const di_position<T>& _T)const{
if(x>_T.x || y>_T.y)return false;
else return true;
}
bool operator>=(const di_position<T>& _T)const{
if(x<_T.x || y<_T.y)return false;
else return true;
}
const di_position<T> operator=(const di_position<T>& _T){
if(this!=&_T){
x=_T.x;
y=_T.y;
}
return *this;
}
template<class S>
const di_position<T> operator=(const di_position<S>& _S){
x=(T)_S.x;
y=(T)_S.y;
return *this;
}
const di_position<T> operator+=(const di_position<T>& _T){
x+=_T.x;
y+=_T.y;
return *this;
}
template<class S>
const di_position<T> operator+=(const di_position<S>& _S){
x+=(T)_S.x;
y+=(T)_S.y;
return *this;
}
const di_position<T> operator-=(const di_position<T>& _T){
x-=_T.x;
y-=_T.y;
return *this;
}
template<class S>
const di_position<T> operator-=(const di_position<S>& _S){
x-=(T)_S.x;
y-=(T)_S.y;
return *this;
}
di_position<T> operator+()const{return *this;}
di_position<T> operator-()const{
di_position<T> ans(*this);
ans.x*=-1;
ans.y*=-1;
return ans;
}
di_position<T> operator+(const di_position<T>& _T)const{
di_position<T> ans(*this);
ans+=_T;
return ans;
}
di_position<T> operator-(const di_position<T>& _T)const{
di_position<T> ans(*this);
ans-=_T;
return ans;
}
di_position<T> operator*(const di_position<T>& _T)const{
di_position<T> ans(*this);
ans.x*=_T.x;
ans.y*=_T.y;
return ans;
}
di_position<T> operator/(const di_position<T>& _T)const{
di_position<T> ans(*this);
if(_T.x==0 || _T.y==0)throw "di_position<T>::operator/(const di_position<T>& _T)const div with 0";
ans.x/=_T.x;
ans.y/=_T.y;
return ans;
}
template<class S>
operator S()const{
di_position<S> ans(*this);
return ans;
}
//friendQ
// friend bool operator==(const di_position<T>& _T1,const di_position<T>& _T2);
friend di_position<T> operator*(const di_position<T>& _T,const T& p){
di_position<T> ans(_T);
ans.x*=p;
ans.y*=p;
return ans;
}
friend di_position<T> operator*(const T& p,const di_position<T>& _T){
di_position<T> ans(_T);
ans.x*=p;
ans.y*=p;
return ans;
}
friend di_position<T> operator/(const di_position<T>& _T,const T& p){
di_position<T> ans(_T);
ans.x/=p;
ans.y/=p;
return ans;
}
template<class S,class U>
friend di_position<U> operator+(const di_position<T>& _T,const di_position<S>& _S);
template<class S,class U>
friend di_position<U> operator-(const di_position<T>& _T,const di_position<S>& _S);
template<class S,class U>
friend di_position<U> operator*(const di_position<T>& _T,const di_position<S>& _S);
template<class S,class U>
friend di_position<U> operator/(const di_position<T>& _T,const di_position<S>& _S);
template<class S,class U>
friend di_position<U> operator*(const di_position<T>& _T,const S& _S);
template<class S,class U>
friend di_position<U> operator/(const di_position<T>& _T,const S& _S);
template<class S,class U>
friend di_position<U> operator*(const S& _S,const di_position<T>& _T);
friend std::ostream& operator<<(std::ostream& out,const di_position<T>& pos){
out<<'('<<pos.x<<','<<pos.y<<')';
return out;
}
};
typedef di_position<int> pint;
typedef di_position<double> pdouble;
inline pdouble operator+(const pint& i,const pdouble& d){return pdouble(i)+d;}
inline pdouble operator-(const pint& i,const pdouble& d){return pdouble(i)-d;}
inline pdouble operator*(const pint& i,const pdouble& d){return pdouble(i)*d;}
inline pdouble operator/(const pint& i,const pdouble& d){return pdouble(i)/d;}
inline pdouble operator*(const pint& i,const double& d){return pdouble(i)*d;}
inline pdouble operator/(const pint& i,const double& d){return pdouble(i)/d;}
inline pdouble operator*(const double& d,const pint& i){return pdouble(i)*d;}
inline pdouble operator+(const pdouble& d,const pint& i){return d+pdouble(i);}
inline pdouble operator-(const pdouble& d,const pint& i){return d-pdouble(i);}
inline pdouble operator*(const pdouble& d,const pint& i){return d*pdouble(i);}
inline pdouble operator/(const pdouble& d,const pint& i){return d/pdouble(i);}
inline pdouble operator*(const pdouble& d,const int& i){return d*double(i);}
inline pdouble operator/(const pdouble& d,const int& i){return d/double(i);}
inline pdouble operator*(const int& i,const pdouble& d){return d*double(i);}
//di_position֘AQ
template<class T>
inline di_position<T> di_positionX(const di_position<T>& p){return di_position<T>(p.x,0);}
template<class T>
inline di_position<T> di_positionY(const di_position<T>& p){return di_position<T>(0,p.y);}
template<class T>
inline di_position<T> di_positionX(const T& p){return di_position<T>(p,0);}
template<class T>
inline di_position<T> di_positionY(const T& p){return di_position<T>(0,p);}
template<class T>
inline di_position<T> di_positionMin(const di_position<T>& p1,const di_position<T>& p2){
di_position<T> tmp=p1;
if(tmp.x>p2.x)tmp.x=p2.x;
if(tmp.y>p2.y)tmp.y=p2.y;
return tmp;
}
template<class T>
inline di_position<T> di_positionMax(const di_position<T>& p1,const di_position<T>& p2){
di_position<T> tmp=p1;
if(tmp.x<p2.x)tmp.x=p2.x;
if(tmp.y<p2.y)tmp.y=p2.y;
return tmp;
}
template<class T>
inline di_position<T> di_positionMinMax(const di_position<T>& p1,const di_position<T>& p2){
di_position<T> tmp=p1;
if(tmp.x>p2.x)tmp.x=p2.x;
if(tmp.y<p2.y)tmp.y=p2.y;
return tmp;
}
template<class T>
inline di_position<T> di_positionMaxMin(const di_position<T>& p1,const di_position<T>& p2){
di_position<T> tmp=p1;
if(tmp.x<p2.x)tmp.x=p2.x;
if(tmp.y>p2.y)tmp.y=p2.y;
return tmp;
}
inline pint pintX(const pint& p){return pint(p.x,0);}
inline pint pintY(const pint& p){return pint(0,p.y);}
inline pint pintX(const int& p){return pint(p,0);}
inline pint pintY(const int& p){return pint(0,p);}
inline pdouble pdoubleX(const pdouble& p){return pdouble(p.x,0.);}
inline pdouble pdoubleY(const pdouble& p){return pdouble(0.,p.y);}
inline pdouble pdoubleX(const double& p){return pdouble(p,0.);}
inline pdouble pdoubleY(const double& p){return pdouble(0.,p);}
inline pint pintMin(const pint& p1,const pint& p2){
pint tmp=p1;
if(tmp.x>p2.x)tmp.x=p2.x;
if(tmp.y>p2.y)tmp.y=p2.y;
return tmp;
}
inline pint pintMax(const pint& p1,const pint& p2){
pint tmp=p1;
if(tmp.x<p2.x)tmp.x=p2.x;
if(tmp.y<p2.y)tmp.y=p2.y;
return tmp;
}
inline pint pintMinMax(const pint& p1,const pint& p2){
pint tmp=p1;
if(tmp.x>p2.x)tmp.x=p2.x;
if(tmp.y<p2.y)tmp.y=p2.y;
return tmp;
}
inline pint pintMaxMin(const pint& p1,const pint& p2){
pint tmp=p1;
if(tmp.x<p2.x)tmp.x=p2.x;
if(tmp.y>p2.y)tmp.y=p2.y;
return tmp;
}
inline pdouble pdoubleMin(const pdouble& p1,const pdouble& p2){
pdouble tmp=p1;
if(tmp.x>p2.x)tmp.x=p2.x;
if(tmp.y>p2.y)tmp.y=p2.y;
return tmp;
}
inline pdouble pdoubleMax(const pdouble& p1,const pdouble& p2){
pdouble tmp=p1;
if(tmp.x<p2.x)tmp.x=p2.x;
if(tmp.y<p2.y)tmp.y=p2.y;
return tmp;
}
inline pdouble pdoubleMinMax(const pdouble& p1,const pdouble& p2){
pdouble tmp=p1;
if(tmp.x>p2.x)tmp.x=p2.x;
if(tmp.y<p2.y)tmp.y=p2.y;
return tmp;
}
inline pdouble pdoubleMaxMin(const pdouble& p1,const pdouble& p2){
pdouble tmp=p1;
if(tmp.x<p2.x)tmp.x=p2.x;
if(tmp.y>p2.y)tmp.y=p2.y;
return tmp;
}
template<class T>
inline T abs2(const di_position<T>& p){return p.x*p.x+p.y*p.y;}
template<class T>
inline double abs(const di_position<T>& p){return sqrt(static_cast<double>(p.x*p.x+p.y*p.y));}
template<class T>
inline di_position<T> ortho(const di_position<T>& p){return di_position<T>(p.y,-p.x);}
template<class T>
inline di_position<T> rot(const di_position<T>& p,const double& angle){return di_position<T>(p.x*cos(angle)-p.y*sin(angle),p.x*sin(angle)+p.y*cos(angle));}
template<class T>
inline T inprd(const di_position<T>& p1,const di_position<T>& p2){return p1.x*p2.x+p1.y*p2.y;}
template<class T>
inline T area(const di_position<T>& p1,const di_position<T>& p2){return p1.x*p2.y-p2.x*p1.y;}
}
#endif
| true |
400b2a4828114e13e2844a67afa35566a7e1cc04 | C++ | hjed/owr_software | /gui/src/oculus_arm_gui/src/FocusArm.cpp | UTF-8 | 545 | 2.546875 | 3 | [] | no_license | /**
* Uses mouse input to center the oculus on the correct point.
* Started by: Harry J.E Day
* Date: 5/11/2015
*/
#include "oculus_arm_gui/FocusArm.hpp"
FocusArm::FocusArm() {
//key to activate this mode
shortcut_key_ = 'o';
}
FocusArm::~FocusArm() {
//does nothing
}
void FocusArm::onInitalize() {
}
void FocusArm::activate() {
}
void FocusArm::deactivate() {
}
int FocusArm::processMouseEvent( rviz::ViewportMouseEvent& event) {
if (event.leftDown() ) {
}
return Render;
}
| true |
86e6cee552efc5ec07bde48924cf62a6aa18b4cd | C++ | bk19881128/Study | /C++_primer/13_chapter/5/hasPtr_test.cc | UTF-8 | 969 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <stdexcept> //runtime_error
#include <list>
#include <deque>
#include <vector>
#include <forward_list>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
class HasPtr {
public:
HasPtr(const std::string &s = std::string()):
ps(new std::string(s)), i(0) { }
HasPtr(const HasPtr &p):
ps(new std::string(*p.ps)), i(p.i) { }
HasPtr& operator=(const HasPtr &);
~HasPtr() { delete ps; }
int getInt() { return i; }
string getString() { return *ps; }
private:
std::string *ps;
int i;
};
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
string *newp = new string(*rhs.ps);
delete ps;
ps = newp;
i = rhs.i;
return *this;
}
int main()
{
HasPtr h1("good");
cout << h1.getInt() << endl;
cout << h1.getString() << endl;
HasPtr h2(h1);
cout << h2.getInt() << endl;
cout << h2.getString() << endl;
HasPtr h3;
h3 = h1;
cout << h3.getInt() << endl;
cout << h3.getString() << endl;
return 0;
}
| true |
6ab1dddc1a6e0603ed404e6cafce74d1de53ee25 | C++ | infparadox/Data-Structures-and-Algorithms | /gametheory/stones.cpp | UTF-8 | 770 | 2.75 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll mex(unordered_set<ll>set)
{
ll ans=0;
while(set.find(ans)!=set.end())
ans++;
return ans;
}
ll calcgrundy(ll n,ll grundy[])
{
if(grundy[n]!=-1)
return grundy[n];
unordered_set<ll>set;
set.insert(calcgrundy(n-2,grundy));
set.insert(calcgrundy(n-3,grundy));
set.insert(calcgrundy(n-5,grundy));
grundy[n]=mex(set);
return grundy[n];
}
int main()
{
ios::sync_with_stdio(false);
ll t;
cin >> t;
ll grundy[101];
for(ll i=0;i<=100;i++)
grundy[i]=-1;
grundy[0]=0;
grundy[1]=0;
grundy[2]=1;
grundy[3]=1;
grundy[4]=2;
grundy[5]=2;
while(t--)
{
ll n;
cin >> n;
ll i;
ll ans=calcgrundy(n,grundy);
if(ans!=0)
cout << "First\n";
else
cout << "Second\n";
}
return 0;
} | true |
64a6960d0279efd547a6a36f1153c658fc7f3663 | C++ | MingNine9999/algorithm | /Problems/boj1654.cpp | UTF-8 | 805 | 3.046875 | 3 | [] | no_license | //Problem Number : 1654
//Problem Title : 랜선 자르기
//Problem Link : https://www.acmicpc.net/problem/1654
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int n, k;
vector<int> v;
int par(long long l, long long r)
{
if (l >= r) {
return l;
}
long long mid = (l + r + 1) / 2;
int num = 0;
for (int i = 0; i < k; i++) {
num += v[i] / mid;
}
if (num >= n) {
return par(mid, r);
}
else {
return par(l, mid - 1);
}
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
int maxi = -1;
cin >> k >> n;
v.resize(k + 1);
for (int i = 0; i < k; i++) {
cin >> v[i];
maxi = max(maxi, v[i]);
}
cout << par(1, (long long)maxi);
return 0;
} | true |
f6c175783bc731e0676f599c1293cf74ece7d97e | C++ | yooncheolkim/study_algorithm | /10971_외판원순회2/10971.cpp | UTF-8 | 681 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int N;
int w[11][11];
int dp[11][1 < 12];
int go(int cur, int visited)
{
if (((1 << N) - 1) == visited)
return w[cur][0];
int &ret = dp[cur][visited];
if (ret != 0) return ret;
ret = 999999999;
for (int next = 0; next < N; next++)
{
if (w[cur][next] == 0) continue;
if (((1 << next) & visited) != 0) continue;
ret = min(ret, go(next, visited | (1 << next)) + w[cur][next]);
}
return ret;
}
int main()
{
cin >> N;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cin >> w[i][j];
}
}
memset(dp, 0, sizeof(dp));
cout << go(0, 1) << endl;
return 0;
}
| true |
7ce5ee59aa48fc8796869c58885410c13851d2cd | C++ | maksym-pasichnyk/NativeParticleSystem | /NativePlugin/Src/Runtime/ParticleSystem/PolynomialCurve.h | UTF-8 | 6,848 | 3.1875 | 3 | [] | no_license | #ifndef POLYONOMIAL_CURVE_H
#define POLYONOMIAL_CURVE_H
template<class T>
class AnimationCurveTpl;
typedef AnimationCurveTpl<float> AnimationCurve;
class Vector2f;
struct Polynomial
{
static float EvalSegment (float t, const float* coeff)
{
return (t * (t * (t * coeff[0] + coeff[1]) + coeff[2])) + coeff[3];
}
float coeff[4];
};
// Smaller, optimized version
struct OptimizedPolynomialCurve
{
enum { kMaxPolynomialKeyframeCount = 3, kSegmentCount = kMaxPolynomialKeyframeCount-1, };
Polynomial segments[kSegmentCount];
float timeValue;
float velocityValue;
// Evaluate double integrated Polynomial curve.
// Example: position = EvaluateDoubleIntegrated (normalizedTime) * startEnergy^2
// Use DoubleIntegrate function to for example turn a force curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateDoubleIntegrated (float t) const
{
float res0, res1;
// All segments are added together. At t = 0, the integrated curve is always zero.
// 0 segment is sampled up to the 1 keyframe
// First key is always assumed to be at 0 time
float t1 = std::min(t, timeValue);
// 1 segment is sampled from 1 key to 2 key
// Last key is always assumed to be at 1 time
float t2 = std::max(0.0F, t - timeValue);
res0 = Polynomial::EvalSegment(t1, segments[0].coeff) * t1 * t1;
res1 = Polynomial::EvalSegment(t2, segments[1].coeff) * t2 * t2;
float finalResult = res0 + res1;
// Add velocity of previous segments
finalResult += velocityValue * std::max(t - timeValue, 0.0F);
return finalResult;
}
// Evaluate integrated Polynomial curve.
// Example: position = EvaluateIntegrated (normalizedTime) * startEnergy
// Use Integrate function to for example turn a velocity curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateIntegrated (float t) const
{
float res0, res1;
// All segments are added together. At t = 0, the integrated curve is always zero.
// 0 segment is sampled up to the 1 keyframe
// First key is always assumed to be at 0 time
float t1 = std::min(t, timeValue);
// 1 segment is sampled from 1 key to 2 key
// Last key is always assumed to be at 1 time
float t2 = std::max(0.0F, t - timeValue);
res0 = Polynomial::EvalSegment(t1, segments[0].coeff) * t1;
res1 = Polynomial::EvalSegment(t2, segments[1].coeff) * t2;
return (res0 + res1);
}
// Evaluate the curve
// extects that t is in the 0...1 range
float Evaluate (float t) const
{
float res0 = Polynomial::EvalSegment(t, segments[0].coeff);
float res1 = Polynomial::EvalSegment(t - timeValue, segments[1].coeff);
float result;
if (t > timeValue)
result = res1;
else
result = res0;
return result;
}
// Find the maximum of a double integrated curve (x: min, y: max)
Vector2f FindMinMaxDoubleIntegrated() const;
// Find the maximum of the integrated curve (x: min, y: max)
Vector2f FindMinMaxIntegrated() const;
// Precalculates polynomials from the animation curve and a scale factor
bool BuildOptimizedCurve (const AnimationCurve& editorCurve, float scale);
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateIntegrated to evaluate the curve
void Integrate ();
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateDoubleIntegrated to evaluate the curve
void DoubleIntegrate ();
// Add a constant force to a velocity curve
// Assumes that you have already called Integrate on the velocity curve.
void AddConstantForceToVelocityCurve (float gravity)
{
for (int i=0;i<kSegmentCount;i++)
segments[i].coeff[1] += 0.5F * gravity;
}
};
// Bigger, not so optimized version
struct PolynomialCurve
{
enum{ kMaxNumSegments = 8 };
Polynomial segments[kMaxNumSegments]; // Cached polynomial coefficients
float integrationCache[kMaxNumSegments]; // Cache of integrated values up until start of segments
float doubleIntegrationCache[kMaxNumSegments]; // Cache of double integrated values up until start of segments
float times[kMaxNumSegments]; // Time value for end of segment
int segmentCount;
// Find the maximum of a double integrated curve (x: min, y: max)
Vector2f FindMinMaxDoubleIntegrated() const;
// Find the maximum of the integrated curve (x: min, y: max)
Vector2f FindMinMaxIntegrated() const;
// Precalculates polynomials from the animation curve and a scale factor
bool BuildCurve(const AnimationCurve& editorCurve, float scale);
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateIntegrated to evaluate the curve
void Integrate ();
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateDoubleIntegrated to evaluate the curve
void DoubleIntegrate ();
// Evaluates if it is possible to represent animation curve as PolynomialCurve
static bool IsValidCurve(const AnimationCurve& editorCurve);
// Evaluate double integrated Polynomial curve.
// Example: position = EvaluateDoubleIntegrated (normalizedTime) * startEnergy^2
// Use DoubleIntegrate function to for example turn a force curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateDoubleIntegrated (float t) const
{
float prevTimeValue = 0.0f;
for(int i = 0; i < segmentCount; i++)
{
if(t <= times[i])
{
const float time = t - prevTimeValue;
return doubleIntegrationCache[i] + integrationCache[i] * time + Polynomial::EvalSegment(time, segments[i].coeff) * time * time;
}
prevTimeValue = times[i];
}
return 1.0f;
}
// Evaluate integrated Polynomial curve.
// Example: position = EvaluateIntegrated (normalizedTime) * startEnergy
// Use Integrate function to for example turn a velocity curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateIntegrated (float t) const
{
float prevTimeValue = 0.0f;
for(int i = 0; i < segmentCount; i++)
{
if(t <= times[i])
{
const float time = t - prevTimeValue;
return integrationCache[i] + Polynomial::EvalSegment(time, segments[i].coeff) * time;
}
prevTimeValue = times[i];
}
return 1.0f;
}
// Evaluate the curve
// extects that t is in the 0...1 range
float Evaluate(float t) const
{
float prevTimeValue = 0.0f;
for(int i = 0; i < segmentCount; i++)
{
if(t <= times[i])
return Polynomial::EvalSegment(t - prevTimeValue, segments[i].coeff);
prevTimeValue = times[i];
}
return 1.0f;
}
};
void SetPolynomialCurveToValue (AnimationCurve& a, OptimizedPolynomialCurve& c, float value);
void SetPolynomialCurveToLinear (AnimationCurve& a, OptimizedPolynomialCurve& c);
void ConstrainToPolynomialCurve (AnimationCurve& curve);
bool IsValidPolynomialCurve (const AnimationCurve& curve);
void CalculateMinMax(Vector2f& minmax, float value);
#endif // POLYONOMIAL_CURVE_H
| true |
b682616333b0223204fcbf50e8f20240d7f64638 | C++ | DGLeming/cpp_blackjack | /cardsMain.cpp | UTF-8 | 6,237 | 3.296875 | 3 | [] | no_license | #include "cardsStruct.cpp"
#include "iostream"
#include <ctime>
#include <time.h>
#include <array>
void printCard(const Card &card)
{
switch (card.rank)
{
case RANK_2: std::cout << '2'; break;
case RANK_3: std::cout << '3'; break;
case RANK_4: std::cout << '4'; break;
case RANK_5: std::cout << '5'; break;
case RANK_6: std::cout << '6'; break;
case RANK_7: std::cout << '7'; break;
case RANK_8: std::cout << '8'; break;
case RANK_9: std::cout << '9'; break;
case RANK_10: std::cout << 'T'; break;
case RANK_JACK: std::cout << 'J'; break;
case RANK_QUEEN: std::cout << 'Q'; break;
case RANK_KING: std::cout << 'K'; break;
case RANK_ACE: std::cout << 'A'; break;
}
switch (card.suit)
{
case SUIT_CLUB: std::cout << 'C'; break;
case SUIT_DIAMOND: std::cout << 'D'; break;
case SUIT_HEART: std::cout << 'H'; break;
case SUIT_SPADE: std::cout << 'S'; break;
}
}
void printDeck(std::array<Card, 52> &deck){
for (Card card : deck){
printCard(card);
std::cout << ' ';
}
}
void swapCards(Card &card1, Card &card2){
Card temp = card1;
card1 = card2;
card2 = temp;
}
int getRandomNumber(int min, int max)
{
/*std::srand(static_cast<unsigned int>(std::time(nullptr)));*/
/*std::srand(time(NULL));*/
srand((unsigned)time(0)+rand());
static const double fraction = 1.0 / (RAND_MAX + 1.0);
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}
void shuffleDeck(std::array<Card, 52> &deck){
for (int i = 0; i < 52; i++){
int random = getRandomNumber(0, 51);
swapCards(deck[i], deck[random]);
}
}
int getCardValue(const Card &card)
{
switch (card.rank)
{
case RANK_2: return 2;
case RANK_3: return 3;
case RANK_4: return 4;
case RANK_5: return 5;
case RANK_6: return 6;
case RANK_7: return 7;
case RANK_8: return 8;
case RANK_9: return 9;
case RANK_10: return 10;
case RANK_JACK: return 10;
case RANK_QUEEN: return 10;
case RANK_KING: return 10;
case RANK_ACE: return 11;
}
return 0;
}
Card getRandomCard(){
Card card;
std::srand(static_cast<unsigned int>(std::time(nullptr)));
int randomRank = getRandomNumber(0, MAX_RANKS);
int randomSuit = getRandomNumber(0, MAX_SUITS);
card.suit = static_cast<CardSuit>(randomSuit);
card.rank = static_cast<CardRank>(randomRank);
return card;
}
std::array<Card, 52> getShuffledDeck(){
std::array<Card, 52> deck;
int cardn = 0;
for (int i = 0; i < MAX_SUITS; i++){
for (int j = 0; j < MAX_RANKS; j++){
deck[cardn].suit = static_cast<CardSuit>(i);
deck[cardn].rank = static_cast<CardRank>(j);
++cardn;
}
}
shuffleDeck(deck);
return deck;
}
int getHandLength(std::array<Card, 11> hand){
int length = 0;
for (int i = 0; i < 11; i++){
if (hand[i].dealed)
++length;
}
return length;
}
void drawCard(std::array<Card, 11> &deck, std::array<Card, 52> &cards, Card &deckPtr){
int length = getHandLength(deck);
deck[length] = deckPtr;
deck[length].dealed = true;
}
int getDeckValue(const std::array<Card, 11> &deck){
int value = 0;
for (int i = 0; i < 11; i++){
if (deck[i].dealed){
value += getCardValue(deck[i]);
}
}
return value;
}
int getMove(){
std::cout << "Would you like to hit or to stand? (h/s)" << std::endl;
char m;
std::cin >> m;
std::cin.ignore(32767, '\n');
switch (m){
case 's': return 0; break;
case 'h': return 1; break;
default: return getMove(); break;
}
}
void playerWon(std::array<Card, 11> &deck, std::array<Card, 11> &dealer){
int playerScore = getDeckValue(deck);
int dealerScore = getDeckValue(dealer);
std::cout << "Congratulations, you won!" << std::endl;
std::cout << "You had score of " << playerScore << ", and dealer had score of " << dealerScore << std::endl;
}
void playerLost(std::array<Card, 11> &deck, std::array<Card, 11> &dealer){
int playerScore = getDeckValue(deck);
int dealerScore = getDeckValue(dealer);
std::cout << "Im sorry, but you lost, better luck next time." << std::endl;
std::cout << "You had score of " << playerScore << ", and dealer had score of " << dealerScore << std::endl;
}
void gameTie(std::array<Card, 11> &deck, std::array<Card, 11> &dealer){
int playerScore = getDeckValue(deck);
std::cout << "Both you and the dealer had score of " << playerScore << ". It is a tie!" << std::endl;
}
void nowDealer(std::array<Card, 11> &deck, std::array<Card, 11> &dealer, std::array<Card, 52> &cardDeck, Card *deckPtr){
short dealerScore = getDeckValue(dealer);
short playerScore = getDeckValue(deck);
if (dealerScore >= 17){
if (dealerScore < 22){
if (dealerScore > playerScore){
playerLost(deck, dealer);
}
else if (dealerScore < playerScore){
playerWon(deck, dealer);
}
else if (dealerScore == playerScore){
gameTie(deck, dealer);
}
}
}
else {
drawCard(dealer,cardDeck,*deckPtr++);
std::cout << "Dealer drew a card a now have a score of " << getDeckValue(dealer) << std::endl;
nowDealer(deck, dealer,cardDeck,deckPtr);
}
}
void doHit(std::array<Card, 11> &deck, std::array<Card, 11> &dealer, std::array<Card, 52> &cardDeck, Card *deckPtr){
drawCard(deck,cardDeck,*deckPtr++);
short deckValue = getDeckValue(deck);
std::cout << "Now your score is " << deckValue << std::endl;
if (deckValue < 22){
if (deckValue == 21){
playerWon(deck, dealer);
}
else {
short dealerValue = getDeckValue(dealer);
if (dealerValue < 22){
if (dealerValue == 21){
playerLost(deck, dealer);
}
else {
int move = getMove();
if (move){
doHit(deck, dealer, cardDeck, deckPtr);
}
else {
nowDealer(deck, dealer, cardDeck, deckPtr);
}
}
}
else {
playerWon(deck, dealer);
}
}
}
else {
playerLost(deck, dealer);
}
}
void startGame(){
std::array<Card, 52> cardDeck = getShuffledDeck();
Card *cardPtr = &cardDeck[0];
std::array<Card, 11> dealerCards;
std::array<Card, 11> myCards;
drawCard(myCards, cardDeck, *cardPtr++);
drawCard(dealerCards, cardDeck, *cardPtr++);
drawCard(myCards, cardDeck, *cardPtr++);
std::cout << "You have " << getDeckValue(myCards) << ", dealer have " << getDeckValue(dealerCards) << std::endl;
int move = getMove();
if (move){
doHit(myCards,dealerCards, cardDeck, cardPtr);
}
else {
nowDealer(myCards, dealerCards, cardDeck, cardPtr);
}
}
| true |
5f2ed32c8bb51aecc414a12618ecd76494e20168 | C++ | vicyan1611/vscode-cpp | /archive/Training Gitgud/EXPRESS.cpp | UTF-8 | 1,868 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int a[1004],max1,max2,res;
pair <int,int> pos1,pos2;
int main()
{
freopen("express.inp","r",stdin);
freopen("express.out","w",stdout);
int n;
cin>>n;
for (int i=1;i<=n;++i)
cin>>a[i];
for (int i=1;i<n;++i)
{
if (a[i]*a[i+1]>max1)
{
max1=a[i]*a[i+1];
pos1.first=i;
pos1.second=i+1;
} else if (a[i]*a[i+1]==max1)
{
if (abs(a[i]-a[i+1])<abs(a[pos1.first]-a[pos1.second]))
{
pos1.first=i;
pos1.second=i+1;
}
}
}
for (int i=1;i<n;++i)
{
if (a[i]*a[i+1]>=max2)
{
if (i!=pos1.first||a[i]*a[i+1]!=max1)
{
if (a[i]*a[i+1]>max2)
{
max2=a[i]*a[i+1];
pos2.first=i;
pos2.second=i+1;
} else
{
if (abs(a[i]-a[i+1])<abs(a[pos2.first]-a[pos2.second]))
{
pos2.first=i;
pos2.second=i+1;
}
}
}
}
}
//cout<<pos1.first<<" "<<pos1.second<<endl<<pos2.first<<" "<<pos2.second;
res=0;
for (int i=1;i<=n;++i)
{
if (i!=pos1.first&&i!=pos1.second&&i!=pos2.first&&i!=pos2.second)
{
res+=a[i];
}
}
if (pos1.first!=pos2.second&&pos1.second!=pos2.first)
{
res+=a[pos1.first]*a[pos1.second]+a[pos2.first]*a[pos2.second];
} else if (pos1.second==pos2.first)
{
res+=a[pos1.first]*a[pos2.first]*a[pos2.second];
} else if (pos2.second==pos1.first)
{
res+=a[pos2.first]*a[pos2.second]*a[pos1.second];
}
cout<<res;
return 0;
} | true |
78dbbe765e8e1ce780b53b6651bab903ce69d8b9 | C++ | sb-baifeng-sb/SpaceTD | /include/components/Turret.hpp | UTF-8 | 809 | 2.53125 | 3 | [] | no_license | /*
* Turret.hpp
*
* Created on: 02/10/2014
* Author: giovani
*/
#ifndef TURRET_HPP_
#define TURRET_HPP_
#include <entityx/entityx.h>
#include "TurretInfo.hpp"
struct Turret : entityx::Component<Turret>
{
Turret(entityx::Entity entity, const TurretInfo& info);
~Turret();
entityx::Entity entity_;
bool ready_;
void fire(entityx::Entity target, entityx::EntityManager& es);
void levelUp();
int damageLevel() const;
int cooldownLevel() const;
int rangeLevel() const;
int nextDamageLevel() const;
int nextCooldownLevel() const;
int nextRangeLevel() const;
int upgradeCost() const;
TurretInfo info_;
private:
void reloadComponents();
int damageLevel(int from, int to) const;
int cooldownLevel(double cd) const;
int rangeLevel(int range) const;
};
#endif /* TURRET_HPP_ */
| true |
5901f3b03a263292418a29f403dbd65cf320eef9 | C++ | mycmac/TDtestsUnitaires | /TDtestsUnitaires/Calculator.cpp | ISO-8859-1 | 645 | 3.28125 | 3 | [] | no_license | #ifndef _Calculator_H_
#define _Calculator_H_
#include <iostream>
#include <math.h>
#include "Calculator.h"
int Calculator::factorielle(int a) {
int fact = 1;
int i = 0;
while (i <= a) {
fact *= i;
i++;
}
return fact;
}
int Calculator::add(int a, int b) {
return a + b;
}
int Calculator::sub(int a, int b) {
return a - b;
}
double Calculator::div(double a, double b) {
//Fonction cre suite au Test 1
// return 2
//Fonction cre suite au Test 2
//return a / b;
//Fonction cre suite au Test 3
if (b == 0) {
std::cerr << "Error: Division by 0 not possible";
exit(-1);
}
else {
return a / b;
}
}
#endif | true |
2ad9880a25a0f0ddd34315ec2c92372aa4b3f0b6 | C++ | bmleight/kegbot_wander | /kegbot_wonder.ino | UTF-8 | 7,896 | 2.53125 | 3 | [] | no_license | #include <NewPing.h>
#include "BMSerial.h"
#include "RoboClaw.h"
#define address 0x80
/* KEGBOT MODES */
const int USER_DRIVE = 1;
const int ROBOT_DRIVE = 2;
RoboClaw roboclaw(15,14);
#define SONAR_NUM 5 // Number or sensors.
#define ITERATION_NUM 4 // Number or iterations.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).
#define DEBUG 1
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTDEC(x) Serial.print (x, DEC)
#define DEBUG_PRINTLN(x) Serial.println (x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTDEC(x)
#define DEBUG_PRINTLN(x)
#endif
#define MOTOR_STILL 1500
//Servo myservo1; // create servo object to control a RoboClaw channel
//Servo myservo2; // create servo object to control a RoboClaw channel
unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM]; // Where the ping distances are stored.
unsigned int history[SONAR_NUM][ITERATION_NUM]; // Store ping distances.
unsigned int average[SONAR_NUM];
uint8_t currentSensor = 0; // Keeps track of which sensor is active.
uint8_t currentIteration = 0;
int speed_left = 0, speed_right = 0;
char commands[256];
int command_index = 0;
int have_command = 0;
int mode = USER_DRIVE;
NewPing sonar[SONAR_NUM] = { // Sensor object array.
NewPing(11, 10, MAX_DISTANCE),
NewPing(9, 8, MAX_DISTANCE),
NewPing(13, 12, MAX_DISTANCE),
NewPing(3, 2, MAX_DISTANCE),
NewPing(7, 6, MAX_DISTANCE),
// NewPing(25, 26, MAX_DISTANCE),
// NewPing(27, 28, MAX_DISTANCE),
// NewPing(29, 30, MAX_DISTANCE),
// NewPing(31, 32, MAX_DISTANCE),
// NewPing(34, 33, MAX_DISTANCE),
// NewPing(35, 36, MAX_DISTANCE),
// NewPing(37, 38, MAX_DISTANCE),
// NewPing(39, 40, MAX_DISTANCE),
// NewPing(50, 51, MAX_DISTANCE),
// NewPing(52, 53, MAX_DISTANCE)
};
void setup() {
Serial.begin(115200);
Serial2.begin(9600);
roboclaw.begin(9600);
pingTimer[0] = millis() + 75; // First ping starts at 75ms, gives time for the Arduino to chill before starting.
for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
// myservo1.attach(4);
// myservo2.attach(5);
}
void loop() {
for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
if (millis() >= pingTimer[i]) { // Is it this sensor's time to ping?
pingTimer[i] += PING_INTERVAL * SONAR_NUM; // Set next time this sensor will be pinged.
if (i == 0 && currentSensor == SONAR_NUM - 1) {
oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
}
sonar[currentSensor].timer_stop(); // Make sure previous timer is canceled before starting a new ping (insurance).
if(cm[currentSensor] == 0) {
history[currentSensor][currentIteration] = MAX_DISTANCE;
}
currentSensor = i; // Sensor being accessed.
cm[currentSensor] = 0; // Make distance zero in case there's no ping echo for this sensor.
sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
}
}
// The rest of your code would go here.
}
void echoCheck() { // If ping received, set the sensor distance to array.
if (sonar[currentSensor].check_timer()) {
cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
history[currentSensor][currentIteration] = cm[currentSensor];
}
}
void computeAverage() {
unsigned int sum;
unsigned int valid_readings;
for (uint8_t i = 0; i < SONAR_NUM; i++) {
// DEBUG_PRINT("Average ");
// DEBUG_PRINT(i);
// DEBUG_PRINT(": ");
sum = valid_readings = 0;
for (uint8_t j = 0; j < ITERATION_NUM; j++) {
// DEBUG_PRINT(history[i][j]);
// if(j < ITERATION_NUM - 1) {
// DEBUG_PRINT(" + ");
// }
if(history[i][j] > 0) {
sum += history[i][j];
valid_readings++;
} else {
sum += 200;
valid_readings++;
}
}
if(valid_readings) {
average[i] = sum / valid_readings;
} else {
average[i] = 0;
}
// DEBUG_PRINT("= ");
// DEBUG_PRINT(sum);
// DEBUG_PRINT(" / ");
// DEBUG_PRINT(valid_readings);
// DEBUG_PRINT(" = ");
// DEBUG_PRINTLN(average[i]);
}
}
void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
computeAverage();
currentIteration = (currentIteration + 1) % ITERATION_NUM;
Serial.println('test');
readCommand();
// moveRobot();
// wander();
// for (uint8_t i = 0; i < SONAR_NUM; i++) {
// Serial.print(average[i]);
// Serial.print("\t");
// }
// for (uint8_t i = 0; i < SONAR_NUM; i++) {
// Serial.print(i);
// Serial.print("=");
// Serial.print(cm[i]);
// Serial.print(" (");
// Serial.print(average[i]);
// Serial.print(") ");
// Serial.print("cm ");
// }
Serial.println();
}
void readCommand() {
int result;
char character;
Serial.println('read command');
while (Serial2.available()) {
Serial.println('test');
// read the incoming byte:
character = Serial2.read();
if(character > 0) {
commands[command_index] = character;
command_index++;
}
if(character == '\n') {
have_command = 1;
}
}
if(have_command) {
//if the command is to change a mode
if(strstr(commands, "mode") != NULL) {
result = sscanf(commands,"{mode:%d}", &mode);
} else {
result = sscanf(commands,"{left:%d,right:%d}", &speed_left, &speed_right);
}
have_command = 0;
command_index = 0;
Serial.println(commands);
}
}
void moveRobot() {
int left = 1500 - (int)(speed_left * 1.25);
int right = 1500 - (int)(speed_right * 1.25);
Serial.println(left);
//Serial.println(right);
roboclaw.BackwardM1(address, left); //Cmd 0
roboclaw.BackwardM2(address, right); //Cmd 5
}
//void sendReadings() {
//
// Serial.print("{\"readings\":[");
//
// for(int i=0; i<num_ir; i++) {
// Serial.print(readings[i]);
// if(i < num_ir-1) {
// Serial.print(",");
// }
// }
//
// Serial.println("]}");
//
//}
void wander() {
float minDistance = 1000;
int minSensor = -1;
for(int i=0; i<SONAR_NUM; i++) {
if(average[i] > 0 && average[i] < minDistance) {
minDistance = average[i];
minSensor = i;
}
}
// Serial.print(minSensor);
// Serial.print(" ");
// Serial.print(minDistance);
// roboclaw.ForwardMixed(address, 0);
// return;
if(minDistance >= 40) {
Serial.println(" forward");
//forward
roboclaw.BackwardM1(address,25); //Cmd 0
roboclaw.BackwardM2(address,25); //Cmd 5
// myservo1.writeMicroseconds(MOTOR_STILL - 50);
// myservo2.writeMicroseconds(MOTOR_STILL - 50);
} else {
if(true) {
Serial.println(" stop");
roboclaw.ForwardM1(address,0); //Cmd 0
roboclaw.BackwardM2(address,0); //Cmd 5
} else if(minSensor < 2) {
Serial.println(" left");
//turn left
roboclaw.ForwardM1(address,25); //Cmd 0
roboclaw.BackwardM2(address,25); //Cmd 5
// myservo1.writeMicroseconds(MOTOR_STILL + 50);
// myservo2.writeMicroseconds(MOTOR_STILL - 50);
} else {
Serial.println(" right");
//turn right
roboclaw.ForwardM1(address,25); //Cmd 0
roboclaw.BackwardM2(address,25); //Cmd 5
// myservo1.writeMicroseconds(MOTOR_STILL - 50);
// myservo2.writeMicroseconds(MOTOR_STILL + 50);
}
}
}
| true |
a231cb0aab4763463a427a49445a503ad2f30780 | C++ | Asoke26/CrackingTheCodingInterview | /RotateMatrix1.7/src/rotate_matrix.cpp | UTF-8 | 792 | 3.84375 | 4 | [] | no_license | #include <vector>
#include <algorithm>
#include <iostream>
void rotate(std::vector<std::vector<int> >& matrix){
// Rotation must be in place
// First calculate the transpose
int n = matrix.size();
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
std::swap(matrix[i][j], matrix[j][i]);
}
}
for (int i = 0; i < n; i++) std::reverse(std::begin(matrix[i]), std::end(matrix[i]));
return;
}
int main(int argc, char ** argv){
std::vector<std::vector<int> > myvec = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
rotate(myvec);
// Print vector
int n = myvec.size();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
std::cout << myvec[i][j] << " ";
}
std::cout << '\n';
}
return 0;
}
| true |
9c1fd7f680e305c211447a541d0235d78daee758 | C++ | lucaparisi91/qmc3 | /dmc/wavefunction/shell.h | UTF-8 | 2,068 | 3.125 | 3 | [
"MIT"
] | permissive | #ifndef SHELL_H
#define SHELL_H
#include <complex>
#include <cmath>
#include <vector>
#include <tuple>
#include <iostream>
#include <algorithm>
#if DIMENSIONS == 3
class shell
{
public:
shell(unsigned int n_) : n(n_){list();};
size_t capacity() const {return shellStructure.size();}
unsigned int level() const {return n;}
const auto & operator[](unsigned int i) const{return shellStructure[i] ;}
private:
unsigned int n;
void list()
{
int nMax=int(sqrt(n));
for (int nx=-nMax;nx<=nMax;nx ++ )
{
for (int ny=-nMax;ny<=nMax;ny++ )
{
for (int nz=-nMax;nz<=nMax;nz++ )
{
if (nx*nx + ny*ny + nz*nz==n)
{
shellStructure.push_back(std::make_tuple(nx,ny,nz) );
}
}
}
}
}
std::vector<std::tuple<int, int,int> > shellStructure;
};
class shellStructure
{
public:
using shell_t = shell;
shellStructure(unsigned int N) : _N(N){
shells.push_back(shell_t(0));
fillingNumbers.push_back(1);
int n=1;
while(fillingNumbers.back() < N)
{
auto sh=shell_t(n);
if ( sh.capacity()>0)
{
shells.push_back(sh);
fillingNumbers.push_back(shells.back().capacity());
fillingNumbers.back()+=fillingNumbers[fillingNumbers.size()-2];
}
n++;
}
};
bool isMagicNumber(int n)
{
return not (std::find(fillingNumbers.begin(),fillingNumbers.end(),n)==fillingNumbers.end());
}
const auto & getMagicNumbers() const {return fillingNumbers;}
const shell_t & getShell(size_t i) const {return shells[i];}
const shell_t & operator[](size_t i) const {return getShell(i);}
size_t nShells() const {return shells.size();}
size_t capacity() const
{
return fillingNumbers[-1];
};
private:
int _N;
std::vector<shell_t> shells;
std::vector<int> fillingNumbers;
std::vector<std::tuple<int,int> > orderedShells;
};
std::ostream & operator<<(std::ostream & out,const shell & shell);
std::ostream & operator<<(std::ostream & out,const shellStructure & sh);
#endif
#endif
| true |