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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
80ed93df2edd890c17ee1defeb0a9220d82fc335 | C++ | alexyuehuang/OOP_Projects | /Lab_2/Lab02/Board.h | UTF-8 | 508 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include "game_pieces.h"
#include <vector>
//use standard namespace
using namespace std;
struct piece {
string name;
string display;
colors color = invalid;
};
//functions
int dimensions(ifstream& a, unsigned int& b, unsigned int& c);
int read(ifstream& a, vector<piece>& d, unsigned int& b, unsigned int& c);
int print(const vector<piece>& a, unsigned int b, unsigned int c);
int neighbors(const vector<piece>& a, unsigned int b, unsigned int c); | true |
2a1439bd42740d951150ae76d86af6b74b025214 | C++ | qiyang0221/leetcode | /Construct Binary Tree from Preorder and Inorder Traversal.cpp | GB18030 | 1,855 | 3.71875 | 4 | [] | no_license | //
//description:
//
//
//solution
//ʾʼֹ
//ĵһмֵ
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int size = preorder.size();
TreeNode * root = recur(preorder,0,size,inorder,0,size);
return root;
}
TreeNode *recur(vector<int> &preorder,int pre_start,int pre_end,vector<int> &inorder,int in_start,int in_end){
if(in_start == in_end || pre_start == pre_end)
return NULL;
TreeNode * root = new TreeNode(preorder[pre_start]);
int mid;
for(mid=in_start;inorder[mid] != preorder[pre_start];mid++);
int len1 = mid - in_start;
root->left = recur(preorder,pre_start+1,pre_start+len1+1,inorder,in_start,mid);
root->right = recur(preorder,pre_start+len1+1,pre_end,inorder,mid+1,in_end);
return root;
}
void inorderTraverse(TreeNode * root){
if(root == NULL)
cout<<"# ";
else{
inorderTraverse(root->left);
cout<<root->val<<" ";
inorderTraverse(root->right);
}
}
};
int main(){
Solution s;
vector<int> preorder,inorder;
preorder.push_back(4);
preorder.push_back(2);
preorder.push_back(1);
preorder.push_back(3);
preorder.push_back(6);
preorder.push_back(5);
preorder.push_back(7);
inorder.push_back(1);
inorder.push_back(2);
inorder.push_back(3);
inorder.push_back(4);
inorder.push_back(5);
inorder.push_back(6);
inorder.push_back(7);
TreeNode * root = s.buildTree(preorder,inorder);
s.inorderTraverse(root);
}
| true |
0db84225dfb164132f7e62ea0bfc8a0de192eb9f | C++ | LencoDigitexer/VSCode_borland_setup | /pr/pr28_EIN.cpp | IBM866 | 4,631 | 3.328125 | 3 | [
"MIT"
] | permissive | #include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#include <math.h>
#include"..\\h\\wind.h"
#include"..\\h\\page_1.h"
class conus{
private:
float h, R, r, V, S;
public:
// ࠬࠬ 㬮砭
// i -> 'i'nput
conus(float hi = 7, float Ri = 10, float ri = 4);
int get_R(void);
int get_r(void);
int get_h(void);
float v(void);
float obr(void);
float plo(void);
void print(char*);
void move(float, float, float);
~conus();
};
//
conus::conus(float hi, float Ri, float ri)
{
h = hi;
R = Ri;
r = ri;
}
// 祭 ࠬ h, R, r
void conus::move(float hi, float Ri, float ri)
{
h = hi;
R = Ri;
r = ri;
}
// R
int conus::get_R()
{
return R;
}
// r
int conus::get_r()
{
return r;
}
// h
int conus::get_h()
{
return h;
}
// ꥬ
float conus::v()
{
float V = (M_PI*get_h()*(get_R()*get_R()+get_R()*get_r()+get_r()*get_r()))/3;
return (V);
}
// ࠧ
float conus::obr()
{
float OBR = sqrt(get_h()*get_h()+(get_R()-get_r())*(get_R()-get_r()));
return (OBR);
}
// ࠧ
float conus::plo()
{
float S = M_PI*(get_r()+get_R())*obr();
return (S);
}
// 뢮 १⮢
void conus::print(char* str)
{
cout << "-----------------------------------------" << endl;
cout << "ꥪ " << str << " - 祭 " << endl;
cout << " ᭮ = " << get_R() << endl;
cout << " 孥 ᭮ = " << get_r() << endl;
cout << " = " << get_h() << endl;
cout << " = " << v() << endl;
cout << " ࠧ饩 = " << obr() << endl;
cout << "頤 孮 = " << plo() << endl;
cout << "-----------------------------------------" << endl << endl;
}
//
conus::~conus()
{
}
void main()
{
clrscr();
conus P; // ꥪ P ࠬࠬ 㬮砭
page_1();
clrscr();
window(1, 1, 80, 25); textbackground(0); clrscr();
P.print("P"); // 뢥 祭
// 祭 ⠬ ꥪ P
P.move(8, 30, 5);
// 뢥 祭 ꥪ P
P.print("P");
conus Z(4, 45, 9); // ꥪ Z
Z.print("Z"); // 뢥 祭 ꥪ Z
// 饭 㭪 ⥫ main() ꥪ P
cout << "-----------------------------------------" << endl;
cout << "ꥪ P - 祭 " << endl;
cout << " ᭮ = " << P.get_R() << endl;
cout << " 孥 ᭮ = " << P.get_r() << endl;
cout << " = " << P.get_h() << endl;
cout << " = " << P.v() << endl;
cout << " ࠧ饩 = " << P.obr() << endl;
cout << "頤 孮 = " << P.plo() << endl;
cout << "-----------------------------------------" << endl << endl;
// 饭 㭪 ⥫ main() ꥪ Z
cout << "-----------------------------------------" << endl;
cout << "ꥪ Z - 祭 " << endl;
cout << " ᭮ = " << Z.get_R() << endl;
cout << " 孥 ᭮ = " << Z.get_r() << endl;
cout << " = " << Z.get_h() << endl;
cout << " = " << Z.v() << endl;
cout << " ࠧ饩 = " << Z.obr() << endl;
cout << "頤 孮 = " << Z.plo() << endl;
cout << "-----------------------------------------" << endl << endl;
getch();
} | true |
1521858bdd991dead1315236001c1de4fcd6fc16 | C++ | Xenakios/XenakiosModules | /dep/rubberband/src/audiocurves/PercussiveAudioCurve.cpp | UTF-8 | 3,240 | 2.546875 | 3 | [] | no_license | /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Rubber Band Library
An audio time-stretching and pitch-shifting library.
Copyright 2007-2020 Particular Programs Ltd.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
Alternatively, if you have a valid commercial licence for the
Rubber Band Library obtained by agreement with the copyright
holders, you may redistribute and/or modify it under the terms
described in that licence.
If you wish to distribute code using the Rubber Band Library
under terms other than those of the GNU General Public License,
you must obtain a valid commercial licence before doing so.
*/
#include "PercussiveAudioCurve.h"
#include "src/system/Allocators.h"
#include "src/system/VectorOps.h"
#include <cmath>
#include <iostream>
namespace RubberBand
{
PercussiveAudioCurve::PercussiveAudioCurve(Parameters parameters) :
AudioCurveCalculator(parameters)
{
m_prevMag = allocate_and_zero<double>(m_fftSize/2 + 1);
}
PercussiveAudioCurve::~PercussiveAudioCurve()
{
deallocate(m_prevMag);
}
void
PercussiveAudioCurve::reset()
{
v_zero(m_prevMag, m_fftSize/2 + 1);
}
void
PercussiveAudioCurve::setFftSize(int newSize)
{
m_prevMag = reallocate(m_prevMag, m_fftSize/2 + 1, newSize/2 + 1);
AudioCurveCalculator::setFftSize(newSize);
reset();
}
float
PercussiveAudioCurve::processFloat(const float *R__ mag, int increment)
{
static float threshold = powf(10.f, 0.15f); // 3dB rise in square of magnitude
static float zeroThresh = powf(10.f, -8);
int count = 0;
int nonZeroCount = 0;
const int sz = m_lastPerceivedBin;
for (int n = 1; n <= sz; ++n) {
float v = 0.f;
if (m_prevMag[n] > zeroThresh) v = mag[n] / m_prevMag[n];
else if (mag[n] > zeroThresh) v = threshold;
bool above = (v >= threshold);
if (above) ++count;
if (mag[n] > zeroThresh) ++nonZeroCount;
}
v_convert(m_prevMag, mag, sz + 1);
if (nonZeroCount == 0) return 0;
else return float(count) / float(nonZeroCount);
}
double
PercussiveAudioCurve::processDouble(const double *R__ mag, int increment)
{
static double threshold = pow(10., 0.15); // 3dB rise in square of magnitude
static double zeroThresh = pow(10., -8);
int count = 0;
int nonZeroCount = 0;
const int sz = m_lastPerceivedBin;
for (int n = 1; n <= sz; ++n) {
double v = 0.0;
if (m_prevMag[n] > zeroThresh) v = mag[n] / m_prevMag[n];
else if (mag[n] > zeroThresh) v = threshold;
bool above = (v >= threshold);
if (above) ++count;
if (mag[n] > zeroThresh) ++nonZeroCount;
}
v_copy(m_prevMag, mag, sz + 1);
if (nonZeroCount == 0) return 0;
else return double(count) / double(nonZeroCount);
}
}
| true |
8cc73de5f5114f5bba980a4bf6b4206e727f702a | C++ | mpzadmin/yuc | /Afzalabadi/base.cpp | UTF-8 | 432 | 3 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
void delay(int delaynumber = 100000000);
int main()
{
string charector ;
cout << "Enter your charector :";
getline(cin, charector);
for( int index = 0; index < charector.length(); index++ )
{
cout << charector[index];
delay();
}
}
void delay(int delaynumber )
{
for( int counter=1; counter<= delaynumber; counter++ );
}
| true |
fc6eecf2b641ad4b15df5b07d1c6653e7d5fa92a | C++ | abozb01/ee205-final | /include/common.h | UTF-8 | 766 | 2.703125 | 3 | [] | no_license |
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#define WIDTH 1280
#define HEIGHT 720
#define PRINT(x) std::cout << x << std::endl
#define ROUND2(x) ((int)(x * 100)) / 100.f
#define STR(x) std::to_string(x)
using vec2i = sf::Vector2i;
using std::string;
class vec2;
float lerp(float, float, float);
vec2 lerp(vec2, vec2, float);
namespace game {
/**
* @brief Round a float to a specified amount of decimals.
*
* @param n
* @param decimals
* @return float
*/
float round(float n, int decimals = 2);
std::string round_str(float n, int decimals = 2);
}
/**
* @brief Cordial directions
*
*/
enum Direction { NONE, LEFT, RIGHT, UP, DOWN };
| true |
877530acf92835a743a9f8c8b9bac246fb6876f8 | C++ | xubury/FoggyEngine | /Engine/TileMap/Map.hpp | UTF-8 | 6,251 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef MAP_HPP
#define MAP_HPP
#include "TileMap/Layer.hpp"
#include "TileMap/Tile.hpp"
#include "TileMap/VMap.hpp"
#include "iostream"
namespace foggy {
template <typename GEOMETRY>
class Map : public VMap {
public:
Map(const Map&) = delete;
Map& operator=(const Map&) = delete;
Map(float size);
void loadFromJson(const Json::Value& root) override;
virtual sf::Vector2i mapCoordsToTile(float x, float y) const override;
virtual sf::Vector2f mapTileToCoords(int x, int y) const override;
virtual const sf::ConvexShape getShape() const override;
virtual std::list<sf::Vector2i> getPath(
const sf::Vector2i& origin, const sf::Vector2i& dest) const override;
virtual sf::Vector2i getPath1(const sf::Vector2i& origin,
const sf::Vector2i& dest) const override;
virtual int getDistance(const sf::Vector2i& origin,
const sf::Vector2i& dest) const override;
};
template <typename GEOMETRY>
Map<GEOMETRY>::Map(float size) : VMap(size) {}
template <typename GEOMETRY>
void Map<GEOMETRY>::loadFromJson(const Json::Value& root) {
auto iter = root["layers"].begin();
auto end = root["layers"].end();
for (; iter != end; ++iter) {
const Json::Value& layer = *iter;
std::string content = layer["content"].asString();
int z = 0;
try {
z = layer["z"].asInt();
} catch (...) {
}
bool isStatic = false;
try {
isStatic = layer["static"].asBool();
} catch (...) {
}
if (content == "tile") {
auto current_layer =
new Layer<Tile<GEOMETRY>>(content, z, isStatic);
auto data_iter = layer["datas"].begin();
auto data_end = layer["datas"].end();
for (; data_iter != data_end; ++data_iter) {
const Json::Value& texture = *data_iter;
int tex_x = texture["x"].asInt();
int tex_y = texture["y"].asInt();
int height = std::max<int>(0, texture["height"].asInt());
int width = std::max<int>(0, texture["width"].asInt());
std::string img = texture["img"].asString();
sf::Texture& tex = m_textures.getOrLoad(img, img);
tex.setRepeated(true);
for (int y = tex_y; y < tex_y + height; ++y) {
for (int x = tex_x; x < tex_x + width; ++x) {
Tile<GEOMETRY> tile(x, y, getTileSize());
tile.setTexture(&tex);
tile.setTextureRect(
GEOMETRY::getTextureRect(x, y, tex.getSize().x));
current_layer->add(std::move(tile), false);
}
}
add(current_layer, false);
}
} else if (content == "sprite") {
auto current_layer = new Layer<sf::Sprite>(content, z, isStatic);
auto data_iter = layer["datas"].begin();
auto data_end = layer["datas"].end();
for (; data_iter != data_end; ++data_iter) {
const Json::Value& data = *data_iter;
int x = data["x"].asInt();
int y = data["y"].asInt();
float ox = 0.5;
float oy = 1;
try {
ox = data["ox"].asFloat();
} catch (...) {
}
try {
oy = data["oy"].asFloat();
} catch (...) {
}
std::string img = data["img"].asString();
sf::Sprite spr(m_textures.getOrLoad(img, img));
spr.setPosition(GEOMETRY::mapTileToCoords(x, y, m_tile_size));
sf::FloatRect rec = spr.getLocalBounds();
spr.setOrigin(rec.width * ox, rec.height * oy);
current_layer->add(std::move(spr), false);
}
add(current_layer, false);
}
}
sortLayers();
}
template <typename GEOMETRY>
sf::Vector2i Map<GEOMETRY>::mapCoordsToTile(float x, float y) const {
return GEOMETRY::mapCoordsToTile(x, y, m_tile_size);
}
template <typename GEOMETRY>
sf::Vector2f Map<GEOMETRY>::mapTileToCoords(int x, int y) const {
return GEOMETRY::mapTileToCoords(x, y, m_tile_size);
}
template <typename GEOMETRY>
const sf::ConvexShape Map<GEOMETRY>::getShape() const {
sf::ConvexShape shape = GEOMETRY::getShape();
shape.setScale(m_tile_size, m_tile_size);
return shape;
}
template <typename GEOMETRY>
std::list<sf::Vector2i> Map<GEOMETRY>::getPath(const sf::Vector2i& origin,
const sf::Vector2i& dest) const {
int distance = GEOMETRY::distance(origin.x, origin.y, dest.x, dest.y);
std::list<sf::Vector2i> res;
sf::Vector2f p(dest.x - origin.x, dest.y - origin.y);
float delta = 1.0 / distance;
float cumul = 0;
res.emplace_back(origin);
for (int i = 0; i < distance; ++i) {
sf::Vector2i pos =
GEOMETRY::round(origin.x + p.x * cumul, origin.y + p.y * cumul);
if (res.back() != pos) res.emplace_back(pos);
cumul += delta;
}
if (res.back() != dest) res.emplace_back(dest);
return res;
}
template <typename GEOMETRY>
sf::Vector2i Map<GEOMETRY>::getPath1(const sf::Vector2i& origin,
const sf::Vector2i& dest) const {
int distance = GEOMETRY::distance(origin.x, origin.y, dest.x, dest.y);
sf::Vector2i res = origin;
sf::Vector2f p(dest.x - origin.x, dest.y - origin.y);
float delta = 1.0 / distance;
float cumul = 0;
for (int i = 0; i < distance; ++i) {
sf::Vector2i pos =
GEOMETRY::round(origin.x + p.x * cumul, origin.y + p.y * cumul);
if (pos != res) {
res = pos;
break;
}
cumul += delta;
}
return res;
}
template <typename GEOMETRY>
int Map<GEOMETRY>::getDistance(const sf::Vector2i& origin,
const sf::Vector2i& dest) const {
return GEOMETRY::distance(origin.x, origin.y, dest.x, dest.y);
}
} // namespace foggy
#endif /* MAP_HPP */
| true |
b6308c455f9b18c4eb614b377f61e186ffb4f652 | C++ | lululombard/SenseoOnlineArduino | /Boiler.cpp | UTF-8 | 708 | 3 | 3 | [] | no_license | #include "Boiler.h"
int max_temp = 410;
Boiler::Boiler(int pin_boiler, int pin_sensor) {
this->pin_boiler = pin_boiler;
this->pin_sensor = pin_sensor;
pinMode(pin_boiler, OUTPUT);
}
void Boiler::off() {
digitalWrite(pin_boiler, LOW);
}
void Boiler::on() {
digitalWrite(pin_boiler, HIGH);
}
boolean Boiler::state() {
return digitalRead(pin_boiler);
}
boolean Boiler::is_max_temp() {
return (get_temp_raw()>=max_temp);
}
int Boiler::get_temp() {
int temp_about = (get_temp_raw()/7);
if (temp_about < 20) return 20;
if (temp_about > 99) return 99;
return (temp_about);
}
int Boiler::get_temp_raw() {
return analogRead(pin_sensor);
}
int Boiler::get_temp_max() {
return max_temp;
}
| true |
4c8149c6ca99600118de1c2272b0b12e553a80df | C++ | yhzhm/Practice | /Course/ProgrammingContestChallengeSE/PCC 2.2.1 贪心 硬币问题.cpp | UTF-8 | 734 | 3.0625 | 3 | [] | no_license | /*
* 有1元、5元、10元、50元、100元的硬币各C1,C5,C10,C50,C100,C500枚。
* 现在要用这些硬币来支付A元,最少需要多少枚硬币?假定本题至少存在一种支付方案。
* 样例输入:c1=3 c5=2 c10=1 c50=3 c100=0 c500=2,a=620;
* 样例输出:6 (500 1枚 50 2枚 10 1枚 5 2枚 合计6枚)
*/
//
// Created by Hz Yang on 2017/5/9.
//硬币问题
#include <iostream>
using namespace std;
int main() {
const int v[6]={1,5,10,50,100,500};
int c[6],A,ans=0;
for (int i = 0; i < 6 ; ++i) {
cin >> c[i];
}
cin >> A;
for (int i = 5; i >=0 ; --i) {
int t=min(A/v[i],c[i]);
A-=t*v[i];
ans+=t;
}
cout << ans <<endl;
return 0;
}
| true |
3b008e694e8a197fc0c5351c399309afa0064518 | C++ | drken1215/algorithm | /DataStructure/union_find_size.cpp | UTF-8 | 2,602 | 3.09375 | 3 | [
"CC0-1.0"
] | permissive | //
// Union-Find (union by size)
//
// verified:
// Yosupo Library Checker - Unionfind
// https://judge.yosupo.jp/problem/unionfind
//
// AOJ Course DSL_1_A Set - Disjoint Set: Union Find Tree
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_1_A&lang=jp
//
/*
併合時の工夫: union by rank
same(x, y): x と y が同じグループにいるか, 計算量はならし O(α(n))
merge(x, y): x と y を同じグループにする, 計算量はならし O(α(n))
size(x): x を含むグループの所属メンバー数
*/
#include <bits/stdc++.h>
using namespace std;
// Union-Find
struct UnionFind {
// core member
vector<int> par;
// constructor
UnionFind() { }
UnionFind(int n) : par(n, -1) { }
void init(int n) { par.assign(n, -1); }
// core methods
int root(int x) {
if (par[x] < 0) return x;
else return par[x] = root(par[x]);
}
bool same(int x, int y) {
return root(x) == root(y);
}
bool merge(int x, int y) {
x = root(x), y = root(y);
if (x == y) return false;
if (par[x] > par[y]) swap(x, y); // merge technique
par[x] += par[y];
par[y] = x;
return true;
}
int size(int x) {
return -par[root(x)];
}
// debug
friend ostream& operator << (ostream &s, UnionFind uf) {
map<int, vector<int>> groups;
for (int i = 0; i < uf.par.size(); ++i) {
int r = uf.root(i);
groups[r].push_back(i);
}
for (const auto &it : groups) {
s << "group: ";
for (auto v : it.second) s << v << " ";
s << endl;
}
return s;
}
};
/*/////////////////////////////*/
// Examples
/*/////////////////////////////*/
void YosupoUnionFind() {
int N, Q;
cin >> N >> Q;
UnionFind uf(N);
for (int q = 0; q < Q; ++q) {
int type, x, y;
cin >> type >> x >> y;
if (type == 0) uf.merge(x, y);
else {
if (uf.same(x, y)) cout << 1 << endl;
else cout << 0 << endl;
}
//cout << uf << endl;
}
}
void AOJ_DSL_1_A() {
int N, Q;
cin >> N >> Q;
UnionFind uf(N);
for (int q = 0; q < Q; ++q) {
int com, x, y;
cin >> com >> x >> y;
if (com == 0) uf.merge(x, y);
else {
if (uf.same(x, y)) cout << 1 << endl;
else cout << 0 << endl;
}
//cout << uf << endl;
}
}
int main() {
YosupoUnionFind();
//AOJ_DSL_1_A();
}
| true |
0975172de5fb6e441d3698e61690bd9f1e36db7d | C++ | JoeDunnStable/how_much_data | /include/gauss_kronrod_impl.h | UTF-8 | 7,412 | 2.84375 | 3 | [
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | /// \file gauss_kronrod_impl.h
/// Implementation of routines to calculate nodes and weights
/// Included in file gauss_kronrod.h when LIBRARY is defined
/// \author Joseph Dunn
/// \copyright 2016, 2017, 2018 Joseph Dunn
/// \copyright Distributed under the terms of the GNU General Public License version 3
#include <Eigen/Eigenvalues>
#include <iomanip>
#include <vector>
#include <algorithm>
namespace gauss_kronrod {
using Eigen::SelfAdjointEigenSolver;
using std::endl;
using std::setw;
using std::setprecision;
using std::right;
using std::vector;
template<typename T>
class sort_data {
public:
T a;
int index;
sort_data() : a(0), index(0){}
sort_data(T a, int index) : a(a), index(index){}
};
template<typename T>
bool sd_lt(const sort_data<T> &lhs,const sort_data<T>& rhs) {
return lhs.a < rhs.a;
}
// toms726 generates the nodes x and weights w for a quadrature rule
// given the recurrence factors a and b for the orthogonal polynomials
//
template<typename myFloat>
void toms726(const int n_gauss, const vector<myFloat>& a, const vector<myFloat>& b,
vector<myFloat>& x, vector<myFloat>& w, const int verbose){
Fmt<myFloat> fmt;
using MatrixXF = Eigen::Matrix<myFloat,Eigen::Dynamic,Eigen::Dynamic>;
using VectorXF = Eigen::Matrix<myFloat,Eigen::Dynamic,1>;
int sumbgt0=0;
for (int j=0; j<n_gauss; j++) sumbgt0+=(b.at(j)>0);
if(sumbgt0!=n_gauss) {
throw std::range_error("toms726: b is not all >0");
}
if (n_gauss == 1) {
x.at(0)=a.at(0);
w.at(0)=b.at(0);
return;
}
MatrixXF J = MatrixXF::Zero(n_gauss,n_gauss);
for (int k=0; k<n_gauss-1; k++){
J(k,k)=a.at(k);
J(k,k+1)=sqrt(b.at(k+1));
J(k+1,k)=J(k,(k+1));
}
J(n_gauss-1,n_gauss-1)=a.at(n_gauss-1);
SelfAdjointEigenSolver<MatrixXF> es;
es.compute(J);
VectorXF e_values = es.eigenvalues(); // These are as yet unsorted
MatrixXF e_vectors = es.eigenvectors();
vector<myFloat> e(n_gauss);
for (int k=0; k<n_gauss; k++) {
e.at(k) = b.at(0) * pow(e_vectors(0,k), 2);
}
vector<sort_data<myFloat> > srt_d(n_gauss);
for (int i=0; i<n_gauss; i++) {
sort_data<myFloat> elem(e_values(i),i);
srt_d.at(i) = elem;
}
std::sort(srt_d.begin(), srt_d.end(),sd_lt<myFloat>);
for (int i=0; i<n_gauss; i++){
if (verbose)
cout<< fmt << srt_d.at(i).a
<< fmt << srt_d.at(i).index << endl;
x.at(i)=srt_d.at(i).a;
w.at(i)=e.at(srt_d.at(i).index);
}
}
template<typename myFloat>
void r_jacobi01(const int n_gauss, const myFloat a, const myFloat b, vector<myFloat>& c,
vector<myFloat>& d){
if((n_gauss<=0)||(a<=-1)||(b<=-1)){
throw std::range_error("r_jacobi01: parameter(s) out of range");
}
r_jacobi(n_gauss, a, b, c, d);
for (int i=0; i<n_gauss; i++) {
c.at(i)=(1+c.at(i))/2;
if (i==0)
d.at(i)=d.at(0)/pow(2,a+b+1);
else
d.at(i)=d.at(i)/4;
}
}
template<typename myFloat>
void r_jacobi(const int n_gauss, const myFloat a, const myFloat b, vector<myFloat>& c,
vector<myFloat>& d){
if((n_gauss<=0)||(a<=-1)||(b<=-1)) {
throw std::range_error("r_jacobi: parameter(s) out of range");
}
myFloat nu = (b-a)/(a+b+2);
myFloat mu = pow(2,a+b+1)*tgamma(a+1)*tgamma(b+1)/tgamma(a+b+2);
if (n_gauss==1) {
c.at(0)=nu;
d.at(0)=mu;
return;
}
c.at(0)=nu;
for (int n=1; n<n_gauss; n++){
myFloat nab=2*n+a+b;
c.at(n) = (pow(b,2)-pow(a,2))*1/(nab*(nab+2));
}
d.at(0) = mu;
d.at(1) = 4*(a+1)*(b+1)/(pow(a+b+2,2)*(a+b+3));
for (int n=2; n<n_gauss; n++) {
myFloat nab=2*n+a+b;
d.at(n)=4*(n+a)*(n+b)*n*(n+a+b)/(pow(nab,2)*(nab+1)*(nab-1));
}
}
template<typename myFloat>
void r_kronrod(const int n_gauss, const vector<myFloat>& a0, const vector<myFloat>& b0,
vector<myFloat>& a, vector<myFloat>& b) {
if (a0.size()<ceil(3.*n_gauss/2.)+1) {
throw std::range_error("r_kronrod: a0 is too short.");
}
for (int k=0; k<=ceil(3.*n_gauss/2.); k++) {
a.at(k) = a0.at(k);
b.at(k) = b0.at(k);
}
vector<myFloat> s((n_gauss/2)+2);
vector<myFloat> t((n_gauss/2)+2);
for (int k=0; k<(n_gauss/2)+2; k++)
t.at(k)=s.at(k)=myFloat(0);
t.at(1)=b[n_gauss+1]; // P.H.
for (int m=0; m<=(n_gauss-2); m++) {
myFloat cumsum = 0;
vector<myFloat> tmp((n_gauss/2)+2);
tmp.at(0)=s.at(0);
for (int k=((m+1)/2); k>=0; k--){
int l = m-k;
cumsum=cumsum + (a.at(k+n_gauss+1) - a.at(l))*t.at(k+1) + b.at(k+n_gauss+1)*s.at(k)
- b.at(l)*s.at(k+1);
tmp.at(k+1)=cumsum;
}
for (int k=((m+1)/2)+2; k<((n_gauss/2)+2); k++)
tmp.at(k)=s.at(k);
for (int k=0; k<((n_gauss/2)+2); k++){
s.at(k)=t.at(k);
t.at(k)=tmp.at(k);
}
}
for (int j=(n_gauss/2); j>=0; j--)
s.at(j+1)=s.at(j);
for (int m=n_gauss-1; m<=(2*n_gauss-3); m++){
myFloat cumsum = 0;
vector<myFloat> tmp((n_gauss/2)+2);
for (int k=m+1-n_gauss; k<=((m-1)/2); k++){
int l=m-k;
int j=n_gauss-1-l;
cumsum=cumsum+-(a.at(k+n_gauss+1)-a.at(l))*t.at(j+1)-b.at(k+n_gauss+1)*s.at(j+1)+b.at(l)*s.at(j+2);
tmp.at(j+1)=cumsum;
}
int j{0};
for (int k=m+1-n_gauss; k<=((m-1)/2); k++){
j=n_gauss-1-m+k;
s.at(j+1)=tmp.at(j+1);
}
int k=((m+1)/2);
if ((m % 2)==0) {
a.at(k+n_gauss+1)=a.at(k)+(s.at(j+1)-b.at(k+n_gauss+1)*s.at(j+2))/t.at(j+2);
}
else {
b.at(k+n_gauss+1)=s.at(j+1)/s.at(j+2);
}
for (int j=0; j<((n_gauss/2)+2); j++) {
myFloat swap = s.at(j);
s.at(j)=t.at(j);
t.at(j)=swap;
}
}
a.at(2*n_gauss)=a.at(n_gauss-1)-b.at(2*n_gauss)*s.at(1)/t.at(1);
return;
}
template<typename myFloat>
Kronrod<myFloat>::Kronrod(const int n_gauss, const int verbose)
: n_gauss(n_gauss), verbose(verbose) {
x_gauss.resize(n_gauss);
w_gauss.resize(n_gauss);
x_kronrod.resize(2*n_gauss+1);
w_kronrod.resize(2*n_gauss+1);
int M = std::max(2*n_gauss,int(ceil(3.*n_gauss/2.)+1));
vector<myFloat> a0(M);
vector<myFloat> b0(M);
r_jacobi01(M,myFloat(0),myFloat(0), a0, b0);
toms726(n_gauss, a0, b0, x_gauss, w_gauss, verbose>4);
vector<myFloat> a(2*n_gauss+1);
vector<myFloat> b(2*n_gauss+1);
r_kronrod(n_gauss, a0, b0, a, b);
toms726(2*n_gauss+1, a, b, x_kronrod, w_kronrod, verbose > 4);
for (int i = 0; i<n_gauss; i++) {
x_gauss.at(i)=2*x_gauss.at(i)-1;
w_gauss.at(i)=2*w_gauss.at(i);
}
for (int i = 0; i<2*n_gauss+1; i++) {
x_kronrod.at(i) = 2*x_kronrod.at(i)-1;
w_kronrod.at(i) = 2*w_kronrod.at(i);
}
} // Kronrod constructor
/// Operator to print the kronrod nodes and wieghts
template<typename myFloat>
ostream& operator<< (ostream& os, const Kronrod<myFloat>& k) {
int d = std::numeric_limits<myFloat>::digits10;
os << "Gauss nodes and weights" << endl << endl;
os << setw(d+10) << right << "Node" << setw(d+10) << right << "Weight" << endl;
for (int i=0; i<k.n_gauss; ++i) {
os << setw(d+10) << setprecision(d) << k.x_gauss.at(i)
<< setw(d+10) << setprecision(d) << k.w_gauss.at(i) << endl;
}
os << endl << "Kronrod nodes and weights" << endl << endl;
os << setw(d+10) << right << "Node" << setw(d+10) << right << "Weight" << endl;
for (int i=0; i<2*k.n_gauss+1; ++i) {
os << setw(d+10) << setprecision(d) << k.x_kronrod.at(i)
<< setw(d+10) << setprecision(d) << k.w_kronrod.at(i) << endl;
}
return os;
}
} // namespace gauss_kronrod
| true |
d7a72a16ca9db267de52ccd1f915b371892c23ac | C++ | newpolaris/tiny_imageformat | /tests/test_formatcracker.cpp | UTF-8 | 8,201 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "al2o3_platform/platform.h"
#include "al2o3_catch2/catch2.hpp"
#include "tiny_imageformat/tinyimageformat_base.h"
#include "tiny_imageformat/tinyimageformat_query.h"
#include <float.h>
TEST_CASE("Format Cracker IsDepthOnly (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = strstr(name, "D16") != nullptr;
shouldBe |= strstr(name, "D24") != nullptr;
shouldBe |= strstr(name, "D32") != nullptr;
shouldBe &= (strstr(name, "S8") == nullptr);
if (TinyImageFormat_IsDepthOnly(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsDepthOnly failed %s", name);
}
CHECK(TinyImageFormat_IsDepthOnly(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker IsStencilOnly (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = (strstr(name, "S8") != nullptr) &&
(strstr(name, "D") == nullptr);
if (TinyImageFormat_IsStencilOnly(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsStencilOnly failed %s", name);
}
CHECK(TinyImageFormat_IsStencilOnly(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker IsDepthAndStencil (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = strstr(name, "D16") != nullptr;
shouldBe |= strstr(name, "D24") != nullptr;
shouldBe |= strstr(name, "D32") != nullptr;
shouldBe &= strstr(name, "S8") != nullptr;
if (TinyImageFormat_IsDepthAndStencil(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsDepthAndStencil failed %s", name);
}
CHECK(TinyImageFormat_IsDepthAndStencil(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker IsFloat (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = strstr(name, "SFLOAT") != nullptr;
shouldBe |= strstr(name, "UFLOAT") != nullptr;
shouldBe |= strstr(name, "SBFLOAT") != nullptr;
if (TinyImageFormat_IsFloat(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsFloat failed %s", name);
}
CHECK(TinyImageFormat_IsFloat(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker IsNormalised (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBeNormalised = strstr(name, "UNORM") != nullptr;
shouldBeNormalised |= strstr(name, "SNORM") != nullptr;
shouldBeNormalised |= strstr(name, "SRGB") != nullptr;
if (TinyImageFormat_IsNormalised(fmt) != shouldBeNormalised) {
LOGINFO("TinyImageFormat_IsNormalised failed %s", name);
}
CHECK(TinyImageFormat_IsNormalised(fmt) == shouldBeNormalised);
}
}
TEST_CASE("Format Cracker IsSigned (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = strstr(name, "SNORM") != nullptr;
shouldBe |= strstr(name, "SSCALED") != nullptr;
shouldBe |= strstr(name, "SINT") != nullptr;
shouldBe |= strstr(name, "SFLOAT") != nullptr;
shouldBe |= strstr(name, "SBFLOAT") != nullptr;
if (TinyImageFormat_IsSigned(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsSigned failed %s", name);
}
CHECK(TinyImageFormat_IsSigned(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker IsSRGB (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = strstr(name, "SRGB") != nullptr;
if (TinyImageFormat_IsSRGB(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsSRGB failed %s", name);
}
CHECK(TinyImageFormat_IsSRGB(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker IsCompressed (C)", "[Image]") {
for (uint32_t i = 0; i < TinyImageFormat_Count; ++i) {
TinyImageFormat fmt = (TinyImageFormat) i;
char const *name = TinyImageFormat_Name(fmt);
bool shouldBe = false;
shouldBe |= (strstr(name, "DXBC") != nullptr);
shouldBe |= (strstr(name, "ETC") != nullptr);
shouldBe |= (strstr(name, "PVRTC") != nullptr);
shouldBe |= (strstr(name, "ASTC") != nullptr);
if (TinyImageFormat_IsCompressed(fmt) != shouldBe) {
LOGINFO("TinyImageFormat_IsCompressed failed %s", name);
}
CHECK(TinyImageFormat_IsCompressed(fmt) == shouldBe);
}
}
TEST_CASE("Format Cracker Min (C)", "[Image]") {
// random sample a few to check
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Red) == Approx(0));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Green) == Approx(0));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Blue) == Approx(0));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Alpha) == Approx(0));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Red) == Approx(-128));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Green) == Approx(-128));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Blue) == Approx(-128));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Alpha) == Approx(-128));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Red) == Approx(-FLT_MAX));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Green) == Approx(-FLT_MAX));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Blue) == Approx(-FLT_MAX));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Alpha) == Approx(-FLT_MAX));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8X8_UNORM, TinyImageFormat_LC_Red) == Approx(0.0));
REQUIRE(TinyImageFormat_Min(TinyImageFormat_R8G8B8A8_SNORM, TinyImageFormat_LC_Red) == Approx(-1.0));
}
TEST_CASE("Format Cracker Max (C)", "[Image]") {
// random sample a few to check
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Red) == Approx(255));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Green) == Approx(255));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Blue) == Approx(255));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_UINT, TinyImageFormat_LC_Alpha) == Approx(255));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Red) == Approx(127));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Green) == Approx(127));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Blue) == Approx(127));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R8G8B8A8_SINT, TinyImageFormat_LC_Alpha) == Approx(127));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Red) == Approx(FLT_MAX));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Green) == Approx(FLT_MAX));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Blue) == Approx(FLT_MAX));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_R32G32B32A32_SFLOAT, TinyImageFormat_LC_Alpha) == Approx(FLT_MAX));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_D32_SFLOAT_S8_UINT, TinyImageFormat_LC_Depth) == Approx(FLT_MAX));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_D32_SFLOAT_S8_UINT, TinyImageFormat_LC_Stencil) == Approx(255));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_D32_SFLOAT, TinyImageFormat_LC_Depth) == Approx(FLT_MAX));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_S8_UINT, TinyImageFormat_LC_Stencil) == Approx(255));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_B8G8R8X8_UNORM, TinyImageFormat_LC_Red) == Approx(1.0));
REQUIRE(TinyImageFormat_Max(TinyImageFormat_B8G8R8A8_SNORM, TinyImageFormat_LC_Red) == Approx(1.0));
} | true |
eca92cd7787ffc1f1e9f3d74bc98574cb4fc1b1b | C++ | AndreasFMueller/AstroPhotography | /control/ice/server/StatisticsI.h | UTF-8 | 2,722 | 2.515625 | 3 | [] | no_license | /*
* StatisticsI.h
*
* (c) 2020 Prof Dr Andreas Müller, Hochschule Rapperswil
*/
#ifndef _StatisticsI_h
#define _StatisticsI_h
#include <types.h>
#include <map>
#include <string>
#include <list>
#include <memory>
namespace snowstar {
class CallStatistics;
typedef std::shared_ptr<CallStatistics> CallStatisticsPtr;
/**
* \brief A container class for call statistics information
*/
class CallStatistics : public std::map<std::string, unsigned long> {
static std::map<Ice::Identity, CallStatisticsPtr> call_statistics;
Ice::Identity _objectidentity;
public:
CallStatistics(const Ice::Identity& objectidentity)
: _objectidentity(objectidentity) {
}
// return information on object ids
static std::list<Ice::Identity> objectidentities();
static unsigned long objectidentityCount();
// return information on objects
static std::list<std::string> operations(
const Ice::Identity& objectidentity);
static unsigned long operationCount(
const Ice::Identity& objectidentity);
// return various counters
static unsigned long calls(const Ice::Identity& objectidentity);
static unsigned long calls(const Ice::Identity& objectidentity,
const std::string& operation);
// count a call to an operation
static void count(const Ice::Identity& objectidentity,
const std::string& operation);
static void count(const Ice::Current& current);
// return number of calls
unsigned long calls(const std::string& operation) const;
unsigned long calls() const;
void count(const std::string& operation);
// access to the call statistics objects
static CallStatisticsPtr recall(
const Ice::Identity& objectidentity);
};
/*
* Implementation of the statistics interface inherited by many
*/
class StatisticsI : virtual public Statistics {
public:
StatisticsI();
~StatisticsI();
// object identities
ObjectIdentitySequence objectidentities(const Ice::Current& current);
Ice::Long objectidentityCount(const Ice::Current& current);
// operations
OperationSequence operations(const Ice::Identity& objectidentity,
const Ice::Current& current);
Ice::Long operationCount(const Ice::Identity& objectidentity,
const Ice::Current& current);
// global statistics
Ice::Long callsPerObject(const Ice::Identity& objectidentity,
const Ice::Current& current);
Ice::Long callsPerObjectAndOperation(const Ice::Identity& objectidentity,
const std::string& operation,
const Ice::Current& current);
// operations for this instance only, uses the object identity in
// the current argument
Ice::Long calls(const Ice::Current& current);
Ice::Long operationCalls(const std::string& operation,
const Ice::Current& current);
};
} // namespace snowstar
#endif /* _StatisticsI_h */
| true |
de9a314b070488ae3109475c91d6a088f9735d27 | C++ | Han-nahh/Kattis-Solutions | /gearchanging.cpp | UTF-8 | 977 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int N, M;
double P;
int main() {
ios_base::sync_with_stdio(0);
cin >> N >> M >> P;
P /= 100;
vector<double> cranks, backs;
for (int i = 0; i < N; ++i) {
double x; cin >> x;
cranks.push_back(x);
}
for (int i = 0; i < M; ++i) {
double x; cin >> x;
backs.push_back(x);
}
sort(cranks.begin(), cranks.end());
sort(backs.begin(), backs.end());
bool can = true;
vector<double> cadence;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
cadence.push_back(cranks[i] / backs[j]);
}
}
sort(cadence.begin(), cadence.end());
for (int i = 0; i + 1 < cadence.size(); ++i) {
if (cadence[i+1] / cadence[i] > (1+P)) {
can = false;
break;
}
}
if (can) {
cout << "Ride on!" << endl;
} else {
cout << "Time to change gears!" << endl;
}
}
| true |
29d1c012ab01292ad21ba2d9cefae836831c8e6a | C++ | kanusahai/EPI | /practice/Enclosed.cpp | UTF-8 | 2,783 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<stack>
#include<cstring>
#include<cstdlib>
using namespace std;
struct Coordinates {
int x;
int y;
};
void DFS(char **matrix, Coordinates cn) {
stack<Coordinates> dfsStack;
int numCols = strlen(matrix[0]);
int numRows = numCols;
matrix[cn.x][cn.y]='G';
dfsStack.push(cn);
while(!dfsStack.empty()) {
Coordinates coord = dfsStack.top();
dfsStack.pop();
if((coord.x)-1>=0 && matrix[coord.x-1][coord.y]=='W') {
Coordinates newCn;
newCn.x=coord.x-1;
newCn.y=coord.y;
matrix[newCn.x][newCn.y]='G';
dfsStack.push(newCn);
}
if((coord.x)+1<numRows && matrix[coord.x+1][coord.y]=='W') {
Coordinates newCn;
newCn.x=coord.x+1;
newCn.y=coord.y;
matrix[newCn.x][newCn.y]='G';
dfsStack.push(newCn);
}
if((coord.y)-1>=0 && matrix[coord.x][coord.y-1]=='W') {
Coordinates newCn;
newCn.x=coord.x;
newCn.y=coord.y-1;
matrix[newCn.x][newCn.y]='G';
dfsStack.push(newCn);
}
if((coord.y)+1<numCols && matrix[coord.x][coord.y+1]=='W') {
Coordinates newCn;
newCn.x=coord.x;
newCn.y=coord.y+1;
matrix[newCn.x][newCn.y]='G';
dfsStack.push(newCn);
}
}
}
void paintEnclosed(char **matrix) {
int numCols = strlen(matrix[0]);
int numRows = numCols;
for(int j=0;j<numCols;j++) {
if(matrix[0][j] == 'W') {
Coordinates cn;
cn.x=0;
cn.y=j;
DFS(matrix, cn);
}
}
for(int j=0;j<numCols;j++) {
if(matrix[numRows-1][j] == 'W') {
Coordinates cn;
cn.x=numRows-1;
cn.y=j;
DFS(matrix, cn);
}
}
for(int i=0;i<numRows;i++) {
if(matrix[i][0] == 'W') {
Coordinates cn;
cn.x=i;
cn.y=0;
DFS(matrix, cn);
}
}
for(int i=0;i<numRows;i++) {
if(matrix[i][numCols-1] == 'W') {
Coordinates cn;
cn.x=i;
cn.y=numCols-1;
DFS(matrix, cn);
}
}
for(int i=0;i<numRows;i++) {
for(int j=0;j<numCols;j++) {
if(matrix[i][j]=='W') {
matrix[i][j]='B';
}
}
}
for(int i=0;i<numRows;i++) {
for(int j=0;j<numCols;j++) {
if(matrix[i][j]=='G') {
matrix[i][j]='W';
}
}
}
}
void printMatrix(char **matrix) {
int numCols = strlen(matrix[0]);
int numRows = numCols;
for(int i=0;i<numRows;i++) {
for(int j=0;j<numCols;j++) {
cout<<matrix[i][j]<<" ";
}
cout<<"\n";
}
}
int main() {
char **matrix=new char*[4];
for(int i=0;i<4;i++) {
matrix[i]=new char[4];
}
for(int i=0;i<4;i++)
for(int j=0;j<4;j++) {
int random = rand();
matrix[i][j]=(random%4==0)?'W':'B';
}
printMatrix(matrix);
paintEnclosed(matrix);
cout<<"\n\n";
printMatrix(matrix);
return 0;
}
| true |
d3cf08a13c443ec43e9f8c9fae60f8fa786ff9af | C++ | PHATHUY88/zendoo-mc-cryptolib | /mc_test/mcTestCall.cpp | UTF-8 | 3,818 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "zendoo_mc.h"
#include "hex_utils.h"
#include <iostream>
#include <cassert>
#include <string>
/*
* Usage:
* 1) ./mcTest "generate" "params_dir"
* 2) ./mcTest "create" <"-v"> "proof_path" "params_dir" "end_epoch_mc_b_hash" "prev_end_epoch_mc_b_hash" "quality"
* "constant" "pk_dest_0" "amount_0" "pk_dest_1" "amount_1" ... "pk_dest_n" "amount_n"
*/
void create_verify(int argc, char** argv)
{
int arg = 2;
bool verify = false;
if (std::string(argv[2]) == "-v"){
arg++;
verify = true;
}
// Parse inputs
auto proof_path = std::string(argv[arg++]);
size_t proof_path_len = proof_path.size();
auto pk_path = std::string(argv[arg]) + std::string("test_mc_pk");
auto vk_path = std::string(argv[arg++]) + std::string("test_mc_vk");
size_t pk_path_len = vk_path.size();
size_t vk_path_len = pk_path_len;
assert(IsHex(argv[arg]));
auto end_epoch_mc_b_hash = SetHex(argv[arg++], 32);
assert(IsHex(argv[arg]));
auto prev_end_epoch_mc_b_hash = SetHex(argv[arg++], 32);
uint64_t quality = strtoull(argv[arg++], NULL, 0);
assert(quality >= 0);
assert(IsHex(argv[arg]));
auto constant = ParseHex(argv[arg++]);
assert(constant.size() == 96);
field_t* constant_f = zendoo_deserialize_field(constant.data());
assert(constant_f != NULL);
// Create bt_list
// Inputs must be (pk_dest, amount) pairs from which construct backward_transfer objects
assert((argc - arg) % 2 == 0);
int bt_list_length = (argc - arg)/2;
assert(bt_list_length >= 0);
// Parse backward transfer list
std::vector<backward_transfer_t> bt_list;
bt_list.reserve(bt_list_length);
for(int i = 0; i < bt_list_length; i ++){
backward_transfer_t bt;
assert(IsHex(argv[arg]));
auto pk_dest = SetHex(argv[arg++], 20);
std::copy(pk_dest.begin(), pk_dest.end(), std::begin(bt.pk_dest));
uint64_t amount = strtoull(argv[arg++], NULL, 0);
assert(amount >= 0);
bt.amount = amount;
bt_list.push_back(bt);
}
// Generate proof and vk
assert(zendoo_create_mc_test_proof(
end_epoch_mc_b_hash.data(),
prev_end_epoch_mc_b_hash.data(),
bt_list.data(),
bt_list_length,
quality,
constant_f,
(path_char_t*)pk_path.c_str(),
pk_path_len,
(path_char_t*)proof_path.c_str(),
proof_path_len
));
// If -v was specified we verify the proof just created
if(verify) {
// Deserialize proof
sc_proof_t* proof = zendoo_deserialize_sc_proof_from_file(
(path_char_t*)proof_path.c_str(),
proof_path_len
);
assert(proof != NULL);
// Deserialize vk
sc_vk_t* vk = zendoo_deserialize_sc_vk_from_file(
(path_char_t*)vk_path.c_str(),
vk_path_len
);
assert(vk != NULL);
// Verify proof
assert(zendoo_verify_sc_proof(
end_epoch_mc_b_hash.data(),
prev_end_epoch_mc_b_hash.data(),
bt_list.data(),
bt_list_length,
quality,
constant_f,
NULL,
proof,
vk
));
zendoo_sc_proof_free(proof);
zendoo_sc_vk_free(vk);
}
zendoo_field_free(constant_f);
}
void generate(char** argv)
{
std::string path = std::string(argv[2]);
assert(zendoo_generate_mc_test_params((path_char_t*)path.c_str(), path.size()));
}
int main(int argc, char** argv)
{
if(std::string(argv[1]) == "generate") {
assert(argc == 3);
generate(argv);
} else if (std::string(argv[1]) == "create"){
assert(argc > 7);
create_verify(argc, argv);
} else {
abort();
}
} | true |
4074ba55c7b3bfffc5ae614b2a403fae349690b4 | C++ | ZephyrZhng/code_win | /data structure/题/2.12 字典序比较.cpp | UTF-8 | 608 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdio>
#include <vector>
#include <string>
#include <numeric>
#include <iterator>
#include <algorithm>
using namespace std;
int lexicographical_compare(const string& a, const string& b)
{
int SHORT = a.size() <= b.size()? a.size(): b.size();
for(int i = 0; i < SHORT; ++i)
{
if(a[i] > b[i]) return 1;
if(a[i] < b[i]) return -1;
}
if(a.size() > b.size()) return 1;
if(a.size() < b.size()) return -1;
return 0;
}
int main()
{
string a, b;
cin >> a >> b;
cout << lexicographical_compare(a, b) << endl;
return 0;
} | true |
f69fb17b27747d160b58b3bd0ace8d820df48644 | C++ | yacubovvs/CubOS_01b | /SDK/build/arduino/nano_SSD1206_128x64/cubos/app_settings.ino | UTF-8 | 13,732 | 2.578125 | 3 | [] | no_license | unsigned char delay_before_turnoff = 6;
/*
case 0: return "5 sec";
case 1: return "10 sec";
case 2: return "30 sec";
case 3: return "1 min";
case 4: return "2 min";
case 5: return "5 min";
case 6: return "10 min";
case 7: return "30 min";
case 8: return "45 min";
case 9: return "1 hour";
*/
#define appNameClass SettingApp // App name without spaces
#define appName "Settings" // App name with spaces (max 16)
class appNameClass: public Application{
public:
byte current_menu_position = 0;
byte current_menu = 0;
virtual void loop() override{
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* >>> MAIN APP LOOP <<< *
* *
*/
//EVERY FRAME CODE
switch(current_menu){
case 0: drawSettingsMenu(); break;
case 1: drawingSelectDeleayTurnOff(); break;
case 2: drawSetTime(); break;
}
/* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
};
#define drawSettingsElement_height 29
#define drawSettingsElement_margin 2
#define drawSettingsElement_margin_left 10
#define drawSettingsElement_padding 3
#define drawSettingsElement_padding_label_value 3
char activeElement = 0;
bool isActivated = false;
void drawSetTime(){
drawString_centered("Setting time", 0);
char v1[3];
char v2[3];
char v3[3];
int_to_char(v1, os_clock_currentTime_hour(), true);
int_to_char(v2, os_clock_currentTime_minutes(), true);
int_to_char(v3, os_clock_currentTime_seconds(), true);
char* val1 = v1;
char* val2 = v2;
char* val3 = v3;
//showFreeMemory();
const int val_y = SCREEN_HEIGHT/2 - FONT_CHAR_HEIGHT/2;
const int val_y_strike = SCREEN_HEIGHT/2 + FONT_CHAR_HEIGHT/2 + 3;
const int val1_x = SCREEN_WIDTH * 1 / 5 - 1;
const int val1_5_x = SCREEN_WIDTH * 7 / 20 - 1;
const int val2_x = SCREEN_WIDTH * 1 / 2 - 1;
const int val2_5_x = SCREEN_WIDTH * 13 / 20 - 1;
const int val3_x = SCREEN_WIDTH * 4 / 5 - 1;
drawString_centered(val1, val1_x, val_y);
drawString_centered(":", val1_5_x, val_y);
drawString_centered(val2, val2_x, val_y);
drawString_centered(":", val2_5_x, val_y);
drawString_centered(val3, val3_x, val_y);
if (isPressStart_Select())isActivated = !isActivated;
if (!isActivated){
if (isPressStart_Left()) activeElement--;
if (isPressStart_Right()) activeElement++;
if (activeElement>2||activeElement<0){
activeElement = 0;
current_menu = 0;
}
}else{
//edit time
if (isPressStart_Left()){
if (activeElement==2){
set_preset_second(os_clock_currentTime_seconds());
}else if (activeElement==1){
set_preset_minute(get_preset_minute() - 1);
}else if (activeElement==0){
set_preset_hour(get_preset_hour() - 1);
}
}else if(isPressStart_Right()){
if (activeElement==2){
set_preset_second(os_clock_currentTime_seconds());
}else if (activeElement==1){
set_preset_minute(get_preset_minute() + 1);
}else if (activeElement==0){
set_preset_hour(get_preset_hour() + 1);
}
}
}
if (isActivated){
switch(activeElement){
case 0:
drawLine(val1_x - 1 - FONT_CHAR_WIDTH*strlen(val1)/2, val_y_strike, val1_x - 1 + FONT_CHAR_WIDTH*strlen(val1)/2, val_y_strike);
break;
case 1:
drawLine(val2_x - 1 - FONT_CHAR_WIDTH*strlen(val2)/2, val_y_strike, val2_x - 1 + FONT_CHAR_WIDTH*strlen(val2)/2, val_y_strike);
break;
case 2:
drawLine(val3_x - 1 - FONT_CHAR_WIDTH*strlen(val3)/2, val_y_strike, val3_x - 1 + FONT_CHAR_WIDTH*strlen(val3)/2, val_y_strike);
break;
}
}else{
switch(activeElement){
case 0:
drawIcon( (const unsigned char *)getIcon(ICON_ARROW_UP), val1_x - 5, val_y_strike + 2, 8, 4);
break;
case 1:
drawIcon( (const unsigned char *)getIcon(ICON_ARROW_UP), val2_x - 5, val_y_strike + 2, 8, 4);
break;
case 2:
drawIcon( (const unsigned char *)getIcon(ICON_ARROW_UP), val3_x - 5, val_y_strike + 2, 8, 4);
break;
}
}
//draw_arror_select_dateTime(SCREEN_WIDTH/5, SCREEN_WIDTH/5, 3, SCREEN_HEIGHT*0.75 );
}
void drawingSelectDeleayTurnOff(){
#define diagram_height 20
#define diagram_padding 5
#define top_margin (SCREEN_HEIGHT-diagram_height-diagram_padding-FONT_CHAR_HEIGHT-15)/2
drawRect_custom(
0,
top_margin + diagram_padding + diagram_height,
SCREEN_WIDTH - 1,
top_margin + diagram_padding + diagram_height,
SCREEN_WIDTH - 1,
top_margin + diagram_padding,
0,
top_margin + diagram_padding + diagram_height,
false
);
if (isPressStart_Left() && delay_before_turnoff!=0){delay_before_turnoff--;}
if (isPressStart_Right() && delay_before_turnoff<10){delay_before_turnoff++;}
drawingSelectDeleayTurnOff_value(delay_before_turnoff*10);
if (isPressStart_Select()){
current_menu = 0;
}
}
void drawingSelectDeleayTurnOff_value(byte percent){
drawRect_custom(
0,
top_margin + diagram_padding + diagram_height,
// Value nums
(SCREEN_WIDTH - 1)*percent/100 + 1,
top_margin + diagram_padding + diagram_height - diagram_height*percent/100,
(SCREEN_WIDTH - 1)*percent/100 + 1,
top_margin + diagram_padding + diagram_height,
//
0,
top_margin + diagram_padding + diagram_height,
true
);
drawString_centered(getDelayBeforTurnOff(), SCREEN_WIDTH/2, diagram_height + top_margin + diagram_padding*2);
drawIcon( (const unsigned char *)getIcon(ICON_ARROW_RIGHT), SCREEN_WIDTH-4, diagram_height + top_margin + diagram_padding*2, 4, 7); // Arrow right
drawIcon( (const unsigned char *)getIcon(ICON_ARROW_LEFT), 0, diagram_height + top_margin + diagram_padding*2, 4, 7); // Arrow left
}
char * getDelayBeforTurnOff(){
switch(delay_before_turnoff){
case 0: return "5 sec";
case 1: return "10 sec";
case 2: return "30 sec";
case 3: return "1 min";
case 4: return "2 min";
case 5: return "5 min";
case 6: return "10 min";
case 7: return "30 min";
case 8: return "45 min";
case 9: return "1 hour";
default: return "Never";
}
}
void drawSettingsMenu(){
if (isPressStart_Left() && current_menu_position>0) current_menu_position--;
if (isPressStart_Right() && current_menu_position<2) current_menu_position++;
this->scroll_to_y = 1-current_menu_position * drawSettingsElement_height + drawSettingsElement_margin + drawSettingsElement_height/2;
drawIcon(
this-> scroll_x + (const unsigned char *)getIcon(0x01), drawSettingsElement_margin_left/2 - 2,
SCREEN_HEIGHT/2-3,
4,
7
);
char v1[3];
char v2[3];
char v3[3];
char time_string[9];
int_to_char(v1, os_clock_currentTime_hour(), true);
int_to_char(v2, os_clock_currentTime_minutes(), true);
int_to_char(v3, os_clock_currentTime_seconds(), true);
sprintf(time_string, "%s:%s:%s", v1, v2, v3);
drawSettingsElement("Sleep after",getDelayBeforTurnOff(),0);
drawSettingsElement("Set time", time_string, 1);
drawSettingsElement("Exit", "", 2);
if (isPressStart_Select()){
switch (current_menu_position){
case 2: os_switch_to_app(-1); break;
case 0: current_menu = 1; break;
case 1: current_menu = 2; break;
}
}
}
void drawSettingsElement(char *label, char *value, byte position){
drawRect(this-> scroll_x + drawSettingsElement_margin_left, this-> scroll_y + position * drawSettingsElement_height + drawSettingsElement_margin, this-> scroll_x + SCREEN_WIDTH - drawSettingsElement_margin, this-> scroll_y + position * drawSettingsElement_height - drawSettingsElement_margin + drawSettingsElement_height);
drawString(label, this-> scroll_x + drawSettingsElement_margin_left + drawSettingsElement_padding, this-> scroll_y + position * drawSettingsElement_height + drawSettingsElement_padding + drawSettingsElement_margin);
drawString(value, this-> scroll_x + SCREEN_WIDTH - drawSettingsElement_margin - drawSettingsElement_padding - strlen(value)*FONT_CHAR_WIDTH, this-> scroll_y + position * drawSettingsElement_height + drawSettingsElement_padding + drawSettingsElement_margin + FONT_CHAR_HEIGHT + drawSettingsElement_padding_label_value);
}
void setup(){
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* >>> APP SETUP ON START <<< *
* *
*/
// ON START APP CODE
this->scroll_y = 1-current_menu_position * drawSettingsElement_height + drawSettingsElement_margin + drawSettingsElement_height/2;
/* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
};
static unsigned const char* getParams(unsigned char type){
switch(type){
case PARAM_TYPE_NAME: return (unsigned char*)appName;
case PARAM_TYPE_ICON: return icon;
default: return (unsigned char*)""; }
};
const static byte icon[];
appNameClass(){ // Constructor
setup();
};
};
const byte appNameClass::icon[] PROGMEM = { //128
//////////////////////////////////////////////////////////////
// PUT YOUR ICON HERE
0x00, 0x0C, 0x30, 0x00, 0x00, 0x1E, 0x78, 0x00,
0x00, 0x3F, 0xFC, 0x00, 0x00, 0x7F, 0xFE, 0x00,
0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
0x00, 0xFF, 0xFF, 0x00, 0x80, 0xFF, 0xFF, 0x01,
0xFE, 0x1F, 0xF8, 0x7F, 0xFF, 0x0F, 0xF0, 0xFF,
0xFF, 0x07, 0xE0, 0xFF, 0xFE, 0x03, 0xC0, 0x7F,
0xFC, 0x01, 0x80, 0x3F, 0xF8, 0x01, 0x80, 0x1F,
0xF0, 0x00, 0x00, 0x1F, 0xF0, 0x00, 0x00, 0x0F,
0xF0, 0x00, 0x00, 0x0F, 0xF8, 0x00, 0x00, 0x1F,
0xFC, 0x01, 0x80, 0x3F, 0xFE, 0x01, 0x80, 0x7F,
0xFF, 0x03, 0xC0, 0xFF, 0xFF, 0x07, 0xE0, 0xFF,
0xFF, 0x0F, 0xF0, 0xFF, 0xFE, 0x3F, 0xFC, 0x7F,
0x80, 0xFF, 0xFF, 0x01, 0x00, 0xFF, 0xFF, 0x00,
0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
0x00, 0x3F, 0xFC, 0x00, 0x00, 0x1F, 0xF8, 0x00,
0x00, 0x1E, 0x78, 0x00, 0x00, 0x0C, 0x30, 0x00,
//
//////////////////////////////////////////////////////////////
}; | true |
5badfc62d9964ed6a4b1fcb244cf22e50ae0b91f | C++ | lz-purple/Source | /app/src/main/java/com/syd/source/aosp/system/tpm/attestation/server/key_store.h | UTF-8 | 3,228 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | //
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ATTESTATION_SERVER_KEY_STORE_H_
#define ATTESTATION_SERVER_KEY_STORE_H_
#include <string>
#include <base/macros.h>
#include "attestation/common/common.pb.h"
namespace attestation {
// A mock-able key storage interface.
class KeyStore {
public:
KeyStore() {}
virtual ~KeyStore() {}
// Reads key data from the store for the key identified by |key_label| and by
// |username|. On success true is returned and |key_data| is populated.
virtual bool Read(const std::string& username,
const std::string& key_label,
std::string* key_data) = 0;
// Writes key data to the store for the key identified by |key_label| and by
// |username|. If such a key already exists the existing data will be
// overwritten.
virtual bool Write(const std::string& username,
const std::string& key_label,
const std::string& key_data) = 0;
// Deletes key data for the key identified by |key_label| and by |username|.
// Returns false if key data exists but could not be deleted.
virtual bool Delete(const std::string& username,
const std::string& key_label) = 0;
// Deletes key data for all keys identified by |key_prefix| and by |username|
// Returns false if key data exists but could not be deleted.
virtual bool DeleteByPrefix(const std::string& username,
const std::string& key_prefix) = 0;
// Registers a key to be associated with |username|.
// The provided |label| will be associated with all registered objects.
// |private_key_blob| holds the private key in some opaque format and
// |public_key_der| holds the public key in PKCS #1 RSAPublicKey format.
// If a non-empty |certificate| is provided it will be registered along with
// the key. Returns true on success.
virtual bool Register(const std::string& username,
const std::string& label,
KeyType key_type,
KeyUsage key_usage,
const std::string& private_key_blob,
const std::string& public_key_der,
const std::string& certificate) = 0;
// Registers a |certificate| that is not associated to a registered key. The
// certificate will be associated with |username|.
virtual bool RegisterCertificate(const std::string& username,
const std::string& certificate) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(KeyStore);
};
} // namespace attestation
#endif // ATTESTATION_SERVER_KEY_STORE_H_
| true |
4a7caa2aba4b37d800a939b8f3aca4bfed1ede05 | C++ | Masters-Akt/CS_codes | /leetcode_sol/669-Trim_A_Binary_Search_Tree.cpp | UTF-8 | 942 | 3.453125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
TreeNode* solve(TreeNode*& root, int low, int high, bool delCurr){
if(!root) return root;
root->left = solve(root->left, low, high, false);
root->right = solve(root->right, low, high, false);
if(root->val>=low && root->val<=high) return root;
TreeNode* ret;
if(root->val<low) ret = root->right;
else ret = root->left;
if(!delCurr) delete(root);
return ret;
}
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
return solve(root, low, high, true);
}
}; | true |
54c250f6b9548ef00eeb3ffc07812510d1953759 | C++ | ryuukk/arc_cpp | /arc/src/math/Quat.cpp | UTF-8 | 449 | 2.796875 | 3 | [] | no_license | #include "Quat.h"
arc::Quat arc::Quat::fromAxis(arc::Vec3 axis, float rad) {
float d = Vec3::len(axis);
if (d == 0.f) return Quat::identity();
d = 1.0f / d;
float l_ang = rad < 0 ? Mathf::PI2() - (std::fmod(-rad, Mathf::PI2())) : std::fmod(rad, Mathf::PI2());
float l_sin = std::sin(l_ang / 2);
float l_cos = std::cos(l_ang / 2);
return Quat(d * axis.x * l_sin, d * axis.y * l_sin, d * axis.z * l_sin, l_cos).nor();
}
| true |
e0e7c253238d0975b90e7f4dcbb67c1a27d23d94 | C++ | verngutz/cp-library | /Convolutions (Arithmetic) - Modular Convolution Square-Root Trick.cpp | UTF-8 | 1,523 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "Convolutions (Arithmetic) - Discrete Fourier Transform.cpp"
using namespace std;
template <typename T> vector<T>& operator+=(vector<T>& a, const vector<T>& b) {
transform(a.begin(), a.end(), b.begin(), a.begin(), plus<T>());
return a;
}
template <typename T> vector<T>& operator-=(vector<T>& a, const vector<T>& b) {
transform(a.begin(), a.end(), b.begin(), a.begin(), minus<T>());
return a;
}
template <typename T> vector<T> operator+(vector<T> a, const vector<T>& b) { return a += b; }
template <typename T> vector<T> operator-(vector<T> a, const vector<T>& b) { return a -= b; }
template <int C = int(sqrt(mint::MOD) + 0.5)> vector<mint>& operator*=(vector<mint>& a, vector<mint>& b) {
vector<complex<double>> a0(a.size()), a1(a.size()), b0(b.size()), b1(b.size());
transform(a.begin(), a.end(), a0.begin(), [](mint& ai) { return ai.val % C; });
transform(a.begin(), a.end(), a1.begin(), [](mint& ai) { return ai.val / C; });
transform(b.begin(), b.end(), b0.begin(), [](mint& bi) { return bi.val % C; });
transform(b.begin(), b.end(), b1.begin(), [](mint& bi) { return bi.val / C; });
vector<complex<double>> z0 = a0 * b0, &z1 = (a0 += a1) *= (b0 += b1), &z2 = a1 *= b1;
(z1 -= z0) -= z2;
for(int i = 0; i < a.size(); i++) {
a[i] = mint(z0[i]) + mint(z1[i]) * C + mint(z2[i]) * C * C;
}
return a;
}
template <int C = int(sqrt(mint::MOD) + 0.5)> vector<mint> operator*(vector<mint> a, vector<mint>& b) { return a *= b; }
| true |
1b068460eb0e0dd8684a4ed13e134db9826bf128 | C++ | LeandroRodriguez/fpietomrearoleanoagus | /ManejoArchivos/Bloque.cpp | UTF-8 | 5,943 | 3.4375 | 3 | [] | no_license | #include "Bloque.h"
/*constructor*/
Bloque::Bloque(const cantBytes& tamanio) {
this->tamanio = tamanio;
this->usados = 0;
this->registros = new list<RegistroVariable*>();
/*el nroBloque se lo setean desde afuera*/
}
Bloque::Bloque(){}
/*destructor*/
Bloque::~Bloque() {
}
/*devuelve true si el registro se pudo insertar, false si no se pudo*/
bool Bloque::agregarRegistro(RegistroVariable* registro) {
/*obtengo el tamanio que ocupa serializado*/
cantBytes tamanioSerializado = registro->getTamanioSerializado();
/*me tendria que fijar con ese tamanio, si entra en el bloque*/
/*verifico que el registro no sea nulo, e inserto*/
if (registro != NULL) {
this->registros->push_back(registro);
} else {
cerr << "Error: Se intento agregar un registro nulo.";
}
/*aumento la cant de tam usado, segun al tamanio serializado del registro que quiero ingresar*/
this->usados += tamanioSerializado;
//guardar en un archivo el nuevo espacio que queda en el bloque
return true;
}
/*devuelve la tira de bytes del objeto serializado*/
Bytes Bloque::serializarse() {
int espacioLibre;
//Bytes serializacion;
/*defino un iterador para recorrer mi lista de registros*/
string serializacion = "";
list<RegistroVariable*>::iterator it = this->registros->begin();
//Serializar cada uno de los registros y los voy metiendo todos juntos en una cadena
for ( ; it != this->registros->end(); it++) {
//le pido al reg que se serialize
Bytes registroSerializado = (*it)->serializarse();
serializacion += (registroSerializado.toString());
}
//lleno el espacio libre con 0's
espacioLibre = this->tamanio - this->usados;
string stringNulo;
for (int i = 0; i < (espacioLibre); i++) {
stringNulo += "0";
}
Bytes bytesNulos(stringNulo);
serializacion+=(bytesNulos.toString());
//creo un string con tantos 0 como espacio libre tenga,
//y lo agrego al final de mi serializacion
Bytes b;
b.agregar(serializacion, 0);
return b;
}
/*recupero mi objeto a partir de una tira de bytes*/
void Bloque::hidratarse(const Bytes& bytesBloque) {
cantBytes tamanio = bytesBloque.getTamanio();/*consigo la cant de bytes pasados*/
cantBytes tamanioDato = 0;
cantBytes tamanioUsado = 0;
int i = 0;
/*cantBytes es un tipo definido en ctes como un long int*/
if (tamanio < LONGITUD_CANT_BYTES) {
cerr << "El tamanio del bloque es muy chico (" << tamanio << ")"<< endl;
return;
}
bool seguir = true;
bool pasoCero = false;
while (seguir) {
/*int = atoi(string)*//*mas info http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/ */
/*obtengo los bytes del bloque pasado desde (tamanioUsado + i * LONGITUD_CANT_BYTES * 2) hasta (LONGITUD_CANT_BYTES)
*eso lo paso a string y le agrego el caracter de fin de linea
*este string es el que convierto en un int con atoi
Como tamanioUsado=0 y i=0 en la primera levanto los primeros 8 bytes.*/
cantBytes datoUID = atoi(bytesBloque.getSubBytes(tamanioUsado + i * LONGITUD_CANT_BYTES * 2 + i, LONGITUD_CANT_BYTES).toString().c_str());
/*si pasoCero(o sea, ya paso el bloque con UID=0) y no levante bytes, corto*/
if ((datoUID == 0)&&(pasoCero))
{
i--; /* vuelvo 8 bytes atras*/
break;
}
/*levanto los siguientes 8 bytes (primer ciclo)*/
tamanioDato = atoi(bytesBloque.getSubBytes(tamanioUsado + i * LONGITUD_CANT_BYTES * 2 + LONGITUD_CANT_BYTES + i, LONGITUD_CANT_BYTES).toString().c_str());
/*si no levante bytes corto*/
if (tamanioDato == 0) {
//cerr << "salame" << endl;
i--;
break;
}
string a = bytesBloque.getSubBytes(tamanioUsado + i * LONGITUD_CANT_BYTES * 2 + LONGITUD_CANT_BYTES*2 + i,1).toString();
bool vivo = (a=="1");
/*levanto a partir de los bytes del paso anterior (primer ciclo) segun tamanioDato, y ahora no lo convierto en int*/
Bytes dato = bytesBloque.getSubBytes(LONGITUD_CANT_BYTES * 2 + i * LONGITUD_CANT_BYTES * 2 + tamanioUsado + i + 1,tamanioDato);
/*Aca es donde recupero el dato en formato de Bytes*/
/*aumento i para desplazarme sobre la tira de BytesBloques*/
i++;
/*Hidrato mi registro variable con la cadena de bytes del dato*/
RegistroVariable* registro = new RegistroVariable(dato);
registro->setNRegistro(datoUID);
registro->setVivo(vivo);
agregarRegistro(registro);
/*Seteo todos sus atributos y lo agrego al bloque*/
tamanioUsado = tamanioUsado + tamanioDato;
/*Voy aumentando el tamanio usado del bloque*/
/*si paso el dato UniqueId de valor 0 seteo esta variable en true*/
if (datoUID == 0) pasoCero=true;
}
/*finalmente seteo tamanios*/
this->tamanio = tamanio;
this->usados = tamanioUsado + i * LONGITUD_CANT_BYTES * 2 + LONGITUD_CANT_BYTES * 2;
}
/*true si tiene lugar para insertar el registro pasado, false si no*/
bool Bloque::tieneLugar(RegistroVariable* registro) {
cantBytes tamanioDelNuevo = registro->getTamanioSerializado();
if (this->tamanio >= tamanioDelNuevo + this->usados) {
return true;
} else {
return false;
}
}
/*Los bloques son de tamanio fijo*/
cantBytes Bloque::getTamanioSerializado() {
return this->tamanio;
}
/*devuelve espacio libre*/
cantBytes Bloque::getEspacioLibre() {
return (this->tamanio - this->usados);
}
/*devuelvo tira de bytes de un registro segun su UID*/
Bytes Bloque::obtenerRegistro(uint32_t nRegistro){
Bytes registroBuscado;
list<RegistroVariable*>::iterator it = this->registros->begin();
/*busco en la lista si encuentro el UID dado. Si lo encuentro devuelvo el dato, sino un string vacio*/
while (it != this->registros->end()) {
RegistroVariable* registro = (RegistroVariable*)*it;
Bytes dato = registro->getDato();
uint32 UID = registro->getNRegistro();
if (UID == nRegistro) {
return dato;
}
it++;
}
return Bytes("");
}
void Bloque::setRegistro(uint32_t UID, RegistroVariable* r){
list<RegistroVariable*>::iterator it;
it=registros->begin();
for(;it!=registros->end();it++){
if((*it)->getNRegistro() == UID)
*it = r;
}
}
| true |
52cf949c591505d19499d3566f6f6b069a007bfc | C++ | pradeep-k/graphlake | /typekv.cpp | UTF-8 | 7,166 | 2.546875 | 3 | [] | no_license | #include "graph.h"
#include "typekv.h"
sid_t typekv_t::type_update(const string& src, const string& dst)
{
sid_t src_id = 0;
sid_t super_id = 0;
vid_t vid = 0;
tid_t type_id;
//allocate class specific ids.
map<string, vid_t>::iterator str2vid_iter = str2vid.find(src);
if (str2vid.end() != str2vid_iter) {
src_id = str2vid_iter->second;
/*
//dublicate entry
//If type mismatch, delete original //XXX
tid_t old_tid = TO_TID(src_id);
if (old_tid != type_id) {
/ *
//Different types, delete
str2vid.erase(str2vid_iter);
cout << "Duplicate unique Id: " << src << " Deleting both. " ;
cout << "Existing Type: " << (char*)(log_beg + t_info[old_tid].type_name) << "\t";
cout << "New Type: " << (char*)(log_beg + t_info[type_id].type_name) << endl;
* /
assert(0);
return INVALID_SID;
}*/
} else {
//create new type
map<string, tid_t>::iterator str2enum_iter = str2enum.find(dst);
//Have not see this type, create one
if (str2enum.end() == str2enum_iter) {
type_id = t_count++;
super_id = TO_SUPER(type_id);
str2enum[dst] = type_id;
t_info[type_id].vert_id = super_id;
t_info[type_id].type_name = strdup(dst.c_str());
t_info[type_id].max_vcount = (1<<21);//guess
string filename = g->odirname + col_info[0]->p_name;
t_info[type_id].strkv.setup(type_id);
t_info[type_id].strkv.file_open(filename, true);
} else { //existing type, get the last vertex id allocated
type_id = str2enum_iter->second;
super_id = t_info[type_id].vert_id;
}
src_id = super_id++;
t_info[type_id].vert_id = super_id;
++g->vert_count;
str2vid[src] = src_id;
vid = TO_VID(super_id);
assert(vid < t_info[type_id].max_vcount);
t_info[type_id].strkv.set_value(vid, src.c_str());
}
return src_id;
}
sid_t typekv_t::type_update(const string& src, tid_t type_id)
{
sid_t src_id = 0;
sid_t super_id = 0;
vid_t vid = 0;
assert(type_id < t_count);
super_id = t_info[type_id].vert_id;
//allocate class specific ids.
map<string, vid_t>::iterator str2vid_iter = str2vid.find(src);
if (str2vid.end() == str2vid_iter) {
src_id = super_id++;
t_info[type_id].vert_id = super_id;
++g->vert_count;
str2vid[src] = src_id;
vid = TO_VID(src_id);
assert(vid < t_info[type_id].max_vcount);
t_info[type_id].strkv.set_value(vid, src.c_str());
} else {
//dublicate entry
//If type mismatch, delete original //XXX
src_id = str2vid_iter->second;
tid_t old_tid = TO_TID(src_id);
if (old_tid != type_id) {
//Different types, delete
assert(0);
return INVALID_SID;
}
}
return src_id;
}
status_t typekv_t::filter(sid_t src, univ_t a_value, filter_fn_t fn)
{
//value is already encoded, so typecast it
tid_t dst = (tid_t) a_value.value_tid;
assert(fn == fn_out);
tid_t type1_id = TO_TID(src);
if (type1_id == dst) return eOK;
return eQueryFail;
}
status_t typekv_t::get_encoded_value(const char* value, univ_t* univ)
{
map<string, tid_t>::iterator str2enum_iter = str2enum.find(value);
if (str2enum.end() == str2enum_iter) {
return eQueryFail;
}
univ->value_tid = str2enum_iter->second;
return eOK;
}
status_t typekv_t::get_encoded_values(const char* value, tid_t** tids, qid_t* counts)
{
tid_t tid;
map<string, tid_t>::iterator str2enum_iter = str2enum.find(value);
if (str2enum.end() == str2enum_iter) {
return eQueryFail;
}
tid = str2enum_iter->second;
assert(tid < t_count + it_count);
if (tid < t_count) {
*counts = 1;
tids[0] = new tid_t;
tids[0][0] = tid;
} else {
*counts = it_info[tid - t_count].count;
tids[0] = it_info[tid - t_count].tlist;
}
return eOK;
}
void typekv_t::make_graph_baseline()
{
}
void typekv_t::file_open(const string& dir, bool trunc)
{
string vtfile;
vtfile = dir + col_info[0]->p_name + ".vtable";
if(trunc) {
//vtf = open(vtfile.c_str(), O_RDWR|O_CREAT|O_TRUNC, S_IRWXU);
vtf = fopen(vtfile.c_str(), "w");
assert(vtf != 0);
} else {
//vtf = open(vtfile.c_str(), O_RDWR|O_CREAT, S_IRWXU);
vtf = fopen(vtfile.c_str(), "r+");
assert(vtf != 0);
}
}
void typekv_t::store_graph_baseline(bool clean)
{
fseek(vtf, 0, SEEK_SET);
//write down the type info, t_info
char type_text[512];
for (tid_t t = 0; t < t_count; ++t) {
#ifdef B32
sprintf(type_text, "%u %u %s\n", t_info[t].max_vcount, TO_VID(t_info[t].vert_id),
t_info[t].type_name);
#elif B64
sprintf(type_text, "%lu %lu %s\n", t_info[t].max_vcount, TO_VID(t_info[t].vert_id),
t_info[t].type_name);
#endif
fwrite(type_text, sizeof(char), strlen(type_text), vtf);
t_info[t].strkv.handle_write();
}
//str2enum: No need to write. We make it from disk during initial read.
//XXX: write down the deleted id list
}
void typekv_t::read_graph_baseline()
{
char line[1024] = {0};
char* token = 0;
tid_t t = 0;
char* saveptr = line;
while (fgets(saveptr, sizeof(line), vtf)) {
token = strtok_r(saveptr, " \n", &saveptr);
t_info[t].max_vcount = strtol(token, NULL, 0);
token = strtok_r(saveptr, " \n", &saveptr);
t_info[t].vert_id = strtol(token, NULL, 0) + TO_SUPER(t);
token = strtok_r(saveptr, " \n", &saveptr);
t_info[t].type_name = strdup(token);
t_info[t].strkv.setup(t);
string filename = g->odirname + col_info[0]->p_name;
t_info[t].strkv.file_open(filename, false);
t_info[t].strkv.read_vtable();
t_info[t].strkv.prep_str2sid(str2vid);
++t;
}
//Populate str2enum now.
for (tid_t t = 0; t < t_count; ++t) {
str2enum[t_info[t].type_name] = t;
}
t_count = t;
}
typekv_t::typekv_t()
{
init_enum(256);
vtf = 0;
}
//Required to be called as we need to have a guess for max v_count
tid_t typekv_t::manual_setup(vid_t vert_count, bool create_vert, const string& type_name/*="gtype"*/)
{
string filename = g->odirname + col_info[0]->p_name;
str2enum[type_name.c_str()] = t_count;
t_info[t_count].type_name = strdup(type_name.c_str());
if (create_vert) {
t_info[t_count].vert_id = TO_SUPER(t_count) + vert_count;
} else {
t_info[t_count].vert_id = TO_SUPER(t_count);
}
t_info[t_count].max_vcount = vert_count;
t_info[t_count].strkv.setup(t_count);
t_info[t_count].strkv.file_open(filename, true);
return t_count++;//return the tid of this type
}
cfinfo_t*
typekv_t::create_instance()
{
return new typekv_t;
}
| true |
9a421ecd913a939d39f530f6922d65a646e8c6c6 | C++ | Anecoz/homco2 | /apps/common/Timestamp.cpp | UTF-8 | 1,092 | 3.078125 | 3 | [] | no_license | #include "Timestamp.h"
#include <chrono>
#include <limits>
static std::int64_t g_invalidSec = std::numeric_limits<std::int64_t>::lowest();
namespace homco2 {
namespace common {
Timestamp::Timestamp()
: _sec(g_invalidSec)
{}
Timestamp::Timestamp(std::int64_t epochSeconds)
: _sec(epochSeconds)
{}
Timestamp Timestamp::now()
{
const auto now = std::chrono::system_clock::now();
const std::int64_t epochSeconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
return Timestamp(epochSeconds);
}
Timestamp::operator bool() const
{
return _sec != g_invalidSec;
}
bool Timestamp::operator==(const Timestamp& other) const
{
return other._sec == _sec;
}
bool Timestamp::operator<(const Timestamp& other) const
{
return other._sec < _sec;
}
bool Timestamp::operator>(const Timestamp& other) const
{
return other._sec > _sec;
}
bool Timestamp::operator<=(const Timestamp& other) const
{
return *this < other || *this == other;
}
bool Timestamp::operator>=(const Timestamp& other) const
{
return *this > other || *this == other;
}
}
} | true |
1a98e4c753a0ade6433d86cd99b4cea5b997d8d6 | C++ | prevwong/oasis-eosio-v2 | /contracts/Marketplace/Marketplace.cpp | UTF-8 | 2,933 | 3.046875 | 3 | [] | no_license | #include "Marketplace.hpp"
#include <eosiolib/asset.hpp>
namespace Oasis {
void Marketplace::buy(name buyer, const uint64_t product_id) {
productIndex products(_code, _code.value);
auto iterator = products.find(product_id);
eosio_assert(iterator != products.end(), "The product was not found");
auto product = products.get(product_id);
eosio_assert(product.quantity > 0, "The product is out of stock");
asset productPrice = asset(product.price, symbol("OAS", 4));
action(permission_level{get_self(),"active"_n}, "anorak"_n, "transfer"_n, make_tuple(buyer, _self, productPrice, string(""))).send();
action(permission_level{get_self(),"active"_n}, "market"_n, "additem"_n, make_tuple(buyer,
product.product_id,
product.name,
product.power,
product.health,
product.ability,
product.level_up
)).send();
update(buyer, product.product_id, -1);
}
void Marketplace::add(name account, const product newProduct) {
require_auth(account);
productIndex products(_code, _code.value);
auto iterator = products.find(newProduct.product_id);
eosio_assert(iterator == products.end(), "Product for this ID already exists!");
products.emplace(account, [&](auto& product) {
product.product_id = newProduct.product_id;
product.name = newProduct.name;
product.power = newProduct.power;
product.health = newProduct.health;
product.ability = newProduct.ability;
product.level_up = newProduct.level_up;
product.quantity = newProduct.quantity;
product.price = newProduct.price;
});
}
void Marketplace::update(name account, const uint64_t product_id, uint64_t quantity) {
require_auth(account);
productIndex products(_code, _code.value);
auto iterator = products.find(product_id);
eosio_assert(iterator != products.end(), "Product not found");
products.modify(iterator, account, [&](auto& product) {
product.quantity += quantity;
});
}
void Marketplace::remove(name account, const uint64_t product_id) {
require_auth(account);
productIndex products(_code, _code.value);
auto iterator = products.find(product_id);
eosio_assert(iterator != products.end(), "Product not found");
products.erase(iterator);
}
void Marketplace::getbyid(const uint64_t product_id){
productIndex products(_code, _code.value);
auto iterator = products.find(product_id);
eosio_assert(iterator != products.end(), "Product ID does not exist");
auto product = products.get(product_id);
print("Id: ", product.product_id);
print(" | Name: ", product.name.c_str());
print(" | Power: ", product.power);
print(" | Health: ", product.health);
print(" | Ability: ", product.ability.c_str());
print(" | Level up: ", product.level_up);
print(" | Quantity: ", product.quantity);
print(" | Price: ", product.price);
}
} | true |
4c711b0d299678cff0a0b39fffd8c0f5e33aa532 | C++ | rhomu/mix_mpcd | /src/random.hpp | UTF-8 | 696 | 3.21875 | 3 | [] | no_license | #ifndef RANDOM_HPP_
#define RANDOM_HPP_
// self explanatory
void init_random();
// return random real, uniform distribution
float random_real();
// return random real, normally distributed
float random_normal();
// return random uint
uint32_t random_uint32();
inline float random_real(float min, float max)
{
return min+random_real()*(max-min);
}
inline float random_normal(float mu, float sigma)
{
return mu + sigma*random_normal();
}
// generate unisgned in range [lower, upper)
inline uint32_t random_uint32(uint32_t lower, uint32_t upper)
{
// this is ok when the range is small compared to UINT_MAX!!!
return ((random_uint32() % (upper-lower+1)) + lower);
}
#endif//RANDOM_HPP_
| true |
994436e9271381238ec287bfbdb1a88d1ff93ced | C++ | s1042992/UVAPractice | /UVA13180.cpp | UTF-8 | 849 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int pearls[1100];
while(cin>>pearls[0] && pearls[0]!=0){
int cnt = 1;
while(cin>>pearls[cnt] && pearls[cnt]!=0){
cnt++;
}
sort(pearls,pearls+cnt);
bool flag=true;
if(cnt%2==0){
flag=false;
}
else{
for(int i=0;i<cnt-1;i+=2){
if(pearls[i] != pearls[i+1]){
flag=false;
}
}
}
if(flag){
cout<<pearls[0];
for(int i=2;i<cnt;i+=2){
cout<<" "<<pearls[i];
}
for(int i=cnt-3;i>=0;i-=2){
cout<<" "<<pearls[i];
}
cout<<endl;
}
else{
cout<<"NO"<<endl;
}
}
}
| true |
84deffbef7338b020def8079053d8d3e4eb557ee | C++ | AntonyHerald/Cpp | /8.cppAdvanced/vectorSTL02.cpp | UTF-8 | 782 | 3.796875 | 4 | [] | no_license | // Vectors are STL in C++, They care sequencial containers that store elements.
// Vectors are dynamic data storage, They can be expanded based on the elements.
//
// Why - When user do not know the size of array/container during design time
// this comes handy to alter the size during run time.
//
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size;
cout<<"Enter the size of the Integer vector ";
cin>>size;
//to initialize the value
vector<int> value(size, 0);
for(int i: value)
cout<< i << endl; //hence this will print all zeros
for(int i=0; i < size ; i++)
{
cout<<"Enter the vector elements "<<i<< " ";
cin >> value[i];
}
for(auto x: value){
cout<< x <<" ";
}
cout<<"-----------------";
return 0;
}
| true |
0e726dae174119fc40dc8f88a7d12af845cce6c9 | C++ | vegardinho/curlingprosjekt | /scrapyard/akselerator__raw_values_.ino | UTF-8 | 3,498 | 2.765625 | 3 | [] | no_license | // MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include <Wire.h>
#include <stdlib.h>
int *med_denne;
int *med_forrige;
int *maalinger;
int ant_var = 6;
int maks_maalinger = 50;
int sekv_nr = 0;
const int MPU_addr=0x68; // I2C address of the MPU-6050
boolean akkurat_startet;
void setup(){
//Allokerer minne
maalinger = malloc(ant_var* maks_maalinger * sizeof(int));
med_denne = malloc(ant_var * sizeof(int));
med_forrige = malloc(ant_var * sizeof(int));
//Nullstiller verdier
for (int i = 0; i < maks_maalinger; i++) {
maalinger[i] = 0;
if (i % 5 == 0) {
med_denne[i / 5] = 0;
med_forrige[i / 5] = 0;
}
}
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
Wire.beginTransmission(0b1101000);
Wire.write(0x1B); //gyroscope config
Wire.write(0x00000000);
Wire.endTransmission();
Wire.beginTransmission(0b1101000);
Wire.write(0x1C); //akselerometer config
Wire.write(0b00011000);
Wire.endTransmission();
}
int int_compare(const void *a, const void *b) {
int *tall_a = (int*) a;
int *tall_b = (int*) b;
return *tall_a - *tall_b;
}
void process_gyro_data(int* gyro_arr) {
gyro_arr[0] = gyro_arr[0] / 131.0;
gyro_arr[1] = gyro_arr[1] / 131.0;
gyro_arr[2] = gyro_arr[2] / 131.0;
}
void process_accel_data(int* acc_arr) {
acc_arr[0] = acc_arr[0] / 16.3840;
acc_arr[1] = acc_arr[1] / 16.3840;
acc_arr[2] = acc_arr[2] / 16.3840;
}
void loop(){
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
// 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
maalinger[maks_maalinger*0 + sekv_nr] = Wire.read()<<8|Wire.read();
// 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) */
maalinger[maks_maalinger*1 + sekv_nr] = Wire.read()<<8|Wire.read();
// 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) */
maalinger[maks_maalinger*2 + sekv_nr] = Wire.read()<<8|Wire.read();
// 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) */
//Hoppe over temp
Wire.read()<<8|Wire.read();
maalinger[maks_maalinger*3 + sekv_nr] = Wire.read()<<8|Wire.read();
// 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) */
maalinger[maks_maalinger*4 + sekv_nr] = Wire.read()<<8|Wire.read();
// 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) */
maalinger[maks_maalinger*5 + sekv_nr] = Wire.read()<<8|Wire.read();
sekv_nr++;
if (sekv_nr >= maks_maalinger) {
for (int i = 0; i < ant_var; i++) {
qsort(maalinger + i*maks_maalinger, maks_maalinger, sizeof(int), int_compare);
med_forrige[i] = med_denne[i];
med_denne[i] = maalinger[i*maks_maalinger + 25];
}
for (int i = 0; i < maks_maalinger * ant_var; i++) {
maalinger[i] = 0;
}
sekv_nr = 0;
process_accel_data(med_denne);
process_gyro_data(med_denne+3);
print(med_denne);
}
}
void print(int* verdier) {
Serial.print("AcX = "); Serial.print(verdier[0]);
Serial.print(" | AcY = "); Serial.print(verdier[1]);
Serial.print(" | AcZ = "); Serial.print(verdier[2]);
Serial.print(" | GyX = "); Serial.print(verdier[3]);
Serial.print(" | GyY = "); Serial.print(verdier[4]);
Serial.print(" | GyZ = "); Serial.println(verdier[5]);
}
| true |
7b7253fc1464c6c8f02841b92587cd95cda3e1d7 | C++ | haxul/cesar-cipher | /encryptions/cesar/begin_encyption.h | UTF-8 | 835 | 2.890625 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include "Cesar.h"
#include "../../helpers/input_helper.h"
using namespace std;
#ifndef UNTITLED_BEGIN_ENCYPTION_H
#define UNTITLED_BEGIN_ENCYPTION_H
void begin_cesar_encryption() {
string text;
int shift;
cout << "cesar algorithm is starting..." << endl;
cout << "enter text (only english letters): " << endl;
clear_cin();
getline(cin , text);
while(true) {
cout << "enter shift: " << endl;
cin >> shift;
if (cin.fail() || shift > 26 || shift < 0) {
clear_cin();
cout << "Only numbers. 0 > Number <= 26" << endl;
continue;
}
break;
}
Cesar cipher(text, shift);
cipher.encrypt();
}
#endif //UNTITLED_BEGIN_ENCYPTION_H
| true |
c41424b8eb335ad18c6b0d27fbf59471ef3873c5 | C++ | theRAMSnake/AI | /src/playgrounds/LogicalPG.cpp | UTF-8 | 4,983 | 2.8125 | 3 | [] | no_license | #include "LogicalPG.hpp"
#include <gacommon/rng.hpp>
#include <stdexcept>
#include <sstream>
namespace pgs
{
class LogicalFitnessEvaluator : public gacommon::IFitnessEvaluator
{
public:
LogicalFitnessEvaluator()
: mInputs({gacommon::ValueIO(), gacommon::ValueIO(), gacommon::ChoiceIO{4}})
, mOutputs({gacommon::ChoiceIO{2}})
{
mChallenges.push_back({0, 0, Operation::Or});
mChallenges.push_back({0, 1, Operation::Or});
mChallenges.push_back({1, 0, Operation::Or});
mChallenges.push_back({1, 1, Operation::Or});
mChallenges.push_back({0, 0, Operation::And});
mChallenges.push_back({0, 1, Operation::And});
mChallenges.push_back({1, 0, Operation::And});
mChallenges.push_back({1, 1, Operation::And});
mChallenges.push_back({0, 0, Operation::Nand});
mChallenges.push_back({0, 1, Operation::Nand});
mChallenges.push_back({1, 0, Operation::Nand});
mChallenges.push_back({1, 1, Operation::Nand});
mChallenges.push_back({0, 0, Operation::Xor});
mChallenges.push_back({0, 1, Operation::Xor});
mChallenges.push_back({1, 0, Operation::Xor});
mChallenges.push_back({1, 1, Operation::Xor});
}
void step()
{
}
gacommon::Fitness evaluate(gacommon::IAgent& agent) override
{
gacommon::Fitness result = 0;
for(auto c : mChallenges)
{
auto inputs = getInputs();
auto outputs = getOutputs();
std::get<gacommon::ValueIO>(inputs[0]).value = static_cast<double>(c.a);
std::get<gacommon::ValueIO>(inputs[1]).value = static_cast<double>(c.b);
std::get<gacommon::ChoiceIO>(inputs[2]).selection = static_cast<std::size_t>(c.op);
auto expected = runChallenge(c);
agent.reset();
agent.run(inputs, outputs);
if(expected == std::get<gacommon::ChoiceIO>(outputs[0]).selection)
{
result++;
}
}
return result;
}
void play(gacommon::IAgent& a, std::ostringstream& out)
{
for(auto c : mChallenges)
{
a.reset();
auto inputs = getInputs();
auto outputs = getOutputs();
std::get<gacommon::ValueIO>(inputs[0]).value = static_cast<double>(c.a);
std::get<gacommon::ValueIO>(inputs[1]).value = static_cast<double>(c.b);
std::get<gacommon::ChoiceIO>(inputs[2]).selection = static_cast<std::size_t>(c.op);
auto printChChoice = [](auto op)
{
switch(op)
{
case Operation::Or:
return "OR";
case Operation::And:
return "AND";
case Operation::Xor:
return "XOR";
case Operation::Nand:
return "NAND";
}
return "";
};
out << std::string("Challenge: ") << c.a << " " << printChChoice(c.op) << " " << c.b << std::endl;
auto expected = runChallenge(c);
a.run(inputs, outputs);
if(expected == std::get<gacommon::ChoiceIO>(outputs[0]).selection)
{
out << "Success" << std::endl;
}
else
{
out << "Fail" << std::endl;
}
}
}
std::vector<gacommon::IOElement> getInputs() const
{
return mInputs;
}
std::vector<gacommon::IOElement> getOutputs() const
{
return mOutputs;
}
private:
enum class Operation
{
Or,
Xor,
And,
Nand
};
struct Challenge
{
int a;
int b;
Operation op;
};
std::size_t runChallenge(const Challenge& c) const
{
switch(c.op)
{
case Operation::Or:
return (c.a || c.b) ? 1 : 0;
case Operation::And:
return (c.a && c.b) ? 1 : 0;
case Operation::Xor:
return (c.a ^ c.b) ? 1 : 0;
case Operation::Nand:
return !(c.a && c.b) ? 1 : 0;
}
throw std::runtime_error("Unexpected at runChallenge");
}
std::vector<Challenge> mChallenges;
std::vector<gacommon::IOElement> mInputs;
std::vector<gacommon::IOElement> mOutputs;
};
gacommon::IFitnessEvaluator& LogicalPG::getFitnessEvaluator()
{
return *mFitnessEvaluator;
}
LogicalPG::LogicalPG()
: mFitnessEvaluator(new LogicalFitnessEvaluator)
{
}
void LogicalPG::step()
{
mFitnessEvaluator->step();
}
void LogicalPG::play(gacommon::IAgent& a, std::ostringstream& out)
{
mFitnessEvaluator->play(a, out);
}
std::string LogicalPG::getName() const
{
return "Logic";
}
std::vector<gacommon::IOElement> LogicalPG::getInputs() const
{
return mFitnessEvaluator->getInputs();
}
std::vector<gacommon::IOElement> LogicalPG::getOutputs() const
{
return mFitnessEvaluator->getOutputs();
}
}
| true |
665c016cd822931f70bca67af650bd4db68d8710 | C++ | Sugrue/UOIT-Projects | /Object Oriented Programming/Assignmnet_3/Assignmnet_3/Before comments/Shape.h | UTF-8 | 208 | 2.546875 | 3 | [] | no_license |
#include <string>
#include <iostream>
#ifndef SHAPE_H
#define SHAPE_H
class Shape{
public:
//constructor
Shape();
virtual double area();
virtual double perimeter();
virtual double volume();
};
#endif | true |
db9f5f618ba6f00d607e2110e83996f75190c30d | C++ | llpm/llpm | /lib/llpm/connection.hpp | UTF-8 | 9,214 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __LLPM_CONNECTION_HPP__
#define __LLPM_CONNECTION_HPP__
#include <llpm/ports.hpp>
#include <llpm/block.hpp>
#include <llpm/exceptions.hpp>
#include <util/macros.hpp>
#include <boost/function.hpp>
#include <set>
#include <map>
#include <unordered_map>
namespace llpm {
// Fwd. defs. Silly rabbit, modern parsing is for kids!
class Interface;
class Module;
/**
* Represents the connection between an output port and an input port.
*/
typedef std::pair<InputPort*, OutputPort*> ConnectionPair;
class Connection : public ConnectionPair {
public:
Connection(OutputPort* source, InputPort* sink) :
ConnectionPair(sink, source) { }
Connection(InputPort* sink, OutputPort* source) :
ConnectionPair(sink, source) { }
Connection() :
ConnectionPair(NULL, NULL) { }
Connection(const ConnectionPair& cp) :
ConnectionPair(cp) { }
Connection(const std::pair<OutputPort*, InputPort*>& p) :
ConnectionPair(p.second, p.first) { }
bool valid() const {
return source() != NULL && sink() != NULL;
}
/// Get the output port driving this connection
OutputPort* source() const {
return second;
}
/// Get the input port being driven by this connection
InputPort* sink() const {
return first;
}
inline Connection& operator=(const ConnectionPair& cp) {
first = cp.first;
second = cp.second;
return *this;
}
};
/**
* Database of connections. Provides fast access to find out which
* input ports are driven by a particular output port and which output
* port drives a particular input port. Blocks contained by this DB
* are implicitly defined by the ports involved in connections, though
* the block list is cached.
*
* Also, ConnectionDB deals with ownership of the blocks. Internally,
* the list of blocks are 'intrusive_ptr's to the blocks so the blocks
* are can be free'd when they are no longer involved in connections.
*/
class ConnectionDB {
Module* _module;
uint64_t _changeCounter;
// Connection data are stored in this bidirectional map
typedef std::unordered_map<OutputPort*, std::set<InputPort*> > SinkIdx;
typedef std::unordered_map<InputPort*, OutputPort*> SourceIdx;
SinkIdx _sinkIdx;
SourceIdx _sourceIdx;
std::set<BlockP> _blacklist;
std::map<BlockP, uint64_t> _blockUseCounts;
std::set<BlockP> _newBlocks;
void registerBlock(BlockP block);
void deregisterBlock(BlockP block);
public:
ConnectionDB(Module* m) :
_module(m),
_changeCounter(0)
{ }
DEF_GET_NP(module);
DEF_GET_NP(changeCounter);
/**
* Returns a pointer to a counter which increments every time a
* change is made to the ConnectionDB. Can be used to as a version
* number for the DB. Especially useful is one wants to cache
* queries on the DB.
*/
const uint64_t* counterPtr() const {
return &_changeCounter;
}
const auto& sinksRaw() const {
return _sinkIdx;
}
const auto& sourcesRaw() const {
return _sourceIdx;
}
class ConstIterator : public SourceIdx::const_iterator {
friend class ConnectionDB;
ConstIterator(SourceIdx::const_iterator iter)
: SourceIdx::const_iterator(iter) { }
public:
Connection operator*() const {
return Connection(
SourceIdx::const_iterator::operator*());
}
};
ConstIterator begin() const {
return ConstIterator(_sourceIdx.begin());
};
ConstIterator end() const {
return ConstIterator(_sourceIdx.end());
};
/**
* Make this block invisible to clients
*/
void blacklist(BlockP b) {
_blacklist.insert(b);
_changeCounter++;
}
/**
* Make this block visible to clients
*/
void deblacklist(BlockP b) {
_blacklist.erase(b);
_changeCounter++;
}
/**
* Is thie block visible to clients?
*/
bool isblacklisted(BlockP b) const {
return _blacklist.count(b) > 0;
}
/**
* Is thie block visible to clients?
*/
bool isblacklisted(Block* b) const {
return _blacklist.count(b->getptr()) > 0;
}
/**
* Is thie block visible to clients?
*/
bool isInternalDriver(const OutputPort* op) const {
return _blacklist.count(op->ownerP()) > 0;
}
void readAndClearNewBlocks(std::set<BlockP>& nb) {
nb.clear();
nb.swap(_newBlocks);
assert(_newBlocks.size() == 0);
}
void clearNewBlocks() {
_newBlocks.clear();
}
void findAllBlocks(std::set<Block*>& blocks) const {
for (auto pr: _blockUseCounts) {
if (pr.second >= 1 && _blacklist.count(pr.first) == 0)
blocks.insert(pr.first.get());
}
}
/**
* Return the set of blocks contained by this DB, filtered by the
* function passed in.
*/
void filterBlocks(boost::function<bool(Block*)>,
std::set<Block*>&);
void connect(OutputPort* o, InputPort* i);
void connect(InputPort* i, OutputPort* o) {
connect(o, i);
}
/**
* Connects one interface to another. If the server interface is already
* connected to something else, an InterfaceMultiplexer is automatically
* created or an existing InterfaceMultiplexer is used.
*/
void connect(Interface*, Interface*);
/**
* Connects one interface to a pair of ports (an implicit interface). If
* the server interface is already connected to something else, an
* InterfaceMultiplexer is automatically created or an existing
* InterfaceMultiplexer is used.
*/
void connect(Interface* srvr, OutputPort* op, InputPort* ip);
void disconnect(OutputPort* o, InputPort* i);
void disconnect(InputPort* i, OutputPort* o) {
disconnect(o, i);
}
void disconnect(Connection c) {
disconnect(c.source(), c.sink());
}
void disconnect(Interface* a, Interface* b);
/**
* Would adding this connection create a cycle?
*/
bool createsCycle(Connection c) const;
bool isUsed(Block* b) const {
auto f = _blockUseCounts.find(b->getptr());
if (f == _blockUseCounts.end())
return false;
return f->second >= 1;
}
bool exists(Connection c) const {
return c.source() == findSource(c.sink());
}
bool connected(OutputPort* op, InputPort* ip) const {
return exists(Connection(op, ip));
}
bool connected(InputPort* ip, OutputPort* op) const {
return exists(Connection(op, ip));
}
size_t numConnections() const {
return _sourceIdx.size();
}
size_t size() const {
return numConnections();
}
void findSinks(const OutputPort* op,
std::vector<const InputPort*>& out) const;
void findSinks(const OutputPort* op,
std::set<const InputPort*>& out) const;
void findSinks(const OutputPort* op,
std::vector<InputPort*>& out) const;
void findSinks(const OutputPort* op,
std::set<InputPort*>& out) const;
unsigned countSinks(const OutputPort* op) const;
OutputPort* findSource(const InputPort* ip) const;
void find(Block* b, std::vector<Connection>&) const;
bool find(const InputPort* ip, Connection& c) const;
void find(const OutputPort* op, std::vector<Connection>& out) const;
Interface* findClient(Interface*) const;
void find(const InputPort* ip, std::vector<OutputPort*>& out) const {
Connection c;
if (find(ip, c))
out.push_back(c.source());
}
void find(const OutputPort* ip, std::vector<InputPort*>& out) const {
std::vector<Connection> ret;
find(ip, ret);
for (auto&& c: ret) {
out.push_back(c.sink());
}
}
void find(const InputPort* ip, std::vector<const OutputPort*>& out) const {
Connection c;
if (find(ip, c))
out.push_back(c.source());
}
void find(const OutputPort* ip, std::vector<const InputPort*>& out) const {
std::vector<Connection> ret;
find(ip, ret);
for (auto&& c: ret) {
out.push_back(c.sink());
}
}
void removeBlock(Block* b);
/**
* Take the contents of the DB passed into this method and put
* them in this DB.
*/
void update(const ConnectionDB& newdb);
/**
* Remaps an input port or output port to point to new
* locations. If the input or output ports are unknown to this
* connection database, the remaps are stored so they may be
* processed later by an update or a connect.
*/
void remap(const InputPort* origPort, const std::vector<InputPort*>& newPorts);
void remap(const InputPort* origPort, InputPort* newPort) {
std::vector<InputPort*> newPorts = {newPort};
remap(origPort, newPorts);
}
void remap(const OutputPort* origPort, OutputPort* newPort);
void remap(const Interface*, Interface*);
};
} // namespace llpm
#endif // __LLPM_CONNECTION_HPP__
| true |
082641f39f9e12455b6583e24352d3dab96595b3 | C++ | harathi6672/ncrwork | /Windows internals/secondarythread/secondarythread.cpp | UTF-8 | 744 | 2.78125 | 3 | [] | no_license | #include <windows.h>
#include <stdio.h>
#include <tchar.h>
DWORD dwc;
DWORD WINAPI thread_func(LPVOID lparam) {
for (int i = 0; i < 10; i++) {
printf("i = %d\n", i);
Sleep(1000);
if (i == 5) {
ExitThread(dwc);
}
}
return 0;
}
int main() {
DWORD thid;
HANDLE hthread;
HANDLE handle_array;
hthread = CreateThread(NULL, 0, thread_func, NULL, 0, &thid);
if (NULL == hthread) {
printf("Unable to create a thread ERROR(%d)", GetLastError());
getchar();
return FALSE;
}
else {
printf("thread is created\n");
}
handle_array = hthread;
WaitForSingleObject(hthread, 6000);
GetExitCodeThread(hthread, &dwc);
printf("Exit code for thread is %ld", dwc);
CloseHandle(hthread);
getchar();
return 0;
}
| true |
bce248b8414f2711fdc35081433d6185cfae9dad | C++ | cjacker/windows.xp.whistler | /source/UTILS/UOFS/OFS/EXTENT.CXX | UTF-8 | 3,948 | 2.875 | 3 | [] | no_license | //+----------------------------------------------------------------------------
//
// File: extent.cxx
//
// Contents: Implementation of classes EXTENTNODE and EXTENTLST.
//
// Classes: EXTENTNODE
// EXTENTLST
//
// Functions: Methods of the above classes.
//
// History: 05-Jan-94 RobDu Created.
//
//-----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include "extent.hxx"
#include "sys.hxx"
//+--------------------------------------------------------------------------
//
// Member: EXTENTNODE
//
// Synopsis: EXTENTNODE constructor.
//
// Arguments: [Addr] -- Extent address.
// [Size] -- Extent size.
//
// Returns: Nothing.
//
//---------------------------------------------------------------------------
EXTENTNODE::EXTENTNODE(
IN CLUSTER Addr,
IN CLUSTER Size
)
{
DbgAssert(IsPowerOfTwo(Size) && Addr % Size == 0);
_Nxt = NULL;
_Prv = NULL;
_Addr = Addr;
_Size = Size;
}
//+--------------------------------------------------------------------------
//
// Member: EXTENTLST
//
// Synopsis: EXTENTLST constructor.
//
// Arguments: None.
// Returns: Nothing.
//
//---------------------------------------------------------------------------
EXTENTLST::EXTENTLST()
{
_pLst = NULL;
}
//+--------------------------------------------------------------------------
//
// Member: EXTENTLST
//
// Synopsis: EXTENTLST destructor.
//
// Arguments: None.
// Returns: Nothing.
//
//---------------------------------------------------------------------------
EXTENTLST::~EXTENTLST()
{
#ifdef DMPEXTENTLSTINFO
DbgPrintf(("\nDump of final extent list:\n\n"));
DmpLst();
#endif
DeleteLst();
}
//+--------------------------------------------------------------------------
//
// Member: AddToLst
//
// Synopsis: Add EXTENTNODE to the extent list.
//
// Arguments: TBS
//
// Returns: Nothing.
//
//---------------------------------------------------------------------------
VOID
EXTENTLST::AddToLst(
IN CLUSTER Addr,
IN CLUSTER Size
)
{
EXTENTNODE * pLst = _pLst;
EXTENTNODE * pNode = new EXTENTNODE(Addr, Size);
if (pNode == NULL)
SYS::RaiseStatusNoMem(__FILE__, __LINE__);
// Place allocated node on the list. We construct the list in
// order of increasing address to cut down on search time.
while (pLst != NULL && pLst->_Addr < pNode->_Addr)
pLst = pLst->_Nxt;
if (pLst == NULL)
{
AddToDLLTail(pNode, _pLst);
}
else if (pLst == _pLst)
{
AddToDLLHead(pNode, _pLst);
}
else
{
DbgPtrAssert(pLst->_Prv);
InsertIntoDLL(pNode, _pLst, pLst->_Prv);
}
}
//+--------------------------------------------------------------------------
//
// Member: AnyPartInLst
//
// Synopsis: Check if any of the clusters in the extent are already in the
// list.
//
// Arguments: [Addr] -- Extent address.
// [Size] -- Extent size.
//
// Returns: TRUE if any of the clusters are already in the list;
// FALSE otherwise.
//
//---------------------------------------------------------------------------
BOOLEAN
EXTENTLST::AnyPartInLst(
IN CLUSTER Addr,
IN CLUSTER Size
)
{
EXTENTNODE * pLst = _pLst;
while (pLst != NULL)
{
if (Addr + Size <= pLst->_Addr)
return FALSE;
else if (Addr < pLst->_Addr + pLst->_Size)
return TRUE;
pLst = pLst->_Nxt;
}
return FALSE;
}
//+--------------------------------------------------------------------------
//
// Member: DeleteLst
//
// Synopsis: Delete any nodes in the list, returning it to a freshly
// constructed state.
//
// Arguments: None.
// Returns: Nothing.
//
//---------------------------------------------------------------------------
VOID
EXTENTLST::DeleteLst()
{
EXTENTNODE * pNode;
while (_pLst != NULL)
{
pNode = _pLst;
_pLst = _pLst->_Nxt;
delete pNode;
}
}
| true |
e2aa2cde8cf6c5c2d4e40b4c2f6f8ead6e763334 | C++ | khaledsliti/CompetitiveProgramming | /LightOJ/LOJ1266.cpp | UTF-8 | 1,401 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
const int N = 1005;
int bit[N][N];
void add(int i, int j, int val)
{
for(int x = i; x < N; x += x & -x)
for(int y = j; y < N; y += y & -y)
bit[x][y] += val;
}
int get(int i, int j)
{
int res = 0;
for(int x = i; x > 0; x -= x & -x)
for(int y = j; y > 0; y -= y & -y)
res += bit[x][y];
return res;
}
int get(int l, int r, int d, int u)
{
return get(r, u) - get(l - 1, u) - get(r, d - 1) + get(l - 1, d - 1);
}
int index(int i, int j)
{
return i * N + j;
}
pair<int, int> index(int idx)
{
return { idx / N, idx % N };
}
int main()
{
int T, tc(1);
scanf("%d", &T);
while(T--){
printf("Case %d:\n", tc++);
int q;
scanf("%d", &q);
unordered_set<int> pts;
while(q--){
int t;
scanf("%d", &t);
if(t == 0){
int x, y;
scanf("%d%d", &x, &y);
x++; y++;
if(pts.find(index(x, y)) == pts.end()){
add(x, y, 1);
pts.insert(index(x, y));
}
}else{
int x1, x2, y1, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
printf("%d\n", get(++x1, ++x2, ++y1, ++y2));
}
}
for(auto& idx : pts){
pair<int, int> p = index(idx);
add(p.first, p.second, -1);
}
}
return 0;
}
| true |
cc3b820ab4c2e424c66edb286e55faf85173eb01 | C++ | peachbupt/Lab | /atl-demo/test-alt/test-alt.cpp | UTF-8 | 569 | 2.53125 | 3 | [] | no_license | // test-alt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "atldemo_i.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr;
IMyClass *pMyClass = NULL;
hr = CoInitialize(NULL);
hr = CoCreateInstance(CLSID_MyClass, NULL, 1,
IID_IMyClass, (void**)&pMyClass);
if(SUCCEEDED(hr))
{
long n = 0;
long sum = 0;
cout << "Input an Integer"<< endl;
cin >> n;
pMyClass->TotalSum(n, &sum);
std::cout<<"sum of 0 - "<< n <<" = "<<sum<<endl;
}
CoUninitialize();
return 0;
}
| true |
1a5213cf903d3a8a74accbbd1325a8a897622c11 | C++ | HULANG-BTB/LazyOJ | /Judger/Compare.cpp | UTF-8 | 12,625 | 3.0625 | 3 | [] | no_license | #include "Compare.h"
#include <string>
#include <fstream>
#include <sstream>
/**
* Class Compare
* Author: Lang Hu
* QQ: 774023581
* Email: admin@oibit.cn
* Date: 2019-10-10
* CompareCode: -2 --- 打开文件失败
* 0 --- 答案错误
* 1 --- 格式错误
* 2 --- 对比通过
**/
namespace lazyoj
{
using std::endl;
using std::fstream;
using std::ios;
using std::size_t;
using std::string;
Compare::Compare(string fileName_1, string fileName_2)
{
this->filename_1 = fileName_1;
this->filename_2 = fileName_2;
this->setStrict();
}
void Compare::setFileOne(string fileName)
{
this->filename_1 = fileName;
}
void Compare::setFileTwo(string fileName)
{
this->filename_2 = fileName;
}
void Compare::setStrict(bool Strict)
{
this->strict = Strict;
}
bool Compare::compare()
{
fstream File1, File2;
File1.open(this->filename_1, ios::in);
File2.open(this->filename_2, ios::in);
if (!File1.is_open())
{
compareInfo << "Failed to open file1!" << std::endl;
compareCode = -2;
return false;
}
if (!File2.is_open())
{
compareInfo << "Failed to open file2!" << std::endl;
compareCode = -2;
return false;
}
string line1, line2;
int count = 1;
while (true)
{
line1.clear();
line2.clear();
// 文件1到末尾 且 文件2到末尾 正确
if (File1.eof() && File2.eof())
{
compareInfo << "AC";
compareCode = 2;
return true;
}
// 如果 文件1到文件末尾 但文件2未到文件尾
else if (File1.eof() && !File2.eof())
{
// 文件2 读取一行
getline(File2, line2);
string newLine = line2;
// 清除换行 回车 空格
this->deleteAllMark(newLine, "\r");
this->deleteAllMark(newLine, "\n");
this->deleteAllMark(newLine, " ");
// 如果是严格模式
if (this->strict)
{
// 如果清除后的字符串长度等于0 或 文件2未到文件尾 格式错误
if (!newLine.size() && File2.eof())
{
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:PE" << endl
<< "Expected:" << endl;
this->compareInfo << "---(NULL)---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---" << line2 << "---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 1;
return false;
}
else
{
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:WA" << endl
<< "Expected:" << endl;
this->compareInfo << "---(NULL)---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---" << line2 << "---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 0;
return false;
}
}
// 非严格模式
else
{
// 如果清除后的字符串长度为0 并且 文件2未到文件尾 答案正确
if (!newLine.size() && File2.eof())
{
this->compareInfo << "AC";
this->compareCode = 2;
return true;
}
else
{
// 否则 答案错误
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:WA" << endl
<< "Expected:" << endl;
this->compareInfo << "---(NULL)---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---" << line2 << "---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 0;
return false;
}
}
}
// 文件1未到末尾 文件2到末尾
else if (!File1.eof() && File2.eof())
{
// 文件1 读取一行
getline(File1, line1);
string newLine = line1;
// 清除 空白字符
this->deleteAllMark(newLine, "\r");
this->deleteAllMark(newLine, "\n");
this->deleteAllMark(newLine, " ");
if (this->strict)
{
// 严格模式
if (!newLine.size() && File1.eof())
{
// 如果清除后的字符串长度为0 并且 文件1未到文件尾 格式错误
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:PE" << endl
<< "Expected:" << endl;
this->compareInfo << "---" << line1 << "---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---(NULL)---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 1;
return false;
}
else
{
// 否则 答案错误
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:WA" << endl
<< "Expected:" << endl;
this->compareInfo << "---" << line1 << "---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---(NULL)---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 0;
return false;
}
}
// 非严格模式
else
{
// 如果新行长度等于0 且文件1到文件末尾 答案正确
if (!newLine.size() && File1.eof())
{
this->compareInfo << "AC";
this->compareCode = 2;
return true;
}
// 否则答案错误
else
{
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:WA" << endl
<< "Expected:" << endl;
this->compareInfo << "---" << line1 << "---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---(NULL)---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 0;
return false;
}
}
}
// 两个文件均未到末尾
else
{
// 分别读取一行
getline(File1, line1);
getline(File2, line2);
// 删除末尾 换行 回车
deleteAllMark(line1, "\r");
deleteAllMark(line2, "\r");
deleteAllMark(line1, "\n");
deleteAllMark(line2, "\n");
// 如果两行内容不相等
if (line1 != line2)
{
// 严格模式 比较格式
if (this->strict)
{
// 删除所有空格
string newLineStd = line1;
string newLineUser = line2;
deleteAllMark(newLineStd, " ");
deleteAllMark(newLineUser, " ");
// 清除空格后相等 格式错误
if (newLineStd == newLineUser)
{
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:PE" << endl
<< "Expected:" << endl;
this->compareInfo << line1 << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << line2 << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 1;
return false;
}
// 否则答案错误
else
{
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:WA" << endl
<< "Expected:" << endl;
this->compareInfo << "---" << line1 << "---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---" << line2 << "---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 0;
return false;
}
}
// 非严格模式 答案错误
else
{
// 删除所有空格
string newLineStd = line1;
string newLineUser = line2;
deleteAllMark(newLineStd, " ");
deleteAllMark(newLineUser, " ");
// 清除空格后不相等 格式错误
if (newLineStd != newLineUser)
{
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << "Line: " << count << " Result:WA" << endl
<< "Expected:" << endl;
this->compareInfo << "---" << line1 << "---" << endl;
this->compareInfo << "Yours:" << endl;
this->compareInfo << "---" << line2 << "---" << endl;
this->compareInfo << "=============" << this->filename_1 << "=============" << endl;
this->compareInfo << endl;
this->compareCode = 0;
return false;
}
}
}
}
count++;
}
return true;
}
void Compare::deleteAllMark(string &val, string mark)
{
string::size_type pos = val.find_first_of(mark);
while (pos != val.npos)
{
val.replace(pos, mark.size(), "");
pos = val.find_first_of(mark);
}
}
int Compare::getCompareCode()
{
return this->compareCode;
}
string Compare::getCompareInfo() const
{
return this->compareInfo.str();
}
} // namespace lazyoj
| true |
680ab204ae6033852c8f7e9d8d4070ac75139ffd | C++ | Joewessel27/MobileBrawler | /src/GameLibrary/Actor/SpriteActor.cpp | UTF-8 | 17,934 | 2.8125 | 3 | [] | no_license |
#include "SpriteActor.h"
#include "../Graphics/PixelIterator.h"
namespace GameLibrary
{
SpriteActorAnimationEvent::SpriteActorAnimationEvent(const SpriteActorAnimationEvent& event)
: target(event.target),
name(event.name),
animation(event.animation)
{
//
}
SpriteActorAnimationEvent& SpriteActorAnimationEvent::operator=(const SpriteActorAnimationEvent& event)
{
target = event.target;
name = event.name;
animation = event.animation;
return *this;
}
SpriteActorAnimationEvent::SpriteActorAnimationEvent(SpriteActor* target, const String& name, Animation* animation)
: target(target),
name(name),
animation(animation)
{
//
}
SpriteActor* SpriteActorAnimationEvent::getTarget() const
{
return target;
}
const String& SpriteActorAnimationEvent::getAnimationName() const
{
return name;
}
Animation* SpriteActorAnimationEvent::getAnimation() const
{
return animation;
}
SpriteActor::SpriteActor() : SpriteActor(0,0)
{
//
}
SpriteActor::SpriteActor(double x1, double y1)
{
x = x1;
y = y1;
animation_current = nullptr;
animation_frame = 0;
animation_prevFrameTime = 0;
animation_direction = Animation::FORWARD;
firstUpdate = true;
prevUpdateTime = 0;
}
SpriteActor::~SpriteActor()
{
for(unsigned int i=0; i<animations.size(); i++)
{
AnimationInfo& info = animations.get(i);
if(info.destruct)
{
delete info.animation;
}
}
}
void SpriteActor::update(ApplicationData appData)
{
prevUpdateTime = appData.getTime().getMilliseconds();
if(firstUpdate)
{
if(animations.size()>0)
{
animation_prevFrameTime = prevUpdateTime;
}
}
firstUpdate = false;
Actor::update(appData);
//update animation loop
if(animation_direction == Animation::STOPPED)
{
animation_prevFrameTime = prevUpdateTime;
}
else if(animation_current!=nullptr)
{
float fps = animation_current->getFPS();
if(fps!=0)
{
long long waitTime = (long long)(1000.0f/fps);
long long finishTime = animation_prevFrameTime + waitTime;
if(finishTime <= prevUpdateTime)
{
animation_prevFrameTime = prevUpdateTime;
if(animation_direction == Animation::FORWARD)
{
animation_frame++;
size_t totalFrames = animation_current->getTotalFrames();
if(animation_frame >= totalFrames)
{
animation_frame = 0;
animation_current->setCurrentFrame(animation_frame);
onAnimationFinish(SpriteActorAnimationEvent(this, animation_name, animation_current));
}
else
{
animation_current->setCurrentFrame(animation_frame);
}
}
else if(animation_direction == Animation::BACKWARD)
{
if(animation_frame == 0)
{
size_t totalFrames = animation_current->getTotalFrames();
if(totalFrames > 0)
{
animation_frame = totalFrames-1;
}
animation_current->setCurrentFrame(animation_frame);
onAnimationFinish(SpriteActorAnimationEvent(this, animation_name, animation_current));
}
else
{
animation_frame--;
animation_current->setCurrentFrame(animation_frame);
}
}
}
}
}
}
void SpriteActor::draw(ApplicationData appData, Graphics graphics) const
{
drawActor(appData, graphics, x, y, scale);
}
void SpriteActor::drawActor(ApplicationData&appData, Graphics&graphics, double x, double y, double scale) const
{
if(visible && scale!=0 && animation_current!=nullptr)
{
graphics.translate(x, y);
Graphics boundingBoxGraphics(graphics);
if(rotation!=0)
{
graphics.rotate(rotation);
}
Graphics frameGraphics(graphics);
if(mirroredHorizontal)
{
if(mirroredVertical)
{
graphics.scale(-scale,-scale);
}
else
{
graphics.scale(-scale,scale);
}
}
else
{
if(mirroredVertical)
{
graphics.scale(scale,-scale);
}
else
{
graphics.scale(scale,scale);
}
}
Actor::draw(appData, graphics);
Graphics actorGraphics(graphics);
actorGraphics.compositeTintColor(color);
actorGraphics.setAlpha((byte)(alpha*255));
animation_current->setCurrentFrame(animation_frame);
animation_current->draw(appData, actorGraphics);
if(frame_visible)
{
frameGraphics.setColor(frame_color);
frameGraphics.drawRect(-(width/2), -(height/2), width, height);
boundingBoxGraphics.setColor(frame_color);
boundingBoxGraphics.drawRect(-(framesize.x/2), -(framesize.y/2), framesize.x, framesize.y);
}
}
}
RectangleD SpriteActor::getFrame() const
{
return RectangleD(x-(framesize.x/2), y-(framesize.y/2), framesize.x, framesize.y);
}
void SpriteActor::scaleToFit(const RectangleD&container)
{
if(width==0 || height==0)
{
double oldScale = scale;
setScale(1);
if(width==0 || height==0)
{
setScale(oldScale);
x = container.x + (container.width/2);
y = container.y + (container.height/2);
return;
}
}
if(container.width==0 || container.height==0)
{
setScale(0);
x = container.x + (container.width/2);
y = container.y + (container.height/2);
return;
}
RectangleD currentFrame = getFrame();
RectangleD oldFrame = currentFrame;
currentFrame.scaleToFit(container);
double ratio = currentFrame.width/oldFrame.width;
x = container.x + (container.width/2);
y = container.y + (container.height/2);
setScale(getScale()*ratio);
}
void SpriteActor::onAnimationFinish(const SpriteActorAnimationEvent& evt)
{
//Open for implementation
}
void SpriteActor::updateSize()
{
if(animation_current == nullptr || animation_current->getTotalFrames()==0)
{
framesize.x = 0;
framesize.y = 0;
width = 0;
height = 0;
return;
}
if(animation_frame > animation_current->getTotalFrames())
{
switch(animation_direction)
{
case Animation::NO_CHANGE:
animation_direction = Animation::FORWARD;
case Animation::STOPPED:
case Animation::FORWARD:
animation_frame = 0;
break;
case Animation::BACKWARD:
animation_frame = animation_current->getTotalFrames()-1;
break;
}
}
RectangleD frame = animation_current->getFrame(animation_frame);
frame.x*=scale;
frame.y*=scale;
frame.width*=scale;
frame.height*=scale;
width = frame.width;
height = frame.height;
frame = rotationMatrix.transform(frame);
framesize.x = frame.width;
framesize.y = frame.height;
}
void SpriteActor::addAnimation(const String&name, Animation*animation, bool destruct)
{
if(animation == nullptr)
{
throw IllegalArgumentException("animation", "null");
}
if(name.length() == 0)
{
throw IllegalArgumentException("name", "cannot be empty string");
}
if(hasAnimation(name))
{
throw IllegalArgumentException("name", "duplicate animation name");
}
AnimationInfo animInfo;
animInfo.name = name;
animInfo.animation = animation;
animInfo.destruct = destruct;
size_t prevSize = animations.size();
animations.add(animInfo);
if(prevSize == 0)
{
changeAnimation(name, Animation::FORWARD);
}
}
void SpriteActor::removeAnimation(const String&name)
{
size_t totalAnimations = animations.size();
for(size_t i=0; i<totalAnimations; i++)
{
AnimationInfo animInfo = animations.get(i);
if(animInfo.name.equals(name))
{
if(animInfo.name.equals(animation_name))
{
animation_current = nullptr;
animation_name = "";
}
if(animInfo.destruct)
{
delete animInfo.animation;
}
animations.remove(i);
return;
}
}
}
bool SpriteActor::hasAnimation(const String&name) const
{
size_t totalAnimations = animations.size();
for(size_t i=0; i<totalAnimations; i++)
{
if(animations.get(i).name.equals(name))
{
return true;
}
}
return false;
}
Animation* SpriteActor::getAnimation(const String&name) const
{
size_t totalAnimations = animations.size();
for(size_t i=0; i<totalAnimations; i++)
{
const AnimationInfo&animInfo = animations.get(i);
if(animInfo.name.equals(name))
{
return animInfo.animation;
}
}
return nullptr;
}
void SpriteActor::changeAnimation(const String&name, const Animation::Direction&direction)
{
if(direction != Animation::FORWARD && direction != Animation::BACKWARD && direction != Animation::STOPPED && direction != Animation::NO_CHANGE)
{
throw IllegalArgumentException("direction", "Invalid enum value");
}
Animation* animation = getAnimation(name);
if(animation == nullptr)
{
throw IllegalArgumentException("name", "animation does not exist");
}
animation_name = name;
animation_current = animation;
switch(direction)
{
case Animation::FORWARD:
case Animation::STOPPED:
{
animation_frame = 0;
animation_prevFrameTime = prevUpdateTime;
animation_direction = direction;
}
break;
case Animation::BACKWARD:
{
size_t totalFrames = animation->getTotalFrames();
if(totalFrames>0)
{
animation_frame = (totalFrames-1);
}
else
{
animation_frame = 0;
}
animation_prevFrameTime = prevUpdateTime;
animation_direction = direction;
}
break;
case Animation::NO_CHANGE:
{
switch(animation_direction)
{
default:
case Animation::NO_CHANGE:
break;
case Animation::FORWARD:
case Animation::STOPPED:
{
if(animation_frame >= animation->getTotalFrames())
{
animation_frame = 0;
}
}
break;
case Animation::BACKWARD:
{
size_t totalFrames = animation->getTotalFrames();
if(animation_frame >= totalFrames)
{
if(totalFrames>0)
{
animation_frame = (totalFrames-1);
}
else
{
animation_frame = 0;
}
}
}
break;
}
}
}
animation->setCurrentFrame(animation_frame);
updateSize();
}
void SpriteActor::changeAnimation(Animation*animation, const Animation::Direction&direction)
{
if(direction != Animation::FORWARD && direction != Animation::BACKWARD && direction != Animation::STOPPED && direction != Animation::NO_CHANGE)
{
throw IllegalArgumentException("direction", "Invalid enum value");
}
animation_name = "";
animation_current = animation;
switch(direction)
{
case Animation::FORWARD:
case Animation::STOPPED:
{
animation_frame = 0;
animation_prevFrameTime = prevUpdateTime;
animation_direction = direction;
}
break;
case Animation::BACKWARD:
{
size_t totalFrames = 0;
if(animation!=nullptr)
{
totalFrames = animation->getTotalFrames();
}
if(totalFrames>0)
{
animation_frame = (totalFrames-1);
}
else
{
animation_frame = 0;
}
animation_prevFrameTime = prevUpdateTime;
animation_direction = direction;
}
break;
case Animation::NO_CHANGE:
{
switch(animation_direction)
{
default:
case Animation::NO_CHANGE:
break;
case Animation::FORWARD:
case Animation::STOPPED:
{
size_t totalFrames = 0;
if(animation!=nullptr)
{
totalFrames = animation->getTotalFrames();
}
if(animation_frame >= totalFrames)
{
animation_frame = 0;
}
}
break;
case Animation::BACKWARD:
{
size_t totalFrames = 0;
if(animation!=nullptr)
{
totalFrames = animation->getTotalFrames();
}
if(animation_frame >= totalFrames)
{
if(totalFrames>0)
{
animation_frame = (totalFrames-1);
}
else
{
animation_frame = 0;
}
}
}
break;
}
}
}
if(animation!=nullptr)
{
animation->setCurrentFrame(animation_frame);
}
updateSize();
}
void SpriteActor::reloadAnimations(AssetManager*assetManager)
{
for(unsigned int i=0; i<animations.size(); i++)
{
animations.get(i).animation->reloadFrames(assetManager);
}
}
bool SpriteActor::checkPointCollision(const Vector2d&point)
{
if(animation_current == nullptr)
{
return false;
}
RectangleD frame = getFrame();
if(frame.contains(point))
{
Vector2d pointFixed = point;
pointFixed.x -= x;
pointFixed.y -= y;
pointFixed = inverseRotationMatrix.transform(pointFixed);
pointFixed.x += width/2;
pointFixed.y += height/2;
if((mirroredHorizontal && !animation_current->isMirroredHorizontal()) || (!mirroredHorizontal && animation_current->isMirroredHorizontal()))
{
pointFixed.x = width - pointFixed.x;
}
if((mirroredVertical && !animation_current->isMirroredVertical()) || (!mirroredVertical && animation_current->isMirroredVertical()))
{
pointFixed.y = height - pointFixed.y;
}
double ratX = pointFixed.x/width;
double ratY = pointFixed.y/height;
if(ratX < 0 || ratY < 0 || ratX>=1 || ratY>=1)
{
return false;
}
TextureImage* img = animation_current->getImage(animation_frame);
RectangleU srcRect = animation_current->getImageSourceRect(animation_frame);
unsigned int pxlX = (unsigned int)(ratX*((double)srcRect.width));
unsigned int pxlY = (unsigned int)(ratY*((double)srcRect.height));
return img->checkPixel((unsigned int)srcRect.x+pxlX,(unsigned int)srcRect.y+pxlY);
}
return false;
}
bool SpriteActor::isColliding(SpriteActor*actor) const
{
if(actor == nullptr)
{
throw IllegalArgumentException("actor", "null");
}
else if(animation_current==nullptr || actor->animation_current==nullptr || scale==0 || actor->scale==0)
{
return false;
}
RectangleD frame = getFrame();
RectangleD actor_frame = actor->getFrame();
if(frame.intersects(actor_frame))
{
RectangleD overlap = frame.getIntersect(actor_frame);
RectangleD actor_overlap = actor_frame.getIntersect(frame);
double incr = 1;
if(scale < actor->scale)
{
incr = scale;
}
else
{
incr = actor->scale;
}
TextureImage* img = animation_current->getImage(animation_frame);
if(img == nullptr)
{
throw IllegalStateException("The animation images within SpriteActor have not been loaded through an AssetManager");
}
RectangleU srcRect = animation_current->getImageSourceRect(animation_frame);
TextureImage* actor_img = actor->animation_current->getImage(actor->animation_frame);
if(actor_img == nullptr)
{
throw IllegalStateException("The animation images within SpriteActor have not been loaded through an AssetManager");
}
RectangleU actor_srcRect = actor->animation_current->getImageSourceRect(actor->animation_frame);
bool mirrorHorizontal = false;
if(mirroredHorizontal != animation_current->isMirroredHorizontal())
{
mirrorHorizontal = true;
}
bool mirrorVertical = false;
if(mirroredVertical != animation_current->isMirroredVertical())
{
mirrorVertical = true;
}
bool actor_mirrorHorizontal = false;
if(actor->mirroredHorizontal != actor->animation_current->isMirroredHorizontal())
{
actor_mirrorHorizontal = true;
}
bool actor_mirrorVertical = false;
if(actor->mirroredVertical != actor->animation_current->isMirroredVertical())
{
actor_mirrorVertical = true;
}
PixelIterator*pxlIter = nullptr;
if(rotation == 0)
{
Vector2u dimensions(img->getWidth(), img->getHeight());
pxlIter = new PixelIterator(dimensions, srcRect, frame, overlap, incr, incr, mirrorHorizontal, mirrorVertical);
}
else
{
TransformD transform = rotationMatrix;
transform.translate(-(width/2), -(height/2));
double ratiox = ((double)srcRect.width)/width;
double ratioy = ((double)srcRect.height)/height;
Vector2u dimensions(img->getWidth(), img->getHeight());
pxlIter = new PixelIterator(dimensions, srcRect, frame, overlap, incr, incr, transform, Vector2d(ratiox, ratioy), mirrorHorizontal, mirrorVertical);
}
PixelIterator& pxlIterRef = *pxlIter;
PixelIterator*actor_pxlIter = nullptr;
if(actor->rotation == 0)
{
Vector2u dimensions(actor_img->getWidth(), actor_img->getHeight());
actor_pxlIter = new PixelIterator(dimensions, actor_srcRect, actor_frame, actor_overlap, incr, incr, actor_mirrorHorizontal, actor_mirrorVertical);
}
else
{
TransformD transform = actor->rotationMatrix;
transform.translate(-(actor->width/2), -(actor->height/2));
double ratiox = ((double)actor_srcRect.width)/actor->width;
double ratioy = ((double)actor_srcRect.height)/actor->height;
Vector2u dimensions(actor_img->getWidth(), actor_img->getHeight());
actor_pxlIter = new PixelIterator(dimensions, actor_srcRect, actor_frame, actor_overlap, incr, incr, transform, Vector2d(ratiox, ratioy), actor_mirrorHorizontal, actor_mirrorVertical);
}
PixelIterator& actor_pxlIterRef = *actor_pxlIter;
bool running = pxlIterRef.nextPixelIndex();
bool actor_running = actor_pxlIterRef.nextPixelIndex();
while(running && actor_running)
{
double pxlIndex = pxlIterRef.getCurrentPixelIndex();
double actor_pxlIndex = actor_pxlIterRef.getCurrentPixelIndex();
bool pxlOn = false;
if(pxlIndex >= 0)
{
pxlOn = img->checkPixel((unsigned int)pxlIndex);
}
bool actor_pxlOn = false;
if(actor_pxlIndex >= 0)
{
actor_pxlOn = actor_img->checkPixel((unsigned int)actor_pxlIndex);
}
if(pxlOn && actor_pxlOn)
{
delete pxlIter;
delete actor_pxlIter;
return true;
}
running = pxlIterRef.nextPixelIndex();
actor_running = actor_pxlIterRef.nextPixelIndex();
}
if(running != actor_running)
{
delete pxlIter;
delete actor_pxlIter;
throw Exception("Unknown collision bug. This exception means there is a bug within the SpriteActor::isColliding function");
}
delete pxlIter;
delete actor_pxlIter;
return false;
}
return false;
}
}
| true |
de22387221074454b3ce8824c628ba2d6a4dcc84 | C++ | anshulkataria4/codechef | /LongContest/Jan19/DifferentNeighbours.cpp | UTF-8 | 2,397 | 3.296875 | 3 | [] | no_license | //Different Neighbours Problem Code: DIFNEIGH
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int>> difngb(vector<vector<int>> v,int *k, int curRow, int curCol, int m, int n){
int rowDir[] = {+2, 0, -2, 0, -1, -1, +1, +1};
int colDir[] = {0, -2, 0, +2, -1, +1, +1, -1};
if(v[curRow][curCol]==0){
int value=1;
//check the possible values
bool canplace=true;
while(1){
canplace=true;
for(int p=0;p<8;p++){
int nextRow = curRow + rowDir[p];
int nextCol = curCol + colDir[p];
if((nextRow >=0) && nextRow <n){
if((nextCol>=0) && nextCol < m){
if(value==v[nextRow][nextCol]){
canplace=false;
break;
}
}
}
}
if(canplace==true){
v[curRow][curCol]=value;
if(value> *k){
*k=value;
}
return v;
}
value++;
}
}
else{
return v;
}
}
int main() {
int t,n,m;
//vector<vector<int>> v;
cin>>t;
while(t--){
cin>>n>>m;
vector<vector<int>> v;
int k=0;
v.resize(n);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
v[i].push_back(0);
}
}
int l=0;
if((m>1 && n>1) &&( m<3 || n<3)){
l=3;
}
else
if ((m>2) && (n>2)) {
l=4;
}
//function to call and fill the vector
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
v=difngb(v,&k,i,j,m,n);
//backtrack
if(k>l){
v[i-1][j]++;
for(int p=i-1;p<=i && p<n ;i--){
for(int q=j+1;q <=j && q<m;j--){
v[p][q]=0;
}
}
i=i-1;
j=j+1;
k=l;
}
}
}
//print the result
cout<<k<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<v[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
| true |
b610033995209ab4d273e690a7e995f1a6f35139 | C++ | stackofsugar/orbit-game | /src/Cursor.cpp | UTF-8 | 301 | 2.609375 | 3 | [] | no_license | #include "../include/pch.h"
using namespace std;
Cursor::Cursor() {
m_posX = m_posY = 0;
}
void Cursor::processAndUpdateMovement(int mouseX, int mouseY) {
m_posX = mouseX - (m_width / 2);
m_posY = mouseY - (m_height / 2);
}
void Cursor::render() {
Texture::render(m_posX, m_posY);
} | true |
fb470a8e699d2d6b89ca291b18b35b31a3fb2f77 | C++ | deepak1214/CompetitiveCode | /Codeforces_problems/Dreamoon and WIFI/solution.cpp | UTF-8 | 2,697 | 3.515625 | 4 | [
"MIT"
] | permissive | // The idea is we need to calculate:
// How many '+' sign exists in both 1st string and 2nd string.
// How many '-' sign exists in both 1st string and 2nd string.
// How many '?' sign exists in 2nd string, if there is no '?' sign exist in the second string we need to check if number of '+' signs in
// 1st string equals to the number of '+' signs in 2nd string, we make the same check for '-' sign, if both conditions are true, it
// means that the probility equals one as the two strings have the same count of both '+' and '-' signs, else probility will be zero as
// both string have different count of either '+' or '-' signs.
// If '?' exists in 2nd string, we need to calculate how many '+' and '-' signs we need to add in the 2nd string, in order to
// calculate the number of ways of inserting both signs in 2nd string, since we care about the order of insertion and since we have only
// 2 signs, therefore there may be a reptition, we need to compute Permutations to calculate how many ways of insertions we can make in
// the 2nd string (factorial of totat num of '?' exists in 2nd string / (factorial of total num of '+' needed * factorial of total num of '-' needed))
// we also need to compute the total number of ways to insert both the 2 signs regardless how many '+' or how many '-' needed for 2nd string
// in order to calculate the probiblity needed.
#include<iostream>
#include<vector>
#include<algorithm>
#include <string>
#include<map>
#include<cmath>
#include <iomanip>
using namespace std;
long long int factorial(int n) {
long long int result = 1;
while (n != 0) {
result *= n;
n--;
}
return result;
}
int main() {
string str1, str2;
cin >> str1 >> str2;
int count1Plus = count(str1.begin(), str1.end(), '+');
int count1Minus = count(str1.begin(), str1.end(), '-');
int count2Plus = count(str2.begin(), str2.end(), '+');
int count2Minus = count(str2.begin(), str2.end(), '-');
int count2Mark = str2.length() - (count2Plus + count2Minus);
if (!count2Mark) {
if (count2Plus == count1Plus && count2Minus == count1Minus) {
cout << "1.000000000000";
return 0;
}
else {
cout << "0.000000000000";
return 0;
}
}
int diffPlus = count1Plus - count2Plus;
int diffMinus = count1Minus - count2Minus;
if (diffPlus + diffMinus == count2Mark && diffPlus >= 0 && diffMinus >=0) {
long long int res = factorial(count2Mark);
long long int res1 = factorial(diffPlus);
long long int res2 = factorial(diffMinus);
double result = (double)res /(double) (res1 * res2);
long long int totalWays = pow(2, count2Mark);
cout << fixed;
cout << setprecision(12);
cout << result / (double)totalWays;
}
else cout << "0.000000000000";
return 0;
} | true |
bb614f24ad7abab79ce6e2704d3864f20e6db6e2 | C++ | SyncShinee/ACM-ICPC | /ACMContest/topcoder/SRM633Round1/B.cpp | UTF-8 | 554 | 3.140625 | 3 | [] | no_license | #include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
class ABBA {
public:
string canObtain(string initial, string target) {
int len;
while (target.size() > 0 && target != initial) {
len = target.size();
if (target[len - 1] == 'A') {
target.erase(len-1, 1);
}
else {
target.erase(len-1, 1);
target.assign(target.rbegin(), target.rend());
}
}
if (target == initial) {
return "Possible";
}
return "Impossible";
}
};
int main() {
} | true |
c38a58deb4b78aeab5e02a43dc1511d5187cd18c | C++ | anilchoudhary/DSA | /GFG__2/sorting/merge_sort.cpp | UTF-8 | 978 | 3.328125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void merge(int arr[], int s, int m, int e)
{
int n1 = m - s + 1;
int n2 = e - m;
int arr1[n1 ], arr2[n2 ];
for (int i = 0; i < n1; i++)
{
arr1[i] = arr[i + s];
}
for (int i = 0; i < n2; i++)
{
arr2[i] = arr[m + 1 + i];
}
int i = 0, j = 0; int k = s;
while (i < n1 && j < n2)
{
if (arr1[i] > arr2[j])
{
arr[k++] = arr2[j];
j++;
}
else
{
arr[k++] = arr1[i];
i++;
}
}
while (i < n1)
{
arr[k++] = arr1[i++];
}
while (j < n2)
{
arr[k++] = arr2[j++];
}
}
void merge_sort(int arr[], int s, int e)
{
if (e > s)
{
int m = s + (e - s) / 2;
merge_sort(arr, s, m);
merge_sort(arr, m + 1, e);
merge(arr, s, m, e);
}
}
int main()
{
int arr[] = {3, 4, 5, 7, 8, 2, 1, 6, 7, 75, 63, 2, 1, 34, 76, 54, 31, 65, 535, 34, 6, 75, 3, 432, 53, 725, 4};
int n = sizeof(arr) / sizeof(arr[0]);
merge_sort(arr, 0, n - 1);
for (auto x : arr)
cout << x << " ";
cout << endl;
return 0;
} | true |
cc2f46e4a6c7fdbd85826cb979d3cd7499245b5e | C++ | TobMit/Informatika3 | /Lekcia 3/Triedecka_Zo_Súboru/Data.cpp | UTF-8 | 408 | 2.765625 | 3 | [] | no_license | #include "Data.h"
Data::Data(DataTyp aHodnota, Data* aNasledovnik)
{
hodnota = aHodnota;
nasledovnik = aNasledovnik;
}
int Porovnaj(const void* data1, const void* data2)
{
DataTyp* dptrdata1 = (DataTyp*)data1;
DataTyp* dptrdata2 = (DataTyp*)data2;
return *dptrdata1 - *dptrdata2;
}
int PorovnajKlesajuco(const void* data1, const void* data2)
{
return -Porovnaj(data2, data1);
}
| true |
7337d6b9801733d8afdaa645cc7ca973da2eeb52 | C++ | Nitapol/ASCII_deletion_distance | /distance1.cpp | UTF-8 | 1,545 | 2.90625 | 3 | [] | no_license | // Copyright (c) 2019 Alexander Lopatin. All rights reserved.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
using namespace std;
int fee(const char& c) { return c; }
string& skip_char(string &dst, const string &src, int skip) {
dst.clear();
for (int i = 0; i < src.size(); i++)
if (i != skip)
dst += src[i];
return dst;
}
int distance1(const string &a, const string &b) {
size_t la = a.size();
size_t lb = b.size();
if (la == lb && a == b)
return 0;
int d = __INT_MAX__;
string s;
for (int i = 0; i < la; i++)
d = min(d, fee(a[i]) + distance1(skip_char(s, a, i), b));
for (int i = 0; i < lb; i++)
d = min(d, fee(b[i]) + distance1(a, skip_char(s, b, i)));
return d;
}
#define LOOP 99999
#define LEN 5
int main() {
assert(distance1("bat", "cat") == fee('b') + fee('c'));
assert(distance1("!~!", "~!!") == 2 * fee('!'));
clock_t start = clock();
int n = 0, d = 0;
do {
stringstream ss;
ss << std::setw(LEN) << std::setfill('0') << n;
string s = ss.str();
for (int i = 0; i < LEN+1; i++) {
string a = s.substr(0, i);
string b = s.substr(i);
int da = distance1(a, b);
int db = distance1(b, a);
assert(da == db);
d += da;
}
} while (n++ < LOOP);
n *= 2*(LEN+1);
double t = (clock() - start) / (double) CLOCKS_PER_SEC;
cout << t << "," << d << "," << n << "," << t/n << endl;
return 0;
}
| true |
1af6e91ddd4d01556829f1c297a9f410f9a0e176 | C++ | MaciejWadowski/cpp | /JIMP_AI/lab_2/polybius/Polybius.cpp | UTF-8 | 1,973 | 3.09375 | 3 | [] | no_license | //
// Created by maciej on 11.03.18.
//
#include "Polybius.h"
using namespace std;
string PolybiusCrypt(string _message){
string output = "";
string message;
for(int i = 0; i < _message.size(); i++)
message += tolower(_message[i]);
char tab[5][5];
int count = 0;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
tab[i][j] = 'a' + count;
count++;
if(tab[i][j] == 'i') count++;
}
}
count = 0;
int size = message.size();
while(count < size){
bool flag = true;
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
if(message[count] == tab[i][j]){
string str = to_string(i+1);
string str2 = to_string(j+1);
output += str;
output += str2;
flag = false;
break;
}
}
if(!flag) break;
}
if(message[count] == 'j') output += "24";
count++;
}
return output;
}
string PolybiusDecrypt(string crypted_mes){
string output = "";
char tab[5][5];
int count = 0;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
tab[i][j] = 'a' + count;
count++;
if(tab[i][j] == 'i') count++;
}
}
count = 0;
int size = crypted_mes.size();
while(count+1 < size){
string c1 = "";
c1 += crypted_mes[count];
string c2 = "";
c2 += crypted_mes[count+1];
bool flag = true;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
if(to_string(i+1) == c1 && to_string(j+1) == c2){
output += tab[i][j];
count+=2;
flag = false;
break;
}
}
if(!flag) break;
}
}
return output;
}
| true |
de75945e00de3857e0e8ab9f6d1349ee250758a4 | C++ | GuLinux/NexstarRemotePlus | /buttons.h | UTF-8 | 626 | 2.796875 | 3 | [] | no_license | #include "singleton.h"
#include <Arduino.h>
#pragma once
class Buttons : public Singleton<Buttons> {
public:
typedef void (*Callback)(void);
Buttons();
void setup(int pin);
void click();
void tick();
enum Clicks { NoButton, SingleClick, DoubleClick, TripleClick, LongClick};
void set_callback(Callback callback, Clicks type);
private:
uint8_t pin;
uint8_t _clicks = 0;
uint32_t _last_down_millis = 0;
uint32_t _last_millis = 0;
Clicks _status = NoButton;
Callback on_click = nullptr;
Callback on_double_click = nullptr;
Callback on_triple_click = nullptr;
Callback on_longpress = nullptr;
};
| true |
f705db63fd4cc1eec56a6e100b37c44d831c92fb | C++ | OMER-B/AdvancedProgramming1 | /ex4/src/server/server.cpp | UTF-8 | 3,813 | 3 | 3 | [] | no_license | #include "server.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <arpa/inet.h>
#define BUFFER 10
using namespace std;
#define MAX_CONNECTED_CLIENTS 2
Server::Server(int port) : serverSocket_(0) {
port_ = port;
cout << "Server" << endl;
}
Server::Server(char *fileName) {
ifstream inFile;
inFile.open(fileName);
inFile >> port_;
inFile.close();
cout << "Server port: " << port_ << endl;
}
void Server::start() {
// Create a socket point
serverSocket_ = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket_ == -1) {
throw "Error opening socket";
}
// Assign a local address to the socket
struct sockaddr_in serverAddress;
bzero((void *) &serverAddress,
sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(port_);
if (bind(serverSocket_,
(struct sockaddr *) &serverAddress,
sizeof(serverAddress)) == -1) {
throw "Error on binding";
}
cout << "Binding succeeded." << endl;
// Start listening to incoming connections
listen(serverSocket_, MAX_CONNECTED_CLIENTS);
// Define the client socket's structures
struct sockaddr_in clientAddress;
socklen_t clientAddressLen;
while (true) {
cout << "Waiting for connections..." << endl;
// Accept a new clients connections.
int firstClientSocket = accept(serverSocket_,
(struct sockaddr *) &clientAddress,
&clientAddressLen);
cout << "First client connected" << endl;
if (firstClientSocket == -1) {
throw "Error on first client accept";
}
int secondClientSocket = accept(serverSocket_,
(struct sockaddr *) &clientAddress,
&clientAddressLen);
cout << "Second client connected" << endl;
if (secondClientSocket == -1) {
throw "Error on second client accept";
}
cout << "Game has started" << endl;
handleClient(firstClientSocket, secondClientSocket);
// Close communication with the clients.
// close(firstClientSocket);
// close(secondClientSocket);
}
}
void Server::notifyClients(int clients[]) {
int NUM0 = 0;
int NUM1 = 1;
cout << "Notifying clients who is who." << endl;
ssize_t n = write(clients[0], &NUM0, sizeof(NUM0));
if (n == -1) {
cout << "Error writing to socket" << endl;
return;
}
n = write(clients[1], &NUM1, sizeof(NUM1));
if (n == -1) {
cout << "Error writing to socket" << endl;
return;
}
}
void Server::handleClient(int firstClient, int secondClient) {
int i = 0;
char move[BUFFER];
ssize_t n;
int clients[] = {firstClient, secondClient};
notifyClients(clients);
while (true) {
// Read new point from client.
n = read(clients[(i % 2)], &move, sizeof(move));
if (n == -1) {
cout << "Error reading row" << endl;
break;
}
if (n == 0) {
cout << "Client disconnected" << endl;
break;
}
if (strcmp(move, "0 0") == 0) {
n = write(clients[(i + 1) % 2], &move, sizeof(move));
if (n == -1) {
cout << "Error writing to socket" << endl;
break;
}
cout << "Game has ended by exit from " << clients[(i % 2)] << endl;
break;
}
if (strcmp(move, "-1 -1") != 0) {
cout << "Got move (" << move << ") from " << clients[(i % 2)] << endl;
}
// Write the point back to the other client.
n = write(clients[(i + 1) % 2], &move, sizeof(move));
if (n == -1) {
cout << "Error writing to socket" << endl;
break;
}
i++;
}
}
Server::~Server() {
stop();
}
void Server::stop() {
close(serverSocket_);
}
| true |
cb824ad5dd8e35dbe027110dc55c12feec15ab5a | C++ | shayankarmaly/UCLA-CS32 | /homework2/eval.cpp | UTF-8 | 6,488 | 3.078125 | 3 | [] | no_license | /*#include <iostream>
#include <stack>
#include <cctype>
#include <string>
using namespace std;
bool fin(const bool values[], string& postfix);
int evaluate(string infix, const bool values[], string& postfix, bool& result)
{
postfix = "";
stack<char> stackOp;
int pTracker = 0;
int numCounter = 0;
for (int k = 0; k < infix.size(); k++)
{
switch (infix[k])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
int ind = k;
while (ind > 0 && infix[ind - 1] == ' ')
ind--;
if (ind > 0 && isdigit(infix[ind - 1]))
return 1;
numCounter++;
postfix += infix[k];
break;
}
case '(':
{
int ind = k;
while (ind > 0 && infix[ind - 1] == ' ')
ind--;
if (ind > 0 && isdigit(infix[ind - 1]))
return 1;
pTracker++;
stackOp.push(infix[k]);
break;
}
case '!':
{
stackOp.push(infix[k]);
break;
}
case ')':
{
int ind = k;
while (ind < infix.size() && infix[ind + 1] == ' ')
ind++;
if (ind < infix.size() && isdigit(infix[ind + 1]))
return 1;
pTracker--;
while (! stackOp.empty() && stackOp.top() != '(')
{
postfix += stackOp.top();
stackOp.pop();
}
if (!stackOp.empty())
stackOp.pop();
break;
}
case '&':
case '|':
{
int ind = k;
while (ind > 0 && (infix[ind - 1] == ' ' || infix[ind - 1] == ')'))
ind--;
if (ind == 0 || ! isdigit(infix[ind - 1]))
{
return 1;
}
ind =k;
while (ind < infix.size() && (infix[ind + 1] == ' ' || infix[ind + 1] == '(' || infix[ind + 1] == '!'))
ind++;
if (ind == infix.size() || ! isdigit(infix[ind + 1]))
{
return 1;
}
while (! stackOp.empty() && ! (stackOp.top() == '('))
{
if (infix[k] == '&')
{
if (stackOp.top() == '|')
break;
}
else if (infix[k] == '!')
{
if (stackOp.top() == '|' || stackOp.top() == '&')
break;
}
postfix += stackOp.top();
stackOp.pop();
}
stackOp.push(infix[k]);
break;
}
}
}
if (pTracker != 0 || numCounter == 0)
return 1;
while (! stackOp.empty())
{
postfix += stackOp.top();
stackOp.pop();
}
result = fin(values, postfix);
return 0;
}
bool fin(const bool values[], string& postfix)
{
stack<bool> stackOp;
for (int ind = 0; ind < postfix.size(); ind++)
{
if (isdigit(postfix[ind]))
{
int total = postfix[ind] - '0';
stackOp.push(values[total]);
}
else if (postfix[ind] == '!')
{
bool op1 = stackOp.top();
stackOp.pop();
op1 = !op1;
stackOp.push(op1);
}
else
{
bool op2 = stackOp.top();
stackOp.pop();
bool op1 = stackOp.top();
stackOp.pop();
bool end;
if (postfix[ind] == '&')
{
if (op1 == true && op2 == true)
end = true;
else
end = false;
}
else if (postfix[ind] == '|')
{
if (op1 == false && op2 == false)
end = false;
else
end = true;
}
stackOp.push(end);
}
}
return stackOp.top();
}
int main()
{
bool ba[10] = {
// 0 1 2 3 4 5 6 7 8 9
true, true, true, false, false, false, true, false, true, false
};
string pf;
bool answer;
assert(evaluate("2| 3", ba, pf, answer) == 0 && pf == "23|" && answer);
assert(evaluate("8|", ba, pf, answer) == 1);
assert(evaluate(" &6", ba, pf, answer) == 1);
assert(evaluate("4 5", ba, pf, answer) == 1);
assert(evaluate("01", ba, pf, answer) == 1);
assert(evaluate("()", ba, pf, answer) == 1);
assert(evaluate("()4", ba, pf, answer) == 1);
assert(evaluate("2(9|8)", ba, pf, answer) == 1);
assert(evaluate("2(&8)", ba, pf, answer) == 1);
assert(evaluate("(6&(7|7)", ba, pf, answer) == 1);
assert(evaluate("x+5", ba, pf, answer) == 0);
assert(evaluate("", ba, pf, answer) == 1);
assert(evaluate("2|3|4", ba, pf, answer) == 0
&& pf == "23|4|" && answer);
assert(evaluate("2|(3|4)", ba, pf, answer) == 0
&& pf == "234||" && answer);
assert(evaluate("4 | !3 & (0&3) ", ba, pf, answer) == 0
&& pf == "43!03&&|" && !answer);
assert(evaluate(" 9 ", ba, pf, answer) == 0 && pf == "9" && !answer);
ba[2] = false;
ba[9] = true;
assert(evaluate("((9))", ba, pf, answer) == 0 && pf == "9" && answer);
assert(evaluate("2| 3", ba, pf, answer) == 0 && pf == "23|" && !answer);
cout << "Passed all tests" << endl;
}
*/ | true |
6debd0e00f2e70b0cd773fbeb0fe847476c82c17 | C++ | mverwe/diall | /interface/rhoMCWeights.h | UTF-8 | 2,628 | 2.71875 | 3 | [
"CC0-1.0"
] | permissive | #ifndef rhoMCWeights_h
#define rhoMCWeights_h
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "TFile.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TString.h"
#include <fstream>
using namespace std;
class rhoMCWeights
{
private:
TString fNameWeightFileCent0 = "/afs/cern.ch/user/m/mverweij/work/PbPb5TeV/mc/subjet/rhoWeightFiles/rhoWeightsCent0.txt";
TString fNameWeightFileCent1 = "/afs/cern.ch/user/m/mverweij/work/PbPb5TeV/mc/subjet/rhoWeightFiles/rhoWeightsCent1.txt";
TString fNameWeightFileCent2 = "/afs/cern.ch/user/m/mverweij/work/PbPb5TeV/mc/subjet/rhoWeightFiles/rhoWeightsCent2.txt";
TString fNameWeightFileCent3 = "/afs/cern.ch/user/m/mverweij/work/PbPb5TeV/mc/subjet/rhoWeightFiles/rhoWeightsCent3.txt";
public:
rhoMCWeights() {}
void set_file_names(TString cent0, TString cent1, TString cent2, TString cent3) {
fNameWeightFileCent0 = cent0;
fNameWeightFileCent1 = cent1;
fNameWeightFileCent2 = cent2;
fNameWeightFileCent3 = cent3;
}
double getWeights(double cent, double rhoCur) {
TString nameFile = "";
int centBin = getCentBin(cent);
if(centBin==0) nameFile = fNameWeightFileCent0;
else if(centBin==1) nameFile = fNameWeightFileCent1;
else if(centBin==2) nameFile = fNameWeightFileCent2;
else if(centBin==3) nameFile = fNameWeightFileCent3;
else {return 0.;}
double weightOld = 0.;
double rhoOld = -1.;
std::string line;
ifstream inputFile(nameFile.Data());
if(inputFile.is_open()) {
while(getline(inputFile,line)) {
std::stringstream ss(line);
float rho, weight;
if(ss >> rho >> weight) {
//Printf("rho: %f weight: %f",rho,weight);
if(rhoCur>rhoOld && rhoCur<=rho) {
//Printf("Looking for this weight rhoCur: %f rho: %f weight: %f",rhoCur,rho,weight);
double slope = (weight-weightOld)/(rho-rhoOld);
double interpolated_weight = weightOld + (rhoCur-rhoOld)*slope;
//Printf("interpolated_weight: %f",interpolated_weight);
inputFile.close();
return interpolated_weight;
}
weightOld = weight;
rhoOld = rho;
}
}
}
inputFile.close();
return 0.;
}
int getCentBin(double cent) {
int fCentBin = 0;
double offset = 2.;
double centMin[4] = {0.+offset ,10.+offset,30.+offset,50.+offset};
double centMax[4] = {10.+offset,30.+offset,50.+offset,80.+offset};
for(int i = 0; i<4; ++i) {
if(cent>=centMin[i] && cent<centMax[i]) fCentBin = i;
}
return fCentBin;
}
};
#endif
| true |
b7d86de172350cdf93149511f59ab5ab9012abe4 | C++ | rfcosta85/CursoCPlusPlus | /exemplosEstacio/estrutura_de_dados/exemplos_aula03/exemplo001.cpp | UTF-8 | 358 | 2.625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
struct coordenadas
{
int x, y;
};
coordenadas a = {-5,2}, b = {6,5};
cout << "\nCoordenadas de a("<< a.x <<","<< a.y <<")";
cout << "\nCoordenadas de b("<< b.x <<","<< b.y <<")";
cout << "\n\n";
getchar;
getchar;
} | true |
e3172f7b4fce53864f46614a8f3d56624c3787fa | C++ | LeonardoFassini/Competitive-Programming | /CodeForces/271A-TIMMY.cpp | UTF-8 | 641 | 3.046875 | 3 | [] | no_license | #include <cstdio>
char a, b, c, d;
void aumenta1(char &a, char &b, char &c, char &d){
if(d == '9'){
d = '0';
if(c == '9'){
c = '0';
if(b == '9'){
b = '0';
if(a == '9'){
a = '0';
printf("1");
}
else a++;
}
else b++;
}
else c++;
}
else d++;
}
int main(void){
char ano[3];
int distintos = 0;
scanf("%s", ano);
a = ano[0];
b = ano[1];
c = ano[2];
d = ano[3];
aumenta1(a, b, c, d);
while(!distintos){
if(a != b && a != c && a != d && b != c && b != d && c != d){ distintos = 1; }
else aumenta1(a, b, c, d);
}
printf("%c%c%c%c\n", a, b, c, d);
return 0;
}
| true |
61a5a4bcb3be5542f4ff611b1aedb1c852f3a2af | C++ | xuermin/leetcode | /countAndsay/countAndsay.cpp | GB18030 | 517 | 3.390625 | 3 | [] | no_license | // countAndsay.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
string countAndSay(int n) {
string output,str;
if (n == 1) {
return "1";
}
str = countAndSay(n - 1);
int count = 1;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == str[i + 1])
count++;
else {
output = output + static_cast<char>(count + '0') + str[i];
count = 1;
}
}
return output;
}
int main()
{
cout << countAndSay(6);
return 0;
}
| true |
461d5da96164ee9d3ded3a8b245a6dd25a3e64c7 | C++ | ArgishtiAyvazyan/DistanceCalculator | /src/IO/CLIParser.cc | UTF-8 | 5,669 | 2.90625 | 3 | [
"MIT"
] | permissive | /**
* @file CLIParser.cc
* @author Argishti Ayvazyan (ayvazyan.argishti@gmail.com)
* @brief Implementation for cli::Parser.
* @date 03-11-2020
* @copyright Copyright (c) 2020
*/
#include "CLIParser.h"
#include <sstream>
#include <iostream>
#include <string_view>
using namespace std::string_view_literals;
namespace
{
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
} // unnamed namespace
io::cli::Parser::Parser() noexcept
: m_argc(0),
m_argv(nullptr)
{ }
io::cli::Parser::Parser(int argc, char** argv, std::string description) noexcept
: m_argc(argc),
m_argv(argv),
m_strApplicationDescription(std::move(description))
{ }
void io::cli::Parser::addOption(
std::string optionName,
const TValueRef& valueRef,
TValue defaultValue, std::string description)
{
ASSERT_ERROR(((callBackIndex == valueRef.index())
|| (callBackWithArgumentIndex == valueRef.index())
|| (requireIndex == defaultValue.index())
|| (valueRef.index() == defaultValue.index()))
, "The value type is not equal to the default value type.");
std::optional<TValue> defValue = std::nullopt;
if (requireIndex != defaultValue.index())
{
defValue.emplace(std::move(defaultValue));
}
[[maybe_unused]] auto [option, inserted] = m_mapOptionNameToValueDefinition.emplace(std::move(optionName)
, ValueDefinition { valueRef, std::move(defValue), std::move(description) });
ASSERT_ERROR(inserted, ("The option is already registered: "s + option->first).c_str());
}
bool io::cli::Parser::parse()
{
return parse(m_argc, m_argv);
}
bool io::cli::Parser::parse(int argc, char** argv)
{
if ((2 == argc) && ("-help"sv == std::string_view {argv[1]}))
{
auto helpMessage = makeHelpMessage();
std::cout << helpMessage << std::endl;
// Exit
return false;
}
for (int i = 1; i < argc; ++i)
{
auto search = m_mapOptionNameToValueDefinition.find(argv[i]);
ASSERT_ERROR (search != std::end(m_mapOptionNameToValueDefinition),
("Invalid option: "s + argv[i]).c_str());
ASSERT_ERROR (search->second.initialized == false
, ("The option is duplicated: "s + argv[i]).c_str());
search->second.initialized = true;
std::visit(overloaded {
[&i, &argv](std::reference_wrapper<std::string>& out) { ++i; stringToValue (out, argv[i]); },
[](std::reference_wrapper<bool>& out) { out.get() = true; },
[&i, &argv](std::reference_wrapper<int>& out) { ++i; stringToValue (out, argv[i]); },
[&i, &argv](std::reference_wrapper<double>& out) { ++i; stringToValue (out, argv[i]); },
[](TCallBack& callBack) { callBack(); },
[&i, &argv](TCallBackWithArgument& callBack) { ++i; callBack(argv[i]); },
}, search->second.valueRef);
search->second.initialized = true;
}
for (auto& [optionName, optionDefinition] : m_mapOptionNameToValueDefinition)
{
if (optionDefinition.initialized)
{
continue;
}
ASSERT_ERROR (optionDefinition.defaultValue.has_value()
, ("The "s + optionName + " option value is required."s).c_str());
std::visit(overloaded {
[def = &optionDefinition](std::reference_wrapper<std::string>& out) {
out.get() = std::get<std::string>(def->defaultValue.value());
},
[def = &optionDefinition](std::reference_wrapper<bool>& out) {
out.get() = std::get<bool>(def->defaultValue.value());
},
[def = &optionDefinition](std::reference_wrapper<int>& out) {
out.get() = std::get<int>(def->defaultValue.value());
},
[def = &optionDefinition](std::reference_wrapper<double>& out) {
out.get() = std::get<double>(def->defaultValue.value());
},
[]( [[maybe_unused]] TCallBack& callBack) { },
[def = &optionDefinition](TCallBackWithArgument& callBack) {
callBack(std::get<std::string>(def->defaultValue.value()));
},
}, optionDefinition.valueRef);
}
return true;
}
void io::cli::Parser::stringToValue(std::reference_wrapper<double>& out, const char* in)
{
double value;
std::istringstream ss { in };
ss >> value;
ASSERT_ERROR(!ss.fail(), ("The"s + in + " to double conversion is failed.").c_str());
out.get() = value;
}
std::string io::cli::Parser::makeHelpMessage() const
{
std::stringstream ssHelp;
if (!m_strApplicationDescription.empty())
{
ssHelp << m_strApplicationDescription << std::endl << std::endl;
}
for (const auto&[optionName, optionDefinition] : m_mapOptionNameToValueDefinition)
{
ssHelp << optionName << ": " << optionDefinition.strDescription << std::endl << std::endl;
}
ssHelp << std::endl;
return std::move(ssHelp).str();
}
void io::cli::Parser::stringToValue(std::reference_wrapper<int>& out, const char* in)
{
int value;
std::istringstream ss { in };
ss >> value;
ASSERT_ERROR(!ss.fail(), ("The"s + in + " to int conversion is failed.").c_str());
out.get() = value;
}
void io::cli::Parser::stringToValue(std::reference_wrapper<std::string>& out, const char* in)
{
out.get() = std::string(in);
}
| true |
3c580811080a2c581f927e4d236f69415992fcc6 | C++ | mojoe12/UVa | /doyourownhomework.cpp | UTF-8 | 691 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <map>
using namespace std;
int main(int argc, char *argv[]) {
int k;
cin >> k;
for (int c = 1; c <= k; c++) {
int n;
cin >> n;
map<string, int> subjects;
for (int i = 0; i < n; i++) {
string subject;
int duration;
cin >> subject >> duration;
subjects.insert( make_pair(subject, duration) );
}
int d;
cin >> d;
string subjectdue;
cin >> subjectdue;
cout << "Case " << c << ": ";
if (subjects.count(subjectdue)) {
int time = subjects[subjectdue];
if (time <= d) cout << "Yesss\n";
else if (time <= d+5) cout << "Late\n";
else cout << "Do your own homework!\n";
}
else cout << "Do your own homework!\n";
}
} | true |
64f2539d15fa1e618549743cc0bba33aea80d3b5 | C++ | irtefa/algo | /codeforces/businessTrip.cc | UTF-8 | 422 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int i, n, m, t = 0;
vector<int> v;
cin >> n;
for (i = 0; i < 12; i++) {
cin >> m;
v.push_back(m);
}
sort(v.rbegin(), v.rend());
for (i = 0; i < v.size(); i++) {
if (t >= n) { cout << i; return 0; }
t += v[i];
}
if (t >= n) cout << i;
else cout << -1;
}
| true |
c6564bb9c0746920725697e0bfe538a2116eee0f | C++ | monaco89/C-Programs | /prime numbers/prime numbers/main.cpp | UTF-8 | 504 | 2.859375 | 3 | [] | no_license | //
// main.cpp
// prime numbers
//
// Created by Nick Monaco on 3/13/13.
// Copyright (c) 2013 Nick Monaco. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
for (int i=2; i<100; i++)
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
break;
else if (j+1 > sqrt(i))
{
cout<< i << " ";
}
}
system("pause");
return 0;
}
| true |
43770fb41b16be7c82b81fdc15d68edc1a8f1fe0 | C++ | Kareliavs/Jumping-bits | /TRABAJO CON CLASE/main.cpp | ISO-8859-1 | 5,443 | 2.59375 | 3 | [] | no_license | #include <allegro.h>
#include "inicia.h"
#include <iostream>
#define MAXFILAS 21
#define MAXCOLUMNAS 82
using namespace std;
//usaremos las variables MAX para hacer una matriz
//que contendran los bloques en x 30 en y 19 y 100pre se deja 1 mas
//de espacios en el vector
BITMAP *buffer;
BITMAP *fondo;
BITMAP *muro;
BITMAP *personaje;
BITMAP *monigote;
BITMAP *comida;
//Declaramos 3 variables int para controlar la pos del muquito y la bala
static int score;
static int variable=0;
int direccion=0;
int px=30*10;//no se por q
int py=30*10;
//def la matriz
char mapa[MAXFILAS][MAXCOLUMNAS]={
" ",
" ",
" o o ",
" ",
" ",
" ",
" xxo xxxxx xxx o xxxxx xxx ",
" xx xxxxx xxx xxxxx xxx ",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
" ",
" ",
" o o o ",
" o ",
" o ",
" o ",
" xx xxx xxxx xx xxx o",
" xx xxx xxxx xx xxx ",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};//se pone NO OLVIDAR
void dibujar_mapa(){
int row,col;
//buscara en todas las filas donde halla x y q si hay q cargue los muros
for(row=0;row<MAXFILAS;row++)
{
for(col=0;col<MAXCOLUMNAS;col++)
{
if(mapa[row][col]=='x')
{
draw_sprite(buffer,muro,(col+variable)*30,row*30);
}
else if(mapa[row][col]=='o')
{
draw_sprite(buffer,comida,(col+variable)*30,row*30);//siempre por el tamao de IMG
if(px/30==col &&py/30==row)//si pacman esta en esa posicion DEBEMOS DIVIDR /30
{
mapa[row][col]=' ';
score++;
}
}
}
}
}
void pantalla()
{
blit(buffer,screen,0,0,0,0,900,570) ;
//blit(fondo,buffer,0,0,0,0,900,570);
}
//funcion que dibuja al pacman
void dibujar_monigote()
{ //desde donde cogemos el pacman en x y y la sotras 3 las medidas del pacman
blit(monigote,personaje,direccion*33,0,0,0,33,33);//imprimimos la img del monigote sobre el peqobuffer "personaje" cewamos
//el resto de coordenadas es desde donde vamos a agarrar una parte de la tira y la dejamos caer
draw_sprite(buffer,personaje,px,py);//para q se respete la trasnparencia del pacman dibujo y el buffer
}
int main()
{
allegro_init();
install_keyboard();
set_color_depth(32);
//iniciamis pantalla de Allegro
set_gfx_mode(GFX_AUTODETECT_WINDOWED,900,570,0,0);
//el tamao de pantalla multiplicado por "30" X los MAX
buffer = create_bitmap(900,570);//crea la ventana
fondo = load_bitmap("escenario_2.bmp",NULL);
muro=load_bitmap("murito_2.bmp",NULL);
//cargamos las IMG del personage y monigote
monigote=load_bitmap("pacman.bmp",NULL);
personaje=create_bitmap(33,33);//fuffer
comida=load_bitmap("Comida.bmp",NULL);
while(!key[KEY_ESC])
{
blit(fondo,buffer,0,0,0,0,900,570);
variable-=1;
//CUIDADO
if(key[KEY_LEFT])
{
direccion=0;
}
else if(key[KEY_RIGHT])
{
direccion=1;
}
else if(key[KEY_UP])
{
direccion=2;
}
else if(key[KEY_DOWN])
{
direccion=3;
}
if(direccion==0)
if(mapa[py/30][(px-30)/30]!='x')
px-=30;
else direccion=4; //no hara mov aluno ya q no existe direccion=4
if(direccion==1)
if(mapa[py/30][(px+30)/30]!='x')
px+=30;
else direccion=4;
if(direccion==2)
if(mapa[(py-30)/30][(px)/30]!='x')
py-=30;
else direccion=4;
if(direccion==3)
if(mapa[(py+30)/30][(px)/30]!='x')
py+=30;
else direccion=4;
//clear(buffer);//limpiara pantalla
if(variable==(MAXCOLUMNAS)*(-1))
{
variable=30;
cout<<"HOL";
}
dibujar_mapa();
dibujar_monigote();
pantalla();//imprimimos todo en pantalla
rest(70);
clear(personaje);//aqui hacemos clear sobre el boffer del personaje asi q no afecta en si a la pantalla
blit(monigote,personaje,4*33,0,0,0,33,33);//imprimira bolita cerrada
draw_sprite(buffer,personaje,px,py);
pantalla();
rest(90);
}
readkey();
destroy_bitmap(buffer);
cout<<"your score"<<score<<endl;
return 0;
}
END_OF_MAIN();
| true |
2dd5b45898d8c0909d5859318366ea0351aef196 | C++ | chm994483868/AlgorithmExample | /Algorithm_C/OfferReview/01_38/24_ReverseList/ReverseList_1.hpp | UTF-8 | 706 | 2.71875 | 3 | [] | no_license | //
// ReverseList_1.hpp
// OfferReview
//
// Created by CHM on 2020/11/4.
// Copyright © 2020 CHM. All rights reserved.
//
#ifndef ReverseList_1_hpp
#define ReverseList_1_hpp
#include <stdio.h>
#include <stdlib.h>
#include "List.hpp"
using namespace List;
namespace ReverseList_1 {
// 24:反转链表
// 题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
ListNode* reverseList(ListNode* pHead);
// 测试代码
ListNode* Test(ListNode* pHead);
// 输入的链表有多个结点
void Test1();
// 输入的链表只有一个结点
void Test2();
// 输入空链表
void Test3();
void Test();
}
#endif /* ReverseList_1_hpp */
| true |
8a462e07b6d4d7917eb484451cf20859c9130943 | C++ | xtay315/RedBook8th | /RedBook8th/Examples/Ex07_lights.cpp | UTF-8 | 2,413 | 2.546875 | 3 | [] | no_license | /*
* Ex07_lights.cpp
*
* Created on: Feb 25, 2014
* Author: Andrew Zhabura
*/
#include "Ex07_lights.h"
#include "GL/LoadShaders.h"
#include "Auxiliary/vmath.h"
#include "Auxiliary/vermilion.h"
Ex07_lights::Ex07_lights()
: OGLWindow("Ex07_lights", "Ex 07-lights (M)")
{
}
Ex07_lights::~Ex07_lights()
{
glUseProgram(0);
glDeleteProgram(render_prog);
}
void Ex07_lights::InitGL()
{
if (! LoadGL() )
return;
ShaderInfo render_shaders[] = {
{ GL_VERTEX_SHADER, "Shaders/sh07_lights.vert" },
{ GL_FRAGMENT_SHADER, "Shaders/sh07_lights.frag" },
{ GL_NONE, NULL }
};
render_prog = LoadShaders( render_shaders );
glLinkProgram(render_prog);
mv_mat_loc = glGetUniformLocation(render_prog, "model_matrix");
prj_mat_loc = glGetUniformLocation(render_prog, "proj_matrix");
col_amb_loc = glGetUniformLocation(render_prog, "color_ambient");
col_diff_loc = glGetUniformLocation(render_prog, "color_diffuse");
col_spec_loc = glGetUniformLocation(render_prog, "color_specular");
object.LoadFromVBM("Media/torus.vbm", 0, 1, 2);
}
void Ex07_lights::Display()
{
static const unsigned int start_time = GetTickCount() - 50000;
float t = float((GetTickCount() - start_time)) / float(0x3FFF);
static const vmath::vec3 X(1.0f, 0.0f, 0.0f);
static const vmath::vec3 Y(0.0f, 1.0f, 0.0f);
static const vmath::vec3 Z(0.0f, 0.0f, 0.8f);
vmath::mat4 mv_matrix(vmath::mat4::identity());
vmath::mat4 prj_matrix(vmath::mat4::identity());
mv_matrix = vmath::translate(vmath::vec3(0.0f, 0.0f, -70.0f)) *
vmath::rotate(80.0f * 3.0f * t, Y) * vmath::rotate(50.0f * 3.0f * t, Z);
float aspect = float(getHeight()) / getWidth();
prj_matrix = vmath::perspective(35.0f, 1.0f / aspect, 0.1f, 100.0f) * mv_matrix;
glUseProgram(render_prog);
glUniformMatrix4fv(mv_mat_loc, 1, GL_FALSE, mv_matrix);
glUniformMatrix4fv(prj_mat_loc, 1, GL_FALSE, prj_matrix);
// Clear, select the rendering program and draw a full screen quad
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
object.Render();
Swap();
}
void Ex07_lights::keyboard( unsigned char key, int x, int y )
{
switch( key ) {
case 'M':
for (int i = 0; i < c_repeat; ++i)
Display();
break;
default:
OGLWindow::keyboard(key, x, y);
break;
}
}
| true |
3be8fc9864871dbaeb16c2b2a2034a5f110e8311 | C++ | Denis1697/Somegame | /Mage.h | UTF-8 | 368 | 3.1875 | 3 | [] | no_license | #pragma once
#include "Character.h"
class Mage : public Character
{
private:
public:
Mage(char * name, int HP, int attackDamage) : Character(name, HP, attackDamage)
{
_intelligence = 7;
_strength = 2;
_agility = 3;
_attackDamage =
attackDamage +
((float)_intelligence * 0.9) +
((float)_agility * 0.1) +
((float)_strength * 0.1);
}
}; | true |
0486905d04bd7a933cf06f0f7e412e6b80e234c0 | C++ | stanleyhon/COMP-four-one-two-eight | /w4/triangle/t.cpp | UTF-8 | 2,067 | 3.671875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int array[100][100];
int dp[100][100];
int totalRows;
void dpGo (int row, int col);
int main(int argc, char **argv)
{
for (int i = 0; i != 100; ++i) {
for (int j = 0; j != 100; ++j) {
array[i][j] = -1;
dp[i][j] = -1;
}
}
cin >> totalRows;
int input;
int currentRow = 0;
int currentColumn = 0;
while (cin >> input) {
// cout << "READ " << input << "\n";
// cout << "WRITE " << currentColumn << " " << currentRow << "\n";
array[currentColumn][currentRow] = input;
currentColumn++;
// row 0 reads 1 things, row 3 reads 4 things
if (currentColumn > currentRow) {
// we've already done "currentColumn" things.
// go up a row
currentRow++;
currentColumn = 0;
}
}
// for (int i = 0; i < 10; i++) {
// for (int j = 0; j < 10; j++) {
// cout << array[i][j] << " ";
// }
// cout << "\n";
// }
dpGo(0,0);
cout << dp[0][0];
return 0;
}
void dpGo (int row, int col) {
if (dp[col][row] == -1) {
if (row == totalRows - 1) {
// cout << "found a bottom one, just putting ourselves " << array[col][row] << " in DP table\n";
dp[col][row] = array[col][row];
return;
} else {
// figure out the best to our left
// and the best to our right
dpGo(row+1,col);
dpGo(row+1,col+1);
// choose the larger
// cout << "comparing " << dp[col][row+1] << " and " << dp[col+1][row+1] << "\n";
if (dp[col][row+1] >= dp[col+1][row+1]) {
// cout << "chose left val " << dp[col][row+1] << "\n";
dp[col][row] = dp[col][row+1] + array[col][row];
} else {
// cout << "chose right " << dp[col+1][row+1] << "\n";
dp[col][row] = dp[col+1][row+1] + array[col][row];
}
}
}
return;
}
| true |
d941d26a959d10fdf6084655100feeff723acda6 | C++ | gkampitakis/mortal-kombat-arcade | /MortalKombat/SpriteHolder.h | UTF-8 | 410 | 2.828125 | 3 | [] | no_license | #include <Sprite.h>
typedef list<Sprite*> SpriteList;
class SpriteHolder {
private:
static SpriteHolder* holder;
protected:
typedef map<unsigned, SpriteList> SpritesByType;
SpritesByType sprites;
public:
SpriteHolder(void) {};
~SpriteHolder() { CleanUp(); };
static SpriteHolder* Get(void);
void Add(Sprite* s);
void Remove(Sprite* s);
SpriteList GetSprites(unsigned type)const;
void CleanUp();
}; | true |
611d572ac3e9b5eea4051739e673775295396646 | C++ | NorilskUshakova/MaxLab | /Source.cpp | UTF-8 | 755 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class DataTime
{
int sec(int god1, int mes1, int den1, int chas1 = 0, int min1 = 0, int sec1 = 0)
{
int god_l1 = god1 - 1970;
int god_l2 = (god_l1 / 4) + 0.5;
int den = god_l1 * 365 + god_l2;
switch (mes1)
{
case 1: den += 31; break;
case 2: den += 69; break;
case 3: den += 90; break;
case 4: den += 120; break;
case 5: den += 151; break;
case 6: den += 181; break;
case 7: den += 212; break;
case 8: den += 243; break;
case 9: den += 273; break;
case 10: den += 304; break;
case 11: den += 334; break;
case 12: den += 365; break;
};
if (god1 % 4)den++;
den += den1;
int sec = den * 86400;
sec += chas1 * 3600;
sec += min1 * 60;
sec += sec1;
return sec;
}
}; | true |
28f93eeaa142cc0815d2ef1e22a9e31aef69bc76 | C++ | asdlei99/khaki | /example/echo.cpp | UTF-8 | 1,772 | 2.75 | 3 | [] | no_license | #include "../khaki.h"
#include <map>
class EchoServer {
public:
EchoServer(khaki::EventLoop* loop, std::string host, int port, int threadNum) :
server_(loop, host, port, threadNum) {
server_.setReadCallback(std::bind(&EchoServer::OnMessage,
this, std::placeholders::_1));
server_.setConnectionCallback(std::bind(&EchoServer::OnConnection,
this, std::placeholders::_1));
server_.setConnCloseCallback(std::bind(&EchoServer::OnConnClose,
this, std::placeholders::_1));
}
void start() {
server_.start();
}
void OnConnection(const khaki::TcpClientPtr& con) {
std::cout << "OnConnection online num : " << server_.getOnlineNum() << std::endl;
std::unique_lock<std::mutex> lck(mtx_);
sessionLists_.insert(std::make_pair(con->getFd(), khaki::TcpWeakPtr(con)));
}
void OnConnClose(const khaki::TcpClientPtr& con) {
std::cout << "OnConnClose online num : " << server_.getOnlineNum() << std::endl;
std::unique_lock<std::mutex> lck(mtx_);
sessionLists_.erase(con->getFd());
}
void OnMessage(const khaki::TcpClientPtr& con) {
khaki::Buffer tmp(con->getBuf());
broadcastMsg(tmp);
}
void broadcastMsg(khaki::Buffer& msg) {
std::unique_lock<std::mutex> lck(mtx_);
for (auto s : sessionLists_) {
khaki::Buffer tmp(msg);
khaki::TcpClientPtr c = s.second.lock();
if(c) {
c->send(tmp);
}
}
}
private:
khaki::TcpThreadServer server_;
std::mutex mtx_;
std::unordered_map<int, khaki::TcpWeakPtr> sessionLists_;
};
int main( int argc, char* argv[] )
{
khaki::EventLoop loop;
khaki::InitLog(khaki::logger, "./echo.log", log4cpp::Priority::DEBUG);
EchoServer echo(&loop, "127.0.0.1", 9527, 4);
echo.start();
loop.loop();
return 0;
} | true |
cc7d8b151af1d0c6feaeb62ab9ed489bf5f1c122 | C++ | cyrilmaitre/white_hole | /src/space_2/LootItemModel.h | UTF-8 | 799 | 2.5625 | 3 | [] | no_license | #pragma once
#include "Item.h"
// Define
#define LOOTITEMMODEL_CONFIG_ID "id"
#define LOOTITEMMODEL_CONFIG_ITEM "item"
#define LOOTITEMMODEL_CONFIG_QUANITYMIN "quantity_min"
#define LOOTITEMMODEL_CONFIG_QUANITYMAX "quantity_max"
class LootItemModel
{
public:
// Constructor - Destructor
LootItemModel(KeyValueFile* p_config);
~LootItemModel(void);
// Getters - Setters
long getIdLootItemModel();
void setIdLootItemModel(long p_id);
Item* getItem();
void setItem(Item* p_item);
int getQuantityMin();
void setQuantityMin(int p_min);
int getQuantityMax();
void setQuantityMax(int p_max);
// Methods
int generateQuantity();
void loadFromConfig(KeyValueFile* p_config);
private:
// Attributs
long mIdLootItemModel;
Item* mItem;
int mQuantityMin;
int mQuantityMax;
};
| true |
0d3f74515ebae192bcfd36c00bb18352ad999737 | C++ | charleschang213/VE281 | /Projects/p4/orderbook.h | UTF-8 | 1,131 | 2.546875 | 3 | [] | no_license | #ifndef ORDERBOOK_H
#define ORDERBOOK_H
#include <vector>
#include <unordered_map>
#include <string>
#include "equity.h"
#include "client.h"
class orderbook{
std::unordered_map<std::string,int> ename,cname;
std::priority_queue<std::string,std::vector<std::string>,std::greater<std::string> > ordered_ename,ordered_cname;
std::vector<equity> equities;
std::vector<client> clients;
std::vector<std::string> tttnames;
bool midpoint,median,transfer,verbose;
int timestamp,income,transferred,completed,cshare;
public:
order order_generate(int oid,std::string line);
orderbook(bool midpoint,bool median,bool transfer,bool verbose,std::vector<std::string> tttnames):
midpoint(midpoint),median(median),transfer(transfer),verbose(verbose),tttnames(tttnames),
ename(),cname(),ordered_ename(),ordered_cname(),equities(),clients(),timestamp(0),income(0),transferred(0),completed(0),cshare(0){}
void order_execute(order neworder);
void endofday();
void endoftime(int ts=-1);
int getts(){return timestamp;}
};
#endif | true |
5a7f2f773fbb2432f885d4107e53865f48ee79dd | C++ | konrad99fgf/ds | /Pilkarz.cpp | WINDOWS-1250 | 1,229 | 2.703125 | 3 | [] | no_license | #include "Pilkarz.h"
#include <fstream>
#include <iostream>
Pilkarz::Pilkarz()
{
//ctor
}
Pilkarz::~Pilkarz()
{
//dtor
}
void Pilkarz::wczytaj_pilkarza(std::fstream & plik)
{
plik>>imie;
plik>>nazwisko>>wiek;
plik>>narodowosc;
std::string poz;
plik>>poz;
wczytajpozycje(poz);
plik>>umiejetnosci;
//std::cout<<imie<<nazwisko<<narodowosc<<umiejetnosci<<wiek<<pokaz_jaka_pozycja();
}
void Pilkarz::wczytajpozycje(std::string k)
{
if(k=="Bramkarz")
{
pozycja_zawodnika=bramkarz;
}
else if(k=="Obroca")
{
pozycja_zawodnika=obronca;
}
else if(k=="Pomocnik")
{
pozycja_zawodnika=pomocnik;
}
else
{
pozycja_zawodnika=napastnik;
}
}
std::string Pilkarz::pokaz_jaka_pozycja()
{
std::string q;
if(pozycja_zawodnika==bramkarz)
{ q="bramkarz";
return q;
}
else if(pozycja_zawodnika==obronca)
{
q="obroca";
return q;
}
else if(pozycja_zawodnika==pomocnik)
{
q="pomocnik";
return q;
}
else
{
q="napastnik";
return q;
}
}
| true |
076387346039d5c12cd294f5e2a79486ef936b2f | C++ | core2062/CORE2017 | /src/Robot.cpp | UTF-8 | 3,432 | 2.734375 | 3 | [] | no_license | #include "Robot.h"
using namespace CORE;
//shared_ptr<CORE2017> Robot = nullptr;
CORE2017 * Robot = nullptr;
CORE2017::CORE2017() :
driveSubsystem(),
hopperSubsystem(),
climberSubsystem(),
gearSubsystem(),
driveTeleController(),
driveGyroController(),
intakeController(),
driverJoystick(0),
operatorJoystick(1)
{
// Robot.shared_ptr(this);
Robot = this;
}
void CORE2017::robotInit() {
setLoopTime(.0125);
}
void CORE2017::teleopInit() {
if(driveWaypointController == nullptr){
driveWaypointController = new DriveWaypointController();
}
driveSubsystem.setController(&driveTeleController);
driveTeleController.enable();
}
void CORE2017::teleop(){
// testMotor.Set(0);
// CORELog::logInf//o("m_encoder Pos: " + to_string(testMotor.m_encoder->GetEncPos()));
// CORELog::logInfo("m_encoder Vel: " + to_string(testMotor.m_encoder->GetEncVel()));
// CORELog::logInfo("m_encoder Accel: " + to_string(testMotor.m_encoder->GetEncAccel()));
}
void CORE2017::test(){
//Lift Test Code
double liftVal = 0.0;
if(operatorJoystick.getButton(CORE::COREJoystick::JoystickButton::DPAD_N)){
liftVal += .25;
}
if(operatorJoystick.getButton(CORE::COREJoystick::JoystickButton::DPAD_S)){
liftVal -=.25;
}
double oldLiftVal = liftVal;
double liftDeltaEnc = hopperSubsystem.getLiftSpeed();
if(abs(((liftDeltaEnc > 0) - (liftDeltaEnc < 0)) - ((oldLiftVal > 0) - (oldLiftVal < 0))) == 2){
std::cout << "Encoder speed and power don't match!" << std::endl;
}
hopperSubsystem.setLift(liftVal);
//Servo Flap Code
if(operatorJoystick.getButton(CORE::COREJoystick::JoystickButton::A_BUTTON)){
hopperSubsystem.openFlap();
} else {
hopperSubsystem.closeFlap();
}
//Pneumatic Flap Code
if(operatorJoystick.getButton(CORE::COREJoystick::JoystickButton::B_BUTTON)){
gearSubsystem.openFlap();
} else {
gearSubsystem.closeFlap();
}
//Intake Code
if(operatorJoystick.getButton(CORE::COREJoystick::JoystickButton::LEFT_BUTTON)){
hopperSubsystem.setIntake(.5);
} else if(operatorJoystick.getButton(CORE::COREJoystick::JoystickButton::RIGHT_BUTTON)){
hopperSubsystem.setIntake(-.5);
} else {
hopperSubsystem.turnOffIntake();
}
//Climber Code
double climbUpVal = abs(operatorJoystick.getAxis(CORE::COREJoystick::JoystickAxis::LEFT_STICK_Y));
double climbDownVal = abs(operatorJoystick.getAxis(CORE::COREJoystick::JoystickAxis::RIGHT_STICK_Y));
climbUpVal *= .25;
climbDownVal *= .25;
climberSubsystem.setClimber(climbUpVal - climbDownVal);
double left = -driverJoystick.getAxis(CORE::COREJoystick::JoystickAxis::LEFT_STICK_Y);
double right = -driverJoystick.getAxis(CORE::COREJoystick::JoystickAxis::RIGHT_STICK_Y);
double oldLeft = left;
double oldRight = right;
std::pair<double, double> driveSpeed = driveSubsystem.getEncoderSpeed();
if(abs(((driveSpeed.first > 0) - (driveSpeed.first < 0)) - ((oldLeft > 0) - (oldLeft < 0))) == 2){
std::cout << "Left Drive Encoder speed and power don't match!" << std::endl;
}
if(abs(((driveSpeed.second > 0) - (driveSpeed.second < 0)) - ((oldRight > 0) - (oldRight < 0))) == 2){
std::cout << "Right Drive Encoder speed and power don't match!" << std::endl;
}
driveSubsystem.setMotorSpeed(left, right);
}
CORE2017::~CORE2017() {
// Robot.reset();
delete Robot;
Robot = nullptr;
}
#ifdef __arm__
START_ROBOT_CLASS(CORE2017)
#else
START_SIMULATED_ROBOT_CLASS(CORE2017)
#endif
| true |
bca23c7818152ba2e48306e21ca6723bc37e5e8e | C++ | diffblue/cbmc | /src/analyses/loop_analysis.h | UTF-8 | 5,755 | 3.015625 | 3 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] | permissive | /*******************************************************************\
Module: Loop analysis
Author: Diffblue Ltd
\*******************************************************************/
/// \file
/// Data structure representing a loop in a GOTO program and an interface shared
/// by all analyses that find program loops.
#ifndef CPROVER_ANALYSES_LOOP_ANALYSIS_H
#define CPROVER_ANALYSES_LOOP_ANALYSIS_H
#include <goto-programs/goto_model.h>
template <class T, typename C>
class loop_analysist;
/// A loop, specified as a set of instructions
template <class T, typename C>
class loop_templatet
{
typedef std::set<T, C> loop_instructionst;
loop_instructionst loop_instructions;
friend loop_analysist<T, C>;
public:
loop_templatet() = default;
template <typename InstructionSet>
explicit loop_templatet(InstructionSet &&instructions)
: loop_instructions(std::forward<InstructionSet>(instructions))
{
}
/// Returns true if \p instruction is in this loop
bool virtual contains(const T instruction) const
{
return !loop_instructions.empty() && loop_instructions.count(instruction);
}
// NOLINTNEXTLINE(readability/identifiers)
typedef typename loop_instructionst::const_iterator const_iterator;
/// Iterator over this loop's instructions
const_iterator begin() const
{
return loop_instructions.begin();
}
/// Iterator over this loop's instructions
const_iterator end() const
{
return loop_instructions.end();
}
/// Number of instructions in this loop
std::size_t size() const
{
return loop_instructions.size();
}
/// Returns true if this loop contains no instructions
bool empty() const
{
return loop_instructions.empty();
}
/// Adds \p instruction to this loop.
/// \return true if the instruction is new
bool insert_instruction(const T instruction)
{
return loop_instructions.insert(instruction).second;
}
};
template <class T, typename C>
class loop_analysist
{
public:
typedef loop_templatet<T, C> loopt;
// map loop headers to loops
typedef std::map<T, loopt, C> loop_mapt;
loop_mapt loop_map;
virtual void output(std::ostream &) const;
/// Returns true if \p instruction is the header of any loop
bool is_loop_header(const T instruction) const
{
return loop_map.count(instruction);
}
loop_analysist() = default;
};
template <typename T, typename C>
class loop_with_parent_analysis_templatet : loop_templatet<T, C>
{
typedef loop_analysist<T, C> parent_analysist;
public:
explicit loop_with_parent_analysis_templatet(parent_analysist &loop_analysis)
: loop_analysis(loop_analysis)
{
}
template <typename InstructionSet>
explicit loop_with_parent_analysis_templatet(
parent_analysist &loop_analysis,
InstructionSet &&instructions)
: loop_templatet<T, C>(std::forward<InstructionSet>(instructions)),
loop_analysis(loop_analysis)
{
}
/// Returns true if \p instruction is in \p loop
bool loop_contains(
const typename loop_analysist<T, C>::loopt &loop,
const T instruction) const
{
return loop.loop_instructions.count(instruction);
}
/// Get the \ref parent_analysist analysis this loop relates to
const parent_analysist &get_loop_analysis() const
{
return loop_analysis;
}
/// Get the \ref parent_analysist analysis this loop relates to
parent_analysist &get_loop_analysis()
{
return loop_analysis;
}
private:
parent_analysist &loop_analysis;
};
template <class T, typename C>
class linked_loop_analysist : loop_analysist<T, C>
{
public:
linked_loop_analysist() = default;
/// Returns true if \p instruction is in \p loop
bool loop_contains(
const typename loop_analysist<T, C>::loopt &loop,
const T instruction) const
{
return loop.loop_instructions.count(instruction);
}
// The loop structures stored in `loop_map` contain back-pointers to this
// class, so we forbid copying or moving the analysis struct. If this becomes
// necessary then either add a layer of indirection or update the loop_map
// back-pointers on copy/move.
linked_loop_analysist(const linked_loop_analysist &) = delete;
linked_loop_analysist(linked_loop_analysist &&) = delete;
linked_loop_analysist &operator=(const linked_loop_analysist &) = delete;
linked_loop_analysist &operator=(linked_loop_analysist &&) = delete;
};
/// Print all natural loops that were found
template <class T, typename C>
void loop_analysist<T, C>::output(std::ostream &out) const
{
for(const auto &loop : loop_map)
{
unsigned n = loop.first->location_number;
std::unordered_set<std::size_t> backedge_location_numbers;
for(const auto &backedge : loop.first->incoming_edges)
backedge_location_numbers.insert(backedge->location_number);
out << n << " is head of { ";
std::vector<std::size_t> loop_location_numbers;
for(const auto &loop_instruction_it : loop.second)
loop_location_numbers.push_back(loop_instruction_it->location_number);
std::sort(loop_location_numbers.begin(), loop_location_numbers.end());
for(const auto location_number : loop_location_numbers)
{
if(location_number != loop_location_numbers.at(0))
out << ", ";
out << location_number;
if(backedge_location_numbers.count(location_number))
out << " (backedge)";
}
out << " }\n";
}
}
template <class LoopAnalysis>
void show_loops(const goto_modelt &goto_model, std::ostream &out)
{
for(const auto &gf_entry : goto_model.goto_functions.function_map)
{
out << "*** " << gf_entry.first << '\n';
LoopAnalysis loop_analysis;
loop_analysis(gf_entry.second.body);
loop_analysis.output(out);
out << '\n';
}
}
#endif // CPROVER_ANALYSES_LOOP_ANALYSIS_H
| true |
93802bd87e0c382f6c78a50637ff6973e000ba7c | C++ | mampfes/colorado | /include/Ratio.hpp | UTF-8 | 455 | 2.71875 | 3 | [] | no_license | #pragma once
#include <cstdint>
namespace colorado
{
template <typename T>
struct Ratio
{
constexpr Ratio(T numArg, T denomArg) :
num{numArg},
denom{denomArg}
{
}
constexpr Ratio() :
num{0},
denom{1}
{
}
T num;
T denom;
};
using LedIndex = Ratio<uint16_t>;
using HueRatio = Ratio<uint8_t>;
} // namespace colorado | true |
fc6b11c1a6b9b96f068fb65e2537e62d50ca4e44 | C++ | zhangji0629/algorithm | /codeforces/contest_1154/A.cpp | UTF-8 | 469 | 2.796875 | 3 | [] | no_license | #include<bits/stdc++.h>
using LL = long long;
LL num[10];
int main()
{
while(std::cin >> num[0] >> num[1] >> num[2] >> num[3]) {
LL sum = 0;
for(int i = 0; i < 4; i++) {
sum += num[i];
}
sum /= 3;
for(int i = 0; i < 4; i++) {
if(sum == num[i]) {
continue;
}
std::cout << sum - num[i] << " ";
}
std::cout << std::endl;
}
return 0;
}
| true |
93098805db27e3949ffa6926d4f3ff05e2ebcffa | C++ | dgant/SAIDA | /src/SAIDA/ReserveBuilding.cpp | UHC | 20,045 | 2.765625 | 3 | [] | no_license | #include "ReserveBuilding.h"
using namespace MyBot;
// TODO attach ǹ reserve .
// onCreate attach ǹ reserve .
// ǹ landing (onComplete?) attach ǹ reserve .
// ǹ lifting attach .
Building::Building(int order, TilePosition pos, TilePosition tileSize, ReserveTypes reserveType) {
this->order = order;
this->pos = pos;
this->tileSize = tileSize;
this->reserveType = reserveType;
this->assignedWorker = nullptr;
this->lastAssignFrame = -1;
}
Building::Building(int order, TilePosition pos, vector<UnitType> unitTypes) {
this->order = order;
this->pos = pos;
this->tileSize = unitTypes.at(0).tileSize();
this->possibleList = unitTypes;
this->reserveType = ReserveTypes::UNIT_TYPE;
this->assignedWorker = nullptr;
this->lastAssignFrame = -1;
}
bool Building::isReservedFor(TilePosition position, TilePosition tileSize) const {
return this->pos == position && this->tileSize == tileSize;
}
bool Building::isReservedFor(TilePosition position, UnitType type) const {
return this->pos == position && canAssignToType(type);
}
bool Building::canAssignToType(UnitType type, bool checkAlreadySet) const {
if (checkAlreadySet) {
if (this->lastAssignFrame + 24 * 20 > TIME)
return false;
}
if (reserveType == ReserveTypes::SIZE) {
return this->tileSize == type.tileSize();
}
else if (reserveType == ReserveTypes::UNIT_TYPE) {
for (UnitType ut : possibleList) {
if (ut == type) {
// ٸ ǹ ϸ Ѿ.
bool canBuild = true;
for (int x = pos.x; x < pos.x + ut.tileWidth() && canBuild; x++) {
for (int y = pos.y; y < pos.y + ut.tileHeight(); y++) {
if (!bw->isBuildable(x, y, true)) {
canBuild = false;
break;
}
}
}
if (canBuild)
return true;
}
}
}
else if (reserveType == ReserveTypes::SPACE) {
return false;
}
else if (reserveType == ReserveTypes::MINERALS || reserveType == ReserveTypes::GAS) {
// TODO ͷ ?
return false;
}
else {
cout << " ȵ." << pos << ", " << tileSize << ", " << possibleList.empty() << endl;
}
return false;
}
void Building::assignWorker(Unit worker) {
this->assignedWorker = worker;
this->lastAssignFrame = TIME;
}
void Building::unassignWorker() {
if (this->lastAssignFrame < TIME) {
this->assignedWorker = nullptr;
this->lastAssignFrame = -1;
}
}
int Building::getOrder() {
return this->order;
}
void Building::setOrder(int order) {
this->order = order;
}
ReserveBuilding::ReserveBuilding() {
firstReserveOrder = 0;
reserveOrder = 0;
_reserveMap = vector< vector<short> >(bw->mapWidth(), vector<short>(bw->mapHeight(), 0));
_avoidMap = vector< vector<bool> >(bw->mapWidth(), vector<bool>(bw->mapHeight(), 0));
// unbuildable ġ
for (int i = 0; i < bw->mapWidth(); i++) {
for (int j = 0; j < bw->mapHeight(); j++) {
if (!bw->isBuildable(i, j)) {
_avoidMap[i][j] = true;
// _avoidList.emplace_back(0, TilePosition(i, j), TilePosition(1, 1), ReserveTypes::UNBUILDABLE);
}
}
}
if (INFO.selfRace == Races::Terran) {
// ļ ġ
TilePosition base = INFO.getMainBaseLocation(S)->getTilePosition();
reserveTiles(base + TilePosition(Terran_Command_Center.tileWidth(), 1), { Terran_Comsat_Station }, 0, 0, 0, 0);
// ö ġ
TerranConstructionPlaceFinder::Instance();
}
}
ReserveBuilding &ReserveBuilding::Instance() {
static ReserveBuilding instance;
return instance;
}
// private
bool ReserveBuilding::reserveTiles(Building &building, TilePosition position, int width, int height, int topSpace, int leftSpace, int rightSpace, int bottomSpace, bool canBuildAddon, bool forceReserve) {
// .
if (!forceReserve && !canReserveHere(position, building.getUnitTypes().empty() ? UnitTypes::None : building.getUnitTypes().front(), width, height, topSpace, leftSpace, rightSpace, bottomSpace, canBuildAddon))
return false;
int addonSize = canBuildAddon ? 2 : 0;
int rwidth = position.x + width + rightSpace + addonSize;
int rheight = position.y + height + bottomSpace;
for (int x = position.x - leftSpace; x < rwidth; x++) {
for (int y = position.y - topSpace; y < rheight; y++) {
TilePosition p = TilePosition(x, y);
if (p.isValid()) {
if (building.isBuildable()) {
_reserveMap[x][y]++;
}
else {
_avoidMap[x][y] = true;
}
if (x < position.x || (position.x + width <= x && position.y == y) || (position.x + width + addonSize <= x && position.y <= y) || (y < position.y && x <= position.x + width) || position.y + height <= y) {
building.addSpaceTile(x, y);
}
}
}
}
return true;
}
bool ReserveBuilding::reserveTiles(TilePosition position, TilePosition size, int topSpace, int leftSpace, int rightSpace, int bottomSpace, ReserveTypes reserveType) {
Building b(reserveOrder, position, size, reserveType);
bool success = reserveTiles(b, position, size.x, size.y, topSpace, leftSpace, rightSpace, bottomSpace);
if (success) {
if (Building::isBuildable(reserveType)) {
reserveOrder++;
_reserveList.push_back(b);
}
else
_avoidList.emplace_back(0, position, size, reserveType);
}
return success;
}
bool ReserveBuilding::reserveTiles(TilePosition position, vector<UnitType> unitTypes, int topSpace, int leftSpace, int rightSpace, int bottomSpace, bool useTypeAddon) {
Building b(reserveOrder, position, unitTypes);
UnitType type = unitTypes.empty() ? UnitTypes::None : unitTypes.at(0);
bool canBuildAddon = false;
vector<UnitType> addonUnitTypes;
if (useTypeAddon) {
for (UnitType unitType : unitTypes) {
if (unitType.canBuildAddon()) {
for (UnitType t : unitType.buildsWhat()) {
if (t.isAddon()) {
addonUnitTypes.push_back(t);
}
}
canBuildAddon = true;
}
}
}
bool success = reserveTiles(b, position, type.tileWidth(), type.tileHeight(), topSpace, leftSpace, rightSpace, bottomSpace, canBuildAddon);
// ̹ false
if (success) {
reserveOrder++;
_reserveList.push_back(b);
if (canBuildAddon)
_reserveList.emplace_back(reserveOrder++, position + TilePosition(type.tileWidth(), 1), addonUnitTypes);
}
return success;
}
void ReserveBuilding::forceReserveTiles(TilePosition position, vector<UnitType> unitTypes, int topSpace, int leftSpace, int rightSpace, int bottomSpace) {
Building b(reserveOrder++, position, unitTypes);
reserveTiles(b, position, unitTypes.front().tileWidth(), unitTypes.front().tileHeight(), topSpace, leftSpace, rightSpace, bottomSpace, false, true);
_reserveList.push_back(b);
}
bool ReserveBuilding::reserveTilesFirst(TilePosition position, vector<UnitType> unitTypes, int topSpace, int leftSpace, int rightSpace, int bottomSpace) {
Building b(--firstReserveOrder, position, unitTypes);
UnitType type;
bool canBuildAddon = false;
vector<UnitType> addonUnitTypes;
for (UnitType unitType : unitTypes) {
type = unitType;
if (unitType.canBuildAddon()) {
for (UnitType t : unitType.buildsWhat()) {
if (t.isAddon()) {
addonUnitTypes.push_back(t);
}
}
canBuildAddon = true;
}
}
bool success = reserveTiles(b, position, type.tileWidth(), type.tileHeight(), topSpace, leftSpace, rightSpace, bottomSpace, canBuildAddon);
// ̹ false
if (success) {
_reserveList.insert(_reserveList.begin(), b);
if (canBuildAddon)
_reserveList.emplace_back(reserveOrder++, position + TilePosition(type.tileWidth(), 1), addonUnitTypes);
}
return success;
}
void ReserveBuilding::forceReserveTilesFirst(TilePosition position, vector<UnitType> unitTypes, int topSpace, int leftSpace, int rightSpace, int bottomSpace) {
if (!position.isValid())
return;
Building b(--firstReserveOrder, position, unitTypes);
reserveTiles(b, position, unitTypes.front().tileWidth(), unitTypes.front().tileHeight(), topSpace, leftSpace, rightSpace, bottomSpace, false, true);
_reserveList.insert(_reserveList.begin(), b);
}
// private _reserveList üũ ش.
void ReserveBuilding::freeTiles(int width, int height, TilePosition position) {
int rwidth = position.x + width;
int rheight = position.y + height;
for (int x = position.x; x < rwidth; x++) {
for (int y = position.y; y < rheight; y++) {
if (_reserveMap[x][y] > 0)
_reserveMap[x][y]--;
}
}
}
void ReserveBuilding::freeTiles(TilePosition position, TilePosition size) {
for (word i = 0; i < _reserveList.size(); i++) {
Building b = _reserveList.at(i);
if (b.isReservedFor(position, size)) {
_reserveList.erase(_reserveList.begin() + i);
freeTiles(size.x, size.y, position);
for (auto space : b.getSpaceList())
if (_reserveMap[space.x][space.y] > 0)
_reserveMap[space.x][space.y]--;
break;
}
}
}
void ReserveBuilding::freeTiles(TilePosition position, UnitType type, bool freeAddon) {
for (word i = 0; i < _reserveList.size(); i++) {
Building b = _reserveList.at(i);
if (b.isReservedFor(position, type.tileSize())) {
_reserveList.erase(_reserveList.begin() + i);
freeTiles(type.tileWidth(), type.tileHeight(), position);
for (auto space : b.getSpaceList())
if (_reserveMap[space.x][space.y] > 0)
_reserveMap[space.x][space.y]--;
if (freeAddon) {
if (type.canBuildAddon()) {
for (UnitType addonUnitType : type.buildsWhat()) {
if (addonUnitType.isAddon()) {
freeTiles(position + TilePosition(4, 1), addonUnitType);
break;
}
}
}
}
break;
}
}
}
void ReserveBuilding::modifyReservePosition(UnitType unitType, TilePosition fromPosition, TilePosition toPosition) {
freeTiles(fromPosition, unitType, true);
reserveTiles(toPosition, { unitType }, 0, 0, 0, 0);
}
bool ReserveBuilding::canReserveHere(TilePosition position, UnitType unitType, int width, int height, int topSpace, int leftSpace, int rightSpace, int bottomSpace, bool canBuildAddon) const {
TilePosition strPosition = position - TilePosition(leftSpace, topSpace);
int rwidth = position.x + width + rightSpace + (canBuildAddon ? 2 : 0);
int rheight = position.y + height + bottomSpace;
// ȿ üũ
if (!strPosition.isValid() || rwidth > (int)_reserveMap.size() || rheight > (int)_reserveMap[0].size()) {
return false;
}
// addon ǹ addon Ȯ
if (canBuildAddon) {
bool needToCheck = true;
// ̹ addon ǹ ִ üũ ʴ´.
for (auto u : bw->getUnitsOnTile(position + TilePosition(width, 1))) {
if (u->getTilePosition() == position + TilePosition(width, 1) && u->getType().isAddon() && u->getType().whatBuilds().first == unitType) {
needToCheck = false;
canBuildAddon = false;
rightSpace = 0;
rwidth -= 2;
break;
}
}
if (needToCheck) {
if (!canReserveHere(position + TilePosition(width, 1), 2, 2, 0, 0, 0, 0)) {
return false;
}
if (!bw->canBuildHere(position + TilePosition(width, 1), Terran_Comsat_Station)) {
return false;
}
}
}
int buildingWidth = position.x + width + (canBuildAddon ? 2 : 0);
int buildingHeight = position.y + height;
for (int x = strPosition.x; x < rwidth; x++) {
for (int y = strPosition.y; y < rheight; y++) {
// space avoid ġ Ǵ.
if (position.x > x || (position.y > y && x <= position.x + width) || (position.x + width <= x && position.y == y) || (buildingWidth <= x && position.y <= y) || buildingHeight <= y) {
// Ŀ ͷ avoid ĥ .
if (unitType == Terran_Command_Center) {
for (auto unit : bw->getUnitsInRectangle(x * 32 + 1, y * 32 + 1, x * 32 + 31, y * 32 + 31)) {
if (unit->getType() != Terran_Missile_Turret && unit->getType() != Terran_Bunker) {
return false;
}
}
}
else if (_reserveMap[x][y] || !bw->isBuildable(x, y, true)) {
return false;
}
else {
for (auto unit : bw->getUnitsInRectangle(x * 32 + 1, y * 32 + 1, x * 32 + 31, y * 32 + 31)) {
if (unit->getType().isSpecialBuilding()) {
return false;
}
}
}
}
// ǹ avoid ʱ üũ
else {
if (_reserveMap[x][y] || !bw->isBuildable(x, y, true) || (_avoidMap[x][y] && unitType != Terran_Bunker && unitType != Terran_Missile_Turret)) {
// addon addon ˻ ʴ´.
if (canBuildAddon && y < position.y && x >= position.x + width)
continue;
return false;
}
}
}
}
return true;
}
void ReserveBuilding::debugCanReserveHere(TilePosition position, UnitType unitType, int width, int height, int topSpace, int leftSpace, int rightSpace, int bottomSpace, bool canBuildAddon) const {
TilePosition strPosition = position - TilePosition(leftSpace, topSpace);
int rwidth = position.x + width + rightSpace + (canBuildAddon ? 2 : 0);
int rheight = position.y + height + bottomSpace;
// ȿ üũ
if (!strPosition.isValid() || rwidth > (int)_reserveMap.size() || rheight > (int)_reserveMap[0].size()) {
cout << "validation fail." << strPosition << " " << rwidth << ", " << rheight << endl;
return;
}
// addon ǹ addon Ȯ
if (canBuildAddon) {
bool needToCheck = true;
// ̹ addon ǹ ִ üũ ʴ´.
for (auto u : bw->getUnitsOnTile(position + TilePosition(width, 1))) {
if (u->getTilePosition() == position + TilePosition(width, 1) && u->getType().isAddon() && u->getType().whatBuilds().first == unitType) {
needToCheck = false;
canBuildAddon = false;
rightSpace = 0;
rwidth -= 2;
break;
}
}
if (needToCheck) {
if (!canReserveHere(position + TilePosition(width, 1), 2, 2, 0, 0, 0, 0)) {
cout << "addon canReserveHere fail." << position + TilePosition(width, 1) << endl;
return;
}
if (!bw->canBuildHere(position + TilePosition(width, 1), Terran_Comsat_Station)) {
cout << "bw->canBuildHere fail." << position + TilePosition(width, 1) << endl;
return;
}
}
}
int buildingWidth = position.x + width + (canBuildAddon ? 2 : 0);
int buildingHeight = position.y + height;
for (int x = strPosition.x; x < rwidth; x++) {
for (int y = strPosition.y; y < rheight; y++) {
// space avoid ġ Ǵ.
if (position.x > x || (position.y > y && x <= position.x + width) || (position.x + width <= x && position.y == y) || (buildingWidth <= x && position.y <= y) || buildingHeight <= y) {
// Ŀ ͷ avoid ĥ .
if (unitType == Terran_Command_Center) {
for (auto unit : bw->getUnitsInRectangle(x * 32 + 1, y * 32 + 1, x * 32 + 31, y * 32 + 31)) {
if (unit->getType() != Terran_Missile_Turret && unit->getType() != Terran_Bunker) {
cout << "another building exists near command center" << endl;
return;
}
}
}
else if (_reserveMap[x][y] || !bw->isBuildable(x, y, true)) {
cout << "space tile check fail.(" << x << ", " << y << ") _reserveMap : " << _reserveMap[x][y] << " bw->isBuildable : " << bw->isBuildable(x, y, true) << endl;
cout << strPosition << rwidth << ", " << rheight << endl;
for (int b = strPosition.y; b < rheight; b++) {
for (int a = strPosition.x; a < rwidth; a++) {
printf("%2d", _reserveMap[a][b]);
}
cout << endl;
}
return;
}
else {
for (auto unit : bw->getUnitsInRectangle(x * 32 + 1, y * 32 + 1, x * 32 + 31, y * 32 + 31)) {
if (unit->getType().isSpecialBuilding()) {
cout << "isSpecialBuilding exist fail.(" << x << ", " << y << ")" << endl;
return;
}
}
}
}
// ǹ avoid ʱ üũ
else {
if (_reserveMap[x][y] || !bw->isBuildable(x, y, true) || (_avoidMap[x][y] && unitType != Terran_Bunker && unitType != Terran_Missile_Turret)) {
// addon addon ˻ ʴ´.
if (canBuildAddon && y < position.y && x >= position.x + width)
continue;
cout << "already reserved fail.(" << x << ", " << y << ") _reserveMap : " << _reserveMap[x][y] << " _avoidMap : " << _avoidMap[x][y] << unitType << endl;
return;
}
}
}
}
}
bool ReserveBuilding::isReservedFor(TilePosition position, UnitType type) const {
for (const Building &b : _reserveList) {
if (b.isReservedFor(position, type)) {
return true;
}
}
return false;
}
TilePosition ReserveBuilding::getReservedPosition(UnitType type) {
for (Building &b : _reserveList) {
if (b.canAssignToType(type, true)) {
return b.TopLeft();
}
}
return TilePositions::None;
}
TilePosition ReserveBuilding::getReservedPosition(UnitType type, Unit builder, UnitType addon) {
for (Building &b : _reserveList) {
if (b.canAssignToType(type, true) && bw->canBuildHere(b.TopLeft(), addon, builder)) {
return b.TopLeft();
}
}
return TilePositions::None;
}
TilePosition ReserveBuilding::getReservedPositionAtWorker(UnitType type, Unit builder) {
for (Building &b : _reserveList) {
TilePosition tl = b.TopLeft();
TilePosition worker = (TilePosition)builder->getPosition();
TilePosition br = b.BottomRight();
if (b.canAssignToType(type, false) && tl.x <= worker.x && tl.y == worker.y && worker.x < br.x && worker.y < br.y)
return b.TopLeft();
}
return TilePositions::None;
}
void ReserveBuilding::assignTiles(TilePosition position, TilePosition size, Unit worker) {
for (word i = 0; i < _reserveList.size(); i++) {
Building &b = _reserveList.at(i);
if (b.isReservedFor(position, size)) {
b.assignWorker(worker);
break;
}
}
}
void ReserveBuilding::assignTiles(TilePosition position, UnitType type, Unit worker) {
for (word i = 0; i < _reserveList.size(); i++) {
Building &b = _reserveList.at(i);
if (b.isReservedFor(position, type)) {
b.assignWorker(worker);
break;
}
}
}
void ReserveBuilding::unassignTiles(TilePosition position, UnitType type) {
for (word i = 0; i < _reserveList.size(); i++) {
Building &b = _reserveList.at(i);
if (b.isReservedFor(position, type)) {
b.unassignWorker();
break;
}
}
}
void ReserveBuilding::reordering(TilePosition tiles[], int strIdx, int endIdx, UnitType unitType) {
vector<int> order;
for (int i = strIdx; i < endIdx; i++) {
TilePosition tile = tiles[i];
for (Building &b : _reserveList) {
if (b.isReservedFor(tile, unitType)) {
order.push_back(b.getOrder());
break;
}
}
}
sort(order.begin(), order.end());
for (int i = strIdx; i < endIdx; i++) {
TilePosition tile = tiles[i];
for (Building &b : _reserveList) {
if (b.isReservedFor(tile, unitType)) {
b.setOrder(order.at(i - strIdx));
break;
}
}
}
sort(_reserveList.begin(), _reserveList.end(), [](Building a, Building b) {
return a.getOrder() < b.getOrder();
});
}
void ReserveBuilding::addTypes(Building building, vector<UnitType> unitTypes) {
for (auto &reserve : _reserveList) {
if (reserve == building) {
reserve.addType(unitTypes);
break;
}
}
}
const vector< Building > ReserveBuilding::getReserveList() {
return _reserveList;
}
const vector< Building > ReserveBuilding::getAvoidList() {
return _avoidList;
}
| true |
6a2733b8700b7f0aa2c8814111b82028e679e6bb | C++ | HO-COOH/NeuroNet | /NeuroNet/Net.cpp | UTF-8 | 15,272 | 2.640625 | 3 | [] | no_license | #include "Net.h"
#include <cmath>
#include <algorithm> //for shuffle the inputs and desired_outputs pair
#include <random>
#include <chrono>
#include <memory>
#include <fstream>
#include <opencv2/opencv.hpp>
#include "Neuron.h"
double tanh_prime(double x)
{
return 1.0 - (tanh(x) * tanh(x));
}
double sigmoid_prime(double x)
{
return sigmoid(x) * (1.0 - sigmoid(x));
}
Net::Net(size_t numberOfInputs, const std::vector<size_t> numberOfNeuronsEachLayer):numberOfInputs(numberOfInputs),numberOfLayers(numberOfNeuronsEachLayer.size())
{
layers.push_back(Layer(numberOfNeuronsEachLayer[0], numberOfInputs));
for (size_t index = 1; index < numberOfNeuronsEachLayer.size(); ++index)
{
layers.push_back(Layer(numberOfNeuronsEachLayer[index], layers.back().numberOfPerceptrons));
}
local_gradients.resize(numberOfNeuronsEachLayer.size());
}
void Net::set_learning_rate(double rate)
{
std::cout << "Learning rate set from " << learning_rate << " -> " << rate << std::endl;
learning_rate = rate;
}
void Net::set_momentum(double momentum)
{
this->momentum = momentum;
momentum_flag = true;
}
Matrix Net::init_input(const Matrix& _input) const
{
if (_input.row()!= numberOfInputs)
{
std::cout << "The input matrix of size: ";
_input.reportSize();
std::cout << " can't init.\n";
}
Matrix temp(_input.row() + 1, 1);
temp(1, 1) = 1;
for (size_t rowIndex = 1; rowIndex <= numberOfInputs; ++rowIndex)
{
temp(rowIndex + 1, 1) = _input(rowIndex, 1);
}
return temp;
}
void Net::init_inputs(const std::vector<Matrix>& _inputs)
{
for (auto& each_input : _inputs)
inputs.push_back(init_input(each_input));
}
void Net::init_weight(const std::vector<Matrix> weights, const std::vector<Matrix>& biases)
{
if (weights.size() != numberOfLayers)
{
std::cout << "The vector of weight matrcies size is " << weights.size() << " but there are " << numberOfLayers << " layers to init!\n";
return;
}
if (biases.size() != numberOfLayers)
{
std::cout << "The vector of weight matrcies size is " << biases.size() << " but there are " << numberOfLayers << " layers to init!\n";
return;
}
size_t i = 0;
layers.back().setOutputFlag();
for (size_t layerIndex=0; layerIndex<layers.size();++layerIndex)
{
if (weights[layerIndex].row() != layers[layerIndex].numberOfPerceptrons || weights[layerIndex].column() != layers[layerIndex].numberOfConnections||biases[layerIndex].row()!=layers[layerIndex].numberOfPerceptrons||biases[layerIndex].column()!=1)
{
std::cout << "The " << layerIndex << " -th weight matrix to init is of wrong size: ";
weights[layerIndex].reportSize();
std::cout << std::endl << "But the layer: ";
layers[layerIndex].report();
return;
}
layers[layerIndex].set(weights[layerIndex], biases[layerIndex]);
weight_k_1.push_back(layers[layerIndex].get_weight());
local_gradients[layerIndex].resize(weights[layerIndex].row(), 1);
}
}
void Net::set_desired_outputs(const std::vector<Matrix> _desired_outputs)
{
desired_outputs = _desired_outputs;
}
Matrix Net::ForwardComputation(size_t k)
{
if (desired_outputs.size() != inputs.size())
{
std::cout << "The batch only contains" << desired_outputs.size() << " desired outputs but there are " << inputs.size() << " inputs!\n";
abort();
}
if (!layers[layers.size() - 1].isOutput())
{
std::cout << "The last layer is not set to output mode!\n";
abort();
}
layers[0].run(inputs[k]);
Matrix out0 = layers[0].output();
size_t layerIndex = 0;
for (size_t layerIndex=1;layerIndex<layers.size();++layerIndex)
{
if (!layers[layerIndex].isReady())
{
std::cout << "Layer" << layerIndex << " in " << k << " iteration is not ready!\n";
abort();
}
else
{
layers[layerIndex].run(out0);
out0 = layers[layerIndex].output();
}
}
return out0;
}
Matrix Net::ForwardComputation(const Matrix& processed_input)
{
layers[0].run(processed_input);
Matrix out0 = layers[0].output();
size_t layerIndex = 0;
for (size_t layerIndex = 1; layerIndex < layers.size(); ++layerIndex)
{
if (!layers[layerIndex].isReady())
{
std::cout << "Layer" << layerIndex << " a single forward computation is not ready!\n";
abort();
}
else
{
layers[layerIndex].run(out0);
out0 = layers[layerIndex].output();
}
}
return out0;
}
Matrix Net::getError(size_t k)
{
using namespace std;
if (desired_outputs[k].row() != layers[numberOfLayers - 1].numberOfPerceptrons|| desired_outputs[k].column()!=1)
{
cout << "The size of desired Output is wrong!\n";
desired_outputs[k].reportSize();
cout << "There are " << layers[numberOfLayers - 1].numberOfPerceptrons << " neurons in the output layer!\n";
}
Matrix error(desired_outputs[k].row(), 1);
for (size_t i = 0; i < desired_outputs[k].row(); ++i)
{
error(i + 1, 1) = desired_outputs[k](i + 1, 1) - layers[layers.size()-1].output()(i+2,1);
}
return error;
}
bool Net::checkResult(const Matrix& output, const Matrix& desired) const
{
return false;
}
void Net::BackwardComputation(size_t k)
{
Matrix error = getError(k);
//std::cout <<"Error vector=\n"<< error << std::endl;
for (size_t i = 0; i < layers.back().numberOfPerceptrons; ++i)
{
local_gradients.back()(i + 1, 1) = error(i + 1, 1) * sigmoid_prime(layers.back().get_neuron_origin_sum(i));
}
//layer (0-numberofLayers-2)
for (int layerIndex = numberOfLayers - 2; layerIndex >= 0; --layerIndex)
{
// (tanh x)'=1-(tanh x)^2
// neurons 0-numberOfPerceptrons
for (size_t rowIndex = 0; rowIndex < layers[layerIndex].numberOfPerceptrons; ++rowIndex)
{
double sum = 0;
//sum up the gradient from back layer
for (size_t i = 0; i < layers[layerIndex + 1].numberOfPerceptrons; ++i)
sum += local_gradients[layerIndex + 1](i + 1, 1) * layers[layerIndex + 1].get_weight()(i + 1, rowIndex+2);
local_gradients[layerIndex](rowIndex + 1, 1) = tanh_prime(layers[layerIndex].get_neuron_origin_sum(rowIndex)) * sum;
}
}
/*We have local_gradients, now compute the updated weights*/
//for layer 0 - numberofLayer-1
for (size_t layerIndex = 0; layerIndex < numberOfLayers; ++layerIndex)
{
Matrix updatedWeight;
if (momentum_flag)
{
if (layerIndex == 0)
updatedWeight = layers[layerIndex].get_weight() * (1 + momentum) - (weight_k_1[layerIndex] * momentum) + ((local_gradients[layerIndex] * inputs[k].transpose()) * learning_rate);
else
updatedWeight = layers[layerIndex].get_weight() * (1 + momentum) - (weight_k_1[layerIndex] * momentum) + ((local_gradients[layerIndex] * layers[layerIndex - 1].output().transpose()) * learning_rate);
}
else
{
if (layerIndex == 0)
updatedWeight = layers[layerIndex].get_weight()+ ((local_gradients[layerIndex] * inputs[k].transpose()) * learning_rate);
else
updatedWeight = layers[layerIndex].get_weight()+ ((local_gradients[layerIndex] * layers[layerIndex - 1].output().transpose()) * learning_rate);
}
weight_k_1[layerIndex] = layers[layerIndex].get_weight();
layers[layerIndex].set(updatedWeight);
//Matrix updatedWeight(layers[layerIndex].numberOfPerceptrons, layers[layerIndex].numberOfConnections + 1);
//if (layerIndex == 0)
//{
// for (size_t j = 0; j < updatedWeight.row(); ++j)
// {
// for (size_t i = 0; i < updatedWeight.column(); ++i)
// {
// updatedWeight(j + 1, i + 1) = layers[layerIndex].get_weight()(j + 1, i + 1) + learning_rate * local_gradients[layerIndex](j + 1, 1) * inputs[k](i + 1, 1);
// }
// }
//}
//else
//{
// for (size_t j = 0; j < updatedWeight.row(); ++j)
// {
// for (size_t i = 0; i < updatedWeight.column(); ++i)
// {
// updatedWeight(j + 1, i + 1) = layers[layerIndex].get_weight()(j + 1, i + 1) + learning_rate * local_gradients[layerIndex](j + 1, 1) * layers[layerIndex-1].output()(i + 1, 1);
// }
// }
//}
//layers[layerIndex].set(updatedWeight);
}
}
void Net::run(size_t epoch, size_t iterations, bool showFinalWeights, bool showEachPass)
{
using namespace std;
//default_random_engine rd;
//uniform_int_distribution<unsigned> random_index(0, inputs.size() - 1);
if (inputs.size() != desired_outputs.size())
{
std::cout << "Error! There are unequal number of inputs and outputs pairs!\n";
abort();
}
size_t pass = 0;
for (size_t t = 0; t < epoch; ++t)
{
for (size_t i = 0; i < iterations; ++i)
{
if (showEachPass)
{
cout << "Pass " << pass++ << ":\n";
Matrix temp = ForwardComputation(i);
for (size_t j = 1; j < temp.row(); ++j)
{
cout << desired_outputs[i](j, 1) << "\t" << temp(j + 1, 1) << endl;
}
cin.get();
}
else
ForwardComputation(i);
BackwardComputation(i);
//show_local_gradients();
}
}
if (showFinalWeights)
{
cout << "final weight:\n\n";
for (auto& each_layer : layers)
{
each_layer.ShowWeight();
cout << endl;
}
}
}
//void Net::update_weights()
//{
// //for layer 0 - numberofLayer-1
// for (size_t layerIndex = 0; layerIndex < numberOfLayers; ++layerIndex)
// {
// Matrix updatedWeight(layers[layerIndex].numberOfPerceptrons, layers[layerIndex].numberOfConnections + 1);
// //for each neuron
// for (size_t neuronIndex = 0; neuronIndex < layers[layerIndex].numberOfPerceptrons; ++neuronIndex)
// {
// //for each connection to the layer
// for (size_t connectionIndex = 0; connectionIndex < layers[layerIndex].numberOfConnections+1; ++connectionIndex)
// {
// if (connectionIndex == 0)
// updatedWeight(neuronIndex + 1, connectionIndex + 1) = layers[layerIndex].get_weight()(neuronIndex + 1, connectionIndex + 1) + learning_rate * local_gradients[layerIndex](neuronIndex + 1, 1) * 1;
// else
// {
// if (layerIndex == 0)
// updatedWeight(neuronIndex + 1, connectionIndex + 1) = layers[layerIndex].get_weight()(neuronIndex + 1, connectionIndex + 1) + learning_rate * local_gradients[layerIndex](neuronIndex + 1, 1) * input(connectionIndex + 1, 1);
// else
// updatedWeight(neuronIndex + 1, connectionIndex + 1) = layers[layerIndex].get_weight()(neuronIndex + 1, connectionIndex + 1) + learning_rate * local_gradients[layerIndex](neuronIndex + 1, 1) * layers[layerIndex - 1].get_neuron_output(connectionIndex-1);
// }
// }
// }
// layers[layerIndex].set(updatedWeight);
// }
//}
//////////////////////////////////////////Debug//////////////////////////////////////////
void Net::show_all_weights()
{
for (auto& each_layer : layers)
{
each_layer.get_weight().reportSize();
std::cout << std::endl;
//each_layer.ShowWeight();
std::cout << std::endl;
}
inputs[0].transpose().reportSize();
local_gradients[0].reportSize();
std::cout << std::endl;
layers[0].output().transpose().reportSize();
}
void Net::show_local_gradients()
{
using namespace std;
for (auto& each_local_gradient : local_gradients)
{
cout << each_local_gradient << endl;
}
}
void Net::show_layers()
{
for (auto& each_layer : layers)
{
each_layer.report();
std::cout << std::endl;
}
}
void Net::show_input_desired_output_pair()
{
using namespace std;
if (inputs.size() != desired_outputs.size())
{
cout << "Inputs.size()!=desired_outputs.size()\n";
return;
}
for (size_t index = 0; index < inputs.size(); ++index)
{
cout << index << ":\n";
cout << inputs[index] << endl << desired_outputs[index] << endl;
}
}
void Net::show_inputs_outputs_size()
{
std::cout << "Input size = " << inputs.size() << std::endl;
if (inputs.size() != desired_outputs.size())
std::cout << "Warning! There are unequal number of inputs and outputs pairs!\n";
}
void Net::show_inputs(size_t index)
{
////std::cout << inputs[index] << std::endl;
///*show the testing image in OpenCV*/
//cv::Mat m2(14, 14, CV_8UC1);
//int index2 = 2;
//for (size_t row = 0; row < 14; ++row)
//{
// for (size_t col = 0; col < 14; ++col)
// {
// m2.at<uchar>(row, col) = inputs[index](index2++, 1)*255.0;
// }
//}
//cv::namedWindow("Figure");
//cv::imshow("Figure", m2);
//cv::waitKey(0);
//cv::destroyWindow("Figure");
}
void Net::show_desired_outputs(size_t index)
{
std::cout << desired_outputs[index] << std::endl;
}
/////////////////////////////////////////////////*Test*///////////////////////////////////////////////////////////////
void Net::test(size_t input_index)
{
using namespace std;
cout << "\nTarget outputs:\n" << desired_outputs[input_index] << "Neural Net output:\n";
cout << ForwardComputation(input_index).slice(2,layers[layers.size()-1].numberOfPerceptrons+1,1,1);
}
std::pair<double, bool> Net::test(const Matrix& input, const Matrix& desired_output, unsigned char label_r, bool showEachPass)
{
using namespace std;
if(showEachPass)
cout << "\nTarget outputs:\n" << desired_output << "Neural Net output:\n";
Matrix result = ForwardComputation(init_input(input)).slice(2, layers[layers.size() - 1].numberOfPerceptrons + 1, 1, 1);
if (showEachPass)
cout << result;
/*calculate error*/
Matrix error = desired_output - result;
double sum = 0;
double max = -1;
unsigned char predicted = 10;
for (size_t i = 0; i < 10; ++i)
{
sum += abs(error(i + 1, 1));
if (result(i + 1, 1) > max)
{
max = result(i + 1, 1);
predicted = i;
}
}
bool correct = (predicted == label_r) ? true : false;
if (showEachPass)
{
cout << "\npredicted=" << (int)predicted << "\t real=" << (int)label_r << endl;
cout << (correct ? "correct" : "wrong!") << endl;
}
return std::make_pair(sum, correct);
}
struct metaData
{
double learning_rate;
double momentum;
size_t inputs;
size_t layers_num;
std::vector<size_t> layers;
};
bool Net::WriteToFile(const std::string fileName)
{
using namespace std;
ofstream metaFile(fileName, ios_base::binary);
ofstream dataFile(fileName + "data", ios_base::binary);
if (!metaFile.is_open()||!dataFile.is_open())
{
metaFile.close();
dataFile.close();
return false;
}
/*Write Meta data*/
//metaFile << "Inputs=" << numberOfInputs << endl;
//metaFile << "Layers=";
//for (auto& layer : layers)
// metaFile << layer.numberOfPerceptrons << ",";
//metaFile << "\b" << endl; //?
//metaFile << "Learning rate=" << learning_rate << endl;
//metaFile << "Momentum=" << momentum << endl;
metaData data{ learning_rate, momentum, numberOfInputs };
for (auto& layer : layers)
data.layers.push_back(layer.numberOfPerceptrons);
data.layers_num = layers.size();
metaFile.write((char*)&data, 2 * (sizeof(double) + sizeof(size_t)));
metaFile.write((char*)&data.layers, data.layers_num * sizeof(layers.front()));
/*write data*/
for (auto& layer : layers)
dataFile.write((char*)&layer.get_weight(), sizeof(layer.get_weight()));
/*close file stream*/
metaFile.close();
dataFile.close();
return true;
}
std::unique_ptr<Net> ReadFromFile(const std::string fileName)
{
using namespace std;
ifstream metaFile(fileName, ios_base::binary);
ifstream dataFile(fileName + "data", ios_base::binary);
if (!metaFile.is_open() || !dataFile.is_open())
{
metaFile.close();
dataFile.close();
return nullptr;
}
metaData data;
metaFile.read((char*)&data, 2 * (sizeof(double)+sizeof(size_t)));
metaFile.read((char*)&data.layers, data.layers_num * sizeof(size_t));
unique_ptr<Net> pt{ make_unique<Net>(data.inputs, data.layers) };
pt->set_learning_rate(data.learning_rate);
if (data.momentum != 0)
pt->set_momentum(data.momentum);
metaFile.close();
dataFile.close();
return pt;
}
| true |
aff60f097e07011dbd51de39e99d6e7291a64800 | C++ | timHau/extensor_coding | /compare/cpp/matrix.cpp | UTF-8 | 704 | 3.15625 | 3 | [] | no_license | #include "matrix.h"
Matrix::Matrix(int nRows, int nCols, vector<Extensor> values)
{
this->nRows = nRows;
this->nCols = nCols;
data = vector<tuple<int, int, Extensor>>();
for (int i = 0; i < values.size(); ++i) {
auto val = values[i];
if (!val.is_zero()) {
int row_index = i / nCols;
int col_index = i % nCols;
data.push_back(tuple<int, int, Extensor> {row_index, col_index, val});
}
}
}
vector<Extensor> Matrix::operator*(const vector<Extensor>& other)
{
vector<Extensor> res(other.size(), Extensor::zero());
for (const auto& triple : data) {
int x = get<0>(triple);
int y = get<1>(triple);
Extensor v = get<2>(triple);
res[x] = res[x] + v * other[y];
}
return res;
} | true |
38be721e38fd49a25db25a3fdbe86539a8682ad8 | C++ | kotabrog/CPP-module | /module-04/ex03/MateriaSource.hpp | UTF-8 | 602 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef MATERIASOURCE_H
#define MATERIASOURCE_H
#include <iostream>
#include <string>
#include "IMateriaSource.hpp"
#define NUM_MATERIA_SOURCE 4
class MateriaSource : public IMateriaSource
{
AMateria* materia[NUM_MATERIA_SOURCE];
bool checkIndex(int index) const;
public:
MateriaSource();
MateriaSource(const MateriaSource& a);
virtual ~MateriaSource();
MateriaSource& operator=(const MateriaSource& a);
const AMateria* getMateria(int index) const;
virtual void learnMateria(AMateria* m);
virtual AMateria* createMateria(std::string const & type);
};
#endif
| true |
4effe523bd57532ed1236e5288e1a3eca443e101 | C++ | caiweihan/Sta | /Sta.cpp | UTF-8 | 1,732 | 2.890625 | 3 | [] | no_license | constexpr unsigned max(unsigned a, unsigned b)
{ return a > b ? a : b; }
template<typename T, typename Alloc = std::allocator<T>, int init_size = max(512 / sizeof(T), 8u)>
class Sta
{
public:
typedef T value_type;
typedef T& reference;
typedef T* pointer;
typedef const T& const_reference;
typedef size_t size_type;
Sta():
p(nullptr),
garbage(nullptr)
{}
~Sta()
{
if(garbage) {
alloc.deallocate(garbage->begin, garbage->end - garbage->begin);
delete garbage;
}
if(p) {
Node *temp;
for(T *i = p->begin; i <= it; i++)
alloc.destroy(i);
alloc.deallocate(p->begin, p->end - p->begin);
temp = p;
p = p->pre;
delete temp;
while(p) {
for(T *i = p->begin; i != p->end; i++)
alloc.destroy(i);
alloc.deallocate(p->begin, p->end - p->begin);
temp = p;
p = p->pre;
delete temp;
}
}
}
void push(T x)
{
++it;
if(! p || it == p->end) {
if(garbage) {
it = garbage->begin;
p = garbage;
garbage = nullptr;
}
else {
size_t x = p ? (p->end - p->begin) * 2 : init_size;
it = alloc.allocate(x);
p = new Node{ p, it, it + x };
}
}
alloc.construct(it, x);
}
void pop()
{
alloc.destroy(it);
if(it == p->begin) {
if(garbage) {
alloc.deallocate(garbage->begin, garbage->end - garbage->begin);
delete garbage;
}
garbage = p;
p = p->pre;
if(p)
it = p->end - 1;
}
else
it--;
}
T& top()
{ return *it; }
bool empty()
{ return ! p; }
size_t size()
{ return p ? p->end - p->begin + it - p->begin - init_size + 1 : 0; }
private:
struct Node
{
Node *pre;
T *begin;
T *end;
};
T *it;
Node *p;
Node *garbage;
Alloc alloc;
};
| true |
2fc605a242260773eddfc938805174c7cff52b77 | C++ | FlorianWolters/cpp-component-core-uncopyable | /include/fw/core/uncopyable_mixin.h | UTF-8 | 1,689 | 3.0625 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* Declares the `fw::core::UncopyableMixin` class.
*
* @file fw/core/uncopyable_mixin.h
* @author Florian Wolters <wolters.fl@gmail.com>
*
* @section License
*
* Copyright Florian Wolters 2014 (http://blog.florianwolters.de).
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef FW_CORE_UNCOPYABLE_MIXIN_H_
#define FW_CORE_UNCOPYABLE_MIXIN_H_
namespace fw {
namespace core {
/**
* The `UncopyableMixin` class prevents objects of a class from being
* copy-constructed or assigned to each other.
*
* `UncopyableMixin` instances should **not** be constructed in standard
* programming.
*
* Instead, the class should be used as:
*
* #include "fw/core/uncopyable_mixin.h"
*
* class MyUncopyable final
* : private fw::core::UncopyableMixin<MyUncopyable> {
* };
*
* `UncopyableMixin` implements the *Curiously Recurring Template Pattern
* (CRTP)* (a. k. a. Mixin-from-above) idiom.
*
* @author Florian Wolters <wolters.fl@gmail.com>
* @tparam TDerived The type of the derived class.
*/
template <class TDerived>
class UncopyableMixin {
public:
/**
* Deleted copy constructor.
*/
UncopyableMixin(UncopyableMixin const&) = delete;
/**
* Deleted assignment operator.
*
* @return n/a
*/
UncopyableMixin& operator=(UncopyableMixin const&) = delete;
protected:
/**
* Initializes a new instance of the `UncopyableMixin` class.
*/
UncopyableMixin() = default;
/**
* Finalizes an instance of the `UncopyableMixin` class.
*/
~UncopyableMixin() = default;
};
} // namespace core
} // namespace fw
#endif // FW_CORE_UNCOPYABLE_MIXIN_H_
| true |
23d113f8d670a907652d7731a23320a6e8a4350b | C++ | Polladin/AOC | /2022/src/day_09/rope_bridge.cpp | UTF-8 | 2,195 | 2.9375 | 3 | [] | no_license | #include "rope_bridge.h"
#include <vector>
#include <set>
#include "common/file_reader.h"
#include "common/common.h"
struct Point
{
int row;
int col;
};
using t_movement = std::pair< char, int >;
using t_input = std::vector< t_movement >;
using t_point = std::pair< int, int >;
t_input prepare_input( const std::string & filename )
{
std::vector< std::string > sInput = FileReader::read_file( filename );
t_input res;
for ( const auto & _line : sInput )
{
std::vector< std::string > params = common::split_line( _line, ' ' );
res.emplace_back( params[ 0 ][ 0 ], std::stoi( params[ 1 ] ) );
}
return res;
}
void move_t( const Point & H, Point & T )
{
if ( std::abs( H.col - T.col ) <= 1
&& std::abs( H.row - T.row ) <= 1 )
{
return;
}
if ( H.row != T.row )
T.row = T.row + ( H.row < T.row ? -1 : 1 );
if( H.col != T.col )
T.col = T.col + ( H.col < T.col ? -1 : 1 );
}
void movement( const t_movement & move, std::vector< Point > & points, std::set< t_coord, PointCmp > & visitedPointsByT )
{
Point & H = points[ 0 ];
switch( move.first )
{
case 'R': H.col += 1; break;
case 'L': H.col -= 1; break;
case 'U': H.row += 1; break;
case 'D': H.row -= 1; break;
default: throw "Wrong input";
}
for ( std::size_t idx = 1; idx < points.size(); ++idx )
move_t( points[ idx - 1 ], points[ idx ] );
visitedPointsByT.insert( t_coord{ points.back().row, points.back().col } );
}
int calc( const t_input & input, int ropeLength )
{
std::set< t_coord, PointCmp > visitedPointsByT;
std::vector< Point > points( ropeLength, Point{ 0, 0 } );
for ( const auto & _move : input )
for ( int repite = 0; repite < _move.second; ++repite )
movement( _move, points, visitedPointsByT );
return visitedPointsByT.size();
}
long long RopeBridge::task_1( const std::string & filename )
{
t_input input = prepare_input( filename );
return calc( input, 2 );
}
long long RopeBridge::task_2( const std::string & filename )
{
t_input input = prepare_input( filename );
return calc( input, 10 );
}
| true |
de3d0b65b5eb066a3a4380a7d548c632a648922b | C++ | SuloUmal/C_Plus_Plus_Beginner | /Project/Good.cpp | UTF-8 | 7,631 | 2.921875 | 3 | [
"MIT"
] | permissive | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <fstream>
#include <iomanip>
#include "Good.h"
#include "Error.h"
using namespace std;
namespace aid
{
Good::Good(char name) {
setEmpty(name);
}
Good::Good(const char* sku, const char* name, const char* unit, int numHand, bool taxApply, double pric, int numNeed) {
set(sku, name, unit, numHand, taxApply, pric, numNeed);
}
//added new function for constructor
void Good::set(const char* sku, const char* nam, const char* unit, int numHand, bool taxApply, double pric, int numNeed) {
if (indicator == 'P'){ setEmpty('P');
}
else { setEmpty(); }
strncpy(itemSku, sku, max_sku_length);
strncpy(goodUnit, unit, max_unit_length);
name(nam);
qntOnHand = numHand;
priceNoTax = pric;
taxable = taxApply;
qntNeed = numNeed;
}
//added new function for constructor
void Good::setEmpty(char type) {
indicator = type;
itemSku[0] = '\0';
goodUnit[0] = '\0';
goodPtr = nullptr;
qntOnHand = 0;
qntNeed = 0;
priceNoTax = 0;
taxable = false;
}
Good::~Good()
{
delete[] goodPtr;
goodPtr = nullptr;
}
Good::Good(const Good ©)
{
int size = strlen(copy.goodPtr);
indicator = copy.indicator;
strncpy(itemSku, copy.itemSku, max_sku_length);
itemSku[max_sku_length] = '\0';
strncpy(goodUnit, copy.goodUnit, max_unit_length);
goodUnit[max_unit_length] = '\0';
qntOnHand = copy.qntOnHand;
qntNeed = copy.qntNeed;
priceNoTax = copy.priceNoTax;
taxable = copy.taxable;
if (copy.goodPtr != nullptr)
{
goodPtr = nullptr;
goodPtr = new char[size];
for (int i = 0; i < size; ++i)
{
goodPtr[i] = copy.goodPtr[i];
}
goodPtr[size] = '\0';
}
}
void Good::name(const char* name)
{
if (name != nullptr)
{
int size = strlen(name);
goodPtr = new char[size];
for (int i = 0; i < size; ++i)
{
goodPtr[i] = name[i];
}
goodPtr[size] = '\0';
}
}
const char* Good::name() const {
return goodPtr;
}
const char* Good::sku() const {
return itemSku;
}
const char* Good::unit() const {
return goodUnit;
}
bool Good::taxed() const {
return taxable;
}
double Good::itemPrice() const {
return priceNoTax;
}
double Good::itemCost() const {
return taxable ? priceNoTax + priceNoTax * tax_rate : priceNoTax;
}
void Good::message(const char* err) {
return errorState.message(err);
}
bool Good::isClear() const {
return errorState.isClear();
}
Good& Good::operator=(const Good ©)
{
if (this != ©)
{
indicator = copy.indicator;
strncpy(itemSku, copy.sku(), max_sku_length);
strncpy(goodUnit, copy.unit(), max_unit_length);
qntOnHand = copy.qntOnHand;
qntNeed = copy.qntNeed;
priceNoTax = copy.priceNoTax;
taxable = copy.taxable;
if (copy.goodPtr != nullptr)
{
int length = strlen(copy.goodPtr);
goodPtr = new char[length];
for (int i = 0; i < length; ++i)
{
goodPtr[i] = copy.goodPtr[i];
}
goodPtr[length] = '\0';
}
else
{
delete[] goodPtr;
goodPtr = nullptr;
}
}
return *this;
}
std::fstream& Good::store(std::fstream& file, bool newLine) const
{
file << indicator << "," << itemSku << "," << goodPtr << "," << goodUnit << "," << taxable << "," << priceNoTax << "," << qntOnHand << "," << qntNeed;
if (newLine) file << endl;
return file;
}
std::fstream& Good::load(std::fstream &file)
{
char itemSku[max_sku_length + 1];
char name[max_name_length + 1];
char goodUnit[max_unit_length + 1];
int qntOnHand;
int qntNeed;
double priceNoTax;
bool taxable;
char ask;
char throw_char;
file.getline(itemSku, max_sku_length, ',');
file.getline(name, max_sku_length, ',');
file.getline(goodUnit, max_sku_length, ',');
file >> ask;
if (ask == '1')
{
taxable = true;
}
else if (ask == '0')
{
taxable = false;
};
file >> throw_char >> priceNoTax >> throw_char >> qntOnHand >> throw_char >> qntNeed >> throw_char;
set(itemSku, name, goodUnit, qntOnHand, taxable, priceNoTax, qntNeed);
return file;
}
std::ostream& Good::write(std::ostream &os, bool linear) const
{
if (errorState.isClear()) {
if (!isEmpty()) {
if (linear)
{
os << setw(max_sku_length) << left << itemSku << '|' << setw(20);
if (goodPtr == nullptr) os << ""; else
os << left << goodPtr << '|';
os << setw(7) << right << fixed << setprecision(2) << itemCost() << '|'
<< setw(4) << right << qntOnHand << '|'
<< setw(10) << left << goodUnit << '|'
<< setw(4) << right << qntNeed << '|';
}
else
{
os << " Sku: " << sku() << endl
<< " Name (no spaces): " << goodPtr << endl
<< " Price: " << itemPrice() << endl << " Price after tax: ";
if (taxable) {
os << itemCost() << endl;
}
else {
os << "N/A"
<< endl;
}
os << " Quantity on Hand: " << quantity() << " " << unit() << endl
<< " Quantity needed: " << qtyNeeded();
}
}
}
else { os << errorState; }
return os;
}
std::istream& Good::read(std::istream& is)
{
char itemSku[max_sku_length + 1];
char goodPtr [max_name_length + 1];
char goodUnit[max_unit_length + 1];
int qntOnHand;
int qntNeed;
double priceNoTax;
char choice;
bool taxable;
Error errorState;
this->errorState.clear();
cout << " Sku: ";
is >> itemSku;
cout << " Name (no spaces): ";
is >> goodPtr;
cout << " Unit: ";
is >> goodUnit;
cout << " Taxed? (y/n): ";
is >> choice;
if (choice != 'y' && choice != 'Y'&& choice != 'n'&& choice != 'N') {
this->errorState.message("Only (Y)es or (N)o are acceptable");
is.setstate(std::ios::failbit);
}
else
if (choice == 'Y' || choice == 'y')
{
taxable = true;
}
else if (choice == 'N' || choice == 'n')
{
taxable = false;
}
if (!is.fail() && this->errorState.isClear()) {
cout << " Price: ";
is >> priceNoTax;
if (is.fail()) {
this->errorState.message("Invalid Price Entry");
is.setstate(std::ios::failbit);
}
}
if (!is.fail() && this->errorState.isClear()) {
cout << " Quantity on hand: ";
is >> qntOnHand;
if (is.fail()) {
this->errorState.message("Invalid Quantity Entry");
is.setstate(std::ios::failbit);
}
}
if (!is.fail() && this->errorState.isClear()) {
cout << " Quantity needed: ";
is >> qntNeed;
if (is.fail()) {
this->errorState.message("Invalid Quantity Needed Entry");
is.setstate(std::ios::failbit);
}
}
if (!is.fail() && this->errorState.isClear()) {
set(itemSku, goodPtr, goodUnit, qntOnHand, taxable, priceNoTax, qntNeed);
}
return is;
}
bool Good::operator==(const char* compare) const {
return strcmp(itemSku, compare) == 0;
}
double Good::total_cost() const {
return itemCost()*qntOnHand;
}
void Good::quantity(int units)
{
qntOnHand = units;
}
bool Good::isEmpty() const {
return strcmp(itemSku, "") == 0;
}
int Good::qtyNeeded() const
{
return qntNeed;
}
int Good::quantity() const
{
return qntOnHand;
}
bool Good::operator>(const char* itemSku) const {
return strcmp(itemSku, "") == 1;
}
bool Good::operator>(const iGood& object) const {
return strcmp(name(), object.name()) == 1;
}
int Good::operator+=(int add) {
return qntOnHand += add;
}
std::ostream& operator<<(std::ostream& os, const iGood& object) {
return object.write(os, true);
}
std::istream& operator>>(std::istream& is, iGood& object) {
return object.read(is);
}
double operator+=(double& total, const iGood& object) {
return total + object.total_cost();
}
} | true |
a04251fd76cb8e8cae4e5b827d03ac6c9e405430 | C++ | league/subpixelize | /subpixelize.cpp | UTF-8 | 1,637 | 3.21875 | 3 | [] | no_license | #include <Magick++.h>
#include <iostream>
#include <cassert>
using std::cout;
using std::string;
using namespace Magick;
/* Each pixel in input image is rendered as
* GRBx
* BRGx
* xxxx
* in the output image. So pixels are 4x3,
* including inter-pixel space.
*/
int main(int argc, char** argv)
{
InitializeMagick(*argv);
if(argc != 3) {
cout << "Usage: " << argv[0] << " input.png output.png\n";
exit(1);
}
const string inputPath = argv[1];
const string outputPath = argv[2];
cout << "Loading " << inputPath << '\n';
Image in (inputPath);
Geometry gin = in.size();
assert(in.depth() <= 8);
assert(in.type() == TrueColorType);
cout << gin.width() << 'x' << gin.height() << '\n';
Geometry gout(gin.width()*4, gin.height()*3);
Image out;
out.size(gout);
out.magick("RGBA");
cout << "Writing " << outputPath << '\n';
for(unsigned x = 0; x < gin.width(); x++) {
for(unsigned y = 0; y < gin.height(); y++) {
Color c = in.pixelColor(x,y);
unsigned i = x*4;
unsigned j = y*3;
// Row 0: GRB
out.pixelColor(i+0, j+0, Color(0, c.greenQuantum(), 0));
out.pixelColor(i+1, j+0, Color(c.redQuantum(), 0, 0));
out.pixelColor(i+2, j+0, Color(0, 0, c.blueQuantum()));
// Row 1: BRG
out.pixelColor(i+0, j+1, Color(0, 0, c.blueQuantum()));
out.pixelColor(i+1, j+1, Color(c.redQuantum(), 0, 0));
out.pixelColor(i+2, j+1, Color(0, c.greenQuantum(), 0));
}
}
out.write(outputPath);
return 0;
}
| true |
0cb5befe3f6e92fce33424184af5a319d92eb792 | C++ | zmq175/DiscManager | /DiskManager/DiskManager/DiscList.cpp | GB18030 | 1,194 | 3.078125 | 3 | [] | no_license | #include "DiscList.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void DiscList::add(Disc &d)
{
Disc* pivot=new Disc(d);
if(ptr)
{
pivot->next=ptr;
}
if(!ptr)
{
pivot->next=NULL;
}
ptr=pivot;
}
void DiscList::display()
{
for (Disc* pivot = ptr; pivot; pivot=pivot->next)
{
pivot->show();
}
}
void DiscList::find()
{
string input = "null";
cout << "ӭʹϵͳ\nҪҵӲƣ\n";
cin >> input;
for (Disc* i = ptr; i ; i=i->next)
{
if (i->getName().find(input)!=i->getName().npos)
{
i->show();
cout << endl;
}
}
}
void DiscList::write()
{
ofstream out("Disclist.dmdata");
for (Disc* i = ptr; i!=NULL ; i=i->next)
{
if (!i->issetISBN())
{
out << i->getName() << i->getCountry() << i->getCategory() << i->getISBN() << i->getTotal()<<endl;
}
}
}
void DiscList::userDiscFind(string iisbn)
{
for (Disc* m = ptr; m ; m = m->next)
{
if (m->getISBN() == iisbn)
{
cout << "ӰƬƣ" << m->getName() << endl;
cout << "ң" << m->getCountry() << endl;
cout << "" << m->getCategory() << endl;
cout << "ISBN" << m->getISBN() << endl;
}
}
} | true |
a96a0252a91bf1378b9651c04b88c55da77a831a | C++ | lamesrich/LouidorRichemond_CSC5_46091_Sum2015 | /blackjack project folder 2 works/project V1/test/main.cpp | UTF-8 | 1,907 | 2.90625 | 3 | [] | no_license | //system library
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//function prototypes
//execution begins here
int main ()
{
//declaring variables
int x=0, y=0, ct=0, ct2=0, SIZE;
srand(time(0));
//prompting user to enter number of players
cout <<"How many players: ";
cin>> SIZE;
int bet[SIZE];
int chips[SIZE];
int card[SIZE];
string name[SIZE];
/*for(x; x<SIZE; x++)
{
ct++;
cout <<"Enter player "<<ct<<" Name: ";
//cin>>name[x];
/*cout <<" buy in $";
cin >>chips[x];
cout <<endl;
}
cout <<endl;*/
for (int j=0; j<SIZE; j++)
{
card[j]=rand()% 11 +1;
}
cout <<endl;
for (int l=0; l<SIZE; l++)
{
ct2++;
//cout
cout <<"Card "<<ct2 <<": "<<card[l]<<endl;
}
//USER PLACING BET
/*for(y; y<SIZE; y++)
{
cout <<name[y] <<" PLace Bet: $";
cin>>bet[y];
}
cout <<endl;
//testing for losing and winning bet
for(int i=0; i<SIZE; i++)
{
if(bet[i]<10)
{
chips[i]-=bet[i];
cout <<name[i] <<" lost bet remaining chips $"<<chips[i]<<endl;
}
else
{
chips[i]+=bet[i];
cout <<name[i] <<" won bet remaining chips $"<<chips[i]<<endl;
}
}*/
cout <<endl;
return 0;
}
| true |
8fe8581e09da8c25322900d5648cae45ef990ff4 | C++ | Mahmoudalziem/ITI_9_month_labs_OS_track | /Data-Structure-Labs/doubleLinkedList/main.cpp | UTF-8 | 3,926 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Employee
{
string name;
int id;
public:
Employee* pNext;
Employee* pPrevious;
Employee()
{name="no name"; id = 0;}
Employee(string n , int i)
{name = n; id = i; pNext = pPrevious = NULL;}
///getter & setter
void setName(string n)
{
name = n;
}
void setId(int i)
{
id = i;
}
string getName()
{
return name;
}
int getId()
{
return id;
}
void getEmp()
{
cout<<"Enter the name and id : ";
cin>>name;
cin>>id;
}
void printEmployee()
{
cout<<"Name : "<< name <<" id: "<< id <<endl;
}
};
class LinkedList
{
protected:
Employee* pStart;
Employee* pEnd;
public:
LinkedList();
~LinkedList();
void addList(Employee *pEmp);
Employee* searchEmp(int key);
void displayAll();
int deleteList(int key);
void freeList();
void insertion(Employee *pNode);
};
LinkedList::LinkedList()
{
pStart = pEnd = NULL;
}
LinkedList::~LinkedList()
{
// freeList();
}
void LinkedList::addList(Employee *pEmp)
{
if( pStart==NULL)
{
pEmp->pNext = NULL;
pEmp->pPrevious = NULL;
pStart = pEnd = pEmp;
}
else
{
pEnd->pNext = pEmp;
pEmp->pPrevious = pEnd;
pEnd = pEmp;
}
}
Employee* LinkedList::searchEmp(int key)
{
Employee *pItem;
pItem = pStart;
while(pItem != NULL && pItem->getId()!= key)
{
pItem = pItem->pNext;
}
return pItem;
}
void LinkedList::displayAll()
{
Employee *pItem;
pItem = pStart;
while(pItem)
{
pItem->printEmployee();
pItem = pItem->pNext;
}
}
int LinkedList::deleteList(int key)
{
Employee *pItem;
int flag = 1;
pItem = searchEmp(key);
if(!pItem)
flag = 0;
else{
if(pItem == pStart)
{
pStart = pStart->pNext;
pStart->pPrevious = NULL;
pItem ->pNext = NULL;
}
else if(pItem == pEnd)
{
pEnd = pEnd->pPrevious;
pEnd->pNext = NULL;
// PItem->pPrevious =NULL;
}
else
{
pItem->pPrevious->pNext=pItem->pNext;
pItem->pNext->pPrevious= pItem->pPrevious;
pItem->pNext=NULL;
pItem->pPrevious=NULL;
}
delete pItem;
}
return flag;
}
void LinkedList::freeList()
{
Employee *pItem;
while(pStart)
{
pItem = pStart;
pStart = pStart->pNext;
delete pItem;
}
pEnd = NULL; ///ask
}
void LinkedList::insertion(Employee *pNode)
{
Employee *pItem;
if(pStart == NULL)
addList(pNode);
else
{
pItem = pStart;
while(pItem && pNode->getId()> pItem->getId())
pItem=pItem->pNext;
if(!pItem)
addList(pNode);
else if(pItem == pStart)
{
pNode->pNext = pStart;
pNode->pPrevious=NULL;
pStart->pPrevious = pNode;
pStart = pNode;
}
else
{
pNode->pNext=pItem;
pNode->pPrevious = pItem->pPrevious;
pItem->pPrevious->pNext = pNode;
pItem->pPrevious=pNode;
}
}
}
int main()
{
int i;
LinkedList LD;
Employee *e=new Employee[2];
Employee e1("ALI" , 35);
for(i = 0 ; i < 2 ; i++)
{
e[i].getEmp();
LD.addList(&e[i]);
}
LD.displayAll();
cout<<"flag : "<<LD.deleteList(5)<<endl;
LD.insertion(&e1);
LD.displayAll();
return 0;
}
| true |
2c93885e155785726371ecc4afac15a8adadd0b7 | C++ | MarcoLotto/ScaenaFramework | /ExampleProject/src/ExamplePipelineBuilder.cpp | WINDOWS-1250 | 9,344 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "ExamplePipelineBuilder.h"
#include "RenderPipelineWithGeometryAndBackWrite.h"
#include "BloomStage.h"
#include "DeferredGeometryStage.h"
#include "PhongLightingStage.h"
#include "BlurStage.h"
#include "UserInterfaceStage.h"
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigForward(UIController* uiController, Scene* scene){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Inicializamos una etapa de geometria forward
ForwardGeometryStage* geometryStage = getGeometryForwardStage(uiController, scene, renderPipelineImp);
// Asignamos los stage al pipeline
renderPipelineImp->addGeometryStage(geometryStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
}
// El forward geometry stage se utiliza para renderizar geometria en una sola etapa (es decir la iluminacion se produce en el mismo shader de geometria)
ForwardGeometryStage* ExamplePipelineBuilder::getGeometryForwardStage(UIController* uiController, Scene* scene, RenderPipelineWithGeometryAndBackWrite* pipeline){
vec2 size = uiController->getScreenSize();
ForwardGeometryStage* geometryStage = new ForwardGeometryStage(size.x, size.y, false);
geometryStage->setScene(scene); // Le seteo la escena a renderizar al geometry stage
scene->getLightingManager()->getShadowManager()->setRenderPipeline(pipeline);
return geometryStage;
}
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigForwardAndBloom(UIController* uiController, Scene* scene){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Inicializamos una etapa de geometria forward
ForwardGeometryStage* geometryStage = getGeometryForwardStage(uiController, scene, renderPipelineImp);
// Inicializamos una etapa de bloom (sobre-exposicion de luz)
vec2 size = uiController->getScreenSize();
BloomStage* bloomStage = new BloomStage(geometryStage, size.x, size.y, 8.0f);
bloomStage->setLumThreshold(0.7f);
// Asignamos los stage al pipeline
renderPipelineImp->addGeometryStage(geometryStage);
renderPipelineImp->addAfterGeometry(bloomStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
}
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigDeferred(UIController* uiController, Scene* scene){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Creamos una etapa de deferred geometry shading (la iluminacin ocurre por separado de la geometria)
DeferredGeometryStage* geometryStage = getGeometryDeferredStage(uiController, scene, renderPipelineImp);
// Ahora creamos una etapa de iluminacion
vec2 size = uiController->getScreenSize();
PhongLightingStage* lightingStage = new PhongLightingStage(geometryStage, size.x, size.y);
lightingStage->setScene(scene);
// Cargamos las etapas al pipeline (geometria e iluminacion ocurren en diferentes etapas)
renderPipelineImp->addGeometryStage(geometryStage);
renderPipelineImp->addAfterGeometry(lightingStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
}
// El forward geometry stage se utiliza para renderizar geometria en una sola etapa (es decir la iluminacion se produce en el mismo shader de geometria)
DeferredGeometryStage* ExamplePipelineBuilder::getGeometryDeferredStage(UIController* uiController, Scene* scene, RenderPipelineWithGeometryAndBackWrite* pipeline){
vec2 size = uiController->getScreenSize();
DeferredGeometryStage* geometryStage = new DeferredGeometryStage(size.x, size.y);
geometryStage->setScene(scene); // Le seteo la escena a renderizar al geometry stage
scene->getLightingManager()->getShadowManager()->setRenderPipeline(pipeline);
return geometryStage;
}
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigDeferredAndDepthOfField(UIController* uiController, Scene* scene, bool nearDepthActive){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Creamos una etapa de deferred geometry shading (la iluminacin ocurre por separado de la geometria)
DeferredGeometryStage* geometryStage = getGeometryDeferredStage(uiController, scene, renderPipelineImp);
// Ahora creamos una etapa de iluminacion
vec2 size = uiController->getScreenSize();
PhongLightingStage* lightingStage = new PhongLightingStage(geometryStage, size.x, size.y);
lightingStage->setScene(scene);
// Creamos un stage de depth of field
DepthOfFieldStage* depthOfFieldStage = getDepthofFieldStage(geometryStage, lightingStage, size, nearDepthActive);
depthOfFieldStage->setDepthAtBlurStart(7.0f);
depthOfFieldStage->setBlurFalloff(1.0f);
// Cargamos las etapas al pipeline (geometria e iluminacion ocurren en diferentes etapas)
renderPipelineImp->addGeometryStage(geometryStage);
renderPipelineImp->addAfterGeometry(lightingStage);
renderPipelineImp->addAfterGeometry(depthOfFieldStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
}
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigDeferredAndSSAO(UIController* uiController, Scene* scene){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Creamos una etapa de deferred geometry shading (la iluminacin ocurre por separado de la geometria)
DeferredGeometryStage* geometryStage = getGeometryDeferredStage(uiController, scene, renderPipelineImp);
// Agregamos una etapa de ambient occlussion (SSAO), y al resultado una de blur (A su vez esto sera utilizado por el stage de
// iluminacion para simular sombras en determinados lugares para iluminacion mas realista)
vec2 size = uiController->getScreenSize();
SSAORenderStage* ssaoStage = new SSAORenderStage(geometryStage, size.x, size.y);
BlurStage* ssaoBlurStage = new BlurStage(ssaoStage, size.x, size.y, 2.5f);
// Ahora creamos una etapa de iluminacion y le damos la informacion del ssao procesado
PhongLightingStage* lightingStage = new PhongLightingStage(geometryStage, size.x, size.y, ssaoBlurStage);
lightingStage->setScene(scene);
// Cargamos las etapas al pipeline (primero geometria, luego ssao, luego su blur y luego con todos los datos a iluminacion)
renderPipelineImp->addGeometryStage(geometryStage);
renderPipelineImp->addAfterGeometry(ssaoStage);
renderPipelineImp->addAfterGeometry(ssaoBlurStage);
renderPipelineImp->addAfterGeometry(lightingStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
}
DepthOfFieldStage* ExamplePipelineBuilder::getDepthofFieldStage(DeferredGeometryStage* geometryStage, BackBufferWriterStage* lastStage, vec2 size, bool nearDepthActive){
DepthOfFieldStage* depthOfFieldStage = NULL;
if(nearDepthActive)
depthOfFieldStage = new DepthOfFieldStage(geometryStage, lastStage, size.x, size.y, 5.0f, 40.0f, false);
else
depthOfFieldStage = new DepthOfFieldStage(geometryStage, lastStage, size.x, size.y, 5.0f, 15.0f, true);
depthOfFieldStage->setBlurFalloff(0.1f);
return depthOfFieldStage;
}
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigForwardAndBlur(UIController* uiController, Scene* scene){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Inicializamos una etapa de geometria forward
ForwardGeometryStage* geometryStage = getGeometryForwardStage(uiController, scene, renderPipelineImp);
// Instaciamos una etapa de blur para aplicar sobre la imagen de geometria final
vec2 size = uiController->getScreenSize();
BlurStage* blurStage = new BlurStage(geometryStage, size.x, size.y, 8.0f);
// Asignamos los stages al pipeline
renderPipelineImp->addGeometryStage(geometryStage);
renderPipelineImp->addAfterGeometry(blurStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
}
RenderPipeline* ExamplePipelineBuilder::getRenderPipelineConfigForwardAndUI(UIController* uiController, Scene* scene){
// Configuro el render pipeline
RenderPipelineWithGeometryAndBackWrite* renderPipelineImp = new RenderPipelineWithGeometryAndBackWrite();
// Inicializamos una etapa de geometria forward
ForwardGeometryStage* geometryStage = getGeometryForwardStage(uiController, scene, renderPipelineImp);
// Instanciamos una etapa de renderizado de UI para mostrar arriba de todo la interfaz de usuario
vec2 size = uiController->getScreenSize();
UserInterfaceStage* userInterfaceStage = new UserInterfaceStage(geometryStage, size.x, size.y);
userInterfaceStage->setUiController(uiController);
// Asignamos los stages al pipeline
renderPipelineImp->addGeometryStage(geometryStage);
renderPipelineImp->addAfterGeometry(userInterfaceStage);
// Terminado el pipeline, lo mando a cargar
renderPipelineImp->updatePipelineScheme();
return renderPipelineImp;
} | true |
e8aef4a0adac3550d5d7ef3b9637bf1e6092ea8a | C++ | nukazuka/RootFileViewer | /include/misc.hh | UTF-8 | 627 | 2.78125 | 3 | [] | no_license | #ifndef MISC_HH
#define MISC_HH
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
template < typename T >
void ShowVC( vector < T >& vT )
{
for( unsigned int i=0; i<vT.size(); i++ )
cout << setw(3) << i << "\t" << vT[i] << endl;
}
template < typename T >
//void ShowVC2D( vector < vector < T > >& vT )
void ShowVC2D( vector < T >& vT )
{
if( vT.size() == 0 )
return ;
for( unsigned int i=0; i<vT.size(); i++ )
{
cout << setw(3) << i << " ";
for( unsigned int j=0; i<vT[i].size(); j++ )
{
cout << vT[i][j] << " " ;
}
cout << endl;
}
}
#endif
| true |
8e2aec5cd23304a7fbf2eb0df39be54e077f8f5c | C++ | nikkaramessinis/QtCurvesCPP | /renderarea.cpp | UTF-8 | 5,500 | 2.6875 | 3 | [] | no_license | #include "renderarea.h"
#include <QPaintEvent>
#include <iostream>
#include <QPainter>
RenderArea::RenderArea(QWidget *parent) : QWidget(parent),mBackgroundColor(0,0,255),mPen(Qt::white),mShape(Astroid){
mPen.setWidth(2);
on_shape_change();
}
QSize RenderArea::minimumSizeHint() const {return QSize(400,400);}
QSize RenderArea::sizeHint() const {return QSize(400,400);}
void RenderArea::on_shape_change(){
switch(mShape){
case Astroid:
mScale=90;
mIntervalLength=2*M_PI;
mStepCount=256;
break;
case Cycloid:
mScale=10;
mIntervalLength=4*M_PI;
mStepCount=128;
break;
case HygensCicloid:
mScale=10;
mIntervalLength=4*M_PI;
mStepCount=256;
break;
case HypoCicloid:
mScale=40;
mIntervalLength=2*M_PI;
mStepCount=256;
break;
case Line:
mScale=50;//line length
mIntervalLength=2;
mStepCount=100;
break;
case Circle:
mScale=100;//line length
mIntervalLength=2*M_PI;
mStepCount=128;
break;
case Ellipse:
mScale=75;//line length
mIntervalLength=2*M_PI;
mStepCount=256;
break;
case Fancy:
mScale=10;//line length
mIntervalLength=12*M_PI;
mStepCount=512;
break;
case StarFish:
mScale=25;//line length
mIntervalLength=6*M_PI;
mStepCount=256;
break;
case Cloud:mScale=10;
mIntervalLength=28*M_PI;
mStepCount=128;
break;
case Sun:
mScale=10;
mIntervalLength=28*M_PI;
mStepCount=128;
break;
default:
break;
}
}
QPointF RenderArea::compute_cycloid(float t){
return QPointF(1.5*(1-cos(t))//x
,1.5*(t-sin(t))//y
);
}
QPointF RenderArea::compute_line(float t){
return QPointF(1-t,1-t);
}
QPointF RenderArea::compute_huygens(float t){
return QPointF(4*(3*cos(t)-cos(3*t)),4*(3*sin(t)-sin(3*t)));
}
QPointF RenderArea::compute_hypocicloid(float t){
return QPointF(
1.5*(2*cos(t)+cos(2*t)),//X
1.5*(2*sin(t)-sin(2*t))//Y
);
}
QPointF RenderArea::compute_astroid(float t){
float cos_t=cos(t);
float sin_t=sin(t);
float x=2*cos_t*cos_t*cos_t;//pow(co_t,3);
float y=2*sin_t*sin_t*sin_t;
return QPointF(x,y);
}
QPointF RenderArea::compute_circle(float t){
float x=cos(t);
float y=sin(t);
return QPointF(x,y);
}
QPointF RenderArea::compute_ellipse(float t){
float a=2;
float b=1.1;
return QPointF(a*cos(t),b*sin(t));
}
QPointF RenderArea::compute_fancy(float t){
return QPointF(11.0f*cos(t)-6*cos((11.0f/6)*t),11.0f*sin(t)-6*sin((11.0f/6)*t));
}
QPointF RenderArea::compute_starfish(float t){
int R=5;
int r=3;
int d=5;
return QPointF((R-r)*cos(t)+d*cos(t*(R-r)/r),(R-r)*sin(t)-d*sin(t*(R-r)/r));
}
QPointF RenderArea::compute_skythings(float t,float sign){
float a=14;
float b=1;
float x=(a+b)*cos(t*b/a)-sign*b*cos(t*(a+b)/a);
float y=(a+b)*sin(t*b/a)-b*sin(t*(a+b)/a);
return QPointF(x,y);
}
QPointF RenderArea::compute_sun(float t){
return compute_skythings(t,-1);
}
QPointF RenderArea::compute_cloud(float t){
return compute_skythings(t,1);
}
QPointF RenderArea::compute(float t)
{
switch(mShape){
case Astroid:
return compute_astroid(t);
break;
case Cycloid:
return compute_cycloid(t);
break;
case HygensCicloid:
return compute_huygens(t);
break;
case HypoCicloid:
return compute_hypocicloid(t);
break;
case Line:
return compute_line(t);
break;
case Circle:
return compute_circle(t);
break;
case Ellipse:
return compute_ellipse(t);
break;
case Fancy:
return compute_fancy(t);
break;
case StarFish:
return compute_starfish(t);
break;
case Cloud:
return compute_cloud(t);
break;
case Sun:
return compute_sun(t);
default:
break;
}
return QPointF(0,0);
}
void RenderArea::paintEvent(QPaintEvent *event){
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing,true);
// switch(mShape){
// case Astroid:
// mBackgroundColor=Qt::green;
// break;
// case Cycloid:
// mBackgroundColor=Qt::blue;
// break;
// case HygensCicloid:
// mBackgroundColor=Qt::black;
// break;
// case HypoCicloid:
// mBackgroundColor=Qt::red;
// break;
// default:
// break;
// }
painter.setBrush(mBackgroundColor);
painter.setPen(mPen);
//drawing area
painter.drawRect(this->rect());
QPoint center=this->rect().center();
QPointF prevPoint=compute(0);
QPoint prevPixel;
prevPixel.setX(prevPoint.x()*mScale+center.x());
prevPixel.setY(prevPoint.y()*mScale+center.y());
float step=mIntervalLength/mStepCount;
for(float t=0;t<mIntervalLength;t+=step){
QPointF point=compute(t);
QPoint pixel;
pixel.setX(point.x()*mScale+center.x());
pixel.setY(point.y()*mScale+center.y());
painter.drawLine(pixel,prevPixel);
prevPixel=pixel;
}
QPointF point=compute(mIntervalLength);
QPoint pixel;
pixel.setX(point.x()*mScale+center.x());
pixel.setY(point.y()*mScale+center.y());
painter.drawLine(pixel,prevPixel);
}
| true |
579c76f91e33fca24dd447d974240de3046dd409 | C++ | aramhamidi/ATM | /src/Screen.cpp | UTF-8 | 945 | 2.953125 | 3 | [] | no_license | /**
* @Author: Aram Hamidi <aramhamidi>
* @Date: 2018-08-21T11:04:58-07:00
* @Email: aram.hamidi@getcruise.com
* @Project: Laser_Driver_A53
* @Filename: Screem.cpp
* @Last modified by: aramhamidi
* @Last modified time: 2018-08-21T12:15:51-07:00
*/
// Screen.cpp
// Member-function definitions for class Screen.
#include <iostream>
using std::cout;
using std::endl;
using std::fixed;
#include <iomanip>
using std::setprecision;
#include "Screen.h" // Screen class definition
// output a message without a newline
void Screen::displayMessage(string message ) const
{
cout << message;
} // end function displayMessage
// output a message with a newline
void Screen::displayMessageLine(string message ) const
{
cout << message << endl;
} // end function displayMessageLine
// output a dollar amount
void Screen::displayDollarAmount( double amount ) const
{
cout << fixed << setprecision( 2 ) << "$" << amount;
} // end function displayDollarAmount
| true |
d560232e1d13a2b512b710fefe71012086b943dd | C++ | kimny22/Algorithm | /heapsort.cpp | UTF-8 | 841 | 3.484375 | 3 | [] | no_license | #include <stdio.h>
void heapify(int A[], int k, int n) {
int left = 2 * k + 1;
int right = 2 * k + 2;
int smaller = 0;
if (right <= n) {
if (A[left] < A[right]) smaller = left;
else smaller = right;
}
else if (left <= n) smaller = left;
else return;
if (A[smaller] < A[k]) {
int t = A[k];
A[k] = A[smaller];
A[smaller] = t;
heapify(A, smaller, n);
}
}
void buildheap(int A[], int n) {
for (int i = n / 2; i >= 0; i--) { heapify(A, i, n); }
}
void heapSort(int A[], int n) {
buildheap(A, n);
for (int i = n; i >= 0; i--) {
int t = A[0];
A[0] = A[i];
A[i] = t;
n--;
heapify(A, 0, n);
}
}
int main() {
int A[10] = { 64,32,1,8,62,78,33,21,87,34 };
for (int i = 0; i < 10; i++) {
printf("%d ", A[i]);
}
heapSort(A, 9);
printf("\nsorted\n");
for (int i = 0; i < 10; i++) {
printf("%d ", A[i]);
}
} | true |
e99b7a77a5ecc9cb416712932e5d009c07eba4e3 | C++ | mcmlevi/Portfolio_Levi_de_koning | /RayTracer/MathLib/vec3f.h | UTF-8 | 4,313 | 2.828125 | 3 | [] | no_license | #pragma once
#include "cmath"
#include <cassert>
#include <xmmintrin.h>
#include <immintrin.h>
_MM_ALIGN16 class Vec3f
{
public:
#pragma warning(push)
#pragma warning(disable : 4201 )
union
{
__m128 SIMD;
float m_coordinates[4];
struct
{
float m_x;
float m_y;
float m_z;
float m_w;
};
};
// Constructors
//Vec3f() :m_x{ 0.f }, m_y{ 0.f }, m_z{ 0.f } { }
Vec3f(float x = 0.f, float y = 0.f, float z = 0.f) : SIMD{_mm_set_ps(0.f,z,y,x)} { }
Vec3f(const __m128& input) :SIMD{input} {}
//Vec3f(Vec3f& rhs) :floats{rhs.floats} {}
/// Overloaded operators that ensure alignment
float& operator[](const int index);
const float& operator[](const int index)const;
// Math operators
Vec3f operator*(const Vec3f& rhs) const;
Vec3f operator*(const float rhs) const;
Vec3f operator-(const Vec3f& rhs) const;
Vec3f operator+(const Vec3f& rhs) const;
Vec3f operator/(const float rhs) const;
// Assignment operators
Vec3f& operator*=(const Vec3f& rhs);
Vec3f& operator*=(const float rhs);
Vec3f& operator/=(const float rhs);
Vec3f& operator+=(const Vec3f& rhs);
Vec3f& operator-=(const Vec3f& rhs);
Vec3f& operator=(const Vec3f& rhs);
// Conditional operators
bool operator==(const Vec3f& rhs)const;
bool operator!=(const Vec3f& rhs)const;
// Vector specific functions
float dot(const Vec3f& rhs)const ;
Vec3f cross(const Vec3f rhs) const;
void clear();
float lenght() const;
float lenght2()const;
Vec3f& normalize();
Vec3f getNormalCopy();
};
inline float& Vec3f::operator[](const int index)
{
assert(index <= 2 && index >= 0);
return m_coordinates[index];
}
inline const float& Vec3f::operator[](const int index) const
{
assert(index <= 2 && index >= 0);
return m_coordinates[index];
}
inline Vec3f Vec3f::operator*(const Vec3f& rhs) const
{
return _mm_mul_ps(this->SIMD, rhs.SIMD);
}
inline Vec3f Vec3f::operator*(const float rhs) const
{
return _mm_mul_ps(this->SIMD, _mm_set_ps1(rhs));
}
inline Vec3f Vec3f::operator-(const Vec3f& rhs) const
{
return _mm_sub_ps(SIMD,rhs.SIMD);
}
inline Vec3f Vec3f::operator+(const Vec3f& rhs) const
{
return _mm_add_ps(SIMD, rhs.SIMD);
}
inline Vec3f Vec3f::operator/(const float rhs) const
{
return _mm_div_ps(SIMD, _mm_set_ps1(rhs));
}
inline Vec3f& Vec3f::operator*=(const Vec3f& rhs)
{
SIMD = _mm_mul_ps(this->SIMD, rhs.SIMD);
return *this;
}
inline Vec3f& Vec3f::operator*=(const float rhs)
{
SIMD = _mm_mul_ps(this->SIMD, _mm_set_ps1(rhs));
return *this;
}
inline Vec3f& Vec3f::operator/=(const float rhs)
{
SIMD = _mm_div_ps(SIMD, _mm_set_ps1(rhs));
return *this;
}
inline Vec3f& Vec3f::operator+=(const Vec3f& rhs)
{
SIMD = _mm_add_ps(SIMD, rhs.SIMD);
return *this;
}
inline Vec3f& Vec3f::operator-=(const Vec3f& rhs)
{
SIMD = _mm_sub_ps(SIMD, rhs.SIMD);
return *this;
}
inline Vec3f& Vec3f::operator=(const Vec3f& rhs)
{
SIMD = rhs.SIMD;
return *this;
}
inline bool Vec3f::operator==(const Vec3f& rhs) const
{
return (((_mm_movemask_ps(_mm_cmpeq_ps(SIMD, rhs.SIMD))) & 0x7) == 0x7);
}
inline bool Vec3f::operator!=(const Vec3f& rhs) const
{
return !(*this == rhs);
}
inline float Vec3f::dot(const Vec3f& rhs) const
{
//return m_x * rhs.m_x + m_y * rhs.m_y + m_z * rhs.m_z;
//float result{};
// 1110 1000
// 0111 1000
return _mm_cvtss_f32(_mm_dp_ps(SIMD, rhs.SIMD, 113));
}
inline Vec3f Vec3f::cross(const Vec3f rhs) const
{
return _mm_sub_ps(
_mm_mul_ps(_mm_shuffle_ps(SIMD, SIMD, _MM_SHUFFLE(3, 0, 2, 1)), _mm_shuffle_ps(rhs.SIMD, rhs.SIMD, _MM_SHUFFLE(3, 1, 0, 2))),
_mm_mul_ps(_mm_shuffle_ps(SIMD, SIMD, _MM_SHUFFLE(3, 1, 0, 2)), _mm_shuffle_ps(rhs.SIMD, rhs.SIMD, _MM_SHUFFLE(3, 0, 2, 1)))
);
}
inline void Vec3f::clear()
{
m_x = 0.f;
m_y = 0.f;
m_z = 0.f;
}
inline Vec3f operator*(float lhs, const Vec3f& rhs)
{
return _mm_mul_ps(rhs.SIMD, _mm_set_ps1(lhs));
}
inline float Vec3f::lenght() const
{
return (_mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(SIMD, SIMD, 113))));
}
inline float Vec3f::lenght2() const
{
return (_mm_cvtss_f32(_mm_dp_ps(SIMD, SIMD, 113)));
}
inline Vec3f& Vec3f::normalize()
{
SIMD = _mm_div_ps(SIMD, _mm_sqrt_ps(_mm_dp_ps(SIMD, SIMD, 127)));
return *this;
}
inline Vec3f Vec3f::getNormalCopy()
{
float magnitude = this->lenght();
return { m_x / magnitude,m_y / magnitude,m_z / magnitude };
}
#pragma warning(pop) | true |
6bd7d097ead919adbd7406e1a43d60702aa2cfb9 | C++ | siy93/Problem_Solving | /10834.cpp | UTF-8 | 497 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int M, s;
int a, b, lcm;
int rotateNum, rotateType;
scanf("%d", &M);
scanf("%d %d %d",&a,&b,&s);
b /= a, a /= a;
rotateNum = b, rotateType = (0 ^ s);
for(int i=0; i<M-1; i++){
scanf("%d %d %d",&a,&b,&s);
lcm = rotateNum / a;
a *= lcm, b *= lcm;
rotateNum = b, rotateType ^= s;
}
printf("%d %d",rotateType, rotateNum);
return 0;
}
| true |
b3ff6ce4d6275746e192d9855df23402a6cca4fb | C++ | Jochen0x90h/RoomControl_old | /Emulator/DeviceState.hpp | UTF-8 | 612 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Device.hpp"
#include "util.hpp"
class DeviceState {
public:
void init(const Device &device) {
this->state = this->lastState = 0;//device.state;
this->interpolator = 0;//device.state << 16;
this->condition = 0xff;
}
/**
* Check if a state is active
*/
bool isActive(const Device &device, uint8_t state);
void setState(const Device &device, uint8_t state);
int update(const Device &device, int ticks);
uint8_t state;
uint8_t lastState;
int interpolator;
// currently active condition, used to trigger it only once when it becomes active
uint8_t condition;
};
| true |
661e4fb231cd02c873202d10bda8bf4b5fbbe0a7 | C++ | GitHubforXiaoming/FragmentsAssemblyAssitant | /Registration.cpp | GB18030 | 13,880 | 2.625 | 3 | [] | no_license | #include "stdafx.h"
#include "Registration.h"
Registration::Registration()
{
}
Registration::Registration(int fragmentsSize, int fracturesSize)
{
this->fragmentsSize = fragmentsSize;
this->fracturesSize = fracturesSize;
fractures = new int*[fragmentsSize];
for (int i = 0; i < fragmentsSize; i++)
fractures[i] = new int[fracturesSize];
for (int i = 0; i < fragmentsSize; i++)
for (int j = 0; j < fracturesSize; j++)
fractures[i][j] = 0;
}
Registration::Registration(vtkSmartPointer<vtkPolyData> source)
{
this->source = source;
points = source->GetPoints();
this->rotateX = vtkSmartPointer<vtkMatrix4x4>::New();
this->rotateY = vtkSmartPointer<vtkMatrix4x4>::New();
this->rotateZ = vtkSmartPointer<vtkMatrix4x4>::New();
}
Registration::~Registration()
{
}
double Registration::Norm(double* a)
{
return sqrt(square(a[0]) + square(a[1]) + square(a[2]));
}
void Registration::Normalize(double* a, double* b)
{
for (int i = 0; i < 3; i++)
b[i] = a[i] / Norm(a);
}
double Registration::Multiply(double* a, double* b)
{
double c = 0;
for (int i = 0; i < 3; i++)
c += a[i] * b[i];
return c;
}
void Registration::GetRotateAxis(double* axis1, double* axis2, double* axis)
{
axis[0] = axis1[1] * axis2[2] - axis2[1] * axis1[2];
axis[1] = axis2[0] * axis1[2] - axis1[0] * axis2[2];
axis[2] = axis1[0] * axis2[1] - axis2[0] * axis1[1];
}
vector<string> Registration::SplitPair(string str, string pattern)
{
vector<string> split;
int position = str.find_first_of(pattern.c_str());
split.push_back(str.substr(0, position));
split.push_back(str.substr(position + 1, str.length()));
return split;
}
vector<string> Registration::SplitString(const string str, const string pattern)
{
vector<string> splitted;
if ("" == str)
{
return splitted;
}
//ȡһ
std::string strs = str + pattern;
size_t pos = strs.find(pattern);
size_t size = strs.size();
while (pos != std::string::npos)
{
std::string x = strs.substr(0, pos);
splitted.push_back(x);
strs = strs.substr(pos + 1, size);
pos = strs.find(pattern);
}
return splitted;
}
vector<int> Registration::GetNextFracture(int fragmentId, vector<pair<string, string>> pairs)
{
vector<int> nextFracture;
bool over = false;
for (int i = 0; i < fracturesSize; i++)
{
// ѰҵǰƬûбʹĶ
if (fractures[fragmentId][i] == 0)
{
// ֪ƥϵѰͬһƬһƥ
for (vector<pair<string, string>>::iterator it = pairs.begin(); it != pairs.end(); it++)
{
int j = atoi(SplitPair(it->first, "-")[0].c_str());
if (fragmentId == j)
{
int m = atoi(SplitPair(it->second, "-")[0].c_str());
int n = atoi(SplitPair(it->second, "-")[1].c_str());
nextFracture.push_back(m);
nextFracture.push_back(n);
over = true;
break;
}
}
if (over)
break;
}
}
return nextFracture;
}
void Registration::MatchStrategy(vector<pair<string, string>> pairs, vector<int>& sequences)
{
int k = 0;
int i, j;
for (vector<pair<string, string>>::iterator it = pairs.begin(); it != pairs.end(); it++)
{
if (k == 0)
{
i = atoi(SplitPair(it->first, "-")[0].c_str());
j = atoi(SplitPair(it->first, "-")[1].c_str());
fractures[i][j] = 1;
sequences.push_back(i);
}
else
{
i = GetNextFracture(i, pairs)[0];
j = GetNextFracture(i, pairs)[1];
fractures[i][j] = 1;
sequences.push_back(i);
}
k++;
}
}
vtkSmartPointer<vtkMatrix4x4> Registration::GetRotateX(double theta)
{
rotateX->SetElement(0, 0, 1);
rotateX->SetElement(0, 1, 0);
rotateX->SetElement(0, 2, 0);
rotateX->SetElement(0, 3, 0);
rotateX->SetElement(1, 0, 0);
rotateX->SetElement(1, 1, cos(theta));
rotateX->SetElement(1, 2, -sin(theta));
rotateX->SetElement(1, 3, 0);
rotateX->SetElement(2, 0, 0);
rotateX->SetElement(2, 1, sin(theta));
rotateX->SetElement(2, 2, cos(theta));
rotateX->SetElement(2, 3, 0);
rotateX->SetElement(3, 0, 0);
rotateX->SetElement(3, 1, 0);
rotateX->SetElement(3, 2, 0);
rotateX->SetElement(3, 3, 1);
return rotateX;
}
vtkSmartPointer<vtkMatrix4x4> Registration::GetRotateY(double theta)
{
rotateY->SetElement(0, 0, cos(theta));
rotateY->SetElement(0, 1, 0);
rotateY->SetElement(0, 2, sin(theta));
rotateY->SetElement(0, 3, 0);
rotateY->SetElement(1, 0, 0);
rotateY->SetElement(1, 1, 1);
rotateY->SetElement(1, 2, 0);
rotateY->SetElement(1, 3, 0);
rotateY->SetElement(2, 0, -sin(theta));
rotateY->SetElement(2, 1, 0);
rotateY->SetElement(2, 2, cos(theta));
rotateY->SetElement(2, 3, 0);
rotateY->SetElement(3, 0, 0);
rotateY->SetElement(3, 1, 0);
rotateY->SetElement(3, 2, 0);
rotateY->SetElement(3, 3, 1);
return rotateY;
}
vtkSmartPointer<vtkMatrix4x4> Registration::GetRotateZ(double theta)
{
rotateZ->SetElement(0, 0, cos(theta));
rotateZ->SetElement(0, 1, -sin(theta));
rotateZ->SetElement(0, 2, 0);
rotateZ->SetElement(0, 3, 0);
rotateZ->SetElement(1, 0, sin(theta));
rotateZ->SetElement(1, 1, cos(theta));
rotateZ->SetElement(1, 2, 0);
rotateZ->SetElement(1, 3, 0);
rotateZ->SetElement(2, 0, 0);
rotateZ->SetElement(2, 1, 0);
rotateZ->SetElement(2, 2, 1);
rotateZ->SetElement(2, 3, 0);
rotateZ->SetElement(3, 0, 0);
rotateZ->SetElement(3, 1, 0);
rotateZ->SetElement(3, 2, 0);
rotateZ->SetElement(3, 3, 1);
return rotateZ;
}
void Registration::InstanceMatrix(vtkSmartPointer<vtkMatrix4x4>& matrix)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j)
matrix->SetElement(i, j, 1);
else
matrix->SetElement(i, j, 0);
}
}
}
void Registration::PCA(vtkSmartPointer<vtkDoubleArray>& eigenvectors)
{
// These would be all of your "x" values.
vtkSmartPointer<vtkDoubleArray> xArray =
vtkSmartPointer<vtkDoubleArray>::New();
xArray->SetNumberOfComponents(1);
xArray->SetName("x");
// These would be all of your "y" values.
vtkSmartPointer<vtkDoubleArray> yArray =
vtkSmartPointer<vtkDoubleArray>::New();
yArray->SetNumberOfComponents(1);
yArray->SetName("y");
// These would be all of your "z" values.
vtkSmartPointer<vtkDoubleArray> zArray =
vtkSmartPointer<vtkDoubleArray>::New();
zArray->SetNumberOfComponents(1);
zArray->SetName("z");
for (vtkIdType i = 0; i < points->GetNumberOfPoints(); i++)
{
double p[3];
points->GetPoint(i, p);
xArray->InsertNextValue(p[0]);
yArray->InsertNextValue(p[1]);
zArray->InsertNextValue(p[2]);
}
vtkSmartPointer<vtkTable> datasetTable =
vtkSmartPointer<vtkTable>::New();
datasetTable->AddColumn(xArray);
datasetTable->AddColumn(yArray);
datasetTable->AddColumn(zArray);
vtkSmartPointer<vtkPCAStatistics> pcaStatistics =
vtkSmartPointer<vtkPCAStatistics>::New();
pcaStatistics->SetInputData(vtkStatisticsAlgorithm::INPUT_DATA, datasetTable);
pcaStatistics->SetColumnStatus("x", 1);
pcaStatistics->SetColumnStatus("y", 1);
pcaStatistics->SetColumnStatus("z", 1);
pcaStatistics->RequestSelectedColumns();
pcaStatistics->SetDeriveOption(true);
pcaStatistics->Update();
///////// Eigenvalues ////////////
vtkSmartPointer<vtkDoubleArray> eigenvalues =
vtkSmartPointer<vtkDoubleArray>::New();
pcaStatistics->GetEigenvalues(eigenvalues);
/*for (vtkIdType i = 0; i < eigenvalues->GetNumberOfTuples(); i++)
{
std::cout << "Eigenvalue " << i << " = " << eigenvalues->GetValue(i) << std::endl;
}*/
///////// Eigenvectors ////////////
pcaStatistics->GetEigenvectors(eigenvectors);
}
void Registration::RotateByAnyAxis(double* start, double* end, vtkSmartPointer<vtkMatrix4x4>& rotateMatrix)
{
// µᣬĺϳ
double axis[3], rotateAxis[3];
for (int i = 0; i < 3; i++)
axis[i] = start[i] + end[i];
Normalize(axis, rotateAxis);
// 趨ת
double a = rotateAxis[0];
double b = rotateAxis[1];
double c = rotateAxis[2];
// һ
rotateMatrix->SetElement(0, 0, square(a) + (1 - square(a)) * -1);
rotateMatrix->SetElement(0, 1, a * b * 2);
rotateMatrix->SetElement(0, 2, a * c * 2);
rotateMatrix->SetElement(0, 3, 0);
// ڶ
rotateMatrix->SetElement(1, 0, a * b * 2);
rotateMatrix->SetElement(1, 1, square(b) + (1 - square(b)) * -1);
rotateMatrix->SetElement(1, 2, b * c * 2);
rotateMatrix->SetElement(1, 3, 0);
//
rotateMatrix->SetElement(2, 0, a * c * 2);
rotateMatrix->SetElement(2, 1, b * c * 2);
rotateMatrix->SetElement(2, 2, square(c) + (1 - square(c)) * -1);
rotateMatrix->SetElement(2, 3, 0);
//
rotateMatrix->SetElement(3, 0, 0);
rotateMatrix->SetElement(3, 1, 0);
rotateMatrix->SetElement(3, 2, 0);
rotateMatrix->SetElement(3, 3, 1);
}
void Registration::RotateByAnyAngle(double* axis, double theta, vtkSmartPointer<vtkMatrix4x4>& rotateMatrix)
{
// 趨ת
double a = axis[0];
double b = axis[1];
double c = axis[2];
// һ
rotateMatrix->SetElement(0, 0, square(a) + (1 - square(a)) * cos(theta));
rotateMatrix->SetElement(0, 1, a * b * (1 - cos(theta)) + c * sin(theta));
rotateMatrix->SetElement(0, 2, a * c * (1 - cos(theta)) - b * sin(theta));
rotateMatrix->SetElement(0, 3, 0);
// ڶ
rotateMatrix->SetElement(1, 0, a * b * (1 - cos(theta)) - c * sin(theta));
rotateMatrix->SetElement(1, 1, square(b) + (1 - square(b)) * cos(theta));
rotateMatrix->SetElement(1, 2, b * c * (1 - cos(theta)) + a * sin(theta));
rotateMatrix->SetElement(1, 3, 0);
//
rotateMatrix->SetElement(2, 0, a * c * (1 - cos(theta)) + b * sin(theta));
rotateMatrix->SetElement(2, 1, b * c * (1 - cos(theta)) - a * sin(theta));
rotateMatrix->SetElement(2, 2, square(c) + (1 - square(c)) * cos(theta));
rotateMatrix->SetElement(2, 3, 0);
//
rotateMatrix->SetElement(3, 0, 0);
rotateMatrix->SetElement(3, 1, 0);
rotateMatrix->SetElement(3, 2, 0);
rotateMatrix->SetElement(3, 3, 1);
}
void Registration::TranslateMatrix(double* start, double* end, vtkSmartPointer<vtkMatrix4x4>& translateMatrix)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i == j)
translateMatrix->SetElement(i, j, 1);
else if (j == 3)
translateMatrix->SetElement(i, j, start[i] - end[i]);
else
translateMatrix->SetElement(i, j, 0);
}
}
}
void Registration::TransformPoints(vtkSmartPointer<vtkMatrix4x4> matrix, vtkSmartPointer<vtkPoints> primitivePoints, vtkSmartPointer<vtkPoints>& transformedPoints)
{
vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
transform->SetMatrix(matrix);
transform->TransformPoints(primitivePoints, transformedPoints);
}
void Registration::TransformPoints(vtkSmartPointer<vtkMatrix4x4> matrix, double* primitivePoint, double* transformedPoint)
{
vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
transform->SetMatrix(matrix);
transform->TransformPoint(primitivePoint, transformedPoint);
}
void Registration::TransformPolyData(vtkSmartPointer<vtkMatrix4x4> matrix, vtkSmartPointer<vtkPolyData>& target)
{
vtkSmartPointer<vtkTransform> transform =
vtkSmartPointer<vtkTransform>::New();
transform->SetMatrix(matrix);
vtkSmartPointer<vtkTransformPolyDataFilter> transformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
transformFilter->SetInputData(source);
transformFilter->SetTransform(transform);
transformFilter->Update();
target->ShallowCopy(transformFilter->GetOutput());
}
void Registration::TransformPolyData(vtkSmartPointer<vtkMatrix4x4> matrix, vtkSmartPointer<vtkPolyData> source, vtkSmartPointer<vtkPolyData>& target)
{
vtkSmartPointer<vtkTransform> transform =
vtkSmartPointer<vtkTransform>::New();
transform->SetMatrix(matrix);
vtkSmartPointer<vtkTransformPolyDataFilter> transformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
transformFilter->SetInputData(source);
transformFilter->SetTransform(transform);
transformFilter->Update();
target->ShallowCopy(transformFilter->GetOutput());
}
void Registration::IterativeClosestPointsTransform(vtkSmartPointer<vtkPolyData> target, vtkSmartPointer<vtkMatrix4x4>& matrix, int maxIterations)
{
// Setup ICP transform
vtkSmartPointer<vtkIterativeClosestPointTransform> icp =
vtkSmartPointer<vtkIterativeClosestPointTransform>::New();
icp->GetLandmarkTransform()->SetModeToRigidBody();
icp->CheckMeanDistanceOn();
icp->SetCheckMeanDistance(1);
icp->SetMaximumMeanDistance(MAXMUMMEANDISTENCE);
icp->SetMaximumNumberOfLandmarks(5000);
// Begin iterate
for (int i = 0; i < maxIterations; i++)
{
icp->SetSource(source);
icp->SetTarget(target);
icp->SetMaximumNumberOfIterations(2);
icp->Modified();
icp->Update();
vtkMatrix4x4::Multiply4x4(icp->GetMatrix(), matrix, matrix);
vtkSmartPointer<vtkPolyData> modified = vtkSmartPointer<vtkPolyData>::New();
TransformPolyData(matrix, modified);
source = modified;
if (icp->GetMeanDistance() <= MAXMUMMEANDISTENCE)
{
break;
}
}
// Get the resulting transformation matrix (this matrix takes the source points to the target points)
vtkSmartPointer<vtkMatrix4x4> m = icp->GetMatrix();
//std::cout << "The resulting matrix is: " << *m << std::endl;
// Transform the source points by the ICP solution
vtkSmartPointer<vtkTransformPolyDataFilter> icpTransformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
icpTransformFilter->SetInputData(source);
icpTransformFilter->SetTransform(icp);
icpTransformFilter->Update();
/*
// If you need to take the target points to the source points, the matrix is:
icp->Inverse();
vtkSmartPointer<vtkMatrix4x4> minv = icp->GetMatrix();
std::cout << "The resulting inverse matrix is: " << *minv << std::cout;
*/
matrix = m;
}
vtkSmartPointer<vtkPolyData> Registration::ConvertToVertex()
{
vtkSmartPointer<vtkVertexGlyphFilter> vertexFilter =
vtkSmartPointer<vtkVertexGlyphFilter>::New();
vertexFilter->SetInputData(source);
vertexFilter->Update();
return vertexFilter->GetOutput();
} | true |
6d41d1a8832b4327e6d26f0b6a6388f36f79b55a | C++ | romie88/leetcode | /73.Set.Matrix.Zeroes.h | UTF-8 | 2,333 | 4 | 4 | [] | no_license | /**
* Algorithms 73 Set Matrix Zeroes Medium
*
* Given a m x n matrix, if an element is 0, set its entire row and column to 0.
* Do it in place.
*
* click to show follow up.
*
* Follow up:
* Did you use extra space?
* A straight forward solution using O(mn) space is probably a bad idea.
* A simple improvement uses O(m + n) space, but still not the best solution.
* Could you devise a constant space solution?
*
* Tags: Array
*/
#include <vector>
class Solution {
public:
/**
* The straightforward idea is to first copy the matrix.
* Check the copied matrix for zero entries and set the corresponding
* row and column zeroes. However this is O(m * n) space.
*
* An improvement is to have two vectors recording the rows and columns
* which need to set zeroes. O(m + n) space.
*
* A further improvement is to use the first row and first column rather
* than creating extra ones. O(1) space.
*/
void setZeroes( std::vector< std::vector< int > > & matrix ) {
bool first_row_has_zero = false;
for ( int i = 0; i < matrix[ 0 ].size(); ++i )
if ( matrix[ 0 ][ i ] == 0 ) {
first_row_has_zero = true;
break;
}
bool first_col_has_zero = false;
for ( int i = 0; i < matrix.size(); ++i )
if ( matrix[ i ][ 0 ] == 0 ) {
first_col_has_zero = true;
break;
}
for ( int i = 1; i < matrix.size(); ++i ) {
for ( int j = 1; j < matrix[ i ].size(); ++j ) {
if ( matrix[ i ][ j ] == 0 ) {
matrix[ i ][ 0 ] = 0;
matrix[ 0 ][ j ] = 0;
}
}
}
for ( int i = 1; i < matrix.size(); ++i ) {
for ( int j = 1; j < matrix[ i ].size(); ++j ) {
if ( matrix[ i ][ 0 ] == 0 || matrix[ 0 ][ j ] == 0 )
matrix[ i ][ j ] = 0;
}
}
if ( first_row_has_zero )
for ( int i = 0; i < matrix[ 0 ].size(); ++i )
matrix[ 0 ][ i ] = 0;
if ( first_col_has_zero )
for ( int i = 0; i < matrix.size(); ++i )
matrix[ i ][ 0 ] = 0;
}
};
| true |
858f89c9d257baa0df57ce1cddbbf98e04645b0d | C++ | Twiebs/Raptor | /src/assets/assets.hpp | UTF-8 | 5,386 | 2.859375 | 3 | [] | no_license | #pragma once
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>
#include <stdint.h>
template<typename TAsset>
struct AssetHandle {
uint32_t arrayIndex;
uint64_t uuid;
};
template<typename TAsset>
inline const TAsset& GetAsset(AssetHandle<TAsset> handle) {
static_assert(false, "GetAsset was called with a generic AssetType. All asset types must have a "
"Template specialization function defined for this procedure");
}
template<typename TAsset>
inline AssetHandle<TAsset> ObtainAssetHandle(const std::string& asset_name) {
static_assert(false, "ObtainAsset was called with a generic AssetType. All asset types must have a "
"Template specialization function for each of the procedures required by the asset manager");
}
template<typename T>
inline const char* TypeName() {
static_assert(false, "TypeName was called with an unregistered typename!");
}
enum class AssetLoadState {
UNLOADED,
LOADED
};
struct AssetState {
AssetLoadState loadedState = AssetLoadState::UNLOADED;
uint32_t assetIndex = 0;
};
struct AssetManifestEntry {
std::string name;
std::string filename;
};
struct AssetManifest {
std::vector<AssetManifestEntry> entries;
void AddEntry(const std::string& name, const std::string& filename);
inline int64_t GetEntryIndex(const std::string& entryName) {
auto result = static_cast<int64_t>(nameToEntryIndexMap[entryName]) - 1;
return result;
}
template<typename TAsset>
void SerializeManifest();
template<typename TAsset>
void DeSerializeManifest();
private:
std::unordered_map<std::string, uint32_t> nameToEntryIndexMap;
};
#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp>
template <class TArchive>
void serialize(TArchive& archive, AssetManifestEntry& entry) {
archive(cereal::make_nvp("assetName", entry.name));
archive(cereal::make_nvp("filename", entry.filename));
}
template<typename TArchive>
void serialize(TArchive& archive, AssetManifest& manifest) {
archive(manifest.entries);
}
template<typename TAsset>
void AssetManifest::SerializeManifest() {
std::ofstream stream(std::string(TypeName<TAsset>()) + ".manifest");
cereal::JSONOutputArchive archive(stream);
archive(*this);
}
template<typename TAsset>
void AssetManifest::DeSerializeManifest() {
std::ifstream stream(std::string(TypeName<TAsset>()) + ".manifest");
if (!stream.is_open()) return;
cereal::JSONInputArchive archive(stream);
archive(*this);
}
template <typename TAsset>
struct AssetManager {
AssetManifest manifest;
std::vector<TAsset> assets;
std::vector<AssetState> assetStates;
AssetManager();
~AssetManager();
AssetHandle<TAsset> ObtainAssetHandle(const std::string& assetName);
const TAsset& GetAsset(AssetHandle<TAsset> handle);
};
template<typename TAsset>
AssetManager<TAsset>::AssetManager() {
manifest.DeSerializeManifest<TAsset>();
assetStates.resize(manifest.entries.size());
}
template<typename TAsset>
AssetManager<TAsset>::~AssetManager() {
manifest.SerializeManifest<TAsset>();
}
template <typename TAsset>
AssetHandle<TAsset> AssetManager<TAsset>::ObtainAssetHandle(const std::string& assetName) {
auto entryIndex = manifest.GetEntryIndex(assetName);
if (entryIndex >= 0) {
auto& assetState = assetStates[entryIndex];
if (assetState.loadedState == AssetLoadState::LOADED) {
auto result = AssetHandle<TAsset> { assetState.assetIndex };
return result;
} else {
auto& manifestEntry = manifest.entries[entryIndex];
auto assetFilename = ASSET_DIRECTORY + manifestEntry.filename;
assets.emplace_back();
auto loadedAssetIndex = assets.size() - 1;
assetState.loadedState = AssetLoadState::LOADED;
assetState.assetIndex = loadedAssetIndex;
auto handle = AssetHandle<TAsset> { loadedAssetIndex };
__LoadAsset<TAsset>(assetFilename, handle);
return handle;
}
}
}
#define DEFINE_ASSET_TYPE_NAME(TAsset) template<> inline const char* TypeName<TAsset>() { return #TAsset; }
#define TYPEDEF_ASSET_HANDLE(TAsset) typedef AssetHandle<TAsset> ##TAsset##Handle;
#define ASSET_MANAGER_NAME(TAsset) __##TAsset##Manager
#define IMPLEMENT_ASSET_MANAGER(TAsset) static AssetManager<TAsset> ASSET_MANAGER_NAME(TAsset)
#define REGISTER_ASSET(TAsset) DEFINE_ASSET_TYPE_NAME(TAsset) TYPEDEF_ASSET_HANDLE(TAsset) IMPLEMENT_ASSET_MANAGER(TAsset)
#define IMPLEMENT_ASSET_LIBARY
#ifdef IMPLEMENT_ASSET_LIBARY
//#define ASSET_MANAGER_NAME(AssetTypeName) __##AssetTypeName##_assset_manager
//#define ASSET_HANDLE_NAME(AssetTypeName) AssetTypeName##Handle
//#define ASSET_MANAGER_DECLERATION(TAssetType) static AssetManager<TAssetType> ASSET_MANAGER_NAME(TAssetType)
//#define ASSET_HANDLE_DECLERATION(TAssetType) typedef AssetHandle<TAssetType> ASSET_HANDLE_NAME(TAssetType)
//#define GET_ASSET_DEFINITION(TAssetType) template<> const TAssetType& GetAsset<TAssetType>(AssetHandle<TAssetType> handle) { return ASSET_MANAGER_NAME(TAssetType).assets[handle.arrayIndex]; }
//#define IMPLEMENT_ASSET(TAssetType) ASSET_MANAGER_DECLERATION(TAssetType); \
//ASSET_HANDLE_DECLERATION(TAssetType); \
//GET_ASSET_DEFINITION(TAssetType)
void AssetManifest::AddEntry(const std::string& name, const std::string& filename) {
AssetManifestEntry entry;
entry.name = name;
entry.filename = filename;
entries.emplace_back(entry);
auto entryIndex = entries.size(); // Intentionaly 1 > then actual index
nameToEntryIndexMap[name] = entryIndex;
}
#endif | true |
728709631b0da1b1eab0f653babe5d3a6f958969 | C++ | MichaelHGitHub/LCA51to100 | /056_Merge_Intervals/revisit.cpp | UTF-8 | 716 | 2.953125 | 3 | [] | no_license | #include <algorithm>
#include "header.h"
vector<vector<int>> merge_r(vector<vector<int>>& intervals)
{
std::sort(intervals.begin(), intervals.end(), [](vector<int> a, vector<int> b)
{
return (a[0] < b[0]);
}
);
int start = intervals[0][0];
int end = intervals[0][1];
vector<vector<int>> result;
for (int i = 1; i < intervals.size(); i++)
{
if (intervals[i][0] > end)
{
result.push_back({ start, end });
start = intervals[i][0];
end = intervals[i][1];
}
else
{
end = max(end, intervals[i][1]);
}
}
result.push_back({ start, end });
return result;
} | true |
57a0f1f7f7cb1d90e2a8beede985f7b523ab0854 | C++ | jrlo1592/Moro | /physics/rigid_body.hpp | UTF-8 | 1,216 | 3.203125 | 3 | [] | no_license | #pragma once
#include "../math/vector2.hpp"
class RigidBody
{
private:
Vector2 m_position;
Vector2 m_velocity;
Vector2 m_center;
double m_mass;
public:
RigidBody(Vector2 & position, Vector2 & velocity, double mass)
{
m_position = position;
m_velocity = velocity;
if (mass < 0)
m_mass = (mass * -1);
else
m_mass = mass;
}
Vector2 getPosition() const
{
return m_position;
}
void setPosition(Vector2 & position)
{
m_position = position;
}
double getX() const
{
return m_position.m_x;
}
void setX(double x)
{
m_position.m_x = x;
}
double getY() const
{
return m_position.m_y;
}
void setY(double y)
{
m_position.m_y = y;
}
Vector2 getVelocity() const
{
return m_velocity;
}
void setVelocity(Vector2 & velocity)
{
m_velocity = velocity;
}
double getMass() const
{
return m_mass;
}
void setMass(double mass)
{
m_mass = mass;
}
Vector2 getCenter() const
{
return m_center;
}
void setCenter(Vector2 & center)
{
m_center = center;
}
};
| true |
0a5cd4157af85e46a8a80ae6ca01a95472f947b5 | C++ | pbisen/practiceCodes | /queuearray.cpp | UTF-8 | 1,655 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct queue
{
int size, cap, front;
int *array;
queue(int c)
{
cap = c;
size = 0;
front = 0;
array = new int[cap];
}
void enque(int input)
{
if (size < cap)
{
array[(front + size)%cap] = input;
size++;
}
else
{
cout << "Error:QueueFull" << endl;
cout << "UnreliableOutputFollows" << endl;
}
}
int deque()
{
if (size > 0)
{
int temp = array[front];
front = (front + 1 )% cap;
size--;
return temp;
}
else{
cout<<"Error:EmptyQueue"<<endl;
return -1;
}
}
int getFront()
{
if (size == 0)
{
return -1;
}
return array[front];
}
int getBack()
{
if (size == 0)
{
return -1;
}
return array[front+size-1];
}
bool isFull()
{
return size == cap - 1;
}
bool isEmpty()
{
return size == 0;
}
int sizeQueue(){
return size;
}
};
int main(){
queue qu(5);
cout<<qu.isEmpty()<<endl;
cout<<qu.isFull()<<endl;
qu.enque(1);
qu.enque(2);
qu.enque(3);
qu.enque(4);
qu.enque(5);
cout<<qu.isEmpty()<<endl;
cout<<qu.isFull()<<endl;
cout<<qu.deque()<<endl;
cout<<qu.deque()<<endl;
qu.enque(6);
qu.enque(7);
cout<<qu.getFront()<<endl;
cout<<qu.getBack()<<endl;
cout<<qu.sizeQueue()<<endl;
} | true |