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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15534749519aabcfc7d234de833df1ba2d5a3a53 | C++ | thrimbor/Hurrican | /Hurrican/src/triggers/Trigger_LaFassSpawner.cpp | UTF-8 | 1,828 | 2.546875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | // --------------------------------------------------------------------------------------
// Der LaFassSpawner
//
// Spawnt in bestimmten Abständen (Value2) das LaFass =)
// --------------------------------------------------------------------------------------
#include "Trigger_LaFassSpawner.hpp"
#include "stdafx.hpp"
// --------------------------------------------------------------------------------------
// Konstruktor
// --------------------------------------------------------------------------------------
GegnerLaFassSpawner::GegnerLaFassSpawner(int Wert1, int Wert2, bool Light) {
Handlung = GEGNER_STEHEN;
BlickRichtung = RECHTS;
Energy = 100;
Value1 = Wert1;
Value2 = Wert2;
// default wert
if (Value2 == 0)
Value2 = 40;
ChangeLight = Light;
Destroyable = false;
OwnDraw = true;
AnimCount = static_cast<float>(Wert2);
DontMove = true;
Active = true;
}
// --------------------------------------------------------------------------------------
// "Bewegungs KI"
// --------------------------------------------------------------------------------------
void GegnerLaFassSpawner::DoKI() {
// Fass spawnen?
if (PlayerAbstand() < 800)
AnimCount -= 1.0f SYNC;
if (AnimCount <= 0.0f) {
AnimCount = static_cast<float>(Value2);
// in die richtige Richtung schubsen
if (Value1 == 0) {
Gegner.PushGegner(xPos, yPos, LAFASS, -5, 0, false);
} else {
Gegner.PushGegner(xPos, yPos, LAFASS, 5, 0, false);
}
}
}
// --------------------------------------------------------------------------------------
// LaFassSpawner explodiert (nicht)
// --------------------------------------------------------------------------------------
void GegnerLaFassSpawner::GegnerExplode() {}
| true |
96005248bdbf5e3387e67290b0ee67afa7626128 | C++ | VAR-solutions/Algorithms | /Dynamic Programming/Egg Dropping Puzzle/cpp/eggDroppingPuzzle.cpp | UTF-8 | 1,018 | 3.453125 | 3 | [
"MIT"
] | permissive |
// A Dynamic Programming based C++ Program for the Egg Dropping Puzzle
# include <stdio.h>
# include <limits.h>
int max(int a, int b) { return (a > b)? a: b; }
int eggDrop(int n, int k)
{
int eggFloor[n+1][k+1];
int res;
int i, j, x;
for (i = 1; i <= n; i++)
{
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
for (i = 2; i <= n; i++)
{
for (j = 2; j <= k; j++)
{
eggFloor[i][j] = INT_MAX;
for (x = 1; x <= j; x++)
{
res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
return eggFloor[n][k];
}
int main()
{
int n = 2, k = 36;
printf ("nMinimum number of trials in worst case with %d eggs and "
"%d floors is %d \n", n, k, eggDrop(n, k));
return 0;
} | true |
b0e2a40370d31db0943f7adbd5cb0eb26f74d4eb | C++ | mtulio/kb | /Faculdade/2008-1_-_III/Estrutura_de_Dados_I/projetos/pilha/ProgramaPrincipal.cpp | UTF-8 | 1,632 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include<string>
#include<stdlib.h>
//#include"no.h"
#include"Pilha.h"
using namespace std;
int main()
{
char palavra[]="subinoonibus";
cout<<" Digite a palavra: ";
cin>>palavra;
//verificando o tamanho da palavra pra usar no proximo loop
int tamanho=0;
for(int i=0;(palavra[i])!= ('\0'); i++){
tamanho++;
}
//criando uma pilha
Pilha palindroma;
//quebrando a palavra
for(int i=0; i<tamanho ; i++){
char let;
let = palavra[i];
//cout<<"\n Letra MAIN atribuir: "<<let;
if(!palindroma.atribuirPilha(let))cout<<"erro atribuir";
//if(palindroma->atribuirPilha(let)) cout<<" Nao foi possivel atribuir"<<endl;
}//fim for
//copiando os elementos do topo da pilha para uma pilha aux
//e assim invertendo a ordem das palavras
//Pilha pilhaAux;
for(int i=0; !palindroma.estaVazio(); i++){
char letra;
if(!palindroma.retirarPilha(letra)) cout<<"erro retirar";
//std::cout<<"\n Letra MAIN RETIRAR: "<<letra;
//comparando cada letra q estava na pilha com a palavra origianal
if(letra != palavra[i]){
cout<<" A palavra nao eh palidroma!!!"<<endl;
cin.get();cin.get();
exit (0);
}
// pilhaAux->atribuirPilha(letra);
}//fim for
cout<<" A palavra eh palindroma!!!"<<endl;
exit(1);
}//fim metodo main
| true |
ad62869cd5541d8989f55444345dffbb2609bff0 | C++ | pandakkkk/DataStructures-Algorithms | /Trees/Binary Tree/110. Balanced Binary Tree.cpp | UTF-8 | 1,105 | 2.5625 | 3 | [] | no_license | /*
____ _ _ _ _ __ __ _ _ _
| _ \(_)___| |__ __ _| |__ | |__ | \/ | __ _| | |__ ___ | |_ _ __ __ _
| |_) | / __| '_ \ / _` | '_ \| '_ \ | |\/| |/ _` | | '_ \ / _ \| __| '__/ _` |
| _ <| \__ \ | | | (_| | |_) | | | | | | | | (_| | | | | | (_) | |_| | | (_| |
|_| \_\_|___/_| |_|\__,_|_.__/|_| |_| |_| |_|\__,_|_|_| |_|\___/ \__|_| \__,_|
*/
#include <bits/stdc++.h>
using namespace std;
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
int height(TreeNode *root, bool &flag)
{
if (root == NULL)
return 0;
int lh = height(root->left, flag);
int rh = height(root->right, flag);
if (abs(lh - rh) > 1)
flag = true;
return max(lh, rh) + 1;
}
bool isBalanced(TreeNode *root)
{
bool flag = false;
height(root, flag);
return flag;
}
}; | true |
a11bd9808f21bf10d2f7cf200e5845fe55facd9f | C++ | graninas/cpp_stm_free | /cpp_stm/stm/stmf/stmf.h | UTF-8 | 8,197 | 3.0625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef STM_STMF_STMF_H
#define STM_STMF_STMF_H
#include "../types.h"
#ifdef STM_DEBUG
#include <iostream>
#endif
namespace stm
{
namespace stmf
{
// STM methods
template <typename A, typename Next>
struct NewTVar
{
A val;
std::string name;
std::function<Next(TVar<A>)> next;
static NewTVar<Any, Next> toAny(
const A& val,
const std::string& name,
const std::function<Next(TVar<A>)>& next)
{
std::function<Next(TVar<A>)> nextCopy = next;
NewTVar<Any, Next> m;
m.val = val; // cast to any
m.name = name;
m.next = [=](const TVarAny& tvarAny)
{
TVar<A> tvar;
tvar.id = tvarAny.id;
tvar.name = tvarAny.name;
return nextCopy(tvar);
};
return m;
}
~NewTVar()
{
#ifdef STM_DEBUG
std::cout << "NewTVar: destructor, name: " << name << std::endl;
#endif
}
NewTVar()
{
#ifdef STM_DEBUG
std::cout << "NewTVar: empty constructor " << std::endl;
#endif
}
explicit NewTVar(const A& val,
const std::string& name,
const std::function<Next(TVar<A>)>& next)
: val(val)
, name(name)
, next(next)
{
#ifdef STM_DEBUG
std::cout << "NewTVar: constructor " << std::endl;
#endif
}
NewTVar(const NewTVar<A, Next>& other)
: val(other.val)
, name(other.name)
, next(other.next)
{
#ifdef STM_DEBUG
std::cout << "NewTVar: copy constructor, name: " << other.name << std::endl;
#endif
}
NewTVar(const NewTVar<A, Next>&& other)
: val(other.val)
, name(other.name)
, next(other.next)
{
#ifdef STM_DEBUG
std::cout << "NewTVar: move constructor, name: " << other.name << std::endl;
#endif
}
NewTVar<A, Next>& operator=(NewTVar<A, Next> other)
{
#ifdef STM_DEBUG
std::cout << "NewTVar: copy assignment operator, name: " << other.name << std::endl;
#endif
std::swap(val, other.val);
std::swap(name, other.name);
std::swap(next, other.next);
return *this;
}
NewTVar<A, Next>& operator=(NewTVar<A, Next>&& other)
{
#ifdef STM_DEBUG
std::cout << "NewTVar: move assignment operator, name: " << other.name << std::endl;
#endif
std::swap(val, other.val);
std::swap(name, other.name);
std::swap(next, other.next);
return *this;
}
};
template <typename A, typename Next>
struct ReadTVar
{
TVar<A> tvar;
std::function<Next(A)> next;
static ReadTVar<Any, Next> toAny(
const TVar<A>& tvar,
const std::function<Next(A)>& next)
{
std::function<Next(A)> nextCopy = next;
TVar<Any> tvar2;
tvar2.id = tvar.id;
tvar2.name = tvar.name;
ReadTVar<Any, Next> m;
m.tvar = tvar2;
m.next = [=](const Any& val)
{
A val2 = std::any_cast<A>(val); // cast from any
return nextCopy(val2);
};
return m;
}
ReadTVar()
{
#ifdef STM_DEBUG
std::cout << "ReadTVar: empty constructor " << std::endl;
#endif
}
explicit ReadTVar(const TVar<A>& tvar,
const std::function<Next(A)>& next)
: tvar(tvar)
, next(next)
{
#ifdef STM_DEBUG
std::cout << "ReadTVar: constructor " << std::endl;
#endif
}
ReadTVar(const ReadTVar<A, Next>& other)
: tvar(other.tvar)
, next(other.next)
{
#ifdef STM_DEBUG
std::cout << "ReadTVar: copy constructor, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
}
ReadTVar(const ReadTVar<A, Next>&& other)
: tvar(other.tvar)
, next(other.next)
{
#ifdef STM_DEBUG
std::cout << "ReadTVar: move constructor, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
}
ReadTVar<A, Next>& operator=(ReadTVar<A, Next> other)
{
#ifdef STM_DEBUG
std::cout << "ReadTVar: copy assignment operator, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
std::swap(tvar, other.tvar);
std::swap(next, other.next);
return *this;
}
ReadTVar<A, Next>& operator=(ReadTVar<A, Next>&& other)
{
#ifdef STM_DEBUG
std::cout << "ReadTVar: move assignment operator, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
std::swap(tvar, other.tvar);
std::swap(next, other.next);
return *this;
}
};
template <typename A, typename Next>
struct WriteTVar
{
TVar<A> tvar;
A val;
std::function<Next(Unit)> next;
static WriteTVar<Any, Next> toAny(
const TVar<A>& tvar,
const A& val,
const std::function<Next(Unit)>& next)
{
std::function<Next(Unit)> nextCopy = next;
TVar<Any> tvar2;
tvar2.id = tvar.id;
tvar2.name = tvar.name;
WriteTVar<Any, Next> m;
m.tvar = tvar2;
m.val = val; // cast to any
m.next = [=](const Unit& unit)
{
return nextCopy(unit);
};
return m;
}
WriteTVar()
{
#ifdef STM_DEBUG
std::cout << "WriteTVar: empty constructor " << std::endl;
#endif
}
explicit WriteTVar(const TVar<A>& tvar,
const A& val,
const std::function<Next(Unit)>& next)
: tvar(tvar)
, val(val)
, next(next)
{
#ifdef STM_DEBUG
std::cout << "WriteTVar: constructor " << std::endl;
#endif
}
WriteTVar(const WriteTVar<A, Next>& other)
: tvar(other.tvar)
, val(other.val)
, next(other.next)
{
#ifdef STM_DEBUG
std::cout << "WriteTVar: copy constructor, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
}
WriteTVar(const ReadTVar<A, Next>&& other)
: tvar(other.tvar)
, val(other.val)
, next(other.next)
{
#ifdef STM_DEBUG
std::cout << "WriteTVar: move constructor, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
}
WriteTVar<A, Next>& operator=(WriteTVar<A, Next> other)
{
#ifdef STM_DEBUG
std::cout << "WriteTVar: copy assignment operator, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
std::swap(tvar, other.tvar);
std::swap(val, other.val);
std::swap(next, other.next);
return *this;
}
WriteTVar<A, Next>& operator=(WriteTVar<A, Next>&& other)
{
#ifdef STM_DEBUG
std::cout << "WriteTVar: move assignment operator, tvar id: "
<< other.tvar.id
<< ", tvar name: "
<< other.tvar.name
<< std::endl;
#endif
std::swap(tvar, other.tvar);
std::swap(val, other.val);
std::swap(next, other.next);
return *this;
}
};
template <typename A, typename Next>
struct Retry
{
};
// Any-specified STM methods
template <typename Next>
using NewTVarA = NewTVar<Any, Next>;
template <typename Next>
using ReadTVarA = ReadTVar<Any, Next>;
template <typename Next>
using WriteTVarA = WriteTVar<Any, Next>;
template <typename Next>
using RetryA = Retry<Any, Next>;
// STMF algebraic data type
template <class Ret>
struct STMF
{
std::variant<
NewTVarA<Ret>,
ReadTVarA<Ret>,
WriteTVarA<Ret>,
RetryA<Ret>
> stmf;
};
} // namespace stmf
} // namespace stm
#endif // STM_STMF_STMF_H
| true |
e78be0f9daa3f34f7f896988de1cea165149051a | C++ | klaoude/Whala | /Whala/Hud.cpp | UTF-8 | 913 | 2.578125 | 3 | [] | no_license | #include "Hud.h"
#include <KlaoudeEngine\RessourceManager.h>
#include "Player.h"
Hud::Hud(float w, float h)
{
m_hudTexture = KlaoudeEngine::RessourceManager::getTexture("Textures/hud.png").id;
m_rectTexture = KlaoudeEngine::RessourceManager::getTexture("Textures/whitePixel.png").id;
m_width = w;
m_height = h;
m_uvRect = glm::vec4(0.f, 0.f, 1.f, 1.f);
m_hudRect = glm::vec4(m_width / 2 - 160, 0, 322.f, 124.f);
}
void Hud::draw(KlaoudeEngine::SpriteBatch& spriteBatch)
{
m_lifeBarRect = glm::vec4(m_width / 2 - 154, 107, m_player->getHealth()*310/m_player->getMaxHealth(), 11.f);
m_zRect = glm::vec4(m_width / 2 - 156, 47, 74, m_player->getzCoolCur() * 52 / m_player->getzCoolMax());
spriteBatch.draw(m_hudRect, m_uvRect, m_hudTexture, 0.f, c_white);
spriteBatch.draw(m_lifeBarRect, m_uvRect, m_rectTexture, 0.f, c_red);
spriteBatch.draw(m_zRect, m_uvRect, m_rectTexture, 0.f, c_darkRed);
} | true |
d21117afd565ab35d532ca3638f39bf4098f6244 | C++ | jianxinzhu/Polymorphism | /PayRoll/SalaryEmployee.hpp | UTF-8 | 583 | 2.90625 | 3 | [] | no_license | /*
name: jianxin zhu
date: aug/16/2020
*/
#ifndef SALARYEMPLOYEE_H
#define SALARYEMPLOYEE_H
#include"Employee.h"
class SalaryEmployee :public Employee
{
public:
SalaryEmployee(const std::string&, const std::string&, const std::string&,const Date&, double = 0, double = 0);
virtual ~SalaryEmployee() = default;
void setWeekHour(double);
void setHourlySalary(double);
double getWeekHour() const;
double getHourlSalary() const;
virtual double earnning() const override;
virtual std::string toString() const override;
private:
double weekHour;
double hourlySalary;
};
#endif
| true |
b421ab2ccb9c0237bfbd9204d0e17603c9ac2060 | C++ | seancui/ECE244-Circuit-Solver | /NodeList.cpp | UTF-8 | 2,656 | 3.6875 | 4 | [] | no_license | //this file contains function definitions for NodeList class
#include "NodeList.h"
#include <iomanip>
NodeList::NodeList(){
nodeHead = NULL;
}
void NodeList::insertNode(int nodeNum_){
Node* cur = nodeHead;
Node* prev;
if(cur == NULL){ //if there are no nodes in list
Node* node = new Node(nodeNum_, NULL);
nodeHead = node;
}
else{
bool break1 = false;
bool break2 = false;
while(cur != NULL){
if (cur->getNodeNum() > nodeNum_){ //if the node to insert's number is smaller than the head node's number
break1 = true;
break; //stop loop to prevent checking other nodes and prevent checking second case
}
if (cur->getNext() != NULL){
if(cur->getNext()->getNodeNum() > nodeNum_){ //if the next node's number is greater than node to insert's number, cur is in the right spot and should insert between current and next node
break2 = true;
break;
}
}
prev = cur;
cur = cur->getNext();
}
if (cur == nodeHead && break1 == true && break2 == false){ //insert to front of list
Node* node = new Node(nodeNum_, cur);
nodeHead = node;
}
else if (break1 == false && break2 == true){ //insert in middle of list
Node* node = new Node(nodeNum_, cur->getNext());
cur->setNext(node);
}
else if (cur == NULL){ //insert to end of list
Node* node = new Node(nodeNum_, NULL);
prev->setNext(node);
}
}
}
bool NodeList::nodeExists(int nodeNum){
Node* cur = nodeHead;
while(cur != NULL){
if (nodeNum == cur->getNodeNum())
return true;
cur = cur->getNext();
}
return false; //otherwise node number not found
}
Node* NodeList::findNode(int nodeNum){
Node* cur = nodeHead;
while(cur != NULL){
if (nodeNum == cur->getNodeNum()){
return cur;
}
cur = cur->getNext();
}
}
Node* NodeList::getHead(){
return nodeHead;
}
void NodeList::printR(string name){
Node* cur = nodeHead;
while (cur != NULL){
cur->printRes(name);
if (cur->getHead()->findR(name) == true)
return; //if the resistor is found in current node return to prevent checking other nodes to prevent printing twice
cur = cur->getNext();
}
}
int NodeList::getSize(){
int size = 0;
Node* cur = nodeHead;
while (cur != NULL){
size += 1;
cur = cur->getNext();
}
return size;
}
| true |
9883d842a15936ce4181151f28c7b8fd55a79ef3 | C++ | M-Schenk-91/forschungsseminar2018 | /cpp/processing/tracking/Trackable.cpp | UTF-8 | 6,419 | 2.71875 | 3 | [] | no_license |
#include "Trackable.h"
#include "TrackableTypes.h"
#include "../datastructures/document.h"
#include "../datastructures/stamp.h"
#include "../datastructures/hand.h"
#include "../datastructures/touch.h"
#include "../../math/smath.h"
Trackable::Trackable(uint8_t type_id, std::string const & name) : m_type_id(type_id), m_name(name)
{}
Trackable::~Trackable() = default;
uint8_t const Trackable::type_id() const
{
return this->m_type_id;
}
std::vector<cv::Point2f> const & Trackable::roi() const
{
return this->m_roi;
}
void Trackable::draw(cv::Mat & target, int const size) const
{
switch(this->m_type_id)
{
case TrackableTypes::PHYSICAL_DOCUMENT:
{
for(auto p = m_roi.begin(); p != m_roi.end(); ++p)
cv::circle(target, * p / size, 5, cv::Scalar(0, 0, 255), -1);
}
break;
case TrackableTypes::TANGIBLE:
{
if(this->m_roi.size() > 0)
{
auto const & s = (* (stamp *) this);
switch(s.type())
{
case stamp::stamp_type::ACCEPT:
cv::putText(target, "ACCEPT", this->roi()[1] / size, 1, 1, cv::Scalar(0, 0, 255));
break;
case stamp::stamp_type::REJECT:
cv::putText(target, "REJECT", this->roi()[1] / size, 1, 1, cv::Scalar(0, 0, 255));
break;
case stamp::stamp_type::NOTED:
cv::putText(target, "NOTED", this->roi()[1] / size, 1, 1, cv::Scalar(0, 0, 255));
break;
}
}
for(auto p = m_roi.begin(); p != m_roi.end(); ++p)
cv::circle(target, * p / size, 5, cv::Scalar(0, 0, 255), -1);
}
break;
case TrackableTypes::HAND:
{
auto const & h = (* (hand *) this);
if(h.roi().size() == 4)
{
for(int i = 0; i < 4; i++)
cv::line(target, this->roi()[i] / size, this->roi()[(i + 1) % 4] / size, cv::Scalar(255, 0, 0));
for(auto const & p : h.finger_tips())
cv::circle(target, p, 5, cv::Scalar(0, 0, 255), -1);
cv::circle(target, h.hand_center(), 5, cv::Scalar(0, 255, 0), -1);
}
}
break;
case TrackableTypes::TOUCH:
{
auto const & t = (* (touch *) this);
cv::circle(target, t.center() / size, 5, cv::Scalar(255, 0, 0), -1);
cv::RotatedRect rr(t.center(), cv::Size(t.width(), t.height()), t.angle());
cv::Point2f pts[4];
rr.points(pts);
for(int i = 0; i < 4; i++)
cv::circle(target, pts[i] / size, 5, cv::Scalar(0, 0, 255), -1);
}
break;
}
}
void Trackable::set_roi(std::vector<cv::Point2f> const & corners, float const factor)
{
switch(this->m_type_id)
{
case TrackableTypes::PHYSICAL_DOCUMENT:
{
m_roi.clear();
cv::Point2f intersection = math::intersection(corners[0], corners[2], corners[1], corners[3]);
intersection.x *= factor;
intersection.y *= factor;
m_roi = std::vector<cv::Point2f>
{
math::transform_marker_corner_points_to_DIN_A4_sheet_corners(cv::Point2f(corners[0].x * factor, corners[0].y * factor), cv::Point2f(corners[3].x * factor, corners[3].y * factor), intersection),
math::transform_marker_corner_points_to_DIN_A4_sheet_corners(cv::Point2f(corners[1].x * factor, corners[1].y * factor), cv::Point2f(corners[2].x * factor, corners[2].y * factor), intersection),
math::transform_marker_corner_points_to_DIN_A4_sheet_corners(cv::Point2f(corners[2].x * factor, corners[2].y * factor), cv::Point2f(corners[1].x * factor, corners[1].y * factor), intersection),
math::transform_marker_corner_points_to_DIN_A4_sheet_corners(cv::Point2f(corners[3].x * factor, corners[3].y * factor), cv::Point2f(corners[0].x * factor, corners[0].y * factor), intersection)
};
this->m_center = math::intersection(this->roi()[2], this->roi()[0], this->roi()[3], this->roi()[1]);
this->m_width = math::vector_norm<float, cv::Point2f>(this->roi()[1] - this->roi()[0]);
this->m_height = math::vector_norm<float, cv::Point2f>(this->roi()[3] - this->roi()[0]);
this->m_angle = (this->roi()[0].x > this->roi()[1].x) ? 360.0f - math::angle_degrees(this->roi()[3]- this->roi()[0], cv::Point2f(1, 0)) : math::angle_degrees(this->roi()[3] - this->roi()[0], cv::Point2f(1, 0));
}
break;
case TrackableTypes::TANGIBLE:
case TrackableTypes::HAND:
{
m_roi.clear();
for(auto p = corners.rbegin(); p != corners.rend(); ++p)
m_roi.push_back(cv::Point(p->x * factor, p->y * factor));
this->m_center = math::intersection(this->roi()[2], this->roi()[0], this->roi()[3], this->roi()[1]);
this->m_width = math::vector_norm<float, cv::Point2f>(this->roi()[1] - this->roi()[0]);
this->m_height = math::vector_norm<float, cv::Point2f>(this->roi()[3] - this->roi()[0]);
this->m_angle = -((this->roi()[0].x > this->roi()[1].x) ? 360.0f - math::angle_degrees(this->roi()[3]- this->roi()[0], cv::Point2f(1, 0)) : math::angle_degrees(this->roi()[3] - this->roi()[0], cv::Point2f(1, 0)));
}
break;
case TrackableTypes::TOUCH:
{
m_roi.clear();
for(auto p = corners.begin(); p != corners.end(); ++p)
m_roi.push_back(cv::Point(p->x * factor, p->y * factor));
}
break;
}
}
void const Trackable::set_center(cv::Point2f const & center)
{
m_center = center;
}
void const Trackable::set_height(float h)
{
m_height = h;
}
void const Trackable::set_width(float w)
{
m_width = w;
}
void const Trackable::set_angle(float a)
{
m_angle = a;
}
cv::Point2f const & Trackable::center() const
{
return m_center;
}
float const Trackable::width() const
{
return m_width;
}
float const Trackable::height() const
{
return m_height;
}
float const Trackable::angle() const
{
return m_angle;
}
std::string const & Trackable::name() const {
return m_name;
}
| true |
9504a32cc4a4257a7dddb3ea3fcd5138264584c1 | C++ | zjpgitte/project | /http服务器/Httpserver.hpp | UTF-8 | 920 | 2.75 | 3 | [] | no_license |
#pragma once
#include <iostream>
#include <pthread.h>
#include "Sock.hpp"
#include "Protocol.hpp"
class HttpServer{
private:
int _lsock; // listen sock
short _port;
public:
HttpServer(short port)
:_lsock(-1)
,_port(port)
{
}
void InitServer(){
_lsock = Sock::Socket();
Sock::SetSockOpt(_lsock);
Sock::Bind(_lsock, _port);
Sock::Listen(_lsock);
}
void Start(){
signal(SIGPIPE, SIG_IGN);
while(true) {
int sock = Sock::Accept(_lsock);
if (sock < 0) {
continue;
}
Log("Notice", "get a new link ...");
// 创建线程服务该套接字。epoll
pthread_t tid;
int* s = new int(sock);
if (pthread_create(&tid, nullptr, Entry::Routine, s) != 0) {
std::cout << "pthread_create error!" << std::endl;
}
}
}
};
| true |
87dc5edd35b302eb097d436e406dc6702207a1b8 | C++ | Wait021/Course-Reviwe | /面向对象程序设计/《C++程序设计基础教程》电子教案/《C++程序设计基础教程》第08章_电子教案/第八章习题课/Array2Link/ex08B03.cpp | GB18030 | 336 | 3.015625 | 3 | [] | no_license | // ex08B03.cpp ϰ8B(3)⣨㵹ã
#include <iostream>
#include "Array2Link.h"
using namespace std;
void Reverse(Node *&head)
{
if(head==NULL)
return;
Node *p, *rest;
rest=head->next;
head->next = NULL;
while(rest)
{
p = rest;
rest = rest->next;
p->next = head;
head = p;
}
}
| true |
e0dac4e461641f695328aaeb1b891c402e7c159a | C++ | HekpoMaH/Olimpiads | /e-maxx/Euler_function/uva11327.cpp | UTF-8 | 615 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int phi(int x){
int result=x;
for(int i=2;i*i<=x;i++){
if(x%i==0){
while(x%i==0)x/=i;
result-=result/i;
}
}
if(x>1)result-=result/x;
return result;
}
int gcd(int a,int b){
return b==0 ? a : gcd(b,a%b);
}
int main(){
long long k,br=1;
cin>>k;
k--;
if(k==0){
cout<<"0/1\n";
return 0;
}
while(k>phi(br)){
k-=phi(br);
br++;
}
int br2=0;
for(int i=1;i<=br;i++){
if(gcd(i,br)==1)br2++;
if(br2==k){
cout<<i<<"/"<<br<<"\n";
return 0;
}
}
}
| true |
782cc4fc15e46878d8c6d3ca62b6fad31a91b28b | C++ | pedropaulovc/UFSC | /ED/ListaInvertida/Indexador/ChaveSecundaria/IndexadorChaveSecundaria.h | UTF-8 | 1,020 | 2.59375 | 3 | [] | no_license | /**
TÍTULO: Implementação buscador textual usando listas invertidas
ALUNOS: Pedro Paulo Vezzá Campos - 09132033 e Felipe dos Santos Silveira - 09132014
MATÉRIA: INE5408
PRAZO: 12 de julho de 2010
PROPÓSITO:
Este programa é uma implementação do enunciado do projeto de implementação II, um buscador textual
utilizando arquivos invertidos.
SOBRE ESSE ARQUIVO:
Descrição da interface de um indexador de chave secundária, contendo métodos e atributos necessários para
a importação, uso e exportação de um índice de chaves secundárias.
*/
#ifndef INDEXADORCHAVESECUNDARIA_H_
#define INDEXADORCHAVESECUNDARIA_H_
#include "../Indexador.h"
#include "../../Portarias/Portaria.h"
class IndexadorChaveSecundaria: public Indexador {
public:
static void exportar(string pasta, string *palavrasChave, int numPalavras,
Portaria **portarias, int numPortarias);
static ListaEncadeada<Portaria>* importar(string pasta, string palavraChave, string arquivoDados);
};
#endif /* INDEXADORCHAVESECUNDARIA_H_ */
| true |
7a594b0d5f8cae6cbfa21a6208c9c849cf1bbf7f | C++ | harukishima/BookStore | /18120256/Menu.cpp | UTF-8 | 1,254 | 2.65625 | 3 | [] | no_license | #include "Menu.h"
Menu::Menu()
{
}
void Menu::guestMenu()
{
cout << "1. Dang nhap" << endl;
cout << "2. Tim sach" << endl;
cout << "3. Hien thi tat ca sach" << endl;
cout << "4. Dang ki" << endl;
cout << "0. Exit" << endl;
}
void Menu::userMenu()
{
cout << "1. Mua sach" << endl;
cout << "2. Cap nhat don hang" << endl;
cout << "3. Tim sach" << endl;
cout << "4. In danh sach hoa don" << endl;
cout << "5. Gui tin nhan" << endl;
cout << "6. Xem hop thu" << endl;
cout << "7. Dang xuat" << endl;
cout << "0. Thoat" << endl;
}
void Menu::adminMenu()
{
cout << "1. Gui tin nhan cho tat ca" << endl;
cout << "2. Gui tin nhan" << endl;
cout << "3. Xem hop thu den" << endl;
cout << "4. Xuat list sach" << endl;
cout << "5. Xoa sach" << endl;
cout << "6. Tim sach" << endl;
cout << "7. Them sach" << endl;
cout << "8. Xoa tat ca sach" << endl;
cout << "9. Dang xuat" << endl;
cout << "10. Blacklist" << endl;
cout << "0. Thoat" << endl;
}
void Menu::publisherMenu()
{
cout << "1. Xem sach" << endl;
cout << "2. Them sach" << endl;
cout << "3. Xoa sach" << endl;
cout << "4. Sua gia" << endl;
cout << "5. Gui tin nhan" << endl;
cout << "6. Xem hop thu" << endl;
cout << "7. Dang xuat" << endl;
cout << "0. Thoat" << endl;
}
| true |
b9db30da8a72e4e72e39c39b8045fbaf13a1d7de | C++ | AppStackCC/APS_EZTASK | /aps_eztask.cpp | UTF-8 | 2,225 | 2.671875 | 3 | [] | no_license | /*
aps_eztask.cpp AppStack easy task for Arduino
=======
WEBSITE
=======
https://www.facebook.com/appstack.in.th
http://www.appstack.in.th
<------------------------------------------------------------------->
@Author
- ultra_mcu@Piak Studiolo LEGO eiei
@Date
- 2015/01/07 , Version 0.2a
- 2015/01/07 , Version 0.2
- 2015/01/07 , Version 0.1c
- 2015/01/05 , Version 0.1
@Tool
- Arduino 1.0.6 on OSX
*/
#include "Arduino.h"
#include "aps_eztask.h"
APS_EZTASK::APS_EZTASK(uint8_t max)
{
if(max == 0)
{
max = 1;
}
this->task_max = max;
this->task_tail_cnt = 0;
this->task = (st_task *)malloc(sizeof(st_task) * max);
memset(this->task,0,sizeof(st_task) * max);
stop();
}
int APS_EZTASK::add(void (*fn)(void),int interval_ms,int enable)
{
uint8_t index = 0;
if(this->task_tail_cnt < this->task_max)
{
index = this->task_tail_cnt;
this->task[this->task_tail_cnt].fn = fn;
this->task[this->task_tail_cnt].time_interval_ms = interval_ms;
this->task[this->task_tail_cnt].enable = enable;
this->task_tail_cnt++;
return index;
}
return -1;
}
int APS_EZTASK::set_interval(int index,int interval_ms)
{
if(index < this->task_max && index < this->task_tail_cnt)
{
this->task[index].time_interval_ms = interval_ms;
return _TRUE_;
}
return _FALSE_;
}
int APS_EZTASK::get_interval(int index)
{
if(index < this->task_max && index < this->task_tail_cnt)
{
return this->task[index].time_interval_ms;
}
return -1;
}
void APS_EZTASK::run()
{
if(this->running_status == _TRUE_)
{
for(task_cnt_loop = 0; task_cnt_loop < task_tail_cnt; task_cnt_loop++)
{
if ((millis() - task[task_cnt_loop].time_cnt) > task[task_cnt_loop].time_interval_ms)
{
task[task_cnt_loop].time_cnt = millis();
if(task[task_cnt_loop].enable == _TASK_ENABLE_)
{
(*task[task_cnt_loop].fn)();
}
}
}
}
}
uint8_t APS_EZTASK::is_running()
{
return this->running_status;
}
void APS_EZTASK::start()
{
this->running_status = _TRUE_;
}
void APS_EZTASK::stop()
{
this->running_status = _FALSE_;
}
| true |
d4e6d7319ca394db243c57f86f036d1307a5f54b | C++ | TimE-CU/CSCI-3302 | /lab4_base/lab4_base.ino | UTF-8 | 7,967 | 2.671875 | 3 | [] | no_license | // UPDATED 10/10
#include <sparki.h>
#define ROBOT_SPEED 0.0278
#define MIN_CYCLE_TIME .100
#define AXLE_DIAMETER 0.0865
#define FWD 1
#define NONE 0
#define BCK -1
// Screen size
#define SCREEN_X_RES 128.
#define SCREEN_Y_RES 64.
// Map size
#define NUM_X_CELLS 12
#define NUM_Y_CELLS 6
// Start line is 18", 2" from bottom left corner
#define START_LINE_X .4572
#define START_LINE_Y .0508
#define SERVO_POS_DEG 45
int current_state = 1;
const int threshold = 800;
int line_left = 1000;
int line_center = 1000;
int line_right = 1000;
float distance = 0.;
unsigned long last_cycle_time = 0;
float pose_x = 0., pose_y = 0., pose_theta = 0., pose_servo = 0.;
int left_wheel_rotating = 0, right_wheel_rotating = 0;
// TODO: Define world_map multi-dimensional array
int disp_arr[NUM_X_CELLS][NUM_Y_CELLS];
// TODO: Figure out how many meters of space are in each grid cell
const float CELL_RESOLUTION_X = 0.60 / NUM_X_CELLS; // Line following map is ~60cm x ~42cm
const float CELL_RESOLUTION_Y = 0.42 / NUM_Y_CELLS; // Line following map is ~60cm x ~42cm
void setup() {
pose_x = START_LINE_X;
pose_y = START_LINE_Y;
pose_theta = 0.;
left_wheel_rotating = NONE;
right_wheel_rotating = NONE;
pose_servo = to_radians(SERVO_POS_DEG);
sparki.servo(-to_degrees(pose_servo)); // Servo axis points down instead of up, so we need to negate it to be consistent with the robot's rotation axis
// TODO: Initialize world_map
sparki.clearLCD();
displayMap();
delay(1000);
last_cycle_time = millis();
for(int i = 0; i<NUM_X_CELLS; i++){
for(int j = 0; j<NUM_Y_CELLS; j++){
disp_arr[i][j] = 0;
}
}
}
float to_radians(float deg) {
return deg * 3.14159 / 180.;
}
float to_degrees(float rad) {
return rad * 180. / 3.14159;
}
// Ultrasonic Sensor Readings -> Robot coordinates
void transform_us_to_robot_coords(float dist, float theta, float *rx, float *ry) {
// TODO
*rx = cos(theta) * dist;
*ry = sin(theta) * dist;
}
// Robot coordinates -> World frame coordinates
void transform_robot_to_world_coords(float x, float y, float *gx, float *gy) {
// TODO
*gx = x + pose_x;
*gy = y + pose_y;
}
bool transform_xy_to_grid_coords(float x, float y, int *i, int *j) {
// TODO: Set *i and *j to their corresponding grid coords
*i = float(x / .6 * (NUM_X_CELLS-1));
*j = float(y / .42 * (NUM_Y_CELLS-1));
// TODO: Return 0 if the X,Y coordinates were out of bounds
if(*i >= NUM_X_CELLS || *j >= NUM_Y_CELLS || *i < 0 || *j < 0)
{
return 0;
}
return 1;
}
// Turns grid coordinates into world coordinates (grid centers)
bool transform_grid_coords_to_xy(int i, int j, float *x, float *y) {
// TODO: Return 0 if the I,J coordinates were out of bounds
if(i >= NUM_X_CELLS || j >= NUM_Y_CELLS || i < 0 || j < 0)
{
return 0;
}
// TODO: Set *x and *y
*x = float(i) *.6 / float(NUM_X_CELLS-1);
*y = float(j) *.42 / float(NUM_Y_CELLS-1);
return 1;
}
bool transform_world_to_screen(float x, float y, float *sx, float *sy)
{
*sx = (x / 0.60) * SCREEN_X_RES;
*sy = (y / 0.42) * SCREEN_Y_RES;
if(*sx < 0 || *sx >= SCREEN_X_RES || *sy < 0 || *sy >= SCREEN_Y_RES)
{
return 0;
}
return 1;
}
void readSensors() {
line_left = sparki.lineLeft();
line_right = sparki.lineRight();
line_center = sparki.lineCenter();
distance = float(sparki.ping()) / 100.;
}
void moveRight() {
left_wheel_rotating = FWD;
right_wheel_rotating = BCK;
sparki.moveRight();
}
void moveLeft() {
left_wheel_rotating = BCK;
right_wheel_rotating = FWD;
sparki.moveLeft();
}
void moveForward() {
left_wheel_rotating = FWD;
right_wheel_rotating = FWD;
sparki.moveForward();
}
void moveBackward() {
left_wheel_rotating = BCK;
right_wheel_rotating = BCK;
sparki.moveBackward();
}
void moveStop() {
left_wheel_rotating = NONE;
right_wheel_rotating = NONE;
sparki.moveStop();
}
void updateOdometry(float cycle_time) {
pose_x += cos(pose_theta) * cycle_time * ROBOT_SPEED * (left_wheel_rotating + right_wheel_rotating)/2.;
pose_y += sin(pose_theta) * cycle_time * ROBOT_SPEED * (left_wheel_rotating + right_wheel_rotating)/2.;
pose_theta += (right_wheel_rotating - left_wheel_rotating) * cycle_time * ROBOT_SPEED / AXLE_DIAMETER;
}
void displayMap() {
// TODO: Measure how many pixels will be taken by each grid cell
const int PIXELS_PER_X_CELL = 0;
const int PIXELS_PER_Y_CELL = 0;
int cur_cell_x=-1, cur_cell_y=-1;
// TODO: Make sure that if the robot is "off-grid", e.g., at a negative grid position or somewhere outside your grid's max x or y position that you don't try to plot the robot's position!
float sx, sy;
if(transform_world_to_screen(pose_x, pose_y, &sx, &sy))
{
// sparki.print(sx);
sparki.drawCircleFilled(sx, sy, 2);
}
// TODO: Draw Map
for(int i = 0; i<NUM_X_CELLS; i++){
for(int j = 0; j<NUM_Y_CELLS; j++){
transform_grid_coords_to_xy(i, j, &sx, &sy);
transform_world_to_screen(sx, sy, &sx, &sy);
if(disp_arr[i][j] == 1){
sparki.drawCircleFilled(sx, sy, 5);
}
else{
sparki.drawCircle(sx, sy, 5);
}
}
}
}
void serialPrintOdometry() {
Serial.print("\n\n\nPose: ");
Serial.print("\nX: ");
Serial.print(pose_x);
Serial.print("\nY: ");
Serial.print(pose_y);
Serial.print("\nT: ");
Serial.print(pose_theta * 180. / 3.14159);
Serial.print("\n");
}
void displayOdometry() {
sparki.println("Pose: ");
sparki.print("X: ");
sparki.println(pose_x);
sparki.print("Y: ");
sparki.println(pose_y);
sparki.print("T: ");
sparki.println(pose_theta * 180. / 3.14159);
}
int get_cell_index(int x, int y)
{
return (x * NUM_X_CELLS) + y;
}
void get_index_pos(int idx, int* x, int* y)
{
*x = idx / NUM_X_CELLS;
*y = idx % NUM_X_CELLS;
}
// Cost to move from idx1 to idx2
int get_cost(int idx1, int idx2)
{
int x1, y1, x2, y2;
get_index_pos(idx1, &x1, &y1);
get_index_pos(idx2, &x2, &y2);
if(disp_arr[x2][y2])
{
return 999;
}
int dist = abs(x1-x2) + abs(y1+y2);
if(dist != 1)
{
return 999;
}
return 1;
}
void loop() {
unsigned long begin_time = millis();
unsigned long begin_movement_time = 0;
unsigned long end_time = 0;
unsigned long delay_time = 0;
float elapsed_time = 0.;
bool found_object = 0;
readSensors();
sparki.clearLCD();
last_cycle_time = (millis() - last_cycle_time);
elapsed_time = last_cycle_time / 1000.;
updateOdometry(elapsed_time);
last_cycle_time = millis(); // Start timer for last motor command to determine cycle time
serialPrintOdometry();
// Mapping Code
sparki.servo(-to_degrees(pose_servo));
// TODO: Check if sensors found an object
float cm_distance = sparki.ping();
float sx, sy;
int px, py;
// TODO: Adjust Map to accommodate new object
if(cm_distance <= 30 && cm_distance != -1) {
transform_us_to_robot_coords(cm_distance/100, pose_theta+to_radians(SERVO_POS_DEG), &sx, &sy);
transform_robot_to_world_coords(sx, sy, &sx, &sy);
transform_xy_to_grid_coords(sx, sy, &px, &py);
disp_arr[px][py] = 1;
}
// displayOdometry();
displayMap();
if (line_center < threshold) {
moveForward();
} else if (line_left < threshold) {
moveLeft();
} else if (line_right < threshold) {
moveRight();
} else {
moveStop();
}
// Check for start line, use as loop closure
// NOTE: Assumes robot is moving counter-clockwise around the map (by setting pose_theta = 0)!
// If your robot is moving clockwise, set pose_theta to pi radians (i.e., pointing left).
if (line_left < threshold && line_right < threshold && line_center < threshold) {
pose_x = START_LINE_X;
pose_y = START_LINE_Y;
pose_theta = 0.;
}
sparki.updateLCD();
end_time = millis();
delay_time = end_time - begin_time;
if (delay_time < 1000*MIN_CYCLE_TIME)
delay(1000*MIN_CYCLE_TIME - delay_time); // make sure each loop takes at least MIN_CYCLE_TIME ms
else
delay(10);
}
| true |
af71555dd8c9336f1595accb8a994280681fb7a1 | C++ | ranea/Bachelor-Projects | /ProcesamientoImagenes/contraste.cpp | UTF-8 | 2,948 | 3.5 | 4 | [
"MIT"
] | permissive | /***************************************************************************
* Fichero: contraste.cpp
*
* Formato: contraste <fichOri> <fichDest> <min> <max>
* <fichOri> nombre del fichero que contiene la imagen original
* <fichDest> nombre del fichero que contiene la imagen que se pretende llegar
* <min> mínimo umbral de contraste
* <max> máximo umbral de contraste
*
*
**************************************************************************/
#include <iostream>
#include <cstdlib>
#include "imagen.h"
#include "utilidades.h"
using namespace std;
/*
* Asignamos el primer píxel como el valor mínimo de gris.
* Recorremos la imagen al completo y determinamos el mínimo
* valor de gris de la imagen
*/
template <class T>
int min_imag (const Imagen<T> &imag)
{
int min = imag(0,0);
for (int i = 0; i < imag.num_filas(); i++)
for (int j = 0; j < imag.num_columnas(); j++)
if (imag(i,j) < min)
min = imag(i,j);
return min;
}
/*
* Asignamos el primer píxel como el valor máximo de gris.
* Recorremos la imagen al completo y determinamos el máximo
* valor de gris de la imagen
*/
template <class T>
int max_imag (const Imagen<T> &imag)
{
int max = imag(0,0);
for (int i = 0; i < imag.num_filas(); i++)
for (int j = 0; j < imag.num_columnas(); j++)
if (imag(i,j) > max)
max = imag(i,j);
return max;
}
/*
* Aplicamos una transformación lineal (redondeada al entero más próximo)
* sobre todos los píxeles de la imagen para conseguir una imagen con más
* contraste (blancos más blancos y negros más negros)
*/
Imagen<unsigned char> contraste(const Imagen<unsigned char> &orig,int min, int max)
{
Imagen<unsigned char> imag(orig);
int a = min_imag(imag);
int b = max_imag(imag);
double constante = (max-min)/(b-a);
for (int i = 0; i < imag.num_filas(); i++)
for (int j = 0; j < imag.num_columnas(); j++)
imag(i,j) = (int) min + constante * (imag(i,j) - a) + 0.5;
return imag;
}
int main(int argc, char const *argv[])
{
int min, max;
const char *origen, *destino;
if (argc != 5){
cerr << "Error: Numero incorrecto de parametros.\n";
cerr << "Uso: contraste <fichOri> <fichDest> <min> <max>\n";
exit (1);
}
/* Leemos los argumentos del main */
origen = argv[1];
destino = argv[2];
min = atoi(argv[3]);
max = atoi(argv[4]);
/* Si min > max, debemos intercambiarlos */
if (min > max)
{
int aux;
aux = min;
min = max;
max = aux;
}
/* Mostramos los ficheros origen y destino */
cout << endl;
cout << "Fichero origen: " << origen << endl;
cout << "Fichero resultado: " << destino << endl << endl;
/* Trabajamos la imagen con las funciones auxiliares */
Imagen<unsigned char> img(leeImagen(origen));
escribeImagen(destino,contraste(img,min,max));
return 0;
} | true |
673934e75d563eebf487a6febdb9721991fe22be | C++ | SimKyuSung/Algorithm | /BeakJoon C++ Algorithm/15639.Rick.cpp | UTF-8 | 459 | 3.34375 | 3 | [] | no_license | /// 15639.Rick
#include <iostream>
#include <string>
#define endl '\n'
using namespace std;
const int n = 6;
string rick[] = { "Give you up", "Let you down", "Run around and desert you", "Make you cry", "Say goodbye", "Tell a lie and hurt you" };
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
string input;
getline(cin, input);
for (auto s : rick) {
if (s == input) {
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
} | true |
22b8378510bc60e00a0642287d46d52fa380a112 | C++ | cattigers/SAINT2 | /src/main/config.h | UTF-8 | 8,410 | 2.9375 | 3 | [] | no_license | #ifndef CONFIG_H_INCLUDED
#define CONFIG_H_INCLUDED
#include <iostream>
#include <string>
#include "param_list.h"
/// @breief Program version number.
#define SAINT2_VERSION "1.1"
// forward declarations
class Runner;
class Sequence;
extern bool reverseSaint;
/// @brief Class for managing program configuration information
/// (from a configuration file, the command line or a mixture of both).
///
/// The general format of a configuration file is:
/// <pre>
/// [section]
/// name = value
/// ...
/// # comment ...
/// </pre>
/// Long lines may be continued on the next line by ending them with "+".
///
/// Only one Config object can exist (this is enforced using the
/// m_instantiated variable).
///
/// Example:
///
/// <pre>
/// int main(int argc, const char **argv)
/// {
/// Config(argc, argv);
/// Runner runner(config);
/// ...
/// }
/// </pre>
class Config
{
public:
/// @brief Constructor.
///
/// @param argc Command line argument count (argument to main()).
/// @param argv Command line arguments (argument to main()).
Config(
int argc, // in - number of command line arguments
const char *argv[] // in - command line arguments
);
/// @brief Destructor.
~Config();
/// @brief Get the number of runs to perform ("-n" command line option).
/// @return Number of runs.
int num_runs() const
{ return m_num_runs; }
/// @brief Get the random number seed to use.
/// @return The seed (if not specified on the command line with "-s",
/// the seed is based on the current time (note: resolution is seconds).
long random_seed() const
{ return m_rnd_seed; }
/// @brief Get the name of the output file.
/// @return The filename: if no "-o" option was specified on the
/// command line, returns an empty string; otherwise, if just one
/// run is being performed, returns the "-o" argument; otherwise
/// returns the "-o" argument with the run number appended.
const std::string outfilename(int run_number) const;
/// @brief Initialise a Runner object with the appropriate type of
/// scorer, strategy, etc.
///
/// @param r [out] Runner object.
void init_runner(Runner *r) const;
/// @brief Initialise an amino acid (or codon) sequence
/// with the configuration values (ie. either from a FASTA file
/// or a literal sequence in the configuration file).
///
/// @param s [out] Amino acid sequence.
void create_sequence(Sequence *s) const;
/// @brief Print parameter values in configuration file format.
void print_params() const;
/// @brief Get the PDB filename specified on the command line ("--" option).
/// @return Filename.
const std::string &pdb_filename() const
{ return m_pdb_filename; }
/// @brief Check if the "-t" flag was included on the command line
/// @return True if flag was included.
bool show_torsion_angles() const
{ return m_show_torsion_angles; }
/// @brief Check if the "-b" flag was included on the command line
/// @return True if flag was included.
bool backbone_only() const
{ return m_backbone_only; }
/// @brief Check if the "-v" flag was included on the command line
/// @return True if flag was included.
bool verbose() const
{ return m_verbose; }
/// @brief Get the chain id specified on the command line (following
/// the PDB filename).
/// @return Chain id (' ' if not specified on the command line).
char pdb_chain() const
{ return m_pdb_chain; }
/// @brief Get the executable name (argv[0] from the command line).
/// @return Executable name.
static const std::string &cmd()
{ return m_cmd; }
/// @brief Print an error message about a missing configuration file
/// parameter and exit.
static void missing_parameter(
const char *section, // config file section
const char *type, // "type" value (may be empty / NULL)
const char *param_name // parameter name
);
private:
/// @brief Sections of the configuration file
/// (each section has a corresponding class).
enum Section
{
S_Sequence, S_Runner, S_Extend, S_Scoring, S_Strategy, S_Movement,
Num_Sections,
S_None
};
private:
// disallow copy and assignment by declaring private versions.
Config(const Config&);
Config& operator = (const Config&);
// @brief Print usage message
void show_usage();
/// @brief Parse command line arguments.
///
/// @param argc Command line argument count.
/// @param argv Command line arguments.
void parse(int argc, const char *argv[]);
/// @brief Parse a single command line option.
///
/// @param arg [in,out] Index of current argument in \a argv.
/// @param argc Command line argument count.
/// @param argv Command line arguments.
void parse_option(int *arg, int argc, const char *argv[]);
/// @brief Check if the end of the argument list has been reached
/// prematurely (after the specified command line option).
///
/// @param argc Command line argument count.
/// @param argv Command line arguments.
/// @param option Current option (without "-", eg. "o").
void check_end_of_args(int arg, int argc, const std::string &option);
/// @brief Check if a command line argument is a (unique) abbreviation
/// of a configuration file section name; if so, parse the
/// parameters that follow.
///
/// @param arg [in,out] Index of current argument in \a argv.
/// @param argc Command line argument count.
/// @param argv Command line arguments.
bool parse_section_args(int *arg, int argc, const char *argv[]);
/// @brief Parse a list of configuration paramaters from the command line
/// (ie. arguments containing "=").
///
/// @param sec Current section.
/// @param arg [in,out] Index of current argument in \a argv.
/// @param argc Command line argument count.
/// @param argv Command line arguments.
void parse_param_args(Section sec, int *arg, int argc,
const char *argv[]);
/// @brief Read a configuration file (the filename was specified
/// on the command line, and is stored in m_config_filename).
void read_config_file();
/// @brief Convert a section name to the corresponding enum
/// (\a str should point to the character after the initial '[').
/// Exits with a message on error.
///
/// @param str Source string.
/// @return The section.
Section parse_section_name(const char *str);
/// @brief Parse a parameter inside a config file
/// (leading white space is assumed to have already been skipped,
/// and the line is assumed not to be a comment).
/// Exits with a message on error.
///
/// @param sec Current section in config file.
/// @param name [in,out] (Last) parameter name; if non-empty, the last
/// line may be continued with the character "+".
/// @param str Current line.
void parse_config_param(Section sec, std::string &name,
const char *str);
/// @brief Check if there were any incompatible parameter values
/// in different sections of the configuration file.
void verify_interdependent_params();
/// @brief Transform all escape sequences in a string (such as \")
/// to single characters.
///
/// @param str [in,out] String to transform.
void transform_escape_sequences(std::string &str);
/// @brief Print an error message about a syntax error on the current
/// line of the config file and exit.
void file_syntax_error();
/// @brief Output a template configuration file.
void print_config_template();
private:
/// Line continuation character (used at the start of continued lines).
static const char c_continue_char;
/// Default number of runs to perform.
static const int c_default_runs;
/// Parameters for each section of the configuration file.
Param_List m_param[Num_Sections];
/// Name of each section.
std::string m_section_name[Num_Sections];
/// (Used for making sure only one object of this class ever exists).
static bool m_instantiated;
/// Command name (argv[0] from command line).
static std::string m_cmd;
/// Name of configuration file (if any).
std::string m_config_filename;
/// Current line number in config file.
int m_config_line_num;
/// Number of runs to perform.
int m_num_runs;
/// Output file (if any).
std::string m_outfile;
/// Random number seed.
long m_rnd_seed;
/// PDB file name (after "--" on command line).
std::string m_pdb_filename;
/// "-t" flag.
bool m_show_torsion_angles;
/// "-b" flag.
bool m_backbone_only;
/// "-v" flag.
bool m_verbose;
/// Chain id following PDF filename (if any).
char m_pdb_chain;
};
#endif // CONFIG_H_INCLUDED
| true |
09fbb6b9cdf69203e2a4f4e4756a89c6141580fe | C++ | j-wreford/jw-paint-tool | /jw-paint-tool/core/ui/component/TextField.cpp | UTF-8 | 2,170 | 3.03125 | 3 | [] | no_license | #include "TextField.h"
paint_tool::TextField::TextField(
const std::string &id,
const SIZE &size,
const std::wstring &placeholder,
const std::string &font_attr_set_id
) : ValueComponent<std::wstring>(id, L""),
placeholder(placeholder) {
registerObserver(this); // observes itself so that it may update the label whenever the value changes
setMinimumSize(size);
setLayoutStrategy(LAYOUT_HORIZONTAL);
setFillBackground(true);
/* create the label shown when there is a value */
p_component_t real_label = std::make_unique<StaticLabel>(
id + "_text_field_real_label",
placeholder, /* initalise the real label with the placeholder text, so that they can be positioned identically */
font_attr_set_id
);
real_label->showIf([this]() {
return getValue().length() > 0;
});
real_label->setAlignment(ALIGN_MIDDLE);
/* create the placeholder label */
p_component_t placeholder_label = std::make_unique<StaticLabel>(
id + "_text_field_placeholder_label",
placeholder,
font_attr_set_id
);
placeholder_label->showIf([this]() {
return getValue().length() == 0;
});
placeholder_label->setAlignment(ALIGN_MIDDLE);
/* add the components */
addHorizontalSpace(10);
addComponent(real_label);
addComponent(placeholder_label);
addHorizontalSpace(10);
}
paint_tool::TextField::~TextField() {
//
}
void paint_tool::TextField::onKeyDown(UINT key, UINT flags) {
std::wstring value = getValue();
/* if the backspace key was pressed, knock off the last character */
if (key == 0x8 && value.length() > 0) {
value.pop_back();
setValue(value);
}
if (key == 0x20)
setValue(getValue() += L" ");
}
void paint_tool::TextField::onChar(UINT key, UINT flags) {
/* bail if this isn't a printable character */
if (!(key >= 0x21 && key <= 0x7d))
return;
char ckey = (char)key;
wchar_t *wckey = new wchar_t[1];
MultiByteToWideChar(CP_UTF8, 0, &ckey, sizeof(char), wckey, 1);
setValue(getValue() += wckey[0]);
}
void paint_tool::TextField::update(ValueComponent<std::wstring> *subject) {
if (StaticLabel *label = dynamic_cast<StaticLabel *>(getComponent(getId() + "_text_field_real_label")))
label->setText(getValue());
} | true |
cd88349f9dad87dd06a543781c6866f8a5effbc6 | C++ | khinbaptista/OpenGL | /TemplateOpenGL/Font2D.h | UTF-8 | 502 | 2.578125 | 3 | [] | no_license | #pragma once
#include <glm/glm.hpp>
#include <SDL.h>
#include "Sprite.h"
class Font2D
{
private:
glm::vec2 dimensions;
int charactersPerLine;
int lineCount;
Sprite *sprite;
public:
Font2D(void);
Font2D(Sprite *sprite, int charactersPerLine, int lineCount, int characterWidth = -1, int characterHeight = -1);
~Font2D();
void Write(SDL_Renderer *renderer, glm::vec2 position, const char* text, int layer = 2);
SDL_Rect CharacterBound(char character);
int MeasureString(const char* text);
}; | true |
2b23b1aed89653edc1638082b03fd482d55ec4f2 | C++ | NeilZhy/Review | /平衡二叉树/AVL树/AVLTree.h | GB18030 | 4,917 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
template<class K,class V>
struct AVLTreeNode
{
AVLTreeNode(K key = 0,V value = 0)
:_left(NULL)
, _right(NULL)
, _parent(NULL)
, _bf(0)
, _key(key)
, _value(value)
{
}
AVLTreeNode<K, V>* _left;
AVLTreeNode<K, V>* _right;
AVLTreeNode<K, V>* _parent;
int _bf;
K _key;
V _value;
};
template<class K,class V>
class AVLTree
{
typedef AVLTreeNode<K, V> Node;
public:
AVLTree()
:_root(NULL)
{}
bool Insert(K key, V value)
{
if (!_root)
{
_root = new Node(key,value);
return true;
}
//λò
Node* cur = _root;
Node* prev = cur;
while (cur)
{
if (key < cur->_key)
{
prev = cur;
cur = cur->_left;
}
else if (key>cur->_key)
{
prev = cur;
cur = cur->_right;
}
else
{
return false;
}
}
cur = new Node(key, value);
if (key < prev->_key)
{
prev->_left = cur;
cur->_parent = prev;
}
else
{
prev->_right = cur;
cur->_parent = prev;
}
//ƽӲת
Node* parent = cur->_parent;
while (parent) //˼һжǷ
{
if (parent->_left == cur)
{
--(parent->_bf);
if (parent->_bf == -2)
{
if (cur->_bf == -1)
{
Rxun(parent);
}
if (cur->_bf == 1)
{
LRxun(parent);
}
break;
}
if (parent->_bf == 0)
{
break;
}
}
else
{
++(parent->_bf);
if (parent->_bf == 2)
{
if (cur->_bf == 1)
{
Lxun(parent);
}
if (cur->_bf == -1)
{
RLxun(parent);
}
break;
}
if (parent->_bf == 0)
{
break;
}
}
cur = parent;
parent = parent->_parent;
}
return true;
}
bool IsAVL()
{
int num = 0;
return _IsAVL(_root,num);
}
private:
bool _IsAVL(Node* root, int& hight) //ݸ߶ж,ߣÿĸ߶ȣ
//Ǻ˼,ʱ临ӶO(n)
{
if (root == NULL)
{
return true;
}
int lefthight = hight;
if (_IsAVL(root->_left, lefthight) == false)
{
return false;
}
int righthight = hight;
if(_IsAVL(root->_right, righthight) == false)
{
return false;
}
if (abs(lefthight - righthight) < 2)
{
lefthight > righthight ? (hight = lefthight + 1) : (hight = righthight + 1);
return true;
}
return false;
}
void Rxun(Node* parent)
{
Node* pprent = parent->_parent;
Node* left = parent->_left;
Node* leftright = left->_right;
parent->_left = leftright;
if (leftright)
{
leftright->_parent = parent;
}
left->_right = parent;
parent->_parent = left;
if (pprent)
{
left->_parent = pprent;
if (pprent->_left == parent)
{
pprent->_left = left;
}
else
{
pprent->_right = left;
}
}
else
{
left->_parent = NULL;
_root = left;
}
parent->_bf = 0;
left->_bf = 0;
}
void RLxun(Node* parent)
{
Node* p = parent;
Node* sub = p->_right;
int num = sub->_left->_bf;
Rxun(parent->_right);
Lxun(parent);
if (num == 1)
{
p->_bf = -1;
}
else
{
sub->_bf = 1;
}
}
void Lxun(Node* parent)
{
Node* pprent = parent->_parent;
Node* right = parent->_right;
Node* rightleft = right->_left;
parent->_right = rightleft;
if (rightleft)
{
rightleft->_parent = parent;
}
right->_left = parent;
parent->_parent = right;
if (pprent)
{
right->_parent = pprent;
if (pprent->_right == parent)
{
pprent->_right = right;
}
else
{
pprent->_left = right;
}
}
else
{
right->_parent = NULL;
_root = right;
}
parent->_bf = 0;
right->_bf = 0;
}
void LRxun(Node* parent)
{
Node* p = parent;
Node* sub = p->_left;
int num = sub->_right->_bf;
Lxun(parent->_left);
Rxun(parent);
if (num == 1)
{
p->_bf = -1;
}
else
{
sub->_bf = 1;
}
}
private:
Node* _root;
};
void test()
{
AVLTree<int, int> tree;
tree.Insert(16,1);
tree.Insert(3, 1);
tree.Insert(7, 1);
tree.Insert(11, 1);
tree.Insert(9, 1);
tree.Insert(26, 1);
tree.Insert(18, 1);
tree.Insert(14, 1);
tree.Insert(15, 1);
cout << tree.IsAVL()<<endl;
AVLTree<int, int> tre;
tre.Insert(4, 1);
tre.Insert(2, 1);
tre.Insert(7, 1);
tre.Insert(1, 1);
tre.Insert(3, 1);
tre.Insert(6, 1);
tre.Insert(15, 1);
tre.Insert(8, 1);
tre.Insert(16, 1);
tre.Insert(14, 1);
tre.Insert(5, 1);
cout << tre.IsAVL() << endl;
AVLTree<int, int> tre1;
tre1.Insert(7, 1);
tre1.Insert(6, 1);
tre1.Insert(15, 1);
tre1.Insert(5, 1);
tre1.Insert(14, 1);
tre1.Insert(16, 1);
tre1.Insert(4, 1);
cout << tre1.IsAVL() << endl;
AVLTree<int, int> t;
t.Insert(3, 1);
t.Insert(1, 1);
t.Insert(6, 1);
t.Insert(0, 1);
t.Insert(2, 1);
t.Insert(5, 1);
t.Insert(15, 1);
t.Insert(7, 1);
t.Insert(16, 1);
t.Insert(14, 1);
t.Insert(-1, 1);
t.Insert(4, 1);
cout << t.IsAVL() << endl;
} | true |
5d23aabe895cbb808a8cace539874b395b4a600c | C++ | MimusTriurus/QtVideoStreamer | /lib/static/FpsChecker/FpsChecker.cpp | UTF-8 | 942 | 2.5625 | 3 | [] | no_license | #include "FpsChecker.h"
int64 FpsChecker::getTimeTicks( ) const {
return _sumTime;
}
double FpsChecker::getTimeMicro( ) const {
return getTimeMilli( ) * 1e3;
}
double FpsChecker::getTimeMilli( ) const {
return getTimeSec( ) * 1e3;
}
double FpsChecker::getTimeSec( ) const {
return ( double )getTimeTicks( )/cv::getTickFrequency( );
}
int64 FpsChecker::getCounter( ) const {
return _counter;
}
void FpsChecker::reset( ) {
_startTime = 0;
_sumTime = 0;
_counter = 0;
}
FpsChecker::FpsChecker( ) :
_counter{ 0 },
_sumTime{ 0 },
_startTime{ 0 }
{
}
void FpsChecker::start( ) {
_startTime = cv::getTickCount( );
}
void FpsChecker::stop( ) {
int64 time = cv::getTickCount( );
if ( _startTime == 0 )
return;
++_counter;
_sumTime += ( time - _startTime );
_startTime = 0;
}
int FpsChecker::fps( ) const {
return cvRound( getCounter( ) / getTimeSec( ) );
}
| true |
4f3a38ecd8f2e8a642a87e9ad8644beb62cbb995 | C++ | mingpuwu/Daily-development | /alg/trie/trie.cpp | UTF-8 | 2,304 | 3.671875 | 4 | [] | no_license | /*
前缀树,字典树
*/
#include <string>
#include <iostream>
#include <vector>
#include <memory.h>
#define MaxNum 26
using namespace std;
struct Node
{
int pass = 0;
int end = 0;
char c = 0;
Node *next[MaxNum] = {nullptr};
Node(int p, int e,char c)
{
this->pass = p;
this->end = e;
this->c = c;
}
};
int SearchString(Node *root, string word)
{
if (root == nullptr)
return 0;
Node *node = root;
for (auto i : word)
{
int index = i - 'a';
node = node->next[index];
if (node == nullptr)
return 0;
}
return node->end;
}
//指针操作的时候务必注意,不能断链
void InsertWord(Node *root, string word)
{
if (root == nullptr)
return;
if (SearchString(root, word) > 0)
return;
Node *node = root;
node->pass++;
for (auto i : word)
{
int index = i - 'a';
if (node->next[index] == nullptr)
{
node->next[index] = new Node(0, 0, i);
}
node = node->next[index];
node->pass++;
}
node->end++;
}
int PrefixWord(Node *root, string word)
{
if (root == nullptr)
return 0;
Node *node = root;
for (auto i : word)
{
int index = i - 'a';
node = node->next[index];
if (node == nullptr)
return 0;
}
return node->pass;
}
//使用递归方式释放底下所有节点
void deleteNode(Node* node)
{
if(node == nullptr)
return;
for(int i = 0; i < MaxNum; i++)
{
deleteNode(node->next[i]);
}
std::cout<<"delete node :"<<node->c<<std::endl;
delete node;
}
int DeleteWord(Node *root, string word)
{
if (SearchString(root, word) != 0)
{
Node *node = root;
node->pass--;
for (auto i : word)
{
int index = i - 'a';
node = node->next[index];
if (--node->pass == 0)
{
//底下所有的节点都需要释放掉
deleteNode(node);
}
}
}
}
int main()
{
Node* root = new Node(0,0,0);
InsertWord(root, "renxinrui");
InsertWord(root,"wumingpu");
//InsertWord(root,"wumingpi");
DeleteWord(root,"wumingpu");
} | true |
4cfe5dbb6145e5cdb30546ee9f63b0cf6124d739 | C++ | hello-choulvlv/hello-world | /OpenGL/source/法线贴图/OpenGL.cpp | GB18030 | 4,279 | 2.515625 | 3 | [] | no_license | //
#include <GL/glew.h>
#include<engine/GLContext.h>
#include<engine/GLProgram.h>
#include<engine/TGAImage.h>
#include<engine/Geometry.h>
#include<engine/Shape.h>
#include<engine/Sprite.h>
#include<engine/GLShadowMap.h>
//Common Data Struct
struct UserData
{
GLProgram *object;
GLuint baseMapId;
GLuint normalMapId;
GLTexture *baseTexture;
GLTexture *normalTexture;
//
GLuint u_baseMapLoc;
GLuint u_normalMapLoc;
GLuint u_normalMatrixLoc;
GLuint u_mvpMatrixLoc;
GLuint u_lightVectorLoc;//ߵķ
//ߵķ
GLVector3 lightVector;
//תĽǶ
float angleArc;
Matrix mvpMatrix;
Matrix3 normalMatrix;
//
GLSphere *vSphere;
};
//
void Init(GLContext *_context)
{
UserData *_user = new UserData();
_context->userObject = _user;
//
_user->object = GLProgram::createWithFile("shader/normal/normal.vsh", "shader/normal/normal.fsh");
_user->u_mvpMatrixLoc = _user->object->getUniformLocation("u_mvpMatrix");
_user->u_baseMapLoc = _user->object->getUniformLocation("u_baseMap");
_user->u_normalMapLoc = _user->object->getUniformLocation("u_normalMap");
_user->u_lightVectorLoc = _user->object->getUniformLocation("u_lightVector");
_user->u_normalMatrixLoc = _user->object->getUniformLocation("u_normalMatrix");
//TGAImage
// TGAImage _baseMap("tga/normal/IceMoon.tga");
// _user->baseMapId = _baseMap.genTextureMap();
_user->baseMapId = 0;
_user->baseTexture = GLTexture::createWithFile("tga/normal/IceMoon.tga");
_user->baseTexture->genMipmap();
//Normal Texture
// TGAImage _normalMap("tga/normal/IceMoonBump.tga");
// _user->normalMapId = _normalMap.genTextureMap();
_user->normalMapId = 0;
_user->normalTexture = GLTexture::createWithFile("tga/normal/IceMoonBump.tga");
_user->normalTexture->genMipmap();
//Sphere
_user->vSphere = GLSphere::createWithSlice(128, 0.6f);
//
_user->lightVector = normalize(&GLVector3(1.0f,1.0f,1.0f));
//
_user->angleArc = 0.0f;
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
}
//
void Update(GLContext *_context, float _deltaTime)
{
UserData *_user = (UserData *)_context->userObject;
_user->angleArc += _deltaTime*12.0f;
if (_user->angleArc >= 360.0f)
_user->angleArc -= 360.0f;
_user->mvpMatrix.identity();
_user->mvpMatrix.rotate(_user->angleArc,0.0f,1.0f,0.0f);
_user->normalMatrix = _user->mvpMatrix.normalMatrix();
}
void Draw(GLContext *_context)
{
UserData *_user = (UserData *)_context->userObject;
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
_user->object->enableObject();
_user->vSphere->bindVertexObject(0);
_user->vSphere->bindTexCoordObject(1);
_user->vSphere->bindNormalObject(2);
_user->vSphere->bindTangentObject(3);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,_user->baseTexture->name() );// _user->baseMapId);
glUniform1i(_user->u_baseMapLoc,0);
//
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, _user->normalTexture->name());// _user->normalMapId);
glUniform1i(_user->u_normalMapLoc,1);
//Matrix
glUniformMatrix4fv(_user->u_mvpMatrixLoc, 1,GL_FALSE,_user->mvpMatrix.pointer());
//normal matrix
glUniformMatrix3fv(_user->u_normalMatrixLoc, 1, GL_FALSE, _user->normalMatrix.pointer());
//
glUniform3fv(_user->u_lightVectorLoc, 1, &_user->lightVector.x);
_user->vSphere->drawShape();
}
void ShutDown(GLContext *_context)
{
UserData *_user = (UserData *)_context->userObject;
_user->object->release();
_user->object = NULL;
glDeleteTextures(1, &_user->baseMapId);
_user->baseMapId = 0;
glDeleteTextures(1, &_user->normalMapId);
_user->normalMapId = 0;
_user->normalTexture->release();
_user->normalTexture = NULL;
_user->baseTexture->release();
_user->baseTexture = NULL;
_user->vSphere->release();
_user->vSphere = NULL;
}
///////////////////////////don not modify below function////////////////////////////////////
| true |
01e343566bac213845f76f7939ac0f6f38e0f8a6 | C++ | Loqaritm/catsay | /catsay.cpp | UTF-8 | 4,236 | 3.0625 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <sstream>
#include <ctime>
#include <string>
#include <fstream>
std::string eightBall(){
std::string answers[] = {"maybe", "yes", "no", "could be", "go for it", "you bet", "dont even", "possible", "420"};
int lenOfAnswers = sizeof(answers)/sizeof(answers[0]);
int result = std::rand() % lenOfAnswers;
return answers[result];
}
std::string magicEightBall(){
std::string answers[] = {"yes", "definitely", "true", "ofcourse", "if you're saying this about ramon then ofcourse", "420"};
int lenOfAnswers = sizeof(answers) / sizeof(answers[0]);
int result = std::rand() % lenOfAnswers;
return answers[result];
}
std::string joke(){
std::ifstream myfile("catsay_jokes.csv");
if(!myfile){
return "COULDN'T LOAD FILE, SO NO JOKES FOR YOU";
}
int number_of_lines = 0;
std::string line = "";
while (std::getline(myfile, line))
++number_of_lines;
int result = std::rand() % number_of_lines;
myfile.clear();
myfile.seekg(0, myfile.beg);
number_of_lines = 0;
while(std::getline(myfile, line)){
if(number_of_lines == result){
break;
}
++number_of_lines;
}
std::stringstream ss;
ss.str("");
bool flag = false;
for (char i : line){
if(flag) ss << i;
if(i=='\r') return "STOP USING WINDOWS FORMATED TEXT FILES";
if(i == ',') flag = true;
}
return ss.str().c_str();
}
int main(int argc, char *argv[]){
std::srand(std::time(0));
std::stringstream mess_ss;
for (int i =1; i < argc; i++){
mess_ss << argv[i];
if (i < argc - 1) mess_ss <<" ";
}
std::string mess;
mess = mess_ss.str();
if(mess == "8ball"){
mess = eightBall();
}
else if(mess == "magic8ball"){
mess = magicEightBall();
}
else if(mess == "joke"){
mess = joke();
}
int lenOfMess = mess.length();
// printf("%d\n", lenOfMess);
std::stringstream ss;
ss << " _";
for (int i = 0; i < lenOfMess; i++){
ss<<"_";
}
ss << "_ \n";
ss << "< ";
ss << mess;
ss << " >\n";
ss << " -";
for (int i = 0; i< lenOfMess; i++){
ss<<"-";
}
ss << "- \n";
ss << " \\ \n";
ss << " \\ \n";
// ss << " (^・ω・^ ) \n";
// ss.str("");
ss << " ▐▀▄ ▄▀▌ ▄▄▄▄▄▄▄ \n";
ss << " ▌▒▒▀▄▄▄▄▄▀▒▒▐▄▀▀▒██▒██▒▀▀▄ \n";
ss << " ▐▒▒▒▒▀▒▀▒▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▀▄ \n";
ss << " ▌▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▄▒▒▒▒▒▒▒▒▒▒▒▒▀▄ \n";
ss << " ▀█▒▒▒█▌▒▒█▒▒▐█▒▒▒▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▌ \n";
ss << " ▀▌▒▒▒▒▒▒▀▒▀▒▒▒▒▒▒▀▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▐ ▄▄ \n";
ss << " ▐▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▌▄█▒█ \n";
ss << " ▐▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒█▒█▀ \n";
ss << " ▐▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒█▀ \n";
ss << " ▐▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▌ \n";
ss << " ▌▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▐ \n";
ss << " ▐▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▌ \n";
ss << " ▌▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▐ \n";
ss << " ▐▄▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▄▌ \n";
ss << " ▀▄▄▀▀▀▀▀▄▄▀▀▀▀▀▀▀▄▄▀▀▀▀▀▄▄▀ \n";
printf(ss.str().c_str());
// printf(argv[1]);
printf("\n");
return 0;
}
| true |
c5887c9b6df13c2231c442e5ebac167d48f2e6aa | C++ | CoupalLee/dlinkedlist | /DLinkedList.cpp | UTF-8 | 1,558 | 3.703125 | 4 | [] | no_license | /*
* DLinkedList.cpp
*
* Created on: Mar 26, 2018
* Author: kareembrathwaite-henry
*/
#include"Node.cpp"
#include <iostream>
#include <ostream>
template <class TYPE>
class DLinkedList {
private:
DLinkedList(const DLinkedList &);
Node<TYPE> *head;
public:
DLinkedList(){
head = new Node<TYPE>(0, head, head);
}
Node<TYPE>* insert(const TYPE& type, Node<TYPE>* current ){//inserts a node
Node<TYPE>* newNode = new Node<TYPE>(type);
Node<TYPE>* temp;
if (isFirst() == NULL)
head = newNode;
else {
while(current->next != NULL){
current = current->next;
}
current->next = newNode;
newNode->previous = current;
}
return newNode;
}
Node<TYPE>* isFirst(){//returns a reference to header node
return head;
}
Node<TYPE>* next(Node<TYPE>* current )const{//returns a reference to next node
return current->next;
}
Node<TYPE>* precedent(Node<TYPE>* current )const{//reference to previous node
return current->previous;
}
Node<TYPE>* remove(Node<TYPE>* N){//removes the node to the right of N
}
bool isEmpty ( ) const{//returns true if the list is empty
}
void display (std::ostream& output ){//writes to a file the elements of the linked list
output << "\nDisplaying: ";
Node<TYPE>* temp = head;
while (temp!=0){
output << temp->value << " ";
temp=temp->next;
}
}
Node<TYPE>* Min(Node<TYPE>* H){//finds the min value in a list headed by H
}
void sort(){//sorts the list (selection sort)
}
};
| true |
807603fac3ff7c678494534215e8cadfa1b43a8e | C++ | shileiyu/nui | /nui/base/ref.h | UTF-8 | 3,477 | 3.078125 | 3 | [] | no_license | #ifndef NUI_BASE_REF_COUNT_H_
#define NUI_BASE_REF_COUNT_H_
#include <nui/nui.h>
namespace nui
{
class RefCountBase
{
protected:
RefCountBase()
: ref_count_(1)
{
memset(tag_, 0, kTagCapcity);
strncpy_s(tag_, "RefCntObj", kMaxTagSize);
}
virtual ~RefCountBase() {};
void Dispose() const
{
delete this;
}
protected:
//disallow cpoy and assign
RefCountBase(const RefCountBase &);
RefCountBase & operator=(const RefCountBase &);
static const size_t kMaxTagSize = 16;
static const size_t kTagCapcity = 20;
char tag_[kTagCapcity];
volatile mutable long ref_count_;
};
class RefCount : public RefCountBase
{
public:
int IncRef() const
{
return ++ref_count_;
}
int DecRef() const
{
int decreased_value = --ref_count_;
if (decreased_value == 0)
this->Dispose();
return decreased_value;
}
protected:
~RefCount() {};
};
class ThreadSafeRefCount : public RefCountBase
{
public:
int IncRef() const
{
return _InterlockedIncrement(&ref_count_);
}
int DecRef() const
{
int decreased_value = _InterlockedDecrement(&ref_count_);
if (decreased_value == 0)
this->Dispose();
return decreased_value;
}
protected:
~ThreadSafeRefCount() {};
};
template<typename T>
class ScopedRef
{
typedef typename T Object;
public:
ScopedRef() : object_(nullptr) {};
ScopedRef(const ScopedRef & other)
: object_(nullptr)
{
Reset(other.object_);
};
ScopedRef(Object * object)
: object_(nullptr)
{
Reset(object);
};
template<typename Derived>
ScopedRef(const ScopedRef<Derived> & other)
: object_(nullptr)
{
Reset(other.Get());
}
~ScopedRef()
{
Reset();
}
Object * operator->()
{
return object_;
}
const Object * operator->() const
{
return object_;
}
ScopedRef & operator=(const ScopedRef & other)
{
Reset(other.object_);
return *this;
}
ScopedRef & operator=(Object * object)
{
Reset(object);
return *this;
}
template<typename Derived>
ScopedRef & operator=(const ScopedRef<Derived> & other)
{
Reset(other.Get());
return *this;
}
bool operator == (const ScopedRef & other) const
{
return this->object_ == other.object_;
}
bool operator != (const ScopedRef & other) const
{
return this->object_ != other.object_;
}
bool operator == (const Object * object) const
{
return this->object_ == object;
}
bool operator != (const Object * object) const
{
return this->object_ != object;
}
Object * Get () const
{
return object_;
}
operator bool() const
{
return IsValid();
}
void Reset()
{
Reset(nullptr);
}
void Reset(Object * object)
{
if (object_)
object_->DecRef();
object_ = object;
if (object_)
object_->IncRef();
return;
}
bool IsValid() const
{
return object_ != nullptr;
}
private:
Object * object_;
};
template<typename T>
ScopedRef<T> Adopt(T * object)
{
ScopedRef<T> ref;
ref.Reset(object);
if(ref)
ref->DecRef();
return ref;
}
}
#endif | true |
87938275e1451f6ea7a6126f4077ab61c3e197eb | C++ | cmeta/WrittenDigitRecognizer | /src/util.cpp | UTF-8 | 2,368 | 3.046875 | 3 | [
"MIT"
] | permissive | /*
* Author: alexanderb
* Adapted into CImg dependency by Michael Wang
*/
#include "util.h"
void Util::DisplayImage(CImg<float>& img) {
//Display image
img.display();
}
//-----------------------------------------------------------------------------------------------
void Util::DisplayMat(CImg<float>& img) {
cout << "-= Display Matrix =-";
int rowCount = 0;
for (int r = 0; r < img._height; r++) {
cout << endl;
int colCount = 0;
for (int c = 0; c < img._width; c++) {
cout << img(c,r) << ", ";
colCount++;
}
rowCount++;
cout << " -> " << colCount << "cols";
}
cout << "-> " << rowCount << "rows" << endl;
}
//-----------------------------------------------------------------------------------------------
void Util::DisplayPointVector(vector<point> vp) {
vector<point>::iterator pIterator;
for(int i=0; i<vp.size(); i++) {
point p = vp[i];
cout << p.x << "," << p.y << "; ";
}
}
//-----------------------------------------------------------------------------------------------
CImg<float> Util::MarkInImage(CImg<float>& img, vector<pointData> points, int r) {
CImg<float> retImg(img);
for(vector<pointData>::iterator it = points.begin(); it != points.end(); ++it) {
point center = (*it).p;
// // down
// for(int r=-radius; r<radius; r++) {
// retImg(Point(center.y+r,center.x+radius)) = Vec3b(0, 0, 255);
// }
// // up
// for(int r=-radius; r<radius; r++) {
// retImg.at<Vec3b>(Point(center.y+r,center.x-radius)) = Vec3b(0, 0, 255);
// }
// // left
// for(int c=-radius; c<radius; c++) {
// retImg.at<Vec3b>(Point(center.y-radius,center.x+c)) = Vec3b(0, 0, 255);
// }
// // right
// for(int c=-radius; c<radius; c++) {
// retImg.at<Vec3b>(Point(center.y+radius,center.x+c)) = Vec3b(0, 0, 255);
// }
// retImg.at<Vec3b>(Point(center.y,center.x)) = Vec3b(0, 255, 0);
int x = center.x;
int y = center.y;
for (int i = x - r; i < x + r; i++) {
for (int j = y - r; j < y + r; j++) {
if (i >= 0 && i < img._width && j >= 0 && j < img._height) {
if (sqrt(pow(i - x, 2) + pow(j - y, 2)) <= r) {
// printf("Draw... i:%d, j:%d\n", i, j);
retImg(i, j, 0) = 255;
retImg(i, j, 1) = 255;
retImg(i, j, 2) = 0;
}
}
}
}
}
return retImg;
}
| true |
a7134508009b135cf836347c21d447874ea27850 | C++ | XenofoR/gameengine | /engine/Include/MemoryAllocator.h | UTF-8 | 636 | 2.546875 | 3 | [] | no_license | #pragma once
#include "MemPool.h"
#include "MemStack.h"
class MemoryAllocator
{
public:
MemoryAllocator(bool p_customer_Al_the_croc);
~MemoryAllocator();
template <class T>
MemPool<T>* CreatePool(unsigned int p_numBlocks, unsigned int p_alignment, bool p_shared)
{
MemPool<T>* pool = new MemPool<T>(p_numBlocks, p_alignment, p_shared, m_customer_Al_the_croc);
return pool;
}
//Note: If you allocate more than some unknown high value, think INT_MAX~ish, you're gonna have a bad bad time
MemStack* CreateStack(unsigned int p_stacksize, unsigned int p_alignment, bool p_shared);
private:
bool m_customer_Al_the_croc;
}; | true |
e2aa684547d1581f0fb1988ec8591143f5257f14 | C++ | flwmxd/Simplification | /main.cpp | UTF-8 | 1,728 | 2.984375 | 3 | [] | no_license | ///////////////////////////////////////////////////
//
// Hamish Carr
// January, 2018
//
// ------------------------
// main.cpp
// ------------------------
//
///////////////////////////////////////////////////
#include <QApplication>
#include "GeometricWindow.h"
#include "GeometricController.h"
#include <stdio.h>
int main(int argc, char **argv)
{ // main()
// initialize QT
QApplication app(argc, argv);
// the geometric surface
GeometricSurfaceDirectedEdge surface;
// check the args to make sure there's an input file
if (argc == 2 || argc == 3)
{ // two parameters - read a file
if (!surface.ReadFileDirEdge(argv[1]))
{ // surface read failed
printf("Read failed for file %s\n", argv[1]);
exit(0);
} // surface read failed
else
{ // surface read succeeded
// create the root widget (window)
std::cout<<argv[2]<<std::endl;
bool tarjan = argc == 3 && (std::string(argv[2]) == "--tarjan" || std::string(argv[2]) == "-t");
GeometricWindow theWindow(&surface, NULL);
// create the controller
GeometricController *theController = new GeometricController(&surface, &theWindow);
// set the initial size
theWindow.resize(600, 640);
// show the window
theWindow.show();
// and reset the interface
theWindow.ResetInterfaceElements();
if(tarjan){
theController->surface->tarjan.start(theController->surface);
}
// set QT running
return app.exec();
} // surface read succeeded
} // two parameters - read a file
else
{ // too many parameters
printf("Usage: %s filename\n", argv[0]);
exit (0);
} // too many parameters
// paranoid return value
exit(0);
} // main()
| true |
3c2ac393913f1418124d12de8b9a9470c845e416 | C++ | ORNL-Fusion/xolotl | /xolotl/core/include/xolotl/core/advection/AdvectionHandler.h | UTF-8 | 2,087 | 3.21875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef ADVECTIONHANDLER_H
#define ADVECTIONHANDLER_H
// Includes
#include <xolotl/core/Constants.h>
#include <xolotl/core/advection/IAdvectionHandler.h>
namespace xolotl
{
namespace core
{
namespace advection
{
/**
* This class realizes the IAdvectionHandler interface responsible for all
* the physical parts for the advection of mobile helium clusters. It needs to
* have subclasses that implement the initialize method.
*/
class AdvectionHandler : public IAdvectionHandler
{
protected:
//! The location of the sink
double location;
//! The collection of advecting clusters.
std::vector<IdType> advectingClusters;
//! The vector containing the value of the sink strength (called A) of the
//! advecting clusters
std::vector<double> sinkStrengthVector;
//! The number of dimensions of the problem
int dimension;
public:
//! The Constructor
AdvectionHandler() : location(0.0), dimension(0)
{
}
//! The Destructor
~AdvectionHandler()
{
}
/**
* Set the number of dimension.
*
* \see IAdvectionHandler.h
*/
void
setDimension(int dim) override
{
dimension = dim;
}
/**
* Set the location of the sink.
*
* \see IAdvectionHandler.h
*/
void
setLocation(double pos) override
{
location = pos;
}
/**
* Get the total number of advecting clusters in the network.
*
* \see IAdvectionHandler.h
*/
int
getNumberOfAdvecting() const override
{
return advectingClusters.size();
}
/**
* Get the vector of index of advecting clusters in the network.
*
* \see IAdvectionHandler.h
*/
const std::vector<IdType>&
getAdvectingClusters() override
{
return advectingClusters;
}
/**
* Get the vector of sink strength.
*
* \see IAdvectionHandler.h
*/
const std::vector<double>
getSinkStrengths() override
{
return sinkStrengthVector;
}
/**
* Get the location of the sink.
*
* \see IAdvectionHandler.h
*/
double
getLocation() const override
{
return location;
}
};
// end class AdvectionHandler
} /* end namespace advection */
} /* end namespace core */
} /* end namespace xolotl */
#endif
| true |
a03e4dd75ce930180424c9f20a5a75776a697586 | C++ | Und3rMySk1n/ood | /lab04_factory/libpainter/Ellipse.h | UTF-8 | 470 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Shape.h"
class CEllipse :
public CShapeImpl<CShape, CShape, CEllipse>
{
public:
CEllipse(Color color, Vertex center, float horizontalRadius, float verticalRadius);
Vertex GetCenter() const;
float GetHorizontalRadius() const;
float GetVerticalRadius() const;
void Draw(ICanvas &canvas) const override;
~CEllipse();
private:
Vertex m_center = { 0, 0 };
float m_horizontalRadius = 0;
float m_verticalRadius = 0;
};
| true |
d24806a3c8397b0d00aaf602e1ff5807843a5945 | C++ | kopaka1822/ObjToHrsfConverter | /ObjSingleIndexBufferConverter/FileHelper.h | UTF-8 | 273 | 3.125 | 3 | [] | no_license | #pragma once
#include <string>
// attempts to retrieve the file directory
inline std::string getDirectory(const std::string &filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\")) + "\\";
return "";
} | true |
a3b1e78f917be334ca5f913bea36b3a7aeabf07c | C++ | gunishmatta/Daily-Programming-Practice | /Basics and Implementations/c++ stl/priorityqueue.cpp | UTF-8 | 716 | 3.296875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int> q;
q.push(-1);
q.push(100);
q.push(30);
q.push(20);
q.push(-100);
q.push(0);
cout<<"Top of PQ is "<<q.top()<<endl; //Greatest element since it arranges in descending order
cout<<"size of PQ is "<<q.size()<<endl;
q.pop();
cout<<"Top of PQ after pop is "<<q.top()<<endl; //2nd largest element
cout<<"size of PQ after pop is "<<q.size()<<endl;
priority_queue<int,vector<int>,greater<int>> q1;
q1.push(-1);
q1.push(100);
q1.push(30);
q1.push(20);
q1.push(-100);
q1.push(0);
cout<<"Top of PQ q1 is "<<q1.top()<<endl; //Smallest number as we have declared PQ q1 using other way
cout<<"size of PQ q1 is "<<q1.size()<<endl;
return 0;
} | true |
ef84cc91ee436532b789339ba280468aca266586 | C++ | alcornwill/logic_simulator | /createcommand.cpp | UTF-8 | 1,212 | 2.734375 | 3 | [] | no_license | #include "createcommand.h"
#include "mygraphicsscene.h"
#include "mainwindow.h"
CreateCommand::CreateCommand(Component *_component, Component *_parent)
{
component = _component;
parent = _parent;
setText("create component");
}
CreateCommand::~CreateCommand()
{
// create/delete commands can hold the last reference to a component that was removed from the scene
// so when the command is deleted, we may need to delete the component or there will be a memory leak
// yes this would probably be solvable with shared pointers, but shared pointers
// can still have dangling pointers. That's why QPointer is cool.
// the component may have already been deleted by the QT parenting memory management system
//Q_ASSERT(component);
if (component && component->deleted)
delete component;
}
void CreateCommand::undo()
{
Q_ASSERT(component);
// delete component
if (component)
mywindow->RemoveComponent(component);
// if the component doesn't exist anymore then this command will sit in the stack and do nothing...
}
void CreateCommand::redo()
{
Q_ASSERT(component);
if (component)
mywindow->AddComponent(component, parent);
}
| true |
95a0d6752b9a90f6d36e2b145cebfe0e855cca9f | C++ | lizhenghong66/open_spiel | /open_spiel/games/landlord/landlord_hand.cc | UTF-8 | 1,425 | 2.515625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "landlord_hand.h"
#include <algorithm>
#include <cassert>
namespace landlord_learning_env {
void LandlordHand::AddCard(LandlordCard card) {
assert(isValidCard(card));
cards_.push_back(card);
}
void LandlordHand::AddCards(std::vector<LandlordCard> cards){
cards_.insert(cards_.end(),cards.begin(),cards.end());
}
void LandlordHand::RemoveFromHand(LandlordCard card,
std::vector<LandlordCard>* discard_pile) {
std::vector<LandlordCard>::iterator result = find(cards_.begin(),cards_.end(),card);
if (result != cards_.end()){
if (discard_pile != nullptr) {
discard_pile->push_back(card);
}
cards_.erase(result);
}
}
std::string LandlordHand::ToString() const {
std::string result = cards2String(cards_);
return result;
}
} // namespace landlord_learning_env
| true |
8f902b743e2118587bb92ec662f633eafd6e8054 | C++ | yuzhishuo/cpp | /leetcode/35.search-insert-position.cpp | UTF-8 | 1,249 | 3.421875 | 3 | [
"Apache-2.0"
] | permissive | /*
* @lc app=leetcode.cn id=35 lang=cpp
*
* [35] 搜索插入位置
*
* https://leetcode-cn.com/problems/search-insert-position/description/
*
* algorithms
* Easy (43.24%)
* Total Accepted: 40.9K
* Total Submissions: 94.6K
* Testcase Example: '[1,3,5,6]\n5'
*
* 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
*
* 你可以假设数组中无重复元素。
*
* 示例 1:
*
* 输入: [1,3,5,6], 5
* 输出: 2
*
*
* 示例 2:
*
* 输入: [1,3,5,6], 2
* 输出: 1
*
*
* 示例 3:
*
* 输入: [1,3,5,6], 7
* 输出: 4
*
*
* 示例 4:
*
* 输入: [1,3,5,6], 0
* 输出: 0
*
*
*/
#include <algorithm>
#include <vector>
using namespace std;
class Solution
{
public:
int searchInsert(vector<int> &nums, int target)
{
int rt = 0;
find_if(nums.begin(), nums.end(), [&](int i) {
if (i < target)
{
rt++;
return false;
}
if (i == target)
{
return true;
}
return false;
});
return rt;
}
};
| true |
bbeb5a394d84345235e185751eed37cdb30988d2 | C++ | asok00000/qzues | /qzueslineedit.cpp | UTF-8 | 804 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "qzueslineedit.h"
QZuesLineEdit::QZuesLineEdit(QWidget *parent)
: QLineEdit(parent), m_isContentChanged(false), m_originContent(""), m_isFirstSet(true)
{
}
QZuesLineEdit::~QZuesLineEdit()
{
}
bool QZuesLineEdit::getContentChanged() const
{
return m_isContentChanged;
}
void QZuesLineEdit::setContentChanged(bool val)
{
m_isContentChanged = val;
}
void QZuesLineEdit::setText(const QString &content)
{
if (m_isFirstSet)
{
m_isFirstSet = false;
m_originContent = content;
}
else
{
if (m_originContent != content)
{
if (!m_isContentChanged)
{
setContentChanged(true);
}
}
else
{
if (m_isContentChanged)
{
setContentChanged(false);
}
}
}
QLineEdit::setText(content);
}
void QZuesLineEdit::reset()
{
QLineEdit::setText(m_originContent);
}
| true |
68df7ea9693c25dec009acb47fb7ad93b46d0ff4 | C++ | jaanvirbains/Pac-Man | /main.cpp | UTF-8 | 4,980 | 2.765625 | 3 | [] | no_license | //Jaanvir, Go Diego, Go, and Kaanstantinople
#include <iostream>
#include <stdio.h>//ALLOWS USER TO INPUT FUNCTIONS FROM A USER THROUGH USE OF CONTROLLER (TMP FILE, PRINT, OPEN AND SCAN)
#include <windows.h>//GET ASNY KEY DEFINES MOVEMENT
#include <vector>
using namespace std;
char dab_map[18][32];
char map[18][32] = {
" _____________________________ ",
"| | | |",
"| ,__, ,___, | | ,___, |",
"| |__| |___| |_| |___| |",
"| |",
"| ,__, ,_______, |",
"| |__| |_______| |",
"| ,___, |",
"| |___| |",
"| ,_, ,_____, |",
"| |_| ,___, |_____| |",
"| |___| |",
"| |",
"| ,_______________, |",
"| |_______________| |",
"| |",
"| | | |",
" _____________|_|_____________ "
};
void ShowMap()
{
for(int i = 0; i < 18; i++) {
printf("%s\n",map[i] );
}
}
void gotoxy( short x, short y )
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE) ;
COORD position = { x, y } ;
SetConsoleCursorPosition( hStdout, position ) ;
}
class communism {
public:
communism( int x, int y ){
this ->x = x;
this ->y = y;
}
void move_x( int p ){
if( map[y][x+p] == ' ' ) x += p;
}
void move_y( int p ){
if( map[y+p][x] == ' ' ) y += p;
}
void move( int p, int q ){
x += p;
y += q;
}
int get_x(){ return x; }
int get_y(){ return y; }
void draw( char p ){
map[x][y] = p;
gotoxy( x, y ); printf( "%c", p );
}
private:
int x;
int y;
};
struct sanic {
short sanic_count;
short x;
short y;
short back;
};
struct target {
short x;
short y;
};
vector<target> sanic_queue;
vector<sanic> MEXArray;
void AddArray( int x, int y, int wc , int back ){
if( dab_map[y][x] == ' ' || dab_map[y][x] == '.' ){
dab_map[y][x] = '#';
sanic dab;
dab.x = x;
dab.y = y;
dab.sanic_count = wc;
dab.back = back;
MEXArray.push_back( dab );
}
}
void FindPath( int sx, int sy, int x, int y ){
memcpy( dab_map, map, sizeof(map) );
MEXArray.clear();
sanic dab;
dab.x = sx;
dab.y = sy;
dab.sanic_count = 0;
dab.back = -1;
MEXArray.push_back( dab );
int i = 0;
while( i < MEXArray.size() ){
if( MEXArray[i].x == x && MEXArray[i].y == y ){
sanic_queue.clear();
target dab2;
while( MEXArray[i].sanic_count != 0 ){
dab2.x = MEXArray[i].x;
dab2.y = MEXArray[i].y;
sanic_queue.push_back( dab2 );
i = MEXArray[i].back;
}
break;
}
AddArray( MEXArray[i].x+1, MEXArray[i].y, MEXArray[i].sanic_count+1, i );
AddArray( MEXArray[i].x-1, MEXArray[i].y, MEXArray[i].sanic_count+1, i );
AddArray( MEXArray[i].x, MEXArray[i].y+1, MEXArray[i].sanic_count+1, i );
AddArray( MEXArray[i].x, MEXArray[i].y-1, MEXArray[i].sanic_count+1, i );
i++;
}
MEXArray.clear();
}
int main()
{
bool running = true;
int x = 15;
int y = 16;
int old_x;
int old_y;
int ex = 1;
int ey = 1;
int pts = 0;
cout<< "Instruction:\n1. Arrow Keys to move Shrek\n2. Eat the dots from Lord Farquaad to gain points\n3. Don't get caught by Lord Farquaad\n\n" << endl;
printf("H -> Hard\nN -> Normal\nE -> EZ/Noob level\n\nInput : ");
char diffi;
int speedmod = 3;
cin >> diffi;
if( diffi == 'N' ){
speedmod = 2;
}else if( diffi == 'H' ){
speedmod = 1;
}
system("cls");
ShowMap();
gotoxy( x, y ); cout << "H";
int frame = 0;
FindPath( ex,ey,x,y );
while( running ){
gotoxy( x, y ); cout << " ";
old_x = x;
old_y = y;
if ( GetAsyncKeyState( VK_UP ) ){
if( map[y-1][x] == '.' ){ y--; pts++; } else
if( map[y-1][x] == ' ' ) y--;
}
if ( GetAsyncKeyState( VK_DOWN ) ){
if( map[y+1][x] == '.' ){ y++; pts++; } else
if( map[y+1][x] == ' ' ) y++;
}
if ( GetAsyncKeyState( VK_LEFT ) ){
if( map[y][x-1] == '.' ){ x--; pts++; } else
if( map[y][x-1] == ' ' ) x--;
}
if ( GetAsyncKeyState( VK_RIGHT ) ){
if( map[y][x+1] == '.' ){ x++; pts++; } else
if( map[y][x+1] == ' ' ) x++;
}
if( old_x != x || old_y != y ){
FindPath( ex,ey,x,y );
}
gotoxy( x,y ); cout << "S";
map[ey][ex] = '.';
gotoxy( ex, ey ); cout << ".";
if( frame%speedmod == 0 && sanic_queue.size() != 0 ){
ex = sanic_queue.back().x;
ey = sanic_queue.back().y;
sanic_queue.pop_back();
}
gotoxy( ex, ey ); cout << "F";
if( ex == x && ey == y ){
break;
}
gotoxy( 32, 18 );
gotoxy( 32, 1 ); cout << pts;
Sleep( 100 );
frame++;
}
system("cls");
printf("You Lost?!? What the Shrek my dood?!?\nThanks to you, Farquad has taken ogre!\nWay to go, dorc.\nYour dank score is : %i ", pts );
cin.get();
cin.get();
return 0;
}
| true |
06128943dbf509d35026346e6203c10d0a4b4aa7 | C++ | FedericoAmura/Taller2016C1TP4MegamanInicia | /editor/Workspace.cpp | UTF-8 | 3,762 | 2.78125 | 3 | [] | no_license | //
// Created by marcos on 23/05/16.
//
#include <iostream>
#include <gdkmm.h>
#include "Workspace.h"
#include "../entities.h"
#define SIZE_TRANSFORM 15.5
typedef Glib::RefPtr<Gdk::Pixbuf> Pixbuf;
typedef drawing_map_t::iterator p_iter;
Workspace::Workspace(Level* level)
: level(level) {
screen_width = (int) Gdk::screen_height()/SIZE_TRANSFORM;
resize();
put(background, 0, 0);
refresh();
}
void Workspace::resize() {
uint x = level->getLength()*screen_width;
uint y = level->getWidth()*screen_width;
set_size_request(x, y);
background.setSize(x, y);
}
Workspace::~Workspace() {
clean();
delete level;
}
bool Workspace::addElement(uint x, uint y, uint id) {
//Add to model
prototype_t element;
element.x = x;
element.y = y;
element.id = id;
if (level->addEntity(element)){
//Add to view
pair<uint, uint> position = std::make_pair(x, y);
Drawing* drawing = new Drawing();
drawing->setImage(sprites.get(id), screen_width, screen_width);
drawings[position] = drawing;
put(*drawing,
std::get<0>(position) * screen_width,
std::get<1>(position) * screen_width);
drawing->show();
resize();
return true;
} else {
return false;
}
}
bool Workspace::removeEntity(uint x, uint y) {
//Remove from model
if (level->removeEntity(x, y)){
//Remove from view
std::pair<uint, uint> position = std::make_pair(x, y);
Drawing* drawing = drawings[position];
drawings.erase(position);
delete drawing;
resize();
return true;
} else {
return false;
}
}
uint Workspace::getId(uint x, uint y) {
return level->getEntity(x, y);
}
bool Workspace::validPosition(uint x, uint y) {
return (x < level->getLength() && y < level->getWidth());
}
void Workspace::replaceLevel() {
//Asks for copy to get same type
Level* new_level = level->cleanCopy();
delete level;
level = new_level;
renew();
}
void Workspace::replaceLevel(string file) {
Level* new_level = level->openCopy(file);
delete level;
level = new_level;
renew();
}
void Workspace::refresh() {
string background_file = level->getBackgroundFile();
//La funcionalidad comentada fue desactivada para la entrega
//final ya que es defectuosa.
/*
if (background_file != "") {
background.setImage(background_file,
screen_width * level->getLength(),
screen_width * level->getWidth());
//background.show();
}
*/
for (uint i = 0; i < level->getLength() ; ++i){
for (uint j = 0; j < level->getWidth() ; ++j){
uint id = level->getEntity(i, j);
if (id != 0) {
pair<uint, uint> position = std::make_pair(i, j);
Drawing* drawing = new Drawing();
drawing->setImage(sprites.get(id), screen_width, screen_width);
drawings[position] = drawing;
put(*drawing,
std::get<0>(position) * screen_width,
std::get<1>(position) * screen_width);
drawing->show();
}
}
}
}
void Workspace::clean() {
for (p_iter it = drawings.begin(); it != drawings.end(); ++it){
Drawing* old = it->second;
delete old;
drawings.erase(it);
}
}
void Workspace::save(string file_name) {
level->toJson(file_name);
}
void Workspace::renew() {
clean();
resize();
refresh();
}
void Workspace::setBackground(string path) {
level->setBackgroundFile(path);
hide();
clean();
refresh();
show();
}
| true |
30b4888bffe17f215aaa7fabc3f55c530fa17f36 | C++ | yuunikorn/mouse-playground | /2019 micromouse/micromouseV4/a_blink.ino | UTF-8 | 469 | 2.921875 | 3 | [] | no_license | /* Basics Blink command for hardware testing
*
* Functions that can be called:
* --> Setup:
* BlinkSetup();
*
* --> Loop:
* BlinkCommand();
*/
void BlinkSetup(){
pinMode(LED_BUILTIN, OUTPUT);
}
void BlinkCommand(){
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
| true |
841902f1577dad9eabb343e798e9dc464d43814c | C++ | dhryniuk/Markov-Chain-Monte-Carlo-in-CPP | /binomial.cpp | UTF-8 | 407 | 2.921875 | 3 | [] | no_license | #include "headers/binomial.h"
bool binomial::positive_support()
{
return true;
}
binomial::binomial(int number, float success) : n{number}, p{success}
{
std::binomial_distribution<int> dis{n,p};
};
binomial::~binomial() {};
int binomial::sample(std::mt19937 generator)
{
return dis(generator);
}
double binomial::pdf(int x)
{
return binom(n,x)*pow(p,x)*pow(1-p,n-x);
} | true |
d61e2a26c3d6a399caae53b877cfdd02a12531ad | C++ | Morseee/police-egypt | /police/src/Image.cpp | UTF-8 | 1,251 | 2.84375 | 3 | [] | no_license | /*
* Image.cpp
*
* Created on: Apr 27, 2012
* Author: amro
*/
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<string>
#include "Image.h"
Image::Image(std::string filename) {
FILE *image = fopen(filename.c_str() , "rb");
unsigned char c;
for(int i=0;i<18;i++)
{
fscanf(image,"%c",&c);
}
unsigned char b[4];
fscanf(image,"%c%c%c%c",&b[0],&b[1],&b[2],&b[3]);
width = (b[3]<<24)|(b[2]<<16)|(b[1]<<8)|b[0];
fscanf(image,"%c%c%c%c",&b[0],&b[1],&b[2],&b[3]);
height = (b[3]<<24)|(b[2]<<16)|(b[1]<<8)|b[0];
for(int i=0;i<28;i++)
fscanf(image,"%c",&c);
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
char r,g,b;
fscanf(image,"%c%c%c",&b,&g,&r);
pixels[i][j].red=r;
pixels[i][j].green=g;
pixels[i][j].blue=b;
}
if((width*3)%4==0)
continue;
for(int j=0;j<4-((width*3)%4);j++)
fscanf(image,"%c",&c);
}
fclose(image);
}
void Image::display(int win_x,int win_y)
{
glBegin(GL_POINTS);
for(int i=0,h=win_y;i<height;i++,h++)
{
for(int j=0,w=win_x;j<width;j++,w++)
{
float r = ((float)pixels[i][j].red)/255.0;
float g = ((float)pixels[i][j].green)/255.0;
float b = ((float)pixels[i][j].blue)/255.0;
glColor3f(r,g,b);
glVertex2i(w,h);
}
}
glEnd();
}
| true |
1b2d0ae1c2ba6eefb735c6a4526b0f086f3d2b2a | C++ | asvgit/hw_third | /main.cpp | UTF-8 | 2,786 | 3.390625 | 3 | [] | no_license | #include <map>
#include "lib.h"
#include <memory>
constexpr int magic_num = 10;
using factorial = util::fact<magic_num>;
template<typename T, typename _Alloc = std::allocator<T>>
class List {
struct Node {
T m_data;
Node *next = nullptr;
List *m_parent;
Node(const T &val, List *parent) : m_data(val), next(nullptr), m_parent(parent) {}
~Node() {
if (next != nullptr) {
m_parent->m_alloc.destroy(next);
m_parent->m_alloc.deallocate(next, 1);
}
}
T& at(const int i) {
if (!i)
return m_data;
return next->at(i - 1);
}
static void append(List *parent, Node *&node, const T &val) {
if (node == nullptr) {
node = parent->m_alloc.allocate(1);
parent->m_alloc.construct(node, std::forward<const T>(val), parent);
return;
}
Node::append(parent, node->next, std::forward<const T>(val));
}
}* head;
friend struct Node;
using RebindedAlloc = typename _Alloc::template rebind<Node>::other;
RebindedAlloc m_alloc;
int m_size;
public:
List() : head(nullptr), m_alloc(), m_size(0) {}
List(const List &list) : head(nullptr), m_alloc(), m_size(0) {
for (size_t i = 0; i < list.size(); ++i)
push_back(list[i]);
}
List(List &&list) : head(nullptr), m_alloc(), m_size(list.m_size) {
std::cout << "List" << std::endl;
std::swap(head, list.head);
}
template<typename __Alloc>
List(const List<T, __Alloc> &list) : head(nullptr), m_alloc(), m_size(0) {
for (size_t i = 0; i < list.size(); ++i)
push_back(list[i]);
}
~List() {
if (head == nullptr)
return;
m_alloc.destroy(head);
m_alloc.deallocate(head, 1);
}
void push_back(const T &val) {
++m_size;
Node::append(this, head, std::forward<const T>(val));
}
T& operator[](const int index) const {
assert(index >= 0 && index < m_size);
return head->at(index);
}
int size() const { return m_size; }
};
int main() {
try {
{
std::map<int, int> m{};
for (size_t i = 0; i < magic_num; ++i) {
m[i] = factorial::val(i);
}
}
{
std::map<int, int, std::less<int>, logging_allocator<std::pair<const int, int>, magic_num / 2>> m {};
for (size_t i = 0; i < magic_num; ++i) {
m[i] = factorial::val(i);
}
for (size_t i = 0; i < magic_num; ++i) {
std::cout << i << " " << m[i] << std::endl;
}
}
{
List<int> a;
for (size_t i = 0; i < magic_num; ++i) {
a.push_back(factorial::val(i));
}
}
{
List<int, logging_allocator<int, magic_num>> a;
for (size_t i = 0; i < magic_num; ++i) {
a.push_back(factorial::val(i));
}
for (size_t i = 0; i < magic_num; ++i) {
std::cout << i << " " << a[i] << std::endl;
}
List<int, logging_allocator<int, magic_num>> b(std::move(a));
}
} catch(const std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| true |
5c06aa33ec96ced787fa0103b65332f9e29ab6f2 | C++ | peutykeure/randomshapegenerator | /src/Rectangle.cpp | UTF-8 | 461 | 2.828125 | 3 | [] | no_license | #include "Rectangle.h"
#include "Color.h"
#include "Shape.h"
Rectangle::Rectangle(int x, int y, int r, int g, int b, int w, int h):Shape(x,y,r,g,b),_width(w),_height(h) {
_moveMultiplier = 1;
}
void Rectangle::draw(sf::RenderWindow *win) const {
int r,g,b;
this->fill.getRGB(r,g,b);
sf::RectangleShape shape(sf::Vector2f(_width, _height));
shape.setFillColor(sf::Color(r, g, b));
shape.setPosition(_x,_y);
win->draw(shape);
}
| true |
5aebe6f57dc77bf8a1b648bb90b7062be006cc2e | C++ | Haar-you/kyopro-lib | /Mylib/Number/Prime/miller_rabin.cpp | UTF-8 | 1,290 | 2.71875 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <initializer_list>
#include "Mylib/Misc/int128.cpp"
namespace haar_lib {
namespace miller_rabin_impl {
uint128_t power(uint128_t a, uint128_t b, uint128_t p) {
uint128_t ret = 1;
while (b > 0) {
if (b & 1) ret = ret * a % p;
a = a * a % p;
b >>= 1;
}
return ret;
}
bool is_composite(uint64_t a, uint64_t p, int s, uint64_t d) {
uint128_t x = power(a, d, p);
if (x == 1) return false;
for (int i = 0; i < s; ++i) {
if (x == p - 1) return false;
x = x * x % p;
}
return true;
}
} // namespace miller_rabin_impl
bool miller_rabin(uint64_t n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
int s = 0;
uint64_t d = n - 1;
while ((d & 1) == 0) {
s += 1;
d >>= 1;
}
if (n < 4759123141) {
for (uint64_t x : {2, 7, 61}) {
if (x < n and miller_rabin_impl::is_composite(x, n, s, d)) return false;
}
return true;
}
for (uint64_t x : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
if (x < n and miller_rabin_impl::is_composite(x, n, s, d)) return false;
}
return true;
}
} // namespace haar_lib
| true |
cfc8fd9332f0459b03bab96e57e73dfd1aabbf5b | C++ | HaydenSansum/ReVera | /reVera_CarreMagique/src/ofApp.cpp | UTF-8 | 5,039 | 3.078125 | 3 | [] | no_license | #include "ofApp.h"
// USER FUNCTIONS
//--------------------------------------------------------------
float ofApp::calcAngle(ofVec2f A, ofVec2f B, ofVec2f C){
// Test angles
ofVec2f first_line = A - B;
ofVec2f second_line = C - B;
float l1_angle = atan2(first_line.y, first_line.x);
float l2_angle = atan2(second_line.y, second_line.x);
// Convert angles to be positive only
if (l1_angle < 0) {
l1_angle_pos = PI + l1_angle;
} else {
l1_angle_pos = l1_angle;
}
if (l2_angle < 0) {
l2_angle_pos = PI + l2_angle;
} else {
l2_angle_pos = l2_angle;
}
// Calculate the halfway angle
float final_angle = ((l1_angle + l2_angle) / 2) + PI;
return (final_angle);
}
// OF FUNCTIONS
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(255);
N = 18; // Number of vertices for the path
width = 100;
seed_val = 26;
// Set up canvas
fbo.allocate(700,700);
// Initialize angles
corner_angle_prev = 0;
corner_angle_next = 0;
// Test Angles
ofVec2f first_line = ofVec2f(0,0) - ofVec2f(100,0);
ofVec2f second_line = ofVec2f(200,100) - ofVec2f(100,0);
float l1_angle = atan2(first_line.y, first_line.x);
float l2_angle = atan2(second_line.y, second_line.x);
// Convert angles to be positive only
if (l1_angle < 0) {
l1_angle_pos = PI + l1_angle;
} else {
l1_angle_pos = l1_angle;
}
if (l2_angle < 0) {
l2_angle_pos = PI + l2_angle;
} else {
l2_angle_pos = l2_angle;
}
// Calculate the halfway angle
float final_angle = ((l1_angle + l2_angle) / 2);
cout << final_angle << endl;
}
//--------------------------------------------------------------
void ofApp::update(){
// Clear vector each time
centers.clear();
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSeedRandom(seed_val);
cam.begin();
ofEnableDepthTest();
ofFill();
ofBackground(214,85,10);
ofSetColor(0);
// Create a vector of centers of N vertices using noise
centers.push_back(ofVec3f(-400, 200, 0)); // Create the starting vertex
for (float i = 0; i < N-2; i++) {
centers.push_back(ofVec3f(ofRandom(-200 - (i*190), 200 + (i*190)), ofRandom(-200 - (i*190), 200 + (i*190)), -250*(i+1)));
}
centers.push_back(ofVec3f(15000, 200, -250*N));// Create the final exit point
// For each pair of points (except final point) - draw a rectangle
for (int i = 0; i < centers.size()-1; i++) {
ofVec3f cur_point = centers[i];
ofVec3f next_point = centers[i+1];
// For simplicity just add on in the vertical direction
float h_width = width/2;
ofVec3f vertex_1 = cur_point + ofVec3f(-sin(corner_angle_prev)*h_width, -cos(corner_angle_prev)*h_width, 0);
ofVec3f vertex_2 = next_point + ofVec3f(-sin(corner_angle_next)*h_width, -cos(corner_angle_next)*h_width, 0);
ofVec3f vertex_3 = next_point + ofVec3f(sin(corner_angle_next)*h_width, cos(corner_angle_next)*h_width, 0);
ofVec3f vertex_4 = cur_point + ofVec3f(sin(corner_angle_prev)*h_width, cos(corner_angle_prev)*h_width, 0);
ofBeginShape();
ofVertex(vertex_1);
ofVertex(vertex_2);
ofVertex(vertex_3);
ofVertex(vertex_4);
ofEndShape(true);
}
ofDisableDepthTest();
cam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if (key == ' ') {
img.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
img.save(ofGetTimestampString() + "screenshot.png");
}
if (key == 'r') {
seed_val = ofRandom(0, 1000);
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
a74361db65e76aa26e71a0c69d72de2f72f4dcad | C++ | yohokuno/nb | /CBomb.h | SHIFT_JIS | 1,504 | 2.890625 | 3 | [] | no_license |
#ifndef _INC_CBOMB_H_
#define _INC_CBOMB_H_
class CBomb:public CObj
{
public:
CBomb(CPlayer *pPlayer);
virtual ~CBomb();
virtual void StepFrame();
virtual void Render();
static void LoadImage();
void Explode(); //
virtual bool ColPlayer(CPlayer *pl){pl->SetOffIceFlag();return false;};
virtual bool OnPlayer(CPlayer *pl){return false;};
virtual bool ColFire(int bombIndex){m_Timer=m_maxTimer-COMBO_TIMER;return false;};
virtual bool SetableBomb(){return false;};
virtual OBJTYPE IsTyoe(){return BOMB;};
int GetCounter(){return m_Timer;};
protected:
CPlayer *m_pPlayer; //ẽvC
int m_Timer; //^C}[FOm_maxTimer܂
int m_maxTimer;
int m_fire; //ΉFOȂЂƃ}X
int m_anmCount; //AjJE^FtOς܂ŐFOMAX_ANMCOUNT-1܂
int m_anmFrame; //Ajt[F摜̍牽Ԗڂ̃t[FOMAX_ANMFRAME-1̊
int m_anmDirect; //Aj̕
//ÓIoϐ
static CMysImageEx s_cimg;
static CMysSoundEx sndSetBomb;
static CMysSoundEx sndExplode;
//wp[
void UpFire(int i);
void DownFire(int i);
void LeftFire(int i);
void RightFire(int i);
//萔
static const int MAX_TIMER;
static const int MAX_ANMCOUNT; //AjJE^̍ől
static const int MAX_ANMFRAME; //Ajt[̐
static const int COMBO_TIMER; //A
};
#endif
| true |
76646a2cacb96b5ec32dfb9be3d28f56a754c3ba | C++ | agentcox/TheAgencyRazorOne | /Listpriv.cpp | UTF-8 | 17,452 | 3.015625 | 3 | [
"MIT"
] | permissive | //--------------------------------------------------------------------------------------------
// Project: The Capricorn Document by Team V
// Team: Charles Cox, Dave Kondor, Dave Wilson, Hideki Saito, Paul Sequeira, Wyatt Jackson
// Desc: Linked List Library - Private Implementation
// Authors: Dave Wilson (initial design and code)
// Wyatt Jackson (comments and tweaks)
// File: listpriv.c
// Changed: 02-25-00 Added deleteObj
//
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
// #includes
//--------------------------------------------------------------------------------------------
#include "agencyinclude.h"
//--------------------------------------------------------------------------------------------
// Function: createList()
// Purpose: Initializes a new linked list object
//
// Inputs: None
//
// Returns: (Success) Pointer to a linked list object
// (Failure) NULL if error creating list pointer
//
// Written by: Dave Wilson (initial design and code)
// Wyatt Jackson (comments and tweaks)
//--------------------------------------------------------------------------------------------
PLIST createList() {
PLIST objList = (PLIST) malloc(sizeof(LIST)); // Allocate memory for pointer
if (objList == NULL) {
return NULL; // Return NULL if memory wasn't allocated
}
objList->head = objList->tail = objList->current = NULL; // Set list head, tail, and current to NULL
objList->objcnt = 0; // Set list count to zero
return objList; // Return list pointer
}
//--------------------------------------------------------------------------------------------
// Function: addtoList(PLIST objList, POTYPE newObject, COMPARE Compare)
// Purpose: Adds a new object to the list based on the provided COMPARE function
//
// Inputs: PLIST objList - Pointer to list to add to
// POTYPE newObject - Object to be added
// COMPARE Compare - Function to use for comparison
// Compare return values: < 0 if object1 is less than object2
// = 0 if object1 is equal to object2
// > 0 if object1 is greater than object2
//
// Returns: (Success) 0 if new object added successfully
// (Failure) -1 if object failed COMPARE function and was not added
// -2 if unable to allocate memory for the new node
// -3 if a very bad thing happened - U.R.E. (unidentified runtime error)
//
// Written by: Dave Wilson (initial design and code)
// Wyatt Jackson (comments and tweaks)
//--------------------------------------------------------------------------------------------
int addtoList(PLIST objList, POTYPE newObject, COMPARE Compare) {
PNODE pNewNode;
if (checkforObject(objList, &newObject, Compare) > -2) {
return -1; // Object failed COMPARE function and was not added
}
// The head of the list exists add the new node to the end
if (objList->head != NULL) {
objList->current = objList->tail; // Set current object to list tail
pNewNode = (PNODE)malloc(sizeof(NODE)); // Allocate memory for the new node
if (pNewNode == NULL) {
return -2; // Unable to allocate memory for the new node
}
pNewNode->nextnode = NULL; // Set the next pointer to NULL to signify end of list
pNewNode->prevnode = objList->tail; // Set previous pointer to former end of list
pNewNode->object = newObject; // Associate the object with this node
objList->current->nextnode = pNewNode; // Set the new node to be the next in the current list
objList->tail = pNewNode; // Set the end of the curent list to point to this node
objList->current = pNewNode; // Set current node to this node
objList->objcnt++; // Icrement the list count by 1
return 0; // Everything super fine - we're good to go
}
// The head of the list doesn't exist set the new node to be the head
if (objList->head == NULL) {
pNewNode = (PNODE)malloc(sizeof(NODE)); // Allocate memory for the new node
if (pNewNode == NULL) {
return -2; // Unable to allocate memory for the new node
}
pNewNode->object = newObject; // Associate the object with this node
pNewNode->nextnode = NULL; // Initial Set to NULL
pNewNode->prevnode = NULL; // Initial Set to NULL
objList->head = pNewNode; // Set the new node to be the head of the current list
objList->tail = pNewNode; // Set the end of the curent list to point to this node
objList->current = pNewNode; // Set current node to this node
objList->objcnt++; // Icrement the list count by 1
return 0; // All systems go
}
return -3; // A very bad thing happened - U.R.E. (unidentified runtime error)
}
//--------------------------------------------------------------------------------------------
// Function: freeList(PLIST objList)
// Purpose: Frees memory used by the list
//
// Inputs: PLIST objList - Pointer to list to de-allocate
//
// Returns: (Success) 0 if list was de-allocated successfully
// (Failure) -1 if the function was passed a NULL list
// -2 if the end of the list is NULL (can't free NULL memory)
//
// Written by: Dave Wilson (initial design and code)
// Wyatt Jackson (comments and tweaks)
//--------------------------------------------------------------------------------------------
int freeList(PLIST objList){
if(objList == NULL) {
return -1; // The function was passed a NULL list
}
objList->current = objList->tail; // Set current node to point to the tail of the list
// Cycle through list draining it until the list count is zero
while (objList->objcnt != 0) {
objList->current = objList->tail->prevnode; // Set the current node to be the second to last node
if(objList->tail == NULL) {
return -2; // The end of the list is NULL (can't free NULL memory)
}
free(objList->tail); // De-allocate the end of the list
objList->tail = objList->current; // Set the end of the list to be the current node
objList->objcnt--; // Decrement the list count by 1
}
return 0; // Everything's Super!
}
//--------------------------------------------------------------------------------------------
// Function: dumpList(PLIST objList, EVALUATE Evaluate, int rate)
// Purpose: Dumps all objects to an evaluate function for printing and the like
//
// Inputs: PLIST objList - Pointer to list to dump
// EVALUATE Evaluate - Function to use for evaluation
// int rate - Rate at which to dump list (if <=0 no pause)
//
// Returns: (Success) 0 if list was successfully dumped
// (Failure) -1 if the function was passed a NULL list
// -2 if the evaluation function was NULL
// -3 if a very bad thing happened - U.R.E. (unidentified runtime error)
//
// Written by: Dave Wilson (initial design and code)
// Wyatt Jackson (comments and tweaks)
//--------------------------------------------------------------------------------------------
int dumpList(PLIST objList,EVALUATE Evaluate, int rate) {
int cnt = 0; // Set counter to zero
if(objList == NULL) {
return -1; // The function was passed a NULL list
}
objList->current = objList->head; // Set current node to the list head
if (Evaluate != NULL) {
// Cycle through each object in the list
while (cnt < objList->objcnt) {
Evaluate(&objList->current->object); // Run the object through the evaluate function
objList->current = objList->current->nextnode; // Set current node to the next node
cnt++; // Increment the counter by 1
if((rate > 0) && (cnt%rate == 0)) {
getch(); // Pause if rate was specified (may need to change according to UI structure)
}
}
}
else {
return -2; // The evaluation function was NULL
}
return 0; // It's all good
}
//--------------------------------------------------------------------------------------------
// Function: checkforObject(PLIST objList, PPOTYPE Object, COMPARE Compare)
// Purpose: Checks for an object in the given list and returns accordingly
//
// Inputs: PLIST objList - Pointer to list to dump
// PPOTYPE Object - Pointer to the object to check for
// COMPARE Compare - Function to use for comparison
// Compare return values: < 0 if object1 is less than object2
// = 0 if object1 is equal to object2
// > 0 if object1 is greater than object2
//
// Returns: (Success) i position of duplicate in list if Compare returns 0
// (Failure) -1 if the function was passed a NULL list
// -2 if no comparable object was found
//
// Written by: Dave Wilson (initial design and code)
// Wyatt Jackson (comments and tweaks)
//--------------------------------------------------------------------------------------------
int checkforObject(PLIST objList, PPOTYPE Object, COMPARE Compare){
int i = 0; // Initialize counter to zero
if(objList == NULL) {
return -1; // The function was passed a NULL list
}
objList->current = objList->head; // Set current node to the list head
// Cycle through objects and compare them
while(i < objList->objcnt) {
if(Compare != NULL) { //&& (Compare != (unsigned long)3435973836) && (Compare != (unsigned long)1836347904)) {
if (Compare(&objList->current->object,Object) == 0) {
return i; // position of duplicate in list if Compare returns 0
}
else {
objList->current = objList->current->nextnode; // Set current node to the next node in the list
}
}
i++; // Increment the counter
}
return -2; // No comparable object was found
}
//--------------------------------------------------------------------------------------------
// Function: findObject(PLIST objList, PPOTYPE Object, COMPARE Compare)
// Purpose: Finds an object in the current list and returns a pointer to it if found
//
// Inputs: PLIST objList - Pointer to list to search
// PPOTYPE Object - Pointer to the object to find
// COMPARE Compare - Function to use for comparison
// Compare return values: < 0 if object1 is less than object2
// = 0 if object1 is equal to object2
// > 0 if object1 is greater than object2
//
// Returns: (Success) PPOTYPE pointer to the object that was found
// (Failure) NULL if the function was passed a NULL list or no matching object was found
//
// Written by: Wyatt Jackson (initial design and comments)
//--------------------------------------------------------------------------------------------
PPOTYPE findObject(PLIST objList, PPOTYPE Object, COMPARE Compare){
int i = 0; // Initialize counter to zero
if(objList == NULL) {
return NULL; // The function was passed a NULL list
}
objList->current = objList->head; // Set current node to the list head
// Cycle through objects and compare them
while(i < objList->objcnt) {
if (Compare(&objList->current->object,Object) == 0){
return &objList->current->object; // Pointer to the object that was found
}
else {
objList->current = objList->current->nextnode; // Set current node to the next node in the list
}
i++; // Increment the counter
}
return NULL; // The object was not found
}
//--------------------------------------------------------------------------------------------
// Function: deleteObject(PLIST objList, PPOTYPE Object)
// Purpose: Deletes & frees an object in the given list
//
// Inputs: PLIST objList - Pointer to list the object to delete is in.
// PPOTYPE Object - Pointer to the object to delete.
//
// Returns: (Success) 0 Object was found, deleted, and freed. List reconnected.
// (Failure) -1 No List to search.
// -2 No pObject was found. Use findObject() first.
// -3 U.R.E (unidentified runtime error
//
//Written by: Dave Wilson (initial design and comments)
//--------------------------------------------------------------------------------------------
int deleteObject(PLIST pObjList, PPOTYPE pObject){
PNODE pPrevNode; //The node "prevnode" in the found object node
PNODE pNextNode; //The node "nextnode" in the found object node
PNODE pTempNode; //Node to be freed.
//List has nothing in it.
if (pObjList == NULL) {
return (-1);
}
//Start traversal of the list at head
pObjList->current = pObjList->head;
//Find the Object in the List.
while ((&(pObjList->current->object) != (pObject)) && (pObjList->current != NULL)) {
pObjList->current = pObjList->current->nextnode;
}
if (pObjList->current == NULL) {
return (-2);
}
pPrevNode = pObjList->current->prevnode;
pNextNode = pObjList->current->nextnode;
if ((pPrevNode == NULL) && (pNextNode == NULL) && (pObjList->current != NULL)) {
//The list consists of only one object
pTempNode = pObjList->current;
pObjList->current = NULL;
pObjList->head = NULL;
pObjList->tail = NULL;
pObjList->objcnt = 0;
memset(&pTempNode->object,0,sizeof(POTYPE)); //garbage collector
free(pTempNode);
return (0);
}
if (pPrevNode == NULL) { //pObjList->current->object is at the head
pTempNode = pObjList->current;
pObjList->current = pNextNode;
pObjList->current->prevnode = NULL;
pObjList->head = pObjList->current;
pObjList->objcnt--;
memset(&pTempNode->object,0,sizeof(POTYPE)); //garbage collector
free(pTempNode);
return (0);
}
if (pNextNode == NULL) { //pObjList->current->object is at the tail
pTempNode = pObjList->current;
pObjList->current = pPrevNode;
pObjList->current->nextnode = NULL;
pObjList->tail = pObjList->current;
pObjList->objcnt--;
memset(&pTempNode->object,0,sizeof(POTYPE)); //garbage collector
free(pTempNode);
return (0);
}
if ((pNextNode != NULL) && (pPrevNode != NULL) && (pObjList->current != NULL)) {
//Somewhere in the list other than head or tail
pTempNode = pObjList->current;
pObjList->current = pObjList->head; //done with current. reset!
pNextNode->prevnode = pPrevNode;
pPrevNode->nextnode = pNextNode;
pObjList->objcnt--;
memset(&pTempNode->object,0,sizeof(POTYPE)); //garbage collector
free(pTempNode);
return (0);
}
else
return (-3);
}
PNODE GetNextListEntry(PNODE previous)
{
if (previous->nextnode == NULL){
return NULL;
}
return previous->nextnode;
}
/*
void sortList(PLIST objlist, COMPARE Compare, SWAP InternalSwapFunction)
{
PLIST walker = objlist;
bool Sorted = true;
int RetValue;
int Counter = 0;
if(!Compare){
return;
}
if(objlist == NULL || objlist->objcnt < 2){
return;
}
do
{
Sorted = true; //ASSUME SORTED IS TRUE UNLESS OTHERWISE DISCOVERED.
for(walker->current = walker->head; walker->current->nextnode != NULL; walker->current = walker->current->nextnode, Counter++)
{
RetValue = Compare(&walker->current->object, &walker->current->nextnode->object);
//IF COMPARE RETURNS 0, EQUAL. OK.
//IF COMPARE RETURNS > 0, SECOND COMES AFTER FIRST. OK.
if(RetValue < 0 && walker->current && walker->current->nextnode){//IF COMPARE RETURNS < 0, FIRST COMES AFTER SECOND. BAD! SWAP.
Sorted = false; //WE'LL HAVE TO RUN THROUGH AGAIN.
if(InternalSwapFunction){
InternalSwapFunction(&walker->current->object, &walker->current->nextnode->object);
}
swapNodes(walker->current, walker->current->nextnode);
}
}
}while(!Sorted);
return;
}
void swapNodes(PNODE first, PNODE second)
{
if(second == NULL || first == NULL){
return;
}
first->nextnode = second->nextnode;
second->prevnode = first->prevnode;
first->prevnode = second;
second->nextnode = first;
//CHANGE THE BOUNDING NODES.
if(first->prevnode != NULL){
first->prevnode->nextnode = second;
}
if(second->nextnode != NULL){
second->nextnode->prevnode = first;
}
}
*/
void sortList(PLIST list, COMPARE SwapCompare, SWAP InternalSwapFunction, COMPARE ListInsertCompare)
{
if(!list || list->objcnt < 2){
return;
}
int i = 0;
PLIST Walker = list;
POTYPE Temp;
bool Sorted = true;
int RetValue;
int Counter = 0;
if(!SwapCompare || !ListInsertCompare){
return;
}
PPOTYPE Array = (PPOTYPE)malloc(sizeof(POTYPE) * list->objcnt); //ARRAY OF POTYPES
int ObjectCount = list->objcnt;
for(i = 0, Walker->current = Walker->head; i < ObjectCount, Walker->current != NULL; i++, Walker->current = Walker->current->nextnode){
if(Walker->current->prevnode){
deleteObject(list, &Walker->current->prevnode->object);
}
Array[i] = Walker->current->object;
}
deleteObject(list, &Walker->head->object);
//We have an array. Run through and swap the segments.
do
{
Sorted = true; //ASSUME SORTED IS TRUE UNLESS OTHERWISE DISCOVERED.
for(i= 0; i < ObjectCount - 1; i++)
{
RetValue = SwapCompare(&(Array[i]), &(Array[i+1]));
//IF COMPARE RETURNS 0, EQUAL. OK.
//IF COMPARE RETURNS > 0, SECOND COMES AFTER FIRST. OK.
if(RetValue < 0){//IF COMPARE RETURNS < 0, FIRST COMES AFTER SECOND. BAD! SWAP.
Sorted = false; //WE'LL HAVE TO RUN THROUGH AGAIN.
if(InternalSwapFunction){
InternalSwapFunction(&(Array[i]), &(Array[i+1]));
}
Temp = Array[i];
Array[i] = Array[i+1];
Array[i+1] = Temp;
}
}
}while(!Sorted);
//ARRAY IS SORTED. RE-INSERT INTO LIST.
for(i = 0; i < ObjectCount; i++){
Temp = Array[i];
addtoList(list, Temp, ListInsertCompare);
}
free(Array);
return;
} | true |
d664521bf15c2057e3d4bea00bc41dd45b76ed80 | C++ | djeemie2000/PlatformPlayground | /Common/libraries/Midi/CVMidiHandler.h | UTF-8 | 1,320 | 2.65625 | 3 | [] | no_license | #ifndef CVMIDIHANDLER_H_INCLUDE
#define CVMIDIHANDLER_H_INCLUDE
#include <mbed.h>
#include "MidiHandler.h"
#include "VoltageOut.h"
class CVMidiHandler : public MidiHandler
{
public:
CVMidiHandler(VoltageOut& cvPitch, VoltageOut& cvVelocity, DigitalOut& gateOut)
: m_cvPitch(cvPitch)
, m_cvVelocity(cvVelocity)
, m_gateOut(gateOut)
, m_Controller(128)
, m_OctaveOffset(-4)
{}
void NoteOn(uint8_t Channel, uint8_t MidiNote, uint8_t Velocity) /*override*/
{
int cv = MidiNote + 12*m_OctaveOffset;
m_cvPitch.WriteVoltage(cv/12.0f);
m_cvVelocity.WriteVoltage(Velocity/40.0f);//[0,128[ to [0.0,3.2[
m_gateOut = 1;
}
void NoteOff(uint8_t Channel, uint8_t MidiNote, uint8_t Velocity) /*override*/
{
m_gateOut = 0;
}
void ContinuousController(uint8_t Channel, uint8_t Controller, uint8_t Value)
{
// learn
if(m_Controller==128)
{
m_Controller = Controller;
}
if(m_Controller == Controller)
{
//assume all CC is voltage offset change
m_OctaveOffset = (Value>>3);//[0,15]
m_OctaveOffset -= 8;//[-8, +7]
}
}
private:
VoltageOut& m_cvPitch;
VoltageOut& m_cvVelocity;
DigitalOut& m_gateOut;
// octave offset
uint8_t m_Controller;//{128};
int m_OctaveOffset;//{-4};
};
#endif /* end of include guard: CVMIDIHANDLER_H_INCLUDE */
| true |
dc6701dbf5549179d9050cf03fcb583fe392e1f7 | C++ | HugoRamc/Distribuidosc- | /Parcial1/Practica1/programa1_2.cpp | UTF-8 | 870 | 3.75 | 4 | [] | no_license | //Equipo 1
//Ejercicio 2:
//Un error común difícil de detectar es dividir dos tipos de datos entero s o un entero con
//un tipo flotante. Elabore un programa para imprimir el resultado de una división entre dos enteros
//y de un entero con un flotante y determine cuál es el error que ocurre
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int ent1 = 20;
int ent2 = 8;
float flot1 = 4.22;
float flot2 = 36.44;
cout << "División de enteros " << ent1/ent2 << "\n";
cout << "División de flotantes " << flot2/flot1 << "\n";
cout << "Division de entero entre flotante "<< flot2/ent2 << "\n";
cout << "Division de flotante entre entero "<< ent1/flot1 << "\n";
//la division de dos enteros regresa un entero y trunca los decimales
//los flotantes conservan los decimales
return 0;
}
| true |
4116b7bf2fa73b90f033e6525dc374f272dbbdc2 | C++ | lpan18/3D-Chair-Generator | /ObjBuffer.cpp | UTF-8 | 10,979 | 2.90625 | 3 | [] | no_license | #include <Eigen/Geometry>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "ObjBuffer.h"
// Read Obj file to ObjBuffer
ObjBuffer ObjBuffer::readObjFile(string filename) {
string line;
int vn = 0, fm = 0;
// Read the file and get the numbers of vertices and faces.
ifstream fin(filename);
while (getline(fin, line)) {
if (line.length() > 1) {
if (line[0] == 'v' && line[1] == ' ') {
vn++;
}
else if (line[0] == 'f' && line[1] == ' ') {
fm++;
}
}
}
ObjBuffer buffer;
buffer.nVertices = vn;
buffer.mFaces = fm;
buffer.vertices = new Vector3f[buffer.nVertices];
buffer.faces = new Vector3i[buffer.mFaces];
// read the file again.
ifstream fin1(filename);
int vi = 0, fi = 0;
float x, y, z;
int v1, v2, v3;
while (getline(fin1, line)) {
if (line.length() > 0) {
if (line[0] == 'v' && line[1] == ' ') {
string str = line.substr(2, line.size() - 1);
istringstream iss(str);
iss >> x >> y >> z;
buffer.vertices[vi] = Vector3f(x, y, z);
vi++;
} else if (line[0] == 'f' && line[1] == ' ') {
string str = line.substr(2, line.size() - 1);
istringstream iss(str);
iss >> v1 >> v2 >> v3;
buffer.faces[fi] = Vector3i(v1, v2, v3);
fi++;
} else if (line.rfind("# Starting mesh", 0) == 0) {
ObjGroup group;
istringstream iss(line);
string temp, name;
iss >> temp >> temp >> temp >> name;
group.name = name;
transform(group.name.begin(), group.name.end(), group.name.begin(), ::tolower);
group.vStart = vi;
buffer.groups.push_back(group);
} else if (line.rfind("g ", 0) == 0) {
buffer.groups.back().vEnd = vi - 1;
buffer.groups.back().fStart = fi;
} else if (line.rfind("# End of mesh", 0) == 0) {
buffer.groups.back().fEnd = fi - 1;
}
}
}
// Set Center and Scale
buffer.resetBound();
return buffer;
}
ObjBuffer ObjBuffer::combineObjBuffers(vector<ObjBuffer*> objBuffers) {
ObjBuffer buffer;
// First, get vCount and fCount and initialize buffer
int vCount = 0;
int fCount = 0;
for (auto b : objBuffers) {
vCount += b->nVertices;
fCount += b->mFaces;
}
buffer.nVertices = vCount;
buffer.mFaces = fCount;
buffer.vertices = new Vector3f[vCount];
buffer.faces = new Vector3i[fCount];
// Iterate objBuffers again for vertices and faces
int vi = 0;
int fi = 0;
for (auto b : objBuffers) {
int viOffset = vi;
for (int i = 0; i < b->nVertices; i++) {
buffer.vertices[vi] = b->vertices[i];
vi++;
}
for (int i = 0; i < b->mFaces; i++) {
buffer.faces[fi] = b->faces[i] + Vector3i(viOffset, viOffset, viOffset);
fi++;
}
}
// Reset vertices and faces for objBuffers
Vector3f* vCurrent = buffer.vertices;
Vector3i* fCurrent = buffer.faces;
for (auto b : objBuffers) {
b->vertices = vCurrent;
b->faces = fCurrent;
vCurrent += b->nVertices;
fCurrent += b->mFaces;
}
buffer.resetBound();
return buffer;
}
ObjBuffer ObjBuffer::getGroup(string groupName) {
ObjBuffer buffer;
// First, get vCount and fCount and initialize buffer
int vCount = 0;
int fCount = 0;
for (auto g : groups) {
if (g.name.rfind(groupName, 0) == 0) {
vCount += g.vEnd - g.vStart + 1;
fCount += g.fEnd - g.fStart + 1;
}
}
buffer.nVertices = vCount;
buffer.mFaces = fCount;
buffer.vertices = new Vector3f[vCount];
buffer.faces = new Vector3i[fCount];
// Iterate groups again for vertices and faces
int vi = 0;
int fi = 0;
for (auto g : groups) {
if (g.name.rfind(groupName, 0) == 0) {
int viOffset = g.vStart - vi;
for (int i = g.vStart; i <= g.vEnd; i++) {
buffer.vertices[vi] = vertices[i];
vi++;
}
for (int i = g.fStart; i <= g.fEnd; i++) {
buffer.faces[fi] = faces[i] - Vector3i(viOffset, viOffset, viOffset);
fi++;
}
}
}
buffer.resetBound();
return buffer;
}
void ObjBuffer::free() {
delete []vertices;
delete []faces;
}
void ObjBuffer::resetBound() {
float maxX, maxY, maxZ;
float minX, minY, minZ;
maxX = maxY = maxZ = -MAXVALUE;
minX = minY = minZ = MAXVALUE;
for (int i = 0; i < nVertices; i++) {
maxX = vertices[i].x() > maxX ? vertices[i].x() : maxX;
maxY = vertices[i].y() > maxY ? vertices[i].y() : maxY;
maxZ = vertices[i].z() > maxZ ? vertices[i].z() : maxZ;
minX = vertices[i].x() < minX ? vertices[i].x() : minX;
minY = vertices[i].y() < minY ? vertices[i].y() : minY;
minZ = vertices[i].z() < minZ ? vertices[i].z() : minZ;
}
bound.maxX = maxX;
bound.maxY = maxY;
bound.maxZ = maxZ;
bound.minX = minX;
bound.minY = minY;
bound.minZ = minZ;
}
float getDist(Vector3f vt, Vector3f p){
Vector3f dvt = vt - p;
return dvt.x() * dvt.x() + dvt.y() * dvt.y() + dvt.z() * dvt.z();
}
// get closest point(compared to vertices and center of face) to p
Vector3f ObjBuffer::getClosestPointTo(Vector3f p) {
float minDistQuad = MAXVALUE;
Vector3f pc;
for (int i = 0; i < nVertices; i++) {
float distQuad = getDist(vertices[i], p);
if (distQuad < minDistQuad) {
minDistQuad = distQuad;
pc = vertices[i];
}
}
//cout << "size" << vertices->size() << endl;
//for (int i = 0; i < mFaces; i++) {
// Vector3i f = faces[i];
// //cout << f[0] - 1 << endl;
// Vector3f vt0 = vertices[f[0] - 1];
// Vector3f vt1 = vertices[f[1] - 1];
// Vector3f vt2 = vertices[f[2] - 1];
// Vector3f vt_center = (vt0 + vt1 + vt2) / 3.0f;
// float dist_center = getDist(vt_center, p);
// if (dist_center < minDistQuad) {
// minDistQuad = dist_center;
// pc = vt_center;
// }
//}
return pc;
}
ChairPartOrigSeatFeatures ChairPartOrigSeatFeatures::fromSeat(ObjBuffer& seat) {
seat.resetBound();
ChairPartOrigSeatFeatures features;
ObjBound bound = seat.bound;
Vector3f center = bound.getCenter();
features.backTopCenter = Vector3f(center.x(), bound.maxY, bound.maxZ);
features.topCenter = Vector3f(center.x(), center.y(), bound.maxZ);
features.bottomCenter = Vector3f(center.x(), center.y(), bound.minZ);
features.width = bound.maxX - bound.minX;
features.depth = bound.maxY - bound.minY;
return features;
}
Vector3f ChairPartOrigSeatFeatures::transform(Matrix3f scale, Vector3f v, Vector3f oldBase, Vector3f newBase) {
Vector3f offset = v - oldBase;
return scale * offset + newBase;
}
ChairPartBuffer ChairPartBuffer::fromSeat(ObjBuffer& seat) {
ChairPartBuffer seat1;
seat1.nVertices = seat.nVertices;
seat1.mFaces = seat.mFaces;
seat1.vertices = seat.vertices;
seat1.faces = seat.faces;
seat1.bound = seat.bound;
seat1.origSeatFeatures = ChairPartOrigSeatFeatures::fromSeat(seat1);
seat1.resetPartFeatures();
return seat1;
}
ChairPartBuffer ChairPartBuffer::fromPart(ObjBuffer& part, ChairPartBuffer& seat) {
ChairPartBuffer part1;
part1.nVertices = part.nVertices;
part1.mFaces = part.mFaces;
part1.vertices = part.vertices;
part1.faces = part.faces;
part1.bound = part.bound;
part1.origSeatFeatures = seat.origSeatFeatures;
part1.resetPartFeatures();
return part1;
}
Vector3f ChairPartBuffer::getFeature(float x, float y, float z) {
Vector3f feature;
float minError = MAXVALUE;
Vector3f v;
float error;
for (int i = 0; i < nVertices; i++) {
v = vertices[i];
error = abs(v.x() - x) + 2 * abs(v.y() - y) + 3 * abs(v.z() - z);
if (error < minError) {
feature = v;
minError = error;
}
}
return feature;
}
void ChairPartBuffer::resetPartFeatures() {
resetBound();
if (nVertices > 0) {
partFeatures.topRightBack = getFeature(bound.minX, bound.maxY, bound.maxZ);
partFeatures.topRightFront = getFeature(bound.minX, bound.minY, bound.maxZ);
partFeatures.topLeftFront = getFeature(bound.maxX, bound.minY, bound.maxZ);
partFeatures.topLeftBack = getFeature(bound.maxX, bound.maxY, bound.maxZ);
partFeatures.bottomRightBack = getFeature(bound.minX, bound.maxY, bound.minZ);
partFeatures.bottomRightFront = getFeature(bound.minX, bound.minY, bound.minZ);
partFeatures.bottomLeftFront = getFeature(bound.maxX, bound.minY, bound.minZ);
partFeatures.bottomLeftBack = getFeature(bound.maxX, bound.maxY, bound.minZ);
} else {
partFeatures.topRightBack =
partFeatures.topRightFront =
partFeatures.topLeftFront =
partFeatures.topLeftBack =
partFeatures.bottomRightBack =
partFeatures.bottomRightFront =
partFeatures.bottomLeftFront =
partFeatures.bottomLeftBack = Vector3f::Zero();
}
}
Vector3f ChairPartBuffer::getTransformed(Vector3f pb, Vector3f p0, Vector3f p1, Vector3f v) {
Vector3f offsetbase = p1 - p0;
float v1x = v.x() + offsetbase.x();
float v1y = v.y() + offsetbase.y();
float scaleZ = (p1.z() - pb.z()) / (p0.z() - pb.z());
float v1z = (v.z() - pb.z()) * scaleZ + pb.z();
return Vector3f(v1x, v1y, v1z);
}
void ChairPartBuffer::transformSingle(Vector3f pb, Vector3f p0, Vector3f p1) {
for (int i = 0; i < nVertices; i++) {
vertices[i] = getTransformed(pb, p0, p1, vertices[i]);
}
}
Vector3f ChairPartBuffer::getTransformedXSym(Vector3f pb, Vector3f p0, Vector3f p1, Vector3f v, bool whetherScaleZ) {
Vector3f offsetbase = p1 - p0;
float v1x = v.x() + (pb.x() - v.x()) / (pb.x() - p0.x()) * offsetbase.x();
float v1y = v.y() + offsetbase.y();
float scaleZ = whetherScaleZ ? ((p1.z() - pb.z()) / (p0.z() - pb.z())) : 1;
float v1z = (v.z() - pb.z()) * scaleZ + pb.z();
return Vector3f(v1x, v1y, v1z);
}
void ChairPartBuffer::transformSingleXSym(Vector3f pb, Vector3f p0, Vector3f p1) {
for (int i = 0; i < nVertices; i++) {
vertices[i] = getTransformedXSym(pb, p0, p1, vertices[i]);
}
}
void ChairPartBuffer::transformDouleXSym(Vector3f pb, Vector3f p0, Vector3f p1, Vector3f q0, Vector3f q1, bool whetherScaleZ) {
for (int i = 0; i < nVertices; i++) {
Vector3f vp = getTransformedXSym(pb, p0, p1, vertices[i], whetherScaleZ);
Vector3f vq = getTransformedXSym(pb, q0, q1, vertices[i], whetherScaleZ);
float wp = vertices[i].y() > p0.y() ? 1.0f :
vertices[i].y() < q0.y() ? 0.0f :
(vertices[i].y() - q0.y()) / (p0.y() - q0.y());
vertices[i] = vp * wp + vq * (1.0f - wp);
}
}
void ChairPartBuffer::align(Vector3f p_target) {
Vector3f pb(bound.getCenter().x(), bound.getCenter().y(), bound.getCenter().z());
float offsetX = p_target.x() - pb.x();
float offsetY = p_target.y() - pb.y();
for (int i = 0; i < nVertices; i++) {
vertices[i].x() += offsetX;
vertices[i].y() += offsetY;
}
}
ChairBuffer ChairBuffer::readObjFile(string fileName) {
ObjBuffer chair = ObjBuffer::readObjFile(fileName);
ObjBuffer seat = chair.getGroup("seat");
ObjBuffer leg = chair.getGroup("leg");
ObjBuffer back = chair.getGroup("back");
ObjBuffer arm = chair.getGroup("arm");
ChairBuffer chairBuffer;
chairBuffer.chair = chair;
chairBuffer.seat = ChairPartBuffer::fromSeat(seat);
chairBuffer.leg = ChairPartBuffer::fromPart(leg, chairBuffer.seat);
chairBuffer.back = ChairPartBuffer::fromPart(back, chairBuffer.seat);
chairBuffer.arm = ChairPartBuffer::fromPart(arm, chairBuffer.seat);
return chairBuffer;
}
void ChairBuffer::free() {
arm.free();
back.free();
leg.free();
seat.free();
chair.free();
} | true |
676b9e0bd9789b03a413f76a373ce059144bf53c | C++ | OuO-language/ouolang | /ouo/mpc.cpp | UTF-8 | 93,653 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "mpc.h"
/*
** State Type
*/
static mpc_state_t mpc_state_invalid(void) {
mpc_state_t s;
s.pos = -1;
s.row = -1;
s.col = -1;
return s;
}
static mpc_state_t mpc_state_new(void) {
mpc_state_t s;
s.pos = 0;
s.row = 0;
s.col = 0;
return s;
}
static mpc_state_t *mpc_state_copy(mpc_state_t s) {
mpc_state_t *r = (mpc_state_t *)malloc(sizeof(mpc_state_t));
memcpy(r, &s, sizeof(mpc_state_t));
return r;
}
/*
** Error Type
*/
static mpc_err_t *mpc_err_new(const char *filename, mpc_state_t s, const char *expected, char recieved) {
mpc_err_t *x = (mpc_err_t *)malloc(sizeof(mpc_err_t));
x->filename = (char *)malloc(strlen(filename) + 1);
strcpy(x->filename, filename);
x->state = s;
x->expected_num = 1;
x->expected = (char **)malloc(sizeof(char*));
x->expected[0] = (char *)malloc(strlen(expected) + 1);
strcpy(x->expected[0], expected);
x->failure = NULL;
x->recieved = recieved;
return x;
}
static mpc_err_t *mpc_err_fail(const char *filename, mpc_state_t s, const char *failure) {
mpc_err_t *x = (mpc_err_t *)malloc(sizeof(mpc_err_t));
x->filename = (char *)malloc(strlen(filename) + 1);
strcpy(x->filename, filename);
x->state = s;
x->expected_num = 0;
x->expected = NULL;
x->failure = (char *)malloc(strlen(failure) + 1);
strcpy(x->failure, failure);
x->recieved = ' ';
return x;
}
void mpc_err_delete(mpc_err_t *x) {
int i;
for (i = 0; i < x->expected_num; i++) {
free(x->expected[i]);
}
free(x->expected);
free(x->filename);
free(x->failure);
free(x);
}
static int mpc_err_contains_expected(mpc_err_t *x, char *expected) {
int i;
for (i = 0; i < x->expected_num; i++) {
if (strcmp(x->expected[i], expected) == 0) { return 1; }
}
return 0;
}
static void mpc_err_add_expected(mpc_err_t *x, char *expected) {
x->expected_num++;
x->expected = (char **)realloc(x->expected, sizeof(char*) * x->expected_num);
x->expected[x->expected_num-1] = (char *)malloc(strlen(expected) + 1);
strcpy(x->expected[x->expected_num-1], expected);
}
static void mpc_err_clear_expected(mpc_err_t *x, char *expected) {
int i;
for (i = 0; i < x->expected_num; i++) {
free(x->expected[i]);
}
x->expected_num = 1;
x->expected = (char **)realloc(x->expected, sizeof(char*) * x->expected_num);
x->expected[0] = (char *)malloc(strlen(expected) + 1);
strcpy(x->expected[0], expected);
}
void mpc_err_print(mpc_err_t *x) {
mpc_err_print_to(x, stdout);
}
void mpc_err_print_to(mpc_err_t *x, FILE *f) {
char *str = mpc_err_string(x);
fprintf(f, "%s", str);
free(str);
}
void mpc_err_string_cat(char *buffer, int *pos, int *max, char const *fmt, ...) {
/* TODO: Error Checking on Length */
int left = ((*max) - (*pos));
va_list va;
va_start(va, fmt);
if (left < 0) { left = 0;}
(*pos) += vsprintf(buffer + (*pos), fmt, va);
va_end(va);
}
static char char_unescape_buffer[4];
static const char *mpc_err_char_unescape(char c) {
char_unescape_buffer[0] = '\'';
char_unescape_buffer[1] = ' ';
char_unescape_buffer[2] = '\'';
char_unescape_buffer[3] = '\0';
switch (c) {
case '\a': return "bell";
case '\b': return "backspace";
case '\f': return "formfeed";
case '\r': return "carriage return";
case '\v': return "vertical tab";
case '\0': return "end of input";
case '\n': return "newline";
case '\t': return "tab";
case ' ' : return "space";
default:
char_unescape_buffer[1] = c;
return char_unescape_buffer;
}
}
char *mpc_err_string(mpc_err_t *x) {
int i;
int pos = 0;
int max = 1023;
char *buffer = (char *)calloc(1, 1024);
if (x->failure) {
mpc_err_string_cat(buffer, &pos, &max,
"%s: error: %s\n", x->filename, x->failure);
return buffer;
}
mpc_err_string_cat(buffer, &pos, &max,
"%s:%i:%i: error: expected ", x->filename, x->state.row+1, x->state.col+1);
if (x->expected_num == 0) { mpc_err_string_cat(buffer, &pos, &max, "ERROR: NOTHING EXPECTED"); }
if (x->expected_num == 1) { mpc_err_string_cat(buffer, &pos, &max, "%s", x->expected[0]); }
if (x->expected_num >= 2) {
for (i = 0; i < x->expected_num-2; i++) {
mpc_err_string_cat(buffer, &pos, &max, "%s, ", x->expected[i]);
}
mpc_err_string_cat(buffer, &pos, &max, "%s or %s",
x->expected[x->expected_num-2],
x->expected[x->expected_num-1]);
}
mpc_err_string_cat(buffer, &pos, &max, " at ");
mpc_err_string_cat(buffer, &pos, &max, mpc_err_char_unescape(x->recieved));
mpc_err_string_cat(buffer, &pos, &max, "\n");
return (char *)realloc(buffer, strlen(buffer) + 1);
}
static mpc_err_t *mpc_err_or(mpc_err_t** x, int n) {
int i, j;
mpc_err_t *e = (mpc_err_t *)malloc(sizeof(mpc_err_t));
e->state = mpc_state_invalid();
e->expected_num = 0;
e->expected = NULL;
e->failure = NULL;
e->filename = (char *)malloc(strlen(x[0]->filename)+1);
strcpy(e->filename, x[0]->filename);
for (i = 0; i < n; i++) {
if (x[i]->state.pos > e->state.pos) { e->state = x[i]->state; }
}
for (i = 0; i < n; i++) {
if (x[i]->state.pos < e->state.pos) { continue; }
if (x[i]->failure) {
e->failure = (char *)malloc(strlen(x[i]->failure)+1);
strcpy(e->failure, x[i]->failure);
break;
}
e->recieved = x[i]->recieved;
for (j = 0; j < x[i]->expected_num; j++) {
if (!mpc_err_contains_expected(e, x[i]->expected[j])) { mpc_err_add_expected(e, x[i]->expected[j]); }
}
}
for (i = 0; i < n; i++) {
mpc_err_delete(x[i]);
}
return e;
}
static mpc_err_t *mpc_err_repeat(mpc_err_t *x, const char *prefix) {
int i;
char *expect = (char *)malloc(strlen(prefix) + 1);
strcpy(expect, prefix);
if (x->expected_num == 1) {
expect = (char *)realloc(expect, strlen(expect) + strlen(x->expected[0]) + 1);
strcat(expect, x->expected[0]);
}
if (x->expected_num > 1) {
for (i = 0; i < x->expected_num-2; i++) {
expect = (char *)realloc(expect, strlen(expect) + strlen(x->expected[i]) + strlen(", ") + 1);
strcat(expect, x->expected[i]);
strcat(expect, ", ");
}
expect = (char *)realloc(expect, strlen(expect) + strlen(x->expected[x->expected_num-2]) + strlen(" or ") + 1);
strcat(expect, x->expected[x->expected_num-2]);
strcat(expect, " or ");
expect = (char *)realloc(expect, strlen(expect) + strlen(x->expected[x->expected_num-1]) + 1);
strcat(expect, x->expected[x->expected_num-1]);
}
mpc_err_clear_expected(x, expect);
free(expect);
return x;
}
static mpc_err_t *mpc_err_many1(mpc_err_t *x) {
return mpc_err_repeat(x, "one or more of ");
}
static mpc_err_t *mpc_err_count(mpc_err_t *x, int n) {
mpc_err_t *y;
int digits = n/10 + 1;
char *prefix = (char *)malloc(digits + strlen(" of ") + 1);
sprintf(prefix, "%i of ", n);
y = mpc_err_repeat(x, prefix);
free(prefix);
return y;
}
/*
** Input Type
*/
/*
** In mpc the input type has three modes of
** operation: String, File and Pipe.
**
** String is easy. The whole contents are
** loaded into a buffer and scanned through.
** The cursor can jump around at will making
** backtracking easy.
**
** The second is a File which is also somewhat
** easy. The contents are never loaded into
** memory but backtracking can still be achieved
** by seeking in the file at different positions.
**
** The final mode is Pipe. This is the difficult
** one. As we assume pipes cannot be seeked - and
** only support a single character lookahead at
** any point, when the input is marked for a
** potential backtracking we start buffering any
** input.
**
** This means that if we are requested to seek
** back we can simply start reading from the
** buffer instead of the input.
**
** Of course using `mpc_predictive` will disable
** backtracking and make LL(1) grammars easy
** to parse for all input methods.
**
*/
enum {
MPC_INPUT_STRING = 0,
MPC_INPUT_FILE = 1,
MPC_INPUT_PIPE = 2
};
typedef struct {
int type;
char *filename;
mpc_state_t state;
char *string;
char *buffer;
FILE *file;
int backtrack;
int marks_slots;
int marks_num;
mpc_state_t* marks;
char* lasts;
char last;
} mpc_input_t;
enum {
MPC_INPUT_MARKS_MIN = 32
};
static mpc_input_t *mpc_input_new_string(const char *filename, const char *string) {
mpc_input_t *i = (mpc_input_t *)malloc(sizeof(mpc_input_t));
i->filename = (char *)malloc(strlen(filename) + 1);
strcpy(i->filename, filename);
i->type = MPC_INPUT_STRING;
i->state = mpc_state_new();
i->string = (char *)malloc(strlen(string) + 1);
strcpy(i->string, string);
i->buffer = NULL;
i->file = NULL;
i->backtrack = 1;
i->marks_num = 0;
i->marks_slots = MPC_INPUT_MARKS_MIN;
i->marks = (mpc_state_t *)malloc(sizeof(mpc_state_t) * i->marks_slots);
i->lasts = (char *)malloc(sizeof(char) * i->marks_slots);
i->last = '\0';
return i;
}
static mpc_input_t *mpc_input_new_pipe(const char *filename, FILE *pipe) {
mpc_input_t *i = (mpc_input_t *)malloc(sizeof(mpc_input_t));
i->filename = (char *)malloc(strlen(filename) + 1);
strcpy(i->filename, filename);
i->type = MPC_INPUT_PIPE;
i->state = mpc_state_new();
i->string = NULL;
i->buffer = NULL;
i->file = pipe;
i->backtrack = 1;
i->marks_num = 0;
i->marks_slots = MPC_INPUT_MARKS_MIN;
i->marks = (mpc_state_t *)malloc(sizeof(mpc_state_t) * i->marks_slots);
i->lasts = (char *)malloc(sizeof(char) * i->marks_slots);
i->last = '\0';
return i;
}
static mpc_input_t *mpc_input_new_file(const char *filename, FILE *file) {
mpc_input_t *i = (mpc_input_t *)malloc(sizeof(mpc_input_t));
i->filename = (char *)malloc(strlen(filename) + 1);
strcpy(i->filename, filename);
i->type = MPC_INPUT_FILE;
i->state = mpc_state_new();
i->string = NULL;
i->buffer = NULL;
i->file = file;
i->backtrack = 1;
i->marks_num = 0;
i->marks_slots = MPC_INPUT_MARKS_MIN;
i->marks = (mpc_state_t *)malloc(sizeof(mpc_state_t) * i->marks_slots);
i->lasts = (char *)malloc(sizeof(char) * i->marks_slots);
i->last = '\0';
return i;
}
static void mpc_input_delete(mpc_input_t *i) {
free(i->filename);
if (i->type == MPC_INPUT_STRING) { free(i->string); }
if (i->type == MPC_INPUT_PIPE) { free(i->buffer); }
free(i->marks);
free(i->lasts);
free(i);
}
static void mpc_input_backtrack_disable(mpc_input_t *i) { i->backtrack--; }
static void mpc_input_backtrack_enable(mpc_input_t *i) { i->backtrack++; }
static void mpc_input_mark(mpc_input_t *i) {
if (i->backtrack < 1) { return; }
i->marks_num++;
if (i->marks_num > i->marks_slots) {
i->marks_slots = i->marks_num + i->marks_num / 2;
i->marks = (mpc_state_t *)realloc(i->marks, sizeof(mpc_state_t) * i->marks_slots);
i->lasts = (char *)realloc(i->lasts, sizeof(char) * i->marks_slots);
}
i->marks[i->marks_num-1] = i->state;
i->lasts[i->marks_num-1] = i->last;
if (i->type == MPC_INPUT_PIPE && i->marks_num == 1) {
i->buffer = (char *)calloc(1, 1);
}
}
static void mpc_input_unmark(mpc_input_t *i) {
if (i->backtrack < 1) { return; }
i->marks_num--;
if (i->marks_slots > i->marks_num + i->marks_num / 2
&& i->marks_slots > MPC_INPUT_MARKS_MIN) {
i->marks_slots =
i->marks_num > MPC_INPUT_MARKS_MIN ?
i->marks_num : MPC_INPUT_MARKS_MIN;
i->marks = (mpc_state_t *)realloc(i->marks, sizeof(mpc_state_t) * i->marks_slots);
i->lasts = (char *)realloc(i->lasts, sizeof(char) * i->marks_slots);
}
if (i->type == MPC_INPUT_PIPE && i->marks_num == 0) {
free(i->buffer);
i->buffer = NULL;
}
}
static void mpc_input_rewind(mpc_input_t *i) {
if (i->backtrack < 1) { return; }
i->state = i->marks[i->marks_num-1];
i->last = i->lasts[i->marks_num-1];
if (i->type == MPC_INPUT_FILE) {
fseek(i->file, i->state.pos, SEEK_SET);
}
mpc_input_unmark(i);
}
static int mpc_input_buffer_in_range(mpc_input_t *i) {
return i->state.pos < (long)(strlen(i->buffer) + i->marks[0].pos);
}
static char mpc_input_buffer_get(mpc_input_t *i) {
return i->buffer[i->state.pos - i->marks[0].pos];
}
static int mpc_input_terminated(mpc_input_t *i) {
if (i->type == MPC_INPUT_STRING && i->state.pos == (long)strlen(i->string)) { return 1; }
if (i->type == MPC_INPUT_FILE && feof(i->file)) { return 1; }
if (i->type == MPC_INPUT_PIPE && feof(i->file)) { return 1; }
return 0;
}
static char mpc_input_getc(mpc_input_t *i) {
char c = '\0';
switch (i->type) {
case MPC_INPUT_STRING: return i->string[i->state.pos];
case MPC_INPUT_FILE: c = fgetc(i->file); return c;
case MPC_INPUT_PIPE:
if (!i->buffer) { c = getc(i->file); return c; }
if (i->buffer && mpc_input_buffer_in_range(i)) {
c = mpc_input_buffer_get(i);
return c;
} else {
c = getc(i->file);
return c;
}
default: return c;
}
}
static char mpc_input_peekc(mpc_input_t *i) {
char c = '\0';
switch (i->type) {
case MPC_INPUT_STRING: return i->string[i->state.pos];
case MPC_INPUT_FILE:
c = fgetc(i->file);
if (feof(i->file)) { return '\0'; }
fseek(i->file, -1, SEEK_CUR);
return c;
case MPC_INPUT_PIPE:
if (!i->buffer) {
c = getc(i->file);
if (feof(i->file)) { return '\0'; }
ungetc(c, i->file);
return c;
}
if (i->buffer && mpc_input_buffer_in_range(i)) {
return mpc_input_buffer_get(i);
} else {
c = getc(i->file);
if (feof(i->file)) { return '\0'; }
ungetc(c, i->file);
return c;
}
default: return c;
}
}
static int mpc_input_failure(mpc_input_t *i, char c) {
switch (i->type) {
case MPC_INPUT_STRING: { break; }
case MPC_INPUT_FILE: fseek(i->file, -1, SEEK_CUR); { break; }
case MPC_INPUT_PIPE: {
if (!i->buffer) { ungetc(c, i->file); break; }
if (i->buffer && mpc_input_buffer_in_range(i)) {
break;
} else {
ungetc(c, i->file);
}
}
default: { break; }
}
return 0;
}
static int mpc_input_success(mpc_input_t *i, char c, char **o) {
if (i->type == MPC_INPUT_PIPE &&
i->buffer &&
!mpc_input_buffer_in_range(i)) {
i->buffer = (char *)realloc(i->buffer, strlen(i->buffer) + 2);
i->buffer[strlen(i->buffer) + 1] = '\0';
i->buffer[strlen(i->buffer) + 0] = c;
}
i->last = c;
i->state.pos++;
i->state.col++;
if (c == '\n') {
i->state.col = 0;
i->state.row++;
}
if (o) {
(*o) = (char *)malloc(2);
(*o)[0] = c;
(*o)[1] = '\0';
}
return 1;
}
static int mpc_input_any(mpc_input_t *i, char **o) {
char x = mpc_input_getc(i);
if (mpc_input_terminated(i)) { return 0; }
return mpc_input_success(i, x, o);
}
static int mpc_input_char(mpc_input_t *i, char c, char **o) {
char x = mpc_input_getc(i);
if (mpc_input_terminated(i)) { return 0; }
return x == c ? mpc_input_success(i, x, o) : mpc_input_failure(i, x);
}
static int mpc_input_range(mpc_input_t *i, char c, char d, char **o) {
char x = mpc_input_getc(i);
if (mpc_input_terminated(i)) { return 0; }
return x >= c && x <= d ? mpc_input_success(i, x, o) : mpc_input_failure(i, x);
}
static int mpc_input_oneof(mpc_input_t *i, const char *c, char **o) {
char x = mpc_input_getc(i);
if (mpc_input_terminated(i)) { return 0; }
return strchr(c, x) != 0 ? mpc_input_success(i, x, o) : mpc_input_failure(i, x);
}
static int mpc_input_noneof(mpc_input_t *i, const char *c, char **o) {
char x = mpc_input_getc(i);
if (mpc_input_terminated(i)) { return 0; }
return strchr(c, x) == 0 ? mpc_input_success(i, x, o) : mpc_input_failure(i, x);
}
static int mpc_input_satisfy(mpc_input_t *i, int(*cond)(char), char **o) {
char x = mpc_input_getc(i);
if (mpc_input_terminated(i)) { return 0; }
return cond(x) ? mpc_input_success(i, x, o) : mpc_input_failure(i, x);
}
static int mpc_input_string(mpc_input_t *i, const char *c, char **o) {
char *co = NULL;
const char *x = c;
mpc_input_mark(i);
while (*x) {
if (mpc_input_char(i, *x, &co)) {
free(co);
} else {
mpc_input_rewind(i);
return 0;
}
x++;
}
mpc_input_unmark(i);
*o = (char *)malloc(strlen(c) + 1);
strcpy(*o, c);
return 1;
}
static int mpc_input_anchor(mpc_input_t* i, int(*f)(char,char)) {
return f(i->last, mpc_input_peekc(i));
}
/*
** Parser Type
*/
enum {
MPC_TYPE_UNDEFINED = 0,
MPC_TYPE_PASS = 1,
MPC_TYPE_FAIL = 2,
MPC_TYPE_LIFT = 3,
MPC_TYPE_LIFT_VAL = 4,
MPC_TYPE_EXPECT = 5,
MPC_TYPE_ANCHOR = 6,
MPC_TYPE_STATE = 7,
MPC_TYPE_ANY = 8,
MPC_TYPE_SINGLE = 9,
MPC_TYPE_ONEOF = 10,
MPC_TYPE_NONEOF = 11,
MPC_TYPE_RANGE = 12,
MPC_TYPE_SATISFY = 13,
MPC_TYPE_STRING = 14,
MPC_TYPE_APPLY = 15,
MPC_TYPE_APPLY_TO = 16,
MPC_TYPE_PREDICT = 17,
MPC_TYPE_NOT = 18,
MPC_TYPE_MAYBE = 19,
MPC_TYPE_MANY = 20,
MPC_TYPE_MANY1 = 21,
MPC_TYPE_COUNT = 22,
MPC_TYPE_OR = 23,
MPC_TYPE_AND = 24
};
typedef struct { char *m; } mpc_pdata_fail_t;
typedef struct { mpc_ctor_t lf; void *x; } mpc_pdata_lift_t;
typedef struct { mpc_parser_t *x; char *m; } mpc_pdata_expect_t;
typedef struct { int(*f)(char,char); } mpc_pdata_anchor_t;
typedef struct { char x; } mpc_pdata_single_t;
typedef struct { char x; char y; } mpc_pdata_range_t;
typedef struct { int(*f)(char); } mpc_pdata_satisfy_t;
typedef struct { char *x; } mpc_pdata_string_t;
typedef struct { mpc_parser_t *x; mpc_apply_t f; } mpc_pdata_apply_t;
typedef struct { mpc_parser_t *x; mpc_apply_to_t f; void *d; } mpc_pdata_apply_to_t;
typedef struct { mpc_parser_t *x; } mpc_pdata_predict_t;
typedef struct { mpc_parser_t *x; mpc_dtor_t dx; mpc_ctor_t lf; } mpc_pdata_not_t;
typedef struct { int n; mpc_fold_t f; mpc_parser_t *x; mpc_dtor_t dx; } mpc_pdata_repeat_t;
typedef struct { int n; mpc_parser_t **xs; } mpc_pdata_or_t;
typedef struct { int n; mpc_fold_t f; mpc_parser_t **xs; mpc_dtor_t *dxs; } mpc_pdata_and_t;
typedef union {
mpc_pdata_fail_t fail;
mpc_pdata_lift_t lift;
mpc_pdata_expect_t expect;
mpc_pdata_anchor_t anchor;
mpc_pdata_single_t single;
mpc_pdata_range_t range;
mpc_pdata_satisfy_t satisfy;
mpc_pdata_string_t string;
mpc_pdata_apply_t apply;
mpc_pdata_apply_to_t apply_to;
mpc_pdata_predict_t predict;
mpc_pdata_not_t not_t;
mpc_pdata_repeat_t repeat;
mpc_pdata_and_t and_t;
mpc_pdata_or_t or_t;
} mpc_pdata_t;
struct mpc_parser_t {
char retained;
char *name;
char type;
mpc_pdata_t data;
};
/*
** This is rather pleasant. The core parsing routine
** is written in about 200 lines of C.
**
** I also love the way in which each parsing type
** concisely matches some construct or pattern.
**
** Particularly nice are the `or` and `and`
** types which have a broken but mirrored structure
** with return value and error reflected.
*/
#define MPC_SUCCESS(x) r->output = x; return 1
#define MPC_FAILURE(x) r->error = x; return 0
#define MPC_PRIMITIVE(x) \
if (x) { MPC_SUCCESS(r->output); } \
else { MPC_FAILURE(mpc_err_fail(i->filename, i->state, "Incorrect Input")); }
enum {
MPC_PARSE_STACK_MIN = 8
};
int mpc_parse_input(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r) {
int j = 0, k = 0;
mpc_result_t results_stk[MPC_PARSE_STACK_MIN];
mpc_result_t *results;
int results_slots = MPC_PARSE_STACK_MIN;
switch (p->type) {
/* Basic Parsers */
case MPC_TYPE_ANY: MPC_PRIMITIVE(mpc_input_any(i, (char**)&r->output));
case MPC_TYPE_SINGLE: MPC_PRIMITIVE(mpc_input_char(i, p->data.single.x, (char**)&r->output));
case MPC_TYPE_RANGE: MPC_PRIMITIVE(mpc_input_range(i, p->data.range.x, p->data.range.y, (char**)&r->output));
case MPC_TYPE_ONEOF: MPC_PRIMITIVE(mpc_input_oneof(i, p->data.string.x, (char**)&r->output));
case MPC_TYPE_NONEOF: MPC_PRIMITIVE(mpc_input_noneof(i, p->data.string.x, (char**)&r->output));
case MPC_TYPE_SATISFY: MPC_PRIMITIVE(mpc_input_satisfy(i, p->data.satisfy.f, (char**)&r->output));
case MPC_TYPE_STRING: MPC_PRIMITIVE(mpc_input_string(i, p->data.string.x, (char**)&r->output));
/* Other parsers */
case MPC_TYPE_UNDEFINED: MPC_FAILURE(mpc_err_fail(i->filename, i->state, "Parser Undefined!"));
case MPC_TYPE_PASS: MPC_SUCCESS(NULL);
case MPC_TYPE_FAIL: MPC_FAILURE(mpc_err_fail(i->filename, i->state, p->data.fail.m));
case MPC_TYPE_LIFT: MPC_SUCCESS(p->data.lift.lf());
case MPC_TYPE_LIFT_VAL: MPC_SUCCESS(p->data.lift.x);
case MPC_TYPE_STATE: MPC_SUCCESS(mpc_state_copy(i->state));
case MPC_TYPE_ANCHOR:
if (mpc_input_anchor(i, p->data.anchor.f)) {
MPC_SUCCESS(NULL);
} else {
MPC_FAILURE(mpc_err_new(i->filename, i->state, "anchor", mpc_input_peekc(i)));
}
/* Application Parsers */
case MPC_TYPE_EXPECT:
if (mpc_parse_input(i, p->data.expect.x, r)) {
MPC_SUCCESS(r->output);
} else {
mpc_err_delete(r->error);
MPC_FAILURE(mpc_err_new(i->filename, i->state, p->data.expect.m, mpc_input_peekc(i)));
}
case MPC_TYPE_APPLY:
if (mpc_parse_input(i, p->data.apply.x, r)) {
MPC_SUCCESS(p->data.apply.f(r->output));
} else {
MPC_FAILURE((mpc_err_t *)r->output);
}
case MPC_TYPE_APPLY_TO:
if (mpc_parse_input(i, p->data.apply_to.x, r)) {
MPC_SUCCESS(p->data.apply_to.f(r->output, p->data.apply_to.d));
} else {
MPC_FAILURE(r->error);
}
case MPC_TYPE_PREDICT:
mpc_input_backtrack_disable(i);
if (mpc_parse_input(i, p->data.predict.x, r)) {
mpc_input_backtrack_enable(i);
MPC_SUCCESS(r->output);
} else {
mpc_input_backtrack_enable(i);
MPC_FAILURE(r->error);
}
/* Optional Parsers */
/* TODO: Update Not Error Message */
case MPC_TYPE_NOT:
mpc_input_mark(i);
if (mpc_parse_input(i, p->data.not_t.x, r)) {
mpc_input_rewind(i);
p->data.not_t.dx(r->output);
MPC_FAILURE(mpc_err_new(i->filename, i->state, "opposite", mpc_input_peekc(i)));
} else {
mpc_input_unmark(i);
mpc_err_delete(r->error);
MPC_SUCCESS(p->data.not_t.lf());
}
case MPC_TYPE_MAYBE:
if (mpc_parse_input(i, p->data.not_t.x, r)) {
MPC_SUCCESS(r->output);
} else {
mpc_err_delete(r->error);
MPC_SUCCESS(p->data.not_t.lf());
}
/* Repeat Parsers */
case MPC_TYPE_MANY:
results = (mpc_result_t *)malloc(sizeof(mpc_result_t) * results_slots);
while (mpc_parse_input(i, p->data.repeat.x, &results[j])) {
j++;
if (j >= results_slots) {
results_slots = j + j / 2;
results = (mpc_result_t *)realloc(results, sizeof(mpc_result_t) * results_slots);
}
}
mpc_err_delete(results[j].error);
MPC_SUCCESS(p->data.repeat.f(j, (mpc_val_t**)results); free(results));
case MPC_TYPE_MANY1:
results = (mpc_result_t *)malloc(sizeof(mpc_result_t) * results_slots);
while (mpc_parse_input(i, p->data.repeat.x, &results[j])) {
j++;
if (j >= results_slots) {
results_slots = j + j / 2;
results = (mpc_result_t *)realloc(results, sizeof(mpc_result_t) * results_slots);
}
}
if (j == 0) {
MPC_FAILURE(mpc_err_many1(results[0].error); free(results));
} else {
mpc_err_delete(results[j].error);
MPC_SUCCESS(p->data.repeat.f(j, (mpc_val_t**)results); free(results));
}
case MPC_TYPE_COUNT:
results = p->data.repeat.n > MPC_PARSE_STACK_MIN
? (mpc_result_t *)malloc(sizeof(mpc_result_t) * p->data.repeat.n)
: results_stk;
while (mpc_parse_input(i, p->data.repeat.x, &results[j])) {
j++;
if (j == p->data.repeat.n) { break; }
}
if (j == p->data.repeat.n) {
MPC_SUCCESS(p->data.repeat.f(j, (mpc_val_t**)results);
if (p->data.repeat.n > MPC_PARSE_STACK_MIN) { free(results); });
} else {
for (k = 0; k < j; k++) {
p->data.repeat.dx(results[k].output);
}
MPC_FAILURE(mpc_err_count(results[j].error, p->data.repeat.n);
if (p->data.repeat.n > MPC_PARSE_STACK_MIN) { free(results); });
}
/* Combinatory Parsers */
case MPC_TYPE_OR:
if (p->data.or_t.n == 0) { MPC_SUCCESS(NULL); }
results = p->data.or_t.n > MPC_PARSE_STACK_MIN
? (mpc_result_t *)malloc(sizeof(mpc_result_t) * p->data.or_t.n)
: results_stk;
for (j = 0; j < p->data.or_t.n; j++) {
if (mpc_parse_input(i, p->data.or_t.xs[j], &results[j])) {
for (k = 0; k < j; k++) {
mpc_err_delete(results[k].error);
}
MPC_SUCCESS(results[j].output;
if (p->data.or_t.n > MPC_PARSE_STACK_MIN) { free(results); });
}
}
MPC_FAILURE(mpc_err_or((mpc_err_t**)results, j);
if (p->data.or_t.n > MPC_PARSE_STACK_MIN) { free(results); });
case MPC_TYPE_AND:
if (p->data.and_t.n == 0) { MPC_SUCCESS(NULL); }
results = p->data.or_t.n > MPC_PARSE_STACK_MIN
? (mpc_result_t *)malloc(sizeof(mpc_result_t) * p->data.or_t.n)
: results_stk;
mpc_input_mark(i);
for (j = 0; j < p->data.and_t.n; j++) {
if (!mpc_parse_input(i, p->data.and_t.xs[j], &results[j])) {
mpc_input_rewind(i);
for (k = 0; k < j; k++) {
p->data.and_t.dxs[k](results[k].output);
}
MPC_FAILURE(results[j].error;
if (p->data.or_t.n > MPC_PARSE_STACK_MIN) { free(results); });
}
}
mpc_input_unmark(i);
MPC_SUCCESS(p->data.and_t.f(j, (mpc_val_t**)results);
if (p->data.or_t.n > MPC_PARSE_STACK_MIN) { free(results); });
/* End */
default:
MPC_FAILURE(mpc_err_fail(i->filename, i->state, "Unknown Parser Type Id!"));
}
return 0;
}
#undef MPC_SUCCESS
#undef MPC_FAILURE
#undef MPC_PRIMITIVE
int mpc_parse(const char *filename, const char *string, mpc_parser_t *p, mpc_result_t *r) {
int x;
mpc_input_t *i = mpc_input_new_string(filename, string);
x = mpc_parse_input(i, p, r);
mpc_input_delete(i);
return x;
}
int mpc_parse_file(const char *filename, FILE *file, mpc_parser_t *p, mpc_result_t *r) {
int x;
mpc_input_t *i = mpc_input_new_file(filename, file);
x = mpc_parse_input(i, p, r);
mpc_input_delete(i);
return x;
}
int mpc_parse_pipe(const char *filename, FILE *pipe, mpc_parser_t *p, mpc_result_t *r) {
int x;
mpc_input_t *i = mpc_input_new_pipe(filename, pipe);
x = mpc_parse_input(i, p, r);
mpc_input_delete(i);
return x;
}
int mpc_parse_contents(const char *filename, mpc_parser_t *p, mpc_result_t *r) {
FILE *f = fopen(filename, "rb");
int res;
if (f == NULL) {
r->output = NULL;
r->error = mpc_err_fail(filename, mpc_state_new(), "Unable to open file!");
return 0;
}
res = mpc_parse_file(filename, f, p, r);
fclose(f);
return res;
}
/*
** Building a Parser
*/
static void mpc_undefine_unretained(mpc_parser_t *p, int force);
static void mpc_undefine_or(mpc_parser_t *p) {
int i;
for (i = 0; i < p->data.or_t.n; i++) {
mpc_undefine_unretained(p->data.or_t.xs[i], 0);
}
free(p->data.or_t.xs);
}
static void mpc_undefine_and(mpc_parser_t *p) {
int i;
for (i = 0; i < p->data.and_t.n; i++) {
mpc_undefine_unretained(p->data.and_t.xs[i], 0);
}
free(p->data.and_t.xs);
free(p->data.and_t.dxs);
}
static void mpc_undefine_unretained(mpc_parser_t *p, int force) {
if (p->retained && !force) { return; }
switch (p->type) {
case MPC_TYPE_FAIL: free(p->data.fail.m); break;
case MPC_TYPE_ONEOF:
case MPC_TYPE_NONEOF:
case MPC_TYPE_STRING:
free(p->data.string.x);
break;
case MPC_TYPE_APPLY: mpc_undefine_unretained(p->data.apply.x, 0); break;
case MPC_TYPE_APPLY_TO: mpc_undefine_unretained(p->data.apply_to.x, 0); break;
case MPC_TYPE_PREDICT: mpc_undefine_unretained(p->data.predict.x, 0); break;
case MPC_TYPE_MAYBE:
case MPC_TYPE_NOT:
mpc_undefine_unretained(p->data.not_t.x, 0);
break;
case MPC_TYPE_EXPECT:
mpc_undefine_unretained(p->data.expect.x, 0);
free(p->data.expect.m);
break;
case MPC_TYPE_MANY:
case MPC_TYPE_MANY1:
case MPC_TYPE_COUNT:
mpc_undefine_unretained(p->data.repeat.x, 0);
break;
case MPC_TYPE_OR: mpc_undefine_or(p); break;
case MPC_TYPE_AND: mpc_undefine_and(p); break;
default: break;
}
if (!force) {
free(p->name);
free(p);
}
}
void mpc_delete(mpc_parser_t *p) {
if (p->retained) {
if (p->type != MPC_TYPE_UNDEFINED) {
mpc_undefine_unretained(p, 0);
}
free(p->name);
free(p);
} else {
mpc_undefine_unretained(p, 0);
}
}
static void mpc_soft_delete(mpc_val_t *x) {
mpc_undefine_unretained((mpc_parser_t *)x, 0);
}
static mpc_parser_t *mpc_undefined(void) {
mpc_parser_t *p = (mpc_parser_t *)calloc(1, sizeof(mpc_parser_t));
p->retained = 0;
p->type = MPC_TYPE_UNDEFINED;
p->name = NULL;
return p;
}
mpc_parser_t *mpc_new(const char *name) {
mpc_parser_t *p = mpc_undefined();
p->retained = 1;
p->name = (char *)realloc(p->name, strlen(name) + 1);
strcpy(p->name, name);
return p;
}
mpc_parser_t *mpc_undefine(mpc_parser_t *p) {
mpc_undefine_unretained(p, 1);
p->type = MPC_TYPE_UNDEFINED;
return p;
}
mpc_parser_t *mpc_define(mpc_parser_t *p, mpc_parser_t *a) {
if (p->retained) {
p->type = a->type;
p->data = a->data;
} else {
mpc_parser_t *a2 = mpc_failf("Attempt to assign to Unretained Parser!");
p->type = a2->type;
p->data = a2->data;
free(a2);
}
free(a);
return p;
}
void mpc_cleanup(int n, ...) {
int i;
mpc_parser_t **list = (mpc_parser_t **)malloc(sizeof(mpc_parser_t*) * n);
va_list va;
va_start(va, n);
for (i = 0; i < n; i++) { list[i] = va_arg(va, mpc_parser_t*); }
for (i = 0; i < n; i++) { mpc_undefine(list[i]); }
for (i = 0; i < n; i++) { mpc_delete(list[i]); }
va_end(va);
free(list);
}
mpc_parser_t *mpc_pass(void) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_PASS;
return p;
}
mpc_parser_t *mpc_fail(const char *m) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_FAIL;
p->data.fail.m = (char *)malloc(strlen(m) + 1);
strcpy(p->data.fail.m, m);
return p;
}
/*
** As `snprintf` is not ANSI standard this
** function `mpc_failf` should be considered
** unsafe.
**
** You have a few options if this is going to be
** trouble.
**
** - Ensure the format string does not exceed
** the buffer length using precision specifiers
** such as `%.512s`.
**
** - Patch this function in your code base to
** use `snprintf` or whatever variant your
** system supports.
**
** - Avoid it altogether.
**
*/
mpc_parser_t *mpc_failf(const char *fmt, ...) {
va_list va;
char *buffer;
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_FAIL;
va_start(va, fmt);
buffer = (char *)malloc(2048);
vsprintf(buffer, fmt, va);
va_end(va);
buffer = (char *)realloc(buffer, strlen(buffer) + 1);
p->data.fail.m = buffer;
return p;
}
mpc_parser_t *mpc_lift_val(mpc_val_t *x) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_LIFT_VAL;
p->data.lift.x = x;
return p;
}
mpc_parser_t *mpc_lift(mpc_ctor_t lf) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_LIFT;
p->data.lift.lf = lf;
return p;
}
mpc_parser_t *mpc_anchor(int(*f)(char,char)) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_ANCHOR;
p->data.anchor.f = f;
return p;
}
mpc_parser_t *mpc_state(void) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_STATE;
return p;
}
mpc_parser_t *mpc_expect(mpc_parser_t *a, const char *expected) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_EXPECT;
p->data.expect.x = a;
p->data.expect.m = (char *)malloc(strlen(expected) + 1);
strcpy(p->data.expect.m, expected);
return p;
}
/*
** As `snprintf` is not ANSI standard this
** function `mpc_expectf` should be considered
** unsafe.
**
** You have a few options if this is going to be
** trouble.
**
** - Ensure the format string does not exceed
** the buffer length using precision specifiers
** such as `%.512s`.
**
** - Patch this function in your code base to
** use `snprintf` or whatever variant your
** system supports.
**
** - Avoid it altogether.
**
*/
mpc_parser_t *mpc_expectf(mpc_parser_t *a, const char *fmt, ...) {
va_list va;
char *buffer;
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_EXPECT;
va_start(va, fmt);
buffer = (char *)malloc(2048);
vsprintf(buffer, fmt, va);
va_end(va);
buffer = (char *)realloc(buffer, strlen(buffer) + 1);
p->data.expect.x = a;
p->data.expect.m = buffer;
return p;
}
/*
** Basic Parsers
*/
mpc_parser_t *mpc_any(void) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_ANY;
return mpc_expect(p, "any character");
}
mpc_parser_t *mpc_char(char c) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_SINGLE;
p->data.single.x = c;
return mpc_expectf(p, "'%c'", c);
}
mpc_parser_t *mpc_range(char s, char e) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_RANGE;
p->data.range.x = s;
p->data.range.y = e;
return mpc_expectf(p, "character between '%c' and '%c'", s, e);
}
mpc_parser_t *mpc_oneof(const char *s) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_ONEOF;
p->data.string.x = (char *)malloc(strlen(s) + 1);
strcpy(p->data.string.x, s);
return mpc_expectf(p, "one of '%s'", s);
}
mpc_parser_t *mpc_noneof(const char *s) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_NONEOF;
p->data.string.x = (char *)malloc(strlen(s) + 1);
strcpy(p->data.string.x, s);
return mpc_expectf(p, "none of '%s'", s);
}
mpc_parser_t *mpc_satisfy(int(*f)(char)) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_SATISFY;
p->data.satisfy.f = f;
return mpc_expectf(p, "character satisfying function %p", f);
}
mpc_parser_t *mpc_string(const char *s) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_STRING;
p->data.string.x = (char *)malloc(strlen(s) + 1);
strcpy(p->data.string.x, s);
return mpc_expectf(p, "\"%s\"", s);
}
/*
** Core Parsers
*/
mpc_parser_t *mpc_apply(mpc_parser_t *a, mpc_apply_t f) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_APPLY;
p->data.apply.x = a;
p->data.apply.f = f;
return p;
}
mpc_parser_t *mpc_apply_to(mpc_parser_t *a, mpc_apply_to_t f, void *x) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_APPLY_TO;
p->data.apply_to.x = a;
p->data.apply_to.f = f;
p->data.apply_to.d = x;
return p;
}
mpc_parser_t *mpc_predictive(mpc_parser_t *a) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_PREDICT;
p->data.predict.x = a;
return p;
}
mpc_parser_t *mpc_not_lift(mpc_parser_t *a, mpc_dtor_t da, mpc_ctor_t lf) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_NOT;
p->data.not_t.x = a;
p->data.not_t.dx = da;
p->data.not_t.lf = lf;
return p;
}
mpc_parser_t *mpc_not(mpc_parser_t *a, mpc_dtor_t da) {
return mpc_not_lift(a, da, mpcf_ctor_null);
}
mpc_parser_t *mpc_maybe_lift(mpc_parser_t *a, mpc_ctor_t lf) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_MAYBE;
p->data.not_t.x = a;
p->data.not_t.lf = lf;
return p;
}
mpc_parser_t *mpc_maybe(mpc_parser_t *a) {
return mpc_maybe_lift(a, mpcf_ctor_null);
}
mpc_parser_t *mpc_many(mpc_fold_t f, mpc_parser_t *a) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_MANY;
p->data.repeat.x = a;
p->data.repeat.f = f;
return p;
}
mpc_parser_t *mpc_many1(mpc_fold_t f, mpc_parser_t *a) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_MANY1;
p->data.repeat.x = a;
p->data.repeat.f = f;
return p;
}
mpc_parser_t *mpc_count(int n, mpc_fold_t f, mpc_parser_t *a, mpc_dtor_t da) {
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_COUNT;
p->data.repeat.n = n;
p->data.repeat.f = f;
p->data.repeat.x = a;
p->data.repeat.dx = da;
return p;
}
mpc_parser_t *mpc_or(int n, ...) {
int i;
va_list va;
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_OR;
p->data.or_t.n = n;
p->data.or_t.xs = (mpc_parser_t **)malloc(sizeof(mpc_parser_t*) * n);
va_start(va, n);
for (i = 0; i < n; i++) {
p->data.or_t.xs[i] = va_arg(va, mpc_parser_t*);
}
va_end(va);
return p;
}
mpc_parser_t *mpc_and(int n, mpc_fold_t f, ...) {
int i;
va_list va;
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_AND;
p->data.and_t.n = n;
p->data.and_t.f = f;
p->data.and_t.xs = (mpc_parser_t **)malloc(sizeof(mpc_parser_t*) * n);
p->data.and_t.dxs = (mpc_dtor_t *)malloc(sizeof(mpc_dtor_t) * (n-1));
va_start(va, f);
for (i = 0; i < n; i++) {
p->data.and_t.xs[i] = va_arg(va, mpc_parser_t*);
}
for (i = 0; i < (n-1); i++) {
p->data.and_t.dxs[i] = va_arg(va, mpc_dtor_t);
}
va_end(va);
return p;
}
/*
** Common Parsers
*/
static int mpc_soi_anchor(char prev, char next) { (void) next; return (prev == '\0'); }
static int mpc_eoi_anchor(char prev, char next) { (void) prev; return (next == '\0'); }
mpc_parser_t *mpc_soi(void) { return mpc_expect(mpc_anchor(mpc_soi_anchor), "start of input"); }
mpc_parser_t *mpc_eoi(void) { return mpc_expect(mpc_anchor(mpc_eoi_anchor), "end of input"); }
static int mpc_boundary_anchor(char prev, char next) {
const char* word = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789_";
if ( strchr(word, next) && prev == '\0') { return 1; }
if ( strchr(word, prev) && next == '\0') { return 1; }
if ( strchr(word, next) && !strchr(word, prev)) { return 1; }
if (!strchr(word, next) && strchr(word, prev)) { return 1; }
return 0;
}
mpc_parser_t *mpc_boundary(void) { return mpc_expect(mpc_anchor(mpc_boundary_anchor), "boundary"); }
mpc_parser_t *mpc_whitespace(void) { return mpc_expect(mpc_oneof(" \f\n\r\t\v"), "whitespace"); }
mpc_parser_t *mpc_whitespaces(void) { return mpc_expect(mpc_many(mpcf_strfold, mpc_whitespace()), "spaces"); }
mpc_parser_t *mpc_blank(void) { return mpc_expect(mpc_apply(mpc_whitespaces(), mpcf_free), "whitespace"); }
mpc_parser_t *mpc_newline(void) { return mpc_expect(mpc_char('\n'), "newline"); }
mpc_parser_t *mpc_tab(void) { return mpc_expect(mpc_char('\t'), "tab"); }
mpc_parser_t *mpc_escape(void) { return mpc_and(2, mpcf_strfold, mpc_char('\\'), mpc_any(), free); }
mpc_parser_t *mpc_digit(void) { return mpc_expect(mpc_oneof("0123456789"), "digit"); }
mpc_parser_t *mpc_hexdigit(void) { return mpc_expect(mpc_oneof("0123456789ABCDEFabcdef"), "hex digit"); }
mpc_parser_t *mpc_octdigit(void) { return mpc_expect(mpc_oneof("01234567"), "oct digit"); }
mpc_parser_t *mpc_digits(void) { return mpc_expect(mpc_many1(mpcf_strfold, mpc_digit()), "digits"); }
mpc_parser_t *mpc_hexdigits(void) { return mpc_expect(mpc_many1(mpcf_strfold, mpc_hexdigit()), "hex digits"); }
mpc_parser_t *mpc_octdigits(void) { return mpc_expect(mpc_many1(mpcf_strfold, mpc_octdigit()), "oct digits"); }
mpc_parser_t *mpc_lower(void) { return mpc_expect(mpc_oneof("abcdefghijklmnopqrstuvwxyz"), "lowercase letter"); }
mpc_parser_t *mpc_upper(void) { return mpc_expect(mpc_oneof("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "uppercase letter"); }
mpc_parser_t *mpc_alpha(void) { return mpc_expect(mpc_oneof("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), "letter"); }
mpc_parser_t *mpc_underscore(void) { return mpc_expect(mpc_char('_'), "underscore"); }
mpc_parser_t *mpc_alphanum(void) { return mpc_expect(mpc_or(3, mpc_alpha(), mpc_digit(), mpc_underscore()), "alphanumeric"); }
mpc_parser_t *mpc_int(void) { return mpc_expect(mpc_apply(mpc_digits(), mpcf_int), "integer"); }
mpc_parser_t *mpc_hex(void) { return mpc_expect(mpc_apply(mpc_hexdigits(), mpcf_hex), "hexadecimal"); }
mpc_parser_t *mpc_oct(void) { return mpc_expect(mpc_apply(mpc_octdigits(), mpcf_oct), "octadecimal"); }
mpc_parser_t *mpc_number(void) { return mpc_expect(mpc_or(3, mpc_int(), mpc_hex(), mpc_oct()), "number"); }
mpc_parser_t *mpc_real(void) {
/* [+-]?\d+(\.\d+)?([eE][+-]?[0-9]+)? */
mpc_parser_t *p0, *p1, *p2, *p30, *p31, *p32, *p3;
p0 = mpc_maybe_lift(mpc_oneof("+-"), mpcf_ctor_str);
p1 = mpc_digits();
p2 = mpc_maybe_lift(mpc_and(2, mpcf_strfold, mpc_char('.'), mpc_digits(), free), mpcf_ctor_str);
p30 = mpc_oneof("eE");
p31 = mpc_maybe_lift(mpc_oneof("+-"), mpcf_ctor_str);
p32 = mpc_digits();
p3 = mpc_maybe_lift(mpc_and(3, mpcf_strfold, p30, p31, p32, free, free), mpcf_ctor_str);
return mpc_expect(mpc_and(4, mpcf_strfold, p0, p1, p2, p3, free, free, free), "real");
}
mpc_parser_t *mpc_float(void) {
return mpc_expect(mpc_apply(mpc_real(), mpcf_float), "float");
}
mpc_parser_t *mpc_char_lit(void) {
return mpc_expect(mpc_between(mpc_or(2, mpc_escape(), mpc_any()), free, "'", "'"), "char");
}
mpc_parser_t *mpc_string_lit(void) {
mpc_parser_t *strchar = mpc_or(2, mpc_escape(), mpc_noneof("\""));
return mpc_expect(mpc_between(mpc_many(mpcf_strfold, strchar), free, "\"", "\""), "string");
}
mpc_parser_t *mpc_regex_lit(void) {
mpc_parser_t *regexchar = mpc_or(2, mpc_escape(), mpc_noneof("/"));
return mpc_expect(mpc_between(mpc_many(mpcf_strfold, regexchar), free, "/", "/"), "regex");
}
mpc_parser_t *mpc_ident(void) {
mpc_parser_t *p0, *p1;
p0 = mpc_or(2, mpc_alpha(), mpc_underscore());
p1 = mpc_many(mpcf_strfold, mpc_alphanum());
return mpc_and(2, mpcf_strfold, p0, p1, free);
}
/*
** Useful Parsers
*/
mpc_parser_t *mpc_startwith(mpc_parser_t *a) { return mpc_and(2, mpcf_snd, mpc_soi(), a, mpcf_dtor_null); }
mpc_parser_t *mpc_endwith(mpc_parser_t *a, mpc_dtor_t da) { return mpc_and(2, mpcf_fst, a, mpc_eoi(), da); }
mpc_parser_t *mpc_whole(mpc_parser_t *a, mpc_dtor_t da) { return mpc_and(3, mpcf_snd, mpc_soi(), a, mpc_eoi(), mpcf_dtor_null, da); }
mpc_parser_t *mpc_stripl(mpc_parser_t *a) { return mpc_and(2, mpcf_snd, mpc_blank(), a, mpcf_dtor_null); }
mpc_parser_t *mpc_stripr(mpc_parser_t *a) { return mpc_and(2, mpcf_fst, a, mpc_blank(), mpcf_dtor_null); }
mpc_parser_t *mpc_strip(mpc_parser_t *a) { return mpc_and(3, mpcf_snd, mpc_blank(), a, mpc_blank(), mpcf_dtor_null, mpcf_dtor_null); }
mpc_parser_t *mpc_tok(mpc_parser_t *a) { return mpc_and(2, mpcf_fst, a, mpc_blank(), mpcf_dtor_null); }
mpc_parser_t *mpc_sym(const char *s) { return mpc_tok(mpc_string(s)); }
mpc_parser_t *mpc_total(mpc_parser_t *a, mpc_dtor_t da) { return mpc_whole(mpc_strip(a), da); }
mpc_parser_t *mpc_between(mpc_parser_t *a, mpc_dtor_t ad, const char *o, const char *c) {
return mpc_and(3, mpcf_snd_free,
mpc_string(o), a, mpc_string(c),
free, ad);
}
mpc_parser_t *mpc_parens(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_between(a, ad, "(", ")"); }
mpc_parser_t *mpc_braces(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_between(a, ad, "<", ">"); }
mpc_parser_t *mpc_brackets(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_between(a, ad, "{", "}"); }
mpc_parser_t *mpc_squares(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_between(a, ad, "[", "]"); }
mpc_parser_t *mpc_tok_between(mpc_parser_t *a, mpc_dtor_t ad, const char *o, const char *c) {
return mpc_and(3, mpcf_snd_free,
mpc_sym(o), mpc_tok(a), mpc_sym(c),
free, ad);
}
mpc_parser_t *mpc_tok_parens(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_tok_between(a, ad, "(", ")"); }
mpc_parser_t *mpc_tok_braces(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_tok_between(a, ad, "<", ">"); }
mpc_parser_t *mpc_tok_brackets(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_tok_between(a, ad, "{", "}"); }
mpc_parser_t *mpc_tok_squares(mpc_parser_t *a, mpc_dtor_t ad) { return mpc_tok_between(a, ad, "[", "]"); }
/*
** Regular Expression Parsers
*/
/*
** So here is a cute bootstrapping.
**
** I'm using the previously defined
** mpc constructs and functions to
** parse the user regex string and
** construct a parser from it.
**
** As it turns out lots of the standard
** mpc functions look a lot like `fold`
** functions and so can be used indirectly
** by many of the parsing functions to build
** a parser directly - as we are parsing.
**
** This is certainly something that
** would be less elegant/interesting
** in a two-phase parser which first
** builds an AST and then traverses it
** to generate the object.
**
** This whole thing acts as a great
** case study for how trivial it can be
** to write a great parser in a few
** lines of code using mpc.
*/
/*
**
** ### Regular Expression Grammar
**
** <regex> : <term> | (<term> "|" <regex>)
**
** <term> : <factor>*
**
** <factor> : <base>
** | <base> "*"
** | <base> "+"
** | <base> "?"
** | <base> "{" <digits> "}"
**
** <base> : <char>
** | "\" <char>
** | "(" <regex> ")"
** | "[" <range> "]"
*/
static mpc_val_t *mpcf_re_or(int n, mpc_val_t **xs) {
(void) n;
if (xs[1] == NULL) { return xs[0]; }
else { return mpc_or(2, xs[0], xs[1]); }
}
static mpc_val_t *mpcf_re_and(int n, mpc_val_t **xs) {
int i;
mpc_parser_t *p = mpc_lift(mpcf_ctor_str);
for (i = 0; i < n; i++) {
p = mpc_and(2, mpcf_strfold, p, xs[i], free);
}
return p;
}
static mpc_val_t *mpcf_re_repeat(int n, mpc_val_t **xs) {
int num;
(void) n;
if (xs[1] == NULL) { return xs[0]; }
if (strcmp((const char *)xs[1], "*") == 0) { free(xs[1]); return mpc_many(mpcf_strfold, (mpc_parser_t *)xs[0]); }
if (strcmp((const char *)xs[1], "+") == 0) { free(xs[1]); return mpc_many1(mpcf_strfold, (mpc_parser_t *)xs[0]); }
if (strcmp((const char *)xs[1], "?") == 0) { free(xs[1]); return mpc_maybe_lift((mpc_parser_t *)xs[0], mpcf_ctor_str); }
num = *(int*)xs[1];
free(xs[1]);
return mpc_count(num, mpcf_strfold, (mpc_parser_t *)xs[0], free);
}
static mpc_parser_t *mpc_re_escape_char(char c) {
switch (c) {
case 'a': return mpc_char('\a');
case 'f': return mpc_char('\f');
case 'n': return mpc_char('\n');
case 'r': return mpc_char('\r');
case 't': return mpc_char('\t');
case 'v': return mpc_char('\v');
case 'b': return mpc_and(2, mpcf_snd, mpc_boundary(), mpc_lift(mpcf_ctor_str), free);
case 'B': return mpc_not_lift(mpc_boundary(), free, mpcf_ctor_str);
case 'A': return mpc_and(2, mpcf_snd, mpc_soi(), mpc_lift(mpcf_ctor_str), free);
case 'Z': return mpc_and(2, mpcf_snd, mpc_eoi(), mpc_lift(mpcf_ctor_str), free);
case 'd': return mpc_digit();
case 'D': return mpc_not_lift(mpc_digit(), free, mpcf_ctor_str);
case 's': return mpc_whitespace();
case 'S': return mpc_not_lift(mpc_whitespace(), free, mpcf_ctor_str);
case 'w': return mpc_alphanum();
case 'W': return mpc_not_lift(mpc_alphanum(), free, mpcf_ctor_str);
default: return NULL;
}
}
static mpc_val_t *mpcf_re_escape(mpc_val_t *x) {
char *s = (char *)x;
mpc_parser_t *p;
/* Regex Special Characters */
if (s[0] == '.') { free(s); return mpc_any(); }
if (s[0] == '^') { free(s); return mpc_and(2, mpcf_snd, mpc_soi(), mpc_lift(mpcf_ctor_str), free); }
if (s[0] == '$') { free(s); return mpc_and(2, mpcf_snd, mpc_eoi(), mpc_lift(mpcf_ctor_str), free); }
/* Regex Escape */
if (s[0] == '\\') {
p = mpc_re_escape_char(s[1]);
p = (p == NULL) ? mpc_char(s[1]) : p;
free(s);
return p;
}
/* Regex Standard */
p = mpc_char(s[0]);
free(s);
return p;
}
static const char *mpc_re_range_escape_char(char c) {
switch (c) {
case '-': return "-";
case 'a': return "\a";
case 'f': return "\f";
case 'n': return "\n";
case 'r': return "\r";
case 't': return "\t";
case 'v': return "\v";
case 'b': return "\b";
case 'd': return "0123456789";
case 's': return " \f\n\r\t\v";
case 'w': return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
default: return NULL;
}
}
static mpc_val_t *mpcf_re_range(mpc_val_t *x) {
mpc_parser_t *out;
size_t i, j;
size_t start, end;
const char *tmp = NULL;
const char *s = (char *)x;
int comp = s[0] == '^' ? 1 : 0;
char *range = (char *)calloc(1,1);
if (s[0] == '\0') { free(x); return mpc_fail("Invalid Regex Range Expression"); }
if (s[0] == '^' &&
s[1] == '\0') { free(x); return mpc_fail("Invalid Regex Range Expression"); }
for (i = comp; i < strlen(s); i++){
/* Regex Range Escape */
if (s[i] == '\\') {
tmp = mpc_re_range_escape_char(s[i+1]);
if (tmp != NULL) {
range = (char *)realloc(range, strlen(range) + strlen(tmp) + 1);
strcat(range, tmp);
} else {
range = (char *)realloc(range, strlen(range) + 1 + 1);
range[strlen(range) + 1] = '\0';
range[strlen(range) + 0] = s[i+1];
}
i++;
}
/* Regex Range...Range */
else if (s[i] == '-') {
if (s[i+1] == '\0' || i == 0) {
range = (char *)realloc(range, strlen(range) + strlen("-") + 1);
strcat(range, "-");
} else {
start = s[i-1]+1;
end = s[i+1]-1;
for (j = start; j <= end; j++) {
range = (char *)realloc(range, strlen(range) + 1 + 1 + 1);
range[strlen(range) + 1] = '\0';
range[strlen(range) + 0] = j;
}
}
}
/* Regex Range Normal */
else {
range = (char *)realloc(range, strlen(range) + 1 + 1);
range[strlen(range) + 1] = '\0';
range[strlen(range) + 0] = s[i];
}
}
out = comp == 1 ? mpc_noneof(range) : mpc_oneof(range);
free(x);
free(range);
return out;
}
mpc_parser_t *mpc_re(const char *re) {
char *err_msg;
mpc_parser_t *err_out;
mpc_result_t r;
mpc_parser_t *Regex, *Term, *Factor, *Base, *Range, *RegexEnclose;
Regex = mpc_new("regex");
Term = mpc_new("term");
Factor = mpc_new("factor");
Base = mpc_new("base");
Range = mpc_new("range");
mpc_define(Regex, mpc_and(2, mpcf_re_or,
Term,
mpc_maybe(mpc_and(2, mpcf_snd_free, mpc_char('|'), Regex, free)),
(mpc_dtor_t)mpc_delete
));
mpc_define(Term, mpc_many(mpcf_re_and, Factor));
mpc_define(Factor, mpc_and(2, mpcf_re_repeat,
Base,
mpc_or(5,
mpc_char('*'), mpc_char('+'), mpc_char('?'),
mpc_brackets(mpc_int(), free),
mpc_pass()),
(mpc_dtor_t)mpc_delete
));
mpc_define(Base, mpc_or(4,
mpc_parens(Regex, (mpc_dtor_t)mpc_delete),
mpc_squares(Range, (mpc_dtor_t)mpc_delete),
mpc_apply(mpc_escape(), mpcf_re_escape),
mpc_apply(mpc_noneof(")|"), mpcf_re_escape)
));
mpc_define(Range, mpc_apply(
mpc_many(mpcf_strfold, mpc_or(2, mpc_escape(), mpc_noneof("]"))),
mpcf_re_range
));
RegexEnclose = mpc_whole(mpc_predictive(Regex), (mpc_dtor_t)mpc_delete);
mpc_optimise(RegexEnclose);
mpc_optimise(Regex);
mpc_optimise(Term);
mpc_optimise(Factor);
mpc_optimise(Base);
mpc_optimise(Range);
if(!mpc_parse("<mpc_re_compiler>", re, RegexEnclose, &r)) {
err_msg = mpc_err_string(r.error);
err_out = mpc_failf("Invalid Regex: %s", err_msg);
mpc_err_delete(r.error);
free(err_msg);
r.output = err_out;
}
mpc_cleanup(6, RegexEnclose, Regex, Term, Factor, Base, Range);
mpc_optimise((mpc_parser_t *)r.output);
return (mpc_parser_t *)r.output;
}
/*
** Common Fold Functions
*/
void mpcf_dtor_null(mpc_val_t *x) { (void) x; return; }
mpc_val_t *mpcf_ctor_null(void) { return NULL; }
mpc_val_t *mpcf_ctor_str(void) { return calloc(1, 1); }
mpc_val_t *mpcf_free(mpc_val_t *x) { free(x); return NULL; }
mpc_val_t *mpcf_int(mpc_val_t *x) {
int *y = (int *)malloc(sizeof(int));
*y = (int)strtol((const char *)x, NULL, 10);
free(x);
return y;
}
mpc_val_t *mpcf_hex(mpc_val_t *x) {
int *y = (int *)malloc(sizeof(int));
*y = (int)strtol((const char *)x, NULL, 16);
free(x);
return y;
}
mpc_val_t *mpcf_oct(mpc_val_t *x) {
int *y = (int *)malloc(sizeof(int));
*y = (int)strtol((const char *)x, NULL, 8);
free(x);
return y;
}
mpc_val_t *mpcf_float(mpc_val_t *x) {
float *y = (float *)malloc(sizeof(float));
*y = (float)strtod((const char *)x, NULL);
free(x);
return y;
}
mpc_val_t *mpcf_strtriml(mpc_val_t *x) {
char *s = (char *)x;
while (isspace(*s)) {
memmove(s, s+1, strlen(s));
}
return s;
}
mpc_val_t *mpcf_strtrimr(mpc_val_t *x) {
char *s = (char *)x;
size_t l = strlen(s);
while (isspace(s[l-1])) {
s[l-1] = '\0'; l--;
}
return s;
}
mpc_val_t *mpcf_strtrim(mpc_val_t *x) {
return mpcf_strtriml(mpcf_strtrimr(x));
}
static const char mpc_escape_input_c[] = {
'\a', '\b', '\f', '\n', '\r',
'\t', '\v', '\\', '\'', '\"', '\0'};
static const char *mpc_escape_output_c[] = {
"\\a", "\\b", "\\f", "\\n", "\\r", "\\t",
"\\v", "\\\\", "\\'", "\\\"", "\\0", NULL};
static const char mpc_escape_input_raw_re[] = { '/' };
static const char *mpc_escape_output_raw_re[] = { "\\/", NULL };
static const char mpc_escape_input_raw_cstr[] = { '"' };
static const char *mpc_escape_output_raw_cstr[] = { "\\\"", NULL };
static const char mpc_escape_input_raw_cchar[] = { '\'' };
static const char *mpc_escape_output_raw_cchar[] = { "\\'", NULL };
static mpc_val_t *mpcf_escape_new(mpc_val_t *x, const char *input, const char **output) {
int i;
int found;
char buff[2];
char *s = (char *)x;
char *y = (char *)calloc(1, 1);
while (*s) {
i = 0;
found = 0;
while (output[i]) {
if (*s == input[i]) {
y = (char *)realloc(y, strlen(y) + strlen(output[i]) + 1);
strcat(y, output[i]);
found = 1;
break;
}
i++;
}
if (!found) {
y = (char *)realloc(y, strlen(y) + 2);
buff[0] = *s; buff[1] = '\0';
strcat(y, buff);
}
s++;
}
return y;
}
static mpc_val_t *mpcf_unescape_new(mpc_val_t *x, const char *input, const char **output) {
int i;
int found = 0;
char buff[2];
char *s = (char *)x;
char *y = (char *)calloc(1, 1);
while (*s) {
i = 0;
found = 0;
while (output[i]) {
if ((*(s+0)) == output[i][0] &&
(*(s+1)) == output[i][1]) {
y = (char *)realloc(y, strlen(y) + 1 + 1);
buff[0] = input[i]; buff[1] = '\0';
strcat(y, buff);
found = 1;
s++;
break;
}
i++;
}
if (!found) {
y = (char *)realloc(y, strlen(y) + 1 + 1);
buff[0] = *s; buff[1] = '\0';
strcat(y, buff);
}
if (*s == '\0') { break; }
else { s++; }
}
return y;
}
mpc_val_t *mpcf_escape(mpc_val_t *x) {
mpc_val_t *y = mpcf_escape_new(x, mpc_escape_input_c, mpc_escape_output_c);
free(x);
return y;
}
mpc_val_t *mpcf_unescape(mpc_val_t *x) {
mpc_val_t *y = mpcf_unescape_new(x, mpc_escape_input_c, mpc_escape_output_c);
free(x);
return y;
}
mpc_val_t *mpcf_escape_regex(mpc_val_t *x) {
mpc_val_t *y = mpcf_escape_new(x, mpc_escape_input_raw_re, mpc_escape_output_raw_re);
free(x);
return y;
}
mpc_val_t *mpcf_unescape_regex(mpc_val_t *x) {
mpc_val_t *y = mpcf_unescape_new(x, mpc_escape_input_raw_re, mpc_escape_output_raw_re);
free(x);
return y;
}
mpc_val_t *mpcf_escape_string_raw(mpc_val_t *x) {
mpc_val_t *y = mpcf_escape_new(x, mpc_escape_input_raw_cstr, mpc_escape_output_raw_cstr);
free(x);
return y;
}
mpc_val_t *mpcf_unescape_string_raw(mpc_val_t *x) {
mpc_val_t *y = mpcf_unescape_new(x, mpc_escape_input_raw_cstr, mpc_escape_output_raw_cstr);
free(x);
return y;
}
mpc_val_t *mpcf_escape_char_raw(mpc_val_t *x) {
mpc_val_t *y = mpcf_escape_new(x, mpc_escape_input_raw_cchar, mpc_escape_output_raw_cchar);
free(x);
return y;
}
mpc_val_t *mpcf_unescape_char_raw(mpc_val_t *x) {
mpc_val_t *y = mpcf_unescape_new(x, mpc_escape_input_raw_cchar, mpc_escape_output_raw_cchar);
free(x);
return y;
}
mpc_val_t *mpcf_null(int n, mpc_val_t** xs) { (void) n; (void) xs; return NULL; }
mpc_val_t *mpcf_fst(int n, mpc_val_t **xs) { (void) n; return xs[0]; }
mpc_val_t *mpcf_snd(int n, mpc_val_t **xs) { (void) n; return xs[1]; }
mpc_val_t *mpcf_trd(int n, mpc_val_t **xs) { (void) n; return xs[2]; }
static mpc_val_t *mpcf_nth_free(int n, mpc_val_t **xs, int x) {
int i;
for (i = 0; i < n; i++) {
if (i != x) { free(xs[i]); }
}
return xs[x];
}
mpc_val_t *mpcf_fst_free(int n, mpc_val_t **xs) { return mpcf_nth_free(n, xs, 0); }
mpc_val_t *mpcf_snd_free(int n, mpc_val_t **xs) { return mpcf_nth_free(n, xs, 1); }
mpc_val_t *mpcf_trd_free(int n, mpc_val_t **xs) { return mpcf_nth_free(n, xs, 2); }
mpc_val_t *mpcf_strfold(int n, mpc_val_t **xs) {
int i;
size_t l = 0;
if (n == 0) { return calloc(1, 1); }
for (i = 0; i < n; i++) { l += strlen((const char *)xs[i]); }
xs[0] = realloc(xs[0], l + 1);
for (i = 1; i < n; i++) {
strcat((char *)xs[0], (const char *)xs[i]); free(xs[i]);
}
return xs[0];
}
mpc_val_t *mpcf_maths(int n, mpc_val_t **xs) {
int **vs = (int**)xs;
(void) n;
if (strcmp((const char *)xs[1], "*") == 0) { *vs[0] *= *vs[2]; }
if (strcmp((const char *)xs[1], "/") == 0) { *vs[0] /= *vs[2]; }
if (strcmp((const char *)xs[1], "%") == 0) { *vs[0] %= *vs[2]; }
if (strcmp((const char *)xs[1], "+") == 0) { *vs[0] += *vs[2]; }
if (strcmp((const char *)xs[1], "-") == 0) { *vs[0] -= *vs[2]; }
free(xs[1]); free(xs[2]);
return xs[0];
}
/*
** Printing
*/
static void mpc_print_unretained(mpc_parser_t *p, int force) {
/* TODO: Print Everything Escaped */
int i;
char *s, *e;
char buff[2];
if (p->retained && !force) {;
if (p->name) { printf("<%s>", p->name); }
else { printf("<anon>"); }
return;
}
if (p->type == MPC_TYPE_UNDEFINED) { printf("<?>"); }
if (p->type == MPC_TYPE_PASS) { printf("<:>"); }
if (p->type == MPC_TYPE_FAIL) { printf("<!>"); }
if (p->type == MPC_TYPE_LIFT) { printf("<#>"); }
if (p->type == MPC_TYPE_STATE) { printf("<S>"); }
if (p->type == MPC_TYPE_ANCHOR) { printf("<@>"); }
if (p->type == MPC_TYPE_EXPECT) {
printf("%s", p->data.expect.m);
/*mpc_print_unretained(p->data.expect.x, 0);*/
}
if (p->type == MPC_TYPE_ANY) { printf("<.>"); }
if (p->type == MPC_TYPE_SATISFY) { printf("<f>"); }
if (p->type == MPC_TYPE_SINGLE) {
buff[0] = p->data.single.x; buff[1] = '\0';
s = (char *)mpcf_escape_new(
buff,
mpc_escape_input_c,
mpc_escape_output_c);
printf("'%s'", s);
free(s);
}
if (p->type == MPC_TYPE_RANGE) {
buff[0] = p->data.range.x; buff[1] = '\0';
s = (char *)mpcf_escape_new(
buff,
mpc_escape_input_c,
mpc_escape_output_c);
buff[0] = p->data.range.y; buff[1] = '\0';
e = (char *)mpcf_escape_new(
buff,
mpc_escape_input_c,
mpc_escape_output_c);
printf("[%s-%s]", s, e);
free(s);
free(e);
}
if (p->type == MPC_TYPE_ONEOF) {
s = (char *)mpcf_escape_new(
p->data.string.x,
mpc_escape_input_c,
mpc_escape_output_c);
printf("[%s]", s);
free(s);
}
if (p->type == MPC_TYPE_NONEOF) {
s = (char *)mpcf_escape_new(
p->data.string.x,
mpc_escape_input_c,
mpc_escape_output_c);
printf("[^%s]", s);
free(s);
}
if (p->type == MPC_TYPE_STRING) {
s = (char *)mpcf_escape_new(
p->data.string.x,
mpc_escape_input_c,
mpc_escape_output_c);
printf("\"%s\"", s);
free(s);
}
if (p->type == MPC_TYPE_APPLY) { mpc_print_unretained(p->data.apply.x, 0); }
if (p->type == MPC_TYPE_APPLY_TO) { mpc_print_unretained(p->data.apply_to.x, 0); }
if (p->type == MPC_TYPE_PREDICT) { mpc_print_unretained(p->data.predict.x, 0); }
if (p->type == MPC_TYPE_NOT) { mpc_print_unretained(p->data.not_t.x, 0); printf("!"); }
if (p->type == MPC_TYPE_MAYBE) { mpc_print_unretained(p->data.not_t.x, 0); printf("?"); }
if (p->type == MPC_TYPE_MANY) { mpc_print_unretained(p->data.repeat.x, 0); printf("*"); }
if (p->type == MPC_TYPE_MANY1) { mpc_print_unretained(p->data.repeat.x, 0); printf("+"); }
if (p->type == MPC_TYPE_COUNT) { mpc_print_unretained(p->data.repeat.x, 0); printf("{%i}", p->data.repeat.n); }
if (p->type == MPC_TYPE_OR) {
printf("(");
for(i = 0; i < p->data.or_t.n-1; i++) {
mpc_print_unretained(p->data.or_t.xs[i], 0);
printf(" | ");
}
mpc_print_unretained(p->data.or_t.xs[p->data.or_t.n-1], 0);
printf(")");
}
if (p->type == MPC_TYPE_AND) {
printf("(");
for(i = 0; i < p->data.and_t.n-1; i++) {
mpc_print_unretained(p->data.and_t.xs[i], 0);
printf(" ");
}
mpc_print_unretained(p->data.and_t.xs[p->data.and_t.n-1], 0);
printf(")");
}
}
void mpc_print(mpc_parser_t *p) {
mpc_print_unretained(p, 1);
printf("\n");
}
/*
** Testing
*/
/*
** These functions are slightly unwieldy and
** also the whole of the testing suite for mpc
** mpc is pretty shaky.
**
** It could do with a lot more tests and more
** precision. Currently I am only really testing
** changes off of the examples.
**
*/
int mpc_test_fail(mpc_parser_t *p, const char *s, const void *d,
int(*tester)(const void*, const void*),
mpc_dtor_t destructor,
void(*printer)(const void*)) {
mpc_result_t r;
(void) printer;
if (mpc_parse("<test>", s, p, &r)) {
if (tester(r.output, d)) {
destructor(r.output);
return 0;
} else {
destructor(r.output);
return 1;
}
} else {
mpc_err_delete(r.error);
return 1;
}
}
int mpc_test_pass(mpc_parser_t *p, const char *s, const void *d,
int(*tester)(const void*, const void*),
mpc_dtor_t destructor,
void(*printer)(const void*)) {
mpc_result_t r;
if (mpc_parse("<test>", s, p, &r)) {
if (tester(r.output, d)) {
destructor(r.output);
return 1;
} else {
printf("Got "); printer(r.output); printf("\n");
printf("Expected "); printer(d); printf("\n");
destructor(r.output);
return 0;
}
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
return 0;
}
}
/*
** AST
*/
void mpc_ast_delete(mpc_ast_t *a) {
int i;
if (a == NULL) { return; }
for (i = 0; i < a->children_num; i++) {
mpc_ast_delete(a->children[i]);
}
free(a->children);
free(a->tag);
free(a->contents);
free(a);
}
static void mpc_ast_delete_no_children(mpc_ast_t *a) {
free(a->children);
free(a->tag);
free(a->contents);
free(a);
}
mpc_ast_t *mpc_ast_new(const char *tag, const char *contents) {
mpc_ast_t *a = (mpc_ast_t *)malloc(sizeof(mpc_ast_t));
a->tag = (char *)malloc(strlen(tag) + 1);
strcpy(a->tag, tag);
a->contents = (char *)malloc(strlen(contents) + 1);
strcpy(a->contents, contents);
a->state = mpc_state_new();
a->children_num = 0;
a->children = NULL;
return a;
}
mpc_ast_t *mpc_ast_build(int n, const char *tag, ...) {
mpc_ast_t *a = mpc_ast_new(tag, "");
int i;
va_list va;
va_start(va, tag);
for (i = 0; i < n; i++) {
mpc_ast_add_child(a, va_arg(va, mpc_ast_t*));
}
va_end(va);
return a;
}
mpc_ast_t *mpc_ast_add_root(mpc_ast_t *a) {
mpc_ast_t *r;
if (a == NULL) { return a; }
if (a->children_num == 0) { return a; }
if (a->children_num == 1) { return a; }
r = mpc_ast_new(">", "");
mpc_ast_add_child(r, a);
return r;
}
int mpc_ast_eq(mpc_ast_t *a, mpc_ast_t *b) {
int i;
if (strcmp(a->tag, b->tag) != 0) { return 0; }
if (strcmp(a->contents, b->contents) != 0) { return 0; }
if (a->children_num != b->children_num) { return 0; }
for (i = 0; i < a->children_num; i++) {
if (!mpc_ast_eq(a->children[i], b->children[i])) { return 0; }
}
return 1;
}
mpc_ast_t *mpc_ast_add_child(mpc_ast_t *r, mpc_ast_t *a) {
r->children_num++;
r->children = (mpc_ast_t **)realloc(r->children, sizeof(mpc_ast_t*) * r->children_num);
r->children[r->children_num-1] = a;
return r;
}
mpc_ast_t *mpc_ast_add_tag(mpc_ast_t *a, const char *t) {
if (a == NULL) { return a; }
a->tag = (char *)realloc(a->tag, strlen(t) + 1 + strlen(a->tag) + 1);
memmove(a->tag + strlen(t) + 1, a->tag, strlen(a->tag)+1);
memmove(a->tag, t, strlen(t));
memmove(a->tag + strlen(t), "|", 1);
return a;
}
mpc_ast_t *mpc_ast_tag(mpc_ast_t *a, const char *t) {
a->tag = (char *)realloc(a->tag, strlen(t) + 1);
strcpy(a->tag, t);
return a;
}
mpc_ast_t *mpc_ast_state(mpc_ast_t *a, mpc_state_t s) {
if (a == NULL) { return a; }
a->state = s;
return a;
}
static void mpc_ast_print_depth(mpc_ast_t *a, int d, FILE *fp) {
int i;
if (a == NULL) {
fprintf(fp, "NULL\n");
return;
}
for (i = 0; i < d; i++) { fprintf(fp, " "); }
if (strlen(a->contents)) {
fprintf(fp, "%s:%lu:%lu '%s'\n", a->tag,
(long unsigned int)(a->state.row+1),
(long unsigned int)(a->state.col+1),
a->contents);
} else {
fprintf(fp, "%s \n", a->tag);
}
for (i = 0; i < a->children_num; i++) {
mpc_ast_print_depth(a->children[i], d+1, fp);
}
}
void mpc_ast_print(mpc_ast_t *a) {
mpc_ast_print_depth(a, 0, stdout);
}
void mpc_ast_print_to(mpc_ast_t *a, FILE *fp) {
mpc_ast_print_depth(a, 0, fp);
}
mpc_val_t *mpcf_fold_ast(int n, mpc_val_t **xs) {
int i, j;
mpc_ast_t** as = (mpc_ast_t**)xs;
mpc_ast_t *r;
if (n == 0) { return NULL; }
if (n == 1) { return xs[0]; }
if (n == 2 && xs[1] == NULL) { return xs[0]; }
if (n == 2 && xs[0] == NULL) { return xs[1]; }
r = mpc_ast_new(">", "");
for (i = 0; i < n; i++) {
if (as[i] == NULL) { continue; }
if (as[i] && as[i]->children_num > 0) {
for (j = 0; j < as[i]->children_num; j++) {
mpc_ast_add_child(r, as[i]->children[j]);
}
mpc_ast_delete_no_children(as[i]);
} else if (as[i] && as[i]->children_num == 0) {
mpc_ast_add_child(r, as[i]);
}
}
if (r->children_num) {
r->state = r->children[0]->state;
}
return r;
}
mpc_val_t *mpcf_str_ast(mpc_val_t *c) {
mpc_ast_t *a = mpc_ast_new("", (const char *)c);
free(c);
return a;
}
mpc_val_t *mpcf_state_ast(int n, mpc_val_t **xs) {
mpc_state_t *s = ((mpc_state_t**)xs)[0];
mpc_ast_t *a = ((mpc_ast_t**)xs)[1];
a = mpc_ast_state(a, *s);
free(s);
(void) n;
return a;
}
mpc_parser_t *mpca_state(mpc_parser_t *a) {
return mpc_and(2, mpcf_state_ast, mpc_state(), a, free);
}
mpc_parser_t *mpca_tag(mpc_parser_t *a, const char *t) {
return mpc_apply_to(a, (mpc_apply_to_t)mpc_ast_tag, (void*)t);
}
mpc_parser_t *mpca_add_tag(mpc_parser_t *a, const char *t) {
return mpc_apply_to(a, (mpc_apply_to_t)mpc_ast_add_tag, (void*)t);
}
mpc_parser_t *mpca_root(mpc_parser_t *a) {
return mpc_apply(a, (mpc_apply_t)mpc_ast_add_root);
}
mpc_parser_t *mpca_not(mpc_parser_t *a) { return mpc_not(a, (mpc_dtor_t)mpc_ast_delete); }
mpc_parser_t *mpca_maybe(mpc_parser_t *a) { return mpc_maybe(a); }
mpc_parser_t *mpca_many(mpc_parser_t *a) { return mpc_many(mpcf_fold_ast, a); }
mpc_parser_t *mpca_many1(mpc_parser_t *a) { return mpc_many1(mpcf_fold_ast, a); }
mpc_parser_t *mpca_count(int n, mpc_parser_t *a) { return mpc_count(n, mpcf_fold_ast, a, (mpc_dtor_t)mpc_ast_delete); }
mpc_parser_t *mpca_or(int n, ...) {
int i;
va_list va;
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_OR;
p->data.or_t.n = n;
p->data.or_t.xs = (mpc_parser_t **)malloc(sizeof(mpc_parser_t*) * n);
va_start(va, n);
for (i = 0; i < n; i++) {
p->data.or_t.xs[i] = va_arg(va, mpc_parser_t*);
}
va_end(va);
return p;
}
mpc_parser_t *mpca_and(int n, ...) {
int i;
va_list va;
mpc_parser_t *p = mpc_undefined();
p->type = MPC_TYPE_AND;
p->data.and_t.n = n;
p->data.and_t.f = mpcf_fold_ast;
p->data.and_t.xs = (mpc_parser_t **)malloc(sizeof(mpc_parser_t*) * n);
p->data.and_t.dxs = (mpc_dtor_t *)malloc(sizeof(mpc_dtor_t) * (n-1));
va_start(va, n);
for (i = 0; i < n; i++) {
p->data.and_t.xs[i] = va_arg(va, mpc_parser_t*);
}
for (i = 0; i < (n-1); i++) {
p->data.and_t.dxs[i] = (mpc_dtor_t)mpc_ast_delete;
}
va_end(va);
return p;
}
mpc_parser_t *mpca_total(mpc_parser_t *a) { return mpc_total(a, (mpc_dtor_t)mpc_ast_delete); }
/*
** Grammar Parser
*/
/*
** This is another interesting bootstrapping.
**
** Having a general purpose AST type allows
** users to specify the grammar alone and
** let all fold rules be automatically taken
** care of by existing functions.
**
** You don't get to control the type spat
** out but this means you can make a nice
** parser to take in some grammar in nice
** syntax and spit out a parser that works.
**
** The grammar for this looks surprisingly
** like regex but the main difference is that
** it is now whitespace insensitive and the
** base type takes literals of some form.
*/
/*
**
** ### Grammar Grammar
**
** <grammar> : (<term> "|" <grammar>) | <term>
**
** <term> : <factor>*
**
** <factor> : <base>
** | <base> "*"
** | <base> "+"
** | <base> "?"
** | <base> "{" <digits> "}"
**
** <base> : "<" (<digits> | <ident>) ">"
** | <string_lit>
** | <char_lit>
** | <regex_lit>
** | "(" <grammar> ")"
*/
typedef struct {
va_list *va;
int parsers_num;
mpc_parser_t **parsers;
int flags;
} mpca_grammar_st_t;
static mpc_val_t *mpcaf_grammar_or(int n, mpc_val_t **xs) {
(void) n;
if (xs[1] == NULL) { return xs[0]; }
else { return mpca_or(2, xs[0], xs[1]); }
}
static mpc_val_t *mpcaf_grammar_and(int n, mpc_val_t **xs) {
int i;
mpc_parser_t *p = mpc_pass();
for (i = 0; i < n; i++) {
if (xs[i] != NULL) { p = mpca_and(2, p, xs[i]); }
}
return p;
}
static mpc_val_t *mpcaf_grammar_repeat(int n, mpc_val_t **xs) {
int num;
(void) n;
if (xs[1] == NULL) { return xs[0]; }
if (strcmp((const char *)xs[1], "*") == 0) { free(xs[1]); return mpca_many((mpc_parser_t *)xs[0]); }
if (strcmp((const char *)xs[1], "+") == 0) { free(xs[1]); return mpca_many1((mpc_parser_t *)xs[0]); }
if (strcmp((const char *)xs[1], "?") == 0) { free(xs[1]); return mpca_maybe((mpc_parser_t *)xs[0]); }
if (strcmp((const char *)xs[1], "!") == 0) { free(xs[1]); return mpca_not((mpc_parser_t *)xs[0]); }
num = *((int*)xs[1]);
free(xs[1]);
return mpca_count(num, (mpc_parser_t *)xs[0]);
}
static mpc_val_t *mpcaf_grammar_string(mpc_val_t *x, void *s) {
mpca_grammar_st_t *st = (mpca_grammar_st_t *)s;
char *y = (char *)mpcf_unescape(x);
mpc_parser_t *p = (st->flags & MPCA_LANG_WHITESPACE_SENSITIVE) ? mpc_string(y) : mpc_tok(mpc_string(y));
free(y);
return mpca_state(mpca_tag(mpc_apply(p, mpcf_str_ast), "string"));
}
static mpc_val_t *mpcaf_grammar_char(mpc_val_t *x, void *s) {
mpca_grammar_st_t *st = (mpca_grammar_st_t *)s;
char *y = (char *)mpcf_unescape(x);
mpc_parser_t *p = (st->flags & MPCA_LANG_WHITESPACE_SENSITIVE) ? mpc_char(y[0]) : mpc_tok(mpc_char(y[0]));
free(y);
return mpca_state(mpca_tag(mpc_apply(p, mpcf_str_ast), "char"));
}
static mpc_val_t *mpcaf_grammar_regex(mpc_val_t *x, void *s) {
mpca_grammar_st_t *st = (mpca_grammar_st_t *)s;
char *y = (char *)mpcf_unescape_regex(x);
mpc_parser_t *p = (st->flags & MPCA_LANG_WHITESPACE_SENSITIVE) ? mpc_re(y) : mpc_tok(mpc_re(y));
free(y);
return mpca_state(mpca_tag(mpc_apply(p, mpcf_str_ast), "regex"));
}
/* Should this just use `isdigit` instead? */
static int is_number(const char* s) {
size_t i;
for (i = 0; i < strlen(s); i++) { if (!strchr("0123456789", s[i])) { return 0; } }
return 1;
}
static mpc_parser_t *mpca_grammar_find_parser(char *x, mpca_grammar_st_t *st) {
int i;
mpc_parser_t *p;
/* Case of Number */
if (is_number(x)) {
i = (int)strtol(x, NULL, 10);
while (st->parsers_num <= i) {
st->parsers_num++;
st->parsers = (mpc_parser_t **)realloc(st->parsers, sizeof(mpc_parser_t*) * st->parsers_num);
st->parsers[st->parsers_num-1] = va_arg(*st->va, mpc_parser_t*);
if (st->parsers[st->parsers_num-1] == NULL) {
return mpc_failf("No Parser in position %i! Only supplied %i Parsers!", i, st->parsers_num);
}
}
return st->parsers[st->parsers_num-1];
/* Case of Identifier */
} else {
/* Search Existing Parsers */
for (i = 0; i < st->parsers_num; i++) {
mpc_parser_t *q = st->parsers[i];
if (q == NULL) { return mpc_failf("Unknown Parser '%s'!", x); }
if (q->name && strcmp(q->name, x) == 0) { return q; }
}
/* Search New Parsers */
while (1) {
p = va_arg(*st->va, mpc_parser_t*);
st->parsers_num++;
st->parsers = (mpc_parser_t **)realloc(st->parsers, sizeof(mpc_parser_t*) * st->parsers_num);
st->parsers[st->parsers_num-1] = p;
if (p == NULL) { return mpc_failf("Unknown Parser '%s'!", x); }
if (p->name && strcmp(p->name, x) == 0) { return p; }
}
}
}
static mpc_val_t *mpcaf_grammar_id(mpc_val_t *x, void *s) {
mpca_grammar_st_t *st = (mpca_grammar_st_t *)s;
mpc_parser_t *p = mpca_grammar_find_parser((char *)x, st);
free(x);
if (p->name) {
return mpca_state(mpca_root(mpca_add_tag(p, p->name)));
} else {
return mpca_state(mpca_root(p));
}
}
mpc_parser_t *mpca_grammar_st(const char *grammar, mpca_grammar_st_t *st) {
char *err_msg;
mpc_parser_t *err_out;
mpc_result_t r;
mpc_parser_t *GrammarTotal, *Grammar, *Term, *Factor, *Base;
GrammarTotal = mpc_new("grammar_total");
Grammar = mpc_new("grammar");
Term = mpc_new("term");
Factor = mpc_new("factor");
Base = mpc_new("base");
mpc_define(GrammarTotal,
mpc_predictive(mpc_total(Grammar, mpc_soft_delete))
);
mpc_define(Grammar, mpc_and(2, mpcaf_grammar_or,
Term,
mpc_maybe(mpc_and(2, mpcf_snd_free, mpc_sym("|"), Grammar, free)),
mpc_soft_delete
));
mpc_define(Term, mpc_many1(mpcaf_grammar_and, Factor));
mpc_define(Factor, mpc_and(2, mpcaf_grammar_repeat,
Base,
mpc_or(6,
mpc_sym("*"),
mpc_sym("+"),
mpc_sym("?"),
mpc_sym("!"),
mpc_tok_brackets(mpc_int(), free),
mpc_pass()),
mpc_soft_delete
));
mpc_define(Base, mpc_or(5,
mpc_apply_to(mpc_tok(mpc_string_lit()), mpcaf_grammar_string, st),
mpc_apply_to(mpc_tok(mpc_char_lit()), mpcaf_grammar_char, st),
mpc_apply_to(mpc_tok(mpc_regex_lit()), mpcaf_grammar_regex, st),
mpc_apply_to(mpc_tok_braces(mpc_or(2, mpc_digits(), mpc_ident()), free), mpcaf_grammar_id, st),
mpc_tok_parens(Grammar, mpc_soft_delete)
));
mpc_optimise(GrammarTotal);
mpc_optimise(Grammar);
mpc_optimise(Factor);
mpc_optimise(Term);
mpc_optimise(Base);
if(!mpc_parse("<mpc_grammar_compiler>", grammar, GrammarTotal, &r)) {
err_msg = mpc_err_string(r.error);
err_out = mpc_failf("Invalid Grammar: %s", err_msg);
mpc_err_delete(r.error);
free(err_msg);
r.output = err_out;
}
mpc_cleanup(5, GrammarTotal, Grammar, Term, Factor, Base);
mpc_optimise((mpc_parser_t *)r.output);
return (st->flags & MPCA_LANG_PREDICTIVE) ? mpc_predictive((mpc_parser_t *)r.output) : (mpc_parser_t *)r.output;
}
mpc_parser_t *mpca_grammar(int flags, const char *grammar, ...) {
mpca_grammar_st_t st;
mpc_parser_t *res;
va_list va;
va_start(va, grammar);
st.va = &va;
st.parsers_num = 0;
st.parsers = NULL;
st.flags = flags;
res = mpca_grammar_st(grammar, &st);
free(st.parsers);
va_end(va);
return res;
}
typedef struct {
char *ident;
char *name;
mpc_parser_t *grammar;
} mpca_stmt_t;
static mpc_val_t *mpca_stmt_afold(int n, mpc_val_t **xs) {
mpca_stmt_t *stmt = ( mpca_stmt_t *)malloc(sizeof(mpca_stmt_t));
stmt->ident = ((char**)xs)[0];
stmt->name = ((char**)xs)[1];
stmt->grammar = ((mpc_parser_t**)xs)[3];
(void) n;
free(((char**)xs)[2]);
free(((char**)xs)[4]);
return stmt;
}
static mpc_val_t *mpca_stmt_fold(int n, mpc_val_t **xs) {
int i;
mpca_stmt_t **stmts = (mpca_stmt_t **)malloc(sizeof(mpca_stmt_t*) * (n+1));
for (i = 0; i < n; i++) {
stmts[i] = (mpca_stmt_t *)xs[i];
}
stmts[n] = NULL;
return stmts;
}
static void mpca_stmt_list_delete(mpc_val_t *x) {
mpca_stmt_t **stmts = (mpca_stmt_t **)x;
while(*stmts) {
mpca_stmt_t *stmt = *stmts;
free(stmt->ident);
free(stmt->name);
mpc_soft_delete(stmt->grammar);
free(stmt);
stmts++;
}
free(x);
}
static mpc_val_t *mpca_stmt_list_apply_to(mpc_val_t *x, void *s) {
mpca_grammar_st_t *st = (mpca_grammar_st_t *)s;
mpca_stmt_t *stmt;
mpca_stmt_t **stmts = (mpca_stmt_t **)x;
mpc_parser_t *left;
while(*stmts) {
stmt = *stmts;
left = mpca_grammar_find_parser(stmt->ident, st);
if (st->flags & MPCA_LANG_PREDICTIVE) { stmt->grammar = mpc_predictive(stmt->grammar); }
if (stmt->name) { stmt->grammar = mpc_expect(stmt->grammar, stmt->name); }
mpc_optimise(stmt->grammar);
mpc_define(left, stmt->grammar);
free(stmt->ident);
free(stmt->name);
free(stmt);
stmts++;
}
free(x);
return NULL;
}
static mpc_err_t *mpca_lang_st(mpc_input_t *i, mpca_grammar_st_t *st) {
mpc_result_t r;
mpc_err_t *e;
mpc_parser_t *Lang, *Stmt, *Grammar, *Term, *Factor, *Base;
Lang = mpc_new("lang");
Stmt = mpc_new("stmt");
Grammar = mpc_new("grammar");
Term = mpc_new("term");
Factor = mpc_new("factor");
Base = mpc_new("base");
mpc_define(Lang, mpc_apply_to(
mpc_total(mpc_predictive(mpc_many(mpca_stmt_fold, Stmt)), mpca_stmt_list_delete),
mpca_stmt_list_apply_to, st
));
mpc_define(Stmt, mpc_and(5, mpca_stmt_afold,
mpc_tok(mpc_ident()), mpc_maybe(mpc_tok(mpc_string_lit())), mpc_sym(":"), Grammar, mpc_sym(";"),
free, free, free, mpc_soft_delete
));
mpc_define(Grammar, mpc_and(2, mpcaf_grammar_or,
Term,
mpc_maybe(mpc_and(2, mpcf_snd_free, mpc_sym("|"), Grammar, free)),
mpc_soft_delete
));
mpc_define(Term, mpc_many1(mpcaf_grammar_and, Factor));
mpc_define(Factor, mpc_and(2, mpcaf_grammar_repeat,
Base,
mpc_or(6,
mpc_sym("*"),
mpc_sym("+"),
mpc_sym("?"),
mpc_sym("!"),
mpc_tok_brackets(mpc_int(), free),
mpc_pass()),
mpc_soft_delete
));
mpc_define(Base, mpc_or(5,
mpc_apply_to(mpc_tok(mpc_string_lit()), mpcaf_grammar_string, st),
mpc_apply_to(mpc_tok(mpc_char_lit()), mpcaf_grammar_char, st),
mpc_apply_to(mpc_tok(mpc_regex_lit()), mpcaf_grammar_regex, st),
mpc_apply_to(mpc_tok_braces(mpc_or(2, mpc_digits(), mpc_ident()), free), mpcaf_grammar_id, st),
mpc_tok_parens(Grammar, mpc_soft_delete)
));
mpc_optimise(Lang);
mpc_optimise(Stmt);
mpc_optimise(Grammar);
mpc_optimise(Term);
mpc_optimise(Factor);
mpc_optimise(Base);
if (!mpc_parse_input(i, Lang, &r)) {
e = r.error;
} else {
e = NULL;
}
mpc_cleanup(6, Lang, Stmt, Grammar, Term, Factor, Base);
return e;
}
mpc_err_t *mpca_lang_file(int flags, FILE *f, ...) {
mpca_grammar_st_t st;
mpc_input_t *i;
mpc_err_t *err;
va_list va;
va_start(va, f);
st.va = &va;
st.parsers_num = 0;
st.parsers = NULL;
st.flags = flags;
i = mpc_input_new_file("<mpca_lang_file>", f);
err = mpca_lang_st(i, &st);
mpc_input_delete(i);
free(st.parsers);
va_end(va);
return err;
}
mpc_err_t *mpca_lang_pipe(int flags, FILE *p, ...) {
mpca_grammar_st_t st;
mpc_input_t *i;
mpc_err_t *err;
va_list va;
va_start(va, p);
st.va = &va;
st.parsers_num = 0;
st.parsers = NULL;
st.flags = flags;
i = mpc_input_new_pipe("<mpca_lang_pipe>", p);
err = mpca_lang_st(i, &st);
mpc_input_delete(i);
free(st.parsers);
va_end(va);
return err;
}
mpc_err_t *mpca_lang(int flags, const char *language, ...) {
mpca_grammar_st_t st;
mpc_input_t *i;
mpc_err_t *err;
va_list va;
va_start(va, language);
st.va = &va;
st.parsers_num = 0;
st.parsers = NULL;
st.flags = flags;
i = mpc_input_new_string("<mpca_lang>", language);
err = mpca_lang_st(i, &st);
mpc_input_delete(i);
free(st.parsers);
va_end(va);
return err;
}
mpc_err_t *mpca_lang_contents(int flags, const char *filename, ...) {
mpca_grammar_st_t st;
mpc_input_t *i;
mpc_err_t *err;
va_list va;
FILE *f = fopen(filename, "rb");
if (f == NULL) {
return mpc_err_fail(filename, mpc_state_new(), "Unable to open file!");
}
va_start(va, filename);
st.va = &va;
st.parsers_num = 0;
st.parsers = NULL;
st.flags = flags;
i = mpc_input_new_file(filename, f);
err = mpca_lang_st(i, &st);
mpc_input_delete(i);
free(st.parsers);
va_end(va);
fclose(f);
return err;
}
static int mpc_nodecount_unretained(mpc_parser_t* p, int force) {
int i, total;
if (p->retained && !force) { return 0; }
if (p->type == MPC_TYPE_EXPECT) { return 1 + mpc_nodecount_unretained(p->data.expect.x, 0); }
if (p->type == MPC_TYPE_APPLY) { return 1 + mpc_nodecount_unretained(p->data.apply.x, 0); }
if (p->type == MPC_TYPE_APPLY_TO) { return 1 + mpc_nodecount_unretained(p->data.apply_to.x, 0); }
if (p->type == MPC_TYPE_PREDICT) { return 1 + mpc_nodecount_unretained(p->data.predict.x, 0); }
if (p->type == MPC_TYPE_NOT) { return 1 + mpc_nodecount_unretained(p->data.not_t.x, 0); }
if (p->type == MPC_TYPE_MAYBE) { return 1 + mpc_nodecount_unretained(p->data.not_t.x, 0); }
if (p->type == MPC_TYPE_MANY) { return 1 + mpc_nodecount_unretained(p->data.repeat.x, 0); }
if (p->type == MPC_TYPE_MANY1) { return 1 + mpc_nodecount_unretained(p->data.repeat.x, 0); }
if (p->type == MPC_TYPE_COUNT) { return 1 + mpc_nodecount_unretained(p->data.repeat.x, 0); }
if (p->type == MPC_TYPE_OR) {
total = 0;
for(i = 0; i < p->data.or_t.n; i++) {
total += mpc_nodecount_unretained(p->data.or_t.xs[i], 0);
}
return total;
}
if (p->type == MPC_TYPE_AND) {
total = 0;
for(i = 0; i < p->data.and_t.n; i++) {
total += mpc_nodecount_unretained(p->data.and_t.xs[i], 0);
}
return total;
}
return 1;
}
void mpc_stats(mpc_parser_t* p) {
printf("Stats\n");
printf("=====\n");
printf("Node Count: %i\n", mpc_nodecount_unretained(p, 1));
}
static void mpc_optimise_unretained(mpc_parser_t *p, int force) {
int i, n, m;
mpc_parser_t *t;
if (p->retained && !force) { return; }
/* Optimise Subexpressions */
if (p->type == MPC_TYPE_EXPECT) { mpc_optimise_unretained(p->data.expect.x, 0); }
if (p->type == MPC_TYPE_APPLY) { mpc_optimise_unretained(p->data.apply.x, 0); }
if (p->type == MPC_TYPE_APPLY_TO) { mpc_optimise_unretained(p->data.apply_to.x, 0); }
if (p->type == MPC_TYPE_PREDICT) { mpc_optimise_unretained(p->data.predict.x, 0); }
if (p->type == MPC_TYPE_NOT) { mpc_optimise_unretained(p->data.not_t.x, 0); }
if (p->type == MPC_TYPE_MAYBE) { mpc_optimise_unretained(p->data.not_t.x, 0); }
if (p->type == MPC_TYPE_MANY) { mpc_optimise_unretained(p->data.repeat.x, 0); }
if (p->type == MPC_TYPE_MANY1) { mpc_optimise_unretained(p->data.repeat.x, 0); }
if (p->type == MPC_TYPE_COUNT) { mpc_optimise_unretained(p->data.repeat.x, 0); }
if (p->type == MPC_TYPE_OR) {
for(i = 0; i < p->data.or_t.n; i++) {
mpc_optimise_unretained(p->data.or_t.xs[i], 0);
}
}
if (p->type == MPC_TYPE_AND) {
for(i = 0; i < p->data.and_t.n; i++) {
mpc_optimise_unretained(p->data.and_t.xs[i], 0);
}
}
/* Perform optimisations */
while (1) {
/* Merge rhs `or` */
if (p->type == MPC_TYPE_OR
&& p->data.or_t.xs[p->data.or_t.n-1]->type == MPC_TYPE_OR
&& !p->data.or_t.xs[p->data.or_t.n-1]->retained) {
t = p->data.or_t.xs[p->data.or_t.n-1];
n = p->data.or_t.n; m = t->data.or_t.n;
p->data.or_t.n = n + m - 1;
p->data.or_t.xs = (mpc_parser_t **)realloc(p->data.or_t.xs, sizeof(mpc_parser_t*) * (n + m -1));
memmove(p->data.or_t.xs + n - 1, t->data.or_t.xs, m * sizeof(mpc_parser_t*));
free(t->data.or_t.xs); free(t->name); free(t);
continue;
}
/* Merge lhs `or` */
if (p->type == MPC_TYPE_OR
&& p->data.or_t.xs[0]->type == MPC_TYPE_OR
&& !p->data.or_t.xs[0]->retained) {
t = p->data.or_t.xs[0];
n = p->data.or_t.n; m = t->data.or_t.n;
p->data.or_t.n = n + m - 1;
p->data.or_t.xs = (mpc_parser_t **)realloc(p->data.or_t.xs, sizeof(mpc_parser_t*) * (n + m -1));
memmove(p->data.or_t.xs + m, t->data.or_t.xs + 1, n * sizeof(mpc_parser_t*));
memmove(p->data.or_t.xs, t->data.or_t.xs, m * sizeof(mpc_parser_t*));
free(t->data.or_t.xs); free(t->name); free(t);
continue;
}
/* Remove ast `pass` */
if (p->type == MPC_TYPE_AND
&& p->data.and_t.n == 2
&& p->data.and_t.xs[0]->type == MPC_TYPE_PASS
&& !p->data.and_t.xs[0]->retained
&& p->data.and_t.f == mpcf_fold_ast) {
t = p->data.and_t.xs[1];
mpc_delete(p->data.and_t.xs[0]);
free(p->data.and_t.xs); free(p->data.and_t.dxs); free(p->name);
memcpy(p, t, sizeof(mpc_parser_t));
free(t);
continue;
}
/* Merge ast lhs `and` */
if (p->type == MPC_TYPE_AND
&& p->data.and_t.f == mpcf_fold_ast
&& p->data.and_t.xs[0]->type == MPC_TYPE_AND
&& !p->data.and_t.xs[0]->retained
&& p->data.and_t.xs[0]->data.and_t.f == mpcf_fold_ast) {
t = p->data.and_t.xs[0];
n = p->data.and_t.n; m = t->data.and_t.n;
p->data.and_t.n = n + m - 1;
p->data.and_t.xs = (mpc_parser_t **)realloc(p->data.and_t.xs, sizeof(mpc_parser_t*) * (n + m - 1));
p->data.and_t.dxs = (mpc_dtor_t *)realloc(p->data.and_t.dxs, sizeof(mpc_dtor_t) * (n + m - 1 - 1));
memmove(p->data.and_t.xs + m, p->data.and_t.xs + 1, (n - 1) * sizeof(mpc_parser_t*));
memmove(p->data.and_t.xs, t->data.and_t.xs, m * sizeof(mpc_parser_t*));
for (i = 0; i < p->data.and_t.n-1; i++) { p->data.and_t.dxs[i] = (mpc_dtor_t)mpc_ast_delete; }
free(t->data.and_t.xs); free(t->data.and_t.dxs); free(t->name); free(t);
continue;
}
/* Merge ast rhs `and` */
if (p->type == MPC_TYPE_AND
&& p->data.and_t.f == mpcf_fold_ast
&& p->data.and_t.xs[p->data.and_t.n-1]->type == MPC_TYPE_AND
&& !p->data.and_t.xs[p->data.and_t.n-1]->retained
&& p->data.and_t.xs[p->data.and_t.n-1]->data.and_t.f == mpcf_fold_ast) {
t = p->data.and_t.xs[p->data.and_t.n-1];
n = p->data.and_t.n; m = t->data.and_t.n;
p->data.and_t.n = n + m - 1;
p->data.and_t.xs = (mpc_parser_t **)realloc(p->data.and_t.xs, sizeof(mpc_parser_t*) * (n + m -1));
p->data.and_t.dxs = (mpc_dtor_t *)realloc(p->data.and_t.dxs, sizeof(mpc_dtor_t) * (n + m - 1 - 1));
memmove(p->data.and_t.xs + n - 1, t->data.and_t.xs, m * sizeof(mpc_parser_t*));
for (i = 0; i < p->data.and_t.n-1; i++) { p->data.and_t.dxs[i] = (mpc_dtor_t)mpc_ast_delete; }
free(t->data.and_t.xs); free(t->data.and_t.dxs); free(t->name); free(t);
continue;
}
/* Remove re `lift` */
if (p->type == MPC_TYPE_AND
&& p->data.and_t.n == 2
&& p->data.and_t.xs[0]->type == MPC_TYPE_LIFT
&& p->data.and_t.xs[0]->data.lift.lf == mpcf_ctor_str
&& !p->data.and_t.xs[0]->retained
&& p->data.and_t.f == mpcf_strfold) {
t = p->data.and_t.xs[1];
mpc_delete(p->data.and_t.xs[0]);
free(p->data.and_t.xs); free(p->data.and_t.dxs); free(p->name);
memcpy(p, t, sizeof(mpc_parser_t));
free(t);
continue;
}
/* Merge re lhs `and` */
if (p->type == MPC_TYPE_AND
&& p->data.and_t.f == mpcf_strfold
&& p->data.and_t.xs[0]->type == MPC_TYPE_AND
&& !p->data.and_t.xs[0]->retained
&& p->data.and_t.xs[0]->data.and_t.f == mpcf_strfold) {
t = p->data.and_t.xs[0];
n = p->data.and_t.n; m = t->data.and_t.n;
p->data.and_t.n = n + m - 1;
p->data.and_t.xs = (mpc_parser_t **)realloc(p->data.and_t.xs, sizeof(mpc_parser_t*) * (n + m - 1));
p->data.and_t.dxs = (mpc_dtor_t *)realloc(p->data.and_t.dxs, sizeof(mpc_dtor_t) * (n + m - 1 - 1));
memmove(p->data.and_t.xs + m, p->data.and_t.xs + 1, (n - 1) * sizeof(mpc_parser_t*));
memmove(p->data.and_t.xs, t->data.and_t.xs, m * sizeof(mpc_parser_t*));
for (i = 0; i < p->data.and_t.n-1; i++) { p->data.and_t.dxs[i] = free; }
free(t->data.and_t.xs); free(t->data.and_t.dxs); free(t->name); free(t);
continue;
}
/* Merge re rhs `and` */
if (p->type == MPC_TYPE_AND
&& p->data.and_t.f == mpcf_strfold
&& p->data.and_t.xs[p->data.and_t.n-1]->type == MPC_TYPE_AND
&& !p->data.and_t.xs[p->data.and_t.n-1]->retained
&& p->data.and_t.xs[p->data.and_t.n-1]->data.and_t.f == mpcf_strfold) {
t = p->data.and_t.xs[p->data.and_t.n-1];
n = p->data.and_t.n; m = t->data.and_t.n;
p->data.and_t.n = n + m - 1;
p->data.and_t.xs = (mpc_parser_t **)realloc(p->data.and_t.xs, sizeof(mpc_parser_t*) * (n + m -1));
p->data.and_t.dxs = (mpc_dtor_t *)realloc(p->data.and_t.dxs, sizeof(mpc_dtor_t) * (n + m - 1 - 1));
memmove(p->data.and_t.xs + n - 1, t->data.and_t.xs, m * sizeof(mpc_parser_t*));
for (i = 0; i < p->data.and_t.n-1; i++) { p->data.and_t.dxs[i] = free; }
free(t->data.and_t.xs); free(t->data.and_t.dxs); free(t->name); free(t);
continue;
}
return;
}
}
void mpc_optimise(mpc_parser_t *p) {
mpc_optimise_unretained(p, 1);
}
| true |
424e5086924897ec689d0dc2039fdf59f9badf87 | C++ | ttyang/sandbox | /sandbox/SOC/2007/signals/libs/glv/include/glv_core.h | UTF-8 | 17,656 | 2.59375 | 3 | [
"BSL-1.0"
] | permissive | #ifndef INC_GLV_CORE_H
#define INC_GLV_CORE_H
/* Graphics Library of Views (GLV) - GUI Building Toolkit
See COPYRIGHT file for authors and license information */
#include "glv_rect.h"
#include "glv_observer_pattern.h"
#include "glv_color.h"
#include "glv_draw.h"
#include <map>
#include <string>
#include <list>
namespace glv {
class GLV;
class View;
/// Type for graphical space values, i.e. dimensions, extents, positions, etc..
typedef float space_t;
/// Type for View rectangle geometry
typedef TRect<space_t> Rect;
/// Type for a drawing callback
typedef void (*drawCallback)(View * v);
/// Type for an event callback
/// The first parameter is the View receiving the event and the second is the
/// GLV context sending the event. The function returns true if the event is
/// to be bubbled up to the receiver's parent View.
typedef bool (*eventCallback)(View * v, GLV& glv);
/// Type for a list of event callbacks
typedef std::list<eventCallback> eventCallbackList;
/// View property flags
enum{
Visible =1<< 0, /**< Whether to draw myself */
DrawBack =1<< 1, /**< Whether to draw back rect */
DrawBorder =1<< 2, /**< Whether to draw border */
CropChildren =1<< 3, /**< Whether to crop children when drawing */
CropSelf =1<< 4, /**< Whether to crop own drawing routine(s) */
Focused =1<< 5, /**< Whether View is focused */
FocusHighlight =1<< 6, /**< Whether to highlight border when focused */
HitTest =1<< 7, /**< Whether View can be clicked */
Controllable =1<< 8, /**< Whether View can be controlled through events */
DrawGrid =1<<28, /**< Whether to draw grid lines between widget elements */
MutualExc =1<<29, /**< Whether only one element of a widget can be non-zero */
SelectOnDrag =1<<30, /**< Whether a new element of a widget is selected while dragging */
Toggleable =1<<31 /**< Whether widget element toggles when clicked */
};
/// Direction types
struct Direction{
/// Direction enumeration
enum{
N = 1<<0, /**< North */
E = 1<<1, /**< East */
S = 1<<2, /**< South */
W = 1<<3 /**< West */
};
Direction(): val(0){}
Direction(int v): val(v){}
operator int(){ return val; }
int val;
};
/// Recognized event types.
namespace Event{
/// Event type enum
enum t{
Null = 0, /**< No event */
// core events
Quit, /**< Application quit */
ContextChange, /**< New graphics context */
// view events
GetFocus, /**< View got focus */
LoseFocus, /**< View lost focus */
// mouse events
MouseDown, /**< Mouse button pressed */
MouseUp, /**< Mouse button released */
MouseMove, /**< Mouse has moved */
MouseDrag, /**< Mouse has moved with a button pressed */
MouseWheel, /**< Mouse wheel moved */
// keyboard events
KeyDown, /**< Keyboard key pressed*/
KeyUp, /**< Keyboard key released */
KeyRepeat, /**< Keyboard key auto-repeated */
// window events
// WindowActivated,
// WindowDeactivated,
Unused, /**< Add to this for runtime event types */
NumTypes /**< Number of event types */
};
/// Returns a string of event type.
const char * string(const Event::t e);
}
/// Constants of keyboard keys.
namespace Key{
enum t{
// Standard ASCII non-printable characters
Enter =3, /**< */
BackSpace =8, /**< */
Tab =9, /**< */
Return =13, /**< */
Escape =27, /**< */
Delete =127, /**< */
// Non-standard, but common keys.
F1=256, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
Insert, Left, Up, Right, Down, PageDown, PageUp, End, Home,
};
}
/// Placement types
namespace Place{
enum t{
TC=1<<0, /**< Top-center */
TR=1<<1, /**< Top-right */
CR=1<<2, /**< Center-right */
BR=1<<3, /**< Bottom-right */
BC=1<<4, /**< Bottom-center */
BL=1<<5, /**< Bottom-left */
CL=1<<6, /**< Center-left */
TL=1<<7, /**< Top-left */
CC=1<<8 /**< Center-center */
};
}
/// Holds keyboard state.
class Keyboard{
friend class GLV;
public:
/// Constructor.
Keyboard();
~Keyboard(){}
int key() const; ///< Returns key code (non-shifted character) of last key event.
int keyAsNumber() const;///< Returns decimal number correlating to key code
bool alt() const; ///< Whether an alt key is down.
bool caps() const; ///< Whether capslock is down.
bool ctrl() const; ///< Whether a ctrl key is down.
bool meta() const; ///< Whether a meta (e.g. windows, apple) key is down.
bool shift() const; ///< Whether a shift key is down.
bool isDown() const; ///< Whether last event was button down.
bool isNumber() const; ///< Whether key is a number key
bool key(int k) const; ///< Whether the last key was 'k'.
void alt (bool state); ///< Set alt key state.
void caps (bool state); ///< Set alt key state.
void ctrl (bool state); ///< Set ctrl key state.
void meta (bool state); ///< Set meta key state.
void shift(bool state); ///< Set shift key state.
void print(); ///< Print keyboard state to stdout.
protected:
int mKeycode; // last key event key number
bool mIsDown; // last key event state (pressed or released)
bool mModifiers[5]; // Modifier key state array (shift, alt, ctrl, caps, meta)
};
/// Holds mouse state.
class Mouse{
friend class GLV;
public:
/// Mouse button enumeration
enum{ Left = 0, Middle, Right, Extra = (GLV_MAX_MOUSE_BUTTONS - 1) };
/// Constructor.
Mouse();
~Mouse(){};
// Accessors
space_t x() const; ///< Current x position.
space_t y() const; ///< Current y position.
space_t x(int button) const; ///< Get button's last down x position.
space_t y(int button) const; ///< Get button's last down y position.
space_t w() const; ///< Current wheel position.
space_t dx() const; ///< Current x velocity.
space_t dy() const; ///< Current y velocity.
space_t dw() const; ///< Current wheel velocity.
space_t ddx() const; ///< Current x acceleration.
space_t ddy() const; ///< Current y acceleration.
space_t ddw() const; ///< Current wheel acceleration.
space_t xRel() const; ///< Current x position relative to current listener.
space_t yRel() const; ///< Current y position relative to current listener.
int button() const; ///< Last event button number.
int clicks() const; ///< Number of sequential clicks of buttons.
bool isDown() const; ///< Whether last event was button down.
bool isDown(int button) const; ///< Whether button is currently down.
bool left() const; ///< Whether left button is currently down.
bool middle() const; ///< Whether middle button is currently down.
bool right() const; ///< Whether right button is currently down.
void setContext(View * v); ///< Translate relative pos into sub-View.
void unsetContext(View * v);///< Translate relative pos out of sub-View.
void print(); ///< Print out information about Mouse to stdout
protected:
// Current (0) and previous (1,2) absolute mouse positions
space_t mX[3], mY[3], mW[3];
// Mouse coords in the current listener's relative coordinate space.
space_t mXRel, mYRel;
bool b[GLV_MAX_MOUSE_BUTTONS]; // button-down states
space_t bx[GLV_MAX_MOUSE_BUTTONS]; // button-down absolute coordinates
space_t by[GLV_MAX_MOUSE_BUTTONS];
int mButton;
int mClicks;
bool mIsDown;
void bufferPos(space_t newPos, space_t * prev3Pos);
void pos(int x1, int y1);
void posRel(space_t relx, space_t rely);
void updateButton(int btn, bool pressed, int clicks);
};
/// Color style for View appearance.
class StyleColor{
public:
StyleColor();
enum{ BlackOnWhite, Gray, WhiteOnBlack };
Color back; ///< Background
Color border; ///< Border outline
Color fore; ///< Foreground
Color text; ///< Text
void set(int preset);
void hsv(float h, float s=1, float v=1);
};
/// Overall appearance scheme.
class Style : public SmartPointer{
public:
Style(bool deletable): SmartPointer(deletable){}
StyleColor color; ///< Color style
/// Get reference to standard style
static Style& standard(){
// Note: This uses a Construct On First Use Idiom to avoid unpredictable
// static initialization order. The memory allocated will get freed from
// the heap when the program exits.
static Style* ans = new Style(false);
return *ans;
}
};
/// The base class of all GUI elements.
class View : public Rect, public Notifier {
friend class GLV;
public:
/// @param[in] left Initial left edge position
/// @param[in] top Initial top edge position
/// @param[in] width Initial width
/// @param[in] height Initial height
/// @param[in] cb Drawing callback
View(space_t left, space_t top, space_t width, space_t height, drawCallback cb=0);
/// @param[in] rect Rect geometry of View
/// @param[in] anchor Anchor place
/// @param[in] cb Drawing callback
View(const Rect& rect=Rect(200, 200), Place::t anchor=Place::TL, drawCallback cb=0);
virtual ~View();
// Doubly linked tree list of views
// TODO: move this stuff to a Node sub-class
View * parent; ///< My parent view
View * child; ///< My first child (next to be drawn)
View * sibling; ///< My next sibling view (drawn after all my children)
void add(View & child); ///< Add a child view to myself, and update linked lists
void makeLastSibling();
void remove(); ///< Remove myself from the parent view, and update linked lists
/// Add a child view to myself
View& operator << (View& child){ add( child); return *this; }
View& operator << (View* child){ add(*child); return *this; }
/// Map of event callback sequences.
std::map<Event::t, eventCallbackList> callbackLists;
drawCallback draw; ///< Drawing callback
bool absToRel(View * target, space_t& x, space_t& y) const;
StyleColor& colors() const; ///< Returns my style colors
int enabled(int prop) const; ///< Returns whether a property is set
int numEventCallbacks(Event::t e) const; ///< Returns number of registered callbacks
void printDescendents() const; ///< Print tree of descendent Views to stdout
void printFlags() const;
Style& style() const { return *mStyle; } ///< Get style object
int visible() const; ///< Returns whether View is visible
View& anchor(space_t mx, space_t my); ///< Set anchor translation factors
View& anchor(Place::t parentPlace); ///< Set anchor place on parent
/// Append callback to a specific event type callback sequence.
void appendCallback(Event::t type, eventCallback cb);
View& operator()(Event::t e, eventCallback cb){ appendCallback(e, cb); return *this; }
void cloneStyle(); ///< Creates own copy of current style
void constrainWithinParent(); ///< Force to remain in parent
View& disable(int prop); ///< Disable property flag(s)
View& enable(int prop); ///< Enable property flag(s)
/// Returns View under these absolute coordinates or 0 if none.
/// The coordinates are modified to be relative to the returned View's.
///
View * findTarget(space_t& x, space_t& y);
void focused(bool b); ///< Set whether I'm focused
void move(space_t x, space_t y); ///< Translate constraining within parent.
void on(Event::t e, eventCallback cb=0); ///< Set first callback for a specific event type.
virtual void onDraw(); ///< Main drawing callback
virtual bool onEvent(Event::t e, GLV& glv); ///< Main event callback
virtual void onResize(space_t dx, space_t dy); ///< Resize callback
View& pos(Place::t p, space_t x=0, space_t y=0);///< Set position according to a specific place on rect
View& property(int prop, bool v); ///< Set property flag(s) to a specfic value
View& stretch(space_t mx, space_t my); ///< Set parent resize stretch factors
void style(Style * style); ///< Set pointer to style
View& toggle(int prop); ///< Toggle property flag(s)
protected:
int mFlags; // Property flags
Style * mStyle; // Visual appearance
space_t mAnchorX, mAnchorY; // Position anchoring factors when parent is resized
space_t mStretchX, mStretchY; // Stretch factors when parent is resized
void drawBack() const; // Draw the back rect
void drawBorder() const; // Draw the border
void reanchor(space_t dx, space_t dy); // Reanchor when parent resizes
};
/// The top-level View.
///
///
class GLV : public View{
public:
/// @param[in] cb My drawing callback
/// @param[in] width Initial width
/// @param[in] height Initial height
GLV(drawCallback cb = 0, space_t width = 800, space_t height = 600);
Mouse mouse; ///< Current mouse state
Keyboard keyboard; ///< Current keyboard state
/// Send this event to everyone in tree
void broadcastEvent(Event::t e);
/// GLV MAIN RENDER LOOP: draw all Views in the GLV
/// The assumption is that we are inside an OpenGL context of size [w, h]
virtual void drawGLV(unsigned int w, unsigned int h);
/// Draws all acive widgest in the GLV
void drawWidgets(unsigned int w, unsigned int h);
void eventType(Event::t e){ mEventType = e; }
Event::t eventType() const { return mEventType; }
/// Clears color and depth buffers. Prepares OpenGL context for draw loop
void preamble(unsigned int w, unsigned int h);
/// Update input event state; called by external event handlers.
/// be sure to set the eventType first!
void propagateEvent();
/// set current event target:
void setFocus(View * v);
void setKeyDown(int keycode); // Sets keyboard and GLV event state
void setKeyUp(int keycode); // Sets keyboard and GLV event state
/// this function will modify the input coordinates to be relative to the target view's origin
void setMouseDown(space_t& x, space_t& y, int button, int clicks);
/// this function will modify the input coordinates to be relative to the target view's origin
void setMouseDrag(space_t& x, space_t& y);
// LJP: Deprecated. This doesn't work right when multiple buttons are held down.
void setMouseDrag(space_t& x, space_t& y, int button, int clicks);
void setMousePos(int x, int y, space_t relx, space_t rely);
/// this function will modify the input coordinates to be relative to the target view's origin
void setMouseUp(space_t& x, space_t& y, int button, int clicks);
void setMouseMove(space_t& x, space_t& y);
void setMouseWheel(int wheelDelta); // Sets mouse and GLV event state
View * focusedView(){ return mFocusedView; }
protected:
View * mFocusedView; // current focused widget
Event::t mEventType; // current event type
// Returns whether the event should be bubbled to parent
bool doEventCallbacks(View& target, glv::Event::t e);
void doFocusCallback(bool get); // Call get or lose focus callback of focused view
};
// Implementation ______________________________________________________________
// View
inline int View::enabled(int prop) const { return mFlags & prop; }
inline int View::visible() const { return enabled(Visible); }
inline View& View::disable (int prop){ mFlags &=~prop; return *this; }
inline View& View::enable (int prop){ mFlags |= prop; return *this; }
inline View& View::property(int prop, bool v){ v ? enable(prop) : disable(prop); return *this; }
inline View& View::toggle (int prop){ mFlags ^= prop; return *this; }
// Keyboard
inline int Keyboard::key() const { return mKeycode; }
inline int Keyboard::keyAsNumber() const { return key() - 48; }
inline bool Keyboard::isDown() const { return mIsDown; }
inline bool Keyboard::isNumber() const { return (key() >= '0') && (key() <= '9'); }
inline bool Keyboard::alt() const { return mModifiers[1]; }
inline bool Keyboard::caps() const { return mModifiers[3]; }
inline bool Keyboard::ctrl() const { return mModifiers[2]; }
inline bool Keyboard::meta() const { return mModifiers[4]; }
inline bool Keyboard::shift() const { return mModifiers[0]; }
inline bool Keyboard::key(int k) const { return mKeycode == k; }
inline void Keyboard::alt (bool state){mModifiers[1] = state;}
inline void Keyboard::caps (bool state){mModifiers[3] = state;}
inline void Keyboard::ctrl (bool state){mModifiers[2] = state;}
inline void Keyboard::meta (bool state){mModifiers[4] = state;}
inline void Keyboard::shift(bool state){mModifiers[0] = state;}
// Mouse
inline space_t Mouse::x() const { return mX[0]; }
inline space_t Mouse::y() const { return mY[0]; }
inline space_t Mouse::x(int button) const { return bx[button]; }
inline space_t Mouse::y(int button) const { return by[button]; }
inline space_t Mouse::w() const { return mW[0]; }
inline space_t Mouse::dx() const { return mX[0] - mX[1]; }
inline space_t Mouse::dy() const { return mY[0] - mY[1]; }
inline space_t Mouse::dw() const { return mW[0] - mW[1]; }
inline space_t Mouse::ddx() const { return mX[0] - 2 * mX[1] + mX[2]; }
inline space_t Mouse::ddy() const { return mY[0] - 2 * mY[1] + mY[2];; }
inline space_t Mouse::ddw() const { return mW[0] - 2 * mW[1] + mW[2];; }
inline space_t Mouse::xRel() const { return mXRel; }
inline space_t Mouse::yRel() const { return mYRel; }
inline int Mouse::button() const { return mButton; }
inline int Mouse::clicks() const { return mClicks; }
inline bool Mouse::isDown() const { return mIsDown; }
inline bool Mouse::isDown(int button) const { return b[button]; }
inline bool Mouse::left() const { return b[Left]; }
inline bool Mouse::middle() const { return b[Middle]; }
inline bool Mouse::right() const { return b[Right]; }
inline void Mouse:: setContext(View * v){mXRel -= v->l; mYRel -= v->t;}
inline void Mouse::unsetContext(View * v){mXRel += v->l; mYRel += v->t;}
inline void Mouse::pos(int x, int y) {
bufferPos((space_t)x, mX);
bufferPos((space_t)y, mY);
}
inline void Mouse::bufferPos(space_t newPos, space_t * pos){
pos[2] = pos[1];
pos[1] = pos[0];
pos[0] = newPos;
}
inline void Mouse::posRel(space_t rx, space_t ry){ mXRel=rx; mYRel=ry;}
} // glv::
#endif
| true |
71bbc9760be45407474528c1777d44547f758ea1 | C++ | IHC1998/LARC | /sensorCor/sensorCor.ino | UTF-8 | 1,554 | 3 | 3 | [] | no_license | //PINOS SENSOR DE COR
int S2 = 9; //9 //2
int S3 = 10; //10 //4
int OUT = 8; //8 //7
int red;
int green;
int blue;
void color() {
// ----- OBS: Os valores dessa tabela irão variar dependendo da luminosidade do local. ------
/* Tabela de Valores do RGB das Cores
COR | RED | GREEN | BLUE |
PRETO | 13 | 22 | 20 |
VERMELHO | 06 | 14 | 12 |
VERDE | 11 | 16 | 15 |
AZUL | 12 | 18 | 13 |
CINZA | 06 | 08 | 07 |
BRANCO | 04 | 04 | 04 |
*/
if (red < 11) {
Serial.println("R");
}
else if (11 < red && red < 25 && green < 20) {
Serial.println("B");
}
else if (20 < red) {
Serial.println("G");
}
}
void calculo_RGB() {
//Seleciona leitura com filtro para vermelho de acordo com a tabela lembra?
digitalWrite(S2, LOW);
digitalWrite(S3, LOW);
//Lê duração do pulso em LOW
red = pulseIn(OUT, LOW); // Função que retorna a duração do pulso em ms
//Seleciona leitura com filtro para verde
digitalWrite(S2, HIGH);
digitalWrite(S3, HIGH);
//Lê duração do pulso em LOW
green = pulseIn(OUT, LOW);
//Seleciona leitura com filtro para azul
digitalWrite(S2, LOW);
digitalWrite(S3, HIGH);
//Lê duração do pulso em LOW
blue = pulseIn(OUT, LOW);
color();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(OUT, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
calculo_RGB();
}
| true |
d2abef4c75d4c22fb20c23447c7103761b971eea | C++ | Mottelz/Conquest | /StrategyDriver.cpp | UTF-8 | 3,567 | 2.859375 | 3 | [] | no_license | #include "StrategyPattern.h"
#include "Player.h"
#include "Startup.h"
#include <ctime>
#include "GameObserver.h"
using namespace std;
int main() {
//LOAD THE MAP
Map * map;
MapLoader maploader;
string mapFile = "maps/World.map";
map = new Map(mapFile);
maploader.readMapFile(mapFile, *map);
//CREATE PLAYERS
// Comment or uncomment to test with different number of players
vector<Player*> players;
players.push_back(new Player("Jon", map));
players.push_back(new Player("Daenerys", map));
players.push_back(new Player("Cersei", map));
players.push_back(new Player("Tyrion", map));
players.push_back(new Player("Arya", map));
//players.push_back(new Player("Sansa", map));
//TEST THE STARTUP CLASS
Startup startup(players);
startup.distributeTerritories(*map);
startup.placeArmies(*map);
vector<string> cards = map->getAllTerritoryNames();
Deck deck(cards, cards.size());
Player* player = players[0];
Map* mapp = map;
HumanPlayer* human = new HumanPlayer();
AggressiveAI* aggressive = new AggressiveAI();
BenevolentAI* benevolent = new BenevolentAI();
RandomAI* random = new RandomAI();
CheaterAI* cheater = new CheaterAI();
string type, redo;
bool again;
int playerCards;
srand((unsigned)time(NULL));
vector<PhaseObserver*> playerPhaseObservers;
AbstractGameStatistics* gameObserver = new gameStatistics(&players, mapp);
//apply decorators
gameObserver = new PlayerDominationObserverDecorator(gameObserver);
gameObserver = new PlayerHandsObserverDecorator(gameObserver);
gameObserver = new ContinentControlObserverDecorator(gameObserver);
do
{
again = false;
cout << "\n***************************************" << endl;
cout << "Please select your type of player:" << endl;
cout << "(1) : Human Player" << endl;
cout << "(2) : Aggressive AI Player" << endl;
cout << "(3) : Benevolent AI Player" << endl;
cout << "(4) : Random Player" << endl;
cout << "(5) : Cheater Player" << endl;
cout << "***************************************\n" << endl;
cin >> type;
for (unsigned int i = 0; i < players.size(); i++)
{
playerPhaseObservers.push_back(new PhaseObserver(players.at(i), mapp));
}
do {
if (type == "1")
{
players[0]->setStrategy(human);
players[0]->play(players[0], mapp, deck);
}
else if (type == "2")
{
players[1]->setStrategy(aggressive);
players[1]->play(players[1], mapp, deck);
}
else if (type == "3")
{
players[2]->setStrategy(benevolent);
players[2]->play(players[2], mapp, deck);
}
else if (type == "4")
{
players[3]->setStrategy(random);
players[3]->play(players[3], mapp, deck);
}
else if (type == "5")
{
players[4]->setStrategy(cheater);
players[4]->play(players[4], mapp, deck);
}
else
{
cout << "Invalid type. Please enter a number between 1, 2 and 3 only." << endl;
again = true;
}
if (again == false)
{
cout << "\n***************************************" << endl;
cout << "Do you want to change your type of player?" << endl;
cout << "(1) : YES" << endl;
cout << "(2) : NO" << endl;
cout << "(3) : END PROGRAM" << endl;
cout << "***************************************\n" << endl;
cin >> redo;
if (redo == "1")
{
again = true;
break;
}
else if (redo == "2")
{
cout << "Continue with same type of player" << endl;
continue;
}
else
{
cout << "End of program." << endl;
again = false;
break;
}
}
} while (true);
} while (again);
return 0;
} | true |
ce6a920c5765f66b1945a1d54f871c6370d0ea76 | C++ | m80126colin/Judge | /before2020/ZeroJudge/ZJ b030.cpp | UTF-8 | 549 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
bool ox_1,ox_2;
int a[128],b[128],i;
string n;
while (getline(cin,n)) {
ox_1=ox_2=1;
for (i=127;i;i--) a[i]=b[i]=0;
for (i=0;i<n.size();i++) a[n[i]]++;
getline(cin,n);
for (i=0;i<n.size();i++) b[n[i]]++;
for (i=65;i<=90;i++) {
if (a[i]!=b[i]) {
ox_1=0;
break;
}
}
for (i=97;ox_1&&i<=122;i++) {
if (a[i]!=b[i]) {
ox_2=0;
break;
}
}
if (ox_1&&ox_2) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
} | true |
2b9fdd5d3fda5f66f9de566cf04a72ff9173a866 | C++ | ibillxia/xleetcode | /2012/20120327SpiralMatrix2.cpp | UTF-8 | 852 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<map>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define FOR(i,n) for(int i=0;i<n;i++)
class Solution {
public:
vector<vector<int> > generateMatrix(int n){
vector<vector<int> > ans(n,vector<int>(n));
if(!n)return ans;
int i,k,l,r,t,b;
k=1;l=0,r=n-1,t=0,b=n-1;
while(l<=r&&t<=b){
//cout<<l<<" "<<r<<" "<<t<<" "<<b<<endl;
for(i=l;i<=r;i++)ans[t][i]=k++;t++;
for(i=t;i<=b;i++)ans[i][r]=k++;r--;
for(i=r;i>=l&&t<=b;i--)ans[b][i]=k++;b--;
for(i=b;i>=t&&l<=r;i--)ans[i][l]=k++;l++;
}
return ans;
}
};
int main()
{
Solution sol;
vector<vector<int> > ans = sol.generateMatrix(2);
FOR(i,ans.size()){
FOR(j,ans[0].size())cout<<ans[i][j]<<" ";
cout<<endl;
}
return 0;
}
| true |
46f597d11c0b3123e57a33ec579e94731696ea4c | C++ | GreenHackersOTC/C | /HelloWorld/HelloWorld/helloworld.cpp | UTF-8 | 301 | 2.5625 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
int genRandom(int n);
int main()
{
int k;
time_t t;
srand((unsigned)time(&t));
for(k=0;k<100;k++)
{
printf("%d\n",genRandom(21));
}
getch();
}
int genRandom(int n)
{
int i=0;
i=rand();
i=(i%n)+1;
return i;
}
| true |
6d9afaddbc3d3c47ab46ffc55adba0507a0f8b36 | C++ | drlongle/leetcode | /algorithms/problem_1676/other.cpp | UTF-8 | 458 | 3.21875 | 3 | [] | no_license | class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, vector<TreeNode*> &nodes) {
unordered_set<TreeNode*> nodeSet(begin(nodes), end(nodes));
return lca(root, nodeSet);
}
TreeNode* lca(TreeNode* root, unordered_set<TreeNode*> &nodes) {
if (!root || nodes.count(root)) return root;
TreeNode* l = lca(root->left, nodes), *r = lca(root->right, nodes);
return l ? r ? root : l : r;
}
};
| true |
8b0f8bd48731a208ce92067be3281651286364c2 | C++ | aguetlein/FootballManager | /src/core/PlayerInfo.cpp | UTF-8 | 1,433 | 3.015625 | 3 | [] | no_license | #include "PlayerInfo.h"
#include <exception>
#include <stdexcept>
namespace fm {
namespace core {
PlayerInfo::PlayerInfo()
: fFirstName(),
fLastName(),
fAge(0)
{
}
PlayerInfo::PlayerInfo(std::string firstName, std::string lastName, int age)
: fFirstName(firstName),
fLastName(lastName),
fAge(age)
{
}
PlayerInfo::PlayerInfo(const PlayerInfo& rhs)
: fFirstName(rhs.fFirstName),
fLastName(rhs.fLastName),
fAge(rhs.fAge)
{
}
PlayerInfo::~PlayerInfo()
{
}
PlayerInfo& PlayerInfo::operator=(const PlayerInfo& rhs)
{
if (this != &rhs)
{
fFirstName = rhs.fFirstName;
fLastName = rhs.fLastName;
fAge = rhs.fAge;
}
return *this;
}
void PlayerInfo::setFirstName(std::string firstName)
{
fFirstName = firstName;
}
void PlayerInfo::setLastName(std::string lastName)
{
fLastName = lastName;
}
void PlayerInfo::setName(std::string firstName, std::string lastName)
{
fFirstName = firstName;
fLastName = lastName;
}
std::string PlayerInfo::getName(bool fullName)
{
std::string name;
if (fullName) name = fFirstName;
else
{
name = fFirstName.substr(0, 1);
name += ".";
}
name += " ";
name += fLastName;
return name;
}
std::string PlayerInfo::getFirstName()
{
return fFirstName;
}
std::string PlayerInfo::getLastName()
{
return fLastName;
}
void PlayerInfo::setAge(int age)
{
fAge = age;
}
int PlayerInfo::getAge()
{
return fAge;
}
} /* namespace core */
} /* namespace fm */
| true |
52ad1277391ab6f71821ba53c1d8a43024477a73 | C++ | wangfyy/dsa | /关于算法竞赛的不完全解决方案/02-树 #/1-二叉树的遍历 #/##重建二叉树 专题.cpp | UTF-8 | 9,556 | 3.296875 | 3 | [] | no_license | 重建二叉树
---后序中序--------------------------------------------------------------------------
【一】PAT-A 170304 原题 D
//给出一个树的中序和后序遍历结果,求它的Z字型层序遍历,也就是偶数层从左往右,奇数层从右往左遍历
// 8
// 12 11 20 17 1 15 8 5 中序
// 12 20 17 11 15 8 5 1 后序
// 1 11 5 8 17 12 20 1 zigzagging sequence
#include <cstdio>
#include <queue>
using namespace std;
struct node {
int data;
node* l;
node* r;
int layer;
};
const int MAXN = 1010;
int N, inOrder[MAXN], postOrder[MAXN], cnt = 0, cnt2 = 0;
node* layerOrder[MAXN];
int leftIndex = 0, rightIndex = 0;
node* create(int inL, int inR, int postL, int postR) {
if(postL > postR) {
return NULL; ////NULL NULL NULL NULL NULL
}
node* root = new node;
root->data = postOrder[postR];
int i;
for(i=0; i<N; i++) {
if(root->data == inOrder[i]) break;
}
int lenL = i - inL; ////// - inL - inL 因为每次的inL不一样,第一次是0,以后就不是了(例如根节点的右子树的左子树的左下标)
root->l = create(inL,i-1,postL,postL+lenL-1); ////// 但是每次的i的值是对的,所以可以直接用i
root->r = create(i+1,inR,postL+lenL,postR-1);
return root;
}
void BFS(node* root) {
queue<node*> q;
q.push(root);
root->layer = 1;
while(!q.empty()) {
node* now = q.front();
layerOrder[cnt++] = now;
q.pop();
if(now->l != NULL) {
q.push(now->l);
now->l->layer = now->layer + 1;
}
if(now->r != NULL) {
q.push(now->r);
now->r->layer = now->layer + 1;
}
}
}
void print() {
//printf("\n[%d %d]\n",leftIndex,rightIndex);
if(layerOrder[leftIndex]->layer % 2 == 0) {
for(int i=leftIndex; i<=rightIndex; i++) {
printf("%d",layerOrder[i]->data);
cnt2++;
if(cnt2 != cnt) printf(" ");
}
} else {
for(int i=rightIndex; i>=leftIndex; i--) {
printf("%d",layerOrder[i]->data);
cnt2++;
if(cnt2 != cnt) printf(" ");
}
}
}
int main() {
scanf("%d",&N);
int i;
for(i=0; i<N; i++) {
scanf("%d",&inOrder[i]);
}
for(i=0; i<N; i++) {
scanf("%d",&postOrder[i]);
}
node* root = create(0,N-1,0,N-1); //////N-1 N-1 N-1 N-1 N-1 N-1
BFS(root);
for(i=0; i<N-1; i++) {
rightIndex = i;
if(layerOrder[i]->layer != layerOrder[i+1]->layer) {
print();
leftIndex = i+1;
}
}
leftIndex = rightIndex;
rightIndex = cnt - 1;
//printf("\n[%d %d]\n",leftIndex,rightIndex);
print();
// printf("\n");
// for(i=0; i<N; i++) {
// printf("%d ",layerOrder[i]->layer);
// }
return 0;
}
【二】PAT-A 1020
Sample Input:
7
2 3 1 5 7 6 4 //后序——左子树->右子树->根节点
1 2 3 4 5 6 7 //中序——左子树->根节点->右子树
Sample Output:
4 1 6 3 5 7 2 //level(层级) order(顺序)
#include <cstdio>
#include <queue>
using namespace std;
const int MAXN = 35;
struct node{
int data;
node* lChild;
node* rChild;
};
int N, postorder[MAXN], inorder[MAXN];
node* create(int postL, int postR, int inL, int inR) { //create create create create // 后序区间[postL,postR] 中序区间[inL,inR]
// 递归边界
if(postL > postR) {
return NULL;
}
// 新建节点,给新建节点的数据域赋值
node* root = new node;
root->data = postorder[postR];
// 寻找inorder里当前根节点的位置k
int k; // k的作用范围
for(k=inL; k<=inR; k++) {
if(inorder[k] == postorder[postR])
break;
}
//// 计算左子树的结点个数,得到下次递归的后序遍历的左子树的范围:postL, postL + numL - 1, ...
//(在后续遍历序列中划分左右子树,因为root的左右子树的头结点分别在左右子树序列的最后一个,
// 所以才有下面的:postL + numL - 1 而不是 postR - 1)
int numL = k - inL;
// 递归式,给新建节点的左右孩子的指针域赋值
root->lChild = create(postL, postL + numL - 1, inL, k - 1);
// 如上面所述,注意:create(postL, postR - 1, inL, k - 1); 错
root->rChild = create(postL + numL, postR - 1, k + 1, inR);
// 若 "..k + 1,.." 写为"inL + k + 1" ,则:递归调用层数太多,提示段错误
return root;
}
void bfs(node* root) {
queue<node*> q; // 注意:node* ,输出时:printf("%d",now->data);
q.push(root);
while(!q.empty()) {
node* now = q.front(); ////
printf("%d",now->data); //
q.pop();
if(now->lChild != NULL) //
q.push(now->lChild);
if(now->rChild != NULL)
q.push(now->rChild);
if(!q.empty()) //
printf(" ");
}
}
int main() {
scanf("%d",&N);
for(int i=0; i<N; i++) {
scanf("%d",&postorder[i]);
}
for(int i=0; i<N; i++) {
scanf("%d",&inorder[i]);
}
// 建树
node* root = create(0, N-1, 0, N-1);
// 层序遍历
bfs(root);
return 0;
}
---先序中序--------------------------------------------------------------------------
PAT-A 1086
123456的push顺序为先序,pop顺序为中序,求后序
Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
#include <cstdio>
#include <cstring>
#include <stack>
#include <ostream>
using namespace std;
const int MAXN = 35;
struct node{
int data;
node* lChild;
node* rChild;
};
int N;
int preOrder[MAXN], inOrder[MAXN];
int preL, preR, inL, inR;
node* create(int preL, int preR, int inL, int inR) {
// 递归边界
if(preL > preR){
return NULL;
}
// data
node* root = new node;
root->data = preOrder[preL];
// k
int k;
for(k=0; k<N; k++) {
if(preOrder[preL] == inOrder[k])
break;
}
// 计算左子树个数
int numLeft = k - inL;
// 递归式
root->lChild = create(preL+1, preL+numLeft, inL, inL+numLeft-1);
//或者写 create(preL+1, preL+numLeft, inL, k-1); 都可以,因为numLeft来源于k: numLeft = k - inL
root->rChild = create(preL+numLeft+1, preR, inL+numLeft+1, inR);
//或者写 create(preL+numLeft+1, preR, k+1, inR);
//上面式子最好上下对应写,即:先写先序的左子树和右子树,在写中序的左右
return root;
}
int j = 1;
void dfs(node* root) { //左->右->中
// 递归边界
if(root == NULL) return;
// 递归式
dfs(root->lChild);
dfs(root->rChild);
if(j != N){
printf("%d ",root->data);
j++;
} else {
printf("%d",root->data);
}
}
int main() {
scanf("%d",&N);
stack<int> s;
char how[5]; //
int x;
int j_1 = 0, j_2 = 0;
for(int i=0; i<N*2; i++) {
scanf("%s",how); //
if(strcmp(how, "Push") == 0) { //
scanf("%d",&x);
preOrder[j_1++] = x;
s.push(x);
} else {
inOrder[j_2++] = s.top(); //
s.pop();
}
}
node* root = create(0, N-1, 0, N-1);
dfs(root);
// for(int i=0; i<N; i++) {
// printf("%d ",preOrder[i]);
// }
// for(int i=0; i<N; i++) {
// printf("%d ",inOrder[i]);
// }
return 0;
}
---层序中序--------------------------------------------------------------------------
ANOJ 180311 模拟 D
给一棵二叉树的层序遍历序列和中序遍历序列,求这棵二叉树的先序遍历序列和后序遍历序列。
7
3 5 4 2 6 7 1
2 5 3 6 4 7 1
3 5 2 4 6 7 1
2 5 6 1 7 4 3
#include <cstdio>
const int maxn = 10010;
int n, num, layer[maxn], in[maxn];
struct tree {
tree *l, *r;
int data;
tree() {
l = r = NULL;
data = 0;
}
};
void PreOrder(tree* root) {
if(root != NULL) {
printf("%d",root->data);
num++;
if(num != n) printf(" ");
PreOrder(root->l);
PreOrder(root->r);
}
}
void PostOrder(tree * root) {
if(root != NULL) {
PostOrder(root->l);
PostOrder(root->r);
printf("%d",root->data);
num++;
if(num != n) printf(" ");
}
}
tree* CreateTree(int* layer, int* in, int t) { //t为当前数组(layer,in)的元素个数
if(t == 0) return NULL;
int Llayer[maxn], Rlayer[maxn];
int Lin[maxn], Rin[maxn];
tree* node = new tree;
node->data = layer[0];
// 在in数组中找出当前根结点的位置
int i;
for(i = 0; i < t; i++)
if(in[i] == layer[0])
break;
// 找出in数组中的左子树和右子树
int cnt = 0; //count
for(int j = 0; j < i ; j++)
Lin[cnt++] = in[j];
cnt = 0;
for(int j = i+1; j < t; j++)
Rin[cnt++] = in[j];
cnt--;
// 找出layer数组中的左子树和右子树
int Llayercnt = 0;
int Rlayercnt = 0;
for(int j = 1; j < t ; j++)
for(int k = 0 ; k < i ; k++)
if(layer[j] == in[k])
Llayer[Llayercnt++] = layer[j];
for(int j = 1; j < t; j++)
for(int k = i ; k < t; k++)
if(layer[j] == in[k])
Rlayer[Rlayercnt++] = layer[j];
node->l = CreateTree(Llayer,Lin,Llayercnt);
node->r = CreateTree(Rlayer,Rin,Rlayercnt);
return node;
}
int main() {
scanf("%d",&n);
for(int i=0; i<n; i++) scanf("%d",&layer[i]);
for(int i=0; i<n; i++) scanf("%d",&in[i]);
tree* root; // 或:tree* root = NULL;
root = CreateTree(layer,in,n);
num = 0;
PreOrder(root);
printf("\n");
num = 0;
PostOrder(root);
return 0;
} | true |
9e4d2f28f1f09d970caeb43e333217f1d1040189 | C++ | dtbinh/Psycho | /tree.cpp | UTF-8 | 8,163 | 2.890625 | 3 | [] | no_license | /**
Psychopath - Board Game
Copyleft (C) <2008> <Olivier Perriquet> (Game conception)
Copyright (C) <2015> <Robache Alexis, Sévin Léo-Paul> (AI conception and implementation>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tree.h"
#include "marble.h"
#include "node.h"
#include "myvectoroftree.h"
#include "board.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
/**
* @brief Tree::Tree constructor void of Tree class
*/
Tree::Tree()
{
level = 0;
nbSons = 0;
treeSize = 0;
father = pT_NULL;
sons = new MyVectorOfTree();
value = -1;
marblesPosition = new int[NB_TOTAL_MARBLE];
}
/**
* @brief Tree::Tree constructor of Tree class
* @param father the Tree object father of this Tree
*/
Tree::Tree(pTree father){
level = 0;
nbSons = 0;
treeSize = 0;
this->father = father;
sons = new MyVectorOfTree();
value = -1;
marblesPosition = new int[NB_TOTAL_MARBLE];
}
Tree::Tree(pTree father, Marble **dispositionPlayerOne, Marble **dispositionPlayerTwo){
level = 0;
nbSons = 0;
treeSize = 0;
this->father = father;
sons = new MyVectorOfTree();
value = -1;
marblesPosition = new int[NB_TOTAL_MARBLE];
this->setMarblePositionsWithDisposition(dispositionPlayerOne, dispositionPlayerTwo);
}
Tree::~Tree()
{
deleteAllSons();
}
/**
* @brief Tree::setLevel setter of level attribute
* @param _level integer
*/
void Tree::setLevel(int _level){
level = _level;
}
/**
* @brief Tree::getLevel getter of level attribute
* @return integer level
*/
int Tree::getLevel(){
return level;
}
/**
* @brief Tree::computeLevel compute this Tree's level from this father's level
* Calls computeLevel of all the sons of this Tree
*/
void Tree::computeLevel(){
if(father != pT_NULL){
level = father->getLevel()+1;
}else{
level = 0;
}
for(int i = 0; i < nbSons; i++){
pTree currentSon = sons->getTree(i);
if(currentSon != NULL){
currentSon->computeLevel();
}
}
}
/**
* @brief Tree::setNbSons setter of nbSons attribute
* @param _nbSons number of sons of this Tree
*/
void Tree::setNbSons(int _nbSons){
nbSons = _nbSons;
}
/**
* @brief Tree::getNbSons getter of nbSons attribute
* @return integer nbSons, the number of sons of this Tree
*/
int Tree::getNbSons(){
return nbSons;
}
void Tree::setValue(int value){
this->value = value;
}
int Tree::getValue(){
return this->value;
}
/**
* @brief Barre only used to display the Tree
* @param c the character displayed nbChar times
* @param nbChar the number of time the character c will be displayed
*/
void Barre(char c, int nbChar){
for(int i = 0; i < nbChar; i++){
cout << c;
}
}
/**
* @brief Tree::displayTreeNode only used to display thr Tree
* displays all the informations of this node
*/
void Tree::displayTreeNode(){
Barre('\t', level);
cout << "+ Tree (" << this << ") : " << endl;
Barre('\t', level);
cout << " - level = " << level << endl;
Barre('\t', level);
cout << " - nbSons = " << nbSons << endl;
Barre('\t', level);
cout << " - Father = " << father << endl;
Barre('\t', level);
cout << " - Sons[" << nbSons << "] = { ";
for(int i=0; i<nbSons; i++) {
if(i>0) {
cout << ", ";
}
cout << sons->getTree(i);
}
cout << " }" << endl;
cout << endl;
}
void Tree::displayMarbles(){
for(int i = 0 ; i < NB_TOTAL_MARBLE/2 ; i++){
cout << marblesPosition[i] << " ; ";
}
cout << endl;
}
/**
* @brief Tree::displayTree only used to display the Tree
* display this Tree's Node, calls this method on all this Trees sons
*/
void Tree::displayTree(){
displayTreeNode();
for(int i = 0; i < nbSons; i++){
pTree currentSon= sons->getTree(i);
if(currentSon != NULL){
currentSon->displayTree();
}
}
}
/**
* @brief Tree::initSons initialise MyVectorOfTree
* @param _nbSons the number of sons of this Tree (not used anymore)
*/
void Tree::initSons(int _nbSons){
if(sons != NULL){
deleteAllSons();
}
nbSons = _nbSons;
sons = new MyVectorOfTree(new Tree());
}
/**
* @brief Tree::deleteAllSons TODO check of this method does not break MyVectorOfTree
*/
void Tree::deleteAllSons(){
for(int i = 0; i < nbSons; i++){
delete sons->getTree(i);
}
deleteSons();
}
/**
* @brief Tree::deleteSons
*/
void Tree::deleteSons(){
if(sons != NULL){
free(sons);
}
nbSons = 0;
sons = NULL;
}
/**
* @brief Tree::createNextSons create _nbSons new sons to this Tree
* @param _nbSons
*/
void Tree::createNextSons(int _nbSons){
Tree* son;
sons = new MyVectorOfTree();
for(int i = 0; i < _nbSons; i++){
son = new Tree();
son->father = this;
son->computeLevel();
sons->addTree(son);
}
this->nbSons = _nbSons;
}
/**
* @brief Tree::addSon add the Tree son at index sonToAdd to MyVectorOfTree
* @param son the Tree to add
* @param sonToAdd the place to add the Tree son
*/
void Tree::addSon(pTree son,int sonToAdd){
nbSons++;
son->father = this;
son->computeLevel();
sons->addTree(son, sonToAdd);
}
/**
* @brief Tree::addSon add the Tree son to the queue of MyVectorOfTree
* @param son the Tree to add
*/
void Tree::addSon(pTree son){
nbSons++;
son->father = this;
son->computeLevel();
sons->addTree(son);
}
// Seek vertically the max value of all sons
/**
* @brief Tree::getMaxValue search the Tree for the maximum value of the sons
* set the value of this Tree to the maximum value of this Tree's sons
* @return an integer, value of this Tree
*/
int Tree::getMaxValue(){
int sonValue = -1;
for(int i = 0; i < nbSons; i++){
sonValue = sons->getTree(i)->getMinValue();
if(value < sonValue){
value = sonValue;
}
}
return this->value;
}
/**
* @brief Tree::getMinValue search the Tree for the minimum vaue of the snons
* set the value of this Tree to the minimum value of this Tree's sons
* @return an integer, value of this Tree
*/
int Tree::getMinValue(){
int sonValue = INT_MAX;
for(int i = 0; i < nbSons; i++){
sonValue = sons->getTree(i)->getMaxValue();
if(value > sonValue){
value = sonValue;
}
}
return this->value;
}
void Tree::setMarblePositionsWithDisposition(Marble ** dispositionPlayerOne, Marble** dispositionPlayerTwo){
for(int i = 0 ; i < NB_TOTAL_MARBLE / 2 ; i++){
this->marblesPosition[i] = dispositionPlayerOne[i]->getMyNode()->getId();
}
for(int i = 0; i < NB_TOTAL_MARBLE / 2; i++){
this->marblesPosition[i+(NB_TOTAL_MARBLE / 2)] = dispositionPlayerTwo[i]->getMyNode()->getId();
}
}
Marble** Tree::getDispositionFromMarblePosition(){
Marble** allMarbles = new Marble*[NB_TOTAL_MARBLE];
for(int i = 0 ; i < NB_TOTAL_MARBLE; i++){
allMarbles[i] = Util::getMarbleFromInt(i);
allMarbles[i]->setMyNode(Board::Instance().getNode(this->marblesPosition[i]));
}
return allMarbles;
}
int* Tree::getMarbleDisposition(){
return this->marblesPosition;
}
/**
* @brief Tree::pruneTree prune the subTree of index sonToPrune and rearange the sons to leave no empty space in the array
* @param sonToPrune the index of the son to prune
*/
void Tree::pruneTree(int sonToPrune){
pTree test = sons->removeTree(sonToPrune);
if(test != NULL){
nbSons--;
}
}
| true |
a566ed9a6689e65d3cb1d64ffadf48f9b409376c | C++ | Andersama/obs-voicemeeter | /circle-buffer.h | UTF-8 | 4,611 | 2.59375 | 3 | [] | no_license | #include <util/bmem.h>
#include <util/platform.h>
#include <util/threading.h>
#include <util/circlebuf.h>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <windows.h>
#include <util/windows/WinHandle.hpp>
#define CAPTURE_INTERVAL INFINITE
#define NSEC_PER_SEC 1000000000LL
extern enum audio_format get_planar_format(audio_format format);
template<class Data>
class StreamableReader {
bool _active = false;
WinHandle _readerThread;
protected:
public:
StreamableReader()
{
_stopStreamingSignal = CreateEvent(nullptr, true, false, nullptr);
}
WinHandle _stopStreamingSignal;
WinHandle stopStreamingSignal()
{
return _stopStreamingSignal;
}
void Disconnect()
{
_active = false;
SetEvent(_stopStreamingSignal);
if (_readerThread.Valid())
WaitForSingleObject(_readerThread, INFINITE);
ResetEvent(_stopStreamingSignal);
}
void Connect(HANDLE h)
{
Disconnect();
_readerThread = h;
_active = true;
}
~StreamableReader()
{
Disconnect();
}
/*Whatever inheirits this class must implement Read*/
/*
void Read(const Data *d)
{
...
}
*/
};
template<class Data>
class StreamableBuffer {
private:
std::vector<Data> _Buf;
std::vector<bool> _Used;
size_t _writeIndex;
bool _active = false;
void incrementWriteIndex()
{
_writeIndex = (_writeIndex+1) % _Buf.size();
}
protected:
public:
WinHandle _writtenToSignal;
WinHandle _stopStreamingSignal;
WinHandle writtenToSignal()
{
return _writtenToSignal;
}
WinHandle stopStreamingSignal()
{
return _stopStreamingSignal;
}
StreamableBuffer(size_t count = 32)
{
if (count == 0)
count = 32;
_Buf.reserve(count);
_Used.reserve(count);
for (size_t i = 0; i < count; i++){
Data c = Data();
_Buf.push_back(c);
_Used.push_back(false);
}
_writtenToSignal = CreateEvent(nullptr, true, false, nullptr);
_stopStreamingSignal = CreateEvent(nullptr, true, false, nullptr);
}
template<class Callable>
void Clear(Callable c) {
for (size_t i = 0; i < _Buf.size(); i++) {
if (_Used[i])
std::invoke(c, _Buf[i]);
}
std::fill_n(_Used.begin(), _Used.size(), false);
}
~StreamableBuffer()
{
Disconnect();
}
size_t writableIndex()
{
return _writeIndex;
}
size_t readableIndex()
{
return (_writeIndex + 1) % _Buf.size();
}
size_t actualIndex(size_t i)
{
return i % _Buf.size();
}
void Disconnect()
{
_active = false;
SetEvent(_stopStreamingSignal);
}
template<class Callable>
void Write(Data &d, Callable c)
{
SetEvent(_writtenToSignal);
std::invoke(c, d, _Buf[_writeIndex], _Used[_writeIndex]);
_Used[_writeIndex] = true;
incrementWriteIndex();
ResetEvent(_writtenToSignal);
}
const Data *Read(size_t i)
{
if (_Buf.size() > 0)
return &_Buf[actualIndex(i)];
else
return nullptr;
}
template<class Reader>
static DWORD WINAPI Stream(void *data)
{
std::string name = "SBData: ";
std::pair<StreamableBuffer<Data>*, Reader*> *p =
static_cast<std::pair<StreamableBuffer<Data>*, Reader*>*>(data);
StreamableBuffer<Data> *device = p->first;
Reader *source = p->second;
name += source->Name();
os_set_thread_name(name.c_str());
int waitResult = 0;
size_t readIndex = device->writableIndex();
HANDLE signals[3] = { device->_writtenToSignal, device->_stopStreamingSignal, source->_stopStreamingSignal };
while (true) {
waitResult = WaitForMultipleObjects(3, signals, false, INFINITE);
switch (waitResult) {
case WAIT_OBJECT_0:
while (readIndex != device->writableIndex()) {
source->Read(device->Read(readIndex));
readIndex = device->actualIndex(readIndex + 1);
}
break;
case WAIT_OBJECT_0+1:
case WAIT_OBJECT_0+2:
delete p;
return 0;
case WAIT_ABANDONED_0:
case WAIT_ABANDONED_0+1:
case WAIT_ABANDONED_0+2:
case WAIT_TIMEOUT:
case WAIT_FAILED:
default:
blog(LOG_ERROR, "%i", waitResult);
delete p;
return 0;
}
}
delete p;
return 0;
}
template<class Reader>
void AddListener(Reader &r)
{
ResetEvent(_stopStreamingSignal);
_active = true;
std::pair<StreamableBuffer<Data>*, Reader*> *pair =
new std::pair<StreamableBuffer<Data>*, Reader*>(this, &r);
r.Connect(CreateThread(nullptr, 0, this->Stream<Reader>, pair, 0, nullptr));
}
template<class Reader>
void AddListener(Reader *r)
{
ResetEvent(_stopStreamingSignal);
_active = true;
std::pair<StreamableBuffer<Data>*, Reader*> *pair =
new std::pair<StreamableBuffer<Data>*, Reader*>(this, r);
r->Connect(CreateThread(nullptr, 0, this->Stream<Reader>, pair, 0, nullptr));
}
};
| true |
384c1ce43a7ef67aca4e02ec44b41ffe7d4c0556 | C++ | kikozzz/cs211-extra-task-1 | /main.cpp | UTF-8 | 2,639 | 2.984375 | 3 | [] | no_license | #include <cassert>
#include <cmath>
#include "extra-task-1.h"
#include <cfloat>
#include<iostream>
using namespace std;
int main()
{
//Task 1
assert(fabs(seconds_difference(1800.0, 3600.0) - 1800.0) < DBL_EPSILON);
assert(fabs(seconds_difference(3600.0, 1800.0) - (-1800.0)) < DBL_EPSILON);
assert(fabs(seconds_difference(1800.0, 2160.0) - 360.0) < DBL_EPSILON);
assert(fabs(seconds_difference(1800.0, 1800.0) - 0.0) < DBL_EPSILON);
//Task 2
assert(fabs(hours_difference(1800.0, 3600.0) - 0.5) < DBL_EPSILON);
assert(fabs(hours_difference(3600.0, 1800.0) - (-0.5)) < DBL_EPSILON);
assert(fabs(hours_difference(1800.0, 2160.0) - 0.1) < DBL_EPSILON);
assert(fabs(hours_difference(1800.0, 1800.0) - 0.0) < DBL_EPSILON);
//Task 3
cout<< to_float_hours(0, 15, 0);
assert(fabs(to_float_hours(0, 15, 0) - 0.25) < DBL_EPSILON);
assert(fabs(to_float_hours(2, 45, 9) - 2.7525) < DBL_EPSILON);
assert(fabs(to_float_hours(1, 0, 36) - 1.01) < DBL_EPSILON);
//Task 4
assert(fabs(to_24_hour_clock(24) - 0.0) < DBL_EPSILON);
assert(fabs(to_24_hour_clock(48) - 0.0) < DBL_EPSILON);
assert(fabs(to_24_hour_clock(25) - 1.0) < DBL_EPSILON);
assert(fabs(to_24_hour_clock(4) - 4.0) < DBL_EPSILON);
assert(fabs(to_24_hour_clock(28.5) - 4.5) < DBL_EPSILON);
//Task 5
assert(get_hours(3800) == 1);
assert(get_minutes(3800) == 3);
assert(get_seconds(3800) == 20);
//Task 6
assert(fabs(time_to_utc(+0, 12.0) - 12.0) < DBL_EPSILON);
assert(fabs(time_to_utc(+1, 12.0) - 11.0) < DBL_EPSILON);
assert(fabs(time_to_utc(-1, 12.0) - 13.0) < DBL_EPSILON);
assert(fabs(time_to_utc(-11, 18.0) - 5.0) < DBL_EPSILON);
assert(fabs(time_to_utc(-1, 0.0) - 1.0) < DBL_EPSILON);
assert(fabs(time_to_utc(-1, 23.0) - 0.0) < DBL_EPSILON);
assert(fabs(time_to_utc(+6, 5.0) - 23.0) < DBL_EPSILON); //Additional test to check passing to previous day
assert(fabs(time_to_utc(-6, 23.0) - 5.0) < DBL_EPSILON);
//Task 7
assert(fabs(time_from_utc(+0, 12.0) - 12.0) < DBL_EPSILON);
assert(fabs(time_from_utc(+1, 12.0) - 13.0) < DBL_EPSILON);
assert(fabs(time_from_utc(-1, 12.0) - 11.0) < DBL_EPSILON);
assert(fabs(time_from_utc(+6, 6.0) - 12.0) < DBL_EPSILON);
assert(fabs(time_from_utc(-7, 6.0) - 23.0) < DBL_EPSILON);
assert(fabs(time_from_utc(-1, 0.0) - 23.0) < DBL_EPSILON);
assert(fabs(time_from_utc(-1, 23.0) - 22.0) < DBL_EPSILON);
assert(fabs(time_from_utc(+1, 23.0) - 0.0) < DBL_EPSILON);
assert(fabs(time_from_utc(-2, 1.0) - 23.0) < DBL_EPSILON); //Additional test to check passing to previous day
} | true |
f7b67b60ad0ecb68bcd2c28b3cf284cc085e6e4d | C++ | MysticalNobody/Light | /Light/Background.cpp | UTF-8 | 1,466 | 2.796875 | 3 | [] | no_license | #include "Background.h"
int Background::getWidth()
{
return bgSprite[0].getGlobalBounds().width;
}
void Background::setSprite(int x, int lay)
{
layer = lay;
xPos = x;
std::string path;
for (int i = 0; i < 4; i++) {
path = "Images/Background/" + std::to_string(layer) + "/" + std::to_string(i) + ".png";
if (layer == 1) {
bgTextrure[i].loadFromFile(path);
bgSprite[i].setTexture(bgTextrure[i]);
bgSprite[i].setScale(4.5, 4.5);
if (i == 0) {
bgSprite[i].setPosition(xPos, 0);
}
else if (i == 1) {
bgSprite[i].setPosition(xPos, 81);
}
else if (i == 2) {
bgSprite[i].setPosition(xPos, 45);
}
else {
bgSprite[i].setPosition(xPos, 252);
}
}
else if (layer == 2) {
if (i == 0) {
bgTextrure[i].loadFromFile(path);
bgSprite[i].setTexture(bgTextrure[i]);
bgSprite[i].setScale(4.5, 4.5);
}
else if (i > 1) {
bgTextrure[i].loadFromFile(path);
bgSprite[i].setTexture(bgTextrure[i]);
bgSprite[i].setScale(3.5, 4.5);
}
bgSprite[i].setPosition(xPos, 0);
}
}
}
void Background::draw(RenderWindow &window, int layer)
{
window.draw(bgSprite[layer]);
}
void Background::updatePos(int xPos1, int xPos2, int xPos3, int xPos4)
{
bgSprite[0].setPosition(xPos1, bgSprite[0].getPosition().y);
bgSprite[1].setPosition(xPos2, bgSprite[1].getPosition().y);
bgSprite[2].setPosition(xPos3, bgSprite[2].getPosition().y);
bgSprite[3].setPosition(xPos4, bgSprite[3].getPosition().y);
}
| true |
085371e45c3611928674690fd7d205717e0aae17 | C++ | duttaANI/AL_Lab | /Interview Bit/Dynamic Prog/Min Jumps Array.cpp | UTF-8 | 1,341 | 2.59375 | 3 | [] | no_license | #define ar array
int Solution::jump(vector<int> &A) {
int n=A.size(),jumps=0,reach=0,maxJump=0;
for(int i=0;i<n-1;i++){
maxJump=max(maxJump,i+A[i]);
if(i==reach){
jumps++;
reach=maxJump;
}
}
if(reach<n-1) return -1;
return jumps;
// int start=0, end=0, maxend=0, steps=0, n=nums.size();
// while(end < n-1)
// {
// ++steps;
// for (int i=start; i<=end; ++i)
// {
// maxend = max(nums[i] + i,maxend);
// }
// start = end;
// end = maxend;
// }
// if(maxend>=n-1)
// return steps;
// else{
// return -1;
// }
// BFS
// int n = A.size();
// vector<int> vis(n,0);
// queue<ar<int,3>> q;
// q.push({0,A[0],0});
// vis[0]=1;
// while(!q.empty()){
// ar<int,3> frnt = q.front(); q.pop();
// if(frnt[0]==n-1){
// return frnt[2];
// }
// for(int j=1;frnt[0]+j<n && j<=frnt[1]; ++j){
// if(!vis[frnt[0]+j]){
// vis[frnt[0]+j] = 1;
// if(frnt[0]+j==n-1){
// return frnt[2]+1;
// }
// q.push({frnt[0]+j,A[frnt[0]+j],frnt[2]+1});
// }
// }
// }
// return -1;
}
| true |
dd2db619ec407f99afd1e48da4ff3f8af54de57c | C++ | jTitor/cmscParallelProcessing | /src/Primitives/AABB.h | UTF-8 | 1,209 | 3.34375 | 3 | [] | no_license | #pragma once
#include "../Math/Vec3.h"
namespace Graphics
{
/**
Represents an axis-aligned bounding box.
*/
class AABB
{
private:
void init(const Vec3& pCenter, const Vec3& pHalfExtents);
//The center of the box.
Vec3 center;
//The distance from the center to
//the given axis' edge on the box.
Vec3 halfExtents;
public:
static AABB FromMinMaxBounds(const Vec3& min, const Vec3& max);
AABB();
AABB(const Vec3& pCenter, const Vec3& pHalfExtents);
/**
Gets the center of the AABB.
This can be used to modify the AABB's center.
*/
Vec3& Center();
/**
Gets a constant reference to the center of the AABB.
*/
const Vec3& GetCenter() const;
/**
Gets the dimensions of the AABB divided by 2.
This can be used to modify the AABB's dimensions.
*/
Vec3& HalfExtents();
/**
Gets a constant reference to the dimensions of the AABB divided by 2.
This can be used to modify the AABB's dimensions.
*/
const Vec3& GetHalfExtents() const;
Vec3 Min() const;
Vec3 Max() const;
/**
Constrains a vector to the AABB.
*/
Vec3 ConstrainVec3(const Vec3& v) const;
Vec3 GetViolatingPlanes(const Vec3& v) const;
bool Contains(const Vec3& v) const;
};
} | true |
91c2779e3b47254cad04b1df43ed8fd4ba9255de | C++ | hmkwizu/LRover | /Rover/Classes/LGPS.cpp | UTF-8 | 771 | 2.671875 | 3 | [] | no_license | //
// LGPS.cpp
// Rover
//
// Created by Luka Gabric on 05/08/15.
// Copyright (c) 2015 Luka Gabric. All rights reserved.
//
#include "LGPS.h"
LGPS::LGPS() {
_gps = new TinyGPS();
_ss = new SoftwareSerial(10, 11);
_ss->begin(9600);
}
void LGPS::readGPSData() {
unsigned long start = millis();
do {
while (_ss->available()) {
_gps->encode(_ss->read());
}
} while (millis() - start < 1000);
}
void LGPS::location(float *lat, float *lon, unsigned long *age) {
readGPSData();
_gps->f_get_position(lat, lon, age);
}
bool LGPS::locationValid(float lat, float lon) {
return (lat != TinyGPS::GPS_INVALID_F_ANGLE && lon != TinyGPS::GPS_INVALID_F_ANGLE);
}
float LGPS::altitude() {
return _gps->f_altitude();
}
| true |
0d089026382eb784ac53aa365042b47584d67a32 | C++ | Astreos/mobile_robots | /userFiles/ctrl/ctrl_interface/specific/Gr3Ctrl.hh | UTF-8 | 587 | 2.671875 | 3 | [] | no_license | /*!
* \author Nicolas Van der Noot
* \file Gr3Ctrl.hh
* \brief Gr3Ctrl class
*/
#ifndef _GR3_CTRL_HH_
#define _GR3_CTRL_HH_
#include "Controller.hh"
#include "CtrlStruct_gr3.h"
/*! \brief Group 3 controller
*/
class Gr3Ctrl: public Controller
{
public:
Gr3Ctrl(int robot_id, int nb_opp);
virtual ~Gr3Ctrl();
virtual void init_controller();
virtual void loop_controller();
virtual void close_controller();
inline ctrlGr3::CtrlStruct* get_cvs() const { return cvs; }
private:
ctrlGr3::CtrlStruct *cvs; ///< controller main structure
};
#endif
| true |
84b6cf8773954189ddc1946318f42678fc99b2dd | C++ | ytazz/Scenebuilder | /src/sbcalc.cpp | UTF-8 | 15,896 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <sbcalc.h>
#include <sbmessage.h>
#include <sbtokenizer.h>
namespace Scenebuilder{;
real_t Calc::unit_length = 1.0;
real_t Calc::unit_rotation = 1.0;
real_t Calc::unit_mass = 1.0;
real_t Calc::unit_time = 1.0;
Calc::Calc(){
Reset();
}
void Calc::Reset(){
terms.clear();
root = cur = 0;
}
void Calc::SetUnitLength(string_iterator_pair str){
unit_length = Calc()(str, Dimension::None);
}
void Calc::SetUnitRotation(string_iterator_pair str){
unit_rotation = Calc()(str, Dimension::None);
}
void Calc::SetUnitMass(string_iterator_pair str){
unit_mass = Calc()(str, Dimension::None);
}
void Calc::SetUnitTime(string_iterator_pair str){
unit_time = Calc()(str, Dimension::None);
}
real_t Calc::ScaleFromUnit(string_iterator_pair unit){
string_iterator_pair str0, str1;
Tokenizer tok(unit, "/", true);
// '/'で分割されている場合
str0 = tok.GetToken();
tok.Next();
if(!tok.IsEnd()){
str1 = tok.GetToken();
real_t num = ScaleFromUnit(str0);
real_t den = ScaleFromUnit(str1);
return num/den;
}
// '^'で分割されている場合
tok.Set(unit, "^", true);
str0 = tok.GetToken();
tok.Next();
if(!tok.IsEnd()){
str1 = tok.GetToken();
real_t val = ScaleFromUnit(str0);
real_t idx = to_int(str1);
return pow(val, idx);
}
// 長さ
if(unit == "km") return 1000.0;
if(unit == "m" ) return 1.0;
if(unit == "cm") return 0.01;
if(unit == "mm") return 0.001;
// 重さ
if(unit == "kg") return 1.0;
if(unit == "g" ) return 0.001;
// 時間
if(unit == "hour" ) return 3600.0;
if(unit == "h" ) return 3600.0;
if(unit == "min" ) return 60.0;
if(unit == "second") return 1.0;
if(unit == "s" ) return 1.0;
// 角度
if(unit == "rad") return 1.0;
if(unit == "deg") return M_PI / 180.0;
// 比率
if(unit == "%") return 0.01;
// 加速度
const real_t G = 9.80665;
if(unit == "G") return G;
// 力
if(unit == "N" ) return 1.0;
if(unit == "mN" ) return 0.001;
if(unit == "kgf") return G;
// モーメント
if(unit == "Nm" ) return 1.0;
if(unit == "mNm" ) return 0.001;
if(unit == "kgfcm") return G * 0.01;
throw CalcSyntaxError();
}
real_t Calc::ScaleFromDimension(int dim){
real_t L = unit_length;
real_t R = unit_rotation;
real_t M = unit_mass;
real_t T = unit_time;
switch(dim){
case Dimension::None : return 1.0;
case Dimension::L : return L;
case Dimension::R : return R;
case Dimension::M : return M;
case Dimension::T : return T;
case Dimension::L_T : return L/T;
case Dimension::L_TT : return L/(T*T);
case Dimension::R_T : return R/T;
case Dimension::ML_TT : return (M*L)/(T*T);
case Dimension::MLL_TT : return (M*L*L)/(T*T);
case Dimension::MLL : return M*L*L;
case Dimension::M_T : return M/T;
case Dimension::M_TT : return M/(T*T);
case Dimension::MLL_RT : return (M*L*L)/(R*T);
case Dimension::MLL_RTT: return (M*L*L)/(R*T*T);
case Dimension::M_LLL : return M/(L*L*L);
}
throw CalcSyntaxError();
}
real_t Calc::GetConstant(string_iterator_pair str){
if(str == "pi") return M_PI;
throw CalcSyntaxError();
}
Calc::math_func_t Calc::GetFunc(string_iterator_pair str){
if(str == "sin" ) return &sin ;
if(str == "cos" ) return &cos ;
if(str == "tan" ) return &tan ;
if(str == "exp" ) return &exp ;
if(str == "log" ) return &log ;
if(str == "sqrt") return &sqrt;
throw CalcSyntaxError();
}
void Calc::SetVariable(const string& name, real_t val){
vars[name] = val;
}
real_t Calc::GetVariable(const string& name){
map<string, real_t>::iterator it = vars.find(name);
if(it == vars.end())
return 0.0;
return it->second;
}
Calc::Term* Calc::CreateTerm(int type){
UTRef<Term> term = new Term();
term->type = type;
terms.push_back(term);
if(cur){
cur->children.push_back(term);
term->parent = cur;
}
else{
term->parent = 0;
}
return term;
}
real_t Calc::operator()(string_iterator_pair eval, int dim){
Reset();
root = cur = CreateTerm(Op::Expr);
string::const_iterator it, ibegin, iend;
ibegin = eval.begin();
iend = eval.end();
it = ibegin;
while(it != iend){
Term* prev = (cur->children.empty() ? 0 : cur->children.back());
char c = *it;
if(c == '+'){
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::Add);
else
CreateTerm(Op::Plus);
it++;
continue;
}
if(c == '-'){
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::Sub);
else
CreateTerm(Op::Minus);
it++;
continue;
}
if(c == '!'){
CreateTerm(Op::Not);
it++;
continue;
}
if(c == '*'){
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::Mul);
else
throw CalcSyntaxError();
it++;
continue;
}
if(c == '/'){
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::Div);
else
throw CalcSyntaxError();
it++;
continue;
}
// logical OR
// it could be either | or || (bitwise OR is not supported)
if(c == '|'){
if(it+1 != iend && *(it+1) == '|')
it++;
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::Or);
else
throw CalcSyntaxError();
it++;
continue;
}
// logical AND
// it could be either & or && (bitwise AND is not supported)
if(c == '&'){
if(it+1 != iend && *(it+1) == '&')
it++;
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::And);
else
throw CalcSyntaxError();
it++;
continue;
}
if(c == '^'){
if(prev && (prev->type == Op::Num || prev->type == Op::Expr || prev->type == Op::Var))
CreateTerm(Op::Pow);
else
throw CalcSyntaxError();
it++;
continue;
}
if(c == '('){
cur = CreateTerm(Op::Expr);
it++;
continue;
}
if(c == ')'){
if(!cur->parent)
throw CalcSyntaxError();
cur = cur->parent;
it++;
continue;
}
if(c == '$'){
it++;
if(it == iend || *it != '(')
throw SyntaxError();
it++;
string_iterator_pair strval;
strval.first = it;
while(it != iend && (isalpha(*it) || isdigit(*it)))
it++;
strval.second = it;
if(it == iend || *it != ')')
throw SyntaxError();
Term* t = CreateTerm(Op::Var);
t->varname = string(strval.first, strval.second);
it++;
continue;
}
if(isdigit(c) || c == '.'){
// [it0, it1) 数値部, [it1, it2) 単位部
string_iterator_pair strval;
strval.first = it;
// 小数点の上 (0桁以上)
while(it != iend && isdigit(*it))
it++;
// 小数点
if(it != iend && *it == '.'){
it++;
// 小数点の下 (1桁以上)
if(it == iend || !isdigit(*it))
throw CalcSyntaxError();
while(it != iend && isdigit(*it))
it++;
}
// 累乗部分
if(it != iend && *it == 'e'){
it++;
if(it != iend && (*it == '+' || *it == '-'))
it++;
// 指数部 (1桁以上)
if(it == iend)
throw CalcSyntaxError();
if(!isdigit(*it))
throw CalcSyntaxError();
while(it != iend && isdigit(*it))
it++;
}
strval.second = it;
Term* t = CreateTerm(Op::Num);
t->val = to_real(strval);
continue;
}
if(isalpha(c) || c == '[' || c == ']' || c == '%'){
string::const_iterator it0, it1;
it0 = it;
// - '['で始まる場合は']'までを単位とする
// - それ以外は(isalpha | '%')を単位とする
bool isUnit = false;
if(it != iend && *it == '['){
it++;
it0 = it;
while(it != iend && *it != ']')
it++;
it1 = it;
if(it != iend)
it++;
isUnit = true;
}
else{
it0 = it;
while(it != iend && (isalpha(*it) || *it == '%'))
it++;
it1 = it;
}
string str(it0, it1);
// 単位かどうかを優先的に調べる
try{
real_t unit = ScaleFromUnit(str);
Term* t = CreateTerm(Op::Unit);
t->val = unit;
continue;
}
catch(Exception&){
if(isUnit)
throw CalcSyntaxError();
}
// 定数
try{
real_t val = GetConstant(str);
Term* t = CreateTerm(Op::Num);
t->val = val;
continue;
}
catch(Exception&){}
// 関数
try{
double (*func)(double) = GetFunc(str);
Term* t = CreateTerm(Op::Func);
t->func = func;
continue;
}
catch(Exception&){}
throw CalcSyntaxError();
}
else{
throw CalcSyntaxError();
}
}
// 数式を評価
bool unitSpecified = false;
real_t val = Eval(root, &unitSpecified);
// 単位が明示されていない場合は物理的次元からスケールを決定
if(!unitSpecified)
val *= ScaleFromDimension(dim);
return val;
}
real_t Calc::Eval(Calc::Term* term, bool* unitSpecified){
if(term->children.empty())
throw CalcSyntaxError();
// まず()式を評価して数値にする
vector<Term*>::iterator it;
for(it = term->children.begin(); it != term->children.end(); it++){
Term* child = *it;
if(child->type == Op::Expr){
child->val = Eval(child);
child->type = Op::Num;
}
}
// substitute values to variables
for(it = term->children.begin(); it != term->children.end(); it++){
Term* child = *it;
if(child->type == Op::Var){
child->val = GetVariable(child->varname);
child->type = Op::Num;
}
}
// 関数
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* next = (it+1 == term->children.end() ? 0 : *(it+1));
if(child->type == Op::Func){
if(!next || next->type != Op::Num)
throw CalcSyntaxError();
child->val = child->func(next->val);
child->type = Op::Num;
it = term->children.erase(it+1);
continue;
}
it++;
}
// 単項演算子 後ろから走査して処理
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* prev = (it == term->children.begin() ? 0 : *(it-1));
Term* next = (it+1 == term->children.end() ? 0 : *(it+1));
// +符号は消すのみ
if(child->type == Op::Plus){
it = term->children.erase(it);
continue;
}
if(child->type == Op::Minus){
// 次の項が無いのはエラー
if(!next)
throw CalcSyntaxError();
// 次の項が数値なら符号を反転し,符号自体は消す
if(next->type == Op::Num){
next->val = -next->val;
it = term->children.erase(it);
continue;
}
// 次の項が符号なら,次の符号を反転し,この符号は消す
if(next->type == Op::Plus){
next->type = Op::Minus;
it = term->children.erase(it);
continue;
}
if(next->type == Op::Minus){
next->type = Op::Plus;
it = term->children.erase(it);
continue;
}
// それ以外はエラー
throw CalcSyntaxError();
}
if(child->type == Op::Not){
if(!next)
throw CalcSyntaxError();
if(next->type == Op::Num){
next->val = !next->val;
it = term->children.erase(it);
continue;
}
throw CalcSyntaxError();
}
// 次へ
it++;
}
// 二項演算子 ^
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* prev = (it == term->children.begin() ? 0 : *(it-1));
Term* next = (it+1 == term->children.end() ? 0 : *(it+1));
if(child->type == Op::Pow){
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
prev->val = pow(prev->val, next->val);
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
it++;
}
// 二項演算子 * /
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* prev = (it == term->children.begin() ? 0 : *(it-1));
Term* next = (it+1 == term->children.end() ? 0 : *(it+1));
if(child->type == Op::Mul){
// 両隣は数値項でないとエラー
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
// 前の数値項を演算結果に置換し,演算子と後ろの数値項は削除
prev->val = prev->val * next->val;
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
if(child->type == Op::Div){
// 両隣は数値項でないとエラー
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
// 前の数値項を演算結果に置換し,演算子と後ろの数値項は削除
// 零除算チェック
if(next->val == 0.0)
throw CalcSyntaxError();
prev->val = prev->val / next->val;
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
it++;
}
// 二項演算子 + -
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* prev = (it == term->children.begin() ? 0 : *(it-1));
Term* next = (it+1 == term->children.end() ? 0 : *(it+1));
if(child->type == Op::Add){
// 両隣は数値項でないとエラー
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
// 前の数値項を演算結果に置換し,演算子と後ろの数値項は削除
prev->val = prev->val + next->val;
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
if(child->type == Op::Sub){
// 両隣は数値項でないとエラー
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
// 前の数値項を演算結果に置換し,演算子と後ろの数値項は削除
prev->val = prev->val - next->val;
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
it++;
}
// || &&
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* prev = (it == term->children.begin() ? 0 : *(it-1));
Term* next = (it+1 == term->children.end() ? 0 : *(it+1));
if(child->type == Op::Or){
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
prev->val = (real_t)((prev->val != 0.0) || (next->val != 0.0));
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
if(child->type == Op::And){
if(!(prev && next && prev->type == Op::Num && next->type == Op::Num))
throw CalcSyntaxError();
prev->val = (real_t)((prev->val != 0.0) && (next->val != 0.0));
it = term->children.erase(it);
it = term->children.erase(it);
continue;
}
it++;
}
// 単位
for(it = term->children.begin(); it != term->children.end(); ){
Term* child = *it;
Term* prev = (it == term->children.begin() ? 0 : *(it-1));
if(child->type == Op::Unit){
// 直前が数値ならそれに単位の係数をかける
if(prev && prev->type == Op::Num){
prev->val *= child->val;
it = term->children.erase(it);
}
// 数値がない場合は'1'だと思って単位を数値に変換
else{
child->type = Op::Num;
}
if(unitSpecified)
*unitSpecified = true;
continue;
}
it++;
}
// ここまで来て単一の数値項が残っていればそれが演算結果,それ以外はエラー
if(term->children.size() == 1 && term->children[0]->type == Op::Num)
return term->children[0]->val;
throw CalcSyntaxError();
}
} | true |
28b6b13011745e5cc330f67b432e9ee67f8e335b | C++ | DustinsCode/CPP_Overload_hw | /main.cpp | UTF-8 | 2,048 | 3.390625 | 3 | [] | no_license | /**
* Class Writing & Operand Overloading HW
*
* @author Dustin Thurston
* @date 10/8/2017
**/
#include <string>
#include <vector>
#include <ctime>
#include <iostream>
#include "Concert.h"
using namespace std;
int main(int argc, char** args){
vector<string> friends(2);
friends[0] = "Ian";
friends[1] = "Cameron";
tm date;
//Create 10 concerts
date.tm_year = 2017;
date.tm_mon = 12;
date.tm_mday = 7;
Concert c1("Ok Go", friends, 9, date);
date.tm_year = 2018;
date.tm_mon = 1;
date.tm_mday = 23;
Concert c2("The Black Keys", friends, 10, date);
date.tm_year = 2018;
date.tm_mon = 7;
date.tm_mday = 4;
Concert c3("Las Aves", friends, 7, date);
date.tm_year = 2017;
date.tm_mon = 12;
date.tm_mday = 7;
Concert c4("Mother Mother", friends, 6, date);
date.tm_year = 2020;
date.tm_mon = 5;
date.tm_mday = 24;
Concert c5("Avenged Sevenfold", friends, 8, date);
date.tm_year = 2017;
date.tm_mon = 10;
date.tm_mday = 10;
Concert c6("Jukebox the Ghost", friends, 10, date);
date.tm_year = 2017;
date.tm_mon = 12;
date.tm_mday = 8;
Concert c7("Sylvan Esso", friends, 9, date);
date.tm_year = 2018;
date.tm_mon = 5;
date.tm_mday = 23;
Concert c8("La Dispute", friends, 10, date);
date.tm_year = 2017;
date.tm_mon = 11;
date.tm_mday = 13;
Concert c9("Haywyre", friends, 6, date);
date.tm_year = 2017;
date.tm_mon = 5;
date.tm_mday = 4;
Concert c0("Weezer", friends, 7, date);
//Put concerts into array to be sorted
vector<Concert> concerts(10);
concerts[0] = c0;
concerts[1] = c1;
concerts[2] = c2;
concerts[3] = c3;
concerts[4] = c4;
concerts[5] = c5;
concerts[6] = c6;
concerts[7] = c7;
concerts[8] = c8;
concerts[9] = c9;
/**
* Sort and print the concerts
* */
sort (concerts.begin(), concerts.begin()+10);
for(int i = 0; i < concerts.size(); i++){
cout << concerts[i] << endl;
}
} | true |
290e6b1e3e52d776434feaedd094324f4efa8044 | C++ | wyuzyf/BoostTest | /BoostTest/BoostTest/BoostTest.cpp | GB18030 | 3,855 | 3.375 | 3 | [] | no_license |
/*
#include <boost/lexical_cast.hpp>
#include <iostream>
using namespace std;
int main()
{
using boost::lexical_cast;
int a = lexical_cast<int>("123");
double b = lexical_cast<double>("123.0123456789");
string s0 = lexical_cast<string>(a);
string s1 = lexical_cast<string>(b);
cout << "number: " << a << " " << b << endl;
cout << "string: " << s0 << " " << s1 << endl;
int c = 0;
try{
c = lexical_cast<int>("abcd");
}
catch (boost::bad_lexical_cast& e){
cout << e.what() << endl;
}
system("pause");
return 0;
}
*/
//time
//(1)time
/*
#include <boost/timer.hpp>
#include <iostream>
using namespace std; //ֿռ
using namespace boost;
int main(){
timer t;
cout << "max timespan:" << t.elapsed_max() / 3600 << "h" << endl;
cout << "max timespan:" << t.elapsed_min() << "s" << endl;
//Ѿŵʱ
cout << "now time elapsed:" << t.elapsed() << "s" << endl;
system("pause");
}
*/
//(2)progress_timer
/*
#include <boost/progress.hpp>
#include <iostream>
using namespace std;
using namespace boost;
int main(){
progress_timer t;
cout << t.elapsed() << endl;
system("pause");
}
*/
//(3)չʱ
//ǰģûʲôûУ
//˼ ڳ˳ʱִȻִTry
//coutݣȴIJһ
/*
#include <boost/progress.hpp>
#include <boost/static_assert.hpp>
#include <iostream>
using namespace std;
using namespace boost;
//ʹģʵprogress_timer
template<int N > class new_progress_timer :public boost::timer{
public:
new_progress_timer(ostream &os = cout) : m_os(os)
{
BOOST_STATIC_ASSERT(N>=0&&N<=10); //̬
}
~new_progress_timer(void) //׳쳣
{
try
{
//״̬
istream::fmtflags old_flags
= m_os.setf(istream::fixed, istream::floatfield);
streamsize old_prec = m_os.precision(N);
//ʱ
m_os << elapsed() << "s \n" << endl;
//ָ״̬
m_os.flags(old_flags);
m_os.precision(old_prec);
}
catch (double){ }
}
private:
ostream & m_os;
};
//template<> class new_progress_timer<2>:public boost::progress_timer
//{};
int main(){
new_progress_timer<10> t;
//cout << "max timespan:" << t.elapsed_max() / 3600 << "h" << endl;
//cout << "max timespan:" << t.elapsed_min() << "s" << endl;
//Ѿŵʱ
//cout << "now time elapsed:" << t.elapsed() << "s" << endl;
system("pause");
}
*/
//(4)progress_display ʾִеĽ
//ҸvĴСpos,pdedԼԼ䣨һ棩
//ڶ棩ַк,ʾǺIJһӦԴBUG
#include <iostream>
#include <filesystem> //ͷļʱofstream fsд
#include <boost/progress.hpp>
#include <vector>
using namespace std;
using namespace boost;
/*
int main()
{
vector<string> v(10); //һַĶ
ofstream fs("c:\\test.txt"); //ļ
//һprogress_displayvĴС
progress_display pd(v.size());
//ʼַдļ
vector<string>::iterator pos;
for (pos = v.begin(); pos != v.end(); pos++)
{
fs << *pos << endl;
pd++; //½ʾ
}
system("pause");
}
*/
int main()
{
vector<string> v(100,"aaa");
v[10] = "";
v[23] = "";
ofstream fs("c:\\test.txt");
progress_display pd(v.size());
vector<string>::iterator pos;
for (pos = v.begin(); pos != v.end(); ++pos)
{
fs << *pos << endl;
++pd; //½ʾ
if (pos->empty())
{
cout << "null string #" << (pos - v.begin()) << endl;
}
}
system("pause");
}
| true |
dbf792f96302bb20c491d430ba7ca508607ed9f8 | C++ | Denk-Development/Airplane-Cabin-Pressure-Control | /MotorController/MotorController.ino | UTF-8 | 1,477 | 3.046875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | const int pwm = 3; // PWM control for motor outputs 1 and 2
const int dir = 2; // direction control for motor outputs 1 and 2
const int motorSlowPin = 5,
forwardControlPin = 7,
backwardControlPin = 6;
const int slowSpeed = 200, // in [0,1000]
fastSpeed = 1000; // in [0, 1000]
uint8_t motorSpeed = 200; // in [0,255]
void setup()
{
pinMode(forwardControlPin, INPUT_PULLUP);
pinMode(backwardControlPin, INPUT_PULLUP);
pinMode(motorSlowPin, INPUT_PULLUP);
// set control pins to be outputs
pinMode(pwm, OUTPUT);
pinMode(dir, OUTPUT);
}
void loop()
{
unsigned long lastMillis = 0;
while (true) {
unsigned long currentMillis = millis();
if (currentMillis < lastMillis) {
lastMillis = currentMillis;
continue;
}
lastMillis = currentMillis;
bool fwd = digitalRead(forwardControlPin) == HIGH;
bool bwd = digitalRead(backwardControlPin) == HIGH;
bool slow = digitalRead(motorSlowPin) == HIGH;
if (fwd && !bwd) {
// forward
digitalWrite(dir, LOW);
analogWrite(pwm, motorSpeed);
}
else if (bwd && !fwd) {
// backward
digitalWrite(dir, HIGH);
analogWrite(pwm, motorSpeed);
}
else {
// neutral
analogWrite(pwm, 0);
}
// turn motor only for a certain period of time
int onDelay = slow ? slowSpeed : fastSpeed;
delay(onDelay);
if (onDelay < 1000) {
analogWrite(pwm, 0);
delay(1000-onDelay);
}
}
}
| true |
28e7f7b923f65e715dc2d2cd5125c1e360e7f71b | C++ | LARG/spl-release | /core/vision/BlobDetector.cpp | UTF-8 | 24,953 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "BlobDetector.h"
BlobDetector::BlobDetector(DETECTOR_DECLARE_ARGS, ColorSegmenter& segmenter) :
DETECTOR_INITIALIZE, color_segmenter_(segmenter) {
verticalPoint = color_segmenter_.verticalPoint;
verticalPointCount = color_segmenter_.verticalPointCount;
horizontalPoint = color_segmenter_.horizontalPoint;
horizontalPointCount = color_segmenter_.horizontalPointCount;
//Blob horizontalBlob[Color::NUM_Colors][MAX_LINE_BLOBS];
for(int i = 0; i < Color::NUM_Colors; i++)
horizontalBlob.push_back(std::vector<Blob>());
//Blob verticalBlob[Color::NUM_Colors][MAX_LINE_BLOBS];
for(int i = 0; i < Color::NUM_Colors; i++)
verticalBlob.push_back(std::vector<Blob>());
}
void BlobDetector::resetOrangeBlobs() {
horizontalBlob[c_ORANGE].clear();
}
void BlobDetector::resetYellowBlobs() {
horizontalBlob[c_YELLOW].clear();
}
void BlobDetector::clearPointBlobReferences(Color color) {
int hstep, vstep;
color_segmenter_.getStepSize(hstep,vstep);
for (int y = 0; y < iparams_.height - vstep; y += vstep)
for (uint16_t i = 0; i < horizontalPointCount[color][y]; i++)
horizontalPoint[color][y][i].lbIndex = (uint16_t)-1;
for (int x = 0; x < iparams_.width - hstep; x += hstep)
for (uint16_t i = 0; i < verticalPointCount[color][x]; i++)
verticalPoint[color][x][i].lbIndex = (uint16_t)-1;
}
void BlobDetector::formWhiteLineBlobs() {
unsigned char horzColors[] = { c_WHITE };
formBlobsWithHorzLineSegs(horzColors, 1);
calculateHorizontalBlobData(c_WHITE);
unsigned char vertColors[] = { c_WHITE };
formBlobsWithVertLineSegs(vertColors, 1);
calculateVerticalBlobData(c_WHITE);
clearPointBlobReferences(c_WHITE);
}
void BlobDetector::formBlueBandBlobs() {
unsigned char vertColors[] = { c_BLUE };
formBlobsWithVertLineSegs(vertColors, 1);
calculateBandBlobData(c_BLUE);
}
void BlobDetector::formPinkBandBlobs() {
unsigned char vertColors[] = { c_PINK };
formBlobsWithVertLineSegs(vertColors, 1);
calculateBandBlobData(c_PINK);
}
void BlobDetector::formYellowBlobs() {
unsigned char horzColors[] = {
c_YELLOW
};
formBlobsWithHorzLineSegs(horzColors, 1);
}
void BlobDetector::formBlobsWithHorzLineSegs(unsigned char * horzColors, int numColors) {
int hstep, vstep;
color_segmenter_.getStepSize(hstep,vstep);
for (int c = 0; c < numColors; c++) {
unsigned char color = horzColors[c];
horizontalBlob[color].clear();
for (int y = 0; y < iparams_.height - vstep; y += vstep) {
for (uint16_t i = 0; i < horizontalPointCount[color][y]; i++) {
if (!horizontalPoint[color][y][i].isValid)
continue;
// Check for overlapping line segments with similar width
uint16_t j;
for (j = 0; j < horizontalPointCount[color][y + vstep]; j++) {
if (!horizontalPoint[color][y + vstep][j].isValid)
continue;
bool overlap =
(horizontalPoint[color][y][i].xi < horizontalPoint[color][y + vstep][j].xf &&
horizontalPoint[color][y][i].xf > horizontalPoint[color][y + vstep][j].xi);
bool similarWidth = (
(horizontalPoint[color][y][i].dx >= horizontalPoint[color][y + vstep][j].dx &&
((vparams_.blobWidthRatio[color] * horizontalPoint[color][y][i].dx <=
8 * horizontalPoint[color][y + vstep][j].dx) ||
(horizontalPoint[color][y][i].dx - horizontalPoint[color][y + vstep][j].dx <= vparams_.blobWidthAbs[color]))) ||
(horizontalPoint[color][y][i].dx <= horizontalPoint[color][y + vstep][j].dx &&
((8 * horizontalPoint[color][y][i].dx >=
vparams_.blobWidthRatio[color] * horizontalPoint[color][y + vstep][j].dx) ||
(horizontalPoint[color][y + vstep][j].dx - horizontalPoint[color][y][i].dx <= vparams_.blobWidthAbs[color]))));
if (overlap && (!vparams_.blobUseWidthRatioHorz[color] || similarWidth))
break;
}
// If no overlapping line segments, continue
if (j == horizontalPointCount[color][y + vstep])
continue;
// If line segment belongs to an existing field line blob
if (y > 0 && horizontalPoint[color][y][i].lbIndex != (uint16_t)-1) {
Blob *bl = &horizontalBlob[color][horizontalPoint[color][y][i].lbIndex];
bl->lpIndex[bl->lpCount++] = (y + vstep) << 16 | j;
horizontalPoint[color][y + vstep][j].lbIndex = horizontalPoint[color][y][i].lbIndex;
// Otherwise, create a new field line blob
} else if (horizontalBlob[color].size() < MAX_LINE_BLOBS - 1) {
const Blob b;
horizontalBlob[color].push_back(b);
Blob *bl = &horizontalBlob[color].back();
bl->lpCount = 0;
bl->lpIndex[bl->lpCount++] = y << 16 | i;
bl->lpIndex[bl->lpCount++] = (y + vstep) << 16 | j;
horizontalPoint[color][y ][i].lbIndex =
horizontalPoint[color][y + vstep][j].lbIndex = horizontalBlob[color].size() - 1;
// bound check
} else {
tlog(30, "****MAX_LINE_BLOBS exceeded while forming blobs. Please increase in Vision.h");
}
}
}
}
}
void BlobDetector::formBlobsWithVertLineSegs(unsigned char * vertColors, int numColors) {
int hstep, vstep;
color_segmenter_.getStepSize(hstep, vstep);
for (uint16_t c = 0; c < numColors; c++) {
unsigned char color = vertColors[c];
verticalBlob[color].clear();
// Form the actual blob
for (int x = 0; x < iparams_.width - hstep; x += hstep) {
//std::cout << "-- x:" << x / hstep << ";";
for (uint16_t i = 0; i < verticalPointCount[color][x]; i++) {
if (!verticalPoint[color][x][i].isValid)
continue;
uint16_t j = 0;
// Check for overlapping line segments with similar width
for (; j < verticalPointCount[color][x + hstep]; j++) {
//std::cout << "1;";
if (!verticalPoint[color][x + hstep][j].isValid)
continue;
//std::cout << "2;";
//if(color == c_WHITE) std::cout << "(" << x / hstep << "," << i << ":" << verticalPoint[color][x][i].yi << "," << verticalPoint[color][x][i].yf << "):(" << (x / hstep + 1) << "," << j << ":" << verticalPoint[color][x + hstep][j].yi << "," << verticalPoint[color][x + hstep][j].yf << ");";
bool overlap =
(verticalPoint[color][x][i].yi < verticalPoint[color][x + hstep][j].yf &&
verticalPoint[color][x][i].yf > verticalPoint[color][x + hstep][j].yi);
bool similarWidth = (
(verticalPoint[color][x][i].dy >= verticalPoint[color][x + hstep][j].dy &&
((vparams_.blobWidthRatio[color] * verticalPoint[color][x][i].dy <=
8 * verticalPoint[color][x + hstep][j].dy) ||
(verticalPoint[color][x][i].dy - verticalPoint[color][x + hstep][j].dy <= vparams_.blobWidthAbs[color]))) ||
(verticalPoint[color][x][i].dy <= verticalPoint[color][x + hstep][j].dy &&
((8 * verticalPoint[color][x][i].dy >=
vparams_.blobWidthRatio[color] * verticalPoint[color][x + hstep][j].dy) ||
(verticalPoint[color][x + hstep][j].dy - verticalPoint[color][x][i].dy <= vparams_.blobWidthAbs[color]))));
//std::cout << "sim: " << similarWidth << ";over: " << overlap << ";";
if (overlap && (!vparams_.blobUseWidthRatioVert[color] || similarWidth))
break;
}
// If no overlapping line segments, continue
if (j == verticalPointCount[color][x + hstep]) {
j = 0;
continue;
}
//std::cout << "3;";
// If line segment belongs to an existing field line blob
if (x > 0 && verticalPoint[color][x][i].lbIndex != (uint16_t)-1) {
Blob *lb =
&verticalBlob[color][verticalPoint[color][x][i].lbIndex];
lb->lpIndex[lb->lpCount++] = (x + hstep) << 16 | j;
verticalPoint[color][x + hstep][j].lbIndex =
verticalPoint[color][x][i].lbIndex;
//std::cout << "4;";
// Otherwise, create a new field line blob
} else if (verticalBlob[color].size() < MAX_LINE_BLOBS - 1){
//std::cout << "st:(" << x / hstep << "," << i << ") ,, ";
const Blob b;
verticalBlob[color].push_back(b);
Blob *lb = &verticalBlob[color].back();
lb->lpCount = 0;
lb->lpIndex[lb->lpCount++] = x << 16 | i;
lb->lpIndex[lb->lpCount++] = (x + hstep) << 16 | j;
verticalPoint[color][x][i].lbIndex =
verticalPoint[color][x + hstep][j].lbIndex = verticalBlob[color].size() - 1;
} else {
tlog(30, "****MAX_LINE_BLOBS exceeded while forming blobs. Please increase in Vision.h");
}
}
}
}
//std::cout << "\n";
}
void BlobDetector::calculateVerticalBlobData (unsigned char color) {
// Calculating Data for each blob
for (uint16_t i = 0; i < verticalBlob[color].size(); i++) {
Blob *lbi = &verticalBlob[color][i];
//if(color == c_WHITE) std::cout << i << ": " << (lbi->lpIndex[0] >> 18) << ",";
lbi->invalid = false;
// To Calculate the start and end slopes, we need to avergae out a few values to get correct results.
uint16_t amountAverage = (2 * lbi->lpCount) / 3;
amountAverage = (amountAverage > 5) ? 5 : amountAverage;
// Start Slope Initial Point
VisionPoint *lp0 = &verticalPoint[color][lbi->lpIndex[0] >> 16][lbi->lpIndex[0] & 0xfffful];
uint16_t y0 = (lp0->yi + lp0->yf) / 2, x0 = lp0->xi;
tlog(45, "Blob %i: (%i, %i)", i, x0, y0);
// Start Slope Finish Point
VisionPoint *lp1 = &verticalPoint[color][lbi->lpIndex[amountAverage] >> 16][lbi->lpIndex[amountAverage] & 0xfffful];
uint16_t y1 = (lp1->yi + lp1->yf) / 2, x1 = lp1->xi;
// End Slope Start Point
VisionPoint *lp2 = &verticalPoint[color][lbi->lpIndex[lbi->lpCount - 1 - amountAverage] >> 16][lbi->lpIndex[lbi->lpCount - 1 - amountAverage] & 0xfffful];
uint16_t y2 = (lp2->yi + lp2->yf) / 2, x2 = lp2->xi;
// End Slope Finish Point
VisionPoint *lp3 = &verticalPoint[color][lbi->lpIndex[lbi->lpCount - 1] >> 16][lbi->lpIndex[lbi->lpCount - 1] & 0xfffful];
uint16_t y3 = (lp3->yi + lp3->yf) / 2, x3 = lp3->xi;
// Calculate Final Values;
lbi->diffStart = ((float) (y1 - y0)) / (x1 - x0);
lbi->diffEnd = ((float) (y3 - y2)) / (x3 - x2);
if (amountAverage == lbi->lpCount - 1) {
lbi->doubleDiff = 0;
} else {
lbi->doubleDiff = (lbi->diffEnd - lbi->diffStart) / (x2 - x0);
}
// Calculate width at the end
amountAverage = (lbi->lpCount > 5) ? 5 : lbi->lpCount - 1;
uint16_t width = 0;
for (uint16_t point = 0; point <= amountAverage; point++) {
uint16_t yi = verticalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].yi;
uint16_t yf = verticalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].yf;
width += yf - yi;
}
width /= amountAverage + 1;
lbi->widthStart = width;
// Calculate width at the end
width = 0;
for (uint16_t point = lbi->lpCount - amountAverage - 1; point < lbi->lpCount; point++) {
uint16_t yi = verticalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].yi;
uint16_t yf = verticalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].yf;
width += yf - yi;
}
width /= amountAverage + 1;
lbi->widthEnd = width;
lbi->xi = x0;
lbi->yi = y0;
lbi->xf = x3;
lbi->yf = y3;
tlog(45, "Blob %i:- Starts at (%i, %i), Ends at (%i, %i), Num Line Points: %i, Calculate Values = (%f, %f, %f), width = (%i, %i)", i, x0, y0, x3, y3, lbi->lpCount, lbi->diffStart, lbi->diffEnd, lbi->doubleDiff, lbi->widthStart, lbi->widthEnd);
}
//std::cout << "\n";
}
void BlobDetector::calculateHorizontalBlobData(unsigned char color) {
// Calculating Data for each blob
for (uint16_t i = 0; i < horizontalBlob[color].size(); i++) {
Blob *lbi = &horizontalBlob[color][i];
lbi->invalid = false;
// To Calculate the start and end slopes, we need to avergae out a few values to get correct results.
uint16_t amountAverage = (2 * lbi->lpCount) / 3;
amountAverage = (amountAverage > 5) ? 5 : amountAverage;
// Start Slope Initial Point
VisionPoint *lp0 = &horizontalPoint[color][lbi->lpIndex[0] >> 16][lbi->lpIndex[0] & 0xfffful];
uint16_t y0 = lp0->yi, x0 = (lp0->xi + lp0->xf) / 2;
// Start Slope Finish Point
VisionPoint *lp1 = &horizontalPoint[color][lbi->lpIndex[amountAverage] >> 16][lbi->lpIndex[amountAverage] & 0xfffful];
uint16_t y1 = lp1->yi, x1 = (lp1->xi + lp1->xf) / 2;
// End Slope Start Point
VisionPoint *lp2 = &horizontalPoint[color][lbi->lpIndex[lbi->lpCount - 1 - amountAverage] >> 16][lbi->lpIndex[lbi->lpCount - 1 - amountAverage] & 0xfffful];
uint16_t y2 = lp2->yi, x2 = (lp2->xi + lp2->xf) / 2;
// End Slope Finish Point
VisionPoint *lp3 = &horizontalPoint[color][lbi->lpIndex[lbi->lpCount - 1] >> 16][lbi->lpIndex[lbi->lpCount - 1] & 0xfffful];
uint16_t y3 = lp3->yi, x3 = (lp3->xi + lp3->xf) / 2;
// Calculate Final Values;
lbi->diffStart = ((float) (x1 - x0)) / (y1 - y0);
lbi->diffEnd = ((float) (x3 - x2)) / (y3 - y2);
if (amountAverage == lbi->lpCount - 1) {
lbi->doubleDiff = 0;
} else {
lbi->doubleDiff = (lbi->diffEnd - lbi->diffStart) / (y2 - y1);
}
// Calculate width at the start
amountAverage = (lbi->lpCount > 5) ? 5 : lbi->lpCount - 1;
uint16_t width = 0;
for (uint16_t point = 0; point <= amountAverage; point++) {
uint16_t xi = horizontalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].xi;
uint16_t xf = horizontalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].xf;
width += xf - xi;
}
width /= amountAverage + 1;
lbi->widthStart = width;
// Calculate width at the end
width = 0;
for (uint16_t point = lbi->lpCount - amountAverage - 1; point < lbi->lpCount; point++) {
uint16_t xi = horizontalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].xi;
uint16_t xf = horizontalPoint[color][lbi->lpIndex[point] >> 16][lbi->lpIndex[point] & 0xfffful].xf;
width += xf - xi;
}
width /= amountAverage + 1;
lbi->widthEnd = width;
lbi->xi = x0;
lbi->yi = y0;
lbi->xf = x3;
lbi->yf = y3;
tlog(45, "Blob %i: (%i, %i) - %f, %f, %f, %i, %i", i, x0, y0, lbi->diffStart, lbi->diffEnd, lbi->doubleDiff, lbi->widthStart, lbi->widthEnd);
}
}
void BlobDetector::verticalBlobSort(unsigned char color) {
// Selection Sort
for (uint16_t i = 0; i < verticalBlob[color].size(); i++) {
Blob *minIndex = &verticalBlob[color][i];
VisionPoint *lp = &verticalPoint[color][minIndex->lpIndex[0] >> 16][minIndex->lpIndex[0] & 0xfffful];
uint32_t minVal = lp->xi * iparams_.height + ((lp->yi + lp->yf) / 2);
bool isOrigValue = true;
for (uint16_t j = i + 1; j < verticalBlob[color].size(); j++) {
Blob *tempIndex = &verticalBlob[color][j];
lp = &verticalPoint[color][tempIndex->lpIndex[0] >> 16][tempIndex->lpIndex[0] & 0xfffful];
uint32_t tempVal = lp->xi * iparams_.height + ((lp->yi + lp->yf) / 2);
if (tempVal < minVal) {
minIndex = tempIndex;
minVal = tempVal;
isOrigValue = false;
}
}
if (!isOrigValue) {
Blob temp = *minIndex;
*minIndex = verticalBlob[color][i];
verticalBlob[color][i] = temp;
}
}
}
void BlobDetector::horizontalBlobSort(unsigned char color) {
// Selection Sort
for (uint16_t i = 0; i < horizontalBlob[color].size(); i++) {
Blob *minIndex = &horizontalBlob[color][i];
VisionPoint *lp = &horizontalPoint[color][minIndex->lpIndex[0] >> 16][minIndex->lpIndex[0] & 0xfffful];
uint32_t minVal = ((lp->xi + lp->xf) / 2) + (lp->yi) * iparams_.width;
bool isOrigValue = true;
for (uint16_t j = i + 1; j < horizontalBlob[color].size(); j++) {
Blob *tempIndex = &horizontalBlob[color][j];
lp = &horizontalPoint[color][tempIndex->lpIndex[0] >> 16][tempIndex->lpIndex[0] & 0xfffful];
uint32_t tempVal = ((lp->xi + lp->xf) / 2) + (lp->yi) * iparams_.width;
if (tempVal < minVal) {
minIndex = tempIndex;
minVal = tempVal;
isOrigValue = false;
}
}
if (!isOrigValue) {
Blob temp = *minIndex;
*minIndex = horizontalBlob[color][i];
horizontalBlob[color][i] = temp;
}
}
}
void BlobDetector::formOrangeBlobs() {
formBlobs(c_ORANGE);
}
void BlobDetector::formBlobs(Color color) {
horizontalBlob[color].clear();
formBlobs(horizontalBlob[color], color);
}
void BlobDetector::formBlobs(BlobCollection& blobs, Color color) {
int hstep, vstep;
color_segmenter_.getStepSize(hstep,vstep);
for (uint16_t y = 0; y < iparams_.height - vstep; y += vstep){
for (uint16_t i = 0; i < horizontalPointCount[color][y]; i++) {
VisionPoint *lpi = &horizontalPoint[color][y][i];
//std::cout << lpi->xi << "," << lpi->xf << ",";
for (uint16_t j = 0; j < horizontalPointCount[color][y + vstep]; j++) {
VisionPoint *lpj = &horizontalPoint[color][y + vstep][j];
// if line segments overlap
if (lpi->xi < lpj->xf && lpi->xf > lpj->xi) {
// if line segment belongs to an existing blob
if (y > 0 && lpi->lbIndex != (uint16_t)-1) {
Blob *bl = &blobs[lpi->lbIndex];
if(bl->lpCount >= MAX_BLOB_VISIONPOINTS) {
tlog(30, "****Max line points exceeded while forming %s blobs. Please increase in Blob.h", getName(color));
}
else {
bl->lpIndex[bl->lpCount++] = (y + vstep) << 16 | j;
lpj->lbIndex = lpi->lbIndex;
}
// otherwise, create a new blob
} else if (blobs.size() < MAX_LINE_BLOBS - 1) {
const Blob b;
blobs.push_back(b);
Blob *bl = &blobs.back();
bl->lpCount = 0;
bl->lpIndex[bl->lpCount++] = y << 16 | i;
bl->lpIndex[bl->lpCount++] = (y + vstep) << 16 | j;
lpi->lbIndex = lpj->lbIndex = blobs.size() - 1;
tlog(30, "Created %s blob", getName(color));
// bound check
} else {
tlog(30, "****MAX_LINE_BLOBS exceeded while forming %s blobs. Please increase in Vision.h", getName(color));
}
}
}
}
}
}
void BlobDetector::calculateOrangeBlobData() {
calculateBlobData(c_ORANGE);
}
void BlobDetector::calculateBlobData(Color color) {
calculateBlobData(horizontalBlob[color], color);
}
void BlobDetector::calculateBlobData(BlobCollection& blobs, Color color) {
// Compute each blob's xi, xf, dx, yi, yf, dy
for (unsigned int i = 0; i < blobs.size(); i++) {
Blob *bl = &blobs[i];
int y = bl->lpIndex[0] >> 16;
int k = bl->lpIndex[0] & 0xffff;
bl->xi = horizontalPoint[color][y][k].xi;
bl->xf = horizontalPoint[color][y][k].xf;
bl->correctPixelRatio = horizontalPoint[color][y][k].dx;
for (int j = 1; j < bl->lpCount; j++) {
int y = bl->lpIndex[j] >> 16;
int k = bl->lpIndex[j] & 0xffff;
VisionPoint *lp = &horizontalPoint[color][y][k];
bl->xi = bl->xi > lp->xi ? lp->xi : bl->xi;
bl->xf = bl->xf < lp->xf ? lp->xf : bl->xf;
bl->correctPixelRatio += lp->dx;
}
bl->dx = bl->xf - bl->xi + 1;
bl->yi = bl->lpIndex[0] >> 16;
bl->yf = bl->lpIndex[bl->lpCount - 1] >> 16;
bl->dy = bl->yf - bl->yi;
bl->avgX = (bl->xi + bl->xf) / 2;
bl->avgY = (bl->yi + bl->yf) / 2;
tlog(30, "%s blob %i calculated: (xi:xf,yi:yf) = (%i:%i,%i:%i)", getName(color), i, bl->xi, bl->xf, bl->yi, bl->yf);
bl->correctPixelRatio /= 0.5f * bl->dx * bl->dy;
tlog(20, "correctpixel[%i] = %f",i,bl->correctPixelRatio);
}
}
void BlobDetector::calculateBandBlobData(Color color) {
for (uint32_t i = 0; i < verticalBlob[color].size(); i++) {
Blob * blob = &verticalBlob[color][i];
int j = 0;
VisionPoint *lp = &verticalPoint[color][blob->lpIndex[j] >> 16][blob->lpIndex[j] & 0xfffful];
blob->xi = lp->xi;
uint32_t sumY = (lp->yi + lp->yf) >> 1 ;
float sumWidth = lp->dy;
uint16_t minY = iparams_.height - 1, maxY = 0;
for (j = 1; j < blob->lpCount; j++) {
lp = &verticalPoint[color][blob->lpIndex[j] >> 16][blob->lpIndex[j] & 0xfffful];
sumY += (lp->yi + lp->yf) >> 1 ;
sumWidth += lp->dy;
minY = std::min(lp->yi, minY);
maxY = std::max(lp->yf, maxY);
}
blob->yi = minY;
blob->yf = maxY;
blob->xf = lp->xi;
blob->avgX = (blob->xf + blob->xi) >> 1;
blob->avgY = sumY / blob->lpCount;
blob->avgWidth = sumWidth / blob->lpCount;
}
}
uint16_t BlobDetector::mergeHorizontalBlobs(Color color, uint16_t* mergeIndex, int mergeCount) {
return mergeBlobs(color, horizontalBlob, mergeIndex, mergeCount);
}
uint16_t BlobDetector::mergeVerticalBlobs(Color color, uint16_t* mergeIndex, int mergeCount) {
return mergeBlobs(color, verticalBlob, mergeIndex, mergeCount);
}
uint16_t BlobDetector::mergeBlobs(Color color, std::vector<BlobCollection>& blobs, uint16_t *mergeIndex, int mergeCount) {
return mergeBlobs(blobs[color], mergeIndex, mergeCount);
}
// This function merges blobs by setting a merge index for blobs that get merged down. The
// merge index of a blob is the index of the earlier blob it was merged with. So the blobs
// that should actually be used are the ones whose merge indexes point to themselves.
// i.e. use blobs[i] iff mergeIndex[i] == i
uint16_t BlobDetector::mergeBlobs(BlobCollection& blobs, uint16_t *mergeIndex, int mergeCount) {
// Initialize
for (uint16_t i = 0; i < blobs.size(); i++)
mergeIndex[i] = mergeCount;
// For each (blob[i], blob[j]) tuple
for (uint16_t i = 0; i < blobs.size(); i++) {
Blob *bli = &blobs[i];
for (uint16_t j = i + 1; j < blobs.size(); j++) {
Blob *blj = &blobs[j];
//tlog(39, "comparing (%i,%i),(%i,%i) with (%i,%i),(%i,%i)", bli->xi, bli->xf, bli->yi, bli->yf, blj->xi, blj->xf, blj->yi, blj->yf);
// Merge close and overlapping blobs
bool closeX = (abs((int)bli->xf - (int)blj->xi) < 30);
bool closeY = (abs((int)bli->yf - (int)blj->yi) < 30);
bool overlapX = (bli->xi <= blj->xf && bli->xf >= blj->xi);
bool overlapY = (bli->yi <= blj->yf && bli->yf >= blj->yi);
//printf("trying to merge blob %i,%i to %i,%i with %i,%i to %i,%i: closex, %i, closey, %i, overx, %i, overy, %i\n",
//bli->xi, bli->xf, bli->yi, bli->yf,
//blj->xi, blj->xf, blj->yi, blj->yf,
//closeX, closeY, overlapX, overlapY);
if ((overlapX && closeY) ||
(closeX && overlapY) ||
(overlapX && overlapY)) {
//tlog(39,"blob %i overlaps with %i: closeX: %i closeY: %i overlapX: %i overlapY: %i", i, j, closeX, closeY, overlapX, overlapY);
bli->xi = std::min(bli->xi, blj->xi);
bli->xf = std::max(bli->xf, blj->xf);
bli->yi = std::min(bli->yi, blj->yi);
bli->yf = std::max(bli->yf, blj->yf);
bli->correctPixelRatio = (bli->dx * bli->dy * bli->correctPixelRatio + blj->dy * blj->dx * blj->correctPixelRatio);
// Update dx, dy
bli->dx = bli->xf - bli->xi;
bli->dy = bli->yf - bli->yi;
bli->correctPixelRatio /= 0.5f * bli->dx * bli->dy;
for (uint16_t k = 0; k < blj->lpCount && bli->lpCount < MAX_BLOB_VISIONPOINTS; k++) {
bli->lpIndex[bli->lpCount++] = blj->lpIndex[k];
}
uint16_t minBlobIndex = std::min(i, j);
uint16_t maxBlobIndex = std::max(i, j);
if(mergeIndex[minBlobIndex] == mergeCount) // if the minimum one hasn't been merged
mergeIndex[maxBlobIndex] = minBlobIndex; // this is the first merging for both blobs, so put them together
else
mergeIndex[maxBlobIndex] = mergeIndex[minBlobIndex]; // otherwise, merge with the earlier blob's merged blob
for (uint16_t k = 0; k < blobs.size(); k++)
if (mergeIndex[k] == maxBlobIndex)
mergeIndex[k] = mergeIndex[maxBlobIndex];
}
}
bli->avgX = (bli->xi + bli->xf) / 2;
bli->avgY = (bli->yi + bli->yf) / 2;
// FYI: This loop is incomplete. After a blob merge, you have
// to restart the entire loop which requires a runtime of O(n^4)
}
uint16_t sum = 0;
for (uint16_t i = 0; i < blobs.size(); i++)
sum += (mergeIndex[i] == mergeCount);
return sum;
}
| true |
a7fe0a51c8534d8d2853fe74d2f711f66e1aa255 | C++ | ey97/CMP202-assessment | /CMP202/Deck.cpp | UTF-8 | 1,428 | 3.40625 | 3 | [] | no_license | #include "Deck.h"
Deck::Deck() {
for (int j = 1; j < 5; j++) {
for (int i = 1; i < 14; i++) {
Card* c = new Card;
c->setRank(i);
c->setSuit(j);
deck52.push_back(*c);
delete c;
}
}
standardDeck = true;
shuffle();
changeDeckType();
}
Deck::~Deck() {
// delete currentDeck;
}
Deck::Deck(int deckCount)
{
//create as many decks as user specifies
//shuffle
for (int k = 0; k < deckCount; k++) {
for (int j = 1; j < 5; j++) {
for (int i = 1; i < 14; i++) {
Card* c = new Card;
c->setRank(i);
c->setSuit(j);
deckUnlim.push_back(*c);
delete c;
}
}
}
standardDeck = false;
shuffle();
changeDeckType();
}
void Deck::shuffle()
{
// random number generator
std::mt19937 rng(std::random_device{}());
if (standardDeck) {
int n = deck52.size();
for (int i = n - 1; i > 0; i--) {
}
std::shuffle(deck52.begin(), deck52.end(),rng);
}
else {
if (!standardDeck) {
int n = deckUnlim.size();
std::shuffle(deckUnlim.begin(), deckUnlim.end(), rng);
}
}
}
void Deck::find(int n) {
for (int i = 0; i < deck52.size()-1; i++) {
if(deck52[i].getRank() == n){
std::cout << " \n\nfound one\n\n";
}
}
}
void Deck::changeDeckType() {
if (standardDeck)
{
currentDeck = &deck52;
}
else {
currentDeck = &deckUnlim;
}
}
Card Deck::deal() {
auto card = currentDeck->back();
currentDeck->pop_back();
return card;
}
| true |
4bd4f672afbdceef933cc23d177cfb693b07495f | C++ | Pywwo/rtype | /commons/network/datagram/BinaryDatagram.hpp | UTF-8 | 1,559 | 2.75 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** rtype
** File description:
** BinaryDatagram.hpp
*/
/* Created the 20/11/2019 at 15:10 by jbulteau */
#ifndef RTYPE_BINARYDATAGRAM_HPP
#define RTYPE_BINARYDATAGRAM_HPP
#include "RtypeDatagram.hpp"
/*!
* @namespace rtype
* @brief Main namespace for all rtype project
*/
namespace rtype {
/*!
* @namespace rtype::network
* @brief Main namespace for all networking
*/
namespace network {
/*!
* @class BinaryDatagram
* @brief Datagram for binary command, mostly used to answer a previous command
*/
class BinaryDatagram : public RtypeDatagram {
public:
/*!
* @brief ctor
*/
BinaryDatagram() = default;
/*!
* @brief dtor
*/
~BinaryDatagram() = default;
/*!
* @brief Create datagram for binary command
* @param value The value to send : OK/KO (true/false)
* @param description The description of the response if needed
*/
void createBinaryDatagram(bool value, const std::string &description);
/*!
* @brief Extract value from datagram
* @param value The value filled with datagram's content
* @param description The description of the response filled with datagram's content
*/
void extractBinaryDatagram(bool &value, std::string &description);
};
}
}
#endif //RTYPE_BINARYDATAGRAM_HPP
| true |
c0ca12a7256c9df9245f53ef9778fa03b4897dff | C++ | iocodz/coj-solutions | /codes/raulcr-p3912-Accepted-s1134547.cpp | UTF-8 | 260 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
string A;
int main()
{
cin >> A;
for(int i = 0 ; i < A.size() ; i++)
if(A[i] == 'i'){
cout << "N";
return 0;
}
cout << "S";
return 0;
}
| true |
7a9fd7cccfccd46d6acba926a787c2a6ec72b66e | C++ | BuiltInParris/CS172 | /Homework 3/Data_Generator.cpp | UTF-8 | 12,097 | 3.265625 | 3 | [] | no_license | //----------------------------------------------------------------------------
//
// Data_Generator program
// Type: Program
//
// This program is designed to create a class skeleton based on user input.
// Author: Stevie Parris
// Date: 4/19/2014
//
// Modified:
//
//----------------------------------------------------------------------------
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <iomanip>
using namespace std;
int main()
{
ofstream hFile, cppFile;
string tempConst;
vector<string> listOperator;
vector<string> listPVN; // list of private variable names
vector<string> listPVT; // list of private variable types
string fileName; // this is also the classname
//MY H FILE
//creating creation comments
cout << "Enter class name: ";
getline(cin, fileName);
hFile.open(fileName + ".h");
cppFile.open(fileName + ".cpp");
cout << "Enter purpose of class: ";
getline(cin, tempConst);
hFile << "//----------------------------------------------------------------------------\n//\n";
hFile << fixed << setw(80) << "// " << fileName << " class\n";
hFile << "// Header\n//\n";
hFile << "// " << tempConst << endl;
cppFile << "//----------------------------------------------------------------------------\n//\n";
cppFile << "// " << fixed << setw(80) << fileName << " class\n";
cppFile << "// Implementation\n//\n";
cppFile << "// " << tempConst << endl;
//Prompt user for input to include in the comment header
cout << "Enter your name: ";
getline(cin, tempConst);
hFile << "// Author: " << tempConst << endl;
cppFile << "// Author: " << tempConst << endl;
cout << "Enter the date: ";
getline(cin, tempConst);
hFile << "// Date: " << tempConst << endl;
hFile << "//\n" << "// Modified: \n";
hFile << "//\n//----------------------------------------------------------------------------\n\n";
cppFile << "// Date: " << tempConst << endl;
cppFile << "//\n" << "// Modified: \n";
cppFile << "//\n//----------------------------------------------------------------------------\n\n";
//get operator information
cout << "Would you like to use an operator? (y or n)" << endl;
getline(cin, tempConst);
while (tempConst != "n")
{
cout << "Which operator: ";
getline(cin, tempConst);
listOperator.push_back(tempConst);
cout << "Would you like to use an operator? (y or n)" << endl;
getline(cin, tempConst);
}
//test to see if defined
hFile << "#ifndef __" << fileName << "__" << endl
<< "#define __" << fileName << "__" << endl << endl;
//header .h
hFile << "#include <string>" << endl;
hFile << "#include <iostream>" << endl;
hFile << "#include <vector>" << endl;
hFile << "#include <fstream>" << endl;
hFile << "using namespace std;" << endl << endl;
hFile << "// Date: " << tempConst << endl;
hFile << "//\n" << "// Modified: \n";
hFile << "//\n//----------------------------------------------------------------------------\n\n";
//header .cpp
cppFile << "#include <string>" << endl;
cppFile << "#include <iostream>" << endl;
cppFile << "#include <vector>" << endl;
cppFile << "#include <fstream>" << endl;
cppFile << "#include \"" << fileName << ".h\"" << endl;
cppFile << "using namespace std;" << endl << endl;
//Creating the class
hFile << "//----------------------------------------------------------------------------\n";
hFile << "//----------------------------------------------------------------------------\n\n";
hFile << "class " << fileName << endl;
hFile << "{" << endl; //declare class
hFile << " public:" << endl;
hFile << " //------------------------------------------------------\n";
hFile << " //----- Constructors -----------------------------------\n";
hFile << " //------------------------------------------------------\n\n";
hFile << " " << fileName << "();" << endl; // create default constructor
cppFile << "//------------------------------------------------------\n";
cppFile << "//----- Constructors -----------------------------------\n";
cppFile << "//------------------------------------------------------\n\n";
cppFile << " " << fileName << "::" << fileName << "() { }" << endl << endl; // create default constructor
//obtain private variables to use in class
cout << "Do you have any private variables? (y or n)" << endl;
getline(cin, tempConst);
while (tempConst != "n")
{
cout << "What is its type? (ex: int, float, etc.)\n";
getline(cin, tempConst);
listPVT.push_back(tempConst);
cout << "What is its name? (an underscore will be inserted after the name)\n";
getline(cin, tempConst);
listPVN.push_back(tempConst);
cout << "Do you have another variable? (y or n)\n";
getline(cin, tempConst);
}
//get number of private variables
int numbEntries = listPVN.size();
//this will hold the list of private variables
string holder;
if (numbEntries > 0)
holder = listPVT[0] + " " + listPVN[0];
if (numbEntries > 1)
{
for (int j = 1; j != numbEntries; j++)
holder = holder + ", " + listPVT[j] + " " + listPVN[j];
}
//Create constructor directly, with all attributes in list form in the .h
hFile << " " << fileName << "(" << holder << ");" << endl;
//create list constructor
cppFile << " " << fileName << "::" << fileName << "(" << holder << ")" << endl;
cppFile << " {" << endl;
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
cppFile << " " << listPVN[j] << "_ = " << listPVN[j] << ";" << endl;
}
cppFile << " }" << endl << endl;
// create copy constructor in the .h file
hFile << " " << fileName << "(const " << fileName << " & my" << fileName << ");" << endl << endl;
cppFile << " " << fileName << "::" << fileName << "(const " << fileName << " & my" << fileName << ")" << endl; // create in .cpp file
cppFile << " {" << endl;
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
cppFile << " " << listPVN[j] << "_ = my" << fileName << ".get" << listPVN[j] << "();" << endl;
}
cppFile << " }" << endl << endl;
hFile << " //------------------------------------------------------\n";
hFile << " //------- Destructor -----------------------------------\n";
hFile << " //------------------------------------------------------\n\n";
hFile << " ~" << fileName << "();" << endl << endl; // create destructor
cppFile << "//------------------------------------------------------\n";
cppFile << "//------- Destructor -----------------------------------\n";
cppFile << "//------------------------------------------------------\n\n";
cppFile << " " << fileName << "::~" << fileName << "() { }" << endl << endl; // create destructor
hFile << " //------------------------------------------------------\n";
hFile << " //------- Inspectors -----------------------------------\n";
hFile << " //------------------------------------------------------\n\n";
cppFile << "//------------------------------------------------------\n";
cppFile << "//------- Inspectors -----------------------------------\n";
cppFile << "//------------------------------------------------------\n\n";
//getter methods, the first loop is the .h the second the .cpp
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
{
hFile << " // This method gets the value of " << listPVN[j] << endl;
hFile << " " << listPVT[j] << " get" << listPVN[j] << "() const;" << endl << endl;
}
}
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
{
cppFile << " // This method gets the value of " << listPVN[j] << endl;
cppFile << " " << listPVT[j] << " " << fileName << "::get" << listPVN[j] << "() const\n";
cppFile << " {" << endl;
cppFile << " return " << listPVN[j] << "_;" << endl;
cppFile << " }" << endl << endl;
}
}
hFile << "\n //------------------------------------------------------\n";
hFile << " //-------- Mutators ------------------------------------\n";
hFile << " //------------------------------------------------------\n\n";
cppFile << "//------------------------------------------------------\n";
cppFile << "//-------- Mutators ------------------------------------\n";
cppFile << "//------------------------------------------------------\n\n";
//setter methods, the first loop is the .h the second the .cpp
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
{
hFile << " // This method sets the value of " << listPVN[j] << " to the value of the parameter." << endl;
hFile << " void set" << listPVN[j] << "(" << listPVT[j] << " " << listPVN[j] << ");" << endl << endl;
}
}
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
{
cppFile << " // This method sets the value of " << listPVN[j] << " to the value of the parameter." << endl;
cppFile << " void " << fileName << "::set" << listPVN[j] << "(" << listPVT[j] << " " << listPVN[j] << ")" << endl;
cppFile << " {" << endl;
cppFile << " " << listPVN[j] << "_ = " << listPVN[j] << ";" << endl;
cppFile << " }" << endl << endl;
}
}
hFile << "\n //------------------------------------------------------\n";
hFile << " //-------- Facilitators --------------------------------\n";
hFile << " //------------------------------------------------------\n\n";
cppFile << "\n//------------------------------------------------------\n";
cppFile << "//-------- Facilitators --------------------------------\n";
cppFile << "//------------------------------------------------------\n\n";
// toString() method in the .cpp
cppFile << " string " << fileName << "::toString()" << endl;
cppFile << " {\n";
cppFile << " //---------------------------------------------------------------------\n";
cppFile << " // Fill this code with code that changes your dataType into a string" << endl;
cppFile << " //---------------------------------------------------------------------\n";
cppFile << " return \"\";" << endl;
cppFile << " }\n";
// output() method .cpp
cppFile << "//------------------------------------------------------\n\n";
cppFile << " void " << fileName << "::" << "output(ostream &out) const\n";
cppFile << " {\n";
cppFile << " out << toString();\n";
cppFile << " }\n";
// toString() and output method .h
hFile << " //------------------------------------------------------\n";
hFile << " //return " << fileName << " in string form\n\n";
hFile << " string toString();" << endl;
hFile << " //------------------------------------------------------\n\n";
hFile << " //------------------------------------------------------\n";
hFile << " //insert " << fileName << " in output stream\n\n";
hFile << " void output(ostream &out) const;\n";
hFile << " //------------------------------------------------------\n\n";
//declare private variables in .h
hFile << " private:\n";
if (numbEntries > 0)
{
for (int j = 0; j != numbEntries; j++)
hFile << " " << listPVT[j] << " " << listPVN[j] << "_" << ";" << endl;
}
hFile << "};" << endl;
if (listOperator.size() > 0)
{
for (int j = 0; j < listOperator.size(); j++)
{
if (listOperator[j] == "<<")
{
hFile << "ostream& operator" << listOperator[j] << " (ostream & out, const " << fileName << " & myFile);\n\n";
cppFile << " ostream& operator" << listOperator[j] << " (ostream & out, const " << fileName << " & myFile)\n";
cppFile << " {\n";
cppFile << " " << fileName << ".output();\n";
cppFile << " return out;\n";
cppFile << " }\n";
}
}
}
hFile << "//----------------------------------------------------------------------------" << endl;
hFile << "//----------------------------------------------------------------------------" << endl << endl;
hFile << "#endif";
ofstream testFile;
testFile.open(fileName + "Tester.cpp");
testFile << "#include <iostream>" << endl;
testFile << "#include <string>" << endl;
testFile << "#include \"" << fileName << ".h\"" << endl;
testFile << "using namespace std;" << endl;
testFile << "int main(void)\n{" << endl;
testFile << " " << fileName << "();\n";
testFile << "}" << endl;
}
| true |
a8c275962b496a577443ce96f7bbfa63ccb1bd7b | C++ | lukeulrich/alignshop-qt | /defunct/SymbolColorScheme.h | UTF-8 | 1,902 | 2.734375 | 3 | [] | no_license | /****************************************************************************
**
** Copyright (C) 2010 Agile Genomics, LLC
** All rights reserved.
** Primary author: Luke Ulrich
**
****************************************************************************/
#ifndef SYMBOLCOLORSCHEME_H
#define SYMBOLCOLORSCHEME_H
#include "CharColorScheme.h"
#include "TextColorStyle.h"
#include <QtCore/QHash>
/**
* SymbolColorScheme extends the base CharColorScheme implementation enabling TextColorStyle's to be defined for
* specific character and symbol combinations.
*
* SymbolColorScheme is compatible with TextColorStyles defined for individual characters; however, preference is given
* to any style defined for a character and symbol combination over the individual style of a specific character.
*/
class SymbolColorScheme : public CharColorScheme
{
public:
// ------------------------------------------------------------------------------------------------
// Constructor
//! Construct an empty symbol color scheme with defaultTextColorStyle
SymbolColorScheme(const TextColorStyle &defaultTextColorStyle = TextColorStyle());
// ------------------------------------------------------------------------------------------------
// Public methods
// Also expose the single parameter textColorStyle method in the base class
using CharColorScheme::textColorStyle;
//! Sets the color style for character and each symbol combination to textColorStyle (any previous association is overwritten)
void setSymbolsTextColorStyle(char character, const QString &symbols, const TextColorStyle &textColorStyle);
//! Returns the color style for the character and symbol combination
TextColorStyle textColorStyle(char character, char symbol) const;
private:
QHash<char, QHash<char, TextColorStyle> > symbolTextColorStyles_;
};
#endif // SYMBOLCOLORSCHEME_H
| true |
9a17d9b531f065154e30f5416a9c5f4a453d4dc2 | C++ | zcphoenix2016/ZenOfDesignPatterns | /LSP/C++/Rifle.hpp | UTF-8 | 210 | 2.59375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "AbstractGun.hpp"
class Rifle : public AbstractGun
{
public:
virtual void shoot() override
{
std::cout << "Rifle shooting ..." << std::endl;
}
};
| true |
a3d3cb40671a77164faf2e93ff71de996cdbebed | C++ | Loks-/competitions | /hackerrank/practice/mathematics/fundamentals/even_odd_query.cpp | UTF-8 | 658 | 2.890625 | 3 | [
"MIT"
] | permissive | // https://www.hackerrank.com/challenges/even-odd-query
#include "common/stl/base.h"
#include "common/vector/read.h"
int main_even_odd_query() {
int N, Q, x, y;
cin >> N;
vector<int> vx = nvector::Read<int>(N);
vx.insert(vx.begin(), 1);
cin >> Q;
for (; Q; --Q) {
cin >> x >> y;
bool b = (x > y) ? true : (vx[x] == 0)
? false
: (vx[x] & 1) ? true : (x >= y)
? false
: (vx[x + 1] == 0);
cout << (b ? "Odd" : "Even") << endl;
}
return 0;
}
| true |
fafd9a42566298a89c2db8c9c860ad971cc0ba70 | C++ | chloekek/zeglo | /zeglor/value.hpp | UTF-8 | 919 | 2.890625 | 3 | [] | no_license | #pragma once
#include <boost/range/iterator_range.hpp>
namespace zeglor
{
// Every value is an instance of this abstract class. The compiler generates
// more subclasses of this class, so you should not blindly cause the layout
// (including the vtable layout) of the base class to be changed.
class value
{
public:
value();
value(value const&) = delete;
value& operator=(value const&) = delete;
virtual ~value();
// Find the values reachable through one indirection from this value.
// The garbage collector will use this information to find reachable
// values.
//
// The order of the values in the returned range is insignificant and
// duplicates are not problematic.
using children_range = boost::iterator_range<value* const*>;
virtual children_range children() const noexcept = 0;
};
}
| true |
affdd72621ffcf480b9f0dd7c724701229e480de | C++ | Red9/server-core | /rnctools/src/FilterExponentialMovingAverage.cpp | UTF-8 | 389 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "FilterExponentialMovingAverage.hpp"
FilterExponentialMovingAverage::FilterExponentialMovingAverage(double alpha_) {
alpha = alpha_;
smoothed = NAN;
}
double FilterExponentialMovingAverage::process(double value) {
if (isnan(smoothed)) {
smoothed = value;
} else {
smoothed = alpha * value + (1.0 - alpha) * smoothed;
}
return smoothed;
} | true |
23f80ccfb9fdbe9315f10af08201929d2977dd3d | C++ | jknery/projetos-gerais-cpp | /source-code-c/05_15_imprime_digitos_num.cpp | ISO-8859-1 | 1,267 | 3.984375 | 4 | [] | no_license | /* Programa que imprime separadamente os digitos de um inteiro,
da esquerda para a direita e da direita para a esquerda */
#include <stdio.h>
#include <stdlib.h>
void imprime_digitos_do_numero(int);
void imprime_digitos_invertidos(int);
int num_inv(int);
int main() {
int num;
printf("Programa que imprime separadamente os digitos de um inteiro, "
"da esquerda para a direita e da direita para a esquerda:\n\n");
printf("Informe um numero inteiro: ");
scanf("%d", &num);
printf("\n\nOs digitos do numero lido sao:\n\n");
imprime_digitos_do_numero(num);
printf("\n\nOs digitos do numero impresso ao cotrario sao:\n\n");
imprime_digitos_invertidos(num);
printf("\n\n");
system("pause");
return 0;
}
/* Funo que imprime separadamente os digitos de um inteiro,
da esquerda para a direita */
void imprime_digitos_do_numero(int num){
if (num >= 10)
imprime_digitos_do_numero(num /10);
printf("%d ", num % 10);
return;
}
/* Funo que imprime separadamente os digitos de um inteiro,
direita para a esquerda */
void imprime_digitos_invertidos(int num){
printf("%d ", num % 10);
if (num >= 10)
imprime_digitos_invertidos(num /10);
return;
}
| true |
334f2365760f094c3a88b689098da4e4463ed093 | C++ | gaurav324/Codejam | /practice/2009_qualification/alien.cc | UTF-8 | 1,989 | 3.15625 | 3 | [] | no_license | // All the includes.
#include <deque>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
// Commons.
using namespace std;
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
// Loops.
#define fori(n) for(int i=0; i<n; ++i)
#define forj(n) for(int j=0; j<n; ++j)
#define fork(n) for(int k=0; k<n; ++k)
// String funtions.
typedef stringstream SS;
void search_replace(string& original, string search_for, string replace_string) {
size_t pos = 0;
while ((pos = original.find(search_for, pos)) != string::npos) {
original.replace(pos, search_for.length(), replace_string);
pos += replace_string.length();
}
}
// Unoredered_map functions.
typedef std::unordered_map<int, long> iimap;
typedef std::unordered_map<string, long> simap;
typedef std::unordered_map<long, string> ismap;
template <typename K, typename V>
bool mfind(std::unordered_map<K, V> map, V value) {
auto search = map.find(value);
if (search == map.end()) {
return false;
} else {
return true;
}
}
// Vector Functions.
typedef vector<long> VI;
typedef vector<double> VD;
typedef vector<long long> VL;
typedef vector<string> VS;
#define sortv(v) sort(v.begin(), v.end())
#define rsortiv(v) sort(v.begin(), v.end(), std::greater<long>())
#define rsortdv(v) sort(v.begin(), v.end(), std::greater<double>())
#define rsortlv(v) sort(v.begin(), v.end(), std::greater<long long>())
// Regular expression.
bool is_match(string pattern, string word) {
regex rx(pattern);
return regex_match(word, rx);
}
// Main Logic
int main() {
int l, d, n;
cin >> l;
cin >> d;
cin >> n;
VS dic;
string word;
fori(d) {
cin >> word;
dic.pb(word);
}
string pattern;
fori(n) {
cin >> pattern;
search_replace(pattern, "(", "[");
search_replace(pattern, ")", "]");
int ans = 0;
forj(d) {
if (is_match(pattern, dic[j])) {
++ans;
}
}
cout << "Case #" << i+1 << ": " << ans << endl;
}
}
| true |
0cc32574690154b316c15f404bf97d55a3bd2bc7 | C++ | jxt8029/Simplex_Fall_2017 | /12_MeshClass - Copy/AppClass.cpp | UTF-8 | 4,416 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "AppClass.h"
void Application::InitVariables(void)
{
////Change this to your name and email
//m_sProgrammer = "Alberto Bobadilla - labigm@rit.edu";
////Alberto needed this at this position for software recording.
//m_pWindow->setPosition(sf::Vector2i(710, 0));
//Make MyMesh object (array)
m_pMesh = new MyMesh[60];
for (int i = 0; i < 60; i++) //initialize all mymesh objects to a given size and color
{
m_pMesh[i].GenerateCube(1.0f, C_BLUE);
}
//Make MyMesh object
//m_pMesh1 = new MyMesh();
//m_pMesh1->GenerateCube(1.0f, C_WHITE);
}
void Application::Update(void)
{
//Update the system so it knows how much time has passed since the last call
m_pSystem->Update();
//Is the arcball active?
ArcBall();
//Is the first person camera active?
CameraRotation();
}
void Application::Display(void)
{
// Clear the screen
ClearScreen();
matrix4 m4Projection = m_pCameraMngr->GetProjectionMatrix();
matrix4 m4View = m_pCameraMngr->GetViewMatrix();
static matrix4 m4Model;
//vector3 v3Position(0, 0, 0); //what position we want
vector3 v3PositionMove(.0005, .0005 * glm::cos(m4Model[3].x), 0); //move right at rate of .0005 per update, follow (co?)sine wave movement in y
// was v3PositionScale in commented lines
//static matrix4 m4Model; //making this static means it's the same model being used every time so it keeps being translated without resetting
//remove static to keep from updating every single update
//m4Model[3] = vector4(v3Position, 1); //set translation portion of matrix equal to position (1 as last value since it's a 4d matrix)
/*
m4Model[1][1] = .5f;
m4Model[2][2] = .5f; Scales down by .5
m4Model[3][3] = .5f;
*/
//m4Model = glm::translate(IDENTITY_M4, v3Position);
//m4Model = glm::translate(m4Model, v3Position); //m4Model starts as the identity matrix, keeps getting position added to it if static
//m4Model = glm::scale(m4Model, v3PositionScale);
//m4Model = glm::rotate(m4Model, 1.f, vector3(0, 0, 1));
//vector specifiies axis of rotation, float specifies angle of rotation
//m_pMesh[0].Render(m4Projection, m4View, m4Model);
//build space invader, line by line horizontally
for (int i = 0; i < 11; i++)
{
//large middle line 11 across
m_pMesh[i].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, 0, 0)));
if (i != 1 && i != 9)
{
m_pMesh[i + 11].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, -1, 0)));
}
//line below that
if(i == 0 || i == 2 || i == 8 || i == 10)
{
m_pMesh[i + 20].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, -2, 0)));
}
//line below
if(i == 3 || i == 4 || i == 6 || i == 7)
{
m_pMesh[i + 24].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, -3, 0)));
}
//line above 11 across line
if(i != 0 && i != 3 && i != 7 && i != 10)
{
m_pMesh[i + 28].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, 1, 0)));
}
//line above that
if(i != 0 && i != 1 && i != 9 && i != 10)
{
m_pMesh[i + 35].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, 2, 0)));
}
//line above that (antena base)
if (i == 3 || i == 7)
{
m_pMesh[i + 42].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, 3, 0)));
}
//line above that (antena top)
if(i == 2 || i == 8)
{
m_pMesh[i + 44].Render(m4Projection, m4View, m4Model * glm::translate(m4Model, vector3(i, 4, 0)));
}
}
//v3PositionMove.y = 3 * glm::sin(1 / 2 * m4Model[3][0]);
//move all cubes that make up the space invader in the same way
for (int j = 0; j < 60; j++) {
m4Model = glm::translate(m4Model, v3PositionMove);
}
//m_pMesh->Render(m_pCameraMngr->GetProjectionMatrix(), m_pCameraMngr->GetViewMatrix(), ToMatrix4(m_qArcBall));
//m_pMesh1->Render(m_pCameraMngr->GetProjectionMatrix(), m_pCameraMngr->GetViewMatrix(), glm::translate(vector3( 3.0f, 0.0f, 0.0f)));
// draw a skybox
m_pMeshMngr->AddSkyboxToRenderList();
//render list call
m_uRenderCallCount = m_pMeshMngr->Render();
//clear the render list
m_pMeshMngr->ClearRenderList();
//draw gui
DrawGUI();
//end the current frame (internally swaps the front and back buffers)
m_pWindow->display();
}
void Application::Release(void)
{
if (m_pMesh != nullptr)
{
delete[] m_pMesh;
m_pMesh = nullptr;
}
//SafeDelete(m_pMesh1);
//release GUI
ShutdownGUI();
} | true |
4fb746da9c18b09e9bfd65a396df3be2c3b94d47 | C++ | kletska/HSE-Course | /module-1/homework/Geometry/hierarchy/point.cpp | UTF-8 | 2,254 | 3.359375 | 3 | [] | no_license | #include "point.h"
#include <cmath>
bool doubleEq(double a, double b) {
const double eps = 1e-6;
return abs(a - b) < eps;
}
Point::Point(double x, double y) : x(x), y(y) {}
Point::Point(const Vector& v) : x(v.x), y(v.y) {}
bool operator==(const Point& a, const Point& b) {
return doubleEq(a.x, b.x) && doubleEq(a.y, b.y);
}
bool operator!=(const Point& a, const Point& b) { return !(a == b); }
bool inSegment(const Point& s1, const Point& s2, const Point& p) {
bool inSameLine = doubleEq(crossProduct(p - s1, s2 - s1), 0);
bool inRay1 = dotProduct(p - s1, s2 - s1) >= 0;
bool inRay2 = dotProduct(p - s2, s1 - s2) >= 0;
return inSameLine && inRay1 && inRay2;
}
Vector operator-(const Point& end, const Point& start) {
return Vector(end.x - start.x, end.y - start.y);
}
Point operator+(const Point& start, const Vector& d) {
return Point(start.x + d.x, start.y + d.y);
}
Vector::Vector(double x, double y) : x(x), y(y) {}
Vector::Vector(const Point& p) : x(p.x), y(p.y) {}
Vector Vector::half() const { return Vector(x / 2, y / 2); }
Vector Vector::reflex() const { return Vector(-x, -y); }
Vector Vector::turn90() const { return Vector(y, -x); }
Vector Vector::rotate(double angle) const {
return Vector(x * cos(angle) - y * sin(angle),
x * sin(angle) + y * cos(angle));
}
double Vector::length() const { return sqrt(x * x + y * y); }
Vector operator+(const Vector& a, const Vector& b) {
return Vector(a.x + b.x, a.y + b.y);
}
Vector operator-(const Vector& a, const Vector& b) {
return Vector(a.x - b.x, a.y - b.y);
}
Vector operator*(double c, const Vector& v) { return Vector(c * v.x, c * v.y); }
Vector operator*(const Vector& v, double c) { return Vector(c * v.x, c * v.y); }
double crossProduct(const Vector& a, const Vector& b) {
return a.x * b.y - a.y * b.x;
}
double dotProduct(const Vector& a, const Vector& b) {
return a.x * b.x + a.y * b.y;
}
bool isClockwise(const std::vector<Point>& points) {
size_t n = points.size();
for (size_t i = 0; i < n; ++i) {
Vector firstRay = points[i] - points[(i + 1) % n];
Vector secondRay = points[(i + 2) % n] - points[(i + 1) % n];
if (crossProduct(firstRay, secondRay) < 0) {
return false;
}
}
return true;
}
| true |
1946a109c6200f668127d5d3ad54f9ed78688ce0 | C++ | u14e/Program-Design-and-Algorithms | /week7/assign_1/t2.cpp | UTF-8 | 1,180 | 3.65625 | 4 | [] | no_license | /*
* 分数求和:
* 输入n个分数并对他们求和,用约分之后的最简形式表示
* eg. q/p = x1/y1 + x2/y2 +....+ xn/yn
* 5/6已经是最简形式,3/6需要规约为1/2, 3/1需要规约成3,10/3就是最简形式
* 输入:
* 第一行的输入n,代表一共有几个分数需要求和
接下来的n行是分数
* eg. 2
* 1/2
* 1/3
* 输出: 输出只有一行,即归约后的结果
* eg. 5/6
*/
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
// 存储结果(sumn/sumd)
int sumn = 0, sumd = 1;
while(n--){
int num, deno;
char slash; // 吃掉斜杠 /
cin >> num >> slash >> deno;
// 1. 先相加
sumn = sumn * deno + sumd * num;
sumd = sumd * deno;
}
// 2. 后约分
// 2.1 求最大公约数 gcd, 这里用的是欧几里得法
int a = sumd, b = sumn, c;
while(a != 0){
c = a;
a = b % a;
b = c;
}
int gcd = b;
// 2.2 分子分母同时除以gcd就可以完成约分
sumd /= gcd;
sumn /= gcd;
if (sumd > 1) {
cout << sumn << '/' << sumd << endl;
} else {
cout << sumn << endl;
}
return 0;
} | true |
864673ef69b042069dd0927f69c9a1eaf335b42c | C++ | sfindeisen/prgctst | /oi/9/1-komiwojazer-baltazar/komi.cpp | UTF-8 | 5,299 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <cstring>
const int MaxN = 30000;
const int MaxPow2 = 15; // 2^15 is enough
const int MaxM = 5000;
const unsigned int Pow2[1 + MaxPow2] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000};
typedef struct {
int a;
int b;
} TEdge;
typedef struct {
unsigned int rdist; // distance to root
int ancestors[1 + MaxPow2];
} TNode;
TEdge edges[2 * MaxN + 3];
TNode nodes[MaxN + 3];
int N = 0;
int e = 0;
using namespace std;
void init() {
memset(edges, 0, sizeof(edges));
memset(nodes, 0, sizeof(nodes));
}
inline void swap(int& a, int& b) {
int tmp = a;
a = b;
b = tmp;
}
inline void swapEdges(int a, int b) {
if (a != b) {
int tmpa = edges[a].a;
int tmpb = edges[a].b;
edges[a].a = edges[b].a;
edges[a].b = edges[b].b;
edges[b].a = tmpa;
edges[b].b = tmpb;
}
}
void qsort(int left, int right) {
if (left < right) {
swapEdges(left, (left + right) / 2);
int m = edges[left].a;
int k = left;
for (int i = left + 1; i <= right; ++i) {
if (edges[i].a <= m)
swapEdges(i, ++k);
}
swapEdges(left, k);
qsort(left, k - 1);
qsort(k + 1, right);
}
}
int findFirstEdge(int left, int right, int ni) {
if (left < right) {
int h = (left + right) / 2;
int ha = edges[h].a;
if (ha < ni)
return findFirstEdge(h + 1, right, ni);
else
if (ha > ni)
return findFirstEdge(left, h - 1, ni);
else {
if ((1 <= h) && (edges[h-1].a == ni))
return findFirstEdge(left, h - 1, ni);
else
return h;
}
} else
return left; // may be incorrect
}
void buildTree() {
std::queue<int> nfifo;
nfifo.push(1);
nodes[1].ancestors[0] = 0;
nodes[1].rdist = 0;
while (! (nfifo.empty())) {
const int ni = nfifo.front();
nfifo.pop();
const int ei = findFirstEdge(0, e-1, ni);
for (int i = ei; (i < e) && (ni == edges[i].a); ++i) {
const int nx = edges[i].b;
if ((1 != nx) && (0 == nodes[nx].ancestors[0])) {
nodes[nx].ancestors[0] = ni;
nodes[nx].rdist = 1 + nodes[ni].rdist;
nfifo.push(nx);
}
}
}
}
inline void initAncestorPtr2(int n, int dist2) {
if (nodes[n].ancestors[dist2])
return;
if (nodes[n].rdist < Pow2[dist2])
return;
initAncestorPtr2(n, dist2 - 1);
int h = nodes[n].ancestors[dist2 - 1];
initAncestorPtr2(h, dist2 - 1);
nodes[n].ancestors[dist2] = nodes[h].ancestors[dist2 - 1];
// cerr << "Node " << n << ": ancestors[" << dist2 << "] := " << nodes[h].ancestors[dist2 - 1] << std::endl;
}
int findAncestor(int n, unsigned int dist) {
// cerr << " findAncestor (" << n << ", " << dist << ")" << std::endl;
if (0 == dist)
return n;
if (1 == dist)
return nodes[n].ancestors[0];
int i = 0;
for (; (i < MaxPow2) && (Pow2[i+1] <= dist); ++i);
initAncestorPtr2(n, i);
return findAncestor(nodes[n].ancestors[i], dist - Pow2[i]);
}
int lowestCommonAncestor(int n1, int n2, int mxp2) {
if (nodes[n1].rdist > nodes[n2].rdist)
swap(n1, n2);
if (nodes[n1].rdist < nodes[n2].rdist) {
int n2a = findAncestor(n2, nodes[n2].rdist - nodes[n1].rdist);
// cerr << " findAncestor (" << n2 << ", " << nodes[n2].rdist - nodes[n1].rdist << ") returned " << n2a << std::endl;
return lowestCommonAncestor(n1, n2a, mxp2);
}
for (int i = mxp2; (0 <= i); --i) {
initAncestorPtr2(n1, i);
initAncestorPtr2(n2, i);
if (nodes[n1].ancestors[i] != nodes[n2].ancestors[i])
return lowestCommonAncestor(nodes[n1].ancestors[i], nodes[n2].ancestors[i], i);
}
return (n1 == n2) ? n1 : (nodes[n1].ancestors[0]);
}
int nodesDistance(int n1, int n2) {
int lca = lowestCommonAncestor(n1, n2, MaxPow2);
// cerr << "lca (" << n1 << "," << n2 << ") = " << lca << std::endl;
return nodes[n1].rdist + nodes[n2].rdist - (2 * nodes[lca].rdist);
}
//void printTree() {
// for (int i = 0; i <= N; ++i) {
// cerr << "Node " << i << ": parent=" << nodes[i].ancestors[0] << " rdist=" << nodes[i].rdist << std::endl;
// }
//}
int main() {
init();
int a, b;
cin >> N;
for (int i = 1; i < N; ++i) {
cin >> a >> b;
// if (a > b) swap(a,b);
edges[e] .a = a;
edges[e++].b = b;
edges[e] .a = b;
edges[e++].b = a;
}
qsort(0, e - 1);
buildTree();
// printTree();
// komiwojazer path
int M = 0;
int prevCity = 0, city = 0;
long totalDistance = 0;
cin >> M;
if (1 <= M)
cin >> prevCity;
for (int i = 1; i < M; ++i) {
cin >> city;
int ndist = nodesDistance(prevCity, city);
// cerr << "distance between " << prevCity << " and " << city << " is " << ndist << std::endl;
totalDistance += ndist;
prevCity = city;
}
cout << totalDistance << std::endl;
}
| true |
2b39bc35b0d71b631ce623715ad0703a03468642 | C++ | ole-aarnseth/CPP_Oblig2_bondesjakk | /class_board.h | UTF-8 | 632 | 2.875 | 3 | [] | no_license | // Navn: Ole Aarnseth
// Studentnr: s180482
#ifndef CLASS_BOARD_H
#define CLASS_BOARD_H
#include <vector>
#include <string>
namespace gameboard{
// These are the marks used for the board
typedef enum{EMPTY, X, O} t_mark;
// These are used as gamestatus-indicators returned by the boardStatus-funkction
typedef enum{UNFINISHED, XWIN, OWIN, DRAW} t_gamestatus;
class board
{
std::vector<std::vector<t_mark> > myBoard;
public:
void makeBoard(int size);
void flushBoard();
int getSize();
void printBoard();
bool insertMark(unsigned int a, unsigned int b, t_mark m);
t_gamestatus boardStatus();
};
}
#endif | true |
9db4c7fb68d1ea7bf2d311d7639fb8c00c394be3 | C++ | OpenLoco/OpenLoco | /src/Core/include/OpenLoco/Core/Exception.hpp | UTF-8 | 2,687 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <exception>
#include <fmt/format.h>
#include <string>
#include <string_view>
namespace OpenLoco::Exception
{
namespace Detail
{
// TODO: Make this consteval for C++20
constexpr std::string_view sanitizePath(std::string_view path)
{
#if defined(OPENLOCO_PROJECT_PATH)
constexpr std::string_view projectPath = OPENLOCO_PROJECT_PATH;
// Removes also the first slash.
return path.substr(projectPath.size() + 1);
#else
return path;
#endif
}
}
// Something like std::source_location except this works prior to C++20.
class SourceLocation
{
std::string _function;
std::string _file;
int _line;
public:
explicit SourceLocation(std::string_view func = __builtin_FUNCTION(), std::string_view file = Detail::sanitizePath(__builtin_FILE()), int line = __builtin_LINE())
: _function(func)
, _file(file)
, _line(line)
{
}
const std::string& file() const noexcept
{
return _file;
}
const std::string& function() const noexcept
{
return _function;
}
int line() const noexcept
{
return _line;
}
};
namespace Detail
{
template<typename TExceptionTag>
class ExceptionBase : public std::exception
{
private:
SourceLocation _location;
std::string _message;
public:
explicit ExceptionBase(const SourceLocation& location = SourceLocation{})
: _location{ location }
{
_message = fmt::format("Exception thrown at '{}' - {}:{}", _location.function(), _location.file(), _location.line());
}
explicit ExceptionBase(const std::string& message, const SourceLocation& location = SourceLocation{})
: _location{ location }
{
_message = fmt::format("Exception '{}', thrown at '{}' - {}:{}", message, _location.function(), _location.file(), _location.line());
}
const char* what() const noexcept override
{
return _message.c_str();
}
};
}
using RuntimeError = Detail::ExceptionBase<struct RuntimeErrorTag>;
using InvalidArgument = Detail::ExceptionBase<struct InvalidArgumentTag>;
using NotImplemented = Detail::ExceptionBase<struct NotImplementedTag>;
using InvalidOperation = Detail::ExceptionBase<struct InvalidOperationTag>;
using BadAllocation = Detail::ExceptionBase<struct BadAllocTag>;
}
| true |
8d995b537d8342341f41fb94a61eee3ee417ebf3 | C++ | rustamNSU/Final_test | /Task3.cpp | UTF-8 | 1,403 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include <thread>
#include <mutex>
class SingletonThreadSafe{
private:
static SingletonThreadSafe* singleton_;
static std::mutex mutex_;
int value_;
SingletonThreadSafe(int value): value_(value){}
public:
SingletonThreadSafe(SingletonThreadSafe &other) = delete;
void operator=(const SingletonThreadSafe &other) = delete;
static SingletonThreadSafe* Instance(int value);
int value() const{
return value_;
}
};
SingletonThreadSafe* SingletonThreadSafe::singleton_ {nullptr};
std::mutex SingletonThreadSafe::mutex_{};
SingletonThreadSafe* SingletonThreadSafe::Instance(int value)
{
std::lock_guard<std::mutex> lock(mutex_);
if(singleton_ == nullptr){
singleton_ = new SingletonThreadSafe(value);
}
return singleton_;
}
void Thread1(){
SingletonThreadSafe* singleton = SingletonThreadSafe::Instance(1);
std::cout << singleton->value() << std::endl;
}
void Thread2(){
SingletonThreadSafe* singleton = SingletonThreadSafe::Instance(2);
std::cout << singleton->value() << std::endl;
}
void Thread3(){
SingletonThreadSafe* singleton = SingletonThreadSafe::Instance(3);
std::cout << singleton->value() << std::endl;
}
int main()
{
std::thread thr1(Thread1);
std::thread thr2(Thread2);
std::thread thr3(Thread3);
thr1.join();
thr2.join();
thr3.join();
return 0;
} | true |
acd82812add18d31e677f538d9c9987f77c8eb41 | C++ | Kaktusryak/GitOOP | /OOP5/OOP5/OOP5.cpp | UTF-8 | 3,650 | 3.03125 | 3 | [] | no_license | // OOP5.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <string>
using namespace std;
class First//перший клас
{
public: string Text;//текст
First(string intext)//конструктор з присвоєння значення тексту
{
Text = intext;
}
int Size()//метод з виведення розміру
{
int t = Text.size();
return t;
}
};
class Second :public First//другий клас, який є дочірнім відносно пешого
{
public: Second(string intext) :First(intext) {}//копіювання конструктора з першого
void Sort()//сортування тесту за спаданням
{
int dif1, dif2,dif3;
for (int i = 0; i < int(Text.size()) - 1; i++)
{
for (int j = 0; j < int(Text.size()) - 1; j++)
{
dif1 = int(Text[j]);
dif2 = int(Text[j + 1]);
dif3 = dif2 - dif1;
if (dif3 > 0)
{
char s;
s = Text[j + 1];
Text[j + 1] = Text[j];
Text[j] = s;
}
}
}
}
void Print()//метод виведення
{
cout << Text;
}
};
int main()
{
cout << "Shulman Denis IS-92 Var 15 " << endl << "Enter data:";
string text;//текст
getline(cin,text);
First Text0 (text);//задання об'єкту з даним текстом
int L = Text0.Size();//довжина тексту 1
cout << "Length of 1:";
cout << L << endl;
Second Text2(text);//задання об'єкту з даним текстом
Text2.Sort();//сортування тексту 2 об'єкту
cout << "Length of 2:";
int L2 = Text2.Size();//довжина тексту 2
cout << L2 << endl;;
cout << "Text:";
Text2.Print();//метод виведення
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
| true |
7abbcb3c6609ebeab56098cc4cba1321d9f32f0d | C++ | ZiluZhang/LeetCode-Solutions | /647.cpp | UTF-8 | 661 | 3.703125 | 4 | [] | no_license | // Palindromic Substrings
// 每一个位置当做中间位置,往两边,如果相等就++
// 注意函数参数是int &型,传参的时候还是myint
class Solution {
public:
int countSubstrings(string s) {
int res = 0;
int len = s.length();
for(int i = 0; i < len; i++) {
checkPalindromic(s, res, i, i, len);
checkPalindromic(s, res, i, i+1, len);
}
return res;
}
void checkPalindromic(string s, int & res, int i, int j, int len) {
while(i >= 0 && j < len && s[i] == s[j]) {
i--;
j++;
res++;
}
return;
}
}; | true |
ba0a5f060bb3595c454a99f801f6c9afa2a74b35 | C++ | SparksEG/LintCode | /LintCode/02_尾部的零.cpp | GB18030 | 1,468 | 3.546875 | 4 | [] | no_license | #include <iostream>
using namespace std;
//#define myself
// * @param n: A long integer
// * @return: An integer, denote the number of trailing zeros in n!
#ifdef myself
long long trailingZeros(long long n)
{
// write your code here, try to do it without arithmetic operators.
int numa, numb;
numa = numb = 0;
int temp;
for (int i = 1; i < n + 1; i++)
{
temp = i;
while (temp % 2 == 0)
{
temp = temp / 2;
numa += 1;
}
while (temp % 5 == 0)
{
temp = temp / 5;
numb += 1;
}
}
if (numa < numb)
return numa;
else
return numb;
}
#else
long long trailingZeros(long long n)
{
long count = 0;
for (int i = 1; pow(5, i) <= n; i++)
count += n / (long)pow(5, i);
return count;
}
#endif
int main()
{
long long n = 127;
cout << trailingZeros(n) << endl;
system("pause");
}
//----------------------ܽ----------------------------*/
// Լ˼·
// 10 = 25; α i(0...n)ͳ2ֵĴ5ֵĴȡΪ𰸡
// Ľ5ֵĴ϶С2ֵĴ
// ȱ㣺ʱ临ӶȲҪnlogn
//
// ˸õ˼·
// 5ֵĴn = 127
// 5, 10, 15, 20, 25, 30, 35, 40...5(ܱ5ĸm)
// 25, 50, 75, 100, 1255 * 5ܱ25ĸn
// 1255 * 5 * 5 ܱ125ĸl
// num = m + n + l; | true |
b881e023af7e60697e7005608ef1239e280f32d5 | C++ | floghos/Estructura-de-Datos | /Boletines/Lab4/LinkedStack.h | UTF-8 | 220 | 2.75 | 3 | [] | no_license | #include "StackADT.h"
struct node {
int data;
node *next;
};
class LinkedStack: public StackADT {
private:
int _size;
node *_top;
public:
LinkedStack();
void push(int data);
int pop();
bool isEmpty();
};
| true |
7cff969dcc92ff0e633237f6ade2b849cc1f3a3d | C++ | ruirodriguessjr/C | /Exercicios Internet Repetição/Soma Impar de Intervalo.cpp | WINDOWS-1250 | 1,006 | 3.703125 | 4 | [] | no_license | //35. Faca um programa que some os numeros impares contidos em um intervalo definido
//pelo usu ario. O usu ario define o valor inicial do intervalo e o valor final deste intervalo
//e o programa deve somar todos os numeros mpares contidos neste intervalo. Caso o
//usu ario digite um intervalo inv alido (comecando por um valor maior que o valor final) deve
//ser escrito uma mensagem de erro na tela, Intervalo de valores inv alido e o programa
//termina. Exemplo de tela de sada: Digite o valor inicial e valor final: 5
//10. Soma dos mpares neste intervalo: 21.
#include<stdio.h>
int main(void){
int i, f, cont, somaimp=0;
printf("Digite o inicio do intervalo: ");
scanf("%d", &i);
printf("Digite o final do intervalo: ");
scanf("%d", &f);
if(i>f){
printf("Intervalo Invalido, Tente novamente.");
}
for(cont=i;cont<=f;cont++){
if(cont%2==1){
somaimp=somaimp+cont;
}
}
printf("A soma dos numeros impares digitdos eh: %d", somaimp);
return(0);
}
| true |
297bdb320d922196dbeae1f31e4e5e46837286d3 | C++ | adisabolic/currencies_converter | /DisjunktniSkupStablo.cpp | WINDOWS-1250 | 4,047 | 3.171875 | 3 | [] | no_license | #include "DisjunktniSkupStablo.h"
#include <iostream>
using namespace std;
/* Dodaje novi odnos dvije valute. Provjerava da li mozda ni jedna valuta ne postoji dosad u stablima, da li samo jedna ili ako obje postoje
u slucaju da su u razlicitim stablima vrsi uniju ta dva stabla tako sto zalijepi stablo manje visine na drugo. U slucaju da su valute u istom stablu
ne radi nista.
*/
void DisjunktniSkupStablo::Dodaj(string v1, string v2, double odnos) {
double d1(1), d2(1);
pair<string, double> s1(Nadji(v1, d1)), s2(Nadji(v2, d2));
if(s1.first == "" && s2.first == "") { // Novo stablo
visine[v1] = visine[v2] = 0;
roditelji[v1] = {v2, odnos};
roditelji[v2] = {v2, 1};
cout<<"Prvo pojavljivanje obje valute."<<endl;
}
else if(s1.first != s2.first) { // Unija
if(s1.first == "" || s2.first == "") {
if(s2.first == "") {
roditelji[v2].first = s1.first;
roditelji[v2].second = (1/odnos) * d1;
visine[v2] = visine[s1.first];
cout<<"Prvo pojavljivanje valute "<<v2<<"."<<endl;
}
else{
roditelji[v1].first = s2.first;
roditelji[v1].second = odnos * d2;
visine[s1.first] = visine[s2.first];
cout<<"Prvo pojavljivanje valute "<<v1<<"."<<endl;
}
}
else {
if(visine[s1.first] < visine[s2.first]) {
roditelji[s1.first].first = s2.first;
roditelji[s1.first].second = odnos * d2;
cout<<"Stablo valute "<<v1<<" kacim na stablo valute "<<v2<<"."<<endl;
}
else {
roditelji[s2.first].first = s1.first;
roditelji[s2.first].second = (1/odnos) * d1;
cout<<"Stablo valute "<<v2<<" kacim na stablo valute "<<v1<<"."<<endl;
}
if(visine[s1.first] == visine[s2.first])
visine[s1.first]++;
}
}
else {
cout<<"Valute su vec u istom stablu."<<endl;
}
}
/* Vraca koliko 1 novcana jedinica valute v1 iznosi u valuti v2.
*/
double DisjunktniSkupStablo::VratiOdnos(string v1, string v2) {
double d1(1), d2(1);
pair<string, double> s1(Nadji(v1, d1)), s2(Nadji(v2, d2));
if(s1.first != s2.first)
return -1;
else
return (d1/d2);
}
/* Pronalazi rekurzivno korijen stabla valute v, usput stavljajuci sve valute na putu kao djecu korijena. Usput se racuna i odnos
valute v i valute u korijenu stabla.
*/
pair<string, double> DisjunktniSkupStablo::Nadji(string v, double &d) {
if(roditelji.find(v) == roditelji.end())
return {"", -1};
if(v != roditelji[v].first) {
d *= roditelji[v].second;
roditelji[v].first = Nadji(roditelji[v].first, d).first;
roditelji[v].second = d;
}
return {roditelji[v].first, d};
}
/* Nadje valutu kojoj se mijenja vrijednost u he tabeli i sve valute kojoj je ta valuta roditelj te ih updateuje na odgovarajuci nacin.
Varijabla procenat moze biti ili pozitivna (porast vrijednosti) ili negativna (pad vrijednosti).
*/
void DisjunktniSkupStablo::PromjenaProcenat(string v, double procenat) {
if(roditelji.find(v) == roditelji.end())
cout<<"Ne postoji valuta u sistemu."<<endl;
else {
if(roditelji[v].first != v)
roditelji[v].second *= (1 + procenat/100);
for (auto it = roditelji.begin(); it != roditelji.end(); it++)
if(it->second.first == v && it->first != v)
it->second.second *= (1 - procenat/100);
}
if(procenat > 0)
cout<<"Valuta "<<v<<" je povecala svoju vrijednost za "<<procenat<<"%."<<endl;
else
cout<<"Valuta "<<v<<" je smanjila svoju vrijednost za "<<-procenat<<"%."<<endl;
}
bool DisjunktniSkupStablo::imaLi(string v) {
return roditelji.find(v) != roditelji.end();
}
| true |