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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
417f171b41a0fef0a74a977db667982273fba7bb | C++ | battleofdie/interview | /leetcode/Valid-Number.cpp | UTF-8 | 2,269 | 3.234375 | 3 | [] | no_license | // Silly and ugly code, I am not satisfied with this code.
class Solution {
public:
bool isNumber(const char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s == NULL) return false;
while(*s != '\0' && *s == ' ') s++;
if(*s == '\0') return false;
int len = strlen(s);
while(*(s+len-1) == ' ') len--;
int left=0, left_dot = 0, right=0, right_dot=0;
bool has_e = false;
const char* end = s + len - 1;
while(s <= end)
{
if(*s == 'e' || *s == 'E')
{
if(has_e) return false;
has_e = true;
if(left == 0) return false; // like: e12
}
else if(*s >= '0' && *s <= '9')
{
if(has_e) right++;
else left++;
}
else if(*s == '.')
{
if(has_e) right_dot++;
else left_dot++;
}
else if(*s == '-')
{
if(has_e)
{
if(right_dot > 0) return false;
if(right > 0) return false;
s++;
while(s != end && *s == ' ') s++;
s--;
}
else
{
if(left_dot > 0) return false;
if(left > 0) return false;
s++;
while(s != end && *s == ' ') s++;
s--;
}
}
else if(*s == '+')
{
if(s[1] == ' ') return false;
if(has_e)
{
if(right_dot > 0) return false;
if(right > 0) return false;
}
else
{
if(left_dot > 0) return false;
if(left > 0) return false;
}
}
else
return false;
s++;
}//while
if(has_e)
return left > 0 && left_dot < 2 && right > 0 && right_dot == 0;
else
return left > 0 && left_dot < 2;
}
};
| true |
51313ab4fcc4e6cf97627034758d0069b8bbf754 | C++ | dwelman/Nibbler | /basicLib/targsrc/UIGroup.cpp | UTF-8 | 1,347 | 2.859375 | 3 | [] | no_license | #include <UIGroup.hpp>
int UIGroup::next = 1;
UIGroup::UIGroup() : ID(next)
{
next++;
}
UIGroup::UIGroup(const UIGroup & src) : ID(next)
{
elem = src.elem;
next++;
}
UIGroup::~UIGroup()
{
}
UIGroup & UIGroup::operator=(const UIGroup & src)
{
elem = src.elem;
return (*this);
}
void UIGroup::hide()
{
for (auto it = elem.begin(), end = elem.end(); it != end; it++)
{
(*it)->hide();
}
}
void UIGroup::show()
{
for (auto it = elem.begin(), end = elem.end(); it != end; it++)
{
(*it)->show();
}
}
void UIGroup::enable()
{
for (auto it = elem.begin(), end = elem.end(); it != end; it++)
{
(*it)->enable();
}
}
void UIGroup::disable()
{
for (auto it = elem.begin(), end = elem.end(); it != end; it++)
{
(*it)->disable();
}
}
void UIGroup::draw(SDL_Renderer *ren)
{
for (auto it = elem.begin(), end = elem.end(); it != end; it++)
{
(*it)->draw(ren);
}
}
void UIGroup::add(UIElement &newElem)
{
if (elem.size() == 0)
elem.push_back(&newElem);
else
{
auto it = elem.begin();
while ((*it)->layer > newElem.layer)
it++;
elem.insert(it, &newElem);
}
}
void UIGroup::checkEvent(const SDL_Event & e, bool exec)
{
for (auto it = elem.begin(), end = elem.end(); it != end; it++)
{
(*it)->checkEvent(e, exec);
}
}
| true |
59b04537a6706045f385f925dec6c224e8122359 | C++ | nr-parikh/RealTimePathPlanning | /nodeStruct.h | UTF-8 | 379 | 2.546875 | 3 | [] | no_license | #pragma once
#include"ofMain.h"
struct Nodes
{
ofVec2f location;
Nodes *parent, *prevParent=NULL;
bool alive = true;
ofColor color = { 10, 12, 160 };
float costToStart;
std::list<Nodes*> children;
Nodes()
{
}
Nodes(float x_, float y_, float costToStart_, Nodes* p_ = NULL)
{
location.x = x_;
location.y = y_;
costToStart = costToStart_;
parent = p_;
}
}; | true |
78eb1e857bbf6217bc428adaccf3b1dc04b1b88b | C++ | H4tch/Basic-SDL2-Demo | /include/camera.h | UTF-8 | 1,850 | 3.296875 | 3 | [
"MIT"
] | permissive | #ifndef _ENGINE_CAMERA_H
#define _ENGINE_CAMERA_H
#include "object.h"
#include "SDL2/SDL_rect.h"
// Camera centers itself over an Object until it hits the map's edge.
// Note, Camera updates the object it is following before it repositions itself
// over it. This prevents the object from 'wiggling' around on the screen.
// If Camera was updated after, then some Objects which are barely on the screen,
// won't be rendered at all until the next frame. Maybe the solution is to expand
// the camera's box to allow for that.
class Camera : public Object
{
SDL_Rect bounds;
// Convert to an Object Id
Object* followedObject;
bool active;
public:
Camera() :active(false)
{
box.w = box.h = 0;
box.x = -(box.w/2);
box.y = -(box.h/2);
bounds.x = bounds.y = bounds.w = bounds.h = 0;
}
void setBounds( SDL_Rect newBounds ) { bounds = newBounds; }
void follow( Object* newObject ) {
this->followedObject = newObject;
active = true;
}
Object* getFocus() { return followedObject; }
void resize( SDL_Rect window ) {
box.w = window.w;
box.h = window.h;
}
void update(const double& dt) override {
if ( active && followedObject ) {
followedObject->update(dt);
SDL_Rect objectBox;
objectBox = followedObject->getBox();
// Center camera over object.
box.x = (objectBox.x + (objectBox.w / 2)) - (box.w / 2);
box.y = (objectBox.y + (objectBox.h / 2)) - (box.h / 2);
// Constrain Camera to the Map
Map::keepInBounds(box, bounds);
// If the map is smaller than camera. Center the camera over the map.
if (bounds.w < box.w) { box.x = bounds.x + (bounds.w / 2) - (box.w / 2); }
if (bounds.h < box.h) { box.y = bounds.y + (bounds.h / 2) - (box.h / 2); }
}
}
void detach() {
followedObject = NULL;
active = false;
}
const bool& isActive(){ return active; }
};
#endif
| true |
4c7c3fec2e02e57701b31b0693a22b0b9236715d | C++ | tothambrus11/arc-2020 | /old/wemos_code/wemos_code.ino | UTF-8 | 1,394 | 2.765625 | 3 | [] | no_license | #define M1A D5
#define M1B D6
#define M2A D7
#define M2B D8
#define M3A D3
#define M3B D4
#define M4A D1
#define M4B D2
long counter1 = 0;
long counter2 = 0;
long counter3 = 0;
long counter4 = 0;
void setup() {
// put your setup code here, to run once:
pinMode(M1A, INPUT_PULLUP);
pinMode(M2A, INPUT_PULLUP);
pinMode(M3A, INPUT_PULLUP);
pinMode(M4A, INPUT_PULLUP);
pinMode(M1B, INPUT_PULLUP);
pinMode(M2B, INPUT_PULLUP);
pinMode(M3B, INPUT_PULLUP);
pinMode(M4B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(M1A), m1Interrupt, CHANGE);
attachInterrupt(digitalPinToInterrupt(M2A), m2Interrupt, CHANGE);
attachInterrupt(digitalPinToInterrupt(M3A), m3Interrupt, CHANGE);
attachInterrupt(digitalPinToInterrupt(M4A), m4Interrupt, CHANGE);
Serial.begin(115200);
}
void m1Interrupt() {
if (digitalRead(M1A) == digitalRead(M1B)) {
counter1--;
} else {
counter1++;
}
}
void m2Interrupt() {
if (digitalRead(M2A) == digitalRead(M2B)) {
counter2++;
} else {
counter2--;
}
}
void m3Interrupt() {
if (digitalRead(M3A) == digitalRead(M3B)) {
counter3++;
} else {
counter3--;
}
}
void m4Interrupt() {
if (digitalRead(M4A) == digitalRead(M4B)) {
counter4++;
} else {
counter4--;
}
}
void loop() {
Serial.println(String(counter1) + " " + String(counter2) + " " + String(counter3) + " " + String(counter4));
}
| true |
3226b99976451afcd06c5f1d606c169dae757bc5 | C++ | ydk1104/PS | /boj/4000~4999/4690.cpp | UTF-8 | 273 | 2.9375 | 3 | [] | no_license | #include<stdio.h>
int main(void){
for(int i=1; i<=100; i++){
for(int j=2; j<=i; j++){
for(int k=j; k<=i; k++){
for(int l=k; l<=i; l++){
if(i*i*i == j*j*j+k*k*k+l*l*l){
printf("Cube = %d, Triple = (%d,%d,%d)\n", i, j, k, l);
}
}
}
}
}
}
| true |
21d0947fd97db061862d9d183a475e692de06116 | C++ | neokito/OpenCLTabu | /TabuSolver/Solution.cpp | UTF-8 | 1,133 | 2.78125 | 3 | [] | no_license | /*
* Solution.cpp
*
* Created on: 14-08-2012
* Author: donty
*/
#include "Solution.h"
namespace tabu {
/* +----------------------+
* | k_ | k_ | k_ | k_ |
* +----------------------+
* |_______n_machines_____|
*/
Solution::Solution(unsigned int n_machines) {
this->n_machines = n_machines;
this->cell_vector = new int[n_machines];
this->cost = -1;
//std::fill( this->cell_vector, this->cell_vector+n_machines, -1 );
}
Solution::~Solution() {
delete[] this->cell_vector;
}
void Solution::init(){
}
int Solution::exchange(unsigned int i, unsigned int j) {
int ret = 0;
if(i!=j && i > 0 && j > 0 && i < n_machines && j < n_machines &&
(cell_vector[i] != cell_vector[j])
){
int aux = cell_vector[i];
cell_vector[i] = cell_vector[j];
cell_vector[j] = aux;
ret = 1;
}
return ret;
}
Solution* Solution::clone() {
Solution *new_sol = new Solution(this->n_machines);
// std::copy(this->cell_vector, this->cell_vector+n_machines,
// new_sol->cell_vector);
for(unsigned int i=0;i<n_machines;i++)
new_sol->cell_vector[i] = this->cell_vector[i];
return new_sol;
}
} /* namespace tabu */
| true |
7e69aaba234aaa2f91ee2b000e5adb92fe8b378e | C++ | moddyz/CXXPythonDocs | /src/cxxpythondocs/vec3f.h | UTF-8 | 2,346 | 3.75 | 4 | [] | no_license | #pragma once
namespace cxxpythondocs {
/// \class Vec3f
///
/// A vector class with 3 floating-point components.
class Vec3f
{
public:
// -----------------------------------------------------------------------
/// \name Construction
// -----------------------------------------------------------------------
/// Default constructor.
Vec3f() = default;
/// Component-wise constructor.
///
/// \param x The x element.
/// \param y The y element.
/// \param z The z element.
inline explicit Vec3f(float x, float y, float z)
: m_x(x)
, m_y(y)
, m_z(z)
{}
// -----------------------------------------------------------------------
/// \name Component accessors
// -----------------------------------------------------------------------
/// Read-only accessor for the x component.
///
/// \return The x component.
inline float X() const { return m_x; }
/// Read-only accessor for the y component.
///
/// \return The y component.
inline float Y() const { return m_y; }
/// Read-only accessor for the z component.
///
/// \return The z component.
inline float Z() const { return m_z; }
/// Mutable accessor for the x component.
///
/// \return The x component.
inline float& X() { return m_x; }
/// Mutable accessor for the y component.
///
/// \return The y component.
inline float& Y() { return m_y; }
/// Mutable accessor for the z component.
///
/// \return The z component.
inline float& Z() { return m_z; }
// -----------------------------------------------------------------------
/// \name Linear Algebra Operations
// -----------------------------------------------------------------------
/// Compute the dot product of this vector and \p other.
///
/// Example usage:
/// \code{.cpp}
/// cxxpythondocs::Vec3f vec(1, 2, 3);
/// cxxpythondocs::Vec3f orthoVec(-1, -1, 1)
/// float dotProduct = vec.DotProduct(orthoVec);
/// assert(dotProduct == 0.0f);
/// \endcode
///
/// \param other The other vector.
///
/// \return The dot product.
float DotProduct(const Vec3f& other) const;
private:
float m_x = 0.0f;
float m_y = 0.0f;
float m_z = 0.0f;
};
} // namespace cxxpythondocs
| true |
1264c8351477ae1e5b95542218d3479a7ba119b5 | C++ | allansp84/metafusion-multiview-learning | /bsifcpp/test.cpp | UTF-8 | 2,576 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <boost/python/numpy.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <fstream>
#include "bsifmodule.h"
namespace p = boost::python;
namespace np = boost::python::numpy;
int main(int argc, char **argv){
if (argc < 2) {
std::cout << "Usage: test <image> " << std::endl;
}
Py_Initialize();
np::initialize();
// cv::Mat image = cv::imread("06117d321_imno.bmp", 0);
cv::Mat image = cv::imread(argv[1], 0);
std::cout << "Image loaded: " << image.rows << "x" << image.cols << std::endl;
// create a numpy array with known shape and values
// uchar sample[image.rows][image.cols];
// memcpy(&sample, image.data, image.cols*image.rows);
np::dtype dt = np::dtype::get_builtin<uchar>();
np::dtype dtr = np::dtype::get_builtin<float>();
np::ndarray myarray = np::from_data(image.data, dt,
p::make_tuple(image.rows,image.cols),
p::make_tuple(image.cols,1),
p::object());
uint8_t dims[] = {7,7,7};
np::ndarray mydims = np::from_data(dims, dt,
p::make_tuple(1,3),
p::make_tuple(1,1),
p::object());
// allocate zeros in the return variable
np::ndarray result = np::zeros(p::make_tuple(image.rows, image.cols), dtr);
std::cout << "About to call BSIF module..." << std::endl;
// call bsif module
bsif_extract(myarray, result, mydims);
std::cout << "Just after calling BSIF module..." << std::endl;
cv::Mat imresult(image.rows, image.cols, CV_32FC1);
std::cout << "Return variable declared..." << std::endl;
const Py_intptr_t *arrsize = result.get_shape();
std::cout << "Return variable size: " << (int)arrsize[0] << "x" << \
(int)arrsize[1] << std::endl;
int length = result.get_nd();
std::cout << "Return variable length: " << length << std::endl;
np::dtype rdt = result.get_dtype();
std::cout << "Size of data item: " << rdt.get_itemsize() << std::endl;
float * data = (float *)result.get_data();
std::cout << "Uchar array pointing to result.get_data(): " << *data << std::endl;
memcpy(imresult.data, data, image.rows*image.cols*sizeof(float));
std::cout << "memcpy..." << std::endl;
// char fname[50];
// std::ofstream outfile;
// sprintf(fname, "./output/cppoutput2.csv");
// outfile.open(fname);
// outfile << cv::format(imresult, cv::Formatter::FMT_CSV) << std::endl;
// outfile.close();
// cv::namedWindow("output", cv::WINDOW_AUTOSIZE);
// cv::imshow("output", imresult);
// cv::waitKey(0);
cv::imwrite("./output/cpp.png",imresult);
std::cout << "The end." << std::endl;
}
| true |
a944ce964d5d4dcce702204b001ed4efa2c47c0c | C++ | skdudn321/algorithm | /baekjoon/11053.cpp | UTF-8 | 487 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> ve;
int main(void){
int N;
int i;
int temp;
scanf("%d", &N);
scanf("%d", &temp);
ve.push_back(temp);
for (i = 1; i < N; i++){
scanf("%d", &temp);
if (temp > ve.back()){
ve.push_back(temp);
}
else{
ve.erase(lower_bound(ve.begin(), ve.end(), temp));
ve.insert(lower_bound(ve.begin(), ve.end(), temp), temp);
}
}
printf("%d", ve.size());
} | true |
0bba85298e07657a5f9a1741a7e8ff38fb8cee29 | C++ | Silverutm/Concursos-Algoritmia | /XV Semana 0ct 2016/findingekt/SolutionMedium.cpp | UTF-8 | 558 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int V;
int AdjMat[160][160];
void floyd()
{
for (int k = 0; k < V; k++) // remember that loop order is k->i->j
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
AdjMat[i][j] = min(AdjMat[i][j], AdjMat[i][k] + AdjMat[k][j]);
}
int main()
{
int k, a, b, q;
cin>>k;
while (k--)
{
cin>>V;
for (int i = 0; i < V; ++i)
for (int j = 0; j < V; ++j)
cin>>AdjMat[i][j];
floyd();
cin>>q;
while (q--)
{
cin>>a>>b;
a; b;
cout<<AdjMat[a][b]<<endl;
}
}
return 0;
} | true |
c1a7b56f380b7f99056199e8f891b44282fbfb2c | C++ | FZU1816K/personal-project | /Cplusplus/031601232/src/src/WordCount/WordNum.cpp | GB18030 | 944 | 2.796875 | 3 | [] | no_license | #include"WordNum.h"
int WordNum(char * filename)
{
map<string, int> Word_Num_map;
char ch;
FILE *file;
fopen_s(&file, filename, "rt");
int flag = 0; // Զ״̬ 0 1 2 3 44ս״̬,0Ϊʼ״̬
int count = 0;
while((ch = fgetc(file)) != EOF)
{
if ('A' <= ch && ch <= 'Z')
ch = ch + 32;
switch (flag) {
case 0:
if (ch >= 'a'&&ch <= 'z') { flag++; }
break;
case 1:
if (ch >= 'a'&&ch <= 'z') { flag++; }
else { flag = 0; }
break;
case 2:
if (ch >= 'a'&&ch <= 'z') { flag++; }
else { flag = 0; }
break;
case 3:
if (ch >= 'a'&&ch <= 'z') { flag++; }
else { flag = 0; }
break;
case 4:
if (ch >= 'a'&&ch <= 'z' || (ch >= '0'&&ch <= '9')) { }
else
{
flag = 0;
count++;
}
break;
}
} /*flag */
if (flag == 4)
{
count++;
}
return count;
} | true |
92508f0889cdec651a5731bb479c748b4b92021f | C++ | andriantolie/Impressionist | /CircleBrush.cpp | UTF-8 | 1,221 | 2.5625 | 3 | [] | no_license | /*
* The implementation of circle brush.
*
*/
#include "ImpressionistUI.h"
#include "ImpressionistDoc.h"
#include "CircleBrush.h"
extern float frand();
CircleBrush::CircleBrush (ImpressionistDoc* pDoc, char* name) : ImpBrush(pDoc, name) {}
void CircleBrush::BrushBegin (const Point source, const Point target) {
ImpressionistDoc* pDoc = GetDocument();
ImpressionistUI* dlg = pDoc->m_pUI;
int size = pDoc->getSize();
glPointSize((float) size);
//glEnable(GL_ALPHA_TEST);
//glAlphaFunc(GL_NOTEQUAL, 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
BrushMove(source, target);
}
void CircleBrush::BrushMove (const Point source, const Point target) {
ImpressionistDoc* pDoc = GetDocument();
ImpressionistUI* dlg=pDoc->m_pUI;
if ( pDoc == NULL ) {
printf( "Circlerush::BrushMove document is NULL\n" );
return;
}
int size = pDoc->getSize();
int radius = size / 2;
glBegin( GL_TRIANGLE_FAN );
SetColor( source );
for (double i = 0; i < 2*M_PI; i+=0.1){
glVertex2d(target.x + radius*cos(i), target.y + radius*sin(i));
}
glEnd();
}
void CircleBrush::BrushEnd (const Point source, const Point target) {
glBlendFunc(GL_NONE, GL_NONE);
glDisable(GL_BLEND);
} | true |
92e22bcf8fd353909ed16c634032ef56b74a2a4c | C++ | Tecelecta/HIP-GSWITCH | /src/data_structures/bitmap.hxx | UTF-8 | 4,897 | 2.671875 | 3 | [] | no_license | #ifndef __BITMAP_CUH
#define __BITMAP_CUH
#include <hip/hip_runtime.h>
#include "utils/utils.hxx"
#include "utils/intrinsics.hxx"
#include "utils/platform.hxx"
template<typename word_t, int sft>
struct bits_t{
int build(int nvertexs){
n_words = (nvertexs + 8*sizeof(word_t)-1) >> sft;
H_ERR(hipMalloc((void**)&dg_bits, sizeof(word_t)*n_words));
reset();
return sizeof(word_t)*n_words;
}
int get_size() { return n_words; }
void reset() { CLEAN(dg_bits, n_words); }
void mark_all(int x) { H_ERR(hipMemset(dg_bits, x, sizeof(word_t)*n_words)); }
void mark_one(int root){
int loc = (root>>sft);
word_t word = 1<<(root&MASK);
excudaMemset<word_t>(dg_bits+loc, word, 1);
}
__device__ __tbdinline__
char* to_bytes() { return (char*)(void*) dg_bits; }
__device__ __tbdinline__
int bytes_size() { return n_words<<(sft-3); }
__device__ __tbdinline__
word_t load_word(int v) { return dg_bits[v>>sft]; }
__device__ __tbdinline__
word_t* load_word_pos(int v) { return &dg_bits[v>>sft]; }
__device__ __tbdinline__
int* load_word_pos_as_int(int v) {
int* ptr = (int*)dg_bits;
return &ptr[v>>5];
}
__device__ __tbdinline__
void store_word(int v, word_t word) { dg_bits[v>>sft] = word; }
__device__ __tbdinline__
void store_word_as_int(int v, int word) {
int* ptr = (int*)dg_bits;
ptr[v>>5] = word;
}
/**
* I'm not sure whether this would work
*/
__device__ __tbdinline__
void store_word_as_ballot_t(int v, ballot_t word){
ballot_t* ptr = (ballot_t*)dg_bits;
ptr[v>>LANE_SHFT] = word;
}
__device__ __tbdinline__
int loc(int v) { return (1<<(v&MASK)); }
__device__ __tbdinline__
int loc_as_int(int v) { return (1<<(v&31)); }
// if bit[v]==0 return true else false;
__device__ __tbdinline__
bool query(int v) {
word_t mask_word = load_word(v);
word_t mask_bit = loc(v);
if(!(mask_bit & mask_word))
return true;
return false;
}
__device__ __tbdinline__
bool query_byte(int v) {
char mask_word = to_bytes()[v>>3];
char mask_bit = 1<<(v&7);
if(!(mask_bit & mask_word))
return true;
return false;
}
// mark the bits of v
// WARNING: no consistency guarantee, so hope for the best.
__device__ __tbdinline__
void mark(int v) {
word_t mask_word = load_word(v);// [A]
word_t mask_bit = loc(v);
if(!(mask_bit & mask_word)){
do{
mask_word |= mask_bit;
store_word(v, mask_word); // others may commit changes after [A]
mask_word = load_word(v);
}while(!(mask_bit & mask_word));
}
}
// mark the bit of v, and return true if the bit==0
// WARNING: no consistency guarantee, so hope for the best.
__device__ __tbdinline__
bool query_and_mark(int v) {
word_t mask_word = load_word(v); // [A]
word_t mask_bit = loc(v);
if(!(mask_bit & mask_word)){
do{
mask_word |= mask_bit;
store_word(v, mask_word); // others may commit changes after [A]
mask_word = load_word(v);
}while(!(mask_bit & mask_word));
return true;
}
return false;
}
// mark the bit of v in atomic manner.
// it guarantees the consistency, with higher overhead.
__device__ __tbdinline__
bool query_and_mark_atomic(int v) {
int mask_bit = loc_as_int(v);
int x = atomicOr(load_word_pos_as_int(v), mask_bit);
if(!( x & mask_bit)) return true;
return false;
}
const int MASK = (1<<sft)-1;
word_t* dg_bits;
int n_words;
};
struct bitmap_t{
int build(int nv){
int gpu_bytes = 0;
gpu_bytes += visited.build(nv);
gpu_bytes += active.build(nv);
gpu_bytes += inactive.build(nv);
return gpu_bytes;
}
void reset(){
visited.reset();
active.reset();
inactive.reset();
}
void clean(){visited.reset();}
void init(int root){
if(root==-1) {
active.mark_all(0xff);
inactive.mark_all(0xff);
}else if(root>=0){
active.mark_one(root);
inactive.mark_one(root);
}else{
active.mark_all(0);
inactive.mark_all(0);
}
}
__device__ bool is_active(int v){return !active.query(v);}
__device__ bool is_inactive(int v){return inactive.query(v);}
__device__ bool is_valid(int v){return is_active(v) || is_inactive(v);}
// return ture if the v is not visited
__device__ bool mark_duplicate_lite(int v){ return visited.query_and_mark(v);}
__device__ bool mark_duplicate_atomic(int v){ return visited.query_and_mark_atomic(v);}
bits_t<char, 3> visited; // use atomicOr
bits_t<char, 3> active; // 1 for active, 0 for others
bits_t<char, 3> inactive; // 0 for inactive , 1 for others
//bits_t<unsigned int, 5> visited; // use atomicOr, must be 4-byte-long
//bits_t<unsigned int, 5> active; // 1 for active, 0 for others
//bits_t<unsigned int, 5> inactive; // 0 for inactive , 1 for others
};
#endif
| true |
ffda9f1b6390166a7e4c2717e3c71794724bdb1d | C++ | NajwaLaabid/CompetitiveProgramming | /CodeForces/MathProblems/A9.cc | UTF-8 | 413 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void) {
int n, k = 1, ans = 0;
vector<int> p;
cin >> n;
// Ys
for( int i = 2; i < n - 1 ; i++ ) {
k = 1;
while ( pow(i, k) <= n ) {
p.push_back( pow(i, k) );
k++;
ans++;
}
}
// number of Ys
cout << ans << endl;
for( int i = 0; i < p.size() - 1; i++ )
cout << p[i] << " ";
// Print Ys
cout << p[i] << endl;
return 0;
} | true |
878ef815711a0515844323bb7b9082d707488440 | C++ | ordinary-developer/education | /cpp/std-11/r_lischner-exploring_cpp_11-2_ed/ch_53-containers/04-array_with_a_user-defined_class/main.cpp | UTF-8 | 666 | 3.25 | 3 | [
"MIT"
] | permissive | #include "card.hpp"
#include "randomint.hpp"
#include <array>
#include <iostream>
int main() {
std::array<card,52> deck;
std::generate(deck.begin(), deck.end(), card_generator{});
randomint picker{ 0, deck.size() - 1 };
for (int i{ 0 }; i != 10; ++i) {
card const& computer_card{ deck.at(picker()) };
std::cout << "I picked " << computer_card << '\n';
card const& user_card{ deck.at(picker()) };
std::cout << "You picked " << user_card << '\n';
if (acehigh_compare(computer_card, user_card))
std::cout << "You win.\n";
else
std::cout << "I win.\n";
}
return 0;
}
| true |
6c03066959139e150d4edc1cb0b8c2a2c99533e4 | C++ | lysakov/Signature | /src/modular_arithmetic.cpp | UTF-8 | 8,550 | 3.125 | 3 | [] | no_license | #include "modular_arithmetic.hpp"
enum {
MOD = 256,
BYTE_SIZE = 8
};
typedef Block::Block<1024> uint1024_t;
struct Division_struct
{
Division_struct (const uint1024_t&, const uint1024_t&);
uint1024_t quoitient;
uint1024_t remainder;
};
uint1024_t operator / (const uint1024_t&, const uint1024_t&);
uint1024_t operator % (const uint1024_t&, const uint1024_t&);
static Division_struct division (const uint1024_t&, const uint1024_t &);
static uint1024_t extend (const uint512_t &);
Division_struct::Division_struct (const uint1024_t &quoitient, const uint1024_t &remainder) : quoitient(quoitient), remainder(remainder)
{}
uint1024_t operator / (const uint1024_t ÷nd, const uint1024_t ÷r)
{
return division(dividend, divider).quoitient;
}
uint1024_t operator % (const uint1024_t ÷nd, const uint1024_t ÷r)
{
return division(dividend, divider).remainder;
}
uint512_t operator / (const uint512_t ÷nd, const uint512_t ÷r)
{
return division(extend(dividend), extend(divider)).quoitient.split<512>()[0];
}
uint512_t operator % (const uint512_t ÷nd, const uint512_t ÷r)
{
return division(extend(dividend), extend(divider)).remainder.split<512>()[0];
}
static uint1024_t extend (const uint512_t &num)
{
uint8_t buf[2 * UINT512_SIZE] = {0};
auto ptr = num.get_bitset();
for (size_t i = 0; i < UINT512_SIZE; ++i) {
buf[i] = ptr[i];
}
return uint1024_t(buf, 2 * UINT512_SIZE);
}
uint512_t extend (const uint256_t &num)
{
uint8_t buf[UINT512_SIZE] = {0};
auto ptr = num.get_bitset();
for (size_t i = 0; i < UINT256_SIZE; ++i) {
buf[i] = ptr[i];
}
return uint512_t(buf, UINT512_SIZE);
}
template <size_t S>
static size_t set_size (const Block::Block<S> &num)
{
for (size_t i = 0; i < (S / BYTE_SIZE); ++i) {
if (num.get_byte(S / BYTE_SIZE - i - 1) != 0) {
return S / BYTE_SIZE - i;
}
}
return 0;
}
static uint1024_t shift_l (const uint1024_t &num, size_t shift_p)
{
const uint8_t *bitset = num.get_bitset();
uint8_t new_bitset[2 * UINT512_SIZE] = {0};
for (size_t i = 0; i < 2 * UINT512_SIZE - shift_p; ++i) {
new_bitset[i + shift_p] = bitset[i];
}
return uint1024_t(new_bitset, 2 * UINT512_SIZE);
}
static uint1024_t extract (const uint1024_t &num, size_t first, size_t last)
{
uint1024_t result;
for (size_t i = first; i <= last; ++i) {
result.set_byte(num.get_byte(i), i);
}
return result;
}
static void change (uint1024_t &num1, const uint1024_t &num2, size_t first, size_t last)
{
for (size_t i = first; i <= last; ++i) {
num1.set_byte(num2.get_byte(i), i);
}
}
static uint1024_t multiplication (const uint1024_t &factor1, uint8_t factor2)
{
uint8_t flag = 0;
uint8_t result[2 * UINT512_SIZE] = {0};
for (size_t i = 0; i < 2 * UINT512_SIZE; ++i) {
result[i] = (uint8_t)((factor1.get_byte(i) * factor2 + flag) % MOD);
flag = (uint8_t)((factor1.get_byte(i) * factor2 + flag) / MOD);
}
return uint1024_t(result, 2 * UINT512_SIZE);
}
static uint1024_t division (const uint1024_t ÷nd, uint8_t divider)
{
uint8_t result[2 * UINT512_SIZE] = {0};
uint8_t remainder = 0;
for (size_t i = 0; i < 2 * UINT512_SIZE; ++i) {
result[2 * UINT512_SIZE - i - 1] = (uint8_t)((dividend.get_byte(2 * UINT512_SIZE - i - 1) + (uint32_t)remainder * MOD) / divider);
remainder = (uint8_t)((dividend.get_byte(2 * UINT512_SIZE - i - 1) + (uint32_t)remainder * MOD) % divider);
}
return uint1024_t(result, 2 * UINT512_SIZE);
}
template <size_t S>
static Block::Block<S> substraction (const Block::Block<S> &ext_min, const Block::Block<S> &ext_sub)
{
int flag = 0;
uint8_t result[S / BYTE_SIZE] = {0};
for (size_t i = 0; i < S / BYTE_SIZE; ++i) {
result[i] = (uint8_t)(ext_min.get_byte(i) - ext_sub.get_byte(i) - flag);
if (ext_min.get_byte(i) < ext_sub.get_byte(i) + flag) {
flag = 1;
} else {
flag = 0;
}
}
return Block::Block<S>(result, S / BYTE_SIZE);
}
template <size_t S>
static Block::Block<S> addition (const Block::Block<S> &addend1, const Block::Block<S> &addend2)
{
uint32_t flag = 0;
uint8_t result[S / BYTE_SIZE] = {0};
for (size_t i = 0; i < S / BYTE_SIZE; ++i) {
result[i] = (uint8_t)(((uint32_t)addend1.get_byte(i) + (uint32_t)addend2.get_byte(i) + flag) % MOD);
flag = ((uint32_t)addend1.get_byte(i) + (uint32_t)addend2.get_byte(i) + flag) / MOD;
}
return Block::Block<S>(result, S / BYTE_SIZE);
}
uint1024_t multiplication (const uint512_t &factor1, const uint512_t &factor2)
{
uint1024_t result = 0;
size_t j = 0;
size_t m = set_size(factor1);
size_t n = set_size(factor2);
while (j < n) {
if (factor2.get_byte(j) == 0) {
result.set_byte(0, j + m);
} else {
uint32_t i = 0;
uint32_t k = 0;
while (i < m) {
uint32_t t = factor1.get_byte(i) * factor2.get_byte(j) + result.get_byte(i + j) + k;
result.set_byte((uint8_t)(t % MOD), i + j);
k = t / MOD;
++i;
}
result.set_byte((uint8_t)k, j + m);
}
++j;
}
return result;
}
static Division_struct division (const uint1024_t ÷nd, const uint1024_t ÷r)
{
uint1024_t dividend_ext = dividend;
uint1024_t quoitient;
size_t dividend_size = set_size(dividend);
size_t divider_size = set_size(divider);
int j = dividend_size - divider_size;
uint8_t norm = MOD / (divider.get_byte(divider_size - 1) + 1);
dividend_ext = multiplication(dividend, norm);
const uint1024_t divider_ext = multiplication(divider, norm);
while (j >= 0) {
uint32_t tmp = (uint32_t)dividend_ext.get_byte(j + divider_size) * MOD + (uint32_t)dividend_ext.get_byte(j + divider_size - 1);
uint32_t q = tmp / divider_ext.get_byte(divider_size - 1);
uint32_t r = tmp % divider_ext.get_byte(divider_size - 1);
do {
if (q == MOD || q * divider_ext.get_byte(divider_size - 2) > MOD * r + dividend_ext.get_byte(j + divider_size - 2)) {
--q;
r += divider_ext.get_byte(divider_size - 1);
} else {
break;
}
} while (r < MOD);
auto tmp1 = extract(dividend_ext, j, j + divider_size);
auto tmp_divider = shift_l(divider_ext, j);
auto mult = multiplication(tmp_divider, (uint8_t)q);
while (tmp1 < mult) {
--q;
mult = multiplication(tmp_divider, (uint8_t)q);
}
tmp1 = substraction(tmp1, mult);
change(dividend_ext, tmp1, j, j + divider_size);
quoitient.set_byte((uint8_t)q, j);
--j;
}
return Division_struct(quoitient, division(dividend_ext, norm));
}
uint512_t inverse (const uint512_t &num, const uint512_t &modulus)
{
uint1024_t r0 = extend(modulus);
uint1024_t r1 = division(extend(num), r0).remainder;
uint512_t p[3];
uint512_t q[3];
p[0] = 1;
auto ds = division(r0, r1);
p[1] = ds.quoitient.split<512>()[0];
q[1] = p[1];
r0 = r1;
r1 = ds.remainder;
int i = 1;
size_t cnt = 1;
while (r1 != (uint1024_t)(0)) {
i = (i + 1) % 3;
++cnt;
auto div_st = division(r0, r1);
q[i] = div_st.quoitient.split<512>()[0];
auto tmp = multiplication(q[i], p[(3 + i - 1) % 3]);
p[i] = addition(tmp.split<512>()[0], p[(3 + i - 2) % 3]);
r0 = r1;
r1 = div_st.remainder;
}
if (cnt % 2) {
return p[(3 + i - 1) % 3].split<512>()[0];
} else {
auto result = substraction(modulus, p[(3 + i - 1) % 3]);
return result.split<512>()[0];
}
}
uint512_t opposite (const uint512_t &num, const uint512_t &modulus)
{
return substraction(modulus, num);
}
uint512_t multiplication (const uint512_t &factor1, const uint512_t &factor2, const uint512_t &modulus)
{
return (multiplication(factor1, factor2) % extend(modulus)).split<512>()[0];
}
uint512_t addition (const uint512_t &addend1, const uint512_t &addend2, const uint512_t &modulus)
{
return (addition(extend(addend1), extend(addend2)) % extend(modulus)).split<512>()[0];
}
uint512_t substraction (const uint512_t &minued, const uint512_t &subtrahend, const uint512_t &modulus)
{
return addition(minued, opposite(subtrahend, modulus), modulus);
}
| true |
322b0aed3c330ba5482d0c7917cab5be556d9bee | C++ | MamoruKato/kato_bar | /src/pedido.cpp | UTF-8 | 619 | 2.625 | 3 | [] | no_license | /*
* pedido.cpp
*
* Created on: 13 de out de 2017
* Author: bruno
*/
#include "pedido.h"
Pedido::Pedido(unsigned int npedido, unsigned int ncliente) {
_pedido = npedido;
_idCliente = ncliente;
_idGarcom = 0;
}
Pedido::~Pedido() {
}
/*
* Retorna a id do cliente que realizou o pedido
*/
unsigned int Pedido::cliente()
{
return _idCliente;
}
/*
* retorna a id do garcom que coletou o pedido
*/
unsigned int Pedido::garcom()
{
return _idGarcom;
}
void Pedido::garcom(unsigned int id)
{
_idGarcom = id;
}
/*
* retorna o conteudo do pedido
*/
unsigned int Pedido::pedido()
{
return _pedido;
}
| true |
5e268d2d929e8568daa675a8c9417bb1037ca68b | C++ | francescozoccheddu/Neighborhood | /Projects/Game/Header Files/Game/Resources/Resource.hpp | UTF-8 | 1,019 | 2.640625 | 3 | [] | no_license | #pragma once
#include <Game/Direct3D.hpp>
#include <Game/Utils/NonCopyable.hpp>
#include <string>
#define GAME_RESOURCES_DIR "Resources/"
class Resource : private NonCopyable
{
public:
virtual void Create (ID3D11Device & device) = 0;
virtual void Destroy () = 0;
virtual bool IsCreated () const = 0;
};
class LoadableResource : public Resource
{
public:
virtual void Load () = 0;
virtual void Unload () = 0;
virtual bool IsLoaded () const = 0;
};
class FileResource : public LoadableResource
{
public:
FileResource (const std::string & _fileName);
const std::string& GetFileName () const;
private:
const std::string m_FileName;
};
class BinaryFileResource : public FileResource
{
public:
using FileResource::FileResource;
~BinaryFileResource ();
void Load () override final;
void Unload () override final;
bool IsLoaded () const override final;
protected:
const void * GetData () const;
int GetSize () const;
private:
void * m_pData { nullptr };
int m_cData { 0 };
}; | true |
e6436d6014f9b042606176fa3da6fbf79d970326 | C++ | uskey512/AtCoder | /ABC/125/c.cpp | UTF-8 | 705 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
int main() {
int n; cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
vector<int> left(n + 1, 0), right(n + 1, 0);
left[1] = a[0];
for (int i = 2; i <= n; ++i) left[i] = gcd(left[i - 1], a[i - 1]);
for (int i = n - 1; 0 <= i; --i) right[i] = gcd(right[i + 1], a[i]);
int res = 0;
for (int i = 0; i < n; ++i) {
int tmp = gcd(left[i], right[i+1]);
if (res < tmp) res = tmp;
}
cout << res << endl;
}
| true |
6f1ca24667f1d0d5f501f16bf2ce73f886812004 | C++ | leolimcav/projeto01-ED | /Matrizes Esparsas/include/Matrix.h | UTF-8 | 1,318 | 3.65625 | 4 | [] | no_license | /*
* Aluno: Leonardo Lima Cavalcante
* Matricula: 427665
*/
#ifndef MATRIX_H
#define MATRIX_H
#include <string>
struct Node;
class Matrix
{
private:
Node *head;
public:
// Constructor: Create a new sparse matrix by initializin an empty
// circular linked list with head node.
Matrix();
// Destructor: Releases all allocated memory.
~Matrix();
// readMatrix: This method reads, from a file input, the elements different
// from zero of a matrix and creates a matrix with the values. The input
// consists in a pair of L(lines) and C(columns) followed by three values
// (i, j, value) for the elements different from zero of the matrix.
// Ex:
// 4, 4 (LxC)
// 1, 1, 50,0 (i, j, value)
// 2, 1, 10.0
// 2, 3, 20.0
// 4, 1, -30.0
// 4, 3, -60.0
// 4, 4, -5.0
void readMatrix(std::string filename);
// print: Prints the values on the stdout, the matrix line by line including
// zeros.
void print();
// insert: Insert a value on the line 'i', column 'j' of the matrix.
void insert(int i, int j, double value);
// sum: This method sum two matrices and return a new matrix C as the result.
Matrix *sum(Matrix *A, Matrix *B);
// multiply: This method multiplies two matrices and return a new matrix C
// as the result.
Matrix *multiply(Matrix *A, Matrix *B);
};
#endif
| true |
6d342ead6b89bb304fab1c41d79cf506afb99937 | C++ | 0xWaleed/qt-httpclient | /test/HttpClientTest.cpp | UTF-8 | 4,614 | 2.953125 | 3 | [] | no_license | //
// Created by MINE on 15/03/2020.
//
#include "dependency/catch.hpp"
#include <HttpClient.h>
#include <QApplication>
SCENARIO("Http Client Library With Basic Operations")
{
QString url(TEST_URL "/anything");
HttpClient httpClient;
GIVEN("Http Client to perform get Requests")
{
WHEN("The http request options is null")
{
THEN("should be success")
{
auto reply = httpClient.get(url);
REQUIRE(reply->statusCode() == 200);
}
}
WHEN("The HttpRequest is initialized")
{
THEN("should be success")
{
HttpRequest req;
auto reply = httpClient.get(url, &req);
REQUIRE(reply->statusCode() == 200);
}
}
}
GIVEN("Http Client to perform post requests")
{
WHEN("The http request options is null")
{
THEN("Should be success")
{
auto reply = httpClient.post(url);
REQUIRE(reply->statusCode() == 200);
}
}
WHEN("The http request option is initialized")
{
THEN("Should be success")
{
HttpRequest httpRequest;
QObject::connect(&httpClient, &HttpClient::beforeRequest, [](const HttpRequest* request) {
REQUIRE(request->timeout() == 3000);
});
httpRequest.setTimeout(3000);
auto reply = httpClient.post(url, &httpRequest);
REQUIRE(reply->statusCode() == 200);
}
}
}
GIVEN("Http Client to perform put requests")
{
WHEN("The http request options is null")
{
THEN("Should be success")
{
auto reply = httpClient.put(url);
REQUIRE(reply->statusCode() == 200);
}
}
WHEN("The http request option is initialized")
{
THEN("Should be success")
{
HttpRequest httpRequest;
QObject::connect(&httpClient, &HttpClient::beforeRequest, [](const HttpRequest* request) {
REQUIRE(request->timeout() == 3000);
});
httpRequest.setTimeout(3000);
auto reply = httpClient.put(url, &httpRequest);
REQUIRE(reply->statusCode() == 200);
}
}
}
GIVEN("Http Client to perform patch requests")
{
WHEN("The http request options is null")
{
THEN("Should be success")
{
auto reply = httpClient.patch(url);
REQUIRE(reply->statusCode() == 200);
}
}
WHEN("The http request option is initialized")
{
THEN("Should be success")
{
HttpRequest httpRequest;
QObject::connect(&httpClient, &HttpClient::beforeRequest, [](const HttpRequest* request) {
REQUIRE(request->timeout() == 3000);
});
httpRequest.setTimeout(3000);
auto reply = httpClient.patch(url, &httpRequest);
REQUIRE(reply->statusCode() == 200);
}
}
}
GIVEN("Http Client to perform delete requests")
{
WHEN("The http request options is null")
{
THEN("Should be success")
{
auto reply = httpClient.del(url);
REQUIRE(reply->statusCode() == 200);
}
}
WHEN("The http request option is initialized")
{
THEN("Should be success")
{
HttpRequest httpRequest;
QObject::connect(&httpClient, &HttpClient::beforeRequest, [](const HttpRequest* request) {
REQUIRE(request->timeout() == 3000);
});
httpRequest.setTimeout(3000);
auto reply = httpClient.del(url, &httpRequest);
REQUIRE(reply->statusCode() == 200);
}
}
}
}
SCENARIO("Http Client Library With Proxy")
{
HttpClient httpClient;
httpClient.setGlobalTimeout(5000);
QString url = "https://httpbin.org/ip";
GIVEN("HttpClient to perform http request with proxy")
{
WHEN("proxy is null")
{
THEN("return current IP")
{
auto reply = httpClient.get(url);
REQUIRE((!reply->json()["origin"].isNull()));
}
}
}
}
| true |
e29263a155f4599d274477fb5a180c335a995492 | C++ | kirillin/acmp | /courses/cpp/cycles/1127_list_of_powers_of_two.cpp | UTF-8 | 356 | 2.828125 | 3 | [] | no_license | /*
Problem N1127
list of powers of two
acmp.ru
Artemov Kirill
*/
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long long n, base;
cin >> n;
base = 2;
if (n <= 2) {
cout << 1 << " ";
}
if (n > 2) {
cout << 1 << " ";
cout << 2 << " ";
}
while ((2 * base) <= n) {
base = base * 2;
cout << base << " ";
}
return 0;
} | true |
241182685db7eaa01dcb2431e94934cd5567e6c9 | C++ | vkg001/DSA-important-question-solutions | /Queue Implimentation (Linked List).cpp | UTF-8 | 2,075 | 3.953125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Queue
{
int num;
Queue *next;
public:
Queue *front;
Queue *end;
Queue()
{
front=NULL;
end=NULL;
}
Queue(int n)
{
num=n;
next=NULL;
}
void enqueue(int n)
{
Queue *nn= new Queue(n);
if(front==NULL)
{
front=end=nn;
}
else
{
end->next=nn;
end=nn;
}
}
void Display()
{
if(front==NULL)
{
cout<<"Queue is Underflow."<<endl;
return;
}
else
{
Queue *temp=front;
cout<<"Front-> ";
while(temp->next!=NULL)
{
cout<<temp->num<<"-> ";
temp=temp->next;
}
cout<<"End"<<endl;
}
}
void dequeue()
{
if(front==NULL)
{
cout<<"Queue is Underflow."<<endl;
return;
}
else
{
Queue *temp=front;
cout<<temp->num<<" deleted."<<endl;
front=front->next;
free(temp);
return;
}
}
void peek()
{
if(front==NULL)
{
cout<<"Queue is Underflow."<<endl;
return;
}
else
{
int c;
cout<<front->num<<" is going to be deleted (1 to delete & 0 to leave)."<<endl;
cin>>c;
if(c==0) dequeue();
}
}
};
int main()
{
int n,i,x;
Queue var;
cout<<"Enter number of elements: ";
cin>>n;
cout<<"Enter elements ->\n";
for(i=0;i<n;i++)
{
cin>>x;
var.enqueue(x);
}
var.Display();
var.peek();
var.dequeue();
var.peek();
var.dequeue();
var.peek();
var.dequeue();
var.peek();
var.dequeue();
var.Display();
return 0;
}
| true |
eea47db282e23de8334332888a188e63081f6ee6 | C++ | danhui/allrgb | /event.h | UTF-8 | 455 | 3.640625 | 4 | [
"MIT"
] | permissive | #pragma once
// Event stores two things:
// 1. What type of event (e.g. mouse down, key up, key down, etc.)
// 2. The value from the event (eg. an ascii code).
class Event {
public:
Event (int type, int value) {
type_ = type;
value_ = value;
}
Event () {
type_ = 0;
value_ = 0;
}
int getType() {
return type_;
}
int getValue() {
return value_;
}
private:
int type_, value_;
};
| true |
b8fe4c9e862f0ceabb8cf3fb8d3c20f6c2b52815 | C++ | Tadamson20192/RayTracer | /Lab8/Ray.h | UTF-8 | 333 | 2.59375 | 3 | [] | no_license | #ifndef Ray_H
#define Ray_H
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
#include "Vector.h"
using namespace std;
class Ray {
public:
float x, y, z;
vec3 origin, direction;
Ray(vec3 inOrigin, vec3 inDirection) : origin(inOrigin), direction(inDirection){
}
};
#endif | true |
a7461d96335c05ca4548dae27ec35d40002a3ad3 | C++ | infinit/elle | /range-v3/test/utility/concepts2.cpp | UTF-8 | 10,676 | 2.625 | 3 | [
"Apache-2.0",
"NCSA",
"LicenseRef-scancode-mit-old-style",
"MIT",
"LicenseRef-scancode-other-permissive",
"BSL-1.0"
] | permissive | // Range v3 library
//
// Copyright Eric Niebler 2014-present
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
#include <concepts/concepts.hpp>
#include "../simple_test.hpp"
struct moveonly
{
moveonly(moveonly&&) = default;
moveonly& operator=(moveonly&&) = default;
};
struct nonmovable
{
nonmovable(nonmovable const &) = delete;
nonmovable& operator=(nonmovable const &) = delete;
};
struct nondefaultconstructible
{
nondefaultconstructible(int) {}
};
struct NotDestructible
{
~NotDestructible() = delete;
};
struct IntComparable
{
operator int() const;
friend bool operator==(IntComparable, IntComparable);
friend bool operator!=(IntComparable, IntComparable);
friend bool operator<(IntComparable, IntComparable);
friend bool operator>(IntComparable, IntComparable);
friend bool operator<=(IntComparable, IntComparable);
friend bool operator>=(IntComparable, IntComparable);
friend bool operator==(int, IntComparable);
friend bool operator!=(int, IntComparable);
friend bool operator==(IntComparable, int);
friend bool operator!=(IntComparable, int);
friend bool operator<(int, IntComparable);
friend bool operator<(IntComparable, int);
friend bool operator>(int, IntComparable);
friend bool operator>(IntComparable, int);
friend bool operator<=(int, IntComparable);
friend bool operator<=(IntComparable, int);
friend bool operator>=(int, IntComparable);
friend bool operator>=(IntComparable, int);
};
struct IntSwappable
{
operator int() const;
friend void swap(int &, IntSwappable);
friend void swap(IntSwappable, int &);
friend void swap(IntSwappable, IntSwappable);
};
static_assert(concepts::same_as<int, int>, "");
static_assert(concepts::same_as<void, void>, "");
static_assert(concepts::same_as<void const, void const>, "");
static_assert(!concepts::same_as<int&, int>, "");
static_assert(!concepts::same_as<void, void const>, "");
static_assert(!concepts::same_as<void(), void(*)()>, "");
static_assert(concepts::convertible_to<int, int>, "");
static_assert(concepts::convertible_to<short&, short const&>, "");
static_assert(concepts::convertible_to<int, short>, "");
static_assert(!concepts::convertible_to<int&, short&>, "");
static_assert(!concepts::convertible_to<int, void>, "");
static_assert(!concepts::convertible_to<int, int&>, "");
static_assert(concepts::unsigned_integral<unsigned>, "");
static_assert(!concepts::unsigned_integral<int>, "");
static_assert(concepts::assignable_from<int&, int>, "");
static_assert(!concepts::assignable_from<int const&, int>, "");
static_assert(!concepts::assignable_from<int, int>, "");
static_assert(concepts::destructible<int>, "");
static_assert(concepts::destructible<const int>, "");
static_assert(!concepts::destructible<void>, "");
static_assert(concepts::destructible<int&>, "");
static_assert(!concepts::destructible<void()>, "");
static_assert(concepts::destructible<void(*)()>, "");
static_assert(concepts::destructible<void(&)()>, "");
static_assert(!concepts::destructible<int[]>, "");
static_assert(concepts::destructible<int[2]>, "");
static_assert(concepts::destructible<int(*)[2]>, "");
static_assert(concepts::destructible<int(&)[2]>, "");
static_assert(concepts::destructible<moveonly>, "");
static_assert(concepts::destructible<nonmovable>, "");
static_assert(!concepts::destructible<NotDestructible>, "");
static_assert(concepts::constructible_from<int>, "");
static_assert(concepts::constructible_from<int const>, "");
static_assert(!concepts::constructible_from<void>, "");
static_assert(!concepts::constructible_from<int const &>, "");
static_assert(!concepts::constructible_from<int ()>, "");
static_assert(!concepts::constructible_from<int(&)()>, "");
static_assert(!concepts::constructible_from<int[]>, "");
static_assert(concepts::constructible_from<int[5]>, "");
static_assert(!concepts::constructible_from<nondefaultconstructible>, "");
static_assert(concepts::constructible_from<int const(&)[5], int(&)[5]>, "");
static_assert(!concepts::constructible_from<int, int(&)[3]>, "");
static_assert(concepts::constructible_from<int, int>, "");
static_assert(concepts::constructible_from<int, int&>, "");
static_assert(concepts::constructible_from<int, int&&>, "");
static_assert(concepts::constructible_from<int, const int>, "");
static_assert(concepts::constructible_from<int, const int&>, "");
static_assert(concepts::constructible_from<int, const int&&>, "");
static_assert(!concepts::constructible_from<int&, int>, "");
static_assert(concepts::constructible_from<int&, int&>, "");
static_assert(!concepts::constructible_from<int&, int&&>, "");
static_assert(!concepts::constructible_from<int&, const int>, "");
static_assert(!concepts::constructible_from<int&, const int&>, "");
static_assert(!concepts::constructible_from<int&, const int&&>, "");
static_assert(concepts::constructible_from<const int&, int>, "");
static_assert(concepts::constructible_from<const int&, int&>, "");
static_assert(concepts::constructible_from<const int&, int&&>, "");
static_assert(concepts::constructible_from<const int&, const int>, "");
static_assert(concepts::constructible_from<const int&, const int&>, "");
static_assert(concepts::constructible_from<const int&, const int&&>, "");
static_assert(concepts::constructible_from<int&&, int>, "");
static_assert(!concepts::constructible_from<int&&, int&>, "");
static_assert(concepts::constructible_from<int&&, int&&>, "");
static_assert(!concepts::constructible_from<int&&, const int>, "");
static_assert(!concepts::constructible_from<int&&, const int&>, "");
static_assert(!concepts::constructible_from<int&&, const int&&>, "");
static_assert(concepts::constructible_from<const int&&, int>, "");
static_assert(!concepts::constructible_from<const int&&, int&>, "");
static_assert(concepts::constructible_from<const int&&, int&&>, "");
static_assert(concepts::constructible_from<const int&&, const int>, "");
static_assert(!concepts::constructible_from<const int&&, const int&>, "");
static_assert(concepts::constructible_from<const int&&, const int&&>, "");
struct XXX
{
XXX() = default;
XXX(XXX&&) = delete;
explicit XXX(int) {}
};
static_assert(concepts::constructible_from<XXX, int>, "");
static_assert(!concepts::move_constructible<XXX>, "");
static_assert(!concepts::movable<XXX>, "");
static_assert(!concepts::semiregular<XXX>, "");
static_assert(!concepts::regular<XXX>, "");
static_assert(concepts::default_constructible<int>, "");
static_assert(concepts::default_constructible<int const>, "");
static_assert(!concepts::default_constructible<int const &>, "");
static_assert(!concepts::default_constructible<int ()>, "");
static_assert(!concepts::default_constructible<int(&)()>, "");
static_assert(!concepts::default_constructible<int[]>, "");
static_assert(concepts::default_constructible<int[5]>, "");
static_assert(!concepts::default_constructible<nondefaultconstructible>, "");
static_assert(concepts::move_constructible<int>, "");
static_assert(concepts::move_constructible<const int>, "");
static_assert(concepts::move_constructible<int &>, "");
static_assert(concepts::move_constructible<int &&>, "");
static_assert(concepts::move_constructible<const int &>, "");
static_assert(concepts::move_constructible<const int &&>, "");
static_assert(concepts::destructible<moveonly>, "");
static_assert(concepts::constructible_from<moveonly, moveonly>, "");
static_assert(concepts::move_constructible<moveonly>, "");
static_assert(!concepts::move_constructible<nonmovable>, "");
static_assert(concepts::move_constructible<nonmovable &>, "");
static_assert(concepts::move_constructible<nonmovable &&>, "");
static_assert(concepts::move_constructible<const nonmovable &>, "");
static_assert(concepts::move_constructible<const nonmovable &&>, "");
static_assert(concepts::copy_constructible<int>, "");
static_assert(concepts::copy_constructible<const int>, "");
static_assert(concepts::copy_constructible<int &>, "");
static_assert(!concepts::copy_constructible<int &&>, "");
static_assert(concepts::copy_constructible<const int &>, "");
static_assert(!concepts::copy_constructible<const int &&>, "");
static_assert(!concepts::copy_constructible<moveonly>, "");
static_assert(!concepts::copy_constructible<nonmovable>, "");
static_assert(concepts::copy_constructible<nonmovable &>, "");
static_assert(!concepts::copy_constructible<nonmovable &&>, "");
static_assert(concepts::copy_constructible<const nonmovable &>, "");
static_assert(!concepts::copy_constructible<const nonmovable &&>, "");
static_assert(concepts::movable<int>, "");
static_assert(!concepts::movable<int const>, "");
static_assert(concepts::movable<moveonly>, "");
static_assert(!concepts::movable<nonmovable>, "");
static_assert(concepts::copyable<int>, "");
static_assert(!concepts::copyable<int const>, "");
static_assert(!concepts::copyable<moveonly>, "");
static_assert(!concepts::copyable<nonmovable>, "");
// static_assert(concepts::predicate<std::less<int>, int, int>, "");
// static_assert(!concepts::predicate<std::less<int>, char*, int>, "");
static_assert(concepts::swappable<int &>, "");
static_assert(concepts::swappable<int>, "");
static_assert(!concepts::swappable<int const &>, "");
static_assert(concepts::swappable<IntSwappable>, "");
static_assert(concepts::swappable_with<IntSwappable, int &>, "");
static_assert(!concepts::swappable_with<IntSwappable, int const &>, "");
static_assert(concepts::totally_ordered<int>, "");
static_assert(concepts::common_with<int, IntComparable>, "");
static_assert(concepts::common_reference_with<int &, IntComparable &>, "");
static_assert(concepts::totally_ordered_with<int, IntComparable>, "");
static_assert(concepts::totally_ordered_with<IntComparable, int>, "");
static_assert(concepts::detail::weakly_equality_comparable_with_<int, int>, "");
static_assert(concepts::equality_comparable<int>, "");
static_assert(concepts::equality_comparable_with<int, int>, "");
static_assert(concepts::equality_comparable_with<int, IntComparable>, "");
static_assert(concepts::equality_comparable_with<int &, IntComparable &>, "");
CPP_template(class T)
(requires concepts::regular<T>)
constexpr bool is_regular(T&&)
{
return true;
}
CPP_template(class T)
(requires (!concepts::regular<T>))
constexpr bool is_regular(T&&)
{
return false;
}
static_assert(is_regular(42), "");
static_assert(!is_regular(XXX{}), "");
int main()
{
return test_result();
}
| true |
ba7b254c0498290f6efbbc6efc1ef85899a148ba | C++ | markuskr/raytracer | /CSGTree.h | UTF-8 | 1,174 | 2.765625 | 3 | [] | no_license | //----------------------------------------------------------------------
/// \author Markus Krallinger 0630748, Group: 20
/// \brief Represents the CSGTree
/// Last Changes: 22.06.2008
//----------------------------------------------------------------------
#ifndef CSGTREE_H
#define CSGTREE_H
#include "Primitive.h"
#include "ResultIntersect.h"
#include "Ray.h"
#include <vector>
using std::vector;
class CSGTree
{
public:
CSGTree(){};
~CSGTree()
{
delete m_tree.back();
};
//--------------------------------------------------------------------
/// \param primitive The primitive to add to the tree
/// \return Index of the primitive in the tree
int addPrimitive( Primitive *primitive )
{
m_tree.push_back(primitive);
return m_tree.size() - 1;
};
//--------------------------------------------------------------------
/// \return primitive The primitive in the tree
/// \param Index of the primitive in the tree
Primitive* getPrimitve(int index)
{
return m_tree[index];
};
//-------------------------------------------------------------------
private:
vector<Primitive *> m_tree;
};
#endif
| true |
c8715bbd4ff4feb441b1a0c185ba632236160fb2 | C++ | KAGSme/GP3-Coursework | /S1313540-GP3-Coursework/cFreeCameraActor.cpp | UTF-8 | 2,685 | 2.71875 | 3 | [] | no_license | #include "cFreeCameraActor.h"
cFreeCameraActor::cFreeCameraActor()
{
}
cFreeCameraActor::~cFreeCameraActor()
{
cInputMgr* iM = cInputMgr::getInstance();
InputAxis* iaV = iM->getInputAxisState("Vertical");
if (iaV)
__unhook(&InputAxis::InputAxisChange, iaV, &cFreeCameraActor::moveVertical);
InputAxis* iaH = iM->getInputAxisState("Horizontal");
if (iaH)
__unhook(&InputAxis::InputAxisChange, iaH, &cFreeCameraActor::moveHorizontal);
InputAction* iaS = iM->getInputActionState("SpeedBoost");
if (iaS)
__unhook(&InputAction::InputActionChange, iaS, &cFreeCameraActor::InputSpeedBoostHold);
}
void cFreeCameraActor::begin()
{
m_camera = new cCamera();
m_camera->setParentTransform(m_transform);
cSceneMgr::getInstance()->setMainCamera(m_camera);
cInputMgr* iM = cInputMgr::getInstance();
InputAxis* iaV = iM->getInputAxisState("Vertical");
if (iaV)
__hook(&InputAxis::InputAxisChange, iaV, &cFreeCameraActor::moveVertical);
InputAxis* iaH = iM->getInputAxisState("Horizontal");
if (iaH)
__hook(&InputAxis::InputAxisChange, iaH, &cFreeCameraActor::moveHorizontal);
InputAction* iaS = iM->getInputActionState("SpeedBoost");
if (iaS)
__hook(&InputAction::InputActionChange, iaS, &cFreeCameraActor::InputSpeedBoostHold);
}
void cFreeCameraActor::update(float elapsedTime)
{
currentElapsedTime = elapsedTime;
//get mouse movement
glm::ivec2 deltaPos = cInputMgr::getInstance()->mouseXYDelta();
std::string sDeltaPos = "x: " + to_string(deltaPos.x) + ", y: " + to_string(deltaPos.y) + "\n";
float deltaPitch = (float)deltaPos.y;
float deltaYaw = (float)deltaPos.x;
glm::quat qPitch = glm::quat(glm::vec3(glm::radians(deltaPitch), 0, 0));
glm::quat qYaw = glm::quat(glm::vec3(0, glm::radians(deltaYaw), 0));
m_transform->getTransformationMatrix();
//combine rotations this way to eliminate unwanted roll
glm::quat total = qPitch * m_transform->getRotation() * qYaw;
m_transform->setRotation(total);
}
void cFreeCameraActor::moveVertical(float state)
{
if (state >0)OutputDebugString("moveVertical pos\n");
else OutputDebugString("moveVertical neg\n");
m_transform->addPosition(m_camera->getTheCameraDirection() * currentElapsedTime * speed * state);
}
void cFreeCameraActor::moveHorizontal(float state)
{
if(state > 0)OutputDebugString("moveHorizontal Pos\n");
else OutputDebugString("moveHorizontal Neg\n");
m_transform->addPosition(m_camera->getTheCameraStrafe() * currentElapsedTime * speed * state);
}
void cFreeCameraActor::InputSpeedBoostHold(bool state)
{
if (state)
{
speed = boostSpeed;
OutputDebugString("speedBoost true\n");
}
else
{
speed = standardSpeed;
OutputDebugString("speedBoost false\n");
}
}
| true |
72b67d7560c959ffae2f0f5273c3c7e1dc7abe5c | C++ | andrewbolster/cppqubmarch2013 | /CppExamples/ObjectOrientation/FriendlyAccess/main.cpp | UTF-8 | 968 | 3.6875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class X;
int test(X& x);
class Z {
public:
int test(X& x);
};
class Y{
private:
//cannot be seen from X as friendship is one way
int hidden;
public:
int test(X& x);
};
class X {
private:
int i;
int func(){return 27;}
friend int test(X& x); //global function test is a friend
friend int Y::test(X& x); //method test in class Y is a friend
friend class Z; //all methods of Z are friends
friend int test2(X& x) { //this rarely used syntax declares
return x.func(); // a global function called test2
} // which is a friend of X
public:
X():i(17){}
};
int test(X& x) {return x.i;}
int Y::test(X& x){return x.i;}
int Z::test(X& x){return x.func();}
int main(){
X x;
Y y;
Z z;
cout << "Values returned are: " << test(x) << " " << test2(x)
<< " " << y.test(x) << " " << z.test(x) << endl;
} | true |
5a0728b16e7978b6a0d3b6ddd48acfbede5a2e39 | C++ | jeanyves-yang/skinning | /project/src/lib/perlin/perlin.hpp | UTF-8 | 1,610 | 2.65625 | 3 | [] | no_license | /*
** TP CPE Lyon
** Copyright (C) 2015 Damien Rohmer
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef PERLIN_HPP
#define PERLIN_HPP
namespace cpe
{
class vec2;
class vec3;
class vec4;
class perlin
{
public:
/** Empty constructor with default values */
perlin();
/** Provides octave and persistency parameters (persistency=1/attenuation)
*
* octave should be a number >0
* persistency should be in ]0,1[
*/
perlin(int octave_param,float persistency_param);
/** Perlin noise in 1D */
float operator()(float p) const;
/** Perlin noise in 2D */
float operator()(vec2 const& p) const;
/** Perlin noise in 3D */
float operator()(vec3 const& p) const;
/** Perlin noise in 4D */
float operator()(vec4 const& p) const;
private:
/** The number of octave (the number of sumation) */
int octave_data;
/** The attenuation for each octave */
float persistency_data;
};
}
#endif
| true |
c57a7869f984894c8ca082f59f0b337bf0b79220 | C++ | impyamin/TP_S2 | /TP5_S2/Node.cpp | UTF-8 | 231 | 2.640625 | 3 | [] | no_license | #include "Node.h"
Node::Node()
{
m_nodes.push_back(this);
}
std::vector<Node *> Node::allNode() const
{
for(Node n:m_nodes)
{
std::cout<<m_nodes.at(n)<<endl;
}
}
std::string Node::asXML() const
{
}
Node::~Node()
{
}
| true |
ae9ff02205b9b4b99999d80e0f0c5fcdeef5cc18 | C++ | kamyu104/LeetCode-Solutions | /C++/number-of-ways-to-stay-in-the-same-place-after-some-steps.cpp | UTF-8 | 543 | 2.75 | 3 | [
"MIT"
] | permissive | // Time: O(n^2), n is the number of steps
// Space: O(n)
class Solution {
public:
int numWays(int steps, int arrLen) {
static const int MOD = 1000000007;
const int l = min(1 + steps / 2, arrLen);
vector<int> dp(l + 2);
dp[1] = 1;
while (steps-- > 0) {
vector<int> new_dp(l + 2);
for (int i = 1; i <= l; ++i) {
new_dp[i] = (uint64_t(dp[i]) + dp[i - 1] + dp[i + 1]) % MOD;
}
dp = move(new_dp);
}
return dp[1];
}
};
| true |
97ea842fe48d900003ea9c627964f518549200f1 | C++ | Ashish65649/My-Repository | /Dijkstra.cpp | UTF-8 | 2,779 | 3.390625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Dijkstra{
private:
map<int,list<pair<int,int> > >m;
public:
void AddEdge(int src,int dest,int weight,bool bidirectional=true){
pair<int,int> p;
p = make_pair(dest,weight);
m[src].push_back(p);
if(bidirectional){
p = make_pair(src,weight);
m[dest].push_back(p);
}
}
int ReturnIndex(map<int,int> &n){
int min = INT_MAX;
int index;
map<int,int> :: iterator ir = n.begin();
index = ir->first;
for(auto x=ir;x!=n.end();x++){
if(min > x->second){
index = x->first;
min = x->second;
}
}
return index;
}
void Print(){
map<int,list<pair<int,int> > > :: iterator it = m.begin();
for(auto a=it; a!=m.end(); a++){
cout<<a->first<<" -> [";
list<pair<int,int> > p = a->second;
for(auto x=p.begin();x!=p.end();x++){
pair<int,int> pr = *x;
cout<<"( "<<pr.first<<","<<pr.second<<" )";
}
cout<<"]"<<endl;
}
}
int DIJKSTRA(int src,int dest){
map<int,int> distance;
distance[src] = 0;
map<int,int> marked;
map<int,int> ans;
ans[src] = 0;
map<int,list<pair<int,int> > > :: iterator it = m.begin();
for(auto a=it; a!=m.end(); a++){
if(a->first != src){
distance[a->first] = INT_MAX;
}
}
while(it++ != m.end()){
int index = ReturnIndex(distance);
list<pair<int,int> > l = m[index];
for(auto s=l.begin();s!=l.end();s++){
pair<int,int> p = *s;
if(!marked[p.first]){
int dist = distance[index] + p.second;
distance[p.first] = min(distance[p.first],dist);
ans[p.first] = distance[p.first];
}
}
marked[index] = 1;
distance.erase(index);
}
map<int,int> :: iterator h = ans.begin();
for(auto f=h;f!=ans.end();f++){
if(dest == f->first)
return f->second;
}
}
};
int main(){
Dijkstra d;
d.AddEdge(0,1,4);
d.AddEdge(0,2,8);
d.AddEdge(1,3,5);
d.AddEdge(2,4,9);
d.AddEdge(1,2,2);
d.AddEdge(3,4,4);
d.AddEdge(2,3,5);
cout<<d.DIJKSTRA(0,2)<<endl;
return 0;
} | true |
84b22c323f34b7e04a34538eff62f271863a02af | C++ | ksvcng/code | /documents/codechef/jan challange2018/test.cpp | UTF-8 | 9,695 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int SieveOfEratosthenes(int n)
{
bool prime[n+1];
int count=0;
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++){ if (prime[p] == true){for (int i=p*2; i<=n; i += p)prime[i] = false;}}
for (int p=2; p<=n; p++){if (prime[p]){cout<<prime[p]<<" ";count++;}}
//cout<<count;
//int *arr = new int[count];
//int i=0;
//for (int p=2; p<=n; p++){if (prime[p]){arr[i++]=p;}}
//int siz=count;
//for(i=0;i<siz;i++){cout<<arr[i]<<" ";}
//cout<<endl<<siz;
return count;
}
int main()
{ int n,i=0;
cin>>n;
int g = SieveOfEratosthenes( n);
cout<<endl<<g;
}
/**
#include<iostream>
#include <vector>
#include <algorithm>
#include<string>
#include<math.h>
#include<bits/stdc++.h>
#define RANGE 255
using namespace std;
int main()
{
//char cc[200002];
// string inp="abcdefghijklmnopqrstuvwxyz";
// for(int i=0;i<200002;i++){cc[i]=inp[i%26];}
//for(int i=0;i<200002;i++){cout<<cc[i]<<" ";}
string str,hstr="";
cin>>str;
char chh[str.length()+1];
strcpy(chh, str.c_str());
// countSort(chh);
// str=chh;
//cout<<str;
// string hstr="";
// for(long long i=0;i<str.length();i++) {
// for(long long j=1;(j+i)<=str.length();j++){hstr.append(str, i, j);}}
// countSort(char arr[])
//{
// The output character array that will have sorted arr
char output[strlen(chh)];
int pos[strlen(chh)];
int temp[strlen(chh)];
for(int i=0;i<strlen(chh);i++){pos[i]=i+1;}
//for(int i=0;i<strlen(chh);i++){cout<<pos[i]<<" ";}
//cout<<endl;
// Create a count array to store count of inidividul
// characters and initialize count array as 0
int count[RANGE + 1], i;
memset(count, 0, sizeof(count));
// Store count of each character
for(i = 0; chh[i]; ++i)
++count[chh[i]];
// Change count[i] so that count[i] now contains actual
// position of this character in output array
for (i = 1; i <= RANGE; ++i)
count[i] += count[i-1];
// Build the output character array
for (i = 0; chh[i]; ++i)
{
output[count[chh[i]]-1] = chh[i];
temp[count[chh[i]]-1]=pos[i];--temp[chh[i]];
--count[chh[i]];
}
// Copy the output array to arr, so that arr now
// contains sorted characters
/** for (i = 0; chh[i]; ++i){
chh[i] = output[i];
pos[i]=temp[i];}
*/
/**
for(int i=0;i<strlen(chh);i++){cout<<temp[i]<<" ";}
cout<<endl;
for(int i=0;i<strlen(chh);i++){cout<<output[i]<<" ";}
cout<<endl;
for(int i=0;i<strlen(chh);i++){cout<<pos[i]<<" ";}
cout<<endl;
for(int i=0;i<strlen(chh);i++){cout<<chh[i]<<" ";}
cout<<endl;
*/
//}
/**
long long q;
cin>>q;
long long g=0;
while(q--){
long long p,m,k,ack;
cin>>p>>m;
k=(p*g)%m+1;
char c=hstr[k-1];
int ascii=int(c);
ack=ascii;
g+=ack;
cout<<c<<endl;
}
return 0;}
*/
/**#include<bits/stdc++.h>
//#include <boost/algorithm/string.hpp>
using namespace std;
int main()
{
string str;
// cin>>str;
string hstr="abcdefghijklmnopqrstuvwxyz";
for(int i=0;i<26;i++){
char c=hstr[i];
long long p;
p=int(c);
cout<<c<<" "<<p<<endl;
}
// hstr[7]='m';
//cout<<hstr[7]<<" hhhhhhhhh ";
//hstr.append(str, 0, 1);
// cout<<hstr<<endl;
// string str="keshavkhgfkkkkkkjjkkkkkkjiykjhjgkl";
/**string str="";
for(int i=0;i<s.length();i++){
str+=s[i];
if(i!=s.length()-1){ str.append(s,i,s.length()-i);}
}
cout<<str;
*/
//strOrig.replaceAll("[aeiouAEIOU]", "");//in java
// replace (str1.begin(), str1.end(), 'k' , 'p');// ok
//boost::erase_all(str1, "a");
//char c=str1[0];
//str1.erase(std::remove(str1.begin(), str1.end(), c), str1.end());//ok
// cout<<str1;
//return 0;
//}
/**
int P,G,M;
cin>>P>>G>>M;
int pii= (P*G)%M+1;
cout<<pii;
*/
/**#include<bits/stdc++.h>
using namespace std;
int val(char c){
int res;
string str="abcdefghijklmnopqrstuvwxyz";
for(int i=0;i<26;i++){if(str[i]=='c'){res=i;break;}}
return res;
}
int main()
{
string str="keshav singh";
string s="blank ";
int value=val([s[s.length()-1]]);
s+=str[3];
cout<<s<<" "<<value;
}
*/
/**
#include<bits/stdc++.h>
using namespace std;
int main()
{ long long t;
cin>>t;
while(t--)
{
long long x,n;
long long sum=0;
cin>>x>>n;
sum=(n*(n+1)/2)-x;
if(sum%2!=0 || n<=3){cout<<"impossible"<<endl;}
else{
string str="";
for(long long i=0;i<n;i++){str+="0";}
str[x-1]='2';
long long var=n;
long long sm=0,des=sum/2;
while(var>0){
if(var!=x){
if(sm+var<=des){str[var-1]='1'; sm+=var;}
if(sm==des){break;}
}
var--;
}
long long p=str.length(),eq=0,eq1=0;
for(long long i=0;i<p;i++){if(str[i]=='1'){eq+=i+1;}}
for(long long i=0;i<p;i++){if(str[i]=='0'){eq1+=i+1;}}
if(des==eq && des==eq1){}
else{str="impossible";}
cout<<str<<endl;
}
}
return 0;
}
*/
/**
#include<bits/stdc++.h>
using namespace std;
int main()
{ int t;
cin>>t;
while(t--)
{
long long x,n;
long long int sum=0;
cin>>x>>n;
sum=(n*(n+1)/2)-x;
cout<<" sum= "<<sum<<endl;
if(sum%2!=0 || n<=3){cout<<"impossible"<<endl;}
else{
// FILE *fp;
// fp=fopen("f1.txt","w");
ofstream fout,ff;
fout.open("f1.txt");
ff.open("f2.txt");
string str="";
for(int i=0;i<n;i++){str+="0";}
str[x-1]='2';
long long var=n;//cout<<var;
int count=0;
long long sm=0,des=sum/2;
cout<<" sum= "<<sum<<" sum/2 = "<<sum/2;
cout<<"sm= "<<sm<<" dec= "<<des<<" var= "<<var;
while(var>0){
// cout<<" loop entered";
if(var!=x){
//if(count<100){cout<<"L";count++;}
if(sm+var<=des){str[var-1]='1'; sm+=var;string ss="/";ff<<var;ff<<ss;}
if(sm==des){break;}
}
var--;
}
//fputs(str,fp);
//fwrite(&str,sizeof(str),1,fp);//compile sucessfully
// fprintf(fp,"ans is %s ",str);
/// string ss1="\n";
// fout<<ss1;
fout<<str;
fout.close();
ff.close();
// fclose(fp);
// cout<<str<<endl;
long long p=str.length(),eq=0;
while(str[p-1]=='1' || str[p-1]=='2'){if(str[p-1]=='1'){eq+=p;}
p--;}
for(int i=0;i<p;i++){if(str[i]=='1'){eq+=i+1;}}
if(des==eq){cout<<"yes"<<endl;}
else{cout<<"no"<<endl;}
}
}
return 0;
}
*/
/**
#include<bits/stdc++.h>
using namespace std;
int main()
{ int t;
cin>>t;
while(t--)
{
long long int x,n;
long long sum=0;
cin>>x>>n;
sum=(n*(n+1)/2)-x;
if(sum%2!=0 || n<=3){cout<<"impossible"<<endl;}
else{
string str="";
for(int i=0;i<n;i++){str+="0";}
str[x-1]='2';
int var=n;
long long sm=0,des=sum/2;
while(var>0){ if(var!=x){
if(sm+var<=des){str[var-1]='1'; sm+=var;}
if(sm==des){break;}
}
var--;
}
cout<<str<<endl;
}
}
return 0;
}
*/
| true |
d02a0819339717401bc9aef25b464549592b852f | C++ | GuyTristram/grt | /include/common/valuepack.h | UTF-8 | 4,123 | 3.25 | 3 | [
"MIT"
] | permissive | #ifndef VALUEPACK_H
#define VALUEPACK_H
#include <tuple>
#include <limits>
#include <cassert>
namespace grt
{
template<class T>
struct value_pack_max { static const size_t value = static_cast<size_t>(T::Count) - 1; };
namespace vp_helpers
{
template<size_t I> struct bits { static const size_t value = bits<I / 2>::value + 1; };
template<> struct bits<0> { static const size_t value = 0; };
template<class T, size_t I> struct mask { static const T value = ( mask<T, I - 1>::value << 1 ) + 1; };
template<class T> struct mask<T, 0> { static const T value = 0; };
template<size_t I, class... Args> struct shift{};
template<size_t I, class Head, class... Tail> struct shift <I, Head, Tail...>
{
static const size_t value = shift<I - 1, Tail...>::value +
bits<value_pack_max<Head>::value>::value;
};
template<class Head, class... Tail> struct shift <0ul, Head, Tail...> { static const size_t value = 0; };
template<class... Args> struct shift <0ul, Args...> { static const size_t value = 0; };
}
/** Pack enum values, bools and integers into a single unsigned int.
*
* The first template argument specifies the type into which the values
* will be packed (usually one of uint8_t, uint16_t, uint32_t, uint64_t).
*
* To use an enum in a value_pack you must either specialize value_pack_max
* for the enum type (there is a macro VALUE_PACK_ENUM_MAX to make this
* easier) or provide "Count" as the last enumerator.
*
* To use an unsigned integer in a value_pack, specify the maximum value
* using packed_int<max>. Signed integers are not supported.
*
* Example use:
*
* enum class A
* {
* A1,
* A2,
* Count
* };
*
* enum class B
* {
* B1,
* B2,
* B3
* };
* VALUE_PACK_ENUM_MAX( B, B3 );
*
* value_pack<std::uint32_t, A, B, bool, packed_int<5>> pack;
*
* pack.set<0>(A::A2);
* pack.set<1>(B::B1);
* pack.set<2>(true);
* pack.set<3>(5); // Ok
* pack.set<3>(6); // Will assert
* auto a = pack.get<0>();
*
*/
template<class T, class... Args> class value_pack
{
public:
template <size_t I>
using type_at = typename std::tuple_element<I, std::tuple<Args...>>::type;
template<size_t I>
type_at<I> get() const
{
return static_cast<type_at<I>>((m_packed >> shift<I>()) & mask<I>());
}
template<size_t I>
void set(type_at<I> value)
{
assert(static_cast<T>(value) <= value_pack_max<type_at<I>>::value);
m_packed = (m_packed & ~(mask<I>() << shift<I>())) | (static_cast<T>(value) << shift<I>());
}
bool operator==(value_pack other) const { return m_packed == other.m_packed; }
bool operator<(value_pack other) const { return m_packed < other.m_packed; }
private:
T m_packed = 0;
template<size_t I> static size_t shift() { return vp_helpers::shift<I, Args...>::value; }
template<size_t I> static T mask()
{
return vp_helpers::mask<T, vp_helpers::bits<value_pack_max<type_at<I>>::value>::value>::value;
}
static const size_t total_size = vp_helpers::shift<sizeof...(Args), Args...>::value;
static_assert(total_size <= std::numeric_limits<T>::digits, "Pack type is too small");
};
template<class E, E Max>
struct packed_enum {
packed_enum( E e ) : e( e ) {}
operator E() const { return e; }
operator size_t() const { return static_cast< size_t >( e ); }
private:
E e;
};
template<class E, E Max> struct value_pack_max<packed_enum<E, Max>> { static const size_t value = static_cast<size_t>(Max); };
template<size_t Max>
struct packed_int {
packed_int( unsigned int i ) : i( i ) {}
operator unsigned int() const { return i; }
private:
unsigned int i;
};
template<size_t Max> struct value_pack_max<packed_int<Max>> { static const size_t value = Max; };
template<> struct value_pack_max<bool> { static const size_t value = 1; };
}
#define VALUE_PACK_ENUM_MAX(Enum, Max) template<> struct grt::value_pack_max<Enum> { static const size_t value = static_cast<size_t>(Enum::Max); };
void test_value_pack();
#endif // VALUEPACK_H
| true |
d04fd74a2428433bd20c57d2b40136a5c74926fd | C++ | bharathstranger/IS_F311_Assignments | /Second_Assign_3D_Scene/Principles of Computer Graphics/OpenGL/Example10_3/Example10_3.cpp | UTF-8 | 5,980 | 2.546875 | 3 | [] | no_license | #include <windows.h> //the windows include file, required by all windows applications
#include <gl\glut.h>
#include "Example10_3.h"
#include "..\bmp.h"
void UpdateCameraPosition(CAMERAINFO *camera) {
LARGE_INTEGER currentTime;
GLfloat elapsedTime;
GLfloat velocity=0;
GLfloat avelocity= 0;
// if up arrow has been pressed, velocity is now forward
if (KEYDOWN(VK_UP))
velocity = 0.4f;
if (KEYDOWN(VK_DOWN))
velocity = -0.4f;
if (KEYDOWN(VK_LEFT))
avelocity = -7;
if (KEYDOWN(VK_RIGHT))
avelocity = 7;
QueryPerformanceCounter(¤tTime);
elapsedTime = (GLfloat)(currentTime.QuadPart - lastTime.QuadPart)/frequency.QuadPart;
lastTime = currentTime;
camera->orientation[0] = 0.;
camera->orientation[1] += avelocity*elapsedTime;
camera->orientation[2] = 0.0;
camera->position[0] += elapsedTime * velocity * ((GLfloat)sin(TORADIANS(camera->orientation[1]))) ;
camera->position[1] = 0.2;
camera->position[2] -= elapsedTime * velocity * ((GLfloat)cos(TORADIANS(camera->orientation[1])));
}
void MoveCameraPosition(CAMERAINFO camera){
glRotatef(camera.orientation[2], 0.,0.,1.);
glRotatef(camera.orientation[1], 0.,1.,0.);
glRotatef(camera.orientation[0], 1.,0.,0.);
glTranslatef(-camera.position[0], -camera.position[1], -camera.position[2]);
}
void Display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
UpdateCameraPosition(&camera);
MoveCameraPosition(camera);
drawWorld(camera);
glFlush();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluPerspective(35., (GLfloat)w/h, 0.5, 50.0);
glMatrixMode(GL_MODELVIEW);
}
void timer(int value)
{
// Force a redisplay .. , also contains game logic
glutPostRedisplay();
// Restart the timer
glutTimerFunc(10, timer, 0);
}
void InitCameraPosition(CAMERAINFO *camera){
camera->position[0] =0;
camera->position[1] = 0.2;
camera->position[2] =0 ;
camera->orientation[0] += 0.0;
camera->orientation[1] = 0.0;
camera->orientation[2] = 0.0;
}
void init(void)
{
glClearColor (0.5,0.5,0.5,0);
glEnable(GL_DEPTH_TEST);
// OpenGL's automatic generation of texture coordinates
{
/* Use the x=0 and z=0 plane for s and t generation
because the plane and the cylinders
(in Object space) rest on the x-z plane */
float tPlane[4] = {0., 0., 1., 0.};
glTexGenfv (GL_T, GL_OBJECT_PLANE, tPlane);
float sPlane[4] = {1., 0., 0., 0.};
glTexGenfv (GL_S, GL_OBJECT_PLANE, sPlane);
}
// Generate the texture coordinates based on object coords distance from the axis.
glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
// Enable OpenGL's automatic generation of texture coordinates
glEnable (GL_TEXTURE_GEN_S);
glEnable (GL_TEXTURE_GEN_T);
glGenTextures(2, textureIDs);
glBindTexture(GL_TEXTURE_2D, textureIDs[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_NEAREST);
bits = ReadBitmap("..\\Images\\terrain.bmp", &info);
glTexImage2D(GL_TEXTURE_2D, 0, 3, info->bmiHeader.biWidth,
info->bmiHeader.biHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE,
bits);
glBindTexture(GL_TEXTURE_2D, textureIDs[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_NEAREST);
bits2 = ReadBitmap("..\\Images\\windows.bmp", &info2);
glTexImage2D(GL_TEXTURE_2D, 0, 3, info2->bmiHeader.biWidth,
info2->bmiHeader.biHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE,
bits2);
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
GLfloat light_position[] = { 0.0, 1.0, 1.0, 0.0 };
GLfloat light_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
GLfloat light_diffuse[] = { 0.5, 0.5, 0.5, 1.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_ambient);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
GLfloat light_position1[] = { -1.0, -1.0, 0.0, 0.0 };
glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glShadeModel (GL_SMOOTH);
GLfloat fogColor[4]= {0.5f, 0.5f, 0.5f, 1.0f}; // Fog Color
glFogi(GL_FOG_MODE, GL_LINEAR); // Fog Mode
glFogfv(GL_FOG_COLOR, fogColor); // Set Fog Color
glFogf(GL_FOG_DENSITY, 0.35f); // How Dense Will The Fog Be
glFogf(GL_FOG_START, 1.0f); // Fog Start Depth
glFogf(GL_FOG_END, 25.0f); // Fog End Depth
glEnable(GL_FOG);
glutTimerFunc(10, timer, 0);
InitCameraPosition(&camera);
InitWorld();
QueryPerformanceCounter(&lastTime);
QueryPerformanceFrequency(&frequency);
}
void main(int argc, char** argv)
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(640, 400);
glutCreateWindow("Terrain Viewing");
init();
glutDisplayFunc(Display);
glutReshapeFunc(reshape);
glutTimerFunc(10, timer, 0);
glutMainLoop();
} | true |
66ac0923df5d15f89484d37765a311fd4ace454b | C++ | Ding-Feng/PAT | /Template/并查集.cpp | UTF-8 | 762 | 2.65625 | 3 | [] | no_license | #include <algorithm>
using namespace std;
vector<int> fa;
class UnionFind {
private:
int* id;
int count;
public:
UnionFind(int n) {
count = n;
id = new int[n];
}
};
int find(int x) {
if (x != fa[x]) {
fa[x] = find(fa[x]); //回溯时的压缩路径
}
return fa[x];
//从x结点搜索到祖先结点所经过的结点都指向该祖先结点
//会导致栈溢出
//路径压缩
int a = x;
while (x != fa[x]) x = fa[x];
while (a != fa[a]) {
int t = a;
a = fa[a];
fa[t] = x;
}
return x;
}
void Union(int a, int b) {
int faA = fa[a];
int faB = fa[b];
if (faA != faB) fa[faA] = faB;
}
int main(int argc, char const* argv[]) { return 0; }
| true |
4d00ad5639c66c9754528ca6aeeec419b83a4878 | C++ | htwsoft/VS2 | /server/XMLWorker/source/XMLWorkerTest.cpp | UTF-8 | 7,531 | 2.8125 | 3 | [] | no_license |
#include "XMLWorkerTest.h"
#include <iostream>
using namespace std;
XMLWorkerTest::XMLWorkerTest()
{
this->xmlWorker = new XMLWorker();
}
XMLWorkerTest::~XMLWorkerTest()
{
delete this->xmlWorker;
}
void XMLWorkerTest::starteTest()
{
this->starteBenutzersteuerung();
}
/*
* Methode Startet die Benutzersteuerung für den Test
*/
void XMLWorkerTest::starteBenutzersteuerung()
{
Menueauswahl benutzerEingabe;
do
{
benutzerEingabe = zeigeMenue();
cout << endl;
try
{
switch(benutzerEingabe)
{
case AUSGEBEN:
this->testeAnzeigeRootNode();
cout << endl;
break;
case NEUE_XML:
this->testeNeueRoot();
break;
case ANZAHL_CHILDS_ROOT:
this->testeAnzahlChildsRoot();
cout << endl;
break;
case CREATE_CHILD:
this->testeCreateChildNode();
cout << endl;
break;
case NODE_WITHOUT_CHILD:
this->testeAusgabeWorkNodeOhneChild();
cout << endl;
break;
case NODE_WITH_CHILD:
this->testeAusgabeWorkNodeMitChild();
cout << endl;
break;
case GET_FIRST_CHILD:
this->testeGetFirstChild();
cout << endl;
break;
case GET_NEXT_CHILD:
this->testeGetNextChild();
break;
case SEARCH_CHILD:
this->testeSearchChild();
cout << endl;
break;
case CREATE_ATTRIBUT:
this->testeCreateAttribut();
break;
case SEARCH_ATTRIBUT:
this->testeSearchAttribut();
cout << endl;
break;
case SET_WORK_NODE:
this->testeSetWorkNode();
cout << endl;
break;
case LOAD_XML:
this->testeLadeXML();
cout << endl;
break;
case SAVE_XML:
this->testeXMLspeichern();
cout << endl;
break;
case ENDE:
cout << "Test beendet!" << endl;
break;
default:
cout << "Ungueltige Eingabe!" << endl;
break;
}
}
catch(const char * c)
{
cout << "Achtung: " << c << endl;
}
catch(...)
{
cout << "Achtung: Unbekannter Fehler!" << endl;
}
}
while(benutzerEingabe != ENDE);
}
void XMLWorkerTest::testeAnzeigeRootNode()
{
XMLNode * rootNode = NULL;
rootNode = this->xmlWorker->getRootNode();
cout << rootNode->toString(true) << endl;
}
void XMLWorkerTest::testeLadeXML()
{
string fileName;
cout << "Welche XML soll geladen werden?: ";
cin >> fileName;
if(this->xmlWorker->loadXML(fileName))
{
cout << endl << "Datei erfolgreich geladen" << endl;
}
else
{
cout << endl << "Datei konnte nicht geladen werden!" << endl;
}
}
void XMLWorkerTest::testeSearchAttribut()
{
XMLAttribut * searchedAttr = NULL;
string name;
cout << "Name des gesuchten Attributes: ";
cin >> name;
searchedAttr = this->xmlWorker->getAttributWithName(name);
if(searchedAttr == NULL)
{
cout << "keine Node gefunden!" << endl;
}
else
{
cout << searchedAttr->toString() << endl;
}
}
void XMLWorkerTest::testeSearchChild()
{
XMLNode * searchedNode = NULL;
string name;
cout << "Name der gesuchten Node: ";
cin >> name;
searchedNode = this->xmlWorker->getChildNodeWithName(name);
if(searchedNode == NULL)
{
cout << "keine Node gefunden!" << endl;
}
else
{
cout << searchedNode->toString() << endl;
}
}
void XMLWorkerTest::testeSetWorkNode()
{
XMLNode * newWorkNode = NULL;
newWorkNode = this->xmlWorker->getFirstChildNode();
this->xmlWorker->setWorkNode(newWorkNode);
cout << "neue WorkNode: " << newWorkNode->toString() << endl;
}
void XMLWorkerTest::testeCreateAttribut()
{
XMLAttribut * attr = NULL;
string name;
string value;
cout << "neues Attribut fuer Node: " << this->xmlWorker->getWorkNode()->getName() << endl;
cout << "Name: ";
cin >> name;
cout << "Value: ";
cin >> value;
attr = this->xmlWorker->createAttribut(name, value);
cout << "neues Attribut: " << attr->toString() << endl;
}
void XMLWorkerTest::testeGetNextChild()
{
XMLNode * child;
child = this->xmlWorker->getNextChildNode();
cout << "First Child: " << child->toString() << endl;
cout << "Father Node: " << child->getFatherNode()->toString() << endl;
}
void XMLWorkerTest::testeGetFirstChild()
{
XMLNode * child;
child = this->xmlWorker->getFirstChildNode();
cout << "First Child: " << child->toString() << endl;
cout << "Father Node: " << child->getFatherNode()->toString() << endl;
}
void XMLWorkerTest::testeXMLspeichern()
{
string fileName;
bool speicherErfolgreich;
cout << "Name der XML-Datei: ";
cin >> fileName;
speicherErfolgreich = this->xmlWorker->saveXML(fileName);
if(speicherErfolgreich)
{
cout << "Datei wurde gespeichert" << endl;
}
else
{
cout << "Fehler beim Speichern der Datei!" << endl;
}
}
/*
* teste Ausgabe der WorkNode ohne Childs
*/
void XMLWorkerTest::testeAusgabeWorkNodeOhneChild()
{
XMLNode * workNode;
workNode = this->xmlWorker->getWorkNode();
cout << workNode->toString() << endl;
}
/*
* teste Ausgabe der WorkNode mit den Childs
*/
void XMLWorkerTest::testeAusgabeWorkNodeMitChild()
{
XMLNode * workNode;
workNode = this->xmlWorker->getWorkNode();
cout << workNode->toString(true) << endl;
}
void XMLWorkerTest::testeCreateChildNode()
{
string name = "";
string value = "";
XMLNode * workNode; //zuletzt angesprochene Node
XMLNode * newChild; //Referenz auf neues Child
workNode = this->xmlWorker->getWorkNode();
cout << "neue Child-Node fuer Node: " << workNode->getName() << endl;
cout << "Name: ";
cin >> name;
cout << "Value: ";
cin >> value;
//erstellen einer neuen Child-Node fuer die zuletzt
//angesprochene Node
newChild = this->xmlWorker->createChildNode(name, value);
cout << "neue Node erstellt: " << newChild->toString() << endl;
}
/*
* Test ob anzahl der Root-ChildNodes richtig ausgegeben wird
*/
void XMLWorkerTest::testeAnzahlChildsRoot()
{
XMLNode * rootNode;
rootNode = this->xmlWorker->getRootNode();
cout << "Anzahl Chids der Root: " << rootNode->getChildCount() << endl;
}
/*
* testen ob anlegen der RoorNode funktioniert
*/
void XMLWorkerTest::testeNeueRoot()
{
string name = "";
cout<<"Name der RoorNode: ";
cin >> name;
this->xmlWorker->createRootNode(name);
}
Menueauswahl XMLWorkerTest::zeigeMenue()
{
int benutzerEingabe = 0;
do
{
cout << "Menueauswahl" << endl
<< "---------------" << endl
<< AUSGEBEN << ": Anzeigen der XML" << endl
<< NEUE_XML << ": Neue Root erstellen" << endl
<< ANZAHL_CHILDS_ROOT << ": Anz. Childs Root" << endl
<< CREATE_CHILD << ": erstelle neue Child-Node" << endl
<< NODE_WITH_CHILD << ": zeige Work-Node mit Child" << endl
<< NODE_WITHOUT_CHILD << ": zeige Work-Node ohne Child" << endl
<< GET_FIRST_CHILD << ": Wechsel zum ersten Child" << endl
<< GET_NEXT_CHILD << ": Wechsel zum naechsten Child" << endl
<< SEARCH_CHILD << ": suchen eines Childs" << endl
<< CREATE_ATTRIBUT << ": Neues Attribut erstellen" << endl
<< SEARCH_ATTRIBUT << ": suchen eines Attributes" << endl
<< SET_WORK_NODE << ": Neue Work Node setzen" << endl
<< LOAD_XML << ": XML laden" << endl
<< SAVE_XML << ": XML speichern" << endl
<< ENDE << ": Ende" << endl;
cout << "Ihre Eingabe: ";
cin >> benutzerEingabe;
cout << endl;
}
while(benutzerEingabe < AUSGEBEN && benutzerEingabe > ENDE);
return static_cast<Menueauswahl>(benutzerEingabe);
} | true |
6fe8de11e86edeb055ddd5d2291260ddd39579f4 | C++ | Thor99/OldAndMaybeNewThingz | /obi/stockMaximizeHackerrank.cpp | UTF-8 | 660 | 2.890625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int testes;
scanf("%d", &testes);
while(testes--){
int N;
vector<int> prices;
long long int profit = 0;
scanf("%d", &N);
for(int i = 0; i < N; i++){
int price;
scanf("%d", &price);
prices.push_back(price);
}
int max_local_profit = 0;
for(int i = N - 1; i >= 0; i--){
max_local_profit = max(max_local_profit, prices[i]);
profit += (long long int) max_local_profit - prices[i];
}
printf("%lld\n", profit);
}
} | true |
75a2c1efb4c8421a6f45606d1d5a2b30394f68b0 | C++ | CompPhysics/ThesisProjects | /doc/MSc/msc_students/former/ChristianF/ThesisCodes/vmc-solver/Math/random.cpp | UTF-8 | 1,289 | 2.65625 | 3 | [
"CC0-1.0"
] | permissive | #include "random.h"
#include <cmath>
long Random::iy = 0;
long Random::iv[NTAB];
long Random::seed = -1;
void Random::setSeed(long seed) {
Random::seed = seed;
}
double Random::nextGaussian(double mean, double standardDeviation) {
double standardNormalRandomNumber = sqrt( -2.0*log(1.0 - nextDouble()) ) * cos( 6.283185307 * nextDouble() );
return standardDeviation*standardNormalRandomNumber + mean;
}
int Random::nextInt(int upperLimit) {
return std::floor(nextDouble() * upperLimit);
}
double Random::nextDouble()
{
int j;
long k;
double temp;
if (Random::seed <= 0 || !iy) {
if (-(Random::seed) < 1) Random::seed=1;
else Random::seed = -(Random::seed);
for(j = NTAB + 7; j >= 0; j--) {
k = (Random::seed)/IQ;
Random::seed = IA*(Random::seed - k*IQ) - IR*k;
if(Random::seed < 0) Random::seed += IM;
if(j < NTAB) iv[j] = Random::seed;
}
iy = iv[0];
}
k = (Random::seed)/IQ;
Random::seed = IA*(Random::seed - k*IQ) - IR*k;
if(Random::seed < 0) Random::seed += IM;
j = iy/NDIV;
iy = iv[j];
iv[j] = Random::seed;
if((temp=AM*iy) > RNMX) return RNMX;
else return temp;
}
| true |
2c29532c5863611e21353c463b5df5c0777c65fe | C++ | hmc-cs-jamelang/hmc-tessellate | /test/diagram-test.cpp | UTF-8 | 13,469 | 3.03125 | 3 | [
"MIT"
] | permissive | /*
* diagram-test.cpp
*
* Tests for the hmc-tessellate interface.
*
* Does NOT test for correct results, simply that the interface works.
*/
#include <algorithm>
#include <cstdlib>
#include <vector>
#include "../src/hmc-tessellate.hpp"
using namespace std;
using namespace hmc;
// tee hee
#define FACE_AREAS 0
// Determines the size of each dimension in each diagram
const int SCALE = 10;
// The number of particles to test in each diagram
const int NUM_PARTICLES = 10;
// Standard function beginning for non-group tests
#define NOGROUP_HEADER(n,d) \
n = NUM_PARTICLES; \
add_n_particles(d, n); \
d.initialize();
// Standard function beginning for group tests
#define GROUP_HEADER(n,d,g1,g2,t) \
n = NUM_PARTICLES; \
g1 = 0; \
g2 = 1; \
add_n_particles_group(d, 0, n/2, g1); \
add_n_particles_group(d, n/2, n, g2); \
d.initialize(); \
t = d.targetGroups(g1);
// Macro for printing the elements of a vector, which we do frequently
#define ITERATE_AND_PRINT(vect) \
for (auto& element : vect) { \
cout << element << " "; \
} \
cout << endl;
// Macro for comparing two values. Print and return a failure state if they
// are different.
#define FAIL_IF_DIFFERENT(fst,snd) \
if (fst != snd) { \
cout << "FAILED" << endl; \
return false; \
}
// Macro for checking whether Diagram function fn affects groups and non-groups
// with the same particles in the same way.
#define COMPARE_TARGET_NOGROUP(groupVector,nogroupVector,fn) \
t = d.targetGroups(red, blue); \
Cell cn; \
for (int i = 0; i < n; ++i) { \
groupVector.clear(); \
nogroupVector.clear(); \
\
c = d.getCell(i, t); \
cn = d.getCell(i); \
c.fn(groupVector); \
cn.fn(nogroupVector); \
\
if (groupVector != nogroupVector) { \
cout << "FAILED" << endl; \
return false; \
} \
} \
cout << "COMPLETE" << endl;
// Macro for running a test and stating whether it passed or failed.
#define TEST_PASS_OR_FAIL(name,fn) \
if (fn) { \
cout << name << " test complete" << endl; \
} \
else { \
cout << name << " test failed" << endl; \
return false; \
}
/*
* random_double
*
* Helper function for tests. Generate a random double between 0 and SCALE.
*/
double random_double()
{
return ((double) rand() / RAND_MAX) * SCALE;
}
/*
* add_n_particles
*
* Helper function for tests. Inserts n particles in diagram d.
*/
void add_n_particles(Diagram& d, int n)
{
for (int id = 0; id < n; ++id) {
d.addParticle(random_double(), random_double(), random_double());
}
}
/*
* add_n_particles_group
*
* Helper function for tests. Inserts particles b through e-1 in diagram d assigned to group g.
*/
void add_n_particles_group(Diagram& d, int b, int e, int g)
{
for (int id = b; id < e; ++id) {
d.addParticle(random_double(), random_double(), random_double(), g);
}
}
/*
* neighbor_test_nogroups
*
* Check that each cell can find its neighbors when there are no groups.
*/
bool neighbor_test_nogroups()
{
int n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
NOGROUP_HEADER(n, d);
vector<int> neighborList;
Cell c;
for (int i = 0; i < n; ++i) {
neighborList.clear();
c = d.getCell(i);
c.computeNeighbors(neighborList);
cout << "Neighbor list of particle " << i << ": ";
ITERATE_AND_PRINT(neighborList);
}
return true;
}
/*
* volume_test_nogroups
*
* Check that each cell can find its volume when there are no groups.
*/
bool volume_test_nogroups()
{
int n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
NOGROUP_HEADER(n,d);
Cell c;
for (int i = 0; i < n; ++i) {
c = d.getCell(i);
cout << "Volume of cell " << i << ": " << c.computeVolume() << endl;
}
return true;
}
/*
* vertices_test_nogroups
*
* Check that each cell can find its vertices when there are no groups.
*/
bool vertices_test_nogroups()
{
int n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
NOGROUP_HEADER(n,d);
vector<double> verticesList;
Cell c;
for (int i = 0; i < n; ++i) {
verticesList.clear();
c = d.getCell(i);
c.computeVertices(verticesList);
cout << "Vertices of cell " << i << ": ";
ITERATE_AND_PRINT(verticesList);
}
return true;
}
#if FACE_AREAS
/*
* face_areas_test_nogroups
*
* Check that each cell can find its face areas when there are no groups.
*/
bool face_areas_test_nogroups()
{
int n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
NOGROUP_HEADER(n,d);
vector<double> areaList;
Cell c;
for (int i = 0; i < n; ++i) {
areaList.clear();
c = d.getCell(i);
c.computeFaceAreas(areaList);
cout << "Face areas of cell " << i << ": ";
ITERATE_AND_PRINT(areaList);
}
return true;
}
#endif
/*
* fake_cell_test_nogroups
*
* Check that a fake cell works correctly when there are no groups.
*/
bool fake_cell_test_nogroups()
{
int n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
NOGROUP_HEADER(n,d);
double x = random_double();
double y = random_double();
double z = random_double();
Cell c = d.getCell(x, y, z);
vector<int> neighborList;
vector<double> verticesList;
vector<double> areaList;
double volume = c.computeVolume();
c.computeNeighbors(neighborList);
c.computeVertices(verticesList);
#if FACE_AREAS
c.computeFaceAreas(areaList);
#endif
cout << "Computed fake particle at (" << x << ", " << y << ", " << z << ")" << endl;
cout << "\tVolume: " << volume << endl;
cout << "\tNeighbors: ";
ITERATE_AND_PRINT(neighborList);
cout << "\tVertices: ";
ITERATE_AND_PRINT(verticesList);
#if FACE_AREAS
cout << "\tFace areas: ";
ITERATE_AND_PRINT(areaList);
#endif
return true;
}
/*
* neighbor_test_targetgroups
*
* Check that each cell can find its neighbors when using target groups.
*/
bool neighbor_test_targetgroups()
{
int red, blue, n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
TargetGroup t;
GROUP_HEADER(n,d,red,blue,t);
vector<int> neighborList;
Cell c;
for (int i = 0; i < n; ++i) {
neighborList.clear();
c = d.getCell(i, t);
c.computeNeighbors(neighborList);
cout << "Neighbors of particle " << i << " in red group: ";
for (auto neighbor : neighborList) {
cout << neighbor << " ";
if (neighbor >= n/2) {
cout << "INVALID NEIGHBOR FOUND" << endl;
return false;
}
}
cout << endl;
}
vector<int> neighborListNoGroups;
cout << "Comparing neighbors with and without groups: ";
COMPARE_TARGET_NOGROUP(neighborList,neighborListNoGroups,computeNeighbors);
return true;
}
/*
* vertices_test_targetgroups
*
* Check that each cell can find its vertices when using target groups.
*/
bool vertices_test_targetgroups()
{
int red, blue, n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
TargetGroup t;
GROUP_HEADER(n,d,red,blue,t);
vector<double> verticesList;
Cell c;
for (int i = 0; i < n; ++i) {
verticesList.clear();
c = d.getCell(i, t);
c.computeVertices(verticesList);
cout << "Vertices of particle " << i << " in red group: ";
ITERATE_AND_PRINT(verticesList);
}
vector<double> verticesListNoGroups;
cout << "Comparing vertices with and without groups: ";
COMPARE_TARGET_NOGROUP(verticesList,verticesListNoGroups,computeVertices);
return true;
}
#if FACE_AREAS
/*
* face_area_test_targetgroups
*
* Check that each cell can find its face areas when using target groups.
*/
bool face_area_test_targetgroups()
{
int red, blue, n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
TargetGroup t;
GROUP_HEADER(n,d,red,blue,t);
vector<double> areaList;
Cell c;
for (int i = 0; i < n; ++i) {
areaList.clear();
c = d.getCell(i, t);
c.computeFaceAreas(areaList);
cout << "Face areas of particle " << i << " in red group: ";
ITERATE_AND_PRINT(areaList);
}
vector<double> areaListNoGroups;
cout << "Comparing face areas with and without groups: ";
COMPARE_TARGET_NOGROUP(areaList,areaListNoGroups,computeFaceAreas);
return true;
}
#endif
/*
* volume_test_targetgroups
*
* Check that each cell can find its volume when using target groups.
*/
bool volume_test_targetgroups()
{
int red, blue, n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
TargetGroup t;
GROUP_HEADER(n,d,red,blue,t);
double volume;
Cell c;
for (int i = 0; i < n; ++i) {
c = d.getCell(i, t);
volume = c.computeVolume();
cout << "Volume of particle " << i << " in red group: " << volume << endl;
}
cout << "Comparing volumes with and without groups: ";
t = d.targetGroups(red, blue);
Cell cn;
for (int i = 0; i < n; ++i) {
c = d.getCell(i, t);
cn = d.getCell(i);
FAIL_IF_DIFFERENT(c.computeVolume(),cn.computeVolume());
}
cout << "COMPLETE" << endl;
return true;
}
/*
* fake_cell_test_targetgroups
*
* Check that a fake cell works correctly when using target groups.
*/
bool fake_cell_test_targetgroups()
{
int red, blue, n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
TargetGroup t;
GROUP_HEADER(n,d,red,blue,t);
double x = random_double();
double y = random_double();
double z = random_double();
Cell c = d.getCell(x, y, z, t);
vector<int> neighborList;
vector<double> verticesList;
vector<double> areaList;
double volume = c.computeVolume();
c.computeNeighbors(neighborList);
c.computeVertices(verticesList);
#if FACE_AREAS
c.computeFaceAreas(areaList);
#endif
cout << "Computed fake particle at (" << x << ", " << y << ", " << z << ")" << endl;
cout << "\tVolume: " << volume << endl;
cout << "\tNeighbors: ";
ITERATE_AND_PRINT(neighborList);
cout << "\tVertices: ";
ITERATE_AND_PRINT(verticesList);
#if FACE_AREAS
cout << "\tFace areas: ";
ITERATE_AND_PRINT(areaList);
#endif
cout << "\tComparing fake cells with and without groups:" << endl;
t = d.targetGroups(red, blue);
c = d.getCell(x, y, z, t);
Cell cn = d.getCell(x, y, z);
neighborList.clear();
verticesList.clear();
areaList.clear();
volume = c.computeVolume();
c.computeNeighbors(neighborList);
c.computeVertices(verticesList);
#if FACE_AREAS
c.computeFaceAreas(areaList);
#endif
vector<int> neighborListNG;
vector<double> verticesListNG;
vector<double> areaListNG;
double volumeNG = c.computeVolume();
cn.computeNeighbors(neighborListNG);
cn.computeVertices(verticesListNG);
#if FACE_AREAS
cn.computeFaceAreas(areaListNG);
#endif
cout << "\t\tComparing volumes: ";
FAIL_IF_DIFFERENT(volume,volumeNG);
cout << "COMPLETE" << endl;
cout << "\t\tComparing neighbors: ";
FAIL_IF_DIFFERENT(neighborList,neighborListNG);
cout << "COMPLETE" << endl;
cout << "\t\tComparing vertices: ";
FAIL_IF_DIFFERENT(verticesList,verticesListNG);
cout << "COMPLETE" << endl;
#if FACE_AREAS
cout << "\t\tComparing face areas: ";
FAIL_IF_DIFFERENT(areaList,areaListNG);
cout << "COMPLETE" << endl;
#endif
return true;
}
/*
* sourcegroup_test
*
* Check that source groups work correctly. Since this should just return a vector
* with specific indices, the test is minimal.
*/
bool sourcegroup_test()
{
int red, blue, n;
Diagram d = Diagram::cube(0, SCALE, 0, SCALE, 0, SCALE);
TargetGroup t;
GROUP_HEADER(n,d,red,blue,t);
vector<int> redVect;
vector<int> blueVect;
vector<int> all;
for (int i = 0; i < n/2; ++i) {
redVect.push_back(i);
all.push_back(i);
}
for (int i = n/2; i < n; ++i) {
blueVect.push_back(i);
all.push_back(i);
}
auto fillGroupVector = [&](std::vector<int>& container, SourceGroup group) {
for (auto& i : group) {
container.push_back(((Cell) d.getCell(i)).getOriginalIndex());
}
std::sort(container.begin(), container.end());
};
vector<int> redGroup, blueGroup, allGroup;
fillGroupVector(redGroup, d.sourceGroups(red));
fillGroupVector(blueGroup, d.sourceGroups(blue));
fillGroupVector(allGroup, d.sourceGroups(red, blue));
cout << "Checking correctness of red source group: ";
FAIL_IF_DIFFERENT(redGroup,redVect);
cout << "COMPLETE" << endl;
cout << "Checking correctness of blue source group: ";
FAIL_IF_DIFFERENT(blueGroup,blueVect);
cout << "COMPLETE" << endl;
cout << "Checking correctness of red and blue source group: ";
FAIL_IF_DIFFERENT(allGroup,all);
cout << "COMPLETE" << endl;
return true;
}
/*
* run_nogroup_tests
*
* Run the tests that do not use groups.
*/
bool run_nogroup_tests()
{
TEST_PASS_OR_FAIL("Neighbor",neighbor_test_nogroups());
TEST_PASS_OR_FAIL("Volume",volume_test_nogroups());
TEST_PASS_OR_FAIL("Vertices",vertices_test_nogroups());
#if FACE_AREAS
TEST_PASS_OR_FAIL("Face areas",face_areas_test_nogroups());
#endif
TEST_PASS_OR_FAIL("Fake cell",fake_cell_test_nogroups());
return true;
}
/*
* run_targetgroup_tests
*
* Run the tests that use target groups.
*/
bool run_targetgroup_tests()
{
TEST_PASS_OR_FAIL("Neighbor",neighbor_test_targetgroups());
TEST_PASS_OR_FAIL("Vertices",vertices_test_targetgroups());
#if FACE_AREAS
TEST_PASS_OR_FAIL("Face areas",face_area_test_targetgroups());
#endif
TEST_PASS_OR_FAIL("Volume",volume_test_targetgroups());
TEST_PASS_OR_FAIL("Fake cell",fake_cell_test_targetgroups());
return true;
}
/*
* main
*
* Runs the tests.
*/
int main()
{
TEST_PASS_OR_FAIL("No group",run_nogroup_tests());
TEST_PASS_OR_FAIL("Target group",run_targetgroup_tests());
TEST_PASS_OR_FAIL("Source group",sourcegroup_test());
return 0;
}
| true |
fe5d97e5bff53dad71038b6b303881a30e452860 | C++ | grahambrooks/lazybuilder | /src/command_line.hpp | UTF-8 | 674 | 3.15625 | 3 | [] | no_license | class is {
public:
static bool verbose_option(const char *option) {
return not_null(option) && switch_char(option[0]) && verbose_char(option[1]) && eos(&option[2]);
}
static bool trigger_option(const char* option) {
return not_null(option) && switch_char(option[0]) && trigger_char(option[1]) && eos(&option[2]);
}
static bool not_null(const char *t) {
return t != NULL;
}
static bool switch_char(const char c) {
return c == '-';
}
static bool verbose_char(const char c) {
return c == 'v';
}
static bool trigger_char(const char c) {
return c == 't';
}
static bool eos(const char *c) {
return *c == 0;
};
};
| true |
89f14cc30cdceace7d4f830c32e54b06e7257d1b | C++ | quanhuynh2007/oop | /matrix/matrixVer1/fractionOperator.cpp | UTF-8 | 2,702 | 3.171875 | 3 | [] | no_license | #include "fractionOperator.h"
Fraction::Fraction()
{
numerator = 0;
denominator = 1;
}
Fraction::Fraction(ulong num, ulong den)
{
if (den < 0)
{
num = -num;
den = -den;
}
if (den == 0)
{
den = 1; num = 0;
}
numerator = num;
denominator = den;
compact();
}
void Fraction::compact()
{
if (denominator == 0)
{
cout << "denominator = 0!!!" << endl;
numerator = 0;
denominator = 1;
return;
}
ulong num = labs(numerator);
ulong den = labs(denominator);
ulong rec = 0;
while (den != 0)
{
rec = num % den;
num = den;
den = rec;
}
//
numerator = (ulong)numerator/num;
denominator = (ulong)denominator/num;
if (denominator < 0)
{
numerator = -numerator;
denominator = -denominator;
}
}
const Fraction Fraction::operator+(const Fraction& src) const
{
Fraction temp;
temp.numerator = numerator * src.denominator + src.numerator * denominator;
temp.denominator = denominator * src.denominator;
temp.compact();
return temp;
}
const Fraction Fraction::operator*(const Fraction& src) const
{
Fraction temp;
temp.numerator = numerator * src.numerator;
temp.denominator = denominator * src.denominator;
temp.compact();
return temp;
}
bool Fraction::operator==(const Fraction& src) const
{
// assumption: after each calculate, Fraction is very simple
return (((numerator == src.numerator)) && ((denominator == src.denominator)));
}
// operator overloading <<
ostream& operator<<(ostream &out, const Fraction& src)
{
string buf;
buf = to_string(src.numerator);
if (src.denominator != 1)
{
buf = buf + "/" + to_string(src.denominator);
}
out << buf;
return out;
}
// ostream& operator<<(ostream &out, const float src)
// {
// out << src;
// return out;
// }
istream& operator>> (istream &is, Fraction& src)
{
string buf;
fflush(stdin); // remove cache
is >> buf;
int pos = buf.find('/'); // Fraction
ulong num, den;
if (pos > 0)
{
num = stoi(buf.substr(0, pos));
den = stoi(buf.substr(pos + 1, buf.length() - pos));
}
else
{
pos = buf.find('.'); // Float
if (pos > 0)
{
den = stoi(buf.substr(pos + 1, buf.length() - pos));
num = stoi(buf.substr(0, pos)) * pow(10, buf.length() - 2) + den;
den = pow(10, buf.length() - 2);
}
else
{
num = stoi(buf);
den = 1;
}
}
src.numerator = num;
src.denominator = den;
src.compact();
return is;
}
| true |
6ae739229bcfc0a4d84551787ffb8a20b823566d | C++ | mothergoose729/AutomatedSTEPV1.0 | /alpha3.0/STEPAutomatedInstaller.cpp | UTF-8 | 3,703 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
using namespace std;
void unpackModDirectories(string);
void cleanup(string);
void specialOps(ifstream&, string);
const char* CONFIG = "source/config";
const char* ARCHIVENAME = "source/name";
const char* SOURCEDIRECTORYFILETXT = "source/sourceDirectory";
const char* UNARCHIVECOMMAND = "7z x \"";
const char* UNARCHIVEFLAGS = "\" -aoa -y -o";
const char* dataDir = "data";
const char* XCOPYCOMMAND = "xcopy /f /e /y /c \"";
const char* DELETE = "rd /s /q \"";
const char* ROBOCOPY = "robocopy /MOVE /e /is \"";
const char* MKDIR = "mkdir \"";
int main(int argc, char *argv[])
{
string command;
string buffer;
string sourceDir;
ifstream sourceDirFile(SOURCEDIRECTORYFILETXT);
getline(sourceDirFile, sourceDir);
sourceDirFile.close();
ifstream config(CONFIG);
command = MKDIR + sourceDir + "\"";
cout << command << endl;
system(command.c_str());
command = MKDIR + sourceDir + "/" + dataDir + "\"";
cout << command << endl;
system(command.c_str());
command = UNARCHIVECOMMAND;
system("mkdir temp");
while(getline(config, buffer))
{
if (buffer[0] == '!')
{
specialOps(config, buffer);
}
else
{
command+= buffer + UNARCHIVEFLAGS + sourceDir;
cout << command << endl;
system(command.c_str());
command = UNARCHIVECOMMAND;
unpackModDirectories(sourceDir);
cleanup(sourceDir);
system("Pause");
}
system("rd /s /q temp");
system("mkdir temp");
}
system("PAUSE");
return EXIT_SUCCESS;
}
void unpackModDirectories(string sourceDir)
{
string command = ROBOCOPY;
string buffer;
system("dir /b /a:d skyrim > dirList.temp");
ifstream dirList("dirList.temp");
while(getline(dirList, buffer))
{
for(int i = 0; buffer[i] != '\0'; i++)
{
buffer[i] = tolower(buffer[i]);
}
if (buffer != dataDir && buffer != "textures" && buffer != "meshes" && buffer != "video" && buffer != "strings" && buffer != "scripts" && buffer != "sound" && buffer != "interface")
{
command+= sourceDir + "\\" + buffer + "\" " + sourceDir;
cout << command << endl;
system(command.c_str());
command = ROBOCOPY;
}
}
dirList.close();
system("del /q dirList.temp");
}
void cleanup(string sourceDir)
{
string command = ROBOCOPY;
string buffer;
system("dir /b /a:d skyrim > dirList.temp");
ifstream dirList("dirList.temp");
while(getline(dirList, buffer))
{
if (buffer != dataDir)
{
command+= sourceDir + "\\" + buffer + "\" " + sourceDir + "\\" + dataDir + "\\" + buffer + "\"";
cout << command << endl;
system(command.c_str());
command = ROBOCOPY;
}
}
command = "move /y " + sourceDir + "\\" + "*.esp " + sourceDir + "\\" + dataDir;
cout << command << endl;
system(command.c_str());
command = "move /y " + sourceDir + "\\" + "*.bsa " + sourceDir + "\\" + dataDir;
cout << command << endl;
system(command.c_str());
command = "move /y " + sourceDir + "\\" + "*.bsl " + sourceDir + "\\" + dataDir;
cout << command << endl;
system(command.c_str());
dirList.close();
system("del /q dirList.temp");
}
void specialOps(ifstream& config, string buffer)
{/*
string command = UNARCHIVECOMMAND + buffer + UNARCHIVEFLAGS + "temp";
system(command.c_str());
while(getline(config, buffer))
{
if (buffer == "!")
{
return;
}
else
{
if (buffer.find(" & ") == buffer.npos || buffer.find(" & ") == buffer.npos)
{
}
}
}
}
*/}
| true |
b81f406dd2e793ed36f6ecec1a7ce79bf4a2f37c | C++ | inter-bellum/Inber | /Neopixels.ino | UTF-8 | 1,886 | 2.8125 | 3 | [] | no_license | #include <Adafruit_NeoPixel.h>
#define LED_PIN 3
#define NUM_NOTES 5
#define NUM_LEDS_PER_HIT 4
#define NUM_LEDS 20
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
//how bright are all the pixels
float pixelBright[NUM_LEDS];
//how fast to dim the pixels
float pixelDimSpeed = 0.11;
//default color of the pixels
uint32_t color;
//how long should it take to dim the pixels
int pixelTimeOut = 100;
LPFilter pixelBrightFilter[NUM_NOTES];
void initPixels() {
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(250); // Set BRIGHTNESS to about 1/5 (max = 255)
for (int i = 0; i < strip.numPixels(); i ++) {
strip.setPixelColor(i, strip.Color(100, 255, 10));
strip.show();
delay(50);
}
delay(100);
for (int i = 0; i < strip.numPixels(); i ++) {
strip.setPixelColor(i, strip.Color(0, 0, 0));
}
strip.show();
color = strip.Color(50, 120, 250);
}
void updatePixels() {
for (int i = 0; i < NUM_LEDS; i++){
uint8_t filterIndex = i / NUM_LEDS_PER_HIT;
pixelBright[filterIndex] = pixelBrightFilter[filterIndex].update(pixelBright[filterIndex], 0.8);
if (pixelBright[filterIndex] > 0) {
pixelBright[filterIndex] -= pixelDimSpeed;
if (pixelBright[filterIndex] < 0){
pixelBright[filterIndex] = 0;
}
Serial.print("LED" + String(i) + ",");
Serial.println(pixelBright[filterIndex]);
}
if (pixelBright[filterIndex] > 1){
pixelBright[filterIndex] = 1;
}
strip.setPixelColor(i, strip.Color(50 * pixelBright[filterIndex], 120 * pixelBright[filterIndex], 250 * pixelBright[filterIndex]));
}
strip.show();
}
void pixelHit(int i) {
pixelBrightFilter[i].force(1);
pixelBright[i] = 1;
}
| true |
3df920307c8678473c3a14fbfa693ca9594506c3 | C++ | piotrGTX/Matrix | /Matrix.h | WINDOWS-1250 | 1,698 | 3.359375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
class Matrix {
public:
static Matrix myMatrixExample(const size_t N, const double a1, const double a2, const double a3);
static Matrix myVectorExample(const size_t N);
// Nie zainicjowana
Matrix(size_t N, size_t M);
Matrix(size_t N);
// Zainicjowana przy pomocy value
Matrix(size_t N, size_t M, double value);
Matrix(size_t N, double value);
// Zainicjowana jawnie podanymi elementami
Matrix(size_t N, size_t M, const double **new_arr);
Matrix(size_t N, const double **new_arr);
// Kopiowanie
Matrix(const Matrix& matrix);
// Przenoszcy
Matrix(Matrix&& matrix);
~Matrix();
Matrix & operator=(const Matrix & matrix);
Matrix & operator=(Matrix&& matrix);
double* const operator[](size_t index);
const double* const operator[](size_t index) const;
Matrix operator+(const Matrix& other) const;
Matrix operator-(const Matrix& other) const;
Matrix operator*(double value) const;
Matrix operator*(const Matrix& other) const;
bool isSquared() const;
bool isTriangularUpper() const;
bool isTriangularLower() const;
bool isVector() const;
bool equalsSize(const Matrix& other) const;
bool canBeMultiple(const Matrix& other) const;
Matrix getTriangularUpper() const;
Matrix getTriangularLower() const;
Matrix getDiagnonal() const;
Matrix podstawienieWPrzod(const Matrix & vector) const;
Matrix podstawienieWTyl(const Matrix & vector) const;
Matrix metodaJacobiego(const Matrix& vector) const;
Matrix metodaSeidla(const Matrix& vector) const;
Matrix faktoryzacjaLU(const Matrix& vector) const;
double norm() const;
size_t getN() const;
size_t getM() const;
private:
size_t N, M;
double ** arr;
};
| true |
2dc77d4991efb8fae12367c4d06d7061e2a08bdf | C++ | AnneLivia/Competitive-Programming | /Online Judges/URI/1115/main.cpp | UTF-8 | 439 | 3.296875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "stdio.h"
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
while(x != 0 && y != 0){
if(x > 0 && y > 0)
cout << "primeiro\n";
else if(x < 0 && y > 0)
cout << "segundo\n";
else if(x < 0 && y < 0)
cout << "terceiro\n";
else if(x > 0 && y < 0)
cout << "quarto\n";
cin >> x >> y;
}
return 0;
}
| true |
1e8091ced057c424243d2c970faa0f9457aecb8f | C++ | MarcDerequitooo/CodeLab2---Files | /Exercise 1 - Biography.cpp | UTF-8 | 513 | 3.40625 | 3 | [] | no_license | #include<iostream>
using namespace std;
main()
{
string name,hometown;
double age;
cout<<"State your Information in this order: \nFull name, Hometown, and Age"<<endl;
getline(cin,name);
getline(cin,hometown);
scanf("%d",&age);
printf("Full Name: %s \n",name.c_str());
printf("Hometown: %s \n",hometown.c_str());
printf("Age: %d \n",age);
printf(" My name is %s,",name.c_str());
printf(" I'm from %s, and",hometown.c_str());
printf(" I'm %d years old",age);
return 0;
}
| true |
b3cf1593273e6eac04e96d70bff22a9187a29138 | C++ | ordinary-developer/education | /cpp/std-17/m_bancila-modern_cpp_programming_cookbook/ch_01-core_lang/04-non-static_member_initialization.cpp | UTF-8 | 4,259 | 3.5625 | 4 | [
"MIT"
] | permissive | // region [how to do it]
#include <iostream>
#include <string>
namespace example_01 {
enum class TextVAlignment { Up, Middle, Bottom };
enum class TextHAlignment { Rigth, Left };
struct Control {
int const DefaultHeight = 14;
int const DefaultWidth = 80;
std::string text;
TextVAlignment valign = TextVAlignment::Middle;
TextHAlignment halign = TextHAlignment::Left;
Control(std::string const& t) : text{ t } {}
Control(std::string const& t, TextVAlignment const va, TextHAlignment const ha)
: text{ t }, valign{ va }, halign{ ha } {}
};
void run() {
Control("example");
}
} // example_01
// endregion [how to do it]
// region [how it works]
namespace example_02 {
struct Point {
double X, Y;
Point(double const x = 0.0, double const y = 0.0) : X{ x }, Y{ y } {}
};
void run() {
Point();
}
} // example_02
#include <iostream>
#include <string>
namespace example_03 {
struct foo {
foo() {
std::cout << "default ctor" << std::endl;
}
foo(std::string const& text) {
std::cout << "ctor '" << text << "'" << std::endl;
}
foo(foo const & other) {
std::cout << "copy ctor" << std::endl;
}
foo(foo&& other) {
std::cout << "move constructor" << std::endl;
}
foo& operator=(foo const& other) {
std::cout << "assignment" << std::endl;
return *this;
}
foo& operator=(foo&& other) {
std::cout << "move assignment" << std::endl;
return *this;
}
~foo() {
std::cout << "dtor" << std::endl;
}
};
struct bar {
foo f;
bar(foo const& value) {
f = value;
}
};
void run() {
foo f{};
bar b{ f };
}
} // example_03
#include <iostream>
#include <string>
namespace example_04 {
struct foo {
foo() {
std::cout << "default ctor" << std::endl;
}
foo(std::string const& text) {
std::cout << "ctor '" << text << "'" << std::endl;
}
foo(foo const & other) {
std::cout << "copy ctor" << std::endl;
}
foo(foo&& other) {
std::cout << "move constructor" << std::endl;
}
foo& operator=(foo const& other) {
std::cout << "assignment" << std::endl;
return *this;
}
foo& operator=(foo&& other) {
std::cout << "move assignment" << std::endl;
return *this;
}
~foo() {
std::cout << "dtor" << std::endl;
}
};
struct bar {
foo f;
bar(foo const& value)
: f{ value } {}
};
void run() {
foo f{};
bar b{ f };
}
} // example_04
#include <string>
namespace example_05 {
enum class TextFlow { LeftToRight, RightToLeft };
struct Control {
int const DefaultHeight{ 20 };
int const DefaultWidth{ 100 };
TextFlow textFlow{ TextFlow::LeftToRight };
std::string text;
Control(std::string const& t) : text{ t } {}
};
void run() {
Control("");
}
} // example_05
#include <iostream>
#include <string>
namespace example_06 {
struct foo {
foo() {
std::cout << "default ctor" << std::endl;
}
foo(std::string const& text) {
std::cout << "ctor '" << text << "'" << std::endl;
}
foo(foo const & other) {
std::cout << "copy ctor" << std::endl;
}
foo(foo&& other) {
std::cout << "move constructor" << std::endl;
}
foo& operator=(foo const& other) {
std::cout << "assignment" << std::endl;
return *this;
}
foo& operator=(foo&& other) {
std::cout << "move assignment" << std::endl;
return *this;
}
~foo() {
std::cout << "dtor" << std::endl;
}
};
struct bar {
foo f{ "default value" };
bar() : f{ "construct initializer" } {}
};
void run() {
bar b{};
}
} // example_06
// endregion [how it works]
#include <iostream>
int main() {
example_01::run();
example_02::run();
example_03::run();
example_04::run();
example_05::run();
example_06::run();
std::cout << "DONE" << std::endl;
return 0;
}
| true |
8f0016ca365fe2f76f7a7e8f49780836c0a2d091 | C++ | stefanobiano/PC | /editDistanceOpenmp.cpp | UTF-8 | 2,026 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <string>
#include <set>
#include<iostream>
#include <time.h>
#include <omp.h>
using namespace std;
class EditDistance {
private:
string firstString;
string secondString;
int firstStringLength;
int secondStringLength;
int editMatrix[1500][1500];
int i, j;
public:
EditDistance(string firstStringP, string secondStringP) {
firstString = firstStringP;
secondString = secondStringP;
firstStringLength = firstString.size();
secondStringLength = secondString.size();
}
int min3(int a, int b, int c) {
return (a < b ? std::min(a, c) : std::min(b, c));
}
int calculate(int fi, int ff, int si, int sf ) {
int i, j;
for (i = fi; i < ff + 1; i++) {
for (j = si; j < sf + 1; j++) {
if (i == 0 || j == 0) {
editMatrix[i][j] = std::max(i, j);
} else {
editMatrix[i][j] = min3(
editMatrix[i - 1][j] + 1,
editMatrix[i][j - 1] + 1,
editMatrix[i - 1][j - 1] + (firstString.at(i - 1) != secondString.at(j - 1) ? 1 : 0));
}
}
}
cout << " ";
cout << "La distanza ? " << editMatrix[firstStringLength][secondStringLength];
return 0;
}
};
int main()
{
EditDistance ed("gagcccgtttcggatattcgcctttcggccaaaaatatggaatttagatagtccttgtgtgcggcctgtcatggttagagccacttagctataggatacccctgccttgcattgcgcggctcctggtgggttcgtaagacgtccaaagagatgc", "gagcccgtttcggatattcgcctttcggccaaaaatatggaatttagatagtccttgtgtgcggcctgtcatggttagagccacttagctataggatacccctgccttgcattgcgcggctcctggtgggttcgtaagacgtccaaagagatgc");
clock_t tStart = clock();
ed.calculate(0, 750, 0, 750);
#pragma omp parallel sections
{
#pragma omp section
ed.calculate(751, 1500, 0, 750);
#pragma omp section
ed.calculate(0, 750, 751, 1500);
}
ed.calculate(751, 1500, 751, 1500);
cout << "\n";
printf("Time taken: %.5fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
| true |
84e1f5e4feac56f713a93fa62bc1605c6ffe6979 | C++ | jakubtyrcha/playground | /Benchmarks/hashmap_benchmarks.cpp | UTF-8 | 1,856 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "Hashmap.h"
#include "box.h"
#define CATCH_CONFIG_ENABLE_BENCHMARKING
#include "catch/catch.hpp"
using namespace Playground;
#include <unordered_map>
TEST_CASE("hashmap fill up", "hashmap_vs_unordered_map")
{
BENCHMARK("Hashmap")
{
Hashmap<i32, i32> h;
for(i32 i=0; i<100000; i++) {
h.Insert(i, i);
}
return h.Size();
};
BENCHMARK("UnorderedMap")
{
std::unordered_map<i32, i32> h;
for(i32 i=0; i<100000; i++) {
h.insert(std::make_pair(i, i));
}
return h.size();
};
}
TEST_CASE("hashmap query (hit)", "hashmap_vs_unordered_map")
{
Hashmap<i32, i32> h;
for (i32 i = 0; i < 100000; i++) {
h.Insert(i, i);
}
BENCHMARK("Hashmap")
{
i32 sum = 0;
for (i32 i = 0; i < 50000; i+=2) {
sum += h.Contains(i) ? 1 : 0;
}
return sum;
};
std::unordered_map<i32, i32> um;
for (i32 i = 0; i < 100000; i++) {
um.insert(std::make_pair(i, i));
}
BENCHMARK("UnorderedMap")
{
i32 sum = 0;
for (i32 i = 0; i < 50000; i+=2) {
sum += As<i32>(um.count(i));
}
return sum;
};
}
TEST_CASE("hashmap query (miss)", "hashmap_vs_unordered_map")
{
Hashmap<i32, i32> h;
for (i32 i = 0; i < 100000; i++) {
h.Insert(i, i);
}
BENCHMARK("Hashmap")
{
i32 sum = 0;
for (i32 i = 100000; i < 150000; i++) {
sum += h.Contains(i) ? 1 : 0;
}
return sum;
};
std::unordered_map<i32, i32> um;
for (i32 i = 0; i < 100000; i++) {
um.insert(std::make_pair(i, i));
}
BENCHMARK("UnorderedMap")
{
i32 sum = 0;
for (i32 i = 100000; i < 150000; i++) {
sum += As<i32>(um.count(i));
}
return sum;
};
}
| true |
c86f506dd7cb1fcf7c45bba561c0971bf7b3368c | C++ | clroot/TIL | /ALGORITHM/자료구조/집합/14425.cpp | UTF-8 | 554 | 2.75 | 3 | [] | no_license | #include "iostream"
#include "string"
#include "unordered_set"
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
unordered_set<string> set;
int answer = 0;
cin >> n >> m;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
set.insert(s);
}
for (int i = 0; i < m; i++) {
string s;
cin >> s;
auto iter = set.find(s);
if (iter != set.end()) {
answer += 1;
}
}
cout << answer << endl;
return 0;
} | true |
a9aea1ebeba8f04af3e201a096a0a8f8fea833c7 | C++ | niuxu18/logTracker-old | /second/download/curl/gumtree/curl_repos_function_1611_curl-7.41.0.cpp | UTF-8 | 328 | 2.734375 | 3 | [] | no_license | static char *
create_hostcache_id(const char *name, int port)
{
/* create and return the new allocated entry */
char *id = aprintf("%s:%d", name, port);
char *ptr = id;
if(ptr) {
/* lower case the name part */
while(*ptr && (*ptr != ':')) {
*ptr = (char)TOLOWER(*ptr);
ptr++;
}
}
return id;
} | true |
03d974ca8ae535f761478fb3fb04be22ac169a85 | C++ | Jody-Lu/Array | /200_Number_of_Islands/numIslands.cpp | UTF-8 | 1,053 | 3.1875 | 3 | [] | no_license | #include <vector>
using namespace std;
class Solution {
public:
void removeIsland(vector<vector<char> >& grid, int y, int x) {
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int m = grid.size(), n = grid[0].size();
grid[y][x] = '0';
for(int i = 0; i < 4; i++) {
int nextX = x + dx[i];
int nextY = y + dy[i];
if(nextX >= 0 && nextX < n &&
nextY >= 0 && nextY < m &&
grid[nextY][nextX] == '1') {
removeIsland(grid, nextY, nextX);
}
}
}
int numIslands(vector<vector<char> >& grid) {
int res = 0;
for(int y = 0; y < grid.size(); y++) {
for(int x = 0; x < grid[0].size(); x++) {
if(grid[y][x] == '1') {
res++;
removeIsland(grid, y, x);
}
}
}
return res;
}
};
| true |
496755893ac1079438fc423bc9e244009d4fcd5c | C++ | MingNine9999/algorithm | /Problems/boj15593.cpp | UTF-8 | 1,383 | 2.984375 | 3 | [] | no_license | //Problem Number : 15593
//Problem Title : Lifeguards (Bronze)
//Problem Link : https://www.acmicpc.net/problem/15593
#include <iostream>
#include <algorithm>
using namespace std;
pair<int, int> t[100001];
int work[100001];
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> t[i].first >> t[i].second;
}
sort(t, t + n);
int latest = -1;
int minIndex = 0;
latest = t[0].second;
work[0] = t[0].second - t[0].first;
for (int i = 1; i < n; i++) {
if (t[i].second < latest) {
work[i] = 0;
minIndex = i;
continue;
}
if (t[i].first < latest) {
work[i - 1] -= latest - t[i].first;
work[i] = t[i].second - latest;
}
else {
work[i] = t[i].second - t[i].first;
}
if (latest < t[i].second) {
latest = t[i].second;
}
if (work[i] < 0) {
work[i] = 0;
}
if (work[i - 1] < 0) {
work[i - 1] = 0;
}
if (work[minIndex] > work[i]) {
minIndex = i;
}
if (work[minIndex] > work[i - 1]) {
minIndex = i - 1;
}
}
int ans = 0;
latest = -1;
for (int i = 0; i < n; i++) {
if (i == minIndex) {
continue;
}
if (t[i].first < latest) {
if (t[i].second > latest) {
ans += t[i].second - latest;
}
}
else {
ans += t[i].second - t[i].first;
}
if (latest < t[i].second) {
latest = t[i].second;
}
}
cout << ans;
return 0;
} | true |
4ed5b4e1dcce8ff68e62f707e1afc4006d3f9618 | C++ | guillaumemoreau/RaOcclusion | /ObjetEtTracking/cameraPos.h | ISO-8859-1 | 3,050 | 2.890625 | 3 | [] | no_license | #ifndef _CAMERAPOS_
#define _CAMERAPOS_
#include <opencv/cv.h>
#include <fstream>
using namespace cv;
//Aruco
#include "aruco\aruco.h"
void axis(float); /**< Afficher des axes dans le repre courant */
/**Lire les matrices "intrinsics" et "distorsion" depuis un fichier.
* <br /> Format du fichier :
* <br /> # comments
* <br /> fx fy cx cy k1 k2 p1 p2 width height 1
*
* @param TheIntrinsicFile : chemin du fichier contenant les infos sur les caractres intrinsques
* @param TheIntriscCameraMatrix matrices de sortie contenant les donnes intrinsques
* @param TheDistorsionCameraParams vecteur de sortie avec les paramtres de distorsion
* @param size taille des images filmes.
* Note : ces images peuvent tre diffrentes de celles utilises pour la calibration (qui sont dans le fichier de calibration).
* Si c'est le cas, les donnes intrinsques doivent tre adaptes correctement.
* C'est pourquoi il est ncessaire de passer ici la taille des images filmes.
* @return true si paramtres lus correctement
*/
bool readIntrinsicFile(string TheIntrinsicFile,Mat & TheIntriscCameraMatrix,Mat &TheDistorsionCameraParams,Size size)
{
// ouvre le fichier
ifstream InFile(TheIntrinsicFile.c_str());
if (!InFile) return false;
char line[1024];
InFile.getline(line,1024); // ne pas lire la premiere ligne (qui contient que des commentaires normalement)
InFile.getline(line,1024); // lire la ligne avec les infos pertinentes
// Transformation vers type stringstream
stringstream InLine;
InLine<<line;
// Crer les matrices
TheDistorsionCameraParams.create(4,1,CV_32FC1);
TheIntriscCameraMatrix=Mat::eye(3,3,CV_32FC1);
// Lire la matrice "intrinsic"
InLine>>TheIntriscCameraMatrix.at<float>(0,0);//fx
InLine>>TheIntriscCameraMatrix.at<float>(1,1); //fy
InLine>>TheIntriscCameraMatrix.at<float>(0,2); //cx
InLine>>TheIntriscCameraMatrix.at<float>(1,2);//cy
// Lire les paramtres de distorsion
for(int i=0;i<4;i++) InLine>>TheDistorsionCameraParams.at<float>(i,0);
// Lire la taille de la camra
float width,height;
InLine>>width>>height;
// Redimensionner les parametres de la camra pour correspondre la taille de l'image
float AxFactor= float(size.width)/ width;
float AyFactor= float(size.height)/ height;
TheIntriscCameraMatrix.at<float>(0,0)*=AxFactor;
TheIntriscCameraMatrix.at<float>(0,2)*=AxFactor;
TheIntriscCameraMatrix.at<float>(1,1)*=AyFactor;
TheIntriscCameraMatrix.at<float>(1,2)*=AyFactor;
// pour le debug
/*
cout<<"fx="<<TheIntriscCameraMatrix.at<float>(0,0)<<endl;
cout<<"fy="<<TheIntriscCameraMatrix.at<float>(1,1)<<endl;
cout<<"cx="<<TheIntriscCameraMatrix.at<float>(0,2)<<endl;
cout<<"cy="<<TheIntriscCameraMatrix.at<float>(1,2)<<endl;
cout<<"k1="<<TheDistorsionCameraParams.at<float>(0,0)<<endl;
cout<<"k2="<<TheDistorsionCameraParams.at<float>(1,0)<<endl;
cout<<"p1="<<TheDistorsionCameraParams.at<float>(2,0)<<endl;
cout<<"p2="<<TheDistorsionCameraParams.at<float>(3,0)<<endl;
*/
return true;
}
#endif
| true |
8e21bcd237d256ba5ef6ec2fc934d49473777b2f | C++ | MacBono/kasumi_a53 | /a53kasumi/kgcore.cpp | UTF-8 | 2,055 | 2.515625 | 3 | [] | no_license | #include "kasumi.h"
#include <stdio.h>
//co is output, cl is length, cc given, ck key build earlier, ca given, cb given, cd given
void KGcore(u8 ca, u8 cb, u32 cc, u8 cd, u8* ck, u8* co, int cl)
{
Struct1 A; // a 64-bit register that is used within the KGCORE function to hold an intermediate value.
Struct1 reg2; // this is our current register used in blocks
u8 inputkey[16], modifiedkey[16];
u16 blockcounter; // block counter which increments with every our "turn"
int i, n;
for (i = 0; i < 16; ++i)
{
inputkey[i] = ck[i]; //copying a key
}
reg2.b32[0] = reg2.b32[1] = 0; //current register
A.b32[0] = A.b32[1] = 0; //modifier register
// initialize modifier register and its values
// different size of inputs cc cb etc so different shifts
// ce at the end 15 bits all 0's
A.b8[0] = (u8)(cc >> 24);
A.b8[1] = (u8)(cc >> 16);
A.b8[2] = (u8)(cc >> 8);
A.b8[3] = (u8)(cc);
A.b8[4] = (u8)(cb << 3);
A.b8[4] |= (u8)(cd << 2);
A.b8[5] = (u8)ca;
for (n = 0; n < 16; ++n)
{
modifiedkey[n] = (u8)(ck[n] ^ 0x55); //Kasumi used to construct modified key
}
KeySchedule(modifiedkey); //this is 1st use of kasumi on block diagram
Kasumi(A.b8);
blockcounter = 0;
KeySchedule(inputkey); //now key schedule for other multiple blocks of kasumi
while (cl > 0)
{
reg2.b32[0] ^= A.b32[0];
reg2.b32[1] ^= A.b32[1];
reg2.b8[7] ^= blockcounter;
Kasumi(reg2.b8); //block production by kasumi
if (cl >= 64) // n should be equal to number of bytes of input data
{
n = 8; // it equals to 8 if cl=>64
}
else
{
n = (cl + 7) / 8; // if cl<64 then it goes 7,6,5,4 etc
}
for (i = 0; i < n; ++i)
{
*co++ = reg2.b8[i]; //assigning to output
}
cl -= 64; // bit counter
++blockcounter; //block diagram counter
}
} | true |
f9cb0bf470d7d2454473b28f091c41dadb1e9dc3 | C++ | msrishu65/codes | /codes/repeat/movezeroestoend.cpp | UTF-8 | 262 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a[]={1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0};
int c=0;
int i;
for(i=0;i<11;i++)
{
if(a[i]!=0)
{
a[c]=a[i] ;
c++;
}
}
for(int j=c;j<11;j++)
a[j]=0;
for(int i=0;i<11;i++)
cout<<a[i]<<" ";
}
| true |
a846d14ea7dcc861b27f27ff6ad89034ad8bda04 | C++ | Ares-Developers/YRpp | /FPSCounter.h | UTF-8 | 1,367 | 2.625 | 3 | [] | no_license | #pragma once
class FPSCounter
{
public:
//!< The number of frames processed in the last second.
static constexpr reference<unsigned int, 0xABCD44u> const CurrentFrameRate{};
//!< The total number of frames elapsed.
static constexpr reference<unsigned int, 0xABCD48u> const TotalFramesElapsed{};
//!< The time it took to process TotalFramesElapsed frames.
static constexpr reference<unsigned int, 0xABCD4Cu> const TotalTimeElapsed{};
//!< Whether the current fps is considered too low.
static constexpr reference<bool, 0xABCD50u> const ReducedEffects{};
//!< The average frame rate for all frames processed.
static inline double GetAverageFrameRate()
{
if(TotalTimeElapsed) {
return static_cast<double>(TotalFramesElapsed)
/ static_cast<double>(TotalTimeElapsed);
}
return 0.0;
}
};
class Detail {
public:
//!< What is considered the minimum acceptable FPS.
static constexpr reference<unsigned int, 0x829FF4u> const MinFrameRate{};
//!< The zone that needs to be left to change
static constexpr reference<unsigned int, 0x829FF8u> const BufferZoneWidth{};
//!< The minimum frame rate considering the buffer zone.
static inline unsigned int GetMinFrameRate()
{ JMP_STD(0x55AF60); }
//!< Whether effects should be reduced.
static inline bool ReduceEffects()
{
return FPSCounter::CurrentFrameRate < GetMinFrameRate();
}
};
| true |
4cd8ba364c4d5d38e5925e87184deab200dd7a05 | C++ | WRodewald/HPEQ | /source/hpeq/AFourierTransformFactory.h | UTF-8 | 1,150 | 3.125 | 3 | [] | no_license | #pragma once
#include "AFourierTransform.h"
#include <memory>
/**
Class implements a simple factory that can create a fourier transform engines
*/
class AFourierTransformFactory
{
public:
/**
Installs the factory as a singleton to be. The singleton will be used to create fourier transform enignes
via #FourierTransform
*/
static AFourierTransformFactory * installStaticFactory(AFourierTransformFactory * factory);
/**
Creates a fourier transform engine with given order @p order. The function forwards the call to #createFourierTransform
of the currently installed #AFourierTransformFactory singleton.
@param order the order
@return the created fourier transform engine. The caller takes ownership.
*/
static AFourierTransform * FourierTransform(unsigned int order);
protected:
/**
The virtual factory function creates a fourier transform engine.
@param order the order
@return the created fourier transform engine. The caller takes ownership.
*/
virtual AFourierTransform * createFourierTransform(unsigned int order) const = 0;
private:
static std::unique_ptr<const AFourierTransformFactory> factoryInstance;
};
| true |
ea504157b0269f449568a4818305685e23438eb3 | C++ | Sonaza/glen | /glen/src/Graphics/MeshLoader.cpp | UTF-8 | 4,100 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <glen/System/Types.hpp>
#include <glen/Graphics/MeshLoader.hpp>
#include <glen/System/ErrorStream.hpp>
namespace
{
//////////////////////////////////////////////////////////////
template <typename T>
T strto(const std::string& s)
{
std::stringstream ss(s);
T temp;
ss >> temp;
return temp;
}
}
namespace glen
{
namespace MeshLoader
{
////////////////////////////////////////////////
bool loadMesh(const std::string& path, MeshData *out)
{
std::ifstream file(path);
if(!file.is_open())
{
err << "Unable to open mesh file: " << path << ErrorStream::error;
return false;
}
std::vector<vec3f> vertices;
std::vector<vec3f> normals;
std::vector<vec3f> texCoords;
// Make sure data target is empty
out->data.clear();
int32 faceCount = 0;
int32 vertexDrawCount = 0;
std::string line;
while(std::getline(file, line))
{
std::stringstream data(line);
std::string id;
double d1, d2, d3;
data >> id;
// Parse data according to type
if(id == "v") // Vertex coordinates
{
data >> d1 >> d2 >> d3;
vertices.push_back(vec3f(
static_cast<float>(d1),
static_cast<float>(d2),
static_cast<float>(d3)
));
}
else if(id == "vt") // Texture coordinates
{
data >> d1 >> d2 >> d3;
texCoords.push_back(vec3f(
static_cast<float>(d1),
static_cast<float>(d2),
static_cast<float>(d3)
));
}
else if(id == "vn") // Vertex normals
{
data >> d1 >> d2 >> d3;
normals.push_back(vec3f(
static_cast<float>(d1),
static_cast<float>(d2),
static_cast<float>(d3)
));
}
else if(id == "f") // Faces
{
faceCount++;
std::vector<std::string> indices;
std::string item;
// Extract all face indices
while(data >> item)
indices.push_back(item);
// Check if face is unsupported
if(indices.size() > 4)
{
err << "OBJ Loader supports meshes with only triangles or quads." << ErrorStream::error;
return false;
}
// If face is a quad sort indices differently
if(indices.size() == 4)
{
std::vector<std::string> temp = indices;
indices.clear();
indices.push_back(temp[0]);
indices.push_back(temp[1]);
indices.push_back(temp[2]);
indices.push_back(temp[2]);
indices.push_back(temp[3]);
indices.push_back(temp[0]);
// Take one more face into account
faceCount++;
}
// Append to the vertex buffer data array according to the indices
for(std::vector<std::string>::iterator it = indices.begin();
it != indices.end(); ++it)
{
std::stringstream temp(*it);
std::string node;
int32 i = 0;
while(std::getline(temp, node, '/'))
{
int32 index = strto<int>(node) - 1;
if(i == 0) // Vertex Coordinate
{
out->data.push_back(vertices[index].x);
out->data.push_back(vertices[index].y);
out->data.push_back(vertices[index].z);
vertexDrawCount++;
}
else if(i == 1) // Texture Coordinate
{
if(!texCoords.empty())
{
out->data.push_back(texCoords[index].x);
out->data.push_back(texCoords[index].y);
out->data.push_back(texCoords[index].z);
}
else
{
out->data.push_back(0.f);
out->data.push_back(0.f);
out->data.push_back(0.f);
}
}
else if(i == 2) // Vertex Normal
{
out->data.push_back(normals[index].x);
out->data.push_back(normals[index].y);
out->data.push_back(normals[index].z);
}
i++;
}
// If if there wasn't enough face data pad it out
if(i < 3)
for(int j=0; j < i * 3; ++j) out->data.push_back(0.f);
}
}
}
//if(out->data.empty()) return false;
// Calculate amount of vertices to be drawn
out->drawCount = vertexDrawCount;
return true;
}
}
}
| true |
9ca8c17600bfb1ea2eff0a6dc26d57c3ada21571 | C++ | hesitationer/cuda-dnn-inference | /cuda/cudnn.hpp | UTF-8 | 18,196 | 2.765625 | 3 | [] | no_license | #ifndef CUDA_CUDNN_HPP
#define CUDA_CUDNN_HPP
#include "error.hpp"
#include "stream.hpp"
#include "utils/noncopyable.hpp"
#include <cudnn.h>
#include <sstream>
#include <string>
#include <cstddef>
#define CHECK_CUDNN(call) cuda::cudnn::detail::check_cudnn_status((call), __FILE__, __LINE__)
namespace cuda {
namespace cudnn {
/* what a mess; do something about these names TODO */
class exception : public cuda::exception {
public:
using cuda::exception::exception;
};
namespace detail {
inline void check_cudnn_status(cudnnStatus_t error, std::string filename, std::size_t lineno) {
if (error != CUDNN_STATUS_SUCCESS) {
std::ostringstream stream;
stream << "CUDNN Error: " << filename << ":" << lineno << '\n';
stream << cudnnGetErrorString(error) << '\n';
throw cuda::cudnn::exception(stream.str());
}
}
}
class handle : noncopyable {
public:
handle() { CHECK_CUDNN(cudnnCreate(&hndl)); }
handle(handle&&) = default;
handle(stream s) : strm(std::move(s)) {
CHECK_CUDNN(cudnnCreate(&hndl));
try {
CHECK_CUDNN(cudnnSetStream(hndl, strm.get()));
}
catch (...) {
CHECK_CUDNN(cudnnDestroy(hndl));
throw;
}
}
~handle() { if(hndl != nullptr) CHECK_CUDNN(cudnnDestroy(hndl)); }
handle& operator=(handle&& other) {
hndl = other.hndl;
other.hndl = nullptr;
return *this;
}
auto get() const noexcept { return hndl; }
private:
cudnnHandle_t hndl;
stream strm;
};
enum class data_format {
nchw,
nhwc
};
namespace detail {
/* get_data_type<T> returns the equivalent cudnn enumeration constant
** for example, get_data_type<T> returns CUDNN_DATA_FLOAT
*/
template <class> auto get_data_type()->decltype(CUDNN_DATA_FLOAT);
template <> inline auto get_data_type<float>()->decltype(CUDNN_DATA_FLOAT) { return CUDNN_DATA_FLOAT; }
template <> inline auto get_data_type<double>()->decltype(CUDNN_DATA_FLOAT) { return CUDNN_DATA_DOUBLE; }
/* get_data_format<T> returns the equivalent cudnn enumeration constant
** for example, get_data_type<data_format::nchw> returns CUDNN_TENSOR_NCHW
*/
template <data_format> auto get_data_format()->decltype(CUDNN_TENSOR_NCHW);
template <> inline auto get_data_format<data_format::nchw>()->decltype(CUDNN_TENSOR_NCHW) { return CUDNN_TENSOR_NCHW; }
template <> inline auto get_data_format<data_format::nhwc>()->decltype(CUDNN_TENSOR_NCHW) { return CUDNN_TENSOR_NHWC; }
}
/* RAII wrapper for cudnnTensorDescriptor_t */
template <class T, data_format format = data_format::nchw>
class tensor_descriptor : noncopyable {
public:
tensor_descriptor() noexcept : descriptor{ nullptr } { }
tensor_descriptor(tensor_descriptor&& other)
: descriptor{ other.descriptor } {
other.descriptor = nullptr;
}
tensor_descriptor(std::size_t N, std::size_t chans, std::size_t height, std::size_t width) {
CHECK_CUDNN(cudnnCreateTensorDescriptor(&descriptor));
try {
CHECK_CUDNN(cudnnSetTensor4dDescriptor(descriptor,
detail::get_data_format<format>(), detail::get_data_type<T>(),
static_cast<int>(N), static_cast<int>(chans),
static_cast<int>(height), static_cast<int>(width)));
} catch (...) {
CHECK_CUDNN(cudnnDestroyTensorDescriptor(descriptor));
throw;
}
}
~tensor_descriptor() { /* destructor throws */
if (descriptor != nullptr) {
CHECK_CUDNN(cudnnDestroyTensorDescriptor(descriptor));
}
}
tensor_descriptor& operator=(tensor_descriptor&& other) noexcept {
descriptor = other.descriptor;
other.descriptor = nullptr;
return *this;
};
auto get() const noexcept { return descriptor; }
private:
cudnnTensorDescriptor_t descriptor;
};
/* RAII wrapper for cudnnFilterDescriptor_t */
template <class T, data_format format = data_format::nchw>
class filter_descriptor : noncopyable {
public:
filter_descriptor() noexcept : descriptor{ nullptr } { }
filter_descriptor(filter_descriptor&& other)
: descriptor{ other.descriptor } {
other.descriptor = nullptr;
}
filter_descriptor(std::size_t output_chans, std::size_t input_chans, std::size_t height, std::size_t width) {
CHECK_CUDNN(cudnnCreateFilterDescriptor(&descriptor));
try {
CHECK_CUDNN(cudnnSetFilter4dDescriptor(descriptor,
detail::get_data_type<T>(), detail::get_data_format<format>(),
static_cast<int>(output_chans), static_cast<int>(input_chans),
static_cast<int>(height), static_cast<int>(width)));
} catch (...) {
CHECK_CUDNN(cudnnDestroyFilterDescriptor(descriptor));
throw;
}
}
~filter_descriptor() { /* destructor throws */
if (descriptor != nullptr) {
CHECK_CUDNN(cudnnDestroyFilterDescriptor(descriptor));
}
}
filter_descriptor& operator=(filter_descriptor&& other) noexcept {
descriptor = other.descriptor;
other.descriptor = nullptr;
return *this;
};
auto get() const noexcept { return descriptor; }
private:
cudnnFilterDescriptor_t descriptor;
};
/* RAII wrapper for cudnnConvolutionDescriptor_t */
template <class T>
class convolution_descriptor : noncopyable {
public:
convolution_descriptor() noexcept : descriptor{ nullptr } { }
convolution_descriptor(convolution_descriptor&& other)
: descriptor{ other.descriptor } {
other.descriptor = nullptr;
}
convolution_descriptor(std::size_t padding_y, std::size_t padding_x,
std::size_t stride_y, std::size_t stride_x,
std::size_t dilation_y, std::size_t dialation_x,
std::size_t groups) {
CHECK_CUDNN(cudnnCreateConvolutionDescriptor(&descriptor));
try {
CHECK_CUDNN(cudnnSetConvolution2dDescriptor(descriptor,
static_cast<int>(padding_y), static_cast<int>(padding_x),
static_cast<int>(stride_y), static_cast<int>(stride_x),
static_cast<int>(dilation_y), static_cast<int>(dialation_x),
CUDNN_CROSS_CORRELATION, detail::get_data_type<T>()));
CHECK_CUDNN(cudnnSetConvolutionGroupCount(descriptor, groups));
} catch (...) {
CHECK_CUDNN(cudnnDestroyConvolutionDescriptor(descriptor));
throw;
}
}
~convolution_descriptor() { /* destructor throws */
if (descriptor != nullptr) {
CHECK_CUDNN(cudnnDestroyConvolutionDescriptor(descriptor));
}
}
convolution_descriptor& operator=(convolution_descriptor&& other) noexcept {
descriptor = other.descriptor;
other.descriptor = nullptr;
return *this;
};
auto get() const noexcept { return descriptor; }
private:
cudnnConvolutionDescriptor_t descriptor;
};
template <class T>
class convolution_algorithm {
public:
convolution_algorithm() : workspace_size{ 0 } { }
convolution_algorithm(convolution_algorithm&) = default;
convolution_algorithm(convolution_algorithm&&) = default;
convolution_algorithm& operator=(convolution_algorithm&) = default;
convolution_algorithm& operator=(convolution_algorithm&&) = default;
template <data_format format = data_format::nchw>
convolution_algorithm(cudnn::handle& handle,
convolution_descriptor<T>& conv,
filter_descriptor<T, format>& filter,
tensor_descriptor<T, format>& input,
tensor_descriptor<T, format>& output) {
CHECK_CUDNN(cudnnGetConvolutionForwardAlgorithm(handle.get(),
input.get(), filter.get(), conv.get(), output.get(),
CUDNN_CONVOLUTION_FWD_PREFER_FASTEST,
0, &algo));
CHECK_CUDNN(cudnnGetConvolutionForwardWorkspaceSize(handle.get(),
input.get(), filter.get(), conv.get(), output.get(),
algo, &workspace_size));
}
auto get() const noexcept { return algo; }
auto get_workspace_size() const noexcept { return workspace_size; }
private:
cudnnConvolutionFwdAlgo_t algo;
std::size_t workspace_size;
};
enum class pooling_type {
max,
average_exclude_padding,
average_include_padding
};
namespace detail {
/* get_pooling_type<T> returns the equivalent cudnn enumeration constant */
auto get_pooling_type(pooling_type type) {
switch (type) {
case pooling_type::max:
return CUDNN_POOLING_MAX;
case pooling_type::average_exclude_padding:
return CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
case pooling_type::average_include_padding:
return CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING;
}
return CUDNN_POOLING_MAX; /* TODO how else do I handle? throw? */
}
}
/* RAII wrapper for cudnnPoolingDescriptor */
class pooling_descriptor : noncopyable {
public:
pooling_descriptor() noexcept : descriptor{ nullptr } { }
pooling_descriptor(pooling_descriptor&& other)
: descriptor{ other.descriptor } {
other.descriptor = nullptr;
}
pooling_descriptor(pooling_type type,
std::size_t window_height, std::size_t window_width,
std::size_t padding_y, std::size_t padding_x,
std::size_t stride_y, std::size_t stride_x) {
CHECK_CUDNN(cudnnCreatePoolingDescriptor(&descriptor));
try {
CHECK_CUDNN(cudnnSetPooling2dDescriptor(descriptor, detail::get_pooling_type(type), CUDNN_PROPAGATE_NAN,
static_cast<int>(window_height), static_cast<int>(window_width),
static_cast<int>(padding_y), static_cast<int>(padding_x),
static_cast<int>(stride_y), static_cast<int>(stride_x)));
} catch (...) {
CHECK_CUDNN(cudnnDestroyPoolingDescriptor(descriptor));
throw;
}
}
~pooling_descriptor() { /* destructor throws */
if (descriptor != nullptr) {
CHECK_CUDNN(cudnnDestroyPoolingDescriptor(descriptor));
}
}
pooling_descriptor& operator=(pooling_descriptor&& other) noexcept {
descriptor = other.descriptor;
other.descriptor = nullptr;
return *this;
};
auto get() const noexcept { return descriptor; }
private:
cudnnPoolingDescriptor_t descriptor;
};
template <class T, data_format format = data_format::nchw> inline
void get_convolution_output_dim(convolution_descriptor<T>& conv,
filter_descriptor<T, format>& filter,
tensor_descriptor<T, format>& input,
std::size_t& n, std::size_t& c, std::size_t& h, std::size_t& w) {
int in, ic, ih, iw;
CHECK_CUDNN(cudnnGetConvolution2dForwardOutputDim(conv.get(), input.get(), filter.get(), &in, &ic, &ih, &iw));
n = static_cast<std::size_t>(in);
c = static_cast<std::size_t>(ic);
h = static_cast<std::size_t>(ih);
w = static_cast<std::size_t>(iw);
}
template <class T, data_format format = data_format::nchw> inline
void get_pooling_output_dim(pooling_descriptor& pooling_desc,
tensor_descriptor<T, format>& input,
std::size_t& n, std::size_t& c, std::size_t& h, std::size_t& w) {
int in, ic, ih, iw;
CHECK_CUDNN(cudnnGetPooling2dForwardOutputDim(pooling_desc.get(), input.get(), &in, &ic, &ih, &iw));
n = static_cast<std::size_t>(in);
c = static_cast<std::size_t>(ic);
h = static_cast<std::size_t>(ih);
w = static_cast<std::size_t>(iw);
}
/* cuDNN requires alpha/beta to be in float for half precision
** hence, half precision is unsupported (due to laziness)
** (this is what std::enable_if is doing there)
*/
template <class T, data_format format = data_format::nchw, class U = unsigned char> inline
typename std::enable_if<std::is_same<T, float>::value || std::is_same<T, double>::value, void>
::type pool(cudnn::handle& handle,
pooling_descriptor& pooling_desc,
tensor_descriptor<T, format>& input_desc,
device_ptr<const T> input_data,
T alpha, T beta,
tensor_descriptor<T, format>& output_desc,
device_ptr<T> output_data) {
CHECK_CUDNN(cudnnPoolingForward(handle.get(), pooling_desc.get(), &alpha,
input_desc.get(), input_data.get(), &beta, output_desc.get(), output_data.get()));
}
/* cuDNN requires alpha/beta to be in float for half precision
** hence, half precision is unsupported (due to laziness)
** (this is what std::enable_if is doing there)
*/
template <class T, data_format format = data_format::nchw, class U = unsigned char> inline
typename std::enable_if<std::is_same<T, float>::value || std::is_same<T, double>::value, void>
::type convolve(cudnn::handle& handle,
filter_descriptor<T, format>& filter_desc,
device_ptr<const T> kernels,
convolution_descriptor<T>& conv_desc,
convolution_algorithm<T>& algo,
device_ptr<U> workspace,
tensor_descriptor<T, format>& input_desc,
device_ptr<const T> input_data,
T alpha,
T beta,
tensor_descriptor<T, format>& output_desc,
device_ptr<T> output_data) {
CHECK_CUDNN(cudnnConvolutionForward(handle.get(), &alpha, input_desc.get(), input_data.get(),
filter_desc.get(), kernels.get(), conv_desc.get(), algo.get(), workspace.get(),
algo.get_workspace_size(), &beta, output_desc.get(), output_data.get()));
}
/* cuDNN requires alpha/beta to be in float for half precision
** hence, half precision is unsupported (due to laziness)
** (this is what std::enable_if is doing there)
*/
template <class T, data_format format = data_format::nchw> inline
typename std::enable_if<std::is_same<T, float>::value || std::is_same<T, double>::value, void>
::type add_tensor(cudnn::handle& handle,
tensor_descriptor<T, format>& bias_desc, const device_ptr<const T> bias_data,
tensor_descriptor<T, format>& output_desc, const device_ptr<T> output_data) {
T alpha = 1.0, beta = 1.0;
CHECK_CUDNN(cudnnAddTensor(handle.get(), &alpha, bias_desc.get(), bias_data.get(), &beta, output_desc.get(), output_data.get()));
}
/* cuDNN requires alpha/beta to be in float for half precision
** hence, half precision is unsupported (due to laziness)
** (this is what std::enable_if is doing there)
*/
template <class T, data_format format = data_format::nchw> inline
typename std::enable_if<std::is_same<T, float>::value || std::is_same<T, double>::value, void>
::type softmax(cudnn::handle& handle,
tensor_descriptor<T, format>& input_desc, device_ptr<const T> input_data,
tensor_descriptor<T, format>& output_desc, device_ptr<T> output_data,
bool log = false) {
T alpha = 1.0, beta = 0.0;
cudnnSoftmaxAlgorithm_t algo = log ? CUDNN_SOFTMAX_LOG : CUDNN_SOFTMAX_ACCURATE;
CHECK_CUDNN(cudnnSoftmaxForward(handle.get(), algo, CUDNN_SOFTMAX_MODE_CHANNEL,
&alpha, input_desc.get(), input_data.get(), &beta, output_desc.get(), output_data.get()));
}
}
}
#endif /* CUDA_CUDNN_HPP */ | true |
69f3ab8dbb524723a45e7d3af29e7febf3feb411 | C++ | sdy1423/Algorithm | /[boj_18233]_러버덕을 사랑하는 모임.cpp | UTF-8 | 1,278 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#define f first
#define s second
using namespace std;
typedef pair<int, int> P;
int n, p, e, ans[21];
vector<P> MinMax;
bool isAnswer;
void FindAns(int bits) {
int Min = 0, Max = 0;
for (int i = 0; i < n; i++) {
if (bits & (1 << i)) {
Min += MinMax[i].f;
Max += MinMax[i].s;
}
}
if (Min <= e && Max >= e) {
isAnswer = true;
int tot = e;
for (int i = 0; i < n; i++) {
if (bits & (1 << i)) {
ans[i] = MinMax[i].f;
tot -= MinMax[i].f;
}
}
for (int i = 0; i < n && tot>0; i++) {
if (bits & (1 << i)) {
if (tot > MinMax[i].s - MinMax[i].f) {
tot -= MinMax[i].s - MinMax[i].f;
ans[i] = MinMax[i].s;
}
else {
ans[i] += tot;
tot = 0;
}
}
}
for (int i = 0; i < n; i++) {
cout << ans[i] << ' ';
}
cout << '\n';
}
else return;
}
void Find(int idx, int cnt, int bits) {
if (cnt == p && !isAnswer) {
FindAns(bits);
return;
}
if (idx == n)return;
Find(idx + 1, cnt, bits);
Find(idx + 1, cnt + 1, bits | (1 << idx));
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> p >> e;
MinMax.resize(n);
for (int i = 0; i < n; i++) cin >> MinMax[i].f >> MinMax[i].s;
Find(0, 0, 0);
if (!isAnswer)cout << -1 << '\n';
return 0;
} | true |
14205a13ee27b2bb57e635e1f186f9ee4a42c560 | C++ | kbuczek/computerScienceStudies | /Algorithms/Semeseter1/sort_selection.cpp | UTF-8 | 1,890 | 3.53125 | 4 | [] | no_license | #include<iostream>
#include <cstdlib>
#include<stdio.h>
#include <ctime>
#define N 100
using namespace std;
int liczbaOperacji = 0;
void sort_selection(int tab[])
{
for (int i = 0; i < N-1; i++)
{
int min = i;
for(int j=i+1; j<N; j++)
{
liczbaOperacji++;
if (tab[j] < tab[min])
{
min = j;
}
}
int temp = tab[min];
tab[min] = tab[i];
tab[i] = temp;
}
}
int main()
{
int tab1[N]; //losowa
int tab2[N]; //posortowana malejąco
int tab3[N]; //posortowana rosnąco
srand((int)time(0));
//wpisz dane do tabic
for(int i=0;i<N;i++)
{
//losowa od 0 do 1000
int r1 = rand() % 1000 + 1;
tab1[i] = r1;
//posortowana malejaco od 0 do 1000
int r2 = ((99-i)*10) + ( rand() % ( (1000-(i*10)) - ((99-i)*10) + 1 ) );
tab2[i] = r2;
//posortowana rosnaco od 0 do 1000
int r3 = ((99-i)*10) + ( rand() % ( (1000-(i*10)) - ((99-i)*10) + 1 ) );
tab3[N-i-1] = r3;
}
sort_selection(tab1);
cout<< "Tablica losowa: " << endl;
for(int i=0; i < N; i++)
{
cout << tab1[i] << " ";
}
cout << endl << "Liczba operacji: " << liczbaOperacji << endl << endl;
liczbaOperacji = 0;
sort_selection(tab2);
cout<< "Tablica posortowana malejaco: " << endl;
for(int i=0; i < N; i++)
{
cout << tab2[i] << " ";
}
cout << endl << "Liczba operacji: " << liczbaOperacji << endl << endl;
liczbaOperacji = 0;
sort_selection(tab3);
cout<< "Tablica posortowana rosnaco: " << endl;
for(int i=0; i < N; i++)
{
cout << tab3[i] << " ";
}
cout << endl << "Liczba operacji: " << liczbaOperacji << endl;
return 0;
}
| true |
0076975a0acf9150bbaf2f5167fcff47a79f7150 | C++ | EnTaroYan/leetcode-answer | /202. Happy Number .cpp | UTF-8 | 1,149 | 4.0625 | 4 | [] | no_license | /*Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer,
replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1*/
//Solution 1
class Solution {
public:
bool isHappy(int n)
{
vector<int> ss;
int sum=0;
while(n>1)
{
ss.push_back(n);
while(n)
{
sum+=pow(n%10,2);
n/=10;
}
if(find(ss.begin(),ss.end(),sum)!=ss.end())
return false;
n=sum;
sum=0;
}
return true;
}
};
//Solution 2
class Solution {
public:
bool isHappy(int n)
{
int sum=0;
while(n>1)
{
while(n)
{
sum+=pow(n%10,2);
n/=10;
}
if(sum==4)
return false;
n=sum;
sum=0;
}
return true;
}
}; | true |
2030243b29dbb852f78dc0de4af05cd5db4e17e0 | C++ | roboclub-tu/Line-Follower | /QTRA_PID/QTRA_PID_Test.ino | UTF-8 | 3,296 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <QTRSensors.h>
QTRSensors qtr;
const uint8_t SensorCount = 5;
uint16_t sensorValues[SensorCount];
//motors
int E1 = 10;
int M1 = 12;
int E2 = 11;
int M2 = 13;
// Motor speed when traveling straight
int M1Speed = 175;
int M2Speed = 175;
int maxSpeed = 255;
// Sensors sum used for stopping
int sumSensors = 0;
// Variables for PID calculation
float Kp = 0.07;
float Ki = 0.0008;
float Kd = 0.6;
int P;
int I;
int D;
int lastError = 0;
//Methods for setting speed of individual wheels
void setLeftMotor(int value){
analogWrite(E1,value);
}
void setRightMotor(int value){
analogWrite(E2, value);
}
void configureSensors() {
qtr.setTypeAnalog();
qtr.setSensorPins((const uint8_t[]) {
A0, A1, A2, A3, A4
}, SensorCount);
delay(500);
}
void calibrationMode() {
pinMode(LED_BUILTIN, OUTPUT);
// turn on Arduino's LED to indicate we are in calibration mode
digitalWrite(LED_BUILTIN, HIGH);
// Call calibrate() 400 times to make calibration take about 10 seconds.
for (uint16_t i = 0; i < 400; i++) {
qtr.calibrate();
}
// turn off Arduino's LED to indicate we are through with calibration
digitalWrite(LED_BUILTIN, LOW);
}
void printCalibrationValues() {
// print the calibration minimum values measured when emitters were on
Serial.begin(9600);
for (uint8_t i = 0; i < SensorCount; i++) {
Serial.print(qtr.calibrationOn.minimum[i]);
Serial.print(' ');
}
Serial.println();
// print the calibration maximum values measured when emitters were on
for (uint8_t i = 0; i < SensorCount; i++) {
Serial.print(qtr.calibrationOn.maximum[i]);
Serial.print(' ');
}
Serial.println();
delay(1000);
}
//This is the algorithm used for calculation
// Refer here : https://create.arduino.cc/projecthub/anova9347/line-follower-robot-with-pid-controller-cdedbd
void PID_control() {
uint16_t position = qtr.readLineBlack(sensorValues);
int error = 2000 - position;
P = error;
I = I + error;
D = error - lastError;
lastError = error;
int motorspeed = P*Kp + I*Ki + D*Kd;
int motorspeeda = (M1Speed + motorspeed);
int motorspeedb = (M2Speed - motorspeed);
if (motorspeeda > maxSpeed) {
motorspeeda = maxSpeed;
}
if (motorspeedb > maxSpeed) {
motorspeedb = maxSpeed;
}
if (motorspeeda < 0) {
motorspeeda = 0;
}
if (motorspeedb < 0) {
motorspeedb = 0;
}
Serial.print("M1 Speed: ");
Serial.print(motorspeeda);
Serial.print(" M2 Speed:");
Serial.print(motorspeedb);
setLeftMotor(motorspeeda);
setRightMotor(motorspeedb);
}
void setup() {
// configure the sensors
configureSensors();
//begin calibration
calibrationMode();
//output values to terminal
printCalibrationValues();
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
}
void loop() {
uint16_t position = qtr.readLineBlack(sensorValues);
PID_control();
// print the sensor values where values are in range 0 - 1000
sumSensors = 0;
for (uint8_t i = 0; i < SensorCount; i++) {
sumSensors += sensorValues[i];
Serial.print(sensorValues[i]);
Serial.print('\t');
}
if(sumSensors < 50) {
setLeftMotor(0);
setRightMotor(0);
}
Serial.print(" SumSensors: ");
Serial.print(sumSensors);
Serial.print(" Position: ");
Serial.println(position);
}
| true |
5d36a60d247efef6731758f6759a83b930e22727 | C++ | drewnoakes/lwsxx | /include/lwsxx/http.hh | UTF-8 | 2,942 | 2.875 | 3 | [] | no_license | #pragma once
#include <functional>
#include <memory>
#include <regex>
#include <stdexcept>
#include <string>
#include <vector>
#include "websocketbuffer.hh"
class libwebsocket_context;
class libwebsocket;
namespace lwsxx
{
enum class HttpMethod
{
GET,
POST
};
enum class HttpStatus : short
{
Unknown = -1,
Success = 200,
BadRequest = 400,
Forbidden = 403,
NotFound = 404,
InternalError = 500
};
class http_exception : public std::exception
{
public:
http_exception(HttpStatus status, std::string what)
: _status(status),
_what(what)
{}
HttpStatus httpStatus() const noexcept { return _status; }
const char* what() const noexcept override { return _what.c_str(); }
private:
HttpStatus _status;
std::string _what;
};
class not_found_exception : public http_exception
{
public:
not_found_exception(std::string what)
: http_exception(HttpStatus::NotFound, what)
{}
};
class bad_request_exception : public http_exception
{
public:
bad_request_exception(std::string what)
: http_exception(HttpStatus::BadRequest, what)
{}
};
class HttpRequest
{
public:
HttpRequest(
libwebsocket_context* context,
libwebsocket* wsi,
size_t contentLength,
std::string url,
std::string queryString,
HttpMethod method,
std::function<void(std::shared_ptr<HttpRequest>)>& callback);
std::string url() const { return _url; }
std::string queryString() const { return _queryString; }
size_t contentLength() const { return _contentLength; }
HttpMethod method() const { return _method; }
std::vector<byte>& bodyData() { return _bodyData; }
void respond(HttpStatus responseCode, std::string contentType, WebSocketBuffer responseBody);
private:
friend class WebSockets;
/// Indicates that the request has been aborted and writing of a response must not occur
void abort() { _isAborted = true; }
void invokeCallback(std::shared_ptr<HttpRequest> request);
void appendBodyChunk(byte* data, size_t len);
libwebsocket_context* _context;
libwebsocket* _wsi;
size_t _contentLength;
std::string _url;
std::string _queryString;
HttpMethod _method;
std::function<void(std::shared_ptr<HttpRequest>)>& _callback;
std::vector<byte> _bodyData;
size_t _bodyDataPos;
bool _headersSent;
std::vector<byte> _responseBody;
size_t _responseBodyPos;
HttpStatus _responseCode;
std::string _responseContentType;
bool _isAborted;
};
struct HttpRouteDetails
{
HttpRouteDetails(HttpMethod method, std::regex urlPattern, std::function<void(std::shared_ptr<HttpRequest>)> callback)
: method(method), urlPattern(urlPattern), callback(callback)
{}
HttpMethod method;
std::regex urlPattern;
std::function<void(std::shared_ptr<HttpRequest>)> callback;
};
}
| true |
f8eee3006c50d7d414869bcfae2e2fa46115966c | C++ | hal-oconnell/prog2100 | /C++ Lessons/Week 10 - Polymorphism/FailBitExample/Source.cpp | UTF-8 | 1,093 | 3.03125 | 3 | [] | no_license | #include <fstream>
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
double num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
fin.open("numbers.txt");
if (fin.fail())
{
cout << "Input file opening failed." << endl;
exit(1);
}
fout.open("output.txt");
if (fout.fail())
{
cout << "Output file opening failed" << endl;
exit(1);
}
fin >> num1 >> num2 >> num3 >> num4 >> num5 >> num6 >> num7 >> num8 >> num9 >> num10;
fout << num1 << " " << num2 << " " << num3 << " " << num4 << " "
<< num5 << " " << num6 << " " << num7 << " " << num8 << " "
<< num9 << " " << endl;
while (!fin.eof())
{
fin >> num10;
fout << num10 << " ";
fin >> num1 >> num2 >> num3 >> num4 >> num5 >> num6 >> num7
>> num8 >> num9 >> num10;
fout << num1 << " " << num2 << " " << num3 << " " << num4 << " "
<< num5 << " " << num6 << " " << num7 << " " << num8 << " "
<< num9 << " " << endl;
}
fin.close();
fout.close();
_getch();
return 0;
}//end main | true |
74fdef8ea3d6ae78f50be1b20889d57716056df3 | C++ | manhhung20020246/Tuan07 | /A3.7.cpp | UTF-8 | 367 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <array>
using namespace std;
void even(int* arr, int length) {
for (int i = 0; i < length; i++)
{
if (arr[i] % 2 == 0){
cout << arr[i] << " ";
}
}
}
int main()
{
int arr[5];
int length = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < length; i++)
{
cin >> arr[i];
}
even(arr, length);
system("pause");
return 0;
}
| true |
21f7d03c3ce21915ddacb09f56554af146a6b711 | C++ | WheretIB/nullc | /NULLC/translation/std_file_bind.cpp | UTF-8 | 6,877 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "runtime.h"
#include <stdio.h>
#include <string.h>
#if defined(_WIN32)
#pragma warning(disable:4996)
#endif
// Array classes
#pragma pack(push, 4)
struct File
{
int flag;
void* id;
};
struct Seek
{
Seek(): value(0){}
Seek(int v): value(v){}
int value;
};
#pragma pack(pop)
File File_File_ref__(void* unused)
{
File ret;
ret.flag = 0;
ret.id = NULL;
return ret;
}
#define FILE_OPENED 1
File File_File_ref_char___char___(NULLCArray< char > name, NULLCArray< char > access, void* __context)
{
File ret;
ret.flag = FILE_OPENED;
ret.id = fopen(name.ptr, access.ptr);
if(!ret.id)
nullcThrowError("Cannot open file.");
return ret;
}
void File__Open_void_ref_char___char___(NULLCArray< char > name, NULLCArray< char > access, File* __context)
{
if(__context->flag & FILE_OPENED)
fclose((FILE*)__context->id);
__context->flag = FILE_OPENED;
__context->id = fopen(name.ptr, access.ptr);
if(!__context->id)
nullcThrowError("Cannot open file.");
}
void File__Close_void_ref__(File* __context)
{
fclose((FILE*)__context->id);
__context->flag = 0;
__context->id = NULL;
}
bool File__Opened_bool_ref__(File* __context)
{
return !!(__context->flag & FILE_OPENED);
}
bool File__Eof_bool_ref__(File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
return !__context->id || feof((FILE*)__context->id);
}
void File__Seek_void_ref_Seek_int_(Seek origin, int shift, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return;
}
if(!__context->id)
{
nullcThrowError("Cannot seek in a closed file.");
return;
}
fseek((FILE*)__context->id, shift, origin.value);
}
long long File__Tell_long_ref__(File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
if(!__context->id)
{
nullcThrowError("Cannot tell cursor position in a closed file.");
return 0;
}
return ftell((FILE*)__context->id);
}
long long File__Size_long_ref__(File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
if(!__context->id)
{
nullcThrowError("Cannot get size of a closed file.");
return 0;
}
long pos = ftell((FILE*)__context->id);
fseek((FILE*)__context->id, 0, SEEK_END);
long res = ftell((FILE*)__context->id);
fseek((FILE*)__context->id, pos, SEEK_SET);
return res;
}
template<typename T>
bool FileWriteType(T data, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return false;
}
if(!__context->id)
{
nullcThrowError("Cannot write to a closed file.");
return false;
}
return 1 == fwrite(&data, sizeof(T), 1, (FILE*)__context->id);
}
bool File__Write_bool_ref_char_(char data, File* __context)
{
return FileWriteType<char>(data, __context);
}
bool File__Write_bool_ref_short_(short data, File* __context)
{
return FileWriteType<short>(data, __context);
}
bool File__Write_bool_ref_int_(int data, File* __context)
{
return FileWriteType<int>(data, __context);
}
bool File__Write_bool_ref_long_(long long data, File* __context)
{
return FileWriteType<long long>(data, __context);
}
bool File__Write_bool_ref_float_(float data, File* __context)
{
return FileWriteType<float>(data, __context);
}
bool File__Write_bool_ref_double_(double data, File* __context)
{
return FileWriteType<double>(data, __context);
}
template<typename T>
bool FileReadType(T* data, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return false;
}
if(!__context->id)
{
nullcThrowError("Cannot read from a closed file.");
return false;
}
return 1 == fread(data, sizeof(T), 1, (FILE*)__context->id);
}
bool File__Read_bool_ref_char_ref_(char* data, File* __context)
{
return FileReadType<char>(data, __context);
}
bool File__Read_bool_ref_short_ref_(short* data, File* __context)
{
return FileReadType<short>(data, __context);
}
bool File__Read_bool_ref_int_ref_(int* data, File* __context)
{
return FileReadType<int>(data, __context);
}
bool File__Read_bool_ref_long_ref_(long long* data, File* __context)
{
return FileReadType<long long>(data, __context);
}
bool File__Read_bool_ref_float_ref_(float* data, File* __context)
{
return FileReadType<float>(data, __context);
}
bool File__Read_bool_ref_double_ref_(double* data, File* __context)
{
return FileReadType<double>(data, __context);
}
int File__Read_int_ref_char___(NULLCArray< char > arr, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
if(!__context->id)
{
nullcThrowError("Cannot read from a closed file.");
return 0;
}
return arr.ptr ? (int)fread(arr.ptr, 1, arr.size, (FILE*)__context->id) : 0;
}
int File__Write_int_ref_char___(NULLCArray< char > arr, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
if(!__context->id)
{
nullcThrowError("Cannot write to a closed file.");
return 0;
}
return arr.ptr ? int(fwrite(arr.ptr, 1, arr.size, (FILE*)__context->id)) : 0;
}
bool File__Print_bool_ref_char___(NULLCArray< char > arr, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return false;
}
if(!__context->id)
{
nullcThrowError("Cannot write to a closed file.");
return false;
}
unsigned length = 0;
for(; length < arr.size; length++)
{
if(!arr.ptr[length])
break;
}
return arr.ptr ? length == fwrite(arr.ptr, 1, length, (FILE*)__context->id) : 0;
}
int File__Read_int_ref_char___int_int_(NULLCArray< char > arr, int offset, int bytes, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
if(!__context->id)
{
nullcThrowError("Cannot read from a closed file.");
return 0;
}
if((long long)bytes + offset > arr.size)
{
nullcThrowError("Array can't hold %d bytes from the specified offset.", bytes);
return 0;
}
return arr.ptr ? int(fread(arr.ptr + offset, 1, bytes, (FILE*)__context->id)) : 0;
}
int File__Write_int_ref_char___int_int_(NULLCArray< char > arr, int offset, int bytes, File* __context)
{
if(!__context)
{
nullcThrowError("ERROR: null pointer access");
return 0;
}
if(!__context->id)
{
nullcThrowError("Cannot write to a closed file.");
return 0;
}
if((long long)bytes + offset > arr.size)
{
nullcThrowError("Array doesn't contain %d bytes from the specified offset.", bytes);
return 0;
}
return arr.ptr ? int(fwrite(arr.ptr + offset, 1, bytes, (FILE*)__context->id)) : 0;
}
| true |
5765ebcb8ec5c3465942f7733c0a82c796be800c | C++ | AABNassim/DPPML-Worker-Source | /PPML/Worker.cpp | UTF-8 | 3,243 | 3.03125 | 3 | [] | no_license | //
// Created by root on 30/06/19.
//
#include "Worker.h"
Worker::Worker() {
}
void Worker::connect_to_mlsp() {
if ((mlsp_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return;
}
mlsp_addr.sin_family = AF_INET;
mlsp_addr.sin_port = htons(mlsp_port);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, mlsp_ip, &mlsp_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return;
}
if (connect(mlsp_sock, (struct sockaddr *)&mlsp_addr, sizeof(mlsp_addr)) < 0)
{
printf("\nConnection Failed \n");
return;
}
send_long(mlsp_sock, 22);
}
void Worker::send_message() {
send(mlsp_sock , hello, strlen(hello) , 0 );
printf("Hello message sent\n");
int valread = read(mlsp_sock , buffer, 1024);
printf("%s\n", buffer);
}
bool Worker::send_data(int sock, void *buf, int buflen)
{
unsigned char *pbuf = (unsigned char *) buf;
while (buflen > 0)
{
int num = send(sock, pbuf, buflen, 0);
pbuf += num;
buflen -= num;
}
return true;
}
bool Worker::send_long(int sock, long value)
{
value = htonl(value);
return send_data(sock, &value, sizeof(value));
}
bool Worker::send_file(int sock, char* path)
{
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
long filesize = ftell(f);
rewind(f);
if (filesize == EOF)
return false;
if (!send_long(sock, filesize))
return false;
if (filesize > 0)
{
char buffer[1024];
do
{
size_t num = (filesize < sizeof(buffer)) ? filesize : sizeof(buffer);
num = fread(buffer, 1, num, f);
if (num < 1)
return false;
if (!send_data(sock, buffer, num))
return false;
filesize -= num;
}
while (filesize > 0);
}
return true;
}
bool Worker::read_data(int sock, void *buf, int buflen)
{
unsigned char *pbuf = (unsigned char *) buf;
while (buflen > 0)
{
int num = recv(sock, pbuf, buflen, 0);
if (num == 0)
return false;
pbuf += num;
buflen -= num;
}
return true;
}
bool Worker::read_long(int sock, long *value)
{
if (!read_data(sock, value, sizeof(value)))
return false;
*value = ntohl(*value);
return true;
}
bool Worker::read_file(int sock, char* path)
{
FILE *f = fopen(path, "wb");
long filesize;
if (!read_long(sock, &filesize))
return false;
if (filesize > 0)
{
char buffer[1024];
do
{
int num = (filesize < sizeof(buffer)) ? filesize : sizeof(buffer);
if (!read_data(sock, buffer, num))
return false;
int offset = 0;
do
{
size_t written = fwrite(&buffer[offset], 1, num-offset, f);
if (written < 1)
return false;
offset += written;
}
while (offset < num);
filesize -= num;
}
while (filesize > 0);
}
return true;
}
| true |
87c54ba1d247edcb10b8057b1ff0c7dab44cf836 | C++ | LLZK/Linux_study | /chat/chat_system/data_pool/data_pool.h | UTF-8 | 682 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<semaphore.h>
using namespace std;
class data_pool
{
public:
data_pool(int _cap,int _size)
:cap(_cap)
,size(_size)
,index1(0)
,index2(0)
{
sem_init(&blank,0,cap);
sem_init(%data,0,0);
}
void getdata(string& instr)
{
sem_wait(blank);
size++;
pool[index1] = instr;
index1++;
index1 %= cap;
sem_post(data);
}
void putdata(const string& outstr)
{
sem_wait(data);
size--;
outstr = pool[index2];
index2++;
index2 %= cap;
sem_post(blank);
}
~data_pool()
{
sem_destroy(&blank);
sem_destroy(&data);
}
private:
sem_t blank;
sem_t data;
int cap;
int size;
int index1;
int index2;
vector<string> pool;
}
| true |
74ab3ccd82977fb41811868f4c157e6da29318e2 | C++ | ProkopHapala/cpp_arch | /ShipSimulator/triangleRayCast/include/TrinagleMesh.h | UTF-8 | 1,845 | 2.65625 | 3 | [] | no_license |
class TrinagleMesh{
public:
int nvert;
int ntri;
Vec3d * verts;
Vec3d * normals;
double * areas;
int * tris;
int viewlist=0;
TrinagleMesh( int nvert_, int ntri_ ){
nvert = nvert_;
ntri = ntri_;
verts = new Vec3d [ nvert ];
tris = new int [ 3 * ntri ];
normals = new Vec3d [ 3 * ntri ];
areas = new double[ 3 * ntri ];
}
void evalNormals(){
int it = 0;
for( int i=0; i<ntri; i++){
Vec3d a,b,c,ab,ac,normal;
a.set( verts[ tris[ it ] ] ); it++;
b.set( verts[ tris[ it ] ] ); it++;
c.set( verts[ tris[ it ] ] ); it++;
ab.set_sub( b, a );
ac.set_sub( c, a );
normal.set_cross( ab, ac );
double area = normal.norm();
areas[i] = area;
normal.mul( 1/area );
normals[i] = normal;
}
}
void make_render( ){
if( viewlist > 0 ) { glDeleteLists( viewlist, 1 ); }
viewlist = glGenLists(1);
glNewList( viewlist , GL_COMPILE );
glShadeModel ( GL_FLAT );
glBegin( GL_TRIANGLES );
int it = 0;
for( int i=0; i<ntri; i++){
Vec3f tmp;
convert( normals[ i ], tmp ); glNormal3f( tmp.x, tmp.y, tmp.z );
convert( verts[ tris[ it ] ], tmp ); it++; glVertex3f( tmp.x, tmp.y, tmp.z );
convert( verts[ tris[ it ] ], tmp ); it++; glVertex3f( tmp.x, tmp.y, tmp.z );
convert( verts[ tris[ it ] ], tmp ); it++; glVertex3f( tmp.x, tmp.y, tmp.z );
}
glEnd( );
glEndList();
}
double ray( const Vec3d &ray0, const Vec3d &hRay, Vec3d& p ){
double tmin = 1e+300;
int it = 0;
for( int i=0; i<ntri; i++){
Vec3d a,b,c,pt;
a.set( verts[ tris[ it ] ] ); it++;
b.set( verts[ tris[ it ] ] ); it++;
c.set( verts[ tris[ it ] ] ); it++;
bool inside;
double t = rayTriangle( ray0, hRay, a,b,c, inside, pt );
if( inside & ( t>0 ) & ( t<tmin ) ){
tmin = t;
p.set( pt );
}
}
}
};
| true |
478bc70d49618cc5c291415cca39dd68c98ce57b | C++ | mirsking/mirsking_leetcode | /medium230_kth_smallest_element_in_BST/main.cpp | UTF-8 | 809 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
vector<int> res;
midTravesal(root, res);
return res[k-1];
}
private:
void midTravesal(TreeNode* root, vector<int>& res)
{
if(!root)
return;
midTravesal(root->left, res);
res.push_back(root->val);
midTravesal(root->right, res);
}
};
int main()
{
TreeNode a(2), b(1), c(3), d(4);
a.left = &b;
a.right = &c;
c.right = &d;
Solution sol;
cout << sol.kthSmallest(&a, 4) << endl;
return 0;
}
| true |
f429bb9e61c1333bc1337965f350789a44729f72 | C++ | SpinHit/Tetris-Plateau | /generation.cpp | UTF-8 | 1,813 | 2.96875 | 3 | [] | no_license | #include "include.h"
void genererTriangle(int tableau[TRIANGLE][A]){
for(int i=0; i<TRIANGLE; i++){
for(int j=0;j<A;j++){
if(j >= MILIEUTRIANGLE - i && j <= MILIEUTRIANGLE + i){
tableau[i][j] = C;
} else {
tableau[i][j] = 3;
}
}
}
}
void genererLosange(int tableau[A][A]){
for(int i=0; i<TRIANGLE; i++){
for(int j=0;j<A;j++){
if(j >= MILIEUTRIANGLE - i && j <= MILIEUTRIANGLE + i){
tableau[i][j] = C;
} else {
tableau[i][j] = 3;
}
}
}
for(int i=TRIANGLE,v=TRIANGLE; i<A; i++,v--){
for(int j=0;j<A;j++){
if(j >= MILIEUTRIANGLE - v && j <= MILIEUTRIANGLE + v){
tableau[i][j] = C;
} else {
tableau[i][j] = 3;
}
}
}
}
void genererCercle(int tableau[A][A]){
for(int i=0; i<TRIANGLE; i++){
for(int j=0;j<A;j++){
if(i == 0 || i == 1 || i == 2 || i == 17 || i == 18 || i == 19){
if( j >= MILIEUTRIANGLE - (6+i) && j <= MILIEUTRIANGLE + (6+i)){
tableau[i][j] = C;
} else {
tableau[i][j] = 3;
}
} else {
tableau[i][j] = C;
}
}
}
for(int i=TRIANGLE,v=TRIANGLE; i<A; i++,v--){
for(int j=0;j<A;j++){
if(i == 0 || i == 1 || i == 2 || i == 16 || i == 17 || i == 18){
if( j >= MILIEUTRIANGLE - (6+v) && j <= MILIEUTRIANGLE + (6+v)){
tableau[i][j] = C;
} else {
tableau[i][j] = 3;
}
} else {
tableau[i][j] = C;
}
}
}
}
| true |
447dad492ed0abc83e56784d894ebed8139e754c | C++ | ducaale/spaceship | /src/player.h | UTF-8 | 8,483 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef PLAYER_H
#define PLAYER_H
#include <fstream>
#include "game.h"
#include "components.h"
#include "json.hpp"
using json = nlohmann::json;
struct CThruster : Component {
Game* game = nullptr;
CAnimatedSprite* cSprite = nullptr;
CHealth* cHealth = nullptr;
bool boosterOn = false;
CThruster(Game* game) : game(game) {}
void init() override {
cSprite = &entity->getComponent<CAnimatedSprite>();
cHealth = &game->manager.getByGroup(Groups::player)->getComponent<CHealth>();
}
void update(float elapsedTime) override {
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || boosterOn) {
entity->addGroup(Groups::drawable);
if(boosterOn) {
cSprite->setScale(0.35f, 0.45f);
}
else {
cSprite->setScale(0.15f, 0.25f);
}
}
else {
entity->delGroup(Groups::drawable);
}
if(!cHealth->isAlive()) entity->delGroup(Groups::drawable);
}
};
struct CPlayerBoost : Component {
Game *game = nullptr;
CPhysics *cPhysics = nullptr;
float normal_acceleration;
float normal_max_speed;
bool boosterOn = false;
float boostDuration = 1.f;
float boostRecharge = 3.f;
float lastBoost = boostRecharge;
CPlayerBoost(Game *game) : game(game) {}
void init() override {
cPhysics = &entity->getComponent<CPhysics>();
normal_acceleration = cPhysics->acceleration;
normal_max_speed = cPhysics->maxSpeed;
}
void update(float elapsedTime) {
lastBoost += elapsedTime;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) {
if(lastBoost > boostRecharge) {
lastBoost = 0;
boosterOn = true;
}
}
if(lastBoost > boostDuration) {
boosterOn = false;
}
if(boosterOn) {
game->manager.getByGroup(Groups::thruster)->getComponent<CThruster>().boosterOn = true;
cPhysics->acceleration = 400.f;
cPhysics->maxSpeed = 400.f;
}
else {
game->manager.getByGroup(Groups::thruster)->getComponent<CThruster>().boosterOn = false;
cPhysics->acceleration = normal_acceleration;
cPhysics->maxSpeed = normal_max_speed;
}
}
};
struct CPlayerMovement : Component {
CTransform *cTransform = nullptr;
CPhysics *cPhysics = nullptr;
CSprite *cSprite = nullptr;
CGun *cGun = nullptr;
CHealth *cHealth = nullptr;
CPlayerBoost *cPlayerBoost = nullptr;
float turn_speed = 0;
CPlayerMovement(float turn_speed) : turn_speed(turn_speed) {}
void init() override {
cTransform = &entity->getComponent<CTransform>();
cPhysics = &entity->getComponent<CPhysics>();
cSprite = &entity->getComponent<CSprite>();
cGun = &entity->getComponent<CGun>();
cHealth = &entity->getComponent<CHealth>();
cPlayerBoost = &entity->getComponent<CPlayerBoost>();
}
void changeView() {
float angle = cSprite->sprite.getRotation();
if(angle < 45 || angle > 315) {
cSprite->changeFrame("left");
}
else if(angle > 135 && angle < 225) {
cSprite->changeFrame("right");
}
else {
cSprite->changeFrame("up_or_down");
}
}
void update(float elapsedTime) override {
if(cHealth->isAlive()) {
if(sf::Keyboard::isKeyPressed(sf::Keyboard::X)) {
fire();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
cTransform->angle -= (turn_speed * elapsedTime );
changeView();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
cTransform->angle += (turn_speed * elapsedTime );
changeView();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || cPlayerBoost->boosterOn) {
cPhysics->accelerate(elapsedTime);
}
}
cPhysics->deccelerate(elapsedTime);
}
void fire() {
sf::Transform t = cSprite->getTransform(false, true);
sf::Vector2f gunPos(0.f, 0.f);
gunPos.y += (cGun->projShot % 2 ? +5 : -5);
gunPos.x -= 150.f;
sf::Vector2f globalPosition = t.transformPoint(gunPos);
float globalAngle = atan2(t.getMatrix()[1], t.getMatrix()[0]) * 180 / PI;
cGun->fire(globalPosition, globalAngle);
}
};
struct CHUD : Component {
Game *game = nullptr;
CHealth *cHealth = nullptr;
sf::Text text;
sf::Sprite healthBar;
sf::Sprite healthBarBackground;
CHUD(Game *game) : game(game) {
text.setFont(game->font);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);
text.setPosition(45, 18);
healthBar = sf::Sprite(game->resource["bar"], {0,112,128,16});
healthBar.setPosition(85, 27);
healthBarBackground = sf::Sprite(game->resource["bar"], {0,0,128,16});
healthBarBackground.setPosition(85, 27);
}
void init() override {
cHealth = &entity->getComponent<CHealth>();
}
void update(float elapsedTime) override {
text.setString(std::to_string(cHealth->health));
healthBar.setScale(cHealth->getHealthPercentage(), 1);
}
void draw() override {
game->renderHUD(text);
game->renderHUD(healthBarBackground);
game->renderHUD(healthBar);
}
};
void createThruster(Game *game, Entity& parent) {
auto& entity = game->manager.addEntity();
entity.addComponent<CTransform>(sf::Vector2f(30.f, 0.f));
entity.addComponent<CParent>(&parent);
float width = 160.f;
float height = 70.f;
float scaleX = 0.15f;
float scaleY = 0.25f;
entity.addComponent<CAnimatedSprite>(game, AnimatedSprite(sf::seconds(0.09)), width/2, height/2);
Animation thrusterAnimation;
thrusterAnimation.setSpriteSheet(game->resource["player"]);
thrusterAnimation.addFrame({320,70,160,70});
thrusterAnimation.addFrame({160,70,160,70});
auto& cSprite = entity.getComponent<CAnimatedSprite>();
cSprite.setScale(scaleX, scaleY);
cSprite.setOrigin(0, height/2);
cSprite.animations["thrusterAnimation"] = thrusterAnimation;
cSprite.setAnimation("thrusterAnimation");
entity.addComponent<CThruster>(game);
entity.addGroup(Groups::thruster);
}
void createPlayer(Game *game) {
//load values from json file
std::ifstream file("values.json");
json values;
file >> values;
sf::Vector2f position = {values["player"]["initial_position"]["x"], values["player"]["initial_position"]["y"]};
float angle = values["player"]["initial_angle"];
float max_speed = values["player"]["max_speed"];
float acceleration = values["player"]["acceleration"];
float turn_speed = values["player"]["turn_speed"];
float gun_speed = values["player"]["gun"]["speed"];
float bullets_per_second = values["player"]["gun"]["bullets_per_second"];
auto& entity = game->manager.addEntity();
entity.addComponent<CTransform>(position, angle);
entity.addComponent<CHealth>(game, 20, 2);
entity.addComponent<CSprite>(game, sf::Sprite(game->resource["player"], {0,0,160,70}));
entity.addComponent<CPhysics>(max_speed, 0.f, acceleration);
entity.addComponent<CPlayerBoost>(game);
entity.addComponent<CGun>(game, sf::Sprite(game->resource["guns"], {0,0,32,16}), bullets_per_second, gun_speed, Groups::player_bullet);
auto& cSprite = entity.getComponent<CSprite>();
cSprite.frames["right"] = std::make_tuple(sf::IntRect(0,0,160,70), sf::Vector2f(80.f, 38.f), sf::Vector2f(0.4f, 0.4f));
cSprite.frames["up_or_down"] = std::make_tuple(sf::IntRect(160,0,160,70), sf::Vector2f(80.f, 35.f), sf::Vector2f(0.4f, 0.4f));
cSprite.frames["left"] = std::make_tuple(sf::IntRect(320,0,160,70), sf::Vector2f(80.f, 32.f), sf::Vector2f(0.4f, 0.4f));
cSprite.changeFrame("right");
entity.addComponent<CExplosion>(game);
entity.addComponent<CBlink>();
entity.addComponent<CPlayerMovement>(turn_speed);
entity.addComponent<CHUD>(game);
entity.addGroup(Groups::drawable);
entity.addGroup(Groups::player);
entity.addGroup(Groups::collidable);
game->manager.refresh();
createThruster(game, entity);
}
#endif /* end of include guard: PLAYER_H */
| true |
8091173d29dba9c8f71a4f84e57c0822af3594d2 | C++ | jonasj65/streamfiler | /streamfiler/tests/ParametersTest.cpp | UTF-8 | 9,539 | 2.5625 | 3 | [] | no_license | /*
* File: ParametersTest.cpp
* Author: Janos Jonas
*
* Created on April 29, 2020, 12:00 AM
*/
#include "ParametersTest.h"
using namespace streamfiler_test;
using namespace streamfiler;
CPPUNIT_TEST_SUITE_REGISTRATION(ParametersTest);
ParametersTest::ParametersTest()
{
}
ParametersTest::~ParametersTest()
{
}
void ParametersTest::setUp()
{
}
void ParametersTest::tearDown()
{
Parameters::releaseInstance();
}
void ParametersTest::testInstancePointer()
{
Parameters* p0 = Parameters::instance;
Parameters* p = Parameters::getInstance();
CPPUNIT_ASSERT((p0 == nullptr) && (p != nullptr));
}
void ParametersTest::testConnectionsGood()
{
char* arg[] = {arg0,arg1S,arg2,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(4, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
CPPUNIT_ASSERT(c1 == 3 && f1.length() > 0 && l1 == DEFAULT_LIMIT && t1 == DEFAULT_TIMEOUT && h1 == false && v1 == false);
}
void ParametersTest::testConnectionsWrong()
{
char* arg[] = {arg0,arg1S,arg2Wrong,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(4, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
CPPUNIT_ASSERT(c1 == DEFAULT_CONNECTIONS && f1.length() > 0 && l1 == DEFAULT_LIMIT && t1 == DEFAULT_TIMEOUT && h1 == false && v1 == false);
}
void ParametersTest::testArg1SWrong()
{
char* arg[] = {arg0,arg1SWrong,arg2,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(4, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
CPPUNIT_ASSERT(c1 == DEFAULT_CONNECTIONS && f1.length() > 0 && l1 == DEFAULT_LIMIT && t1 == DEFAULT_TIMEOUT && h1 == false && v1 == false);
}
void ParametersTest::testArg1LWrong()
{
char* arg[] = {arg0,arg1LWrong,arg2,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(4, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
CPPUNIT_ASSERT(c1 == DEFAULT_CONNECTIONS && f1.length() > 0 && l1 == DEFAULT_LIMIT && t1 == DEFAULT_TIMEOUT && h1 == false && v1 == false);
}
void ParametersTest::testArg1SMissing()
{
char* arg[] = {arg0,arg1SMissing,arg2,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(4, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
CPPUNIT_ASSERT(c1 == DEFAULT_CONNECTIONS && f1.length() > 0 && l1 == DEFAULT_LIMIT && t1 == DEFAULT_TIMEOUT && h1 == false && v1 == false);
}
void ParametersTest::testArg1LMissing()
{
char* arg[] = {arg0,arg1LMissing,arg2,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(4, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
CPPUNIT_ASSERT(c1 == DEFAULT_CONNECTIONS && f1.length() > 0 && l1 == DEFAULT_LIMIT && t1 == DEFAULT_TIMEOUT && h1 == false && v1 == false);
}
void ParametersTest::testParametersAll()
{
char* arg[] = {arg0,arg1S,arg2,arg3S,arg4,arg5S,arg6,arg7S,arg8,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(10, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
//CPPUNIT_ASSERT(c1 == 3 && f1.length() > 0 && l1 == 10 && t1 == 10000 && h1 == false && v1 == false);
}
void ParametersTest::testParametersAllLong()
{
char* arg[] = {arg0,arg1L,arg2,arg3L,arg4,arg5L,arg6,arg7L,arg8,port};
int c0 = Parameters::getInstance()->getConnections();
std::string f0 = Parameters::getInstance()->getDirectoryStr();
int l0 = Parameters::getInstance()->getLimit();
int t0 = Parameters::getInstance()->getTimeout();
bool h0 = Parameters::getInstance()->getHelp();
bool v0 = Parameters::getInstance()->getVerbose();
bool ok = Parameters::getInstance()->parseParams(10, arg);
int c1 = Parameters::getInstance()->getConnections();
std::string f1 = Parameters::getInstance()->getDirectoryStr();
int l1 = Parameters::getInstance()->getLimit();
int t1 = Parameters::getInstance()->getTimeout();
bool h1 = Parameters::getInstance()->getHelp();
bool v1 = Parameters::getInstance()->getVerbose();
CPPUNIT_ASSERT(ok);
CPPUNIT_ASSERT(c0 == -10 && f0.empty() && l0 == -10 && t0 == -10 && h0 == false && v0 == false);
//CPPUNIT_ASSERT(c1 == 3 && f1.length() > 0 && l1 == 10 && t1 == 10000 && h1 == false && v1 == false);
} | true |
4a31f2188d33aa6a7e3e53b8f023e45bb464148a | C++ | azurite/AST-245-N-Body | /src/first_task.cpp | UTF-8 | 8,943 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <memory>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <cmath>
#include <mgl2/mgl.h>
#include <Eigen/Dense>
#include <data.hpp>
#include <particle.hpp>
#include <gravitysolvers.hpp>
#include <first_task.hpp>
std::unique_ptr<std::vector<Particle>> p(Data::readFromFile("data.ascii"));
std::vector<Particle> particles = *p;
float pMass = 0.0;
float totalMass = 0.0;
float radius = 0.0;
float scaleLength = 0.0;
float epsilon = 0.0; // softening
float t_relax = 0.0;
float r0 = std::numeric_limits<float>::max(); // center of system to avoid problems with dividing by 0
float rhm = 0.0; // half mass radius
float Mass(float r, bool strictlyLess = false)
{
float M = 0.0;
for(Particle &p : particles) {
float r2 = p.radius2();
if((!strictlyLess && r2 <= r*r) || (strictlyLess && r2 < r*r)) {
M += p.m();
}
}
return M;
}
float density_hernquist(float r)
{
return (totalMass / (2 * M_PI)) * (scaleLength / r) * (1 / std::pow(r + scaleLength, 3));
}
// Computes force F where F = m*a
float force_hernquist(float r)
{
// Assumption: G = 1
return -totalMass * pMass / ((r + scaleLength) * (r + scaleLength));
}
void calculate_constants()
{
pMass = particles[0].m(); // all particles have the same mass
for(Particle &p : particles) {
totalMass += p.m();
radius = std::max(p.radius2(), radius);
r0 = std::min(p.radius2(), r0);
}
r0 = std::sqrt(r0) + std::numeric_limits<float>::epsilon();
radius = std::sqrt(radius);
float dr = radius / 100000;
for(float r = r0; r <= radius; r += dr) {
if(Mass(r) >= totalMass * 0.5) {
rhm = r;
break;
}
}
scaleLength = rhm / (1 + std::sqrt(2));
// https://en.wikipedia.org/wiki/Mean_inter-particle_distance
// after plugging in n = totalMass / (4/3*PI*r^3) in the formula most terms cancel out
epsilon = radius / std::pow(totalMass, 1.0/3.0);
t_relax = compute_relaxation();
// exact mean inter-particle separation
/*
epsilon = .0;
for(Particle &p : particles) {
for(Particle &q : particles) {
epsilon += (p.r() - q.r()).norm();
}
}
long n = particles.size();
epsilon /= (n*(n-1));
*/
std::cout << "First Task " << std::endl;
std::cout << "------------------" << std::endl;
std::cout << " pMass: " << pMass << std::endl;
std::cout << " totalMass: " << totalMass << std::endl;
std::cout << " radius: " << radius << std::endl;
std::cout << " r0: " << r0 << std::endl;
std::cout << " rhm: " << rhm << std::endl;
std::cout << " scaleLength: " << scaleLength << std::endl;
std::cout << " softening: " << epsilon << std::endl;
std::cout << " t_relax: " << t_relax << std::endl;
std::cout << "------------------" << std::endl;
}
float compute_relaxation()
{
// Assumption: G = 1
float N = particles.size();
float vc = std::sqrt(totalMass * 0.5 / rhm);
float t_cross = rhm / vc;
float t_relax = N / (8 * std::log(N)) * t_cross;
return t_relax;
}
void step1()
{
r0 = 0.005;
int numSteps = 50;
std::vector<float> hDensity;
std::vector<float> nDensity;
std::vector<float> rInput;
std::vector<float> errors;
// creates evenly spaced intervals on a log scale on the interval [r0, radius]
// drLinToLog(i) gives the start of the ith interval on [r0, radius]
auto drLinToLog = [&](int i) {
return r0 * std::pow(radius / r0, (float)i / (float)numSteps);
};
// transforms the numerical data into a dimension desirable for plotting
// here we want to avoid problems with 0 on log scales since log(0) is undefined
auto plotFit = [](float x) {
return x + std::numeric_limits<float>::epsilon();
};
for(int i = 0; i <= numSteps; i++) {
float r = drLinToLog(i);
float r1 = drLinToLog(i + 1);
float MShell = Mass(r1, true) - Mass(r, true);
float VShell = 4.0/3.0*M_PI*(r1*r1*r1 - r*r*r);
float nRho = MShell / VShell;
float numParticlesInShell = MShell / pMass;
// p = n*m/v, err = sqrt(n) =>
// p_err = sqrt(n)/n*p = sqrt(n)*n*m/(n*v) = sqrt(n)*m/v
// p = density, n = #particles, m = pMass
float rhoError = std::sqrt(numParticlesInShell) * pMass / VShell;
hDensity.push_back(plotFit(density_hernquist((r + r1) / 2)));
nDensity.push_back(plotFit(nRho));
errors.push_back(rhoError);
rInput.push_back(r);
}
mglData hData;
hData.Set(hDensity.data(), hDensity.size());
mglData nData;
nData.Set(nDensity.data(), nDensity.size());
mglData rData;
rData.Set(rInput.data(), rInput.size());
mglData eData;
eData.Set(errors.data(), errors.size());
mglGraph gr(0, 1200, 800);
float outMin = std::min(hData.Minimal(), nData.Minimal());
float outMax = std::max(hData.Maximal(), nData.Maximal());
gr.SetRange('x', rData);
gr.SetRange('y', outMin, outMax);
gr.SetFontSize(2);
gr.SetCoor(mglLogLog);
gr.Axis();
gr.Label('x', "Radius [l]", 0);
gr.Label('y', "Density [m]/[l]^3", 0);
gr.Plot(rData, hData, "b");
gr.AddLegend("Hernquist", "b");
gr.Plot(rData, nData, "r .");
gr.AddLegend("Numeric", "r .");
gr.Error(rData, nData, eData, "qo");
gr.AddLegend("Poissonian Error", "qo");
gr.Legend();
gr.WritePNG("density_profiles.png");
}
void step2()
{
r0 = 0.005;
int numSteps = 100;
std::vector<float> softenings;
std::vector<float> dAnalytic;
std::vector<float> rInput;
// creates evenly spaced intervals on a log scale on the interval [r0, radius]
// drLinToLog(i) gives the start of the ith interval on [r0, radius]
auto drLinToLog = [&](int i) {
return r0 * std::pow(radius / r0, (float)i / (float)numSteps);
};
// transforms the numerical data into a dimension desirable for plotting
// here we want to plot the magnitude of the force and add a small nonzero
// number to the force to avoid problems with 0 on log scales since log(0) is undefined
auto plotFit = [](float x) {
return std::abs(x) + std::numeric_limits<float>::epsilon();
};
// calculate the analytical force in the hernquist model
for(int i = 0; i <= numSteps; i++) {
float r = drLinToLog(i);
dAnalytic.push_back(plotFit(force_hernquist(r)));
rInput.push_back(r);
}
std::unique_ptr<Gravitysolver::Direct> solver(new Gravitysolver::Direct());
std::vector<mglData> plotData;
for(int i = 1; i <= 7; i++) {
solver->readData("data/direct-nbody-" + std::to_string(i) + ".txt");
softenings.push_back(solver->softening());
std::vector<float> dNumeric;
// project the force vector of each particle towards the center of the system
const MatrixData &solverData = solver->data();
Eigen::VectorXf f_center(solverData.cols());
float fx, fy, fz, x, y, z, norm;
for(int i = 0; i < solverData.cols(); i++) {
x = solverData(1, i);
y = solverData(2, i);
z = solverData(3, i);
fx = solverData(7, i);
fy = solverData(8, i);
fz = solverData(9, i);
norm = std::sqrt(x*x + y*y + z*z);
// project the force vector onto the normalized sphere normal
f_center(i) = (x*fx + y*fy + z*fz) / norm;
}
for(int i = 0; i <= numSteps; i++) {
float r = drLinToLog(i);
float r1 = drLinToLog(i + 1);
float dr = r1 - r;
float f = 0.0;
int numParticles = 0;
// calculate the average gravitational force in a shell
for(int i = 0; i < particles.size(); i++) {
Particle p = particles[i];
if(r <= p.radius() && p.radius() < r1) {
f += f_center(i);
numParticles++;
}
}
f = (numParticles == 0 ? .0 : f / numParticles);
dNumeric.push_back(plotFit(f));
}
mglData cData;
cData.Set(dNumeric.data(), dNumeric.size());
plotData.push_back(cData);
}
mglData aData;
aData.Set(dAnalytic.data(), dAnalytic.size());
mglData rData;
rData.Set(rInput.data(), rInput.size());
mglGraph gr(0, 1200, 800);
float outMin;
float outMax;
for(int i = 0; i < plotData.size(); i++) {
outMin = std::max(std::min(plotData[i].Minimal(), aData.Minimal()), 50.0);
outMax = std::max(plotData[i].Maximal(), aData.Maximal());
}
gr.SetRange('x', rData);
gr.SetRange('y', outMin, outMax);
gr.SetFontSize(2);
gr.SetCoor(mglLogLog);
gr.Axis();
gr.Label('x', "Radius [l]", 0);
gr.Label('y', "Force [m]^2[l]^{-2}", 0);
gr.Plot(rData, aData, "b");
gr.AddLegend("Analytic", "b");
// colors for plotting
const char *opt[7] = {"r +", "c +", "m +", "h +", "l +", "n +", "q +"};
for(int i = 0; i < plotData.size(); i++) {
std::stringstream ss;
ss << "\\epsilon = " << std::setprecision(4) << softenings[i] << " [l]";
gr.Plot(rData, plotData[i], opt[i]);
gr.AddLegend(ss.str().c_str(), opt[i]);
}
gr.Legend();
gr.WritePNG("forces.png");
}
void first_task()
{
calculate_constants();
step1();
step2();
}
| true |
30d2642cc988976074d00b41ec219f6c82fb8041 | C++ | xbaby123/C-program | /Botnet/Botnet_module/module/main.cpp | UTF-8 | 5,251 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
void decodeMessage(char* fdMessage, string &decodedMessage);
void str2chr(char [], string s);
int String2CharPointer(string s, char* a);
int main()
{
char *fbMessage = "child_1_n ask_1_v pleasure_1_n tie_1_v uncle_1_n read_1_v enemy_1_n speak_1_v standard_1_n catch_1_v ruler_1_n enjoy_1_v energy_1_n nab_2_v speed_1_n carry_1_v climate_1_n shoot_1_v image_1_n may_1_v author_1_n gain_1_v exchange_1_n start_1_v shirt_1_n agree_1_v basis_1_n cannot_1_v dollar_1_n join_1_v pain_1_n explain_1_v grandmother_1_n";
string temp ="";
char *a;
char b[500];
decodeMessage(fbMessage,temp);
String2CharPointer(temp,a);
//str2chr(b,temp);
//cout << temp << endl;
printf("%s",a);
cout << "Hello world!" << endl;
return 0;
}
void decodeMessage(char* fbMessage, string &temp)
{
int len = strlen(fbMessage);
int i,j;
int newWord = 1;
char c;
char d;
for(i = 0 ; i<len ; i++ )
{
c= fbMessage[i];
if('a'<= c && c<='z' && newWord)
{
if(i<len-1){
d=fbMessage[i+1];
}else
{
continue;
}
switch(c)
{
case 'a':
{
if(d=='p')
temp.append("\'");
else
temp.append(string(1,c));
break;
}
case 'q':
{
if(d=='u')
temp.append("\"");
else
temp.append(string(1,c));
break;
}
case 'h':
{
if(d=='a')
temp.append("#");
else
temp.append(string(1,c));
break;
}
case 'p':
{
if(d=='e')
temp.append("%");
else
temp.append(string(1,c));
break;
}
case 's':
{
if(d=='l')
{
temp.append("(");
}else if(d=='r')
{
temp.append(")");
}
else if(d=='h')
{
temp.append("/");
}else if(d=='p')
{
temp.append(" ");
}else
temp.append(string(1,c));
break;
}
case 'm':
{
if(d=='i')
temp.append("-");
else
temp.append(string(1,c));
break;
}
case 'd':
{
if(d=='o')
temp.append(".");
else
temp.append(string(1,c));
break;
}
case 'c':
{
if(d=='o')
{
temp.append(",");
}else if(d=='l')
{
temp.append(":");
}else
temp.append(string(1,c));
break;
}
default :
{
temp.append(string(1,c));
break;
}
}
newWord = 0;
i++;
continue;
}else if(c==' ')
{
newWord = 1;
}
}
}
void str2chr(char b[],string s)
{
int len = s.length();
int i;
for(i=0;i<len;i++){
b[i]=s[i];
}
b[i]='\0';
}
int String2CharPointer(string s, char* a)
{
int n = s.size();
int i = 0;
a =(char *)malloc((n+1)*sizeof(char));
while(a[i]=s[i])
i++;
a[i]='\0';
return 1;
}
//int Split(char *inStr, void *saveArray)
//{
// int i,j,index=0;
//
// char *lines[MAX_LINES];
//
// memset(lines,0,sizeof(lines));
//
// j=strlen(inStr);
// if (j<1) return -1;
//
// lines[index++]=inStr;
// for (i=0;i < j;i++)
// if ((inStr[i]=='\x0A') || (inStr[i]=='\x0D'))
// inStr[i]='\x0';
//
// //Now that all cr/lf have been converted to NULL, save the pointers...
// for (i=0;i < j;i++) {
// if ((inStr[i]=='\x0') && (inStr[i+1]!='\x0')) {
// if (index < MAX_LINES)
// lines[index++] = &inStr[i+1];
// else
// break;
// }
// }
//
// if (saveArray!=0)
// memcpy(saveArray,lines,sizeof(lines));
//
// return index;
//}
| true |
de8314f4c9ef0eeaa75061c37ca62eb03cc474dc | C++ | MikeGitb/data_matrix | /tests/src/test_data_matrix.cpp | UTF-8 | 1,313 | 3.34375 | 3 | [] | no_license | #include <data_matrix/data_matrix.h>
#include <catch2/catch.hpp>
#include <iostream>
using namespace mba;
TEST_CASE( "Insert", "[data_matrix_tests]" )
{
data_matrix<int, float, double, std::vector<int>> data;
mba::column<float> row2 = data.template get<1>();
mba::column<std::vector<int>> row4 = data.template get<3>();
data.push_back( 1, 1.0, 2.0, {} );
CHECK( data.get<0>()[0] == 1 );
CHECK( data.get<1>()[0] == 1.0 );
CHECK( data.get<2>()[0] == 2.0 );
CHECK( data.get<3>()[0].size() == 0 );
}
TEST_CASE( "Iterate", "[data_matrix_tests]" )
{
data_matrix<int, float, double> data;
data.push_back( 1, 1.0f, 0.0 );
data.push_back( 2, 1.2f, 0.0 );
data.push_back( 3, 1.3f, 0.0 );
data.push_back( 4, 1.4f, 0.0 );
for( auto e : data ) {
std::get<2>( e ) = std::get<0>( e ) * std::get<1>( e );
}
for( auto e : data ) {
CHECK( std::get<2>( e ) == std::get<0>( e ) * std::get<1>( e ) );
}
}
TEST_CASE( "erase", "[data_matrix_tests]" )
{
data_matrix<int, float, double> data;
data.push_back( 1, 1.0f, 0.0 );
data.push_back( 2, 1.2f, 0.0 );
data.push_back( 3, 1.3f, 0.0 );
data.push_back( 4, 1.4f, 0.0 );
data.erase( data.begin() + 1, data.begin() + 3 );
CHECK( data.size() == 2 );
for( auto e : data ) {
CHECK( std::get<2>( e ) == std::get<0>( e ) * std::get<1>( e ) );
}
}
| true |
82246e5ae7f26c54d49fcb361e46ea3b5f2bdfb6 | C++ | NuckleR/LR_8 | /LR_8(2)/LR_8(2)/File.cpp | WINDOWS-1251 | 9,439 | 2.765625 | 3 | [] | no_license | #include "File.h"
#include "Casino.h"
#include "Exception.h"
#include <io.h>
#include <sys/types.h>
#include <stdio.h>
File& operator<<(File& file, const char* s)
{
try {
if (!file.file.is_open()){
throw 1;
}
}
catch (int i){
Exception ex(i);
ex.Print();
}
string str = s;
file.file << str;
return file;
}
fstream& operator<<(fstream& out, Casino& Cas) {
try {
if (!out.is_open()){
throw 1;
}
}
catch (int i){
Exception ex(i);
ex.Print();
}
int a = out.tellg();
string art_name = Cas.get_name();
size_t len1 = art_name.size() + 1;
int money = Cas.get_money();
int profit = Cas.get_profit();
int players = Cas.get_players();
out.write((char*)(&len1), sizeof(len1));
out.write((char*)(art_name.c_str()), len1);
out.write((char*)(&money), sizeof(money));
out.write((char*)(&profit), sizeof(profit));
out.write((char*)(&players), sizeof(players));
return out;
}
File& operator<<(File& file, Casino& Cas)
{
int pos = 0, a = 0, size = 0;
try {
if (!file.file.is_open()){
throw 1;
}
}
catch (int i){
Exception ex(i);
ex.Print();
}
if (file.key == txt) {
file.file << Cas.get_name() << " " << Cas.get_money() << " " << Cas.get_profit() << " " << Cas.get_players() << " " <<endl;
}
else if (file.key == bin) {
string name = Cas.get_name();
size_t len1 = name.size() + 1;
int money = Cas.get_money();
int profit = Cas.get_profit();
int players = Cas.get_players();
file.file.write((char*)(&len1), sizeof(len1));
file.file.write((char*)(name.c_str()), len1);
file.file.write((char*)(&money), sizeof(money));
file.file.write((char*)(&profit), sizeof(profit));
file.file.write((char*)(&players), sizeof(players));
}
return file;
}
ostream& operator<<(ostream& out, File& file)
{
int a = 0;
try {
if (!file.file.is_open()){
throw 1;
}
}
catch (int i){
Exception ex(i);
ex.Print();
}
if (file.key == txt) {
string str;
while (!file.file.eof()) {
std::getline(file.file, str);
a = file.file.tellg();
cout << str << endl;
}
}
else if (file.key == bin) {
int i = 0;
int size = 0, step = 0;
while (i < file.size) {
int money;
int profit;
int players;
size_t len;
file.file.read((char*)(&len), sizeof(len));
char* name = new char[len];
file.file.read((char*)(name), len);
name[len - 1] = '\0';
file.file.read((char*)(&money), sizeof(int));
file.file.read((char*)(&profit), sizeof(int));
file.file.read((char*)(&players), sizeof(int));
cout << name << " " << money << " " << profit << " " << players << endl;
delete[] name;
i++;
}
}
return out;
}
int File::edit(int line)
{
this->open("wr");
int a, b;
Casino* tmpe = new Casino[get_size()];
try {
if (!file.is_open()){
throw 1;
}
}
catch (int i){
Exception ex(i);
ex.Print();
return 3;
}
Casino tmp;
if (this->key == txt) {
string temp;
for (int i = 0; i < get_size(); i++) {
std::getline(this->file, temp, ' ');
tmpe[i].set_name(temp);
std::getline(this->file, temp, ' ');
tmpe[i].set_money(stoi(temp));
std::getline(this->file, temp, ' ');
tmpe[i].set_profit(stoi(temp));
std::getline(this->file, temp, '\n');
tmpe[i].set_players(stoi(temp));
}
}
else if (this->key == bin) {
size_t len;
for (int i = 0; i < get_size(); i++) {
this->file.read((char*)(&len), sizeof(len));
char* n = new char[len];
string name;
int money = 0;
int profit = 0;
int players = 0;
this->file.read((char*)(n), len);
name = n;
name[len - 1] = '\0';
this->file.read((char*)(&money), sizeof(int));
this->file.read((char*)(&profit), sizeof(int));
this->file.read((char*)(&players), sizeof(int));
tmpe[i].set_name(name);
tmpe[i].set_money(money);
tmpe[i].set_profit(profit);
tmpe[i].set_players(players);
}
a = file.tellg();
}
cout << " ?\n1 - \n2 - \n3 - \n4 - \n5 - - ( )\n" << endl;
int choice;
do {
cin >> choice;
if (cin.fail()) {
cin.clear();
cin.ignore(32767, '\n');
cout << "\n\n : ";
choice = -1;
}
else break;
} while (choice < 0 || choice>5);
if(choice!=5)cout << " : ";
switch (choice) {
case 1: {
string a;
rewind(stdin);
cin >> a;
tmpe[line-1].set_name(a);
break;
}
case 2: {
int a;
while (true) {
cin >> a;
if (cin.fail()) {
cin.clear();
cin.ignore(32767, '\n');
cout << "\n\n : ";
}
else break;
}
tmpe[line-1].set_money(a);
break;
}
case 3: {
int a;
while (true) {
cin >> a;
if (cin.fail()) {
cin.clear();
cin.ignore(32767, '\n');
cout << "\n\n : ";
}
else break;
}
tmpe[line-1].set_profit(a);
break;
}
case 4: {
int a;
while (true) {
cin >> a;
if (cin.fail()) {
cin.clear();
cin.ignore(32767, '\n');
cout << "\n\n : ";
}
else break;
}
tmpe[line-1].set_players(a);
break;
}
case 5: {
break;
}
} if (choice == 5) {
this->file.close();
return 0;
}
a = this->file.tellg();
this->file.seekg(0, ios_base::end);
b = this->file.tellg();
this->file.seekg(0, ios_base::beg);
if (this->key == txt) {
this->file.close();
this->file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
this->file.clear();
for (int i = 0; i < get_size(); i++) {
*this << tmpe[i];
}
}
else if (this->key == bin) {
this->file.close();
this->file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
this->file.clear();
for (int i = 0; i < get_size(); i++) {
*this << tmpe[i];
}
}
this->close();
return 1;
}
//------------------------------
void File::del(int line)
{
this->open("wr");
int a, b;
string name;
int money = 0;
int profit = 0;
int players = 0;
try {
if (!file.is_open()) {
throw 1;
}
}
catch (int i) {
Exception ex(i);
ex.Print();
return;
}
Casino tmp;
string temp;
Casino* tmpe = new Casino[get_size()];
if (this->key == txt) {
for (int i = 0; i < line - 1; i++) {
std::getline(this->file, temp);
}
a = this->file.tellg();
std::getline(this->file, temp);
b = this->file.tellg();
for (int i = line; i < get_size(); i++) {
this->file.seekg(b, ios_base::beg);
std::getline(this->file, temp);
this->file.seekg(a, ios_base::beg);
this->file << temp << "\n";
a = this->file.tellg();
this->file.seekg(a, ios_base::beg);
std::getline(this->file, temp);
b = this->file.tellg();
}
set_size(get_size() - 1);
this->file.seekg(0, ios_base::beg);
for (int i = 0; i < get_size(); i++) {
std::getline(this->file, temp, ' ');
tmpe[i].set_name(temp);
std::getline(this->file, temp, ' ');
tmpe[i].set_money(stoi(temp));
std::getline(this->file, temp, ' ');
tmpe[i].set_profit(stoi(temp));
std::getline(this->file, temp, '\n');
tmpe[i].set_players(stoi(temp));
}
this->file.close();
this->file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
this->file.clear();
int g = get_size();
for (int i = 0; i < g; i++) {
*this << tmpe[i];
}
this->file.close();
}
else if (this->key == bin) {
size_t len;
fstream temper;
Casino *tmpe = new Casino [get_size()];
char* r = new char[0];
temper.open("temper.bin", ios_base::in | ios_base::out);
for (int g = 0; g < line-1; g++) {
this->file.read((char*)(&len), sizeof(len));
char* n = new char[len];
name = "";
money = 0;
profit = 0;
players = 0;
this->file.read((char*)(n), len);
name = n;
name[len - 1] = '\0';
this->file.read((char*)(&money), sizeof(int));
this->file.read((char*)(&profit), sizeof(int));
this->file.read((char*)(&players), sizeof(int));
tmpe[g].set_name(name);
tmpe[g].set_money(money);
tmpe[g].set_profit(profit);
tmpe[g].set_players(players);
} ff();
for (int i = line; i < get_size(); i++) {
this->file.read((char*)(&len), sizeof(len));
char* n = new char[len];
name = "";
money = 0;
profit = 0;
players = 0;
this->file.read((char*)(n), len);
name = n;
name[len - 1] = '\0';
this->file.read((char*)(&money), sizeof(int));
this->file.read((char*)(&profit), sizeof(int));
this->file.read((char*)(&players), sizeof(int));
tmpe[i-1].set_name(name);
tmpe[i-1].set_money(money);
tmpe[i-1].set_profit(profit);
tmpe[i - 1].set_players(players);
}
this->file.close();
this->file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
this->file.clear();
set_size(get_size()-1);
for (int i = 0; i < get_size(); i++) {
*this << tmpe[i];
}
a = this->file.tellg();
this->file.close();
}
}
| true |
557baa6bd086d42205dd6dc9489cf0c66007213e | C++ | SHornung1/KFParticle | /KFParticle/KFParticleField.h | UTF-8 | 7,170 | 3.0625 | 3 | [] | no_license | //----------------------------------------------------------------------------
// Class for approximation of the magnetic field for KF Particle
// .
// @author I.Kisel, M.Zyzak
// @version 1.0
// @since 20.08.13
//
//
// -= Copyright © ALICE HLT and CBM L1 Groups =-
//____________________________________________________________________________
#ifndef KFParticleField_h
#define KFParticleField_h 1
#include <iostream>
/** @class KFParticleFieldValue
** @brief A class to store a vector with the magnetic field values {Bx, By, Bz} at the certain point.
** @author M.Zyzak, I.Kisel
** @date 05.02.2019
** @version 1.0
**
** The class is used to represent the vector of the magnetic field at the certain position of the track.
** It contains three components of the magnetic field: Bx, By and Bz. It allows to combine the current
** field measurement with another measurement using a weight.
**/
class KFParticleFieldValue
{
public:
KFParticleFieldValue():x(0.f),y(0.f),z(0.f){};
float_v x; ///< Bx component of the magnetic field
float_v y; ///< By component of the magnetic field
float_v z; ///< Bz component of the magnetic field
void Combine( KFParticleFieldValue &B, float_v w )
{
/** Function allows to combine the current magntic field measurement with another measurement
** weighted by "w"
** \param[in] B - another field measurement to be combined with the current value
** \param[in] w - weight of the measurement being added
**/
x+= w*( B.x - x );
y+= w*( B.y - y );
z+= w*( B.z - z );
}
/** Operator to print components of the magnetic field in order Bx, By, Bz.
** \param[in] out - output stream where the values will be printed
** \param[in] B - field vecrot to be printed
**/
friend std::ostream& operator<<(std::ostream& out, KFParticleFieldValue &B){
return out << B.x[0] << " | " << B.y[0] << " | " << B.z[0];
};
};
/** @class KFParticleFieldRegion
** @brief A class to store an approximation of the magnetic field along the particle trajectory. Is used for nonhomogeneous field.
** @author M.Zyzak, I.Kisel
** @date 05.02.2019
** @version 1.0
**
** The class is used to store the approximation of the magnetic field along the particle trajectory.
** Each component Bx, By, Bz is approximated with a parabola function depending on the z coordinate.
** The class is fully vectorised, all parameters are stored in SIMD vectors.
** The class is used in case of the CBM-like nonhomogenious magnetic field.
**/
class KFParticleFieldRegion
{
public:
KFParticleFieldRegion() {};
KFParticleFieldRegion(const float field[10])
{
/** Sets current vectorised representation of the magnetic field approximation from the scalar input array.
** \param[in] field[10] - the scalar input array with the magnetic field approximation
**/
for(int i=0; i<10; i++)
fField[i] = field[i];
}
KFParticleFieldValue Get(const float_v z)
{
/** Returns a magnetic field vector calculated using current parametrisation at the given Z coordinate.
** \param[in] z - value of the Z coordinate, where magnetic field should be calculated.
**/
float_v dz = (z-fField[9]);
float_v dz2 = dz*dz;
KFParticleFieldValue B;
B.x = fField[0] + fField[1]*dz + fField[2]*dz2;
B.y = fField[3] + fField[4]*dz + fField[5]*dz2;
B.z = fField[6] + fField[7]*dz + fField[8]*dz2;
return B;
}
void Set( const KFParticleFieldValue &B0, const float_v B0z,
const KFParticleFieldValue &B1, const float_v B1z,
const KFParticleFieldValue &B2, const float_v B2z )
{
/** Approximates the magnetic field with the parabolas using three points along the particle trajectory.
** \param[in] B0 - magnetic field vector at the first point
** \param[in] B0z - Z position of the first point
** \param[in] B1 - magnetic field vector at the second point
** \param[in] B1z - Z position of the second point
** \param[in] B2 - magnetic field vector at the third point
** \param[in] B2z - Z position of the third point
**/
fField[9] = B0z;
float_v dz1 = B1z-B0z, dz2 = B2z-B0z;
float_v det = 1.f/(float_v(dz1*dz2*(dz2-dz1)));
float_v w21 = -dz2*det;
float_v w22 = dz1*det;
float_v w11 = -dz2*w21;
float_v w12 = -dz1*w22;
float_v dB1 = B1.x - B0.x;
float_v dB2 = B2.x - B0.x;
fField[0] = B0.x;
fField[1] = dB1*w11 + dB2*w12 ;
fField[2] = dB1*w21 + dB2*w22 ;
dB1 = B1.y - B0.y;
dB2 = B2.y - B0.y;
fField[3] = B0.y;
fField[4] = dB1*w11 + dB2*w12 ;
fField[5] = dB1*w21 + dB2*w22 ;
dB1 = B1.z - B0.z;
dB2 = B2.z - B0.z;
fField[6] = B0.z;
fField[7] = dB1*w11 + dB2*w12 ;
fField[8] = dB1*w21 + dB2*w22 ;
}
void Set( const KFParticleFieldValue &B0, const float_v B0z,
const KFParticleFieldValue &B1, const float_v B1z )
{
/** Approximates the magnetic field with the strainght line using two points.
** \param[in] B0 - magnetic field vector at the first point
** \param[in] B0z - Z position of the first point
** \param[in] B1 - magnetic field vector at the second point
** \param[in] B1z - Z position of the second point
**/
fField[9] = B0z;
float_v dzi = 1.f/(float_v( B1z - B0z));
fField[0] = B0.x;
fField[3] = B0.y;
fField[6] = B0.z;
fField[1] = ( B1.x - B0.x )*dzi;
fField[4] = ( B1.y - B0.y )*dzi;
fField[7] = ( B1.z - B0.z )*dzi;
fField[2] = fField[5] = fField[8] = 0.f;
}
void SetOneEntry( const float* field, int iEntry=0 )
{
/** Sets one element of the SIMD vector with index iEntry.
** \param[in] field - a scalar input array with the approximation of the magnetic field
** \param[in] iEntry - entry number of the current SIMD vectors to be set with the input approximation
**/
for(int i=0; i<10; i++)
fField[i][iEntry] = field[i];
}
void SetOneEntry( const int i0, const KFParticleFieldRegion &f1, const int i1 )
{
/** Copies the field approximation from the vector f1 with index i1 to the SIMD vector elemets of the current object with index i0.
** \param[in] i0 - index of the SIMD vector elements of the current field approximation to be set
** \param[in] f1 - input approximation of the magnetic field
** \param[in] i1 - index of the SIMD vector elements of the input approximation to be copied to the current object
**/
for(int i=0; i<10; i++)
fField[i][i0] = f1.fField[i][i1];
}
/** The coefficients of the field approximation: \n
** cx0 = fField[0], cx1 = fField[1], cx2 = fField[2] - coefficients of the Bx approximation; \n
** cy0 = fField[3], cy1 = fField[4], cy2 = fField[5] - coefficients of the By approximation; \n
** cz0 = fField[6], cz1 = fField[7], cz2 = fField[8] - coefficients of the Bz approximation; \n
** z0 = fField[9] - reference Z coordinate. \n
** Bx(z) = cx0 + cx1*(z-z0) + cx2*(z-z0)^2 \n
** By(z) = cy0 + cy1*(z-z0) + cy2*(z-z0)^2 \n
** Bz(z) = cz0 + cz1*(z-z0) + cz2*(z-z0)^2
**/
float_v fField[10];
};
#endif
| true |
5fb5e157512e0dbe84ff54c3438a58af7be5b6b4 | C++ | Iftekhar79/Competitve-Programming | /URI/uri2417.cpp | UTF-8 | 467 | 2.890625 | 3 | [] | no_license | // Championship
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c;
int x,y,z;
cin>>a>>b>>c;
cin>>x>>y>>z;
int point_a= a*3 + b;
int point_x= x*3 + y;
if(point_a> point_x || point_a == point_x && c>z ){
cout<<"C"<<endl;
}
else if(point_a < point_x || point_a == point_x && c<z ){
cout<<"F"<<endl;
}
else if(point_a == point_x && c==z )
cout<<"="<<endl;
}
| true |
98d112e93cd18c63ec6482f969504e5f6bc0aae3 | C++ | vpamrit/ArduinoSPIClientLib | /src/SPIClient.cpp | UTF-8 | 7,118 | 2.59375 | 3 | [] | no_license | #include <SPIClient.h>
static uint8_t PACKET_RETRY_LIMIT = 5;
bool ModeSwitch::set()
{
state = true;
return state;
}
bool ModeSwitch::use(bool consume)
{
if (!consume)
return state;
bool ret = state;
state = false;
return ret;
}
MessageToBeReceived SPIClient::msgComingIn;
MessageToBeSent SPIClient::msgGoingOut;
volatile bool SPIClient::full = false;
volatile SPIClient::CLIENT_STATE SPIClient::mode = SPIClient::CLIENT_STATE::FLUSHING;
ModeSwitch SPIClient::modeSwitch;
const uint32_t SPIClient::FLUSH_BYTES = sizeof(SPIPacketHeader) + NUM_BYTES_PER_PACKET * 2;
bool SPIClient::accept(uint8_t structType, char *buffer, uint16_t length, bool forcedTransmit)
{
return msgGoingOut.acceptTransmission(structType, buffer, length, forcedTransmit);
}
Metadata SPIClient::readMessage(char *buffer)
{
return msgComingIn.readMessage(buffer);
}
uint8_t
SPIClient::handleFlush(char c)
{
static uint32_t nullSequence = 0;
static uint32_t oneSequence = 0;
static bool seqMet = false;
if (c == 0x00)
{
++nullSequence;
seqMet = nullSequence > (double)(FLUSH_BYTES) / 1.25;
}
else
{
if (seqMet)
{
if (c == FLUSH_REQUEST_BYTE)
{
if (++oneSequence == 5)
{
seqMet = false;
nullSequence = 0;
oneSequence = 0;
return FLUSH_NEW_TRANSMISSION; // retransmit packet
}
}
seqMet = false;
nullSequence = 0;
oneSequence = 0;
return FLUSH_CRITICAL_ERROR;
}
}
return FLUSH_NOOP;
};
uint8_t SPIClient::performFlushGet()
{
static uint32_t nullSequence = 0;
static uint32_t oneSequence = 0;
if (nullSequence < (double)(FLUSH_BYTES) / 1.25)
{
nullSequence++;
return 0x00;
}
if (++oneSequence == 5)
{
nullSequence = 0;
oneSequence = 0;
SET_MODE_SWITCH(START_UP);
}
return FLUSH_REQUEST_BYTE; // send one, or signal two
};
uint8_t SPIClient::performStartUpGet(bool consumeStateFreshness)
{
static SPIPacketHeaderUnion header;
static uint8_t byteNum = 0;
if (modeSwitch.use(consumeStateFreshness))
{
header.header = SPIPacketHeader(START_UP_STRUCT, NONE);
byteNum = 0;
}
// writing phase
return header.buffer[byteNum];
}
void SPIClient::performStartUpUpdate(char c, bool consume)
{
static SPIPacketHeaderUnion header;
static uint8_t byteNum = 0;
if (modeSwitch.use(consume))
{ // check 'first time'
header.header = SPIPacketHeader(START_UP_STRUCT, NONE);
byteNum = 0;
}
header.buffer[byteNum++] = c;
if (byteNum == sizeof(SPIPacketHeader))
{
if (header.header.structType == START_UP_STRUCT && header.header.length == 0)
{
SET_MODE_SWITCH(STANDARD); // go ahead
}
else
{
SET_MODE_SWITCH(FLUSHING);
}
}
return;
}
uint8_t SPIClient::performStandardGet()
{
return msgGoingOut.getCurrentByte();
}
void SPIClient::performStandardUpdate(char c, SPIPacketHeaderUnion &header, char *dataBuf)
{
static uint32_t byteIndex = 0;
if (modeSwitch.use(true)) // first switch
{
byteIndex = 0;
}
// read packet
if (byteIndex < sizeof(SPIPacketHeader))
{
header.buffer[byteIndex++] = c;
}
else if (byteIndex < NUM_BYTES_PER_PACKET)
{
dataBuf[byteIndex++ - sizeof(SPIPacketHeader)] = c;
}
// on complete
if (byteIndex == NUM_BYTES_PER_PACKET)
{
ReadTransmissionState readState;
if (verifyHeaderChecksum(header.header) && verifyDataChecksum(dataBuf, header.header))
{
readState = msgComingIn.writePacket(header.header, dataBuf);
}
else
{
// no clue what's happening, just resend stuff
readState.incomingRequest = NONE;
readState.outgoingRequest = NONE;
}
byteIndex = 0;
msgGoingOut.updateState(&readState);
if (readState.incomingRequest == RETRY_TRANSMISSION || msgComingIn.readRetries + msgGoingOut.writeRetries >= PACKET_RETRY_LIMIT)
{
SET_MODE_SWITCH(FLUSHING);
}
return;
}
// brainlessly update
msgGoingOut.updateState(nullptr);
}
// uint8_t SPIClient::operate()
// {
// Serial.println
// return 0x0;
// }
uint8_t SPIMaster::operate()
{
static SPIPacketHeaderUnion headerBuf;
static char dataBuf[NUM_BYTES_PER_PACKET];
Serial.println("operate");
// use mode to set variable states
uint8_t packetRes;
switch (mode)
{
case FLUSHING:
Serial.println("Flushing...");
packetRes = performFlushGet();
if (modeSwitch.use())
{
msgGoingOut.reset();
msgComingIn.reset();
}
break;
case START_UP:
Serial.println("Start...");
// packetRes = performFlushGet();
packetRes = performStartUpGet(false);
break;
case STANDARD: // normal read and write
Serial.println("Begin...");
packetRes = performStandardGet();
break;
}
char spiReturn = SPI.transfer(packetRes);
uint8_t slaveFlushState = handleFlush(spiReturn);
// interpret whether we are flushing or not
switch (slaveFlushState)
{
case FLUSH_NEW_TRANSMISSION:
case FLUSH_CRITICAL_ERROR:
if (!IS_MODE(FLUSHING))
{
SET_MODE_SWITCH(FLUSHING);
}
break;
case FLUSH_NOOP: // all is well
break;
};
switch (mode)
{
case FLUSHING:
break;
case START_UP:
performStartUpUpdate(spiReturn, true); // very first byte of input is useless for both
break;
case STANDARD: // normal read and write
performStandardUpdate(spiReturn, headerBuf, dataBuf);
break;
}
return packetRes;
};
#if !defined(ESP8266)
uint8_t SPISlave::operate()
{
static SPIPacketHeaderUnion headerBuf;
static char dataBuf[NUM_BYTES_PER_PACKET];
char spiReturn = SPDR; // read from the register ??
uint8_t slaveFlushState = handleFlush(spiReturn);
char packetRes;
// interpret whether we are flushing or not
switch (slaveFlushState)
{
case FLUSH_NEW_TRANSMISSION:
case FLUSH_CRITICAL_ERROR:
if (!IS_MODE(FLUSHING))
SET_MODE_SWITCH(FLUSHING);
break;
case FLUSH_NOOP: // all is well
break;
};
// update get and return
switch (mode)
{
case FLUSHING:
packetRes = performFlushGet();
break;
case START_UP:
performStartUpUpdate(spiReturn, false);
packetRes = performStartUpGet(true);
break;
case STANDARD: // normal read and write
performStandardUpdate(spiReturn, headerBuf, dataBuf);
packetRes = performStandardGet();
break;
}
SPDR = packetRes;
return packetRes;
}
#endif // (defined ESP8266) | true |
9df4ceef28ca8b32c5f67f722878766749b7cebe | C++ | pratham-0094/100DaysOfCode | /Day-44/78_SubSet.cpp | UTF-8 | 956 | 3.4375 | 3 | [] | no_license | // https://leetcode.com/problems/subsets/submissions/
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<vector<int>> ans;
vector<vector<int>> subsets(vector<int> &nums)
{
int n = nums.size();
vector<int> sub;
for (int i = 0; i < (1 << n); i++)
{
for (int j = 0; j < n; j++)
{
if (i & (1 << j))
{
sub.push_back(nums[j]);
}
}
ans.push_back(sub);
sub.clear();
}
return ans;
}
};
int main()
{
vector<int> n = {1, 2, 3};
Solution code;
vector<vector<int>> v = code.subsets(n);
for (int i = 0; i < v.size(); i++)
{
for (int j = 0; j <v.size(); j++)
{
cout << v[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
1309953d249c7958a078c4cdd1c434621ad4788f | C++ | toddxue/todd-algorithm | /graph.h | UTF-8 | 3,758 | 3.203125 | 3 | [] | no_license | /*
* graph.h --
*
* graph data structures and misc routines
*
* 2010/01/17: initial release by Todd Xue
*/
#ifndef _graph_h
#define _graph_h
#include <stdio.h>
struct Vertex {
// draw support
int x;
int y;
int no;
int edges_c;
void* data;
struct Edge* edges[100];
};
struct Edge {
int no;
void* data;
Vertex* from;
Vertex* to;
};
struct Graph {
int vertices_c;
int edges_c;
Vertex** vertices;
Edge* edges;
Graph() {
vertices_c = 0;
vertices = new Vertex*[100];
edges_c = 0;
edges = new Edge[10000];
}
~Graph() {
delete[] edges;
delete[] vertices;
}
void print(char* title = 0);
void draw(struct Draw& d);
void vertex(Vertex* v) { vertices[vertices_c++] = v; }
void edge(Vertex* from, Vertex* to) {
Edge* e = &edges[edges_c++];
e->from = from;
e->to = to;
from->edges[from->edges_c++] = e;
}
private:
Graph(Graph const&);
void operator = (Graph const&);
};
namespace graph {
struct Matrix {
void** _data;
int* matrix;
int dim;
Matrix(int dim) : dim(dim) {
_data = new void* [dim];
matrix = new int [dim*dim];
}
~Matrix() {
delete[] matrix;
delete[] _data;
}
int& edge(int i, int j) { return matrix[i*dim + j]; }
void*& data(int i) { return _data[i]; }
void print() {
for (int i = 0; i < dim; ++i) {
for (int j = 0; j < dim; ++j)
printf("%2d ", edge(i, j));
printf("\n");
}
}
private:
Matrix(Matrix const&);
void operator = (Matrix const&);
};
struct AdjList {
struct A;
struct V {
void* data;
A* adjs;
};
struct A {
A* next;
void* data;
int vno;
A* free_next;
};
A* free_head;
int dim;
V* varr;
AdjList(int dim) : free_head(0), dim(dim) {
varr = new V[dim];
for (int i = 0; i < dim; ++i)
varr[i].adjs = 0;
}
~AdjList() {
while (free_head) {
A* free = free_head;
free_head = free->free_next;
delete free;
}
delete[] varr;
}
void edge(int i, int j) {
A* a = new A;
a->free_next = free_head;
free_head = a;
a->vno = j;
a->next = varr[i].adjs;
varr[i].adjs = a;
}
void print() {
for (int i = 0; i < dim; ++i) {
printf("%2d :", i);
for (A* a = varr[i].adjs; a; a = a->next)
printf(" %2d", a->vno);
printf("\n");
}
}
private:
AdjList(AdjList const&);
void operator = (AdjList const&);
};
struct AdjList2 {
int* arr;
int dim;
int e;
AdjList2(int dim, int e) : dim(dim), e(e) {
arr = new int[dim + 1 + e * 2];
for (int i = 0; i <= dim; ++i)
arr[i] = 0;
}
~AdjList2() {
delete[] arr;
}
void print() {
for (int i = 0; i < dim; ++i) {
printf("%2d :", i);
for (int j = arr[i]; j < arr[i+1]; ++j)
printf(" %2d", arr[j]);
printf("\n");
}
}
private:
AdjList2(AdjList2 const&);
void operator = (AdjList2 const&);
};
}
#endif
| true |
6ae8b6552cbd4a4f19a40bb377f03fb745d087fe | C++ | BlueLightning42/word-creator | /main.cpp | UTF-8 | 1,244 | 3.109375 | 3 | [] | no_license | #include "wordcreator.h" //dependancies are <fstream> <vector> <unordered_map> <string> <cstring>
// switched from fmt to iostream before uploading to github
#include <iostream>
void logger(std::string _to_log) {
std::cout << _to_log << std::endl;
}
int main() {
//initialize with the sound directory and callback function to call on errors
WordCreator sounds("./sound_dir/", logger);
// fmt::print(sounds.make("{blends}{vowels}"));
std::cout << sounds.make("Ta{vowels}{blends||vowels}") << std::endl; //prints something like Tawao or Tauysh
std::cout << sounds.make("A{ |20|vowels}{ |70|vowels}{blends}") << std::endl; //prints something like Ashr
auto vowels = sounds["vowels"];
std::cout << "List of values in the vowels csv:" << std::endl;
for (const auto& v : vowels) {
std::cout << " |" << v << "|";
} // prints |e| |ee| |ea| |ie| |ei| etc,
std::cout << std::endl;
WordCreator words("./word_dir/", logger);
std::cout << words.make("Hello, {title|80|honorific} {adjective}") << std::endl; //prints something Hello, Master petty
std::cout << words.make("{honorific} and {honorific} {adjective} are friends with {title} {adjective}") << std::endl; // Mrs and Missus toxic are friends with Prince small
return 0;
}
| true |
7f6184b231ae1b34980919aa7fc4212dd612e0b9 | C++ | EndlessDex/cs225-fall2016 | /mp2/scene.h | UTF-8 | 698 | 2.75 | 3 | [] | no_license | #ifndef SCENE_H
#define SCENE_H
#include "image.h"
#include "png.h"
struct data { Image* pic; int x; int y; };
class Scene
{
public:
Scene(int max);
~Scene();
Scene(const Scene &source);
const Scene& operator=(const Scene &source);
void changemaxlayers(int newmax);
void addpicture(const char *FileName, int index, int x, int y);
void changelayer(int index, int newindex);
void translate(int index, int xcoord, int ycoord);
void deletepicture(int index);
Image* getpicture(int index) const;
Image drawscene() const;
private:
data* imageArray;
int maxSize;
void copy(const Scene &source);
void clear();
void nullify();
};
#endif
| true |
c229e34e6795f7c500905ac3ce1cc73c0af0b32d | C++ | rakhiagr/Splitwise | /splitwise_transactions.cpp | UTF-8 | 2,352 | 3 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <stack>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
#include <sstream>
#include <iomanip>
using namespace std;
// class person_compare
// {
// public:
// bool operator()(pair<string, int> p1, pair<string, int> p2)
// {
// return p1.second < p2.second;
// }
// };
int32_t main()
{
int no_of_transactions, friends;
cin >> no_of_transactions >> friends;
string x, y;
int amount;
unordered_map<string, int> net;
while (no_of_transactions)
{
cin >> x >> y >> amount;
if (!net.count(x))
net[x] = 0;
if (!net.count(y))
net[y] = 0;
net[x] -= amount;
net[y] += amount;
no_of_transactions--;
}
//Using multiset so that we can have multiple equal values in a sorted order
multiset<pair<int, string> > m;
for (auto p : net)
{
string person = p.first;
int amount = p.second;
if (net[person] != 0)
m.insert(make_pair(amount, person));
}
int count = 0;
while (!m.empty())
{
auto low = m.begin();
auto high = prev(m.end());
//pop out two elements from start and end as they would be the max credit and max credit
int debit = low->first;
string debit_person = low->second;
int credit = high->first;
string credit_person = high->second;
m.erase(low);
m.erase(high);
int settled_amount = min(-debit, credit);
debit += settled_amount;
credit -= settled_amount;
cout << debit_person << " will pay " << settled_amount << " to " << credit_person << endl;
//The remainder of the settlement is pushed back into the multiset
if (debit != 0)
{
m.insert(make_pair(debit, debit_person));
}
if (credit != 0)
{
m.insert(make_pair(credit, credit_person));
}
count++;
}
cout << "Total number of transactions to be done -> " << count << endl;
} | true |
e90e766d198bf607297d697e5eb4471d4ba844d7 | C++ | gky360/contests | /atcoder/panasonic2020/f/Main.cpp | UTF-8 | 1,102 | 2.8125 | 3 | [] | no_license | /*
[panasonic2020] F - Fractal Shortest Path
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(c) (c).begin(), (c).end()
const int K = 30;
int Q;
bool blocked(ll s1, ll s2, ll t1, ll t2) {
return s1 == s2 && s1 % 3 == 1 && abs(t2 - t1) >= 2;
}
ll calc(ll x1, ll y1, ll x2, ll y2) {
ll p = 1;
ll ans = 0;
REP(i, K) {
if (blocked(x1 / p, x2 / p, y1 / p, y2 / p)) {
ll tmp = min(min(x1 % p, x2 % p) + 1, p - max(x1 % p, x2 % p));
ans = max(ans, tmp);
}
p *= 3;
}
return ans;
}
ll solve(ll x1, ll y1, ll x2, ll y2) {
ll ans = abs(x1 - x2) + abs(y1 - y2) +
2 * max(calc(x1, y1, x2, y2), calc(y1, x1, y2, x2));
return ans;
}
int main() {
cin >> Q;
for (int i = 0; i < Q; i++) {
ll a, b, c, d;
cin >> a >> b >> c >> d;
a--, b--, c--, d--;
cout << solve(a, b, c, d) << endl;
}
return 0;
}
| true |
e52a9d97c567fa083eaa4cabe0bebd43bc3fd029 | C++ | denfer57/ProjetSyntheseL3 | /Projet_synthese/Polygone.cpp | ISO-8859-1 | 3,590 | 3.0625 | 3 | [] | no_license | #include "Polygone.h"
#include "Visiteur.h"
Polygone::Polygone(){ }
Polygone::Polygone(vector<Point> points) : listesPoints(points){ }
Polygone::Polygone(const Couleur & couleur) : Forme(couleur) { }
string Polygone::toString() const
{
ostringstream oss;
oss << "Polygone : { Points : { ";
int taille = listesPoints.size();
for (int i = 0; i < taille; i++)
{
oss << listesPoints[i];
if (taille > i + 1)
oss << ",";
oss << " ";
}
oss << "}";
return oss.str();
}
int Polygone::getNombrePoints()
{
return listesPoints.size();
}
void Polygone::visite(Visiteur *v)
{
v->visite(this);
}
void Polygone::translation(double translationX, double translationY)
{
vector<Point>::iterator it;
Point pointCourant;
double valeurX, valeurY;
for (it = listesPoints.begin(); it != listesPoints.end(); it++) {
pointCourant = *it;
valeurX =pointCourant.getX() + translationX;
valeurY =pointCourant.getY() + translationY;
pointCourant.setX(valeurX);
pointCourant.setY(valeurY);
*it = pointCourant;
}
}
void Polygone::homothetie(const Point & p, double rapport)
{
vector<Point>::iterator it;
Point pointCourant;
double distPX, distPY;
for (it = listesPoints.begin(); it != listesPoints.end(); it++) {
pointCourant = *it;
distPX = pointCourant.getX() - p.getX();
distPX = abs(distPX);
distPY = pointCourant.getY() - p.getY();
distPY = abs(distPY);
pointCourant.setX(p.getX() + (distPX*rapport));
pointCourant.setY(p.getY() + (distPY*rapport));
*it = pointCourant;
}
}
void Polygone::rotation(const Point & p, double angle)
{
vector<Point>::iterator it;
Point pointCourant;
double distPX, distPY, angleRad, distDeplX, distDeplY;
for (it = listesPoints.begin(); it != listesPoints.end(); it++) {
pointCourant = *it;
// Calcul des distances entre le centre de rotation et le centre du cercle faire tourner
distPX = pointCourant.getX() - p.getX();
distPX = abs(distPX);
distPY = pointCourant.getY() - p.getY();
distPY = abs(distPY);
// Conversion de l'angle en radians
angleRad = angle * (3.141592 / 180);
// Calcul de la distance entre le nouvel emplacement du point aprs rotation et le centre de rotation
distDeplX = cos(angleRad)*distPX - sin(angleRad)*distPY;
distDeplY = sin(angleRad)*distPX + cos(angleRad)*distPY;
// On met les coordonnes jour
pointCourant.setX(p.getX() + distDeplX);
pointCourant.setY(p.getY() + distDeplY);
*it = pointCourant;
}
}
double Polygone::calculAire()
{
// Application de la mthode de https://fr.wikihow.com/calculer-la-surface-d%27un-polygone #3
vector<Point>::iterator itXFirst;
vector<Point>::iterator itYFirst;
Point pointCourantX, pointCourantY, pointSuivantX, pointSuivantY;
double xFirst = 0, yFirst = 0, aireGlobale = 0;
itXFirst = listesPoints.begin();
itYFirst = listesPoints.begin();
while (itXFirst != listesPoints.end()) {
pointCourantX = *itXFirst;
pointCourantY = *itYFirst;
itXFirst++;
itYFirst++;
if (itXFirst != listesPoints.end())
{
pointSuivantX = *itXFirst;
}
if (itYFirst != listesPoints.end())
{
pointSuivantY = *itYFirst;
}
xFirst += (pointCourantX.getX()*pointSuivantY.getY());
yFirst += (pointCourantY.getY()*pointSuivantX.getX());
}
xFirst = abs(xFirst);
yFirst = abs(yFirst);
aireGlobale = (yFirst - xFirst) / 2;
return aireGlobale;
}
void Polygone::ajoutePoint(Point & p)
{
//tester s'il existe deja
listesPoints.push_back(p);
}
Point Polygone::operator[](int pos) const
{
return listesPoints[pos];
}
Polygone * Polygone::clone() const
{
return new Polygone(*this);
}
| true |
a32f867cff7d4b3526e52c2ddcbb47c743f86a3a | C++ | raywhz/Stack-and-Queue | /07 Stack infix to postfix.cpp | UTF-8 | 2,383 | 3.84375 | 4 | [] | no_license | //
// 07 Stack infix to postfix.cpp
// (a+b)*(c+d) == ab+cd+*
// Stack and Queue
//
// Created by Haozhou Wu on 10/2/17.
// Copyright © 2017 Haozhou Wu. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// function to convert infix to postfix
string in2post(string exp);
// functiont to verify whether it is an numeric operand
bool isOperand(char mychar);
// function to verify whether it is an operator
bool isOperator(char mychar);
// function to verify the precendence
// if op1 has higher precendence, return 1
bool precendence(char op1, char op2);
int main(){
string mystring;
cout << "Enter a string: " << endl;
getline(cin, mystring);
string postfix = in2post(mystring);
cout << "Postfix is: " << postfix << endl;
return 0;
}
bool isOperator(char mychar){
if (mychar =='+' || mychar =='-' || mychar =='*' || mychar =='/')
return true;
return false;
}
bool isOperand(char C){
if (C>='0' && C<='9')
return true;
if (C>='a' && C<='z')
return true;
if (C>='A' && C<='Z')
return true;
return false;
}
string in2post(string exp){
stack<char> S;
string postfix = "";
for(int i = 0; i < exp.length(); i++){
if(exp[i] == ' ' || exp[i] == ',')
continue;
else if(isOperator(exp[i])){
while(!S.empty() && S.top()!='(' && precendence(S.top(), exp[i])){
postfix += exp[i];
S.pop();
}
S.push(exp[i]);
}
else if(isOperand(exp[i])){
postfix += exp[i];
}
else if(exp[i] == '(')
S.push(exp[i]);
else if(exp[i] == ')'){
while(!S.empty() && S.top() != '('){
postfix += S.top();
S.pop();
}
S.pop(); // pop the opening paretheses
}
}
while(!S.empty()){
postfix += S.top();
S.pop();
}
return postfix;
}
int getWeight(char mychar){
if(mychar == '+' || mychar == '-')
return 1;
if(mychar == '*' || mychar == '/')
return 2;
return -1;
};
bool precendence(char op1, char op2){
int weight1 = getWeight(op1);
int weight2 = getWeight(op2);
return weight1 > weight2? true:false;
}
| true |
8102645f7402f0d6521ac098c893290b59659311 | C++ | raghumdani/typocoder | /Solutions/432.cpp | UTF-8 | 416 | 3.0625 | 3 | [] | no_license | ///a(n) = (1+a(floor(n/2))) mod 3.
#include<bits/stdc++.h>
using namespace std ;
long long x ;
int solve(long long int i)
{
if(i == 0 )
return 0 ;
else
{
return((1 + solve(floor(i/2)))%3) ;
}
}
int main()
{
int g ;
cin>>g;
while(g--)
{
cin>>x;
int ans = solve(x) ;
if(ans!= 0)
cout<<"Alice\n";
else
cout<<"Bob\n";
}
return 0;
} | true |
ae5b970c3180f4cf118259d7cd8223e1ad43ad60 | C++ | ESdove/Cpp-syntax-analysis | /47-类模板/47-类模板/Array.hpp | UTF-8 | 1,875 | 3.984375 | 4 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
using namespace std;
template <typename Item>
class Array
{
friend ostream &operator<<<>(ostream &, const Array<Item> &);
// 用于指向首元素
Item *m_data;
// 元素个数
int m_size;
// 容量
int m_capacity;
void checkIndex(int index);
public:
Array(int capacity = 0);
~Array();
void add(Item value);
void remove(int index);
void insert(int index, Item value);
Item get(int index);
int size();
Item operator[](int index);
};
template <typename Item>
Array<Item>::Array(int capacity)
{
m_capacity = (capacity > 0) ? capacity : 10;
// 申请堆空间
m_data = new Item[m_capacity];
}
template <typename Item>
Array<Item>::~Array()
{
if (m_data == NULL) return;
delete[] m_data;
}
template <typename Item>
void Array<Item>::checkIndex(int index)
{
if (index < 0 || index >= m_size)
{
// 报错:抛异常
throw "数组下标越界";
}
}
template <typename Item>
void Array<Item>::add(Item value)
{
if (m_size == m_capacity)
{
// 扩容
/*
1.申请一块更大的新空间
2.将旧空间的数据拷贝到新空间
3.释放旧空间
*/
cout << "空间不够" << endl;
return;
}
m_data[m_size++] = value;
}
template <typename Item>
void Array<Item>::remove(int index)
{
checkIndex(index);
}
template <typename Item>
void Array<Item>::insert(int index, Item value)
{
}
template <typename Item>
Item Array<Item>::get(int index)
{
checkIndex(index);
return m_data[index];
}
template <typename Item>
int Array<Item>::size()
{
return m_size;
}
template <typename Item>
Item Array<Item>::operator[](int index)
{
return get(index);
}
template <typename Item>
ostream &operator<<<>(ostream &cout, const Array<Item> &array)
{
cout << "[";
for (int i = 0; i < array.m_size; i++)
{
if (i != 0)
{
cout << ", ";
}
cout << array.m_data[i];
}
return cout << "]";
} | true |
6467bb91c052cef22e49d315fa02c3b83e88ca5f | C++ | junwang-nju/mysimulator | /include/new/pdb/atom/position/interface.h | UTF-8 | 621 | 2.5625 | 3 | [] | no_license |
#ifndef _PDB_Atom_Position_Interface_H_
#define _PDB_Atom_Position_Interface_H_
namespace mysimulator {
struct PDBAtomPosition {
public:
typedef PDBAtomPosition Type;
double X,Y,Z;
PDBAtomPosition() : X(0), Y(0), Z(0) {}
~PDBAtomPosition() { clearData(); }
void clearData() { X=Y=Z=0.; }
bool isvalid() const { return true; }
private:
PDBAtomPosition(const Type&) {}
Type& operator=(const Type&) { return *this; }
};
void release(PDBAtomPosition& P) { P.clearData(); }
bool IsValid(const PDBAtomPosition& P) { return P.isvalid();}
}
#endif
| true |
32b5632e35e1a1098d51d109457510ed075f5afa | C++ | Shiiiin/cpp | /baekjoon/problem1259.cpp | UTF-8 | 913 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
string n;
while(true){
cin >> n;
if(n == "0") break;
int split = n.length()/2;
if(n.length() %2 == 0){
string left = n.substr(0, split);
string right = n.substr(split, n.length());
reverse(right.begin(), right.end());
if( left == right ){
cout << "yes" << endl;
}else{
cout << "no" << endl;
}
}else{
string left = n.substr(0, split);
string right = n.substr(split+1, n.length());
reverse(right.begin(), right.end());
if( left == right ){
cout << "yes" << endl;
}else{
cout << "no" << endl;
}
}
}
return 0;
} | true |
85647929a6b67e583c997ee4d1b3dc63172acafb | C++ | jincaoawei/Simple-Simulator | /Force/AngularSpringForce.h | UTF-8 | 462 | 2.890625 | 3 | [] | no_license | #pragma once
#include "Force.h"
class AngularSpringForce : public Force{
public:
AngularSpringForce(Particle* p1, Particle* p2, Particle* p3, double angle, double ks, double kd);
void draw() override;
void update();
private:
Particle * const m_p1; // particle 1
Particle * const m_p2; // particle 2
Particle * const m_p3; // particle 3
double const m_angle; // rest angle
double const m_ks, m_kd; // spring strength constants
};
| true |
ec6b385e9ae86023bb0ce0a2914c2bc2a7da7bb2 | C++ | muellesi/PSE_2018 | /PSE_2018_Gruppe1/src/test/test.cpp | UTF-8 | 354 | 2.5625 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "../Logging.hpp"
TEST(EmptyTest, TrueAndFalse)
{
bool b = true;
EXPECT_EQ(b, true);
EXPECT_NE(b, false);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
// When testing, we want the maximum available log output
Logging::setMaxLevel(DIAG_VERBOSE);
return RUN_ALL_TESTS();
}
| true |
d4a1e86a30848b2eebd444dfa97c572f9b6c01fe | C++ | MicrosoftDocs/cpp-docs | /docs/mfc/codesnippet/CPP/cstring-formatting-and-message-box-display_1.cpp | UTF-8 | 1,250 | 3.28125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | // The following example extracts a series of name, value pairs from a
// given source string:
// Input string consisting of a number of name, value pairs
LPCTSTR lpszSource = _T("\"Name\"=\"John Smith\"\n")
_T("\"Company\"=\"Contoso, Ltd\"\n\"Salary\"=\"25,000\"");
CString strNameValue; // an individual name, value pair
int i = 0; // substring index to extract
while (AfxExtractSubString(strNameValue, lpszSource, i))
{
// Prepare to move to the next substring
i++;
CString strName, strValue; // individual name and value elements
// Attempt to extract the name element from the pair
if (!AfxExtractSubString(strName, strNameValue, 0, _T('=')))
{
// Pass an error message to the debugger for display
OutputDebugString(_T("Error extracting name\r\n"));
continue;
}
// Attempt to extract the value element from the pair
if (!AfxExtractSubString(strValue, strNameValue, 1, _T('=')))
{
// Pass an error message to the debugger for display
OutputDebugString(_T("Error extracting value element\r\n"));
continue;
}
// Pass the name, value pair to the debugger for display
CString strOutput = strName + _T(" equals ") + strValue + _T("\r\n");
OutputDebugString(strOutput);
} | true |