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 |
---|---|---|---|---|---|---|---|---|---|---|---|
96248b8fc51fb044f60529f1326a431c7e442438
|
C++
|
GritBear/MuSee
|
/itunesvisualswindowssdk - muSee/CreationCore.h
|
UTF-8
| 2,072 | 2.59375 | 3 |
[] |
no_license
|
/*This is the art creation core
It creates magical art experience through smart probabilistic model
It collects all the objects and related parameter, then assign probability to individual object
It also come with transistion effect core and user drawing core
*/
#pragma once
#include "CreationInterface.h"
#include "AInterface.h"
class CreationCore : CreationInterface{
private:
protected:
vector<float>animationStartingProbability;
vector<float>backgroundProbability;
vector<float>verticalAnimationStartingProbability;
//current state storage variables
list<int> backgroundIDList;
list<int> backgroundVerticalAnimationIndexList;
vector<list<int>> MelodyAnimationIndexVecList;
public:
CreationCore(DataReader *aReader); //legacy code
CreationCore(CreationCoreComponent *aCreationCoreComponentStruct);
~CreationCore(){Destroy();}
void Destroy();
void Init();
//----------------------
//Update methods
void Update();
//=================================================================================
//Creation Part
//=================================================================================
void NextAnimation(int &Index , vector<float> &probabilityVect);
void NextVerticalAnimation(float percentageIntoTheTheme, int &Index, vector<float> &probabilityVect);
void NextBackground(int &Index);
void AnimationProbUpdate();
void BackgroundProbUpdate();
//=================================================================================
//Transistion Part
//=================================================================================
//=================================================================================
//User Drawing Effect
//=================================================================================
//storage maintenance
void RemoveTooOldEntries(bool Removeall = false);
void TractChange();
//=================================================================================
//Getter and Setter
RhythmicEventCore * GetRhythmicEvenCore(){return theRhythmicEventCore;}
};
| true |
1897563ec5430400dfa131050d07561c448005ff
|
C++
|
inessousacaldas/exercise_opengl
|
/include/game/brick.h
|
UTF-8
| 1,164 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef BRICK_H
#define BRICK_H
// std includes
#include <map>
#include <memory>
// external libs includes
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
// project includes
#include "game/game_object.h"
#include "game/animation.h"
class Brick: public GameObject
{
public:
Brick(const glm::vec2& position,
const glm::vec2& size,
const glm::vec3& color,
Texture* sprite,
bool isSolid = false);
~Brick();
void startAnimation(GLfloat delay); // animates the brick
bool isAnimating(); // checks if any animation is active
// getters
bool isSolid() const { return isSolid_; }
bool isDestroyed() const { return isDestroyed_; }
bool isPrepared() const { return animations_.size() == 0 ? true : false ; }
// setters
void isDestroyed(bool isDestroyed) { isDestroyed_ = isDestroyed; }
void render (const SpriteRenderer& renderer) override;
private:
bool isSolid_;
bool isDestroyed_;
GLfloat lastTime_; // last call for rendering
GLfloat deltaTime_;
std::map<std::string, std::unique_ptr<Animation>> animations_;
glm::vec2 scale_;
};
#endif
| true |
adfc3f68770ee6a6b62e8f358bbb58dff54dd3e8
|
C++
|
UtkarshBhardwaj123/Commit-Ur-Code
|
/Day - 1/ekta.cpp
|
UTF-8
| 538 | 3.0625 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPowerOfTwo (long long x)
{
if(x==0)
return false;
return ((x&(x-1))==0);
}
string canJump(long long N) {
if(isPowerOfTwo(N))
return "YES";
else
return "NO";
}
};
int main(){
int t;
cin>>t;
while(t--){
long long N;
cin>>N;
Solution ob;
cout<<ob.canJump(N)<<endl;
}
return 0;
}
| true |
29e3decc289f921bd7de88fb2a797307938bc5d9
|
C++
|
almoreir/algorithm
|
/cd3/정보올림피아드관련/정보올림피아드관련/문제들/문제/문제모음2/12월13일-4문제/kim/미정/boom/boom.cpp
|
UHC
| 4,547 | 2.796875 | 3 |
[] |
no_license
|
#include <fstream.h>
#include <string.h>
#include <iomanip.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <conio.h>
#define MAXM 200
#define MAXN 200
int M, N; //M y, N x
int Arr[MAXM+1][MAXN+1];
int Dy[MAXM+1][MAXN+1][3]; //ڽ ִ 簢 -> Dy[][0=x, 1=y, 2=簢]
int Set[MAXM+1][MAXN+1]; //üũ .
int Cnt; // ź
#define INFILE "boom.in"
#define OUTFILE "boom.out"
#define MAKEM 200 //y ũ
#define MAKEN 200 //x ũ
#define MAKET 1
int MakeArr[MAXM][MAXN];
void makedata()
{
ofstream out(INFILE);
out << MAKEM << " " << MAKEN << endl;
int i, j, x, y, v;
i=0;
srand(time(NULL));
while(i<MAKET) {
y=rand()%MAKEM+1;
x=rand()%MAKEN+1;
if(MakeArr[y][x]==1) continue;
MakeArr[y][x]=1;
i++;
}
for(i=1; i<=MAKEM; i++) {
for(j=1; j<=MAKEN; j++) {
v=(MakeArr[i][j]==0)? 1 : 0;
if(j!=1) out << " ";
out << v;
}
out << endl;
}
}
//̳
void printDy()
{
int i,j;
for(i=1; i<=M; i++) {
for(j=1; j<=N; j++) {
cout << setw(3) << Arr[i][j];
}
cout << endl;
}
cout << endl;
for(i=1; i<=M; i++) {
for(j=1; j<=N; j++) {
cout << setw(3) << Dy[i][j][2];
}
cout << endl;
}
cout << endl;
cout << "--------------------------" << endl;
}
//迭
int printcnt;
int printSet[MAXM+1][MAXN+1];
void print()
{
int i,j;
for(i=1; i<=M; i++) {
for(j=1; j<=N; j++) {
if(printSet[i][j]==1) {
cout << setw(3) << "*";
} else {
cout << setw(3) << Set[i][j];
}
printSet[i][j]=0;
}
cout << endl;
}
cout << endl;
//getch();
printcnt=0;
}
//ź ڸ 1
void putting(int boomy, int boomx, int size)
{
int i,j, sx, sy;
sy=boomy;
for(i=0; i<size; i++) {
sx=boomx;
for(j=0; j<size; j++) {
Set[sy][sx]++;
printSet[sy][sx]=printcnt+1;
sx--;
}
sy--;
}
}
//ڽ ġ ϴ ִ ū 簢 ã
//ź ߸, ź ڸ Set[]ǥ 1 .
void setting(int y, int x)
{
int size, pos, startx, starty;
int posx, posy, line, linesize;
int i,j, sx, sy;
int cnt, max, boomx, boomy;
//if(y==6 && x==10) {
// int a=7;
//}
//3¥ 5¥ ź .
for(size=5; size>1; size-=2) {
//size ٸŭ ̵.
startx=x+(size-1);
starty=y+(size-1);
max=0;
for(line=0; line<=size; line++) {
if(line==size) {
linesize=size-1;
posx=startx-1;
posy=y;
} else {
linesize=line+1;
posx=startx;
posy=starty-line;
}
for(pos=0; pos<linesize; pos++) {
if(posy <= M && posx <= N) {
// = ź .
if(Dy[posy][posx][2] >= size) {
sy=posy;
cnt=0;
for(i=0; i<size; i++) {
sx=posx;
for(j=0; j<size; j++) {
if(Set[sy][sx]==0) {
cnt++;
}
sx--;
}
sy--;
}
if(max < cnt) {
max=cnt;
boomx=posx;
boomy=posy;
if(max==size*size) {
putting(boomy, boomx, size);
return;
}
}
//return;
}
}
posx--;
posy++;
}
}
//ĽŲ , max 0 ƴϸ,
// ܰ Ž ߴ.
//ֳϸ, Ľų ִٸ, ū ĽŰ ϴϱ.
if(max!=0) {
putting(boomy, boomx, size);
}
}
// ó 1¥ ź.
Set[y][x]++;
printSet[y][x]=printcnt+1;
}
int min(int a, int b, int c)
{
if(a < b) {
if(a < c) {
return a;
} else {
return c;
}
} else {
if(b < c) {
return b;
} else {
return c;
}
}
}
void boom()
{
int i,j;
ifstream in(INFILE);
in >> M >> N;
for(i=1; i<=M; i++) {
for(j=1; j<=N; j++) {
in >> Arr[i][j];
}
}
//ڽ ϸ鼭 ū 簢
for(i=1; i<=M; i++) {
for(j=1; j<=N; j++) {
if(Arr[i][j]==0) {
Dy[i][j][0]=0;
Dy[i][j][1]=0;
Dy[i][j][2]=0;
} else {
//xǥ
Dy[i][j][0]=Dy[i][j-1][0]+1;
//yǥ
Dy[i][j][1]=Dy[i-1][j][1]+1;
//簢
Dy[i][j][2]=min(Dy[i][j][0], Dy[i][j][1], Dy[i-1][j-1][2]+1);
}
}
}
//printDy();
for(i=1; i<=M; i++) {
for(j=1; j<=N; j++) {
if( Set[i][j]==0 && Arr[i][j]==1 ) {
setting(i,j);
Cnt++;
print();
cout << Cnt << endl;
getch();
}
}
}
ofstream out(OUTFILE);
out << Cnt;
}
void main()
{
//makedata();
boom();
}
| true |
d79e252f5329136e66a5f873e035cb2d394d1932
|
C++
|
onikolas/solatlong
|
/src/envmaker.cpp
|
UTF-8
| 3,180 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include "exr.h"
using namespace std;
const float PI = 3.14159265358979323846;
int main(int argc, char** argv)
{
if(argc < 4)
{
cout << "\n Create a latitude longitude HDR environemnt map from a fisheye HDR image \n";
cout << " Usage: envmaker [fisheye image] [diameter] [focal length] [center x] [center y] [width] [latlong image]\n\n";
cout << " [fisheye image] Image to process\n";
cout << " [diameter] Diameter of the image circle in pixels\n";
cout << " [focal length] The focal length. Enter -1 if not known\n";
cout << " [center x] Center of the image circle\n";
cout << " [center y] \n";
cout << " [width] Width of the latlong to be created. Height is set to width/2)\n";
cout << " [latlong image] Filename of the latlong image\n\n";
return -1;
}
int centerx, centery;
int latlong_w, latlong_h;
int diameter = atoi(argv[2]);
float camera_f = atof(argv[3]);
if(camera_f == -1)
{
cout << "Finding the focal length from the diameter not yet implemented\n";
return -1;
}
//read the fisheye exr
fRGB *fisheye, *latlong;
int w,h;
ReadEXR(argv[1], 1, fisheye, w, h);
if(argc >= 6)
{
centerx = atoi(argv[4]);
centery = atoi(argv[5]);
}
else
{
centerx = w/2;
centery = h/2;
}
if(argc >=7)
{
latlong_w = atoi(argv[6]);
latlong_h = latlong_w/2;
}
else
{
cout << "Setting latlong image height to diameter/2" << endl;
latlong_h = diameter/2;
latlong_w = latlong_h*2;
}
if(latlong_h > diameter)
cout << "Warning: width > diameter. This will result in upscaling\n";
latlong = new fRGB[latlong_w*latlong_h];
//initialize to black
for(int i=0; i<latlong_w*latlong_h; i++)
latlong[i] = fRGB(0,0,0);
//go over the pixels of the new image
for(int i=0 ; i<=latlong_h/2; i++)
{
for(int j=0; j<latlong_w; j++)
{
float theta = (i*PI)/latlong_h;
float phi = (j*2*PI)/latlong_w;
//find pixel on fisheye image corresponding to i,j (theta,phi)
//Using mapping function R = 2*f*sin(theta/2) (equisolid) for Sigma 4.5mm F2.8 EX DC HSM Circular Fisheye
//Other lenses can be added later if needed
float R = 2 * camera_f * sin(theta/2); //this R is in mm because f is in mm
float maxR = 2 * camera_f * sin(PI/4); //max theta = 90
int pixelR = (R/maxR) * diameter/2; //R in pixels
int x = pixelR * cos(phi) + centerx;
int y = pixelR * sin(phi) + centery;
//asuming that the image is a perfect semisphere (equisolid is ?)
//int x = (diameter/2) * sin(theta) * cos(phi) + centerx;
//int y = (diameter/2) * sin(theta) * sin(phi) + centery;
for(int a=-1; a<2; a++)
for(int b=-1; b<2; b++)
latlong[i*latlong_w+j] += fisheye[(y+a)*w+x+b];
latlong[i*latlong_w+j] = latlong[i*latlong_w+j]/9;
//latlong[i*latlong_w+j] = fisheye[y*w+x];
}
}
string filename;
if(argc == 8)
filename = argv[7];
else
{
//add .latlong to the input filename
filename= argv[1];
int dot = filename.find(".exr");
filename = filename.substr(0, dot);
filename += ".latlong.exr";
}
WriteEXR(filename, latlong, latlong_w, latlong_h);
return 0;
}
| true |
699502993da4039053a15842a915b5bc22364977
|
C++
|
davschne/accelerated-cpp
|
/ch14/Handle.h
|
UTF-8
| 1,179 | 3.3125 | 3 |
[] |
no_license
|
#ifndef HANDLE_H
#define HANDLE_H
// 14.1.1/255
// handle that manages memory for polymorphic object
// copying a handle copies the underlying object
template<class T>
class Handle {
public:
Handle(): p {nullptr} { }
Handle(const Handle& s):
p {s.p ? s.p->clone() : nullptr}
{ }
// assignment copies the underlying object
Handle& operator=(const Handle& rhs) {
if (&rhs != this) {
delete p;
p = rhs.p ? rhs.p->clone() : 0;
}
return *this;
}
Handle(Handle&& s): p {s.p} {
s.p = nullptr;
}
Handle& operator=(Handle&& rhs) {
std::swap(p, rhs.p);
return *this;
}
~Handle() { delete p; }
Handle(T* t): p {t} { }
// is the handle bound to an object?
operator bool() const { return p; }
// get the object (as ref)
T& operator*() const {
if (p) {
return *p;
}
throw runtime_error("unbound Handle");
}
// get the object (as ptr)
T* operator->() const {
if (p) {
return p;
}
throw runtime_error("unbound Handle");
}
private:
T* p;
};
#endif
| true |
8e5b39c3f19d1b9776b6e99e26504080cc7628d5
|
C++
|
davega-code/Algorithms
|
/Strings/Problems/CodChf_ShiftTheString.cpp
|
UTF-8
| 1,458 | 3.234375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
vector <int> Build_Failure(string pattern)
{
vector <int> F(pattern.size()+1);
F[0] = F[1] = 0; // Empty string and first preffix are always 0
for(int i = 2 ; i <= pattern.size(); i++)
{
int j = F[i - 1]; // lets check if we can expand from the previous index of the partial match
while(true)
{
if(pattern[j] == pattern[i -1]) // if our next character to match matches the first character of the suffix
{ // then we haven found another common prefix/suffix
F[i] = j + 1;
break;
}
if(j == 0) //if j still 0 that means that there wasn't a match at all
{
F[i] = 0;
break;
}
j = F[j]; // lets check the next possible partial match to see if we can expand that one
}
}
return F;
}
int KMP(string text, string patttern) // only counts ocurrrences, modify to obtain locations (easy come on)
{
vector <int> F = Build_Failure(patttern);
int count = 0;
int state = 0;
int index = 0;
int res = 0;
int pos = 0;
bool flag = false;
while(index < text.size())
{
if(text[index] == patttern[state] )
{
state++;
index++;
if(res < state)
{
res = state;
pos = index-state;
//cout<<res<<' '<<pos<<endl;
}
if(state == patttern.size()) count++;
}
else if( state > 0) state = F[state];
else index++;
}
return pos;
}
int main()
{
int n;
cin>>n;
string a,b;
cin>>a>>b;
b = b+b;
cout<<KMP(b,a)<<endl;
return 0;
}
| true |
ca6f0bf296486640a439b3a6f444dde3e0f8400d
|
C++
|
wiwitrifai/competitive-programming
|
/hackerearth/july-circuits-19/tiredness.cpp
|
UTF-8
| 3,929 | 2.75 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
struct point {
int x, y;
point(int x = 0, int y = 0) : x(x), y(y) {};
bool operator==(point p) const { return x == p.x && y == p.y; }
bool operator<(point p) const { return y == p.y ? x < p.x : y < p.y; }
void read() {
scanf("%d %d", &x, &y);
}
};
ostream& operator<<(ostream& os, point p) {
return os << "(" << p.x << "," << p.y << ")";
}
long long dist(point a, point b) {
return abs(a.x - b.x) + abs(a.y - b.y);
}
point nearest(point p, point recA, point recB) {
vector<point> candidate;
if (recA.x <= p.x && p.x <= recB.x && recA.y <= p.y && p.y <= recB.y)
return p;
if (recA.x <= p.x && p.x <= recB.x) {
candidate.push_back(point(p.x, recA.y));
candidate.push_back(point(p.x, recB.y));
}
if (recA.y <= p.y && p.y <= recB.y) {
candidate.push_back(point(recA.x, p.y));
candidate.push_back(point(recB.x, p.y));
}
candidate.push_back(recA);
candidate.push_back(recB);
candidate.push_back(point(recA.x, recB.y));
candidate.push_back(point(recB.x, recA.y));
point ret = candidate[0];
long long best = dist(ret, p);
for (point c : candidate) {
long long cur = dist(c, p);
if (cur < best) {
best = cur;
ret = c;
}
}
return ret;
}
vector<tuple<int, point, point>> newpaths;
void set_path(int id, tuple<int, point, point> entry) {
if (id >= (int)newpaths.size())
newpaths.push_back(entry);
else
newpaths[id] = entry;
}
int main() {
auto startclock = clock();
int n, d;
scanf("%d %d", &n, &d);
vector<tuple<int, point, point>> canopies(n+1);
for (int i = 0; i <= n; ++i) {
point a, b;
int cost;
a.read();
b.read();
if (i) {
if (a.x > b.x)
swap(a.x, b.x);
if (a.y > b.y)
swap(a.y, b.y);
}
scanf("%d", &cost);
canopies[i] = make_tuple(cost, a, b);
}
vector<tuple<int, point, point>> paths;
paths.emplace_back(canopies[0]);
vector<int> ids(n);
iota(ids.begin(), ids.end(), 1);
sort(ids.begin(), ids.end(), [&](int l, int r) {
return get<0>(canopies[l]) < get<0>(canopies[r]);
});
get<0>(paths[0]) = 0;
long long cur = dist(get<1>(canopies[0]), get<2>(canopies[0])) * get<0>(canopies[0]) + d;
for (int i : ids) {
if ((double)(clock() - startclock) / CLOCKS_PER_SEC > 4.8)
break;
int cost;
point a, b;
tie(cost, a, b) = canopies[i];
int iter = 0;
int sz = (int)paths.size();
for (auto & path : paths) {
point p, q;
int c;
tie(c, p, q) = path;
int id = c;
c = get<0>(canopies[c]);
long long changes = - (1LL * dist(p, q) * c + d);
point f = nearest(p, a, b), g = nearest(q, a, b);
changes += (dist(p, f) + dist(g, q)) * cost + dist(f, g) * c + d;
int cnt = 0;
if (!(f == p))
changes += d, ++cnt;
if (!(g == q))
changes += d, ++cnt;
if (changes < 0 && sz + cnt <= int(1e5)) {
if (!(f == p))
set_path(iter++, make_tuple(id, p, f));
set_path(iter++, make_tuple(i, f, g));
if (!(g == q))
set_path(iter++, make_tuple(id, g, q));
cur += changes;
sz += cnt;
}
else
set_path(iter++, path);
}
int pos = 0;
cur = 0;
for (int j = 0; j < iter;) {
int k = j, can = get<0>(newpaths[j]);
while (k < iter && get<0>(newpaths[k]) == can) ++k;
point a = get<1>(newpaths[j]), b = get<2>(newpaths[k-1]);
if (paths.size() <= pos) {
paths.emplace_back(can, a, b);
}
else
paths[pos] = make_tuple(can, a, b);
++pos;
cur += dist(a, b) * get<0>(canopies[can]) + d;
j = k;
}
if (paths.size() > pos)
paths.resize(pos);
}
printf("%d\n", (int)paths.size());
for (auto & path : paths) {
point p, q;
int c;
tie(c, p, q) = path;
printf("%d %d %d %d %d\n", p.x, p.y, q.x, q.y, c);
}
return 0;
}
| true |
15e53d47495aa6d7240629491a257d746c533533
|
C++
|
KeiHasegawa/ISO_IEC_14882
|
/12_Special_member_functions/1_Constructors/1_ok/test001.cpp
|
UTF-8
| 520 | 4 | 4 |
[] |
no_license
|
/*
* A functional notation type conversion (5.2.3) can be used to create new
* objects of its type. [Note: The syntax looks like an explicit call of the
* constructor.]
*/
#include <stdio.h>
struct complex {
double re;
double im;
complex(double r, double i) : re(r), im(i) {}
};
void cprint(const complex&);
int main()
{
complex zz = complex(1,2.3);
cprint( complex(7.8,1.2) );
return 0;
}
void cprint(const complex& c)
{
printf("c.re = %f, c.im = %f\n", c.re, c.im);
}
| true |
33d3f746a308fe2c3de27f7ae940879a4b914c87
|
C++
|
omkarlenka/leetcode
|
/fruit_into_basket.cpp
|
UTF-8
| 1,120 | 3.046875 | 3 |
[] |
no_license
|
//
// fruit_into_basket.cpp
//
// Created by omlenka on 12/04/20.
// Copyright © 2020 omkar lenka. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int totalFruit(vector<int>& tree)
{
int max_fruits = 1;
int same_res = 1, diff_val = -1, diff_res = 1;
for(int i = tree.size()-2;i>=0;i--)
{
if(tree[i] != tree[i+1] && tree[i] != diff_val)
{
diff_res = same_res+1;
diff_val = tree[i+1];
same_res = 1;
}
else if(tree[i] == diff_val)
{
same_res = 1;
diff_val = tree[i+1];
diff_res += 1;
}
else //tree[i] == tree[i+1];
{
same_res += 1;
diff_res += 1;
}
if(same_res > max_fruits)
max_fruits = same_res;
if(diff_res > max_fruits)
max_fruits = diff_res;
}
return max_fruits;
}
int main()
{
int n;
cin >> n;
vector<int> v(n);
for(int i = 0;i<n;i++)
cin >> v[i];
cout << totalFruit(v);
return 0;
}
| true |
6cdee78fa1ab1131eb2fa0874954c1b5dbd14458
|
C++
|
Dieg657/GoS_Version2
|
/pycalculos.h
|
UTF-8
| 4,193 | 2.65625 | 3 |
[] |
no_license
|
#ifndef PYCALCULOS_H
#define PYCALCULOS_H
#include "header.hpp"
class PyC{
private:
PyObject *moduleMainString;
PyObject *moduleMain;
PyObject *func;
PyObject *args;
PyObject *result;
public:
PyC();
void desalocarPy();
double calcularBloqueio(double erlang, long slot);
double calcularProbEspera(double erlang, long slot);
double calcularOcupacaoVia(double erlang, long slot);
double faixasRequeridas(long faixas, long fator);
double nivelServico(double eC, double erlang, long slot, long tempoDesejado, long tempoSimulado);
~PyC();
};
#endif // PYCALCULOS_H
PyC::PyC()
{
Py_Initialize();
moduleMainString = PyString_FromString("__main__");
moduleMain = PyImport_Import(moduleMainString);
PyRun_SimpleString(
"import math \n"\
"def mul(a, b): \n"\
" return a * b \n"\
" \n"\
"def erlangB(E, M): \n"\
" InversoProbBloqueio = 1.0 \n"\
" for i in range(1, M): \n"\
" InversoProbBloqueio = 1.0 + ((i / E) * InversoProbBloqueio) \n"\
" Bloqueio = 1.0 / InversoProbBloqueio \n"\
" return Bloqueio * 100 \n"\
" \n"\
"def erlangC(E, M): \n"\
" ePower = E**M \n"\
" mFactorial = math.factorial(M) \n"\
" X = ePower / mFactorial * (M/(M-E)) \n"\
" Y = 0 \n"\
" for i in range(0, M): \n"\
" a = E**i \n"\
" b = math.factorial(i) \n"\
" Y = Y + (a/b) \n"\
" return (X / ((X+Y))) * 100 \n"\
" \n"\
"def ocupacaoVia(E, M): \n"\
" return (E/M) * 100 \n"\
" \n"\
"def faixasRequeridas(M, Fator): \n"\
" return (M/(1 - (Fator/100))) \n"\
" \n"\
"def nivelServico(B, M , E, ANT, MediaDuracao): \n"\
" C = -((M-E) * ANT/MediaDuracao) \n"\
" C = math.pow(math.e, C) \n"\
" Resultado = 1 - (B * C) \n"\
" return Resultado * 100 \n"\
);
}
void PyC::desalocarPy()
{
Py_DECREF(func);
Py_DECREF(args);
Py_DECREF(result);
}
double PyC::calcularBloqueio(double erlang, long slot)
{
PyObject *func = PyObject_GetAttrString(moduleMain, "erlangB");
PyObject *args = PyTuple_Pack(2, PyFloat_FromDouble(erlang), PyLong_FromDouble(slot));
PyObject *result = PyObject_CallObject(func, args);
return PyFloat_AsDouble(result);
}
double PyC::calcularProbEspera(double erlang, long slot)
{
func = PyObject_GetAttrString(moduleMain, "erlangC");
args = PyTuple_Pack(2, PyFloat_FromDouble(erlang), PyLong_FromDouble(slot));
result = PyObject_CallObject(func, args);
return PyFloat_AsDouble(result);
}
PyC::~PyC()
{
Py_Finalize();
}
| true |
73ce96b23150ea032b6f95797e7c22ce11abd8ba
|
C++
|
ootakakazuki/atcoder_practice
|
/pra/dp_slimes.cpp
|
UTF-8
| 1,191 | 2.71875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
int N; cin >> N;
vector<ll> a(N + 1, 0);
vector<vector<ll>> dp(N + 1, vector<ll>(N + 1, 0));
for (int i = 0; i < N; i++)
{
int tmp; cin >> tmp;
a[i + 1] = tmp + a[i];
}
for (int w = 2; w <= N; w++)
{
for (int l = 0; l < N - w + 1; l++)
{
int r = l + w;
ll tmp = 1LL<<60;
//long long tmp=9999999999999999LL;
for (int k = l + 1; k < r; k++)
{
tmp = min(tmp, dp[l][k] + dp[k][r]);
// dp[l][r] = min(dp[l][r], dp[l][k] + dp[k][r]) + a[r] - a[l];
}
dp[l][r] = tmp + a[r] - a[l];
cout << "l=" << l << " r=" << r << " " << dp[l][r] << endl;
}
}
cout << dp[0][N] << endl;
}
/*
#include <bits/stdc++.h>
using namespace std;
long long dp[444][444];
vector<long long> sum(1);
int main(){
int N;
cin >> N;
vector<long long> a(N);
for(auto &i:a)cin >> i;
for(int i=0;i<N;i++)sum.push_back(sum[i]+a[i]);
for(int w=2;w<=N;w++){
for(int l=0;l<=N-w;l++){
int r=l+w;
long long tmp=9999999999999999LL;
for(int x=l+1;x<r;x++)tmp=min(tmp,dp[l][x]+dp[x][r]);
dp[l][r]=tmp+sum[r]-sum[l];
}
}
cout << dp[0][N] << endl;
return 0;
}
*/
| true |
79edfb2917fd12e56f511417ebece8ff136738cd
|
C++
|
mane-paata/C-_HPC
|
/student_hw3_src/max_performance.cpp
|
UTF-8
| 411 | 3 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdlib>
#include "Timer.hpp"
using namespace std;
int main(){
size_t N = 1024*1024*1024;
double num1 = random(), num2 = random(), sum = 0.0, time;
Timer T;
T.start();
for (size_t i = 0; i < N; ++i)
sum += num1*num2;
T.stop();
cout << sum << endl;
time = T.elapsed();
cout << "Time elapsed " << time << endl;
cout << "Floating point rate " << N/time << endl;
}
| true |
864ec469e3e3fc5b6fe904da4e0aaf949ccc3147
|
C++
|
Loodwood/SemestralkaPosko
|
/pong/Pong/Ball.h
|
UTF-8
| 2,289 | 3.421875 | 3 |
[] |
no_license
|
#ifndef BALL_H
#define BALL_H
#include "Vec2.h"
enum class CollisionType
{
None,
Top,
Middle,
Bottom,
Left,
Right
};
struct Contact
{
CollisionType type;
float penetration;
};
//definovanoe konstant pre velkost nasej lopticky
const int BALL_WIDTH = 15;
const int BALL_HEIGHT = 15;
const int WINDOW_WIDTH_B = 1280;
const int WINDOW_HEIGHT_B = 720;
class Ball
{
public:
Ball(Vec2 position, Vec2 velocity)
: position(position), velocity(velocity)
{
// pre to ze vsetky atributy v rect su int potrebujeme pretypovanie
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
rect.w = BALL_WIDTH;
rect.h = BALL_HEIGHT;
}
// vzdy sa bude volat pri vykreslovani a pohybe lopticky
void Draw(SDL_Renderer* renderer)
{
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
// metoda sluzi na vykreslenie objektu na obrazovku
SDL_RenderFillRect(renderer,&rect);
}
void CollideWithWall(Contact const& contact)
{
if ((contact.type == CollisionType::Top)
|| (contact.type == CollisionType::Bottom))
{
position.y += contact.penetration;
velocity.y = -velocity.y;
}
else if (contact.type == CollisionType::Left)
{
position.x = WINDOW_WIDTH_B / 2.0f;
position.y = WINDOW_HEIGHT_B / 2.0f;
velocity.x = 1.0f;
velocity.y = 0.75f * 1.0f;
}
else if (contact.type == CollisionType::Right)
{
position.x = WINDOW_WIDTH_B / 2.0f;
position.y = WINDOW_HEIGHT_B / 2.0f;
velocity.x = -1.0f;
velocity.y = 0.75f * 1.0f;
}
}
void CollideWithPaddle(Contact const& contact)
{
position.x += contact.penetration;
velocity.x = -velocity.x;
if (contact.type == CollisionType::Top)
{
velocity.y = -.75f * 1.0f;
}
else if (contact.type == CollisionType::Bottom)
{
velocity.y = 0.75f * 1.0f;
}
}
void Update(float dt)
{
position += velocity * dt;
}
// astribut pre nasu loptu kde sa nachadza
Vec2 position;
// atribut pre pobyh lopticky
Vec2 velocity;
// a SDL na vykreslenie tvaru nasej lopticky
SDL_Rect rect{};
};
#endif /* BALL_H */
| true |
4eb55a6ae01749157748bb9f7863b7f0e9323af5
|
C++
|
orahmad/Mancala
|
/Player.h
|
UTF-8
| 928 | 2.78125 | 3 |
[] |
no_license
|
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
#include <vector>
#include "Board.h"
#include "Side.h"
class Player
{
public:
Player(std::string name);
std::string name() const;
virtual bool isInteractive() const;
virtual int chooseMove(const Board& b, Side s) const = 0;
virtual ~Player();
private:
string m_name;
};
class BadPlayer : public Player
{
public:
BadPlayer(std::string name);
virtual int chooseMove(const Board& b, Side s) const;
virtual ~BadPlayer();
};
class HumanPlayer : public Player
{
public:
HumanPlayer(std::string name);
virtual bool isInteractive() const;
virtual int chooseMove(const Board& b, Side s) const;
virtual ~HumanPlayer();
};
class SmartPlayer : public Player
{
public:
SmartPlayer(std::string name);
virtual int chooseMove(const Board& b, Side s) const;
virtual ~SmartPlayer();
private:
GameTree* m_privr;
};
#endif
| true |
100b083527005954d4b9c51d0bdb2fd8d3a5106c
|
C++
|
HXLLL/xstore
|
/xcache/src/translation_table.hh
|
UTF-8
| 2,426 | 2.625 | 3 |
[] |
no_license
|
#pragma once
#include <vector>
#include "../../deps/r2/src/common.hh"
#include "../../xutils/marshal.hh"
#include "./lib.hh"
namespace xstore {
namespace xcache {
using namespace r2;
// only leaf the 8-bit of the incarnation
const usize kIncarBit = 8;
const usize kIncarMask = bitmask<usize>(kIncarBit);
template<typename EntryType>
struct TT
{
explicit TT(const ::xstore::string_view& s) { this->from_serialize(s); }
TT() = default;
using ET = EntryType;
std::vector<EntryType> entries;
EntryType& operator[](int i) { return entries.at(i); }
auto add(const EntryType& e) { entries.push_back(e); }
auto get_wo_incar(const usize& i) -> EntryType
{
// not implemented
// 1. retrieve the value
auto addr = (*this)[i];
// 2. trim the incarnation
addr = addr >> kIncarBit;
return addr;
}
auto add_w_incar(const EntryType& e, const usize& incar)
{
auto temp = e << kIncarBit;
ASSERT(temp >> kIncarBit == e);
temp |= (incar & kIncarMask);
entries.push_back(temp);
}
auto size() const -> usize { return entries.size(); }
auto mem() const -> usize { return this->size() * sizeof(EntryType); }
auto clear() { entries.clear(); }
/*!
The serialization protocol works as follows:
| num entries | entry 0 | entry 1|, ....
num_entries: u32
*/
auto serialize() const -> std::string
{
std::string res;
res += ::xstore::util::Marshal<u32>::serialize_to(this->size());
for (uint i = 0; i < this->size(); ++i) {
res += ::xstore::util::Marshal<EntryType>::serialize_to(entries[i]);
}
return res;
}
static auto tt_entry_sz() -> usize { return sizeof(EntryType); }
auto tt_sz() -> usize
{
return sizeof(u32) + this->entries.size() * sizeof(EntryType);
}
auto from_serialize(const ::xstore::string_view& d)
{
char* cur_ptr = (char*)(d.data());
ASSERT(d.size() >= sizeof(u32));
u32 n = ::xstore::util::Marshal<u32>::deserialize(cur_ptr, d.size());
ASSERT(d.size() >= sizeof(u32) + n * sizeof(EntryType))
<< d.size() << "; n:" << n;
// ASSERT(n < 2048) << n;
cur_ptr += sizeof(u32);
this->clear();
this->entries.resize(n);
for (uint i = 0; i < n; ++i) {
this->entries[i] =
::xstore::util::Marshal<EntryType>::deserialize(cur_ptr, d.size());
cur_ptr += sizeof(EntryType);
}
}
};
} // namespace xcache
} // namespace xstore
| true |
0b8fcf3f239a72604394807a7ff3e7eddb2e8bd3
|
C++
|
hhland/stl-lab
|
/22/Chapter22_5/main.cpp
|
GB18030
| 654 | 3.40625 | 3 |
[] |
no_license
|
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
void print(int x){
cout << x << " ";
}
int main(void){
vector<int> v1, v2;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
//ӡv1v2
cout << "ǰ, v1=";
for_each(v1.begin(), v1.end(), print);
cout << "v2=";
for_each(v2.begin(), v2.end(), print);
cout << endl;
//v1v2
swap_ranges(v1.begin(), v1.end(), v2.begin());
//ӡv1v2
cout << ", v1=";
for_each(v1.begin(), v1.end(), print);
cout << "v2=";
for_each(v2.begin(), v2.end(), print);
cout << endl;
return 0;
}
| true |
f2d89d15b20509da1f9811a242018da724969874
|
C++
|
tagoro9/Practicas-ETSII
|
/SSI/practica_4/aes/lib/keys/keys.cc
|
UTF-8
| 1,432 | 2.90625 | 3 |
[] |
no_license
|
#include "keys.h"
Keys::Keys(const Bitset key, char MODE) {
//Inicializar la clave
_key = new BitsetMatrix(4,4,key.to_s());
//Generacion de la clave expandida
BitsetMatrix exp_key(4,44);
//Copiar las 4 primeras columnas de la clave
for (int i = 0; i < 4;i++)
exp_key.set_column(i,(_key->get_column(i)));
for (int i(4),j(1); i < exp_key.get_columns(); i++) {
//Si la columna es multiplo de 4
if ((i % 4) == 0) {
//RotWord
exp_key.set_column(i,exp_key.get_column(i-1));
exp_key.rotate(i,1);
//SubBytes
exp_key.set_column(i,AesFunctions::SubBytes(exp_key[i]));
//Xor final
Bitset Xor = ((exp_key.get_column(i)) ^ (exp_key.get_column(i-4)))^ ( Bitset( AesFunctions::padZeros( AesFunctions::int2bin(AesFunctions::RCON[j]),32 ) )) ;
exp_key.set_column(i,Xor);
j++;
}
else {
exp_key.set_column(i,(exp_key[i-1])^(exp_key[i-4]));
}
}
_keys = new BitsetMatrix(exp_key);
}
BitsetMatrix Keys::get_key() const {
return (*_key);
}
BitsetMatrix Keys::get_key(const int i) {
BitsetMatrix result(4,4);
for (int j = 0; j < 4 ; j++) {
result.set_column(j,_keys->get_column(i*(_keys->get_rows())+j));
}
return result;
}
BitsetMatrix Keys::operator[](const int j) const {
//j ha de estar entre 0 y 10
int start = j*4;
int end = start + 4;
string aux;
for (int i = start; i < end; i++) {
aux += (*_keys)[i].to_s();
}
return BitsetMatrix(4,4,aux);
}
Keys::~Keys() {
delete _key;
}
| true |
b82e21943991c20e59e955d8acae346626e7c1dc
|
C++
|
ttzztztz/leetcodeAlgorithms
|
/Lintcode/1445. Delete Characters.cpp
|
UTF-8
| 513 | 3.203125 | 3 |
[] |
no_license
|
class Solution {
public:
/**
* @param s: The string s
* @param t: The string t
* @return: Return if can get the string t
*/
bool canGetString(string &s, string &t) {
// Write your code here
const int n = s.size(), m = t.size();
int ptr1 = 0, ptr2 = 0;
while (ptr2 < m) {
while (ptr1 < n && s[ptr1] != t[ptr2]) ptr1++;
if (ptr1 >= n) return false;
ptr1++, ptr2++;
}
return ptr2 == m;
}
};
| true |
ea5eb5fd8a557aa905504feae0dbf2ae4d4d371f
|
C++
|
ALEHACKsp/fps_spoofer
|
/fps_spoofer/CMem.h
|
UTF-8
| 2,109 | 2.953125 | 3 |
[] |
no_license
|
#pragma once
#include <Windows.h>
#define ASM_JMP 0xE9
#define ASM_NOP 0x90
class CMem
{
public:
template<class T, class U> static void PutSingle(U pMemory, T value);
template<class T, class U, class V> static void Put(U pMemory, V pValue, unsigned long uiLen);
template<class T, class U> static T Get(U pMemory);
template <class T> static BOOL Unprotect(T lpMemory, SIZE_T dwSize, DWORD* pOut = NULL);
template <class T> static void Set(T lpMemory, unsigned char ucByte, size_t uiSize);
template <class T, class U> static void InstallJmp(T address, U proxy, DWORD& jumpback, DWORD dwLen, DWORD jumpbackPos = NULL);
template <class T, class U> static void InstallJmp(T address, U proxy, DWORD dwLen = 5);
static void ApplyJmp(BYTE* pAddress, DWORD dwProxy, DWORD dwLen);
static void Cpy(void* address, const void* src, int size);
static void RedirectCall(int address, void *func);
private:
static DWORD m_dwUnprotectDummy;
};
template <class T, class U>
void CMem::InstallJmp(T address, U proxy, DWORD& jumpback, DWORD dwLen, DWORD jumpbackPos)
{
if (!jumpbackPos)
jumpbackPos = dwLen;
jumpback = (DWORD)address + jumpbackPos;
ApplyJmp((BYTE*)address, (DWORD)proxy, dwLen);
}
template <class T, class U>
static void CMem::InstallJmp(T address, U proxy, DWORD dwLen)
{
return ApplyJmp((BYTE*)address, (DWORD)proxy, dwLen);
}
template<class T, class U>
void CMem::PutSingle(U pMemory, T value)
{
*(T*)pMemory = value;
}
template<class T, class U, class V>
void CMem::Put(U pMemory, V pValue, unsigned long uiLen)
{
for (size_t i = 0; i < uiLen; ++i)
PutSingle<T, T*>((T*)(pMemory)+i, *((T*)(pValue)+i));
}
template<class T, class U>
T CMem::Get(U pMemory)
{
return *(T*)pMemory;
}
template <class T>
BOOL CMem::Unprotect(T lpMemory, SIZE_T dwSize, DWORD* pOut)
{
return VirtualProtect((void*)lpMemory, dwSize, PAGE_EXECUTE_READWRITE, pOut ? pOut : &m_dwUnprotectDummy);
}
template <class T>
void CMem::Set(T lpMemory, unsigned char ucByte, size_t uiSize)
{
memset((void*)lpMemory, ucByte, uiSize);
}
| true |
0f37d004f136bed181e9ae58e97fe223bc47171d
|
C++
|
rcirca/irose
|
/src/lib_util/CDXHPC.H
|
UTF-8
| 896 | 2.671875 | 3 |
[] |
no_license
|
#ifndef _H_CDXHPC
#define _H_CDXHPC
#define WIN32_EXTRA_LEAN
#include <windows.h>
class CDXHPC
{
private :
DWORD m_dwTmpTIME;
DWORD m_dwCheckTIME;
DWORD m_dwLastTIME;
protected:
// counter variables
LARGE_INTEGER m_freq, m_restart;
LARGE_INTEGER m_current, m_excess;
LARGE_INTEGER m_tmpcurrent;
public:
CDXHPC();
virtual ~CDXHPC() {};
// starts the counter
BOOL Start();
// returns the current # of ms since counter was started
DWORD GetValue();
// waits for a specified ms since the counter was started
// note that if its already been that long since it was started
// the function would exit immediately
void Wait(DWORD dwWaitms);
// resets the counter back to zero
DWORD Reset();
DWORD GetCheckTime() { return m_dwCheckTIME; }
DWORD GetCurrentTIME ();
DWORD GetPassTIME () { return ( m_dwCheckTIME - m_dwLastTIME ); }
};
#endif /* #ifndef _H_CDXHPC */
| true |
ccc96daf5d69b976ecd8a41fab2b6c5417766fa1
|
C++
|
SirTorresDev/EDA
|
/1ªParte/NuevosEjercicios/Ejercicio25/Ejercicio25/Source.cpp
|
UTF-8
| 1,138 | 3.046875 | 3 |
[] |
no_license
|
//Roberto Torres Prensa
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int minVectorG(const vector<int>datos, const int i, const int j) {
if (i + 1 >= j) { //Hay 2 elemento
if (datos[i] > datos[j]) {
return datos[j];
}
else {
return datos[i];
}
}
else {
int mitad = (i + j) / 2;
if (datos[mitad] < datos[i]){
return minVectorG(datos, mitad, j);
}
else {
return minVectorG(datos, i, mitad);
}
}
}
//Analisis y justificacion del coste
/*
Costes
*/
void minVector(const vector<int>datos, const int numElementos) {
cout << minVectorG(datos, 0, numElementos) << endl;
}
int main() {
// Para la entrada por fichero.
#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif
// Resolvemos
int numElementos = 0;
// Resolvemos
while (std::cin >> numElementos) {
vector<int> datos(numElementos);
for (int j = 0; j < numElementos; j++) {
cin >> datos[j];
}
minVector(datos, numElementos-1);
}
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
}
| true |
87d9044e125fe021076a60c695fdc8df41f9862c
|
C++
|
Tatyumi/LifeGame
|
/LifeGame/CellManager.h
|
SHIFT_JIS
| 996 | 2.890625 | 3 |
[] |
no_license
|
#pragma once
#include "FieldManager.h"
enum ECellState
{
DEPOPULATION = 1, // ߑa
BORN = 3, // a
DENSE = 4, // ߖ
};
class CCellManager
{
public:
// RXgN^
CCellManager();
//
void Initialize();
// J[\ݒ菈
void SetCursor(CFieldManager* cField);
// J[\ړ
void MoveCursor();
// tB[hɃZ̏Ԃf
void ReflectCellState(CFieldManager* cField);
// אڂ鐶Z̐擾
int GetAdjacenLivesCount(int vecY, int vecX);
// ̐Ɉڍs
void NextGeneration();
// cell̃ANZT
int GetCell(int vecY, int vecX) { return cell[vecY][vecX]; }
void SetCell(int vecY, int vecX, int state) { cell[vecY][vecX] = state; };
private:
// J[\xW
int cursorX;
// J[\yW
int cursorY;
// Z̔zuꏊ
int cell[FIELD_HEIGHT][FIELD_WIDTH];
// ̐̃Z
int nextCell[FIELD_HEIGHT][FIELD_WIDTH];
};
| true |
1224b78532a59f84b90a9e97eadb86d8c24ec8ca
|
C++
|
nad2000/functional-programming-using-cpp
|
/square_values.cpp
|
UTF-8
| 1,889 | 3.1875 | 3 |
[] |
no_license
|
#include <algorithm>
#include <iterator>
#include <vector>
#include <fplus/fplus.hpp>
using namespace std;
typedef std::vector<int> Inst;
int square(int x) {
return x * x;
}
Inst square_vec_goto(const Inst& xs) {
Inst ys;
ys.reserve(xs.size());
auto it = begin(xs);
loopBegin:
if (it == end(xs)) goto loopEnd;
ys.push_back(square(*it));
++it;
goto loopBegin;
loopEnd:
return ys;
}
Inst square_vec_for0(const Inst& xs) {
Inst ys;
ys.reserve(xs.size());
for(auto i=0; i<xs.size(); ++i) ys.push_back(xs[i]);
return ys;
}
Inst square_vec_while(const Inst& xs) {
Inst ys;
ys.reserve(xs.size());
auto it = begin(xs);
while (it != end(xs)) {
ys.push_back(square(*it));
++it;
}
return ys;
}
Inst square_vec_for(const Inst& xs) {
Inst ys;
ys.reserve(xs.size());
for (auto it = begin(xs); it != end(xs); ++it) ys.push_back(square(*it));
return ys;
}
Inst square_vec_range_based_for(const Inst& xs) {
Inst ys;
ys.reserve(xs.size());
for (int x: xs) ys.push_back(square(x));
return ys;
}
// STL provides std_transform
Inst square_vec_std_trsnsform(const Inst& xs) {
Inst ys;
ys.reserve(xs.size());
transform(begin(xs), end(xs), back_inserter(ys), square);
return ys;
}
// This is a higher order function... a function that uses anoter function as an
// input.
template <typename F, typename T> vector<T> transform_vec(F f, const vector<T>& xs) {
vector<T> ys;
ys.reserve(xs.size());
transform(begin(xs), end(xs), back_inserter(ys), f);
return ys;
}
// Maximally readable code:
Inst sqr_transform_vec(const Inst& xs) {
return transform_vec(square, xs);
}
// Usgin fplus:
Inst sqr_fplus_vec(const Inst& xs) {
return fplus::transform(square, xs);
}
int main() {
Inst xs(8192);
//for (auto i = 0; i < 65536; ++i) sqr_fplus_vec(xs);
for (auto i = 0; i < 65536; ++i) square_vec_for0(xs);
// for (auto i = 0; i < 65536; ++i) square_vec_goto(xs);
}
| true |
76dd3666d5c6da9827c6011fb97b145fe4351b77
|
C++
|
TaihuLight/stealthdb
|
/src/enclave/enc_timestamp_ops.cpp
|
UTF-8
| 1,820 | 3.046875 | 3 |
[] |
no_license
|
//
// ENCRYPTED TIMESTAMPS(8 bytes) FUNCTIONs
//
#include "enclave/enclave.h"
#include "enclave/enclave_t.h" /* print_string */
extern sgx_aes_ctr_128bit_key_t p_key;
/* Compare two encrypted timestamps(int64 - 8 bytes) by aes_gcm algorithm
@input: uint8_t array - encrypted source1
size_t - length of encrypted source1 (SGX_AESGCM_IV_SIZE + INT64_LENGTH + SGX_AESGCM_MAC_SIZE = 36)
uint8_t array - encrypted source2
size_t - length of encrypted source2 (SGX_AESGCM_IV_SIZE + INT64_LENGTH + SGX_AESGCM_MAC_SIZE = 36)
uint8_t array - which contains the result 1 (if a > b). -1 (if b > a), 0 (if a == b)
size_t - length of result (TIMESTAMP_LENGTH = 4)
@return:
* SGX_error, if there was an error during decryption
*/
int enc_timestamp_cmp(uint8_t *src1, size_t src1_len, uint8_t *src2, size_t src2_len, uint8_t *result, size_t res_len) {
TIMESTAMP dectm1, dectm2;
int resp, cmp;
uint8_t *src1_decrypted = (uint8_t *)malloc(TIMESTAMP_LENGTH);
uint8_t *src2_decrypted = (uint8_t *)malloc(TIMESTAMP_LENGTH);
resp = decrypt_bytes(src1, src1_len, src1_decrypted, TIMESTAMP_LENGTH);
if (resp != SGX_SUCCESS)
return resp;
resp = decrypt_bytes(src2, src2_len, src2_decrypted, TIMESTAMP_LENGTH);
if (resp != SGX_SUCCESS)
return resp;
memcpy(&dectm1, src1_decrypted, TIMESTAMP_LENGTH);
memcpy(&dectm2, src2_decrypted, TIMESTAMP_LENGTH);
cmp = (dectm1 == dectm2) ? 0 : ((dectm1 < dectm2) ? -1 : 1);
memcpy(result, &cmp, INT32_LENGTH);
memset_s(src1_decrypted, TIMESTAMP_LENGTH, 0, TIMESTAMP_LENGTH);
memset_s(src2_decrypted, TIMESTAMP_LENGTH, 0, TIMESTAMP_LENGTH);
memset_s(&dectm1, TIMESTAMP_LENGTH, 0, TIMESTAMP_LENGTH);
memset_s(&dectm2, TIMESTAMP_LENGTH, 0, TIMESTAMP_LENGTH);
free_allocated_memory(src1_decrypted);
free_allocated_memory(src2_decrypted);
return resp;
}
| true |
c4c86cfb0cbdcd96c20d4e3bd1fda331488a0be8
|
C++
|
takami228/atcoder
|
/exawizards2019/c.cpp
|
UTF-8
| 1,119 | 2.640625 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
int main(){
int n, q;
string s;
cin >> n >> q >> s;
char t[q];
char d[q];
int g[n];
map<char, vector<int> > m;
for(int i = 0; i < q; i++){
cin >> t[i] >> d[i];
}
for(int i = 0; i < n; i++){
g[i] = 1;
}
for(int i = 0; i < s.size(); i++){
m[s.at(i)].push_back(i);
}
for(int i = 0; i < q; i++){
vector<int> v = m[t[i]];
for(int j = 0; j < v.size(); j++){
int tmp = v[j];
if(d[i] == 'L'){
if(tmp == 0){
g[tmp] = 0;
} else {
g[tmp-1]+=g[tmp];
g[tmp] = 0;
}
} else {
if(tmp == n-1){
g[tmp] = 0;
} else {
g[tmp+1]+=g[tmp];
g[tmp] = 0;
}
}
}
}
int ans = 0;
for(int i = 0; i < n; i++){
ans += g[i];
}
cout << ans << endl;
return 0;
}
| true |
5a9fd4cc4a120898b494df7455655f2a771b4328
|
C++
|
abhishekxix/Programs
|
/algorithms/practice.cpp
|
UTF-8
| 1,337 | 3.296875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
class Entity {
private:
int weight;
int profit;
public:
Entity(int weight = 0, int profit = 0)
: weight {weight}, profit {profit}
{}
int get_weight() {
return weight;
}
int get_profit() {
return profit;
}
};
int max_value(int max_weight, std::vector<Entity> &items) {
std::vector<std::vector<int>> maximum(items.size() + 1, std::vector<int>(max_weight + 1));
int max_value {};
int weight {};
for(int i {1}; i <= items.size(); i++) {
for(int j {1}; j <= max_weight; j++) {
max_value = maximum.at(i - 1).at(j);
if(items.at(i -1).get_weight() < j) {
max_value = maximum.at(i - 1).at(j - items.at(i - 1).get_weight()) + items.at(i - 1).get_profit();
maximum.at(i).at(j) = std::max(maximum.at(i).at(j), max_value);
}
}
}
return maximum.at(items.size()).at(max_weight);
}
int main() {
int n {};
int w {};
std::cin >> n >> w;
std::vector<Entity> items;
while(n--) {
int weight {};
int profit {};
std::cin >> weight >> profit;
items.push_back(Entity (weight, profit));
}
std::cout << max_value(w, items) << '\n';
}
| true |
d8cfbc15a6558d26a6359e6ce4a34416025e0d43
|
C++
|
kaulszhang/base
|
/include/util/protocol/rtsp/RtspError.h
|
GB18030
| 11,673 | 2.703125 | 3 |
[] |
no_license
|
// Rtsp.h
#ifndef _UTIL_PROTOCOL_RTSP_ERROR_H_
#define _UTIL_PROTOCOL_RTSP_ERROR_H_
namespace util
{
namespace protocol
{
namespace rtsp_error {
enum errors
{
already_bind = 1, // 1 rtspѾ
not_bind, // 2 rtspѾ
already_open, // 3 rtspѾ
not_open, // 4 rtspδ
busy_work, // 5 rtspڽ
format_error, // 6 rtspͷʽ
continue_ = 100, // Continue
ok = 200, // OK
created = 201, // Created
low_on_storage_space = 250, // Low on Storage Space
multiple_choices = 300, // Multiple Choices
moved_permanently = 301, // Moved Permanently
moved_temporarily = 302, // Moved Temporarily
see_other = 303, // See Other
not_modified = 304, // Not Modified
use_proxy = 305, // Use Proxy
bad_request = 400, // Bad Request
unauthorized = 401, // Unauthorized
payment_required = 402, // Payment Required
forbidden = 403, // Forbidden
not_found = 404, // Not Found
method_not_allowed = 405, // Method Not Allowed
not_acceptable = 406, // Not Acceptable
proxy_authentication_required = 407, // Proxy Authentication Required
request_time_out = 408, // Request Time-out
gone = 410, // Gone
length_required = 411, // Length Required
precondition_failed = 412, // Precondition Failed
request_entity_too_large = 413, // Request Entity Too Large
request_uri_too_large = 414, // Request-URI Too Large
unsupported_media_type = 415, // Unsupported Media Type
parameter_not_understood = 451, // Parameter Not Understood
conference_not_found = 452, // Conference Not Found
not_enough_bandwidth = 453, // Not Enough Bandwidth
session_not_found = 454, // Session Not Found
method_not_valid_in_this_state = 455, // Method Not Valid in This State
header_field_not_valid_for_resource = 456, // Header Field Not Valid for Resource
invalid_range = 457, // Invalid Range
parameter_is_read_only = 458, // Parameter Is Read-Only
aggregate_operation_not_allowed = 459, // Aggregate operation not allowed
only_aggregate_operation_allowed = 460, // Only aggregate operation allowed
unsupported_transport = 461, // Unsupported transport
destination_unreachable = 462, // Destination unreachable
internal_server_error = 500, // Internal Server Error
not_implemented = 501, // Not Implemented
bad_gateway = 502, // Bad Gateway
service_unavailable = 503, // Service Unavailable
gateway_time_out = 504, // Gateway Time-out
rtsp_version_not_supported = 505, // RTSP Version not supported
option_not_supported = 551, // Option not supported
};
namespace detail {
class rtsp_category
: public boost::system::error_category
{
public:
const char* name() const BOOST_SYSTEM_NOEXCEPT
{
return "rtsp";
}
std::string message(int value) const
{
switch (value) {
case rtsp_error::already_bind:
return "RTSP server has already binded";
case rtsp_error::not_bind:
return "RTSP server has not binded";
case rtsp_error::already_open:
return "RTSP session has already opened";
case rtsp_error::not_open:
return "RTSP session has not opened";
case rtsp_error::busy_work:
return "RTSP client is busy working";
case rtsp_error::format_error:
return "RTSP packet format error";
case rtsp_error::continue_:
return "Rtsp Continue";
case rtsp_error::ok:
return "Rtsp OK";
case rtsp_error::created:
return "Rtsp Created";
case rtsp_error::low_on_storage_space:
return "Rtsp Low on Storage Space";
case rtsp_error::multiple_choices:
return "Rtsp Multiple Choices";
case rtsp_error::moved_permanently:
return "Rtsp Moved Permanently";
case rtsp_error::moved_temporarily:
return "Rtsp Moved Temporarily";
case rtsp_error::see_other:
return "Rtsp See Other";
case rtsp_error::not_modified:
return "Rtsp Not Modified";
case rtsp_error::use_proxy:
return "Rtsp Use Proxy";
case rtsp_error::bad_request:
return "Rtsp Bad Request";
case rtsp_error::unauthorized:
return "Rtsp Unauthorized";
case rtsp_error::payment_required:
return "Rtsp Payment Required";
case rtsp_error::forbidden:
return "Rtsp Forbidden";
case rtsp_error::not_found:
return "Rtsp Not Found";
case rtsp_error::method_not_allowed:
return "Rtsp Method Not Allowed";
case rtsp_error::not_acceptable:
return "Rtsp Not Acceptable";
case rtsp_error::proxy_authentication_required:
return "Rtsp Proxy Authentication Required";
case rtsp_error::request_time_out:
return "Rtsp Request Time-out";
case rtsp_error::gone:
return "Rtsp Gone";
case rtsp_error::length_required:
return "Rtsp Length Required";
case rtsp_error::precondition_failed:
return "Rtsp Precondition Failed";
case rtsp_error::request_entity_too_large:
return "Rtsp Request Entity Too Large";
case rtsp_error::request_uri_too_large:
return "Rtsp Request-URI Too Large";
case rtsp_error::unsupported_media_type:
return "Rtsp Unsupported Media Type";
case rtsp_error::parameter_not_understood:
return "Rtsp Parameter Not Understood";
case rtsp_error::conference_not_found:
return "Rtsp Conference Not Found";
case rtsp_error::not_enough_bandwidth:
return "Rtsp Not Enough Bandwidth";
case rtsp_error::session_not_found:
return "Rtsp Session Not Found";
case rtsp_error::method_not_valid_in_this_state:
return "Rtsp Method Not Valid in This State";
case rtsp_error::header_field_not_valid_for_resource:
return "Rtsp Header Field Not Valid for Resource";
case rtsp_error::invalid_range:
return "Rtsp Invalid Range";
case rtsp_error::parameter_is_read_only:
return "Rtsp Parameter Is Read-Only";
case rtsp_error::aggregate_operation_not_allowed:
return "Rtsp Aggregate operation not allowed";
case rtsp_error::only_aggregate_operation_allowed:
return "Rtsp Only aggregate operation allowed";
case rtsp_error::unsupported_transport:
return "Rtsp Unsupported transport";
case rtsp_error::destination_unreachable:
return "Rtsp Destination unreachable";
case rtsp_error::internal_server_error:
return "Rtsp Internal Server Error";
case rtsp_error::not_implemented:
return "Rtsp Not Implemented";
case rtsp_error::bad_gateway:
return "Rtsp Bad Gateway";
case rtsp_error::service_unavailable:
return "Rtsp Service Unavailable";
case rtsp_error::gateway_time_out:
return "Rtsp Gateway Time-out";
case rtsp_error::rtsp_version_not_supported:
return "Rtsp RTSP Version not supported";
case rtsp_error::option_not_supported:
return "Rtsp Option not supported";
default:
return "rtsp error";
}
}
};
} // namespace detail
inline const boost::system::error_category & get_category()
{
static detail::rtsp_category instance;
return instance;
}
static boost::system::error_category const & rtsp_category = get_category();
inline boost::system::error_code make_error_code(
errors e)
{
return boost::system::error_code(
static_cast<int>(e), get_category());
}
} // namespace rtsp_error
} // namespace protocol
} // namespace util
namespace boost
{
namespace system
{
template<>
struct is_error_code_enum<util::protocol::rtsp_error::errors>
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
using util::protocol::rtsp_error::make_error_code;
#endif
}
}
#endif // _UTIL_PROTOCOL_RTSP_ERROR_H_
| true |
cb3f429b4d591ccf65b032b8bdec540d5157b2a2
|
C++
|
VitorPChaves/AssimpTest
|
/src/main.cc
|
UTF-8
| 1,977 | 2.578125 | 3 |
[] |
no_license
|
#include <Shader.h>
#include <Model.h>
#include <Camera.h>
#include <Things.h>
GLFWwindow* window = nullptr;
Camera* camera = new Camera;
void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
camera->mouse_callback(window, xpos, ypos);
}
bool initGL() {
if (!glfwInit()) {
fprintf(stderr, "Failed to initialize GLFW\n");
return false;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
window = glfwCreateWindow(1024, 768, "Audaces CG Internship Test", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not OpenGL 3.3 compatible.\n");
glfwTerminate();
return false;
}
glfwMakeContextCurrent(window);
glewExperimental = true; // http://glew.sourceforge.net/basic.html
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
return -1;
}
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glEnable(GL_BLEND);// you enable blending function
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return true;
}
int main() {
if (!initGL()) {
return -1;
}
Things* things = new Things;
things->initBuffers();
Shader shader("C:/Users/Vitor/Documents/AdvancedOpenGL/shaders/vs.txt", "C:/Users/Vitor/Documents/AdvancedOpenGL/shaders/fs.txt");
glEnable(GL_DEPTH_TEST);
do {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera->input(window);
shader.use();
shader.setInt("texture1", 0);
camera->camProjection(&shader);
things->drawFloor(&shader);
things->drawCube(&shader);
glfwSwapBuffers(window);
glfwPollEvents();
} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && !glfwWindowShouldClose(window));
things->~Things();
glfwTerminate();
return 0;
}
| true |
a3daa385a4272fbb35323b7ad5833eb2be1eac21
|
C++
|
jedichien/self-driving
|
/project_7_kidnapped_vehicle/learn/loc_motion.cpp
|
UTF-8
| 2,467 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <algorithm>
#include <vector>
#include "norm.h"
using namespace std;
/**
* initialize priors
*/
vector<float> init_priors(unsigned int map_size, vector<float> landmark_positions, float control_stdev);
/**
* motion model
*/
float motion_model(float pseudo_position, float movement, vector<float> priors, unsigned int map_size, int control_stdev);
int main() {
float control_stdev = 1.0f;
// meters vehicle moves per time step
float movement_per_timestamp = 1.0f;
// number of x position on map
unsigned int map_size = 25;
// initialize landmark
vector<float> landmark_positions {5, 10, 20};
// initialize priors
vector<float> priors = init_priors(map_size, landmark_positions, control_stdev);
for (unsigned int i = 0; i < map_size; i++) {
float pseudo_position = float(i);
// get the motion model probability for each x position
float motion_prob = motion_model(pseudo_position, movement_per_timestamp, priors, map_size, control_stdev);
cout << "pseudo_position: " << pseudo_position << ", " << "motion_prob: " << motion_prob << endl;
}
return 0;
}
float motion_model(float pseudo_position, float movement,
vector<float> priors, unsigned int map_size, int control_stdev) {
float position_prob = 0.0f;
for (unsigned int j=0; j < map_size; j++) {
float next_pesudo_position = float(j);
float distance_ij = pseudo_position - next_pesudo_position;
// transition probability
// The distibution generated consist of standard variance given by control, and mean value given by mean of movement in unit time.
float transition_prob = normpdf(distance_ij, movement, control_stdev);
position_prob += transition_prob * priors[j];
}
return position_prob;
}
vector<float> init_priors(unsigned int map_size, vector<float> landmark_positions, float control_stdev) {
vector<float> priors(map_size, 0.0);
// normal distribution value of 2 times standard variance
// plus 1 means due to this distribution's centre is 1, so have to shift 1 unit.
float normalization_term = landmark_positions.size() * (control_stdev * 2 + 1);
for (unsigned int i = 0; i < landmark_positions.size(); i++) {
int landmark_centre = landmark_positions[i];
priors[landmark_centre] = 1.0f/normalization_term;
priors[landmark_centre-1] = 1.0f/normalization_term;
priors[landmark_centre+1] = 1.0f/normalization_term;
}
return priors;
}
| true |
59ef79a95594012da39f6fd7e84d8a31c07e7eed
|
C++
|
vaibhavpandey2012000/compatative-Programming
|
/bitwise/uniqe_number_2.cpp
|
UTF-8
| 577 | 2.9375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int count_set(int ans)
{
int as=0;
while((ans&1)!=1)
{
as++;
ans=ans>>1;
}
return as;
}
void count_num(vector<int> &v,int n)
{
int ans=0;
for(int i=0;i<n;i++)
{
ans=ans^v[i];
}
int ss=count_set(ans);
int mask=(1<<ss),ff=0;
// cout<<mask<<endl;
for(int i=0;i<n;i++)
{
if((v[i] & mask)==0)
{
ff ^=v[i];
}
}
int se=ans^ff;
if(ff>se)
cout<<se<<" "<<ff<<endl;
else
cout<<ff<<" "<<se<<endl;
}
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
count_num(v,n);
}
| true |
0aae873500bc7f19f89803a8ea562a70776ec4e6
|
C++
|
lamnot/Cplusplus
|
/day6_Basic_Classes/Listing_6.5_Demo _of_Interface_vs_implementation_conflicts.cpp
|
UTF-8
| 1,265 | 3.828125 | 4 |
[] |
no_license
|
/*
* Listing6.5.cpp
* A demonstration of violations of the interface
*
* Created on: 3 Dec 2012
* Author: hp
*/
/*
//Headers and Includes
#include <iostream>
using namespace std;
//Types and defines
class cCat // cCat class declaration
{
public:
cCat(int initialAge); // cCat class constructor
~cCat(); // cCat class deconstructor
int GetAge() const; // constant, data member accessor funtion
void SetAge(int age); // data member accessor funtion
void Meow(); // other member function (method)
private:
int itsAge; // member variable (data member)
};
cCat::cCat(int initialAge) { // initialises itAge class variable
itsAge = initialAge;
cout << "cCat class constructor,\n";
}
cCat::~cCat() {
cout << "cCat class Destructor, takes no action";
}
int cCat::GetAge() const { // violates const(read only)
return (itsAge++);
}
void cCat::SetAge(int age) {
itsAge = age;
}
void cCat::Meow() {
cout << "Meouws!!!\n";
}
//Main program
int main()
{
cCat Frisky; // doesn't match function declaration
Frisky.Meow(); //
Frisky.Bark(); // no such member function (method) available
Frisky.itsAge = 7; // private data member, inaccessible from outside the class
return 0;
}
*/
| true |
f5cee43bc2dce1652b7d6a42e3594aaf00ff94d8
|
C++
|
acrobatman/libofd
|
/utils/StringFormatter.h
|
UTF-8
| 1,053 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef __UTILS_STRINGFORMATTER_H__
#define __UTILS_STRINGFORMATTER_H__
#include <vector>
#include <cstdio>
namespace utils {
class StringFormatter {
public:
struct GuardedPointer {
GuardedPointer(StringFormatter * sf) : sf(sf) { ++(sf->buf_cnt); }
GuardedPointer(const GuardedPointer & gp) : sf(gp.sf) { ++(sf->buf_cnt); }
~GuardedPointer(void) { --(sf->buf_cnt); }
operator char* () const { return &(sf->buf.front()); }
private:
StringFormatter * sf;
};
StringFormatter() : buf_cnt(0) { buf.reserve(L_tmpnam); }
/*
* Important:
* there is only one buffer, so new strings will replace old ones
*/
GuardedPointer operator () (const char * format, ...);
private:
friend struct GuardedPointer;
std::vector<char> buf;
int buf_cnt;
};
} //namespace utils
#endif // __UTILS_STRINGFORMATTER_H__
| true |
8bbbe36bd2c421b127dd78407b357bf479974cbe
|
C++
|
likan999/ContestSolver
|
/UvaOnline/Solve11504.cpp
|
UTF-8
| 2,550 | 2.84375 | 3 |
[] |
no_license
|
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
struct Vertex {
vector<int> outs;
int scc;
int preorder;
};
struct StackFrame {
int ip = 0;
int i;
size_t nextOutIndex = 0;
};
Vertex vertices[100000];
int sccs, C;
vector<int> S, P;
bool ins[100000];
vector<StackFrame> stack;
void findScc(int i) {
stack.clear();
stack.emplace_back();
stack.back().i = i;
outer:
while (!stack.empty()) {
StackFrame& current = stack.back();
i = current.i;
Vertex& v = vertices[i];
switch (current.ip) {
case 0:
P.emplace_back(v.preorder = C++);
S.emplace_back(i);
current.ip = 1;
case 1:
while (current.nextOutIndex < v.outs.size()) {
int out = v.outs[current.nextOutIndex++];
Vertex& w = vertices[out];
int p = w.preorder;
if (p == -1) {
stack.emplace_back();
stack.back().i = out;
goto outer;
} else if (w.scc == -1) {
while (P.back() > p) {
P.pop_back();
}
}
}
if (P.back() == v.preorder) {
P.pop_back();
int top;
do {
top = S.back();
S.pop_back();
vertices[top].scc = sccs;
} while (top != i);
++sccs;
}
stack.pop_back();
break;
default:
__builtin_unreachable();
}
}
}
int compute() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
Vertex& v = vertices[i];
v.outs.clear();
v.preorder = v.scc = -1;
}
for (int i = 0; i < m; i++) {
int from, to;
cin >> from >> to;
vertices[from - 1].outs.emplace_back(to - 1);
}
for (int i = 0; i < n; i++) {
vector<int>& outs = vertices[i].outs;
sort(outs.begin(), outs.end());
auto last = unique(outs.begin(), outs.end());
outs.resize(last - outs.begin());
}
sccs = C = 0;
S.clear();
P.clear();
for (int i = 0; i < n; i++) {
if (vertices[i].preorder == -1) {
findScc(i);
}
}
fill(ins, ins + sccs, false);
for (int i = 0; i < n; i++) {
int from = vertices[i].scc;
for (int out: vertices[i].outs) {
int to = vertices[out].scc;
if (to != from) {
ins[to] = true;
}
}
}
return count(ins, ins + sccs, false);
}
int main() {
istream::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cout << compute() << '\n';
}
cout << flush;
quick_exit(0);
}
| true |
c5e8c7e775c434ce668e65820cd624f72f49cb81
|
C++
|
rugbyprof/2143-Object-Oriented-Programming
|
/Lectures/03-Game_Of_Life/helper.hpp
|
UTF-8
| 198 | 2.953125 | 3 |
[] |
no_license
|
using namespace std;
int** allocate(int width,int height) {
int **array = new int *[height];
for (int i = 0; i < height; i++) {
array[i] = new int[width];
}
return array;
}
| true |
5d07e1ff28e996d06ebe6eb9dd0d86aa9a0b42a6
|
C++
|
aldebaran/libqi
|
/qi/type/detail/anyiterator.hxx
|
UTF-8
| 1,437 | 2.984375 | 3 |
[] |
permissive
|
#pragma once
/*
** Copyright (C) 2013 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_DETAIL_ANYITERATOR_HXX_
#define _QITYPE_DETAIL_ANYITERATOR_HXX_
#include <qi/type/typeinterface.hpp>
namespace qi {
inline AnyReference AnyIterator::operator*()
{
if (kind() == TypeKind_Iterator)
return static_cast<IteratorTypeInterface*>(_type)->dereference(_value);
else
throw std::runtime_error("Expected iterator");
}
template<typename T>
AnyIterator::AnyIterator(const T& ref)
: AnyValue(AnyReference::from(ref))
{}
inline AnyIterator::AnyIterator()
{}
inline AnyIterator::AnyIterator(const AnyReference& p)
: AnyValue(p)
{}
inline AnyIterator::AnyIterator(const AnyValue& v)
: AnyValue(v)
{}
inline AnyIterator& AnyIterator::operator++()
{
if (kind() != TypeKind_Iterator)
throw std::runtime_error("Expected an iterator");
static_cast<IteratorTypeInterface*>(_type)->next(&_value);
return *this;
}
inline AnyIterator AnyIterator::operator++(int)
{
if (kind() != TypeKind_Iterator)
throw std::runtime_error("Expected an iterator");
AnyIterator it2 = *this;
static_cast<IteratorTypeInterface*>(_type)->next(&_value);
return it2;
}
inline bool operator==(const AnyIterator& a, const AnyIterator& b)
{
return a.asReference() == b.asReference();
}
inline bool operator!=(const AnyIterator& a, const AnyIterator& b)
{
return !(a==b);
}
}
#endif // _QITYPE_DETAIL_ANYITERATOR_HXX_
| true |
38bf65a19ab79ba5a73b56915c3d1c73e6e548df
|
C++
|
gregoire-caulys/greenhouse-control
|
/FanControlInProgress/sensors.cpp
|
UTF-8
| 3,010 | 2.71875 | 3 |
[] |
no_license
|
/**
PROJECT : Greenhouse Project
FILENAME : sensors.cpp
DESCRIPTION :
Classes for sensors
AUTHORS :
Gaspard Feuvray, Gregoire Gentile
*/
#include "sensors.h"
// Writes all measurements in json format
String build_json(String sensor_measurements[SENSORS_NB]) {
String str = "*{";
for(int i=0; i<SENSORS_NB; i++) {
// add delimiter
if(i!=0) {
str = str + ",";
}
// add sensor
str = str + sensor_measurements[i];
}
return str+"}*";
}
//______________________ LIGHT _____________________________
// I2C communication
LightSensor::LightSensor(String name) : _name(name), SI1145(SI114X()) {
}
String LightSensor::get_measurements() {
String vis = String(SI1145.ReadVisible());
String ir = String(SI1145.ReadIR());
char uv_str[8] = "";
dtostrf((float)SI1145.ReadUV()/100, 5, 3, uv_str);
String uv(uv_str);
return "\""+_name+"\":{\"vis\":"+vis+",\"ir\":"+ir+",\"uv\":"+uv+"}";
}
String LightSensor::get_name() {
return _name;
}
bool LightSensor::init() {
return SI1145.Begin();
}
//____________________ TEMP HUMID SHT __________________________
// I2C communication
TempHumSensor::TempHumSensor(String name): _name(name), sht31(SHT31()){
_temperature = 21;}
String TempHumSensor::get_measurements() {
char humidity_str[8] = "";
dtostrf(sht31.getHumidity(),7,2, humidity_str);
String humidity = String(humidity_str);
char temperature_str[8] = "";
dtostrf(sht31.getTemperature(), 7, 2, temperature_str);
String temperature = String(temperature_str);
_temperature = temperature.toInt();
return "\""+_name+"\":{\"hum\":"+humidity+",\"temp\":"+temperature+"}";
}
String TempHumSensor::get_name() {
return _name;
}
bool TempHumSensor::init(int i2c_adr) {
return sht31.begin(i2c_adr);
}
//____________________ TEMP HUMID DHT __________________________
// analog communication
//____________________ MOISTURE __________________________
// analog communication
MoistureSensor::MoistureSensor(String name, int pin) : _name(name), _pin(pin) {
}
String MoistureSensor::get_measurements() {
int moisture = analogRead(_pin);
return "\""+_name+"\":"+String(moisture);
}
String MoistureSensor::get_name() {
return _name;
}
void MoistureSensor::init() {
}
//____________________ FLOWMETER __________________________
// analog communication
FlowMeter::FlowMeter(String name, int pin) : _name(name), _pin(pin) {
}
String FlowMeter::get_measurements() {
int flow = analogRead(_pin);
return "\""+_name+"\":"+String(flow);
}
String FlowMeter::get_name() {
return _name;
}
void FlowMeter::init() {
}
//______________________ CO2 __________________________
// I2C communication
/*
Co2Sensor::Co2Sensor(String name): _name(name) _ccs(Adafruit_CCS811()){
}
String Co2Sensor::get_measurements() {
return "\""+_name +"\":{\"temp\":"+String(_temperature)+",\"co2\":"+String(_CO2PPM)+"}";
}
String Co2Sensor::get_name() {
return _name;
}
void Co2Sensor::init(int i2c_adr) {
_ccs.begin()
}
*/
| true |
ac2f5a3d6d00d3d10d346d2fcc2eae3195ddae30
|
C++
|
asgaonkar/RSA-Blind-Signature
|
/main.cpp
|
UTF-8
| 2,230 | 3.328125 | 3 |
[] |
no_license
|
/*
Project Members:
1. Jaswant Pakki - 1208755310
2. Atit Gaonkar - 1217031322
*/
#include <stdio.h>
#include <stdlib.h>
#include <array>
#include <iostream>
#include <random>
#include <cmath>
#include "RSA.h"
#include "BigInt.h"
#define RAND_LIMIT32 0x7FFFFFFF
using namespace RSAUtil;
using namespace std;
int main(int argc, char *argv[])
{
cout<<"Blind Signature";
/*
Step 01: Alice obtains the public key and Modulus N of the person (Bob) who is to sign the message
*/
RSA Bob;
//cout<<"\nPublic Key (N): "<<Bob.getModulus().toHexString();
//cout<<"\nPublic Key (E): "<<Bob.getPublicKey().toHexString();
/*
Step 02: Obtain a random number and its inverse with respect to the Modulus [Not phi] of Bob
*/
srand(time(0));
BigInt rand = std::rand();
//printf("\nRandom: %x",rand);
cout<<"\nRandom Number: "<<rand.toHexString();
//Step 03: Alice obtains/generates a message to be signed.
BigInt message = (random()%RAND_LIMIT32);
//printf("\nMessage: %x",message);
cout<<"\nMessage: "<<message.toHexString();
/*
Step 04: Alice encrypts the random number with the public key.
Step 05: Alice multiplies this value by the message.
Step 06: Alice then takes a modulus over N
*/
RSA *rsa_bob = &Bob;
BigInt after_mul = (rsa_bob->encrypt(rand) * message) % rsa_bob->getModulus();
//printf("\nAfter Multiplied: %x",after_mul);
cout<<"\nAfter Multiplied: "<<after_mul.toHexString();
/*
Step 07: Alice sends it to Bob
Step 08: Bob simply decrypts the received value with the private key
*/
BigInt blind_sig = Bob.decrypt(after_mul);
//printf("\nBlind Signature: %x",blind_sig);
cout<<"\nBlind signature: "<<blind_sig.toHexString();
/*
Step 09: Bob sends it back to Alice
Step 10: Alice then multiplied the received value with the inverse and takes a modulus over N.
*/
BigInt sig = (blind_sig * modInverse(rand, Bob.getModulus())) % Bob.getModulus();
//printf("\nSignature: %x",sig);
cout<<"\nSignature: "<<sig.toHexString();
/*
Step 11: To obtain the original message from it, again encrypt it with Bob’s Public Key.
*/
cout<<"\nVerify: "<<message.toHexString()<<" & "<<Bob.encrypt(sig).toHexString();
//printf("\nVerify: %x & %x",message,sig);
cout<<"\n";
return 0;
}
| true |
11978c99a96bf521ba4170bee80d20b2923df9d7
|
C++
|
Niraka/PinballGame
|
/PinballGame/source/Map.cpp
|
UTF-8
| 4,786 | 2.578125 | 3 |
[] |
no_license
|
#include "Map.h"
/**
Constructs a default Map. */
Map::Map()
{
m_collisionsManager.addCollisionListener(this);
m_currentState = State::WAITING;
}
/**
Sets the gravity of the map. Gravity is applied to every non-static GameObject
every game loop.
@param vGravity The gravity vector. */
void Map::setGravity(Vector2D& vGravity)
{
m_vGravity = vGravity;
}
/**
Clears all GameObjects from the map, clearing up any used memory as it goes. */
void Map::clearGameObjects()
{
for (std::vector<GameObject*>::iterator it = m_gameObjects.begin(); it != m_gameObjects.end(); ++it)
{
delete &(*it)->getCollidable()->getShape();
delete *it;
}
m_gameObjects.clear();
}
/**
Sets the state of the map. *
@param newState The new state. */
void Map::setState(Map::State newState)
{
m_currentState = newState;
}
/**
Returns the state of the map.
@return The state of the map. */
Map::State Map::getState()
{
return m_currentState;
}
/**
Creates the user interface for the map. The interface is consistent across all maps.
@param bl A pointer to the button listener to add to components that require one.
@param uim A reference to the UIManager that will manage the newly created UI. */
void Map::createUI(UIButtonListener* bl, UIManager& uim)
{
std::string sScoreComponent;
UIBuilder b(uim);
b.buildUI("../data/user_interfaces/game/avalanche_constructor.txt", bl, sScoreComponent);
uim.setUILoaded(UIManager::UIs::MAP_AVALANCHE, true);
// Link the score component
UIComponent* u = uim.getUIComponentRef(sScoreComponent);
UIText* txt = dynamic_cast<UIText*>(u);
m_scoreUIComponent = txt;
}
/**
Deletes the user interface for the map.
@param uim A reference to the UIManager containing the UI to be deleted. */
void Map::deleteUI(UIManager& uim)
{
UIDestructor d(uim);
d.deconstructUI("../data/user_interfaces/game/avalanche_destructor.txt");
uim.setUILoaded(UIManager::UIs::MAP_AVALANCHE, false);
}
/**
Resets the maps clock to 0. */
void Map::resetClock()
{
m_clock.restart();
}
/**
Returns a reference to the maps clock.
@return A reference to the maps clock. */
sf::Clock Map::getClock() const
{
return m_clock;
}
/**
Resets the score to 0. Updates the score display accordingly. */
void Map::resetScore()
{
m_scoreTracker.setScore(0.f);
m_scoreTracker.setScoreMultiplier(1.f);
updateScoreDisplay();
}
/**
Returns the current score.
@return The current score. */
float Map::getScore() const
{
return m_scoreTracker.getScore();
}
/**
Registers a MapEventListener with this map.
@param l The MapEventListener to add. */
void Map::addMapEventListener(MapEventListener* l)
{
m_mapEventListeners.push_back(l);
}
/**
Launches a game over event to all MapEventListeners registered with this map. */
void Map::launchEvent_gameOver()
{
for (std::vector<MapEventListener*>::iterator it = m_mapEventListeners.begin(); it != m_mapEventListeners.end(); ++it)
{
(*it)->gameOver(this);
}
}
/**
Updates the UIText component with the new score value. If the component was not set (The component was missing from the
map file, the program will crash (Intentionally). */
void Map::updateScoreDisplay()
{
m_scoreUIComponent->setString(&std::string(std::to_string((int)m_scoreTracker.getScore())));
m_scoreUIComponent->setAlignment(UIText::Alignment::CENTRE);
}
/**
Searches for the first GameObject with the given name and returns a pointer to it.
@param sGOName The name of the GameObject to get.
@return The first GameObject found with the given name, or a nullptr if no GameObject was found. */
GameObject* Map::getGameObject(std::string sGOName)
{
for (std::vector<GameObject*>::iterator it = m_gameObjects.begin(); it != m_gameObjects.end(); ++it)
{
if ((*it)->getName() == sGOName)
{
return *it;
}
}
return nullptr;
}
/**
Searches for every GameObject whos name contains the given name. Returns a vector of pointers to the found
GameObjects.
@param sGOName The name to search with.
@return A vector of pointers to GameObjects whos names contained the given name. */
std::vector<GameObject*> Map::getGameObjects(std::string sGOName)
{
std::vector<GameObject*> gameObjects;
for (std::vector<GameObject*>::iterator it = m_gameObjects.begin(); it != m_gameObjects.end(); ++it)
{
if ((*it)->getName().find(sGOName) != std::string::npos)
{
gameObjects.push_back(*it);
}
}
return gameObjects;
}
/**
Draws the map to the target. Consult the SFML Graphics documentation for further information.
@see sf::RenderTarget
@see sf::RenderStates
@param target The target to draw to.
@param states The RenderStates. */
void Map::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
for (std::vector<GameObject*>::const_iterator it = m_gameObjects.begin(); it != m_gameObjects.end(); ++it)
{
target.draw(**it);
}
}
| true |
1b33f2f663a1e62645cc6648ae71afaccce53899
|
C++
|
zoejiaen/MyPaintTest3
|
/shape.cpp
|
UTF-8
| 1,857 | 3.140625 | 3 |
[] |
no_license
|
#include "shape.h"
#include <QDebug>
Line::Line(const QPoint &p1, const QPoint &p2, const QColor &color, int width) :
m_p1(p1),
m_p2(p2),
m_color(color),
m_width(width)
{
}
void Line::draw(QPainter &painter) const
{
QPen pen(m_color);
pen.setWidth(m_width);
QPen temp = painter.pen();
painter.setPen(pen);
painter.drawLine(m_p1, m_p2);
painter.setPen(temp);
}
Rectangle::Rectangle(const QPoint &p1, const QPoint &p2, const QColor &color, int width) :
m_p1(p1),
m_p2(p2),
m_color(color),
m_width(width)
{
}
void Rectangle::draw(QPainter &painter) const
{
QPen pen(m_color);
pen.setWidth(m_width);
QPen temp = painter.pen();
painter.setPen(pen);
painter.drawRect(QRect(m_p1, m_p2));
painter.setPen(temp);
}
Ellipse::Ellipse(const QPoint &p1, const QPoint &p2, const QColor &color, int width) :
m_p1(p1),
m_p2(p2),
m_color(color),
m_width(width)
{
}
void Ellipse::draw(QPainter &painter) const
{
QPen pen(m_color);
pen.setWidth(m_width);
QPen temp = painter.pen();
painter.setPen(pen);
painter.drawEllipse(QRect(m_p1, m_p2));
painter.setPen(temp);
}
Pencil::Pencil(const QColor &color, int width) :
m_color(color),
m_width(width)
{
}
Pencil::Pencil(const QPoint &point, const QColor &color, int width) :
m_color(color),
m_width(width)
{
m_pointVector.push_back(point);
}
void Pencil::addPoint(const QPoint &p)
{
m_pointVector.push_back(p);
}
void Pencil::draw(QPainter &painter) const
{
if (m_pointVector.size() < 2)
return;
QPen pen(m_color);
pen.setWidth(m_width);
QPen temp = painter.pen();
painter.setPen(pen);
for (size_t i = 1; i < m_pointVector.size(); i++)
painter.drawLine(m_pointVector[i - 1], m_pointVector[i]);
painter.setPen(temp);
}
| true |
aa1ccebd0667ec82246df6c59954753765177974
|
C++
|
axxonite/algorithms
|
/EPI/Solutions/15_BinarySearchTrees/15.1_is_binary_tree_a_bst_solution.cpp
|
UTF-8
| 654 | 2.765625 | 3 |
[] |
no_license
|
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
#include "stdafx.h"
#include "binary_tree_prototype.h"
#include "binary_tree_utils.h"
namespace Solutions
{
bool IsBinaryTreeBST( const unique_ptr<BinaryTreeNode<int>>& tree, int low, int high )
{
if ( !tree )
return true;
if ( tree->data < low || tree->data > high )
return false;
return IsBinaryTreeBST( tree->left, low, tree->data ) && IsBinaryTreeBST( tree->right, tree->data, high );
}
bool IsBinaryTreeBST( const unique_ptr<BinaryTreeNode<int>>& tree )
{
return IsBinaryTreeBST( tree, numeric_limits<int>::min(), numeric_limits<int>::max() );
}
}
| true |
f44d6a1d2116ba1b38ece988621b0c75e9a11583
|
C++
|
karanb1/Ladder
|
/drinks.cpp
|
UTF-8
| 260 | 2.59375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,sum=0;
double percentage;
cin >> n;
int arr[n];
for(int i=0;i<n;i++){
cin >> arr[i];
sum+=arr[i];
}
percentage =(double) sum/n;
cout<< percentage;
}
| true |
d855d5aa948177f34ee89115f351ac3bc3977852
|
C++
|
EudaldV98/Piscine_Cpp
|
/module_08/ex01/main.cpp
|
UTF-8
| 3,363 | 2.9375 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jvaquer <jvaquer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/26 12:48:21 by jvaquer #+# #+# */
/* Updated: 2021/01/26 12:51:35 by jvaquer ### ########.fr */
/* */
/* ************************************************************************** */
#include "span.hpp"
int main()
{
srand(time(NULL));
std::cout << "\nSubject test : " << std::endl;
Span sp = Span(5);
sp.addNumber(5);
sp.addNumber(3);
sp.addNumber(17);
sp.addNumber(9);
sp.addNumber(11);
std::cout << sp.shortestSpan() << std::endl;
std::cout << sp.longestSpan() << std::endl;
std::cout << "\nMy test : " << std::endl;
Span test(8);
std::cout << "trying with vector of size 8" << std::endl;
for (int i = 0; i < 8 ; i++)
{
test.addNumber(i * (i % 2 == 0 ? i : -i));
std::cout << i << ": " << i * (i % 2 == 0 ? i : -i) << "|";
}
std::cout << std::endl;
std::cout << "Shortest : " << test.shortestSpan() << std::endl;
std::cout << "Longest : " << test.longestSpan() << std::endl;
Span a = Span(1001);
std::cout << "\ntrying to put 1002 element in a vector of size 1001" << std::endl;
try
{
a.addNumber(0, 1002);
}
catch(const std::exception& e)
{
std::cerr << e.what();
}
std::cout << "\ntrying to put 1001 element in a vector of size 1001" << std::endl;
a.addNumber(0, 1001);
std::cout << "shortest Span : "<< a.shortestSpan() << std::endl;
std::cout << "longest Span : " << a.longestSpan() << std::endl;
std::cout << "\ntrying to know the shortest span in a vector with no value " << std::endl;
Span c = Span(5);
try
{
std::cout << "shortest Span : "<< c.shortestSpan() << std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what();
}
std::cout << "\ntrying to know the longest span in a vector with no value " << std::endl;
try
{
std::cout << "longest Span : "<< c.shortestSpan() << std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what();
}
c.addNumber(2);
std::cout << "\ntrying to know the shortest span in a vector with 1 value " << std::endl;
try
{
std::cout << "shortest Span : "<< c.longestSpan() << std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what();
}
std::cout << "\ntrying to know the longestest span in a vector with 1 value " << std::endl;
try
{
std::cout << "longest Span : "<< c.longestSpan() << std::endl;
}
catch(const std::exception& e)
{
std::cerr << e.what();
}
Span d = Span(15000);
std::cout << "\ncreation of a vector of size 15000 filled with random " << std::endl;
for (int i = 0; i < 15000; i++)
{
d.addNumber((rand() % 1000000000));
}
std::cout << "shortest Span : "<< d.shortestSpan() << std::endl;
std::cout << "longest Span : " << d.longestSpan() << std::endl;
return (0);
}
| true |
49751f925b329f44220bb5af1222b3ae5444634b
|
C++
|
iCodeIN/leetcode-4
|
/LC_272.cpp
|
UTF-8
| 1,317 | 3.234375 | 3 |
[] |
no_license
|
void dfs(TreeNode* root, priority_queue<pair<double, int>>& pq, double target, int k) {
if(!root) return;
pq.push(make_pair(fabs(target - double(root->val)), root->val));
if(pq.size() > k)
pq.pop();
dfs(root->left, pq, target, k);
dfs(root->right, pq, target, k);
}
vector<int> closestKValues(TreeNode* root, double target, int k) {
priority_queue<pair<double, int>> pq;
vector<int> result;
dfs(root, pq, target, k);
while(!pq.empty()) {
result.push_back(pq.top().second);
pq.pop();
}
return result;
}
public class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
LinkedList<Integer> res = new LinkedList<>();
collect(root, target, k, res);
return res;
}
public void collect(TreeNode root, double target, int k, LinkedList<Integer> res) {
if (root == null) return;
collect(root.left, target, k, res);
if (res.size() == k) {
//if size k, add curent and remove head if it's optimal, otherwise return
if (Math.abs(target - root.val) < Math.abs(target - res.peekFirst()))
res.removeFirst();
else return;
}
res.add(root.val);
collect(root.right, target, k, res);
}
}
| true |
5a57a27f379ac026dd98279b287ff09372c73883
|
C++
|
JeongKwonHo/cplusplus
|
/CPP_BASIC/03_VAR/constexpr2.cpp
|
UTF-8
| 847 | 3.546875 | 4 |
[] |
no_license
|
/*
*
핵심 정리
1. 상수의 종류
- runtime constant
- compile-time constant (constexpr)
2. constexpr은 compile-time 상수로만 초기화 할 수 있다.
3. 배열의 크기
- C89문법 : 컴파일 시간 상수만 가능하다.
- C99문법 : 변수도 가능하다. VC++은 지원 안함.
*
*/
#include <iostream>
int main()
{
//const int c = 10; // 컴파일 시간 상수
// 컴파일 시간에 c를 사용하는곳을 매크로 처럼 이미 fix해버림
// 이를 위해 constexpr이라는 키워드가 생성.
int n = 10;
const int c = n; // 실행시간 상수
// c에 접근 할때 메모리에서 직접 읽어옴 그러므로 20이 출력
//int* p = &c; //error
int* p = (int*)&c; //ok..
*p = 20;
std::cout<< c <<std::endl; // 10 20
std::cout<< *p <<std::endl; // 20 10
}
| true |
05a426b4d167aa29f47afbfae33c1d658a444ec7
|
C++
|
thangvubk/MultiGroupLevelLogger
|
/logger.cpp
|
UTF-8
| 1,348 | 2.671875 | 3 |
[] |
no_license
|
#include "logger.h"
#include <stdio.h>
#define LOG_MAX_LEN 1024
pthread_mutex_t Logger::_loggerMutex;
const char* Logger::LogGroupNames[] = {"GROUP_1", "GROUP_2"};
static int loggerConfig[][4] ={
0, //LOG_LEVEL_DEBUG
0, //LOG_LEVEL_INFO
0, //LOG_LEVEL_WARNING
1, //LOG_LEVEL_ERROR
//group 2
0, //LOG_LEVEL_DEBUG
0, //LOG_LEVEL_INFO
1, //LOG_LEVEL_WARNING
1 //LOG_LEVEL_ERROR
};
void Logger::print(LOG_LEVEL_T type, LOG_GROUP_T group, const char* fmt, ...)
{
if ((type == LOG_LEVEL_INFO && loggerConfig[group][LOG_LEVEL_INFO] == 0) ||
(type == LOG_LEVEL_WARNING && loggerConfig[group][LOG_LEVEL_WARNING] == 0) ||
(type == LOG_LEVEL_ERROR && loggerConfig[group][LOG_LEVEL_ERROR] == 0) ||
(type == LOG_LEVEL_DEBUG && loggerConfig[group][LOG_LEVEL_DEBUG] == 0))
{
return;
}
char msg[LOG_MAX_LEN];
va_list args;
va_start(args, fmt);
vsnprintf(msg, LOG_MAX_LEN, fmt, args);
va_end(args);
msg[LOG_MAX_LEN-1] = '\0';
const char* strType;
switch (type)
{
case LOG_LEVEL_INFO:
strType = "INFO";
break;
case LOG_LEVEL_WARNING:
strType = "WARNING";
break;
case LOG_LEVEL_ERROR:
strType = "ERROR";
break;
case LOG_LEVEL_DEBUG:
strType = "DEBUG";
break;
default: strType = "PRINT";
}
printf("%-14s|%5s: %s\n", LogGroupNames[group], strType, msg);
}
| true |
27f999381d5c504a0a19e802318d2d16a922d88e
|
C++
|
hellolijj/OJ
|
/leet-code/数组/442-数组中重复的数据.cpp
|
UTF-8
| 1,292 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
/*给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。
找到所有出现两次的元素。
你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[2,3]
*/
/*
testcase
[4,3,2,7,8,2,3,1]
[1]
[1,2]
*/
#include <cstdio>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
while(nums[i] != i+1) {
if(nums[i] == nums[nums[i]-1]) {
res.push_back(nums[i]);
break;
}
// swap(nums[i], nums[nums[i]-1]);
int temp = nums[i];
nums[i] = nums[nums[i]-1];
nums[nums[i]-1] = temp;
}
}
return res;
}
};
int main() {
class Solution solu;
int a[8] = {4,3,2,7,8,2,3,1};
vector<int> p;
for(int i = 0; i < 8; i++) {
p.push_back(a[i]);
}
vector<int> res = solu.findDuplicates(p);
for(int i = 0; i < res.size(); i++) {
printf("%d ", res[i]);
}
return 0;
}
| true |
d1485813ed940d7b7fef7fa474a237e689228a0d
|
C++
|
frcepeda/Contest-Archive
|
/Codeforces/Practice/UKIEPC 2015/I.cpp
|
UTF-8
| 1,072 | 2.921875 | 3 |
[] |
no_license
|
#include <cstdio>
#include <algorithm>
#include <cctype>
#include <cstring>
using namespace std;
char s[10000];
char *hard = "bcdgknpt";
char *endings[3] = {"ah", "oh", "uh"};
bool ishard(char c){
for (int i = 0; hard[i]; i++)
if (hard[i] == c)
return true;
return false;
}
char start(char c){
int r = 0;
for (int i = 1; hard[i] != '\0'; i++)
if (abs(hard[r] - c) > abs(hard[i] - c))
r = i;
return hard[r];
}
int end(char c){
int r = 0;
for (int i = 1; i < 3; i++)
if (abs(endings[r][0] - c) > abs(endings[i][0] - c))
r = i;
return r;
}
int main(){
int i;
bool first = true;
while (scanf("%s", s) != EOF){
if (!first) putchar(' ');
else first = false;
int n = strlen(s);
bool up = isupper(s[0]);
s[0] = start(tolower(s[0]));
for (i = 0; i < n && s[i] != '-'; i++);
for (i++; i < n; i++)
if (ishard(s[i]))
s[i] = s[0];
if (up)
s[0] = toupper(s[0]);
for (i = 0; i < n; i++)
if (s[i] != '-')
putchar(s[i]);
if (ishard(tolower(s[n-1])))
printf("%s", endings[end(s[n-1])]);
}
putchar('\n');
}
| true |
2b02f6d670dcf64ebc7e46ee025e9c80fb477614
|
C++
|
z-siddy/vublockchain
|
/headers/hash.h
|
UTF-8
| 2,236 | 3.03125 | 3 |
[] |
no_license
|
//
// Created by zygsi on 9/13/2019.
//
#ifndef VUBLOCKCHAIN_HASH_H
#define VUBLOCKCHAIN_HASH_H
#include <chrono>
#include "main.h"
#include <vector>
#include <random>
#include <sstream>
#include <fstream>
namespace hash {
class Timer {
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
std::chrono::duration<float> duration;
public:
void startClock() {
start = std::chrono::high_resolution_clock::now();
}
void endClock(string opName) {
end = std::chrono::high_resolution_clock::now();
duration = end-start;
cout << endl << opName << " took: " << duration.count() << " s" << std::endl;
}
};
class Hash {
private:
string _hashedValue;
string _inputValue;
std::vector<int> hashVec;
void divideToBlocks() {
for(auto i = _inputValue.begin(); i != _inputValue.end(); ++i) {
hashVec.push_back((*i)^hashVec.size());
}
};
void getHashedValue() {
long long int seed = std::accumulate(hashVec.begin(), hashVec.end(), hashVec.size()) + (int)_inputValue[0]*6969/(_inputValue.length()+2) * 69;
std::mt19937 rand(seed + 69.69);
std::uniform_int_distribution<int> variant(0,2);
std::uniform_int_distribution<int> number(48, 57);
std::uniform_int_distribution<int> letter(97, 102);
std::uniform_int_distribution<int> sletter(65, 70);
std::stringstream hashStream;
for (int i=0;i<64;i++){
int var = variant(rand);
if(var == 0)
hashStream << (char)number(rand);
else if(var == 1)
hashStream << (char)letter(rand);
else
hashStream << (char)sletter(rand);
}
_hashedValue = hashStream.str();
};
public:
void getInput(string in) {
_inputValue = in;
};
string hashThis() {
divideToBlocks();
getHashedValue();
return _hashedValue;
};
};
}
#endif //VUBLOCKCHAIN_HASH_H
| true |
dda531d703ff4f9ec526ebdd816c34f7ad0a669e
|
C++
|
nobalpha/open-source-contribution
|
/CPP/PrepBytesCP/BoxesandToys.cpp
|
UTF-8
| 304 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
//Question Link- https://mycode.prepbytes.com/problems/fundamentals/BOXTOY
#include <bits/stdc++.h>
using namespace std;
int main()
{
int box=0;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int t;
int c;
cin>>t>>c;
if(c-t>=2)
{
box++;
}
}
cout<<box;
return 0;
}
| true |
3c770e4876813f6eecd0ae574f57a3cdb200a15f
|
C++
|
hojin-koh/cpp-aspartame
|
/tests/optarr/optnum.cc
|
UTF-8
| 4,887 | 3.28125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <aspartamev0/optarr.h>
#include <catch2/catch_test_macros.hpp>
#include <stdexcept>
SCENARIO("Number Array Opts", "[optarrnum]") {
GIVEN("Empty array options") {
aspartamev0::OptArrInt ei;
aspartamev0::OptArrFloat ef;
aspartamev0::OptArrBool eb;
THEN("They have correct size") {
REQUIRE(ei.size() == 0);
REQUIRE(ef.size() == 0);
REQUIRE(eb.size() == 0);
}
THEN("Accessing them from different directions throws") {
REQUIRE_THROWS(ei[0]);
REQUIRE_THROWS(ei[-1]);
REQUIRE_THROWS(ef[0]);
REQUIRE_THROWS(ef[-1]);
REQUIRE_THROWS(eb[0]);
REQUIRE_THROWS(eb[-1]);
}
}
GIVEN("Individual options") {
aspartamev0::OptArrInt i {30, 40, 50};
aspartamev0::OptArrFloat f {0.25, 0.75};
aspartamev0::OptArrBool b {false, false, true, true};
THEN("We can get the sizes of these options") {
REQUIRE(i.size() == 3);
REQUIRE(f.size() == 2);
REQUIRE(b.size() == 4);
}
THEN("They should have that default value") {
REQUIRE(i[0] == 30);
REQUIRE(i[1] == 40);
REQUIRE(i[2] == 50);
REQUIRE(f[0] == 0.25);
REQUIRE(f[1] == 0.75);
REQUIRE(!b[0]);
REQUIRE(!b[1]);
REQUIRE(b[2]);
REQUIRE(b[3]);
}
THEN("They should be accessible through negative index") {
REQUIRE(i[-3] == 30);
REQUIRE(i[-2] == 40);
REQUIRE(i[-1] == 50);
REQUIRE(f[-2] == 0.25);
REQUIRE(f[-1] == 0.75);
REQUIRE(!b[-4]);
REQUIRE(!b[-3]);
REQUIRE(b[-2]);
REQUIRE(b[-1]);
}
THEN("Their individual value can be set") {
i[1] = 27;
REQUIRE(i[-2] == 27);
f[1] = 1.25;
REQUIRE(f[-1] == 1.25);
b[0] = true;
REQUIRE(b[-4]);
}
THEN("Their contents can be cleared") {
i.clear();
REQUIRE(i.size() == 0);
f.clear();
REQUIRE(f.size() == 0);
b.clear();
REQUIRE(b.size() == 0);
}
THEN("They should have the default value after reset") {
i.clear();
i.reset();
REQUIRE(i.size() == 3);
REQUIRE(i[-1] == 50);
f.clear();
f.reset();
REQUIRE(f.size() == 2);
REQUIRE(f[-1] == 0.75);
b.clear();
b.reset();
REQUIRE(b.size() == 4);
REQUIRE(b[-1]);
}
THEN("Out-of-bound access should throw") {
REQUIRE_THROWS(i[5]);
REQUIRE_THROWS(f[8]);
REQUIRE_THROWS(b[9]);
REQUIRE_THROWS(i[5] = 10);
REQUIRE_THROWS(f[8] = 2.5);
REQUIRE_THROWS(b[9] = false);
}
}
//GIVEN("Some same-type options") {
// aspartamev0::OptInt i1 {10};
// aspartamev0::OptInt i2 {20};
// aspartamev0::OptInt i2a {i2};
// THEN("Assign one to another shouldn't affect the default value") {
// i1 = i2;
// REQUIRE(i1.getDefault() == 10);
// REQUIRE(i1 == 20);
// i1.reset();
// REQUIRE(i1 == 10);
// }
// THEN("Copy-constructed option should have same default value") {
// REQUIRE(i2a == 20);
// REQUIRE(i2a.getDefault() == 20);
// }
//}
//GIVEN("Individual options to be set by strings") {
// aspartamev0::OptInt i {30};
// aspartamev0::OptFloat f {0.25};
// aspartamev0::OptBool b {false};
// THEN("They can be set with strings") {
// i.set("75");
// REQUIRE(i == 75);
// f.set("0.5");
// REQUIRE(f == 0.5);
// b.set("true");
// REQUIRE(b);
// }
// THEN("Non-parsable things will throw exceptions or fails silently") {
// REQUIRE_THROWS_AS(i.set("xxxooo"), std::domain_error);
// i.set("oioioi", false);
// REQUIRE(i == 0);
// REQUIRE_THROWS_AS(f.set("xxxooo"), std::domain_error);
// f.set("oioioi", false);
// REQUIRE(f == 0);
// REQUIRE_THROWS_AS(b.set("rrrrrr"), std::domain_error);
// b.set("rrrrrr", false);
// REQUIRE(!b);
// }
// THEN("Nullptr will throw exceptions") {
// REQUIRE_THROWS_AS(i.set(nullptr), std::domain_error);
// REQUIRE_THROWS_AS(f.set(nullptr), std::domain_error);
// REQUIRE_THROWS_AS(b.set(nullptr), std::domain_error);
// }
//}
//GIVEN("Special parsings for integer") {
// aspartamev0::OptInt i {30};
// THEN("All sorts of weird values can be parsed") {
// i.set(" 149872");
// REQUIRE(i == 149872);
// i.set("0x6fffff");
// REQUIRE(i == 7340031);
// i.set(" -5578");
// REQUIRE(i == -5578);
// i.set(" \n\r\t-3005ABCDEF");
// REQUIRE(i == -3005);
// i.set("77.981");
// REQUIRE(i == 77);
// }
//}
//GIVEN("Special parsings for boolean") {
// aspartamev0::OptBool b {false};
// THEN("All sorts of weird values can be parsed") {
// b.set("vvv");
// REQUIRE(b);
// b.reset();
// b.set("Yaa");
// REQUIRE(b);
// b.reset();
// b.set(" \n\r\tT");
// REQUIRE(b);
// b.reset();
// }
//}
}
| true |
80fbc7d7c90127c18e935624576b69a45c55999a
|
C++
|
GwonDalhyeon/LevelSet
|
/FastMarching/FastMarchingLevelset.h
|
UTF-8
| 12,664 | 3.125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
struct LevelSet
{
int* pointIndex;
int xNum, yNum;
double* xCood;
double* yCood;
double* Phi;
double dx, dy;
int* pointStatus;
int alive, narrowBand, farAway;
int aliveCount, narrowBandCount, farAwayCount;
LevelSet();
LevelSet(int gridNum, double dX);
LevelSet(int gridNum, double dX, double* functionPhi);
LevelSet(int gridxNum, int gridyNum, double dX, double dY);
LevelSet(int gridxNum, int gridyNum, double dX, double dY, double* functionPhi);
LevelSet operator=(LevelSet orignal_LevelSet)
{
xNum = orignal_LevelSet.xNum;
yNum = orignal_LevelSet.yNum;
dx = orignal_LevelSet.dx;
dy = orignal_LevelSet.dy;
alive =orignal_LevelSet.alive;
narrowBand = orignal_LevelSet.narrowBand;
farAway = orignal_LevelSet.farAway;
pointIndex = new int [xNum*yNum];
pointStatus = new int [xNum*yNum];
xCood = new double [xNum*yNum];
yCood = new double [xNum*yNum];
Phi = new double [xNum*yNum];
for (int i = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
pointIndex[i+j*xNum]= orignal_LevelSet.pointIndex[i+j*xNum];
xCood[i+j*xNum] = orignal_LevelSet.xCood[i+j*xNum];
yCood[i+j*xNum] = orignal_LevelSet.yCood[i+j*xNum];
pointStatus[i+j*xNum] = orignal_LevelSet.pointStatus[i+j*xNum];
}
}
return *this;
}
double derivation2x(int i,int j, double* A);
double derivation2y(int i,int j, double* A);
double derivation1x_plus(int i,int j, double* A);
double derivation1y_plus(int i,int j, double* A);
double derivation1x_minus(int i,int j, double* A);
double derivation1y_minus(int i,int j, double* A);
};
LevelSet :: LevelSet()
{
dx = 0.0; dy = 0.0; pointStatus = NULL;
xNum=0; yNum=0; pointIndex=NULL; xCood=NULL; yCood=NULL; Phi = NULL;
alive=-1, narrowBand=0, farAway=1;
aliveCount=0, narrowBandCount=0, farAwayCount=xNum*yNum;
}
LevelSet::LevelSet(int gridNum, double dX)
{
alive=-1, narrowBand=0, farAway=1;
dx = dX;
dy = dX;
xNum = gridNum; yNum = gridNum;
pointIndex = new int [xNum*yNum];
xCood = new double [xNum*yNum];
yCood = new double [xNum*yNum];
Phi = new double [xNum*yNum];
pointStatus = new int[xNum*yNum];
aliveCount=0, narrowBandCount=0, farAwayCount=xNum*yNum;
for (int i = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
pointIndex[i+j*xNum]=i+j*xNum;
xCood[i+j*xNum] = -dx/2*((double)xNum-1) + dx* ((double)i);
yCood[i+j*xNum] = -dx/2*((double)yNum-1) + dx* ((double)j);
pointStatus[i+j*xNum] = farAway;
}
}
}
LevelSet::LevelSet(int gridNum, double dX, double* functionPhi)
{
dx = dX;
dy = dX;
alive=-1, narrowBand=0, farAway=1;
xNum = gridNum; yNum = gridNum;
pointIndex = new int [xNum*yNum];
xCood = new double [xNum*yNum];
yCood = new double [xNum*yNum];
Phi = new double [xNum*yNum];
pointStatus = new int[xNum*yNum];
aliveCount=0, narrowBandCount=0, farAwayCount=xNum*yNum;
for (int i = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
pointIndex[i+j*xNum]=i+j*xNum;
xCood[i+j*xNum] = -dx/2*((double)xNum-1) + dx* ((double)i);
yCood[i+j*xNum] = -dx/2*((double)yNum-1) + dx* ((double)j);
Phi[i+j*xNum]= functionPhi[i+j*xNum];
pointStatus[i+j*xNum] = farAway;
}
}
}
LevelSet::LevelSet(int gridxNum, int gridyNum, double dX, double dY)
{
dx = dX;
dy = dY;
alive=-1, narrowBand=0, farAway=1;
xNum = gridxNum; yNum = gridyNum;
pointIndex = new int [xNum*yNum];
xCood = new double [xNum*yNum];
yCood = new double [xNum*yNum];
Phi = new double [xNum*yNum];
pointStatus = new int[xNum*yNum];
aliveCount=0, narrowBandCount=0, farAwayCount=xNum*yNum;
for (int i = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
pointIndex[i+j*xNum]=i+j*xNum;
xCood[i+j*xNum] = -dx/2*((double)xNum-1) + dx* ((double)i);
yCood[i+j*xNum] = -dx/2*((double)yNum-1) + dx* ((double)j);
pointStatus[i+j*xNum] = farAway;
}
}
}
LevelSet::LevelSet(int gridxNum, int gridyNum, double dX, double dY, double* functionPhi)
{
dx = dX;
dy = dY;
alive=-1, narrowBand=0, farAway=1;
xNum = gridxNum; yNum = gridyNum;
pointIndex = new int [xNum*yNum];
xCood = new double [xNum*yNum];
yCood = new double [xNum*yNum];
Phi = new double [xNum*yNum];
pointStatus = new int[xNum*yNum];
aliveCount=0, narrowBandCount=0, farAwayCount=xNum*yNum;
for (int i = 0; i < xNum; i++)
{
for (int j = 0; j < yNum; j++)
{
pointIndex[i+j*xNum]=i+j*xNum;
xCood[i+j*xNum] = -dx/2*((double)xNum-1) + dx* ((double)i);
yCood[i+j*xNum] = -dx/2*((double)yNum-1) + dx* ((double)j);
Phi[i+j*xNum]= functionPhi[i+j*xNum];
pointStatus[i+j*xNum] = farAway;
}
}
}
#ifndef HeapsortAlgorithm_heapsort_h
#define HeapsortAlgorithm_heapsort_h
#include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;
struct HeapsortTree
{
int length;
int* indexArray;
double* dataArray;
bool* flagArray;
HeapsortTree();
HeapsortTree(int l);
void deleteHeap(struct HeapsortTree* inputHeap);
HeapsortTree operator=(HeapsortTree& originHeap)
{
length = NULL;
indexArray = NULL;
dataArray = NULL;
flagArray = NULL;
length = originHeap.length;
indexArray = new int [length];
dataArray = new double [length];
flagArray = new bool [length];
for (int i = 0; i < length; i++)
{
indexArray[i]=originHeap.indexArray[i];
dataArray[i]=originHeap.dataArray[i];
flagArray[i]=originHeap.flagArray[i];
}
}
// HeapsortTree(struct HeapsortTree *inputHeap);
// struct HeapsortTree *low;
// void makingTree(struct HeapsortTree inputheap);
};
HeapsortTree :: HeapsortTree()
{
length = 0;
indexArray= NULL;
dataArray = NULL;
flagArray = NULL;
}
HeapsortTree :: HeapsortTree(int l)
{
length =l; //(int) sizeof(inputArray)/2;
indexArray = new int [length];
dataArray = new double [length];
flagArray = new bool [length];
}
void HeapsortTree :: deleteHeap(struct HeapsortTree* inputHeap)
{
inputHeap->dataArray=NULL;
inputHeap->flagArray=NULL;
inputHeap->indexArray = NULL;
}
struct HeapsortTree* checkingUpSorting(struct HeapsortTree *inputHeap,int child)
{
int parent = floor((child-1)/2);
if (parent<0)
{
return NULL;
}
if (inputHeap->dataArray[parent]>inputHeap->dataArray[child])
{
double tempData = inputHeap->dataArray[child];
double tempIndex = inputHeap->indexArray[child];
inputHeap->dataArray[child] = inputHeap->dataArray[parent];
inputHeap->dataArray[parent] = tempData;
inputHeap->indexArray[child] = inputHeap->indexArray[parent];
inputHeap->indexArray[parent] = tempIndex;
inputHeap->flagArray[child] = true;
inputHeap->flagArray[parent] = false;
checkingUpSorting(inputHeap, parent);
return inputHeap ;
}
return NULL;
}
struct HeapsortTree* HeapInitial(double* inputArray, int arraySize)
{
struct HeapsortTree* temp= new HeapsortTree(arraySize);
temp->dataArray[0] = inputArray[0];
temp->indexArray[0]=0;
temp->flagArray[0]= true;
for (int i = 0; i < temp->length; i++)
{
if (2*i+1<temp->length)
{
temp->dataArray[2*i+1] = inputArray[2*i+1];
temp->indexArray[2*i+1] = 2*i+1;
temp->flagArray[2*i+1] = false;
if (temp->dataArray[i]>temp->dataArray[2*i+1])
{
double tempData = temp->dataArray[2*i+1];
int tempIndex = temp->indexArray[i];
temp->dataArray[2*i+1] = temp->dataArray[i];
temp->dataArray[i] = tempData;
temp->indexArray[i] = temp->indexArray[2*i+1];
temp->indexArray[2*i+1] = tempIndex;
temp->flagArray[2*i+1]=true;
temp->flagArray[i] = false;
checkingUpSorting(temp,i);
}
}
if (2*i+2<temp->length)
{
temp->dataArray[2*i+2] = inputArray[2*i+2];
temp->indexArray[2*i+2] = 2*i+2;
if (temp->dataArray[i]>temp->dataArray[2*i+2])
{
double tempData = temp->dataArray[2*i+2];
int tempIndex = temp->indexArray[i];
temp->dataArray[2*i+2] =temp-> dataArray[i];
temp->dataArray[i] = tempData;
temp->indexArray[i] = temp->indexArray[2*i+2];
temp->indexArray[2*i+2] = tempIndex;
temp->flagArray[2*i+2] = true;
temp->flagArray[i] = false;
checkingUpSorting(temp,i);
}
}
}
return temp;
}
struct HeapsortTree* HeapRearrange(struct HeapsortTree *inputHeap,int place)
{
if (2*place+1>=inputHeap->length)
{
inputHeap->flagArray[place] = true;
return inputHeap;
}
if (2*place+2 < inputHeap->length)
{
if (inputHeap->dataArray[2*place+1]>inputHeap->dataArray[2*place+2])
{
if (inputHeap->dataArray[2*place+2]<inputHeap->dataArray[place])
{
double tempData = inputHeap->dataArray[2*place+2];
int tempIndex = inputHeap->indexArray[2*place+2];
inputHeap->dataArray[2*place+2] =inputHeap-> dataArray[place];
inputHeap->dataArray[place] = tempData;
inputHeap->indexArray[2*place+2] = inputHeap->indexArray[2*place+2];
inputHeap->indexArray[place] = tempIndex;
inputHeap->flagArray[2*place+2] = false;
inputHeap->flagArray[place] = true;
HeapRearrange(inputHeap,2*place+2);
}
}
else
{
if (inputHeap->dataArray[2*place+1]<inputHeap->dataArray[place])
{
double tempData = inputHeap->dataArray[2*place+1];
int tempIndex = inputHeap->indexArray[2*place+1];
inputHeap->dataArray[2*place+1] = inputHeap->dataArray[place];
inputHeap->dataArray[place] = tempData;
inputHeap->indexArray[2*place+1] = inputHeap->indexArray[place];
inputHeap->indexArray[place] = tempIndex;
inputHeap->flagArray[2*place+1]=false;
inputHeap->flagArray[place] = true;
HeapRearrange(inputHeap,2*place+1);
}
}
}
else
{
if (inputHeap->dataArray[2*place+1]<inputHeap->dataArray[place])
{
double tempData = inputHeap->dataArray[2*place+1];
int tempIndex = inputHeap->indexArray[2*place+1];
inputHeap->dataArray[2*place+1] = inputHeap->dataArray[place];
inputHeap->dataArray[place] = tempData;
inputHeap->indexArray[2*place+1] = inputHeap->indexArray[place];
inputHeap->indexArray[place] = tempIndex;
inputHeap->flagArray[2*place+1]=false;
inputHeap->flagArray[place] = true;
for (int i = 0; i < inputHeap->length; i++)
{
cout <<inputHeap->indexArray[i]<<" = "<< inputHeap->dataArray[i]<<"\n";
}
cout<<"\n";
HeapRearrange(inputHeap,2*place+1);
}
}
return inputHeap;
}
struct HeapsortTree* diminish(struct HeapsortTree* originHeap)
{
struct HeapsortTree* resultHeap = new HeapsortTree(originHeap->length-1);
resultHeap->length = originHeap->length-1;
resultHeap->indexArray = new int [originHeap->length-1];
resultHeap->dataArray = new double [originHeap->length-1];
resultHeap->flagArray = new bool [originHeap->length-1];
resultHeap->indexArray[0]=originHeap->indexArray[resultHeap->length];
resultHeap->dataArray[0]=originHeap->dataArray[resultHeap->length];
resultHeap->flagArray[0]=originHeap->flagArray[resultHeap->length];
for (int i = 1; i < resultHeap->length; i++)
{
resultHeap->indexArray[i]=originHeap->indexArray[i];
resultHeap->dataArray[i]=originHeap->dataArray[i];
resultHeap->flagArray[i]=originHeap->flagArray[i];
}
return resultHeap;
}
struct HeapsortTree* diminish(struct HeapsortTree* originHeap, int level)
{
struct HeapsortTree* resultHeap = new HeapsortTree(originHeap->length-1);
resultHeap->length = level;
resultHeap->indexArray = new int [level];
resultHeap->dataArray = new double [level];
resultHeap->flagArray = new bool [level];
resultHeap->indexArray[0]=originHeap->indexArray[originHeap->length-1];
resultHeap->dataArray[0]=originHeap->dataArray[originHeap->length-1];
resultHeap->flagArray[0]=originHeap->flagArray[originHeap->length-1];
for (int i = 1; i < level; i++)
{
resultHeap->indexArray[i]=originHeap->indexArray[i-1 + originHeap->length - level];
resultHeap->dataArray[i]=originHeap->dataArray[i-1 + originHeap->length - level];
resultHeap->flagArray[i]=originHeap->flagArray[i-1 + originHeap->length - level];
}
return resultHeap;
}
struct HeapsortTree* HeapExtract(struct HeapsortTree *inputHeap, int level)
{
if (level==0)
{
return NULL;
}
if (level == inputHeap->length)
{
inputHeap->dataArray[0] = inputHeap->dataArray[0];
inputHeap->flagArray[0] = inputHeap->flagArray[0];
inputHeap->indexArray[0] = inputHeap->indexArray[0];
HeapExtract(inputHeap,level-1);
}
else
{
struct HeapsortTree* tempHeap = diminish(inputHeap, level);
struct HeapsortTree* tempResult = HeapRearrange(tempHeap,0);
for (int i = 0; i < tempResult->length; i++)
{
inputHeap->dataArray[inputHeap->length - level+i] = tempResult->dataArray[i];
inputHeap->flagArray[inputHeap->length - level+i] = tempResult->flagArray[i];
inputHeap->indexArray[inputHeap->length - level+i] = tempResult->indexArray[i];
}
HeapExtract(inputHeap,level-1);
}
return inputHeap;
}
#endif
| true |
41f1a8cef9d398da3a318a0aa0c10192b668d089
|
C++
|
marianbitsov23/TuesWork
|
/OOP/C++/required-hw-oop/test/clothing.h
|
UTF-8
| 492 | 2.59375 | 3 |
[] |
no_license
|
#ifndef CLOTHING_H
#define CLOTHING_H
#include <string>
#include <iostream>
#include "stock.h"
using namespace std;
class Clothing : public Stock{
public:
string color;
double size;
string material;
Clothing();
Clothing(string name, double price, double quantity, Provider provider, int shippingDays, string color, double size, string material);
Clothing(string color, double size, string material);
void print_info();
};
#endif
| true |
96931f44c2d36b0132f9f8a4095b453304f4cae8
|
C++
|
vitorgabrielmoura/Exercises
|
/C++/Ex08.cpp
|
ISO-8859-1
| 426 | 3.125 | 3 |
[] |
no_license
|
#include <iostream>
#include <math.h>
using namespace std;
/* Nos exerccios C e D, crie o quadro resumo, algoritmo descritivo e o cdigo fonte com base nos diagramas de blocos*/
int main(int argc, char** argv) {
setlocale(LC_ALL, "Portuguese");
const float G = 9.8;
float altura, TQ;
cout << "Digite a altura: ";
cin >> altura;
TQ = sqrt(2 * altura) / G;
cout << "O TQ vale " << TQ << endl;
return 0;
}
| true |
b6fa370fc43077e46311b22a7ec30dd241f8f88d
|
C++
|
slingthor/mathing
|
/mathing_test/Vector4Tests.cpp
|
UTF-8
| 5,475 | 3.296875 | 3 |
[] |
no_license
|
#include "pch.h"
#include "../mathing/Math/Vector4.h"
using namespace Math;
TEST(Vector4, initialization)
{
auto vector = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
EXPECT_EQ(1, vector.X());
EXPECT_EQ(2, vector.Y());
EXPECT_EQ(3, vector.Z());
EXPECT_EQ(4, vector.W());
}
TEST(Vector4, EqualsTrue)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
EXPECT_TRUE(vector1 == vector2);
}
TEST(Vector4, EqualsFalse)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(1.0f, 2.0f, 3.0f, 5.0f);
EXPECT_FALSE(vector1 == vector2);
}
TEST(Vector4, NotEqual)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(1.0f, 2.0f, 3.0f, 5.0f);
EXPECT_TRUE(vector1 != vector2);
}
TEST(Vector4, NotEqualFalse)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
EXPECT_FALSE(vector1 != vector2);
}
TEST(Vector4, Addition)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(5.0f, 6.0f, 7.0f, 8.0f);
auto sum = vector1 + vector2;
EXPECT_EQ(sum.X(), 6);
EXPECT_EQ(sum.Y(), 8);
EXPECT_EQ(sum.Z(), 10);
EXPECT_EQ(sum.W(), 12);
}
TEST(Vector4, Subtraction)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(8.0f, 7.0f, 6.0f, 5.0f);
auto difference = vector2 - vector1;
EXPECT_EQ(difference.X(), 7.0f);
EXPECT_EQ(difference.Y(), 5.0f);
EXPECT_EQ(difference.Z(), 3.0f);
EXPECT_EQ(difference.W(), 1.0f);
}
TEST(Vector4, ComponentMultiplication)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(5.0f, 6.0f, 7.0f, 8.0f);
auto product = vector1 * vector2;
EXPECT_EQ(product.X(), 5.0f);
EXPECT_EQ(product.Y(), 12.0f);
EXPECT_EQ(product.Z(), 21.0f);
EXPECT_EQ(product.W(), 32.0f);
}
TEST(Vector4, leftScalarMultiplication)
{
auto scalar = 2.0f;
auto vector = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto product = scalar * vector;
EXPECT_EQ(product.X(), 2.0f);
EXPECT_EQ(product.Y(), 4.0f);
EXPECT_EQ(product.Z(), 6.0f);
EXPECT_EQ(product.W(), 8.0f);
}
TEST(Vector4, rightScalarMultiplication)
{
auto vector = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto scalar = 2.0f;
auto product = vector * scalar;
EXPECT_EQ(product.X(), 2.0f);
EXPECT_EQ(product.Y(), 4.0f);
EXPECT_EQ(product.Z(), 6.0f);
EXPECT_EQ(product.W(), 8.0f);
}
TEST(Vector4, componentWiseDivision)
{
auto vector1 = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
auto vector2 = Vector4(5.0f, 6.0f, 12.0f, 8.0f);
auto quotent = vector2 / vector1;
EXPECT_EQ(quotent.X(), 5.0f);
EXPECT_EQ(quotent.Y(), 3.0f);
EXPECT_EQ(quotent.Z(), 4.0f);
EXPECT_EQ(quotent.W(), 2.0f);
}
TEST(Vector4, scalarDivision)
{
auto vector = Vector4(2.0f, 4.0f, 6.0f, 8.0f);
auto scalar = 2.0f;
auto product = vector / scalar;
EXPECT_EQ(product.X(), 1.0f);
EXPECT_EQ(product.Y(), 2.0f);
EXPECT_EQ(product.Z(), 3.0f);
EXPECT_EQ(product.W(), 4.0f);
}
TEST(Vector4, setters)
{
auto vector = Vector4();
vector.SetX(1.0f);
vector.SetY(2.0f);
vector.SetZ(3.0f);
EXPECT_EQ(vector.X(), 1);
EXPECT_EQ(vector.Y(), 2);
EXPECT_EQ(vector.Z(), 3);
}
TEST(Vector4, zero)
{
auto zero = Vector4::Zero();
EXPECT_EQ(zero.X(), 0);
EXPECT_EQ(zero.Y(), 0);
EXPECT_EQ(zero.Z(), 0);
EXPECT_EQ(zero.W(), 0);
}
TEST(Vector4, Distance)
{
auto distance = Vector4(1.0f, 1.0f, 1.0f, 1.0f).Distance(Vector4(1.0f, 1.0f, 1.0f, 2.0f));
EXPECT_EQ(1, distance);
}
TEST(Vector4, Magnitude)
{
auto magnitude = Vector4(0.0f, 0.0f, 0.0f, 2.0f).Magnitude();
EXPECT_EQ(magnitude, 2);
}
TEST(Vector4, SquaredMagnitude)
{
auto squaredMagnitude = Vector4(0.0f, 0.0f, 0.0f, 3.0f).SquaredMagnitude();
EXPECT_EQ(squaredMagnitude, 9);
}
TEST(Vector4, Normalized)
{
auto vector{ Vector4(4.0f,5.0f,6.0f,7.0f).Normalized() };
EXPECT_TRUE(abs(vector.X() - 0.356348f) < 0.001f);
EXPECT_TRUE(abs(vector.Y() - 0.44535f) < 0.001f);
EXPECT_TRUE(abs(vector.Z() - 0.534522f) < 0.001f);
EXPECT_TRUE(abs(vector.W() - 0.62361f) < 0.001f);
}
TEST(Vector4, DotProduct)
{
auto vector1{ Vector4(1.0f,2.0f,3.0f,4.0f) };
auto vector2{ Vector4(5.0f,6.0f,7.0f, 8.0f) };
auto dotProduct = vector1.Dot(vector2);
EXPECT_EQ(dotProduct, 70);
}
TEST(Vector4, Projection)
{
auto vector1{ Vector4(2.0f,2.0f,2.0f, 0.0f) };
auto vector2{ Vector4(1.0f,0.0f,0.0f, 0.0f) };
auto projVec1onVec2{ vector1.Projection(vector2) };
EXPECT_EQ(projVec1onVec2, Vector4(2.0f, 0.0f, 0.0f, 0.0f));
}
TEST(Vector4, AdditionAssignment)
{
auto vector{ Vector4(1.0f, 1.0f, 1.0f, 1.0f) };
vector += Vector4(2.0f, 2.0f, 2.0f, 2.0f);
EXPECT_EQ(vector, Vector4(3.0f, 3.0f, 3.0f, 3.0f));
}
TEST(Vector4, SubtractionAssignment)
{
auto vector{ Vector4(1.0f,1.0f,1.0f, 1.0f) };
vector -= { Vector4(2.0f, 2.0f, 2.0f, 2.0f)};
EXPECT_EQ(vector, Vector4(-1.0f, -1.0f, -1.0f, -1.0f));
}
TEST(Vector4, MultiplicationAssignment)
{
auto vector{ Vector4(1.0f,1.0f,1.0f, 1.0f) };
vector *= { Vector4(2.0f, 2.0f, 2.0f, 2.0f)};
EXPECT_EQ(vector, Vector4(2.0f, 2.0f, 2.0f, 2.0f));
}
TEST(Vector4, DivisionAssignment)
{
auto vector{ Vector4(1.0f,1.0f,1.0f, 1.0f) };
vector /= { Vector4(0.5f, 0.5f, 0.5f, 0.5f)};
EXPECT_EQ(vector, Vector4(2.0f, 2.0f, 2.0f, 2.0f));
}
TEST(Vector4, ScalarMultiplicationAssignment)
{
auto vector{ Vector4(1.0f, 1.0f, 1.0f, 1.0f) };
vector *= 2.0f;
EXPECT_EQ(vector, Vector4(2.0f, 2.0f, 2.0f, 2.0f));
}
TEST(Vector4, ScalarDivisionAssignment)
{
auto vector{ Vector4(4.0f, 4.0f, 4.0f, 4.0f) };
vector /= 2.0f;
EXPECT_EQ(vector, Vector4(2.0f, 2.0f, 2.0f, 2.0f));
}
| true |
819f524ed6f98d9a3ff8a62267370bd2a06088c4
|
C++
|
executors/futures-impl
|
/rapperswil-prototype/memory.hpp
|
UTF-8
| 11,155 | 3.03125 | 3 |
[] |
no_license
|
// Copyright (c) 2018 NVIDIA Corporation
// Author: Bryce Adelstein Lelbach <brycelelbach@gmail.com>
//
// Distributed under the Boost Software License v1.0 (boost.org/LICENSE_1_0.txt)
#if !defined(FUTURES_MEMORY_HPP)
#define FUTURES_MEMORY_HPP
#include <utility>
#include <new>
#include <memory>
#include <iterator>
#include "type_deduction.hpp"
///////////////////////////////////////////////////////////////////////////////
template <typename ForwardIt>
ForwardIt constexpr destroy(ForwardIt first, ForwardIt last)
{
for (; first != last; ++first)
destroy_at(std::addressof(*first));
return first;
}
template <typename Allocator, typename ForwardIt>
ForwardIt constexpr destroy(Allocator&& alloc, ForwardIt first, ForwardIt last)
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
for (; first != last; ++first)
destroy_at(alloc_T, std::addressof(*first));
return first;
}
template <typename ForwardIt, typename Size>
ForwardIt constexpr destroy_n(ForwardIt first, Size n)
{
for (; n > 0; (void) ++first, --n)
destroy_at(std::addressof(*first));
return first;
}
template <typename Allocator, typename ForwardIt, typename Size>
ForwardIt constexpr destroy_n(Allocator&& alloc, ForwardIt first, Size n)
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
for (; n > 0; (void) ++first, --n)
destroy_at(alloc_T, std::addressof(*first));
return first;
}
template <typename T>
void constexpr destroy_at(T* location)
{
location->~T();
}
template <typename Allocator, typename T>
void constexpr destroy_at(Allocator&& alloc, T* location)
{
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
traits::destroy(FWD(alloc), location);
}
template <typename ForwardIt, typename... Args>
void uninitialized_construct(
ForwardIt first, ForwardIt last, Args const&... args
)
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; current != last; ++current)
::new (static_cast<void*>(std::addressof(*current))) T(args...);
} catch (...) {
destroy(first, current);
throw;
}
}
template <typename Allocator, typename ForwardIt, typename... Args>
void uninitialized_allocator_construct(
Allocator&& alloc, ForwardIt first, ForwardIt last, Args const&... args
)
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
ForwardIt current = first;
try {
for (; current != last; ++current)
traits::construct(alloc_T, std::addressof(*current), args...);
} catch (...) {
destroy(alloc_T, first, current);
throw;
}
}
template <typename ForwardIt, typename Size, typename... Args>
void uninitialized_construct_n(
ForwardIt first, Size n, Args const&... args
)
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
ForwardIt current = first;
try {
for (; n > 0; (void) ++current, --n)
::new (static_cast<void*>(std::addressof(*current))) T(args...);
} catch (...) {
destroy(first, current);
throw;
}
}
template <typename Allocator, typename ForwardIt, typename Size, typename... Args>
void uninitialized_allocator_construct_n(
Allocator&& alloc, ForwardIt first, Size n, Args const&... args
)
{
using T = typename std::iterator_traits<ForwardIt>::value_type;
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
ForwardIt current = first;
try {
for (; n > 0; (void) ++current, --n)
traits::construct(alloc_T, std::addressof(*current), args...);
} catch (...) {
destroy(alloc_T, first, current);
throw;
}
}
///////////////////////////////////////////////////////////////////////////////
// wg21.link/p0316r0
template <typename T, typename Allocator>
struct allocator_delete final
{
using allocator_type
= typename std::remove_cv_t<std::remove_reference_t<Allocator>>::template
rebind<T>::other;
using pointer = typename std::allocator_traits<allocator_type>::pointer;
template <typename UAllocator>
allocator_delete(UAllocator&& other) noexcept
: alloc_(FWD(other))
{}
template <typename U, typename UAllocator>
allocator_delete(
allocator_delete<U, UAllocator> const& other
) noexcept
: alloc_(other.get_allocator())
{}
template <typename U, typename UAllocator>
allocator_delete(
allocator_delete<U, UAllocator>&& other
) noexcept
: alloc_(MV(other.get_allocator()))
{}
template <typename U, typename UAllocator>
allocator_delete& operator=(
allocator_delete<U, UAllocator> const& other
) noexcept
{
alloc_ = other.get_allocator();
return *this;
}
template <typename U, typename UAllocator>
allocator_delete& operator=(
allocator_delete<U, UAllocator>&& other
) noexcept
{
alloc_ = MV(other.get_allocator());
return *this;
}
void operator()(pointer p)
{
using traits = std::allocator_traits<allocator_type>;
if (nullptr != p)
{
traits::destroy(get_allocator(), p);
traits::deallocate(get_allocator(), p, 1);
}
}
allocator_type& get_allocator() noexcept { return alloc_; }
allocator_type const& get_allocator() const noexcept { return alloc_; }
void swap(allocator_delete& other) noexcept
{
using std::swap;
swap(alloc_, other.alloc_);
}
private:
allocator_type alloc_;
};
template <typename T, typename Allocator>
struct allocator_array_delete final
{
using allocator_type
= typename std::remove_cv_t<std::remove_reference_t<Allocator>>::template
rebind<T>::other;
using pointer = typename std::allocator_traits<allocator_type>::pointer;
template <typename UAllocator>
allocator_array_delete(UAllocator&& other, std::size_t n) noexcept
: alloc_(FWD(other)), count_(n)
{}
template <typename U, typename UAllocator>
allocator_array_delete(
allocator_array_delete<U, UAllocator> const& other
) noexcept
: alloc_(other.get_allocator()), count_(other.count_)
{}
template <typename U, typename UAllocator>
allocator_array_delete(
allocator_array_delete<U, UAllocator>&& other
) noexcept
: alloc_(MV(other.get_allocator())), count_(other.count_)
{}
template <typename U, typename UAllocator>
allocator_array_delete& operator=(
allocator_array_delete<U, UAllocator> const& other
) noexcept
{
alloc_ = other.get_allocator();
count_ = other.count_;
return *this;
}
template <typename U, typename UAllocator>
allocator_array_delete& operator=(
allocator_array_delete<U, UAllocator>&& other
) noexcept
{
alloc_ = MV(other.get_allocator());
count_ = other.count_;
return *this;
}
void operator()(pointer p)
{
using traits = std::allocator_traits<allocator_type>;
if (nullptr != p)
{
destroy_n(get_allocator(), p, count_);
traits::deallocate(get_allocator(), p, count_);
}
}
allocator_type& get_allocator() noexcept { return alloc_; }
allocator_type const& get_allocator() const noexcept { return alloc_; }
void swap(allocator_array_delete& other) noexcept
{
using std::swap;
swap(alloc_, other.alloc_);
swap(count_, other.count_);
}
private:
allocator_type alloc_;
std::size_t count_;
};
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename Allocator, typename... Args>
auto allocate_unique(
Allocator&& alloc, Args&&... args
)
{
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
auto hold_deleter = [&alloc_T] (auto p) {
traits::deallocate(alloc_T, p, 1);
};
using hold_t = std::unique_ptr<T, decltype(hold_deleter)>;
auto hold = hold_t(traits::allocate(alloc_T, 1), hold_deleter);
traits::construct(alloc_T, hold.get(), FWD(args)...);
auto deleter = allocator_delete<T, decltype(alloc_T)>(alloc_T);
return std::unique_ptr<T, decltype(deleter)>(hold.release(), move(deleter));
}
template <typename T, typename Allocator>
auto uninitialized_allocate_unique(
Allocator&& alloc
)
{
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
auto hold_deleter = [&alloc_T] (auto p) {
traits::deallocate(alloc_T, p, 1);
};
using hold_t = std::unique_ptr<T, decltype(hold_deleter)>;
auto hold = hold_t(traits::allocate(alloc_T, 1), hold_deleter);
auto deleter = allocator_delete<T, decltype(alloc_T)>(alloc_T);
return std::unique_ptr<T, decltype(deleter)>(hold.release(), move(deleter));
}
template <typename T, typename Allocator, typename Size, typename... Args>
auto allocate_unique_n(
Allocator&& alloc, Size n, Args&&... args
)
{
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
auto hold_deleter = [n, &alloc_T] (auto p) {
traits::deallocate(alloc_T, p, n);
};
using hold_t = std::unique_ptr<T, decltype(hold_deleter)>;
auto hold = hold_t(traits::allocate(alloc_T, n), hold_deleter);
uninitialized_allocator_construct_n(alloc_T, hold.get(), n, FWD(args)...);
auto deleter = allocator_array_delete<T, Allocator>(alloc_T, n);
return std::unique_ptr<T, decltype(deleter)>(hold.release(), move(deleter));
}
template <typename T, typename Allocator, typename Size>
auto uninitialized_allocate_unique_n(
Allocator&& alloc, Size n
)
{
using traits = typename std::allocator_traits<
std::remove_cv_t<std::remove_reference_t<Allocator>>
>::template rebind_traits<T>;
auto alloc_T = typename traits::allocator_type(FWD(alloc));
auto hold_deleter = [n, &alloc_T] (auto p) {
traits::deallocate(alloc_T, p, n);
};
using hold_t = std::unique_ptr<T[], decltype(hold_deleter)>;
auto hold = hold_t(traits::allocate(alloc_T, n), hold_deleter);
auto deleter = allocator_array_delete<T, Allocator>(alloc_T, n);
return std::unique_ptr<T[], decltype(deleter)>(hold.release(), move(deleter));
}
///////////////////////////////////////////////////////////////////////////////
#endif // FUTURES_MEMORY_HPP
| true |
ca421f517f9fa242d4dcac0f28bcfe6dab1af3b6
|
C++
|
Gimenesomenes/Carolina-
|
/mediapond.cpp
|
ISO-8859-2
| 242 | 2.578125 | 3 |
[] |
no_license
|
#include<stdio.h>
main(){
float a,b,c,mediapond;
printf("Digite as 3 notas\n");
scanf("%f", &a);
scanf("%f", &b);
scanf("%f", &c);
mediapond=((a*2)+(b*3)+(c*1))/6;
printf("A mdia ponderada das notas : %5.2f", mediapond);
}
| true |
bbe7e965dd3b7571afd35998fdc2cadfcac6dcd8
|
C++
|
Absurdius/c-misc
|
/lab4/nameserver/mns.h
|
UTF-8
| 376 | 2.53125 | 3 |
[] |
no_license
|
/*
* Interface MNS
* implement this interface.
*/
#ifndef MNS_H
#define MNS_H
#include <map>
class MNS : public NameServerInterface
{
public:
MNS();
virtual void insert(const HostName&, const IPAddress&);
virtual bool remove(const HostName&);
virtual IPAddress lookup(const HostName&) const;
private:
std::map<HostName, IPAddress> data;
};
#endif
| true |
b343f7c84e890a82f1c1a68402706bfd774ba05f
|
C++
|
ferluque/PracticaFinalED
|
/src/Ruta.cpp
|
UTF-8
| 1,768 | 3.359375 | 3 |
[] |
no_license
|
#include "Ruta.h"
using namespace std;
istream& operator>>(istream& in, Ruta& ruta) {
int num_puntos;
in >> num_puntos;
in.ignore();
for (int i=0; i<num_puntos; i++) {
Punto nuevo;
in >> nuevo;
ruta.puntos.push_back(nuevo);
in.ignore();
}
return in;
}
ostream& operator<<(ostream& out, const Ruta& ruta) {
out << ruta.puntos.size() << " ";
for (Ruta::const_iterator it = ruta.cbegin(); it != ruta.cend(); ++it) {
out << (*it) << " ";
}
out << endl;
return out;
}
// ITERATOR
Ruta::iterator::iterator(list<Punto>::iterator lit) : it(lit) {}
Ruta::iterator& Ruta::iterator::operator++() {
++it;
return *this;
}
Ruta::iterator& Ruta::iterator::operator--() {
--it;
return *this;
}
bool Ruta::iterator::operator!=(const Ruta::iterator& otro) {
return (it != otro.it);
}
Ruta::iterator Ruta::begin() {
iterator it(puntos.begin());
return it;
}
Ruta::iterator Ruta::end() {
iterator it(puntos.end());
return it;
}
Punto& Ruta::iterator::operator*() {
return (*it);
}
// CONST_ITERATOR
Ruta::const_iterator::const_iterator(list<Punto>::const_iterator clit) : cit(clit) {}
Ruta::const_iterator& Ruta::const_iterator::operator++() {
++cit;
return *this;
}
Ruta::const_iterator& Ruta::const_iterator::operator--() {
--cit;
return *this;
}
bool Ruta::const_iterator::operator!=(const Ruta::const_iterator& otro) {
return (cit != otro.cit);
}
const Punto& Ruta::const_iterator::operator*() {
return (*cit);
}
Ruta::const_iterator Ruta::cbegin() const {
const_iterator begin(puntos.cbegin());
return begin;
}
Ruta::const_iterator Ruta::cend() const {
const_iterator end(puntos.cend());
return end;
}
| true |
712fd49d1c4fb4b134f0e8cff5d681301a1467bc
|
C++
|
dwentzel/bounce
|
/headers/logging/log_sync.h
|
UTF-8
| 761 | 2.828125 | 3 |
[] |
no_license
|
#ifndef BOUNCE_LOGGING_LOG_SYNC_
#define BOUNCE_LOGGING_LOG_SYNC_
#include <ostream>
#include <sstream>
namespace bounce {
class LogSync {
public:
explicit LogSync(std::wostream& output_stream);
~LogSync();
template<typename T>
LogSync& operator<<(const T& t);
LogSync& operator<<(std::wostream& (*manip)(std::wostream&))
{
manip(buffer_stream_);
return *this;
}
private:
std::wostream& output_stream_;
std::wstringstream buffer_stream_;
};
template<typename T>
LogSync& LogSync::operator<<(const T& t)
{
buffer_stream_ << t;
return *this;
}
}
#endif // BOUNCE_LOGGING_LOG_SYNC_
| true |
a468524eeeeba60326ad1927c21f966294e32136
|
C++
|
AJ92/Math
|
/src/Geometry/sphere.cpp
|
UTF-8
| 653 | 3.140625 | 3 |
[] |
no_license
|
#include "Geometry/sphere.h"
Sphere::Sphere()
{
pos = Vector3(-1,-1,-1);
radius = -1;
}
Sphere::Sphere(Vector3 pos, double radius) :
pos(pos),
radius(radius)
{
}
Sphere::Sphere(double pos_x, double pos_y, double pos_z, double radius) :
pos(Vector3(pos_x,pos_y,pos_z)),
radius(radius)
{
}
Vector3 Sphere::getPos(){
return pos;
}
double Sphere::getRadius(){
return radius;
}
void Sphere::setPos(Vector3 pos){
this->pos = pos;
}
void Sphere::setPos(double pos_x, double pos_y, double pos_z){
this->pos = Vector3(pos_x, pos_y, pos_z);
}
void Sphere::setRadius(double radius){
this->radius = radius;
}
| true |
ec636e91c8681a8a364eca9a773931ab2e46a863
|
C++
|
kevin-plumyoen/Projet_UdeS_DX11
|
/Sources/VectorStorage.h
|
UTF-8
| 9,692 | 3.140625 | 3 |
[] |
no_license
|
#ifndef DEF_ECS_VECTOR_STORAGE_H
#define DEF_ECS_VECTOR_STORAGE_H
#include "Entity.h"
#include "StorageTraits.h"
#include <vector>
#include <utility>
#include <iterator>
#include <cassert>
// A storage must store components
// A storage must associate a component with an entity
struct EntityIndexAlreadyInUse{};
template<typename ComponentType>
class VectorStorage {
public:
using component_type = ComponentType;
#pragma region Iterators
class Iterator {
friend VectorStorage;
public:
using value_type = std::pair<Entity, component_type>;
using iterator_category = std::forward_iterator_tag;
using difference_type = std::size_t;
using pointer = value_type*;
using reference = value_type&;
private:
using component_pair = std::pair<Entity, component_type>;
const std::vector<bool>& alives;
std::vector<component_pair>& values;
std::size_t index;
Iterator(const std::vector<bool>& alives, std::vector<component_pair>& values) noexcept
: alives{ alives }
, values{ values }
, index{ values.size() } {
}
Iterator(const std::vector<bool>& alives, std::vector<component_pair>& values, std::size_t idx) noexcept
: Iterator{ alives, values } {
index = idx;
while (index < alives.size() && !alives[index]) {
++index;
}
}
public:
bool operator==(const Iterator& other) const noexcept {
return index == other.index;
}
bool operator!=(const Iterator& other) const noexcept {
return index != other.index;
}
Iterator & operator++() {
do {
++index;
} while(index < values.size() && !alives[index]);
return *this;
}
Iterator operator++(int) {
Iterator previous = *this;
++(*this);
return previous;
}
reference operator*() noexcept {
return values[index];
}
pointer operator->() noexcept {
return &values[index];
}
};
class ConstIterator {
friend VectorStorage;
public:
using value_type = std::pair<Entity, component_type>;
using iterator_category = std::forward_iterator_tag;
using difference_type = std::size_t;
using pointer = const value_type*;
using reference = const value_type&;
private:
using component_pair = std::pair<Entity, component_type>;
const std::vector<bool>& alives;
const std::vector<component_pair>& values;
std::size_t index;
ConstIterator(const std::vector<bool>& alives, const std::vector<component_pair>& values)
: alives{ alives }
, values{ values }
, index{ values.size() } {
}
ConstIterator(const std::vector<bool>& alives, const std::vector<component_pair>& values, std::size_t idx)
: ConstIterator{ alives, values } {
index = idx;
while (index < alives.size() && !alives[index]) {
++index;
}
}
public:
bool operator==(const ConstIterator& other) const noexcept {
return index == other.index;
}
bool operator!=(const ConstIterator& other) const noexcept {
return index != other.index;
}
ConstIterator & operator++() {
do {
++index;
} while(index < values.size() && !alives[index]);
return *this;
}
ConstIterator operator++(int) {
ConstIterator previous = *this;
++(*this);
return previous;
}
reference operator*() const noexcept {
return values[index];
}
pointer operator->() const noexcept {
return &values[index];
}
};
#pragma endregion Iterators
#pragma region EntityIterators
class EntityIterator {
friend VectorStorage;
public:
using value_type = Entity;
using iterator_category = std::forward_iterator_tag;
using difference_type = std::size_t;
using pointer = const value_type*;
using reference = const value_type&;
private:
using component_pair = std::pair<Entity, component_type>;
const std::vector<bool>& alives;
const std::vector<component_pair>& values;
std::size_t index;
EntityIterator(const std::vector<bool>& alives, const std::vector<component_pair>& values)
: alives{ alives }
, values{ values }
, index{ values.size() } {
}
EntityIterator(const std::vector<bool>& alives, const std::vector<component_pair>& values, std::size_t idx)
: EntityIterator{ alives, values } {
index = idx;
while (index < alives.size() && !alives[index]) {
++index;
}
}
public:
bool operator==(const EntityIterator& other) const noexcept {
return index == other.index;
}
bool operator!=(const EntityIterator& other) const noexcept {
return index != other.index;
}
EntityIterator & operator++() {
do {
++index;
} while(index < values.size() && !alives[index]);
return *this;
}
EntityIterator operator++(int) {
EntityIterator previous = *this;
++(*this);
return previous;
}
reference operator*() noexcept {
return values[index].first;
}
pointer operator->() noexcept {
return &values[index].first;
}
};
#pragma endregion EntityIterators
class Entities {
friend VectorStorage;
public:
using iterator = EntityIterator;
private:
iterator begin_, end_;
Entities(iterator begin, iterator end)
: begin_{ begin }, end_{ end } {
}
public:
iterator begin() const noexcept { return begin_; }
iterator end() const noexcept { return end_; }
};
private:
std::vector<bool> alives;
std::vector<std::pair<Entity, component_type>> components;
void prepare_space_for(Entity entity) {
const std::size_t new_size = entity.index() + 1;
if (new_size >= alives.size()) {
alives.resize(new_size, false);
components.resize(new_size);
}
}
public:
using iterator = Iterator;
using const_iterator = ConstIterator;
std::pair<iterator, bool> attach(Entity entity, const component_type& component) {
prepare_space_for(entity);
// Entity's index already attached but not the same entity
if (alives[entity.index()] && components[entity.index()].first != entity) {
throw EntityIndexAlreadyInUse{};
}
const bool value_inserted = !alives[entity.index()];
if(value_inserted) {
alives[entity.index()] = true;
components[entity.index()] = std::make_pair(entity, component);
}
return std::make_pair(iterator(alives, components, entity.index()),
value_inserted);
}
std::pair<iterator, bool> attach(Entity entity, component_type&& component) {
prepare_space_for(entity);
// Entity's index already attached but not the same entity
if (alives[entity.index()] && components[entity.index()].first != entity) {
throw EntityIndexAlreadyInUse{};
}
const bool value_inserted = !alives[entity.index()];
if(value_inserted) {
alives[entity.index()] = true;
components[entity.index()] = std::make_pair(entity, std::move(component));
}
return std::make_pair(iterator(alives, components, entity.index()),
value_inserted);
}
void detach(Entity entity) {
if (entity.index() < alives.size() && alives[entity.index()] && components[entity.index()].first == entity) {
alives[entity.index()] = false;
}
}
bool is_attached(Entity entity) const noexcept {
if (entity.index() < components.size() && alives[entity.index()]) {
return components[entity.index()].first == entity;
}
return false;
}
// Iterators on elements
iterator begin() noexcept { return iterator{alives, components, 0}; }
iterator end() noexcept { return iterator{alives, components}; }
const_iterator begin() const noexcept { return const_iterator{alives, components, 0}; }
const_iterator end() const noexcept { return const_iterator{alives, components}; }
const_iterator cbegin() const noexcept { return begin(); }
const_iterator cend() const noexcept { return end(); }
iterator find(Entity entity) noexcept {
if (entity.index() < alives.size()
&& alives[entity.index()]
&& components[entity.index()].first == entity) {
return iterator{alives, components, entity.index()};
}
return end();
}
const_iterator find(Entity entity) const noexcept {
if (entity.index() < alives.size()
&& alives[entity.index()]
&& components[entity.index()].first == entity) {
return const_iterator{alives, components, entity.index()};
}
return end();
}
// Iterators on entities
const Entities entities() const noexcept {
return Entities{EntityIterator{alives, components, 0}, EntityIterator{alives, components}};
}
void clear() {
alives.clear();
components.clear();
}
};
template<typename ComponentType>
struct is_storage<VectorStorage<ComponentType>> {
static constexpr const bool value = true;
};
#endif
| true |
5fc3fb4f1c27ba4afa8af71223e1868a7efec202
|
C++
|
Blast07/Leetcode
|
/factorial-trailing-zeroes.cpp
|
UTF-8
| 147 | 2.796875 | 3 |
[] |
no_license
|
class Solution {
public:
int trailingZeroes(int n) {
int res =0;
int five = 5;
while(n){
res += n/five;
n /= five;
}
return res;
}
};
| true |
2732dbc528ab62a4a68c7cc4331a31b1c712ba3a
|
C++
|
luhdriloh/c_the_quest
|
/vector_averages/vector_averages.cpp
|
UTF-8
| 716 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
double find_average(vector<double> numbers);
int main ()
{
vector<double> values;
double average;
double current_value;
while(cin >> current_value)
values.push_back(current_value);
cout << "the average of these numbers is "
<< find_average(values) << endl;
return 0;
}
double find_average(vector<double> numbers)
{
double sum = 0;
// vector<double>::size_type gives us the size of a vector no
// matter what size it is
typedef vector<double>::size_type vector_size;
vector_size number_size = numbers.size();
for(const double &i : numbers)
sum += i;
return sum / number_size;
}
| true |
ae7dbb1e82fb4c005dd753378992292dadcc77fb
|
C++
|
minisparrow/acm
|
/spiralmatrix.cpp
|
UTF-8
| 1,296 | 3.515625 | 4 |
[] |
no_license
|
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));// 结果矩阵
int i = 0;
int j = 0;// (i,j)指示当前所在格子
res[i][j] = 1;// 进入第一个格子,即左上角格子
while(res[i][j] != n * n)// 终止条件
{
while(j + 1 < n && 0 == res[i][j + 1])// 判断是否可以向右前进
{
res[i][j + 1] = res[i][j] + 1;
++j;// 向右前进一格并填充数据
}
while(i + 1 < n && 0 == res[i + 1][j])// 判断是否可以向下前进
{
res[i + 1][j] = res[i][j] + 1;
++i;// 向下前进一格并填充数据
}
while(j - 1 >= 0 && 0 == res[i][j - 1])// 判断是否可以向左前进
{
res[i][j - 1] = res[i][j] + 1;
--j;// 向左前进一格并填充数据
}
while(i - 1 >= 0 && 0 == res[i - 1][j])// 判断是否可以向上前进
{
res[i - 1][j] = res[i][j] + 1;
--i;// 向上前进一格并填充数据
}
}
return res;// 所有格子均走完,返回结果矩阵
}
};
| true |
04f4d65853cbf1663cb13209a29d803875c4ae38
|
C++
|
HackBL/Syracuse-University
|
/CIS-554/Fall 2019 Classnotes/2019_10_03_Lecture_LRvalue.cpp
|
UTF-8
| 767 | 3.765625 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
/*
Entity or expression that can only appear on right side of an assignment statement is Rvalue
Entity that can appear on either side of an assignment statement is Lvalue
*/
void addValue(int &value) { cout << value+10<< endl; } //Lvalue reference version
void addValue(int&& value) { cout << value +100<<endl; } //Rvalue reference version
int main() {
int i{ 1 }, j{ 2 };
addValue(i); //i is Lvalue; will call Lvalue version
addValue(j + 5); //j+5 is Rvalue; will call Rvalue version
addValue(500); //500 is Rvalue; will call Rvalue version
addValue(move(i)); //move(i) will temporarily cast i as R-value; and will call Rvalue vaersion
addValue(i);//i is still Lvalue; will call Lvalue version
cin.get();
return 0;
}
| true |
8ef4f69c69558313cfc91eb884df44da8da5404b
|
C++
|
zhuxb/C-ATTL3
|
/C-ATTL3/core/gpu/curand/CuRANDGenerator.hpp
|
UTF-8
| 2,364 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
/*
* CuRANDGenerator.hpp
*
* Created on: 5 Aug 2018
* Author: Viktor Csomor
*/
#ifndef C_ATTL3_CORE_GPU_CURAND_CURANDGENERATOR_H_
#define C_ATTL3_CORE_GPU_CURAND_CURANDGENERATOR_H_
#include "core/gpu/cuda/CUDAArray.hpp"
#include "CuRANDError.hpp"
namespace cattle {
namespace gpu {
namespace {
template<typename Scalar>
using NormalGenerationRoutine = curandStatus_t (*)(curandGenerator_t, Scalar*, std::size_t, Scalar, Scalar);
template<typename Scalar>
__inline__ NormalGenerationRoutine<Scalar> normal_gen_routine() { return &curandGenerateNormalDouble; }
template<> __inline__ NormalGenerationRoutine<float> normal_gen_routine() { return &curandGenerateNormal; }
template<typename Scalar>
using UniformGenerationRoutine = curandStatus_t (*)(curandGenerator_t, Scalar*, std::size_t);
template<typename Scalar>
__inline__ UniformGenerationRoutine<Scalar> uniform_gen_routine() { return &curandGenerateUniformDouble; }
template<> __inline__ UniformGenerationRoutine<float> uniform_gen_routine() { return &curandGenerateUniform; }
}
/**
* A template class for generating normally or uniformly distributed random numbers
* using the cuRAND generator.
*/
template<typename Scalar>
class CuRANDGenerator {
public:
static constexpr curandRngType_t RNG_TYPE = CURAND_RNG_PSEUDO_DEFAULT;
inline CuRANDGenerator() :
gen() {
curandAssert(curandCreateGenerator(&gen, RNG_TYPE));
}
inline ~CuRANDGenerator() {
curandAssert(curandDestroyGenerator(gen));
}
/**
* @param mean The mean of the distribution.
* @param sd The standard deviation of the distribution.
* @param array The device array to fill with the randomly generated numbers.
*/
inline void generate_normal(Scalar mean, Scalar sd, CUDAArray<Scalar>& array) const {
NormalGenerationRoutine<Scalar> norm_gen = normal_gen_routine<Scalar>();
curandAssert(norm_gen(gen, array.data(), array.size() * sizeof(Scalar), mean, sd));
}
/**
* @param array The device array to fill with the randomly generated numbers.
*/
inline void generate_uniform(CUDAArray<Scalar>& array) const {
UniformGenerationRoutine<Scalar> uni_gen = uniform_gen_routine<Scalar>();
curandAssert(uni_gen(gen, array.data(), array.size() * sizeof(Scalar)));
}
private:
curandGenerator_t gen;
};
} /* namespace gpu */
} /* namespace cattle */
#endif /* C_ATTL3_CORE_GPU_CURAND_CURANDGENERATOR_H_ */
| true |
ed55cd1b9df62a8769d9ce571c723075ee903654
|
C++
|
kiliakis/cpp-benchmark
|
/random_generators/tests/randomtest_synch_rad2.cpp
|
UTF-8
| 3,938 | 2.515625 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <random>
#include <chrono>
#include <math.h>
#include <stdlib.h>
#include <blond/vector_math.h>
#include <blond/utilities.h>
#include <blond/math_functions.h>
#include <blond/optionparser.h>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
using namespace std;
long int N_t = 1;
long int N_p = 100000;
int N_threads = 1;
long int n_kicks = 1;
string prog_name = "synch_rad2";
std::random_device rd;
boost::mt19937_64 gen(rd());
boost::normal_distribution<> dist(0.0, 1.0);
chrono::duration<double> synch_rad_d(0.0);
chrono::duration<double> rand_gen_d(0.0);
chrono::duration<double> quantum_d(0.0);
void parse_args(int argc, char **argv);
int main(int argc, char *argv[])
{
parse_args(argc, argv);
omp_set_num_threads(N_threads);
ofstream file(prog_name+"_numbers.txt");
for (int i = 0; i < N_t; i++) {
for (int j = 0; j < N_p; ++j)
{
file << dist(gen) << "\n";
}
}
return 0;
}
void parse_args(int argc, char **argv)
{
using namespace std;
using namespace option;
enum optionIndex {
UNKNOWN,
HELP,
N_THREADS,
N_TURNS,
N_PARTICLES,
N_KICKS,
OPTIONS_NUM
};
const option::Descriptor usage[] = {
{
UNKNOWN, 0, "", "", Arg::None, "USAGE: ./myprog [options]\n\n"
"Options:"
},
{
HELP, 0, "h", "help", Arg::None,
" --help, -h Print usage and exit."
},
{
N_TURNS, 0, "t", "turns", util::Arg::Numeric,
" --turns=<num>, -t <num> Number of turns (default: 500)"
},
{
N_KICKS, 0, "k", "n_kicks", util::Arg::Numeric,
" --kicks=<num>, -k <num> Number of kicks (default: 1)"
},
{
N_PARTICLES, 0, "p", "particles", util::Arg::Numeric,
" --particles=<num>, -p <num> Number of particles (default: "
"100k)"
},
{
N_THREADS, 0, "m", "threads", util::Arg::Numeric,
" --threads=<num>, -m <num> Number of threads (default: 1)"
},
{
UNKNOWN, 0, "", "", Arg::None,
"\nExamples:\n"
"\t./myprog\n"
"\t./myprog -t 1000 -p 10000 -m 4\n"
},
{0, 0, 0, 0, 0, 0}
};
argc -= (argc > 0);
argv += (argc > 0); // skip program name argv[0] if present
Stats stats(usage, argc, argv);
vector<Option> options(stats.options_max);
vector<Option> buffer(stats.buffer_max);
Parser parse(usage, argc, argv, &options[0], &buffer[0]);
if (options[HELP]) {
printUsage(cout, usage);
exit(0);
}
for (int i = 0; i < parse.optionsCount(); ++i) {
Option &opt = buffer[i];
// fprintf(stdout, "Argument #%d is ", i);
switch (opt.index()) {
case HELP:
// not possible, because handled further above and exits the program
case N_TURNS:
N_t = atoi(opt.arg);
// fprintf(stdout, "--numeric with argument '%s'\n", opt.arg);
break;
case N_KICKS:
n_kicks = atoi(opt.arg);
// fprintf(stdout, "--numeric with argument '%s'\n", opt.arg);
break;
case N_THREADS:
N_threads = atoi(opt.arg);
// fprintf(stdout, "--numeric with argument '%s'\n", opt.arg);
break;
case N_PARTICLES:
N_p = atoi(opt.arg);
// fprintf(stdout, "--numeric with argument '%s'\n", opt.arg);
break;
case UNKNOWN:
// not possible because Arg::Unknown returns ARG_ILLEGAL
// which aborts the parse with an error
break;
}
}
}
| true |
6b9907dc67b3f540f8302750f516091d84d9a490
|
C++
|
ryancarr/HackerRank
|
/30DaysOfCode/Day16/main.cpp
|
UTF-8
| 373 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::stoi;
using std::string;
int main()
{
string S;
cin >> S;
int result = NULL;
try
{
result = stoi(S);
cout << result << endl;
}
catch(std::exception e)
{
cout << "Bad String" << endl;
}
return 0;
}
| true |
2c2d7835771902d83efca4206940e7c5e27eb054
|
C++
|
L-Xiafeng/I_AM_A_UESTC_Student
|
/DataStruct课程/第三次上机实验.cpp
|
WINDOWS-1252
| 2,866 | 3.046875 | 3 |
[] |
no_license
|
//۰ by zhou Yuchuan
#include <bits/stdc++.h>
using namespace std;
#define END 999999
#define Info char
#define MAX 100
typedef struct{
int key;
Info data;
}RecType;
void QuickSort(RecType R[],int l,int r);
int partition(RecType R[],int l,int r);
int BinarySearch(RecType R[],int l,int r,int data);
int UpperBound(RecType R[],int l,int r,int data);
int LowerBound(RecType R[],int l,int r,int data);
void ReadFile(FILE*fp,RecType R[],int *n);
void Disp(RecType R[],int n);
void ChooseFind(RecType R[],int n)
{
printf("\n");
printf("Three choice and operation prompt:\nBinarySort: B/b\nUpperBound: U/u\nLowerBound: L/l\n");
printf("Please choose the method of sort: ");
char ch;
scanf("%c",&ch);
printf("\n");
printf("Enter the number you want to search: ");
int num;scanf("%d",&num);printf("\n");
switch(ch)
{
case 'B':case 'b':printf("The location of %d is %dth\n",num,BinarySearch(R,0,n,num));break;
case 'U':case 'u':printf("The location of %d is %dth\n",num,UpperBound(R,0,n,num));break;
case 'L':case 'l':printf("The location of %d is %dth\n",num,LowerBound(R,0,n,num));break;
default: printf("Illeagal Input\n");break;
}
}
int main(void)
{
FILE*fp;
if ((fp=fopen("in.txt","r"))==NULL)
{
perror("");
exit(EXIT_FAILURE);
}
RecType R[MAX];int n=0;
memset(R,0,sizeof(R));
ReadFile(fp,R,&n);fclose(fp);
printf("Before sort: ");Disp(R,n);
QuickSort(R,0,n);printf("After sort: ");Disp(R,n);
ChooseFind(R,n);
return 0;
}
void QuickSort(RecType R[],int l,int r)
{
int i;
if (l<r-1)
{
i=partition(R,l,r);
QuickSort(R,l,i);
QuickSort(R,i,r);
}
}
int partition(RecType R[],int l,int r)
{
int i=l,j=r-1;
RecType tmp=R[i];
while (i<j)
{
while (i<j&&R[j].key>=tmp.key)
j--;
R[i]=R[j];
while (i<j&&R[i].key<=tmp.key)
i++;
R[j]=R[i];
}
R[i]=tmp;
return i+1;
}
int BinarySearch(RecType R[],int l,int r,int data)
{
int mid;
while (l<r)
{
mid=(l+r)/2;
if (data==R[mid].key) return mid+1;
else if (R[mid].key>data)
r=mid;
else
l=mid+1;
}
printf("NOT Find!\n");
exit(EXIT_FAILURE);
}
int UpperBound(RecType R[],int l,int r,int data)
{
int mid;
while (l<r)
{
mid=(l+r)/2;
if (R[mid].key<=data)
l=mid+1;
else r=mid;
}
if (R[l-1].key!=data)
{
printf("NOT Find!\n");
exit(EXIT_FAILURE);
}
return l;
}
int LowerBound(RecType R[],int l,int r,int data)
{
int mid;
while (l<r)
{
mid=(l+r)/2;
if (R[mid].key>=data)
r=mid;
else l=mid+1;
}
if (R[l].key!=data)
{
printf("NOT Find!\n");
exit(EXIT_FAILURE);
}
return l+1;
}
void ReadFile(FILE*fp,RecType R[],int*n)
{
int i=0;
int num;
while (fscanf(fp,"%d",&num)!=EOF){
R[i++].key=num;
(*n)++;
}
R[i].key=END;
}
void Disp(RecType R[],int n)
{
int i;
for (i=0;i<n;i++)
{
printf("%d%c",R[i].key,i==n-1?'\t':' ');
}
printf("The sum of number is %d\n",n);
}
| true |
4842a81bd13fa9465933b65f917fda1462779689
|
C++
|
FrostyBonny/FundamentalsOfCompiling
|
/语义分析/main.cpp
|
UTF-8
| 14,663 | 2.796875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;
struct table {
string name;
int address;
};
fstream file;
fstream file_out;
vector<string> token;
string str;
vector<table *> varTable;
//int vartablep = 0;
int datap = 0;
int labelp = 0;
int declaration_list();
int statement_list();
int A();
int declaration_stat();
int B();
int if_stat();
int bool_expression();
int arithmetic_expression();
int term();
int factor();
int D();
int C();
int statement();
int while_stat();
int for_stat();
int assignment_expression();
int read_stat();
int write_stat();
int compound_stat();
int assignment_stat();
int name_def(string name);
int look_up(string name, int *address);
void error(string line, int state) {
cout << "第" << line << "行" << "发生" << state << "错误" << endl;
}
vector<string> splite(const string &s, const string &c)//分割字符用的
{
std::string::size_type pos1, pos2;
vector<string> v;
pos2 = s.find(c);
pos1 = 0;
while (std::string::npos != pos2) {
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if (pos1 != s.length()) {
v.push_back(s.substr(pos1));
}
return v;
}
void getNextLine() {
if (file.eof()) {
return;
}
getline(file, str);
if (str == "") {
token[0] = "错误";
token[1] = "错误";
return;
}
token = splite(str, " ");
cout << token[0] << " " << token[1] << " " << token[2] << endl;
}
void readFile() {
file.open("E:\\result.txt", ios::app | ios::out | ios::in);
if (!file.is_open()) {
cout << "读取词法分析结果文件出错" << endl;
}
file_out.open("E:\\final.txt", ios::trunc | ios::out);
if (!file_out.is_open()) {
cout << "打开输出文件出错" << endl;
}
}
int program() {
int state = 0;
getNextLine();
if (token[0] != "{") {
state = 1;
return state;
}
getNextLine();
state = declaration_list();
if (state != 0) {
return state;
}
state = statement_list();
if (state != 0) {
return state;
}
if (token[0] != "}") {
state = 2;
}
return state;
}
int statement_list() {
int state = 0;
if (token[0] == "if" || token[0] == "while" || token[0] == "for" || token[0] == "read" ||
token[0] == "write" || token[0] == "{" || token[0] == "ID" || token[0] == ";") {
// getNextLine();
state = B();
} else if (token[0] == "}") {
getNextLine();
} else {
state = 1;
}
return state;
}
int B() {
int state = 0;
if (token[0] == "if" || token[0] == "while" || token[0] == "for" || token[0] == "read" ||
token[0] == "write" || token[0] == "{" || token[0] == "ID" || token[0] == ";") {
// getNextLine();
state = statement();
if (state != 0) {
return state;
}
state = B();
} else if (token[0] == "}") {
state = 0;
} else {
state = 1;
}
return state;
}
int statement() {
int state = 0;
if (token[0] == "if") {
state = if_stat();
} else if (token[0] == "while") {
state = while_stat();
} else if (token[0] == "for") {
state = for_stat();
} else if (token[0] == "read") {
state = read_stat();
} else if (token[0] == "write") {
state = write_stat();
} else if (token[0] == "{") {
state = compound_stat();
} else if (token[0] == "ID") {
state = assignment_stat();
} else if (token[0] == ";") {
getNextLine();
state = 0;
}
return state;
}
int assignment_stat() {
int state = 0;
state = assignment_expression();
return state;
}
int compound_stat() {
int state = 0;
if (token[0] != "{") {
state = 1;
return state;
}
getNextLine();
state = statement_list();
if (state != 0) {
return state;
}
// getNextLine();
if (token[0] != "}") {
state = 1;
return state;
}
getNextLine();
return state;
}
int write_stat() {
int state = 0;
if (token[0] != "write") {
state = 1;
return state;
}
getNextLine();
state = arithmetic_expression();
if(state != 0){
return state;
}
// 1123代码
if(token[1] != ";"){
state = 4;
return state;
}
file_out<<" OUT"<<endl;
file_out<<" POP"<<endl;
getNextLine();
return state;
}
int read_stat() {
int state = 0;
int address;
if (token[0] != "read") {
state = 1;
return state;
}
getNextLine();
if (token[0] != "ID") {
state = 1;
}
state = look_up(token[1],&address);
if(state != 0) return state;
file_out<<" IN"<<endl;
file_out<<" STO "<<address<<endl;
file_out<<" POP"<<endl;
getNextLine();
// 1123代码
if(token[1] != ";"){
state = 4;
return state;
}
getNextLine();
return state;
}
int for_stat() {
int state = 0;
int lable1;
int lable2;
int lable3;
int lable4;
if (token[0] != "for") {
state = 1;
return state;
}
getNextLine();
if (token[0] != "(") {
state = 1;
return state;
}
getNextLine();
state = assignment_expression();
if (state != 0) {
return state;
}
if (token[0] != ";") {
state = 1;
return state;
}
lable1 = labelp++;
file_out<<"LABEL"<<lable1<<":"<<endl;
getNextLine();
state = bool_expression();
if (state != 0) {
return state;
}
lable2 = labelp++;
file_out<<" BRF LABEL"<<lable2<<endl;
lable3 = labelp++;
file_out<<" BR LABEL"<<lable3<<endl;
if (token[0] != ";") {
state = 1;
return state;
}
lable4 = labelp++;
file_out<<"LABEL"<<lable4<<":"<<endl;
getNextLine();
state = assignment_expression();
if (state != 0) {
return state;
}
file_out<<" BR LABEL"<<lable1<<endl;
if (token[0] != ")") {
state = 1;
return state;
}
file_out<<"LABEL"<<lable3<<":"<<endl;
getNextLine();
state = statement();
if(state != 0) return state;
file_out<<" BR LABEL"<<lable4<<endl;
file_out<<"LABEL"<<lable2<<":"<<endl;
return state;
}
int assignment_expression() {
int state = 0;
int address;
if (token[0] != "ID") {
state = 1;
return state;
}
state = look_up(token[1], &address);
if (state != 0) {
return state;
}
getNextLine();
if (token[0] != "=") {
state = 1;
return state;
}
getNextLine();
state = arithmetic_expression();
if (state != 0) {
return state;
}
// 1!!!!!!!
file_out << " STO " << address << endl;
file_out << " POP" << endl;
return state;
}
int while_stat() {
int state = 0;
int lable1;
int lable2;
lable1 = labelp++;
file_out<<"LABEL"<<lable1<<":"<<endl;
if (token[0] != "while") {
state = 1;
return state;
}
getNextLine();
if (token[0] != "(") {
state = 1;
return state;
}
getNextLine();
state = bool_expression();
if (state != 0) {
return state;
}
// getNextLine();
if (token[0] != ")") {
state = 1;
return state;
}
lable2 = labelp++;
file_out<<" BRF LABEL"<<lable2<<endl;
getNextLine();
state = statement();
if(state != 0){
return state;
}
file_out<<" BR LABEL"<<lable1<<endl;
file_out<<"LABEL"<<lable2<<":"<<endl;
return state;
}
int if_stat() {
int state = 0;
int lable1;
int lable2;
if (token[0] != "if") {
state = 1;
return state;
}
getNextLine();
if (token[0] != "(") {
state = 1;
return state;
}
getNextLine();
state = bool_expression();
if (state != 0) {
return state;
}
if (token[0] != ")") {
state = 1;
return state;
}
// !!!!!!!!
lable1 = labelp++;
file_out<<" BRF LABEL"<<lable1<<endl;
getNextLine();
state = statement();
if (state > 0) {
return state;
}
// !!!!!!!1
lable2 = labelp++;
file_out<<" BR LABEL"<<lable2<<endl;
file_out<<"LABEL"<<lable1<<":"<<endl;
if (token[0] == "else") {
getNextLine();
state = statement();
}
file_out<<"LABEL"<<lable2<<":"<<endl;
return state;
}
int bool_expression() {
int state = 0;
if (token[0] == "(" || token[0] == "ID" || token[0] == "NUM") {
state = arithmetic_expression();
if (state != 0) {
return state;
}
if (token[0] == ">" || token[0] == "<" || token[0] == ">=" ||
token[0] == "<=" || token[0] == "==" || token[0] == "!=") {
string temp = token[0];
getNextLine();
state = arithmetic_expression();
if (state != 0) {
return state;
}
// !!!!!!!!!!!!!!
if (temp == ">") file_out << " GT" << endl;
if (temp == ">=") file_out << " GE" << endl;
if (temp == "<") file_out << " LES" << endl;
if (temp == "<=") file_out << " LE" << endl;
if (temp == "==") file_out << " EQ" << endl;
if (temp == "!=") file_out << " NOTEQ" << endl;
} else {
state = 1;
}
}
return state;
}
int arithmetic_expression() {
int state = 0;
if (token[0] == "(" || token[0] == "ID" || token[0] == "NUM") {
state = term();
if (state != 0) {
return state;
}
state = C();
} else {
state = 1;
}
return state;
}
int C() {
int state = 0;
if (token[0] == "+" || token[0] == "-") {
string temp = token[0];
getNextLine();
state = term();
if (state != 0) {
return state;
}
// !!!!!!!!!!!!!
if (temp == "+") file_out << " ADD" << endl;
if (temp == "-") file_out << " SUB" << endl;
state = C();
} else if (token[0] == ">" || token[0] == "<" || token[0] == ">=" ||
token[0] == "<=" || token[0] == "==" || token[0] == "!=" ||
token[0] == ")" || token[0] == ";") {
state = 0;
} else {
state = 1;
}
return state;
}
int term() {
int state = 0;
if (token[0] == "(" || token[0] == "ID" || token[0] == "NUM") {
state = factor();
if (state != 0) {
return state;
}
state = D();
} else {
state = 1;
}
return state;
}
int D() {
int state = 0;
if (token[0] == "*" || token[0] == "/") {
string temp = token[0];
getNextLine();
state = factor();
if (state != 0) {
return state;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (temp == "*") file_out << " MULT" << endl;
if (temp == "/") file_out << " DIV" << endl;
// getNextLine();
state = D();
} else if (token[0] == ">" || token[0] == "<" || token[0] == ">=" ||
token[0] == "<=" || token[0] == "==" || token[0] == "!=" ||
token[0] == "+" || token[0] == "-" || token[0] == ";" || token[0] == ")") {
state = 0;
} else {
state = 1;
}
return state;
}
int factor() {
int state = 0;
if (token[0] == "(") {
getNextLine();
state = arithmetic_expression();
if (state != 0) {
return state;
}
getNextLine();
} else if (token[0] == "ID") {
int address;
state = look_up(token[1], &address);
if (state != 0) {
return state;
}
file_out << " LOAD " << address << endl; // !!!!!!!!!!!!!!!!!!
getNextLine();
} else if (token[0] == "NUM") {
file_out << " LOADI " << token[1] << endl; // !!!!!!!!!!!!!!!!!!
getNextLine();
} else {
state = 1;
}
return state;
}
int declaration_list() {
int state = 0;
if (token[0] == "int") {
state = A();
return state;
} else {
state = 3;
return state;
}
}
int A() {
int state = 0;
if (token[0] == "int") {
state = declaration_stat();
if (state > 0) {
return state;
}
state = A();
return state;
} else if (token[0] == "if" || token[0] == "while" || token[0] == "for" ||
token[0] == "read" || token[0] == "write" ||
token[0] == "{" || token[0] == ";" ||
token[0] == "ID" || token[0] == "(" ||
token[0] == "NUM" || token[0] == "}") {
return 0;
} else {
state = 4;
return state;
}
}
int declaration_stat() {
int state = 0;
if (token[0] != "int") {
state = 5;//缺少类型标识符
}
getNextLine();
if (token[0] != "ID") {
state = 6;//不是标识符号
return state;
}
state = name_def(token[1]);
getNextLine();
if (token[0] != ";") {
state = 7;//缺少分号
return state;
}
getNextLine();
return state;
}
int name_def(string name) {
int state = 0;
vector<table *>::iterator iterator1 = varTable.begin();
for (; iterator1 != varTable.end(); iterator1++) {
if ((*iterator1)->name == name) {
state = 30;// 变量重复定义
return state;
}
}
table *temp = new table;
temp->name = name;
temp->address = datap;
datap++;
varTable.push_back(temp);
return state;
}
int look_up(string name, int *address) {
int state = 0;
vector<table *>::iterator iterator1 = varTable.begin();
for (; iterator1 != varTable.end(); iterator1++) {
if ((*iterator1)->name == name) {
*address = (*iterator1)->address;
return state;
}
}
state = 23;//变量未声明
return state;
}
void closeFile() {
file.close();
file_out.close();
}
int main() {
int state = 0;
readFile();
state = program();
if (state != 0) {
error(token[2], state);
} else {
cout << "成功" << endl;
}
closeFile();
return 0;
}
| true |
758d1f63f5ace1fcbaff109dc99d9999f135f630
|
C++
|
fink-arthur/C-PvZ-Project
|
/src/MoneyTurret.cpp
|
UTF-8
| 930 | 2.921875 | 3 |
[] |
no_license
|
#include "MoneyTurret.h"
#include "Environment.h"
#include "GraphicPrimitives.h"
#include <ctime>
#include <sys/time.h>
MoneyTurret::~MoneyTurret(){
}
/* This function makes the player gain 4 money every second the game is running */
void MoneyTurret::act() {
struct timeval tp2;
gettimeofday(&tp2, NULL);
time2 = tp2.tv_sec * 1000000 + tp2.tv_usec;
if ((time2 - time1) > 1000000) {
Environment::money += 4;
struct timeval tp1;
gettimeofday(&tp1, NULL);
time1 = tp1.tv_sec * 1000000 + tp1.tv_usec;
}
}
/* This function draws the turret */
void MoneyTurret::draw() {
GraphicPrimitives::drawFillRect2D(posX - 0.003f, posY - 0.05f, 0.1f, 0.1f, r, g, b);
GraphicPrimitives::drawFillRect2D(posX - 0.01f, posY + 0.06f, 0.12f, 0.026f, 0.0f, 0.0f, 0.0f);
for( int i = 0; i < health_points; i++) {
GraphicPrimitives::drawFillRect2D((posX - 0.008f) + (i * 0.023), posY + 0.062f, 0.023f, 0.02f, 1.0f, 1.0f, 1.0f);
}
}
| true |
815e6dc063871fee823741c35681b9aae95029aa
|
C++
|
Autoquark/SdlBreakout
|
/SdlBreakout/SdlBreakout.Library/Point.cpp
|
UTF-8
| 1,404 | 2.78125 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "Point.h"
#include "AxisAlignedRectF.h"
#include "Line.h"
std::optional<Contact> Point::CastAgainst(const Shape& other, const Vector2F& movement, const InternalityFilter internalityFilter) const
{
return other.CastAgainstThis(*this, movement, internalityFilter);
}
std::optional<Contact> Point::CastAgainstThis(const AxisAlignedRectF& other, const Vector2F& movement, const InternalityFilter internalityFilter) const
{
throw new std::exception();
}
std::optional<Contact> Point::CastAgainstThis(const CircleF& other, const Vector2F& movement, const InternalityFilter internalityFilter) const
{
throw new std::exception();
}
std::optional<Contact> Point::CastAgainstThis(const Point& other, const Vector2F& movement, const InternalityFilter internalityFilter) const
{
throw new std::exception();
}
std::optional<Contact> Point::CastAgainstThis(const Line& other, const Vector2F& movement, const InternalityFilter internalityFilter) const
{
return optionalUtilities::Apply<Contact>(other.CastAgainstThis(*this, -movement, internalityFilter), [&](auto x)
{
return x.Invert(-movement, other.GetCentre());
});
}
void Point::Translate(Vector2F amount)
{
position += amount;
}
void Point::SetCentre(Vector2F position)
{
this->position = position;
}
AxisAlignedRectF Point::GetAxisAlignedBoundingBox() const
{
return AxisAlignedRectF(position, Vector2F(0, 0));
}
| true |
9d16233924b30e0d8300755d30739dc502a799e6
|
C++
|
pipo-chen/mooc-datastruct
|
/data-struct/PK/main.cpp
|
UTF-8
| 636 | 2.71875 | 3 |
[] |
no_license
|
//
// main.cpp
// PK
//
// Created by mk on 2021/7/20.
//
#include <iostream>
/**
5 局 3 胜 每一局都有两队伍的变化
*/
int main(int argc, const char * argv[]) {
int a = 100, b = 100, a_win = 0, b_win = 0;
for (int i = 0; i < 5; i++) {
//a 循环一百次 b 循环 100 ci
for (int a_score = 0; a_score < 101; a_score++) {
for (int b_score = 0; b_score < 101; b++) {
if (b_score < a_score) {
a_win
}
}
}
//每 5 次 记录一下胜利
}
//记录max 最大的时候 a b 的情况
return 0;
}
| true |
16092d544dae4379b3f87e3d07cdbfc18c62adc6
|
C++
|
sjzlyl406/Practice
|
/test75.cpp
|
UTF-8
| 3,605 | 3.046875 | 3 |
[
"LicenseRef-scancode-boost-original"
] |
permissive
|
/*************************************************************************
> File Name: test75.cpp
> Author: leon
> Mail: sjzlyl406@163.com
> Created Time: 2015年07月09日 星期四 21时28分13秒
************************************************************************/
/*********************************************************************
* 在路由器中,一般来说转发模块采用最大前缀匹配原则进行目的端口查找,具体如下:
* IP地址和子网地址匹配:
* IP地址和子网地址所带掩码做AND运算后,得到的值与子网地址相同,则该IP地址与该子网匹配。
*
* 比如:
* IP地址:192.168.1.100
* 子网:192.168.1.0/255.255.255.0,其中192.168.1.0是子网地址,255.255.255.0是子网掩码。
* 192.168.1.100&255.255.255.0 = 192.168.1.0,则该IP和子网192.168.1.0匹配
* IP地址:192.168.1.100
* 子网:192.168.1.128/255.255.255.192
* 192.168.1.100&255.255.255.192 = 192.168.1.64,则该IP和子网192.168.1.128不匹配
* 最大前缀匹配:
* 任何一个IPv4地址都可以看作一个32bit的二进制数,
* 比如192.168.1.100可以表示为:11000000.10101000.00000001.01100100,
* 192.168.1.0可以表示为11000000.10101000.00000001.00000000
* 最大前缀匹配要求IP地址同子网地址匹配的基础上,二进制位从左到右完全匹配的位数尽量多(从左到右子网地址最长)。比如:
* IP地址192.168.1.100,同时匹配子网192.168.1.0/255.255.255.0和子网192.168.1.64/255.255.255.192,
* 但对于子网192.168.1.64/255.255.255.192,匹配位数达到26位,多于子网192.168.1.0/255.255.255.0的24位,因此192.168.1.100最大前缀匹配子网是192.168.1.64/255.255.255.192。
* 示例
* 输入:
* ip_addr = "192.168.1.100"
* net_addr_array[] =
* {
* "192.168.1.128/255.255.255.192",
* "192.168.1.0/255.255.255.0",
* "192.168.1.64/255.255.255.192",
* "0.0.0.0/0.0.0.0",
* ""
* }
* 输出:n = 2
* ****************************************************************/
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
void toNum(std::string str,unsigned int *num)
{
std::stringstream ss(str);
char c;
ss >> num[0] >> c >> num[1] >> c >> num[2] >> c >> num[3];
}
bool isMatch(unsigned int *ipnum, unsigned int *net, unsigned int *mat)
{
bool ret = true;
for(int i = 0; i < 4; ++i) {
if((ipnum[i]&mat[i]) != (net[i]&mat[i]))
ret = false;
}
return ret;
}
bool isMaxMatch(const std::string &str1, const std::string &str2)
{
size_t index = str1.find('/');
std::string netstr1(str1.substr(index+1));
index = str2.find('/');
std::string netstr2(str2.substr(index+1));
return netstr1 > netstr2;
}
int ip(std::string ipstr, std::vector<std::string> netvec)
{
unsigned int ipnum[4] = {0};
unsigned int net[4] = {0};
unsigned int mat[4] = {0};
int ret = -1;
size_t index = 0;
toNum(ipstr, ipnum);
for(index = 0; index != netvec.size(); ++index) {
size_t Dash = netvec[index].find('/');
toNum(netvec[index].substr(0, Dash), net);
toNum(netvec[index].substr(Dash+1), mat);
std::cout << net[3] << mat[3] << ipnum[3]<< std::endl;
if(isMatch(ipnum, net, mat)) {
if(ret == -1)
ret = index;
else {
if(isMaxMatch(netvec[index], netvec[ret]))
ret = index;
}
}
}
return ret+1;
}
int main(void)
{
std::string ip_addr;
std::vector<std::string> net_addr_array;
std::string tmp;
std::cin >> ip_addr;
std::cin.get();
while(std::cin >> tmp) {
net_addr_array.push_back(tmp);
}
int n = ip(ip_addr, net_addr_array);
std::cout << n << std::endl;
return 0;
}
| true |
ff41a775a4998acac87b0795515f6911a24608d8
|
C++
|
alisatsar/itstep
|
/CPP/template/array/array.h
|
UTF-8
| 1,263 | 3.65625 | 4 |
[] |
no_license
|
#pragma once
template<class T, int N>
class Array
{
public:
T m_array[N];
Array();
/*в классе
template<int N1>
Array(Array<T, N1> const& rhs)
{
for (int i = 0; i < N1; i++)
{
m_array[i] = i < N1 ? rhs.m_array[i] : T(); //T() конструктор по умолчанию, который заполняется 0
}
}*/
template<int N1>
Array(Array<T, N1> const& rhs);
T& operator[](int ind);
int GetSize() const;
template<int N1>
Array<T, N>& operator=(const Array<T, N1>& rhs);
};
template<class T, int N>
template<int N1>
Array<T, N>& Array<T, N>::operator=(const Array<T, N1>& rhs)
{
if ((void*)this != (void*)&rhs)
{
for (int i = 0; i < N; ++i)
{
m_array[i] = i < N1 ? rhs.m_array[i] : T();
}
}
return *this;
}
//за классом
template<class T, int N>
template<int N1>
Array<T, N>::Array(const Array<T, N1>& rhs)
{
for (int i = 0; i < N; ++i)
{
m_array[i] = i < N1 ? rhs.m_array[i] : T();
}
}
template<class T, int N>
Array<T, N>::Array()
{
memset(m_array, 0, N);
}
template<class T, int N>
T& Array<T, N>:: operator[](int ind)
{
if (ind < 0 || ind >= N)
{
std::cout << "Invalid index!\n";
}
return m_array[ind];
}
template<class T, int N>
int Array<T, N>::GetSize() const
{
return N;
}
| true |
813be433ccb6124c6e9be3e9fc5710c45a182823
|
C++
|
josthelvish/Edx-DEV210.2x-LAB2
|
/Student.cpp
|
UTF-8
| 417 | 2.828125 | 3 |
[] |
no_license
|
//
// Created by jsilva on 19-12-2017.
//
#include "Student.h"
Student::Student(const string &firstName, const string &lastName, int age, const string &address, const string &city,
unsigned int phoneNumber) : Person(firstName, lastName, age, address, city, phoneNumber) {}
Student::Student() : Person() {
}
void Student::sitInClass() {
std::cout << "Sitting in main theater" << std::endl;
}
| true |
9997ff531e5a364a59331d20f9861179ad5e185e
|
C++
|
Girl-Code-It/Beginner-CPP-Submissions
|
/Urvashi/milestone-28(Hashmaps)/Leetcode/Level-2/Top_K_Frequent_Words.cpp
|
UTF-8
| 733 | 3.0625 | 3 |
[] |
no_license
|
bool cmp(const pair<int, string> &a, const pair<int, string> &b)
{
if (a.first > b.first)
return true;
else if (a.first == b.first)
return (a.second < b.second);
else
return false;
}
class Solution
{
public:
vector<string> topKFrequent(vector<string> &words, int k)
{
map<string, int> m;
for (auto i : words)
m[i]++;
vector<pair<int, string>> v;
for (auto i : m)
v.push_back({i.second, i.first});
sort(v.begin(), v.end(), cmp);
vector<string> ans;
for (auto i : v)
{
ans.push_back(i.second);
if (ans.size() == k)
break;
}
return ans;
}
};
| true |
3d66af334598072a770c7b7c738ffb045d28aa3c
|
C++
|
frogost/Task1
|
/main.cpp
|
UTF-8
| 205 | 3.1875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
char c = 125;
cout << char(c*3) << endl;
cout << char(c/3) << endl;
cout << char(c+3) << endl;
cout << char(c-3);
return 0;
}
| true |
6711d8a721390fa458cbc558a2fbd7e3f1894d57
|
C++
|
LowCostCustoms/asio_coro
|
/tests/test_async_wait.cpp
|
UTF-8
| 1,006 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#include "asio_coro/asio_coro.hpp"
#include "catch2/catch.hpp"
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
TEST_CASE("async_wait returns an awaitable that resumes the coroutine upon the associated timer is triggered") {
boost::system::error_code wait_error;
std::chrono::steady_clock::time_point wait_started_at;
std::chrono::steady_clock::time_point wait_expired_at;
boost::asio::io_context context;
asio_coro::spawn_coroutine(context, [&]() mutable -> asio_coro::task<void> {
boost::asio::steady_timer timer(context);
wait_started_at = std::chrono::steady_clock::now();
timer.expires_at(wait_started_at + std::chrono::milliseconds(100));
wait_error = co_await asio_coro::async_wait(timer);
wait_expired_at = std::chrono::steady_clock::now();
});
context.run();
REQUIRE(!wait_error);
REQUIRE(std::chrono::duration_cast<std::chrono::milliseconds>(wait_expired_at - wait_started_at) >=
std::chrono::milliseconds(100));
}
| true |
c2431301ac4638c12ffaff9efae4753f6c4d85b7
|
C++
|
makredzic/zadaca3
|
/zad5/main.cpp
|
UTF-8
| 593 | 3.578125 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
template<typename Iter> bool jednako(Iter it1begin, Iter it1end, Iter it2begin) {
while(it1begin != it1end) {
if (*it1begin != *it2begin) return false;
it1begin++;
it2begin++;
}
return true;
}
int main() {
std::string rijec;
std::cout << "Unesite rijec: ";
while(std::cin >> rijec) {
std::string reverse = std::string(rijec.rbegin(), rijec.rend());
if (jednako(rijec.begin(), rijec.end(), reverse.begin())) std::cout << "Rijec je palindrom.\n"; else std::cout<< "Rijec nije palindrom.\n";
}
return 0;
}
| true |
f206c2b0d88e6f59fe82205a20741c843cf8a4b6
|
C++
|
teddy8997/LeetCode
|
/Medium/22. Generate Parentheses/generateParenthesis.cpp
|
UTF-8
| 732 | 3.609375 | 4 |
[] |
no_license
|
/*
time complexity: O(2^n)
space complexity: O(k + n)
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
string cur = "";
vector<string> ans;
if(n > 0){
dfs(n, n, cur, ans);
}
return ans;
}
private:
void dfs(int l, int r, string &cur, vector<string> &ans){
if(l + r == 0){
ans.push_back(cur);
return;
}
if(r < l){
return;
}
if(l > 0){
cur += '(';
dfs(l - 1, r, cur, ans);
cur.pop_back();
}
if(r > 0){
cur += ')';
dfs(l, r - 1, cur, ans);
cur.pop_back();
}
}
};
| true |
17d7aa5befa8cbe63c20c8b2b6e72c86020f44ea
|
C++
|
nodakai/exp
|
/ofstreamPerf.cpp
|
UTF-8
| 2,957 | 2.6875 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
#include <time.h>
long long diffTimespecUsec(const ::timespec &a, const ::timespec &b)
{
return (a.tv_sec - b.tv_sec) * 1000 * 1000 + (a.tv_nsec - b.tv_nsec) / 1000;
}
static ::timespec ts0, ts1;
static long long d0, d1, d2, d3, d4, d5, d6, d7;
#define PRT(x) cout << #x " == " << x << " us." << endl
static void test01()
{
__asm__ __volatile__ ("# NOP" : : );
{
::clock_gettime(CLOCK_REALTIME, &ts0);
ifstream ifs("/home/nodakai/.vimrc");
::clock_gettime(CLOCK_REALTIME, &ts1);
d0 = diffTimespecUsec(ts1, ts0);
}
__asm__ __volatile__ ("# NOP" : : );
{
ifstream ifs;
::clock_gettime(CLOCK_REALTIME, &ts0);
ifs.open("/home/nodakai/.vimrc");
::clock_gettime(CLOCK_REALTIME, &ts1);
d1 = diffTimespecUsec(ts1, ts0);
}
__asm__ __volatile__ ("# NOP" : : );
{
ifstream ifs("/home/nodakai/.vimrc");
::clock_gettime(CLOCK_REALTIME, &ts0);
ifs.close();
::clock_gettime(CLOCK_REALTIME, &ts1);
d2 = diffTimespecUsec(ts1, ts0);
}
__asm__ __volatile__ ("# NOP" : : );
{
{
ifstream ifs("/home/nodakai/.vimrc");
::clock_gettime(CLOCK_REALTIME, &ts0);
}
::clock_gettime(CLOCK_REALTIME, &ts1);
d3 = diffTimespecUsec(ts1, ts0);
}
__asm__ __volatile__ ("# NOP" : : );
PRT(d0);
PRT(d1);
PRT(d2);
PRT(d3);
}
#define GET(ts) ::clock_gettime(CLOCK_REALTIME, &ts)
static void test02()
{
string datA(200, 'A'), datB(2000, 'B');
{
GET(ts0);
{
ofstream ofs("ofstreamPerfA.out", std::ios::out | std::ios::app );
ofs << datA;
}
GET(ts1);
d0 = diffTimespecUsec(ts1, ts0);
}
{
GET(ts0);
{
ofstream ofs("/dev/shm/ofstreamPerfA.out", std::ios::out | std::ios::app );
ofs << datA;
}
GET(ts1);
d1 = diffTimespecUsec(ts1, ts0);
}
{
GET(ts0);
{
ofstream ofs("ofstreamPerfA.out", std::ios::out | std::ios::app );
ofs << datA;
}
GET(ts1);
d0 = diffTimespecUsec(ts1, ts0);
}
{
GET(ts0);
{
ofstream ofs("ofstreamPerfB.out", std::ios::out | std::ios::app );
ofs << datB;
}
GET(ts1);
d2 = diffTimespecUsec(ts1, ts0);
}
{
GET(ts0);
{
ofstream ofs("/dev/shm/ofstreamPerfB.out", std::ios::out | std::ios::app );
ofs << datB;
}
GET(ts1);
d3 = diffTimespecUsec(ts1, ts0);
}
PRT(d0);
PRT(d1);
PRT(d2);
PRT(d3);
}
int main()
{
const int N = 3;
for (int i = 1; i <= 100; ++i)
delete[] (new int[1000 * i]);
for (int i = 0; i < N; ++i) {
// test01();
test02();
cout << endl;
}
}
| true |
ad979059649de85faabb38483b78c25ccc0d9d28
|
C++
|
shubhampathak09/codejam
|
/dfs/efficient_approach_array duplicatrs.cpp
|
UTF-8
| 531 | 3.125 | 3 |
[] |
no_license
|
// duplicates in array o(n) time complexity and o(1) space
// elements in arays in raneg 1 to n
// coding interview problem
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[]={ 4, 3, 2, 7, 8, 2, 3, 1};
int n=sizeof(a)/sizeof(a[0]);
vector<int>ans;
// a[0]=4 => a[4-1]=a[3]=7=>-ve
// if the element is already negetive push it into ans
for(int i=0;i<n;i++)
{
if(a[a[i]-1]>0)
a[a[i]-1]=-1*a[a[i]-1];
else
ans.push_back(abs(a[i]));
}
for(auto x:ans)
cout<<x;
}
| true |
ea955f8f5c2618e0e96fa861b9ddda5eb8329d24
|
C++
|
snoowty/Morning
|
/ABC030_c_2.cpp
|
UTF-8
| 2,043 | 3.75 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
// index が条件を満たすかどうか
// bool isOK(int index, int key) {
// if (v[index] >= key) return true;
// else return false;
// }
// 汎用的な二分探索のテンプレ
int binary_search(int key, vector<int> v) {
int left = -1; //「index = 0」が条件を満たすこともあるので、初期値は -1
int right = (int)v.size(); // 「index = a.size()-1」が条件を満たさないこともあるので、初期値は a.size()
/* どんな二分探索でもここの書き方を変えずにできる! */
while (right - left > 1) {
int mid = left + (right - left) / 2;
if (v[mid] >= key) right = mid;
else left = mid;
}
/* left は条件を満たさない最大の値、right は条件を満たす最小の値になっている */
return right;
}
int main() {
int n, m;
cin >> n >> m;
int x, y;
cin >> x >> y;
vector<int> a(n);
vector<int> b(m);
for(int i = 0; i < n; i++) cin >> a[i];
for(int i = 0; i < m; i++) cin >> b[i];
// for(int i = 0; i < n; i++) cout << a[i] << endl;
// 現在時刻 time
int time = a[0];
// cout << time << endl;
// 往復回数 cnt
int cnt = 0;
while(1) {
time += x;
// cout << "x++:" << time << endl;
int element = binary_search(time, b);
// for(int i = 0; i < m; i++) {
// if(time <= b[i]) {
if(element == m) {
cout << cnt << endl;
return 0;
}
time = b[element];
// cout << "b[i] :" << time << endl;
// if(time > b[m-1]) {
// cout << cnt << endl;
// return 0;
// }
time += y;
cnt++;
// cout << "y++:" << time << endl;
element = binary_search(time, a);
// for(int i = 0; i < n; i++) {
// if(time <= a[i]) {
if(element == n) {
cout << cnt << endl;
return 0;
}
time = a[element];
// cout << "a[i] :" << time << endl;
// if(time > a[n-1]) {
// cout << cnt << endl;
// return 0;
// }
}
// cout << cnt << endl;
}
| true |
45b1268319e6534d97b9dd5ec3cb6d1f15936406
|
C++
|
RobertWeber1/canopen
|
/tests/od.cc
|
UTF-8
| 2,420 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
#include "catch.h"
#include <canopen/object_dictionary.h>
template<class T>
constexpr T max(T a, T b)
{
return (a < b) ? b : a;
}
template<size_t COUNT>
constexpr size_t max_();
template<>
constexpr size_t max_<0>()
{
return 0;
}
template <size_t COUNT, class FIRST, typename... REST>
constexpr size_t max_()
{
return max(sizeof(FIRST), max_<sizeof ... (REST), REST...>());
}
template<class ... ARGS>
constexpr size_t max_buffer_size()
{
return max_<sizeof...(ARGS), ARGS ...>();
}
template<size_t COUNT>
constexpr size_t align_();
template<>
constexpr size_t align_<0>()
{
return 0;
}
template <size_t COUNT, class FIRST, typename... REST>
constexpr size_t align_()
{
return max(std::alignment_of<FIRST>::value, align_<sizeof ... (REST), REST...>());
}
template<class ... ARGS>
constexpr size_t alignment_value()
{
return align_<sizeof...(ARGS), ARGS ...>();
}
template<class ... ARGS>
struct Buffer
{
private:
using Self_t = Buffer<ARGS...>;
static constexpr std::size_t Alignment = alignment_value<ARGS...>();
static constexpr std::size_t Size = max_buffer_size<ARGS...>();
alignas(Alignment) uint8_t s_[Size];
size_t pos_ = 0;
public:
template<class T>
operator T () const
{
return *reinterpret_cast<T const*>(s_);
}
template<class T>
bool operator==(T const& val)
{
return *reinterpret_cast<T const*>(s_) == val;
}
template<class T>
Self_t& operator=(T const& value)
{
(*reinterpret_cast<T*>(s_)) = value;
pos_ = 0;
return *this;
}
void put(uint8_t byte)
{
s_[pos_++] = byte;
}
uint8_t get()
{
return s_[pos_++];
}
void reset()
{
pos_ = 0;
}
};
struct foo
{
int a, b;
double c;
};
TEST_CASE("calculate max buffer size")
{
REQUIRE(max_buffer_size() == 0);
REQUIRE((max_buffer_size<bool>()) == 1);
REQUIRE((max_buffer_size<bool, bool>()) == 1);
REQUIRE((max_buffer_size<bool, uint16_t>()) == 2);
REQUIRE((max_buffer_size<bool, uint16_t, foo>()) == 16);
}
TEST_CASE("calculate alignment")
{
REQUIRE(alignment_value() == 0);
REQUIRE((alignment_value<bool>()) == 1);
REQUIRE((alignment_value<bool, bool>()) == 1);
REQUIRE((alignment_value<bool, uint16_t>()) == 2);
REQUIRE((alignment_value<bool, uint16_t, foo>()) == 8);
}
TEST_CASE("Buffer")
{
Buffer<int, bool, float> buffer;
buffer = false;
bool val = (buffer == false);
REQUIRE(val);
buffer = true;
val = (buffer == true);
REQUIRE(val);
}
| true |
25926e4afa93ad1f1d277f045eeca8bb375c757f
|
C++
|
jbxplan/GMLToolbox-src
|
/Sonst/X3D-Module/X3D-Module/Writable/X3D/Grouping.h
|
UTF-8
| 792 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#pragma once
#include "..\Metaable.h"
#include "Optional.h"
#include "Shape.h"
#include <list>
namespace X3D
{
class Grouping : public Metaable
{
public:
virtual ~Grouping();
void addGrouping(Grouping* grouping) { m_groupings.push_back(grouping); }
void addShape(Shape* shape) { m_shapes.push_back(shape); }
void defineChildren(const std::list<Grouping*>& groupings) { m_groupings = groupings; }
void defineShapes(const std::list<Shape*>& sh) { m_shapes = sh; }
//virtual IDable* getElementById(const std::string ident);
virtual void write(tinyxml2::XMLPrinter& printer);
private:
//child elements
std::list<Shape*> m_shapes;
std::list<Grouping*> m_groupings;
void writeGroups(tinyxml2::XMLPrinter& printer);
};
}
| true |
455469ee6b40eec43132f235cdd85d65cffd1fa5
|
C++
|
Sergimech/arduino-ros-examples
|
/src/oscillator_configurable/oscillator_configurable.ino
|
UTF-8
| 1,126 | 2.640625 | 3 |
[] |
no_license
|
/****
* Oscillator configurable
**/
//Includes
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <ros.h>
#include <std_msgs/Float32.h>
#include <std_msgs/UInt16.h>
//ROS variables
ros::NodeHandle nh_;
std_msgs::Float32 float_msg_;
ros::Publisher publisher_("wave", &float_msg_);
//Other variables
float angle_ = 0;
const float PI_ = 3.141592;
//Store a 2 byte value, positive numbers useful range of 0 to 65,535 (2^16) - 1
unsigned int frequency = 50;
void write_freq(const std_msgs::UInt16& cmd_msg)
{
frequency = cmd_msg.data;
}
//Subscriber
ros::Subscriber<std_msgs::UInt16> sub("freq", write_freq);
//Setup
void setup()
{
//ROS init and subscribe
nh_.initNode();
nh_.advertise(publisher_);
nh_.subscribe(sub);
}
void loop()
{
//Increment the angle
angle_ = angle_ + PI_/100;
if (angle_ > 2*PI_) angle_ = angle_ - 2.0*PI_;
//Publish
float_msg_.data = cos(angle_);
publisher_.publish(&float_msg_);
//spin (ros sync and attend callbacks, if any ...)
nh_.spinOnce();
//relax (50ms)
delay(frequency);
}
| true |
935a21f1f156a44a6ed51a94f3c66d7a3a1f4f7e
|
C++
|
1BB3/c-programs
|
/1_2.cpp
|
UTF-8
| 278 | 2.859375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <conio.h>
main(){
int a,b,c;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
c=a;
a=b;
b=c;
printf("The numbers after swapping are : %d%d",a,b);
getch();
}
| true |
19473217bb0d0d394ac8587a4a5123027152d38b
|
C++
|
vasilmao/LinkArrFast
|
/LinkedList.cpp
|
UTF-8
| 13,935 | 3.046875 | 3 |
[] |
no_license
|
#include "LinkedList.h"
#ifdef _DEBUG
#define ASSERT_OK {if (LinkedList_ok(list) != LISTOK) {LinkedList_dump(list); assert(!"OK");}}
#else
#define ASSERT_OK
#endif
void LinkedListPopSortedEnd (struct LinkedList* list, size_t pop_index);
void LinkedListPushSortedLinking (struct LinkedList* list, Elem_t value, size_t index);
size_t LinkedListUpdateFreeCell (struct LinkedList* list);
void LinkedListInsertEmpty (struct LinkedList* list, Elem_t value);
void freeNode (struct LinkedList* list, size_t free_index);
struct LinkedList* NewLinkedList(size_t capacity) {
assert(capacity > 0);
struct LinkedList* list = (struct LinkedList*)calloc(1, sizeof(struct LinkedList));
list->array = (struct Node*)calloc(capacity, sizeof(struct Node));
list->capacity = capacity;
list->first_free = 1;
list->size = 0;
for (size_t i = 0; i < capacity; ++i) {
list->array[i].value = NAN;
if (i < capacity - 1 && i > 0) {
list->array[i].next = i + 1;
}
if (i > 1) {
list->array[i].prev = i - 1;
}
}
list->sorted = true;
ASSERT_OK
return list;
}
size_t LinkedListGetPhysicalIndex(struct LinkedList* list, size_t logic_index) {
assert(list);
assert(0 <= logic_index && logic_index < list->size);
ASSERT_OK
if (list->sorted) {
return logic_index + list->head;
}
if (logic_index == 0) {
return list->head;
}
if (logic_index == list->size - 1) {
return list->tail;
}
printf("WARNING! GETTING PHYSICAL INDEX IS SLOW OPERATION!!1!\n");
size_t phys_i = list->head;
for (size_t i = 0; i < logic_index; ++i) {
phys_i = list->array[phys_i].next;
}
return phys_i;
ASSERT_OK
}
Elem_t LinkedListGetIthLogical(struct LinkedList* list, size_t index) {
assert(list);
assert(0 <= index && index < list->size);
ASSERT_OK
if (list->sorted) {
return LinkedListGetIthLogicalSorted(list, index);
}
return list->array[LinkedListGetPhysicalIndex(list, index)].value;
}
Elem_t LinkedListGetFront(struct LinkedList* list) {
return LinkedListGetIthLogical(list, list->head);
}
Elem_t LinkedListGetBack(struct LinkedList* list) {
return LinkedListGetIthLogical(list, list->tail);
}
void LinkedListPushBack(struct LinkedList* list, Elem_t value) {
if (list->size == 0) {
LinkedListInsertEmpty(list, value);
} else {
LinkedListPushAfterPhysI(list, value, list->tail);
}
}
void LinkedListPushFront(struct LinkedList* list, Elem_t value) {
if (list->size == 0) {
LinkedListInsertEmpty(list, value);
} else {
LinkedListPushBeforePhysI(list, value, list->head);
}
}
void LinkedListPopBack(struct LinkedList* list) {
LinkedListPopPhysI(list, list->tail);
}
void LinkedListPopFront(struct LinkedList* list) {
LinkedListPopPhysI(list, list->head);
}
void LinkedListInsertEmpty(struct LinkedList* list, Elem_t value) {
size_t push_index = list->first_free;
list->first_free = list->array[list->first_free].next;
list->array[list->first_free].prev = 0;
list->array[push_index].next = 0;
list->array[push_index].prev = 0;
list->array[push_index].value = value;
list->head = push_index;
list->tail = push_index;
list->size++;
}
void LinkedListPushSortedLinking(struct LinkedList* list, size_t place_to_insert) {
assert(list);
assert(list->size > 0);
assert(list->sorted);
struct Node* array = list->array;
if (array[place_to_insert].prev != 0) {
array[array[place_to_insert].prev].next = array[place_to_insert].next;
}
if (array[place_to_insert].next != 0) {
array[array[place_to_insert].next].prev = array[place_to_insert].prev;
}
if (place_to_insert == list->first_free) {
list->first_free = array[place_to_insert].next;
}
}
size_t LinkedListUpdateFreeCell(struct LinkedList* list) {
size_t ans = list->first_free;
list->first_free = list->array[list->first_free].next;
list->array[list->first_free].prev = 0;
return ans;
}
void LinkedListPushAfterPhysI(struct LinkedList* list, Elem_t value, size_t index) {
assert(list);
assert(list->size > 0);
assert(!isnan(list->array[index].value));
ASSERT_OK
size_t place_to_insert = 0;
struct Node* array = list->array;
if (list->sorted && index == list->tail && index < list->capacity) {
place_to_insert = list->tail + 1;
LinkedListPushSortedLinking(list, list->tail + 1);
} else {
list->sorted = false;
place_to_insert = LinkedListUpdateFreeCell(list);
}
array[place_to_insert].value = value;
array[place_to_insert].next = list->array[index].next;
array[place_to_insert].prev = index;
array[index].next = place_to_insert;
size_t right = array[place_to_insert].next;
if (right != 0) {
array[right].prev = place_to_insert;
} else {
list->tail = place_to_insert;
}
list->size++;
ASSERT_OK
}
void LinkedListPushBeforePhysI(struct LinkedList* list, Elem_t value, size_t index) {
assert(list);
assert(list->size > 0);
assert(!isnan(list->array[index].value));
ASSERT_OK
size_t place_to_insert = 0;
struct Node* array = list->array;
if (list->sorted && index == list->head && list->head > 1) {
/*it is still sorted*/
place_to_insert = list->head - 1;
LinkedListPushSortedLinking(list, place_to_insert);
} else {
list->sorted = false;
place_to_insert = LinkedListUpdateFreeCell(list);
}
array[place_to_insert].value = value;
array[place_to_insert].next = index;
array[place_to_insert].prev = list->array[index].prev;
array[index].prev = place_to_insert;
size_t left = array[place_to_insert].prev;
if (left != 0) {
array[left].next = place_to_insert;
} else {
list->head = place_to_insert;
}
list->size++;
ASSERT_OK
}
void LinkedListPopSortedEnd(struct LinkedList* list, size_t pop_index) {
assert(list);
assert(!isnan(list->array[pop_index].value));
assert(list->sorted);
struct Node* array = list->array;
size_t left_i = array[pop_index].prev;
size_t right_i = array[pop_index].next;
if (pop_index == list->head) {
if (pop_index == 1) {
array[pop_index].prev = 0;
array[pop_index].next = list->first_free;
array[list->first_free].prev = pop_index;
} else {
array[pop_index].prev = pop_index - 1;
array[array[pop_index - 1].next].prev = pop_index;
array[pop_index].next = array[pop_index - 1].next;
array[pop_index - 1].next = pop_index;
}
} else {
array[pop_index].next = pop_index + 1;
array[array[pop_index + 1].prev].next = pop_index;
array[pop_index].prev = array[pop_index + 1].prev;
array[pop_index + 1].prev = pop_index;
}
}
void freeNode(struct LinkedList* list, size_t free_index) {
list->array[list->first_free].prev = free_index;
list->array[free_index].next = list->first_free;
list->first_free = free_index;
}
void LinkedListPopPhysI(struct LinkedList* list, size_t pop_index) {
assert(list);
assert(!isnan(list->array[pop_index].value));
ASSERT_OK
struct Node* array = list->array;
size_t left_i = array[pop_index].prev;
size_t right_i = array[pop_index].next;
if (left_i != 0) {
array[left_i].next = right_i;
}
if (right_i != 0) {
array[right_i].prev = left_i;
}
if (list->sorted && (pop_index == list->head || pop_index == list->tail )) {
LinkedListPopSortedEnd(list, pop_index);
} else {
list->sorted = false;
freeNode(list, pop_index);
}
array[pop_index].value = NAN;
if (left_i == 0) {
list->head = right_i;
}
if (right_i == 0) {
list->tail = left_i;
}
list->size--;
ASSERT_OK
}
//!
int LinkedList_ok(struct LinkedList* list) {
assert(list);
if (list->size < 0) {
return SIZEERROR;
}
if (list->capacity <= 0 || list->size > list->capacity) {
return CAPACITYERROR;
}
if (list->array == NULL) {
return ARRAYPOINTERERROR;
}
size_t cur_ind = list->head;
for (size_t i = 0; i < list->size; ++i) {
if (cur_ind == 0) {
return INDEXERRORS;
}
if (i == list->size - 1 && cur_ind != list->tail) {
return LASTINDEXERROR;
}
if (i == list->size - 1 && list->tail != cur_ind) {
return TAILERROR;
}
cur_ind = list->array[cur_ind].next;
if (i == list->size - 1 && cur_ind != 0) {
return INDEXERRORS;
}
}
return LISTOK;
}
void LinkedList_dump(struct LinkedList* list) {
FILE* output = fopen("listdump.txt", "w");
assert(output);
#define DEF_ERROR(error, number) \
if (result == number) { \
fprintf(output, " (%s) {\n", #error); \
} else
fprintf(output, "LinkedList [%p]", list);
int result = LinkedList_ok(list);
#include "errors.h"
/*else*/ printf("(error number %d) {\n", result);
#undef DEF_ERROR
fprintf(output, "\tcapacity = %-4zu\n", list->capacity);
fprintf(output, "\tsize = %-4zu\n", list->size);
fprintf(output, "\tfirst_free = %-4zu\n", list->first_free);
fprintf(output, "\thead = %-4zu\n", list->head);
fprintf(output, "\ttail = %-4zu\n", list->tail);
fprintf(output, "\tsorted = %-4d\n", list->sorted);
fprintf(output, "\tarray [%p] {\n", list->array);
for (size_t i = 0; i < list->capacity; ++i) {
fprintf(output, "\t\t[%-3zu] = {next: %-4zu | prev: %-4zu | value: %lf}\n", i, list->array[i].next, list->array[i].prev, list->array[i].value);
}
fprintf(output, "\t}\n}");
fclose(output);
LinkedList_make_graph(list);
}
void LinkedList_make_graph(struct LinkedList* list) {
assert(list);
const char* start_str = "digraph structs {\n\trankdir=HR;\toutputOrder=nodesfirst;\n";
FILE* output = fopen("graph.txt", "w");
assert(output);
fprintf(output, start_str);
struct Node* array = list->array;
for (size_t i = 0; i < list->capacity; ++i) {
size_t last_elem = array[i].prev;
size_t next_elem = array[i].next;
fprintf(output, "\tel%-8zu [shape=record,label=\"{{<f0> phys pos:\\n %zu} | { <f1>prev:\\n %zu | value:\\n %lf | <f2> next:\\n %zu}}\"", i, i, last_elem, array[i].value, next_elem);
if (isnan(array[i].value)) {
fprintf(output, "style=filled,fillcolor=\"#ff8080\"]\n");
} else {
fprintf(output, "]\n");
}
if (i < list->capacity - 1) {
fprintf(output, "\tel%-8zu ->el%-8zu [style=invis]\n", i, i + 1);
}
}
size_t cur_elem = list->head;
for (size_t i = 0; i < list->capacity; ++i) {
cur_elem = i;
size_t last_elem = array[cur_elem].prev;
size_t next_elem = array[cur_elem].next;
if (next_elem != 0) {
fprintf(output, "\tel%-8zu:<f2> -> el%-8zu:<f0> [color=\"red\",constraint=false];\n", cur_elem, next_elem);
}
if (last_elem != 0) {
fprintf(output, "\tel%-8zu:<f1> -> el%-8zu:<f0> [color=\"blue\"];\n", cur_elem, last_elem);
}
cur_elem = array[cur_elem].next;
}
cur_elem = list->head;
for(size_t i = 0; i < list->size; ++i) {
size_t last_elem = array[cur_elem].prev;
size_t next_elem = array[cur_elem].next;
fprintf(output, "\tellog%-5zu [shape=record,label=\"{{logical_pos: %zu |<f0> phys pos:\\n %zu} | { <f1>prev:\\n %zu | value:\\n %lf | <f2> next:\\n %zu}}\"]\n", cur_elem, i, cur_elem, last_elem, array[cur_elem].value, next_elem);
cur_elem = next_elem;
}
cur_elem = list->head;
for(size_t i = 0; i < list->size; ++i) {
size_t last_elem = array[cur_elem].prev;
size_t next_elem = array[cur_elem].next;
if (next_elem != 0) {
fprintf(output, "\tellog%-5zu:<f2> -> ellog%-5zu:<f0> [color=\"red\"];\n", cur_elem, next_elem);
}
if (last_elem != 0) {
fprintf(output, "\tellog%-5zu:<f1> -> ellog%-5zu:<f0> [color=\"blue\"];\n", cur_elem, last_elem);
}
cur_elem = next_elem;
}
fprintf(output, "}");
fclose(output);
system("dot -Tsvg graph.txt > img.svg");
}
void LinkedListSort(struct LinkedList* list) {
assert(list);
ASSERT_OK
struct Node* new_array = (struct Node*)calloc(list->capacity, sizeof(struct Node));
assert(new_array);
size_t cur_ind = list->head;
new_array[0].value = NAN;
for (size_t i = 0; i < list->size; ++i) {
new_array[i + 1].value = list->array[cur_ind].value;
new_array[i + 1].prev = i;
new_array[i + 1].next = i + 2;
cur_ind = list->array[cur_ind].next;
}
for (size_t i = list->size + 1; i < list->capacity; ++i) {
if (i != list->capacity - 1) {
new_array[i].next = i + 1;
}
new_array[i].value = NAN;
if (i != list->size + 1) {
new_array[i].prev = i - 1;
}
}
new_array[list->size].next = 0;
free(list->array);
list->array = new_array;
list->first_free = list->size + 1;
list->head = 1;
list->tail = list->size;
list->sorted = true;
ASSERT_OK
}
void DestroyLinkedList(struct LinkedList* list) {
free(list->array);
free(list);
}
Elem_t LinkedListGetIthLogicalSorted(struct LinkedList* list, size_t index) {
assert(list);
assert(index < list->size);
assert(list->sorted);
ASSERT_OK
return list->array[index + list->head].value;
}
| true |
94f29d1aa24033c42074646bd55834e8bf036fc3
|
C++
|
ausaafnabi/Delhi-University-Bsc-CS-Honours
|
/Discrete-Structures/q20.cpp
|
UTF-8
| 357 | 3.34375 | 3 |
[] |
no_license
|
//This program is to find number of leaf nodes in a full m-array tree with i internal vertices
#include<iostream>
using namespace std;
int main()
{
int m,i;
cout<<"Enter the value of m in the tree";
cin>>m;
cout<<"Enter the number of internal vertices";
cin>>i;
cout<<"The number of leaf nodes are "<<(m-1)*i+1<<'\n';
return 0;
}
| true |
b9504cc178f9c00d5f27fdf38023f5e41abe007c
|
C++
|
gcc-o-o/cpp_code
|
/content_1/stonewt/stone2.cpp
|
UTF-8
| 355 | 2.796875 | 3 |
[] |
no_license
|
//stone2.cpp -- testing class Stonewt
//compile with stonewt1.cpp
#include <iostream>
using std::cout;
#include "stonewt1.h"
void display(Stonewt st, int times);
int main()
{
Stonewt incognito{20.0};
incognito.show_pds();
incognito.show_stn();
cout << "incognito * 3\n";
incognito = incognito * 3.0;
incognito.show_pds();
incognito.show_stn();
}
| true |
2f192edcda22b1da12747f1cd00be65e47fb5ef6
|
C++
|
Tocknicsu/oj
|
/pcca/2015_1/0916/pb.cpp
|
UTF-8
| 1,173 | 2.765625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int t[4][4], d;
void move(){
for(int k = 0 ; k < 4 ; k++){
for(int i = 0 ; i < 4 ; i++){
for(int j = 0 ; j < 3 ; j++){
if(!t[i][j])
swap(t[i][j], t[i][j+1]);
}
}
}
}
void add(){
for(int i = 0 ; i < 4 ; i++){
for(int j = 0 ; j < 3 ; j++){
if(t[i][j] == t[i][j+1]){
t[i][j] *= 2;
t[i][j+1] = 0;
}
}
}
}
void trans(int x){
for(int k = 0 ; k < x ; k++){
for(int i = 0 ; i < 4 ; i++){
for(int j = 0 ; j < i ; j++)
swap(t[i][j], t[j][i]);
}
for(int i = 0 ; i < 2 ; i++){
for(int j = 0 ; j < 4 ; j++)
swap(t[i][j], t[3-i][j]);
}
}
}
int main(){
for(int i = 0 ; i < 4 ; i++)
for(int j = 0 ; j < 4 ; j++)
cin >> t[i][j];
cin >> d;
trans(d);
move();
add();
move();
trans(4-d);
for(int i = 0 ; i < 4 ; i++){
for(int j = 0 ; j < 4 ; j++)
cout << t[i][j] << ' ';
cout << endl;
}
return 0;
}
| true |
b3685aa6958e2845f6eb05e5f2a0b462f38957f0
|
C++
|
KatarinaBakic/Projektivna-geometrija
|
/src/main.cpp
|
UTF-8
| 14,189 | 2.703125 | 3 |
[] |
no_license
|
#include <iostream>
#include <GL/glut.h>
#include <cmath>
#include <Eigen/Dense>
#include <Eigen/Geometry>
using Eigen::MatrixXf;
MatrixXf p1(1, 3), p2(1, 3), q1(1, 3), q2(1, 3);
static int window_width, window_height;
static int timer_active = 0 ;
static float timer = 0;
double parametar_max = 50;
static void on_keyboard(unsigned char key, int x, int y);
static void on_timer(int value);
static void on_reshape(int width, int height);
static void on_display(void);
void nacrtaj_ose();
void svetlo_materijali();
void pocetni_krajnji_parametri();
MatrixXf Euler2A( double ugao1, double ugao2, double ugao3 );
void AxisAngle( MatrixXf A, MatrixXf &p, double & fi );
MatrixXf Rodigez( MatrixXf P, double fi );
MatrixXf A2Euler( MatrixXf A );
MatrixXf AxisAngle2Q( MatrixXf p, double fi );
void Q2AxisAngle( MatrixXf q, MatrixXf &p, double & fi );
void ortogonalna( MatrixXf A );
Eigen::Vector4d slerp( MatrixXf q1, MatrixXf q2, double t_m, double par );
int main (int argc, char ** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(1000, 1000);
glutCreateWindow("Animacija: ");
glClearColor(0, 0, 0, 1);
svetlo_materijali();
glutReshapeFunc(on_reshape);
glutKeyboardFunc(on_keyboard);
glutDisplayFunc(on_display);
glutIdleFunc(on_display);
glutMainLoop();
return 0;
}
static void on_keyboard(unsigned char key, int x, int y){
switch (key) {
case 27:
/* Zavrsava se program. */
exit(0);
break;
case 'g' :
case 'G' :
if (!timer_active) {
glutTimerFunc(50, on_timer, 0);
timer_active = 1;
}
break;
case 's' :
case 'S' :
timer_active = 0;
break;
}
}
static void on_reshape(int width, int height) {
/* Pamte se sirina i visina prozora. */
window_width = width;
window_height = height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 40,
window_width/(float)window_height, 1, 500);
}
void pocetni_krajnji_parametri(){
/* Pocetni polozaj: */
glPushMatrix();
p1 << 3.2, 3.4, 4.2 ;
glTranslatef( p1(0), p1(1), p1(2) );
MatrixXf vektor_p1(1, 3), vektor_p2(1, 3);
double fi1, fi2 ;
AxisAngle(Euler2A(3*M_PI/4.0, M_PI/4.0, 2*M_PI/5.0), vektor_p1, fi1);
q1 = AxisAngle2Q (vektor_p1, fi1);
glRotatef(fi1/M_PI*180, vektor_p1(0), vektor_p1(1), vektor_p1(2));
glColor3f(1, 0.5, 0);
glutWireCube(1);
// nacrtaj_ose();
glPopMatrix();
// Krajnji polozaj:
glPushMatrix ();
p2 << -0.25, -0.45, -1.9 ;
glTranslatef( p2(0), p2(1), p2(2) );
AxisAngle( Euler2A( 2*M_PI/3.0, -4*M_PI/7.0, 7*M_PI/4.0 ), vektor_p2, fi2 );
glRotatef(fi2/M_PI*180, vektor_p2(0), vektor_p2(1), vektor_p2(2));
q2 = AxisAngle2Q( vektor_p2, fi2 );
glColor3f(1, 0.5, 0);
glutWireCube(1);
// nacrtaj_ose();
glPopMatrix();
}
void nacrtaj_ose(){
glBegin(GL_LINES);
glColor3f(1,0,0);
glVertex3f(0,0,0);
glVertex3f(17,0,0);
glEnd();
glBegin(GL_LINES);
glColor3f(0,1,0);
glVertex3f(0,0,0);
glVertex3f(0,17,0);
glEnd();
glBegin(GL_LINES);
glColor3f(0,0,1);
glVertex3f(0,0,0);
glVertex3f(0,0,17);
glEnd();
}
void svetlo_materijali(){
glEnable(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
/*Koeficijenti za osvetljenje: pozicija svetla, ambientalno, difuzno i spekularno */
GLfloat light_position[] = {5, 5, 5, 2};
GLfloat light_diffuse[] = {1, 1, 1, 1};
/*Ukljucivanje svetla: */
/*Postavljanje svetla: */
glLightfv( GL_LIGHT0, GL_POSITION, light_position );
glLightfv( GL_LIGHT0, GL_DIFFUSE, light_diffuse );
glLightf ( GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.01 );
glLightf ( GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.01 );
glEnable(GL_LIGHT0);
/*Koeficijenti za materijale: */
GLfloat ambient_coeffs[]={0.4,0.2,0.3,1};
GLfloat specular_coeffs[]={0.6,0.7,0.6,1};
GLfloat diffuse_coeffs[]={0.9,0.8,0.9,1};
GLfloat shininess=70;
/*Postavljanje materijala: */
glMaterialfv(GL_FRONT,GL_AMBIENT, ambient_coeffs);
glMaterialfv(GL_FRONT, GL_SPECULAR, specular_coeffs);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_coeffs);
glMaterialf(GL_FRONT, GL_SHININESS, shininess);
}
static void on_timer(int value) {
if(value != 0)
return;
if( timer < parametar_max ) {
timer += 0.4;
glutPostRedisplay();
}
if(timer_active)
glutTimerFunc(50, on_timer, 0);
}
static void on_display(void){
/* Brise se prethodni sadrzaj prozora. */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Podesava se tacka pogleda. */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(15, 30, 15,
0, 0, 0,
0, 1, 0
);
/* Zelimo da objekti budu zadate boje */
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
nacrtaj_ose();
pocetni_krajnji_parametri();
glPushMatrix();
MatrixXf pk(1, 3);
pk = (1 - timer/parametar_max )*p1 + ( timer/parametar_max )*p2 ;
double x = pk(0), y = pk(1), z = pk(2) ;
glTranslatef(x, y, z);
Eigen::Vector4d qs = slerp( q1, q2, parametar_max, timer );
MatrixXf qs_matrix (1, 4), vektor_p(1, 3), vektor_p1(1, 3), vektor_p2(1, 3) ;
// potreban nam je qs kao matrica, radi daljeg racuna
qs_matrix << qs(0), qs(1), qs(2), qs(3);
double fi ;
Q2AxisAngle ( qs_matrix, vektor_p, fi);
glRotatef(fi/M_PI*180, vektor_p(0), vektor_p(1), vektor_p(2) );
glColor3f(0.7, 0, 0.5);
glutSolidCube(1);
nacrtaj_ose();
glPopMatrix();
glutSwapBuffers();
}
MatrixXf Euler2A(double ugao1, double ugao2, double ugao3){
// std::cout << "\nUlazni uglovi:\n" << "fi :" <<ugao1 << ", teta:" << ugao2 << ", psi: "<<ugao3 << "\n\n" ;
MatrixXf Rx(3, 3), Ry(3, 3), Rz(3, 3);
Rx<< 1, 0, 0,
0, cos(ugao1), -sin(ugao1),
0, sin(ugao1), cos(ugao1);
Ry<< cos(ugao2), 0, sin(ugao2),
0, 1, 0,
-sin(ugao2), 0, cos(ugao2);
Rz<< cos(ugao3), -sin(ugao3), 0,
sin(ugao3), cos(ugao3), 0,
0, 0, 1;
return Rz * Ry * Rx;
}
/*ulaz: ortogonalna matrica A , detA= 1
izlaz: jedinicni vektor p i ugao fi, takav da je A= Rp(fi)
*/
void AxisAngle ( MatrixXf A, MatrixXf &p, double & fi ){
MatrixXf E(3, 3);
E<< 1, 0, 0,
0, 1, 0,
0, 0, 1;
//moramo da proverimo da li je matrica A ortogonalna:
// ortogonalna(A);
/*prvo odredjujemo sopstveni vektor p za lambda=1;
p je resenje sistema A-lambda*E= A-E,
tj. (A-lambda*E)p=0 , p= x,y,z;
*/
MatrixXf P(3, 3);
P= A - E;
// std::cout<<"P:\n "<<P<<std::endl;
//sistem je ranga 2 ili manje, pa su nam dovoljne samo prve 2 jednacine:
Eigen::Vector3d v1(P(0, 0), P(0, 1), P(0, 2));
Eigen::Vector3d v2(P(1, 0), P(1, 1), P(1, 2));
Eigen::Vector3d v3(P(2, 0), P(2, 1), P(2, 2));
//p = v1 X v2;
Eigen::Vector3d p_cross= v1.cross(v2);
// std::cout<<" v1 i v2: \n"<< p_cross<<"\n";
//treba nam norma da odredimo jedinicni vektor :
double norma_p= sqrt(p_cross(0) * p_cross(0) + p_cross(1) * p_cross(1) + p_cross(2) * p_cross(2));
if(norma_p==0){
p_cross=v1.cross(v3);
norma_p= sqrt(p_cross(0) * p_cross(0) + p_cross(1) * p_cross(1) + p_cross(2) * p_cross(2));
}
// std::cout<<"norma_p :\n"<<norma_p<<"\n";
Eigen::Vector3d p_jedinicni= ( 1 / norma_p) * p_cross;
// std::cout<<p_jedinicni<<"\n";
// treba da odredimo vektor koji je normalan na p: to je npr vektor v1 ili v2:
Eigen::Vector3d u= v2;
// std::cout<< "u:\n"<<u<<"\n";
// radi lakseg mnozenja prebacimo u matricu:
MatrixXf u_pom (3, 1);
u_pom<< u(0), u(1), u(2);
// std::cout<<u_pom<<"\n";
MatrixXf u_primPom= A * u_pom;
//vratimo rezulat u vektor za dalji racun:
Eigen::Vector3d u_prim (u_primPom(0), u_primPom(1), u_primPom(2));
// std::cout<<"u_prim:\n"<<u_prim<<"\n";
// trazimo norme za u i uPrim:
double norma_u= sqrt(u(0) * u(0) + u(1) * u(1) + u(2) * u(2));
double norma_uPrim= sqrt(u_prim(0) * u_prim(0) + u_prim(1) * u_prim(1) + u_prim(2) * u_prim(2));
/*--trazimo ugao fi= arcsoc((u*uPrim)/(norma_u*norma_uPrim)):---*/
/* proizvod 2 vektora: (x,y,z)*(x1,y1,z1)= x*x1+y*y1+z*z1: ---> koristimo dot: */
double proizvod_vektori= u.dot (u_prim);
double proizvod_norme= norma_u * norma_uPrim;
//dobijamo ugao fi:
fi= acos(proizvod_vektori / proizvod_norme);
/*proveravamo da li je determinanta proizvoda [u,uPrim,p] <0, ako jeste onda je p=-p:
da bi rotacija bila u pozitivnom smeru */
MatrixXf proizvod(3, 3);
proizvod<< u(0), u(1), u(2),
u_prim(0), u_prim(1), u_prim(2),
p_jedinicni(0), p_jedinicni(1), p_jedinicni(2);
// std::cout<<"proizvod :\n"<<proizvod<<"\n\n";
double det= proizvod.determinant();
// std::cout<<"det: \n"<<det<<"\n";
//da bi rotacija bila u pozitivnom smeru:
if(det < 0){
p_jedinicni= p_jedinicni*(-1);
}
//vracamo jedinicni vektor p:
p<< p_jedinicni(0), p_jedinicni(1), p_jedinicni(2);
}
/*vracamo matricu rotacije oko orijentisanog (jedinicnog) vektora p, za ugao fi: */
MatrixXf Rodigez(MatrixXf P, double fi){
MatrixXf E(3, 3), px(3, 3);
E<< 1, 0, 0,
0, 1, 0,
0, 0, 1;
//matrica vektorskog mnozenja jedinicnim vektorom p=(p1,p2,p3)
px<< 0, -P(2), P(1),
P(2), 0, -P(0),
-P(1), P(0), 0;
//std::cout<<"px :\n "<<px<<"\n\n";
//potrebna nam je matrica Rp(φ) =ppT+ cosφ(E−ppT) + sinφp×,
//mnozimo P i P transponovano:
MatrixXf Ppom(3, 1);
Ppom<< P(0), P(1), P(2);
MatrixXf Ptrans= Ppom.transpose();
MatrixXf PPtrans= Ppom * Ptrans;
//std::cout<<"P :\n"<<PPtrans<<"\n\n";
//cos(fi)*(E-P*Ptrans); -- drugi sabirak u Rp(fi):
MatrixXf CosFi= cos(fi) * (E - PPtrans);
//std::cout<< "cos(fi):\n"<< CosFi<< "\n\n";
//sin(fi)*px --treci sabirak u Rp(fi):
MatrixXf SinFi= sin(fi) * px;
//std::cout<< "sin(fi):\n"<< SinFi<< "\n\n";
MatrixXf Rp= PPtrans + CosFi + SinFi;
return Rp;
}
/*
ulaz: ortogonalna matrica A , detA= 1;
izlaz: Ojlerovi uglovi: */
MatrixXf A2Euler (MatrixXf A){
double ugao1, ugao2, ugao3;
if(A(2, 0) < 1){
if(A(2, 0) > -1){
ugao1= atan2(A(2, 1), A(2, 2));
ugao2= asin(-A(2, 0));
ugao3= atan2(A(1, 0), A(0, 0));
}
else{
ugao1= 0;
ugao2= M_PI/2;
ugao3= atan2(-A(0, 1), A(1, 1));
}
}
else{
ugao1= 0;
ugao2= -M_PI/2;
ugao3= atan2(-A(0, 1), A(1, 1));
}
MatrixXf rez(1, 3);
rez<< ugao1, ugao2, ugao3;
return rez;
}
/* rotacija u kvaternionu:
ulaz: rotacija oko ose p za ugao fi
izlaz: jedinicni kvaternion, q=[x,y,z,w]=[sin(fi)*(px, py, pz),cos(fi)]; */
MatrixXf AxisAngle2Q (MatrixXf p, double fi){
double w= cos(fi/2);
p= p.normalized();
double x= sin(fi/2) * p(0);
double y= sin(fi/2) * p(1);
double z= sin(fi/2) * p(2);
MatrixXf q(1, 4);
q<< x, y, z, w;
return q;
}
/*kvaternion u rotaciji:
ulaz: jedinicni kvaternion q
izlaz: jedinicni vektor p i ugao fi=[0, 2*pi): */
void Q2AxisAngle(MatrixXf q, MatrixXf &p, double & fi){
q= q.normalized();
double w= q(3);
if(w < 0){
q= q*(-1);
}
fi = 2.0 * acos(w);
p<< q(0), q(1), q(2);
if( abs(w) == 1 ) {
p<< 1, 0, 0;
}
else {
p = p.normalized();
}
//std::cout<<p<<"\n";
}
void ortogonalna(MatrixXf A){
// double det = A.determinant();
// std::cout<<det<<"\n";
MatrixXf E(3, 3);
E<< 1, 0, 0,
0, 1, 0,
0, 0, 1;
MatrixXf A_pom= A.transpose()*A;
if (A_pom.isApprox(E)){
std::cout<< "( Jeste ortogonalna matrica. )\n";
}
else{
std::cout<< "( Nije ortogonalna matrica. )\n";
}
}
/* funkcija SLerp:
ulaz : 2 jedinicna kvarterniona q1 i q2, duzinu interpolacije t_m i parametar t=[0,t_m]
izlaz: jedinicni kvarternion qs(t), koji zadaje orijentaciju u trenutku t.
*/
Eigen::Vector4d slerp (MatrixXf q1, MatrixXf q2, double t_m, double par){
//cos0=<q1,q2>
// treba nam vektor, zbog funkcije .dot ;
Eigen::Vector4d q1_vec (q1(0), q1(1), q1(2), q1(3));
Eigen::Vector4d q2_vec (q2(0), q2(1), q2(2), q2(3));
double q1_norma = q1_vec.norm();
double q2_norma = q2_vec.norm();
if(par == 0)
return q1_vec;
if( par == t_m)
return q1_vec;
//norme su 1:
double sk_proizvod= q1_vec.dot(q2_vec)/(q1_norma * q2_norma);
//std::cout<<"Skalarni proizvod: "<< sk_proizvod <<"\n";
//idi po kracem luku sfere:
if (sk_proizvod < 0){
q1= q1*(-1);
sk_proizvod= sk_proizvod*(-1);
}
// ako su kvarternioni previse blizu:
if (sk_proizvod > 0.95){
return q1_vec;
}
//trazimo ugao: fi = acos (cos0<q1, q2>);
double fi= acos(sk_proizvod);
Eigen::Vector4d qs = ( sin (fi*(1 - par/ t_m )))/ ( sin(fi))* q1_vec + (sin(fi* par/ t_m))/ (sin(fi))* q2_vec;
return qs;
}
| true |
9b288d48623337565637e46498d626a3f53abff7
|
C++
|
mdonaka/CompetitiveProgrammingCpp
|
/Test/DataStructure/DisjointSparseTable_xor.test.cpp
|
UTF-8
| 930 | 2.546875 | 3 |
[] |
no_license
|
#define PROBLEM "https://yukicoder.me/problems/no/1456"
#include <iostream>
#include <unordered_set>
#include "./../../Library/DataStructure/DisjointSparseTable.hpp"
using ll = long long;
using std::cout;
using std::cin;
constexpr char endl = '\n';
struct F { auto operator()(ll x, ll y) { return x ^ y; } };
using SG = SemiGroup<ll, F>;
signed main() {
ll n, k;
cin >> n >> k;
std::vector<ll> a; a.reserve(n);
for(int _ = 0; _ < n; ++_) {
ll x; cin >> x;
a.emplace_back(x);
}
auto dst = DisjointSparseTable<SG>(n, a);
std::unordered_set<ll> st;
for(int i = 0; i < n; ++i) {
st.emplace(dst.get(0, i) ^ k);
}
if(st.find(0) != st.end()) { cout << "Yes" << endl; return 0; }
for(int i = 0; i < n; ++i) {
if(st.find(dst.get(0, i)) != st.end()) { cout << "Yes" << endl; return 0; }
}
cout << "No" << endl;
}
| true |
fcb9b2c854063a0e89cd4d7c344514b24efee899
|
C++
|
namse/meteor
|
/src/Meteor/Sprite.h
|
UTF-8
| 1,113 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "D2DRenderer.h"
#include "D2DBitmap.h"
#include <string>
class CSprite
{
protected:
float m_ImageWidth;
float m_ImageHeight;
float m_ColorR, m_ColorG, m_ColorB;
float m_Opacity;
public:
CSprite()
: m_ImageWidth(0.f), m_ImageHeight(0.f),
m_ColorR(0.f), m_ColorG(0.f), m_ColorB(0.f), m_Opacity(1.f)
{}
virtual ~CSprite(){}
static CSprite * Create( std::wstring path );
virtual void Destroy() {}
virtual void Render() {}
float GetImageWidth() const { return m_ImageWidth; }
float GetImageHeight() const { return m_ImageHeight; }
float GetOpacity() const { return m_Opacity; }
void SetImageWidth ( float width ) { m_ImageWidth = width; }
void SetImageHeight ( float height ) { m_ImageHeight = height; }
void SetOpacity ( float opacity ) { m_Opacity = opacity; }
};
class CD2DSprite : public CSprite
{
public:
CD2DSprite();
CD2DSprite( std::wstring path );
virtual ~CD2DSprite();
void Destroy();
void Render();
private:
CD2DRenderer * m_pD2DRenderer;
CD2DBitmap * m_pD2DBitmap;
D2D1::Matrix3x2F m_Matrix;
};
| true |
40373f1a2ef0cdcad30cb8f0658f132b977f263a
|
C++
|
0xj4m35/C-Fundamental
|
/Another source/bai_6_rw.cpp
|
UTF-8
| 658 | 3.09375 | 3 |
[] |
no_license
|
#include <stdio.h>
int main(){
int num;
char c;
do{
int first=0, last=0, i=0;
printf("Enter a collection of Integers and finish by number 0\n\n");
do{
i += 1;
printf("Integer <%d> : ", i);
scanf("%d", &num);
if (num==0)
break;
else
if (num==24){
if (first==0){
first=i;
last=i;
} else
last=i;
}
} while (num!=0);
if (first==0)
printf("Number <24> is not found.");
else
printf("First and Last index of number < 24 >: %d %d", first, last);
printf("\n\nAnother Program? <Y/N> : ");
scanf("%s", &c);
} while ((c=='Y') || (c=='y'));
return(0);
}
| true |
28251205b14f38fff8bb6f7bec9cb030d0760517
|
C++
|
jgaines42/Steric_dipeptides
|
/C_code/aa_setup.cxx
|
UTF-8
| 5,200 | 2.59375 | 3 |
[] |
no_license
|
#include "aa_setup.h"
#define PI 3.14159265
using namespace std;
// int phi_index[], int psi_index[], int chi1_index[], int chi2_index[], int chi3_index[], int CH3_1_index[], int CH3_2_index[], int end_CH3_1_index[], int end_CH3_2_index[]
void get_dihedral_indexes(std::string aa_name, int index_array[9][4]){
if (aa_name.compare("Val") == 0){
int this_index[10][4] = {{4, 6, 8, 20}, // phi
{6, 8, 20, 22}, // psi
{6, 8, 10, 12}, // chi1
{-1, -1, -1, -1}, //chi2
{-1, -1, -1, -1}, //chi3
{8, 10, 12, 13}, //CH3 1
{8, 10, 16, 17}, //CH3 2
{6, 4, 1, 0}, // end CH3 1
{20, 22, 24, 25}, // end CH3 2
{-1, -1, -1, -1}, //OH
};
for (int i = 0; i < 10; i++){
for (int j = 0; j < 4; j++){
index_array[i][j]=this_index[i][j];
}
}
}
else if (aa_name.compare("Ile") == 0){
int this_index[10][4] = {{4, 6, 8, 23}, // phi
{6, 8, 23, 25}, // psi
{6, 8, 10, 16}, // chi1
{8, 10, 16, 19}, //chi2
{-1, -1, -1, -1}, //chi3
{8, 10, 12, 13}, //CH3 1
{10, 16, 19, 20}, //CH3 2
{6, 4, 1, 0}, // end CH3 1
{23, 25, 27, 28}, // end CH3 2
{-1, -1, -1, -1}, //OH
};
for (int i = 0; i < 10; i++){
for (int j = 0; j < 4; j++){
index_array[i][j]=this_index[i][j];
}
}
}
else if (aa_name.compare("Ser") == 0){
int this_index[10][4] = {{4, 6, 8, 15}, // phi
{6, 8, 15, 17}, // psi
{6, 8, 10, 13}, // chi1
{-1, -1, -1, -1}, //chi2
{-1, -1, -1, -1}, //chi3
{-1, -1, -1, -1}, //CH3 1
{-1, -1, -1, -1}, //CH3 2
{6, 4, 1, 0}, // end CH3 1
{15, 17, 19, 21}, // end CH3 2
{8, 10, 13, 14}, // OH
};
for (int i = 0; i < 10; i++){
for (int j = 0; j < 4; j++){
index_array[i][j]=this_index[i][j];
}
}
}
else {
int this_index[10][4] = {{4, 6, 8, 20}, // phi
{6, 8, 20, 22}, // psi
{6, 8, 10, 12}, // chi1
{-1, -1, -1, -1}, //chi2
{-1, -1, -1, -1}, //chi3
{8, 10, 12, 13}, //CH3 1
{8, 10, 16, 17}, //CH3 2
{6, 4, 1, 0}, // end CH3 1
{20, 22, 24, 25}, // end CH3 2
{-1, -1, -1, -1}, //OH
};
for (int i = 0; i < 10; i++){
for (int j = 0; j < 4; j++){
index_array[i][j]=this_index[i][j];
}
}
}
}
void get_move_indexes(std::string aa_name, int moveAtomID_phi[], int moveAtomID_psi[], int moveAtomID_chi1[], int moveAtomID_chi2[], int moveAtomID_chi3[], int moveAtomID_CH3_1[], int moveAtomID_CH3_2[], int moveAtomID_end_CH3_1[], int moveAtomID_end_CH3_2[], int moveAtomID_OH[]){
if (aa_name.compare("Val") == 0){
int ID_phi[30] = {20, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27};
int ID_psi [30]= {8, 21, 22, 23, 24, 25, 26, 27};
int ID_chi1[30] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int ID_CH3_1[30] = {4, 13, 14, 15};
int ID_CH3_2 [30]= {4, 17, 18, 19};
int ID_end_CH3_1[30] = {4, 0, 2, 3};
int ID_end_CH3_2[30] = {4, 25, 26, 27};
std::copy(ID_phi, ID_phi+ID_phi[0], moveAtomID_phi);
std::copy(ID_psi, ID_psi+ID_psi[0], moveAtomID_psi);
std::copy(ID_chi1, ID_chi1+ID_chi1[0], moveAtomID_chi1);
std::copy(ID_CH3_1, ID_CH3_1+ID_CH3_1[0], moveAtomID_CH3_1);
std::copy(ID_CH3_2, ID_CH3_2+ID_CH3_2[0], moveAtomID_CH3_2);
std::copy(ID_end_CH3_1, ID_end_CH3_1+ID_end_CH3_1[0], moveAtomID_end_CH3_1);
std::copy(ID_end_CH3_2, ID_end_CH3_2+ID_end_CH3_2[0], moveAtomID_end_CH3_2);
}
else if (aa_name.compare("Ile") == 0){
int ID_phi[30] = {23, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
int ID_psi [30]= {8, 24, 25, 26, 27, 28, 29, 30};
int ID_chi1[30] = {13, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
int ID_chi2[30] = {7, 17, 18, 19, 20, 21, 22};
int ID_CH3_1[30] = {4, 13, 14, 15};
int ID_CH3_2 [30]= {4, 20, 21, 22};
int ID_end_CH3_1[30] = {4, 0, 2, 3};
int ID_end_CH3_2[30] = {4, 28, 29, 30};
std::copy(ID_phi, ID_phi+ID_phi[0], moveAtomID_phi);
std::copy(ID_psi, ID_psi+ID_psi[0], moveAtomID_psi);
std::copy(ID_chi1, ID_chi1+ID_chi1[0], moveAtomID_chi1);
std::copy(ID_CH3_1, ID_CH3_1+ID_CH3_1[0], moveAtomID_CH3_1);
std::copy(ID_CH3_2, ID_CH3_2+ID_CH3_2[0], moveAtomID_CH3_2);
std::copy(ID_end_CH3_1, ID_end_CH3_1+ID_end_CH3_1[0], moveAtomID_end_CH3_1);
std::copy(ID_end_CH3_2, ID_end_CH3_2+ID_end_CH3_2[0], moveAtomID_end_CH3_2);
}
else if (aa_name.compare("Ser") == 0){
int ID_phi[30] = {15, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
int ID_psi [30]= {8, 16, 17, 18, 19, 20, 21, 22};
int ID_chi1[30] = {5, 11, 12, 13, 14};
int ID_end_CH3_1[30] = {4, 0, 2, 3};
int ID_end_CH3_2[30] = {4, 28, 29, 30};
int ID_end_OH[30] = {2, 14};
std::copy(ID_phi, ID_phi+ID_phi[0], moveAtomID_phi);
std::copy(ID_psi, ID_psi+ID_psi[0], moveAtomID_psi);
std::copy(ID_chi1, ID_chi1+ID_chi1[0], moveAtomID_chi1);
std::copy(ID_end_OH, ID_end_OH+ID_end_OH[0], moveAtomID_OH);
std::copy(ID_end_CH3_1, ID_end_CH3_1+ID_end_CH3_1[0], moveAtomID_end_CH3_1);
std::copy(ID_end_CH3_2, ID_end_CH3_2+ID_end_CH3_2[0], moveAtomID_end_CH3_2);
}
}
| true |
edcc16f78fd8d9673dd49700092887101e8c4a5a
|
C++
|
Ariemn2929/College-Programs
|
/C++ Practice Programs/Ch 4/Ch 4/26/26.cpp
|
UTF-8
| 805 | 3.78125 | 4 |
[] |
no_license
|
// 26.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
// The switch statement in this program uses the "fall through"
// feature to catch both uppercase and lowercase letters entered
// by the user.
#include <iostream>
using namespace std;
int main()
{
char feedGrade;
// Get the desired grade of feed.
cout << "Our pet food is available in three grades:\n";
cout << "A, B, and C. Which do you want pricing for? ";
cin >> feedGrade;
// Display the price.
switch (feedGrade)
{
case 'a':
case 'A': cout << "60 cents per pound.\n";
break;
case 'b':
case 'B': cout << "40 cents per pound.\n";
break;
case 'c':
case 'C': cout << "25 cents per pound.\n";
break;
default: cout << "That is an invalid choice.\n";
}
return 0;
}
| true |
f413b27ab9443cb625c63dc6e63489ffb61ad8e3
|
C++
|
Lureif/arduino-funtime
|
/glowing_leds/glowing_led_name.ino
|
UTF-8
| 788 | 2.765625 | 3 |
[] |
no_license
|
#include <FastLED.h>
#include <stdlib.h>
#include <stdio.h>
#define LED_PIN A3
#define NUM_LEDS 200
#define BRIGHTNESS 50
CRGB leds[NUM_LEDS];
void setup()
{
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
}
void loop()
{
unsigned int i;
unsigned int str_counter;
unsigned int r;
unsigned int g;
unsigned int b;
static const char *str = "ARTHUR EST UN SUCEUR";
i, r, g, b = 0;
str_counter = 0;
while (i <= NUM_LEDS)
{
while (str_counter <= strlen(str))
{
r = abs(rand() % 100 - rand() % 100);
g = abs(rand() % 100 - rand() % 100);
b = abs(rand() % 100 - rand() % 100);
leds[str[str_counter]] = CRGB(r, g, b);
FastLED.show();
delay(500);
str_counter++;
}
str_counter = 0;
i += strlen(str);
}
}
| true |