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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8cb23f4f8d0cde9f701fb9dbebacce9dea94402a | C++ | codeplaysoftware/parallelts-range-exploration | /range-v3/test/view/chunk.cpp | UTF-8 | 4,834 | 3.109375 | 3 | [
"NCSA",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] | permissive | // Range v3 library
//
// Copyright Eric Niebler 2014
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
#include <list>
#include <vector>
#include <forward_list>
#include <range/v3/core.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/chunk.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/repeat.hpp>
#include <range/v3/view/cycle.hpp>
#include "../simple_test.hpp"
#include "../test_utils.hpp"
int main()
{
using namespace ranges;
std::vector<int> v = view::iota(0,11);
auto rng1 = v | view::chunk(3);
::models<concepts::RandomAccessRange>(rng1);
::models<concepts::SizedRange>(rng1);
auto it1 = ranges::begin(rng1);
::check_equal(*it1++, {0,1,2});
::check_equal(*it1++, {3,4,5});
::check_equal(*it1++, {6,7,8});
::check_equal(*it1++, {9,10});
CHECK(it1 == ranges::end(rng1));
::check_equal(*ranges::next(it1, -3), {3,4,5});
CHECK(size(rng1), 4u);
if (!ranges::v3::detail::broken_ebo)
CHECK(sizeof(rng1.begin()) == sizeof(v.begin()) * 2 + sizeof(std::ptrdiff_t) * 2);
std::forward_list<int> l = view::iota(0,11);
auto rng2 = l | view::chunk(3);
::models<concepts::ForwardRange>(rng2);
::models_not<concepts::BidirectionalRange>(rng2);
::models_not<concepts::SizedRange>(rng2);
auto it2 = ranges::begin(rng2);
::check_equal(*it2++, {0,1,2});
::check_equal(*it2++, {3,4,5});
::check_equal(*it2++, {6,7,8});
::check_equal(*it2++, {9,10});
CHECK(it2 == ranges::end(rng2));
if (!ranges::v3::detail::broken_ebo)
CHECK(sizeof(rng2.begin()) == sizeof(l.begin()) * 2 + sizeof(std::ptrdiff_t));
{
// An infinite, cyclic range with cycle length == 1
auto fives = view::repeat(5);
::models<concepts::RandomAccessRange>(fives);
auto rng = fives | view::chunk(3);
auto it = rng.begin();
using It = decltype(it);
static_assert(RandomAccessIterator<It>(), "");
auto it2 = next(it,3);
CHECK((it2 - it) == 0);
::check_equal(*it, {5,5,5});
::check_equal(*it2, {5,5,5});
}
{
// An infinite, cyclic range with cycle length == 3
std::initializer_list<int> ints = {0,1,2};
auto cyc = ints | view::cycle;
//[0,1],[2,0],[1,2],[0,1],[2,0],[1,2],
auto rng = cyc | view::chunk(2);
auto it = rng.begin();
using It = decltype(it);
static_assert(RandomAccessIterator<It>(), "");
auto it2 = next(it,2);
::check_equal(*it, {0,1});
::check_equal(*it2, {1,2});
// Strange, but not wrong necessarily:
CHECK((it - it) == 0);
CHECK((next(it) - it) == 1);
CHECK((next(it,2) - it) == 0);
CHECK((next(it,3) - it) == 0);
CHECK((next(it,4) - it) == 1);
CHECK((next(it,5) - it) == 0);
CHECK((next(it,6) - it) == 0);
CHECK((next(it,7) - it) == 1);
}
{
// An infinite, cyclic range with cycle length == 3
std::initializer_list<int> ints = {0,1,2};
auto cyc = ints | view::cycle;
//[0,1,2,0],[1,2,0,1],[2,0,1,2],...
auto rng = cyc | view::chunk(4);
auto it = rng.begin();
using It = decltype(it);
static_assert(RandomAccessIterator<It>(), "");
auto it2 = next(it,2);
::check_equal(*it, {0,1,2,0});
::check_equal(*it2, {2,0,1,2});
// Strange, but not wrong necessarily:
CHECK((it - it) == 0);
CHECK((next(it) - it) == 0);
CHECK((next(it,2) - it) == 0);
CHECK((next(it,3) - it) == 0);
CHECK((next(it,4) - it) == 0);
CHECK((next(it,5) - it) == 0);
CHECK((next(it,6) - it) == 0);
CHECK((next(it,7) - it) == 0);
}
{
// An infinite, cyclic range with cycle length == 10
std::initializer_list<int> ints = {0,1,2,3,4,5,6,7,8,9};
auto cyc = ints | view::cycle;
auto rng = cyc | view::chunk(3);
//[0,1,2],[3,4,5],[6,7,8],[9,0,1],[2,3,4],...
auto it = rng.begin();
using It = decltype(it);
static_assert(RandomAccessIterator<It>(), "");
auto it2 = next(it,2);
::check_equal(*it, {0,1,2});
::check_equal(*it2, {6,7,8});
// Strange, but not wrong necessarily:
CHECK((it - it) == 0);
CHECK((next(it) - it) == 1);
CHECK((next(it,2) - it) == 2);
CHECK((next(it,3) - it) == 3);
CHECK((next(it,4) - it) == 0);
CHECK((next(it,5) - it) == 1);
CHECK((next(it,6) - it) == 2);
CHECK((next(it,7) - it) == 0);
}
return ::test_result();
}
| true |
fa1b790e4b00dbb86e4fa590df72caa34ae0b749 | C++ | Robertorosmaninho/4_Semester_2019_UFMG | /ALG1/TP_2/src/include/lib.h | UTF-8 | 609 | 2.65625 | 3 | [] | no_license | #ifndef GREEDY_H
#define GREEDY_H
#include <vector>
#include <tuple>
class Lib{
private:
int _N = 0, _M = 0; //max_Cash and #Islands
std::vector<std::tuple<float, int, int>> _islands; //cost/points, cost, points
int _days = 0;
int _total_points = 0;
int _days_pd = 0;
int _total_points_pd = 0;
public:
Lib(int N, int M);
~Lib();
void set_islands(std::vector<std::tuple<float, int, int>> island);
void set_greedy(); //Greedy
void set_dynamic_programming(int N, int M); //PD
int get_days();
int get_total_points();
int get_days_pd();
int get_total_points_pd();
};
#endif
| true |
4068f05843ad99acae3290b175943cff3bce6b9e | C++ | kc991229/practice | /2021.3.14/test.cpp | UTF-8 | 1,281 | 2.96875 | 3 | [] | no_license | //数数问题
#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<int> GetNum(vector<int> vec, int size, int k)
{
vector<int> res(size - k + 1);
vector<vector<int>> dp(size, vector<int>(size));
map<int, int> mp;
for (int i = 0; i < size-1; i++)
{
mp.clear();
dp[i][i] = vec[i];
mp[vec[i]]++;
for (int j = i+1; j < size; j++)
{
mp[vec[j]]++;
if (mp[dp[i][j - 1]] != mp[vec[j]])
dp[i][j] = max(mp[dp[i][j - 1]], mp[vec[j]]);
else
dp[i][j] = min(dp[i][j - 1], vec[j]);
}
}
for (int i = 0, j=k-1; i < size-k+1; i++,j++)
{
res[i] = dp[i][j];
}
return res;
}
//寻找数字
vector<int> FindNums(string s)
{
vector<string> vec;
string tmp = "";
for (auto str : s)
{
if (str >= '0' && str <= '9')
{
tmp += str;
}
else
{
if (tmp != "")
{
vec.push_back(tmp);
tmp = "";
}
}
}
if (tmp != "")
vec.push_back(tmp);
vector<int> res;
for (auto st : vec)
{
res.push_back(atoi(st.c_str()));
}
return res;
}
| true |
dc0a80e1b144500fd6b525f44fbed7e2915ec3a2 | C++ | guilhermehrn/patimos | /AdmBase.cpp | UTF-8 | 2,421 | 2.53125 | 3 | [] | no_license | /*
* admBase.cpp
*
* Created on: Mar 24, 2015
* Author: guilherme
*/
#include "AdmBase.h"
AdmBase::AdmBase(char* caminhoBase) {
//incializa a consulta.
this->consulta = "select from";
//inicializa o caminho da base
this->caminhoBase = caminhoBase;
//Inicializa os rotulos da tabela
this->atributos[0].rotulo = "sexo";
//this->atributos[0].tamanho = 1;
this->atributos[1].rotulo = "idade";
//this->atributos[1].tamanho = 7;
this->atributos[2].rotulo = "rendamensal";
//this->atributos[2].tamanho = 10;
this->atributos[3].rotulo = "escolaridade";
//this->atributos[3].tamanho = 2;
this->atributos[4].rotulo = "idioma";
//this->atributos[4].tamanho = 12;
this->atributos[5].rotulo = "pais";
//this->atributos[5].tamanho = 8;
this->atributos[6].rotulo = "localizador";
//this->atributos[6].tamanho = 24;
}
void AdmBase::modificarConsulta(string consulta) {
this->consulta = consulta;
}
string AdmBase::retornarRotuloIndex(int i) {
return this->atributos[i].rotulo;
}
int AdmBase::retornarIdexRotulo(string rotulo) {
int aux = -1;
for (int i = 0; i < 7; i++) {
if (this->atributos[i].rotulo == rotulo) {
aux = i;
}
}
return aux;
}
int AdmBase::retornarTamanhoRotulo(string rotulo) {
//int i = retornarIdexRotulo(rotulo);
//return this->atributos[i].tamanho;
return 0;
}
int AdmBase::retornarTamanhoRotuloIndex(int i) {
//TODO por hora ainda não vai ser necesario
//return this->atributos[i].tamanho;
return 0;
}
void fazerConsulta(string consulta){
//TODO
}
void AdmBase::AbrirBase(){
this->arquivo.open(this->caminhoBase);
}
void AdmBase::fecharBase(){
arquivo.close();
}
int avg(list<Pessoa> resp, int indexcap){
//TODO
}
void coutn(list<Pessoa> resp, int *sexo0, int *sexo1){
sexo0 = 0;
sexo1= 0;
for (std::list<Pessoa>::iterator it=resp.begin() ; it != resp.end(); ++it){
if(*it->sexo == 0){
sexo0++;
}else{
sexo1++;
}
}
}
void groupby(list<Pessoa> resp){
//TODO
}
void AdmBase::lerBase(){
//TODO
}
void AdmBase::auxConsulta1(){
lerBase();
//TODO
}
void AdmBase::auxConsulta2(){
//TODO
}
void AdmBase::auxConsulta3(){
//TODO
}
void AdmBase::auxConsulta4(){
//TODO
}
void AdmBase::auxConsulta5(){
//TODO
}
void AdmBase::auxConsulta6(){
//TODO
}
void AdmBase::auxConsulta7(){
//TODO
}
void AdmBase::fazerConsultaFixa(int numConsulta){
//TODO
}
AdmBase::~AdmBase() {
// TODO Auto-generated destructor stub
}
| true |
e5bd07f60510e442666d31b5fc7d6db727545d48 | C++ | jjzhang166/Utils-2 | /graph/Curve.h | UTF-8 | 629 | 2.5625 | 3 | [] | no_license | #ifndef _CURVE_H
#define _CURVE_H
#include <deque>
#include <vector>
#include <string>
#include <timing/chrono.h>
#include "CurveEntry.h"
using namespace std;
#define CURVE_EXPIRATION 5.0
#define CURVE_GC 1000
class Curve
{
public:
Curve(string name_, Rhoban::chrono *start_);
~Curve();
void push(double value);
vector<pair<double, double> > getValues(double time);
void garbageCollect(double expiration);
double elapsed();
string name;
protected:
Rhoban::chrono *start;
deque<CurveEntry*> *values;
int count;
};
#endif // _CURVE_H
| true |
fbe630e4bae2246e62164e4e75255aa4fe0b8d82 | C++ | NWChen/tshirt-shooting-robot | /Code/arduino/shooter_tester/shooter_tester.ino | UTF-8 | 422 | 2.5625 | 3 | [] | no_license | #include <Servo.h>
#define k_mLeft 10
#define k_mRight 9
#define k_pSpeed A0
Servo left;
Servo right;
double speed;
void setup() {
Serial.begin(9600);
left.attach(k_mLeft);
right.attach(k_mRight);
}
void loop() {
speed = (double)map(analogRead(k_pSpeed), 0, 1023, 90, 180);
if(speed<110) speed=90;
left.write(speed);
right.write(180-speed);
Serial.println(String(speed) + ", " + String(180-speed));
}
| true |
76f098ad592786eca283028f64c1d4d081011c71 | C++ | sbhonde1/apex_simulator | /LSQ.cpp | UTF-8 | 3,013 | 3.15625 | 3 | [] | no_license | //
// @author: sonu
// @date: 12/10/18.
//
#include "LSQ.h"
#include "lsq_entry.h"
#include "helper.h"
using namespace std;
/*returns slot id
* if slot id = -1
* couldn't insert into lsq
*/
int LSQ::add_instruction_to_LSQ(LSQ_entry entry) {
if (isFull()) {
return -1;
} else if (isempty()) {
head = tail = 0;
} else {
tail = (tail + 1) % size; // tail++
}
// entry is added if and only if slot is UNALLOCATED
if (entry.allocated == UNALLOCATED) {
entry.setM_status(1);
entry.setM_index((tail)); // Assigning Slot ID here and then pushing in queue.
lsq_queue[tail] = entry; // Adding to queue
lsq_queue[tail].allocated = ALLOCATED; // Mark slot status as 'ALLOCATED'
entry.allocated = ALLOCATED;
pc_slot_map.insert(pair<int, int>(entry.getM_pc(), entry.getM_index())); // mapping pc -->index
}
return entry.getM_index();
}
LSQ_entry* LSQ::retire_instruction_from_LSQ() {
LSQ_entry* entry;
// Memory operation is performed here.
if (isempty()) {
return NULL;
} else {
entry = &lsq_queue[head];
// When retiring, Mark slot status as 'UNALLOCATED'.
lsq_queue[head].allocated = UNALLOCATED;
pc_slot_map.erase(lsq_queue[head].getM_pc()); // remove from map
if (head == tail) // Last element
{
head = tail = -1;
} else {
head = (head + 1) % size; // head++
}
}
return entry;
}
void LSQ::flushLSQEntries(int cfid) {
for (int i = 0; i < LSQ_SIZE; i++) {
if (lsq_queue[i].CFID == cfid) {
lsq_queue[i].allocated = 0;
}
}
}
LSQ::LSQ() {
head = tail = -1;
size = LSQ_SIZE;
}
bool LSQ::isFull() {
if ((tail + 1) % size == head)
return true;
else
return false;
}
bool LSQ::isempty() {
if (head == -1 && tail == -1)
return true;
else
return false;
}
LSQ::~LSQ() {
}
void LSQ::print_slot_contents(int index) {
if (index == -1) {
cout << "LSQ is Empty" << endl;
} else {
cout << "Slot No: " << index << endl;
cout << &lsq_queue[index];
}
}
ostream& operator<<(std::ostream& out, const LSQ* rob) {
out << " ** LSQ Circular Buffer Data ** " << endl;
for (int i = 0; i < LSQ_SIZE; ++i) {
out << "Slot No: " << i << endl;
out << &rob->lsq_queue[i] << endl;
}
return out;
}
void LSQ::print_lsq(int limit) {
cout << " ** LSQ Circular Buffer Data ** " << endl;
for (int i = 0; i < limit; ++i) {
cout << "Slot No: " << i << endl;
cout << &lsq_queue[i] << endl;
}
}
bool LSQ::update_LSQ_index(int index, int status, int memory_address) {
// find the respective slot and update it.
LSQ_entry* entry = &lsq_queue[index];
if (entry->allocated != UNALLOCATED) {
// Check LOAD/STORE instruction based on it, update slots.
int type = entry->getM_which_ins(); // LOAD/STORE
entry->setM_memory_addr(memory_address);
entry->setM_is_memory_addr_valid(status);
entry->setM_status(1);
} else
return false;
return true;
}
LSQ_entry *LSQ::check_head_instruction_from_LSQ() {
LSQ_entry* entry;
if (isempty()) {
return NULL;
} else {
entry = &lsq_queue[head];
}
return entry;
}
| true |
27d5313c3568a73923c2eba7a12d5f26d72965ca | C++ | cynic64/render-cpp | /src/ll/rpass.cpp | UTF-8 | 1,942 | 2.703125 | 3 | [] | no_license | #include "rpass.hpp"
#include <stdexcept>
namespace ll::rpass {
auto attachment(VkFormat format,
AttachmentSettings settings) -> VkAttachmentDescription {
VkAttachmentDescription info{};
info.format = format;
info.samples = settings.samples;
info.loadOp = settings.load;
info.storeOp = settings.store;
info.stencilLoadOp = settings.stencil_load;
info.stencilStoreOp = settings.stencil_store;
info.initialLayout = settings.initial_layout;
info.finalLayout = settings.final_layout;
return info;
}
auto attachment_ref(uint32_t idx, VkImageLayout layout) -> VkAttachmentReference {
VkAttachmentReference info{};
info.attachment = idx;
info.layout = layout;
return info;
}
auto subpass(uint32_t color_ref_ct, VkAttachmentReference* color_refs, SubpassSettings settings)
-> VkSubpassDescription
{
VkSubpassDescription info{};
info.pipelineBindPoint = settings.bind_point;
info.colorAttachmentCount = color_ref_ct;
info.pColorAttachments = color_refs;
return info;
}
auto dependency(VkSubpassDependency settings) -> VkSubpassDependency {
// So useful... I feel like a Java programmer
return settings;
}
auto rpass(VkDevice device,
uint32_t attachment_ct, VkAttachmentDescription* attachments,
uint32_t subpass_ct, VkSubpassDescription* subpasses,
uint32_t dependecy_ct, VkSubpassDependency* dependencies)
-> VkRenderPass
{
VkRenderPassCreateInfo rpass_info{};
rpass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rpass_info.attachmentCount = attachment_ct;
rpass_info.pAttachments = attachments;
rpass_info.subpassCount = subpass_ct;
rpass_info.pSubpasses = subpasses;
rpass_info.dependencyCount = dependecy_ct;
rpass_info.pDependencies = dependencies;
VkRenderPass rpass{};
if (vkCreateRenderPass(device, &rpass_info, nullptr, &rpass) != VK_SUCCESS)
throw std::runtime_error("Could not create render pass!");
return rpass;
}
}
| true |
4061cacb02d881c241ccd6eaa33e6a9ea2016998 | C++ | e-kohler/CG | /Shape.h | UTF-8 | 1,488 | 2.75 | 3 | [
"MIT"
] | permissive | #ifndef SHAPE_H
#define SHAPE_H
#include "Vector2z.h"
#include "Camera.h"
#include <gtk/gtk.h>
#include <list>
#include <vector>
#include <string>
class Shape {
protected:
std::string name;
public:
std::vector<Vector2z> world_coords;
Shape(std::string name);
~Shape();
virtual void draw(cairo_t* cr, Camera* camera) = 0; // o draw depende da camera, pois a cada redesenho, as propriedades da câmera sao levadas em conta
std::string getName();
virtual void transform(std::vector<std::vector<float> > matrix);
};
class Point : public Shape {
public:
Point(std::string name);
void draw(cairo_t* cr, Camera* camera) override;
};
class Line : public Shape {
public:
Line(std::string name);
void draw(cairo_t* cr, Camera* camera) override;
};
class Polygon : public Shape {
public:
Polygon(std::string name);
void draw(cairo_t* cr, Camera* camera) override;
gboolean filled;
};
class Curve : public Shape {
public:
Curve(std::string name);
void draw(cairo_t*cr, Camera* camera) override;
virtual void generate_curve() = 0;
std::vector<Vector2z> points{};
float step;
};
class Bezier : public Curve {
public:
Bezier(std::string name);
void generate_curve();
};
class Spline : public Curve {
public:
Spline(std::string name);
void generate_curve();
};
#endif | true |
4c093fcd9e3298c25365532ffb8511c195111493 | C++ | bmjoy/ZenonEngine | /znEngine/SceneFunctional/Scene3D.h | UTF-8 | 719 | 2.671875 | 3 | [] | no_license | #pragma once
#include "SceneNode3D.h"
class Scene3D : public Object
{
public:
Scene3D();
virtual ~Scene3D();
std::shared_ptr<SceneNode3D> GetRootNode() const;
template<class T, class ... Args>
std::shared_ptr<T> CreateSceneNode(std::shared_ptr<SceneNode3D> Parent, Args&&... _Args);
void Accept(IVisitor& visitor);
void OnUpdate(UpdateEventArgs& e);
private:
std::shared_ptr<SceneNode3D> m_pRootNode;
};
template<class T, class ... Args>
inline std::shared_ptr<T> Scene3D::CreateSceneNode(std::shared_ptr<SceneNode3D> Parent, Args&& ..._Args)
{
std::shared_ptr<T> newNode = std::make_shared<T>(_Args);
newNode->SetParent(Parent);
newNode->RegisterComponents();
return newNode;
}
| true |
b467ba4d6d588b6da014ce7de609d326dd0b75b4 | C++ | juniway/lint | /algorithms/sort/basic3.cpp | UTF-8 | 1,171 | 3.5625 | 4 | [] | no_license | #include <stdio.h>
/*
* Bubble Sort
* O(n^2)
*/
void bubbleSort(int a[], int n){
int i, j, temp;
for (i = (n - 1); i >= 0; i--){
for (j = 1; j <= i; j++){
if (a[j-1] > a[j]){
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}
// selection sort
// best case: O(n^2)
// avrg case: O(n^2)
// worst case: O(n^2)
void selection_sort(int a[], int n){
int i, j;
int min, temp;
for (i = 0; i < n-1; i++){
min = i;
for (j = i+1; j < n; j++){
if (a[j] < a[min])
min = j;
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
// insertion_sort
// best case: O(n)
// avrg case: O(n^2)
// worst case: O(n^2)
void insertion_sort(int a[], int n){
int i, j, index;
for (i = 1; i < n; i++){
index = a[i];
j = i;
while ((j>0)&&(a[j-1] > index)){
a[j]=a[j-1];
j=j-1;
}
a[j]=index;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
heap_sort(a, n);
int i=0;
for(; i<n;i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
| true |
147c61cf2cb7569cf4c2812267278659f6d2f2f6 | C++ | hsntrq/towers-defense-sdl | /towercards/goldcard.hpp | UTF-8 | 317 | 2.6875 | 3 | [] | no_license | #include "towercard.hpp"
/**
* \brief This class stores the attributes and methods specific to the bomb tower
*
*/
class GoldCard : public TowerCard
{
public:
/**
* Simple constructor
*/
GoldCard();
/**
* Constructor that initializes attributes
*/
GoldCard(int x, int y);
}; | true |
30611577917ce2463c893f8870c428f6c27ce6f7 | C++ | sd2048/LeetCode | /976. Largest Perimeter Triangle.cpp | UTF-8 | 588 | 3.421875 | 3 | [] | no_license | bool decrSort(int a, int b) { return( a > b ); }
class Solution {
public:
int largestPerimeter(vector<int>& A)
{
std::sort(A.begin(), A.end(), decrSort);
int max = 0;
for (int i = 0; i < A.size()-2; ++i) // leave space for the two smaller sides (a, b)
{
if (A[i+1] + A[i+2] > A[i]) // valid triangle
{
int perimeter = A[i+1] + A[i+2] + A[i];
if (perimeter > max)
max = perimeter;
}
}
return max;
}
}; | true |
551626c07faed5341e027901f73ddc96d3751e95 | C++ | jakcron/libnintendo-hac | /src/DeltaMetaExtendedHeader.cpp | UTF-8 | 2,096 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <nn/hac/DeltaMetaExtendedHeader.h>
nn::hac::DeltaMetaExtendedHeader::DeltaMetaExtendedHeader()
{
clear();
}
nn::hac::DeltaMetaExtendedHeader::DeltaMetaExtendedHeader(const DeltaMetaExtendedHeader& other)
{
*this = other;
}
void nn::hac::DeltaMetaExtendedHeader::operator=(const DeltaMetaExtendedHeader& other)
{
clear();
mRawBinary = other.mRawBinary;
mApplicationId = other.mApplicationId;
mExtendedDataSize = other.mExtendedDataSize;
}
bool nn::hac::DeltaMetaExtendedHeader::operator==(const DeltaMetaExtendedHeader& other) const
{
return (mApplicationId == other.mApplicationId) \
&& (mExtendedDataSize == other.mExtendedDataSize);
}
bool nn::hac::DeltaMetaExtendedHeader::operator!=(const DeltaMetaExtendedHeader& other) const
{
return !(*this == other);
}
void nn::hac::DeltaMetaExtendedHeader::toBytes()
{
mRawBinary.alloc(sizeof(sDeltaMetaExtendedHeader));
sDeltaMetaExtendedHeader* info = (sDeltaMetaExtendedHeader*)mRawBinary.data();
info->application_id = mApplicationId;
info->extended_data_size = mExtendedDataSize;
}
void nn::hac::DeltaMetaExtendedHeader::fromBytes(const byte_t* bytes, size_t len)
{
if (len < sizeof(sDeltaMetaExtendedHeader))
{
throw fnd::Exception(kModuleName, "DeltaMetaExtendedHeader too small");
}
const sDeltaMetaExtendedHeader* info = (const sDeltaMetaExtendedHeader*)bytes;
mApplicationId = info->application_id.get();
mExtendedDataSize = info->extended_data_size.get();
}
const fnd::Vec<byte_t>& nn::hac::DeltaMetaExtendedHeader::getBytes() const
{
return mRawBinary;
}
void nn::hac::DeltaMetaExtendedHeader::clear()
{
mRawBinary.clear();
mApplicationId = 0;
mExtendedDataSize = 0;
}
uint64_t nn::hac::DeltaMetaExtendedHeader::getApplicationId() const
{
return mApplicationId;
}
void nn::hac::DeltaMetaExtendedHeader::setApplicationId(uint64_t application_id)
{
mApplicationId = application_id;
}
uint32_t nn::hac::DeltaMetaExtendedHeader::getExtendedDataSize() const
{
return mExtendedDataSize;
}
void nn::hac::DeltaMetaExtendedHeader::setExtendedDataSize(uint32_t size)
{
mExtendedDataSize = size;
} | true |
4553aa94623f147c72a63df5866c760271e75aa4 | C++ | ssi-anik/acm | /acm11541.cpp | UTF-8 | 911 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
int main()
{
char str[300];
int i,j,k,
testCaseRunning=1,totalTestCase;
scanf("%d",&totalTestCase);
getchar();
while(testCaseRunning++<=totalTestCase)
{
printf("Case %d: ",testCaseRunning-1);
gets(str);
char c,pc=EOF;
char num[100]={'\0'};
i=0,j=0;
while(j<=strlen(str))
{
if(j!=strlen(str))
c=str[j];
if(isdigit(c) && j<strlen(str))
{
num[i++]=c;
num[i]='\0';
}
else if((isalpha(c)&&pc!=EOF) || j==strlen(str))
{
i = atoi(num);
for(i;i>=1;i--)
printf("%c",pc);
num[0] = '\0';
}
if(isalpha(c))
pc = c;
j++;
}
printf("\n");
}
return 0;
}
| true |
e2ecf03f823e9ff861fe5702f37cf42446703aba | C++ | Dagmoores/Cplusplus | /Introducao_a_C++/Challenges/challenge9.cpp | UTF-8 | 705 | 3.921875 | 4 | [] | no_license | //Challenge9
/* Crie um Algoritimo em C++ utilizando apenas ponteiros, em que o
usuário informa a idade de duas pessoas, e o Algoritmo informa a
média destas duas idades. */
#include <iostream>
using namespace std;
int main () {
int age1;
int age2;
int* pointerAge1;
int* pointerAge2;
//Age 1 request
cout << "Enter the age of person 1: ";
cin >> age1;
cout << endl;
//Age 2 request
cout << "Enter the age of person 2: ";
cin >> age2;
cout << endl;
pointerAge1 = &age1;
pointerAge2 = &age2;
cout << "The media between the age 1 and the age 2 is: ";
cout << (*pointerAge1 + *pointerAge2) / 2;
cout << endl;
return 0;
}
| true |
6391151aed3414e7373b7d7b238b898991fcc207 | C++ | Goto-Tatsu/imgui_dx11_gm31_ | /GAME/control.cpp | SHIFT_JIS | 5,961 | 2.5625 | 3 | [] | no_license | #include "control.h"
#include "stdio.h"
using namespace DirectX;
void KeyInput::Reset()
{
for (int i = 0; i < KEY_ARRAY_NUM; ++i) {
aKeyboard[i] = 0;
aKeyboardOld[i] = 0;
}
}
bool KeyInput::Update(const MouseCapture& mouse)
{
BYTE keyary[KEY_ARRAY_NUM];
if (!GetKeyboardState(keyary)) {
for (int i = 0; i < KEY_ARRAY_NUM; ++i) { keyary[i] = 0; }
return false;
}
return Update(mouse, keyary);
}
bool KeyInput::Update(const MouseCapture& mouse, BYTE keyary[KEY_ARRAY_NUM])
{
for (int i = 0; i < KEY_ARRAY_NUM; ++i) {
aKeyboardOld[i] = aKeyboard[i];
}
for (int i = 0; i < KEY_ARRAY_NUM; ++i) { aKeyboard[i] = keyary[i]; }
Wheel = mouse.Wheel;
LastPt = CursorPt;
CursorPt = mouse.CursorPt;
if (KeyDown(VK_LBUTTON))LClickPt = CursorPt;
if (KeyDown(VK_MBUTTON))MClickPt = CursorPt;
if (KeyDown(VK_RBUTTON))RClickPt = CursorPt;
return true;
}
bool KeyInput::KeyDown(int vk) const
{
if ((unsigned)vk >= KEY_ARRAY_NUM)return false;
bool now = (aKeyboard[vk] & 0x80) != 0;
bool old = (aKeyboardOld[vk] & 0x80) != 0;
return now && !old;
}
bool KeyInput::KeyOn(int vk) const
{
if ((unsigned)vk >= KEY_ARRAY_NUM)return false;
return (aKeyboard[vk] & 0x80) != 0;
}
bool KeyInput::KeyUp(int vk) const
{
if ((unsigned)vk >= KEY_ARRAY_NUM)return false;
bool now = (aKeyboard[vk] & 0x80) != 0;
bool old = (aKeyboardOld[vk] & 0x80) != 0;
return !now && old;
}
//======================================================================
DirectX::XMMATRIX CameraCtrl::GetViewMatrix()
{
XMVECTOR campos = { 0,0,Dist, 1 };
XMMATRIX camrot = XMMatrixRotationRollPitchYaw(RotV, RotH, 0);
campos = XMVector4Transform(campos, camrot);
XMVECTOR lookat = At;
if (bCharaMode) {
lookat += vCharaPos;
}
XMVECTOR Eye = XMVectorAdd(campos, lookat);
XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
return XMMatrixLookAtLH(Eye, lookat, Up);
}
//-----------------------------
void CameraCtrl::Reset()
{
At = IniAt;
RotH = IniRotH;
RotV = IniRotV;
Dist = IniDist;
vCharaPos = DirectX::XMVectorSet(0, 0, 0, 1);
vCharaRot = DirectX::XMVectorSet(0, 0, 0, 0);
}
namespace {
// -`+@
FLOAT SubAngle(FLOAT a0, FLOAT a1)
{
FLOAT sub = a0 - a1;
if (sub > XM_PI)sub -= XM_2PI;
if (sub < -XM_PI)sub += XM_2PI;
return sub;
}
FLOAT AngleLimit(FLOAT a)
{
int i = (int)(a / XM_2PI);
a = a - FLOAT(i) * XM_2PI;
if (a > XM_PI)a -= XM_2PI;
if (a < -XM_PI)a += XM_2PI;
return a;
}
}
//-----------------------------
void CameraCtrl::Ctrl(const KeyInput& key_input, FLOAT elapsed_time_sec)
{
static bool last_move_camera = false;
bool move_camera = false;
if (key_input.KeyOn(VK_RBUTTON)) {
move_camera = true;
FLOAT dx = static_cast<FLOAT>(key_input.CursorPt.x - key_input.LastPt.x);
FLOAT dy = static_cast<FLOAT>(key_input.CursorPt.y - key_input.LastPt.y);
RotH += SpeedMouseRot * dx;
RotV -= SpeedMouseRot * dy;
if (RotH > XM_PI)RotH -= XM_2PI;
if (RotH < -XM_PI)RotH += XM_2PI;
if (RotV > LimitRotV)RotV = LimitRotV;
if (RotV < -LimitRotV)RotV = -LimitRotV;
}
if (key_input.Wheel != 0.0f) {
move_camera = true;
Dist -= SpeedWheelMove * key_input.Wheel;
if (Dist < DistMin)Dist = DistMin;
if (Dist > DistMax)Dist = DistMax;
}
if (key_input.KeyOn(VK_MBUTTON)) {
move_camera = true;
XMMATRIX view = GetViewMatrix();
view = XMMatrixInverse(nullptr, view);
FLOAT dx = static_cast<FLOAT>(key_input.CursorPt.x - key_input.LastPt.x);
FLOAT dy = static_cast<FLOAT>(key_input.CursorPt.y - key_input.LastPt.y);
At -= view.r[0] * dx * SpeedMouseSlide;
At += view.r[1] * dy * SpeedMouseSlide;
}
if (key_input.KeyOn(VK_RIGHT)) {
move_camera = true;
RotH += SpeedRotH * elapsed_time_sec;
if (RotH > XM_PI)RotH -= XM_2PI;
}
if (key_input.KeyOn(VK_LEFT)) {
move_camera = true;
RotH -= SpeedRotH * elapsed_time_sec;
if (RotH < -XM_PI)RotH += XM_2PI;
}
if (key_input.KeyOn(VK_DOWN)) {
move_camera = true;
RotV += SpeedRotV * elapsed_time_sec;
if (RotV > LimitRotV)RotV = LimitRotV;
}
if (key_input.KeyOn(VK_UP)) {
move_camera = true;
RotV -= SpeedRotV * elapsed_time_sec;
if (RotV < -LimitRotV)RotV = -LimitRotV;
}
if (key_input.KeyOn(VK_PRIOR)) {//PageUp
move_camera = true;
Dist -= SpeedDist * elapsed_time_sec;
if (Dist < DistMin)Dist = DistMin;
}
if (key_input.KeyOn(VK_NEXT)) {//PageDown
move_camera = true;
Dist += SpeedDist * elapsed_time_sec;
if (Dist > DistMax)Dist = DistMax;
}
XMVECTOR move = { 0,0,0,0 };
if (key_input.KeyOn('W'))move = XMVectorSetZ(move, -1.0f);
if (key_input.KeyOn('S'))move = XMVectorSetZ(move, 1.0f);
if (key_input.KeyOn('D'))move = XMVectorSetX(move, -1.0f);
if (key_input.KeyOn('A'))move = XMVectorSetX(move, 1.0f);
if (key_input.KeyOn('C'))move = XMVectorSetY(move, -1.0f);
if (key_input.KeyOn('E'))move = XMVectorSetY(move, 1.0f);
if (XMVectorGetX(XMVector3Length(move)) > 0.0f) {
move_camera = true;
move = XMVector3Normalize(move);
move = XMVectorScale(move, SpeedMove * elapsed_time_sec);
move = XMVector3Transform(move, XMMatrixRotationY(RotH));
if (key_input.KeyOn(VK_LSHIFT))move *= 2.0f;
if (bCharaMode) {
vCharaPos += move;
FLOAT move_ang = atan2f(-XMVectorGetX(move), -XMVectorGetZ(move));
FLOAT now_ang = XMVectorGetY(vCharaRot);
FLOAT sub_ang = SubAngle(move_ang, now_ang);
const FLOAT rot_speed = 0.25f;
if (sub_ang > rot_speed)sub_ang = rot_speed;
if (sub_ang < -rot_speed)sub_ang = -rot_speed;
now_ang = AngleLimit(now_ang + sub_ang);
//kari
vCharaRot = XMVectorSet(0, now_ang, 0, 0);
}
else {
At = XMVectorAdd(At, move);
}
}
#if 0
if (!move_camera && last_move_camera) {
//I
char camera[256];
sprintf_s(camera, "\tINI_ROT %f, %f;\n\tINI_LOOKAT %f, %f, %f;\n\tINI_DIST %f;\n//-----\n",
RotH, RotV,
//RotH*180.0f / XM_PI, RotV*180.0f / XM_PI,
XMVectorGetX(At), XMVectorGetY(At), XMVectorGetZ(At),
Dist);
OutputDebugStringA(camera);
}
last_move_camera = move_camera;
#endif
}
| true |
b60cbda435ff7a6e54586c38402acea4416933a0 | C++ | mehranagh20/ACM-ICPC | /uva/11080-Place-the-Guards/11080-Place-the-Guards.cpp | UTF-8 | 1,803 | 2.546875 | 3 | [] | no_license | //In The Name Of God
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vii> vvii;
typedef set<int> si;
typedef vector<si> vsi;
typedef pair<double, double> dd;
#define inf 1000000000
#define eps 1e-9
vvi graph;
vi color;
int n;
int bfs(int s) {
int ans = 1, tmp = 1;
queue<int> queue1; queue1.push(s);
color[s] = 0;
bool isBipartite = true;
while(isBipartite && !queue1.empty()) {
int top = queue1.front(); queue1.pop();
for(auto &e : graph[top]) {
if(color[e] == -1) {
tmp++;
color[e] = 1 - color[top];
if(color[e] == 0) ans++;
queue1.push(e);
}
else if(color[e] == color[top]) {
isBipartite = false; break;
}
}
}
if(!isBipartite) return -1;
return ans > tmp - ans ? tmp - ans : ans;
}
int main() {
ios::sync_with_stdio(0);
int tc; cin >> tc;
while(tc--) {
int m, nod1, nod2; cin >> n >> m;
graph.clear(); graph.resize(n);
for(int i = 0; i < m; i++) {
cin >> nod1 >> nod2;
graph[nod1].push_back(nod2);
graph[nod2].push_back(nod1);
}
int ans = 0;
color.clear(); color.resize(n, -1);
for(int i = 0; i < n; i++)
if(color[i] == -1) {
int tmp = bfs(i);
if(tmp == -1) {
ans = -1;
break;
}
ans += tmp == 0 ? 1 : tmp;
}
cout << ans << endl;
}
return 0;
} | true |
5299ac7e005d4a1d85de507454431a1113a80ca5 | C++ | AliEissa2077/speedopoint | /SpeedoPoint/date.h | UTF-8 | 516 | 2.796875 | 3 | [] | no_license | #pragma once
#ifndef DATE_H
#define DATE_H
#include <ctime>
class date {
private:
int day;
int month;
int year;
int hour;
int minute;
public:
date();
date(int d, int m, int y);
date(int d, int m, int y, int h, int min);
float operator-(float inp) {
float var1 = 0;
var1 += day*24;
var1 += hour;
var1 += minute/60;
return inp - var1;
}
int getYear();
int getMonth();
int getDay();
int getHour();
int getMinute();
};
#endif DATE_H
| true |
50405e34865ce223a3a12ac2ff72c18d0dcee98a | C++ | mr-stocki/giulia_ESCape | /lib/mcp_can/mcp_can/examples/send/send.ino | UTF-8 | 1,295 | 2.5625 | 3 | [
"MIT"
] | permissive | // demo: CAN-BUS Shield, send data
#include <df_can.h>
#include <SPI.h>
const int SPI_CS_PIN = 10;
MCPCAN CAN(SPI_CS_PIN); // Set CS pin
void setup()
{
Serial.begin(115200);
int count = 50; // the max numbers of initializint the CAN-BUS, if initialize failed first!.
do {
CAN.init(); //must initialize the Can interface here!
if(CAN_OK == CAN.begin(CAN_500KBPS)) // init can bus : baudrate = 500k
{
Serial.println("DFROBOT's CAN BUS Shield init ok!");
break;
}
else
{
Serial.println("DFROBOT's CAN BUS Shield init fail");
Serial.println("Please Init CAN BUS Shield again");
delay(100);
if (count <= 1)
Serial.println("Please give up trying!, trying is useless!");
}
}while(count--);
}
unsigned char data[8] = {'D', 'F', 'R', 'O', 'B', 'O', 'T', '!'};
void loop()
{
// send data: id = 0x06, standrad flame, data len = 8, data: data buf
CAN.sendMsgBuf(0x06, 0, 8, data);
delay(100); // send data per 100ms
}
| true |
e72944069bd2fe41b0d0c80af9aa919c8167ca96 | C++ | JaumeMontagut/CITM_2_Project2_BuffManager | /exercices/Buff_manager/j1Entity.cpp | UTF-8 | 1,506 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "j1Entity.h"
#include <vector>
#include "PugiXml/src/pugiconfig.hpp"
#include "PugiXml/src/pugixml.hpp"
#include "p2Log.h"
#include "Module_Buff.h"
#include "j1App.h"
#include "j1Scene.h"
Entity::Entity(int x, int y) : x(x), y(y) {
}
bool Entity::Start()
{
return true;
}
bool Entity::Update(float dt)
{
return true;
}
j1Entity::j1Entity()
{
name.assign("entity");
}
bool j1Entity::Awake(pugi::xml_node & node)
{
entities_node = node;
return true;
}
bool j1Entity::Start()
{
Entity * new_entity = nullptr;
for (pugi::xml_node entity_node = entities_node.child("entity"); entity_node != nullptr; entity_node = entity_node.next_sibling("entity"))
{
if (std::strcmp(entity_node.attribute("type").as_string(), "character") == 0)
{
new_entity = new Character(entity_node);
if (std::strcmp(entity_node.child("name").attribute("value").as_string(), "dwarf") == 0)
{
App->scene->dwarf = (Character*)new_entity;
}
else if (std::strcmp(entity_node.child("name").attribute("value").as_string(), "goblin") == 0)
{
App->scene->goblin = (Character*)new_entity;
}
entities.push_back(new_entity);
}
else {
LOG("Entity type not found.");
}
}
for (std::vector<Entity*>::iterator iter = entities.begin(); iter != entities.end(); ++iter)
{
(*iter)->Start();
}
return true;
}
bool j1Entity::Update(float dt) {
for (std::vector<Entity*>::iterator iter = entities.begin(); iter != entities.end(); ++iter)
{
(*iter)->Update(dt);
}
return true;
}
| true |
0a341a7ef9568b2ce431dbb75b166f9afba6455a | C++ | TheRedLancer/Boilerplate-Maker-Cpp | /Main.cpp | UTF-8 | 670 | 2.890625 | 3 | [] | no_license | #include "Boiler.h"
int main(int argc, char * argv[]) { //argv[1] = directory path, argv[2] = file name
ifstream commentHeader;
commentHeader.open("header.txt");
if (argc != 3) {
cout << "ERROR: Two(2) command line arguments required: directory path, file name" << endl;
exit(-1);
}
string dirPath, fileName;
fileDirName(argv, dirPath, fileName);
makeCppFile(argv, commentHeader);
makeHeaderFile(argv, commentHeader);
makeMainFile(argv, commentHeader);
cout << "Succesfully created boilerplate code for " << fileName
<< " in directory: " << dirPath << endl;
commentHeader.close();
return 0;
} | true |
6c3fa321203b13b52b34672af6caaf9159a28267 | C++ | kgd-al/ReusWorld | /src/misc/autocalibrator.cpp | UTF-8 | 6,481 | 2.953125 | 3 | [
"MIT"
] | permissive | #include <csignal>
#include "../simu/simulation.h"
#include "kgd/external/cxxopts.hpp"
struct ITest {
virtual const std::string& name (void) const = 0;
virtual void operator() (void) const = 0;
virtual void next (bool success) const = 0;
virtual bool preciseEnough (void) const = 0;
virtual void finalize (void) const = 0;
virtual std::string finalState (void) const = 0;
virtual void doPrint (std::ostream &os) const = 0;
friend std::ostream& operator<< (std::ostream &os, const ITest &t) {
t.doPrint(os);
return os;
}
};
template <template <typename> class ConfigValue, typename T>
struct Test : public ITest {
ConfigValue<T> &cvalue;
const T baseValue;
T min, max;
float margin;
bool decreasing;
mutable T currMin, currVal, currMax;
mutable bool converged;
mutable T finalValue;
Test (ConfigValue<T> &cvalue, T min, T value, T max, float margin, bool decreasing)
: cvalue(cvalue), baseValue(value),
min(min), max(max), margin(margin), decreasing(decreasing),
currMin(min), currVal(value), currMax(max),
converged(false), finalValue(currVal) {}
const std::string& name (void) const override {
return cvalue.name();
}
void operator() (void) const override {
cvalue.overrideWith(currVal);
}
void next (bool success) const override {
if (decreasing) {
if (success) currMax = currVal; // Search for stricter (lower) value
else currMin = currVal; // Went too low, ease up
} else {
if (success) currMin = currVal; // Search for stricter (higher) value
else currMax = currVal; // Went too high, ease down
}
currVal = .5f * (currMin + currMax);
}
bool preciseEnough (void) const override {
return (currMax - currMin) < (max - min) / (1<<10) ;
}
void finalize (void) const override {
finalValue = currVal;
float r = 1.f + margin;
if (decreasing)
finalValue *= r;
else finalValue /= r;
finalValue = std::max(min, std::min(finalValue, max));
cvalue.overrideWith(finalValue);
converged = true;
}
void doPrint (std::ostream &os) const override {
os << name() << " (" << min;
if (min < currMin) os << "..." << currMin;
if (currMin < currVal) os << "...>" << currVal << "<";
if (currVal < currMax) os << "..." << currMax;
if (currMax < max) os << "..." << max;
os << ")";
}
std::string finalState (void) const override {
std::ostringstream oss;
oss << name() << ": " << baseValue << " >> " << finalValue << " ("
<< currVal << " "
<< (decreasing ? "*" : "/")
<< " " << (1.f + margin)
<< ")";
return oss.str();
}
};
template <template <typename> class CV, typename T>
static auto lowerBoundTest (CV<T> &configValue, float min, float margin) {
return std::make_unique<Test<CV, T>> (configValue, min, configValue(), configValue(), margin, true);
}
template <template <typename> class CV, typename T>
static auto upperBoundTest (CV<T> &configValue, float max, float margin) {
return std::make_unique<Test<CV, T>> (configValue, configValue(), configValue(), max, margin, false);
}
using SConfig = config::Simulation;
int main(void) {
static constexpr uint SEEDS = 20;
static const std::unique_ptr<ITest> tests[] {
// upperBoundTest(SConfig::lifeCost, 1., .2),
// lowerBoundTest(SConfig::assimilationRate, 0., .2),
// upperBoundTest(SConfig::saturationRate, 10., .2),
lowerBoundTest(SConfig::baselineShallowWater, 0., .2),
lowerBoundTest(SConfig::baselineLight, 0., .2),
upperBoundTest(SConfig::floweringCost, 9, 0),
};
static const auto envGenome = [] {
rng::FastDice dice (0);
return genotype::Environment::random(dice);
}();
static const auto plantGenomes = [] {
std::vector<genotype::Plant> genomes;
for (uint i=0; i<SEEDS; i++) {
rng::FastDice dice (i);
genomes.push_back(genotype::Plant::random(dice));
}
return genomes;
}();
auto oldStopAtYear = SConfig::stopAtYear.overrideWith(5);
auto oldStopAtMinGen = SConfig::stopAtMinGen.overrideWith(10);
auto oldStopAtMaxGen = SConfig::stopAtMaxGen.overrideWith(20);
auto oldVerbosity = SConfig::verbosity.overrideWith(0);
SConfig::setupConfig("auto", config::Verbosity::SHOW);
std::cout << "\nEnvironment genome is:\n" << envGenome << std::endl;
std::cout << "\nPlant genomes are: " << std::endl;
{
uint i=0;
for (const auto &g: plantGenomes)
std::cout << i++ << "/" << SEEDS << ": " << g << std::endl;
}
const auto &initSeeds = SConfig::initSeeds();
for (const auto &test_ptr: tests) {
const ITest &test = *test_ptr;
bool success = false;
std::cout << std::endl;
while (!(test.preciseEnough() && success)) {
test();
std::cout << "## Testing " << test << ": " << std::flush;
uint successCount = 0, totalPlants = 0, totalSteps = 0;
for (uint i=0; i<SEEDS; i++) { // Various rng seeds
simu::Simulation s;
s.init(envGenome, plantGenomes[i]);
while (!s.finished())
s.step();
bool thisSuccess = (s.plants().size() >= initSeeds);
successCount += thisSuccess;
totalPlants += s.plants().size();
totalSteps += s.time().toTimestamp();
std::cout << (thisSuccess ? '+' : '-') << std::flush;
s.destroy();
}
success = (SEEDS == successCount);
test.next(success);
std::cout << " ";
if (success) {
std::cout << "success (" << float(totalSteps) / SEEDS
<< " avg steps and " << float(totalPlants) / SEEDS
<< " plants)";
if (test.preciseEnough()) std::cout << ". Precise enough, stopping here";
} else
std::cout << "failure.";
std::cout << std::endl;
}
test.finalize();
std::cout << "# Final value for " << test.finalState() << std::endl;
}
stdfs::path configPath ("configs/auto-calibration/");
std::cout << "\nWriting calibrated config file(s) to " << configPath << std::endl;
SConfig::stopAtYear.overrideWith(oldStopAtYear);
SConfig::stopAtMinGen.overrideWith(oldStopAtMinGen);
SConfig::stopAtMaxGen.overrideWith(oldStopAtMaxGen);
SConfig::verbosity.overrideWith(oldVerbosity);
config::Simulation::printConfig(configPath);
std::cout << "\nAuto-calibration summary:\n";
for (const auto &test_ptr: tests)
std::cout << "\t- " << test_ptr->finalState() << std::endl;
return 0;
}
| true |
ce660d0516b57343d42adefcaad311212f1f1df5 | C++ | bluebynick/ES-1036-Labs | /ES1036Labs/Lab 004/npaul5_lab04_q1.cpp | UTF-8 | 2,765 | 4.53125 | 5 | [] | no_license | #include <iostream>
/*
Nick's More Choice Convertor
Programmer: Nicholas Paul
Date: October 26th 2017
In this program we will convert Celsius into Fahrenheit, Centimeters to Inches, Meters to Feet, or Km/h toMPH.
You will be asked for an input at the beginning that will indicate your choice.
The options are:
1. Celsius to Fahrenheit
2. Centimeters to Inches
3. Meters to Feet
4. Km/h to MPH
5. Exit
The program will follow the direction of the integer choice you inputted
Features:
-Uses method calls and makes use of Switch structure to handle the program direction
-Uses a do while loop for error catching (my first do-While loop yeeek)
*/
using namespace std;
double celToFaren() { //fucntion that converts the given Celsius input into Farenheit and returns the value
double input;
cout << "\nPlease input a temperature in Celsius:\n";
cin >> input;
input = (9.0/5.0)*input +32;
return input;
}
double cmToInch() { //fucntion that converts the given cm input into inches and returns the value
double input;
cout << "\nPlease input a length in Cm:\n";
cin >> input;
input = 0.39*input;
return input;
}
double mToFeet() { //fucntion that converts the given m input into feet and returns the value
double input;
cout << "\nPlease input a length in m:\n";
cin >> input;
input = 3.28*input;
return input;
}
double kmphToMph() { //fucntion that converts the given kmph input into mph and returns the value
double input;
cout << "\nPlease input a speed in Km/h:\n";
cin >> input;
input = input/1.609;
return input;
}
int main() {
//variable declaration
int input = 0;
bool loopEnder = false;
//introduction
cout << "Hi! Welcome to Nick's More Choice Convertor! In this program we will convert \nCelsius into Fahrenheit, Centimeters to Inches, Meters to Feet, or Km/h toMPH. \nYou will be asked for an input at the beginning that will indicate your choice.\n";
do {
//program direction
cout << "\nInput an integer choice(1-5):\n\nThe options are:\n\n\t1. Celsius to Fahrenheit\n\t2. Centimeters to Inches\n\t3. Meters to Feet\n\t4. Km/h to MPH\n\t5. Exit\n";
cin >> input;
switch (input) {
case 1:
cout << "You're temperature in Farenheit is " << celToFaren() << endl;
break;
case 2:
cout << "You're length in Inches is " << cmToInch() << endl;
break;
case 3:
cout << "You're length in Inches is " << mToFeet() << endl;
break;
case 4:
cout << "You're speed in MPH is " << kmphToMph() << endl;
break;
case 5:
loopEnder = true;
break;
default:
cout << "\nPlease input a number from 1-5\n\n";
loopEnder = false;
}
} while (loopEnder == false);
//conclusiton
cout << "\nThank you for using Nick's More Choice Convertor!\n\nHave a nice day :)\n\n";
return 0;
} | true |
7b3e6f10166047137777b95ff42c96ad556c55c8 | C++ | spywhere/os-sim | /src/ui/table.cpp | UTF-8 | 3,283 | 3.234375 | 3 | [] | no_license | #include "table.h"
#include <sstream>
uiTable::uiTable(Logger logger){
this->logger = logger;
this->showHeader();
}
void uiTable::showHeader(){
this->headerVisible = true;
}
void uiTable::hideHeader(){
this->headerVisible = false;
}
void uiTable::checkColumn(int index, std::string col){
if(this->colSize.size() >= index){
if(this->colSize[index] < col.length()){
this->colSize[index] = col.length();
}
}
}
void uiTable::printAlign(std::string str, int width, int alignment){
int w = width-str.length();
int lp = w/2;
int rp = w-lp;
if(alignment==UITABLE_RIGHT){
while(w-->0){
this->logger << " ";
}
}
if(alignment==UITABLE_CENTER){
while(lp-->0){
this->logger << " ";
}
}
this->logger << str;
if(alignment==UITABLE_CENTER){
while(rp-->0){
this->logger << " ";
}
}
if(alignment==UITABLE_LEFT){
while(w-->0){
this->logger << " ";
}
}
}
int uiTable::totalColumnLength(){
int sum=0;
for(int i=0;i<this->colSize.size();i++){
sum+=this->colSize[i];
}
return sum;
}
std::string uiTable::toString(int num){
std::stringstream ss;
ss << num;
return ss.str();
}
void uiTable::addColumn(std::string col, int alignment){
this->colSize.push_back(col.length());
this->tableHeader.push_back(col);
this->colAlignment.push_back(alignment);
}
void uiTable::addColumn(const char* col, int alignment){
this->addColumn(std::string(col), alignment);
}
void uiTable::setColumn(int index, std::string col, int alignment){
this->checkColumn(index, col);
this->tableHeader[index] = col;
this->colAlignment[index] = alignment;
}
void uiTable::setColumn(int index, const char* col, int alignment){
this->setColumn(index, std::string(col), alignment);
}
std::string uiTable::getColumn(int index){
if(index <= this->tableHeader.size()){
return this->tableHeader[index];
}
return std::string();
}
void uiTable::addRow(std::vector<std::string> row){
for(int i=0;i<row.size();i++){
this->checkColumn(i, row[i]);
}
this->tableRow.push_back(row);
}
void uiTable::addRow(std::vector<const char*> row){
std::vector<std::string> nrow;
for(int i=0;i<row.size();i++){
nrow.push_back(std::string(row[i]));
}
this->addRow(nrow);
}
void uiTable::setRow(int index, std::vector<std::string> row){
this->tableRow[index] = row;
for(int i=0;i<row.size();i++){
this->checkColumn(i, row[i]);
}
}
void uiTable::setRow(int index, std::vector<const char*> row){
std::vector<std::string> nrow;
for(int i=0;i<row.size();i++){
nrow.push_back(std::string(row[i]));
}
this->setRow(index, nrow);
}
void uiTable::clear(){
this->colSize.clear();
this->colAlignment.clear();
this->tableHeader.clear();
this->tableRow.clear();
}
void uiTable::print(){
if(this->headerVisible){
for(int i=0;i<this->tableHeader.size();i++){
this->logger << " ";
this->printAlign(this->tableHeader[i], this->colSize[i], this->colAlignment[i]);
}
this->logger << " \n";
for(int i=0;i<this->totalColumnLength()+(this->tableHeader.size()+1);i++){
this->logger << "=";
}
this->logger << "\n";
}
for(int r=0;r<this->tableRow.size();r++){
for(int i=0;i<this->tableRow[r].size();i++){
this->logger << " ";
this->printAlign(this->tableRow[r][i], this->colSize[i], this->colAlignment[i]);
}
this->logger << " \n";
}
} | true |
fbbea38c35e2b579be12d74535cf57a486cd9dc6 | C++ | bdcarter/Intro2CPPassignments-projects | /Stack-Queue-practice/QueueFunction.cpp | UTF-8 | 2,865 | 4.34375 | 4 | [] | no_license | /*****************************************************
* Program filename: QueueFunction.cpp
* Author: Brianna Carter
* Date: 5/17/2015
* Description: This creates a double linked list with FIFO characeristics,
* adds 3 values to the list, and removes them.
* ****************************************************/
#include <cstddef>
#include <iostream>
/**************************************
* structure for the nodes
****************************************/
struct QueueLike
{
int value;
QueueLike *next;
};
/******************************************
* Function: add
* Description: creates the three nodes in the
* structure
* Input: three int values
* Output: none
* *******************************************/
QueueLike* add(int num1, int num2, int num3)
{
std::cout << "Adding: " << std::endl;
QueueLike *top; //points to the first node in the list
QueueLike *bottom; //points to the last node in the list
top = new QueueLike; //create the first node
bottom = top; //point the bottom node to the only element
top->value = num1; //set the value
top->next = NULL; //the next pointer is NULL
std::cout << num1 << std::endl;
QueueLike *two = new QueueLike; //add the second element
two->value = num2;
two->next = NULL;
top->next = two; //the first 'next' pointer is now two
bottom = two; //this is now the bottom of the queue
std::cout << num2 << std::endl;
QueueLike *three = new QueueLike; //add the third element
three->value = num3;
three->next = NULL;
two->next = three; //second 'next' pointer is now three
bottom = three; //this is now the bottom of the queue
std::cout << num3 << std::endl;
return top;
}
/********************************************
* Function: display
* Description: Displays the list of numbers
* Input: pointer to the top value
* Output: none
* ******************************************/
void display(QueueLike *top)
{
std::cout << "List: " << std::endl;
QueueLike *ptr = top;
while(ptr !=NULL)
{ std::cout << ptr->value << std::endl; //as long as there is an element, display them
ptr = ptr->next;} //move pointer to next element
}
/********************************************
* Function: remove
* Description: Removes the values one at at time
* and displays the value
* Input: pointer to the top value
* Output: none
* ******************************************/
void remove(QueueLike *list)
{
QueueLike *trash; //temporary pointer to hold value being deleted
std::cout << "Deleting: " << std::endl;
for(int x = 0; x < 3; x++) //loop through the three nodes and delete
{ std::cout << list->value << std::endl;
trash = list;
list = list->next;
delete trash;
}
}
/*************************************/
int main()
{
QueueLike *list = add(32, 14, 2);
display(list);
remove(list);
return 0;
} | true |
9697b06d8fafeb5ee501133d187fb5aba750f7fa | C++ | MazenHassani/AdvancedAlgorithmsCourse | /Week1/1/Queries.cpp | UTF-8 | 546 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int lower_bound (int a[], int n, int x)
{
int M,R=n,L=-1;
while(R-L>1)
{
M=L+(R-L)/2;
if (a[M]>x) //f(M)
R=M;
else
L=M;
}
return R;
}
int main()
{
int n,m,x,a[200001];
cin>>n>>m;
for (int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
for (int i = 0; i < m; i++)
{
cin>>x;
cout<<lower_bound(a, n, x)<<" ";
}
cout<<endl;
return 0;
} | true |
fd30020975a7c9051283ea1a7d365ad4e6c744a2 | C++ | gentlecolts/Mongoose-Rendering-Engine | /engine/core/core.h | UTF-8 | 2,245 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef CORE_H_INCLUDED
#define CORE_H_INCLUDED
/*
includes all relevant definitions and classes
the user should not need to specify includes for any particular datatypes
all aspects of this engine must use the namespace MG
*/
#include "../2d/surface.h"
#include "../object/object.h"
#include "event.h"
#include "threadpool.h"
#include "../camera/camera.h"
#include "scene.h"
#include <thread>
#include <vector>
namespace MG{
class engine:public event{
private:
//TODO: vector may not be the best choice of structure, consider linked list or maybe even a tree for parallelism
std::vector<event*> events;
bool isEventSync=true;//if this is false, then event checking is done in a separate thread
void pollEvents();
void threadedPolling();
std::thread *evtThread;
window win;
long updateTimestamp=0;
sceneContainer scene;
//implemented in draw.cpp
//runs all staticUpdate and threadedUpdate calls
void updateTasks(int id,int numThreads);
public:
camera mainCamera;
surface hud,render;//2d overlay and 3d render surface respectively
bool showHud=true,showScene=true;
uint32_t bgCol=0;
long targetFPS=60;//long solely for consistency as it is compared to the return of clock()
//implemented in core.cpp
///TODO: determine need for alternate constructors
engine();//these should simply be a call to init
~engine();//i know i am going to need this at some point
void init();//(re)initialize the engine. this should initialize everything and free any objects that might have been in use
void mainLooper();//do main loop and waiting for the user
//implemented in scene.cpp
sceneContainer* getActiveScene();
//implemented in draw.cpp
bool isTimeToUpdate();
void update();
void initWindow(int width,int height,int flags=SDL_WINDOW_SHOWN);
void setTitle(const char* title);
//implemented in envineEvents.cpp
int registerEvent(event* evt);//returns the array index
void removeEvent(int index);//TODO: maybe create one that takes a pointer instead
bool setEventAsync(bool b);//even if the internals are positive is synchronous, it seems more sensible from a user side to have the function do this
void quit();//inherited from event class
};
}
#endif // CORE_H_INCLUDED
| true |
456f270cc77b4237ad5fd5940f66a0f6b649dd50 | C++ | xtuer/Qt | /QtBook/Widget/TopWindow/gui/TopWindow.cpp | UTF-8 | 2,156 | 2.515625 | 3 | [] | no_license | #include "TopWindow.h"
#include "ui_TopWindow.h"
#include "util/NinePatchPainter.h"
#include <QDebug>
#include <QPainter>
#include <QPixmap>
#include <QMouseEvent>
#include <QSizeGrip>
TopWindow::TopWindow(QWidget *centralWidget) : ui(new Ui::TopWindow) {
ui->setupUi(this);
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
ninePatchPainter = new NinePatchPainter(QPixmap(":/image/top-window/shadow.png"), 23, 12, 23, 33);
QGridLayout *l = qobject_cast<QGridLayout *>(layout());
// 替换中心的 centralWidget
delete l->replaceWidget(ui->centralWidget, centralWidget);
delete ui->centralWidget;
// 缩放窗口的 QSizeGrip
QSizeGrip *sizeGrip = new QSizeGrip(this);
sizeGrip->setStyleSheet("width: 15px; height: 15px; background: red;");
l->addWidget(sizeGrip, 1, 0, Qt::AlignRight | Qt::AlignBottom);
// 点击按钮 X 退出程序
connect(ui->closeButton, &QPushButton::clicked, [this] {
close();
});
}
TopWindow::~TopWindow() {
delete ui;
delete ninePatchPainter;
}
void TopWindow::setTitle(const QString &title) {
ui->titleLabel->setText(title);
}
void TopWindow::paintEvent(QPaintEvent *event) {
Q_UNUSED(event);
QPainter painter(this);
ninePatchPainter->paint(&painter, rect());
}
// 鼠标按下时记录此时鼠标的全局坐标和窗口左上角的坐标
void TopWindow::mousePressEvent(QMouseEvent *event) {
mousePressedPosition = event->globalPos();
windowPositionBeforeMoving = frameGeometry().topLeft();
}
// 鼠标放开时设置 mousePressedPosition 为空坐标
void TopWindow::mouseReleaseEvent(QMouseEvent *event) {
Q_UNUSED(event);
mousePressedPosition = QPoint();
}
// 鼠标移动时如果 mousePressedPosition 不为空,则说明需要移动窗口
// 鼠标移动的位移差,就是窗口移动的位移差
void TopWindow::mouseMoveEvent(QMouseEvent *event) {
if (!mousePressedPosition.isNull()) {
QPoint delta = event->globalPos() - mousePressedPosition;
QPoint newPosition = windowPositionBeforeMoving + delta;
move(newPosition);
}
}
| true |
e7b684804783668e8b2c0f7f76707adf503db219 | C++ | m7mdkamal/LeCompiler | /include/lexer/LexicalAnalyser.h | UTF-8 | 882 | 2.640625 | 3 | [] | no_license | /*
* LexicalAnalyser.h
*
* Created on: Apr 13, 2016
* Author: mohamed
*/
#ifndef LEXICAL_LEXICALANALYSER_H_
#define LEXICAL_LEXICALANALYSER_H_
#include <string>
#include <map>
#include <set>
#include <sstream>
#include <iostream>
#include "Token.h"
#include "Tag.h"
class LexicalAnalyser {
public:
LexicalAnalyser(std::string source);
void setSourceCode(std::string source);
bool next();
virtual ~LexicalAnalyser();
Token nextToken();
int getLineNumber() const {
return lineNumber;
}
private:
std::map<std::string, int> word;
std::string sourceCode;
std::stringstream sstream;
std::set<std::string> keywords;
Token nextNumberToken(char ch);
Token nextStringToken();
Token nextAlphaToken(char i);
Token nextOperatorToken(char ch);
int lineNumber;
};
#endif /* LEXICAL_LEXICALANALYSER_H_ */
| true |
29f04b8bb0da0164aa9310738857bcc389d2e8d4 | C++ | i6o6i/cannydetect | /matrics.cpp | UTF-8 | 8,739 | 2.625 | 3 | [
"MIT"
] | permissive | #include "matrics.hpp"
Point0::Point0(int x,int y)
{
this->x=x;
this->y=y;
}
matrics::matrics(const char *filename)
{
bgr = imread(filename, IMREAD_COLOR);
cvtColor(bgr, gray, COLOR_BGR2GRAY);
rows = bgr.rows;
cols = bgr.cols;
}
void matrics::gausblur(int i)
{
GauBlurMat = Mat();
GaussianBlur(gray, GauBlurMat, Size(i, i), 0, 0);
}
void matrics::enhance(operators op)
{
double jx, jy;
float hypotenuse;
es0.resize(boost::extents[rows - 2][cols - 2][2]);
es0 = Esn0(boost::extents[rows - 2][cols - 2][2]);
for(size_t i = 1; i < rows - 2; i++)
for(size_t j = 1; j < cols - 2; j++)
{
switch(op) {
case oper2x2: {
jx = -GauBlurMat.at<uchar>(i, j) + GauBlurMat.at<uchar>(i, j + 1)
- GauBlurMat.at<uchar>(i + 1, j) + GauBlurMat.at<uchar>(i + 1, j + 1);
jy = GauBlurMat.at<uchar>(i, j) + GauBlurMat.at<uchar>(i, j + 1)
- GauBlurMat.at<uchar>(i + 1, j) - GauBlurMat.at<uchar>(i + 1, j + 1);
}break;
case sobel: {
jx = GauBlurMat.at<uchar>(i - 1, j + 1) + 2 * GauBlurMat.at<uchar>(i, j + 1) + GauBlurMat.at<uchar>(i + 1, j + 1)
- (GauBlurMat.at<uchar>(i - 1, j - 1) + 2 * GauBlurMat.at<uchar>(i, j - 1) + GauBlurMat.at<uchar>(i + 1, j - 1));
jy = GauBlurMat.at<uchar>(i + 1, j - 1) + 2 * GauBlurMat.at<uchar>(i + 1, j) + GauBlurMat.at<uchar>(i + 1, j + 1)
- (GauBlurMat.at<uchar>(i - 1, j - 1) + 2 * GauBlurMat.at<uchar>(i - 1, j) + GauBlurMat.at<uchar>(i - 1, j + 1));
}break;
}
es0[i - 1][j - 1][strength] = sqrt(jx * jx + jy * jy);
es0[i - 1][j - 1][tangent] = jy / jx;
}
}
matrics::thinMat matrics::triTo2d(Esn0 es0)
{
thinMat a(boost::extents[es0.shape()[0]][es0.shape()[1]]);
for(size_t i = 0; i < es0.shape()[0]; i++)
for(size_t j = 0; j < es0.shape()[1]; j++)
a[i][j] = es0[i][j][strength];
return a;
}
Mat matrics::doubleArray2Mat(thinMat boostarr)
{
Mat res = Mat::zeros(Size(boostarr.shape()[1], boostarr.shape()[0]), CV_64F);
for(size_t i = 0; i < boostarr.shape()[0]; i++)
for(size_t j = 0; j < boostarr.shape()[1]; j++)
{
res.at<double>(i, j) = boostarr[i][j];
}
normalize(res, res, 0, 1, NORM_MINMAX);
return res;
}
void matrics::nonmaximaSupress()
{
enum direction {horizenal, oblique45, vertical, oblique135};
double tangen[4];
double tmp;
int es0rows=es0.shape()[0],es0cols=es0.shape()[1];
direction dir;
In.resize(boost::extents[es0rows - 2][es0cols - 2]);
In = thinMat(boost::extents[es0rows - 2][es0cols - 2]);
for(int i = 0; i < 4; i++)
tangen[i] = tan(2 * i * oneighthPI + oneighthPI);
for(size_t i = 1; i < es0rows - 2; i++)
for(size_t j = 1; j < es0cols - 2; j++)
{
tmp = es0[i][j][tangent];
dir = (tmp > tangen[3]) ? horizenal : (direction) ((tmp > tangen[2]) + (tmp > tangen[1]) + (tmp > tangen[0]));
switch(dir)
{
case horizenal:
In[i - 1][j - 1] = (es0[i - 1][j][strength] < es0[i][j][strength]
&& es0[i][j][strength] > es0[i + 1][j][strength])
? es0[i][j][strength] : 0;break;
case oblique45:
In[i - 1][j - 1] = (es0[i - 1][j - 1][strength] < es0[i][j][strength]
&& es0[i][j][strength] > es0[i + 1][j + 1][strength])
? es0[i][j][strength] : 0;break;
case vertical:
In[i - 1][j - 1] = (es0[i][j - 1][strength] < es0[i][j][strength]
&& es0[i][j][strength] > es0[i][j + 1][strength])
? es0[i][j][strength] : 0;break;
case oblique135:
In[i - 1][j - 1] = (es0[i + 1][j - 1][strength] < es0[i][j][strength]
&& es0[i][j][strength] > es0[i + 1][j + 1][strength])
? es0[i][j][strength] : 0;break;
}
}
}
/*
void matrics::doubleTholdNlink(double th, double tl)
{
enum direction {horizenal, oblique45, vertical, oblique135};
double tmp,tangen[4];
int stepx,stepy;
int rows=In.shape()[0],cols=In.shape()[1];
Infinal.resize(boost::extents[rows][cols]);
boost::multi_array<bool, 2> visited(boost::extents[rows][cols]);
typedef boost::multi_array<bool, 2>::index visitedIndex;
direction dir;
for(int i = 0; i < 4; i++)
tangen[i] = tan(2 * i * oneighthPI + oneighthPI);
for(visitedIndex i = 0; i < rows; i++)
for(visitedIndex j = 0; j < cols; j++)
{
visited[i][j] = false;
Infinal[i][j]=0;
}
for(thinMat::index i = 0; i < rows; i++)
for(thinMat::index j = 0; j < cols; j++)
{
if(visited[i][j]||In[i][j]<th)
continue;
tmp=es0[i][j][tangent];
dir=(tmp > tangen[3]) ? horizenal : (direction) ((tmp > tangen[2]) + (tmp > tangen[1]) + (tmp > tangen[0]));
int i_=i,j_=j;
do{
switch((int)dir)
{
case horizenal:stepx=0;stepy=1;break;
case oblique45:stepx=1;stepy=1;break;
case vertical:stepx=1;stepy=0;break;
case oblique135:stepx=-1;stepy=1;break;
}
do{
Infinal[i_][j_]=In[i_][j_];
j_+=stepx;
i_+=stepy;
}while(j_<=0&&In[i_][j_]>=th);
if(j <= 0)
continue;
else{
}
}while(In[i_][j_]>=tl);
}
}
*/
void matrics::doubleTholdNlink(double maxthreshold, double minthreshold)
{
std::stack<Point0> s;
std::queue<Point0> q;
int x,y;
bool connected = false;
size_t rows=In.shape()[0],cols=In.shape()[1];
boost::multi_array<int, 2> visited(boost::extents[rows][cols]);
Infinal.resize(boost::extents[rows][cols]);
for(size_t i = 0; i < rows; i++)
for(size_t j = 0; j < cols; j++)
{
visited[i][j] = 0;
Infinal[i][j]=0;
}
//初始化visited矩阵边界已访问
for(size_t i = 0; i < rows; i++){
visited[i][0] = 1;
visited[i][cols - 1] = 1;
}
for(size_t j = 0; j < cols; j++){
visited[0][j] = 1;
visited[rows - 1][j] = 1;
}
//
for(size_t i = 1; i < rows - 1; i++){
for(size_t j = 1; j < cols - 1; j++){
if(In[i][j] > maxthreshold){
visited[i][j] = 2;
}
else if(In[i][j] < minthreshold){
visited[i][j] = 1;
}
else if( minthreshold <= In[i][j] &&
In[i][j] <= maxthreshold &&
visited[i][j] == 0
){
s.push(Point0(i, j));
q.push(Point0(i, j));
visited[i][j] = 1;
while (!s.empty())
{
Point0 p = s.top();
s.pop();
x = p.x;
y = p.y;
//中上
if( minthreshold <= In[x - 1][y] &&
In[x - 1][y] <= maxthreshold &&
visited[x - 1][y] == 0
){
s.push(Point0(x - 1, y));
q.push(Point0(x - 1, y));
visited[x - 1][y] = 1;
}
//中下
if( minthreshold <= In[x + 1][y] &&
In[x + 1][y] <= maxthreshold &&
visited[x + 1][y] == 0
){
s.push(Point0(x + 1, y));
q.push(Point0(x + 1, y));
visited[x + 1][y] = 1;
}
//左上
if( minthreshold <= In[x - 1][y - 1] &&
In[x - 1][y - 1] <= maxthreshold &&
visited[x - 1][y - 1] == 0
){
s.push(Point0(x - 1, y - 1));
q.push(Point0(x - 1, y - 1));
visited[x - 1][y - 1] = 1;
}
//左中
if( minthreshold <= In[x][y - 1] &&
In[x][y - 1] <= maxthreshold &&
visited[x][y - 1] == 0
){
s.push(Point0(x, y - 1));
q.push(Point0(x, y - 1));
visited[x][y - 1] = 1;
}
//左下
if( minthreshold <= In[x + 1][y - 1] &&
In[x + 1][y - 1] <= maxthreshold &&
visited[x + 1][y - 1] == 0
){
s.push(Point0(x + 1, y - 1));
q.push(Point0(x + 1, y - 1));
visited[x + 1][y - 1] = 1;
}
//右上
if( minthreshold <= In[x - 1][y + 1] &&
In[x - 1][y + 1] <= maxthreshold &&
visited[x - 1][y + 1] == 0
){
s.push(Point0(x - 1, y + 1));
q.push(Point0(x - 1, y + 1));
visited[x - 1][y + 1] = 1;
}
//右中
if( minthreshold <= In[x][y + 1] &&
In[x][y + 1] <= maxthreshold &&
visited[x][y + 1] == 0
){
s.push(Point0(x, y + 1));
q.push(Point0(x, y + 1));
visited[x][y + 1] = 1;
}
//右下
if( minthreshold <= In[x + 1][y + 1] &&
In[x + 1][y + 1] <= maxthreshold &&
visited[x + 1][y + 1] == 0
){
s.push(Point0(x + 1, y + 1));
q.push(Point0(x + 1, y + 1));
visited[x + 1][y + 1] = 1;
}
//判断是否与强边界点连通
if (connected == false)
{
for (int m = -1; m <= 1; m++)
{
for (int n = -1; n <= 1; n++)
{
if (In[x + m][y + n] > maxthreshold)
{
connected = true;
}
}
}
}
}//while循环体
if (connected == true)
{
while (!q.empty()) {
Point0 p = q.front();
q.pop();
x = p.x;
y = p.y;
visited[x][y] = 2;
}
connected = false;
}
}//弱边界判断体
}
}
for(size_t i=0;i<visited.shape()[0];i++)
for(size_t j=0;j<visited.shape()[1];j++)
{
if(visited[i][j]==2)
{
Infinal[i][j]=255;
}
//std::cout<<i<<","<<j<<" "<<visited[i][j]<<Infinal[i][j]<<" ";
}
}
| true |
41f7b706abacdb29b6b645f0235d4698a25d9963 | C++ | Delebrith/return-of-the-neighbours | /kNN_NBC/NBC/CreatedPoint.h | UTF-8 | 292 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "point.h"
class CreatedPoint :
public Point
{
std::vector<double> attributeValues;
public:
CreatedPoint() {};
CreatedPoint(const std::vector<double> attributeValues) : attributeValues(attributeValues) {};
const std::vector<double>* getAttributeValues() const;
};
| true |
e0b29185f849c8ef775a2f614037947a1de78015 | C++ | PanCheng111/leetcode | /10/test.cpp | UTF-8 | 1,338 | 2.984375 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class Solution {
private:
int **opt;
public:
bool checkMatch(int i, int j, int l1, int l2, const string s, const string p) {
if (j == l2) return i == l1;
//if (i == l1) return j == l2;
if (opt[i][j] != -1) return opt[i][j];
bool ret = false;
if (j < l2 - 1 && p[j + 1] == '*') {
bool ret1 = false, ret2 = false;
if (i < l1 && (s[i] == p[j] || p[j] == '.')) ret1 = checkMatch(i + 1, j, l1, l2, s, p);
ret2 = checkMatch(i, j + 2, l1, l2, s, p);
ret = ret1 || ret2;
}
else {
if (i < l1 && (s[i] == p[j] || p[j] == '.')) ret = checkMatch(i + 1, j + 1, l1, l2, s, p);
else ret = false;
}
opt[i][j] = ret;
return ret;
}
bool isMatch(string s, string p) {
int len1 = s.length();
int len2 = p.length();
opt = new int*[len1 + 1];
for (int i = 0; i <= len1; i++) {
opt[i] = new int[len2 + 1];
for (int j = 0; j <= len2; j++)
opt[i][j] = -1;
}
return checkMatch(0, 0, len1, len2, s, p);
}
};
int main() {
Solution s;
printf("%d\n", s.isMatch("aa", "a*"));
return 0;
} | true |
0ee4a6fa5a06921fe9202e3ed4369305da5cf655 | C++ | macieg/jnp3 | /kontroler.cc | UTF-8 | 655 | 2.796875 | 3 | [] | no_license | #include "kontroler.h"
#include "sejf.h"
#include <iostream>
Kontroler::Kontroler(const Sejf* sejf)
{
this->sejf = sejf;
}
Kontroler::operator bool() const
{
return (sejf->get_available_accesses() > 0);
}
bool Kontroler::break_in() const
{
return (sejf->get_break_in());
}
bool Kontroler::is_manipulated() const
{
return (sejf->get_is_manipulated());
}
std::ostream& operator<<(std::ostream& out, const Kontroler &kontroler)
{
if (kontroler.break_in())
{
out << "ALARM: WLAMANIE" << std::endl;
}
else if (kontroler.is_manipulated())
{
out << "ALARM: ZMANIPULOWANY" << std::endl;
}
else
{
out << "OK" << std::endl;
}
return out;
}
| true |
22c6a7e1c9ed6e605b07920c2ae6e5741e13571c | C++ | Oscer2016/cpp | /example300/transport.cpp | UTF-8 | 460 | 2.671875 | 3 | [] | no_license | /*************************************************************************
> File Name: transport.cpp
> Author: hp
> Mail: hepan@xiyoulinux.org
> Created Time: 2016年12月11日 星期日 00时23分25秒
************************************************************************/
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int i = 1;
float j = 2.234;
i = (int)j;
cout<<"赋值后的i值: "<<i<<endl;
return 0;
}
| true |
82fa187b103ea694f1ce2308871f4b7cddfafac9 | C++ | toyama1710/cpp_library | /util/coordinate_compression.hpp | UTF-8 | 1,003 | 3.046875 | 3 | [
"CC0-1.0"
] | permissive | #ifndef COORDINATE_COMPRESSION_HPP
#define COORDINATE_COMPRESSION_HPP
#include <algorithm>
#include <vector>
template <class T>
struct CoordinateCompression {
std::vector<T> p;
template <class InputItr>
CoordinateCompression(InputItr first, InputItr last) : p(first, last) {
std::sort(p.begin(), p.end());
p.erase(unique(p.begin(), p.end()), p.end());
};
int zip(T x) {
return std::lower_bound(p.begin(), p.end(), x) - p.begin();
};
T unzip(int x) {
return p[x];
};
int size() {
return p.size();
};
};
template <class T>
struct CoordinateCompressionBuilder {
std::vector<T> p;
CoordinateCompressionBuilder() = default;
template <class InputItr>
CoordinateCompressionBuilder(InputItr first, InputItr last)
: p(first, last){};
void push(T x) {
p.push_back(x);
};
CoordinateCompression<T> build() {
return CoordinateCompression<T>(p.begin(), p.end());
};
};
#endif
| true |
5b2b485fdc47d230b85246f8d5b479fc5f019247 | C++ | nomawni/coco | /Coco/Coco/Coco.cpp | UTF-8 | 3,119 | 3.203125 | 3 | [] | no_license | // Coco.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <boost/asio.hpp>
#include "Client.h"
#include "ResponseHandler.h"
#include "Server.h"
void handler(unsigned int request_id,
const std::string& response,
const boost::system::error_code& ec) {
if (ec.value() == 0) {
std::cout << "Request #" << request_id
<< "Has completed: Response : "
<< response << std::endl;
}
else if (ec == boost::asio::error::operation_aborted) {
std::cout << " Request #" << request_id
<< " Has been cancelled by the user" << std::endl;
}
else {
std::cout << " Request #" << request_id
<< "Failed! Error code = " << ec.value()
<< " Error Message " << ec.message() << std::endl;
}
}
// The default size of the thread =>
// Server
const unsigned int DEFAULT_THREAD_POOL_SIZE = 2;
int main()
{
unsigned short port_num = 3333;
try {
std::cout << " Welcome" << std::endl;
auto num_threads = std::thread::hardware_concurrency();
Client client(num_threads);
//ResponseHandler handler;
// Initiate a request with id 1
client.emulate(10,
"127.0.0.1",
3333,
handler,
1
);
std::this_thread::sleep_for(std::chrono::seconds(5));
// Initiate another request
client.emulate(11,
"127.0.0.1",
3333,
handler,
2);
// Then decide to cancel the request with id 1
client.cancelRequest(1);
// Does nothing for 6 seconds
std::this_thread::sleep_for(std::chrono::seconds(6));
// Initiate one more request with id 3
client.emulate(12,
"127.0.0.1",
3333,
handler,
3);
// Does nothing for 15 seconds
std::this_thread::sleep_for(std::chrono::seconds(15));
// Then decide to exit the application
client.close();
}
catch (boost::system::system_error &ec) {
std::cout << "Error occured: The error code is : " << ec.code()
<< " Message " << ec.what();
return ec.code().value();
}
try {
Server server;
unsigned int thread_pool_size =
std::thread::hardware_concurrency() * 2;
if (thread_pool_size == 0) {
thread_pool_size = DEFAULT_THREAD_POOL_SIZE;
server.Start(port_num, thread_pool_size);
std::this_thread::sleep_for(std::chrono::seconds(60));
server.Stop();
}
}
catch (boost::system::system_error& e) {
std::cout << " Error occured! Error code = "
<< e.code() << " Message. "
<< e.what();
}
// std::cout << "Hello World!\n";
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
3d3ec2b50d299215f6ff687cc6186c7a7192d526 | C++ | afcidk/poj | /POJ-1149.cpp | UTF-8 | 2,166 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define MAX 1005
#define INF 0x7fffffff
using namespace std;
int cap[MAX][MAX], flow[MAX][MAX];
int visited[MAX];
int past[MAX];
int pig[MAX];
int solve(int s, int t);
int main()
{
int m, n;
while(scanf("%d%d", &m, &n)==2){
memset(visited, 0, sizeof(visited));
memset(cap, 0, sizeof(cap));
memset(flow, 0, sizeof(flow));
memset(past, 0, sizeof(past));
for(int i=1; i<=m; ++i){
scanf("%d", &pig[i]);
}
//0=start, n+1=end
int x, a;
for(int i=1; i<=n; ++i){
scanf("%d", &x);
for(int j=1; j<=x; ++j){
scanf("%d", &a);
if(!past[a]){
past[a] = i;
cap[0][i]+=pig[a];
}
else{
cap[past[a]][i]=INF;
}
}
scanf("%d", &x);
cap[i][n+1]=x;
}
printf("%d\n", solve(0, n+1));
}
return 0;
}
int solve(int s, int t){
int ret=0;
while(true){
memset(visited, 0, sizeof(visited));
queue<int> que;
que.push(s);
while(!que.empty()){
int cur = que.front();
que.pop();
visited[cur]=1;
for(int i=0; i<=t; ++i){
if(!visited[i]){
if(cap[cur][i]-flow[cur][i]>0 || flow[i][cur]>0){
past[i] = cur;
que.push(i);
}
}
}
}
if(!visited[t]) break;
else{
int f=INF;
for(int i=t; i!=s; i=past[i]){
int pre = past[i];
if(cap[pre][i]-flow[pre][i]>0) f = min(f, cap[pre][i]-flow[pre][i]);
else f = min(f, flow[i][pre]);
}
for(int i=t; i!=s; i=past[i]){
int pre = past[i];
if(cap[pre][i]-flow[pre][i]>0) flow[pre][i]+=f;
else flow[i][pre]-=f;
}
ret+=f;
}
}
return ret;
}
| true |
8c5bcd2e73e4dac3971b9a48218c6883a00e4ad5 | C++ | DangerMouseB/DA_Bones_Mirror | /Eispack.cpp | UTF-8 | 10,669 | 2.5625 | 3 | [] | no_license |
#include "Platform.h"
#include "Eispack.h"
#include "Strict.h"
#include "SquareMatrix.h"
#include "Exceptions.h"
#include "Decompositions.h"
#include "Numerics.h"
#include "Functionals.h"
namespace
{
double Pythag(double a, double b)
{
return sqrt(Square(a) + Square(b));
}
double BetterPythag(double a, double b)
{
double p = Max(fabs(a), fabs(b));
if (p == 0.0)
return 0.0;
double r = Square(Min(fabs(a), fabs(b)) / p);
for (;;)
{
const double t = 4.0 + r;
if (t == 4.0)
return p;
const double s = r / t;
const double u = 1.0 + 2.0 * s;
p *= u;
r *= Square(s / u);
}
}
inline double DSign(double r, double p)
{
return p * r > 0.0 ? r : -r;
}
// throughout this file, double-letter integer indices are 0-offset (reduced by 1 from their Fortran origins), while single-letter indices have the same numerical value as in the Fortran code
// e.g. n is not changed, but ii is
void TQL2
(Vector_<>* d, // diagonals of tridiagonal matrix -- replaced with eigenvalues in descrnding order
Vector_<>* e, // subdiagonal elements (in elements [1, n)) -- destroyed during analysis
Matrix_<>* z) // transformation matrix output from TRed2 -- replaced with eigenvectors
{
static const int MAX_ITERATIONS = 30;
const int n = d->size();
std::copy(Next(e->begin()), e->end(), e->begin()); // now e is populated in [0, n-1)
e->back() = 0.0;
double f = 0.0, tst1 = 0.0;
for (int ll = 0; ll < n; ++ll)
{
tst1 = Max(tst1, fabs((*d)[ll]) + fabs((*e)[ll]));
int mm = ll;
for (;;)
{
assert(mm < n); // because e->back() == 0, we will always break out
const double tst2 = tst1 + fabs((*e)[mm]);
if (tst2 == tst1)
break;
++mm;
}
if (mm != ll) // therefore (*e)[ll] is significantly nonzero
{
for (int j = 0; ; ++j) // iteration counter
{
REQUIRE(j < MAX_ITERATIONS, "Exhausted iterations in TQL");
// form shift
const double g = (*d)[ll];
const double p0 = ((*d)[ll + 1] - g) / (2.0 * (*e)[ll]);
const double r = Pythag(p0, 1.0);
(*d)[ll] = (*e)[ll] / (p0 + DSign(r, p0));
const double dl1 = (*d)[ll + 1] = (*e)[ll] * (p0 + DSign(r, p0));
const double h = g - (*d)[ll];
for (int ii = ll + 2; ii < n; ++ii)
(*d)[ii] -= h;
f += h;
// QL transformation
const double el1 = (*e)[ll + 1];
double p = (*d)[mm];
double c = 1.0, c2 = 1.0, s = 0.0;
double c3, s2;
for (int ii = mm - 1; ii >= ll; --ii)
{
c3 = c2;
c2 = c;
s2 = s;
const double g = c * (*e)[ii];
const double h = c * p;
const double r = Pythag(p, (*e)[ii]);
(*e)[ii + 1] = s * r;
s = (*e)[ii] / r;
c = p / r;
p = c * (*d)[ii] - s * g;
(*d)[ii + 1] = h + s * (c * g + s * (*d)[ii]);
// form eigenvector
for (int kk = 0; kk < n; ++kk)
{
const double h = (*z)(kk, ii + 1);
(*z)(kk, ii + 1) = s * (*z)(kk, ii) + c * h;
(*z)(kk, ii) = c * (*z)(kk, ii) - s * h;
}
}
const double p1 = -s * s2 * c3 * el1 * (*e)[ll] / dl1;
(*e)[ll] = s * p1;
(*d)[ll] = c * p1;
const double tst2 = tst1 + fabs((*e)[ll]);
if (tst2 == tst1)
break; // out of iterative loop
}
}
(*d)[ll] += f;
}
// order eigenvalues and eigenvectors (this code does not follow the Fortran implementation)
Vector_<int> keys = Vector::UpTo(n);
Sort(&keys, [&](int ii, int jj) { return (*d)[ii] > (*d)[jj]; });
// need the inverse of that permutation
Vector_<int> locs(n);
for (int ii = 0; ii < n; ++ii)
locs[keys[ii]] = ii;
for (int ik = 0; ik < n; ++ik)
{
const int jk = keys[ik];
assert(jk >= ik);
if (jk != ik)
{
std::swap((*d)[ik], (*d)[jk]);
std::swap_ranges(z->Col(ik).begin(), z->Col(ik).end(), z->Col(jk).begin());
keys[locs[ik]] = keys[ik];
locs[keys[ik]] = locs[ik];
}
}
}
void TRed2
(const Matrix_<>& a, // must be symmetric; only the lower triangle is used
Vector_<>* d, // will be populated with the diagonal elements of the tridiagonal reduced matrix
Vector_<>* e, // will be populated with the sub-diagonal elements of the reduced matrix, in elements [1, n)
Matrix_<>* z) // will be populated with the orthogonal transformation matrix produced in the reduction
{
const int n = a.Rows();
*z = a;
*d = Copy(a.Row(n - 1));
e->Resize(n);
for (int ii = n - 1; ii >= 1; --ii)
{
int ll = ii - 1;
double h = 0.0, scale = 0.0;
for (int kk = 0; kk <= ll; ++kk)
scale += fabs((*d)[kk]);
if (scale == 0.0)
{
(*e)[ii] = (*d)[ll];
for (int jj = 0; jj <= ll; ++jj)
{
(*d)[jj] = (*z)(ll, jj);
(*z)(ii, jj) = (*z)(jj, ii) = 0.0;
}
}
else
{
for (int kk = 0; kk <= ll; ++kk)
{
(*d)[kk] /= scale;
h += Square((*d)[kk]);
}
const double f0 = (*d)[ll];
const double g = -DSign(sqrt(h), f0);
(*e)[ii] = scale * g;
h -= f0 * g;
(*d)[ll] = f0 - g;
// form a * u
for (int jj = 0; jj <= ll; ++jj)
(*e)[jj] = 0.0;
for (int jj = 0; jj <= ll; ++jj)
{
const double f = (*d)[jj];
(*z)(jj, ii) = f;
double g = (*e)[jj] + (*z)(jj, jj) * f;
for (int kk = jj + 1; kk <= ll; ++kk)
{
g += (*z)(kk, jj) * (*d)[kk];
(*e)[kk] += (*z)(kk, jj) * f;
}
(*e)[jj] = g;
}
// form p
double f = 0.0;
for (int jj = 0; jj <= ll; ++jj)
{
(*e)[jj] /= h;
f += (*e)[jj] * (*d)[jj];
}
double hh = 0.5 * f / h;
// form q
for (int jj = 0; jj <= ll; ++jj)
(*e)[jj] -= hh * (*d)[jj];
// form reduced a
for (int jj = 0; jj <= ll; ++jj)
{
for (int kk = jj; kk <= ll; ++kk)
(*z)(kk, jj) -= (*d)[jj] * (*e)[kk] + (*e)[jj] * (*d)[kk];
(*d)[jj] = (*z)(ll, jj);
(*z)(ii, jj) = 0.0;
}
}
(*d)[ii] = h;
}
// accumulation of transformation matrices
for (int ii = 1; ii < n; ++ii)
{
int ll = ii - 1;
(*z)(n - 1, ll) = (*z)(ll, ll);
(*z)(ll, ll) = 1.0;
const double h = (*d)[ii];
if (h != 0.0)
{
for (int kk = 0; kk <= ll; ++kk)
(*d)[kk] = (*z)(kk, ii) / h;
for (int jj = 0; jj <= ll; ++jj)
{
double g = 0.0;
for (int kk = 0; kk <= ll; ++kk)
g += (*z)(kk, ii) * (*z)(kk, jj);
for (int kk = 0; kk <= ll; ++kk)
(*z)(kk, jj) -= g * (*d)[kk];
}
}
for (int kk = 0; kk <= ll; ++kk)
(*z)(kk, ii) = 0.0;
}
for (int ii = 0; ii < n; ++ii)
{
(*d)[ii] = (*z)(n - 1, ii);
(*z)(n - 1, ii) = 0.0;
}
(*z)(n - 1, n - 1) = 1.0;
(*e)[0] = 0.0;
}
} // leave local
void Eispack::RS
(const Matrix_<>& a, // the matrix to decompose -- must be symmetric
Vector_<>* w, // will be populated with eigenvalues
Matrix_<>* z) // will be populated with eigenvectors
{
Vector_<> fv1;
TRed2(a, w, &fv1, z);
TQL2(w, &fv1, z);
}
//----------------------------------------------------------------------------
// wrap the raw EISPACK functionality in SymmetricMatrixDecomposition_
namespace
{
struct EigenSystem_ : SymmetricMatrixDecomposition_
{
Vector_<> d_; // of eigenvalues
Vector_<Vector_<>> u_; // of eigenvectors
int Size() const override { return u_[0].size(); }
int Rank() const override { return d_.size(); }
void XMultiply_af
(const Vector_<>& x,
Vector_<>* b)
const override
{
b->Resize(x.size());
b->Fill(0.0);
for (int ii = 0; ii < d_.size(); ++ii)
Transform(b, u_[ii], LinearIncrement(InnerProduct(x, u_[ii]) * d_[ii]));
}
void XSolve_af
(const Vector_<>& b,
Vector_<>* x)
const override
{
x->Resize(b.size());
x->Fill(0.0);
REQUIRE(Rank() == Size(), "Eigensystem is not full rank");
for (int ii = 0; ii < d_.size(); ++ii)
{
REQUIRE(!IsZero(d_[ii]), "Eigensystem is singular");
Transform(x, u_[ii], LinearIncrement(InnerProduct(b, u_[ii]) / d_[ii]));
}
}
Vector_<>::const_iterator MakeCorrelated
(Vector_<>::const_iterator iid_begin,
Vector_<>* correlated)
const override
{
correlated->Resize(Size());
correlated->Fill(0.0);
for (int ii = 0; ii < d_.size(); ++ii)
{
REQUIRE(d_[ii] >= 0.0, "Eigensystem is not positive semidefinite");
Transform(correlated, u_[ii], LinearIncrement(*iid_begin++ * sqrt(d_[ii])));
}
return iid_begin;
}
};
} // leave local
SymmetricMatrixDecomposition_* NewEigenSystem
(const Matrix_<>& a,
double discard_threshold, // discard eigenmodes with eigenvalues below this
double error_threshold) // error on eigenvalues below this
{
std::unique_ptr<EigenSystem_> retval(new EigenSystem_);
Matrix_<> z;
Eispack::RS(a, &retval->d_, &z);
// process eigenmodes
NOTICE(error_threshold);
while (!retval->d_.empty())
{
REQUIRE(retval->d_.back() > error_threshold, "Eigenvalue is too small");
if (retval->d_.back() > discard_threshold)
break;
retval->d_.pop_back();
}
for (int ii = 0; ii < Max(1, retval->d_.size()); ++ii) // don't let u be empty, even if d is, because Size() uses u
retval->u_.push_back(Copy(z.Col(ii)));
return retval.release();
}
| true |
698410086db07dbe2a7f84dd28a80ae059233e07 | C++ | astephens4/Iriss | /Iriss/Orientation.hpp | UTF-8 | 456 | 2.53125 | 3 | [] | no_license | #ifndef IRISS_ORIENTATION_H
#define IRISS_ORIENTATION_H 1
#include "Utils/Packable.hpp"
namespace Iriss {
class Orientation : public Utils::Packable {
public:
static const unsigned char ORNTMSG = 3;
float roll;
float pitch;
float yaw;
Orientation(float r, float p, float y);
virtual void pack(std::vector<uint8_t>& bytes) const;
virtual void unpack(const std::vector<uint8_t>& bytes);
};
};
#endif // IRISS_ORIENTATION_H
| true |
95af82ec24540c42993c5e94337decaed17b6341 | C++ | zhangjiangen/hopper | /devel/CSGLib/src/ML_Line.cpp | UTF-8 | 4,083 | 2.9375 | 3 | [
"WTFPL"
] | permissive |
// Author: Greg Santucci
// Email: thecodewitch@gmail.com
// Project page: http://code.google.com/p/csgtestworld/
// Website: http://createuniverses.blogspot.com/
#include "ML_Line.h"
#include "ML_Maths.h"
#include "ML_Transform.h"
mlVector3D mlLine::Centroid(void) const
{
return (a + b) * 0.5f;
}
mlVector3D mlLine::Midpoint(void) const
{
return Centroid();
}
mlVector3D mlLine::Interpolate(mlFloat fT) const
{
return ((b - a) * fT) + a;
}
mlFloat mlLine::Length(void) const
{
return (a - b).Magnitude();
}
void mlLine::SetLengthFromA(mlFloat fNewLength)
{
mlVector3D vDirection = (b - a).Normalised();
b = a + vDirection * fNewLength;
}
mlVector3D mlLine::ProjectPoint(const mlVector3D & point) const
{
mlVector3D forward = b - a;
mlVector3D forwardNormalised = forward.Normalised();
mlFloat dotProduct = forwardNormalised * (point - a);
return a + dotProduct * forwardNormalised;
}
mlLine mlLine::ShortestLineToLine(const mlLine & line) const
{
mlVector3D p13 = a - line.a;
mlVector3D p43 = line.b - line.a;
mlVector3D p21 = b - a;
mlFloat d1343 = p13 * p43;
mlFloat d4321 = p43 * p21;
mlFloat d1321 = p13 * p21;
mlFloat d4343 = p43 * p43;
mlFloat d2121 = p21 * p21;
mlFloat denom = d2121 * d4343 - d4321 * d4321;
mlFloat numer = d1343 * d4321 - d1321 * d4343;
mlFloat mua = numer / denom;
mlFloat mub = (d1343 + d4321 * (mua)) / d4343;
return mlLine(a + mua * p21, line.a + mub * p43);
}
bool mlLine::ProjectionIsOnLine(const mlVector3D & point) const
{
mlVector3D vProjected = ProjectPoint(point);
mlFloat length = Length();
mlVector3D aToPoint = a - point;
mlFloat aToPointLength = aToPoint.Magnitude();
mlVector3D bToPoint = b - point;
mlFloat bToPointLength = bToPoint.Magnitude();
if(aToPointLength > length)
return false;
if(bToPointLength > length)
return false;
return true;
}
bool mlLine::IsOnLine(const mlVector3D & point) const
{
mlVector3D vProjected = ProjectPoint(point);
mlFloat fDistance = (point - vProjected).Magnitude();
if(fDistance > 0.01f)
{
return false;
}
//mlVector3D forward = a - b;
//mlFloat length = forward.Magnitude();
mlFloat length = Length();
//forward.Normalise();
mlVector3D aToPoint = a - point;
mlFloat aToPointLength = aToPoint.Magnitude();
//aToPoint.Normalise();
mlVector3D bToPoint = b - point;
mlFloat bToPointLength = bToPoint.Magnitude();
//bToPoint.Normalise();
//if((aToPoint - forward).Magnitude() > 0.01f)
// return false;
if(aToPointLength > length)
return false;
if(bToPointLength > length)
return false;
return true;
}
mlVector3D mlLine::RotatePoint(mlVector3D vPoint, mlFloat fAngle)
{
mlVector3D vCenter = ProjectPoint(vPoint);
mlVector3D vRadial = vPoint - vCenter;
mlFloat fRadius = vRadial.Magnitude();
vRadial.Normalise();
mlVector3D vAxis = a - b;
vAxis.Normalise();
//mlVector3D vTangent = mlVectorCross(vRadial, vAxis);
mlVector3D vTangent = mlVectorCross(vAxis, vRadial);
mlMatrix3x3 matSpace(vRadial, vTangent, vAxis);
//mlMatrix3x3 matSpace(vRadial, vAxis, vTangent);
//mlMatrix3x3 matSpace(vTangent, vRadial, vAxis);
//mlMatrix3x3 matSpace(vTangent, vAxis, vRadial);
//mlMatrix3x3 matSpace(vAxis, vTangent, vRadial);
//mlMatrix3x3 matSpace(vAxis, vRadial, vTangent);
mlTransform trnSpace(mlQuaternionFromRotationMatrix(matSpace), vCenter);
// Test begin
mlVector3D vForward = trnSpace.TransformVector(mlVector3D(0,0,1));
mlVector3D vRight = trnSpace.TransformVector(mlVector3D(1,0,0));
mlVector3D vUp = trnSpace.TransformVector(mlVector3D(0,1,0));
// Test end
trnSpace.ApplyRotation(mlQuaternion(vForward, fAngle));
mlVector3D vPushback;
vPushback = trnSpace.TransformVector(mlVector3D(-fRadius, 0, 0));
//vPushback = trnSpace.TransformVector(mlVector3D(0, fRadius, 0));
//vPushback = trnSpace.TransformVector(mlVector3D(0, 0, fRadius));
mlVector3D vRotated = vCenter - vPushback;
return vRotated;
}
mlVector3D mlLine::MoveInSameDirection(const mlVector3D & vStart, float fDistance) const
{
mlVector3D vDir = b - a;
vDir.Normalise();
return vStart + (vDir * fDistance);
}
| true |
4511f45158da0ffb3b742e3437f5bf80d9a9a651 | C++ | odeblic/joad-project | /network/serialization.cpp | UTF-8 | 2,487 | 3.125 | 3 | [] | no_license | #include "serialization.hpp"
#include <arpa/inet.h>
#include <cstdint>
#include <cstring>
#include <endian.h>
#include <string>
ByteBuffer::ByteBuffer()
: mContent{}, mCursor(0), mError(false)
{
}
ByteBuffer::~ByteBuffer()
{
}
void ByteBuffer::pushU8(std::uint8_t value)
{
return push(value);
}
void ByteBuffer::pushU16(std::uint16_t value)
{
return push(htons(value));
}
void ByteBuffer::pushU32(std::uint32_t value)
{
return push(htonl(value));
}
void ByteBuffer::pushU64(std::uint64_t value)
{
return push(htonll(value));
}
void ByteBuffer::pushFloat(float value)
{
return push(htonf(value));
}
void ByteBuffer::pushBytes(char const *buffer, std::size_t size)
{
if (mCursor + size <= mContent.size())
{
std::memcpy(&mContent[mCursor], reinterpret_cast<std::uint8_t const *>(buffer), size);
mCursor += size;
}
else
{
mError = true;
}
}
void ByteBuffer::pushStr(std::string const &value)
{
pushU16(value.size());
pushBytes(value.c_str(), value.size());
}
template <typename T>
void ByteBuffer::push(T const &value)
{
if (mCursor + sizeof(T) <= mContent.size())
{
std::memcpy(&mContent[mCursor], &value, sizeof(T));
mCursor += sizeof(T);
}
else
{
mError = true;
}
}
std::size_t ByteBuffer::getSize() const
{
return !mError ? mCursor : 0;
}
std::uint8_t const *ByteBuffer::getData() const
{
return !mError ? &mContent[0] : 0;
}
std::uint64_t ByteBuffer::htonll(std::uint64_t value)
{
if (htons(1) == 1)
{
return value;
}
else
{
std::uint64_t result;
auto aliasVal = reinterpret_cast<char *>(&value);
auto aliasRes = reinterpret_cast<char *>(&result);
aliasRes[0] = aliasVal[7];
aliasRes[1] = aliasVal[6];
aliasRes[2] = aliasVal[5];
aliasRes[3] = aliasVal[4];
aliasRes[4] = aliasVal[3];
aliasRes[5] = aliasVal[2];
aliasRes[6] = aliasVal[1];
aliasRes[7] = aliasVal[0];
return result;
}
}
float ByteBuffer::htonf(float value)
{
if (htons(1) == 1)
{
return value;
}
else
{
float result;
auto aliasVal = reinterpret_cast<char *>(&value);
auto aliasRes = reinterpret_cast<char *>(&result);
aliasRes[0] = aliasVal[3];
aliasRes[1] = aliasVal[2];
aliasRes[2] = aliasVal[1];
aliasRes[3] = aliasVal[0];
return result;
}
}
| true |
0beb1c1dd0de491d1736cda199dce2ea18ef4aa8 | C++ | hota1024/OpenSiv3D | /Siv3D/include/Siv3D/Spherical.hpp | UTF-8 | 4,062 | 2.734375 | 3 | [
"MIT"
] | permissive | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Fwd.hpp"
# include "Vector3D.hpp"
# include "MathConstants.hpp"
namespace s3d
{
/// <summary>
/// 球面座標
/// </summary>
struct Spherical
{
double r, theta, phi;
Spherical() = default;
constexpr Spherical(double _r, double _theta, double _phi) noexcept
: r(_r)
, theta(_theta)
, phi(_phi) {}
constexpr Spherical(Arg::r_<double> _r, Arg::theta_<double> _theta, Arg::phi_<double> _phi) noexcept
: r(*_r)
, theta(*_theta)
, phi(*_phi) {}
constexpr Spherical(Arg::r_<double> _r, Arg::phi_<double> _phi, Arg::theta_<double> _theta) noexcept
: r(*_r)
, theta(*_theta)
, phi(*_phi) {}
constexpr Spherical(Arg::theta_<double> _theta, Arg::r_<double> _r, Arg::phi_<double> _phi) noexcept
: r(*_r)
, theta(*_theta)
, phi(*_phi) {}
constexpr Spherical(Arg::theta_<double> _theta, Arg::phi_<double> _phi, Arg::r_<double> _r) noexcept
: r(*_r)
, theta(*_theta)
, phi(*_phi) {}
constexpr Spherical(Arg::phi_<double> _phi, Arg::r_<double> _r, Arg::theta_<double> _theta) noexcept
: r(*_r)
, theta(*_theta)
, phi(*_phi) {}
constexpr Spherical(Arg::phi_<double> _phi, Arg::theta_<double> _theta, Arg::r_<double> _r) noexcept
: r(*_r)
, theta(*_theta)
, phi(*_phi) {}
Spherical(const Vec3& pos)
: r(pos.length())
, theta(std::acos(pos.y / r))
, phi(std::atan2(pos.z, pos.x)) {}
[[nodiscard]] constexpr Spherical operator +() const noexcept
{
return *this;
}
[[nodiscard]] constexpr Spherical operator -() const noexcept
{
return{ r, theta + Math::Pi, phi + Math::Pi };
}
[[nodiscard]] Vec3 operator +(const Vec3& v) const
{
return toVec3() + v;
}
[[nodiscard]] Vec3 operator -(const Vec3& v) const
{
return toVec3() - v;
}
[[nodiscard]] Vec3 toFloat3() const
{
const double s = std::sin(theta);
return{ r * s * std::cos(phi), r * std::cos(theta), r * s * std::sin(phi) };
}
[[nodiscard]] Vec3 toVec3() const
{
const double s = std::sin(theta);
return{ r * s * std::cos(phi), r * std::cos(theta), r * s * std::sin(phi) };
}
[[nodiscard]] operator Vec3() const
{
return toVec3();
}
};
}
//////////////////////////////////////////////////
//
// Format
//
//////////////////////////////////////////////////
namespace s3d
{
inline void Formatter(FormatData& formatData, const Spherical& value)
{
Formatter(formatData, Vec3(value.r, value.theta, value.phi));
}
template <class CharType>
inline std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& output, const Spherical& value)
{
return output << CharType('(')
<< value.r << CharType(',')
<< value.theta << CharType(',')
<< value.phi << CharType(')');
}
template <class CharType>
inline std::basic_istream<CharType>& operator >>(std::basic_istream<CharType>& input, Spherical& value)
{
CharType unused;
return input >> unused
>> value.r >> unused
>> value.theta >> unused
>> value.phi >> unused;
}
}
//////////////////////////////////////////////////
//
// Hash
//
//////////////////////////////////////////////////
namespace std
{
template <>
struct hash<s3d::Spherical>
{
[[nodiscard]] size_t operator ()(const s3d::Spherical& value) const noexcept
{
return s3d::Hash::FNV1a(value);
}
};
}
//////////////////////////////////////////////////
//
// fmt
//
//////////////////////////////////////////////////
namespace fmt
{
template <class ArgFormatter>
void format_arg(BasicFormatter<s3d::char32, ArgFormatter>& f, const s3d::char32*& format_str, const s3d::Spherical& value)
{
const auto tag = s3d::detail::GetTag(format_str);
const auto fmt = U"({" + tag + U"},{" + tag + U"},{" + tag + U"})";
f.writer().write(fmt, value.r, value.theta, value.phi);
}
}
| true |
e538d074843de58da6e722242afeac066db9ebb5 | C++ | andreucm/sketches | /27_offLineYarpPublisher/offLinePublisher.cpp | UTF-8 | 6,353 | 2.65625 | 3 | [] | no_license |
#include "offLinePublisher.h"
CoffLinePublisher::CoffLinePublisher(const double firstTS, const string configFileName, bool vb)
{
userFirstTimeStamp = firstTS;
openFiles(configFileName);
initializeTimeStamps();
verbose = vb;
}
CoffLinePublisher::~CoffLinePublisher()
{
unsigned int ii;
for (ii=0; ii<fileSet.size(); ii++) fileSet.at(ii)->close();
fileSet.clear();
for (ii=0; ii<portSet.size(); ii++) portSet.at(ii)->close();
portSet.clear();
if (verbose) cout << "End of CoffLinePublisher DESTRUCTOR " << endl;
}
void CoffLinePublisher::initializeNow()
{
firstNow = timeStamp();
cout << " First Log File Time Stamp: "; printTimeStamp(logFileFirstTimeStamp, &cout); cout << endl;
cout << " Starting Off-line Loop Time: "; printTimeStamp(firstNow, &cout); cout << endl;
}
int CoffLinePublisher::publishNextData()
{
unsigned int numC, ii;
double tsi, now, dT;
//reads data from the file indicated by the index iiNext
fileSet.at(iiNext)->get(); //just extract a space char after the time stamp already read
fileSet.at(iiNext)->getline(buf, MAX_CHARS_PER_LINE);//reads the data row up to the end
numC = fileSet.at(iiNext)->gcount();
if (verbose)
{
cout << endl << "Read Data: ";
printTimeStamp(timeStamps.at(iiNext), &cout);
cout << ": " << buf << endl;
}
//publishData thorugh YARP ports
Bottle & bot = portSet.at(iiNext)->prepare();
bot.clear();
bot.addDouble(timeStamps.at(iiNext)); //add time stamp at the first field of the bottle
fillBottle(iiNext, buf, bot);
if (verbose)
{
cout << "Published Data: ";
cout << bot.toString() << endl;
}
portSet.at(iiNext)->write();
//clear buffer
clearBuffer(numC);
//reads the next ts for the current active file
(*fileSet.at(iiNext)) >> tsi;
timeStamps.at(iiNext) = tsi;
//checks end of file
if ( fileSet.at(iiNext)->eof() )
{
cout << "End of File for file id: " << iiNext << endl;
fileStatus.at(iiNext) = END_OF_FILE;
timeStamps.at(iiNext) = timeStamp();
}
//checks if all files are EOF
bool all_eof = true;
for (ii=1; ii<fileStatus.size(); ii++)
{
if ( fileStatus.at(ii) == ACTIVE_FILE )
{
all_eof = false;
break;
}
}
if (all_eof) return ALL_FILES_ENDED;
//decides the next file
tsi = timeStamps.at(0);
iiNext=0;
for (ii=1; ii<fileSet.size(); ii++)
{
if ( ( fileStatus.at(ii) == ACTIVE_FILE ) && ( timeStamps.at(ii) < tsi ) )
{
tsi = timeStamps.at(ii);
iiNext=ii;
}
}
//sleeps up to the next time stamp
now = timeStamp();
dT = (timeStamps.at(iiNext)-logFileFirstTimeStamp) - (now-firstNow);
if ( dT<0 ) dT = 0;
dT = dT*(double)1e6;
usleep((int)dT);
return RUNNING;
}
void CoffLinePublisher::openFiles(const string configFileName)
{
ifstream configFile;
string dataFileName;
ifstream *dataFile;
BufferedPort<Bottle> *bPort;
cout << "Opening files indicated by config file: " << configFileName << endl;
configFile.open(configFileName.c_str(), ifstream::in); //opens config file
while (!configFile.eof())
{
configFile.getline(buf,MAX_CHARS_PER_LINE, ' '); //reads up to reach MAX_CHARS_PER_LINE,' ' or eof
//cout << "Read chars: " << configFile.gcount() << "; Opening file: " << buf.str().c_str() << endl;
if ( configFile.gcount() > 3 ) //"heuristic" condition to avoid last spacing line to be confused as a file
{
//cout << "Read chars: " << configFile.gcount() << endl;
cout << "; Opening file: " << buf << endl;
dataFile = new ifstream();
dataFile->open(buf);
fileSet.push_back(dataFile);//adds data file to the set
timeStamps.push_back(0);//initializes time stamp vector to 0
fileStatus.push_back(ACTIVE_FILE); //indicates that the file is active
clearBuffer(configFile.gcount());
configFile.getline(buf,MAX_CHARS_PER_LINE, '\n'); //reads port name
cout << "port name: " << buf << endl;
bPort = new BufferedPort<Bottle>;
bPort->open(buf);
portSet.push_back(bPort);
clearBuffer(configFile.gcount());
}
}
}
void CoffLinePublisher::initializeTimeStamps()
{
unsigned int ii;
double tsi;
//advances file seek position up to the first row data with timestamp>= userFirstTimeStamp
for (ii=0; ii<fileSet.size(); ii++)
{
(*fileSet.at(ii)) >> tsi;
timeStamps.at(ii) = tsi;
while ( tsi < userFirstTimeStamp )
{
fileSet.at(ii)->getline(buf, MAX_CHARS_PER_LINE);
clearBuffer(fileSet.at(ii)->gcount());//discard line
(*fileSet.at(ii)) >> tsi;
timeStamps.at(ii) = tsi; //updates data time stamp for this file
}
//cout << timeStamps.at(ii) << endl;
}
//initializes logFileFirstTimeStamp and iiNext
logFileFirstTimeStamp = timeStamps.at(0);
iiNext=0;
for (ii=1; ii<timeStamps.size(); ii++)
{
if ( timeStamps.at(ii) <= logFileFirstTimeStamp)
{
logFileFirstTimeStamp = timeStamps.at(ii);
iiNext = ii;
}
}
//cout << iiNext << "; " << logFileFirstTimeStamp << endl;
}
//this method should be replaced by some more elaborated method allowing to parse log files from a given data pattern described as a txt file or xml
void CoffLinePublisher::fillBottle(unsigned int bottleLayout, const char *buffer, Bottle & bot)
{
stringstream stream_buf;
string aux_string;
int aux_int;
double aux_double;
stream_buf << buffer;
if (verbose)cout << "streamBuf (Line " << __LINE__ << "): " << stream_buf.str() << endl;
switch(bottleLayout)
{
case 0:
stream_buf >> aux_int;
bot.addInt(aux_int);
stream_buf >> aux_int;
bot.addInt(aux_int);
stream_buf >> aux_double;
bot.addInt(aux_double);
break;
case 1:
stream_buf >> aux_int;
bot.addInt(aux_int);
getline (stream_buf,aux_string);
bot.addString(aux_string.c_str());
break;
default:
cout << "Warning: Unknown bottle layout!" << endl;
break;
}
}
void CoffLinePublisher::clearBuffer(const unsigned int nn)
{
unsigned int ii;
for (ii=0; ii<nn; ii++) buf[ii] = '\0';
}
double CoffLinePublisher::timeStamp()
{
timeval timeStamp;
gettimeofday(&timeStamp, NULL);
return (double)(timeStamp.tv_sec + timeStamp.tv_usec/1e6);
}
void CoffLinePublisher::printTimeStamp(const double tS, ostream *ost)
{
streamsize nn, ww;
ios_base::fmtflags fmtfl;
char cc;
fmtfl = ost->flags(ios::left);
cc = ost->fill('0');
ww = ost->width(TIME_STAMP_DIGITS);
nn = ost->precision(TIME_STAMP_DIGITS);
(*ost) << tS;
ost->flags(fmtfl);
ost->fill(cc);
ost->width(ww);
ost->precision(nn);
}
| true |
4c275070e15fae3a291723f161bf40b2d22d34ae | C++ | aws/aws-sdk-cpp | /generated/src/aws-cpp-sdk-quicksight/include/aws/quicksight/model/Template.h | UTF-8 | 9,845 | 2.59375 | 3 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/quicksight/QuickSight_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/quicksight/model/TemplateVersion.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace QuickSight
{
namespace Model
{
/**
* <p>A template object. A <i>template</i> is an entity in Amazon QuickSight that
* encapsulates the metadata required to create an analysis and that you can use to
* create a dashboard. A template adds a layer of abstraction by using placeholders
* to replace the dataset associated with an analysis. You can use templates to
* create dashboards by replacing dataset placeholders with datasets that follow
* the same schema that was used to create the source analysis and template.</p>
* <p>You can share templates across Amazon Web Services accounts by allowing users
* in other Amazon Web Services accounts to create a template or a dashboard from
* an existing template.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/Template">AWS
* API Reference</a></p>
*/
class Template
{
public:
AWS_QUICKSIGHT_API Template();
AWS_QUICKSIGHT_API Template(Aws::Utils::Json::JsonView jsonValue);
AWS_QUICKSIGHT_API Template& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_QUICKSIGHT_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline Template& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline Template& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the template.</p>
*/
inline Template& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>The display name of the template.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The display name of the template.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The display name of the template.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The display name of the template.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The display name of the template.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The display name of the template.</p>
*/
inline Template& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The display name of the template.</p>
*/
inline Template& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The display name of the template.</p>
*/
inline Template& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>A structure describing the versions of the template.</p>
*/
inline const TemplateVersion& GetVersion() const{ return m_version; }
/**
* <p>A structure describing the versions of the template.</p>
*/
inline bool VersionHasBeenSet() const { return m_versionHasBeenSet; }
/**
* <p>A structure describing the versions of the template.</p>
*/
inline void SetVersion(const TemplateVersion& value) { m_versionHasBeenSet = true; m_version = value; }
/**
* <p>A structure describing the versions of the template.</p>
*/
inline void SetVersion(TemplateVersion&& value) { m_versionHasBeenSet = true; m_version = std::move(value); }
/**
* <p>A structure describing the versions of the template.</p>
*/
inline Template& WithVersion(const TemplateVersion& value) { SetVersion(value); return *this;}
/**
* <p>A structure describing the versions of the template.</p>
*/
inline Template& WithVersion(TemplateVersion&& value) { SetVersion(std::move(value)); return *this;}
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline const Aws::String& GetTemplateId() const{ return m_templateId; }
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline bool TemplateIdHasBeenSet() const { return m_templateIdHasBeenSet; }
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline void SetTemplateId(const Aws::String& value) { m_templateIdHasBeenSet = true; m_templateId = value; }
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline void SetTemplateId(Aws::String&& value) { m_templateIdHasBeenSet = true; m_templateId = std::move(value); }
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline void SetTemplateId(const char* value) { m_templateIdHasBeenSet = true; m_templateId.assign(value); }
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline Template& WithTemplateId(const Aws::String& value) { SetTemplateId(value); return *this;}
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline Template& WithTemplateId(Aws::String&& value) { SetTemplateId(std::move(value)); return *this;}
/**
* <p>The ID for the template. This is unique per Amazon Web Services Region for
* each Amazon Web Services account.</p>
*/
inline Template& WithTemplateId(const char* value) { SetTemplateId(value); return *this;}
/**
* <p>Time when this was last updated.</p>
*/
inline const Aws::Utils::DateTime& GetLastUpdatedTime() const{ return m_lastUpdatedTime; }
/**
* <p>Time when this was last updated.</p>
*/
inline bool LastUpdatedTimeHasBeenSet() const { return m_lastUpdatedTimeHasBeenSet; }
/**
* <p>Time when this was last updated.</p>
*/
inline void SetLastUpdatedTime(const Aws::Utils::DateTime& value) { m_lastUpdatedTimeHasBeenSet = true; m_lastUpdatedTime = value; }
/**
* <p>Time when this was last updated.</p>
*/
inline void SetLastUpdatedTime(Aws::Utils::DateTime&& value) { m_lastUpdatedTimeHasBeenSet = true; m_lastUpdatedTime = std::move(value); }
/**
* <p>Time when this was last updated.</p>
*/
inline Template& WithLastUpdatedTime(const Aws::Utils::DateTime& value) { SetLastUpdatedTime(value); return *this;}
/**
* <p>Time when this was last updated.</p>
*/
inline Template& WithLastUpdatedTime(Aws::Utils::DateTime&& value) { SetLastUpdatedTime(std::move(value)); return *this;}
/**
* <p>Time when this was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreatedTime() const{ return m_createdTime; }
/**
* <p>Time when this was created.</p>
*/
inline bool CreatedTimeHasBeenSet() const { return m_createdTimeHasBeenSet; }
/**
* <p>Time when this was created.</p>
*/
inline void SetCreatedTime(const Aws::Utils::DateTime& value) { m_createdTimeHasBeenSet = true; m_createdTime = value; }
/**
* <p>Time when this was created.</p>
*/
inline void SetCreatedTime(Aws::Utils::DateTime&& value) { m_createdTimeHasBeenSet = true; m_createdTime = std::move(value); }
/**
* <p>Time when this was created.</p>
*/
inline Template& WithCreatedTime(const Aws::Utils::DateTime& value) { SetCreatedTime(value); return *this;}
/**
* <p>Time when this was created.</p>
*/
inline Template& WithCreatedTime(Aws::Utils::DateTime&& value) { SetCreatedTime(std::move(value)); return *this;}
private:
Aws::String m_arn;
bool m_arnHasBeenSet = false;
Aws::String m_name;
bool m_nameHasBeenSet = false;
TemplateVersion m_version;
bool m_versionHasBeenSet = false;
Aws::String m_templateId;
bool m_templateIdHasBeenSet = false;
Aws::Utils::DateTime m_lastUpdatedTime;
bool m_lastUpdatedTimeHasBeenSet = false;
Aws::Utils::DateTime m_createdTime;
bool m_createdTimeHasBeenSet = false;
};
} // namespace Model
} // namespace QuickSight
} // namespace Aws
| true |
6930a6ce1c250990891c37ab81a73bc955e9a342 | C++ | Francinildo-Figueiredo/Projetos-em-C-mais-mais | /Conversor_de_bases_numericas/Conversor.cpp | ISO-8859-1 | 5,781 | 3.296875 | 3 | [
"MIT"
] | permissive | #include "Conversor.h"
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
using std::to_string;
using std::stoi;
#include <cmath>
using std::pow;
#include <cctype>
using std::isdigit;
Conversor::Conversor( unsigned long long d, long long b, string oct, string hd )
{
setDecimal( d );
setBinary( b );
setOctal( oct );
setHexadecimal( hd );
}
bool Conversor::setDecimal( unsigned long long d )
{
bool verificador = true;
if ( d >= 0 )
{
decimal = d;
}
else
verificador = false;
return verificador;
}
bool Conversor::setBinary( long long b )
{
long long aux = b;
while ( aux != 0 )
{
if ( aux % 10 == 1 || aux % 10 == 0 )
{
aux /= 10;
}
else
{
aux = 0;
b = 0;
cout << "O nmero digitado no esta em binrio!" << endl;
return false;
}
}
if ( aux == 0 && b != 0 )
binary = b;
else
binary = 0;
return true;
}
bool Conversor::setOctal( string oct )
{
bool verificador = true;
if ( oct.size() < 22 || oct[0] >= '0' && oct[0] < '2' )
{
for ( size_t i = 0; i < oct.size(); i++ )
{
if ( oct[i] >= '0' && oct[i] <= '7' )
octal = oct;
else
{
verificador = false;
cout << "O nmero digitado no est em octal!\n" << endl;
}
}
}
else
{
cout << "O octal digitado no esta na faixa de 0 - 777777777777777777777!\n" << endl;
verificador = false;
}
return verificador;
}
bool Conversor::setHexadecimal( string hexd )
{
if ( hexd.size() <= 16 )
{
for ( size_t i = 0; i < hexd.size(); i++ )
{
hexd[i] = toupper( hexd[i] );
}
for ( size_t i = 0; i < hexd.size(); i++ )
{
if ( ( hexd[i] >= 'A' && hexd[i] <= 'F' ) || isdigit( hexd[i] ) )
{
hexadecimal = hexd;
}
else
{
cout << "O nmero digitado no esta em hexadecimal!\n" << endl;
return false;
}
}
return true;
}
else
{
cout << "O hexadecimal digitado no esta na faixa de 0 - FFFFFFFFFFFFFFFF!" << endl;
return false;
}
}
unsigned long long Conversor::getDecimal() const
{
return decimal;
}
long long Conversor::getBinary() const
{
return binary;
}
string Conversor::getOctal() const
{
return octal;
}
string Conversor::getHexadecimal() const
{
return hexadecimal;
}
long long Conversor::convertDecimaltoBinary() const
{
unsigned long long aux = getDecimal();
int resto = 0;
int i = 0;
long long bin = 0;
if ( aux <= 65535 )
{
while ( aux != 0 )
{
resto = aux % 2;
bin += resto * pow( 10, i );
i++;
aux /= 2;
}
}
return bin;
}
unsigned long long Conversor::convertBinarytoDecimal() const
{
long long aux = getBinary();
unsigned long long decimalNumber = 0;
int i = 0;
while ( aux != 0 )
{
decimalNumber += ( aux % 10 ) * pow( 2, i );
i++;
aux /= 10;
}
return decimalNumber;
}
string Conversor::convertDecimaltoOctal() const
{
unsigned long long aux = getDecimal();
size_t count = 0;
while ( aux != 0 )
{
aux /= 8;
count++;
}
int *numbers = new int[ count ];
aux = getDecimal();
if ( aux == 0 )
return "0";
for ( size_t i = count - 1; aux != 0; i-- )
{
numbers[i] = aux % 8;
aux /= 8;
}
string oct;
for ( size_t i = 0; i < count; i++ )
{
oct.append( to_string( numbers[i] ) );
}
delete [] numbers;
return oct;
}
unsigned long long Conversor::convertOctaltoDecimal() const
{
string oct = getOctal();
int size = getOctal().size();
string *aux = new string[size];
unsigned long long number = 0;
int p = size - 1;
for ( size_t i = 0; i < size; i++ )
{
aux[i] = oct[i];
}
for ( size_t i = 0; i < size; i++ )
{
number += stoi( aux[i] ) * pow( 8, p);
p--;
}
delete [] aux;
return number;
}
string Conversor::convertDecimaltoHexa() const
{
unsigned long long aux = getDecimal();
size_t count = 0;
while ( aux != 0 )
{
aux /= 16;
count++;
}
int *numbers = new int[ count ];
aux = getDecimal();
for ( size_t i = count - 1; aux != 0; i-- )
{
numbers[i] = aux % 16;
aux /= 16;
}
string hexadecimal;
for ( size_t i = 0; i < count; i++ )
{
if ( numbers[i] > 9 )
{
switch( numbers[i] )
{
case 10:
hexadecimal.append( "A" );
break;
case 11:
hexadecimal.append( "B" );
break;
case 12:
hexadecimal.append( "C" );
break;
case 13:
hexadecimal.append( "D" );
break;
case 14:
hexadecimal.append( "E" );
break;
case 15:
hexadecimal.append( "F" );
break;
default:
break;
}
}
else
hexadecimal.append( to_string( numbers[i] ) );
}
delete [] numbers;
return hexadecimal;
}
unsigned long long Conversor::convertHexatoDecimal() const
{
string hexad = getHexadecimal();
int size = getHexadecimal().size();
string *aux = new string[ size ];
int *numbers = new int[ size ];
for ( size_t i = 0; i < size; i++ )
{
switch( hexad[i] )
{
case 'A':
aux[i] = "10";
break;
case 'B':
aux[i] = "11";
break;
case 'C':
aux[i] = "12";
break;
case 'D':
aux[i] = "13";
break;
case 'E':
aux[i] = "14";
break;
case 'F':
aux[i] = "15";
break;
default:
break;
}
if ( isdigit( hexad[i] ) )
aux[i] = hexad[i];
}
int p = size - 1;
cout << "Calculo: ";
for ( size_t i = 0; i < size; i++ )
{
cout << aux[i] << "x16^" << p << " + ";
p--;
}
cout << '0' << endl << endl;
for ( size_t i = 0; i < size; i++ )
{
numbers[i] = stoi( aux[i] );
}
delete [] aux;
unsigned long long number = 0;
p = size - 1;
for ( size_t i = 0; i < size; i++ )
{
number += numbers[i] * pow(16, p);
p--;
}
delete [] numbers;
if ( hexad == "FFFFFFFFFFFFFFFF" )
return 18446744073709551615;
else
return number;
}
| true |
216d2e65a8f925668475bfc067967d3b0e02349a | C++ | WhiZTiM/ParserDataStructures | /include/FVector.hpp | UTF-8 | 11,884 | 2.875 | 3 | [] | no_license | /*
* ParserDataStructures
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Author: Ibrahim Timothy Onogu
* Email: ionogu@acm.org
* Project Date: March, 2016
*/
#ifndef FVECTOR_H
#define FVECTOR_H
#include "Config.hpp"
#include <utility>
#include <type_traits>
#include <initializer_list>
#include <iterator>
using SizeType = uint32_t;
template<typename T>
class FVector{
struct detail {
template<bool IsConst>
class iterator
{
public:
using difference_type = std::ptrdiff_t;
using value_type = std::conditional_t<IsConst, std::add_const_t<T>, T>;
using pointer = value_type*;
using reference = value_type&;
using iterator_category = std::random_access_iterator_tag;
private:
explicit iterator(pointer data) : ptr(data){}
public:
iterator() = default;
iterator(const iterator&) = default;
iterator& operator = (const iterator&) = default;
operator iterator<true> () const { return iterator<true>(ptr); }
pointer operator -> () const { return ptr; }
reference operator * () const { return *ptr; }
iterator& operator ++ () { ++ptr; return *const_cast<iterator*>(this); }
iterator operator ++ (int) { iterator t(*this); ++ptr; return t; }
iterator& operator -- () { --ptr; return *const_cast<iterator*>(this); }
iterator operator -- (int) { iterator t(*this); --ptr; return t; }
iterator& operator += (int idx) { ptr +=idx; return *const_cast<iterator*>(this); }
iterator& operator -= (int idx) { ptr -=idx; return *const_cast<iterator*>(this); }
iterator operator + (int idx) const { return iterator(ptr + idx); }
iterator operator - (int idx) const { return iterator(ptr - idx); }
reference operator [] (std::ptrdiff_t idx) const { return *(ptr + idx); }
std::ptrdiff_t operator - (const iterator& other) const { return (ptr - other.ptr); }
friend bool operator == (const iterator& lhs, const iterator& rhs){ return lhs.ptr == rhs.ptr; }
friend bool operator != (const iterator& lhs, const iterator& rhs){ return!(lhs.ptr == rhs.ptr); }
friend bool operator < (const iterator& lhs, const iterator& rhs){ return (rhs.ptr - lhs.ptr) > 0; }
friend bool operator > (const iterator& lhs, const iterator& rhs){ return (lhs.ptr - rhs.ptr) > 0; }
friend bool operator <= (const iterator& lhs, const iterator& rhs){ return (rhs.ptr - lhs.ptr) >= 0; }
friend bool operator >= (const iterator& lhs, const iterator& rhs){ return (lhs.ptr - rhs.ptr) >= 0; }
private:
friend class FVector<T>;
pointer ptr = nullptr;
};
};
public:
//Forward Iterators
using iterator = typename detail::template iterator<false>;
using const_iterator = typename detail::template iterator<true>;
iterator begin() {return iterator(m_data); }
const_iterator begin() const {return const_iterator(m_data); }
const_iterator cbegin() const {return const_iterator(m_data); }
iterator end() {return iterator(m_data+m_size); }
const_iterator end() const {return const_iterator(m_data+m_size); }
const_iterator cend() const {return const_iterator(m_data+m_size); }
//Reverse Iterators
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
reverse_iterator rbegin() {return reverse_iterator(iterator(m_data + m_size)); }
const_reverse_iterator rbegin() const {return const_reverse_iterator(iterator(m_data + m_size)); }
const_reverse_iterator crbegin() const {return const_reverse_iterator(iterator(m_data + m_size)); }
reverse_iterator rend() {return reverse_iterator(iterator(m_data)); }
const_reverse_iterator rend() const {return const_reverse_iterator(iterator(m_data)); }
const_reverse_iterator crend() const {return const_reverse_iterator(iterator(m_data)); }
public:
using value_type = T;
using size_type = SizeType;
using pointer = value_type*;
using reference = value_type&;
using const_pointer = const value_type*;
using const_reference = const value_type&;
using difference_type = std::ptrdiff_t;
struct reserve_tag_t{};
static reserve_tag_t reserve_tag;
FVector(){}
FVector(SizeType sz){
resize(sz);
}
FVector(SizeType sz, reserve_tag_t){
reserve(sz);
}
FVector(SizeType sz, const T& t){
reserve(sz);
for(SizeType i = 0; i < sz; i++)
push_back(t);
}
FVector(std::initializer_list<T> ls){
emplace_back(ls);
}
FVector(FVector&& other) noexcept {
move_from(std::move(other));
}
FVector(const FVector& other){
copy_from(other);
}
FVector& operator = (FVector&& other) noexcept {
if(this == &other) return *this;
move_from(std::move(other));
}
FVector& operator = (const FVector& other) noexcept {
if(this == &other) return *this;
copy_from(other);
}
~FVector() noexcept {
SFAllocator<T>::deallocate(m_data);
}
inline bool FORCE_INLINE empty() const {
return m_size == 0;
}
inline SizeType FORCE_INLINE size() const {
return m_size;
}
inline SizeType FORCE_INLINE capacity() const {
return m_capacity;
}
inline FORCE_INLINE T& operator [] (SizeType idx){
return m_data[idx];
}
inline FORCE_INLINE T const& operator [] (SizeType idx) const{
return m_data[idx];
}
inline FORCE_INLINE T& at(SizeType idx) {
if(!(idx < m_size))
throw std::out_of_range("Invalid Range given");
return m_data[idx];
}
inline FORCE_INLINE T const& at(SizeType idx) const{
return const_cast<FVector*>(this)->at(idx);
}
void push_back(const T& val){
emplace_back(T(val));
}
void push_back(T&& val){
emplace_back(std::move(val));
}
void pop_back() {
call_destructor(m_data[m_size - 1]);
--m_size;
}
T& back(){ return m_data[m_size-1]; }
const T& back() const { return m_data[m_size-1]; }
T& front(){ return m_data[0]; }
const T& front() const { return m_data[0]; }
void clear() noexcept {
for(SizeType i=0; i<m_size; i++)
call_destructor(m_data[i]);
m_size = 0;
}
iterator erase(const_iterator pos){
return erase(pos, pos + 1);
}
iterator erase(const_iterator first, const_iterator last){
int S = first - cbegin();
int L = last - cbegin();
int diff = L - S;
if(diff <= 0 || int(m_size) - diff <= 0)
return end();
for(int i = S; i < L; i++){
call_destructor(m_data[i]);
}
for(int i = S; unsigned(i + diff) < m_size; i++){
new (m_data+i) T(std::move(m_data[i + diff]));
call_destructor(m_data[i + diff]);
}
m_size -= diff;
auto kpx = m_data + (L - 1);
return iterator(kpx);
}
template<typename... Args>
void emplace_back(Args&&... arg){
if(m_size >= m_capacity)
grow_capacity(); //should be same as calling reserve((m_size+1) * 2);
new(m_data+m_size) T(std::forward<Args>(arg)...);
m_size += 1;
}
void emplace_back(std::initializer_list<T> ls){
if(ls.size() + m_size >= m_capacity){
if(ls.size() + m_size >= (m_capacity+1)*2)
reserve(ls.size() + m_size);
else
grow_capacity();
}
unsigned idx = 0;
for(auto it = std::begin(ls); it != std::end(ls); ++it)
new(m_data + m_size + idx++) T(std::move(*it));
m_size += idx;
}
void swap(FVector& other){
using std::swap;
swap(m_size, other.m_size);
swap(m_data, other.m_data);
swap(m_capacity, other.m_capacity);
}
friend void swap(FVector& lhs, FVector& rhs){ //for ADL
lhs.swap(rhs);
}
template<typename... Arg>
void resize(SizeType sz, Arg&&... arg){
reserve(sz);
if(sz > m_size)
for(SizeType i=m_size; i<sz; i++)
new(m_data+i) T(std::forward(arg)...);
else
for(SizeType i=sz; i<m_size; i++)
call_destructor(m_data[i]);
m_size = sz;
}
void reserve(SizeType sz){
if(sz > m_capacity){
T* data = static_cast<T*>(SFAllocator<T>::allocate(sz));
for(SizeType i=0; i < m_size; i++){
new(data+i) T(std::move(m_data[i])); //! TODO: move if only noexcept;
call_destructor(m_data[i]);
}
SFAllocator<T>::deallocate(m_data);
m_capacity = sz;
m_data = data;
}
}
// Unlike C++'s STL, this is a binding request
void shrink_to_fit(){
if(m_size < m_capacity){
T* data = static_cast<T*>(SFAllocator<T>::allocate(m_size));
for(SizeType i=0; i < m_size; i++){
new(data+i) T(std::move(m_data[i])); //! TODO: move if only noexcept;
call_destructor(m_data[i]);
}
SFAllocator<T>::deallocate(m_data);
m_capacity = m_size;
m_data = data;
}
}
void assign(size_type count, const T& value){
reserve(count);
size_type i = 0, sc = std::min(count, m_size);
for(; i < sc; i++)
operator [](i) = value;
for(; i < count; i++)
new(m_data + i) T(value);
m_size = count;
}
void assign(std::initializer_list<T> ilist){
reserve(ilist.size());
size_type i = 0, sc = std::min(ilist.size(), std::size_t(m_size));
auto it = std::begin(ilist);
for(; it != std::end(ilist); ++it)
operator [](i++) = *it;
for(; it != std::end(ilist); ++it)
new(m_data + i++) T(*it);
m_size = ilist.size();
}
template< class InputIt >
void assign( InputIt first, InputIt last ){
size_type i = 0;
for(; (first != last) && (i < m_size); ++first, i++)
operator [](i) = *first;
for(; first != last; ++first, i++)
emplace_back(*first);
m_size = i;
}
inline void FORCE_INLINE move_from(FVector&& other){
clear();
swap(other);
}
inline void FORCE_INLINE copy_from(const FVector& other){
clear();
reserve(other.m_size);
for(SizeType i=0; i < m_capacity; i++)
new(m_data+i) T(*(other.m_data[i]));
}
private:
T* m_data = nullptr;
SizeType m_capacity = 0;
SizeType m_size = 0;
template<typename U> inline
std::enable_if_t<std::is_class<U>::value, void>
FORCE_INLINE call_destructor(U& t){
t.~U();
}
template<typename U> inline
std::enable_if_t<!std::is_class<U>::value, void>
FORCE_INLINE call_destructor(U&){}
void inline FORCE_INLINE grow_capacity() { reserve((m_capacity+1) * 2); }
};
template<typename T>
typename FVector<T>::reserve_tag_t FVector<T>::reserve_tag = typename FVector<T>::reserve_tag_t{};
#endif // FVECTOR_H
| true |
b57e4ab4403f8f767a794804f9901ecc86da346b | C++ | jaykpatel1996/DailyCodes | /array/boring questions/RomanToInteger.cpp | UTF-8 | 746 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<map>
using namespace std;
//MCMIV
int RomanToInteger(string s)
{
map<char, int> m;
m['I'] = 1; m['V'] = 5;m['X'] = 10;m['L'] = 50;m['C'] = 100;m['D'] = 500;m['M'] = 1000;
int i = 0;
int res = 0;
while (s[i] != '\0')
{
int curr_val = m[s[i]];
if (i + 1 < s.length())
{
if (curr_val < m[s[i + 1]])
{
res += m[s[i + 1]] - curr_val;
i++;
}
else
{
res += curr_val;
}
}
else
{
res += curr_val;
}
i++;
}
return res;
}
int IntegerToRoman(integer N)
{
map<int, char> m;
}
int main()
{
string input;
int number;
cout << "enter the Roman String";
cin >> input;
cout << RomanToInteger(input);
cout << "Enter the integer";
cin >> number;
}
| true |
53a00e206f9edf9c5f8622384ff149f42a6508bb | C++ | MaximeRedstone/Chess | /Rook.h | UTF-8 | 515 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef ROOK_H
#define ROOK_H
#include"Piece.h"
#include"ChessBoard.h"
using namespace std;
class Rook: public Piece {
friend class ChessBoard;
private:
bool hasMoved;
Rook(bool hasMoved) : hasMoved(hasMoved) {}
/* Check valid move */
bool validMove(int fileTo, int rankTo, ChessBoard &chessboard) override;
/* Retrieve piece name */
string getName() override;
/* Update hasMoved */
void updateMoved() override;
/* Get moved status */
bool getMovedStatus() override;
};
#endif
| true |
c162a6a6d9220995a6dd1263ceca471acf491657 | C++ | newincpp/Obake | /Window/Linux/Window.cpp | UTF-8 | 3,055 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <cassert>
#include <iostream>
#include "Window.hh"
#include <Core.hh>
System::Window::Window() : _connection(nullptr), _screen(nullptr) {
OBAKE_ADD(createWindow);
OBAKE_LOOP {
OBAKE_ADD(refresh);
}
}
void System::Window::createWindow() {
if (_core) {
_core->eventsManager.bindEvent("Window Event", this, &Window::windowEvent);
_core->eventsManager.bindEvent("Create Window", this, &Window::createWindow);
_core->eventsManager.bindEvent("Get Windows Handle", this, &Window::sendWindowHandle);
}
const xcb_setup_t* setup;
xcb_screen_iterator_t iter;
int scr;
_connection = xcb_connect(NULL, &scr);
assert(_connection != NULL);
setup = xcb_get_setup(_connection);
iter = xcb_setup_roots_iterator(setup);
while (scr-- > 0)
xcb_screen_next(&iter);
_screen = iter.data;
_setupWindow();
}
void System::Window::destroyWindow() {
xcb_destroy_window(_connection, _window);
xcb_disconnect(_connection);
_connection = nullptr;
}
void System::Window::sendWindowHandle() {
}
void System::Window::windowEvent() {
}
void System::Window::_setupWindow() {
uint32_t value_list[2];
uint16_t width = 1920;
uint16_t height = 1024;
_window = xcb_generate_id(_connection);
value_list[0] = _screen->black_pixel;
value_list[1] = XCB_EVENT_MASK_KEY_PRESS |
XCB_EVENT_MASK_EXPOSURE |
XCB_EVENT_MASK_STRUCTURE_NOTIFY |
XCB_EVENT_MASK_POINTER_MOTION |
XCB_EVENT_MASK_BUTTON_PRESS |
XCB_EVENT_MASK_BUTTON_RELEASE;
xcb_create_window(_connection,
XCB_COPY_FROM_PARENT,
_window, _screen->root,
0, 0, width, height, 0, // TODO: put dynamic width and height
XCB_WINDOW_CLASS_INPUT_OUTPUT,
_screen->root_visual,
XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK, value_list);
xcb_intern_atom_cookie_t cookie = xcb_intern_atom(_connection, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(_connection, cookie, 0);
xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(_connection, 0, 16, "WM_DELETE_WINDOW");
_atom_wm_delete_window = xcb_intern_atom_reply(_connection, cookie2, 0);
xcb_change_property(_connection, XCB_PROP_MODE_REPLACE,
_window, (*reply).atom, 4, 32, 1,
&(*_atom_wm_delete_window).atom);
std::string windowTitle("test");
xcb_change_property(_connection, XCB_PROP_MODE_REPLACE,
_window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8,
windowTitle.size(), windowTitle.c_str());
free(reply);
xcb_map_window(_connection, _window);
xcb_flush(_connection);
}
void System::Window::refresh() {
_lastEvent = xcb_wait_for_event(_connection);
if (_lastEvent->response_type == XCB_EXPOSE) {
std::cout << "flush" << std::endl;
xcb_flush(_connection);
} else if (_lastEvent->response_type == XCB_BUTTON_PRESS) {
std::cout << "mouse" << std::endl;
destroyWindow();
} else if (_lastEvent->response_type == XCB_KEY_PRESS) { // "press" seems ignored while "released" seems to be called while pressed...
std::cout << "keyboard" << std::endl;
destroyWindow();
}
std::cout << "refresh" << std::endl;
if (_connection == nullptr) {
shutdown();
}
}
| true |
0a2694422def39f4134c63d782071a719c600b7e | C++ | mandliors/SpikeEngine | /Spike Engine/src/Events/EventDispatcher.cpp | UTF-8 | 438 | 2.609375 | 3 | [] | no_license | #include "EventDispatcher.h"
namespace Spike {
EventDispatcher::EventDispatcher(int eventType, void(*func)(SDL_Event& event))
{
m_EventType = eventType;
m_Function = func;
}
EventDispatcher::EventDispatcher(void(*func)(SDL_Event& event))
{
m_EventType = -1;
m_Function = func;
}
int EventDispatcher::GetEventType()
{
return m_EventType;
}
void EventDispatcher::Dispatch(SDL_Event& event)
{
m_Function(event);
}
} | true |
eb22ff5b959aa53ea50eb4349e5536e2348f7e59 | C++ | TriLoo/c_algorithm | /63GuPiaoZuiDaZhi/main.cpp | UTF-8 | 895 | 3.734375 | 4 | [] | no_license | /**
* @author smh
* @date 2018.08.24
*
* @brief 剑指offer第63题
* 股票的最大利润
*
* 思路:
* 1. 最大的利润就是最大的差值
*/
#include <iostream>
#include <vector>
using namespace std;
int getMaxProfit(vector<int> &values)
{
if (values.size() <= 1)
return 0;
int minV = values.at(0);
int currMax = values.at(1) - values.at(0);
for (int i = 2; i < values.size(); ++i)
{
if (values.at(i-1) < minV)
minV = values.at(i-1);
int currDiff = values.at(i) - minV;
if (currDiff > currMax)
currMax = currDiff;
}
return currMax;
}
int main() {
int N;
cin >> N;
vector<int> values(N, 0);
for (int i = 0; i < N; ++i) {
cin >> values.at(i);
}
if (values.size() == 0)
return 0;
cout << getMaxProfit(values) << endl;
return 0;
} | true |
d6e8c7aa38e83ae7d57c770332dce49d17e7b240 | C++ | Wizmann/ACM-ICPC | /POJ/2/2115.cc | UTF-8 | 774 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | //Result:wizmann 2115 Accepted 164K 0MS C++ 735B
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
// (A + C*x) MOD 2^D == B
long long x,y;
long long eEuclid(long long a,long long b)
{
long long ret;
if(b==0)
{
x=1;y=0;
return a;
}
else
{
ret=eEuclid(b,a%b);
long long t=x;
x=y;
y=t-a/b*y;
return ret;
}
}
long long solve(long long a,long long b,long long n)
{
long long d=eEuclid(a,n);
if(b%d!=0) return -1;
long long e=x*(b/d)%n+n;
return e%(n/d);
}
int main()
{
freopen("input.txt","r",stdin);
long long a,b,c,d;
while(1)
{
scanf("%lld%lld%lld%lld",&a,&b,&c,&d);
if(a+b+c+d==0) break;
d=(1LL<<d);
long long ans=solve(c,b-a,d);
if(ans==-1) puts("FOREVER");
else printf("%lld\n",ans);
}
return 0;
}
| true |
de09f234586589473ffba8e5fdd6d3027c552c51 | C++ | jam-xd/Competitive-Programing | /#Codeforces/900/A. Devu, the Singer and Churu, the Joker/439_A.cpp | UTF-8 | 447 | 2.78125 | 3 | [] | no_license | //http://codeforces.com/contest/439/problem/A
#include <bits/stdc++.h>
using namespace std;
int main()
{
int canciones, tiempo;
cin>>canciones>>tiempo;
deque<int>gg(canciones);
int sum = 0;
for(int i=0;i<canciones;i++){
cin>>gg[i];
sum = sum + gg[i];
}
if(sum + (canciones-1)*10 > tiempo)cout<<"-1"<<endl;
else{
int r = (tiempo - sum) / 5;
cout<<r<<endl;
}
return 0;
} | true |
91afd3f4e9fa584a8ddea8171038db14adea51c6 | C++ | promoter/shmqueue | /shmmqueue.cpp | UTF-8 | 16,823 | 2.515625 | 3 | [] | no_license | //
// messagequeue_h
//
// Created by 杜国超 on 17/6/22.
// Copyright © 2017年 杜国超. All rights reserved.
//
#include <string.h>
#include <cstdlib>
#include <stdio.h>
#include <memory>
#include <sys/shm.h>
#include "shmmqueue.h"
namespace shmmqueue
{
BYTE *CMessageQueue::m_pCurrAddr = nullptr;
CMessageQueue::CMessageQueue()
{
m_stMemTrunk = new stMemTrunk();
InitLock();
}
CMessageQueue::CMessageQueue(eQueueModel module, key_t shmid, size_t size)
{
m_stMemTrunk = new stMemTrunk();
m_stMemTrunk->m_iBegin = 0;
m_stMemTrunk->m_iEnd = 0;
m_stMemTrunk->m_iKey = shmid;
m_stMemTrunk->m_iSize = (unsigned int)size;
m_stMemTrunk->m_eQueueModule = module;
InitLock();
}
CMessageQueue::~CMessageQueue()
{
if (m_pReadLock) {
delete m_pReadLock;
m_pReadLock = nullptr;
}
if (m_pWriteLock) {
delete m_pWriteLock;
m_pWriteLock = nullptr;
}
}
int CMessageQueue::SendMessage(BYTE *message, MESS_SIZE_TYPE length)
{
if (!message || length <= 0) {
return (int) eQueueErrorCode::QUEUE_PARAM_ERROR;
}
std::shared_ptr<CSafeShmWlock> lock = nullptr;
//修改共享内存写锁
if (IsWriteLock() && m_pWriteLock) {
lock.reset(new CSafeShmWlock(m_pWriteLock));
}
// 首先判断是否队列已满
int size = GetFreeSize();
if (size <= 0) {
return (int) eQueueErrorCode::QUEUE_NO_SPACE;;
}
//空间不足
if ((length + sizeof(MESS_SIZE_TYPE)) > size) {
return (int) eQueueErrorCode::QUEUE_NO_SPACE;
}
MESS_SIZE_TYPE usInLength = length;
BYTE *pbyCodeBuf = QueueBeginAddr();
BYTE *pTempDst = &pbyCodeBuf[0];
BYTE *pTempSrc = (BYTE *) (&usInLength);
//写入的时候我们在数据头插上数据的长度,方便准确取数据
unsigned int tmpEnd = m_stMemTrunk->m_iEnd;
for (MESS_SIZE_TYPE i = 0; i < sizeof(usInLength); i++) {
pTempDst[tmpEnd] = pTempSrc[i]; // 拷贝 Code 的长度
tmpEnd = (tmpEnd + 1) % GetQueueLength(); // % 用于防止 Code 结尾的 idx 超出 codequeue
}
//空闲区在中间
if (m_stMemTrunk->m_iBegin > tmpEnd) {
memcpy((void *) &pbyCodeBuf[tmpEnd], (const void *) message, (size_t) usInLength);
}
else //空闲区在两头
{
//队列尾部剩余长度
unsigned long endLen = QueueEndAddr() - (QueueBeginAddr() + tmpEnd);
//尾部放不下需要分段拷贝的情况
if (length > endLen) {
memcpy((void *) &pbyCodeBuf[tmpEnd], (const void *) &message[0], endLen);
memcpy((void *) &pbyCodeBuf[0], (const void *) &message[endLen], (size_t) (length - endLen));
}
else {
memcpy((void *) &pbyCodeBuf[tmpEnd], (const void *) &message[0], (size_t) length);
}
}
//数据写入完成修改m_iEnd,保证读端不会读到写入一半的数据
m_stMemTrunk->m_iEnd = (tmpEnd + length) % GetQueueLength();
return (int) eQueueErrorCode::QUEUE_OK;
}
int CMessageQueue::GetMessage(BYTE *pOutCode)
{
if (!pOutCode) {
return (int) eQueueErrorCode::QUEUE_PARAM_ERROR;
}
std::shared_ptr<CSafeShmWlock> lock = nullptr;
//修改共享内存写锁
if (IsReadLock() && m_pReadLock) {
lock.reset(new CSafeShmWlock(m_pReadLock));
}
int nTempMaxLength = GetDataSize();
if (nTempMaxLength <= 0) {
return (int) eQueueErrorCode::QUEUE_NO_MESSAGE;
}
BYTE *pbyCodeBuf = QueueBeginAddr();
// 如果数据的最大长度不到2(存入数据时在数据头插入了数据的长度,长度本身)
if (nTempMaxLength <= (int) sizeof(MESS_SIZE_TYPE)) {
printf("[%s:%d] ReadHeadMessage data len illegal,nTempMaxLength %d \n", __FILE__, __LINE__, nTempMaxLength);
PrintfTrunk();
m_stMemTrunk->m_iBegin = m_stMemTrunk->m_iEnd;
return (int) eQueueErrorCode::QUEUE_DATA_SEQUENCE_ERROR;
}
MESS_SIZE_TYPE usOutLength;
BYTE *pTempDst = (BYTE *) &usOutLength; // 数据拷贝的目的地址
BYTE *pTempSrc = &pbyCodeBuf[0]; // 数据拷贝的源地址
//取出数据的长度
for (MESS_SIZE_TYPE i = 0; i < sizeof(short); i++) {
pTempDst[i] = pTempSrc[m_stMemTrunk->m_iBegin];
m_stMemTrunk->m_iBegin = (m_stMemTrunk->m_iBegin + 1) % GetQueueLength();
}
// 将数据长度回传
//取出的数据的长度实际有的数据长度,非法
if (usOutLength > (int) (nTempMaxLength - sizeof(MESS_SIZE_TYPE)) || usOutLength < 0) {
printf("[%s:%d] ReadHeadMessage usOutLength illegal,usOutLength: %d,nTempMaxLength %d \n",
__FILE__, __LINE__, usOutLength, nTempMaxLength);
PrintfTrunk();
m_stMemTrunk->m_iBegin = m_stMemTrunk->m_iEnd;
return (int) eQueueErrorCode::QUEUE_DATA_SEQUENCE_ERROR;
}
pTempDst = &pOutCode[0]; // 设置接收 Code 的地址
// 数据在中间
if (m_stMemTrunk->m_iBegin < m_stMemTrunk->m_iEnd) {
memcpy((void *) pTempDst, (const void *) &pTempSrc[m_stMemTrunk->m_iBegin], (size_t) (usOutLength));
}
else {
//尾部数据长度
unsigned long endLen = QueueEndAddr() - MessageBeginAddr();
//次数据包分布在队列的两端
if (endLen < usOutLength) {
memcpy((void *) pTempDst, (const void *) &pTempSrc[m_stMemTrunk->m_iBegin], (size_t) endLen);
pTempDst += endLen;
memcpy((void *) pTempDst, (const void *) &pTempSrc[0], (size_t) (usOutLength - endLen));
}
else // 否则,直接拷贝
{
memcpy((void *) pTempDst, (const void *) &pTempSrc[m_stMemTrunk->m_iBegin], (size_t) (usOutLength));
}
}
m_stMemTrunk->m_iBegin = (m_stMemTrunk->m_iBegin + usOutLength) % GetQueueLength();
return usOutLength;
}
/**
*函数名 : PeekHeadCode
*功能描述 : 查看共享内存管道(不改变读写索引)
* Error code: -1 invalid para; -2 not enough; -3 data crashed
**/
int CMessageQueue::ReadHeadMessage(BYTE *pOutCode)
{
if (!pOutCode) {
return (int) eQueueErrorCode::QUEUE_PARAM_ERROR;
}
std::shared_ptr<CSafeShmRlock> lock = nullptr;
//修改共享内存写锁
if (IsReadLock() && m_pReadLock) {
lock.reset(new CSafeShmRlock(m_pReadLock));
}
int nTempMaxLength = GetDataSize();
if (nTempMaxLength <= 0) {
return (int) eQueueErrorCode::QUEUE_NO_MESSAGE;
}
BYTE *pbyCodeBuf = QueueBeginAddr();
// 如果数据的最大长度不到2(存入数据时在数据头插入了数据的长度,长度本身)
if (nTempMaxLength < (int) sizeof(MESS_SIZE_TYPE)) {
printf("[%s:%d] ReadHeadMessage data len illegal,nTempMaxLength %d \n", __FILE__, __LINE__, nTempMaxLength);
return (int) eQueueErrorCode::QUEUE_DATA_SEQUENCE_ERROR;
}
MESS_SIZE_TYPE usOutLength;
BYTE *pTempDst = (BYTE *) &usOutLength; // 数据拷贝的目的地址
BYTE *pTempSrc = &pbyCodeBuf[0]; // 数据拷贝的源地址
//取出数据的长度
unsigned int tmpBegin = m_stMemTrunk->m_iBegin;
for (MESS_SIZE_TYPE i = 0; i < sizeof(short); i++) {
pTempDst[i] = pTempSrc[tmpBegin];
tmpBegin = (tmpBegin + 1) % GetQueueLength();
}
// 将数据长度回传
//取出的数据的长度实际有的数据长度,非法
if (usOutLength > (int) (nTempMaxLength - sizeof(MESS_SIZE_TYPE)) || usOutLength < 0) {
printf("[%s:%d] ReadHeadMessage usOutLength illegal,usOutLength: %d,nTempMaxLength %d \n",
__FILE__, __LINE__, usOutLength, nTempMaxLength);
PrintfTrunk();
return (int) eQueueErrorCode::QUEUE_DATA_SEQUENCE_ERROR;
}
pTempDst = &pOutCode[0]; // 设置接收 Code 的地址
// 数据在中间
if (tmpBegin < m_stMemTrunk->m_iEnd) {
memcpy((void *) pTempDst, (const void *) &pTempSrc[tmpBegin], (size_t) (usOutLength));
}
else {
//尾部数据长度
unsigned long endLen = QueueEndAddr() - MessageBeginAddr();
//次数据包分布在队列的两端
if (endLen < usOutLength) {
memcpy((void *) pTempDst, (const void *) &pTempSrc[tmpBegin], (size_t) endLen);
pTempDst += endLen;
memcpy((void *) pTempDst, (const void *) &pTempSrc[0], (size_t) (usOutLength - endLen));
}
else // 否则,直接拷贝
{
memcpy((void *) pTempDst, (const void *) &pTempSrc[tmpBegin], (size_t) (usOutLength));
}
}
return usOutLength;
}
/**
*函数名 : GetOneCode
*功能描述 : 从指定位置iCodeOffset获取指定长度nCodeLength数据
* */
int CMessageQueue::DeleteHeadMessage()
{
std::shared_ptr<CSafeShmWlock> lock = nullptr;
//修改共享内存写锁
if (IsReadLock() && m_pReadLock) {
lock.reset(new CSafeShmWlock(m_pReadLock));
}
int nTempMaxLength = GetDataSize();
if (nTempMaxLength <= 0) {
return (int) eQueueErrorCode::QUEUE_NO_MESSAGE;
}
BYTE *pbyCodeBuf = QueueBeginAddr();
// 如果数据的最大长度不到2(存入数据时在数据头插入了数据的长度,长度本身)
if (nTempMaxLength < (int) sizeof(MESS_SIZE_TYPE)) {
printf("[%s:%d] ReadHeadMessage data len illegal,nTempMaxLength %d \n", __FILE__, __LINE__, nTempMaxLength);
PrintfTrunk();
return (int) eQueueErrorCode::QUEUE_DATA_SEQUENCE_ERROR;
}
MESS_SIZE_TYPE usOutLength;
BYTE *pTempDst = (BYTE *) &usOutLength; // 数据拷贝的目的地址
BYTE *pTempSrc = &pbyCodeBuf[0]; // 数据拷贝的源地址
//取出数据的长度
for (MESS_SIZE_TYPE i = 0; i < sizeof(short); i++) {
pTempDst[i] = pTempSrc[m_stMemTrunk->m_iBegin];
m_stMemTrunk->m_iBegin = (m_stMemTrunk->m_iBegin + 1) % GetQueueLength();
}
// 将数据长度回传
//数据的长度非法
if (usOutLength > (int) (nTempMaxLength - sizeof(MESS_SIZE_TYPE)) || usOutLength < 0) {
m_stMemTrunk->m_iBegin = m_stMemTrunk->m_iEnd;
return (int) eQueueErrorCode::QUEUE_DATA_SEQUENCE_ERROR;
}
m_stMemTrunk->m_iBegin = (m_stMemTrunk->m_iBegin + usOutLength) % GetQueueLength();
return usOutLength;
}
void CMessageQueue::PrintfTrunk()
{
printf("Mem trunk address 0x%p,key %d , size %d, begin %d, end %d, queue module %d \n",
m_stMemTrunk,
m_stMemTrunk->m_iKey,
m_stMemTrunk->m_iSize,
m_stMemTrunk->m_iBegin,
m_stMemTrunk->m_iEnd,
m_stMemTrunk->m_eQueueModule);
}
BYTE *CMessageQueue::QueueBeginAddr()
{
return m_pCurrAddr + sizeof(stMemTrunk);
}
BYTE *CMessageQueue::QueueEndAddr()
{
return m_pCurrAddr + m_stMemTrunk->m_iSize;
}
BYTE *CMessageQueue::MessageBeginAddr()
{
return QueueBeginAddr() + m_stMemTrunk->m_iBegin;
}
BYTE *CMessageQueue::MessageEndAddr()
{
return QueueBeginAddr() + m_stMemTrunk->m_iEnd;
}
//获取空闲区大小
unsigned int CMessageQueue::GetFreeSize()
{
//长度应该减去预留部分长度8,保证首尾不会相接
return GetQueueLength() - GetDataSize() - EXTRA_BYTE;
}
//获取数据长度
unsigned int CMessageQueue::GetDataSize()
{
//第一次写数据前
if (m_stMemTrunk->m_iBegin == m_stMemTrunk->m_iEnd) {
return 0;
}
//数据在两头
else if (m_stMemTrunk->m_iBegin > m_stMemTrunk->m_iEnd) {
return (unsigned int)(m_stMemTrunk->m_iEnd + (QueueEndAddr() - MessageBeginAddr()));
}
else //数据在中间
{
return m_stMemTrunk->m_iEnd - m_stMemTrunk->m_iBegin;
}
}
unsigned int CMessageQueue::GetQueueLength()
{
return (unsigned int) (m_stMemTrunk->m_iSize - sizeof(stMemTrunk));
}
void CMessageQueue::InitLock()
{
if (IsReadLock()) {
m_pReadLock = new CShmRWlock((key_t) (m_stMemTrunk->m_iKey + 1));
}
if (IsWriteLock()) {
m_pWriteLock = new CShmRWlock((key_t) (m_stMemTrunk->m_iKey + 2));
}
}
bool CMessageQueue::IsReadLock()
{
return (m_stMemTrunk->m_eQueueModule == eQueueModel::MUL_READ_MUL_WRITE ||
m_stMemTrunk->m_eQueueModule == eQueueModel::MUL_READ_ONE_WRITE);
}
bool CMessageQueue::IsWriteLock()
{
return (m_stMemTrunk->m_eQueueModule == eQueueModel::MUL_READ_MUL_WRITE ||
m_stMemTrunk->m_eQueueModule == eQueueModel::ONE_READ_MUL_WRITE);
}
/**
*函数名 : CreateShareMem
*功能描述 : 创建共享内存块
*参数 : iKey:共享内存块唯一标识key vSize:大小
*返回值 : 共享内存块地址
**/
BYTE *CMessageQueue::CreateShareMem(key_t iKey, long vSize, enShmModule &shmModule, int &shmId)
{
size_t iTempShmSize;
if (iKey < 0) {
printf("[%s:%d] CreateShareMem failed. errno:%s \n", __FILE__, __LINE__, strerror(errno));
exit(-1);
}
iTempShmSize = (size_t) vSize;
//iTempShmSize += sizeof(CSharedMem);
printf("Try to malloc share memory of %d bytes... \n", iTempShmSize);
shmId = shmget(iKey, iTempShmSize, IPC_CREAT | IPC_EXCL | 0666);
if (shmId < 0) {
if (errno != EEXIST) {
printf("[%s:%d] Alloc share memory failed, iKey:%d , size:%d , error:%s \n",
__FILE__, __LINE__, iKey, iTempShmSize, strerror(errno));
exit(-1);
}
printf("Same shm seg (key= %d ) exist, now try to attach it... \n", iKey);
shmId = shmget(iKey, iTempShmSize, 0666);
if (shmId < 0) {
printf("Attach to share memory %d failed, %s . Now try to touch it \n", shmId, strerror(errno));
shmId = shmget(iKey, 0, 0666);
if (shmId < 0) {
printf("[%s:%d] Fatel error, touch to shm failed, %s.\n", __FILE__, __LINE__, strerror(errno));
exit(-1);
}
else {
printf("First remove the exist share memory %d \n", shmId);
if (shmctl(shmId, IPC_RMID, NULL)) {
printf("[%s:%d] Remove share memory failed, %s \n", __FILE__, __LINE__, strerror(errno));
exit(-1);
}
shmId = shmget(iKey, iTempShmSize, IPC_CREAT | IPC_EXCL | 0666);
if (shmId < 0) {
printf("[%s:%d] Fatal error, alloc share memory failed, %s \n",
__FILE__, __LINE__, strerror(errno));
exit(-1);
}
}
}
else {
shmModule = enShmModule::SHM_RESUME;
printf("Attach to share memory succeed.\n");
}
}
else {
shmModule = enShmModule::SHM_INIT;
}
printf("Successfully alloced share memory block, (key=%d), id = %d, size = %d \n", iKey, shmId, iTempShmSize);
BYTE *tpShm = (BYTE *) shmat(shmId, NULL, 0);
if ((void *) -1 == tpShm) {
printf("[%s:%d] create share memory failed, shmat failed, iShmId = %d, error = %s. \n",
__FILE__, __LINE__, shmId, strerror(errno));
exit(0);
}
return tpShm;
}
/************************************************
函数名 : DestroyShareMem
功能描述 : 销毁共享内存块
参数 : iKey:共享内存块唯一标识key
返回值 : 成功0 错误:错误码
************************************************/
int CMessageQueue::DestroyShareMem(key_t iKey)
{
int iShmID;
if (iKey < 0) {
printf("[%s:%d] Error in ftok, %s. \n", __FILE__, __LINE__, strerror(errno));
return -1;
}
printf("Touch to share memory key = %d... \n", iKey);
iShmID = shmget(iKey, 0, 0666);
if (iShmID < 0) {
printf("[%s:%d] Error, touch to shm failed, %s \n", __FILE__, __LINE__, strerror(errno));
return -1;
}
else {
printf("Now remove the exist share memory %d \n", iShmID);
if (shmctl(iShmID, IPC_RMID, NULL)) {
printf("[%s:%d] Remove share memory failed, %s \n", __FILE__, __LINE__, strerror(errno));
return -1;
}
printf("Remove shared memory(id = %d, key = %d) succeed. \n", iShmID, iKey);
}
return 0;
}
CMessageQueue *CMessageQueue::CreateInstance(key_t shmkey,
size_t queuesize,
eQueueModel queueModule)
{
enShmModule shmModule;
int shmId = 0;
CMessageQueue::m_pCurrAddr = CMessageQueue::CreateShareMem(shmkey, queuesize, shmModule, shmId);
CMessageQueue *messageQueue;
if (shmModule == enShmModule::SHM_INIT) {
messageQueue = new CMessageQueue(queueModule, shmId, queuesize);
}
else {
messageQueue = new CMessageQueue();
}
messageQueue->PrintfTrunk();
return messageQueue;
}
}
| true |
16f6be3d281dc82f3f798509e957f30c224163dc | C++ | nikhilponnuru/Justcodeit | /DFS.cpp | UTF-8 | 1,300 | 3.484375 | 3 | [] | no_license | //As adjaceny list model is being used I am using list library here
#include<iostream>
#include<list>
using namespace std;
class graph //also structures can be used
{
private:
int size; //to declare number of vertices of graph
list<int> *pointer;
public:
graph(int size);
void dfs_start(int start_vertice,int visited[]);
void graph_addEdge(int u,int v);
};
graph::graph(int size)
{
this->size=size;
pointer=new list<int>[size];
}
void graph::graph_addEdge(int u,int v)
{
pointer[u].push_back(v);
}
void dfs_start(int start_vertice,int visited[])
{
visited[start_vertice]=1;
cout<<start_vertice;
list<int>:: iterator it;
for(it=pointer[start_vertice].begin();it!=pointer.end();it++)
{
if(!visited[*it])
dfs_start(*it,visited);
}
}
int main()
{
int i,size_,start;
cout<<"Enter number of graph nodes";
cin>>size_;
graph(size_);
int *visited = new int[size_];
//statically I am adding Edges but can be easily done also at runtime
graph g(size_);
g.graph_addEdge(0,1);
g.graph_addEdge(3,2);
g.graph_addEdge(2,2);
g.graph_addEdge(3,0);
g.graph_addEdge(3,3);
g.graph_addEdge(1,3);
cout<<"Enter start point";
cin>>start;
for(i=0;i<size_;i++)
visited[i]=0;
dfs_start(start,visited);
return 0;
}
| true |
fa8290786506dd5641bfe0cd60ce0bed64d1a559 | C++ | utsavdubey724/Competitive-programming | /Leetcode/C++/Easy/isUgly.cpp | UTF-8 | 1,075 | 3.6875 | 4 | [] | no_license | /*
Problem: 263. Ugly Number
Date: August 02, 2021
Author: Utsav Dubey, utsav_201700433@smit.smu.edu.in
Difficulty: Easy
Source: https://leetcode.com/problems/ugly-number/
Question:
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
Example 1:
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: n = 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.
Example 4:
Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
-2^31 <= n <= 2^31 - 1
*/
class Solution {
public:
bool isUgly(int n) {
if(n==0)
return false;
bool flag=false;
while(n%2==0){
n/=2;
}
while(n%3==0){
n/=3;
}
while(n%5==0){
n/=5;
}
if(n==1)
return true;
return false;
}
};
| true |
82dbb6d1a3ddf23c0b50e99e4ec8b461be13fe4c | C++ | Pedro-Appel/Organizador-de-Tabelas | /TadPilha.cpp | UTF-8 | 1,018 | 2.71875 | 3 | [] | no_license |
#include <iostream>
#include "TadPilha.h"
TadPilha::TadPilha() {
this->topo = NULL;
this->Ftopo = NULL;
}
bool TadPilha::vazia() {
return this->topo == NULL;
}
bool TadPilha::Fvazia() {
return this->Ftopo == NULL;
}
void TadPilha::push(NoAbb * noAbb) {
NoPilha * no = new NoPilha(noAbb);
if (!this->vazia()) {
no->setProx(this->topo);
}
this->topo = no;
}
void TadPilha::Fpush(FinAbb * finAbb) {
FinPilha * no = new FinPilha(finAbb);
if (!this->Fvazia()) {
no->setFProx(this->Ftopo);
}
this->Ftopo = no;
}
NoPilha * TadPilha::pop() {
if (vazia()) {
return NULL;
}
NoPilha * noRetorno = this->topo;
this->topo = noRetorno->getProx();
return noRetorno;
}
FinPilha * TadPilha::Fpop() {
if (Fvazia()) {
return NULL;
}
FinPilha * noFetorno = this->Ftopo;
this->Ftopo = noFetorno->getFProx();
return noFetorno;
}
NoPilha * TadPilha::gettopo(){
return this->topo;
}
FinPilha * TadPilha::Fgettopo(){
return this->Ftopo;
}
| true |
7649d1d5986b7df8f453fe65a5a603c0a4ffd0b2 | C++ | Dolphiniac/Vulkan | /Engine/Code/Engine/Network/NetPacket.cpp | UTF-8 | 2,168 | 2.84375 | 3 | [] | no_license | #include "Engine/Network/NetPacket.hpp"
#include "Engine/Core/ErrorWarningAssert.hpp"
#include "Engine/Math/MathUtils.hpp"
//-----------------------------------------------------------------------------------------------
bool NetPacket::WriteContents(const NetMessage& msg)
{
MessageHeader msgHeader;
msgHeader.flags = msg.GetFlags();
msgHeader.type = msg.GetMessageType();
uint16_t payloadSize = msg.GetSize();
msgHeader.messageSize = sizeof(MessageHeader) + payloadSize;
msgHeader.reliableID = msg.GetReliableID();
msgHeader.sequenceID = msg.GetSequenceID();
if (GetWritableBytes() < msgHeader.messageSize)
{
return false;
}
Write<MessageHeader>(msgHeader);
//Messages should already be in correct byte order, so write them forward
BytePacker::WriteForward(msg.GetContents(), (void**)&m_currPtr, payloadSize);
//Increase message count by one
PacketHeader* header = (PacketHeader*)m_buffer;
header->messageCount++;
return true;
}
//-----------------------------------------------------------------------------------------------
void NetPacket::ReadContents(byte* outBuffer, uint16_t messageSize)
{
BytePacker::ReadForward(outBuffer, (void**)&m_currPtr, messageSize);
m_remainingMessages--;
}
//-----------------------------------------------------------------------------------------------
uint16_t NetPacket::Advance(int numBytes)
{
numBytes = Clampi(numBytes, 0, GetWritableBytes());
m_currPtr += numBytes;
return (uint16_t)numBytes;
}
//-----------------------------------------------------------------------------------------------
void NetPacket::Initialize(int bufferSize)
{
PacketHeader* header = ReadPacketHeaderAndAdvance();
byte numMessages = header->messageCount;
int packetSize = sizeof(PacketHeader);
for (int i = 0; i < numMessages; i++)
{
MessageHeader* msgHeader = ReadMessageHeaderAndAdvance();
packetSize += msgHeader->messageSize;
Advance(msgHeader->messageSize - sizeof(MessageHeader));
}
ASSERT_OR_DIE(bufferSize == packetSize, "Packet corrupted. Buffer size does not match packet read size");
//Rewind read
m_currPtr = m_buffer + sizeof(PacketHeader);
m_remainingMessages = numMessages;
} | true |
14b365fbb703042f2b23d8b106419e4ea110299e | C++ | RishabD/GraphTheory | /graph_theory.cpp | UTF-8 | 3,479 | 3.859375 | 4 | [] | no_license | /*
Shortest path v2.0
Code below finds shortest path.
The one I made doesn't need to traverse through all paths. I used semi-aysncronous code to find the path by effectively searching through all paths at the same time.
The first one that finishes is shortest path.
Code can be easily modified to find all paths in increasing order of path length
I didn't use arrays for a lot of the components due to time complexity and also simplicity
*/
#include <iostream>
#include <vector>
#include <map>
std::vector<int> tasks;//Tasks is only used to execute tasks at front and place tasks at end. Arrays would be far slower since items would constantly need to be shifted
std::vector<int> solution;//Solution is only used to add numbers to end of vector. Arrays could be used but would comlicate code
std::map<int, bool> vals_done;//Map is used to check if value has been traversed or not. Time complexity of searching in map vs array is much better.
class graph
{
public:
int highest_vertex_number;
int adj_list[100][100]; //Almost all data is constantly being accessed, so array is best due to low latency.
//Sets adj graph to all 0's
void reset_graph()
{
for (int i = 1; i <= highest_vertex_number;i++)
{
for (int j = 1; j <= highest_vertex_number;j++)
{
adj_list[i][j] = 0;
}
std::cout << std::endl;
}
std::cout << std::endl << std::endl;
}
//Prints out adj graph
void print_graph()
{
for (int i = 1; i <= highest_vertex_number;i++)
{
for (int j = 1; j <= highest_vertex_number;j++)
{
std::cout << adj_list[i][j];
}
std::cout << std::endl;
}
std::cout << std::endl << std::endl;
}
//1 means adjacent, 0 means not adjacent
void add_edge(int i, int j)
{
adj_list[i][j] = 1;
adj_list[j][i] = 1;
}
void del_edge(int i, int j)
{
adj_list[i][j] = 0;
adj_list[j][i] = 0;
}
//Task manager. Continously completes functions in task list until empty
void iterate()
{
while (!tasks.empty())
{
tasks[0];
tasks.erase(tasks.begin());
vals_done.clear();//Resets code to be used again
}
}
//Function called in main which then sets some prerequesites and triggers _short_path
void short_path(int v1, int v2)
{
std::vector<int> path = { v1 };
vals_done[2] = 1;
tasks.push_back(_short_path(v1, v2, path));
solution.empty();
iterate();
}
//Finds shortest path and stores in vector solution
int _short_path(int v1, int v2, std::vector<int> path)
{
//Saves path in solution if it hs reached end. Clears tasks as well (This part can be modified to save more paths that lead to the end vertex)
if (adj_list[v1][v2] == 1)
{
solution = path;
solution.push_back(v2);
tasks.clear();
}
//Checks for possible path branches and creates a new instance of _short_path to explore said branches
else
{
for (int i = 1; i <= highest_vertex_number; i++)
{
if (adj_list[i][v2] == 1 && !vals_done[i] && i != v1)
{
vals_done[i] = 1;
std::vector<int> new_path = path;
new_path.push_back(i);
tasks.push_back(_short_path(i, v2, new_path));
}
}
}
//Required, but I don't use.
return(0);
}
};
//Test code
int main()
{
graph data1;
data1.highest_vertex_number = 9;
data1.reset_graph();
data1.add_edge(2, 3);
data1.add_edge(3, 4);
data1.add_edge(4, 5);
data1.add_edge(2, 6);
data1.add_edge(6, 5);
data1.add_edge(2, 1);
data1.short_path(2, 5);
for (int i = 0; i < solution.size(); i++)
std::cout << solution[i] << ' ';
return(0);
}
| true |
ca11224a46244d8a315ab40400eea1593ee92d5c | C++ | bendem/SchoolCars | /src/utils/TermUtils.cpp | UTF-8 | 3,151 | 2.78125 | 3 | [] | no_license | #include "utils/TermUtils.hpp"
const String TermUtils::ESCAPE_SEQUENCE = "\033[";
void TermUtils::setEchoInput(bool echo) {
// Get current settings
termios settings;
tcgetattr(STDIN_FILENO, &settings);
// Change ICANON flag
if (echo) {
settings.c_lflag |= ECHO;
} else {
settings.c_lflag &= ~(ECHO);
}
// Apply new settings
tcsetattr(STDIN_FILENO, TCSANOW, &settings);
}
void TermUtils::setRawInput(bool isRaw) {
// Get current settings
termios settings;
tcgetattr(STDIN_FILENO, &settings);
// Change ICANON flag
if (isRaw) {
settings.c_lflag &= ~(ICANON);
settings.c_lflag &= ~(ECHO);
} else {
settings.c_lflag |= ICANON;
settings.c_lflag |= ECHO;
}
// Apply new settings
tcsetattr(STDIN_FILENO, TCSANOW, &settings);
}
// Manipulators without args
ostream& saveCursorPosition(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << 's'; }
ostream& restoreCursorPosition(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << 'u'; }
ostream& clear(ostream& os) { return os << ClearManip(true); }
ostream& cursorUp(ostream& os) { return os << CursorMoveManip(1, 'A'); }
ostream& cursorDown(ostream& os) { return os << CursorMoveManip(1, 'B'); }
ostream& cursorLeft(ostream& os) { return os << CursorMoveManip(1, 'D'); }
ostream& cursorRight(ostream& os) { return os << CursorMoveManip(1, 'C'); }
ostream& black(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "30m"; }
ostream& red(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "31m"; }
ostream& green(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "32m"; }
ostream& yellow(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "33m"; }
ostream& blue(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "34m"; }
ostream& magenta(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "35m"; }
ostream& cyan(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "36m"; }
ostream& white(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "37m"; }
ostream& reset(ostream& os) { return os << TermUtils::ESCAPE_SEQUENCE << "0m"; }
ostream& operator<<(ostream& os, const ClearManip& m) {
os << TermUtils::ESCAPE_SEQUENCE << 2 << 'J';
if(m.resetPosition) {
os << cursorPosition(1, 1);
}
return os;
}
ClearManip clear(bool resetPos) { return ClearManip(resetPos); }
ostream& operator<<(ostream& os, const CursorMoveManip& m) {
return os << TermUtils::ESCAPE_SEQUENCE << m.nb << m.c;
}
CursorMoveManip cursorUp(unsigned int nb = 1) { return CursorMoveManip(nb, 'A'); }
CursorMoveManip cursorDown(unsigned int nb = 1) { return CursorMoveManip(nb, 'B'); }
CursorMoveManip cursorLeft(unsigned int nb = 1) { return CursorMoveManip(nb, 'D'); }
CursorMoveManip cursorRight(unsigned int nb = 1) { return CursorMoveManip(nb, 'C'); }
ostream& operator<<(ostream& os, const CursorSetPosManip& m) {
return os << TermUtils::ESCAPE_SEQUENCE << m.y << ';' << m.x << 'H';
}
CursorSetPosManip cursorPosition(unsigned int x, unsigned int y) { return CursorSetPosManip(x, y); }
| true |
ec719907544f18863582f3db3c776da54c84b85b | C++ | laviniameds/CP | /studying/tree_heap_hash/UVa-11849/11849.cpp | UTF-8 | 542 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <set>
using namespace std;
int main(){
set<int> cds_jack;
int qtd_jack, qtd_jill, cd, count = 0;
while(cin >> qtd_jack >> qtd_jill, qtd_jack && qtd_jill){
while(qtd_jack--){
cin >> cd;
cds_jack.insert(cd);
}
while(qtd_jill--){
cin >> cd;
if(cds_jack.find(cd) != cds_jack.end())
count++;
}
cout << count << "\n";
count = 0;
cds_jack.clear();
}
return 0;
}
| true |
66b178516d8a58b8dbd0422b2ee480412b51be74 | C++ | lucaslongaray/simuladores-netuno | /gpu_sonar_simulation/include/vizkit3d_normal_depth_map/test/Material_test.cpp | UTF-8 | 5,374 | 2.546875 | 3 | [] | no_license | #define BOOST_TEST_MODULE "Material_test"
#include <boost/test/unit_test.hpp>
// OpenSceneGraph includes
#include <osg/AlphaFunc>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Image>
#include <osg/ShapeDrawable>
#include <osg/StateSet>
#include <osgViewer/Viewer>
// Rock includes
#include <normal_depth_map/NormalDepthMap.hpp>
#include <normal_depth_map/ImageViewerCaptureTool.hpp>
// OpenCV includes
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/contrib/contrib.hpp>
// C++ includes
#include <iostream>
using namespace normal_depth_map;
BOOST_AUTO_TEST_SUITE(MaterialProperties)
// check if two matrixes are equals
bool are_equals (const cv::Mat& image1, const cv::Mat& image2) {
cv::Mat diff = image1 != image2;
return (cv::countNonZero(diff) == 0);
}
// insert a sphere in the scene with desired position, radius and reflectance properties
void addSimpleObject(osg::ref_ptr<osg::Group> root, osg::Vec3 position, float radius, float reflectance) {
// create the drawable
osg::ref_ptr<osg::Drawable> drawable = new osg::ShapeDrawable(new osg::Sphere(position, radius));
// create the stateset and add the uniform
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet();
stateset->addUniform(new osg::Uniform("reflectance", reflectance));
// add the stateset to the drawable
drawable->setStateSet(stateset);
if(!root->getNumChildren()) {
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
root->addChild(geode);
}
root->getChild(0)->asGeode()->addDrawable(drawable);
}
// compute the normal depth map for a osg scene
cv::Mat computeNormalDepthMap(osg::ref_ptr<osg::Group> root, float maxRange, float fovX, float fovY) {
uint height = 500;
// normal depth map
NormalDepthMap normalDepthMap(maxRange, fovX * 0.5, fovY * 0.5);
ImageViewerCaptureTool capture(fovY, fovX, height);
capture.setBackgroundColor(osg::Vec4d(0, 0, 0, 0));
normalDepthMap.addNodeChild(root);
// grab scene
osg::ref_ptr<osg::Image> osgImage = capture.grabImage(normalDepthMap.getNormalDepthMapNode());
osg::ref_ptr<osg::Image> osgDepth = capture.getDepthBuffer();
cv::Mat cvImage = cv::Mat(osgImage->t(), osgImage->s(), CV_32FC3, osgImage->data());
cv::Mat cvDepth = cv::Mat(osgDepth->t(), osgDepth->s(), CV_32FC1, osgDepth->data());
cvDepth = cvDepth.mul( cv::Mat1f(cvDepth < 1) / 255);
std::vector<cv::Mat> channels;
cv::split(cvImage, channels);
channels[1] = cvDepth;
cv::merge(channels, cvImage);
cv::cvtColor(cvImage, cvImage, cv::COLOR_RGB2BGR);
cv::flip(cvImage, cvImage, 0);
return cvImage.clone();
}
BOOST_AUTO_TEST_CASE(differentMaterials_testCase) {
float maxRange = 20.0f;
float fovX = M_PI / 3; // 60 degrees
float fovY = M_PI / 3; // 60 degrees
float radius = 5;
osg::Vec3 position(0, 0, -14);
// create the scenes
osg::ref_ptr<osg::Group> root1 = new osg::Group();
addSimpleObject(root1, position, radius, 1.0);
cv::Mat scene1 = computeNormalDepthMap(root1, maxRange, fovX, fovY);
osg::ref_ptr<osg::Group> root2 = new osg::Group();
addSimpleObject(root2, position, radius, 0.35);
cv::Mat scene2 = computeNormalDepthMap(root2, maxRange, fovX, fovY);
osg::ref_ptr<osg::Group> root3 = new osg::Group();
addSimpleObject(root3, position, radius, 1.40);
cv::Mat scene3 = computeNormalDepthMap(root3, maxRange, fovX, fovY);
osg::ref_ptr<osg::Group> root4 = new osg::Group();
addSimpleObject(root4, position, radius, 2.12);
cv::Mat scene4 = computeNormalDepthMap(root4, maxRange, fovX, fovY);
std::vector<cv::Mat> channels1, channels2, channels3, channels4;
cv::split(scene1, channels1);
cv::split(scene2, channels2);
cv::split(scene3, channels3);
cv::split(scene4, channels4);
// assert that normal matrixes are differents
BOOST_CHECK(are_equals(channels1[0], channels2[0]) == false);
BOOST_CHECK(are_equals(channels1[0], channels3[0]) == false);
BOOST_CHECK(are_equals(channels1[0], channels4[0]) == false);
BOOST_CHECK(are_equals(channels2[0], channels3[0]) == false);
BOOST_CHECK(are_equals(channels2[0], channels4[0]) == false);
BOOST_CHECK(are_equals(channels3[0], channels4[0]) == false);
// output
cv::Mat output1, output2, output;
cv::hconcat(scene1, scene2, output1);
cv::hconcat(scene3, scene4, output2);
cv::vconcat(output1, output2, output);
cv::resize(output, output, cv::Size(output.rows / 2, output.cols / 2));
cv::imshow("singleobject material test", output);
cv::waitKey();
}
BOOST_AUTO_TEST_CASE(objectsDifferentMaterials_testCase) {
float maxRange = 20.0f;
float fovX = M_PI / 3; // 60 degrees
float fovY = M_PI / 3; // 60 degrees
// create the scene
osg::ref_ptr<osg::Group> root = new osg::Group();
addSimpleObject(root, osg::Vec3(-3.0, 2.5, -10), 2, 0.5);
addSimpleObject(root, osg::Vec3( 0.0, -2.5, -10), 2, 1.0);
addSimpleObject(root, osg::Vec3( 3.0, 2.5, -10), 2, 1.5);
// normal depth map
cv::Mat scene = computeNormalDepthMap(root, maxRange, fovX, fovY);
// output
cv::imshow("multiobject material test", scene);
cv::waitKey();
}
BOOST_AUTO_TEST_SUITE_END()
| true |
714f2b6e53f0c78b405436d7a42c9fd70f8dcaae | C++ | Annushka34/c-Examples | /32стаціонар/08_List/08_List/QueueRing.cpp | WINDOWS-1251 | 1,610 | 3.640625 | 4 | [] | no_license | //#include<iostream>
//using namespace std;
//
//
//class MyQueue
//{
//private:
// struct Node
// {
// int val;
// Node* next;
// };
// // -
// Node * pHead;
// Node * pTail;
// int size;
//
//public:
// MyQueue()
// {
// pHead = nullptr;
// pTail = nullptr;
// size = 0;
// }
// bool Pop(int &val)
// {
// if (size == 0) return false;
// Node* pDel = pHead;
// val = pDel->val;
// if (size > 1)
// {
// pHead = pHead->next;
// }
// Push(pDel->val);
// delete pDel;
// size--;
// return true;
// }
// bool Push(int val)
// {
// Node * pNew = new Node();
// pNew->next = nullptr;
// pNew->val = val;
// size++;
// if (!pHead)
// {
// pHead = pNew;
// pTail = pNew;
// pTail->next = nullptr;
// return true;
// }
// pTail->next = pNew;
// pTail = pNew;
// return true;
// }
// bool Clear()
// {
// if (size == 0) return false;
// Node*pDel = pHead;
// while (pHead != nullptr)
// {
// pDel = pHead;
// pHead = pHead->next;
// delete pDel;
// size--;
// }
// }
// bool Show()
// {
// cout << "\n--------------SHOW----------\n";
// if (size == 0) return false;
// Node*pCur = pHead;
// while (pCur != nullptr)
// {
// cout << pCur->val << " ";
// pCur = pCur->next;
// }
// cout << endl;
// }
//};
//
//void main()
//{
// MyQueue q;
// q.Push(11);
// q.Push(3);
// q.Push(2);
// q.Push(8);
// //q.Clear();
// q.Show();
// int val;
// q.Pop(val);
//
// q.Show();
//
// for (size_t i = 0; i < 7; i++)
// {
// if ( q.Pop(val) )
// cout << val << " ";
// else cout << "empty ";
// }
// cout << endl;
//} | true |
4bedb1c96fb48975d1354d333161485678d2dddc | C++ | georgerapeanu/c-sources | /Siruri 2/main.cpp | UTF-8 | 1,080 | 2.546875 | 3 | [] | no_license | #include <iostream>
using namespace std;
long long S[1805][605];
long long N,M,K;
long long adun(long long a,long long b){
a += b;
if(a >= M){
a -= M;
}
return a;
}
long long mult(long long a,long long b){
long long rez = 0;
while(b){
if(b & 1){
rez = adun(rez,a);
}
b >>= 1;
a = adun(a,a);
}
return rez;
}
int main() {
cin >> N >> K >> M;
for(int i = 1;i <= 3 * K;i++){
for(int j = 1;j <= i;j++){
S[i][j] = mult(i,adun(S[i - 1][j - 1],1));
}
}
if(3 * K <= N){
long long rez = 0;
long long a = N + 3 * K + 1;
long long b = N - 3 * K;
if(b % 2 == 0){
b /= 2;
}
else{
a /= 2;
}
rez = mult(a,b);
for(int i = 1;i <= 3 * K;i++){
rez = adun(rez,S[i][min(i * 1LL,K)]);
}
cout << rez;
}
else{
long long rez = 0;
for(int i = 1;i <= N;i++){
rez = adun(rez,S[i][min(i * 1LL,K)]);
}
cout << rez;
}
return 0;
}
| true |
91044b49232196357526f8930076c4ddcb3f5a26 | C++ | xiao9616/dataStruct | /List/cpp/DoubleList.h | UTF-8 | 738 | 2.640625 | 3 | [] | no_license | //
// Created by user on 2019/9/18.
//
#ifndef CPP_DOUBLELIST_H
#define CPP_DOUBLELIST_H
#include <iostream>
#include <list>
using namespace std;
class DListNode {
public:
DListNode *prev, *next;
int val;
DListNode(DListNode *prev = nullptr, DListNode *next = nullptr, int val = 0);
virtual ~DListNode();
};
class DoubleList {
private:
DListNode *head, *tail;
public:
DoubleList(DListNode *head = nullptr, DListNode *tail = nullptr);
virtual ~DoubleList();
void add2head(int val);
void add2tail(int val);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int val);
bool isEmpty();
bool isExist(int val);
bool showList();
};
#endif //CPP_DOUBLELIST_H
| true |
722da095f8b3766cad40deba9b77639123f1170e | C++ | WhiZTiM/coliru | /Archive2/39/91302648439db6/main.cpp | UTF-8 | 650 | 3.125 | 3 | [] | no_license | //PUNTEROS
#include <stdio.h>
/*void mul(int a, int b, int s)
{
s=a*b;
}
void mult(int a, int b, int* s)
{
*s=a*b;
}*/
/*
void p()
{
int s;
printf("%d\n",s);
}
void q()
{
int n = 248;
printf("%d\n",n);
}
*/
int* m()
{
int a=29;
return &a;
}
int main()
{
/*int a=8;
int* s;
s= &a;
printf("%p\n",s);
printf("%d\n",*s);
*s = 25;
printf("%d\n",*s);*/
/*int* p = (int*) 0xF9;
printf("%p\n",p);
printf("%d\n",*p);*/
/*int a=9;
int b=5;
int r;
mult(a,b,&r);
printf("%d\n",r);*/
/*p();
q();*/
int* f=m();
printf("%d\n",*f);
} | true |
4f9a9cae49bbc7889c1ced606fafd69a12e25dbe | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/boost/pfr/detail/make_integer_sequence.hpp | UTF-8 | 2,564 | 2.53125 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | // Copyright (c) 2018 Sergei Fedorov
// Copyright (c) 2019-2021 Antony Polukhin
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PFR_DETAIL_MAKE_INTEGER_SEQUENCE_HPP
#define BOOST_PFR_DETAIL_MAKE_INTEGER_SEQUENCE_HPP
#pragma once
#include <boost/pfr/detail/config.hpp>
#include <type_traits>
#include <utility>
#include <cstddef>
namespace boost { namespace pfr { namespace detail {
#if BOOST_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE == 0
#ifdef __has_builtin
# if __has_builtin(__make_integer_seq)
# define BOOST_PFR_USE_MAKE_INTEGER_SEQ_BUILTIN
# endif
#endif
#ifdef BOOST_PFR_USE_MAKE_INTEGER_SEQ_BUILTIN
using std::integer_sequence;
// Clang unable to use namespace qualified std::integer_sequence in __make_integer_seq.
template <typename T, T N>
using make_integer_sequence = __make_integer_seq<integer_sequence, T, N>;
#undef BOOST_PFR_USE_MAKE_INTEGER_SEQ_BUILTIN
#else
template <typename T, typename U>
struct join_sequences;
template <typename T, T... A, T... B>
struct join_sequences<std::integer_sequence<T, A...>, std::integer_sequence<T, B...>> {
using type = std::integer_sequence<T, A..., B...>;
};
template <typename T, T Min, T Max>
struct build_sequence_impl {
static_assert(Min < Max, "Start of range must be less than its end");
static constexpr T size = Max - Min;
using type = typename join_sequences<
typename build_sequence_impl<T, Min, Min + size / 2>::type,
typename build_sequence_impl<T, Min + size / 2 + 1, Max>::type
>::type;
};
template <typename T, T V>
struct build_sequence_impl<T, V, V> {
using type = std::integer_sequence<T, V>;
};
template <typename T, std::size_t N>
struct make_integer_sequence_impl : build_sequence_impl<T, 0, N - 1> {};
template <typename T>
struct make_integer_sequence_impl<T, 0> {
using type = std::integer_sequence<T>;
};
template <typename T, T N>
using make_integer_sequence = typename make_integer_sequence_impl<T, N>::type;
#endif // !defined BOOST_PFR_USE_MAKE_INTEGER_SEQ_BUILTIN
#else // BOOST_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE == 1
template <typename T, T N>
using make_integer_sequence = std::make_integer_sequence<T, N>;
#endif // BOOST_PFR_USE_STD_MAKE_INTEGRAL_SEQUENCE == 1
template <std::size_t N>
using make_index_sequence = make_integer_sequence<std::size_t, N>;
template <typename... T>
using index_sequence_for = make_index_sequence<sizeof...(T)>;
}}} // namespace boost::pfr::detail
#endif
| true |
d9fdc2c3fe60d4afe6cb33b4ad6f3ee3ce7fcbb0 | C++ | huajing225/GraphicsFileConverter | /src/brc2pov/main.cpp | UTF-8 | 4,549 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <algorithm>
#include <QtCore>
using namespace std;
class Node {
public:
Node(): x(0), y(0), z(0), r(1) {}
Node(float x_, float y_, float z_, float r_): x(x_), y(y_), z(z_), r(r_) {}
void print() const
{
printf(" <%f, %f, %f>, %f\n", x, y, z, r);
}
public:
float x;
float y;
float z;
float r;
};
class Branch {
public:
int branchLevel() const { return branch_level; }
void setBranchLevel(int level) { branch_level = level; }
bool empty() const { return nodeList.empty(); }
void append(const Node& node) { nodeList.append(node); }
void clear() { nodeList.clear(); }
void print(const char* spline_method, const char* texture, const char* scale, float threshold=0.0) const;
private:
QVector<Node> simplify(float threshold) const;
void simplify(const QVector<Node>& nodes, const QVector<float>& thetas, int beg, int end, float threshold, QVector<Node>& res) const;
void print(const QVector<Node>& nodes, const char* spline_method, const char* texture, const char* scale) const;
private:
int branch_level;
QVector<Node> nodeList;
};
float calculateTheta(const Node& first, const Node& second)
{
float x = second.x - first.x;
float y = second.y - first.y;
float z = second.z - first.z;
float res = acos(z / sqrt(x * x + y * y + z * z));
return res;
}
void Branch::simplify(const QVector<Node>& nodes, const QVector<float>& thetas, int beg, int end, float threshold, QVector<Node>& res) const
{
if (beg + 1 == end) {
res.append(nodes[beg]);
return;
}
if (*max_element(thetas.begin() + beg, thetas.begin() + end) - *min_element(thetas.begin() + beg, thetas.begin() + end) < threshold) {
res.append(nodes[beg]);
return;
}
int mid = (beg + end) / 2;
simplify(nodes, thetas, beg, mid, threshold, res);
simplify(nodes, thetas, mid, end, threshold, res);
}
QVector<Node> Branch::simplify(float threshold) const
{
QVector<Node> nodes;
QVector<float> thetas;
for (int i = 0; i < nodeList.size() - 1; ++i)
thetas.append(calculateTheta(nodeList[i], nodeList[i + 1]));
simplify(nodeList, thetas, 0, thetas.size(), threshold, nodes);
nodes.append(nodeList.last());
return nodes;
}
void Branch::print(const char* spline_method, const char* texture, const char* scale, float threshold) const
{
QVector<Node> simpNodeList = simplify(threshold);
print(simpNodeList, spline_method, texture, scale);
}
void Branch::print(const QVector<Node>& nodes, const char* spline_method, const char* texture, const char* scale) const
{
printf("sphere_sweep {\n");
printf(" %s_spline\n", spline_method);
printf(" %d,\n", nodes.size());
foreach (const Node& node, nodes)
node.print();
printf(" pigment { image_map {\"%s\"} scale %s }\n", texture, scale);
printf(" finish {ambient 0.8 diffuse 0.8 phong 0.2}\n");
printf("}\n\n");
}
int main(int argc, char* argv[])
{
if (argc != 7) {
printf("Usage: brc2pov.exe filename.brc cubic[linear] texture.jpg scale simp_threshold min_branch_level,max_branch_level");
exit(-1);
}
QStringList branch_levels = QString(argv[6]).split(",");
int min_branch_level = branch_levels.at(0).toInt();
int max_branch_level = branch_levels.at(1).toInt();
QFile brcfile(argv[1]);
if (!brcfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
printf("Can not open brc file %s", argv[1]);
exit(-2);
}
Branch branch;
QTextStream in(&brcfile);
while (!in.atEnd()) {
QStringList items = in.readLine().split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (items.empty())
continue;
if (items[0] == "g") {
if (!branch.empty() && branch.branchLevel() >= min_branch_level && branch.branchLevel() <= max_branch_level) {
branch.print(argv[2], argv[3], argv[4], QString(argv[5]).toFloat());
}
branch.clear();
}
if (items[0] == "p") {
branch.setBranchLevel(items[5].toInt());
}
if (items[0] == "v") {
branch.append(Node(items[1].toFloat(), items[2].toFloat(), items[3].toFloat(), items[4].toFloat()));
}
}
if (branch.branchLevel() >= min_branch_level && branch.branchLevel() <= max_branch_level) {
branch.print(argv[2], argv[3], argv[4], QString(argv[5]).toFloat());
}
brcfile.close();
return 0;
}
| true |
ebd4f9a12d2ab73dc4411251fc090c94b22dadff | C++ | Amankumar-code/GeeksForGeeksSolution | /Track/Searching/5. Majority Element.cpp | UTF-8 | 447 | 3.265625 | 3 | [] | no_license | class Solution{
public:
// Function to find majority element in the array
// a: input array
// size: size of input array
int majorityElement(int a[], int n)
{
if(n==1) return a[0];
map<int,int>m;
for(int i=0;i<n;i++)
{
m[a[i]]++;
}
for (auto i : m)
{
if(i.second>n/2)
return i.first;
}
return -1;
}
};
| true |
820d0651917175de7cb29b213f2d690de36e5607 | C++ | tanimoto-y/procon30_comp_ProvisionalOutput | /for_VisualStudio/procon30_comp_ProvisionalOutput/node.cpp | SHIFT_JIS | 2,245 | 3.46875 | 3 | [] | no_license | #include "node.hpp"
/**
Node::Node:
NodeNX̃RXgN^
m[h̎WƐem[hݒ肷iem[hȂꍇnullptrwj
@param argX m[hɐݒ肷xW
@param argY m[hɐݒ肷yW
@param argParentNodePtr ݒ肷em[h̃|C^
*/
Node::Node(const int argX, const int argY, Node* argParentNodePtr) {
mX = argX;
mY = argY;
mThisNodePtr = this;
mParentNodePtr = argParentNodePtr;
if (mParentNodePtr != nullptr) {
mTreeHigh = mParentNodePtr->getTreeHigh()+1;
}
else {
mTreeHigh = 0;
}
}
/**
Node::setChildNode:
qm[hݒ肷
@param argChildNodePtr ݒ肷qm[h̃|C^
*/
void Node::setChildNode(Node* argChildNodePtr) {
mChildNodesPtr.push_back(argChildNodePtr);
//argChildNodePtr->setParentNode(mThisNodePtr);
}
/**
Node::getChildNode:
qm[h̃|C^Ԃ
@param n qm[h̔ԍ
@return nԖڂ̎qm[h̃|C^
*/
Node* Node::getChildNode(const int n) {
if (n > mChildNodesPtr.size()) {
cout << "vfm[h̐Ă܂" << endl;
return nullptr;
}
return mChildNodesPtr[n];
}
/**
Node::setParentNode:
em[h̐ݒs
@param argParentNodePtr em[h̃|C^
*/
void Node::setParentNode(Node* argParentNodePtr) {
mParentNodePtr = argParentNodePtr;
}
/**
Node::getParentNode:
em[h̃|C^Ԃ
@return em[h̃|C^
*/
Node* Node::getParentNode() {
return mParentNodePtr;
}
/**
Node::getThisNode:
̃m[h̃|C^Ԃ
@return ̃m[h̃|C^
*/
Node* Node::getThisNode() {
return mThisNodePtr;
}
/**
Node::getPosition:
̃m[hVec2^ōWԂ
@return ̃m[hW
*/
Vec2 Node::getPosition() {
return Vec2{mX, mY};
}
/**
Node::getTreeHigh:
m[h̍iԏ̐eǂꂾĂ邩jԂ
@return m[h̍
*/
int Node::getTreeHigh() {
return mTreeHigh;
}
| true |
cf1153c0e1e68f83b900d071f4f4c53dcb57823d | C++ | kritsanaphat/week3-2 | /week3-2/Source.cpp | UTF-8 | 975 | 4.09375 | 4 | [] | no_license | #include<stdio.h>
void Plus(int a, int b) {
printf("%d + %d = %d\n", a, b, a + b);
}
void Minus(int a, int b) {
printf("%d - %d = %d\n", a, b, a - b);
}
void Multiplied(int a, int b) {
printf("%d * %d = %d\n", a, b, a * b);
}
void Divide(int a, int b) {
float c;
c = (float)a / b;
printf("%d / %d = %f\n", a, b, c);
}
int main() {
int i, num1, num2;
do {
printf("Calculate\n");
printf("1 Plus\n");
printf("2 Minus\n");
printf("3 Multiplied\n");
printf("4 Divide\n");
printf("5 Exit\n");
printf("Select choice :");
scanf_s("%d", &i);
if (i < 1 || i>5) printf("Enter 1-5 only\n");
else if (i == 5) break;
else {
printf("Enter number1 :");
scanf_s("%d", &num1);
printf("Enter number2 :");
scanf_s("%d", &num2);
if (i == 1) {
Plus(num1, num2);
}
else if (i == 2) {
Minus(num1, num2);
}
else if (i == 3) {
Multiplied(num1, num2);
}
else if (i == 4) {
Divide(num1, num2);
}
}
} while (i != 5);
} | true |
6fc40733b47a310c097e80db82a9502c3231e922 | C++ | ARM-software/ATP-Engine | /stats.hh | UTF-8 | 5,624 | 2.8125 | 3 | [
"BSD-3-Clause-Clear",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* SPDX-License-Identifier: BSD-3-Clause-Clear
*
* Copyright (c) 2015 ARM Limited
* All rights reserved
* Created on: Oct 19, 2015
* Author: Matteo Andreozzi
*/
#ifndef _AMBA_TRAFFIC_PROFILE_STATS_HH_
#define _AMBA_TRAFFIC_PROFILE_STATS_HH_
#include <cstdint>
#include <string>
#include <cmath>
#include <limits>
#include "proto/tp_stats.pb.h"
using namespace std;
namespace TrafficProfiles {
/*!
*\brief Statistics collection class
*
* This class provides methods and storage to collect and store statistics
* at any level in the ATP hierarchy. It can also export recorded values
* as Google Protocol Buffer objects
*/
class Stats {
//! started flag : signals that the start time has been initialised
bool started;
public:
//! Start time since when stats are computed
uint64_t startTime;
//! Time scale factor: used to export time in seconds
uint64_t timeScale;
//! last time statistics were recorded
uint64_t time;
//! total packet sent counter
uint64_t sent;
//! total packet received counter
uint64_t received;
//! how many data have been generated
uint64_t dataSent;
//! how many data have been received
uint64_t dataReceived;
//! previous latency - used to compute jitter
double prevLatency;
//! cumulative response jitter
double jitter;
//! cumulative response latency
double latency;
//! FIFO buffer underruns
uint64_t underruns;
//! FIFO buffer overruns
uint64_t overruns;
//! Cumulative OT (CurTxn)
uint64_t ot;
//! Number of OT measurements
uint64_t otN;
//! Cumulative FIFO level (CurLvl)
uint64_t fifoLevel;
//! Number of FIFO level measurements
uint64_t fifoLevelN;
//! Default Constructor
Stats();
//! Default destructor
virtual ~Stats();
/*!
* records a send event
*\param t the time the event occurred
*\param data the amount of data sent
*\param o outstanding transactions
*/
void send (const uint64_t, const uint64_t, const uint64_t=0);
/*!
* records a receive event
*\param t the time the event occurred
*\param data the amount of data received
*\param l the latency measured for this data reception
*/
void receive (const uint64_t, const uint64_t, const double);
/*!
* records a FIFO update event
*\param l the FIFO level
*\param u whether the FIFO did underrun
*\param o whether the FIFO did overrun
*/
void fifoUpdate(const uint64_t, const bool, const bool);
//! resets all statistics counters
inline void reset() {started=false, startTime=numeric_limits<uint64_t>::max(), time=0,
sent=0, received=0, dataSent=0,
dataReceived=0, prevLatency=.0, jitter=.0, latency=.0,
underruns=0, overruns=0, ot=0, otN=0, fifoLevel=0,
fifoLevelN=0;}
/*!
* Starts the statistics from the given time,
* if not already started
*\param t start time
*/
inline void start(const uint64_t t) { if (!started) {started=true; startTime=t;}}
/*!
* Advances the time to a specific value
* going backwards in time is prevented
*\param t time to set
*/
void setTime(const uint64_t);
/*!
* Dumps statistics
*\return a formatted string with all statistics
*/
const string dump() const;
/*!
* Method to compute and get the rate for sent data
*\return the data rate
*/
inline double sendRate () const
{ return (time? (double)dataSent/((double)time - (double)startTime)*timeScale:0); }
/*!
* Method to compute and get the rate for received data
*\return the data rate
*/
inline double receiveRate () const
{ return (time? (double)dataReceived/((double)time - (double)startTime)*timeScale:0);}
/*
* Method to compute and get the average response latency
*\return the average response latency
*/
inline double avgLatency() const
{ return latency/(double)(timeScale * received); }
/*
* Method to compute and get the request to response jitter
*\return the computed response jitter
*/
inline double avgJitter() const
{ return jitter/(double)(timeScale); }
/*
* Method to compute and get the average OT
*\return the average OT count
*/
inline uint64_t avgOt() const { return otN ? ceil((double)ot/(double)otN) : 0;}
/*
* Method to compute and get the average FIFO level
*\return the average FIFO level
*/
inline uint64_t avgFifoLevel() const {return fifoLevelN ? (fifoLevel/fifoLevelN) : 0;}
/*!
* Method to compute and return the stats finish time
*\return the stats time in seconds
*/
inline double getTime() const {return (double)time/(double)timeScale;}
/*!
* Method to compute and return the stats start time
*\return the stats time in seconds
*/
inline double getStartTime() const {return (double)startTime/(double)timeScale;}
/*!
* Exports statistics as Google Protocol Buffer object
*\return a Google Protocol Buffer StatObject
*/
const StatObject* xport() const;
/*!
* Sum operator: merges two Stats objects
*\param s the Stats object to add
*\return the sum by value
*/
Stats operator+(const Stats&);
/*!
* Add operator: adds Stats objects
* fields to this one
*\param s the Stats object to add
*\return this object by reference
*/
Stats& operator+=(const Stats&);
};
} /* namespace TrafficProfiles */
#endif /* _AMBA_TRAFFIC_PROFILE_STATS_HH_ */
| true |
f64fc12ece96935ed7395b4c5f490f6e29e5a48b | C++ | yalagamsrinivas/CPP-Training | /CPPTraining/LambdaExpression.cpp | UTF-8 | 895 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
double dData[] = {-0.001, 5.0251, -0.3, 9.365, 0.365, 89.5654};
vector<double> v_dData;
for (auto Data : dData)
{
v_dData.push_back(Data);
}
cout << "Before Transform : " << endl;
for (auto &Data : v_dData)
{
cout << Data << "\t";
}
cout << endl;
std::transform(v_dData.begin(), v_dData.end(), v_dData.begin(),
[](double dTempData)
{
return dTempData < 0 ? 0 : dTempData;
});
cout << "After Transform : " << endl;
for (auto &Data : v_dData)
{
cout << Data << "\t";
}
cout << endl;
//sorting
sort(v_dData.begin(), v_dData.end(), [](const int& a, const int& b) -> bool
{
return a < b;
});
cout << "After Transform : " << endl;
for (auto &Data : v_dData)
{
cout << Data << "\t";
}
cout << endl;
system("pause");
return EXIT_SUCCESS;
} | true |
069c5a20f1df12dee232baddc7fccf5922b302d8 | C++ | guerarda/rt1w | /src/core/arena.cpp | UTF-8 | 1,588 | 3.09375 | 3 | [
"MIT"
] | permissive | #include "rt1w/arena.hpp"
#include "rt1w/error.h"
constexpr size_t cache_line_size = 64;
constexpr size_t extra_alloc_size = 256 * 1024;
struct hdr {
struct hdr *prev;
uint8_t *next;
uint8_t *limit;
};
struct _Arena : Arena {
_Arena();
~_Arena() override;
void *alloc(size_t n) override;
struct hdr *m_hdr;
struct {
size_t count = 0;
size_t allocated = 0;
size_t used = 0;
} m_info;
};
_Arena::_Arena()
{
m_hdr = (struct hdr *)malloc(sizeof(*m_hdr));
m_hdr->prev = nullptr;
m_hdr->next = nullptr;
m_hdr->limit = nullptr;
}
_Arena::~_Arena()
{
struct hdr *h = m_hdr;
while (h) {
struct hdr *tmp = h->prev;
free(h);
h = tmp;
}
}
void *_Arena::alloc(size_t n)
{
/* Round up n so it's 16-byte aligned */
n = ((n + 15) & (size_t)(~15));
if (!(m_hdr->next && m_hdr->limit) || size_t(m_hdr->limit - m_hdr->next) < n) {
size_t s = n + extra_alloc_size;
struct hdr *p = (struct hdr *)malloc(sizeof(*p) + s);
/* Keep track of allocations */
m_info.count += 1;
m_info.allocated += s;
/* Align usable memory after the header */
void *aligned = (void *)(p + 1);
std::align(cache_line_size, s, aligned, s);
*p = *m_hdr;
m_hdr->prev = p;
m_hdr->next = (uint8_t *)aligned;
m_hdr->limit = m_hdr->next + s;
}
void *p = m_hdr->next;
m_hdr->next += n;
m_info.used += n;
return p;
}
uptr<Arena> Arena::create()
{
return std::make_unique<_Arena>();
}
| true |
ef9f43ab49737ba3d16c9ecfab70d82c3674c73a | C++ | benyeoh/arf | /Src/RendererUtils/RUPostTransVertCacheOpt.h | UTF-8 | 2,199 | 2.546875 | 3 | [] | no_license | //==============================================================================
//
// RUPostTransVertCacheOpt.h
//
// Based on Tom Forsyth's implementation:
// http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
//
// Author: Ben Yeoh
// Date: 2/2/2009
//
//==============================================================================
#pragma once
_NAMESPACE_BEGIN
class RUPostTransVertCacheOpt
{
const static uint CACHE_SIZE = 32;
const static int INVALID_CACHE_POS = -1;
struct CacheNode;
struct TriangleData
{
boolean isAdded;
float score;
int vertIndices[3];
};
struct VertexData
{
const static uint MAX_TRIANGLE_INDICES = 128;
CacheNode* pNode;
float score;
int numTotalTriangles;
int numTrianglesNotAdded;
int triangleIndices[MAX_TRIANGLE_INDICES];
};
struct CacheNode
{
uint pos;
VertexData* pVert;
CacheNode* pNext;
CacheNode* pPrev;
};
private:
VertexData* m_pVertices;
uint m_NumVertices;
TriangleData* m_pTriangles;
TriangleData** m_ppDrawnTriangles;
uint m_NumDrawnTriangles;
uint m_NumTriangles;
CacheNode m_CacheNodes[CACHE_SIZE];
CacheNode* m_pHead;
CacheNode* m_pTail;
TriangleData* m_pHighestTriangle;
public:
RUPostTransVertCacheOpt()
: m_pVertices(NULL)
, m_NumVertices(0)
, m_pTriangles(NULL)
, m_NumTriangles(0)
, m_NumDrawnTriangles(0)
, m_pHighestTriangle(NULL)
, m_pHead(NULL)
, m_pTail(NULL)
{
}
~RUPostTransVertCacheOpt()
{
}
private:
inline void MoveToHead(CacheNode* pNode);
inline float GetVertexScore(VertexData* pVert);
inline float GetTriangleScore(TriangleData* pTri);
VertexData* AddOneVertToCache(VertexData& vert);
void AddToVertCache(VertexData& v1,
VertexData& v2,
VertexData& v3);
void InitializeTriangles(IRIndexBuffer* pIB);
void InitializeVertices();
void DrawTriangle(TriangleData& tri);
void Simulate();
void RemoveTriangleFromVertex(TriangleData& tri, VertexData& data);
public:
void Optimize(IRIndexBuffer* pToOptimize, uint numVertices);
};
_NAMESPACE_END
| true |
dcb444e80bf4cd5065eda2da249627431a79ba79 | C++ | MariaTeresaFerreira/CAL-proj | /Projeto_Parte1/Projeto_Parte1/src/Accommodation.h | UTF-8 | 2,422 | 3.75 | 4 | [] | no_license | /*
* Accommodation.h
*
* Created on: 23/03/2018
* Author: Francisco Miranda; Jo�o Vaz Gama Amaral; Maria Teresa Ferreira;
*/
#ifndef SRC_ACCOMMODATION_H_
#define SRC_ACCOMMODATION_H_
#include "Period.h"
#include "Libraries.h"
class Accommodation{
private:
/**
* @brief Variable that stores the accommodation price with no added cost
*/
int basePrice;
/**
* @brief Variable that stores the accommodation facility's name
*/
std::string name;
/**
* @brief Vector that stores the different periods that affect the accommodation's price
*/
std::vector<Period*> periods;
public:
/**
* @brief Default constructor for the Accommodation class
*/
Accommodation();
/**
* @brief Constructor for the Accommodation class that sets the price, the name, and the periods vector as the received arguments
* @param price
* @param name
* @param periods
*/
Accommodation(float price, std::string name, std::vector<Period*> periods);
/**
* @brief Gets the current value of the base price of the accommodation
* @return basePrice
*/
int getBasePrice();
/**
* @brief Gets the current name of the accommodation
* @return name
*/
std::string getName();
/**
* @brief Gets the current periods vector
* @return periods
*/
std::vector<Period*> getAllPeriods();
/**
* @brief Returns the period that the date given as an argument is inserted into
* @param d
* @return Period
*/
Period* getPeriod(Date d);
/**
* @brief Calculates the final price for the given date with the base price and the period that the date is from
* @param d
* @return price for the given date
*/
int getPrice(Date d);
/**
* @brief Overloading of the << operator in order to present the information in a user friendly way
* @param o
* @param a
* @return ostream
*/
friend std::ostream & operator <<(std::ostream &o, const Accommodation &a){
o << "The accommodation name is:" << a.name << std::endl;
o << "It has a base price of: " << a.basePrice << std::endl;
o << "All the seasons: " << std::endl;
for(size_t i = 0; i < a.periods.size(); i++){
o << "\t" << (*a.periods[i]) << std::endl;
o << std::endl;
}
return o;
}
};
#endif /* SRC_ACCOMMODATION_H_ */
| true |
9c796185539842a286b8af0f707e6d9020e2050a | C++ | saumya66/Competitive-Programming- | /CODEFORCES/A2OJ Practice/1300 Codeforces Rating 1399/WayTooLongWords.cpp | UTF-8 | 534 | 2.546875 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve()
{
string s;
cin>>s;
ll l =s.length();
if(l>10){
string ans ;
ans = ans+ s[0];
ans=ans+ to_string(l-2);
ans=ans + s[l-1];
cout<<ans ;
}
else {
cout<<s;
}
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL);
/*
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
*/
ll n;
cin>>n;
for(ll i=0;i<n;i++)
{
solve();
cout << "\n";
}
return 0;
}
| true |
cb45d09eb2f8c47f63ebb240174d05120179f369 | C++ | jgrowl/carcassonne | /src/left_side_connections.cc | UTF-8 | 997 | 2.796875 | 3 | [] | no_license | #include "left_side_connections.h"
namespace carcassonne
{
LeftSideConnections::LeftSideConnections()
{
}
LeftSideConnections::LeftSideConnections(const LeftSideConnections& src)
: SideConnections(src)
{
CopyFrom(src);
}
LeftSideConnections& LeftSideConnections::
operator=(const LeftSideConnections& rhs)
{
if(this == &rhs) {
return (*this);
}
CopyFrom(rhs);
return (*this);
}
void LeftSideConnections::
CopyFrom(const LeftSideConnections& src)
{
}
SideConnections* LeftSideConnections::
Clone() const
{
return new LeftSideConnections(*this);
}
std::vector<std::string> LeftSideConnections::ToStringVector() const
{
std::vector<std::string> connections;
connections.push_back("Left(itself)");
if(clockwise_) {
connections.push_back("Top");
}
if(across_) {
connections.push_back("Right");
}
if(counterclockwise_) {
connections.push_back("Bottom");
}
return connections;
}
LeftSideConnections::~LeftSideConnections()
{
}
}
| true |
06036ac7f9039e26074e7beeda827aa847ad1c24 | C++ | Dreadbot/Dreadbot-V | /src/XMLInput.cpp | UTF-8 | 10,105 | 2.75 | 3 | [] | no_license | #include "XMLInput.h"
#include "Config.h"
namespace dreadbot
{
//SimplePneumatic stuff
SimplePneumatic::SimplePneumatic()
{
invert = false;
dPneumatic = nullptr;
sPneumatic = nullptr;
actionCount = 2;
}
void SimplePneumatic::Set(DoubleSolenoid::Value value)
{
if (invert)
{
if (value == DoubleSolenoid::kForward)
value = DoubleSolenoid::kReverse;
else if (value == DoubleSolenoid::kReverse)
value = DoubleSolenoid::kForward;
}
if (actionCount > 1) //Is this a double solenoid?
dPneumatic->Set(value);
else if (value != DoubleSolenoid::kOff)
sPneumatic->Set(true);
else
sPneumatic->Set(false);
}
//SimpleMotor stuff
SimpleMotor::SimpleMotor()
{
CAN = false;
invert = false;
CANMotor = nullptr;
PWMMotor = nullptr;
}
void SimpleMotor::Set(float value)
{
if (invert)
value *= -1;
if (CAN && CANMotor != nullptr)
CANMotor->Set(value);
else if (!CAN && PWMMotor != nullptr)
PWMMotor->Set(value);
}
//MotorGrouping stuff
MotorGrouping::MotorGrouping()
{
deadzone = 0;
}
void MotorGrouping::Set(float value)
{
if (fabs(value) < deadzone)
value = 0; //Automatic deadzone processing
for (auto iter = motors.begin(); iter != motors.end(); iter++)
iter->Set(value);
//Ta-da!
}
void MotorGrouping::SetDeadzone(float newDeadzone)
{
deadzone = fabs(newDeadzone); //No negative deadzones.
}
//PneumaticGrouping stuff
void PneumaticGrouping::Set(DoubleSolenoid::Value value)
{
for (auto iter = pneumatics.begin(); iter != pneumatics.end(); iter++)
iter->Set(value);
//Ta-da!
}
void PneumaticGrouping::Set(float value)
{
//Deadzone processing
if (fabs(value) < deadzone)
value = 0;
if (value == 0)
Set(DoubleSolenoid::kOff);
else if (value > 0)
Set(DoubleSolenoid::kForward);
else if (value < 0)
Set(DoubleSolenoid::kReverse);
}
void PneumaticGrouping::SetDeadzone(float newDeadzone)
{
deadzone = fabs(newDeadzone);
}
//XMLInput stuff
XMLInput* XMLInput::singlePtr = nullptr;
XMLInput::XMLInput()
{
drivebase = nullptr;
for (int i = 0; i < MAX_CONTROLLERS; i++)
controllers[i] = nullptr;
for (int i = 0; i < MAX_MOTORS; i++)
{
canMotors[i] = nullptr;
pwmMotors[i] = nullptr;
}
for (int i = 0; i < MAX_PNEUMS; i++)
{
dPneums[i] = nullptr;
sPneums[i] = nullptr;
}
driveController = 1;
for (int i = 0; i < 3; i++)
{
axes[i] = 0;
deadzones[i] = 0;
inverts[i] = 0; //Since inverts is an array of bools, this sets it to false
}
}
XMLInput* XMLInput::getInstance()
{
if (singlePtr == nullptr)
singlePtr = new XMLInput;
return singlePtr;
}
void XMLInput::setDrivebase(dreadbot::MecanumDrive* newDrivebase)
{
drivebase = newDrivebase;
}
void XMLInput::updateDrivebase()
{
double sPoints[3];
sPoints[x] = controllers[driveController]->GetRawAxis(axes[x]);
sPoints[y] = controllers[driveController]->GetRawAxis(axes[y]);
sPoints[r] = controllers[driveController]->GetRawAxis(axes[r]);
for (int i = 0; i < 3; i++)
{
//Deadzones
if (fabs(sPoints[i]) < deadzones[i])
sPoints[i] = 0;
//Sensitivity
bool negative = false;
if (sPoints[i] < 0)
negative = true;
//y = 1.75(x - 0.4)^3 + 0.6x^2 + 0.12
sPoints[i] = (1.75f * pow((std::fabs(sPoints[i]) - 0.4f), 3.0f)) + (0.6f * pow(std::fabs(sPoints[i]), 2.0f)) + 0.12;
if (negative)
sPoints[i] *= -1.0f;
//Inverts
if (inverts[i])
sPoints[i] *= -1;
}
// Desensitize rotation even more
sPoints[r] /= 1.5;
SmartDashboard::PutNumber("sX", sPoints[x]);
SmartDashboard::PutNumber("sY", sPoints[y]);
SmartDashboard::PutNumber("sR", sPoints[r]);
if (drivebase != nullptr) //Idiot check
drivebase->Drive_v(sPoints[x], sPoints[y], sPoints[r]);
}
Joystick* XMLInput::getController(int ID)
{
if (ID < MAX_CONTROLLERS && ID > -1)
{
if (controllers[ID] == nullptr)
controllers[ID] = new Joystick(ID);
return controllers[ID];
}
return nullptr;
}
CANTalon* XMLInput::getCANMotor(int ID)
{
if (ID < MAX_CONTROLLERS - 1 && ID > -1)
{
if (canMotors[ID] == nullptr)
canMotors[ID] = new CANTalon(ID);
return canMotors[ID];
}
return nullptr;
}
Talon* XMLInput::getPWMMotor(int ID)
{
if (ID < MAX_CONTROLLERS - 1 && ID > -1)
{
if (pwmMotors[ID] == nullptr)
pwmMotors[ID] = new Talon(ID);
return pwmMotors[ID];
}
return nullptr;
}
DoubleSolenoid* XMLInput::getDPneum(int forwardID)
{
if (forwardID < MAX_PNEUMS - 1 && forwardID > -1)
return dPneums[forwardID];
return nullptr;
}
Solenoid* XMLInput::getSPneum(int ID)
{
if (ID > MAX_PNEUMS - 1 || ID < 0)
return nullptr;
if (sPneums[ID] == nullptr)
sPneums[ID] = new Solenoid(ID);
return sPneums[ID];
}
MotorGrouping* XMLInput::getMGroup(string name)
{
if (mGroups.count(name) > 0) //Checks how many elements have this key. If none do, return nullptr.
return &mGroups[name]; //This syntax is awesome; note that mGroups absolutely is NOT an array!
return nullptr;
}
PneumaticGrouping* XMLInput::getPGroup(string name)
{
if (pGroups.count(name) > 0) //Checks out many elements have this key. If none do, return nullptr.
return &pGroups[name];
return nullptr;
}
void XMLInput::loadXMLConfig()
{
pGroups.clear();
mGroups.clear();
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_string(config.c_str());
SmartDashboard::PutNumber("XML Load Status: ", result.status);
SmartDashboard::PutString("XML Load Result: ", result.description());
//Load drivebase motors
int motorList[4];
pugi::xml_node base = doc.child("Dreadbot").child("Drivebase");
for (auto motor = base.child("motors").child("motor"); motor; motor = motor.next_sibling())
{
string motorPos = motor.attribute("position").as_string();
if (motorPos == "frontLeft")
motorList[0] = atoi(motor.child_value());
else if (motorPos == "frontRight")
motorList[1] = atoi(motor.child_value());
else if (motorPos == "backLeft")
motorList[2] = atoi(motor.child_value());
else if (motorPos == "backRight")
motorList[3] = atoi(motor.child_value());
}
drivebase->Set(motorList[0], motorList[1], motorList[2], motorList[3]);
//Drivebase control loading - rig joystick
int controlID = base.child("controller").attribute("controllerID").as_int();
if (controllers[controlID] == nullptr)
controllers[controlID] = new Joystick(controlID);
driveController = controlID;
//Drivebase control loading - get axes
string invert;
for (auto axis = base.child("controller").child("axis"); axis; axis = axis.next_sibling())
{
string axisDir = axis.attribute("dir").as_string();
invert = axis.child_value("invert");
if (axisDir == "transY")
{
axes[y] = atoi(axis.child_value("ID"));
deadzones[y] = atof(axis.child_value("deadzone"));
if (invert.find("true")) //I really don't understand how this works...
inverts[y] = false;
else
inverts[y] = true;
}
else if (axisDir == "transX")
{
axes[x] = atoi(axis.child_value("ID"));
deadzones[x] = atof(axis.child_value("deadzone"));
if (invert.find("true"))
inverts[x] = false;
else
inverts[x] = true;
}
else if (axisDir == "rot")
{
axes[r] = atoi(axis.child_value("ID"));
deadzones[r] = atof(axis.child_value("deadzone"));
if (invert.find("true"))
inverts[r] = false;
else
inverts[r] = true;
}
}
//Load all motor groups
pugi::xml_node motorgroups = doc.child("Dreadbot").child("motorgroups");
for (auto motorgroup = motorgroups.child("group"); motorgroup; motorgroup = motorgroup.next_sibling())
{
//Assign group information
MotorGrouping newMGroup;
newMGroup.name = motorgroup.attribute("name").as_string();
//Check for duplicate motor groups, and output if there are
if (mGroups.count(newMGroup.name) > 0)
SmartDashboard::PutBoolean("Duplicate Motor Groups", true);
newMGroup.deadzone = fabs(motorgroup.attribute("deadzone").as_float());
for (auto motor = motorgroup.child("motor"); motor; motor = motor.next_sibling())
{
//Get motor-specific information and assign motor pointers
SimpleMotor newMotor;
newMotor.CAN = motor.attribute("CAN").as_bool();
if (newMotor.CAN)
newMotor.CANMotor = getCANMotor(motor.attribute("outputID").as_int());
else
newMotor.PWMMotor = getPWMMotor(motor.attribute("outputID").as_int());
newMotor.invert = motor.attribute("invert").as_bool();
newMGroup.motors.push_back(newMotor);
}
mGroups[newMGroup.name] = newMGroup; //Synatx is beautiful; mGroups is NOT an array!
}
//Load all pneumatic groups
pugi::xml_node pneumgroups = doc.child("Dreadbot").child("pneumaticgroups");
for (auto pneumgroup = pneumgroups.child("group"); pneumgroup; pneumgroup = pneumgroup.next_sibling())
{
PneumaticGrouping newPGroup;
newPGroup.name = pneumgroup.attribute("name").as_string();
//Check for duplicate motor groups, and output if there are
if (pGroups.count(newPGroup.name) > 0)
SmartDashboard::PutBoolean("Duplicate Pneumatic Groups", true);
newPGroup.deadzone = fabs(pneumgroup.attribute("deadzone").as_float());
for (auto pneumatic = pneumgroup.child("dsolenoid"); pneumatic; pneumatic = pneumatic.next_sibling())
{
SimplePneumatic newPneum;
newPneum.invert = pneumatic.attribute("invert").as_bool();
newPneum.actionCount = pneumatic.attribute("actionCount").as_int();
if (newPneum.actionCount > 1) //Is this a double solenoid?
{
int forwardID = pneumatic.attribute("forwardID").as_int();
int reverseID = pneumatic.attribute("reverseID").as_int();
if (getDPneum(forwardID) != nullptr)
newPneum.dPneumatic = getDPneum(forwardID);
else
{
newPneum.dPneumatic = new DoubleSolenoid(forwardID, reverseID);
dPneums[forwardID] = newPneum.dPneumatic;
}
}
else //This is a single solenoid
newPneum.sPneumatic = getSPneum(pneumatic.attribute("ID").as_int());
newPGroup.pneumatics.push_back(newPneum);
}
pGroups[newPGroup.name] = newPGroup;
}
}
}
| true |
f7f04605fbe8205bce346fccdcc2087ec187b3dd | C++ | JialeWei/6D_pose_filter_and_smoother | /src/main.cpp | UTF-8 | 10,512 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cassert>
#include <Eigen/Geometry>
#include <random>
#include <chrono>
#include <iomanip>
#include "../include/kalman_filter.h"
#include "../include/kalman_smoother.h"
void dataReader(std::vector<std::vector<double>> &res, const std::string &pathname) {
std::ifstream infile;
infile.open(pathname.data());
assert(infile.is_open());
std::vector<double> line;
std::string s;
while (getline(infile, s)) {
std::istringstream is(s);
double d;
while (!is.eof()) {
is >> d;
line.push_back(d);
}
res.push_back(line);
line.clear();
s.clear();
}
infile.close();
}
Eigen::VectorXd getPose(const std::vector<double>& data_per_line){
Eigen::VectorXd frame(12);
for (int i = 0; i < 12; i++) {
frame(i) = data_per_line[i];
}
Eigen::VectorXd pose(6);
double x = frame(11);
double y = frame(3);
double z = frame(7);
Eigen::Matrix3d rot;
rot << frame(0), frame(1), frame(2),
frame(4), frame(5), frame(6),
frame(8), frame(9), frame(10);
Eigen::Vector3d euler_angles = rot.eulerAngles(2, 1, 0);
pose << x, y, z, euler_angles(2), euler_angles(1), euler_angles(0);
return pose;
}
int main() {
std::string path = "../data/poses/00.txt";
double dt = 1.0 / 10;
double dt2 = dt * dt / 2;
int n = 18;
int m = 6;
Eigen::MatrixXd A(n, n);
Eigen::MatrixXd C(m, n);
Eigen::MatrixXd Q(n, n);
Eigen::MatrixXd R(m, m);
Eigen::MatrixXd P(n, n);
A.setIdentity();
A(0, 6) = dt;
A(1, 7) = dt;
A(2, 8) = dt;
A(3, 9) = dt;
A(4, 10) = dt;
A(5, 11) = dt;
A(6, 12) = dt;
A(7, 13) = dt;
A(8, 14) = dt;
A(9, 15) = dt;
A(10, 16) = dt;
A(11, 17) = dt;
A(0, 12) = dt2;
A(1, 13) = dt2;
A(2, 14) = dt2;
A(3, 15) = dt2;
A(4, 16) = dt2;
A(5, 17) = dt2;
C.setZero();
C.block(0, 0, m, m) = Eigen::MatrixXd::Identity(m, m);
Q.setIdentity() * 0.5;
R.setIdentity() * 5.5;
P.setIdentity();
std::vector<std::vector<double>> data;
dataReader(data, path);
Eigen::VectorXd x0(n), z0(m);
Eigen::VectorXd init_pose(6);
init_pose = getPose(data[0]);
x0.setZero();
x0.head(6) = init_pose;
z0 = init_pose;
double t = 0;
kalman_filter kf(x0, t, dt);
kf.setMatrices(A, C, Q, R, P, z0);
std::vector<Eigen::VectorXd> kf_x;
std::vector<double> kf_t;
std::vector< Eigen::VectorXd> measurements;
kf_x.push_back(kf.getState());
kf_t.push_back(kf.getTime());
measurements.push_back(z0);
for (int i = 1; i < data.size(); i++) {
Eigen::VectorXd pose = getPose(data[i]);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
const double mean = 0.0;
const double stddev_x = 2.34;
const double stddev_y = 2.34;
const double stddev_z = 2.34;
const double stddev_roll = 2.34;
const double stddev_pitch = 2.34;
const double stddev_yaw = 2.34;
std::normal_distribution<double> dist_x(mean, stddev_x);
std::normal_distribution<double> dist_y(mean, stddev_y);
std::normal_distribution<double> dist_z(mean, stddev_z);
std::normal_distribution<double> dist_R(mean, stddev_roll);
std::normal_distribution<double> dist_P(mean, stddev_pitch);
std::normal_distribution<double> dist_Y(mean, stddev_yaw);
double x_m = pose(0) + dist_x(generator);
double y_m = pose(1) + dist_y(generator);
double z_m = pose(2) + dist_z(generator);
double R_m = pose(3) + dist_R(generator);
double P_m = pose(4) + dist_P(generator);
double Y_m = pose(5) + dist_Y(generator);
Eigen::VectorXd measurement(m);
measurement << x_m, y_m, z_m, R_m, P_m, Y_m;
kf.update(measurement);
measurements.push_back(measurement);
kf_x.push_back(kf.getState());
kf_t.push_back(kf.getTime());
}
std::vector<Eigen::VectorXd> kf_x_ = kf.getAllStates();
std::vector<Eigen::MatrixXd> kf_P_ = kf.getAllP();
std::vector<Eigen::MatrixXd> kf_V_ = kf.getAllV();
Eigen::VectorXd x_T = kf_x_.back();
Eigen::MatrixXd V_T = kf_V_.back();
double t_T = kf.getTime();
kalman_smoother ks(x_T, t_T, dt);
ks.setMatrices(A, V_T);
for (int i = (int) data.size() - 2; i >= 0; i--) {
Eigen::VectorXd x_in = kf_x_[i];
Eigen::MatrixXd P_in = kf_P_[i];
Eigen::MatrixXd V_in = kf_V_[i];
ks.smooth(x_in, P_in, V_in);
}
std::vector<Eigen::VectorXd> rts_x_ = ks.getAllStates();
std::reverse(rts_x_.begin(), rts_x_.end());
std::cout<<kf_x.size()<<", "<<rts_x_.size()<<std::endl;
std::cout<<data.size()<<", "<<kf_t.size()<<std::endl;
Eigen::VectorXd measurement(12);
double rmse_kf = 0;
double rmse_rts = 0;
std::ofstream out_txt_file;
out_txt_file.open("../result/out.txt", std::ios::out | std::ios::trunc);
out_txt_file << std::scientific;
for (int i = 0; i < data.size(); i++) {
Eigen::VectorXd gt_pose(6);
gt_pose = measurements[i];
rmse_kf += (gt_pose - C * kf_x_[i]).transpose() * (gt_pose - C * kf_x_[i]);
rmse_rts += (gt_pose - C * rts_x_[i]).transpose() * (gt_pose - C * rts_x_[i]);
out_txt_file << kf_t[i] << ","
<< gt_pose(0) << ","
<< gt_pose(1) << ","
<< gt_pose(2) << ","
<< gt_pose(3) << ","
<< gt_pose(4) << ","
<< gt_pose(5) << ","
<< (C * kf_x_[i])(0) << ","
<< (C * kf_x_[i])(1) << ","
<< (C * kf_x_[i])(2) << ","
<< (C * kf_x_[i])(3) << ","
<< (C * kf_x_[i])(4) << ","
<< (C * kf_x_[i])(5) << ","
<< (C * rts_x_[i])(0) << ","
<< (C * rts_x_[i])(1) << ","
<< (C * rts_x_[i])(2) << ","
<< (C * rts_x_[i])(3) << ","
<< (C * rts_x_[i])(4) << ","
<< (C * rts_x_[i])(5)
<< std::endl;
}
out_txt_file.close();
rmse_kf = sqrt(rmse_kf / (int) data.size());
rmse_rts = sqrt(rmse_rts / (int) data.size());
std::cout << "rmse_kf = " << rmse_kf << std::endl;
std::cout << "rmse_rts = " << rmse_rts << std::endl;
// std::vector<double> measurements = {
// 1.04202710058, 1.10726790452, 1.2913511148, 1.48485250951, 1.72825901034,
// 1.74216489744, 2.11672039768, 2.14529225112, 2.16029641405, 2.21269371128,
// 2.57709350237, 2.6682215744, 2.51641839428, 2.76034056782, 2.88131780617,
// 2.88373786518, 2.9448468727, 2.82866600131, 3.0006601946, 3.12920591669,
// 2.858361783, 2.83808170354, 2.68975330958, 2.66533185589, 2.81613499531,
// 2.81003612051, 2.88321849354, 2.69789264832, 2.4342229249, 2.23464791825,
// 2.30278776224, 2.02069770395, 1.94393985809, 1.82498398739, 1.52526230354,
// 1.86967808173, 1.18073207847, 1.10729605087, 0.916168349913, 0.678547664519,
// 0.562381751596, 0.355468474885, -0.155607486619, -0.287198661013, -0.602973173813
// };
//
// double dt = 1.0 / 30;
// int n = 3;
// int m = 1;
//
// Eigen::MatrixXd A(n, n);
// Eigen::MatrixXd C(m, n);
// Eigen::MatrixXd Q(n, n);
// Eigen::MatrixXd R(m, m);
// Eigen::MatrixXd P(n, n);
//
// A << 1, dt, 0, 0, 1, dt, 0, 0, 1;
// C << 1, 0, 0;
// Q << .05, .05, .0, .05, .05, .0, .0, .0, .0;
// R << 10000;
// P << .1, .1, .1, .1, 10000, 10, .1, 10, 100;
//
// Eigen::VectorXd x0(n), z0(m);
// double t = 0;
// x0 << measurements[0], 0, -9.81;
// z0 << measurements[0];
//
// kalman_filter kf(x0, t, dt);
// kf.setMatrices(A, C, Q, R, P, z0);
//
// Eigen::VectorXd z(m);
// std::vector<double> kf_x;
// std::vector<double> kf_t;
//
// kf_x.push_back(kf.getState().transpose()(0));
// kf_t.push_back(kf.getTime());
//
// for (int i = 1; i < measurements.size(); i++) {
// //t += dt;
// z << measurements[i];
// //kf.predict();
// kf.update(z);
// kf_x.push_back(kf.getState().transpose()(0));
// kf_t.push_back(kf.getTime());
// }
//
// std::vector<Eigen::VectorXd> kf_x_ = kf.getAllStates();
// std::vector<Eigen::MatrixXd> kf_P_ = kf.getAllP();
// std::vector<Eigen::MatrixXd> kf_V_ = kf.getAllV();
//
// Eigen::VectorXd x_T = kf_x_.back();
// Eigen::MatrixXd V_T = kf_V_.back();
// double t_T = kf.getTime();
//
// kalman_smoother ks(x_T, t_T, dt);
// ks.setMatrices(A, V_T);
//
// for (int i = (int) measurements.size() - 2; i >= 0; i--) {
// Eigen::VectorXd x_in = kf_x_[i + 1];
// Eigen::MatrixXd P_in = kf_P_[i + 1];
// Eigen::MatrixXd V_in = kf_V_[i + 1];
// ks.smooth(x_in, P_in, V_in);
// }
//
// std::vector<Eigen::VectorXd> rts_x_ = ks.getAllStates();
// std::reverse(rts_x_.begin(), rts_x_.end());
//
// Eigen::VectorXd measurement(m);
// double rmse_kf = 0;
// double rmse_rts = 0;
//
// std::ofstream out_txt_file;
// out_txt_file.open("../result/out.txt", std::ios::out | std::ios::trunc);
// out_txt_file << std::fixed;
//
// for (int i = 0; i < measurements.size(); i++) {
// measurement << measurements[i];
// rmse_kf += (measurement(0) - kf_x[i]) * (measurement(0) - kf_x[i]);
// rmse_rts += (measurement(0) - rts_x_[i](0)) * (measurement(0) - rts_x_[i](0));
//
// std::cout.setf(std::ios::fixed);
// std::cout.width(15);
// std::cout.setf(std::ios::showpoint);
// std::cout.precision(3);
//
// std::cout << "z = " << measurement<<"\t"
// << "x_filtered = " << kf_x[i] << "\t"
// << "x_smoothed = " << rts_x_[i](0) << std::endl;
//
//
// out_txt_file << kf_t[i] << "," << measurement <<","<<kf_x[i]<<","<<rts_x_[i](0)<< std::endl;
// }
// out_txt_file.close();
//
// rmse_kf = sqrt(rmse_kf / (int) measurements.size());
// rmse_rts = sqrt(rmse_rts / (int) measurements.size());
//
// std::cout << "rmse_kf = " << rmse_kf << std::endl;
// std::cout << "rmse_rts = " << rmse_rts << std::endl;
return 0;
}
| true |
1d37f2ca798cfc989a12c1556221b9b266a53c9d | C++ | PenteractStudios/Tesseract | /Project/Source/Components/Component.h | UTF-8 | 2,384 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Components/ComponentType.h"
#include "FileSystem/JsonValue.h"
#include "Utils/UID.h"
class GameObject;
#if defined(TESSERACT_ENGINE_API)
/* do nothing. */
#elif defined(_MSC_VER)
#define TESSERACT_ENGINE_API __declspec(dllexport)
#endif
class Component {
public:
Component(ComponentType type, GameObject* owner, UID id, bool active);
virtual ~Component();
// ------- Core Functions ------ //
virtual void Init(); // Called after instantiating the objects. Children may not be loaded yet.
virtual void Start(); // Called after init when playing the game. Also called when starting the game.
virtual void Update(); // Updates the Component at each frame. Called on owner->Update()
virtual void DrawGizmos(); // Draws the visual representation of the component in the screen (if exists, I.E. Light direction or camera frustum).
virtual void OnEditorUpdate(); // Draw the ImGui elements & info of the Component in the Inspector. Called from PanelInspector->Update()
virtual void Save(JsonValue jComponent) const; // Operations to serialise this Component when saving the scene. Called from owner->Save().
virtual void Load(JsonValue jComponent); // Operations to initialise this Component when a scene is loaded. Called from owner->Load().
virtual bool CanBeRemoved() const; // Used in inspectorPanel to check if there are any dependencies that "forbid" the component from being removed
// ---- Visibility Setters ----- //
TESSERACT_ENGINE_API void Enable();
TESSERACT_ENGINE_API void Disable();
// ---- Virtual Enable/Disable callbacks ----//
virtual void OnEnable() {}
virtual void OnDisable() {}
// ---------- Getters ---------- //
TESSERACT_ENGINE_API ComponentType GetType() const;
TESSERACT_ENGINE_API GameObject& GetOwner() const;
TESSERACT_ENGINE_API UID GetID() const;
TESSERACT_ENGINE_API bool IsActive() const;
bool IsActiveInternal() const;
protected:
ComponentType type = ComponentType::UNKNOWN; // See ComponentType.h for a list of all available types.
bool active = true; // Visibility of the Component. If active is false the GameObject behaves as if this Component doesn't exist.
private:
UID id = 0; // Unique identifier for the component
GameObject* owner = nullptr; // References the GameObject this Component applies its functionality to. Its 'parent'.
};
| true |
d8f9a0eceaca71b2aa46edd00b1943c17a63ecc2 | C++ | dentych/APKX | /Checkpoint.hpp | UTF-8 | 1,417 | 2.65625 | 3 | [] | no_license | #pragma once
#include <map>
#include <vector>
#include <iostream>
#include <boost/signals2.hpp>
#include <mutex>
#include "Package.hpp"
typedef std::string TDestinationAddress;
class ICheckpoint {
public:
std::string getName() const;
virtual void checkIn(TPackage package) = 0;
protected:
ICheckpoint(std::string name = "") : name_(name) {}
std::string name_;
};
class ICollectable {
typedef boost::signals2::signal<void()> TSignal;
public:
virtual TPackageVector& getContent() = 0;
TSignal signal;
protected:
std::mutex contentMutex_;
};
class RouteCheckpoint : public ICheckpoint {
public:
RouteCheckpoint(ICheckpoint *nextCheckpoint) : nextCheckpoint_(nextCheckpoint) {}
void checkIn(TPackage package);
void addRoute(TDestinationAddress address, ICheckpoint *checkpoint);
protected:
ICheckpoint *getRoute(TDestinationAddress address);
void dispatch(TPackage package);
void dispatch(TPackage package, ICheckpoint *checkpoint);
bool hasRoute(TDestinationAddress address);
private:
std::map<TDestinationAddress, ICheckpoint *> routes_;
ICheckpoint *nextCheckpoint_;
};
class PackageBox : public ICheckpoint, public ICollectable {
public:
PackageBox() {}
PackageBox(std::string name) : ICheckpoint(name) {}
void checkIn(TPackage package);
TPackageVector& getContent();
private:
std::vector<TPackage> content_;
};
| true |
48977b3999fb82239aa3dc6b0f04091645f45c5d | C++ | HabibCodeMage/Binarysearchtreeafter | /Binarysearchtree.cpp | UTF-8 | 1,619 | 2.78125 | 3 | [] | no_license | // Binarysearchtree.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include"BST.h"
using namespace std;
int main()
{
BST<int> obj;
obj.insert(7);
obj.insert(4);
obj.insert(13);
obj.insert(2);
obj.insert(6);
obj.insert(11);
obj.insert(15);
obj.insert(1);
obj.insert(3);
obj.insert(5);
obj.insert(9);
obj.insert(12);
obj.insert(14);
obj.insert(16);
obj.insert(8);
obj.insert(10);
cout << "BREDTH FIRST SEARCH:\n";
obj.bredthfirst(obj.Root());
obj.removenode(7);
obj.removenode(15);
cout << "\nBREDTH FIRST SEARCH:\n";
obj.bredthfirst(obj.Root());
cout << "\nINORDER TRAVERSAL:\n";
obj.inorder(obj.Root());
cout << "\nHEIGHT OF TREE:\n";
cout<<obj.height(obj.Root())<<endl;
cout << "\nDepth of Root->right->left:\n";
BST<int>::position object = obj.Root();
cout<<obj.depth(object.right().left());
cout << "\n Mininimun in BST:\n"
<<obj.min();
cout << "\n Maximum in BST:\n"
<< obj.max();
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
5613709f8e59530d5fd62492460d9cd44e371890 | C++ | BartoszewskiA/Programowanie-obiektowe-WYKLAD-Int.-techniczna-2021 | /w07p02.cpp | UTF-8 | 1,254 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
class RGB
{
private:
int R;
int G;
int B;
public:
RGB(int r=0, int g=0, int b=0) : R(r), G(g), B(b) {}
string toString()
{
stringstream temp;
temp<<"R="<<R<<" G="<<G<<" B="<<B<<endl;
return temp.str();
}
void zamien_na_monochromatyczne()
{
int mono = round((R+G+B)/3.0);
R=G=B=mono;
}
friend RGB suma(RGB &k1, RGB &k2);
friend RGB* suma_dynamicznie(RGB* k1, RGB* k2);
};
RGB suma(RGB &k1, RGB &k2)
{
RGB temp;
temp.R = (k1.R + k2.R) / 2;
temp.G = (k1.G + k2.G) / 2;
temp.B = (k1.B + k2.B) / 2;
return temp;
}
RGB* suma_dynamicznie(RGB* k1, RGB* k2)
{
RGB* temp = new RGB;
temp->R = (k1->R + k2->R) / 2;
temp->G = (k1->G + k2->G) / 2;
temp->B = (k1->B + k2->B) / 2;
return temp;
}
int main()
{
// RGB p1(200,20,30);
// RGB p2(100,200,50);
//p1.zamien_na_monochromatyczne();
// RGB wynik = suma(p1,p2);
// cout<<wynik.toString();
RGB* p1 = new RGB(200,30,50);
RGB* p2 = new RGB(100,40,30);
RGB* wynik = suma_dynamicznie(p1,p2);
cout<<wynik->toString();
delete p1,p2, wynik;
return 0;
} | true |
e0a26a9460ca3eaccdbbbd2eb1c9ba2b01615035 | C++ | RobMa/raytracer | /src/global.cpp | UTF-8 | 572 | 2.625 | 3 | [] | no_license |
#include "global.hpp"
#define _USE_MATH_DEFINES
#include <math.h>
using namespace Util;
SE3 Util::createSE3(double ax, double ay, double az, double tx, double ty, double tz)
{
SE3 rx { Eigen::AngleAxisd(ax, Eigen::Vector3d(1, 0, 0)) };
SE3 ry { Eigen::AngleAxisd(ay, Eigen::Vector3d(0, 1, 0)) };
SE3 rz { Eigen::AngleAxisd(az, Eigen::Vector3d(0, 0, 1)) };
SE3 tl { Eigen::Translation3d(tx, ty, tz) };
return tl * rz * ry * rx;
}
double Util::degToRad(double deg)
{
return deg / 180.0 * M_PI;
}
double Util::radToDeg(double rad)
{
return rad * 180 / M_PI;
}
| true |
f78ea276c0272047be2fe746682ac6154f15b995 | C++ | chenjianlong/cpp-research | /diamond2.cpp | UTF-8 | 1,861 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class A
{
public:
int a_;
};
// class B: public A
class B: public virtual A
{
public:
int b_;
};
// class C: public A
class C: public virtual A
{
public:
int c_;
};
class D: public B, C
{
public:
int d_;
};
/*typedef void (*pfn)(A&a);
void dispaly(D &d)
{
cout << "dispaly: addr=" << hex << &d << endl;
cout << " d=" << dec << d.d_ << " a=" << d.a_ << endl;
}*/
int main(int, char *[])
{
// 菱形继承简析:
// 非虚继承时输出:
// sizeof(A)=4
// sizeof(B)=8 addr=0x7ffd38f05600
// sizeof(C)=8 addr=0x7ffd38f05608
// sizeof(D)=20 addr=0x7ffd38f05600
// 非虚继承时,有两份 A
// 虚继承时输出:
// sizeof(A)=4 addr=0x7ffc1571c430
// sizeof(B)=16 addr=0x7ffc1571c410
// sizeof(C)=16 addr=0x7ffc1571c420
// sizeof(D)=40 addr=0x7ffc1571c410
// 虚继承时,有一份 A,
// B C 各有一个指针指向 A
D d;
// cout << "sizeof(A)=" << sizeof(A) << " addr=" << hex << &(A&)d << endl;
//cout << "sizeof(A)=" << sizeof(A) << endl;
cout << "sizeof(B)=" << dec << sizeof(B) << " addr=" << hex << &(B&)d << endl;
cout << "sizeof(C)=" << dec << sizeof(C) << " addr=" << hex << &(C&)d << endl;
cout << "sizeof(D)=" << dec << sizeof(D) << " addr=" << hex << &d << endl;
// More Effective C++ 条款 31
// 以下代码在虚继承的情况下会崩溃
// sizeof(A)=4 addr=0x7ffe4b6c2f10
// sizeof(B)=16 addr=0x7ffe4b6c2ef0
// sizeof(C)=16 addr=0x7ffe4b6c2f00
// sizeof(D)=40 addr=0x7ffe4b6c2ef0
// dispaly: addr=0x7ffe4b6c2ef0
// d=0 a=1265381376
// dispaly: addr=0x7ffe4b6c2f10
// [1] 10659 segmentation fault (core dumped) ./a.out
/*dispaly(d);
pfn p = (pfn) dispaly;
p((B&) d);*/
return 0;
}
// vim: set et ts=4 sts=4 sw=4:
| true |
c406ca91a23adfeb3282a7c11d70a183acc745b3 | C++ | sabyrrakhim06/eyden-tracer-06 | /src/CameraTarget.h | UTF-8 | 629 | 2.9375 | 3 | [] | no_license | #pragma once
#include "CameraPerspective.h"
class CCameraTarget : public CCameraPerspective {
public:
// --- PUT YOUR CODE HERE ---
CCameraTarget(Size resolution, const Vec3f& pos, const Vec3f& target, const Vec3f& up, float angle) :
CCameraPerspective(resolution, pos, normalize(target - pos), up, angle) {
m_target = target;
}
virtual void setPosition(const Vec3f& pos) override {
m_pos = pos;
}
virtual void setTarget(const Vec3f target) {
m_target = target;
}
Vec3f getTarget(void) {
return m_target;
}
private:
Vec3f m_target; ///< Camera target point in WCS
Vec3f m_pos;
};
| true |
4eb0b477f5295a96ad3a23a6e1f31ed56b7ebe59 | C++ | chetan-anand/coding | /SUBGCD.cpp | UTF-8 | 435 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b)
{
int temp;
while(b)
{
int temp=a%b;
a=b;
b=temp;
}
return a;
}
int main()
{
int t,i,j,k;
cin>>t;
while(t--)
{
int n,a[110000],temp;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
temp=a[0];
for(i=1;i<n;i++)
{
temp=gcd(temp,a[i]);
if(temp==1)
{
cout<<n<<endl;
break;
}
}
if(temp!=1)
cout<<"-1"<<endl;
}
return 0;
}
| true |
5fc0fe4659fb0f67059dcc8b247d6fa665d5c9cd | C++ | Sparky384/FRC_2015 | /projects/config_reader/src/ConfigReader.h | UTF-8 | 644 | 2.9375 | 3 | [] | no_license | /*
* ConfigReader.h
*
* Singleton class for reading configuration file
*
*/
#ifndef CONFIGREADER_H_
#define CONFIGREADER_H_
#include <string>
#include <map>
using namespace std;
class ConfigReader {
public:
// make the implementation of this class a singleton
static ConfigReader* getInstance(string filename="config.txt");
~ConfigReader();
int getIntValue(string key);
float getFloatValue(string key);
string getStringValue(string key);
private:
ConfigReader(string filename="config.txt");
static ConfigReader* instance;
map<string, string>* keyValueMap;
};
#endif /* CONFIGREADER_H_ */
| true |
bafc8bc1379f80e90b73cc66a9005cfb75da9aaf | C++ | gregjesl/simpleson | /json.cpp | UTF-8 | 30,174 | 3.234375 | 3 | [
"MIT"
] | permissive | /*! \file json.cpp
* \brief Simpleson source file
*/
#include "json.h"
#include <string.h>
#include <assert.h>
/*! \brief Checks for an empty string
*
* @param str The string to check
* @return True if the string is empty, false if the string is not empty
* @warning The string must be null-terminated for this macro to work
*/
#define EMPTY_STRING(str) (*str == '\0')
/*! \brief Moves a pointer to the first character that is not white space
*
* @param str The pointer to move
*/
#define SKIP_WHITE_SPACE(str) { const char *next = json::parsing::tlws(str); str = next; }
/*! \brief Determines if the end character of serialized JSON is encountered
*
* @param obj The JSON object or array that is being written to
* @param index The pointer to the character to be checked
*/
#define END_CHARACTER_ENCOUNTERED(obj, index) (obj.is_array() ? *index == ']' : *index == '}')
/*! \brief Determines if the supplied character is a digit
*
* @param input The character to be tested
*/
#define IS_DIGIT(input) (input >= '0' && input <= '9')
/*! \brief Format used for integer to string conversion */
const char * INT_FORMAT = "%i";
/*! \brief Format used for unsigned integer to string conversion */
const char * UINT_FORMAT = "%u";
/*! \brief Format used for long integer to string conversion */
const char * LONG_FORMAT = "%li";
/*! \brief Format used for unsigned long integer to string conversion */
const char * ULONG_FORMAT = "%lu";
/*! \brief Format used for character to string conversion */
const char * CHAR_FORMAT = "%c";
/*! \brief Format used for floating-point number to string conversion */
const char * FLOAT_FORMAT = "%f";
/*! \brief Format used for double floating-opint number to string conversion */
const char * DOUBLE_FORMAT = "%lf";
const char* json::parsing::tlws(const char *input)
{
const char *output = input;
while(!EMPTY_STRING(output) && std::isspace(*output)) output++;
return output;
}
json::jtype::jtype json::jtype::peek(const char input)
{
switch (input)
{
case '[':
return json::jtype::jarray;
case '"':
return json::jtype::jstring;
case '{':
return json::jtype::jobject;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return json::jtype::jnumber;
case 't':
case 'f':
return json::jtype::jbool;
case 'n':
return json::jtype::jnull;
default:
return json::jtype::not_valid;
}
}
json::jtype::jtype json::jtype::detect(const char *input)
{
const char *start = json::parsing::tlws(input);
return json::jtype::peek(*start);
}
void json::reader::clear()
{
std::string::clear();
if(this->sub_reader != NULL) {
delete this->sub_reader;
this->sub_reader = NULL;
}
this->read_state = 0;
}
json::reader::push_result json::reader::push(const char next)
{
// Check for opening whitespace
if(this->length() == 0 && std::isspace(next)) return reader::ACCEPTED;
// Get the type
const json::jtype::jtype type = json::jtype::peek(this->length() > 0 ? this->front() : next);
// Store the return
reader::push_result result = reader::REJECTED;
#if DEBUG
const size_t start_length = this->length();
#endif
switch(type)
{
case json::jtype::jarray:
result = this->push_array(next);
break;
case json::jtype::jbool:
result = this->push_boolean(next);
assert(result != WHITESPACE);
break;
case json::jtype::jnull:
result = this->push_null(next);
assert(result != WHITESPACE);
break;
case json::jtype::jnumber:
result = this->push_number(next);
assert(result != WHITESPACE);
break;
case json::jtype::jobject:
result = this->push_object(next);
break;
case json::jtype::jstring:
result = this->push_string(next);
assert(result != WHITESPACE);
break;
case json::jtype::not_valid:
result = reader::REJECTED;
break;
}
// Verify the expected length change
#if DEBUG
if(result == ACCEPTED) assert(this->length() - start_length == 1);
else assert(this->length() == start_length);
#endif
// Return the result
return result;
}
bool json::reader::is_valid() const
{
switch (this->type())
{
case jtype::jarray:
return this->get_state<array_reader_enum>() == ARRAY_CLOSED;
case jtype::jbool:
if(this->length() < 4) return false;
if(this->length() == 4 && *this == "true") return true;
if(this->length() == 5 && *this == "false") return true;
return false;
case jtype::jnull:
return (this->length() == 4 && *this == "null");
case jtype::jnumber:
switch (this->get_state<number_reader_enum>())
{
case NUMBER_ZERO:
case NUMBER_INTEGER_DIGITS:
case NUMBER_FRACTION_DIGITS:
case NUMBER_EXPONENT_DIGITS:
return true;
default:
return false;
}
case jtype::jobject:
return this->get_state<object_reader_enum>() == OBJECT_CLOSED;
case jtype::jstring:
return this->get_state<string_reader_enum>() == STRING_CLOSED;
case jtype::not_valid:
return false;
}
throw std::logic_error("Unexpected return");
}
bool is_control_character(const char input)
{
switch (input)
{
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
case '"':
case '\\':
return true;
default:
return false;
}
}
bool is_hex_digit(const char input)
{
return IS_DIGIT(input) || (input >= 'a' && input <= 'f') || (input >= 'A' && input <= 'F');
}
json::reader::push_result json::reader::push_string(const char next)
{
const string_reader_enum state = this->get_state<string_reader_enum>();
switch (state)
{
case STRING_EMPTY:
assert(this->length() == 0);
if(next == '"') {
assert(this->length() == 0);
this->push_back(next);
this->set_state(STRING_OPENING_QUOTE);
return ACCEPTED;
}
return REJECTED;
case STRING_OPENING_QUOTE:
assert(this->length() == 1);
this->set_state(STRING_OPEN);
// Fall through deliberate
case STRING_OPEN:
assert(this->length() > 0);
switch (next)
{
case '\\':
this->set_state(STRING_ESCAPED);
break;
case '"':
this->set_state(STRING_CLOSED);
break;
default:
// No state change
break;
}
this->push_back(next);
return ACCEPTED;
case STRING_ESCAPED:
if(is_control_character(next)) {
this->set_state(STRING_OPEN);
this->push_back(next);
return ACCEPTED;
} else if(next == 'u') {
this->set_state(STRING_CODE_POINT_START);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case STRING_CODE_POINT_START:
assert(this->back() == 'u');
if(!is_hex_digit(next)) return REJECTED;
this->push_back(next);
this->set_state(STRING_CODE_POINT_1);
return ACCEPTED;
case STRING_CODE_POINT_1:
assert(is_hex_digit(this->back()));
if(!is_hex_digit(next)) return REJECTED;
this->push_back(next);
this->set_state(STRING_CODE_POINT_2);
return ACCEPTED;
case STRING_CODE_POINT_2:
assert(is_hex_digit(this->back()));
if(!is_hex_digit(next)) return REJECTED;
this->push_back(next);
this->set_state(STRING_CODE_POINT_3);
return ACCEPTED;
case STRING_CODE_POINT_3:
assert(is_hex_digit(this->back()));
if(!is_hex_digit(next)) return REJECTED;
this->push_back(next);
this->set_state(STRING_OPEN);
return ACCEPTED;
case STRING_CLOSED:
return REJECTED;
}
throw std::logic_error("Unexpected return");
}
json::reader::push_result json::reader::push_array(const char next)
{
const array_reader_enum state = this->get_state<array_reader_enum>();
switch (state)
{
case ARRAY_EMPTY:
assert(this->sub_reader == NULL);
if(next == '[') {
this->set_state(ARRAY_OPEN_BRACKET);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case ARRAY_OPEN_BRACKET:
assert(this->sub_reader == NULL);
if(std::isspace(next)) return WHITESPACE;
if(next == ']') {
this->set_state(ARRAY_CLOSED);
this->push_back(next);
return ACCEPTED;
}
begin_reading_value:
if(json::jtype::peek(next) == json::jtype::not_valid) return REJECTED;
this->sub_reader = new reader();
this->set_state(ARRAY_READING_VALUE);
// Fall-through deliberate
case ARRAY_READING_VALUE:
assert(this->sub_reader != NULL);
if(this->sub_reader->is_valid() && std::isspace(next)) return WHITESPACE;
switch (this->sub_reader->push(next))
{
case ACCEPTED:
return ACCEPTED;
case WHITESPACE:
return WHITESPACE;
case REJECTED:
switch (next)
{
case ']':
if(!this->sub_reader->is_valid()) return REJECTED;
this->append(this->sub_reader->readout());
delete this->sub_reader;
this->sub_reader = NULL;
this->push_back(next);
this->set_state(ARRAY_CLOSED);
return ACCEPTED;
case ',':
if(!this->sub_reader->is_valid()) return REJECTED;
this->append(this->sub_reader->readout());
delete this->sub_reader;
this->sub_reader = NULL;
this->push_back(next);
this->set_state(ARRAY_AWAITING_NEXT_LINE);
return ACCEPTED;
default:
return REJECTED;
}
}
// This point should not be reached
break;
case ARRAY_AWAITING_NEXT_LINE:
if(std::isspace(next)) return WHITESPACE;
goto begin_reading_value;
case ARRAY_CLOSED:
return REJECTED;
}
throw std::logic_error("Unexpected return");
}
json::reader::push_result json::reader::push_object(const char next)
{
const object_reader_enum state = this->get_state<object_reader_enum>();
switch (state)
{
case OBJECT_EMPTY:
assert(this->sub_reader == NULL);
if(next == '{') {
this->set_state(OBJECT_OPEN_BRACE);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case OBJECT_OPEN_BRACE:
assert(this->sub_reader == NULL);
if(next == '}') {
this->set_state(OBJECT_CLOSED);
this->push_back(next);
return ACCEPTED;
}
// Fall-through deliberate
case OBJECT_AWAITING_NEXT_LINE:
if(std::isspace(next)) return WHITESPACE;
if(next != '"') return REJECTED;
this->sub_reader = new kvp_reader();
#if DEBUG
assert(
#endif
this->sub_reader->push(next)
#if DEBUG
== ACCEPTED);
#else
;
#endif
this->set_state(OBJECT_READING_ENTRY);
return ACCEPTED;
case OBJECT_READING_ENTRY:
assert(this->sub_reader != NULL);
switch (this->sub_reader->push(next))
{
case ACCEPTED:
return ACCEPTED;
case WHITESPACE:
return WHITESPACE;
case REJECTED:
if(!this->sub_reader->is_valid()) return REJECTED;
if(std::isspace(next)) return WHITESPACE;
switch (next)
{
case '}':
this->append(this->sub_reader->readout());
delete this->sub_reader;
this->sub_reader = NULL;
this->push_back(next);
this->set_state(OBJECT_CLOSED);
return ACCEPTED;
case ',':
this->append(this->sub_reader->readout());
delete this->sub_reader;
this->sub_reader = NULL;
this->push_back(next);
this->set_state(OBJECT_AWAITING_NEXT_LINE);
return ACCEPTED;
default:
return REJECTED;
}
}
// This point should never be reached
break;
case OBJECT_CLOSED:
return REJECTED;
}
throw std::logic_error("Unexpected return");
}
json::reader::push_result json::reader::push_number(const char next)
{
const number_reader_enum state = this->get_state<number_reader_enum>();
switch (state)
{
case NUMBER_EMPTY:
assert(this->length() == 0);
if(next == '-') {
this->set_state(NUMBER_OPEN_NEGATIVE);
this->push_back(next);
return ACCEPTED;
} else if(IS_DIGIT(next)) {
this->set_state(next == '0' ? NUMBER_ZERO : NUMBER_INTEGER_DIGITS);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case NUMBER_OPEN_NEGATIVE:
if(IS_DIGIT(next)) {
this->set_state(next == '0' ? NUMBER_ZERO : NUMBER_INTEGER_DIGITS);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case NUMBER_INTEGER_DIGITS:
assert(IS_DIGIT(this->back()));
if(IS_DIGIT(next)) {
this->push_back(next);
return ACCEPTED;
}
// Fall-through deliberate
case NUMBER_ZERO:
switch (next)
{
case '.':
this->set_state(NUMBER_DECIMAL);
this->push_back(next);
return ACCEPTED;
case 'e':
case 'E':
this->set_state(NUMBER_EXPONENT);
this->push_back(next);
return ACCEPTED;
default:
return REJECTED;
}
case NUMBER_DECIMAL:
assert(this->back() == '.');
if(IS_DIGIT(next)) {
this->set_state(NUMBER_FRACTION_DIGITS);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case NUMBER_FRACTION_DIGITS:
assert(IS_DIGIT(this->back()));
if(IS_DIGIT(next)) {
this->push_back(next);
return ACCEPTED;
} else if(next == 'e' || next == 'E') {
this->set_state(NUMBER_EXPONENT);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case NUMBER_EXPONENT:
assert(this->back() == 'e' || this->back() == 'E');
if(next == '+' || next == '-') {
this->set_state(NUMBER_EXPONENT_SIGN);
this->push_back(next);
return ACCEPTED;
}
// Fall-through deliberate
case NUMBER_EXPONENT_SIGN:
case NUMBER_EXPONENT_DIGITS:
if(IS_DIGIT(next)) {
this->set_state(NUMBER_EXPONENT_DIGITS);
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
}
throw std::logic_error("Unexpected return");
}
json::reader::push_result json::reader::push_boolean(const char next)
{
const char *str_true = "true";
const char *str_false = "false";
const char *str = NULL;
if(this->length() == 0) {
switch (next)
{
case 't':
case 'f':
this->push_back(next);
return ACCEPTED;
default:
return REJECTED;
}
}
// Determine which string to use
switch (this->at(0))
{
case 't':
str = str_true;
break;
case 'f':
str = str_false;
break;
default:
throw json::parsing_error("Unexpected state");
}
assert(str == str_true || str == str_false);
// Push the value
if(this->length() < strlen(str) && str[this->length()] == next) {
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
}
json::reader::push_result json::reader::push_null(const char next)
{
switch (this->length())
{
case 0:
if(next == 'n') {
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case 1:
if(next == 'u') {
this->push_back(next);
return ACCEPTED;
}
return REJECTED;
case 2:
case 3:
if(next == 'l') {
this->push_back(next);
return ACCEPTED;
}
// Fall through
case 4:
return REJECTED;
default:
throw json::parsing_error("Unexpected state");
}
}
json::reader::push_result json::kvp_reader::push(const char next)
{
if(this->_key.length() == 0) {
if(std::isspace(next)) return WHITESPACE;
if(next == '"') {
this->_key.push(next);
assert(this->_key.type() == json::jtype::jstring);
assert(this->_key.length() == 1);
return ACCEPTED;
}
return REJECTED;
} else if (!this->_key.is_valid()) {
return this->_key.push(next);
}
// At this point the key should be valid
assert(this->_key.is_valid());
if(!this->_colon_read) {
if(std::isspace(next)) return WHITESPACE;
if(next == ':') {
this->_colon_read = true;
return ACCEPTED;
}
return REJECTED;
}
// At this point the colon should be read
assert(this->_colon_read);
// Check for a fresh start
if(reader::length() == 0 && std::isspace(next))
{
assert(reader::get_state<char>() == 0);
return WHITESPACE;
}
return reader::push(next);
}
std::string json::kvp_reader::readout() const
{
return this->_key.readout() + ":" + reader::readout();
}
std::string json::parsing::read_digits(const char *input)
{
// Trim leading white space
const char *index = json::parsing::tlws(input);
// Initialize the result
std::string result;
// Loop until all digits are read
while (
!EMPTY_STRING(index) &&
(
*index == '0' ||
*index == '1' ||
*index == '2' ||
*index == '3' ||
*index == '4' ||
*index == '5' ||
*index == '6' ||
*index == '7' ||
*index == '8' ||
*index == '9'
)
)
{
result += *index;
index++;
}
// Return the result
return result;
}
std::string json::parsing::decode_string(const char *input)
{
const char *index = input;
std::string result;
if(*index != '"') throw json::parsing_error("Expecting opening quote");
index++;
bool escaped = false;
// Loop until the end quote is found
while(!(!escaped && *index == '"'))
{
if(escaped)
{
switch (*index)
{
case '"':
case '\\':
case '/':
result += *index;
break;
case 'b':
result += '\b';
break;
case 'f':
result += '\f';
break;
case 'n':
result += '\n';
break;
case 'r':
result += '\r';
break;
case 't':
result += '\t';
break;
case 'u':
// #todo Unicode support
index += 4;
break;
default:
throw json::parsing_error("Expected control character");
}
escaped = false;
} else if(*index == '\\') {
escaped = true;
} else {
result += *index;
}
index++;
}
return result;
}
std::string json::parsing::encode_string(const char *input)
{
std::string result = "\"";
while (!EMPTY_STRING(input))
{
switch (*input)
{
case '"':
case '\\':
case '/':
result += "\\";
result += *input;
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
result += *input;
break;
}
input++;
}
result += '\"';
return result;
}
json::parsing::parse_results json::parsing::parse(const char *input)
{
// Strip white space
const char *index = json::parsing::tlws(input);
// Validate input
if (EMPTY_STRING(index)) throw json::parsing_error("Input was only whitespace");
// Initialize the output
json::parsing::parse_results result;
result.type = json::jtype::not_valid;
// Initialize the reader
json::reader stream;
// Iterate
while(!EMPTY_STRING(input) && stream.push(*index) != json::reader::REJECTED)
{
index++;
}
if(stream.is_valid()) {
result.value = stream.readout();
result.type = stream.type();
}
result.remainder = index;
return result;
}
std::vector<std::string> json::parsing::parse_array(const char *input)
{
// Initalize the result
std::vector<std::string> result;
const char *index = json::parsing::tlws(input);
if (*index != '[') throw json::parsing_error("Input was not an array");
index++;
SKIP_WHITE_SPACE(index);
if (*index == ']')
{
return result;
}
const char error[] = "Input was not properly formated";
while (!EMPTY_STRING(index))
{
SKIP_WHITE_SPACE(index);
json::parsing::parse_results parse_results = json::parsing::parse(index);
if (parse_results.type == json::jtype::not_valid) throw json::parsing_error(error);
if(parse_results.type == json::jtype::jstring) {
result.push_back(json::parsing::decode_string(parse_results.value.c_str()));
} else {
result.push_back(parse_results.value);
}
index = json::parsing::tlws(parse_results.remainder);
if (*index == ']') break;
if (*index == ',') index++;
}
if (*index != ']') throw json::parsing_error(error);
index++;
return result;
}
json::jobject::entry::operator int() const { return this->get_number<int>(INT_FORMAT); }
json::jobject::entry::operator unsigned int() const { return this->get_number<unsigned int>(UINT_FORMAT); }
json::jobject::entry::operator long() const { return this->get_number<long>(LONG_FORMAT); }
json::jobject::entry::operator unsigned long() const { return this->get_number<unsigned long>(ULONG_FORMAT); }
json::jobject::entry::operator char() const { return this->get_number<char>(CHAR_FORMAT); }
json::jobject::entry::operator float() const { return this->get_number<float>(FLOAT_FORMAT); }
json::jobject::entry::operator double() const { return this->get_number<double>(DOUBLE_FORMAT); }
json::jobject::entry::operator std::vector<int>() const { return this->get_number_array<int>(INT_FORMAT); }
json::jobject::entry::operator std::vector<unsigned int>() const { return this->get_number_array<unsigned int>(UINT_FORMAT); }
json::jobject::entry::operator std::vector<long>() const { return this->get_number_array<long>(LONG_FORMAT); }
json::jobject::entry::operator std::vector<unsigned long>() const { return this->get_number_array<unsigned long>(ULONG_FORMAT); }
json::jobject::entry::operator std::vector<char>() const { return this->get_number_array<char>(CHAR_FORMAT); }
json::jobject::entry::operator std::vector<float>() const { return this->get_number_array<float>(FLOAT_FORMAT); }
json::jobject::entry::operator std::vector<double>() const { return this->get_number_array<double>(DOUBLE_FORMAT); }
void json::jobject::proxy::set_array(const std::vector<std::string> &values, const bool wrap)
{
std::string value = "[";
for (size_t i = 0; i < values.size(); i++)
{
if (wrap) value += json::parsing::encode_string(values[i].c_str()) + ",";
else value += values[i] + ",";
}
if(values.size() > 0) value.erase(value.size() - 1, 1);
value += "]";
this->sink.set(key, value);
}
json::jobject json::jobject::parse(const char *input)
{
const char error[] = "Input is not a valid object";
const char *index = json::parsing::tlws(input);
json::jobject result;
json::reader stream;
switch (*index)
{
case '{':
// Result is already an object
break;
case '[':
result = json::jobject(true);
break;
default:
throw json::parsing_error(error);
break;
}
index++;
SKIP_WHITE_SPACE(index);
if (EMPTY_STRING(index)) throw json::parsing_error(error);
while (!EMPTY_STRING(index) && !END_CHARACTER_ENCOUNTERED(result, index))
{
// Get key
kvp entry;
if(!result.is_array()) {
json::parsing::parse_results key = json::parsing::parse(index);
if (key.type != json::jtype::jstring || key.value == "") throw json::parsing_error(error);
entry.first = json::parsing::decode_string(key.value.c_str());
index = key.remainder;
// Get value
SKIP_WHITE_SPACE(index);
if (*index != ':') throw json::parsing_error(error);
index++;
}
SKIP_WHITE_SPACE(index);
json::parsing::parse_results value = json::parsing::parse(index);
if (value.type == json::jtype::not_valid) throw json::parsing_error(error);
entry.second = value.value;
index = value.remainder;
// Clean up
SKIP_WHITE_SPACE(index);
if (*index != ',' && !END_CHARACTER_ENCOUNTERED(result, index)) throw json::parsing_error(error);
if (*index == ',') index++;
result += entry;
}
if (EMPTY_STRING(index) || !END_CHARACTER_ENCOUNTERED(result, index)) throw json::parsing_error(error);
index++;
return result;
}
json::key_list_t json::jobject::list_keys() const
{
// Initialize the result
key_list_t result;
// Return an empty list if the object is an array
if(this->is_array()) return result;
for(size_t i = 0; i < this->data.size(); i++)
{
result.push_back(this->data.at(i).first);
}
return result;
}
void json::jobject::set(const std::string &key, const std::string &value)
{
if(this->array_flag) throw json::invalid_key(key);
for (size_t i = 0; i < this->size(); i++)
{
if (this->data.at(i).first == key)
{
this->data.at(i).second = value;
return;
}
}
kvp entry;
entry.first = key;
entry.second = value;
this->data.push_back(entry);
}
void json::jobject::remove(const std::string &key)
{
for (size_t i = 0; i < this->size(); i++)
{
if (this->data.at(i).first == key)
{
this->remove(i);
}
}
}
json::jobject::operator std::string() const
{
if (is_array()) {
if (this->size() == 0) return "[]";
std::string result = "[";
for (size_t i = 0; i < this->size(); i++)
{
result += this->data.at(i).second + ",";
}
result.erase(result.size() - 1, 1);
result += "]";
return result;
} else {
if (this->size() == 0) return "{}";
std::string result = "{";
for (size_t i = 0; i < this->size(); i++)
{
result += json::parsing::encode_string(this->data.at(i).first.c_str()) + ":" + this->data.at(i).second + ",";
}
result.erase(result.size() - 1, 1);
result += "}";
return result;
}
}
std::string json::jobject::pretty(unsigned int indent_level) const
{
std::string result = "";
for(unsigned int i = 0; i < indent_level; i++) result += "\t";
if (is_array()) {
if(this->size() == 0) {
result += "[]";
return result;
}
result += "[\n";
for (size_t i = 0; i < this->size(); i++)
{
switch(json::jtype::peek(*this->data.at(i).second.c_str())) {
case json::jtype::jarray:
case json::jtype::jobject:
result += json::jobject::parse(this->data.at(i).second).pretty(indent_level + 1);
break;
default:
for(unsigned int j = 0; j < indent_level + 1; j++) result += "\t";
result += this->data.at(i).second;
break;
}
result += ",\n";
}
result.erase(result.size() - 2, 1);
for(unsigned int i = 0; i < indent_level; i++) result += "\t";
result += "]";
} else {
if(this->size() == 0) {
result += "{}";
return result;
}
result += "{\n";
for (size_t i = 0; i < this->size(); i++)
{
for(unsigned int j = 0; j < indent_level + 1; j++) result += "\t";
result += "\"" + this->data.at(i).first + "\": ";
switch(json::jtype::peek(*this->data.at(i).second.c_str())) {
case json::jtype::jarray:
case json::jtype::jobject:
result += std::string(json::parsing::tlws(json::jobject::parse(this->data.at(i).second).pretty(indent_level + 1).c_str()));
break;
default:
result += this->data.at(i).second;
break;
}
result += ",\n";
}
result.erase(result.size() - 2, 1);
for(unsigned int i = 0; i < indent_level; i++) result += "\t";
result += "}";
}
return result;
} | true |
fb7d8d753c8f2cb08bfab832f948c8d29654105b | C++ | jguillaumes/MeteoArduino | /clocks/MeteoClockRTC.cpp | UTF-8 | 2,225 | 2.859375 | 3 | [] | no_license | /*
* MeteoClockRTC.cpp
*
* Created on: Sep 25, 2018
* Author: jguillaumes
*/
#include <Arduino.h>
#include "MeteoClockRTC.h"
MeteoClockRTC::~MeteoClockRTC() {
RTC_DS3231 *rtc = (RTC_DS3231 *) _theRTC;
delete rtc;
_theRTC = NULL;
}
//+
// Constructor: creates a new RTC_DS3231 instance and stores a pointer
// to it as a private variable.
// The variable is stored as a void pointer so the header file does not
// have to #include the RTClib.h. If it did there would be name conflicts
// with the software clock
//-
MeteoClockRTC::MeteoClockRTC() {
RTC_DS3231 *rtc = new RTC_DS3231;
this->_theRTC = (void *) rtc;
}
//+
// Enable output of square waves at 1Hz to trigger
// interrupts
//-
void MeteoClockRTC::enableInterrupt() {
RTC_DS3231 *rtc = (RTC_DS3231 *) this->_theRTC;
rtc->begin();
rtc->writeSqwPinMode(DS3231_SquareWave1Hz);
}
//+
// Disable output of square waves
//-
void MeteoClockRTC::disableInterrupt() {
RTC_DS3231 *rtc = (RTC_DS3231 *) this->_theRTC;
rtc->begin();
rtc->writeSqwPinMode(DS3231_OFF);
}
//+
// Set (adjust) the clock using separate parameters for each
// date and time component.
// There is no formal checking done. If the combo is not correct the
// results are undefined.
//-
void MeteoClockRTC::setClock(int year, int month, int day,
int hour, int minute, int second){
DateTime dt(year, month, day, hour, minute, second);
((RTC_DS3231 *) this->_theRTC)->adjust(dt);
}
//+
// Get the current date and time as a YYYYMMDDhhmmss string
//-
String MeteoClockRTC::getClock() {
DateTime now;
char timbuf[15];
now = ((RTC_DS3231 *) this->_theRTC)->now();
sprintf(timbuf, "%04d%02d%02d%02d%02d%02d", now.year(), now.month(), now.day(),
now.hour(), now.minute(), now.second());
return String(timbuf);
}
DateTime MeteoClockRTC::getDateTime() {
return ((RTC_DS3231 *)this)->now();
}
//+
// Verify if the clock is physically present on the 2WI bus
// responds with consistent results.
//-
bool MeteoClockRTC::checkClock() {
bool rtcPresent;
RTC_DS3231 *rtc = (RTC_DS3231 *) _theRTC;
// rtc->begin();
if (rtc->now().year() > 2100) {
rtcPresent = false;
} else {
rtcPresent = true;
}
return rtcPresent;
}
| true |
1560082e1a63a26f435710fe2ce6cdffe41b0ee3 | C++ | sqwsummerwind/summer | /net/EventLoopThread.cc | UTF-8 | 920 | 2.546875 | 3 | [] | no_license | //2016.9.13
//qiangwei.su
//
#include <boost/bind.hpp>
#include "EventLoopThread.h"
#include "EventLoop.h"
using namespace summer;
using namespace summer::net;
EventLoopThread::EventLoopThread(const ThreadInitCallback& cb, const std::string& name)
:loop_(NULL),
mutex_(),
cond_(mutex_),
exiting_(false),
callback_(cb),
name_(name),
thread_(boost::bind(&EventLoopThread::threadFunc, this), name_)
{
}
EventLoopThread::~EventLoopThread()
{
exiting_ = true;
if(loop_)
{
loop_->quit();
thread_.join();
}
}
EventLoop* EventLoopThread::startLoop()
{
assert(!thread_.started());
thread_.start();
{
MutexLockGuard lock(mutex_);
while(loop_ == NULL)
{
cond_.wait();
}
}
return loop_;
}
void EventLoopThread::threadFunc()
{
EventLoop loop;
if(callback_)
{
callback_(&loop);
}
{
MutexLockGuard lock(mutex_);
loop_ = &loop;
cond_.notify();
}
loop.loop();
loop_ = NULL;
}
| true |
aecc5f3b932fcbf547613212f31fa0cc133e238e | C++ | rrivas-utec/Semana10 | /Ejercicio1.cpp | UTF-8 | 2,298 | 3.390625 | 3 | [] | no_license | // Librerias
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
// Namespaces
using namespace std;
// Crear clases contenidas
struct TLlanta
{
string marca;
string perfiles;
float radio;
float espesor;
};
struct TMotor
{
string marca;
string modelo;
float cilindrada;
float potencia;
float rpms;
};
struct TTimon
{
string marca;
float radio;
};
struct TAsiento
{
string material;
string color;
};
class CAuto
{
TMotor motor; // Relacion con ocurrencia 1 a 1
TTimon timon; // Relacion con ocurrencia 1 a 1
vector<TLlanta> listaLLantas; // Relacion con ocurrencia 1 a muchos
vector<TAsiento> listaAsientos; // Relacion con ocurrencia 1 a muchos
public:
CAuto()
{
// Crear 4 llantas
for (int i= 0; i < 4; i++)
listaLLantas.push_back({"Dunlop", "60", 17, 10});
// Crear 5 Asientos
for (int i= 0; i < 5; i++)
listaAsientos.push_back({"Cuero", "Negro"});
// Definimos el timon
timon.marca = "Mono";
timon.modelo = "Deportivo";
// Definimos el Motor
motor.marca = "Roll Royce";
motor.modelo = "V8";
motor.rpms = 6000;
motor.potencia = 300;
motor.cilindrada = 4000;
}
CAuto(int nLlantas, int nAsientos, TTimon timon, TMotor motor)
{
// Crear n llantas
for (int i= 0; i < nLlantas; i++)
listaLLantas.push_back({"Dunlop", "60", 17, 10});
// Crear n Asientos
for (int i= 0; i < nAsientos; i++)
listaAsientos.push_back({"Cuero", "Negro"});
// Definimos el timon
this->timon = timon;
// Definimos el Motor
this->motor = motor;
}
};
// Programa Principal
int main ()
{
CAuto estandar; // 4 Ruedas, 5 Asientos, Timon, Motor
TTimon timon;
timon.marca = "Pegaso";
timon.modelo = "Deportivo";
TMotor motor;
motor.marca = "Ferrari";
motor.modelo = "V8";
motor.rpms = 6000;
motor.potencia = 500;
motor.cilindrada = 6000;
CAuto personalizado (4, 2, timon, motor);
return 0;
} | true |
9e7d21e85ab62e032d2185f6f78c2e2847e986bd | C++ | nish-works/DSA-Probs-Sols | /bitwise/power_set_using_bitwise.cpp | UTF-8 | 588 | 3.015625 | 3 | [] | no_license |
#include <bits/stdc++.h>
using namespace std;
// Efficient solution: TC: Theta(2^n * n)
void solve(string s)
{
int sLength = s.length();
int powerSetSize = pow(2, sLength);
for (int counter = 0; counter < powerSetSize; counter++)
{
for (int j = 0; j < sLength; j++)
{
if ((counter & (1 << j)) != 0)
cout << s[j];
}
cout << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(0); // fast IO
cin.tie(0);
cout.tie(0);
string s;
cin >> s;
vector<string> v;
solve(s);
return 0;
}
| true |
48e9259c9b85f4be6e217d2daabd3c29c9db2719 | C++ | momja/CPU-Raytracer | /GFX/Scene/Primitives/Cylinder.h | UTF-8 | 878 | 3.015625 | 3 | [] | no_license | //
// Created by Maxwell James Omdal on 2/10/20.
//
#ifndef RAYCASTER_CYLINDER_H
#define RAYCASTER_CYLINDER_H
#include "Primitive.h"
#include "../../Color.h"
class Cylinder: public Primitive {
public:
float radius;
Point3D center;
Vector3D orientation;
float height;
// Default Constructor
Cylinder() :
radius(1),
center(Point3D(0,0,0)),
orientation(Vector3D(0,0,1)),
height(1) {
}
// Constructor
Cylinder(const Point3D& center, Vector3D orientation, const float radius, const float height) :
radius(radius),
center(center),
orientation(orientation.normal()),
height(height){
}
float rayIntersects(Ray3D ray) override;
Vector3D normalAtPoint(Point3D point) override;
Color colorAtPoint(const Point3D& point) override;
};
#endif //RAYCASTER_CYLINDER_H
| true |
b4c1a554a4bfbf315fd922f3ff262f43d6b41cb6 | C++ | byu-cpe/ecen629_student | /partitioner/src/partitioner_main.cpp | UTF-8 | 1,529 | 2.921875 | 3 | [] | no_license | #include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "Block.h"
#include "Chromosome.h"
#include "Design.h"
#include "Net.h"
#include "utils.h"
int main(int argc, char **argv) {
if (argc != 3) {
printf("Usage: ./partitioner circuit_file seed\n");
exit(-1);
}
// Seed RNG
int rng_seed = std::stoi(argv[2]);
Design design(rng_seed);
// Open circuit file
std::string filePath(argv[1]);
std::ifstream fp(filePath);
assert(fp.good());
std::string line;
int idx = 1;
while (true) {
if (!std::getline(fp, line))
break;
std::vector<std::string> words = split(line, ' ');
auto wordIter = words.begin();
Block *block = design.addBlock(idx++);
wordIter++;
for (; wordIter != words.end(); wordIter++) {
int idx = std::stoi(*wordIter);
Net *net = design.getOrCreateNet(idx);
block->addNet(net);
net->addBlock(block);
}
}
printf("Num blocks: %d\n", design.getNumBlocks());
printf("Num nets : %d\n", design.getNumNets());
GeneticPartitioner partitioner(design);
Chromosome *best = partitioner.getBestInPopulation();
printf("Random population best solution cost: %d\n", best->getCost());
design.genGraph(best, "initial");
partitioner.run();
best = partitioner.getBestInPopulation();
best->recalcCutCost();
printf("Solution is balanced: %s\n", best->isBalanced() ? "true" : "false");
printf("Solution cost: %d\n", best->getCost());
design.genGraph(best, "final");
}
| true |
689ee11bbbaf267536c5d220796fd39d08c88a06 | C++ | AhmedMahmoud129/- | /QUESTION 1/QUESTION 1/QUESTION 1.cpp | UTF-8 | 748 | 3.484375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float year, month = 0, i, sum = 0, max = 0, mini = 9999999999;
for (year = 1; year <= 10; year++)
{
for (i = 1; i <= 12; i++)
{
cout << "Enter the month earning";
cin >> month;
if (month > max)
{
max = month;
}
if (month < mini)
{
mini = month;
}
sum = sum + month;
}
cout << "The sum is " << sum << endl;
cout << "The avg is" << sum / 12 << endl;
cout << "The max is" << max << endl;
cout << "The mini is" << mini << endl;
}
return 0;
}
| true |
626b6ff016ce2ae0347634713db137df0771ebab | C++ | Ermelber/KMP-Tools | /AbstractKMP/Area.cpp | UTF-8 | 802 | 2.6875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Area.cpp
* Author: Ermii
*
* Created on 25 settembre 2016, 15.31
*/
#include "Area.h"
Area::Area(AreaPoint* area) {
nr_entries = area->nr_entries;
if (nr_entries==0) return;
entries = new areaentry_t[nr_entries];
for (int i=0;i<nr_entries;i++)
entries[i] = *area->entries[i];
}
AreaPoint* Area::ToAREA()
{
AreaPoint* area = new AreaPoint();
area->nr_entries = nr_entries;
if (nr_entries>0)
{
area->entries = new areaentry_t*[nr_entries];
for (int i=0;i<nr_entries;i++)
area->entries[i] = &entries[i];
}
return area;
} | true |
fe9b3e792b9b9722b2a03c407cb24b6fdeb27c19 | C++ | jdtuck/fdasrvf_MATLAB | /gropt/Manifolds/Stiefel/StieVector.h | UTF-8 | 772 | 3.046875 | 3 | [] | no_license | /*
This file defines the class of a point on the tangent space of the Stiefel manifold \St(p, n) = \{X \in R^{n \times p} | X^T X = I_p\}
SmartSpace --> Element --> StieVector
---- WH
*/
#ifndef STIEVECTOR_H
#define STIEVECTOR_H
#include "Manifolds/Element.h"
#include <new>
#include <iostream>
#include "Others/def.h"
/*Define the namespace*/
namespace ROPTLIB{
class StieVector : public Element{
public:
/*Construct an empty vector on the tangent space of Stiefel manifold St(p, n) with only size information. */
StieVector(integer n, integer p = 1, integer num = 1);
/*Create an object of StieVector with same size as this StieVector.*/
virtual StieVector *ConstructEmpty(void) const;
};
}; /*end of ROPTLIB namespace*/
#endif // end of STIEVECTOR_H
| true |