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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27907750117514dc581e036f484bfa867ca2ca93 | C++ | bridgeQiao/STLite | /src/stlite/jw_list.hpp | UTF-8 | 7,052 | 3.25 | 3 | [] | no_license | #pragma once
#include "jw_iterator.hpp"
#include "jw_alloc.hpp"
#include "jw_construct.hpp"
namespace jw {
// list node
template<typename T>
struct __list_node
{
__list_node<T>* prev;
__list_node<T>* next;
T data;
};
// iterator
template<typename T, typename Ref, typename Ptr>
struct __list_iterator
{
using link_type = __list_node<T>*;
using iterator = __list_iterator<T, T&, T*>;
using const_iterator = __list_iterator<T, const T&, const T*>;
using Self = __list_iterator<T, Ref, Ptr>;
using value_type = T;
using pointer = Ptr;
using reference = Ref;
using iterator_category = bidirectional_iterator_tag;
using size_type = size_t;
using differcen_type = ptrdiff_t;
void incr() { node = node->next; }
void decr() { node = node->prev; }
__list_iterator(link_type position) : node(position) {}
// look like POD's pointer
reference operator*() const { return node->data; }
pointer operator->() const { return &(operator*()); }
bool operator==(const Self& rhs) const { return this->node == rhs.node; }
bool operator!=(const Self& rhs) const { return this->node != rhs.node; }
Self& operator++() {
incr();
return *this;
}
Self operator++(int) {
Self tmp = *this;
incr();
return tmp;
}
Self& operator--() {
decr();
return *this;
}
Self operator--(int) {
Self tmp = *this;
decr();
return *this;
}
// data member
link_type node;
};
template<typename T, typename Alloc = alloc>
class list {
protected:
using list_node = __list_node<T>;
using list_node_allocator = simple_alloc<list_node, alloc>;
public:
using link_type = __list_node<T>*;
using iterator = __list_iterator<T, T&, T*>;
using const_iterator = __list_iterator<T, const T&, const T*>;
using value_type = T;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = size_t;
using difference_type = ptrdiff_t;
protected:
link_type get_node() { return list_node_allocator::allocate(1); }
void put_node(link_type p) { list_node_allocator::deallocate(p); }
link_type create_node(const T& x) {
link_type result = get_node();
construct(&(result->data), x);
return result;
}
void destroy_node(link_type p) {
destroy(&(p->data));
put_node(p);
}
void empty_initialize() {
node = get_node();
node->next = node;
node->prev = node;
}
void range_initialize(const_pointer first, const_pointer last) {
empty_initialize();
const_pointer tmp = first;
while (tmp != last) {
insert(end(), *tmp);
++tmp;
}
}
void transfer(iterator position, iterator first, iterator last) {
if (position != last) {
// process the iterators' prev node
position.node->prev->next = first.node;
first.node->prev->next = last.node;
last.node->prev->next = position.node;
// process the iterators' node
link_type pos_prev = position.node->prev;
position.node->prev = last.node->prev;
last.node->prev = first.node->prev;
first.node->prev = pos_prev;
}
}
public:
// construct
list() {
empty_initialize();
}
list(const_pointer first, const_pointer last) {
range_initialize(first, last);
}
list(std::initializer_list<T> x) {
range_initialize(x.begin(), x.end());
}
~list()
{
clear();
destroy_node(node);
}
iterator begin() { return node->next; }
const_iterator begin() const { return node->next; }
iterator end() { return node; }
const_iterator end() const { return node; }
bool empty() const { return begin() == end(); }
size_type size() const {
size_type count = 0;
const_iterator current(node->next);
while (current != end())
{
++current;
++count;
}
return count;
}
void clear();
reference front() { return *begin(); }
const_reference front() const { return *begin(); }
reference back() { return *(--end()); }
const_reference back() const { return node->prev->data; }
void insert(iterator position, const T& x) {
link_type new_node = create_node(x);
new_node->next = position.node;
new_node->prev = position.node->prev;
position.node->prev->next = new_node;
position.node->prev = new_node;
}
iterator erase(iterator position) {
link_type prev_link = position.node->prev;
link_type next_link = position.node->next;
prev_link->next = next_link;
next_link->prev = prev_link;
destroy_node(position.node);
return iterator(next_link);
}
void push_front(const T& x) {
insert(begin(), x);
}
void push_back(const T& x) {
insert(end(), x);
}
void pop_front() {
erase(begin());
}
void pop_back() {
iterator tmp = end();
erase(--tmp);
}
void remove(const T& x);
void splice(iterator position, list& x) {
if (!x.empty())
transfer(position, x.begin(), x.end());
}
void splice(iterator position, list& x, iterator i) {
iterator j = i;
++j;
if (i == position || j == position) return;
transfer(position, i, j);
}
void merge(list& x);
void reverse();
void swap(list& x) { std::swap(node, x.node); }
void sort();
protected:
link_type node;
};
template<typename T, typename Alloc>
void list<T, Alloc>::clear()
{
link_type cnt = node->next;
link_type tmp = cnt;
while (cnt != node) {
tmp = cnt;
destroy_node(tmp);
cnt = cnt->next;
}
}
template<typename T, typename Alloc>
void list<T, Alloc>::remove(const T& x) {
iterator cnt = begin();
iterator iend = end();
while (cnt != iend) {
if (*cnt == x)
cnt = erase(cnt);
++cnt;
}
}
template<typename T, typename Alloc>
void list<T, Alloc>::merge(list& x)
{
iterator first1 = begin();
iterator last1 = end();
iterator first2 = x.begin();
iterator last2 = x.end();
// insert x to self. x and self have been sorted in ascending order
while (first1 != last1 && first2 != last2)
{
if (*first2 < *first1) {
iterator next = first2;
transfer(first1, first2, ++next);
first2 = next;
}
else
++first1;
}
// if x left any node
if (first2 != last2) transfer(last1, first2, last2);
}
template<typename T, typename Alloc>
void list<T, Alloc>::reverse()
{
// size == 0 || size == 1
if (node->next == node || node->next->next == node)
return;
// size >= 2
iterator first = begin();
++first;
while (first != end())
{
iterator old = first;
++first;
transfer(begin(), old, first);
}
}
template<typename T, typename Alloc>
void list<T, Alloc>::sort() {
if (node->next == node || node->next->next == node)
return;
// tmp obj
list<T, Alloc> carry;
list<T, Alloc> counter[64];
int fill = 0;
while (!empty()) {
carry.splice(carry.begin(), *this, begin());
int i = 0;
while (i<fill && !counter[i].empty())
{
counter[i].merge(carry);
carry.swap(counter[i++]);
}
carry.swap(counter[i]);
if (i == fill) ++fill;
}
for (int i = 1; i < fill; ++i)
counter[i].merge(counter[i - 1]);
swap(counter[fill - 1]);
}
} | true |
e342a0339ea5e2c29b6b7cb8420c187da328fd87 | C++ | Hee-Jae/Algorithm | /boj/2263.cpp | UTF-8 | 1,042 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int in[100001]={}, inPos[100001]={};
int post[100001]={};
void make_tree(int in_start, int in_end, int post_start, int post_end){
if(in_start > in_end) return;
if(post_start > post_end) return;
else{
cout << post[post_end] << " ";
int root = inPos[post[post_end]];
// cout << node*2 << " " << in_start << " " << root-1 << " " << post_start << " " << post_start+root-1-in_start << "\n";
// cout << node*2+1 << " " << root+1 << " " << in_end << " " << post_start+root-in_start << " " << post_end-1 << "\n";
// cout << node << " " << in_start << " " << in_end << " " << post_start << " " << post_end << "\n";
make_tree(in_start, root-1, post_start, post_start+root-1-in_start);
make_tree(root+1, in_end, post_start+root-in_start, post_end-1);
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i=0; i<n; i++){
cin >> in[i];
inPos[in[i]] = i;
}
for(int i=0; i<n; i++){
cin >> post[i];
}
make_tree(0,n-1,0,n-1);
} | true |
4f5071f75f871850fd4ce5c2a803f4ea404eeabf | C++ | Petru98/Minesweeper | /src/MenuBar.cpp | UTF-8 | 4,737 | 2.78125 | 3 | [] | no_license | #include "MenuBar.hpp"
#include "textures.hpp"
const sf::Vector2f MenuBar::MENU_BUTTON_OFFSET = {6.0f, 4.0f};
void MenuBar::draw(sf::RenderTarget& target, sf::RenderStates states)const
{
states.transform.combine(this->getTransform());
target.draw(m_background, states);
for(std::size_t i = 0; i < m_menus_count; ++i)
target.draw(m_menus[i]->button, states);
if(m_open_menu != nullptr)
target.draw(*m_open_menu, states);
}
MenuBar::MenuBar() : m_background(), m_next_position(this->MENU_BUTTON_OFFSET), m_menus_count(0),
m_open_menu(nullptr), m_pressed_menu(nullptr)
{
m_background.setFillColor(sf::Color(236, 233, 216));
m_background.setOutlineThickness(-1.0f);
m_background.setOutlineColor(sf::Color(192, 192, 192));
}
MenuBar::~MenuBar()
{}
void MenuBar::addMenu(Menu& menu)
{
m_menus[m_menus_count] = &menu;
++m_menus_count;
menu.setPosition(0.0f, this->HEIGHT);
menu.button.setPosition(m_next_position);
m_next_position += menu.button.getSize() + this->MENU_BUTTON_OFFSET;
}
void MenuBar::closeMenu()
{
if(m_open_menu != nullptr)
{
m_open_menu->close();
m_open_menu = nullptr;
}
}
Menu* MenuBar::openMenu(Menu* menu)
{
this->closeMenu();
m_open_menu = menu;
if(m_open_menu != nullptr)
m_open_menu->open();
return m_open_menu;
}
Menu* MenuBar::openMenu(const float x, const float y)
{
Menu* menu = getMenu(x,y);
return this->openMenu(menu);
}
Menu* MenuBar::getMenu(const float x, const float y)const
{
if(m_menus_count == 0 || x < this->MENU_BUTTON_OFFSET.x || x >= m_next_position.x ||
y < this->MENU_BUTTON_OFFSET.y || y >= this->MENU_BUTTON_OFFSET.y + (*m_menus)->getSize().y)
return nullptr;
for(std::size_t i = 0; i < m_menus_count; ++i)
{
const float current_position_x = m_menus[i]->button.getPosition().x;
if(current_position_x > x)
break;
if(current_position_x + m_menus[i]->button.getSize().x > x)
return m_menus[i];
}
return nullptr;
}
Menu* MenuBar::getOpenMenu()const
{
return m_open_menu;
}
void MenuBar::setSize(const float width, const float height)
{
m_background.setSize(sf::Vector2f(width, height));
}
void MenuBar::setSize(const sf::Vector2f size)
{
m_background.setSize(size);
}
sf::Vector2f MenuBar::getSize()const
{
return m_background.getSize();
}
/* Events */
void MenuBar::handleEvent(const sf::Event& event)
{
if(m_open_menu == nullptr)
Scene::handleEvent(event);
else
{
if(event.type != sf::Event::MouseButtonPressed && event.type != sf::Event::MouseButtonReleased)
M_forwardEvent(event);
else
{
if(m_open_menu->contains(event.mouseButton.x, event.mouseButton.y) == true)
M_forwardEvent(event);
else if(this->contains(event.mouseButton.x, event.mouseButton.y) == true)
Scene::handleEvent(event);
else
this->closeMenu();
}
}
}
void MenuBar::M_forwardEvent(const sf::Event& event)
{
m_open_menu->handleEvent(event);
if(m_open_menu->isOpen() == false)
m_open_menu = nullptr;
}
void MenuBar::onClosed() {}
void MenuBar::onResized(const sf::Event::SizeEvent& event) {}
void MenuBar::onLostFocus() {}
void MenuBar::onGainedFocus() {}
void MenuBar::onTextEntered(const sf::Event::TextEvent& event) {}
void MenuBar::onKeyPressed(const sf::Event::KeyEvent& event) {}
void MenuBar::onKeyReleased(const sf::Event::KeyEvent& event) {}
void MenuBar::onMouseWheelScrolled(const sf::Event::MouseWheelScrollEvent& event) {}
void MenuBar::onMouseButtonPressed(const sf::Event::MouseButtonEvent& event)
{
Menu* menu = getMenu(event.x, event.y);
if(menu != nullptr)
{
m_pressed_menu = menu;
m_pressed_menu->button.press();
}
}
void MenuBar::onMouseButtonReleased(const sf::Event::MouseButtonEvent& event)
{
if(m_pressed_menu == nullptr)
this->closeMenu();
else
{
m_pressed_menu->button.release();
if(m_pressed_menu != m_open_menu)
this->openMenu(m_pressed_menu);
else
this->closeMenu();
m_pressed_menu = nullptr;
}
}
void MenuBar::onMouseMoved(const sf::Event::MouseMoveEvent& event)
{
if(m_pressed_menu != nullptr && m_pressed_menu->button.contains(event.x, event.y) == false)
m_pressed_menu = nullptr;
}
void MenuBar::onMouseEntered() {}
void MenuBar::onMouseLeft() {}
| true |
df0cb8d58db13425c04e4d73483e30f5d7259c65 | C++ | JohN-D/Info-2-Praktikum | /Praktikum Info2/Aufgabenblock_1/PKW.h | UTF-8 | 819 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Fahrzeug.h"
#include <string>
using namespace std;
class PKW : public Fahrzeug
{
public:
PKW(void) : Fahrzeug() {};
PKW(string sName) : Fahrzeug(sName) {};
PKW(string sName, double dMaxGeschwindigkeit) : Fahrzeug(sName, dMaxGeschwindigkeit) {};
PKW(string sName, double dMaxGeschwindigkeit, double dVerbrauch, double dTankvolumen = 55);
PKW(const PKW& objekt);
virtual ~PKW(void);
virtual void vAusgabe(void);
virtual void vAbfertigung(void);
double dTanken(double dMenge=0.0);
double dVerbrauch();
virtual double p_dGeschwindigkeit(void);
ostream& ostreamAusgabe(ostream& Ausgabe);
virtual PKW& operator=(PKW& objekt);
protected:
virtual void vInitialisierung(void);
private:
double p_dVerbrauch;
double p_dTankinhalt;
double p_dTankvolumen;
}; | true |
74ad1b61d77c0d721f63969fafe3d531034c5e6d | C++ | lxpzh/leetcode-solutions | /260. Single Number III.cpp | UTF-8 | 616 | 2.953125 | 3 | [] | no_license | class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
unordered_map<int, int> m;
for (auto const& num : nums) {
auto iter = m.find(num);
if (iter == m.end()) {
m.insert({num, 1});
} else {
++iter->second;
}
}
vector<int> result;
for (auto const& num : nums) {
if (m[num] == 1) {
result.push_back(num);
}
}
return result;
return nums;
}
}; | true |
d45c1275b73d91c40582a74b50b41cfb6b30f8fc | C++ | tiandada/Cpp_Primer_Notes | /code/9.52.cpp | UTF-8 | 509 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <string>
using std::cout;
using std::endl;
using std::stack;
using std::string;
int main()
{
string str("s = (1+1)");
stack<char> stk;
bool spush = false;
for (auto const &i : str)
{
if(i == '(')
{
spush = true;
continue;
}
if(i == ')')
spush = false;
if(spush)
stk.push(i);
}
string rep;
while(!stk.empty())
{
rep += stk.top();
stk.pop();
}
str.replace(str.find("(")+1, rep.size(), rep);
cout << str << endl;
return 0;
}
| true |
60c95bd494cf35e6be4bd725b0bfa09ee82e28b3 | C++ | ZishanHuang/cracking_the_coding_interview | /Ch 8 Recursion and Dynamic Programming/8_3_magicIndex/8_3_magicIndex.cpp | UTF-8 | 2,189 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int magicIndex(const vector<int> & arr){
for(int i=0; i<arr.size(); i++){
if(arr[i] == i) return i;
}
return -1;
}
int magicIndex2(const vector<int> & arr){
int low = 0;
int high = arr.size()-1;
while(true){
if(arr[low] == low) return low;
if(arr[high] == high) return high;
if(low == high){
if(arr[low] == low) return low;
break;
}
if(arr[low] > low){
low = arr[low];
}
if(arr[high] < high){
high = arr[high];
}
int mid = (low + high) / 2;
if(arr[mid] == mid){
return mid;
}
else if(arr[mid] > mid){
high = mid;
}
else{ // arr[mid] < mid
low = mid;
}
}
return -1;
}
// book's solution rewritten by me in iterative method
int magicIndexSolution(const vector<int> & arr){
int low = 0;
int high = arr.size()-1;
while(true){
if(low > high){
return -1;
}
int mid = (low + high) / 2;
if(arr[mid] == mid){
return mid;
}
else if(arr[mid] > mid){
high = mid - 1;
}
else{ // arr[mid] < mid
low = mid + 1;
}
}
// return -1;
}
// book's solution (elements in array sorted and distinct)
int magicIndexSolution2(const vector<int> & arr, int low, int high){
if(low > high){
return -1;
}
int mid = (low + high) / 2;
if(arr[mid] == mid){
return mid;
}
else if(arr[mid] > mid){
return magicIndexSolution2(arr, low, mid-1);
}
else{ // arr[mid] < mid
return magicIndexSolution2(arr, mid+1, high);
}
}
// book's solution (elements in array sorted, not distinct)
int magicIndexSolutionNotDistinct2(const vector<int> & arr, int low, int high){
if(low > high){
return -1;
}
int mid = (low + high) / 2;
if(arr[mid] == mid){
return mid;
}
// search left
int leftIndex = min(mid-1, arr[mid]);
int left = magicIndexSolution2(arr, low, leftIndex);
if(left > 0){
return left;
}
int rightIndex = max(mid+1, arr[mid]);
int right = magicIndexSolution2(arr, rightIndex, high);
return right;
}
int main(){
vector<int> arr;
int n;
cin >> n;
for(int i=0; i<n;i++){
int tmp;
cin >> tmp;
arr.push_back(tmp);
}
cout << "magic index: " << magicIndex(arr) <<endl;
cout << "magic index: " << magicIndex2(arr) <<endl;
} | true |
518c75139ff8ccaf25053a85b1eab31e0ae7785d | C++ | MaSteve/UVA-problems | /UVA00374.cpp | UTF-8 | 387 | 2.953125 | 3 | [
"MIT"
] | permissive | #include <cstdio>
using namespace std;
long long power(long long b, long long e, long long mod) {
if (e == 0) return 1%mod;
if (e == 1) return b%mod;
long long aux = power(b, e/2, mod);
aux = (aux*aux)%mod;
if (e%2) aux = (aux*(b%mod))%mod;
return aux;
}
int main() {
int b, p, m;
while (scanf("%d %d %d", &b, &p, &m) == 3) {
printf("%lld\n", power(b, p, m));
}
return 0;
} | true |
91da3d22550ea005d4aeb7d1fd0ba019604fbbca | C++ | potal/miku_server | /common/auto_lock.h | UTF-8 | 626 | 2.640625 | 3 | [] | no_license | #ifndef AUTO_LOCK_H_
#define AUTO_LOCK_H_
#ifdef _WIN32
#include <Windows.h>
#else
#include <pthread.h>
#endif
class AutoLock
{
private:
#ifdef _WIN32
CRITICAL_SECTION *auto_lock_ptr_;
#else
pthread_mutex_t *auto_lock_ptr_;
#endif
public:
#ifdef _WIN32
AutoLock(CRITICAL_SECTION * lock_ptr)
{
auto_lock_ptr_ = lock_ptr;
EnterCriticalSection(auto_lock_ptr_);
}
~AutoLock()
{
LeaveCriticalSection(auto_lock_ptr_);
}
#else
AutoLock(pthread_mutex_t * mutex_t)
{
auto_lock_ptr_ = mutex_t;
pthread_mutex_lock(auto_lock_ptr_);
}
~AutoLock()
{
pthread_mutex_unlock(auto_lock_ptr_);
}
#endif
};
#endif
| true |
dd7eb541d8699ea913b7d102574ff05cf47eee8f | C++ | stackCuiBin/DataStructure | /project/DTLib/inc/SmartPointer.h | UTF-8 | 944 | 2.796875 | 3 | [] | no_license | /*
* @Descripttion:
* @version: V0.01
* @Author: Cuibb
* @Date: 2019-07-30 01:00:26
* @LastEditors: Cuibb
* @LastEditTime: 2021-07-09 00:42:48
*/
#ifndef SMARTPOINTER_H
#define SMARTPOINTER_H
#include "Pointer.h"
namespace DTLib
{
template < typename T >
class SmartPointer : public Pointer<T>
{
public:
SmartPointer(T* p = NULL) : Pointer<T>(p) { }
SmartPointer(const SmartPointer<T>& obj)
{
this->m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
}
SmartPointer<T>& operator = (const SmartPointer<T>& obj)
{
if(this != &obj)
{
T* temp = this->m_pointer;
this->m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
delete temp;
}
return *this;
}
~SmartPointer()
{
delete this->m_pointer;
}
};
}
#endif // SMARTPOINTER_H
| true |
810f4a2816bb3934ad276d9a50c5701e38882570 | C++ | ElTangoBandito/Asteroids | /Asteroids/Explosion.cpp | UTF-8 | 1,484 | 2.765625 | 3 | [] | no_license | #include "Explosion.h"
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Main.hpp>
#include <iostream>
Explosion::Explosion(sf::Vector2f positionIn, int typeIn) {
this->position = positionIn;
this->type = typeIn;
this->explosionColor = sf::Color(rand() % 256, rand() % 256, rand() % 256, 125);
this->radius = 1.0f;
switch (this->type) {
case 0:
this->life = 60;
this->radiusIncreaseRate = 0.1;
break;
case 1:
this->life = 30;
this->radiusIncreaseRate = 0.13;
break;
case 2:
this->life = 15;
this->radiusIncreaseRate = 0.15;
break;
case 3:
this->life = rand() % 30 + 40;
this->radiusIncreaseRate = rand() % 15 * 0.01;
break;
}
updateOrigin();
}
Explosion::~Explosion() {}
void Explosion::updateOrigin() {
this->origin.x = this->position.x + this->radius;
this->origin.y = this->position.y + this->radius;
}
void Explosion::update(float deltaTime) {
//this->explosionColor = sf::Color(rand() % 256, rand() % 256, rand() % 256, 125);
this->radius += this->radiusIncreaseRate * deltaTime;
this->life--;
updateOrigin();
}
void Explosion::draw(sf::RenderWindow* windowIn) {
sf::CircleShape c(this->radius);
c.setPosition(this->origin);
c.setOrigin(this->radius*2, this->radius*2);
c.setFillColor(sf::Color(255,255,255,0));
c.setOutlineColor(this->explosionColor);
c.setOutlineThickness(2);
windowIn->draw(c);
} | true |
8a33fe2fd2bec6ba7a5a879b8f5fa3b3933cb182 | C++ | shivamkaushik12007/practice | /apc/atoi.cpp | UTF-8 | 718 | 2.515625 | 3 | [] | no_license |
int Solution::atoi(const string A) {
int n=A.size();
int i=0;
while(A[i]==' '){
i++;
}
int cm=1;
if(A[i]=='-'||A[i]=='+'){
cm=A[i]=='+'?1:1;
cm=A[i]=='-'?-1:1;
i++;
}
if(A[i]<'0'||A[i]>'9')
return 0;
int sum=0;
long long int sum1=0;
while(A[i]!='\0' && A[i]!=' '){
int n=(int)A[i]-48;
sum1=sum1*10+n;
sum=sum*10+n;
i++;
if(A[i]<'0'||A[i]>'9')
break;
}
if(sum1!=sum&&cm==1)
return INT_MAX;
if(sum1!=sum&&cm==-1)
return INT_MIN;
if(cm==-1){
int k=-sum;
return k;
}
return sum;
}
| true |
09fe232ec85bfd785e5e5139b35c5bee36ab4802 | C++ | leviathanbadger/gfn-compiler | /Gfnc/Parser/UnaryExpressionSyntax.cpp | UTF-8 | 4,098 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "Parser/UnaryExpressionSyntax.h"
#include "Parser/PrimaryExpressionSyntax.h"
#include "Tokenizer/Token.h"
#include "Emit/MethodBuilder.h"
#include "Emit/OpLdcI4.h"
#include "Runtime/RuntimeType.h"
#include "Runtime/MethodGroup.h"
#include "Runtime/MethodOverload.h"
namespace Gfn::Compiler::Parser
{
ExpressionSyntax *UnaryExpressionSyntax::tryParse(Cursor<Tokenizer::Token*> &cursor)
{
if (cursor.current()->isOperator())
{
auto op = cursor.current()->op();
if (op == "+"s || op == "-"s || op == "!"s)
{
auto startIndex = cursor.current()->startIndex();
auto snapshot = cursor.snapshot();
cursor.next();
ExpressionSyntax *rhs = tryParseSyntax<UnaryExpressionSyntax>(cursor);
if (rhs == nullptr) cursor.reset(snapshot);
else return new UnaryExpressionSyntax(startIndex, cursor.current()->startIndex() - startIndex, rhs, op);
}
}
return tryParseSyntax<PrimaryExpressionSyntax>(cursor);
}
UnaryExpressionSyntax::UnaryExpressionSyntax(uint32_t startIndex, uint32_t length, ExpressionSyntax *expr, const std::string op)
: ExpressionSyntax(startIndex, length), m_expr(expr), m_op(op), m_selectedOperatorOverload(nullptr)
{
}
UnaryExpressionSyntax::~UnaryExpressionSyntax()
{
SafeDelete(this->m_expr);
}
ExpressionSyntax *UnaryExpressionSyntax::expr() const
{
return this->m_expr;
}
const std::string UnaryExpressionSyntax::op() const
{
return this->m_op;
}
bool UnaryExpressionSyntax::tryResolveType()
{
if (this->m_resolvedType != nullptr) return true;
//Note: this top part is to handle the special case of having the minimum value for uint32_t
if (this->isNegativeNumericLimit())
{
this->m_resolvedType = Runtime::RuntimeType::int32();
return true;
}
if (!this->expr()->tryResolveType()) return false;
auto exprType = this->expr()->resolvedType();
auto operatorMethodName = this->getOperatorMethodName();
auto methods = exprType->getStaticMethods(operatorMethodName);
if (methods != nullptr)
{
this->m_selectedOperatorOverload = methods->findOverload({ exprType });
}
if (this->m_selectedOperatorOverload == nullptr) return false;
this->m_resolvedType = this->m_selectedOperatorOverload->returnType();
return true;
}
void UnaryExpressionSyntax::emit(Emit::MethodBuilder &mb) const
{
this->assertTypeIsResolved();
//Note: this top part is to handle the special case of having the minimum value for uint32_t
if (this->isNegativeNumericLimit())
{
mb.addOpcode(new Emit::OpLdcI4(std::numeric_limits<int32_t>::min()));
return;
}
this->expr()->emit(mb);
this->m_selectedOperatorOverload->emitInvoke(mb);
}
void UnaryExpressionSyntax::repr(std::stringstream &stream) const
{
stream << this->op() << this->expr();
}
std::string UnaryExpressionSyntax::getOperatorMethodName() const
{
if (this->op() == "+"s) return "__op_UnaryPlus"s;
else if (this->op() == "-"s) return "__op_UnaryNegation"s;
else if (this->op() == "!"s) return "__op_LogicalNot"s;
else throw std::logic_error("Invalid unary expression operation: "s + this->op());
}
bool UnaryExpressionSyntax::isNegativeNumericLimit() const
{
if (this->op() != "-"s) return false;
auto primaryExpr = dynamic_cast<PrimaryExpressionSyntax*>(this->expr());
if (primaryExpr == nullptr) return false;
if (primaryExpr->type() != PrimaryExpressionType::IntegerLiteral || primaryExpr->intLiteralValue() != (uint64_t)-(int64_t)std::numeric_limits<int32_t>::min()) return false;
if (primaryExpr->startIndex() != this->startIndex() + 1) return false;
return true;
}
}
| true |
5ac5ba33d5de076b8c76bf46c496de8e59a0db1a | C++ | plepers/blur_hdr_cube | /cubicblur/cubicblur.cpp | UTF-8 | 9,938 | 2.578125 | 3 | [] | no_license | // cubicblur.cpp : Defines the entry point for the console application.
//
#include "cubicblur.h"
using namespace TCLAP;
using namespace std;
float** splitCrossmap( HDRLoaderResult* hdrRes );
float* assembleCrossmap( float** faces, int faceSize );
unsigned char* f32toRgbe( float* faces, int w, int h, double base );
float* subscale( float* pixels, int w, int h, int level );
float** subscaleFaces(float** faces, int w, int h, int level );
int numMipForSize( int inSize ) {
int mip = 1;
int size = inSize;
while( size > 2 ) {
size = size >> 1;
mip++;
}
return mip;
}
int getMipForSize( int reqSize, int inSize ) {
int nummips = numMipForSize( inSize );
for( int m = 0; m<nummips;m++ ) {
if(( inSize >> m ) <= reqSize ) return m;
}
return -1;
}
bool IsPowerOfTwo(unsigned int x)
{
return (x != 0) && ((x & (x - 1)) == 0);
}
double getNewBase( char min, char max ) {
double newbaseMax = pow( pow( 2.0, (double)max ), 1.0/128.0 );
double newbaseMin = pow( pow( 2.0, (double)min ), -1.0/128.0 );
if( newbaseMax > newbaseMin)
return newbaseMax;
return newbaseMin;
}
int main(int argc, char* argv[])
{
int faceSize;
CmdLine cmd("diffusefilter - generate blured cube map", ' ', "0.1");
ValueArg<string> a_input("i","input","input raw cube texture",true,"","string", cmd );
ValueArg<string> a_output("o","output","output raw file",true,"","string", cmd );
ValueArg<float> a_power("p","power","fresnel power",false,1.0,"float", cmd );
ValueArg<float> a_curve("c","curve","dot curve",false,1.0,"float", cmd );
ValueArg<float> a_mix("m","mix","dot curve",false,0.0,"float", cmd );
ValueArg<int> a_size("s","size","output size",false,64,"int", cmd );
SwitchArg a_rebase("r","rebase", "maximize exponent range", true);
cmd.add( a_rebase );
cmd.parse( argc, argv );
const char* input = a_input.getValue().c_str();
const char* output = a_output.getValue().c_str();
const float power = a_power.getValue();
const float curve = a_curve.getValue();
const float mix = a_mix.getValue();
int size = a_size.getValue();
const bool rebase = a_rebase.getValue();
if( ! IsPowerOfTwo( size ) ) {
printf( "error - output size %i must be POT", size );
return 2;
}
printf( "blurring input cube texture \n input %s \n output %s \n" , input, output );
//==================================================
// Load hdr file
//==================================================
HDRLoaderResult* hdrData = new HDRLoaderResult();
HDRLoader* hdrLoader = new HDRLoader();
if( ! hdrLoader->load( input, *hdrData ) ) {
printf( "error loading %s \n", input );
return 1;
}
faceSize = hdrData->height/4;
printf( "input loaded \n size : %i*%i \n range %i>%i \n", hdrData->width, hdrData->height , hdrData->eMin, hdrData->eMax );
double base;
if( rebase )
base = getNewBase( hdrData->eMin, hdrData->eMax );
else
base = 2.0f;
//==================================================
// extract faces
//==================================================
int mlevel = 1;
printf( "splitCrossmap \n" );
float** faces = splitCrossmap( hdrData );
//==================================================
// process blur
//==================================================
int rescaleMul = -1; // subscale source to have source double size of output
int mip = getMipForSize( size, faceSize ) - rescaleMul;
if( mip > 0 ) {
float** sfaces = subscaleFaces( faces, faceSize, faceSize, mip );
faceSize = faceSize >> mip;
for (int j = 0; j < 6; ++j )
free( faces[j] );
free( faces );
faces = sfaces;
}
float** blurred = blurFaces( faces, faceSize, size, power, curve, mix );
//size = hdrData->height/4;
//==================================================
// reassembling
//==================================================
printf( "assembleCrossmap \n" );
float* assembled = assembleCrossmap( blurred, size );
//float* assembled = assembleCrossmap( faces, size );
printf( "f32toRgbe (base : %f)\n", base );
const unsigned char* rgbe = f32toRgbe( assembled, size*3, size*4, base );
printf( "encode png \n" );
/*Encode the image*/
unsigned error = lodepng_encode32_file( output, rgbe, size*3, size*4 );
/*if there's an error, display it*/
if(error) printf("error %u: %s \n", error, lodepng_error_text(error));
delete hdrLoader;
delete hdrData;
free( faces );
free( assembled );
return 0;
}
float** subscaleFaces(float** faces, int w, int h, int level ) {
float ** sfaces = (float **) malloc( 6 * sizeof( float* ) );
for (int j = 0; j < 6; ++j)
sfaces[j] = subscale( faces[j], w, h, level );
return sfaces;
}
float* subscale( float* pixels, int w, int h, int level ) {
int rw = w >> level;
int rh = h >> level;
int sx, sy;
int w3 = w*3;
int rw3 = rw*3;
int p;
int scale = 1<<(level);
int scale2 = scale*scale;
int plen = w*h;
float* res = (float*) malloc( plen * sizeof(float)*3 );
double pbuffR;
double pbuffG;
double pbuffB;
for( int y = 0; y< rh; y++ ) {
for( int x = 0; x< rw; x++ ) {
pbuffR = 0.0f;
pbuffG = 0.0f;
pbuffB = 0.0f;
sx = x*scale;
sy = y*scale;
for( int i = sy; i< sy+scale; i++ ) {
for( int j = sx; j< sx+scale; j++ ) {
p = (i*w3 + j*3);
pbuffR += pixels[ p ];
pbuffG += pixels[ p + 1 ];
pbuffB += pixels[ p + 2 ];
}
}
p = (y*rw3 + x*3);
res[ p ] = pbuffR/scale2;
res[ p + 1 ] = pbuffG/scale2;
res[ p + 2 ] = pbuffB/scale2;
}
}
return res;
}
unsigned char* f32toRgbe( float* pixels, int w, int h, double base ) {
//base = 2.0;
int j;
int resSize = w*h;
unsigned char* rgbe = ( unsigned char* ) malloc( resSize*4*sizeof( unsigned char* ) );
float r, g, b;
double e, re;
int f;
double logbase = log( base );
int c = 0;
int fc = 0;
for (j = 0; j < resSize; j++) {
fc = j*3;
c = j*4;
r = pixels[fc];
g = pixels[fc+1];
b = pixels[fc+2];
re = max( r, max( g, b ) );
f = int( ceil( log( re ) / logbase ) );
if( f < -128.0f ) f = -128.0f;
if( f > 127.0f ) f = 127.0f;
e = pow( base, f );
r = r*255.0f / e;
g = g*255.0f / e;
b = b*255.0f / e;
f += 128.0f;
rgbe[c] = char( r );
rgbe[c+1] = char( g );
rgbe[c+2] = char( b );
rgbe[c+3] = char( f );
}
return rgbe;
}
float* assembleCrossmap( float** faces, int faceSize) {
int i;
int j;
int p;
float* face;
float* startPos;
int fsize = sizeof( float );
int facesize3 = faceSize*3;
const int linelen = fsize*3*faceSize;
int twidth = faceSize * 3;
int theight = faceSize * 4;
int resSize = faceSize*faceSize*12* 3;
float* source = (float*) malloc( resSize * sizeof(float) );
for (j = 0; j < resSize; ++j) {
source[j] = 0.0;
}
// left face
face = faces[0];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ twidth * (faceSize+j)*3 ];
memcpy( startPos, face, linelen );
face += facesize3;
}
// right face
face = faces[1];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (twidth * (faceSize+j) + (2 * faceSize))*3 ];
memcpy( startPos, face, linelen );
face += facesize3;
}
// top face
face = faces[2];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (twidth * j + (faceSize))*3 ];
memcpy( startPos, face, linelen );
face += facesize3;
}
// bottom face
face = faces[3];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (twidth * (2*faceSize+j) + (faceSize))*3 ];
memcpy( startPos, face, linelen );
face += facesize3;
}
// front face
face = faces[4];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (twidth * (faceSize+j) + (faceSize))*3 ];
memcpy( startPos, face, linelen );
face += facesize3;
}
// back face (vertical revert)
face = faces[5];
int c = 0;
for (j = 0; j < faceSize; ++j) {
for ( i = 0; i < faceSize; ++i) {
p = (( twidth * (theight-j-1) )+(2 * faceSize - (i + 1) ))*3;
source[ p ] = face[c++];
source[ p+1 ] = face[c++];
source[ p+2 ] = face[c++];
}
}
return source;
}
float** splitCrossmap( HDRLoaderResult* hdrRes ){
int i;
int j;
int p;
int faceSize;
int faceSize3;
int lineByteslen;
float* startPos;
int fsize = sizeof( float );
float* face;
float ** faces;
float* source;
source = hdrRes->cols;
faceSize = hdrRes->height/4;
faceSize3 = faceSize*3;
const int cpylen = faceSize*fsize*3;
faces = (float **) malloc( 6 * sizeof( float* ) );
lineByteslen = hdrRes->width * 12;
for (j = 0; j < 6; ++j)
faces[j] = (float *) malloc( faceSize*faceSize*3 * sizeof( float ) );
// left face
face = faces[0];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (hdrRes->width * (faceSize+j))*3 ];
memcpy( face, startPos, cpylen );
face += faceSize3;
}
// right face
face = faces[1];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (hdrRes->width * (faceSize+j) + (2 * faceSize))*3 ];
memcpy( face, startPos, cpylen );
face += faceSize3;
}
// top face
face = faces[2];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (hdrRes->width * j + (faceSize))*3 ];
memcpy( face, startPos, cpylen );
face += faceSize3;
}
// bottom face
face = faces[3];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (hdrRes->width * (2*faceSize+j) + (faceSize))*3 ];
memcpy( face, startPos, cpylen );
face += faceSize3;
}
// front face
face = faces[4];
for (j = 0; j < faceSize; ++j) {
startPos = &source[ (hdrRes->width * (faceSize+j) + (faceSize))*3 ];
memcpy( face, startPos, cpylen );
face += faceSize3;
}
// back face (vertical revert)
face = faces[5];
int c = 0;
for (j = 0; j < faceSize; ++j) {
for ( i = 0; i < faceSize; ++i) {
p = (( hdrRes->width * (hdrRes->height-j-1) )+(2 * faceSize - (i + 1) ))*3;
face[c++] = source[ p ];
face[c++] = source[ p+1 ];
face[c++] = source[ p+2 ];
}
}
return faces;
}
| true |
21ef46f5e2a9de979d936bdd622fab14849d734b | C++ | fubyo/osccalibrator | /juce/extras/Jucer (experimental)/Source/Utility/jucer_MiscUtilities.cpp | UTF-8 | 14,139 | 2.5625 | 3 | [] | no_license | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-10 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#include "../jucer_Headers.h"
//==============================================================================
const int64 hashCode64 (const String& s)
{
return s.hashCode64() + s.length() * s.hashCode() + s.toUpperCase().hashCode();
}
const String createAlphaNumericUID()
{
String uid;
static const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random r (Random::getSystemRandom().nextInt64());
for (int i = 7; --i >= 0;)
{
r.setSeedRandomly();
uid << chars [r.nextInt (numElementsInArray (chars))];
}
return uid;
}
const String randomHexString (Random& random, int numChars)
{
String s;
const char hexChars[] = "0123456789ABCDEF";
while (--numChars >= 0)
s << hexChars [random.nextInt (16)];
return s;
}
const String hexString8Digits (int value)
{
return String::toHexString (value).paddedLeft ('0', 8);
}
const String createGUID (const String& seed)
{
String guid;
Random r (hashCode64 (seed + "_jucersalt"));
guid << "{" << randomHexString (r, 8); // (written as separate statements to enforce the order of execution)
guid << "-" << randomHexString (r, 4);
guid << "-" << randomHexString (r, 4);
guid << "-" << randomHexString (r, 4);
guid << "-" << randomHexString (r, 12) << "}";
return guid;
}
//==============================================================================
static void skipWhitespace (const String& s, int& i)
{
while (CharacterFunctions::isWhitespace (s[i]))
++i;
}
const StringPairArray parsePreprocessorDefs (const String& s)
{
StringPairArray result;
int i = 0;
while (s[i] != 0)
{
String token, value;
skipWhitespace (s, i);
while (s[i] != 0 && s[i] != '=' && ! CharacterFunctions::isWhitespace (s[i]))
token << s[i++];
skipWhitespace (s, i);
if (s[i] == '=')
{
++i;
skipWhitespace (s, i);
while (s[i] != 0 && ! CharacterFunctions::isWhitespace (s[i]))
{
if (s[i] == ',')
{
++i;
break;
}
if (s[i] == '\\' && (s[i + 1] == ' ' || s[i + 1] == ','))
++i;
value << s[i++];
}
}
if (token.isNotEmpty())
result.set (token, value);
}
return result;
}
const StringPairArray mergePreprocessorDefs (StringPairArray inheritedDefs, const StringPairArray& overridingDefs)
{
for (int i = 0; i < overridingDefs.size(); ++i)
inheritedDefs.set (overridingDefs.getAllKeys()[i], overridingDefs.getAllValues()[i]);
return inheritedDefs;
}
const String replacePreprocessorDefs (const StringPairArray& definitions, String sourceString)
{
for (int i = 0; i < definitions.size(); ++i)
{
const String key (definitions.getAllKeys()[i]);
const String value (definitions.getAllValues()[i]);
sourceString = sourceString.replace ("${" + key + "}", value);
}
return sourceString;
}
//==============================================================================
void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
{
Viewport* const viewport = e.eventComponent->findParentComponentOfClass ((Viewport*) 0);
if (viewport != 0)
{
const MouseEvent e2 (e.getEventRelativeTo (viewport));
viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
}
}
void drawComponentPlaceholder (Graphics& g, int w, int h, const String& text)
{
g.fillAll (Colours::white.withAlpha (0.4f));
g.setColour (Colours::grey);
g.drawRect (0, 0, w, h);
g.drawLine (0.5f, 0.5f, w - 0.5f, h - 0.5f);
g.drawLine (0.5f, h - 0.5f, w - 0.5f, 0.5f);
g.setColour (Colours::black);
g.setFont (11.0f);
g.drawFittedText (text, 2, 2, w - 4, h - 4, Justification::centredTop, 2);
}
void drawRecessedShadows (Graphics& g, int w, int h, int shadowSize)
{
ColourGradient cg (Colours::black.withAlpha (0.15f), 0, 0,
Colours::transparentBlack, 0, (float) shadowSize, false);
cg.addColour (0.4, Colours::black.withAlpha (0.07f));
cg.addColour (0.6, Colours::black.withAlpha (0.02f));
g.setGradientFill (cg);
g.fillRect (0, 0, w, shadowSize);
cg.point1.setXY (0.0f, (float) h);
cg.point2.setXY (0.0f, (float) h - shadowSize);
g.setGradientFill (cg);
g.fillRect (0, h - shadowSize, w, shadowSize);
cg.point1.setXY (0.0f, 0.0f);
cg.point2.setXY ((float) shadowSize, 0.0f);
g.setGradientFill (cg);
g.fillRect (0, 0, shadowSize, h);
cg.point1.setXY ((float) w, 0.0f);
cg.point2.setXY ((float) w - shadowSize, 0.0f);
g.setGradientFill (cg);
g.fillRect (w - shadowSize, 0, shadowSize, h);
}
//==============================================================================
int indexOfLineStartingWith (const StringArray& lines, const String& text, int startIndex)
{
startIndex = jmax (0, startIndex);
while (startIndex < lines.size())
{
if (lines[startIndex].trimStart().startsWithIgnoreCase (text))
return startIndex;
++startIndex;
}
return -1;
}
//==============================================================================
PropertyPanelWithTooltips::PropertyPanelWithTooltips()
: lastComp (0)
{
addAndMakeVisible (&panel);
startTimer (150);
}
PropertyPanelWithTooltips::~PropertyPanelWithTooltips()
{
}
void PropertyPanelWithTooltips::paint (Graphics& g)
{
g.setColour (Colour::greyLevel (0.15f));
g.setFont (13.0f);
TextLayout tl;
tl.appendText (lastTip, Font (14.0f));
tl.layout (getWidth() - 10, Justification::left, true); // try to make it look nice
if (tl.getNumLines() > 3)
tl.layout (getWidth() - 10, Justification::left, false); // too big, so just squash it in..
tl.drawWithin (g, 5, panel.getBottom() + 2, getWidth() - 10,
getHeight() - panel.getBottom() - 4,
Justification::centredLeft);
}
void PropertyPanelWithTooltips::resized()
{
panel.setBounds (0, 0, getWidth(), jmax (getHeight() - 60, proportionOfHeight (0.6f)));
}
void PropertyPanelWithTooltips::timerCallback()
{
Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
if (newComp != 0 && newComp->getTopLevelComponent() != getTopLevelComponent())
newComp = 0;
if (newComp != lastComp)
{
lastComp = newComp;
String newTip (findTip (newComp));
if (newTip != lastTip)
{
lastTip = newTip;
repaint (0, panel.getBottom(), getWidth(), getHeight());
}
}
}
const String PropertyPanelWithTooltips::findTip (Component* c)
{
while (c != 0 && c != this)
{
TooltipClient* const tc = dynamic_cast <TooltipClient*> (c);
if (tc != 0)
{
const String tip (tc->getTooltip());
if (tip.isNotEmpty())
return tip;
}
c = c->getParentComponent();
}
return String::empty;
}
//==============================================================================
FloatingLabelComponent::FloatingLabelComponent()
: font (10.0f)
{
setInterceptsMouseClicks (false, false);
}
void FloatingLabelComponent::remove()
{
if (getParentComponent() != 0)
getParentComponent()->removeChildComponent (this);
}
void FloatingLabelComponent::update (Component* parent, const String& text, const Colour& textColour, int x, int y, bool toRight, bool below)
{
colour = textColour;
Rectangle<int> r;
if (text != getName())
{
setName (text);
glyphs.clear();
glyphs.addJustifiedText (font, text, 0, 0, 200.0f, Justification::left);
glyphs.justifyGlyphs (0, std::numeric_limits<int>::max(), 0, 0, 1000, 1000, Justification::topLeft);
r = glyphs.getBoundingBox (0, std::numeric_limits<int>::max(), false)
.getSmallestIntegerContainer().expanded (1, 1);
}
else
{
r = getLocalBounds();
}
r.setPosition (x + (toRight ? 3 : -(r.getWidth() + 3)), y + (below ? 2 : -(r.getHeight() + 2)));
setBounds (r);
parent->addAndMakeVisible (this);
}
void FloatingLabelComponent::paint (Graphics& g)
{
g.setFont (font);
g.setColour (Colours::white.withAlpha (0.5f));
g.fillRoundedRectangle (0, 0, (float) getWidth(), (float) getHeight(), 3);
g.setColour (colour);
glyphs.draw (g, AffineTransform::translation (1.0f, 1.0f));
}
//==============================================================================
RelativeRectangleLayoutManager::RelativeRectangleLayoutManager (Component* parentComponent)
: parent (parentComponent)
{
parent->addComponentListener (this);
}
RelativeRectangleLayoutManager::~RelativeRectangleLayoutManager()
{
parent->removeComponentListener (this);
for (int i = components.size(); --i >= 0;)
components.getUnchecked(i)->component->removeComponentListener (this);
}
void RelativeRectangleLayoutManager::setMarker (const String& name, const RelativeCoordinate& coord)
{
for (int i = markers.size(); --i >= 0;)
{
MarkerPosition* m = markers.getUnchecked(i);
if (m->markerName == name)
{
m->position = coord;
applyLayout();
return;
}
}
markers.add (new MarkerPosition (name, coord));
applyLayout();
}
void RelativeRectangleLayoutManager::setComponentBounds (Component* comp, const String& name, const RelativeRectangle& coords)
{
jassert (comp != 0);
// All the components that this layout manages must be inside the parent component..
jassert (parent->isParentOf (comp));
for (int i = components.size(); --i >= 0;)
{
ComponentPosition* c = components.getUnchecked(i);
if (c->component == comp)
{
c->name = name;
c->coords = coords;
triggerAsyncUpdate();
return;
}
}
components.add (new ComponentPosition (comp, name, coords));
comp->addComponentListener (this);
triggerAsyncUpdate();
}
void RelativeRectangleLayoutManager::applyLayout()
{
for (int i = components.size(); --i >= 0;)
{
ComponentPosition* c = components.getUnchecked(i);
// All the components that this layout manages must be inside the parent component..
jassert (parent->isParentOf (c->component));
c->component->setBounds (c->coords.resolve (this).getSmallestIntegerContainer());
}
}
const Expression RelativeRectangleLayoutManager::getSymbolValue (const String& objectName, const String& edge) const
{
if (objectName == RelativeCoordinate::Strings::parent)
{
if (edge == RelativeCoordinate::Strings::right) return Expression ((double) parent->getWidth());
if (edge == RelativeCoordinate::Strings::bottom) return Expression ((double) parent->getHeight());
}
if (objectName.isNotEmpty() && edge.isNotEmpty())
{
for (int i = components.size(); --i >= 0;)
{
ComponentPosition* c = components.getUnchecked(i);
if (c->name == objectName)
{
if (edge == RelativeCoordinate::Strings::left) return c->coords.left.getExpression();
if (edge == RelativeCoordinate::Strings::right) return c->coords.right.getExpression();
if (edge == RelativeCoordinate::Strings::top) return c->coords.top.getExpression();
if (edge == RelativeCoordinate::Strings::bottom) return c->coords.bottom.getExpression();
}
}
}
for (int i = markers.size(); --i >= 0;)
{
MarkerPosition* m = markers.getUnchecked(i);
if (m->markerName == objectName)
return m->position.getExpression();
}
return Expression();
}
void RelativeRectangleLayoutManager::componentMovedOrResized (Component& component, bool wasMoved, bool wasResized)
{
triggerAsyncUpdate();
if (parent == &component)
handleUpdateNowIfNeeded();
}
void RelativeRectangleLayoutManager::componentBeingDeleted (Component& component)
{
for (int i = components.size(); --i >= 0;)
{
ComponentPosition* c = components.getUnchecked(i);
if (c->component == &component)
{
components.remove (i);
break;
}
}
}
void RelativeRectangleLayoutManager::handleAsyncUpdate()
{
applyLayout();
}
RelativeRectangleLayoutManager::MarkerPosition::MarkerPosition (const String& name, const RelativeCoordinate& coord)
: markerName (name), position (coord)
{
}
RelativeRectangleLayoutManager::ComponentPosition::ComponentPosition (Component* component_, const String& name_, const RelativeRectangle& coords_)
: component (component_), name (name_), coords (coords_)
{
}
| true |
ff41f98b6fec14a5be02085a7ff5df9b677d06dd | C++ | shubhlohiya/production-planning-cs218 | /DP.cpp | UTF-8 | 3,528 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
#include <chrono>
#include <climits>
using namespace std;
using namespace std::chrono;
using ll = long long;
ll getcost(int M, int D[], int E, ll Hcost, ll Fcost,
ll S, int C, int OTC, ll OTPrice, ll W){
// Naming of parameters is as described in the Problem Statement
int total_demand = 0; // sum of demand over m months
for(int i=0; i<M; i++)
total_demand += D[i];
// safe measure of max possible required employees
int e_max = max(E, (int)ceil(total_demand/C));
// safe measure of max possible inventory in storage (all produce)
int inventory_max = e_max*(C+OTC);
// Solution Space: All possible combinations of employees and inventory
// at the beginning of each month for M months
// Creating cost table of size (M+1, inventory_max+1, e_max+1)
vector<ll> temp1(e_max+1, LLONG_MAX);
vector<vector<ll> > temp2(inventory_max+1, temp1);
vector<vector<vector<ll> > > cost(M+1, temp2);
// cost[i][j][k] is the minimum production cost from month i to M with
// j carpets in storage and k employees at the beginning of month i
// adjust for the hiring/firing cost at end of M months to get E employees
for(int j=0; j<=inventory_max; j++)
for(int k=0; k<=e_max; k++)
cost[M][j][k] = (k<=E)? Hcost*(E-k) : Fcost*(k-E);
// Fill table
for(int i=M-1; i>=0; i--){
for(int j=0; j<=inventory_max; j++){
if(i==0 && j!=0)
continue;
for(int k=0; k<=e_max; k++){
if(i==0 && k!=E)
continue;
for(int j_next=0; j_next<=inventory_max; j_next++){
for(int k_next=0; k_next<=e_max; k_next++){
//required overtime carpets in month i
int o = D[i] - (j-j_next + C*k_next);
if(o<0 || o > k_next*OTC) // invalid
continue;
// hiring, firing, overtime, salary and inventory
// storage costs for month i
ll hc, fc, oc, salary, ic;
if(k_next>=k){
hc = Hcost*(k_next-k);
fc = 0;
}
else{
fc = Fcost*(k-k_next);
hc = 0;
}
oc = o*OTPrice;
salary = k_next*S;
ic = j*W;
// Recurrence
cost[i][j][k] = min(cost[i][j][k],
hc+fc+oc+salary+ic+cost[i+1][j_next][k_next]);
// The recurrence relates minimum production cost for
// months i...M to that of months (i+1)...M by minimizing
// over all possible combinations of next month j and k
// (inventory and employees) after adding the corresponding
// hiring, firing, overtime, salary and storage costs
}
}
}
}
}
// min production cost for M months starting with E employees and 0 inventory
return cost[0][0][E];
// Time Analysis:
// Clearly filling the DP table is the most expensive operation and will
// dominate the time complexity
// Total entries we update: (M)*(e_max+1)*(inventory_max+1)+1
// Time to update each entry: (e_max)*(inventory_max)
// as we are minimizing over all possible combinations from month i+1
// Time complexity of the Algorithm: O(M*(e_max^2)*(inventory_max^2))
// where e_max and inventory_max are defined as above
}
int main(){
int M;
cin>>M;
int D[M];
for(int i=0; i<M; i++)
cin>>D[i];
int E,C,OTC;
ll Hcost, Fcost, S, OTPrice, W;
cin>>E;
cin>>Hcost>>Fcost;
cin>>S;
cin>>C;
cin>>OTC;
cin>>OTPrice;
cin>>W;
auto start = high_resolution_clock::now();
ll min_cost = getcost(M, D, E, Hcost, Fcost, S, C, OTC, OTPrice, W);
auto end = high_resolution_clock::now();
cout<<min_cost<<" ";
cout<<((double)duration_cast<microseconds>(end-start).count())/1e6;
} | true |
5b794c766bcd60436d0cb7866fe151ef68273ff4 | C++ | cfcv/Perceptron | /perceptron.cpp | UTF-8 | 5,368 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <fstream>
#include <ctime>
#include <cstdlib>
#define TABLE_LENGHT 4
#define TABLE_WIDTH 3
#define FILE_NAME "TruthTable.txt"
#define DEBUG_TRAINING 0
#define THRESHOLD 0.9
using namespace std;
class Perceptron {
public:
Perceptron(double tr, double lr, double p1, double p2) : threshold(tr), learningRate(lr) {
this->weights.push_back(p1);
this->weights.push_back(p2);
}
void TrainPerceptron(const vector< vector<int> >& trainingData);
int run(double x, double y);
private:
double threshold;
double learningRate;
double output;
vector<double> weights;
};
//Functions definitions
void ReadDataSet(vector< vector<int> > &data);
void ShowDataSet(const vector< vector<int> > &data);
void Presentation();
int main(){
double random_weight1, random_weight2, x, y;
int z;
vector< vector<int> > data_set(TABLE_LENGHT);
for(int i = 0; i < data_set.size(); ++i){
data_set[i].resize(TABLE_WIDTH);
}
Presentation();
try{
ReadDataSet(data_set);
}catch(const char* msg){
cout << msg << endl;
}
ShowDataSet(data_set);
srand(time(0));
random_weight1 = (double)(rand()%41 - 20)/10;
random_weight2 = (double)(rand()%41 - 20)/10;
Perceptron mlp(THRESHOLD, 0.1, random_weight1, random_weight2);
mlp.TrainPerceptron(data_set);
cout << "Now you can test it!!!(-1 to stop)" << endl;
while(true){
cout << "Entrada 1: ";
cin >> x;
if(x == -1) break;
cout << "Entrada 2: ";
cin >> y;
z = mlp.run(x, y);
cout << "Saida: " << z << endl;
}
return 0;
}
//------------------ Global functions implementations ------------------
void Presentation(){
cout << "---------------------------------------------------- Perceptron ----------------------------------------------------" << endl;
cout << "This program was made to simulade GATE PORTS(AND, OR...) \nwith the simplest neural network(Perceptron)\n";
cout << "there is only an input layer with 2 neurons and one output layer with one neuron, it will output 1 or 0.\n";
cout << "You will have to input the truth table throught the file TruthTable.txt and it will train to output the correct values\n";
cout << "--------------------------------------------------------------------------------------------------------------------\n" << endl;
}
void ReadDataSet(vector< vector<int> > &data){
ifstream table(FILE_NAME);
if(table.is_open()){
for(int i = 0; i < TABLE_LENGHT; ++i){
table >> data[i][0] >> data[i][1] >> data[i][2];
}
}
else{
throw "Cannot Read Truth Table";
}
}
void ShowDataSet(const vector< vector<int> > &data){
cout << endl << "INPUT TABLE: " << endl;
cout << "\tX\tY\t Z" << endl;
cout << "\t---------------------" << endl;
for(int i = 0 ; i < TABLE_LENGHT; ++i){
for(int j = 0; j < TABLE_WIDTH; ++j){
if(j == TABLE_WIDTH-1){
cout << "| ";
}
if(j == 0){
cout << "\t";
}
cout << data[i][j] << "\t";
}
cout << endl;
}
}
//------------------------------------------------------------------------
//------------------ Perceptron functions implementations ------------------
void Perceptron::TrainPerceptron(const vector< vector<int> >& trainingData){
cout << endl << "TRAINING..." << endl;
int c = 1;
double input_x, input_y, sum;
int output, error;
char pause;
while(true){
c = 0;
for(int i = 0; i < TABLE_LENGHT; ++i){
//calcule error
input_x = trainingData[i][0] * this->weights[0];
input_y = trainingData[i][1] * this->weights[1];
sum = input_x + input_y;
if(sum > this->threshold){
output = 1;
}
else{
output = 0;
}
if(DEBUG_TRAINING){
cout << "Caso " << i << endl;
cout << "pesos: " << this->weights[0] << " , " << this->weights[1] << endl;
cout << "input_x: " << input_x << endl;
cout << "input_y: " << input_y << endl;
cout << "output: " << output << endl;
}
if(output != trainingData[i][2]){
c = 1;
error = trainingData[i][2] - output;
this->weights[0] = this->weights[0] + (error * trainingData[i][0] * this->learningRate);
this->weights[1] = this->weights[1] + (error * trainingData[i][1] * this->learningRate);
if(DEBUG_TRAINING){
cout << "Error: " << error << endl;
cout << "novos pesos: " << this->weights[0] << " , " << this->weights[1] << endl;
}
}
}
if(c == 0) break;
}
cout << endl << "Final weights: " << this->weights[0] << " , " << this->weights[1] << endl;
}
int Perceptron::run(double x, double y){
double input_x = x * this->weights[0];
double input_y = y * this->weights[1];
double sum = input_x + input_y;
if(sum > this->threshold){
return 1;
}
return 0;
}
//--------------------------------------------------------------------------- | true |
784d1b2e36c3bf0c0c6e2735b41b263a5693ac06 | C++ | TensShinet/learn_graphics | /Lesson 5: Moving the camera/test.cpp | UTF-8 | 325 | 2.515625 | 3 | [
"MIT",
"Zlib"
] | permissive | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include "model.h"
int main() {
std::string stringvalues = "f 24/1/24 25/2/25 26/3/26";
std::istringstream iss(stringvalues.c_str());
char trash;
Vec3f tmp;
iss >> trash >> trash;
std::cout<< trash << '\n';
return 0;
} | true |
4c7fa72b2b5ff48eeacb81274b7ded15ea3432ba | C++ | rachitvk/Competitive-Programming | /Codeforces/Codeforces Round 550/B-Parity Alternated Deletions.cpp | UTF-8 | 723 | 2.765625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int>even,odd;
for(int i=0;i<n;i++){
int x;
cin >> x;
if(x%2)
odd.push_back(x);
else
even.push_back(x);
}
sort(even.begin(),even.end());
sort(odd.begin(),odd.end());
long long ans = 0;
if(odd.size() > even.size()){
int n= odd.size()-even.size()-1;
for(int i=0;i<n;i++)
ans+=odd[i];
}else if(odd.size()<even.size()){
int n= even.size()-odd.size()-1;
for(int i=0;i<n;i++)
ans+=even[i];
}else{
ans=0;
}
cout << ans << endl;
} | true |
7a272efb27e86bd37f868a2b199b0e3a03518645 | C++ | rubenglezortiz/Proyectos2-2020-21 | /PaintlLess/Textura.cpp | UTF-8 | 1,181 | 3.109375 | 3 | [
"CC0-1.0"
] | permissive | #include "Textura.h"
#include <iostream>
using namespace std;
void Textura::clear() {
SDL_DestroyTexture(texture);
texture = nullptr;
w = h = 0;
}
void Textura::load(string filename, uint nRows, uint nCols) {
SDL_Surface* tempSurface = IMG_Load(filename.c_str());
if (tempSurface == nullptr) throw string("Error loading surface from " + filename);
clear();
texture = SDL_CreateTextureFromSurface(renderer, tempSurface);
if (texture == nullptr) throw string("Error loading texture from " + filename);
numRows = nRows;
numCols = nCols;
w = tempSurface->w;
h = tempSurface->h;
fw = w / numCols;
fh = h / numRows;
SDL_FreeSurface(tempSurface);
}
void Textura::render(const SDL_Rect& destRect, SDL_RendererFlip flip) const {
SDL_Rect srcRect;
srcRect.x = 0; srcRect.y = 0;
srcRect.w = w; srcRect.h = h;
SDL_RenderCopyEx(renderer, texture, &srcRect, &destRect, 0, 0, flip);
}
void Textura::renderFrame(const SDL_Rect& destRect, int row, int col, int angle, SDL_RendererFlip flip) const {
SDL_Rect srcRect;
srcRect.x = fw * col;
srcRect.y = fh * row;
srcRect.w = fw;
srcRect.h = fh;
SDL_RenderCopyEx(renderer, texture, &srcRect, &destRect, angle, 0, flip);
} | true |
d477d9e1b7975ea5da88b909f7278dcb32ce2a8e | C++ | checkoutb/LeetCodeCCpp | /ge2000/LT2037_2022-02-26_Minimum_Number_of_Moves_to_Seat_Everyone.cpp | UTF-8 | 818 | 2.96875 | 3 | [] | no_license |
#include "../header/myheader.h"
class LT2037
{
public:
// D D
//Runtime: 14 ms, faster than 49.16% of C++ online submissions for Minimum Number of Moves to Seat Everyone.
//Memory Usage: 18.2 MB, less than 44.92% of C++ online submissions for Minimum Number of Moves to Seat Everyone.
// seat 的 位置, student 的 位置。
// 一个位置可以多个seat,多个student。
// 应该是 都sort,然后一一对应 需要走几步。
int lt2037a(vector<int>& seats, vector<int>& students)
{
std::sort(begin(seats), end(seats));
sort(begin(students), end(students));
int ans = 0;
for (int i = 0; i < seats.size(); i++)
{
ans += abs(seats[i] - students[i]);
}
return ans;
}
};
int main()
{
LT2037 lt;
return 0;
}
| true |
b783a2aab1095641ad3e602080914ba26bb0ce25 | C++ | elsioantunes/cloud9 | /(spoj)/histograma.cpp | UTF-8 | 447 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main(){
int X, Y, C, c;
while(true){
cin >> X;
cin >> Y;
cin >> C;
if (X==0) break;
int *h = new int[X*Y];
for(int i=0;i<C+1;i++) h[i]=0;
for(int i=0;i<X;i++)
for(int j=0;j<Y;j++){
cin >> c;
h[c]++;
}
for(int i=0;i<C+1;i++)
cout << i << ":" << h[i] << " ";
cout << endl;
}
return 0;
}
| true |
534c66fffd7d5bb4a52a8ff2b64a1f7fbbf7dad6 | C++ | grasmanek94/sluice2017 | /product/DoorOneSecondMotor.cpp | UTF-8 | 598 | 2.859375 | 3 | [] | no_license | #include "DoorOneSecondMotor.hpp"
DoorOneSecondMotor::DoorOneSecondMotor(SluiceNetworkHandler* handler, const std::string& door_name)
: Door(handler, door_name)
{}
bool DoorOneSecondMotor::Open()
{
timer.Restart();
return Door::Open();
}
bool DoorOneSecondMotor::Close()
{
timer.Restart();
return Door::Close();
}
bool DoorOneSecondMotor::Stop()
{
return Door::Stop();
}
void DoorOneSecondMotor::Update()
{
Door::Update();
if ((state == DoorStateOpening || state == DoorStateClosing) && timer.ElapsedMilliseconds() > 450)
{
state == DoorStateOpening ?
Open() :
Close();
}
}
| true |
eba0995d3132cf34cb0ab101c79c55117fd5d5cd | C++ | MrLukeKR/Party-Animals | /G53GRA.Framework/Code/SpecialFX/Confetti.h | UTF-8 | 675 | 2.71875 | 3 | [] | no_license | #pragma once
#include "DisplayableObject.h"
#include "Animation.h"
/*
Party Animals: Confetti (Header File)
Author: Luke K. Rose
April 2018
*/
class Confetti :
public DisplayableObject,
public Animation {
public:
/*
Public Constructor/Destructor
*/
Confetti(float x, float y, float z) {
dropLoc[0] = (x);
dropLoc[1] = (y);
dropLoc[2] = (z);
for (int i = 0; i < 3; i++)
pos[i] = dropLoc[i] + ((rand() % 100) - 50);
}
~Confetti() {};
/*
Public methods
*/
void Display();
void Update(const double& dT);
private:
/*
Private variables
*/
float
r = (rand() % 10) / 10.0f,
g = (rand() % 10) / 10.0f,
b = (rand() % 10) / 10.0f;
float dropLoc[3];
}; | true |
059e89c67b1e4bd4510f48001bcc6e761d619ced | C++ | paweldata/Kodowanie-i-kompresja-danych | /lista6/src/Decoder.cpp | UTF-8 | 3,889 | 2.875 | 3 | [] | no_license | #include <cmath>
#include <bitset>
#include "Decoder.h"
#include "TGAHeader.h"
Decoder::Decoder() {
this->redLowPassDict = std::map<std::string, int>();
this->redHighPassDict = std::map<std::string, int>();
this->greenLowPassDict = std::map<std::string, int>();
this->greenHighPassDict = std::map<std::string, int>();
this->blueLowPassDict = std::map<std::string, int>();
this->blueHighPassDict = std::map<std::string, int>();
}
void Decoder::getDictionary(std::ifstream &file) {
file >> std::noskipws >> this->size;
int value;
int maxValue = (int)pow(2, this->size);
for (int i = 0; i < maxValue; i++) {
std::string code = Decoder::decToBin(i, this->size);
file.read((char*)&value, sizeof(value));
this->redLowPassDict[code] = value;
file.read((char*)&value, sizeof(value));
this->redHighPassDict[code] = value;
file.read((char*)&value, sizeof(value));
this->greenLowPassDict[code] = value;
file.read((char*)&value, sizeof(value));
this->greenHighPassDict[code] = value;
file.read((char*)&value, sizeof(value));
this->blueLowPassDict[code] = value;
file.read((char*)&value, sizeof(value));
this->blueHighPassDict[code] = value;
}
}
std::string Decoder::decToBin(int value, uint8_t size) {
std::string result(size, '0');
for (int i = size - 1; value > 0; i--) {
result[i] = char((value % 2) + 48);
value /= 2;
}
return result;
}
void Decoder::writeHeaderToFile(std::ifstream &inFile, std::ofstream &outFile) {
TGAHeader header = TGAHeader();
inFile.read(reinterpret_cast<char*>(&header), sizeof(header));
this->height = header.height;
this->width = header.width;
outFile.write((char*)&header, sizeof(header));
}
void Decoder::writePixelsToFile(std::ifstream& inFile, std::ofstream& outFile) {
std::vector<Pixel> pixels = this->getImage(inFile);
int imageSize = pixels.size();
for (int i = 0; i < imageSize; i++) {
outFile << pixels[i].red;
outFile << pixels[i].green;
outFile << pixels[i].blue;
}
}
std::vector<Pixel> Decoder::getImage(std::ifstream& file) {
int imageSize = this->width * this->height;
std::vector<Pixel> pixels(imageSize);
std::string code;
std::string currCode;
int redLowValue;
int redHighValue;
int greenLowValue;
int greenHighValue;
int blueLowValue;
int blueHighValue;
uint8_t fileValue = 0;
while (file >> std::noskipws >> fileValue)
code.append(std::bitset<8>(fileValue).to_string());
for (int i = 0, j = 0; i < imageSize; i += 2) {
redLowValue = this->redLowPassDict[code.substr(j, this->size)];
j += this->size;
redHighValue = this->redHighPassDict[code.substr(j, this->size)];
j += this->size;
greenLowValue = this->greenLowPassDict[code.substr(j, this->size)];
j += this->size;
greenHighValue = this->greenHighPassDict[code.substr(j, this->size)];
j += this->size;
blueLowValue = this->blueLowPassDict[code.substr(j, this->size)];
j += this->size;
blueHighValue = this->blueHighPassDict[code.substr(j, this->size)];
j += this->size;
pixels[i].red = (uint8_t)(std::max(0, std::min(255, redLowValue - redHighValue)));
pixels[i].green = (uint8_t)(std::max(0, std::min(255, greenLowValue - greenHighValue)));
pixels[i].blue = (uint8_t)(std::max(0, std::min(255, blueLowValue - blueHighValue)));
pixels[i + 1].red = (uint8_t)(std::max(0, std::min(255, redLowValue + redHighValue)));
pixels[i + 1].green = (uint8_t)(std::max(0, std::min(255, greenLowValue + greenHighValue)));
pixels[i + 1].blue = (uint8_t)(std::max(0, std::min(255, blueLowValue + blueHighValue)));
}
return pixels;
}
| true |
4298aea8a1a16bd7dcf1ca82b3ba23cdc98b93ea | C++ | ciupmeister/Surse | /numar4/main.cpp | UTF-8 | 791 | 2.625 | 3 | [] | no_license | #include <cstdio>
#define DN 2005
int ni,nz,a[DN],b[DN];
void imp(int x[], int y) {
int i,r=0;
i=x[0];
for(;i;) {
r=r*10+x[i];
x[i]=r/y;
r=r%y;
i--;
}
for(;!x[x[0]];--x[0]);
}
void afis(int x[]) {
for(int i=x[0];i>0; --i) printf("%d",x[i]);
}
int main()
{
freopen("numar4.in","r",stdin);
freopen("numar4.out","w",stdout);
scanf("%d %d",&ni,&nz);
int i;
a[0]=ni+nz;
for(i=ni+nz; i>0; --i) scanf("%d",&a[i]);
b[0]=nz+1; b[nz+1]=1;
for(i=nz;i!=0 && a[1]%2==0;) {
imp(a,2);
imp(b,2);
--i;
}
for(i=nz;i!=0 && a[1]%5==0;) {
imp(a,5);
imp(b,5);
--i;
}
printf("%d\n",a[0]);
afis(a);
printf("\n%d\n",b[0]);
afis(b);
return 0;
}
| true |
6ff2ad270089141a565b5b4ce8f6abe42a4cb908 | C++ | wonbae/Algorithm | /SWEA/SWEA_1215.cpp | UTF-8 | 2,180 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
int main(){
int Palindrome_Len,len;
char Teststr[8][8] = {0,};
len = sizeof(Teststr[0]);
int count = 0;
bool flag = false;
for(int tc = 1; tc <= 10; tc++){
cin>>Palindrome_Len;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
cin>>Teststr[i][j];
}
}
//Row
count = 0;
for(int i = 0; i < len; i++){
for(int j = 0; j < len - Palindrome_Len + 1; j++)
{
int left = j;
int right = j + Palindrome_Len - 1;
while(left <= right){
if(Teststr[i][left] == Teststr[i][right])
{
left++;
right--;
// count++;
flag = true;
}
else
{
flag = false;
break;
}
}
if(flag){
count++;
flag = false;
}
}
}
//Column
for(int i = 0; i < len; i++){
for(int j = 0; j < len-Palindrome_Len+1; j++)
{
int top = j;
int bottom = j + Palindrome_Len - 1;
while(top <= bottom){
if(Teststr[top][i] == Teststr[bottom][i])
{
top++;
bottom--;
// count++;
flag = true;
}
else
{
flag = false;
break;
}
}
if(flag){
count++;
flag = false;
}
}
}
cout<<"#"<<tc<<" "<<count<<endl;
}
return 0;
} | true |
106e4ecc0b97eea990e39401a0b2bb983635b5b1 | C++ | pgarnaut/sha256 | /main.cpp | UTF-8 | 1,316 | 2.671875 | 3 | [
"Zlib"
] | permissive | //
// author: patrick garnaut
// date: AUG 2010
//
// small piece of rubbish code to read a file and run the sha256 over it
//
//
#include "sha256.h"
#include "types.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE 256
void usage(int argc, char **argv)
{
printf("%s <filename> (optionally -v)\n", argv[0]);
exit(1);
}
int main(int argc, char **argv)
{
FILE *f;
char *fname = 0;
uint8 buf[CHUNK_SIZE];
uint8 hash[32];
uint32 res;
uint64 fileSize = 0;
Sha256Digest sha;
int verbose = 0;
#ifdef uint32
printf("defined\n");
#endif
if(argc < 2)
usage(argc, argv);
for(int i=1; i<argc; i++)
if(!strcasecmp(argv[i], "-v"))
verbose = 1;
else
fname = argv[i];
if((f = fopen(fname, "rb")))
{
while( (res = fread(buf, 1, CHUNK_SIZE, f)) > 0 && (fileSize += res))
sha.update(buf, res);
sha.finalise();
sha.getHash(hash);
for(int i=0; i<32; i++)
printf("%.2x", hash[i]);
if(verbose)
printf(" %s %lld\n", argv[1], fileSize);
else
printf("\n");
}
else
{
printf("error opening: %s\n", argv[1]);
return 1;
}
return 0;
} | true |
79f5ddc8435751378a9aaa083b0fd8769d85c23a | C++ | Mathrix16/ASD | /Mergesort.cpp | UTF-8 | 1,062 | 3.328125 | 3 | [] | no_license | #include "Mergesort.h"
void Mergesort::merge(int input[], int left, int middle, int right)
{
int n1 = middle - left + 1;
int n2 = right - middle;
int* L = new int[n1];
int* R = new int[n2];
for (int i = 0; i < n1; i++)
L[i] = input[left + i];
for (int j = 0; j < n2; j++)
R[j] = input[middle + 1 + j];
int i = 0;
int j = 0;
int k = left;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
input[k] = L[i];
i++;
}
else
{
input[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
input[k] = L[i];
i++;
k++;
}
while (j < n2)
{
input[k] = R[j];
j++;
k++;
}
delete[] L;
delete[] R;
}
void Mergesort::Sort(int input[], int left, int right)
{
if (left < right)
{
int m = left + (right - left) / 2;
Sort(input, left, m);
Sort(input, m + 1, right);
merge(input, left, m, right);
}
}
| true |
5a80b3db9e3af8573d3d130ed331abd797d38aae | C++ | rlannon/csin | /src/parser/statement/function_definition.hpp | UTF-8 | 773 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "definition.hpp"
#include "../../util/data_type.hpp"
namespace statement
{
class function_definition : public definition
{
std::vector<std::unique_ptr<statement_base>> formal_parameters;
data_type return_type;
public:
const data_type& get_type_information() const;
std::vector<const statement_base*> get_formal_parameters() const;
function_definition(const std::string& name,
const data_type& return_type,
std::vector<std::unique_ptr<statement_base>>& args_ptr,
std::unique_ptr<statement_block>&& procedure_ptr);
function_definition();
virtual ~function_definition() = default;
};
}
| true |
8b75554c7b270df55fee7e78ef8889dd34016029 | C++ | AlolyanRoaa/CircuitDesign-5Servos-potentiometers | /5_servos_with_potentiometer1.ino | UTF-8 | 1,187 | 3.03125 | 3 | [] | no_license | // C++ code
//
#include <Servo.h>
Servo gripper, wrist, elbow, shoulder, base;
int gpin = 5;// analog pin used to connect the potentiometer
int wpin = 4;
int epin = 3;
int spin = 2;
int bpin = 1;
int gval, wval, eval, sval, bval; // variable to read the value from the analog pin
void setup()
{
gripper.attach(9);
wrist.attach(10);
elbow.attach(6);
shoulder.attach(5);
base.attach(11);
}
void loop()
{
gval = analogRead(gpin); // reads the value of potentiometer (value originally btw 0 and 1023)
gval = map(gval,0 , 1023, 0, 180); // set to use it w/servo ( and set value btw 0 and 180)
gripper.write(gval); // sets the servo position to the value
delay(15); // waits for the servo to move
wval = analogRead(wpin);
wval = map(wval,0 , 1023, 0, 180);
wrist.write(wval);
delay(15);
eval = analogRead(epin);
eval = map(eval,0 , 1023, 0, 180);
elbow.write(eval);
delay(15);
sval = analogRead(spin);
sval = map(sval,0 , 1023, 0, 180);
shoulder.write(sval);
delay(15);
bval = analogRead(bpin);
bval = map(bval,0 , 1023, 0, 180);
base.write(bval);
delay(15);
} | true |
0cbca0cd1774bccbe1d83d966eb834654f6e9c61 | C++ | alexandraback/datacollection | /solutions_5634947029139456_1/C++/Zwergesel/solution.cpp | UTF-8 | 1,983 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int n, l;
string a[150], b[150];
int a1[40], b1[40];
void flip(int j) {
for (int i=0; i<n; i++) {
a[i][j] = '1' + '0' - a[i][j];
}
}
bool prefix(int k) {
for (int i=0; i<n; i++) {
for (int j=0; j<=k; j++) {
if (a[i][j] != b[i][j]) return false;
}
}
return true;
}
int rsolve(int j) {
if (j == l) return prefix(j-1) ? 0 : -1;
//cout << a1[j] << " " << b1[j] << "\n";
if (a1[j] == b1[j]) {
//cout << "Bit " << j << " is good\n";
sort(a, a+n);
sort(b, b+n);
bool flipable = n % 2 == 0 && a1[j] == n / 2;
if (flipable) {
//cout << "Flipable, try both\n";
int s1 = prefix(j) ? rsolve(j+1) : -1;
flip(j);
sort(a, a+n);
sort(b, b+n);
int s2 = prefix(j) ? rsolve(j+1) : -1;
if (s2 >= 0) s2++;
flip(j);
if (s1 < 0) return s2;
if (s2 < 0) return s1;
return min(s1, s2);
} else if (prefix(j)) {
//cout << "Prefix is good\n";
return rsolve(j+1);
} else {
//cout << "Prefix is wrong and not flipable\n";
return -1;
}
} else if (n - a1[j] == b1[j]) {
//cout << "Bit " << j << " is force-flip\n";
flip(j);
sort(a, a+n);
sort(b, b+n);
if (!prefix(j)) {
flip(j);
return -1;
} else {
int s = rsolve(j+1);
if (s >= 0) s++;
flip(j);
return s;
}
} else {
//cout << "Bit " << j << " is wrong\n";
return -1;
}
}
int solve() {
cin >> n >> l;
// Reset & Read
fill_n(a1, l, 0);
fill_n(b1, l, 0);
for (int i=0; i<n; i++) {
cin >> a[i];
for (int j=0; j<l; j++) {
if (a[i][j] == '1') a1[j]++;
}
}
for (int i=0; i<n; i++) {
cin >> b[i];
for (int j=0; j<l; j++) {
if (b[i][j] == '1') b1[j]++;
}
}
// Process
return rsolve(0);
}
int main() {
int t;
cin >> t;
for (int casenum=1; casenum<=t; casenum++) {
cout << "Case #" << casenum << ": ";
int solution = solve();
if (solution >= 0) {
cout << solution << "\n";
} else {
cout << "NOT POSSIBLE\n";
}
}
return 0;
} | true |
827e5bb0106ade1c865d9245506559863a7328fd | C++ | Jasuse/BitIO | /BitReader.cpp | UTF-8 | 961 | 3.1875 | 3 | [] | no_license | #include "BitReader.h"
BitReader::BitReader(std::fstream* stream) : m_stream(stream), buffer(0), bitcount(0)
{
if (!stream->is_open())
{
throw std::runtime_error("Unable to initialize closed filestream");
}
}
bool BitReader::good()
{
return (m_stream->good() && (m_stream->peek(), !m_stream->eof())) || (bitcount != 0);
}
bool BitReader::ReadBit()
{
if (!bitcount)
{
if (m_stream->good())
{
*m_stream >> buffer;
bitcount = 8;
}
else
{
throw std::runtime_error("File stream is not good :(");
}
}
--bitcount;
return (buffer >> bitcount) & 1;
}
unsigned char BitReader::ReadByte()
{
if (bitcount == 8)
{
bitcount = 0;
return buffer;
}
unsigned char res = 0;
for (int i = 0; i < 8; ++i)
{
res |= (ReadBit() << i);
}
return res;
}
void BitReader::Close()
{
m_stream->close();
}
| true |
7ddd5d4f14dcf5d0e0c0e5fec775e1f7b8890a07 | C++ | wlhee/practice-on-programming | /week3/CDragon.cpp | UTF-8 | 892 | 3.15625 | 3 | [] | no_license | #include "CWarrior.hpp"
#include "Type.hpp"
class CDragon: public CWarrior {
private:
Weapon weapon;
int damage;
float morale;
public:
CDragon(int id, const CHeadquarter *pHQ, WarriorType type, int strength);
Weapon getWeapon() const { return weapon; }
void setWeapon(Weapon &w) { weapon = w; }
int getDamage() const { return damage; }
void setDamage(int d) { damage = d; }
float getMorale() const { return morale; }
void setMorale(double &m) { morale = m; }
void print() const;
};
CDragon::CDragon(int id, const CHeadquarter *pHQ, WarriorType type, int life)
:CWarrior(id, pHQ, type, life)
{
weapon = (Weapon)(id%3);
morale = (double)(pHQ -> getLifePool()) / life;
}
void CDragon::print() const {
std::cout << "It has a " << weaponString[weapon]
<< ",and it's morale is ";
std::cout.precision(2);
std::cout << morale << std::endl;
}
| true |
d23c1a11b2371651e9d4bedaee8a94971ee5a264 | C++ | lucasjliu/web | /src/Poller.cpp | UTF-8 | 3,009 | 2.78125 | 3 | [] | no_license | //
// Poller.cpp
//
// by jiahuan.liu
// 11/28/2016
//
#include <unistd.h>
#include "Poller.h"
#include "Logger.h"
#ifdef OS_LINUX
#include <sys/epoll.h>
#elif defined(__APPLE__) || defined(MACH)
#include <sys/event.h>
#else
#error "platform unsupported"
#endif
#ifdef OS_LINUX
class Epoller : public PollerBase
{
public:
Epoller();
~Epoller();
void create(int iMaxConn = MAX_CONN) override;
void add(int fd, void* data, uint32_t events) override;
void del(int fd, void* data, uint32_t events) override;
void mod(int fd, void* data, uint32_t events) override;
int wait(int iMs) override;
private:
void _ctrl(int fd, void* data, uint32_t events, uint32_t op) override;
private:
bool _et;
epoll_event* _actEv;
};
PollerBase* newInstance() {return new Epoller();}
#elif defined(__APPLE__) || defined(MACH)
class Kqueue : public PollerBase
{
public:
Kqueue();
~Kqueue();
void create(int iMaxConn = MAX_CONN) override;
void add(int fd, void* data, uint32_t events) override;
void del(int fd, void* data, uint32_t events) override;
void mod(int fd, void* data, uint32_t events) override;
int wait(int iMs) override;
struct kevent& get(int i) const {return _actEv[i];}
private:
void _ctrl(int fd, void* data, uint32_t events, uint32_t op) override;
private:
struct kevent* _actEv;
};
PollerBase* newInstance() {return new Kqueue();}
Kqueue::Kqueue()
{
_fd = -1;
_actEv = nullptr;
_maxConn = MAX_CONN;
}
Kqueue::~Kqueue()
{
if (_actEv)
{
delete[] _actEv;
_actEv = nullptr;
}
if (_fd > 0)
{
::close(_fd);
}
}
void Kqueue::create(int iMaxConn)
{
_fd = kqueue();
if (_fd < 0)
{
LOG_FATAL << "kqueue init error";
throw Exception("kqueue init error");
}
_maxConn = iMaxConn;
if (_actEv)
{
delete[] _actEv;
}
_actEv = new struct kevent[_maxConn];
}
void Kqueue::_ctrl(int fd, void* data, uint32_t events, uint32_t op)
{
struct timespec now;
now.tv_nsec = 0;
now.tv_sec = 0;
struct kevent ev[2];
int n = 0;
if (events & READ_EVENT)
{
EV_SET(&ev[n++], fd, EVFILT_READ, op, 0, 0, data);
}
if (events & WRITE_EVENT)
{
EV_SET(&ev[n++], fd, EVFILT_WRITE, op, 0, 0, data);
}
if (kevent(_fd, ev, n, NULL, 0, &now))
{
LOG_FATAL << "kqueue ctrl error";
throw Exception("kqueue ctrl error");
}
}
void Kqueue::add(int fd, void* data, uint32_t events)
{
_ctrl(fd, data, events, EV_ADD|EV_ENABLE);
}
void Kqueue::del(int fd, void* data, uint32_t events)
{
_ctrl(fd, data, events, EV_DELETE);
}
void Kqueue::mod(int fd, void* data, uint32_t events)
{
_ctrl(fd, data, events, EV_ADD|EV_ENABLE);
}
int Kqueue::wait(int iMs)
{
struct timespec timeout;
timeout.tv_sec = iMs / 1000;
timeout.tv_nsec = (iMs % 1000) * 1000 * 1000;
return kevent(_fd, NULL, 0, _actEv, _maxConn, &timeout);
}
#endif | true |
0decf70a7047080f9fc8394ae94c6f05e03bb765 | C++ | gaozihang/ShadowMap_Point_Light_OpenGL | /opengl4.3_test_program/camera.h | UTF-8 | 2,704 | 3.0625 | 3 | [] | no_license | #pragma once
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
enum Camera_Movement {
FORWARD,
BACKWARD,
LEFT,
RIGHT
};
const float PITCH = 0.0f;
const float YAW = -90.0f;
const float SPEED = 2.5f;
const float SENSITIVITY = 0.1f;
const float ZOOM = 45.0f;
class Camera
{
public:
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;
float Yaw;
float Pitch;
float MovementSpeed;
float MouseSensitivity;
float Zoom;
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f),
float yaw = YAW, float pitch = PITCH)
{
Front = glm::vec3(0.0f, 0.0f, -1.0f);
MovementSpeed = SPEED;
MouseSensitivity = SENSITIVITY;
Zoom = ZOOM;
Position = position;
WorldUp = up;
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
glm::mat4 GetViewMatrix()
{
glm::vec3 front = glm::normalize(-Front);
glm::vec3 right = glm::normalize(glm::cross(glm::normalize(WorldUp), front));
glm::vec3 up = glm::normalize(glm::cross(front, right));
float tmp1[16] = {
right.x, up.x, front.x, 0,
right.y, up.y, front.y, 0,
right.z, up.z, front.z, 0,
0, 0, 0, 1
};
float tmp2[16] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-Position.x, -Position.y, -Position.z, 1
};
return glm::make_mat4(tmp1) * glm::make_mat4(tmp2);
//return glm::lookAt(Position, Position + Front, Up);
}
void ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
Position += Front * velocity;
if (direction == BACKWARD)
Position -= Front * velocity;
if (direction == LEFT)
Position -= Right * velocity;
if (direction == RIGHT)
Position += Right * velocity;
//Position.y = 0.0f;
}
void ProcessMouseMovement(float xoffset, float yoffset, bool constrainPitch = true)
{
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
if (constrainPitch)
{
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
}
updateCameraVectors();
}
void ProcessMouseScroll(float yoffset)
{
if (Zoom >= 1.0f && Zoom <= 45.0f)
Zoom -= yoffset;
if (Zoom <= 1.0f)
Zoom = 1.0f;
if (Zoom >= 45.0f)
Zoom = 45.0f;
}
private:
void updateCameraVectors()
{
glm::vec3 front;
front.x = cos(glm::radians(Pitch)) * cos(glm::radians(Yaw));
front.y = sin(glm::radians(Pitch));
front.z = cos(glm::radians(Pitch)) * sin(glm::radians(Yaw));
Front = glm::normalize(front);
Right = glm::normalize(glm::cross(Front, WorldUp));
Up = glm::normalize(glm::cross(Right, Front));
}
}; | true |
d4877502b6f2d288bba9a3dff7c3dc921d0d1156 | C++ | flappyZeng/C-plus-plus-Learning | /TextQuery.cpp | GB18030 | 2,909 | 3.046875 | 3 | [] | no_license | #include"TextQuery.h"
TextQuery::TextQuery(std::ifstream& infile):file(new std::vector<std::string>()) {
std::string line;
std::string word;
int countLine = 0;
while (std::getline(infile, line))
{
file->emplace_back(line);
std::istringstream iss(line);
while (iss >> word)
{
auto& lines = wm[word]; //map±Ĭµļֵ
if (!lines)
lines.reset(new std::set<line_no>); //resetָָµڴռ䣬ԭָʾĿռ
lines->insert(countLine);
}
countLine++;
}
}
TextQueryWithStrBlob::TextQueryWithStrBlob(std::ifstream& infile): file(new StrBlob())
{
std::string line;
std::string word;
int countLine = 0;
while (std::getline(infile, line))
{
file->push_back(line);
std::istringstream iss(line);
while (iss >> word)
{
auto& lines = wm[word]; //map±Ĭµļֵ
if (!lines)
lines.reset(new std::set<line_no>); //resetָָµڴռ䣬ԭָʾĿռ
lines->insert(countLine);
}
countLine++;
}
}
QueryResult TextQuery::query(const std::string& s) const
{
static wsetp nodata(new std::set<line_no>); //̬ͿԵò
auto loc = wm.find(s);
if (loc == wm.end())
{
return QueryResult(s, nodata, file);
}
else
return QueryResult(s, loc->second, file);
}
QueryResultWithSrBlob TextQueryWithStrBlob::query(std::string& s)
{
static wsetp nodata(new std::set<line_no>); //̬ͿԵò
auto loc = wm.find(s);
if (loc == wm.end())
{
return QueryResultWithSrBlob(s, nodata, file);
}
else
return QueryResultWithSrBlob(s, loc->second, file);
}
std::ostream& print(std::ostream& os,const QueryResult& query_result)
{
os << query_result.sought << " occurs " << query_result.lines->size() << " "
<< make_plural(query_result.lines->size(), "time", "s") << std::endl;
for (auto num : *query_result.lines)
{
os << "\t(line " << num + 1 << ") ";
os << *(query_result.file->begin() + num) << std::endl;
}
std::cout << std::endl;
return os;
}
std::ostream& print(std::ostream& os, const QueryResultWithSrBlob& query_result)
{
os << query_result.sought << " occurs " << query_result.lines->size() << " "
<< make_plural(query_result.lines->size(), "time", "s") << std::endl;
for (auto num : *query_result.lines)
{
os << "\t(line " << num + 1 << ") ";
os << StrBlobPtr(*query_result.file,num).deref() << std::endl;
}
std::cout << std::endl;
return os;
}
std::string make_plural(size_t ctr, const std::string& word, const std::string& end)
{
return (ctr > 1) ? word + end : word;
}
void runQueries(std::ifstream& infile)
{
TextQueryWithStrBlob tq(infile);
while (true)
{
std::cout << "Enter wrod to look for, or q to quit: ";
std::string s;
if (!(std::cin >> s) || s == "q") break;
print(std::cout, tq.query(s));
}
}
| true |
9c9f66a18d78a2d90b09d9032aac5bc65d5a41de | C++ | laurensiusadi/elearning-pweb | /public/similarity_plugin/input/10/12/10 12 5112100100--3.12.cpp | UTF-8 | 543 | 3.421875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
class Account
{
private :
int accountBalance;
public :
Account(int aB)
{
if(aB>=0)
accountBalance=aB;
else
{
accountBalance=0;
cout<<"Initial balance was invalid\n";
}
}
void credit(int nominal)
{
accountBalance+=nominal;
}
void debit(int nilai)
{
if(nilai<=accountBalance)
accountBalance-=nilai;
else
cout<<"Debit amount exceeded account balance\n";
}
int returnBalance()
{
return accountBalance;
}
};
int main()
{
return 0;
}
| true |
2052325c5092e5d2a6ae7baa3fcbea1237971218 | C++ | confusedconsciousness/geeks-for-geeks | /Graph/directed_graph_check_cyclicity.cpp | UTF-8 | 4,277 | 3.625 | 4 | [] | no_license | #include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int EDGES = 100;
int INPUTS[EDGES][2]; // at max we can have 100 edges
/*
In this problem we'll be given an directed graph, our aim is to detect whether there is a cycle present?
This problem is little bit tricky than its undirected counterpart
The idea is you are given a source and if you reach your source again while searching then there exists a cycle
*/
// *************** CREATE GRAPH UNDIRECTED *******************
struct Node{
int value;
vector<struct Node*> neighbours;
bool visited;
};
struct Node* create_node(int value){
struct Node* new_node = new Node();
new_node->value = value;
new_node->visited = false;
return new_node;
}
void link_them(int n1, int n2, struct Node** arrayOfNodes){
// this function takes two parameters
// the value of nodes i.e n1 and n2
// this function adds n2 to n1s neighbour and not n1 to n2s since it is directed
struct Node* node1 = arrayOfNodes[n1];
struct Node* node2 = arrayOfNodes[n2];
node1->neighbours.push_back(node2);
}
int bfs(struct Node* S){
queue<struct Node*> Q;
S->visited = true;
Q.push(S);
while(!Q.empty()){
struct Node* current_node = Q.front();
//cout<<"total neighbours: "<<current_node->neighbours.size()<<"\n";
Q.pop();
// we will look at its all neighbours
for(int i = 0; i < current_node->neighbours.size(); ++i){
if(current_node->neighbours[i]->visited == true && current_node->neighbours[i] == S){
// there exist a cycle
return 1;
}else if(current_node->neighbours[i]->visited == false){
// visit the node
current_node->neighbours[i]->visited = true;
Q.push(current_node->neighbours[i]);
}
}
}
return 0;
}
void reinitialise(struct Node** arrayOfNodes, int n){
struct Node* temp;
for(int i = 0; i < n; ++i){
temp = arrayOfNodes[i];
temp->visited = false;
}
}
// Different approach
// we'll store the ancestor into a vector and as we check if there is a neighbour which is visited and ancestor then you return true
vector<struct Node*> ancestors;
bool dfs_visit(struct Node* S){
S->visited = true;
// we'll look its neighbours but before let's push it into the ancestors
ancestors.push_back(S);
for(int i = 0; i < S->neighbours.size(); ++i){
if(S->neighbours[i]->visited == true){
// let's look in the ancestor list
for(int j = 0; j < ancestors.size(); ++j){
if(ancestors[j] == S->neighbours[i]){
cout<<" called";
return 1;
}
}
return 0;
}else if(S->neighbours[i]->visited == false){
dfs_visit(S->neighbours[i]);
}
}
return 0;
}
int dfs(struct Node** arrayOfNodes, int n){
int sum = 0;
for(int i = 0; i < n; ++i){
if(arrayOfNodes[i]->visited == false){
sum += dfs_visit(arrayOfNodes[i]);
}
}
}
int main(){
// input will be in the following format
// n, e // n is total nodes and e is total edges
// followed by e lines taking input
// e1, e2 means e1 is connected to e2
int n, e;
cin>>n>>e;
for(int i = 0; i < e; ++i){
for(int j = 0; j < 2; ++j){
cin>>INPUTS[i][j];
}
}
// let's create n nodes
struct Node* arrayOfNodes[n];
for(int i = 0; i < n; ++i){
arrayOfNodes[i] = create_node(i); // we are naming the nodes from 0 to n - 1
}
// it's time to make links
int n1, n2;
for(int i = 0; i < e; ++i){
n1 = INPUTS[i][0];
n2 = INPUTS[i][1];
link_them(n1, n2, arrayOfNodes);
}
// BFS approach kind of poor irony
int sum = 0;
for(int i = 0; i < n; ++i){
if(sum > 0){
break;
}
sum += bfs(arrayOfNodes[i]);
reinitialise(arrayOfNodes, n);
}
if(sum > 0){
cout<<"There exists a cycle";
}else{
cout<<"No cycle exists";
}
// DFS approach
//cout<<"Cycle?: "<<dfs(arrayOfNodes, n);
return 0;
} | true |
d2fadf898579b49167fe61014b35908e34a39343 | C++ | void-trinity/OOPs-Assignment | /Assignment 4/5.cpp | UTF-8 | 1,294 | 4 | 4 | [] | no_license | #include <iostream>
using namespace std;
int days_arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class Date{
public:
int day, month, year;
void add_days(int d){
while(d){
day++;
d--;
if(day > days_arr[month-1])
{
day = 1;
month++;
if (month == 13)
{
year++;
month = 1;
}
}
}
}
void subtract_days(int d){
while(d){
d--;
day--;
if(day <= 0)
{
month--;
if(month == 0)
{
year--;
month = 12;
}
day = days_arr[month-1];
}
}
}
};
int main()
{
Date d1;
int days;
cout << "Enter date: ";
cin >> d1.day >> d1.month >> d1.year;
cout << endl << "Enter days to be added: ";
cin >> days;
d1.add_days(days);
cout << endl << d1.day << "-" << d1.month << "-" << d1.year;
cout << endl << "Enter days to be subtracted: ";
cin >> days;
d1.subtract_days(days);
cout << endl << d1.day << "-" << d1.month << "-" << d1.year;
return 0;
}
| true |
34316c0030565e55be7d8d09a7a26722c9efab1b | C++ | DanielDelchev/vector-vs-list-comparisson | /VectorTester.cpp | UTF-8 | 8,756 | 3.6875 | 4 | [] | no_license | #include "VectorTester.h"
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <iostream>
#include <algorithm>
/**
* @brief this function currenty does nothing
* @detailed this function is private and it contains the action which must be preformed in the destructor,should any dynamic memory be handled manually
* @see VectorTester::~VectorTester()
* @return nothing, function is void
* @date 16/01/2016
*/
void VectorTester::destroy(){
}
/**
* @brief Class destructor
* @detailed virtual destructor for the class, currently does nothing since no dynamic memory is being handled manually
* @see VectorTester::destroy()
* @return nothing
* @date 16/01/2016
*/
VectorTester::~VectorTester(){
destroy();
}
/**
* @brief Class constructor
* @detailed creates a VectorTester whith n integers integers inserted in its vector container
* @param count - the number of elements to be intialized in the container
* @return nothing it s a constructor
* @date 16/01/2016
*/
VectorTester::VectorTester(size_t count):sorted(false){
vec.assign(count,42);/** replaces the content of the container with "count" cpoies of 42 */
} /** since this is a constructor no destruction of old elements takes place */
/**
* @brief container capacity
* @detailed returns the current capacity of the container
* @return the current capacity of the container
* @date 16/01/2016
*/
size_t VectorTester::capacity()const{
return vec.vector::capacity();
}
/**
* @brief container size
* @detailed returns the current size of the container meaning how many integers are stored in it currently
* @return the current size of the container
* @date 16/01/2016
*/
size_t VectorTester::size()const{
return vec.vector::size();
}
/**
* @brief check wheter the container is empty
* @detailed performs a check whether the container is empty
* @return wheter the container is empty
* @date 16/01/2016
*/
bool VectorTester::empty()const{
return vec.vector::empty();
}
/**
* @brief adds an integer at the back of the container
* @detailed puts the given integer at the back of the container which is a vector
* @return void
* @param x - the integer we are adding
* @date 16/01/2016
*/
void VectorTester::push_back(int x){
if (size()!=0 && x < vec[size()-1] ){
sorted = false;
}
vec.vector::push_back(x);
}
/**
* @brief removes an integer from the back of the container
* @detailed removes the last integer at the back of the container
* @return void
* @date 16/01/2016
*/
void VectorTester::pop_back(){
vec.vector::pop_back();
}
/**
* @brief removes all content from the container
* @detailed removes all integers in the vector using the pop_back() member-function
* @return void
* @see pop_back()
* @date 16/01/2016
*/
void VectorTester::clear(){
while (!empty()){
pop_back();
}
}
/**
* @brief inserts an element into the container
* @detailed adds the integer x at the specified positon of the container (if possible) if position is not valid then position%=size
* @return void
* @param position- the index of the position at which we want to add the element x
* @param x - the integer we want to add
* @date 16/01/2016
*/
void VectorTester::insertAt(size_t position,int x){
sorted = false;
if (position < size()){
std::vector<int> :: iterator at_pos = begin() + position;
vec.vector::insert(at_pos,x);
}
if (position >= size() && empty()){ // if the position is not valid and container is empty
std::vector<int> :: iterator at_pos = begin();
vec.vector::insert(at_pos,x);
}
else if (position >= size() && !empty()){ // if the position is not valid and container not empty
std::vector<int> :: iterator at_pos = begin() + (position % size()); //if containe was empty we would be performing (int)position % 0
vec.vector::insert(at_pos,x);
}
}
/**
* @brief removes an element from the container
* @detailed removes the integer at the specified positon of the container (if possible) if position is not valid then position%=size
* @return void
* @param position- the index of the position from which we want to remove an element
* @date 16/01/2016
*/
void VectorTester::removeAt(size_t position){
if (!empty()){//making sure the container is not empty already, in which case removing is impossible
if (position < size()){
std::vector<int> :: iterator at_pos = begin() + position;
vec.vector::erase(at_pos);
}
if (position >= size()){
std::vector<int> :: iterator at_pos = begin() + (position % size());
vec.vector::erase(at_pos);
}
}
}
/**
* @brief iterator
* @return an iterator to the beginning of the container
* @date 16/01/2016
*/
std::vector<int> :: iterator VectorTester::begin(){
return vec.vector::begin();
}
/**
* @brief iterator
* @return an iterator to the end of the container
* @date 16/01/2016
*/
std::vector<int> :: iterator VectorTester::end(){
return vec.vector::end();
}
/**
* @brief iterator
* @return an iterator to the reversed beginning of the container
* @date 16/01/2016
*/
std::vector<int> :: reverse_iterator VectorTester::rbegin(){
return vec.vector :: rbegin();
}
/**
* @brief iterator
* @return an iterator to the reversed end of the container
* @date 16/01/2016
*/
std::vector<int> :: reverse_iterator VectorTester::rend(){
return vec.vector::rend();
}
/**
* @brief constant iterator
* @return a constant iterator to the beginning of the container
* @date 16/01/2016
*/
std::vector<int> :: const_iterator VectorTester::cbegin()const{
return vec.vector::cbegin();
}
/**
* @brief constnat iterator
* @return a constant iterator to the end of the container
* @date 16/01/2016
*/
std::vector<int> :: const_iterator VectorTester::cend()const{
return vec.vector::cend();
}
/**
* @brief constnat iterator
* @return a constant iterator to the reversed beginning of the container
* @date 16/01/2016
*/
std::vector<int> :: const_reverse_iterator VectorTester::crbegin()const{
return vec.vector::crbegin();
}
/**
* @brief constant iterator
* @return a constant iterator to the reversed end of the container
* @date 16/01/2016
*/
std::vector<int> :: const_reverse_iterator VectorTester::crend()const{
return vec.vector::crend();
}
/**
* @brief prints the vector content
* @return void
* @date 16/01/2016
*/
void VectorTester::printContent()const{
size_t counter= size();
for (size_t i=0;i<counter;++i){
std::cout<<vec[i]<<" ";
}
std::cout<<std::endl;
}
/**
* @brief operator for reference
* @return reference to the integer in the specified position
* @param position - the position for which a reference is returned
* @date 16/01/2016
*/
int& VectorTester::operator[](size_t position){
return vec[position];
}
/**
* @brief operator for constant reference
* @return constant reference to the integer in the specified position
* @param position - the position for which a constant reference is returned
* @date 16/01/2016
*/
const int& VectorTester::operator[](size_t position)const{
return vec[position];
}
/**
* @brief tells us if the container is sorted ascendingly
* @return a check whether the container is sorted ascendingly
* @date 16/01/2016
*/
bool VectorTester::isSorted()const{
return sorted;
}
/**
* @brief sorts the vector using <algorithm> library function sort(iterator,iterator)
* @return void
* @date 16/01/2016
*/
void VectorTester::sort(){
std::sort(vec.begin(),vec.end());
sorted=true;
}
/**
* @brief performs binary search
* @detailed this function is private and shall not be called over an unsorted container
* @return the position at which the element has been found or -1 if it hasnt been found
* @date 16/01/2016
*/
int VectorTester::find(int x,int left,int right)const{
if (left>right){
return -1;
}
int medium = (left + right)/2;
if ( vec[medium] ==x){
return medium;
}
else if (x > vec[medium]){
return find(x,medium+1,right);
}
else {
return find(x,left,right-1);
}
return -1;
}
/**
* @brief performs binary search
* @detailed this function is public
* @return pointer to the element we sought in the container or NULL if it hasnt been found
* @date 16/01/2016
*/
int* VectorTester::findElement(int x){
if (empty()){
return NULL;
}
if (!sorted){
sort();
}
int result = find(x,0,size()-1);
if (result == -1){
return NULL;
}
return &(this->operator[](result));
}
| true |
fcfb28a6e6786456033713032d46e5a851033c18 | C++ | darcyg/Caramel | /include/Caramel/Numeric/NumberConverter.h | UTF-8 | 3,077 | 2.921875 | 3 | [] | no_license | // Caramel C++ Library - Numeric Amenity - Number Converter Header
#ifndef __CARAMEL_NUMERIC_NUMBER_CONVERTER_H
#define __CARAMEL_NUMERIC_NUMBER_CONVERTER_H
#pragma once
#include <Caramel/Setup/CaramelDefs.h>
#include <Caramel/Numeric/NumberTraits.h>
#include <cfloat>
namespace Caramel
{
///////////////////////////////////////////////////////////////////////////////
//
// Number Converter
// - Converters between arithmetic types.
//
// Primary Template
template< typename OutputT, typename InputT >
struct NumberConverter;
//
// Specialization - Output to Int32
//
template<>
struct NumberConverter< Int32, Int64 >
{
static Bool CanExactConvert( Int64 value )
{
return INT32_MIN <= value && value <= INT32_MAX;
}
};
template<>
struct NumberConverter< Int32, Uint64 >
{
static Bool CanExactConvert( Uint64 value )
{
return value <= INT32_MAX;
}
};
//
// Specialization - Output to Uint32
//
template<>
struct NumberConverter< Uint32, Int64 >
{
static Bool CanExactConvert( Int64 value )
{
return 0 <= value && value <= UINT32_MAX;
}
};
template<>
struct NumberConverter< Uint32, Uint64 >
{
static Bool CanExactConvert( Uint64 value )
{
return value <= UINT32_MAX;
}
};
//
// Specialization - Output to Float
//
template<>
struct NumberConverter< Float, Int32 >
{
static Bool CanExactConvert( Int32 value )
{
return FloatTraits::MIN_EXACT_INT32 <= value && value <= FloatTraits::MAX_EXACT_INT32;
}
};
template<>
struct NumberConverter< Float, Uint32 >
{
static Bool CanExactConvert( Uint32 value )
{
return value <= FloatTraits::MAX_EXACT_UINT32;
}
};
template<>
struct NumberConverter< Float, Int64 >
{
static Bool CanExactConvert( Int64 value )
{
return FloatTraits::MIN_EXACT_INT32 <= value && value <= FloatTraits::MAX_EXACT_INT32;
}
};
template<>
struct NumberConverter< Float, Uint64 >
{
static Bool CanExactConvert( Uint64 value )
{
return value <= FloatTraits::MAX_EXACT_UINT32;
}
};
template<>
struct NumberConverter< Float, Double >
{
static Bool CanExactConvert( Double value )
{
return -FLT_MAX <= value && value <= FLT_MAX;
}
};
//
// Specialization - Output to Double
//
template<>
struct NumberConverter< Double, Int32 >
{
static Bool CanExactConvert( Int32 value ) { return true; }
};
template<>
struct NumberConverter< Double, Uint32 >
{
static Bool CanExactConvert( Uint32 value ) { return true; }
};
template<>
struct NumberConverter< Double, Int64 >
{
static Bool CanExactConvert( Int64 value )
{
return DoubleTraits::MIN_EXACT_INT64 <= value && value <= DoubleTraits::MAX_EXACT_INT64;
}
};
template<>
struct NumberConverter< Double, Uint64 >
{
static Bool CanExactConvert( Uint64 value )
{
return value <= DoubleTraits::MAX_EXACT_UINT64;
}
};
///////////////////////////////////////////////////////////////////////////////
} // namespace Caramel
#endif // __CARAMEL_NUMERIC_NUMBER_CONVERTER_H
| true |
0585573e99bbea56084b1ef0bafe04814da9e674 | C++ | TedaLIEz/SimpleH264 | /include/parser/parser.h | UTF-8 | 2,021 | 2.78125 | 3 | [] | no_license | //
// Created by aLIEzTed on 5/14/18.
//
#ifndef SIMPLEH264_PARSER_H
#define SIMPLEH264_PARSER_H
#include <sstream>
#include <context.h>
#include "h264/sps.h"
#include "util/golomb.h"
template<class T>
class Parser {
public:
Parser() = default;
virtual T parse(unsigned char *data, unsigned long len, unsigned long &offset) = 0;
virtual int getType() = 0;
virtual ~Parser() = default;
int uev_decode(unsigned char *data, unsigned long &offset, const std::string &name) {
long len = -1;
auto rst = golomb::get_uev_decode(data, offset, len);
std::ostringstream oss;
oss << "Error decoding " << name << " at offset " << offset;
ASSERT(len > 0, oss.str());
offset += len;
return rst;
}
int sev_decode(unsigned char *data, unsigned long &offset, const std::string &name) {
long len = -1;
auto rst = golomb::get_sev_decode(data, offset, len);
std::ostringstream oss;
oss << "Error decoding " << name << " at offset " << offset;
ASSERT(len > 0, oss.str());
offset += len;
return rst;
}
bool get_bool(unsigned char *data, unsigned long &offset) {
return static_cast<bool>(bit::get_bit(data, offset++));
}
unsigned long read_bit(unsigned char *data, unsigned long bit_len, unsigned long &offset) {
auto rst = bit::next_bit(data, bit_len, offset);
offset += bit_len;
return rst;
}
/**
* return 0 if we have more rbsp data, else return the length of trailing zeros
*
* @param data the encoded data store in unsigned char array
* @param len length of data in bytes
* @param offset offset by bits
* @return 0 if we have more rbsp data, else return the length of trailing zeros
*/
int more_rbsp_data(unsigned char *data, unsigned long len, unsigned long offset) {
auto trailing_len = len * 8 - offset;
auto trailing_rst = bit::next_bit(data, trailing_len, offset);
auto mask = 1 << (trailing_len - 1);
if (mask != trailing_rst) return 0;
else return trailing_len;
}
};
#endif //SIMPLEH264_PARSER_H
| true |
d901634d8d45f9dab7ac42d21a6b0fbe9bbbd4ad | C++ | flameshimmer/Leet2015_2.5 | /Leet2015_2.5/Leet2015_2/WordBreakII.cpp | UTF-8 | 482 | 3.109375 | 3 | [] | no_license | #include "stdafx.h"
//Given a string s and a dictionary of words dict, add spaces in s to
//construct a sentence where each word is a valid dictionary word.
//
//Return all such possible sentences.
//
//For example, given
//s = "catsanddog",
//dict = ["cat", "cats", "and", "sand", "dog"].
//
//A solution is["cats and dog", "cat sand dog"]
namespace Solution2_5
{
namespace WordBreakII
{
void Main()
{
}
}
}
| true |
ebfabef5de4599c71f7b2b21617c1c1c29647f2e | C++ | lwzswufe/CppCode | /Cmake/Sell_Strategy.cpp | UTF-8 | 424 | 2.5625 | 3 | [] | no_license | #include "Sell_Strategy.h"
void Sell_Strategy::init()
{
this->position_vec = {{"600000", 100}, {"600004", 54}};
}
void Sell_Strategy::run()
{
;
}
void Sell_Strategy::update(Stock_Data* data_ptr)
{
for(auto position: this->position_vec)
{
if(data_ptr->code == position.first &&
data_ptr->trade_pr - position.second > 5)
printf("sell code:%s", position.first.c_str());
}
} | true |
da45dbe96447dc664806ae87463d37a0afea039c | C++ | matheusmso/code | /uva/900.cpp | UTF-8 | 308 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
int f(int x) {
if (x == 1)
return 1;
if (x == 2)
return 2;
return f(x-1) + f(x-2);
}
int main() {
int x;
while(scanf("%d", &x) == 1) {
if (x == 0)
return 0;
printf("%d\n", f(x));
}
return 0;
}
| true |
3d6b0ee3920a41ff050c1970c776ecb8fb751182 | C++ | kerinin/arduino-splines | /spline.cpp | UTF-8 | 2,825 | 3.1875 | 3 | [] | no_license | #include "WProgram.h"
#include "spline.h"
#include <math.h>
Spline::Spline(void) {
_prev_point = 0;
}
Spline::Spline( float x[], float y[], int numPoints, int degree )
{
setPoints(x,y,numPoints);
setDegree(degree);
_prev_point = 0;
}
Spline::Spline( float x[], float y[], float m[], int numPoints )
{
setPoints(x,y,m,numPoints);
setDegree(Hermite);
_prev_point = 0;
}
void Spline::setPoints( float x[], float y[], int numPoints ) {
_x = x;
_y = y;
_length = numPoints;
}
void Spline::setPoints( float x[], float y[], float m[], int numPoints ) {
_x = x;
_y = y;
_m = m;
_length = numPoints;
}
void Spline::setDegree( int degree ){
_degree = degree;
}
float Spline::value( float x )
{
if( _x[0] > x ) {
return _y[0];
}
else if ( _x[_length-1] < x ) {
return _y[_length-1];
}
else {
for(int i = 0; i < _length; i++ )
{
int index = ( i + _prev_point ) % _length;
if( _x[index] == x ) {
_prev_point = index;
return _y[index];
} else if( (_x[index] < x) && (x < _x[index+1]) ) {
_prev_point = index;
return calc( x, index );
}
}
}
}
float Spline::calc( float x, int i )
{
switch( _degree ) {
case 0:
return _y[i];
case 1:
if( _x[i] == _x[i+1] ) {
// Avoids division by 0
return _y[i];
} else {
return _y[i] + (_y[i+1] - _y[i]) * ( x - _x[i]) / ( _x[i+1] - _x[i] );
}
case Hermite:
return hermite( ((x-_x[i]) / (_x[i+1]-_x[i])), _y[i], _y[i+1], _m[i], _m[i+1], _x[i], _x[i+1] );
case Catmull:
if( i == 0 ) {
// x prior to spline start - first point used to determine tangent
return _y[1];
} else if( i == _length-2 ) {
// x after spline end - last point used to determine tangent
return _y[_length-2];
} else {
float t = (x-_x[i]) / (_x[i+1]-_x[i]);
float m0 = (i==0 ? 0 : catmull_tangent(i) );
float m1 = (i==_length-1 ? 0 : catmull_tangent(i+1) );
return hermite( t, _y[i], _y[i+1], m0, m1, _x[i], _x[i+1]);
}
}
}
float Spline::hermite( float t, float p0, float p1, float m0, float m1, float x0, float x1 ) {
return (hermite_00(t)*p0) + (hermite_10(t)*(x1-x0)*m0) + (hermite_01(t)*p1) + (hermite_11(t)*(x1-x0)*m1);
}
float Spline::hermite_00( float t ) { return (2*pow(t,3)) - (3*pow(t,2)) + 1;}
float Spline::hermite_10( float t ) { return pow(t,3) - (2*pow(t,2)) + t; }
float Spline::hermite_01( float t ) { return (3*pow(t,2)) - (2*pow(t,3)); }
float Spline::hermite_11( float t ) { return pow(t,3) - pow(t,2); }
float Spline::catmull_tangent( int i )
{
if( _x[i+1] == _x[i-1] ) {
// Avoids division by 0
return 0;
} else {
return (_y[i+1] - _y[i-1]) / (_x[i+1] - _x[i-1]);
}
}
| true |
3cf3f2fa174252803d6171a42d1d4d75c797490c | C++ | changchuming/rpi-gun | /arduino/i2c/i2c.ino | UTF-8 | 2,288 | 2.875 | 3 | [] | no_license | #include <Wire.h>
#include <Servo.h>
#include <SoftwareSerial.h>
#define SLAVE_ADDRESS 0x04
// Servo
Servo pan_servo;
Servo tilt_servo;
int pan_pin = 10;
int tilt_pin = 11;
// Pan tilt angles
int pan_angle = 90;
int tilt_angle = 60;
int encoded_thetas = 0;
int pan_theta = 0;
int tilt_theta = 0;
int motorControl = 9;
int count = 0;
void setup() {
// Set up I2C
// Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receive_data);
Wire.onRequest(send_data);
// Serial.println("Ready!");
pinMode(motorControl, OUTPUT);
pan_servo.attach(pan_pin);
tilt_servo.attach(tilt_pin);
pan_servo.write(pan_angle);
tilt_servo.write(tilt_angle);
delay(1000);
}
void loop() {
delay(200);
if (count > 0) {
count++;
}
if (count > 3) {
count = 0;
digitalWrite(motorControl, LOW);
int pan_angle = 90;
int tilt_angle = 60;
pan_servo.attach(pan_pin);
tilt_servo.attach(tilt_pin);
pan_servo.write(pan_angle);
tilt_servo.write(tilt_angle);
delay(2000);
}
pan_servo.detach();
tilt_servo.detach();
}
void receive_data(int byte_count) {
// Serial.print("receive_data");
while (Wire.available()) {
// Read encoded pan tilt thetas
encoded_thetas = Wire.read();
// Serial.print("Data received: ");
// Serial.println(encoded_thetas);
// Pan and tilt thetas are encoded such that encoded_thetas = (pan_theta+8)*16+(tilt_theta+8)
// Pan and tilt thetas are in the range [-7, 7]
if (encoded_thetas == 0) {
run_motor();
} else {
pan_theta = encoded_thetas/16 - 8;
tilt_theta = encoded_thetas%16 - 8;
// Serial.println(pan_theta);
// Serial.println(tilt_theta);
pan_angle-=pan_theta;
tilt_angle+=tilt_theta;
if (pan_angle > 180) {pan_angle = 180;}
if (pan_angle < 0) {pan_angle = 0;}
if (tilt_angle > 180) {tilt_angle = 180;}
if (tilt_angle < 0) {tilt_angle = 0;}
// Servo
pan_servo.attach(pan_pin);
tilt_servo.attach(tilt_pin);
pan_servo.write(pan_angle);
tilt_servo.write(tilt_angle);
}
}
}
void send_data() {
Wire.write(encoded_thetas);
}
// Run motor to shoot water
void run_motor() {
// Serial.println("Run motor!");
digitalWrite(motorControl, HIGH);
count = 1;
}
| true |
a3a0ccca142aaef062930ce369322f048aa7e753 | C++ | NiteshPidiparars/CodeBlock | /C++/OverloadOperatorTimeClass.cpp | UTF-8 | 803 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
class Time
{
private:
int HR,MIN,SEC;
public:
void setTime(int h,int m,int s)
{
HR = h;
MIN = m;
SEC = s;
}
void showTime()
{
cout<<endl<<HR<<" : "<<MIN<<" : "<<SEC;
}
void normalize()
{
MIN = MIN+SEC/60;
SEC=SEC%60;
HR=HR+MIN/60;
MIN=MIN%60;
}
Time operator +(Time t)
{
Time temp;
temp.SEC = SEC + t.SEC;
temp.MIN = MIN + t.MIN;
temp.HR = HR + t.HR;
temp.normalize();
return(temp);
}
};
int main()
{
Time t1,t2,t3;
t1.setTime(4,35,26);
t2.setTime(3,50,45);
t3 = t1+t2;//t3 = t1.operator+(t2)
t1.showTime();
t2.showTime();
t3.showTime();
getch();
}
| true |
ed1b32950eefc0b3cdcc2ad62aa43a97760016ae | C++ | oujinhaoai/shadertoy | /source/body.h | UTF-8 | 663 | 2.6875 | 3 | [] | no_license | #pragma once
#include "utils.h"
struct Body
{
Body(const OVR::Vector3f& position, const OVR::Vector3f& angles);
void apply_inputs(const OVR::Vector3f& lin_inputs, const OVR::Vector3f& ang_inputs, float dt);
void integrate(float dt);
OVR::Matrix4f get_matrix() const;
private:
void updateController(SDL_Joystick* joystick, float dt, OVR::Vector3f& linImpulse, OVR::Vector3f& angImpulse);
OVR::Vector3f m_position; // position of the centre of the body
OVR::Quatf m_orientation; // Orientation of the body in quaternion form
OVR::Vector3f m_linear_velocity; // linear velocity
OVR::Vector3f m_angular_velocity; // rotational velocity
};
| true |
c11c79af21563c746042796a8bb42d78a6122c86 | C++ | SdobnovE/msu_cpp_autumn_2019 | /09/main.cpp | UTF-8 | 1,779 | 2.578125 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<fstream>
#include<queue>
#include<algorithm>
#include<thread>
#include<pthread.h>
#include<atomic>
#include<string>
#include<condition_variable>
#include<mutex>
#include<functional>
#include"sort.h"
using namespace std;
int main()
{
uint64_t* memory1 = new uint64_t[LEN];
uint64_t* memory2 = new uint64_t[LEN];
mutex mut;
ifstream File;
size_t que = 0;
size_t curr_que = 0, len1 = 0, len2 = 0;
string Data_Name = "data";
/*1*/auto time = std::chrono::high_resolution_clock::now();
create_data(Data_Name);
/*1*/auto T1 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - time ).count();
cout << "WRITE\n";
File.open(Data_Name, std::ios::binary);
/*2*/time = std::chrono::high_resolution_clock::now();
thread t1(bind(thread_func, data{memory1, memory2, len1, len2, mut, 0, File, que, curr_que}));
thread t2(bind(thread_func, data{memory1, memory2, len1, len2, mut, 1, File, que, curr_que}));
t1.join();
t2.join();
/*2*/auto T2 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - time ).count();
File.close();
/*3*/time = std::chrono::high_resolution_clock::now();
if (!compare_files(Data_Name, "final"))
cout << "WRONG SORT\n";
else
cout << "done\n";
/*3*/auto T3 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - time ).count();
cout << T1*1e-6 << " " << T2*1e-6 << " " << T3*1e-6 << endl;
//4.88018 37.3277 12.9579
delete[] memory1;
delete[] memory2;
return 0;
}
| true |
7212051262781d9a39b384b0c00a15ad5e5e4822 | C++ | cyx233/MyDB | /src/system/instance.h | UTF-8 | 3,695 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef THDB_INSTANCE_H_
#define THDB_INSTANCE_H_
#include "condition/conditions.h"
#include "defines.h"
#include "field/fields.h"
#include "index/index.h"
#include "manager/index_manager.h"
#include "manager/recovery_manager.h"
#include "manager/table_manager.h"
#include "manager/transaction_manager.h"
#include "record/transform.h"
#include "result/results.h"
#include "table/schema.h"
namespace thdb {
class Instance {
public:
Instance();
~Instance();
bool CreateTable(const String &sTableName, const Schema &iSchema,
bool useTxn = false);
bool DropTable(const String &sTableName);
/**
* @brief 获得列在表中的位置信息
*/
FieldID GetColID(const String &sTableName, const String &sColName) const;
/**
* @brief 获得列的类型
*/
FieldType GetColType(const String &sTableName, const String &sColName) const;
/**
* @brief 获得列的长度
*/
Size GetColSize(const String &sTableName, const String &sColName) const;
std::vector<PageSlotID> Search(const String &sTableName, Condition *pCond,
const std::vector<Condition *> &iIndexCond,
Transaction *txn = nullptr);
uint32_t Delete(const String &sTableName, Condition *pCond,
const std::vector<Condition *> &iIndexCond,
Transaction *txn = nullptr);
uint32_t Update(const String &sTableName, Condition *pCond,
const std::vector<Condition *> &iIndexCond,
const std::vector<Transform> &iTrans,
Transaction *txn = nullptr);
PageSlotID Insert(const String &sTableName,
const std::vector<String> &iRawVec,
Transaction *txn = nullptr);
Record *GetRecord(const String &sTableName, const PageSlotID &iPair,
Transaction *txn = nullptr) const;
std::vector<Record *> GetTableInfos(const String &sTableName) const;
std::vector<String> GetTableNames() const;
std::vector<String> GetColumnNames(const String &sTableName) const;
/**
* @brief 获取一个Table *指针,要求存在表,否则报错
*/
Table *GetTable(const String &sTableName) const;
/**
* @brief 判断列是否为索引列
*/
bool IsIndex(const String &sTableName, const String &sColName) const;
/**
* @brief 获取一个Index*指针,要求存在索引,否则报错
*/
Index *GetIndex(const String &sTableName, const String &sColName) const;
std::vector<Record *> GetIndexInfos() const;
bool CreateIndex(const String &sTableName, const String &sColName,
FieldType iType);
bool DropIndex(const String &sTableName, const String &sColName);
TransactionManager *GetTransactionManager() const {
return _pTransactionManager;
}
RecoveryManager *GetRecoveryManager() const { return _pRecoveryManager; }
/**
* @brief 实现多个表的JOIN操作
*
* @param iResultMap 表名和对应的Filter过程后PageSlotID结果的Map
* @param iJoinConds 所有表示Join条件的Condition的Vector
* @return std::pair<std::vector<String>, std::vector<Record *>>
* Pair第一项为JOIN结果对应的Table列的列名,列的顺序自行定义;
* Pair第二项为JOIN结果,结果数据Record*中的字段顺序需要和列名一致。
*/
std::pair<std::vector<String>, std::vector<Record *>> Join(
std::map<String, std::vector<PageSlotID>> &iResultMap,
std::vector<Condition *> &iJoinConds);
private:
TableManager *_pTableManager;
IndexManager *_pIndexManager;
TransactionManager *_pTransactionManager;
RecoveryManager *_pRecoveryManager;
};
} // namespace thdb
#endif
| true |
8cfb50fc6b95f5d04afa495af869073086ad2508 | C++ | olgt/Laboratorio_EDD_201612341_Proyecto1 | /arbol_binario.cpp | UTF-8 | 8,553 | 3.1875 | 3 | [] | no_license | #include "arbol_binario.h"
Arbol_Binario::Arbol_Binario()
{
this->raiz = NULL;
}
Arbol_Binario::~Arbol_Binario(){
Delete(this->raiz);
}
void Arbol_Binario::Delete(Nodo_Binario *raiz){
if(raiz==NULL){return;}
if(raiz->getIzquierda() != NULL){
Delete(raiz->getIzquierda());
}
if(raiz->getDerecha() != NULL){
Delete(raiz->getDerecha());
}
raiz->getListaPuntos()->~Lista_Puntos();
raiz->setIzquierda(NULL);
raiz->setDerecha(NULL);
delete raiz;
raiz = NULL;
}
Nodo_Binario* Arbol_Binario::getObjeto(int id, Nodo_Binario* raiz){
Nodo_Binario* actual = NULL;
if(raiz->getIzquierda() != NULL){
if(actual == NULL){
actual = getObjeto(id, raiz->getIzquierda());
}
}
if(raiz->getDerecha() != NULL){
if(actual == NULL){
actual = getObjeto(id, raiz->getDerecha());
}
}
if(id == raiz->getId()){
return raiz;
} else {
return actual;
}
}
Nodo_Binario* Arbol_Binario::getRaiz(){
return this->raiz;
}
Nodo_Binario* Arbol_Binario::insertar(Nodo_Binario* raiz, int id, string nombre, char letra, string color, Lista_Puntos* xy, Nodo_Binario* padre){
if(raiz==NULL){
raiz = new Nodo_Binario(id, nombre, letra, color, xy, padre);
raiz->setDerecha(NULL);
raiz->setIzquierda(NULL);
} else if(id<raiz->getId()){
Nodo_Binario* izq = insertar(raiz->getIzquierda(), id, nombre, letra, color, xy, raiz);
//izq->setIzquierda(NULL);
//izq->setDerecha(NULL);
if(izq->getId() != raiz->getId()){
raiz->setIzquierda(izq);
}
} else if(id>raiz->getId()){
Nodo_Binario* der = insertar(raiz->getDerecha(), id, nombre, letra, color, xy, raiz);
//der->setIzquierda(NULL);
//der->setDerecha(NULL);
if(der->getId() != raiz->getId()){
raiz->setDerecha(der);
}
} else if(id == raiz->getId()){
raiz->setId(id);
raiz->setName(nombre);
raiz->setLetra(letra);
raiz->setColor(color);
raiz->setListaPuntos(xy);
raiz->setPadre(padre);
}
return raiz;
}
void Arbol_Binario::recorrerPostorden(Nodo_Binario *raiz){
if(raiz->getIzquierda() != NULL){
recorrerPostorden(raiz->getIzquierda());
}
if(raiz->getDerecha() != NULL){
recorrerPostorden(raiz->getDerecha());
}
cout << "Dato: " << raiz->getId() << endl;
}
void Arbol_Binario::recorrerPreorden(Nodo_Binario *raiz){
cout << "Dato: " << raiz->getId() << endl;
if(raiz->getIzquierda() != NULL){
recorrerPreorden(raiz->getIzquierda());
}
if(raiz->getDerecha() != NULL){
recorrerPreorden(raiz->getDerecha());
}
}
void Arbol_Binario::recorrerInorden(Nodo_Binario* raiz){
if(raiz == NULL){
return;
}
recorrerInorden(raiz->getIzquierda());
cout << "* " << raiz->getId() << ". " << raiz->getName()
<< "#X: " << raiz->getListaPuntos()->getSizeX() << "#Y: " << raiz->getListaPuntos()->getSizeY() << endl;;
recorrerInorden(raiz->getDerecha());
}
Arbol_Binario* Arbol_Binario::copiarEsteArbolPreOrden(){
Arbol_Binario* nuevoArbol = new Arbol_Binario();
Nodo_Binario* raiz = this->getRaiz();
nuevoArbol->insertar(raiz->getId(), raiz->getName(), raiz->getLetra(), raiz->getColor(), raiz->getListaPuntos()->copiarEstaLista());
nuevoArbol->llenarArbolCopiado(raiz, nuevoArbol);
return nuevoArbol;
}
void Arbol_Binario::llenarArbolCopiado(Nodo_Binario* raiz, Arbol_Binario* nuevoArbol){
if(raiz == NULL){
return;
}
//Nodo_Binario* nuevo = new Nodo_Binario(raiz->getId(), raiz->getName(), raiz->getLetra(), raiz->getColor(), raiz->getListaPuntos()->copiarEstaLista(), NULL);
nuevoArbol->insertar(nuevoArbol->getRaiz(), raiz->getId(), raiz->getName(), raiz->getLetra(), raiz->getColor(), raiz->getListaPuntos()->copiarEstaLista(), NULL);
if(raiz->getIzquierda()!=NULL){
llenarArbolCopiado(raiz->getIzquierda(), nuevoArbol);
}
if(raiz->getDerecha()!=NULL){
llenarArbolCopiado(raiz->getDerecha(), nuevoArbol);
}
}
void Arbol_Binario::insertar(int id, string nombre, char letra, string color, Lista_Puntos* xy){
this->raiz=insertar(this->getRaiz(), id, nombre, letra, color, xy, NULL);
}
void Arbol_Binario::crearGrafica(string nombreProyecto, int idNivel){
Nodo_Binario* aux = this->getRaiz();
string nombreArchivo = "./Imagenes/" + nombreProyecto + "_Nivel_" + to_string(idNivel) + "_ABB" + ".gv";
string nombreGrafica = "./Imagenes/" + nombreProyecto + "_Nivel_" + to_string(idNivel) + "_ABB" + ".ps";
cout << "ARBOL BINARIO" << endl;
ofstream MyFile(nombreArchivo);
MyFile << "digraph G {";
MyFile << "\n";
MyFile << "rankdir = TB; \n";
MyFile << "node [shape=record, width=.1, height=.1]; \n";
if(this->getRaiz()->getDerecha() == NULL && this->getRaiz()->getIzquierda() == NULL){
MyFile << "Objeto_" << aux->getName() << aux->getId() << "; \n";
} else {
try {
crearGraficaRamas(MyFile, aux);
} catch (exception e) {
cout << e.what() << endl;
}
}
cout << "Done, ";
MyFile << "}";
MyFile.close();
try {
cout << "Creating, " << endl;
system(("dot -Tps " + nombreArchivo + " -o " + nombreGrafica).c_str());
cout << "Graph Done";
} catch (exception e) {
cout << "Oscar error occurred" << endl;
}
}
void Arbol_Binario::crearGraficaRamas(ofstream &file, Nodo_Binario* aux){
cout << "CodigoNodo: " << aux->getId() << endl;
if(aux->getIzquierda() != NULL){
file << "Objeto_" << aux->getName() << "_id_" << aux->getId() << "->" << "Objeto_" << aux->getIzquierda()->getName() << "_id_" << aux->getIzquierda()->getId() << "; \n";
crearGraficaRamas(file, aux->getIzquierda());
}
if(aux->getDerecha() != NULL){
file << "Objeto_" << aux->getName() << "_id_" << aux->getId() << "->" << "Objeto_" << aux->getDerecha()->getName() << "_id_" << aux->getDerecha()->getId() << "; \n";
crearGraficaRamas(file, aux->getDerecha());
}
}
//Funciones para EliminarNodoDeArbolBinario
void Arbol_Binario::eliminarNodo(Nodo_Binario* raiz, int id){
if(this->getRaiz() == NULL){
return;
}
else if(id < raiz->getId()){
eliminarNodo(raiz->getIzquierda(), id);
}
else if(id > raiz->getId()){
eliminarNodo(raiz->getDerecha(), id);
}
else if (id == raiz->getId()){
eliminarNodoDeArbol(raiz);
}
}
void Arbol_Binario::eliminarNodoDeArbol(Nodo_Binario *raizEliminar){
if(raizEliminar->getIzquierda() && raizEliminar->getDerecha()){ //Si nodo tiene izq & der
Nodo_Binario* menor = minimo(raizEliminar);
raizEliminar->setId(menor->getId());
raizEliminar->setName(menor->getName());
raizEliminar->setColor(menor->getColor());
raizEliminar->setLetra(menor->getLetra());
raizEliminar->setListaPuntos(menor->getListaPuntos());
eliminarNodoDeArbol(menor);
}
else if(raizEliminar->getIzquierda()){
reemplazar(raizEliminar, raizEliminar->getIzquierda());
destruir(raizEliminar);
} else if (raizEliminar->getDerecha()){
reemplazar(raizEliminar, raizEliminar->getDerecha());
destruir(raizEliminar);
} else{
reemplazar(raizEliminar, NULL);
destruir(raizEliminar);
}
}
//Funcion Determina nodo mas izquierdo
Nodo_Binario* Arbol_Binario::minimo(Nodo_Binario* raiz){
if(raiz == NULL){
return NULL;
}
if(raiz->getIzquierda()){
return minimo(raiz->getIzquierda());
}
else {
return raiz;
}
}
void Arbol_Binario::reemplazar(Nodo_Binario* nodoRemplazar, Nodo_Binario* nuevoNodo){
if(nodoRemplazar->getPadre()){
if(nodoRemplazar->getPadre()->getIzquierda() != NULL && nodoRemplazar->getId() == nodoRemplazar->getPadre()->getIzquierda()->getId()){
nodoRemplazar->getPadre()->setIzquierda(nuevoNodo);
}
else if(nodoRemplazar->getId() == nodoRemplazar->getPadre()->getDerecha()->getId()){
nodoRemplazar->getPadre()->setDerecha(nuevoNodo);
}
}
if(nuevoNodo){
//asignar padre
nuevoNodo->setPadre(nodoRemplazar->getPadre());
}
}
void Arbol_Binario::destruir(Nodo_Binario *raizEliminar){
raizEliminar->setIzquierda(NULL);
raizEliminar->setDerecha(NULL);
delete raizEliminar;
}
| true |
aecb25dc9aa3c666dae74d9a9a9e3a765fc315ba | C++ | ColinParrott/raytracer | /shapes/selfbalance.hpp | UTF-8 | 779 | 2.9375 | 3 | [] | no_license | // Self Balancing Binary Search Tree
// Adapted from https://www.tutorialspoint.com/cplusplus-program-to-implement-self-balancing-binary-search-tree
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#define pow2(n) (1 << (n))
using namespace std;
struct avl//node declaration
{
int d;
int index;
struct avl *l;
struct avl *r;
};
class avl_tree
{
public://declare functions
int height(avl *);
int difference(avl *);
avl * rr_rotat(avl *);
avl * ll_rotat(avl *);
avl * lr_rotat(avl*);
avl * rl_rotat(avl *);
avl * balance(avl *);
avl * insert(avl *, int, int);
int search (avl *, int);
void show(avl *, int);
void inorder(avl *);
void preorder(avl *);
void postorder(avl*);
avl_tree()
{
r = NULL;
}
avl *r;
};
| true |
4cf5055c9b7f446af6edba7db95ef0b35f6a9cb1 | C++ | ChangguHan/studyAlgorithm | /Simulation/BJ-15686.cpp | UTF-8 | 1,384 | 3.046875 | 3 | [] | no_license | // 백트래킹 위치 조합 : 2^(M)
// 각 위치에서 최소거리 치킨집 확인 : N^2
// 치킨집마다 확인 N*M
// N=50, M=13 이니까 치킨집마다 확인하는게 빠르겠군
// O(NM2^M) : 650*1e3*8 = 5e6
#include <iostream>
#include <vector>
using namespace std;
int N,M;
int map[60][60];
vector<pair<int, int> > chick;
vector<pair<int, int> > home;
vector<int> v;
int minv = 3600*13;
int cal() {
int rs=0;
// 각 집에서
for (auto eh : home) {
// 각 치킨집까지
int minv = 3600;
for (int i : v) {
auto ec = chick[i];
minv = min(minv, abs(eh.first-ec.first) + abs(eh.second-ec.second));
}
rs += minv;
}
return rs;
}
void dfs(int dep) {
if(dep==M) {
minv = min(minv, cal());
return;
}
int idx=-1;
if(v.size() !=0) idx = v.back();
for (int i=idx+1; i<chick.size(); i++) {
v.push_back(i);
dfs(dep+1);
v.pop_back();
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
for (int j=0; j<N; j++) {
for (int i=0; i<N; i++) {
cin >> map[j][i];
if(map[j][i] == 1) home.push_back(make_pair(j,i));
if(map[j][i] == 2) chick.push_back(make_pair(j,i));
}
}
// 조합
dfs(0);
cout << minv << '\n';
return 0;
}
| true |
a322f9a6e1f31977de008448501469f97f0b65af | C++ | leetrent/BeginnerCPP | /Challenges/Challenge16-Polymorphism/SavingsAccount.h | UTF-8 | 694 | 3.046875 | 3 | [] | no_license | #ifndef _SAVINGSACCOUNT_H_
#define _SAVINGSACCOUNT_H_
#include "Account.h"
class SavingsAccount : public Account
{
private:
static constexpr const char *default_name = "Unamed Savings Account";
static constexpr const double default_balance = 0.0;
static constexpr const double default_interest_rate = 0.0;
protected:
double interestRate;
public:
SavingsAccount(std::string name = default_name, double balance = default_balance, double interestRate = default_interest_rate);
virtual ~SavingsAccount() = default;
virtual bool deposit(double amount) override;
virtual bool withdraw(double amount) override;
virtual void print(std::ostream &os) const override;
};
#endif
| true |
f654330d98e1a456d7c3a69cb973d1a8fb88efda | C++ | franceschi/CECS2223 | /Lab_11/Product.h | WINDOWS-1258 | 786 | 3.375 | 3 | [] | no_license | #pragma once
#ifndef Product_H
#define Product_H
#include <string>
#include <iostream>
using namespace std;
class Product
{
private:
string productName;
string productBarCode;
public:
Product();
Product(string productName, string productBarCode);
Product(const Product & tempProduct);
~Product();
//(get y set)
void setBarCode(string);
void setName(string);
string getBarCode() const;
string getName() const;
//(operator overloading) =, ==
Product & operator= (const Product & tempProduct);
//El operador == solo va a comparar contra el atributo productBarCode.
bool operator== (const Product &);
//Friends
friend ostream &operator << (ostream &, const Product &);
friend istream &operator >> (istream & in, Product &);
};
#endif // !Product_H
| true |
ad0916d26ce3b2b83a27b992b16a3cf56ea1f8be | C++ | yasinxdxd/orbit_simulation | /include/Math/Vectors.h | UTF-8 | 2,557 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#ifndef GO_VECTORS_H
#define GO_VECTORS_H
#include <cmath>
#include "Core/Definitions.h"
#define GO_PI 3.14159265359
#define GO_R2D(radian) radian * 180 / GO_PI
#define GO_D2R(degree) degree * GO_PI / 180
#define GO_DIST(x1,y1,x2,y2) sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)))
namespace go
{
template<class T>
class Vec2
{
public:
T x, y;
Vec2() { this->x = 0; this->y = 0; }
Vec2(T x, T y) { this->x = x; this->y = y; }
Vec2<T> operator+(Vec2<T> v) const
{
Vec2<T> result = go::Vec2<T>(this->x + v.x, this->y + v.y);
return result;
}
Vec2<T> operator-(Vec2<T> v) const
{
Vec2<T> result = go::Vec2<T>(this->x - v.x, this->y - v.y);
return result;
}
template<typename N>
Vec2<T> operator*(N n) const
{
Vec2<T> result = go::Vec2<T>(this->x*n, this->y*n);
return result;
}
Vec2<T> operator+=(Vec2<T> v)
{
*this = *this + v;
return *this;
}
Vec2<T> operator-=(Vec2<T> v)
{
*this = *this - v;
return *this;
}
template<typename N>
Vec2<T> operator*=(N n)
{
*this = *this * n;
return *this;
}
};
template<class T>
class Vec3
{
public:
T x, y, z;
Vec3() { this->x = 0; this->y = 0; this->z = 0; }
Vec3(T x, T y, T z) { this->x = x; this->y = y; this->z = z; }
Vec3<T> operator+(Vec3<T> v) const
{
Vec3<T> result = go::Vec3<T>(this->x + v.x, this->y + v.y, this->z + v.z);
return result;
}
Vec3<T> operator-(Vec2<T> v) const
{
Vec3<T> result = go::Vec3<T>(this->x - v.x, this->y - v.y, this->z - v.z);
return result;
}
template<typename N>
Vec3<T> operator*(N n) const
{
Vec3<T> result = go::Vec3<T>(this->x * n, this->y * n, this->z * n);
return result;
}
Vec3<T> operator+=(Vec3<T> v)
{
*this = *this + v;
return *this;
}
Vec3<T> operator-=(Vec3<T> v)
{
*this = *this - v;
return *this;
}
template<typename N>
Vec3<T> operator*=(N n)
{
*this = *this * n;
return *this;
}
};
template<class T>
class Vec4
{
public:
T x, y, z, w;
Vec4() { this->x = 0; this->y = 0; this->z = 0; this->w = 0; }
Vec4(T x, T y, T z, T w) { this->x = x; this->y = y; this->z = z; this->w = w; }
};
typedef Vec2<GOuint> Vec2ui;
typedef Vec2<GOfloat> Vec2f;
typedef Vec2<GOint> Vec2i;
typedef Vec2<GOdouble> Vec2d;
typedef Vec3<GOuint> Vec3ui;
typedef Vec3<GOfloat> Vec3f;
typedef Vec3<GOint> Vec3i;
typedef Vec3<GOsint> Vec3si;
typedef Vec4<GOuint> Vec4ui;
typedef Vec4<GOfloat> Vec4f;
typedef Vec4<GOint> Vec4i;
}
#endif //GO_VECTORS_H
| true |
3326534ad4e43b55a2a37c24f713630100ac10c0 | C++ | suhyun1/problem-solving | /suhyun/SWEA1234_비밀번호.cpp | UTF-8 | 687 | 2.890625 | 3 | [] | no_license | #include<iostream>
#include<stack>
using namespace std;
int main(int argc, char** argv)
{
int test_case;
int T=10;
for(test_case = 1; test_case <= T; ++test_case)
{
int len;
string secret;
cin >> len >> secret;
stack<char> s;
for(int i=0;i<len;i++){
if(!s.empty() && s.top()==secret[i])
s.pop();
else
s.push(secret[i]);
}
string tmp="";
while(!s.empty()){
tmp += s.top() ;
s.pop();
}
cout << "#" <<test_case << " ";
for(int i=tmp.length()-1; i>=0; i--)
cout << tmp[i];
cout << endl;
}
return 0;
} | true |
6cd29b7c099b59cef4215075b3145f2361b3ac1c | C++ | makreft/openPubSub | /openPubSub/VariableNode.h | UTF-8 | 2,195 | 2.671875 | 3 | [] | no_license | //
// Created by sba on 28.02.20.
//
#ifndef SMARTFACTORYLIB_VARIABLENODE_H
#define SMARTFACTORYLIB_VARIABLENODE_H
#include <vector>
#include <open62541/server.h>
#include "UATypes.h"
#include "Errors.h"
class NodeDataBase{
public:
bool isInit(){
return _init;
}
virtual void init(UA_Server *server, UA_NodeId id) = 0;
protected:
bool _init = false;
UA_NodeId _id;
UA_Server * _server;
const UA_DataType * _type;
};
template<typename T>
class NodeData : public NodeDataBase{
public:
NodeData() = default;
void init(UA_Server *server, UA_NodeId id) override {
this->_id = id;
this->_server = server;
// TODO Typecheck
this->_type = get_UA_Type<T>();
this->_init = true;
}
NodeData<T> & operator=(T rhs) {
if (!_init) {
throw not_initialized();
}
UA_Variant val;
UA_Variant_setScalar(&val, &rhs, this->_type);
UA_Server_writeValue(this->_server, this->_id, val);
return *this;
}
operator T() const { // NOLINT
UA_Variant val;
UA_Server_readValue(this->_server, this->_id, &val);
T data = *(T *) val.data;
UA_Variant_clear(&val);
return data;
}
};
template<typename T>
class NodeData<std::vector<T>> : public NodeDataBase{
public:
NodeData() = default;
void init(UA_Server *server, UA_NodeId id) override {
this->_id = id;
this->_server = server;
// TODO Typecheck
this->_type = get_UA_Type<T>();
this->_init = true;
}
NodeData<std::vector<T>> & operator=(std::vector<T> rhs) {
if (!_init) {
throw not_initialized();
}
UA_Variant val;
UA_Variant_setArray(&val, rhs.data(), rhs.size(), this->_type);
UA_Server_writeValue(this->_server, this->_id, val);
return *this;
}
operator std::vector<T>() const { // NOLINT
UA_Variant val;
UA_Server_readValue(this->_server, this->_id, &val);
std::vector<T> ret((T *) val.data, ((T *)val.data) + val.arrayLength);
return ret;
}
};
#endif //SMARTFACTORYLIB_VARIABLENODE_H
| true |
75009616925358a9b433622cebea5ab90e02b202 | C++ | SakiiR/Arcade | /Loader.cpp | UTF-8 | 5,072 | 2.75 | 3 | [] | no_license | //
// Loader.cpp for Arcade in /home/dupard_e/rendus/cpp_arcade
//
// Made by Erwan Dupard
// Login <dupard_e@epitech.net>
//
// Started on Wed Mar 9 15:53:55 2016 Erwan Dupard
// Last update Sun Apr 3 23:17:38 2016 Barthelemy Gouby
//
#include "Loader.hh"
Loader::Loader() : _game(0), _display(0), _graphicHandle(0), _gameHandle(0)
{}
Loader::~Loader()
{}
bool Loader::loadGraphicLibrary(const std::string &filePath)
{
display_create_t *create_display;
void *oldGraphicHandle = NULL;
void *newGraphicHandle = NULL;
IDisplay *oldDisplay = NULL;
if (this->_graphicHandle)
{
oldGraphicHandle = this->_graphicHandle;
oldDisplay = this->_display;
}
if ((newGraphicHandle = dlopen(filePath.c_str(), RTLD_LAZY | RTLD_GLOBAL)) == NULL)
{
std::cerr << "[-] Failed To Open Library : " << dlerror() << std::endl;
return (false);
}
if ((create_display = (display_create_t *)dlsym(newGraphicHandle, "create")) == NULL)
{
dlclose(newGraphicHandle);
std::cerr << "[-] Failed To Load Symbol : " << dlerror() << std::endl;
return (false);
}
this->_graphicHandle = newGraphicHandle;
if (oldGraphicHandle)
{
oldDisplay->closeDisplay();
delete oldDisplay;
dlclose(oldGraphicHandle);
}
this->_display = create_display();
return (true);
}
bool Loader::loadGameLibrary(const std::string &filePath)
{
game_create_t *create_game;
if (this->_gameHandle)
{
this->_display->cleanScreen();
dlclose(this->_gameHandle);
}
if ((this->_gameHandle = dlopen(filePath.c_str(), RTLD_LAZY | RTLD_GLOBAL)) == NULL)
{
std::cerr << "[-] Failed To Open Library : " << dlerror() << std::endl;
return (false);
}
if ((create_game = (game_create_t *)dlsym(this->_gameHandle, "create")) == NULL)
{
std::cerr << "[-] Failed To Load Symbol : " << dlerror() << std::endl;
return (false);
}
this->_game = create_game();
return (true);
}
bool Loader::loadInitialGraphicLibrary(const std::string &filePath)
{
std::vector<std::string>::iterator it = this->_displaysPaths.begin();
while (it != this->_displaysPaths.end())
{
if (*it == filePath)
{
if (!this->loadGraphicLibrary(filePath))
return (false);
this->_selectedDisplay = it;
break;
}
it++;
}
if (it == this->_displaysPaths.end())
throw std::runtime_error("Library not found");
return (true);
}
void Loader::loadInitialGameLibrary(const std::string &filePath)
{
std::vector<std::string>::iterator it = this->_gamesPaths.begin();
while (it != this->_gamesPaths.end())
{
if (*it == filePath)
{
this->loadGameLibrary(filePath);
this->_selectedGame = it;
break;
}
it++;
}
if (it == this->_gamesPaths.end())
throw std::runtime_error("Library not found");
}
void Loader::loadNextGraphicLibrary()
{
if (std::next(this->_selectedDisplay) == this->_displaysPaths.end())
this->_selectedDisplay = this->_displaysPaths.begin();
else
this->_selectedDisplay++;
if (loadGraphicLibrary(*(this->_selectedDisplay)))
this->_display->initDisplay();
}
void Loader::loadNextGameLibrary()
{
if (std::next(this->_selectedGame) == this->_gamesPaths.end())
this->_selectedGame = this->_gamesPaths.begin();
else
this->_selectedGame++;
if (loadGameLibrary(*(this->_selectedGame)))
{
this->_game->startGame();
}
}
void Loader::loadPreviousGraphicLibrary()
{
if (this->_selectedDisplay == this->_displaysPaths.begin())
this->_selectedDisplay = std::prev(this->_displaysPaths.end());
else
this->_selectedDisplay--;
if (loadGraphicLibrary(*(this->_selectedDisplay)))
this->_display->initDisplay();
}
void Loader::loadPreviousGameLibrary()
{
if (this->_selectedGame == this->_gamesPaths.begin())
this->_selectedGame = std::prev(this->_gamesPaths.end());
else
this->_selectedGame--;
if (loadGameLibrary(*this->_selectedGame))
this->_game->startGame();
}
IGame *Loader::getGame() const
{
return (this->_game);
}
IDisplay *Loader::getDisplay() const
{
return (this->_display);
}
void Loader::retrieveFilesNames(std::string directoryPath,
std::vector<std::string> &pathsTab)
{
DIR *dir;
dirent *entry;
std::regex isLibrary(".*\\.so");
if ((dir = opendir(directoryPath.c_str())) == NULL)
throw std::runtime_error("Failed to open directory");
while ((entry = readdir(dir)) != NULL)
{
if (std::regex_match(entry->d_name, isLibrary))
pathsTab.push_back(directoryPath + std::string(entry->d_name));
}
closedir(dir);
}
void Loader::loadFilesNames()
{
retrieveFilesNames("lib/", this->_displaysPaths);
retrieveFilesNames("games/", this->_gamesPaths);
this->_selectedGame = this->_gamesPaths.begin();
this->_selectedDisplay = this->_displaysPaths.begin();
}
const std::vector<std::string> &Loader::getGamesPaths() const
{
return (this->_gamesPaths);
}
const std::vector<std::string> &Loader::getDisplaysPaths() const
{
return (this->_displaysPaths);
}
| true |
9f570327842d217eca2fb05010981d0f614957bd | C++ | nagyrobert1996/bevprog | /szohossz_shiftelessel.cpp | UTF-8 | 147 | 2.71875 | 3 | [] | no_license | #include "iostream"
int main()
{
int a = 1;
int db = 0;
while(a != 0)
{
++db;
a = a << 1;
}
std::cout << "Eredmeny: " << db << "\n";
}
| true |
37e6ea4edd220c03f275a3229356af73fb983eca | C++ | Badabum/Prata_task | /chapter_8/chapter8_1/chapter8(ex2).cpp | UTF-8 | 953 | 3.5 | 4 | [] | no_license | #include "stdafx.h"
#include <iostream>
#include <string>
struct CandyBar
{
std::string name;
double mass;
int calories;
};
void show(const CandyBar& bar);
void setstr(char*str);
void set(CandyBar&bar,char*name="Millennium Munch",double mass=2.85,int calories=350);
void main()
{
using std::cout;
using std::cin;
char name[80];
double mass(0);
int calor(0);
CandyBar mybar;
cout<<"Enter name of candy bar: ";
cin.getline(name,80);
cout<<"Enter mass value: ";
(cin>>mass).get();
cout<<"Enter calories: ";
(cin>>calor).get();
set(mybar,name,mass,calor);
show(mybar);
cin.get();
}
void show(const CandyBar& bar)
{
std::cout<<"Name:"<<bar.name<<std::endl;
std::cout<<"Mass: "<<bar.mass<<std::endl;
std::cout<<"Calories: "<<bar.calories<<std::endl;
}
void set(CandyBar &bar,char*name,double mass,int calories)
{
bar.name=name;
bar.mass=mass;
bar.calories=calories;
}
void setstr(char*str)
{
std::cout<<"String: "<<str<<std::endl;
} | true |
d29a2d919239b6ea3413bcb5f8b4ed772795d5c0 | C++ | naeimsalib/High_Adventure_Travel_Agency | /Lab2.cpp | UTF-8 | 7,214 | 3.59375 | 4 | [] | no_license | //CSC 211 Lab 2
// Naeim Salib
#include <iostream>
using namespace std;
//Function Declration
void climbing();
void scuba();
void skyDive();
void spelunk();
int menu();
//Assigned variavles
const double climbRate = 300; // to Hold base rate of Devil's Courthouse adventure
const double scubaRate = 1000; // to hold base rate of Scuba Bahamas package
const double skyDiveRate = 400; // to hold base rate of Sky Dive Colorado Package
const double caveRate = 700; // to hold base rate of Barron Cliff Spelunk Package
const double climbInstruct = 100; // to holds charge for rock Climbing instruction.
const double scubaInstruct = 100; // to holds charge for scuba instruction.
const double dailyCampRental = 40; //to hold daily charge, per person for equipment rental.
const double dayLodge1 = 65; // holds daily cost of lodging option 1 of sky dive Colorado package.(Wilderness Lodge)
const double dayLodge2 = 120; // Holds daily cost of lodging option 2 of sky dive Colorado package.(Luxury Inn.)
//Main Function that calls Menu Function and Displays program Control to the appropriate module,
//Based on the User's Choice of package.
int main(){
int choice; // Holds User Input Choice for package.
do {
choice = menu();
//Switch Case to call the function according to user's choice
switch (choice){
case 1:
climbing ();
break;
case 2:
scuba ();
break;
case 3:
skyDive ();
break;
case 4:
spelunk ();
break;
default:
cout << "Wrong input" << endl;
}
} while (choice != 5);
cout << "Exiting Program" << endl;
return 0;
}
//Function To Display a menu listing the vacation packages.
//Allows the user to enter a selection, which is returned to the main Function
int menu(){
cout << "High Adventure tavel Agency" << endl;
cout << "----------------------------" << endl;
cout << "1. Camping\n"; //Choice index for users
cout << "2. Scuba Diving\n";
cout << "3. Sky Dive\n";
cout << "4. Spelunk\n";
cout << "Please 1, 2, 3, 4, or 5: ";
int choice;
cin >> choice;
return choice;
}
// Function to Ask the user for data necessary to calculate charges for the Devil's Courthouse Adventure Weekend Package
void climbing() {
double beginner, advanced, renting, baseCharge, instruction, totalCharge,discount = 0;
cout << endl;
cout << "Devil's Courthouse Adventure Weekend" << endl;
cout << "--------------------------------------"<< endl;
cout << "How many will be going who need an instructor? ";
cin >> beginner;
cout << "How many Advanced Climbers will be going? ";
cin >> advanced;
cout << "How many will rent camping eqipment? ";
cin >> renting;
baseCharge = climbRate * (beginner + advanced);
instruction = climbInstruct * beginner;
//calculates The Customer's Discounts
if (beginner + advanced >= 5){
discount = baseCharge * 0.1;
}
totalCharge = baseCharge + instruction - discount +
40 * 3 * renting;
cout << "Number in party: " << beginner + advanced << endl;
cout << "Base Charge: $ " << baseCharge << endl;
cout << "Instruction Cost: $" << instruction << endl;
cout << "Equipment Rental: $" << 40 * 3 * renting << endl;
cout << "Discount $" << discount << endl;
cout << "Total charge: $"<< totalCharge << endl;
cout << "Required Deposit: $" << totalCharge * 0.5 << endl;
cout << endl;
cout << endl;
}
// Function to Ask the user for data necessary to calculate charges for the Scuba bahamas Package
void scuba(){
double beginner, advanced, baseCharge, instruction, totalCharge,discount = 0;
cout << endl;
cout << "Scuba Bahama" << endl;
cout << "-------------------------------------" << endl;
cout << "How many will be going who need an instructor? ";
cin >> beginner;
cout << "How many advanced scuba divers be going? ";
cin >> advanced;
baseCharge = scubaRate * (beginner + advanced);
//calculates The Customer's Discounts
if (beginner + advanced >= 5){
discount = baseCharge * 0.1;
}
instruction = scubaInstruct * beginner;
totalCharge = baseCharge + instruction - discount;
cout << "Number in Party: " << beginner + advanced << endl;
cout <<" Base charge: $ " << scubaRate << endl;
cout << "Instruction Cost: $" << instruction << endl ;
cout << "Discount: $" << discount << endl;
cout << "Total charge: $" << totalCharge << endl;
cout << "Required Deposit: $ " << totalCharge * 0.5 << endl;
cout << endl;
cout << endl;
}
// Function to Ask the user for data necessary to calculate charges for the Sky Dive Colorado package
void skyDive(){
double number, baserate, wildernessLodge, luxuryInn, lodge, totalCharge,discount = 0;
cout << "Sky Dive Colorado" << endl;
cout << "-----------------------------------" << endl;
cout << "How many will be going? ";
cin >> number;
cout << "How many Will stay at wilderness Lodge? ";
cin >> wildernessLodge;
cout << "How many will stay at Luxury Inn? ";
cin >> luxuryInn;
baserate = skyDiveRate * number;
//calculates The Customer's Discounts
if (number >= 5){
discount = baserate * 0.1;
cout << "\nYour discount amount is $" << discount;
}
lodge = luxuryInn * dayLodge2 + wildernessLodge * dayLodge1;
totalCharge = baserate + lodge - discount;
cout << "Number in party: " << number <<endl;
cout << "Base Charge: " << baserate << endl;
cout << "Lodging: $" << lodge << endl;
cout << "Discount: $" << discount << endl;
cout << "Total charge: $" << totalCharge << endl;
cout << "Required Deposit: $ " << totalCharge * 0.5 << endl;
cout << endl;
cout << endl;
}
// Function to Asks the user for data necessary to calculate charges for Barron Cliff Spelunk package
void spelunk(){
double number, baseRate, totalCharge,renting, rentalCost, discount = 0;
cout << "Barron Cliff Spelunk weekend" << endl;
cout << "-----------------------------------" << endl;
cout << "Please enter the number of people in party? ";
cin >> number;
cout << "Please enter the number of party renting equipment? ";
cin >> renting;
rentalCost = dailyCampRental * 8 * number;
baseRate = caveRate * number;
//calculates The Customer's Discounts
if (number >= 5){
discount = baseRate * 0.1;
}
cout << "Number in Party: " << number << endl;
cout << "Base charge: $ " << baseRate << endl;
cout << "Equipment rental $" << rentalCost << endl;
cout << "Discount: $ " << discount << endl;
cout << "Total charge: $" << baseRate + rentalCost - discount << endl;
cout << "Required Deposit: $ " << totalCharge * 0.5 << endl;
cout << endl;
cout << endl;
}
| true |
54e217770589aae09eb46ef3eef55ef88985a4d9 | C++ | DR9885/Pong | /Development/Pong.Box2D/Pong.Box2D/CapsuleCollider.h | UTF-8 | 898 | 3.578125 | 4 | [] | no_license | /* This is a combination of 2 circles and a rectangle bound. The sizes adjust with the height and width of the capsule object. */
#pragma once
#ifndef CAPSULE_H
#define CAPSULE_H
class capsule {
public:
real height, width;
vector2* position;
rect* middle;
circle* circle1;
circle* circle2;
capsule(){
position= vector2::ONE();
height = 1;
width = 1;
middle = new rect(height*2/3, width, 1, 1);
circle1 = new circle(width*1/2, 1, 1+1/2*height);
circle2 = new circle(width*1/2, 1, 1-1/2*height);
}
capsule(real h, real w, real x, real y)
{
position= new vector2(x,y);
height = h;
width = w;
middle = new rect(height*2/3, width, x, y);
circle1 = new circle(width*1/2, x, y+1/2*height);
circle2 = new circle(width*1/2, x, y-1/2*height);
}
~capsule(){
delete position;
delete middle;
delete circle1;
delete circle2;
}
private:
};
#endif | true |
564779fad545e99cfc6909b482d0c6383205cd22 | C++ | Lujie1996/Leetcode | /373. Find K Pairs with Smallest Sums/373. Find K Pairs with Smallest Sums/main.cpp | UTF-8 | 1,758 | 3.328125 | 3 | [] | no_license | //
// main.cpp
// 373. Find K Pairs with Smallest Sums
//
// Created by Jie Lu on 2019/2/10.
// Copyright © 2019 Jie Lu. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
int i = 0, j = 0;
vector<pair<int,int>> res;
if (nums1.size() == 0 || nums2.size() == 0) {
return res;
}
int maxCount = min(k, (int)(nums1.size() * nums2.size()));
while (res.size() < maxCount) {
res.push_back({nums1[i], nums2[j]});
if (i + 1 < nums1.size() && j + 1 < nums2.size()) {
if (nums1[i+1] + nums2[j] <= nums1[i] + nums2[j+1]) {
i++;
}
else {
j++;
}
}
else {
if (i == nums1.size() && j == nums2.size()) {
break;
}
if (i == nums1.size() - 1) {
if (nums1[i] + nums1[j] <= nums1[0] + nums2[j+1]) {
i = 0;
j++;
}
else {
j++;
}
}
else {
if (nums1[i] + nums1[j] <= nums1[i+1] + nums2[0]) {
j = 0;
i++;
}
else {
i++;
}
}
}
}
return res;
}
int main(int argc, const char * argv[]) {
vector<int> nums1{1,1,2}, nums2{1,2,3};
vector<pair<int, int>> res = kSmallestPairs(nums1, nums2, 10);
for (auto a : res) {
cout<<a.first<<" "<<a.second<<endl;
}
// [[1,1],[1,1],[2,1],[1,2],[1,2],[2,2],[1,3],[1,3],[2,3]]
return 0;
}
| true |
53cc17596ab530105d4610ca336592e19d32d5fc | C++ | ywnwa/compiler-pl0-cpp | /identifiermanager.h | UTF-8 | 1,737 | 2.75 | 3 | [] | no_license |
#ifndef IDENTIFIERMANAGER_H
#define IDENTIFIERMANAGER_H
#include <QtCore/QList>
#include <QtCore/QString>
class IdentifierManager
{
public:
IdentifierManager();
~IdentifierManager();
void setName( const QString &name );
void setValue( int value );
bool pushConstIdentifier();
bool pushVariableIdentifier();
bool pushProcedure();
bool endProcedure();
bool hasVariableIdentifier( const QString &name ) const;
bool hasConstIdentifier( const QString &name ) const;
bool hasProcedureIdentifier( const QString &name ) const;
bool hasLocalVariableIdentifier( const QString &name ) const;
bool hasLocalConstIdentifier( const QString &name ) const;
bool hasLocalProcedureIdentifier( const QString &name ) const;
int procedureIndex( const QString &name ) const;
int constIndex( const QString &name ) const;
int constIndex( int value ) const;
int currentProcedureIndex() const;
int currentProcedureVariableSize() const;
int procedureCount() const;
QList<int> constIdentifierValues() const;
enum VariableType
{
Local,
Main,
Global
};
void getVariableAddress( const QString &name, VariableType &type, int &address, int &procedureIndex ) const;
private:
class IdentifierBase;
class ConstIdentifier;
class VariableIdentifier;
class ProcedureIdentifier;
IdentifierBase* find( int type, const QString &name ) const;
IdentifierBase* findLocal( int type, const QString &name ) const;
ProcedureIdentifier *mMainProcedure;
ProcedureIdentifier *mCurrentProcedure;
int mProcedureCounter;
QList<int> mConstIdentifierValues;
QString mCurrentName;
int mCurrentValue;
};
#endif
| true |
e2a7e10c98c97604fa56c6cd6179d2ae61add261 | C++ | rishabh-11/C-- | /placement prep/linkedlist/rotate_list.cpp | UTF-8 | 668 | 3.21875 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::rotateRight(ListNode* A, int B) {
if(A==NULL)return A;
int len=0;
ListNode* head=A;
ListNode* tail=A;
ListNode* ans=A;
while(A)
{
len++;
if(A->next)
{
tail=A->next;
}
A=A->next;
}
B=B%len;
if(B==0)return ans;
len=len-B-1;
ListNode* temp=head;
while(len)
{
len--;
temp=temp->next;
}
tail->next=head;
ans=temp->next;
temp->next=NULL;
return ans;
} | true |
847fba1fa7ce31f2be3e4ef1b4d5721e2a556486 | C++ | mosqlwj/leetcode | /344_反转字符串.cpp | UTF-8 | 609 | 3.296875 | 3 | [] | no_license | //
// Created by lwj on 2020/5/12.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// 递归
void reverseString(vector<char>& s) {
helper(s, 0, s.size()-1);
}
void helper(vector<char>& s, int l, int r) {
if (l >= r)
return;
int tmp = s[l];
s[l] = s[r];
s[r] = tmp;
helper(s, ++l, --r);
}
};
int main() {
vector<char> s = {'h', 'e', 'l', 'l', 'o'};
Solution().reverseString(s);
for(auto c : s) {
cout << c << " ";
}
return 0;
} | true |
5583537672afc4e45290ad01f58097cb27e6a7b2 | C++ | blockspacer/vrm_core | /test/core/static_if/static_if_return.cpp | UTF-8 | 1,164 | 3.125 | 3 | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "../../utils/test_utils.hpp"
#include <cstddef>
#include <vrm/core/config.hpp>
#include <vrm/core/static_if.hpp>
struct banana
{
};
struct apple
{
};
struct chestnut
{
};
template <typename T>
using is_banana = std::integral_constant<bool, std::is_same<banana, T>{}>;
template <typename T>
using is_apple = std::integral_constant<bool, std::is_same<apple, T>{}>;
template <typename T>
auto eat_fruit(T fruit)
{
return vrm::core::static_if(is_banana<T>{})
.then([](auto&)
{
return 0;
})
.else_if(is_apple<T>{})
.then([](auto&)
{
return 10.f;
})
.else_([](auto&)
{
return 'x';
})(fruit);
}
TEST_MAIN()
{
auto b = eat_fruit(banana{});
auto a = eat_fruit(apple{});
auto c = eat_fruit(chestnut{});
static_assert(std::is_same<decltype(b), int>{}, "");
static_assert(std::is_same<decltype(a), float>{}, "");
static_assert(std::is_same<decltype(c), char>{}, "");
TEST_ASSERT_OP(b, ==, 0);
TEST_ASSERT_OP(a, ==, 10.f);
TEST_ASSERT_OP(c, ==, 'x');
return 0;
}
| true |
a9e9099ab6e88befdf27d2e1ee759fae617af179 | C++ | jack06215/C-programming-quiz | /diet.cpp | UTF-8 | 1,723 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
int main()
{
int arr1[] = {1,3,5,7,10};
int arr2[] = {2,3,7,8,9};
int target = 12;
int high = target + 1;
int low = target - 1;
int width = sizeof(arr1)/sizeof(arr1[0]);
int height = sizeof(arr2)/sizeof(arr2[0]);
std::vector<int> sum;
std::unordered_set<int> result;
for (const int& i : arr1)
for (const int& j : arr2)
sum.push_back(i + j);
int stride = sizeof(arr1)/sizeof(arr1[0]);
int idx_h = 0;
int buttom = sizeof(arr2)/sizeof(arr2[0]);
int step = buttom;
while (idx_h < buttom || step < 0)
{
int col = step - 1;
int row = stride * idx_h;
if (sum[col + row] < target)
{
for (int i = 0; i < step; i++)
{
int tmp = sum[row + i];
if (std::abs(tmp-low) < (high-low))
{
std::cout << "arr1[" << i << "] + arr2[" << row << "] = " << tmp << std::endl;
result.insert(tmp);
}
}
}
else if (sum[col + row] >= target)
{
for (int i = col + row; i < buttom * stride; i+=stride)
{
int tmp = sum[i];
if (std::abs(tmp-low) < (high-low))
{
std::cout << "arr1[" << i-stride << "] + arr2[" << row << "] = " << tmp << std::endl;
result.insert(tmp);
}
}
}
idx_h++;
step--;
}
for (const int& num: result)
std::cout << num << " ";
std::cout << '\n';
return 0;
}
| true |
ada0b28970c66ebbd7cbb60d178e1c6f57146b67 | C++ | Vashishtha/CAlgoPractice | /staircase.cpp | UTF-8 | 3,137 | 3.46875 | 3 | [] | no_license | //There exists a staircase with N steps,
//and you can climb up either 1 or 2 steps at a time.
//Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
//For example, if N is 4, then there are 5 unique ways:
//1, 1, 1, 1
//2, 1, 1
//1, 2, 1
//1, 1, 2
//2, 2
//What if, instead of being able to climb 1 or 2 steps at a time,
//you could climb any number from a set of positive integers X?
//For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
#include<vector>
#include<iostream>
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
unordered_map<int,long long> memo;
long long getWays(const std::vector<int> stepSizes, int N)
{
cout << "stairs remaing: " << N << endl;
if (N == 0)
{
cout << "stairs finished." << endl;
return 1;
}
long long total = 0;
if(memo.find(N) != memo.end())
{
total = memo[N];
cout << "result found in map." << endl;
}
else
{
cout << "calculate ways" << endl;
for(int i : stepSizes)
{
if (N-i >= 0)
{
total += getWays(stepSizes,N-i);
}
}
memo[N] = total;
}
return total;
}
void waysTOClimb(const std::vector<int>&& _steps, int N)
{
std::cout << "TotalNumber of ways to climb staircase is: " << getWays(_steps,N) << std::endl;
return;
}
std::vector<std::string> split_string(std::string input_string) {
//This will remove duplicate ' ' delimeter(actually moves them to the end of string)
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
//erase duplicate delimeters
input_string.erase(new_end, input_string.end());
//not sure why we need it after erase need to check looks like redundant code for erase
//while (input_string[input_string.length() - 1] == ' ') {
// input_string.pop_back();
//}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
int main()
{
int stairSize;
std::cout << "Get size of staircase: " << std::endl;
std::cin >> stairSize;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Get step sizes: " << std::endl;
std::string ar_stepSizes;
std::getline(std::cin, ar_stepSizes);
std::vector<std::string> ar_steps = split_string(ar_stepSizes);
std::vector<int> stepSizes;
for (int ar_itr = 0; ar_itr < ar_steps.size(); ar_itr++) {
int ar_item = stoi(ar_steps[ar_itr]);
stepSizes.push_back(ar_item);
std::cout << stepSizes[stepSizes.size()-1] << std::endl;
}
waysTOClimb(std::move(stepSizes),stairSize);
return 0;
}
| true |
357d78b1cabab01b9acf30c1785fec446f397230 | C++ | AmazingCaddy/leetcode | /Remove_Duplicates_from_Sorted_Array.cpp | UTF-8 | 503 | 2.90625 | 3 | [] | no_license | class Solution {
public:
void test () {
int a[] = {1, 2, 3, 4, 5, 10, 2, 3, 1, 20, 1};
int n = 11;
int ans[] = {1, 2, 3, 4, 5, 10, 20};
int ans_n = 7;
sort (a, a + n);
int len = this -> removeDuplicates(a, n);
for (int i = 0; i < len; i ++) {
cout << a[i] << " ";
}
cout << "\n";
}
int removeDuplicates(int A[], int n) {
if (n <= 1) {
return n;
}
int len = 1;
for (int i = 1; i < n; i ++) {
if (A[i] != A[i - 1]) {
A[len ++] = A[i];
}
}
return len;
}
}; | true |
df5a440fffef4b5f0004a32b11b3f48d0356b8d2 | C++ | dpatino07/Student-Roster-Program | /student.cpp | UTF-8 | 2,672 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
#include <iostream>
#include "student.h"
#include "degree.h"
using namespace std;
Student::Student() {
}
Student::Student(string newStudentID, string newFirstName, string newLastName, string newEmailAddress, int newAge, int newNumDaysInCourse[3], Degree newDegree) {
setStudentID(newStudentID);
setFirstName(newFirstName);
setLastName(newLastName);
setEmailAddress(newEmailAddress);
setAge(newAge);
setNumDaysInCourse(newNumDaysInCourse);
setDegreeProgram(newDegree);
}
// Accessor for each instance
string Student::getStudentID() {
return studentID;
}
string Student::getFirstName() {
return firstName;
}
string Student::getLastName() {
return lastName;
}
string Student::getEmailAddress() {
return emailAddress;
}
int Student::getAge() {
return age;
}
int* Student::getNumDaysInCourse() {
return numDaysInCourse;
}
Degree Student::getDegreeProgram() {
return degree;
}
// Mutators for each instance
void Student::setStudentID(string newStudentID) {
studentID = newStudentID;
}
void Student::setFirstName(string newFirstName) {
firstName = newFirstName;
}
void Student::setLastName(string newLastName) {
lastName = newLastName;
}
void Student::setEmailAddress(string newEmailAddress) {
emailAddress = newEmailAddress;
}
void Student::setAge(int newAge) {
age = newAge;
}
void Student::setNumDaysInCourse(int days[]) {
for (int i = 0; i < 3; i++) {
numDaysInCourse[i] = days[i];
}
}
void Student::setDegreeProgram(Degree newDegree) {
degree = newDegree;
}
void Student::print() {
int* numDaysInCourse = getNumDaysInCourse();
string degree;
cout << getStudentID() << "\t";
cout << "First Name: " << getFirstName() << "\t";
cout << "Last Name: " << getLastName() << "\t";
cout << "Email Address: " << getEmailAddress() << "\t";
cout << "Age: " << getAge() << "\t";
cout << "Number of Days In Course: " << numDaysInCourse[0] << ", " << numDaysInCourse[1] << ", " << numDaysInCourse[2] << "\t";
cout << "Degree Program: " << degree << "\n";
switch (getDegreeProgram()) {
case 0: cout << "Security";
break;
case 1: cout << "Networking";
break;
case 2: cout << "Software";
break;
}
return;
}
Student::~Student() {
};
| true |
36cc093f92a43552c1986ec022953161298de492 | C++ | ToruNiina/Jarngreipr | /jarngreipr/util/parse_range.hpp | UTF-8 | 2,427 | 3.125 | 3 | [
"MIT"
] | permissive | #ifndef JARNGREIPR_PARSE_RANGE_HPP
#define JARNGREIPR_PARSE_RANGE_HPP
#include <jarngreipr/util/log.hpp>
#include <string>
#include <vector>
#include <cstdint>
#include <regex>
#include <numeric>
#include <cassert>
namespace jarngreipr
{
//
// [1,5] -> {1,2,3,4,5}
// [1,5) -> {1,2,3,4}
// (1,5) -> {2,3,4}
// (1,5] -> {2,3,4,5}
//
template<typename integerT = std::int64_t>
typename std::enable_if<std::is_integral<integerT>::value, std::vector<integerT>
>::type parse_range(std::string str)
{
while(str.front() == ' ') {str.erase(str.begin());}
while(str.back() == ' ') {str.pop_back();}
std::regex syntax(R"((\(|\[)\s*((\+|-)?\d+),\s*((\+|-)?\d+)\s*(\)|\]))");
std::smatch sm;
if(!std::regex_match(str, sm, syntax))
{
log::error("syntax error in range \"", str, "\"\n");
log::error("expected like: \"[1,10]\", \"[10, 20)\"\n");
return {};
}
const auto front = static_cast<integerT>(std::stoll(sm.str(2)));
const auto back = static_cast<integerT>(std::stoll(sm.str(4)));
assert(front <= back);
const bool contains_front = (str.front() == '[');
const bool contains_back = (str.back() == ']');
std::vector<integerT> ints(back - front + 1);
std::iota(ints.begin(), ints.end(), front);
if(!contains_front) {ints.erase(ints.begin());}
if(!contains_back) {ints.pop_back();}
return ints;
}
//
// "A:D" -> ["A", "B", "C", "D"]
//
inline std::vector<std::string> parse_chain_range(std::string str)
{
while(str.front() == ' ') {str.erase(str.begin());}
while(str.back() == ' ') {str.pop_back();}
std::regex syntax(R"((\s*)([A-Z])(\s*:\s*)([A-Z])(\s*))");
std::smatch sm;
if(!std::regex_match(str, sm, syntax))
{
if(str.size() == 1u && std::isupper(str.at(0)) != 0)
{
return std::vector<std::string>{str};
}
log::error("syntax error in range \"", str, "\"\n");
log::error("expected like: \"A:D\", \"C:F\"\n");
return {};
}
const auto front = sm.str(2);
const auto back = sm.str(4);
assert(front.size() == 1u);
assert(back .size() == 1u);
std::vector<std::string> chains;
//XXX here it assumes that the character encoding is ASCII or UTF-8
for(char c = front.at(0); c <= back.at(0); ++c)
{
chains.emplace_back(1, c);
}
return chains;
}
} // jarngriepr
#endif// JARNGREIPR_PARSE_RANGE_HPP
| true |
9d8683d50a5b598ca00d9ae4e20d0ea438160ecb | C++ | thedewangan/spoj | /aggrcow.cpp | UTF-8 | 1,017 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;
// predicate - with x as minimum diff, C cows are NOT able to fit
bool p(int x, vector<unsigned int> s, int C) {
int cowsAccomodated = 1;
int latestStall = 0;
for(int i = 1; i < s.size(); i++) {
if(s[i] - s[latestStall] >= x) {
cowsAccomodated++;
latestStall = i;
if(cowsAccomodated == C) return false;
}
}
return true;
}
int main()
{
int T;
cin>>T;
while(T--) {
int N, C;
cin>>N>>C;
vector<unsigned int> s;
s.resize(N);
for(int i = 0; i < N; i++) cin>>s[i];
sort(s.begin(), s.end());
//cout<<p(4, s, 3);
int lo, hi;
lo = 0;
hi = *max_element(s.begin(), s.end()) - *min_element(s.begin(), s.end());
// cout<<lo<<" "<<hi;
while(lo < hi) {
int x = lo + (hi - lo + 1)/2;
if(p(x, s, C) == true) hi = x - 1;
else lo = x;
}
// if (p(x) == true) no diff found
cout<<lo<<endl;
}
return 0;
} | true |
4f1b95c7bd94b341c1e14c74d25de36075d03810 | C++ | Rayti/humanist-invaders | /include/Foe.hpp | UTF-8 | 478 | 2.578125 | 3 | [] | no_license | #pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
class Foe {
public:
Foe(sf::RenderWindow *window, sf::Sprite sprite, sf::Vector2f position, int speed);
~Foe();
bool is_alive();
void draw_foe();
void move_right();
void move_left();
void move_down();
sf::Vector2f get_position();
int get_size();
private:
sf::RenderWindow *window;
sf::Vector2f position;
int size;
int hp;
int speed;
sf::Sprite sprite;
}; | true |
2ef04f241e407760c9aecb269898dbae488add25 | C++ | 136397089/Windows_Projects | /CreatAllParameter - 副本/CreatAllParameter/StatisticeTool.h | GB18030 | 5,441 | 2.65625 | 3 | [] | no_license | #pragma once
#ifndef STATICTOOL_H
#define STATICTOOL_H
#include <string>
#include <vector>
#include <algorithm>
#include "number/NumberInter.h"
#include "Number/commonfunction.h"
using namespace std;
struct StaticResults
{
float RiseDayRate;//ռ
float FallDayRate;//ռ
float MaxRise;//ǵ
CDate BeginDate;
StockDataType RiseRate1;//仯1
StockDataType RiseRate2;//仯2
StockDataType RiseRate3;//仯3
StockDataType FallRate1;//仯1
StockDataType FallRate2;//仯2
StockDataType FallRate3;//仯3
CharaPointType _IndexType;
StaticResults(){
RiseRate1 = 0;
RiseRate2 = 0;
RiseRate3 = 0;
RiseDayRate = 0;
FallDayRate = 0;
MaxRise = 0;
_IndexType = _eUndefindType;
}
};
struct DayPrice
{
StockDataType _closeData;
StockDataType _highData;
StockDataType _lowData;
StockDataType _openData;
StockDataType _frontclose;
StockDataType _fronthigh;
StockDataType _frontlow;
StockDataType _frontopen;
};
class CStatisticeTool
{
public:
CStatisticeTool();
~CStatisticeTool();
//ҲͬʱpriceChangeRateĵСֵ
bool GetMaxChangeRates(const VStockData& priceChangeRate, StaticResults& maxChangeRate);
//ÿڵһı仯
bool GetEveryDayChangeRate(const VStockData& vdatalist, VStockData& chanRate);
//ͳƵһںʱļ۸ٷֱ
StockDataType GetPricePosition(const StockDataTable& _inputdata);
//ʵľֵ
bool GetRateOfReturn(const VStockData& priceChangeResult,StockDataType returnrate);
//GetMaxChangeRatesʹõIJDaySizeͬͳʱ
unsigned int _statisDaySize1;
unsigned int _statisDaySize2;
unsigned int _statisDaySize3;
//
string _LastError;
};
//ʵĺ
inline StockDataType GetReturnRate_H(DayPrice oneDayPrice);
inline StockDataType GetReturnRate_L(DayPrice oneDayPrice);
inline StockDataType GetReturnRate_C(DayPrice oneDayPrice);
inline StockDataType GetReturnRate_O(DayPrice oneDayPrice);
inline StockDataType GetLogarithmicReturnRate_H(DayPrice oneDayPrice);
inline StockDataType GetLogarithmicReturnRate_L(DayPrice oneDayPrice);
inline StockDataType GetLogarithmicReturnRate_C(DayPrice oneDayPrice);
inline StockDataType GetLogarithmicReturnRate_O(DayPrice oneDayPrice);
StockDataType GetReturnRate_H(DayPrice oneDayPrice){
StockDataType frontRealPrice = oneDayPrice._frontclose;//(oneDayPrice._frontclose + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = (oneDayPrice._highData - frontRealPrice) / frontRealPrice * 100;
if (ReturnRate >= 11.0f || ReturnRate <= -11.0f)
return 0;
return ReturnRate;
}
StockDataType GetReturnRate_L(DayPrice oneDayPrice){
StockDataType frontRealPrice = oneDayPrice._frontclose;//(oneDayPrice._frontclose + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = (oneDayPrice._lowData - frontRealPrice) * 100 / frontRealPrice;
if (ReturnRate >= 11.0f || ReturnRate <= -11.0f)
return 0;
return ReturnRate;
}
StockDataType GetReturnRate_C(DayPrice oneDayPrice){
StockDataType frontRealPrice = oneDayPrice._frontclose;//(oneDayPrice._frontclose + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = (oneDayPrice._closeData - frontRealPrice) * 100 / frontRealPrice;
if (ReturnRate >= 11.0f || ReturnRate <= -11.0f)
return 0;
return ReturnRate;
}
StockDataType GetReturnRate_O(DayPrice oneDayPrice){
StockDataType frontRealPrice = oneDayPrice._frontclose;//(oneDayPrice._frontclose + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = (oneDayPrice._openData - frontRealPrice) * 100 / frontRealPrice;
if (ReturnRate >= 11.0f || ReturnRate <= -11.0f)
return 0;
return ReturnRate;
}
StockDataType GetLogarithmicReturnRate_H(DayPrice oneDayPrice){
StockDataType frontRealPrice = (oneDayPrice._frontopen + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = log((oneDayPrice._highData - frontRealPrice) / frontRealPrice + 1);
// if (ReturnRate > 10 || ReturnRate < -10)
// return 0;
return ReturnRate;
}
StockDataType GetLogarithmicReturnRate_L(DayPrice oneDayPrice){
StockDataType frontRealPrice = (oneDayPrice._frontopen + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = log((oneDayPrice._lowData - frontRealPrice) / frontRealPrice + 1);
// if (ReturnRate > 10 || ReturnRate < -10)
// return 0.0f;
return ReturnRate;
}
StockDataType GetLogarithmicReturnRate_C(DayPrice oneDayPrice){
StockDataType frontRealPrice = (oneDayPrice._frontopen + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = log((oneDayPrice._closeData - frontRealPrice) / frontRealPrice + 1);
// if (ReturnRate > 10 || ReturnRate < -10)
// return 0;
return ReturnRate;
}
StockDataType GetLogarithmicReturnRate_O(DayPrice oneDayPrice){
StockDataType frontRealPrice = (oneDayPrice._frontopen + oneDayPrice._fronthigh + oneDayPrice._frontlow) / 3;
StockDataType ReturnRate = log((oneDayPrice._openData - frontRealPrice) / frontRealPrice + 1);
// if (ReturnRate > 10 || ReturnRate < -10)
// return 0;
return ReturnRate;
}
#endif
| true |
43223488d59177e0dca0c38d330574ed9c99711f | C++ | anasmoni/competitive-programming | /uva_cpp/11727uva.cpp | UTF-8 | 349 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
#define nmax(a,b,c) (max(a,b)>c ? max(a,b) : c)
#define nmin(a,b,c) (min(a,b)<c ? min(a,b) : c)
using namespace std;
int main()
{
int t ;
cin>>t;
for(int i=1 ; i<=t ; i++)
{
int a,b,c;
cin>>a>>b>>c;
cout<<"case "<<i<<": "<<a+b+c-nmax(a,b,c)-nmin(a,b,c)<<endl;
}
return 0;
}
| true |
f0f4ee1f8f75cfade747ee2fd2f7cf53a323f7e5 | C++ | mflehmig/Adept-2 | /include/adept/Minimizer.h | UTF-8 | 8,598 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"GFDL-1.1-or-later",
"Apache-2.0"
] | permissive | /* Minimizer.h -- class for minimizing the cost function of an optimizable object
Copyright (C) 2020 European Centre for Medium-Range Weather Forecasts
Author: Robin Hogan <r.j.hogan@ecmwf.int>
This file is part of the Adept library.
*/
#ifndef AdeptMinimizer_H
#define AdeptMinimizer_H 1
#include <adept/Optimizable.h>
namespace adept {
enum MinimizerAlgorithm {
MINIMIZER_ALGORITHM_LIMITED_MEMORY_BFGS = 0,
MINIMIZER_ALGORITHM_LEVENBERG,
MINIMIZER_ALGORITHM_LEVENBERG_MARQUARDT,
MINIMIZER_ALGORITHM_NUMBER_AVAILABLE
};
enum MinimizerStatus {
MINIMIZER_STATUS_SUCCESS = 0,
MINIMIZER_STATUS_EMPTY_STATE,
MINIMIZER_STATUS_MAX_ITERATIONS_REACHED,
MINIMIZER_STATUS_FAILED_TO_CONVERGE,
MINIMIZER_STATUS_INVALID_COST_FUNCTION,
MINIMIZER_STATUS_INVALID_GRADIENT,
MINIMIZER_STATUS_INVALID_BOUNDS,
MINIMIZER_STATUS_NUMBER_AVAILABLE,
MINIMIZER_STATUS_NOT_YET_CONVERGED
};
// Return a C string describing the minimizer status
const char* minimizer_status_string(MinimizerStatus status);
// Return the order of a minimization algorithm: 0 indicates only
// the cost function is required, 1 indicates the first derivative
// is required, 2 indicates the second derivative is required, while
// -1 indicates that the algorithm is not recognized.
inline int minimizer_algorithm_order(MinimizerAlgorithm algo) {
switch (algo) {
case MINIMIZER_ALGORITHM_LIMITED_MEMORY_BFGS:
return 1;
break;
case MINIMIZER_ALGORITHM_LEVENBERG:
case MINIMIZER_ALGORITHM_LEVENBERG_MARQUARDT:
return 2;
break;
default:
return -1;
}
}
// Convenience function for initializing vectors representing the
// lower and upper bounds on state variables
inline void minimizer_initialize_bounds(int nx, adept::Vector& x_lower,
adept::Vector& x_upper) {
x_lower.resize(nx);
x_upper.resize(nx);
x_lower = -std::numeric_limits<Real>::max();
x_upper = std::numeric_limits<Real>::max();
}
// A class that can minimize a function using various algorithms
class Minimizer {
public:
// Tedious C++98 initializations
Minimizer(MinimizerAlgorithm algo)
: algorithm_(algo),
max_iterations_(100), // <=0 means no limit
max_step_size_(-1.0),
converged_gradient_norm_(0.1),
ensure_updated_state_(-1),
levenberg_damping_min_(1.0/128.0),
levenberg_damping_max_(100000.0),
levenberg_damping_multiplier_(2.0),
levenberg_damping_divider_(5.0),
levenberg_damping_start_(0.0),
levenberg_damping_restart_(1.0/4.0) { }
Minimizer(const std::string& algo)
: max_iterations_(100), // <=0 means no limit
max_step_size_(-1.0),
converged_gradient_norm_(0.1),
ensure_updated_state_(-1),
levenberg_damping_min_(1.0/128.0),
levenberg_damping_max_(100000.0),
levenberg_damping_multiplier_(2.0),
levenberg_damping_divider_(5.0),
levenberg_damping_start_(0.0),
levenberg_damping_restart_(1.0/4.0)
{ set_algorithm(algo); }
// Unconstrained minimization
MinimizerStatus minimize(Optimizable& optimizable, Vector x);
// Constrained minimization
MinimizerStatus minimize(Optimizable& optimizable, Vector x,
const Vector& x_lower, const Vector& x_upper);
// Functions to set parameters defining the general behaviour of
// minimization algorithms
void set_algorithm(MinimizerAlgorithm algo) { algorithm_ = algo; }
void set_algorithm(const std::string& algo);
void set_max_iterations(int mi) { max_iterations_ = mi; }
void set_converged_gradient_norm(Real cgn) { converged_gradient_norm_ = cgn; }
void set_max_step_size(Real mss) { max_step_size_ = mss; }
// Ensure that the last call to compute the cost function uses the
// "solution" state vector returned by minimize. This ensures that
// any variables in user classes that inherit from Optimizable are
// up to date with the returned state vector. The "order" argument
// indicates which the order of derivatives required (provided
// they are supported by the minimizing algorithm):
// 0=cost_function, 1=cost_function_gradient,
// 2=cost_function_gradient_hessian.
void ensure_updated_state(int order = 2) { ensure_updated_state_ = order; }
// Return parameters defining behaviour of minimization algorithms
MinimizerAlgorithm algorithm() { return algorithm_; }
std::string algorithm_name();
int max_iterations() { return max_iterations_; }
Real converged_gradient_norm() { return converged_gradient_norm_; }
// Functions to set parameters defining the behaviour of the
// Levenberg and Levenberg-Marquardt algorithm
void set_levenberg_damping_limits(Real damp_min, Real damp_max);
void set_levenberg_damping_start(Real damp_start);
void set_levenberg_damping_restart(Real damp_restart);
void set_levenberg_damping_multiplier(Real damp_multiply, Real damp_divide);
// Query aspects of the algorithm progress after it has completed
int n_iterations() const { return n_iterations_; }
int n_samples() const { return n_samples_; }
Real cost_function() const { return cost_function_; }
Real gradient_norm() const { return gradient_norm_; }
Real start_cost_function() const { return start_cost_function_; }
MinimizerStatus status() const { return status_; }
protected:
// Specific minimization algorithms
MinimizerStatus
minimize_limited_memory_bfgs(Optimizable& optimizable, Vector x);
// Call the Levenberg-Marquardt algorithm; if use_additive_damping
// is true then the Levenberg algorithm is used instead
MinimizerStatus
minimize_levenberg_marquardt(Optimizable& optimizable, Vector x,
bool use_additive_damping = false);
MinimizerStatus
minimize_levenberg_marquardt_bounded(Optimizable& optimizable, Vector x,
const Vector& min_x,
const Vector& max_x,
bool use_additive_damping = false);
// DATA
// Minimizer type
MinimizerAlgorithm algorithm_;
// Variables controling the general behaviour of the minimizer,
// used by all gradient-based algorithms
int max_iterations_; // <=0 means no limit
Real max_step_size_;
Real converged_gradient_norm_;
int ensure_updated_state_;
// Variables controling the specific behaviour of the
// Levenberg-Marquardt minimizer
Real levenberg_damping_min_;
Real levenberg_damping_max_;
Real levenberg_damping_multiplier_;
Real levenberg_damping_divider_;
Real levenberg_damping_start_;
Real levenberg_damping_restart_;
// Variables set during the running of an algorithm and available
// to the user afterwards
// Number of iterations that successfully reduced the cost function
int n_iterations_;
// Number of calculations of the cost function
int n_samples_;
Real start_cost_function_;
Real cost_function_;
Real gradient_norm_;
MinimizerStatus status_;
};
// Implement inline member functions
// Functions to set parameters defining the behaviour of the
// Levenberg and Levenberg-Marquardt algorithm
inline void
Minimizer::set_levenberg_damping_limits(Real damp_min, Real damp_max) {
if (damp_min <= 0.0) {
throw optimization_exception("Minimum damping factor in Levenberg-Marquardt algorithm must be positive");
}
else if (damp_max <= damp_min) {
throw optimization_exception("Maximum damping factor must be greater than minimum in Levenberg-Marquardt algorithm");
}
levenberg_damping_min_ = damp_min;
levenberg_damping_max_ = damp_max;
}
inline void
Minimizer::set_levenberg_damping_start(Real damp_start) {
if (damp_start < 0.0) {
throw optimization_exception("Start damping factor in Levenberg-Marquardt algorithm must be positive or zero");
}
levenberg_damping_start_ = damp_start;
}
inline void
Minimizer::set_levenberg_damping_restart(Real damp_restart) {
if (damp_restart <= 0.0) {
throw optimization_exception("Restart damping factor in Levenberg-Marquardt algorithm must be positive");
}
levenberg_damping_restart_ = damp_restart;
}
inline void
Minimizer::set_levenberg_damping_multiplier(Real damp_multiply,
Real damp_divide) {
if (damp_multiply <= 1.0 || damp_divide <= 1.0) {
throw optimization_exception("Damping multipliers in Levenberg-Marquardt algorithm must be greater than one");
}
levenberg_damping_multiplier_ = damp_multiply;
levenberg_damping_divider_ = damp_divide;
}
};
#endif
| true |
25a872faaf982b16de21a8ab5953b99706c13042 | C++ | jonasdahl/cprog-lab3 | /sword.cpp | UTF-8 | 254 | 2.65625 | 3 | [] | no_license | #include "sword.h"
#include <sstream>
using namespace std;
namespace lotr {
string Sword::to_string() const {
stringstream stream;
stream << Weapon::to_string() << endl;
stream << "Det är ett svärd också" << endl;
return stream.str();
}
} | true |
256316f890b9e95d5161dab06fe36518c1f247da | C++ | JulienZeng/bky-data-structure | /百科园-第五章/原题/1/Program.cpp | GB18030 | 4,280 | 3.671875 | 4 | [] | no_license | /*------------------------------------------------
ơ
--------------------------------------------------
ÿԪؾΪһַ˳
ΪǰУԪΪ'#'ʱʾýΪգ
дαС
뽨ǰС
αС
1
ab##c##
1
abc
--------------------------------------------------
ע⣺Դ¡Ķ
mainеκݣں
Ļbeginend֮д䡣
*********Begin******************** End **********ɾ
------------------------------------------------*/
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int I;
void bky();
//Ķ洢ʾ
typedef struct BiNode
{
char data; //
struct BiNode *lchild,*rchild; //Һָ
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T,char s[])
{
//s洢˰ֵɵУԪΪ'#'ʱʾýΪգ
//sʾĶT
char ch;
ch=s[I++];
if(ch=='#') T=NULL; //ݹ
else{
T=new BiTNode;
T->data=ch; //ɸ
CreateBiTree(T->lchild,s); //ݹ鴴
CreateBiTree(T->rchild,s); //ݹ鴴
} //else
} //CreateBiTree
//*********************************************************************
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status; // StatusǺֵͣǺ״̬룬OK
typedef BiTree QElemType ;//еԪ
// е˳洢ṹ(ѭ)ڽ̿64ҳ
#define MAXQSIZE 50 // г+1
typedef struct
{ QElemType *base; // ʼĶ̬洢ռ
int front; // ͷָ룬вգָͷԪ
int rear; // βָ룬вգָβԪصһλ
}SqQueue;
// ѭеĻ
//㷨3.11ѭеijʼ
Status InitQueue(SqQueue &Q) {//һնQ
Q.base = new QElemType[MAXQSIZE]; //ΪзһΪMAXSIZEռ
if (!Q.base)
exit(OVERFLOW); //洢ʧ
Q.front = Q.rear = 0; //ͷָβָΪ㣬Ϊ
return OK;
}
//㷨3.13ѭе
Status EnQueue(SqQueue &Q, QElemType e) {//ԪeΪQµĶβԪ
if ((Q.rear + 1) % MAXQSIZE == Q.front) //βָѭϼ1ͷָ룬
return ERROR;
Q.base[Q.rear] = e; //Ԫزβ
Q.rear = (Q.rear + 1) % MAXQSIZE; //βָ1
return OK;
}
//㷨3.14ѭеij
Status DeQueue(SqQueue &Q, QElemType &e) {//ɾQĶͷԪأeֵ
if (Q.front == Q.rear)
return ERROR; //ӿ
e = Q.base[Q.front]; //ͷԪ
Q.front = (Q.front + 1) % MAXQSIZE; //ͷָ1
return OK;
}
int QueueEmpty(SqQueue Q)
{
if (Q.front == Q.rear) //п
return 1;
else
return 0;
}
//******************************************************************
void LevelOrderTraverse(BiTree T,char Lever[])
{//öвα,αLever鷵
/*********Begin**********/
/********** End **********/
}
int main()
{
BiTree T;
char s[100];
char Lever[100];
cin>>s;
I=0; //ȫֱCreateBiTree()Ҫʹ
CreateBiTree(T,s);
LevelOrderTraverse(T,Lever);
cout<<Lever<<endl;
bky();
return 0;
}
void bky()
{
ofstream fout("output.txt");
ifstream fin("in.txt");
BiTree T;
char s[100];
char Lever[100];
int k=5;
while(k--)
{
fin>>s;
I=0; //ȫֱCreateBiTree()Ҫʹ
CreateBiTree(T,s);
LevelOrderTraverse(T,Lever);
fout<<Lever<<endl;
}
}
| true |
ef1807d7683188eec7e17668151c53e0e53a2bc8 | C++ | hetpatel4902/cpp_programs | /cpp_practicals/Pro25.cpp | UTF-8 | 577 | 3.546875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class PointS
{
int x,y;
public:
PointS ( int x1, int y1 )
{
x = x1;
y = y1;
}
PointS (const PointS &p1)
{
x = p1.x;
y = p1.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
PointS p1(11,19);
PointS p2 = p1;
cout << "p1.x = " << p1.getX() << ", p1.y =" <<p1.getY() << endl;
cout << "p2.x = " << p2.getX() << ", p2.y =" <<p2.getY() << endl;
return 0;
}
| true |
a34e00dd5401a2cf4e548b871e8d36559681c314 | C++ | believeszw/LeetCode | /AllQuestions/title1.cc | UTF-8 | 1,340 | 3.3125 | 3 | [] | no_license | //
// Created by PC-Saw on 2018/12/25.
// Copyright (c) 2020 believe. All rights reserved.
//
#include "util.h" // NOLINT
#include <unordered_map>
#include <vector>
// 题号 1 : Two Sum
//
// Given an array of integers, return indices of the two numbers such that they
// add up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
//
/*
Example 1:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
* */
class Title1 {
public:
static std::vector<int> TwoSum(const std::vector<int> &nums, int target) {
// 哈希表和map在这个数量级下性能差异不明显
std::unordered_map<int, int> unordered_map;
int size = nums.size();
for (int i = 0; i < size; ++i) {
int complement = target - nums[i];
if (unordered_map.find(complement) != unordered_map.end()) {
return std::vector<int>{unordered_map.find(complement)->second, i};
}
unordered_map[nums[i]] = i;
}
return std::vector<int>{-1, -1};
}
};
TEST(AllQueTitle1, test) {
std::vector<int> vector = {2, 7, 11, 15};
std::vector<int> ret = {0};
{
ScopedTimer timer("Title1::TwoSum");
ret = Title1::TwoSum(vector, 9);
}
EXPECT_EQ(0, ret[0]);
EXPECT_EQ(1, ret[1]);
}
| true |
2641462dba96585acea9c191282491c78c31f1da | C++ | zhang165/simpleShader | /object.cpp | UTF-8 | 7,541 | 3.296875 | 3 | [] | no_license | #include "object.hpp"
#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <cmath>
#include <cfloat>
#include <iostream>
// 2016 Version
bool Object::intersect(Ray ray, Intersection &hit) const
{
// Assert the correct values of the W coords of the origin and direction.
// You can comment this out if you take great care to construct the rays
// properly.
ray.origin[3] = 1;
ray.direction[3] = 0;
Ray localRay(i_transform * ray.origin, i_transform * ray.direction);
//!!! USEFUL NOTES: to calculate depth in localIntersect(), if the intersection happens at
//ray.origin + ray.direction * t, then t is just the depth
//!!! USEFUL NOTES: Here direction might be scaled, so you must not renormalize it in
//localIntersect(), or you will get a depth in local coordinate system,
//which can't be compared with intersections with other objects
if (localIntersect(localRay, hit)) {
// Assert correct values of W.
hit.position[3] = 1;
hit.normal[3] = 0;
// Transform intersection coordinates into global coordinates.
hit.position = transform * hit.position;
hit.normal = (n_transform * hit.normal).normalized();
return true;
}
return false;
}
//INTERSECTIONS
// helper function from Scratchapixel
bool solveQuadratic(const double &a, const double &b, const double &c, double &x0, double &x1){
double discr = b * b - 4 * a * c; // b^2 - 4*ac
if (discr < 0) return false;
else if (discr == 0) x0 = x1 = -0.5 * b / a;
else {
double q = (b > 0) ? -0.5 * (b + sqrt(discr)) : -0.5 * (b - sqrt(discr));
x0 = q / a;
x1 = c / q;
}
if (x0 > x1) std::swap(x0, x1);
return true;
}
bool Sphere::localIntersect(Ray const &ray, Intersection &hit) const {
//////////////////
// YOUR CODE HERE
// For this part you are required to calculate if a ray has intersected your sphere.
// Be sure to cover all the possible intersection scenarios(zero, one, and two points of intersection).
// Test your result by comparing the output depth image of your algorithm with the provided example solution's results.
// Here in local coordinate system, the sphere is centered on (0, 0, 0)
//with radius 1.0
//
// NOTE: hit.depth is the current closest intersection depth, so don't
// accept any intersection that happens further away than that.
double radius = this->radius;
radius = radius * radius;
Vector p0 = Vector(0,0,0);
double t0, t1;
Vector L = ray.origin - p0;
double a = ray.direction.dot(ray.direction);
double b = 2 * ray.direction.dot(L);
double c = L.dot(L) - radius;
if (!solveQuadratic(a, b, c, t0, t1)) return false;
if (t0 > t1) std::swap(t0, t1); // make t0 the smallest
if (t0 < 0) {
t0 = t1; // if t0 is negative, let's use t1 instead
if (t0 < 0) return false; // both t0 and t1 are negative
}
if(hit.depth < t0) return false; // take the closest depth
hit.depth = t0;
hit.position = ray.origin + ray.direction * hit.depth;
hit.normal = hit.position;
return true;
}
bool Plane::localIntersect(Ray const &ray, Intersection &hit) const{
//////////////////
// YOUR CODE HERE
// The implementation of this part is similar to the previous part in that you are
// calculating if a line has intersected your plane.Test this function in a similar
// way to the previous part(note that as you do new objects will appear).
// Do not accept intersection while ray is inside the plane
// Here in local coordinate system, the plane is at z = 0
//
// NOTE: hit.depth is the current closest intersection depth, so don't
// accept any intersection that happens further away than that.
Vector n = Vector(0, 0, 1);
Vector p0 = Vector(0, 0, 0);
double ln = n.dot(ray.direction);
if (abs(ln) <= 1e-6) return false; // parallel
double op = (ray.origin - p0).dot(n);
if (abs(op) <= 1e-6) return false; // inside
double t = -(op) / ln;
if ((t < 0 ) || (hit.depth < t)) return false; // take the closest valid ray
hit.depth = t;
hit.normal = n;
hit.position = ray.origin + ray.direction * t;
return true;
}
bool Mesh::intersectTriangle(Ray const &ray, Triangle const &tri, Intersection &hit) const
{
// Extract vertex positions from the mesh data.
Vector const &p0 = positions[tri[0].pi];
Vector const &p1 = positions[tri[1].pi];
Vector const &p2 = positions[tri[2].pi];
//////////////////
// YOUR CODE HERE
// Think back through the course and try to decide what equations might help you decide on which
// side of the bounding lines of the triangle the ray intersects.
// Test this part just like the above two parts; when triangle intersection is working properly,
// you should be able to see full meshes appear in your scenes.
//
// NOTE: hit.depth is the current closest intersection depth, so don't
// accept any intersection that happens further away than that.
//!!! USEFUL NOTES: for the intersection point, its normal should satisfy hit.normal.dot(ray.direction) < 0
Vector v0v1 = p1 - p0;
Vector v0v2 = p2 - p0;
// PLANE TEST
Vector n = v0v1.cross(v0v2);
double ln = n.dot(ray.direction);
if (abs(ln) <= 1e-6) return false; // parallel
double op = (ray.origin - p0).dot(n);
if (abs(op) <= 1e-6) return false; // inside
double t = -(op) / ln;
Vector P = ray.origin + t * ray.direction; // the intersection point
// INSIDE TEST
Vector C; // vector perpendicular to triangle's plane
Vector edge0 = p1 - p0;
Vector vp0 = P - p0;
C = edge0.cross(vp0);
if (n.dot(C) < 0) return false; // P is on the right side
Vector edge1 = p2 - p1;
Vector vp1 = P - p1;
C = edge1.cross(vp1);
if (n.dot(C) < 0) return false; // P is on the right side
Vector edge2 = p0 - p2;
Vector vp2 = P - p2;
C = edge2.cross(vp2);
if (n.dot(C) < 0) return false; // P is on the right side;
if (hit.depth < t || t < 0) return false;
hit.depth = t;
hit.normal = n;
hit.position = P;
return true;
}
bool Conic::localIntersect(Ray const &ray, Intersection &hit) const {
//////////////////
// YOUR CODE HERE (creative license)
return false;
}
// Intersections!
bool Mesh::localIntersect(Ray const &ray, Intersection &hit) const
{
// Bounding box check
double tNear = -DBL_MAX, tFar = DBL_MAX;
for (int i = 0; i < 3; i++) {
if (ray.direction[i] == 0.0) {
if (ray.origin[i] < bboxMin[i] || ray.origin[i] > bboxMax[i]) {
// Ray parallel to bounding box plane and outside of box!
return false;
}
// Ray parallel to bounding box plane and inside box: continue;
}
else {
double t1 = (bboxMin[i] - ray.origin[i]) / ray.direction[i];
double t2 = (bboxMax[i] - ray.origin[i]) / ray.direction[i];
if (t1 > t2) std::swap(t1, t2); // Ensure t1 <= t2
if (t1 > tNear) tNear = t1; // We want the furthest tNear
if (t2 < tFar) tFar = t2; // We want the closest tFar
if (tNear > tFar) return false; // Ray misses the bounding box.
if (tFar < 0) return false; // Bounding box is behind the ray.
}
}
// If we made it this far, the ray does intersect the bounding box.
// The ray hits the bounding box, so check each triangle.
bool isHit = false;
for (size_t tri_i = 0; tri_i < triangles.size(); tri_i++) {
Triangle const &tri = triangles[tri_i];
if (intersectTriangle(ray, tri, hit)) {
isHit = true;
}
}
return isHit;
}
double Mesh::implicitLineEquation(double p_x, double p_y,
double e1_x, double e1_y,
double e2_x, double e2_y) const
{
return (e2_y - e1_y)*(p_x - e1_x) - (e2_x - e1_x)*(p_y - e1_y);
}
| true |
0f77c7742c649aeda4ddae5f2281fa11645ec568 | C++ | scottyfulton/WormholeAdventure2 | /WormholeAdventure_v2/GObject.cpp | UTF-8 | 1,735 | 2.703125 | 3 | [] | no_license | #pragma once
#include "GObject.h"
using namespace glm;
/*
** Each GObject's light sources should be obtained by looping through every object, determining if a GObject is a light,
** then sorting (binarySort) for the 10 closest light sources
*/
GObject::GObject(){}; // implicitly called when child classes are constructed
GObject::GObject(GLuint shaderID, GLuint textureID, GLuint vaoID, GLsizei numVertices, glm::vec3 pos, glm::vec3 rot ) {
this->shader = shaderID;
this->texture = textureID;
this->vao = vaoID;
this->numVertices = numVertices;
this->pos = pos;
this->rot = rot;
};
GObject::~GObject() {
}
void GObject::update(double time, double dt) { //manipulates position data (particles follow wormhole, ship moves in xy-plane, asteroids follow path inside wormhole)
};
void GObject::render(double alpha){
//Shader
glUseProgram(shader);
//VAO
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
//Texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glEnable(GL_DEPTH_TEST);
//Interpolate
/*
//Interpolate
posI.x = (float) (pos.x + (vel.x * alpha));
posI.y = (float) (pos.y + (vel.y * alpha));
posI.z = (float) (pos.z + (vel.z * alpha));
*/
//translation
translateMatrix = glm::mat4(1.0);
//Transformation
transformationMatrix = glm::mat4(1.0);
transformationMatrix = glm::translate(transformationMatrix, pos);
//Uniform
glUniform1i(texture, 0);
glUniformMatrix4fv(glGetUniformLocation(shader, "transformationMatrix"), 1, false, glm::value_ptr(transformationMatrix));
//Draw
glDrawArrays(GL_TRIANGLES, 0, numVertices);
}
/*
reset matrix
*/ | true |
f0758f66697750523763ce171351177b3d377b67 | C++ | angelopagliuca/fiea-game-engine | /source/Library.Shared/Factory.h | UTF-8 | 3,017 | 2.984375 | 3 | [] | no_license | #pragma once
#include <gsl/gsl>
#include <limits>
#include "HashMap.h"
namespace FieaGameEngine
{
/// <summary>
/// Our configuration language allows us to express the intention of creating objects, based on the name
/// of their type. Factory, is suitable for use with any interface class that has a default constructor.
/// The game engine will use this Factory to create objects by their type name.
/// </summary>
template <typename T>
class Factory
{
public:
/// <summary>
/// Returns a string representing the name of the class the factory instantiates.
/// </summary>
/// <returns>string representing the name of the class</returns>
virtual const std::string& ClassName() const = 0;
/// <summary>
/// Pure virtual create function
/// </summary>
/// <returns>new object of that type given</returns>
virtual gsl::owner<T*> Create() const = 0;
/// <summary>
/// Given a class name (string), return the associated concrete factory.
/// </summary>
/// <param name="className">given class name</param>
/// <returns>the associated concrete factory</returns>
static const Factory* const Find(const std::string& className);
/// <summary>
/// Given a class name (string), returns a new object of that type.
/// </summary>
/// <param name="className">given class name</param>
/// <returns>new object of that type given</returns>
static gsl::owner<T*> Create(const std::string& className);
/// <summary>
/// resizes the factory map of all factories
/// </summary>
/// <param name="bucketSize">new size</param>
static void Resize(size_t bucketSize);
/// <summary>
/// returns number of factories
/// </summary>
/// <returns>number of factories</returns>
static size_t Size();
/// <summary>
/// is factories empty?
/// </summary>
/// <returns>true if no factories false otherwise</returns>
static bool IsEmpty();
protected:
static void Add(const Factory& factory);
static void Remove(const Factory& factory);
private:
inline static HashMap<std::string, const Factory* const> _factories;
};
}
/// <summary>
/// ConcreteFactory is the macro used to create derived factories
/// </summary>
#define ConcreteFactory(ConcreteProductT, AbstractProductT) \
class ConcreteProductT##Factory final : public FieaGameEngine::Factory<AbstractProductT> \
{ \
public: \
ConcreteProductT##Factory() { FieaGameEngine::Factory<AbstractProductT>::Add(*this); } \
~ConcreteProductT##Factory() { FieaGameEngine::Factory<AbstractProductT>::Remove(*this); } \
const std::string& ClassName() const override { return _className; } \
gsl::owner<ConcreteProductT*> Create() const override { return new ConcreteProductT(); } \
private: \
inline static const std::string _className{ #ConcreteProductT }; \
};
#include "Factory.inl" | true |
8b98fd43a7e67bad397f167e000204f2f5edc738 | C++ | BeatEngine/sieve-of-eratosthenes | /primesSieve.cpp | UTF-8 | 1,733 | 3.703125 | 4 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
int* findPrimes(int max = 100)
{
int* arr = (int*)malloc(sizeof(int) * max);
if(arr == 0)
{
return 0;
}
memset(arr,0, sizeof(int)*21);
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[4] = 5;
arr[6] = 7;
arr[10] = 11;
arr[12] = 13;
arr[16] = 17;
arr[18] = 19;
//3,5,7,9,11,13,15,17,19
// 5 --> 15
// 3 --> 9
int maxMinus = max - 1;
for(int i = 21; i < maxMinus; i+=2)
{
int imo = i-1;
arr[i] = 0;
if(i % 3 == 0
|| i % 5 == 0
|| i % 7 == 0
|| i % 11 == 0
|| i % 13 == 0
|| i % 17 == 0
|| i % 19 == 0
)
{
arr[imo] = 0;
}
else
{
int c = 21;
bool notPrime = false;
while (c < i)
{
if(i % c == 0)
{
arr[imo] = 0;
notPrime = true;
break;
}
c += 2;
}
if(notPrime)
{
continue;
}
else
{
arr[imo] = i;
}
}
}
return arr;
}
void printPrimes(int* arr, int sizeElements = 0)
{
for(int i = 0; i < sizeElements; i++)
{
if(arr[i] != 0)
{
printf("%d, ", arr[i]);
}
}
}
int main()
{
int max = 100000;
int* primes = findPrimes(max);
if(primes)
{
printPrimes(primes, max);
free(primes);
}
else
{
printf("Allocation error!\n");
}
return 0;
}
| true |
62fb863142ff9264c147bb5ed9a4d972c5480a10 | C++ | ooooo-youwillsee/leetcode | /0000-0500/0421-Maximum XOR of Two Numbers in an Array/cpp_0421/main.cpp | UTF-8 | 197 | 2.609375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "Solution1.h"
int main() {
Solution solution;
vector<int> nums = {3, 10, 5, 25, 2, 8};
int ans = solution.findMaximumXOR(nums);
cout << ans << endl;
return 0;
}
| true |
b6a6f4e9700ae1bcb1438858edbe478234a43de3 | C++ | howlie190/POSD_HW3 | /term.h | UTF-8 | 265 | 2.78125 | 3 | [] | no_license | #ifndef term_h
#define term_h
#include <string>
using std :: string;
class Term {
public:
virtual string symbol() const = 0;
virtual string value() const { return symbol(); }
virtual bool match(Term &term) { return symbol() == term.symbol(); }
};
#endif | true |
46ab4114c973f27b1693155fa9d1104dda564dd0 | C++ | msanchezzg/UVaOnlineJudge | /12000-12999/12403/saveSetu_12403.cpp | UTF-8 | 366 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main(){
int total,donacion,casos,i;
total=0;
i=0;
string entrada;
cin>>casos;
while(i<casos){
i++;
cin>>entrada;
if (entrada.compare("report")==0) cout<<total<<endl;
else{
cin>>donacion;
total+=donacion;
}
}
return 0;
}
| true |
dfaea1f8feac3f5dca7609eb9b661bc12b064258 | C++ | webformation/initiationCPP | /exceptionCapteur.h | UTF-8 | 637 | 2.796875 | 3 | [] | no_license | #ifndef EXCEPTIONCAPTEUR_H_INCLUDED
#define EXCEPTIONCAPTEUR_H_INCLUDED
class exceptionCapteur {
private:
string message;
public:
exceptionCapteur(string message) : message(message) {}
string what() {
return message;
}
};
class capteurParametreInvalide : public exceptionCapteur {
public:
using exceptionCapteur::exceptionCapteur;
};
class capteurErreurInitialisation : public exceptionCapteur {
public:
using exceptionCapteur::exceptionCapteur;
};
class capteurErreurLecture : public exceptionCapteur {
public:
using exceptionCapteur::exceptionCapteur;
};
#endif // EXCEPTIONCAPTEUR_H_INCLUDED
| true |
f6fbed74bb9d83eb6e34af688e098913a73a7331 | C++ | vyomkeshj/TriangulationFEM | /Source/point_cloud_reader.cpp | UTF-8 | 708 | 2.953125 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "../headers/point_cloud.h"
using namespace std;
using namespace algorithms;
vector<Vec3D *> point_cloud_reader::get_point_cloud() {
vector<Vec3D *> points = vector<Vec3D *>();
cout << "Loading: ";
string filename = "Resource/sample.txt";
ifstream file(filename);
double x = 0, y = 0, z = 0;
int _red = 0, _green = 0, _blue = 0;
char hex;
while (file >> hex) {
file >> x >> y >> z >> _red >> _green >> _blue;
Vec3D *dot = new Vec3D(x, y, z, (uint8_t) _red, (uint8_t) _green, (uint8_t) _blue);
points.push_back(dot);
}
file.close();
return points;
}
| true |
12d26d3d87226d3870925e0f7456d9e86b1a25dd | C++ | ggmorais/flappybird-sfml | /sources/Pipes.cpp | UTF-8 | 2,189 | 3.046875 | 3 | [] | no_license | #include <Pipes.hpp>
#include <Player.hpp>
#include <constants.hpp>
Pipes::Pipes(std::string texturePath)
{
if (!m_texture.loadFromFile(texturePath))
std::cerr << "Error loading pipes texture\n";
m_sprite_top.setTexture(m_texture);
m_sprite_bottom.setTexture(m_texture);
m_sprite_top.setScale(2.f, -2.f);
m_sprite_bottom.setScale(SPRT_SCALE);
}
float Pipes::getWidth()
{
return m_sprite_top.getGlobalBounds().width;
}
void Pipes::setX(float x)
{
m_sprite_top.setPosition(x, m_sprite_top.getPosition().y);
m_sprite_bottom.setPosition(x, m_sprite_bottom.getPosition().y);
}
void Pipes::update(sf::RenderTarget& target)
{
if (m_sprite_bottom.getPosition().y == 0) {
m_sprite_top.setPosition(m_sprite_top.getPosition().x, m_sprite_top.getGlobalBounds().height - 400.f);
m_sprite_bottom.setPosition(m_sprite_bottom.getPosition().x, target.getSize().y - m_sprite_bottom.getGlobalBounds().height + 400.f);
}
m_sprite_top.move(m_speed, 0.f);
m_sprite_bottom.move(m_speed, 0.f);
if (m_sprite_top.getPosition().x + m_sprite_top.getGlobalBounds().width < 0) {
float newPosX = target.getSize().x + m_sprite_top.getGlobalBounds().width;
float randomY = rand() % 150 + 1;
m_sprite_top.setPosition(newPosX, m_sprite_top.getGlobalBounds().height - 550.f + randomY);
m_sprite_bottom.setPosition(newPosX, target.getSize().y - m_sprite_bottom.getGlobalBounds().height + 150.f + randomY);
}
}
void Pipes::render(sf::RenderTarget& target)
{
target.draw(m_sprite_top);
target.draw(m_sprite_bottom);
}
bool Pipes::checkPlayerSuccess(Player& player)
{
if (player.getPosition().x > m_sprite_bottom.getPosition().x &&
player.getPosition().x + player.getRect().width < m_sprite_bottom.getPosition().x + m_sprite_bottom.getGlobalBounds().width) {
return true;
}
return false;
}
bool Pipes::checkPlayerCollision(Player& player)
{
if (m_sprite_top.getGlobalBounds().intersects(player.getRect())) {
return true;
}
if (m_sprite_bottom.getGlobalBounds().intersects(player.getRect())) {
return true;
}
return false;
}
| true |
3ba68a7aa100aeac13cb5d1733a24cc9b621a4b3 | C++ | cyberfenrir/programs-C | /Untitled4.cpp | UTF-8 | 766 | 3.421875 | 3 | [] | no_license | #include<iostream.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main( )
{
char str1[800], str2[800];
cout<<"Enter first string: ";
cin.getline(str1, 800);
cout<<"Enter second string: ";
cin.getline(str2, 800);
int l = 0; //Hold length of second string
//finding length of second string
for(l = 0; str2[l] != '\0'; l++);
int i, j;
for(i = 0, j = 0; str1[i] != '\0' && str2[j] != '\0'; i++)
{
if(str1[i] == str2[j])
{
j++;
}
else
{
j = 0;
}
}
if(j == l)
{
cout<<"Substring found at position "<< i - j + 1;
}
else
{
cout<<"Substring not found";
}
cout<<"\n";
return 0;
} | true |
f6c8ee6f9d2daa9cf8722358b440dc962ee320b8 | C++ | Cookiefan/ZigZag | /Zigzag/May/CF#354/D.cpp | UTF-8 | 1,953 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define maxn 1200
using namespace std;
int v[maxn][maxn][4];
int mp[maxn][maxn][4];
struct point
{
int x, y, z;
point(){}
point(int x, int y, int z):x(x),y(y),z(z){}
friend point operator +(point a, point b)
{
return point(a.x+b.x, a.y+b.y, (a.z+b.z)%4);
}
friend bool operator ==(point a, point b)
{
return a.x==b.x && a.y==b.y;
};
}st, ed;
const point dir[5]={point(-1,0,0), point(0,1,0), point(1,0,0), point(0,-1,0), point(0, 0, 1)};
deque<point> q;
deque<int> step;
int n,m;
char c;
int tran(char c)//0 door
{
if (c=='+') return 0;
if (c=='L') return 8;
if (c=='D') return 4;
if (c=='R') return 2;
if (c=='U') return 1;
if (c=='-') return 5;
if (c=='|') return 10;
if (c=='^') return 14;
if (c=='>') return 13;
if (c=='v') return 11;
if (c=='<') return 7;
else return 15;
}
bool judge(point a, point b, int e)
{
if (e==4) return 1;
if (!(1<=b.x && b.x<=n && 1<=b.y && b.y<=m)) return 0;
int k=a.z;
if (!mp[a.x][a.y][(e+4-k)%4] && !mp[b.x][b.y][(e+6-k)%4]) return 1;
return 0;
}
int travel(point st, point ed)
{
memset(v,0,sizeof(v));
q.push_back(st);
step.push_back(0);
v[st.x][st.y][st.z]=1;
while (!q.empty())
{
point now=q.front();
//cout<<now.x<<' '<<now.y<<' '<<now.z<<endl;
int s=step.front();
if (now==ed) return s;
q.pop_front();
step.pop_front();
for (int i=0;i<5;i++)
{
point tmp=now+dir[i];
if (judge(now, tmp, i) && !v[tmp.x][tmp.y][tmp.z] )
{
q.push_back(tmp);
step.push_back(s+1);
v[tmp.x][tmp.y][tmp.z]=1;
}
}
}
return -1;
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
scanf(" %c",&c);
int mask=tran(c);
for (int k=0;k<4;k++)
mp[i][j][k]=(mask>>k)&1;
// for (int k=3;k>=0;k--)
// cout<<mp[i][j][k]<<' ';
// cout<<endl;
}
int x,y;
scanf("%d%d",&x,&y);
st=point(x,y,0);
scanf("%d%d",&x,&y);
ed=point(x,y,0);
printf("%d\n",travel(st, ed));
return 0;
} | true |
60ebbc5f0d4674ebdabba3e50fd4531768f15556 | C++ | Wilhelmshaven/LeetCode-OJ | /LeetCode OJ/Number of Digit One.cpp | UTF-8 | 452 | 2.890625 | 3 | [] | no_license | int countDigitOne(int n) {
if (n<1)return 0;
long ten = 1, cnt = 0, right, left, now;
while (n / ten != 0)
{
right = n%ten; //High NUM
left = n / (ten * 10); //Low NUM
now = (n / ten) % 10; //Now Dight
if (now == 0)cnt = cnt + left*ten;
else if (now == 1)cnt = cnt + left*ten + 1 + right;
else cnt = cnt + (left + 1)*ten;
ten = ten * 10;
}
return cnt;
}
//Runtime: 0 ms
//Your runtime beats 1.67% of c submissions. | true |
caf81688f8f9c3582c6286bcdf2435bf04d60719 | C++ | ortlaz/Laba2 | /include/Massive.h | WINDOWS-1251 | 767 | 3.171875 | 3 | [] | no_license | #ifndef MASSIVE_H
#define MASSIVE_H
#include <cstdlib>
class Massive
{
std::size_t last; //-
int *data; //
std::size_t max_elem; //
public:
int pop(void); //
void push(int);//
int size(void);//
bool empty(void);//
Massive();
Massive(int);
virtual ~Massive();
private:
Massive(const Massive&) = delete; //
};
#endif // MASSIVE_H
| true |
7f968bd4a661affba35d8590a9b0ded27eb4674b | C++ | exetr/CS2040C | /Problem Sets/ps2b.cpp | UTF-8 | 3,887 | 3.59375 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class LinkedList {
struct Node {
char c;
Node* next;
};
public:
Node* head;
//constructor
LinkedList() {
head = NULL;
}
void insertNode(int pos, char c) {
//insert data into new temp node
Node* temp = new Node();
temp->c = c;
temp->next = NULL;
//if linked list is empty
if ((head == NULL) && (pos == 0)) {
head = temp;
}
//else if insert at start of linked list
else if (pos == 0) {
temp->next = head;
//head->next = temp;
head = temp;
} else {
int i = 1;
Node* prev = head;
//loop to desired node before point of insertion
while ((prev->next != NULL) && (i != pos)) {
prev = prev->next;
i++;
}
if (i == pos) {
Node* current = prev->next;
prev->next = temp;
temp->next = current;
} else {
prev->next=temp;
}
}
}
void deleteFirst() {
Node* temp = new Node();
temp = head;
head = head->next;
delete temp;
}
void deleteLast() {
Node* current = new Node();
Node* prev = new Node();
current = head;
while (current->next != NULL) {
prev = current;
current = current->next;
}
prev->next = NULL;
delete current;
}
void deleteNode(int x) {
Node* current = new Node();
Node* prev = new Node();
current = head;
for (int i=0; i<x-1; i++) {
prev=current;
current = current->next;
}
prev->next = current->next;
delete current;
}
void printList() {
if (head==NULL) {
cout << "linked list is empty" << endl;
} else {
Node* current = head;
while(current!=NULL) {
cout << current->c;
current = current->next;
}
cout << endl;
}
}
};
int main() {
/* LinkedList* text = new LinkedList();
text->insertNode(0, 'a');
text->insertNode(0, 'b');
text->insertNode(2, 'c');
text->insertNode(3, 'd');
text->insertNode(4, 'e');
text->printList(); */
unsigned int tc;
cin >> tc;
cin.ignore(100, '\n');
for (int i=0; i<tc; i++) {
char c;
int curPos = 0;
int endPos = 0;
LinkedList* output = new LinkedList();
for (c=getchar(); c != '\n';) {
if (c == '<') {
if (curPos == 0) {
; //do nothing
} else {
if ((curPos-1) == 0 ) {
output->deleteFirst();
} else if (curPos == endPos) {
output->deleteLast();
} else {
output->deleteNode(curPos);
}
curPos--;
endPos--;
}
} else if (c == '[') {
curPos = 0;
} else if (c == ']') {
curPos = endPos;
} else {
//cout << curPos << endl;
output->insertNode(curPos, c);
curPos++;
endPos++;
}
c = getchar();
}
output->printList();
}
return 0;
} | true |
f76c2f25f38ed84f7b7e1995390c5e2f9449892d | C++ | contrapct/onlinej | /valid palindrome.cpp | UTF-8 | 1,627 | 3.21875 | 3 | [] | no_license | class Solution {
public:
bool isPalindrome(string s) {
int start=0,end = s.length()-1;
int ch_start=0,ch_end=0;
while(start<=end){
if(start == end) return true;
ch_start=0,ch_end=0;
while(start <= end && !('a'<=s[start] && s[start]<='z') )
if(!('A'<=s[start] && s[start]<='Z'))
if(!('0'<=s[start] && s[start]<='9'))
++start;
else break;
else break;
while(start <=end && !('a'<=s[end] && s[end]<='z') )
if(!('A'<=s[end] && s[end]<='Z'))
if(!('0'<=s[end] && s[end]<='9'))
--end;
else break;
else break;
if(start>end) return true;
if( 'a'<=s[start] && s[start]<='z'){
ch_start = (s[start]-'a');
++start;
}
else
if( 'A'<=s[start] && s[start]<='Z'){
ch_start = (s[start]-'A');
++start;
}
else if('0'<=s[start] && s[start]<='9'){
ch_start = s[start]-'0'+100;
++start;
}
if('a'<=s[end] && s[end]<='z'){
ch_end = (s[end]-'a');
--end;
}
else
if('A'<=s[end] && s[end]<='Z'){
ch_end = (s[end]-'A');
--end;
}
else if('0'<=s[end] && s[end]<='9'){
ch_end = s[end]-'0'+100;
--end;
}
if(ch_end!=ch_start) return false;
}
return true;
}
}; | true |