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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dc44743b6c15456713e66ca90e23d9aa8b913297 | C++ | 0x2f0713/rolling-door-controller-backend | /src/Controller/Controller.h | UTF-8 | 290 | 2.65625 | 3 | [] | no_license | #ifndef Controller_h
#define Controller_h
#include "Arduino.h"
class Controller
{
public:
Controller(int pinUp, int pinDown, int pinStop, int pinLock);
void up();
void down();
void stop();
void lock();
private:
int _pinUp, _pinDown, _pinStop, _pinLock;
};
#endif | true |
cd861841f5fc7aa7b72e66d1495782d6ac652348 | C++ | Nik404/Dynamic-Prograamming | /staircaseGeneralizeed.cpp | UTF-8 | 1,376 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <cstring>
#include <climits>
using namespace std;
int dp[1000];
// recursive
// Time:O(k^n)
int ways(int n,int k){
if(n == 0) return 1;
if(n < 0) return 0;
int ans = 0;
for(int j=1;j<=k;j++){
ans += ways(n-j,k);
}
return ans;
}
// TDDP
// time O(n*k)
int ways2(int *dp,int n,int k){
if(n == 0) return 1;
if(n < 0) return 0;
if(dp[n] > 0) return dp[n];
int output = 0;
for(int j=1;j<=k;j++){
output += ways(n-j,k);
}
return dp[n] = output;
}
// BUDP
// time : O(n*k)
int ways3(int n,int k){
int *dp = new int[n+1];
dp[0] = 1;
for(int step=1;step<=n;step++){
dp[step] = 0;
for(int j = 1;j<=k;j++){
if(step-j >= 0){
dp[step] += dp[step-j];
}
}
}
return dp[n];
}
// can be done in O(n)
int waysBUDPOptimized(int n,int k){
int *dp = new int[n+1];
dp[0] = 1;
dp[1] = 1;
for(int step=1;step<=n;step++){
// dp[step] = 0;
if(dp[step-k] >= 0){
dp[step+1] = 2*dp[step-1] - dp[step-k];
}
else{
dp[step+1] = 2*dp[step-1];
}
}
return dp[n];
}
int main(int argc, char const *argv[])
{
int n,k;
cin>>n>>k;
int *dp = new int[n+1];
for(int i=0;i<=n;i++){
dp[i] = 0;
}
cout<<ways(n,k)<<endl;
cout<<ways2(dp,n,k)<<endl;
cout<<ways3(n,k)<<endl;
cout<<waysBUDPOptimized(n,k)<<endl;
return 0;
} | true |
eb9db5c85649ea632dc453512e5dadb4916748da | C++ | uddeepk/cs202 | /labs/lab05/main.cpp | UTF-8 | 2,606 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
using std::cin;
using std::cout;
using std::setw;
using std::ostream;
using std::ofstream;
using std::ifstream;
int main() {
//
// std::ofstream fout("example.txt");
//
// for (int i = 0 ; i < 100 ; ++i) {
// //cout << setw(5) << i * i;
// fout << setw(5) << i * i;
// }
//
// std::ifstream fin("example.txt");
//
// fin.seekg(83 * 5);
// int x;
// fin >> x;
// cout << "83 squared is " << x << std::endl;
//
//
// int a[100] = {1, 2, 3};
// int ii = 8 * 8;
// ofstream fout("data.dat", std::ios::binary | std::ios::out);
// fout.write( reinterpret_cast<const char*> (&a), sizeof(int)*100);
// fout.close();
//
// ifstream fin("data.dat", std::ios::binary | std::ios::in);
//
// for (int j = 0; j < 4 ; ++j) {
// char c;
// fin.read(reinterpret_cast<char *>(&c), sizeof(c));
// cout << (unsigned int)(c) << std::endl;
// }
// Binary Files
// Purpose
//
// In this lab, you will get open and read from a binary file containing integer data.
// What to Do
//
// Write a program that opens and reads from the binary file data.dat.
//
// Read the integers from the file
// Print the number of integers, their sum, and the average.
//
// There are two reasonable ways to know how many integers to read. The first, and easiest is to test the stream after each read and see whether it failed or not (just as we normally do for input.) The second is to determine the file size ahead of time, using seekg() relative to the end, then tellg() to find out where you are.
//
//
ifstream fin("data.dat", std::ios::binary | std::ios::in);
if (!fin) {
cout << "You messed up." << std::endl;
if(fin.eof()) {
cout << "Error not enough data" << std::endl;
}
return -1;
}
int counter = 0, sum = 0, number;
//(X) Notice I can use while (fin.read(reinterpret_cast<char *>(&number), sizeof(int))) and
//remove the if(!fin) check.
while (true) { //Because I am using
// fin.seekg(counter*sizeof(int)); // Unnecessary
fin.read(reinterpret_cast<char *>(&number), sizeof(int)); //Look at note above (X)
if (!fin) { //Look at note above (X)
break;
}
cout << number << std::endl;
sum += number;
++counter;
}
cout << "The number of integers : " << counter << std::endl;
cout << "The sum: " << sum << std::endl;
cout << "The average: " << static_cast<double> (sum) / counter << std::endl;
return 0;
}
| true |
e0376d2f6d70bb15eeb2dbe5ef272a2e2a9b0695 | C++ | TabrynP/Tabryn_Palmer_CMSC312_2019 | /Process.cpp | UTF-8 | 4,622 | 2.78125 | 3 | [] | no_license | #include "Process.h"
Process::Process(const std::string& program_file, std::shared_ptr<SharedMemory> mem) {
init_process(init_program_file(program_file));
shared_memory = mem;
process_PCB.program_file = program_file;
}
Process::Process(const Process& old_process) {
process_map_vector = old_process.process_map_vector;
process_PCB = old_process.process_PCB;
children = old_process.children;
virtual_memory = old_process.virtual_memory;
is_child = old_process.is_child;
is_parent = old_process.is_parent;
just_ran = old_process.just_ran;
is_shortest_job = old_process.is_shortest_job;
}
void Process::update_state(State new_state) {
process_PCB.process_state = new_state;
}
static int parse_number(std::string program_line) {
std::size_t pos;
if (program_line.find(":") != std::string::npos) {
pos = program_line.find(": ") + 2;
}
else {
pos = program_line.find(" ");
}
std::string temp_str = program_line.substr(pos);
std::stringstream temp_strstream(temp_str);
int output;
temp_strstream >> output;
return output;
}
std::shared_ptr<Process> Process::fork() {
srand(time(NULL));
int process = rand() % 4 + 1;
std::string program_file = "Process_" + std::to_string(process) + ".txt";
std::shared_ptr<Process> child = std::make_shared<Process>(program_file, shared_memory);
set_child(child);
child->is_child = true;
is_parent = true;
return child;
}
void Process::abort(Process& child) {
for (auto it = children.begin(); it != children.end(); ++it) {
Process& temp = (*(*it));
if (temp == child) {
temp.update_state(EXIT);
}
}
}
void Process::init_process(const std::vector<std::string>& program_file) {
int total_runtime = 0;
std::string name = "placeholder";
State current_state = NEW;
process_PCB.in_critical = false;
process_PCB.in_memory = false;
process_PCB.random_IO = 0;
for (int i = 0; i < program_file.size(); i++) {
if (program_file[i].find("Name: ") != std::string::npos) {
std::size_t pos = program_file[i].size();
std::size_t pos_2 = program_file[i].find(" ");
std::size_t pos_3 = pos - pos_2;
name = program_file[i].substr(pos_2);
}
else if (program_file[i].find("Total Runtime: ") != std::string::npos) {
total_runtime = parse_number(program_file[i]);
}
else if (program_file[i].find("Memory: ") != std::string::npos) {
process_PCB.memory = parse_number(program_file[i]);
}
else if (
program_file[i].find("CALCULATE") != std::string::npos ||
program_file[i].find("YIELD") != std::string::npos ||
program_file[i].find("OUT") != std::string::npos
) {
bool is_critical = false;
bool end_critical = false;
if (program_file[i - 1] == "CRITICAL_in") {
is_critical = true;
end_critical = false;
}
else if (program_file[i - 1] == "CRITICAL_out") {
end_critical = true;
is_critical = false;
}
int map_int = parse_number(program_file[i]);
std::size_t pos = program_file[i].find(" ");
std::string map_string = program_file[i].substr(0, pos);
process_map_vector.push_back(ProcessMap(map_string, map_int, is_critical, end_critical));
}
else if (program_file[i].find("I/O") != std::string::npos) {
bool end_critical = false;
int seed = parse_number(program_file[i]);
std::size_t pos = program_file[i].find(" ");
std::string map_string = program_file[i].substr(0, pos);
srand((unsigned int)(time)(NULL));
int map_int = rand() % (seed * 10);
if (program_file[i - 1] == "CRITICAL_out") {
end_critical = true;
}
else {
end_critical = false;
}
process_map_vector.push_back(ProcessMap(map_string, map_int, false, end_critical));
}
else {
continue;
}
}
process_PCB.process_state = current_state;
process_PCB.total_runtime = total_runtime;
process_PCB.name = name;
process_PCB.current_instruction = 0;
process_PCB.is_sleeping = false;
is_child = false;
process_PCB.total_runtime = 0;
for (int i = 0; i < process_map_vector.size(); i++) {
process_PCB.total_runtime += process_map_vector[i].runtime;
}
is_parent = false;
priority = 0;
virtual_memory = VirtualMemory(process_PCB.memory);
just_ran = false;
is_shortest_job = false;
}
std::vector<std::string> Process::init_program_file(const std::string& file_in) {
std::string line;
std::ifstream program_file;
std::vector<std::string> file_lines;
program_file.open(file_in);
if (program_file.is_open()) {
while (std::getline(program_file, line)) {
file_lines.push_back(line);
}
}
return file_lines;
} | true |
77636bfc2c23542a4720b342100d0f696827a432 | C++ | elephantjay/kickstart-practice | /2018-Round-A/P1-EvenDigits.cpp | UTF-8 | 1,157 | 3.125 | 3 | [] | no_license | /* Kickstart Round A
*/
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <string>
using namespace std;
long long int integerOfEights(int length) {
char eights[length];
for(int i = 0; i < length; i++) {
eights[i] = '8';
}
return atoll(eights);
}
int main ()
{
int t;
cin >> t;
for( int i = 1 ; i <= t ; i++ )
{
long long int num, len, result = 0;
string n;
cin >> n;
num = stoll(n);
len = n.length();
int firstOddDigitPos = -1;
for (int j = 0; j < len; j++) {
if (n[j] % 2 == 1) {
firstOddDigitPos = j;
break;
}
}
if (firstOddDigitPos == -1) {
cout << "Case #" << i << ": " << 0 << endl;
continue;
}
long long int remain;
string r;
for (int j = firstOddDigitPos; j < len; j++) {
r += n[j];
}
remain = stoll(r);
int digit = r[0] - '0';
long long int lower = ((digit - 1) * pow(10, r.length()-1)) + integerOfEights(r.length()-1);
if (digit == 9) {
result = remain - lower;
}
else {
long long int upper = (digit+ 1) * pow(10, r.length()-1);
result = min(upper-remain, remain-lower);
}
cout << "Case #" << i << ": " << result << endl;
}
return 0;
} | true |
13f7051b52fc1e01eaf92c4e847609796ba40017 | C++ | nic-cs151-master/lecture | /ch14/maxOf.cpp | UTF-8 | 1,294 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int maxOf(const vector<int> &numbers);
int maxOf2(const vector<int> &numbers);
vector<int> subList(const vector<int> &v, int m, int n);
int main()
{
vector<int> elems{137, 271, 828, 182, 200, 983, 1023, 33, 12, 103};
cout << maxOf(elems) << endl;
cout << maxOf2(elems) << endl;
return 0;
}
int maxOf2(const vector<int> &numbers)
{
if (numbers.size() == 1)
{
return numbers[0];
}
else
{
// cout << "size: " << numbers.size() << '\n';
int half = numbers.size() / 2;
// cout << half << ' ' << numbers.size() - 1 << '\n';
vector<int> upper = subList(numbers, 0, half-1);
vector<int> lower = subList(numbers, half, numbers.size()-1);
return max(maxOf2(upper), maxOf2(lower));
}
}
int maxOf(const vector<int> &numbers)
{
if (numbers.size() == 1)
{
return numbers[0];
}
else
{
int first = numbers[0];
vector<int> rest = subList(numbers, 1, numbers.size()-1);
return max(first, maxOf(rest));
}
}
vector<int> subList(const vector<int> &v, int m, int n)
{
auto first = v.cbegin() + m;
auto last = v.cbegin() + n + 1;
vector<int> subVec(first, last);
return subVec;
} | true |
2522ee105cad068f2b60ea06c13def9a806d3f29 | C++ | hegoimanzano/KIMERA | /src/Sym_equation.cpp | UTF-8 | 3,055 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "Sym_equation.h"
Sym_equation::Sym_equation(string expresion_)
{
expresion=expresion_;
read_expresions_set_parameters(expresion_);
}
Sym_equation::~Sym_equation()
{
//dtor
}
long long int Sym_equation::read_expresions_set_parameters(string expresion_)
{
//A+ax+B+by+C+cz
A=0.0; a=1.0; B=0.0; b=1.0; C=0.0; c=1.0;
if (expresion_.compare("'x,y,z'")==0)
{
return 0;
}
long long int index = expresion_.find('x');
long long int indey = expresion_.find('y');
long long int indez = expresion_.find('z');
//buscamos + o - antes que la x
string prex = expresion_.substr (index-1,index);
if (prex.compare("-")==0) a=-1.0;
if (prex.compare("+")==0 || prex.compare("-")==0)
{
string prexx = expresion_.substr (index-2,index-1);
string prexxxx = expresion_.substr (index-4,index-3);
double den=stod(prexx);
double num=stod(prexxxx);
A=num/den;
}
string prey = expresion_.substr (indey-1,indey);
if (prey.compare("-")==0) b=-1.0;
if (prey.compare("+")==0 || prey.compare("-")==0)
{
string preyy = expresion_.substr (indey-2,indey-1);
string preyyyy = expresion_.substr (indey-4,indey-3);
double den=stod(preyy);
double num=stod(preyyyy);
B=num/den;
}
string prez = expresion_.substr (indez-1,indez);
if (prez.compare("-")==0) c=-1.0;
if (prez.compare("+")==0 || prez.compare("-")==0)
{
string prezz = expresion_.substr (indez-2,indez-1);
string prezzzz = expresion_.substr (indez-4,indez-3);
double den=stod(prezz);
double num=stod(prezzzz);
C=num/den;
}
return 0;
}
/**
string prex = expresion_.substr (0,index);
long long int indexplusminusx=prex.find("+");
//si no se encuentra, a=1.0
if (indexplusminusx==npos) a=1.0
string str = "0,07";
long long int index = str.find(',');
str.replace(index, index+1, '.');
double number = stod(str);
A=0.0;
B=0.0;
C=0.0;
a=0.0;
b=0.0;
c=0.0;
*/
Position Sym_equation::get_sym_pos(Position * position_)
{
double x=position_->get_x();
double y=position_->get_y();
double z=position_->get_z();
long long int newid=NEWPOSID;
vector<string> types=position_->get_types();
vector<double> probs=position_->get_probs();
double newx=A+a*x;
double newy=B+b*y;
double newz=C+c*z;
string firsttype=types.at(0);
double firstprob=probs.at(0);
Position auxposition=Position(newx,newy,newz,newid,firsttype,firstprob);
//add the rest of the types and probs
long long int typessize=types.size();
if (typessize>1)
{
for ( long long int i=1; i<(long long int)types.size(); i++)
{
auxposition.add_type_prob(types.at(i),probs.at(i));
}
}
return auxposition;
}
| true |
7f0de595ab3a5452214a21ffbb57e05222239388 | C++ | ritik-patel05/CompetitiveProgramming | /Olympaid/Baltic/BOI_11_Vikings.cpp | UTF-8 | 5,219 | 2.546875 | 3 | [] | no_license | /*
Author: Ritik Patel
*/
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& STL DEBUGGER &&&&&&&&&&&&&&&&&&&&&&&&&&&
// #define _GLIBCXX_DEBUG // Iterator safety; out-of-bounds access for Containers, etc.
// #pragma GCC optimize "trapv" // abort() on (signed) integer overflow.
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& LIBRARIES &&&&&&&&&&&&&&&&&&&&&&&&&&&
#include <bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
template<typename T, typename V = __gnu_pbds::null_type>
using ordered_set = __gnu_pbds::tree<T, V, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;
*/
//find_by_order()->returns an iterator to the k-th largest element(0-based indexing)
//order_of_key()->Number of items that are strictly smaller than our item
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& DEFINES &&&&&&&&&&&&&&&&&&&&&&&&&&&
#define int long long int
// #define ll long long int
#define all(i) i.begin(), i.end()
#define sz(a) (int)a.size()
// #define ld long double
// const ld PI = 3.141592;
const int dx4[4] = {0, 1, 0, -1};
const int dy4[4] = {-1, 0, 1, 0};
const int dx8[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
const int dy8[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& DEBUG &&&&&&&&&&&&&&&&&&&&&&&&&&&
#define XOX
vector<string> vec_splitter(string s) {
for(char& c: s) c = c == ','? ' ': c;
stringstream ss; ss << s;
vector<string> res;
for(string z; ss >> z; res.push_back(z));
return res;
}
void debug_out(vector<string> __attribute__ ((unused)) args, __attribute__ ((unused)) int idx) { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, Head H, Tail... T) {
if(idx > 0) cerr << ", ";
stringstream ss; ss << H;
cerr << args[idx] << " = " << ss.str();
debug_out(args, idx + 1, T...);
}
#ifdef XOX
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __VA_ARGS__)
#else
#define debug(...) 42
#endif
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& CODE &&&&&&&&&&&&&&&&&&&&&&&&&&&
const int MAXN = 705;
char g[MAXN][MAXN];
int N, M;
int sx, sy;
int tx, ty;
int vx, vy;
const int inf = 1e9;
int vd[MAXN][MAXN];
int cover[MAXN][MAXN];
bool vis[MAXN][MAXN];
void bfs(){
queue<pair<int, pair<int, int>>> q;
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= M; ++j)
vd[i][j] = cover[i][j] = inf;
auto valid = [&](int i, int j){
if(i >= 1 and i <= N and j >= 1 and j <= M)
return true;
return false;
};
q.push({0, {vx, vy}});
vd[vx][vy] = 0;
while(!q.empty()){
auto p = q.front(); q.pop();
int d = p.first;
int x = p.second.first, y = p.second.second;
for(int k = 0; k < 4; ++k){
int nx = x + dx4[k];
int ny = y + dy4[k];
if(valid(nx, ny) and vd[nx][ny] == inf and g[nx][ny] != 'I'){
vd[nx][ny] = d + 1;
q.push({d + 1, {nx, ny}});
}
}
}
for(int i = 1; i <= N; ++i){
for(int j = 1; j <= M; ++j){
if(vd[i][j] == inf){
continue;
}
cover[i][j] = min(cover[i][j], vd[i][j]);
for(int k = j + 1; k <= M and g[i][k] != 'I'; ++k){
cover[i][k] = min(cover[i][k], vd[i][j]);
}
for(int k = j - 1; k >= 1 and g[i][k] != 'I'; --k){
cover[i][k] = min(cover[i][k], vd[i][j]);
}
for(int k = i + 1; k <= N and g[k][j] != 'I'; ++k){
cover[k][j] = min(cover[k][j], vd[i][j]);
}
for(int k = i - 1; k >= 1 and g[k][j] != 'I'; --k){
cover[k][j] = min(cover[k][j], vd[i][j]);
}
}
}
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= M; ++j)
cover[i][j] = max(cover[i][j], (int)1);
q.push({0, {sx, sy}});
while(!q.empty()){
auto p = q.front(); q.pop();
int d = p.first, x = p.second.first, y = p.second.second;
if(x == tx and y == ty){
cout << "YES\n";
return;
}
for(int k = 0; k < 4; ++k){
int nx = x + dx4[k];
int ny = y + dy4[k];
if(valid(nx, ny) and !vis[nx][ny] and g[nx][ny] != 'I' and d + 1 < cover[nx][ny]){
vis[nx][ny] = true;
q.push({d + 1, {nx, ny}});
}
}
}
cout << "NO\n";
return;
}
void solve(){
cin >> N >> M;
for(int i = 1; i <= N; ++i){
for(int j = 1; j <= M; ++j){
cin >> g[i][j];
if(g[i][j] == 'Y')
sx = i, sy = j;
else if(g[i][j] == 'V')
vx = i, vy = j;
else if(g[i][j] == 'T')
tx = i, ty = j;
}
}
bfs();
}
int32_t main(){
ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int T = 1;
// cin >> T;
for(int i = 1; i <= T; ++i){
// brute();
solve();
}
return 0;
}
/*
Sample inp
| true |
2393941eee2a6f68aaa118995aae9c240d087cb6 | C++ | hiluyx/MultiPerson_ChatRoom | /MultiPerson_ChatRoom/User.cpp | UTF-8 | 236 | 2.5625 | 3 | [] | no_license | #include "User.h"
bool User::login_verification(const char* pass)
{
if (strlen(pass) <= 0 || strlen(password) != strlen(pass))
{
return false;
}
if (0 == strcmp(password, pass))
{
return true;
}
else
{
return false;
}
} | true |
89fb372d1b80f52b0deb0177b49bcbef149762f5 | C++ | dendisuhubdy/gaia | /util/fibers/fibers_ext.cc | UTF-8 | 2,062 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | // Copyright 2019, Beeri 15. All rights reserved.
// Author: Roman Gershman (romange@gmail.com)
//
#include "util/fibers/fibers_ext.h"
namespace std {
ostream& operator<<(ostream& o, const ::boost::fibers::channel_op_status op) {
using ::boost::fibers::channel_op_status;
if (op == channel_op_status::success) {
o << "success";
} else if (op == channel_op_status::closed) {
o << "closed";
} else if (op == channel_op_status::full) {
o << "full";
} else if (op == channel_op_status::empty) {
o << "empty";
} else if (op == channel_op_status::timeout) {
o << "timeout";
}
return o;
}
} // namespace std
namespace util {
namespace fibers_ext {
using namespace boost;
// Not sure why we need compare_exchange_strong only in case of timed-wait but
// I am not gonna deep dive now.
inline bool should_switch(fibers::context* ctx, std::intptr_t expected) {
return ctx->twstatus.compare_exchange_strong(expected, static_cast<std::intptr_t>(-1),
std::memory_order_acq_rel) ||
expected == 0;
}
void condition_variable_any::notify_one() noexcept {
auto* active_ctx = fibers::context::active();
// get one context' from wait-queue
spinlock_lock_t lk{wait_queue_splk_};
while (!wait_queue_.empty()) {
auto* ctx = &wait_queue_.front();
wait_queue_.pop_front();
if (should_switch(ctx, reinterpret_cast<std::intptr_t>(this))) {
// notify context
lk.unlock();
active_ctx->schedule(ctx);
break;
}
}
}
void condition_variable_any::notify_all() noexcept {
auto* active_ctx = fibers::context::active();
// get all context' from wait-queue
spinlock_lock_t lk{wait_queue_splk_};
wait_queue_t tmp;
tmp.swap(wait_queue_);
lk.unlock();
// notify all context'
while (!tmp.empty()) {
fibers::context* ctx = &tmp.front();
tmp.pop_front();
if (should_switch(ctx, reinterpret_cast<std::intptr_t>(this))) {
// notify context
active_ctx->schedule(ctx);
}
}
}
} // namespace fibers_ext
} // namespace util
| true |
2c6cfa7c8614e61cdbab13173882e26e9eb10ad9 | C++ | AnnamaryC/Codigo | /C++/Spanish/Proyecto3_2.cpp | UTF-8 | 708 | 3.03125 | 3 | [] | no_license | //Annamary W. Cartagena
//802-15-1232
//fecha
//Proyecto3_2
#include <iostream>
using namespace std;
int main(){
char x;
cout << "Porfavor indique una de las condiciones climaticas abreviadas a su letra inicial" << endl;
cout << "(T)Tormenta, (L)Lluvia, (B)Bueno, (S)Seco" << endl;
cin >> x;
if(x == 't'|| x =='T')
cout << "TORMENTA: Usar impermeable y sombrero." << endl;
else if (x == 'l'|| x =='L')
cout << "LLUVIA: Usar impermeable y paraguas." << endl;
else if (x == 'b'|| x =='B')
cout << "BUENO: Usar chaqueta y paraguas." << endl;
else if (x == 's'|| x =='S')
cout << "SECO: Usar chaqueta." << endl;
else
cout << "Error 1: Condicion Climatica invalida" << endl;
return 0;
}
| true |
d86468c84943708af65de39e73e7a4eb0f5d1e6c | C++ | MAZHIWEI0820/ma_zhiwei | /main6.19.cpp | GB18030 | 411 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
double hypotenuse(double x,double y)
{
double z=1.0;
z=sqrt(x*x+y*y);
return z;
}
int main()
{
int x;
int y;
cout<<"ֱεһֱDZΪ: ";
cin>>x;
cout<<"ֱεһֱDZΪ: ";
cin>>y;
cout<<"ֱεбΪ: "<<hypotenuse(x,y)<<endl;
return 0;
}
| true |
07046ed8c0e2ea961e8090073b2a1d832da228c9 | C++ | grapeot/cppsugar | /test.cpp | UTF-8 | 2,088 | 3.375 | 3 | [] | no_license | // unit test file for the func namespace
#include <iostream>
#include <string>
#include "cppsugar"
using namespace std;
using namespace func;
using namespace util;
template<typename T>
bool IsEqual(const vector<T> &a, const vector<T> &b) {
if (a.size() != b.size()) { return false; }
for (size_t i = 0; i < a.size(); i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
int main() {
// test basic functions
auto vec = Range(0, 2, 20);
if (!IsEqual(vec, vector<int>{0, 2, 4, 6, 8, 10, 12, 14, 16, 18})) { return -1; }
cout << "[PASS] Range passed." << endl;
vec = Map<int, int>(vec, [](int x) { return x + 1; });
if (!IsEqual(vec, vector<int>{1, 3, 5, 7, 9, 11, 13, 15, 17, 19})) { return -1; }
cout << "[PASS] Map passed." << endl;
vec = Filter<int>(vec, [](int x) { return (x % 3 == 0); });
if (!IsEqual(vec, vector<int>{3, 9, 15})) { return -1; }
cout << "[PASS] Filter passed." << endl;
if (Sum(vec) != 27) { return -1; }
if (Average(vec) != 9) { return -1; }
cout << "[PASS] Sum and average passed." << endl;
if (Min(vec) != 3) { cout << "[FAIL] Min test failed." << endl; return -1; }
if (Max(vec) != 15) { cout << "[FAIL] Max test failed." << endl; return -1; }
if (ArgMin(vec) != 0) { cout << "[FAIL] Argmin test failed." << endl; return -1; }
if (ArgMax(vec) != 2) { cout << "[FAIL] ArgMax test failed." << endl; return -1; }
cout << "[PASS] Min/Max and ArgMin/ArgMax passed." << endl;
// test chain
// test string replace
string str = "shability";
Replace(str, "sha", "niu");
if (str.compare("niubility")) {
cout << "[FAIL] String replacement test failed." << endl;
return -1;
}
else {
cout << "[PASS] String replacement test passed." << endl;
}
// test print
cout << Print("var = ", 2) << endl;
cout << Print("var = ", 2, ", var2 = ", 3.0) << endl;
cout << "[PASS] All passed!" << endl;
return 0;
}
| true |
a979f6f1c3c1aaf32beb982419a4ceec5ec6c155 | C++ | dc-tw/leetcode | /190-Reverse Bits.cpp | UTF-8 | 288 | 2.734375 | 3 | [] | no_license | class Solution {
public:
uint32_t reverseBits(uint32_t n) {
unsigned s = 8 * sizeof(n);
uint32_t mask = ~0;
while ((s = s >> 1) > 0) {
mask ^= mask << s;
n = ((n >> s) & mask) | ((n << s) & (~mask));
}
return n;
}
}; | true |
d13017a353b0be4f68a774d9be9c3284bd8c94d3 | C++ | Fakizer/airhokey | /Airhokey/Airhokey/Src/TextureManager.cpp | UTF-8 | 475 | 2.828125 | 3 | [] | no_license | #include "TextureManager.h"
SDL_Texture* TextureManager::LoadTexture(const char* filename) {
SDL_Surface* tempSurface = IMG_Load(filename);
SDL_Texture* tex = SDL_CreateTextureFromSurface(Game::renderer, tempSurface);
SDL_FreeSurface(tempSurface);
return tex;
}
void TextureManager::Draw(SDL_Texture* tex, const SDL_Rect * src, const SDL_Rect * dest, SDL_RendererFlip flip) {
SDL_RenderCopyEx(Game::renderer, tex, src, dest, NULL, NULL, flip);
} | true |
cbc1300ab2d807676426499597032b4450f3f138 | C++ | jgpATs2w/uned-lenguajes-programacion | /Tema_6_asignaciones_expresiones/declaracionArray1.cpp | ISO-8859-3 | 718 | 3.71875 | 4 | [] | no_license | // Fichero: declaracionArray1.cpp
#include <iostream>
int main()
{
// Declaracin e inicializacin del array num
int num[] = { 2, 3, 5, 8, 100 };
// Escritura en la consola de los componentes de num
std::cout << "num:\t"
<< num[0] << ",\t"
<< num[1] << ",\t"
<< num[2] << ",\t"
<< num[3] << ",\t"
<< num[4] << std::endl;
// Declaracin del array x
double x[3];
// Entrada por teclado del valor de los componentes de x
std::cout << "Introduzca los tres componentes del vector: ";
std::cin >> x[0] >> x[1] >> x[2];
// Escritura en la consola del valor de los componentes de x
std::cout << "x:\t"
<< x[0] << ",\t"
<< x[1] << ",\t"
<< x[2] << std::endl;
return 0;
}
| true |
15b5b6db44334c323de91f88511508d0a90625c0 | C++ | portaloffreedom/tol-controllers | /shared/source/CppnGenome.cpp | UTF-8 | 4,187 | 2.828125 | 3 | [] | no_license | #include "CppnGenome.h"
CppnGenome::CppnGenome(int size) : size(size)
{
//Create a new genome.
std::vector<NEAT::GeneticNodeGene> nodeVector;
//The bias node. The activation function is linear so
//It will simply output its value.
nodeVector.push_back(NEAT::GeneticNodeGene(
INPUT_BIAS,
TYPE_INPUT,
DRAW_POS_ZERO,
RANDOM_ACTIVATION_FALSE,
ACTIVATION_FUNCTION_LINEAR)
);
//The input nodes for the x and y values for the activation value matrix
//Random activation is false here, but it might be better to make it true
nodeVector.push_back(NEAT::GeneticNodeGene(
INPUT_X,
TYPE_INPUT,
0,
DRAW_POS_ZERO,
RANDOM_ACTIVATION_TRUE)
);
nodeVector.push_back(NEAT::GeneticNodeGene(
INPUT_Y,
TYPE_INPUT,
0,
DRAW_POS_ZERO,
RANDOM_ACTIVATION_TRUE)
);
//The output node of the network.
nodeVector.push_back(NEAT::GeneticNodeGene(
OUTPUT,
TYPE_OUTPUT,
0,
DRAW_POS_HALF_MAX,
RANDOM_ACTIVATION_TRUE)
);
//The creation of the new genome.
//New individuals will start with a 'fully' connected network:
//the input nodes will be connected to the output node.
//Handled by smart pointer
cppn = boost::shared_ptr<NEAT::GeneticIndividual>(new NEAT::GeneticIndividual(
nodeVector,
CREATE_TOPOLOGY_TRUE,
EDGE_DENSITY_FULLY_CONNECTED)
);
}
CppnGenome::CppnGenome(const CppnGenome& genome1) : size(genome1.size), cppn(genome1.cppn)
{
}
CppnGenome::CppnGenome(std::istream& stream)
{
std::string genomeStr;
std::string cppnStr;
stream >> genomeStr >> size >> cppnStr;
cppn = boost::shared_ptr<NEAT::GeneticIndividual>(new NEAT::GeneticIndividual(stream));
}
CppnGenome::~CppnGenome()
{
}
string CppnGenome::toString() const
{
std::string result = std::string("genome ");
result.append(std::to_string(size));
result.append(" cppn ");
ostringstream oss;
cppn->dump(oss);
result.append(oss.str());
return result;
}
void CppnGenome::mutate()
{
cppn = boost::shared_ptr<NEAT::GeneticIndividual>(new NEAT::GeneticIndividual(cppn, true));
mutateSize();
}
void CppnGenome::crossoverAndMutate(const CppnGenome& genome)
{
cppn = boost::shared_ptr<NEAT::GeneticIndividual>(new NEAT::GeneticIndividual(cppn, genome.getCppn(), true));
//The random between 0 and 1 ensures that a crossover of, for example,
//5 and 6 will result in 5 only 50% of the time, and 6 the other 50%.
//Not using it would give a bias to the smaller parent.
size = (size + genome.getSize() + RANDOM.getRandomDouble()) / 2.0;
mutateSize();
}
boost::shared_ptr<NEAT::GeneticIndividual> CppnGenome::getCppn() const
{
return cppn;
}
double CppnGenome::getSize() const
{
return size;
}
void CppnGenome::mutateSize()
{
if (RANDOM.getRandomDouble() < SIZE_MUTATION_RATE)
{
// std::default_random_engine generator;
// std::normal_distribution<double> distribution(0,SIZE_MUTATION_STRENGTH);
// std::binomial_distribution<int> distribution(2,0.5);
// double randomMutation = distribution(generator);
int randomMutation = RANDOM.getRandomWithinRange(-1, 1);
size = size + randomMutation;
if(size < CPPN_GRID_MINIMUM_SIZE) {
size = CPPN_GRID_MINIMUM_SIZE;
}
}
} | true |
694f76ec4814348d552893de4ceb22001e71c4c8 | C++ | 1234bpv/CPA-Programing-Essentials-in-C- | /Chapter2/cpa_lab_2_3_19_-9--C/cpa_lab_2_3_19_(9)-C.cpp | UTF-8 | 254 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(void) {
int n;
long botnum;
cout << "Enter odd number: ";
cin >> n;
botnum = n*n;
botnum -= n * 2 - 2;
cout << botnum << endl;
system("pause");
return 0;
}
| true |
e416c635c9667e07ad6b5af02fb7f100df84fa28 | C++ | paumayr/cppexamples | /CppWorkshop/CppWorkshopSamples/Demo_Exceptions/main.cpp | UTF-8 | 1,102 | 3.3125 | 3 | [] | no_license | #include <exception>
#include <iostream>
#include <cmath>
struct square_root_exception : public std::exception
{
public:
};
class StackMonitor
{
public:
~StackMonitor()
{
std::cout << "Destructing" << std::endl;
}
};
float squareRoot(float f)
{
if (f < 0.0f)
{
throw square_root_exception();
}
return sqrtf(f);
}
void readFile(int *data, std::string filename)
{
// throw std::exception("reading file failed");
}
void ComplexCalculation()
{
int * daten = new int[1000];
//StackMonitor sm;
readFile(daten, "filename");
squareRoot(-100.0f);
//throw int(10);
delete[] daten;
}
int main(int argc, char **argv)
{
try
{
ComplexCalculation();
std::cout << "this line will never be printed" << std::endl;
}
catch(square_root_exception &sqex)
{
std::cout << "negate square root!??!" << std::endl;
}
catch(std::exception &ex)
{
std::cout << "caught exception " << ex.what() << std::endl;
}
catch(...)
{
std::cout << "something else happened" << std::endl;
}
std::cin.get();
return 0;
}
| true |
4740f6a9732844c693f4508f0d77cf1d5dfebf5b | C++ | bhavikmalhotra/DSA | /pointer/char_array.cpp | UTF-8 | 948 | 4.0625 | 4 | [] | no_license | #include <iostream>
using namespace std;
//char behave differntly beacause of the way cout is implemanted ; char prints till it finds the null char;
int main(){
int a[] = {1,2,3};
char b[] = "abc";
cout<< a <<endl;//prints address of a
cout<< *a <<endl;
cout<< b <<endl;//thisd prints thew entire strings at that array till it encounters the null character this is because of the way cout is implemented.
char *c = &b[0];
cout<< c <<endl;//expected to print address like the other pointers but behave diffrebtly because the way cout is implemented
char d = 'g';
char *d1 = &d;
cout<< d <<endl;
cout<< d1 <<endl;//expected to print the address but we know char prints the value at the memory but the interesting thing that happend here is that
//it printed the value but it did not stop after it it printed till it found the null character in the memory;
} | true |
6e3a79dde87874209448555c32f335862325e0cd | C++ | ttgc/network_tp2 | /main/src/client.cpp | UTF-8 | 2,528 | 2.765625 | 3 | [] | no_license | #include "client.hpp"
#include "player.hpp"
#include "enemy.hpp"
namespace client
{
Client::Client(const std::string& ip, uint16_t port) noexcept :
m_ConnectionClient(), m_loop(uvw::Loop::getDefault())
{
m_ConnectionClient = m_loop->resource<uvw::TCPHandle>();
m_ConnectionClient->on<uvw::ErrorEvent>([](const uvw::ErrorEvent &, uvw::TCPHandle &)
{
std::cout << "An error as occured" << std::endl;
});
m_ConnectionClient->on<uvw::ConnectEvent>([](const uvw::ConnectEvent &, uvw::TCPHandle &tcp)
{
std::cout << "Connected to Server" << std::endl;
tcp.read();
});
m_ConnectionClient->on<uvw::DataEvent>([this](const uvw::DataEvent& evt, uvw::TCPHandle &)
{
const auto repManager = ReplicationManager::get();
gsl::span<char> receivedData(evt.data.get(), evt.length);
InputStream receivedStream(receivedData);
repManager.lock()->replicate(receivedStream);
std::vector<GameObject*> vectObjects = repManager.lock()->getObjects();
std::for_each(vectObjects.begin(), vectObjects.end(), [this](GameObject* Obj)
{
std::cout << "Replication data : " << Obj->ClassID() << " received." << std::endl;
if (Obj->ClassID() == 1)
{
const auto player = reinterpret_cast<Player*>(Obj);
const auto pos = player->getPosition();
const auto rot = player->getRotation();
std::cout << "Player " << player->getName() << ": (" <<
pos.x << ", " << pos.y << ", " << pos.z << ") - (" <<
rot.x << ", " << rot.y << ", " << rot.z << ", " << rot.w << ")" <<
std::endl;
}
else if (Obj->ClassID() == 2)
{
const auto enemy = reinterpret_cast<Enemy*>(Obj);
const auto pos = enemy->getPosition();
const auto rot = enemy->getRotation();
std::cout << "Enemy " << enemy->getType() << ": (" <<
pos.x << ", " << pos.y << ", " << pos.z << ") - (" <<
rot.x << ", " << rot.y << ", " << rot.z << ", " << rot.w << ")" <<
std::endl;
}
}
);
});
m_ConnectionClient->connect(ip, port);
m_loop->run();
}
Client::~Client() noexcept
{
m_ConnectionClient->stop();
m_ConnectionClient->clear();
m_ConnectionClient->close();
}
} | true |
142c89be7102a4f2d5f648cabcf1b47649942fcb | C++ | jnyabe/cpp_test | /graph/adj_matrix.cpp | UTF-8 | 1,976 | 3.1875 | 3 | [] | no_license | #include "adj_matrix.h"
AdjMatrix::AdjMatrix(int num_vertex)
: m_num_vertex(num_vertex)
{
m_matrix.resize(m_num_vertex * m_num_vertex, 0);
}
AdjMatrix::AdjMatrix(const AdjMatrix& mat)
: Graph(mat)
{
m_num_vertex = mat.m_num_vertex;
m_matrix.resize(m_num_vertex * m_num_vertex, 0);
std::copy(mat.m_matrix.begin(), mat.m_matrix.end(), back_inserter(m_matrix));
}
int AdjMatrix::AddVertex(const Vertex &v)
{
if(v.m_id > m_num_vertex)
{
int num_vertex = v.m_id;
std::vector<int> tmp(num_vertex * num_vertex, 0);
for(int i=0; i < m_num_vertex; i++)
{
for(int j=0; j < m_num_vertex; j++)
{
tmp[i* num_vertex + j] = m_matrix[i * m_num_vertex + j];
}
}
m_matrix.resize(num_vertex * num_vertex);
for(int i=0; i < num_vertex * num_vertex; i++)
m_matrix[i] = tmp[i];
m_num_vertex = num_vertex;
}
return 0;
}
int AdjMatrix::RemoveVertex(const Vertex &v)
{
for(int i=0; i < m_num_vertex; i++)
{
// clean edge to/from the denoted vertex
m_matrix[m_num_vertex * i + v.m_id - 1] = 0;
m_matrix[(v.m_id - 1) * m_num_vertex + i] = 0;
}
return 0;
}
int AdjMatrix::AddEdge(const Vertex& from, const Vertex& to, int cost)
{
int ret = 0;
if(m_num_vertex < from.m_id)
{
ret = AddVertex(from);
}
if(m_num_vertex < to.m_id)
{
ret = AddVertex(to);
}
m_matrix[(from.m_id-1) * m_num_vertex + (to.m_id - 1)] = cost;
m_matrix[(to.m_id-1) * m_num_vertex + (from.m_id - 1)] = cost;
return ret;
}
int AdjMatrix::RemoveEdge(const Vertex& from, const Vertex& to)
{
m_matrix[(from.m_id-1) * m_num_vertex + (to.m_id - 1)] = 0;
m_matrix[(to.m_id-1) * m_num_vertex + (from.m_id - 1)] = 0;
return 0;
}
void AdjMatrix::Clear(void)
{
m_num_vertex = 0;
m_matrix.clear();
}
void AdjMatrix::Dump() const
{
printf("# of vertex: %d\n", m_num_vertex);
for(int i=0; i < m_num_vertex; i++)
{
for(int j=0; j < m_num_vertex; j++)
{
printf("%d%c", m_matrix[j + i * m_num_vertex],
(j == m_num_vertex - 1)? '\n':',');
}
}
}
| true |
2025a2bc2b43ad47d8d5387615355c83f9668da1 | C++ | vishnuRND/Programs | /compress.cpp | UTF-8 | 695 | 2.59375 | 3 | [] | no_license | // compress.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{
char string1[]="abcd";
int k=strlen(string1);
int *a=(int *)malloc(k*sizeof(int));
int start=0,i=0,j=0,count=1;
while(string1[i+1]!='\0')
{
if(string1[i]==string1[i+1])
{
count++;
if(start==0)
{
a[j]=string1[i];
a[++j]=count;
start=1;
}
else
a[j]=count;
}
else
{
j=j++;
count=1;
a[j]=string1[i+1];
a[++j]=count;
}
i++;
}
for(int start=0;start<=j;start++)
{
if(a[start]>=97)
printf("%c",a[start]);
else
printf("%d",a[start]);
}
return 0;
}
| true |
690b17db7ba68c0e299caad17fc746eba21bba01 | C++ | WilliamLewww/Thane | /src/board/truck.cpp | UTF-8 | 2,487 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "truck.h"
void Truck::setAngle(double* angle) {
boardAngle = angle;
};
void Truck::setWheelColor(int r, int g, int b) {
wheelColor[0] = r;
wheelColor[1] = g;
wheelColor[2] = b;
}
void Truck::setWidth(int width) {
leftTruck.setSize(1, width);
rightTruck.setSize(1, width);
leftTruck.setColor(truckColor[0], truckColor[1], truckColor[2], 255);
rightTruck.setColor(truckColor[0], truckColor[1], truckColor[2], 255);
};
void Truck::updatePosition(Vector2 left, Vector2 right) {
leftTruck.setPositionCentered(left);
rightTruck.setPositionCentered(right);
leftTruck.setAngle(*boardAngle);
rightTruck.setAngle(*boardAngle);
if (turnLeft && additionalAngle > -turnRadius) {
if (additionalAngle > 0) {
additionalAngle -= recovery * timer.getTimeSeconds();
}
else {
additionalAngle -= carveStrength * timer.getTimeSeconds();
}
}
if (turnRight && additionalAngle < turnRadius) {
if (additionalAngle < 0) {
additionalAngle += recovery * timer.getTimeSeconds();
}
else {
additionalAngle += carveStrength * timer.getTimeSeconds();
}
}
if (!turnRight && !turnLeft) {
if (additionalAngle > 0) {
if (additionalAngle - recovery * timer.getTimeSeconds() <= 0) {
additionalAngle = 0;
}
else {
additionalAngle -= recovery * timer.getTimeSeconds();
}
}
if (additionalAngle < 0) {
if (additionalAngle + recovery * timer.getTimeSeconds() > 0) {
additionalAngle = 0;
}
else {
additionalAngle += recovery * timer.getTimeSeconds();
}
}
}
leftTruck.addAngle(additionalAngle);
rightTruck.addAngle(-additionalAngle);
};
void Truck::draw(bool ridingSwitch) {
leftTruck.draw();
rightTruck.draw();
if (!ridingSwitch) {
drawing.drawRect(leftTruck.getTopRight() - Vector2(1, 1), 3, 3, leftTruck.getAngle(), wheelColor);
drawing.drawRect(leftTruck.getBottomRight() - Vector2(1, 1), 3, 3, leftTruck.getAngle(), wheelColor);
drawing.drawRect(rightTruck.getTopRight() - Vector2(1, 1), 3, 3, rightTruck.getAngle(), wheelColor);
drawing.drawRect(rightTruck.getBottomRight() - Vector2(1, 1), 3, 3, rightTruck.getAngle(), wheelColor);
}
else {
drawing.drawRect(leftTruck.getTopRight(), 3, 3, leftTruck.getAngle(), wheelColor);
drawing.drawRect(leftTruck.getBottomRight(), 3, 3, leftTruck.getAngle(), wheelColor);
drawing.drawRect(rightTruck.getTopRight(), 3, 3, rightTruck.getAngle(), wheelColor);
drawing.drawRect(rightTruck.getBottomRight(), 3, 3, rightTruck.getAngle(), wheelColor);
}
}; | true |
3336a1a94536628b1823c07e2142356e18ebcccc | C++ | hgedek/cpp-samples | /function_traits.cpp | UTF-8 | 941 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <tuple>
// decltype for all function (member or not ) will return a type as
// RT(...)(Args) so
// members will be T::* and non-members or statics will be (*) ...
// (*) => function
// * => others
template <class T> // here we will trigger second specialization with &T::operator() => (S::*)(Args...)
struct function_traits: public function_traits<decltype(&T::operator())>{};
template <class CT, class RT, class...Args>
struct function_traits<RT(CT::*)(Args...) const > {
enum {
num_args = sizeof...(Args)
};
typedef RT result_type;
template <size_t N>
struct arg {
typedef typename std::tuple_element<N, std::tuple<Args...>>::type type;
};
};
struct S {
void operator()(int,float,double) const {}
};
int main() {
std::cout << function_traits<S>::num_args << std::endl;
std::cout << typeid(function_traits<S>::arg<2>::type).name() << std::endl;
}
| true |
27e7b259c3eba13465e80adb771cb6686456c125 | C++ | somethingExciting/UOP-CS-Coursework | /COMP53/cpp_practice/pointers.cpp | UTF-8 | 363 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
//double arr[20];
int size;
cout << "Enter size: ";
cin >> size;
double *arr = new double[size];
double *p1, *p2;
p1 = arr;
//p2 = &arr[19];
p2 = &arr[size - 1];
size = p2 - p1;
cout << "P1 = " << p1 << " P2 = " << p2 << " size = " << size << endl;
cout << (p2 - p1) << endl;
system("pause");
} | true |
775d1919cf85024ad8c5f93566a07f1d26358755 | C++ | kevinzhangftw/Optimal-Greedy-Solution | /OptimialGreedySolutionMinimizeInjectivePairing/main.cpp | UTF-8 | 1,574 | 2.609375 | 3 | [] | no_license | //
// main.cpp
// OptimialGreedySolutionMinimizeInjectivePairing
//
// Created by Kevin Zhang on 2016-07-31.
// Copyright © 2016 Kevin Zhang. All rights reserved.
//
#include <iostream>
#include "RecSolver.hpp"
#include "IterSolver.hpp"
#include "PInfo.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
bool IterMode = false, RecMode = true;
// if (argc != 2) {
// cout << "Recursive Usage: \"Match R < sample.in\"" << endl;
// cout << "Iterative Usage: \"Match I < sample.in\"" << endl;
// return 0;
// }
// if (argv[1][0] == 'I') {
// RecMode = false;
// } else if (argv[1][0] == 'R') {
// IterMode = false;
// } else {
// cout << "Recursive Usage: \"Match R < sample.in\"" << endl;
// cout << "Iterative Usage: \"Match I < sample.in\"" << endl;
// return 0;
// }
ProblemInfo *PInfo = new ProblemInfo();
PInfo->m = 6;
PInfo->n = 5;
PInfo->S = new int[PInfo->m];
PInfo->H = new int[PInfo->n];
for (int i = 160; i <= 160+PInfo->m; ++i) {
PInfo->S[i-160]= i;
cout << " " << PInfo->S[i-160];
}
cout << " " << endl;
for (int i = 170; i <= 170+PInfo->n; ++i) {
PInfo->H[i-170]= i;
cout << " " << PInfo->H[i-170];
}
// PInfo->Read();
cout << "the solution: " << endl;
if (IterMode) {
cout << " " << IterSolve(PInfo) << endl;
}
if (RecMode) {
cout << " " << RecSolve(PInfo) << endl;
}
// delete PInfo;
return 0;
}
| true |
bae7eca613dce712912af11e2f33d55fb089024a | C++ | DanuAdiP/bilangan-positif-negatif | /bilpostfngtf.cpp | UTF-8 | 396 | 3.21875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int bil;
cout<<"Nama = Danu Adiputra"<<endl;
cout<<"NIM = 311810929"<<endl;
cout<<"Kelas = 18.B.2"<<endl<<endl;
cout<<"PROGRAM MENGETAHUI BILANGAN POSITIF DAN NEGATIF"<<endl<<endl;
cout<<"Masukkan angka = ";cin>>bil;
cout<<bil;
if(bil<0)
cout<<" adalah bilangan negatif";
else if(bil>0)
cout<<" adalah bilangan positif";
return 0;
}
| true |
93fd9c3dd813d066f7c6d2261985bcac7b70d23b | C++ | junxianzzz97/ista | /q4.cpp | UTF-8 | 431 | 3.46875 | 3 | [] | no_license | #include<iostream>
using namespace std;
//季節判定
int main()
{
int input=0;
cin>>input;
switch(input/3)//取商數為區分點
{
case 1:cout<<"Spring"<<endl;break;//商數為1,(3,4,5)
case 2:cout<<"Summer"<<endl;break;//商數為2,(6,7,8)
case 3:cout<<"Autumn"<<endl;break;//商數為3,(9,10,11)
default :cout<<"Winter"<<endl;//其餘(12(商數為4),1,2)皆為冬季
}
return 0;
} | true |
ff99cc7b180516762676d2e35c971f47f00b6a62 | C++ | KazukiHiraizumi/Arduino | /dcuino2/Algor.h | UTF-8 | 569 | 2.515625 | 3 | [] | no_license | #ifndef _Algor_h
#define _Algor_h
#include "Arduino.h"
extern void algor_prepare();
extern uint8_t algor_update(int32_t time,int32_t duty);
extern uint8_t algor_param[8*7];
/*
inline float accumulate(float *arr1,float *arr2){
float sum=0;
for(;arr1<arr2;arr1++) sum+=*arr1;
return sum;
}
inline uint32_t accumulate(uint32_t *arr1,uint32_t *arr2){
uint32_t sum=0;
for(;arr1<arr2;arr1++) sum+=*arr1;
return sum;
}
*/
template<typename T> inline long accumulate(T *arr1,T *arr2){
long sum=0;
for(;arr1<arr2;arr1++) sum+=*arr1;
return sum;
}
#endif
| true |
289b3122ab88ef468204cd1eda7123e04ca2bd67 | C++ | tsr9804/computer-science-foundations | /C++/ticketsales.h | UTF-8 | 1,406 | 3.625 | 4 | [] | no_license | // ShowTicket class
#include<string>
class ShowTicket {
bool isSold;
protected:
std::string row;
std::string seatNumber;
public:
ShowTicket(std::string row, std::string seatNumber){
this -> row = row;
this -> seatNumber = seatNumber;
isSold = false;
};
ShowTicket() { isSold = false; }
bool is_sold() { return isSold; }
void sell_seat() { isSold = true; }
virtual std::string print_ticket() {
std::string status = row + " " + seatNumber;
if(is_sold())
status += " sold";
else
status += " available";
return status;
}
};
class SportTicket :public ShowTicket {
bool beerSold;
public:
SportTicket(std::string row, std::string seatNumber)
: ShowTicket (row, seatNumber)
{
beerSold = false;
}
bool beer_sold() { return beerSold; }
void sell_beer() { beerSold = true; }
std::string print_ticket() override {
std::string status = row + " " + seatNumber;
if(is_sold())
status += " sold";
else
status += " available";
if(beer_sold())
status += " beer";
else
status += " nobeer";
return status;
}
};
class TicketSales{
public:
std::string print_ticket(ShowTicket *myticket){
return myticket -> print_ticket();
}
};
| true |
e9d350f530ce209e7a338aa93f7ea9b9eca70044 | C++ | Alan-Lee123/POJ | /Data Structure/1634.cpp | UTF-8 | 1,118 | 2.625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <string>
#include <set>
#include <cstdlib>
#include <ctime>
using namespace std;
struct point
{
int h, s, id, cnt, boss;
point() {}
point(int id, int h, int s) : id(id), h(h), s(s), cnt(1) {}
bool operator < (const point& p) const
{
return s < p.s;
}
};
point ps[31000];
point idx[1000000];
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
int m, q;
scanf("%d%d", &m, &q);
for (int i = 0; i < m; ++i)
{
int h, s, id;
scanf("%d%d%d", &id, &s, &h);
ps[i] = point(id, h, s);
}
ps[m] = point(0, 3000000, 20000000);
++m;
sort(ps, ps + m);
stack<point> st;
for (int i = 0; i < m; ++i)
{
while (!st.empty() && st.top().h <= ps[i].h)
{
ps[i].cnt += st.top().cnt;
idx[st.top().id].boss = ps[i].id;
st.pop();
}
idx[ps[i].id] = ps[i];
st.push(ps[i]);
}
for (int i = 0; i < q; ++i)
{
int id;
scanf("%d", &id);
point t = idx[id];
printf("%d %d\n", t.boss, t.cnt - 1);
}
}
return 0;
} | true |
4e17fffdc81e6fec83ee6389e4c96cf0dd243bee | C++ | rajat1712/someusefulcodes | /DynamicProgramming/maxRectangle/maxRectangleSum.cpp | UTF-8 | 1,097 | 3.109375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int kadaneAlgo(int *arr,int n){
int max_so_far=arr[0];
int max_ending_here=0;
int start,end,s;
for(int i=0;i<n;i++){
max_ending_here=max_ending_here+arr[i];
if(max_so_far < max_ending_here){
max_so_far=max_ending_here;
}
if(max_ending_here<0){
max_ending_here=0;
}
}
return max_so_far;
}
int maxSumRectangle(int m,int n,int **input){
int maxSum=INT_MIN;
int maxLeft;
int maxRight;
int maxUp;
int maxDown;
int newArray[m];
int sum=0;
int start;
int end;
for(int left=0;left<n;left++){
for(int right=left;right<n;right++){
for(int i=0;i<m;i++){
newArray[i]=newArray[i]+input[i][right];
}
sum=kadaneAlgo(newArray,n);
if(sum > maxSum){
maxSum=sum;
}
}
}
return maxSum;
}
int main(){
int m;
cin>>m;
int n;
cin>>n;
int **input=new int*[m];
for(int i=0;i<m;i++){
input[i]=new int[n];
for(int j=0;j<n;j++){
cin>>input[i][j];
}
}
int ans=maxSumRectangle(m,n,input);
cout<<ans<<endl;
}
| true |
04e839e390acf87ddecbb5bae1bf6d96d2061b35 | C++ | Hillol18/Amazon_interview_problem_solution | /Cutoff Ranks.cpp | UTF-8 | 3,032 | 3.953125 | 4 | [] | no_license | /*
Link: https://aonecode.com/amazon-online-assessment-cutoff-ranks
A group of work friends at Amazon is playing a competitive video game together. During the game, each player receives a certain amount of points based on their performance. At the end of a round, players who achieve at least a cutoff rank get to "level up" their character, gaining increased abilities for them. Given the scores of the players at the end of the round, how many players will be able to level up their character?
Note that players with equal scores will have equal ranks, but the player with the next lowest score will be ranked based on the position within the list of all players' scores. For example, if there are four players, and three players tie for first place, their ranks would be 1,1,1, and 4. Also, no player with a score of O can level up, no matter what their rank.
Write an algorithm that returns the count of players able to level up their character.
Input
The input to the function/method consists of three arguments:
cutOffRank, an integer representing the cutoff rank for levelin up the player's character;
num, an integer representing the total number of scores;
scores, a list of integers representing the scores of the players.
Output
Return an integer representing the number of players who will be able to level up their characters at the end of the round.
Constraints
1 <= num <= 10^5
0 <= scores[i] <= 100
0 <= i < num
cutOffRank <= num
Examples
Example 1:
Input:
cutOffRank = 3
num= 4
scores=[100, 50, 50, 25 ]
Output:
3
Explanation:
There are num= 4 players, where the cutOffRank is 3 and scores = [100, 50,50, 25]. These players' ranks are [1, 2, 2, 4]. Because the players need to have a rank of at least 3 to level up their characters, only the first three players will be able to do so.
So, the output is 3.
Example 2:
Input:
cutOffRank = 4
num=5
scores=[2,2,3,4,5]
Output:
5
Explanation:
In order, the players achieve the ranks [4,4,3,2,1]. Since the cutOffRank is 4, all 5 players will be able to level up their characters.
So, the output is 5.
*/
#include <iostream>
#include <vector>
using namespace std;
int getCutOffRanks(int cutOffRanks, vector<int> scores)
{
int n = scores.size();
if (cutOffRanks >= n)
return n;
int ans = 0;
int m = 0;
for (int i = 0; i < n; i++) {
m = max(m, scores[i]);
}
for (int i = m; i > 0; i--)
{
int cnt = 0;
for (int j = 0; j < n; j++)
{
if (scores[j] >= i)
{
cnt++;
}
}
ans = cnt;
if (ans >= cutOffRanks)
{
break;
}
}
return ans;
}
int main()
{
vector<int> arr{25, 23, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 76, 76, 80};
cout << getCutOffRanks(2, arr) << endl;
vector<int> arr1{0, 0, 0, 8, 19, 89};
cout << getCutOffRanks(5, arr1) << endl;
return 0;
}
/*
Time complexity: O(n*m) where n = number of players and m = maximum scores
*/
| true |
be6b33329c4d3b8399ca5405ca900477697e5b5e | C++ | iljeodugu/Opt_Algorithm | /초급/Queue, Stack/혜진_주식가격.cpp | UTF-8 | 547 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int cnt;
int main()
{
//input
vector<int> prices{ 1, 2, 3, 2, 3 };
//process
vector<int> sol;
for (int i = 0; i < prices.size()-1; i++)
{
cnt = 0;
for (int j = i + 1; j < prices.size(); j++)
{
if (prices[i] <= prices[j])
{
cnt++;
}
else
{
cnt++;
break;
}
}
sol.push_back(cnt);
}
sol.push_back(0);
//output
for (int i = 0; i < prices.size(); i++)
{
cout << sol[i] << " ";
}cout << endl;
} | true |
5e84c1fa6468d62d0a17bd99f853aaaf6c0aec45 | C++ | Rudy02/CPP-Fundementals | /inheritance/static_variables/Mother.cpp | UTF-8 | 439 | 3.21875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include "Mother.h"
using namespace std;
int Mother::numOfMothers = 0;
Mother::Mother()
{
Mother::numOfMothers++;
}
Mother::Mother(string name)
{
Mother::numOfMothers++;
this->nameOfMother = name;
}
Mother::~Mother()
{
cout << "Mother " << this-> nameOfMother << " was destroyed." << endl;
Mother::numOfMothers--;
}
int Mother::getNumOfMothers()
{
return numOfMothers;
} | true |
5225152b164fa6365f5f86dc1d4457ef5fa4859a | C++ | Hazurl/Framework-haz | /include/haz/GameObject/Component/2D/Transform.hpp | UTF-8 | 1,332 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef __HAZ_2D_TRANFORM
#define __HAZ_2D_TRANFORM
#include <haz/Tools/Macro.hpp>
#include <haz/Tools/Utility.hpp>
#include <haz/Geometry/2D/Vector.hpp>
#include <haz/GameObject/GameObject.hpp>
#include <vector>
#include <string>
BEG_NAMESPACE_HAZ_2D
class Transform : public Component {
public:
/* Ctor Dtor */
Transform(GameObject* go);
Transform(GameObject* go, Vectorf const& pos, Vectorf const& sca, float rot);
~Transform();
Component* clone(GameObject* go) const;
/* Stringify */
std::string to_string() const;
std::vector<std::string> pretty_strings() const;
friend std::ostream& operator <<(std::ostream& os, Transform const& t);
/* Position */
Vectorf position() const;
void position(Vectorf const& p);
Vectorf globalPosition() const;
void globalPosition(Vectorf const& p);
/* Scale */
Vectorf scale() const;
void scale(Vectorf const& s);
Vectorf globalScale() const;
void globalScale(Vectorf const& s);
/* Rotation */
float rotation() const;
void rotation(float r);
float globalRotation() const;
void globalRotation(float r);
/* Component Implementation */
void onEnable();
void onDisable();
private:
Vectorf pos;
Vectorf sca;
float rot;
};
END_NAMESPACE_HAZ_2D
#endif | true |
c8ba46ca262695fb1ec0004c81fc59d10b42c933 | C++ | jwbuurlage/Motor | /src/MotorShaderManager.cpp | UTF-8 | 10,354 | 2.640625 | 3 | [] | no_license | #include "MotorShaderManager.h"
#include "MotorFilesystem.h"
#include "MotorLogger.h"
namespace Motor {
template<> ShaderManager* Singleton<ShaderManager>::singleton = 0;
//
// ShaderManager::Shader methods
//
ShaderManager::Shader::Shader(ShaderType _type){
type = _type;
loaded = false;
compiled = false;
linkError = false;
switch(type){
case Vertex: { handle = glCreateShader(GL_VERTEX_SHADER); } break;
case Fragment: { handle = glCreateShader(GL_FRAGMENT_SHADER); } break;
default: handle = 0; break;
}
}
ShaderManager::Shader::~Shader(){
//If the shader is still attached, OpenGL will flag it for deletion and delete it as soon as it is detached
if( handle ) glDeleteShader(handle);
}
bool ShaderManager::Shader::load(const char* filename){
pFile shaderFile = Filesystem::getSingleton().getFile(filename);
if( !shaderFile ){
Logger::getSingleton() << Logger::ERROR << "Shader file not found: " << filename << endLog;
}else{
const GLchar* shaderSource = shaderFile->data;
glShaderSource(handle, 1, &shaderSource, NULL);
loaded = true;
compiled = false;
}
return loaded;
}
bool ShaderManager::Shader::compile(){
if( !loaded ){
Logger::getSingleton().log(Logger::WARNING, "Trying to compile shader while no source loaded.");
compiled = false;
}else{
glCompileShader(handle);
GLint value;
glGetShaderiv(handle, GL_COMPILE_STATUS, &value);
if( value == GL_TRUE ){
compiled = true;
}else{
compiled = false;
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &value);
if( value > 0 ){
GLchar* infoLog = new GLchar[value];
glGetShaderInfoLog(handle, value, &value, infoLog);
Logger::getSingleton() << Logger::ERROR << "Shader compilation error: ";
Logger::getSingleton() << infoLog << endLog;
delete[] infoLog;
}
}
}
return compiled;
}
//
// ShaderManager::ShaderProgram methods
//
ShaderManager::ShaderProgram::ShaderProgram(){
handle = glCreateProgram();
linked = false;
}
ShaderManager::ShaderProgram::~ShaderProgram(){
for( std::vector<Shader*>::iterator iter = shaders.begin(); iter != shaders.end(); ++iter ){
glDetachShader(handle, (*iter)->getHandle());
}
glDeleteProgram(handle);
}
void ShaderManager::ShaderProgram::attachShader(Shader* shader){
shaders.push_back(shader);
glAttachShader(handle, shader->getHandle());
}
bool ShaderManager::ShaderProgram::link(){
if( linked ){
Logger::getSingleton().log(Logger::WARNING, "Trying to link shader program that is already linked.");
}else if( shaders.size() < 2 ){
Logger::getSingleton().log(Logger::WARNING, "Trying to link program with less than 2 attached shaders.");
}else{
glLinkProgram(handle);
GLint value;
glGetProgramiv(handle, GL_LINK_STATUS, &value);
if( value == GL_TRUE ){
linked = true;
}else{
linked = false;
//Get the link log info and then the compilation log for all attached shaders.
//First determine the size of the buffer needed
GLint maxBufLen = 0;
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &value);
maxBufLen = value;
for( std::vector<Shader*>::iterator iter = shaders.begin(); iter != shaders.end(); ++iter ){
glGetShaderiv((*iter)->getHandle(), GL_INFO_LOG_LENGTH, &value);
if( value > maxBufLen ) maxBufLen = value;
}
//The buffer will now be big enough to hold all error messages (not at once!)
GLchar* infoLog = new GLchar[maxBufLen];
Logger::getSingleton() << Logger::ERROR << "Shader link error followed by compilation logs: ";
//Now get the log info
glGetProgramInfoLog(handle, maxBufLen, &value, infoLog);
if( value > 0 ) //If it returned a message
Logger::getSingleton() << "\n" << infoLog;
//Display compilation log of all attached shaders and mark them as invalid
for( std::vector<Shader*>::iterator iter = shaders.begin(); iter != shaders.end(); ++iter ){
(*iter)->setLinkError(true);
glGetShaderInfoLog((*iter)->getHandle(), maxBufLen, &value, infoLog);
if( value > 0 ) //If it returned a message
Logger::getSingleton() << "\n" << infoLog;
}
delete[] infoLog;
Logger::getSingleton() << endLog;
}
}
return linked;
}
void ShaderManager::ShaderProgram::use(){
glUseProgram(handle);
}
void ShaderManager::ShaderProgram::enableAttribs(){
for(AttribIterator iter = attribs.begin(); iter != attribs.end(); ++iter ){
glEnableVertexAttribArray(iter->second);
}
}
void ShaderManager::ShaderProgram::bindAttrib(GLuint index, const char* attribName){
if(linked){
Logger::getSingleton().log(Logger::WARNING, "Trying to bind attribute to shader program that is already linked");
}else{
attribs.insert(AttribContainer::value_type(attribName, index));
glBindAttribLocation(handle, index, attribName);
}
}
void ShaderManager::ShaderProgram::vertexAttribPointer(const char* name, GLint size, GLenum type, bool normalize, GLsizei stride, const GLvoid* data){
const AttribIterator attr = attribs.find(name);
if( attr != attribs.end() ) {
glVertexAttribPointer(attr->second, size, type, normalize, stride, data);
}
}
void ShaderManager::ShaderProgram::vertexAttribPointer(GLuint index, GLint size, GLenum type, bool normalize, GLsizei stride, const GLvoid* data){
glVertexAttribPointer(index, size, type, normalize, stride, data);
}
GLuint ShaderManager::ShaderProgram::getUniformLocation(const char* varname){
return glGetUniformLocation(handle, varname);
}
void ShaderManager::ShaderProgram::setUniform1f(const char* varname, float value){
glUniform1f(getUniformLocation(varname), value);
}
void ShaderManager::ShaderProgram::setUniform1i(const char* varname, int value){
glUniform1i(getUniformLocation(varname), value);
}
void ShaderManager::ShaderProgram::setUniform3fv(const char* varname,const float* values){
glUniform3fv(getUniformLocation(varname), 1, values);
}
void ShaderManager::ShaderProgram::setUniformMatrix4fv(const char* varname, const float* mat){
glUniformMatrix4fv(getUniformLocation(varname), 1, false, mat);
}
//
// ShaderManager methods
//
ShaderManager::ShaderManager(){
activeProgram = 0;
}
ShaderManager::~ShaderManager()
{
unloadAllShaders();
}
void ShaderManager::unloadAllShaders(){
//Unload all shaders
for( ShaderProgramContainer::iterator iter = shaderPrograms.begin(); iter != shaderPrograms.end(); ++iter ){
delete iter->second; //will call corresponding opengl functions
}
shaderPrograms.clear();
for( ShaderContainer::iterator iter = shaders.begin(); iter != shaders.end(); ++iter ){
delete iter->second; //will call corresponding opengl functions
}
shaders.clear();
}
ShaderManager::Shader* ShaderManager::makeShader(const char* shaderName, ShaderType type, const char* sourceFile){
ShaderContainer::iterator shader = shaders.find(shaderName);
if( shader != shaders.end() ) return shader->second;
Shader* newShader = new Shader(type);
if( newShader->load(sourceFile) ){
if( newShader->compile() ){
shaders.insert(ShaderContainer::value_type(shaderName,newShader));
return newShader;
}
}
//It did not load or compile: delete it
delete newShader;
return 0;
}
ShaderManager::ShaderProgram* ShaderManager::createProgram(const char* programName){
ShaderProgram* newProgram = new ShaderProgram();
shaderPrograms.insert(ShaderProgramContainer::value_type(programName, newProgram));
return newProgram;
}
void ShaderManager::attachShader(const char* programName, const char* shaderName){
ShaderProgramContainer::iterator program = shaderPrograms.find(programName);
ShaderContainer::iterator shader = shaders.find(shaderName);
if( program == shaderPrograms.end() ){
Logger::getSingleton() << Logger::WARNING << "attachShader could not find \"" << programName << "\"" << endLog;
}else if( shader == shaders.end() ){
Logger::getSingleton() << Logger::WARNING << "attachShader could not find \"" << shaderName << "\"" << endLog;
}else{
program->second->attachShader(shader->second);
}
}
ShaderManager::ShaderProgram* ShaderManager::makeShaderProgram(const char* programName, const char* vertexShaderFile, const char* fragmentShaderFile){
//Create the shaders with filename as name
Shader* vsShader = makeShader(vertexShaderFile, Vertex, vertexShaderFile);
Shader* fsShader = makeShader(fragmentShaderFile, Fragment, fragmentShaderFile);
if( vsShader == 0 || fsShader == 0 ) return 0;
ShaderProgram* newProgram = new ShaderProgram();
shaderPrograms.insert(ShaderProgramContainer::value_type(programName, newProgram));
newProgram->attachShader(vsShader);
newProgram->attachShader(fsShader);
return newProgram;
}
void ShaderManager::bindAttrib(const char* programName, const char* attribName, GLuint index){
ShaderProgramContainer::iterator program = shaderPrograms.find(programName);
if( program == shaderPrograms.end() ){
Logger::getSingleton() << Logger::WARNING << "bindAttrib could not find \"" << programName << "\"" << endLog;
}else{
program->second->bindAttrib(index, attribName);
}
}
bool ShaderManager::linkProgram(const char* programName){
ShaderProgramContainer::iterator program = shaderPrograms.find(programName);
if( program == shaderPrograms.end() ){
Logger::getSingleton() << Logger::WARNING << "linkProgram could not find \"" << programName << "\"" << endLog;;
return false;
}else{
return program->second->link();
}
}
void ShaderManager::setActiveProgram(const char* programName){
ShaderProgramContainer::iterator program = shaderPrograms.find(programName);
if( program == shaderPrograms.end() ){
Logger::getSingleton() << Logger::WARNING << "setActiveProgram could not find \"" << programName << "\"" << endLog;
}else{
if( program->second->isLinked() ){
if( activeProgram != program->second ){ //Already activated
activeProgram = program->second;
activeProgram->use();
activeProgram->enableAttribs();
}
}
}
}
}
| true |
e516d7b803e98c1edd2a2fd1e8fb94c773b8faa9 | C++ | xingri/dasdas | /robot/CommandServer.ino | UTF-8 | 6,324 | 2.640625 | 3 | [] | no_license | /*********************************************************************************************
* File: CommandServer
* Project: LG Exec Ed Program
* Copyright: Copyright (c) 2014 Anthony J. Lattanze
* Versions:
* 1.0 May 2014.
*
* Description:
*
* This program runs on an Arduio processor with a WIFI shield. This program will act as a
* general server that runs on the Arbot. Commands are send via a client Java program
* (RemoteControl.java). This pair of applications serve to provide remote control of the Arbot
* over WiFi. Note that this application acts as a server, the Java program (RemoteControl.java)
* is the client. Note that fixed IP addresses are not possible for this lab, so you must plug
* the Arbot into your PC to first get the IP address for the client, then you can connect to
* bot and control it. General flow, is that the client connects to the server (tbe Arbot), sends
* a single command and then closes. The reason for this is that the Arduino WIFI shield socket
* will timeout unless you are streaming data to it. The supported commands are forward, backward
* jog right/left (slight turns), and stop. Other commands can easily be added to this and
* client applications can easily be extend.
*
* Compilation and Execution Instructions: Compiled using Arduino IDE 1.0.4
*
* Parameters: None
*
************************************************************************************************/
#include <SPI.h>
#include <WiFi.h>
#define SERIAL_DEBUG 1
#if SERIAL_DEBUG
#define println_serial(fmt,...) Serial.println(fmt,##__VA_ARGS__);
#define print_serial(fmt,...) Serial.print(fmt,##__VA_ARGS__);
#else
#define println_serial(var)
#define print_serial(var)
#endif
#define PORTID 501
struct robot_cmd {
char cmd;
char arg;
};
char ssid[] = "CMU"; // The network SSID (name)
int status = WL_IDLE_STATUS; // The status of the network connections
WiFiServer server(PORTID); // The WIFI status,.. we are using port 500
char inChar; // This is a character sent from the client
IPAddress ip; // The IP address of the shield
IPAddress subnet; // The subnet we are connected to
long rssi; // The WIFI shield signal strength
byte mac[6]; // MAC address of the WIFI shield
boolean done; // Loop flag
boolean commandRead; // Loop flag
#if 0
void go_forward(char);
void go_backward(char);
void turn_left(char);
void turn_right(char);
void stop(char);
void go_station(char);
void near_station(char);
#endif
void go_forward(char step) {
println_serial(__func__);
}
void go_backward(char step) {
println_serial(__func__);
}
void turn_left(char step) {
println_serial(__func__);
}
void turn_right(char step) {
println_serial(__func__);
}
void stop(char dummy) {
println_serial(__func__);
}
void go_station(char station) {
println_serial(__func__);
}
void near_station(char dummy) {
println_serial(__func__);
}
void (*robot_action[])(char)= {
&go_forward,
&go_backward,
&turn_left,
&turn_right,
&go_station,
&near_station,
&stop,
};
byte receive_cmd() {
char command = 0;
WiFiClient client = server.available();
if (client) {
print_serial("Client connected...");
println_serial( "Waiting for a command......" );
while ( client.available() == 0 ) {
delay( 500 );
}
command = client.read();
print_serial( "Command:: " );
println_serial( command, HEX);
/* send acknowledgement */
server.write(command);
client.stop();
println_serial( "Client Disconnected.\n" );
} else {
command = 0xff;
}
return command;
}
struct robot_cmd *process_cmd(char raw_cmd) {
/* On initial state, robot is stopped */
static struct robot_cmd processed_cmd = {
6, /* 6 : stop command */
0, /* don't care of arguement */
};
processed_cmd.cmd = raw_cmd >> 4;
processed_cmd.arg = raw_cmd & 0x0f;
return &processed_cmd;
}
void do_cmd(char cmd, char arg) {
void (*action)(char);
action = robot_action[cmd];
action(arg);
}
void setup() {
#if SERIAL_DEBUG
// Initialize serial port. This is used for debug.
Serial.begin(9600);
#endif
// Attempt to connect to WIfI network indicated by SSID.
while ( status != WL_CONNECTED) {
print_serial("Attempting to connect to SSID: ");
println_serial(ssid);
status = WiFi.begin(ssid);
}
// Print connection information to the debug terminal
printConnectionStatus();
// Start the server and print a message to the terminial.
server.begin();
println_serial("The Command Server is started.");
println_serial("--------------------------------------\n\n");
} // setup
void loop() {
byte raw_cmd = 0;
struct robot_cmd *real_cmd;
raw_cmd = receive_cmd();
/* raw_cmd is 0xff, there is not any rx data *
* refer to real_cmd for actual movement of robot
* real_cmd->cmd
* 0 : go forward
* 1 : go backward
* 2 : turn left
* 3 : turn right
* 4 : go station
* 5 : near station
* 6 : stop
* real_cmd->arg
* if cmd is 'go {forward|backward}'
* # of movement step
* else if cmd is 'turn {left|right}'
* # of jogging step
* else if cmd is 'go station'
* # of station
* else
* no meaning
*/
if (raw_cmd != 0xff) {
real_cmd = process_cmd(raw_cmd);
print_serial("Command :");
println_serial(real_cmd->cmd, HEX);
print_serial("Arg :");
println_serial(real_cmd->arg, HEX);
}
do_cmd(real_cmd->cmd, real_cmd->arg);
} // loop
void printConnectionStatus() {
// Print the basic connection and network information: Network, IP, and Subnet mask
ip = WiFi.localIP();
print_serial("Connected to ");
print_serial(ssid);
print_serial(" IP Address:: ");
println_serial(ip);
subnet = WiFi.subnetMask();
print_serial("Netmask: ");
println_serial(subnet);
// Print our MAC address.
WiFi.macAddress(mac);
print_serial("WiFi Shield MAC address: ");
print_serial(mac[5],HEX);
print_serial(":");
print_serial(mac[4],HEX);
print_serial(":");
print_serial(mac[3],HEX);
print_serial(":");
print_serial(mac[2],HEX);
print_serial(":");
print_serial(mac[1],HEX);
print_serial(":");
println_serial(mac[0],HEX);
// Print the wireless signal strength:
rssi = WiFi.RSSI();
print_serial("Signal strength (RSSI): ");
print_serial(rssi);
println_serial(" dBm");
} // printConnectionStatus
| true |
319f01b884a5b3ccd3d79df1cc1810625a66a011 | C++ | chagdurova/dasha_sasha_ploschad | /ad.cpp | WINDOWS-1251 | 737 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
class square {
int a, b;
public:
square(int l, int w) {a=l; b=w;}
int gets() {
return a*b;
};
int getp() {
return 2*(a+b);};
};
class krug {
double a,r;
public:
krug( double w) {r=w;}
double gets() {
return 3.14*(r*r);
};
double getp() {
return 2*(3.14*r) ;};
};
void main()
{square a(2,12);
setlocale(LC_ALL,"Russian");
cout << " " << a.gets();
cout << " " << a.getp();
krug r(6);
cout << " " << r.gets();
cout << " " << r.getp();
system("pause");
}
| true |
7d3e2da18db745a04d024981e997e0a2a450d9e8 | C++ | lennedy/EncoderPID | /Encoder.cpp | UTF-8 | 998 | 2.875 | 3 | [] | no_license | #include "Encoder.h"
Encoder::Encoder(unsigned int pin1, unsigned int pin2):CONTADOR_PIN(pin1),SENTIDO_PIN(pin2){
numPulsos=0;
}
void Encoder::config(){
pinMode(CONTADOR_PIN,INPUT);
pinMode(SENTIDO_PIN,INPUT);
}
void Encoder::lerPulso(){
//Serial.println("teste");
if(pinEdgeHigh()){
if(digitalRead(SENTIDO_PIN))
numPulsos++;
else
numPulsos--;
}
}
bool Encoder::pinEdgeHigh(){
static int valPin=0;
static int valPinLast=0;
valPin = digitalRead(CONTADOR_PIN);
if(valPin != valPinLast){
if(valPin == HIGH){
valPinLast= valPin;
return true;
}
}
valPinLast= valPin;
return false;
}
float Encoder::calculaVelocidade(){
const long pulsosAtuais = getNumPulsos();
const long tempoAtual = millis();
long deltaS = pulsosAtuais - numPulsosAnterior;
long deltaT = tempoAtual - tempoAnterior;
float velocidade = deltaS/((float)deltaT);
tempoAnterior = tempoAtual;
numPulsosAnterior = pulsosAtuais;
return velocidade;
}
| true |
0c435dcf800b26010819d4103304989671847c4f | C++ | ChemCryst/crystals | /gui/ccchartellipse.cpp | UTF-8 | 891 | 2.78125 | 3 | [] | no_license |
#include "crystalsinterface.h"
#include "crconstants.h"
#include "ccchartellipse.h"
#include "crchart.h"
CcChartEllipse::CcChartEllipse(bool filled)
{
x=0;
y=0;
w=0;
h=0;
fill = filled;
}
CcChartEllipse::CcChartEllipse(bool filled, int ix, int iy, int iw, int ih )
{
x=ix;
y=iy;
w=iw;
h=ih;
fill = filled;
}
CcChartEllipse::~CcChartEllipse()
{
}
bool CcChartEllipse::ParseInput(deque<string> & tokenList)
{
//Just read four integers.
x = atoi( tokenList.front().c_str() );
tokenList.pop_front();
y = atoi( tokenList.front().c_str() );
tokenList.pop_front();
w = atoi( tokenList.front().c_str() );
tokenList.pop_front();
h = atoi( tokenList.front().c_str() );
tokenList.pop_front();
return true;
}
void CcChartEllipse::Draw(CrChart* chartToDrawOn)
{
chartToDrawOn->DrawEllipse(x,y,w,h,fill);
}
| true |
829d9f223295a97791177ff162d437dee0889ee0 | C++ | huynkprovn/monbat | /arduino/sketchbook/_18_interpreting_sensor_values/_18_interpreting_sensor_values.ino | UTF-8 | 1,108 | 2.734375 | 3 | [] | no_license | #include <Time.h>
#include <TimeAlarms.h> // Require the TimeAlarms.ccp file modification
float charge;
float i, iprev;
float v;
void setup()
{
Serial.begin(9600);
setTime(18,15,0,15,12,12);
Alarm.timerRepeat(2,captureData);
charge = 0.0000;
i=0.0000;
iprev=0.0000;
v=0.0000;
}
void captureData()
{
v=voltaje(analogRead(0));
i=temperature(analogRead(1));
charge = calc_ah_drained(iprev, i, charge, 1);
Serial.print(now());
Serial.print(" : Voltaje : ");
Serial.print(v);
Serial.print("Vdc, Corriente : ");
Serial.print(i);
Serial.print("A, Carga : ");
Serial.print(charge);
Serial.println("Ah");
iprev=i;
}
float voltaje(word sensorvalue)
{
return float(((sensorvalue*3.2226/1000)+4.1030)/0.4431);
}
float current(word sensorvalue)
{
return float(((sensorvalue*3.2226/1000)-1.6471)/0.0063);
}
float temperature(word sensorvalue)
{
return float(((sensorvalue*3.2226/1000)-0.5965)/0.0296);
}
float calc_ah_drained(float sa0, float sa1, float ah0, int fs)
{
return (float(fs)/3600)*((sa0+sa1)/2)+ah0;
}
void loop()
{
Alarm.delay(10);
}
| true |
016075b06f687be3eee3431ec2b276c4e576e814 | C++ | AndreicaRadu/Infoarena-and-Codeforces-Problems | /1230A.cpp | UTF-8 | 424 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a , b , c , d;
cin >> a >> b >> c >> d;
int sum = (a + b + c + d);
if(sum%2 == 1)
{
cout << "NO";
return 0;
}
sum = sum/2;
if(a == sum || b == sum || c == sum || d == sum || a+b == sum || a+c == sum || a+d == sum || b+c == sum || b+d == sum || c+d == sum)
cout << "YES";
else cout << "NO";
return 0;
}
| true |
27405d7fea4d4474ff6a6153ed5f87655243d958 | C++ | imace/rtcube | /server/server.cpp | UTF-8 | 1,061 | 2.734375 | 3 | [] | no_license | #include "../proto/proto.h"
#include "../util/HostPort.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " ip:port" << std::endl;
return 1;
}
auto dest = HostPort{argv[1]};
::sockaddr_in6 sin6;
::memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
::memcpy(&sin6.sin6_addr, dest.ip, 16);
sin6.sin6_port = dest.port;
auto s = socket(PF_INET6, SOCK_DGRAM, 0);
if (s < 0)
{
perror("Opening socket.");
return 1;
}
if (bind(s, (::sockaddr*) &sin6, sizeof(sin6)) < 0)
{
perror("Binding socket.");
return 1;
}
for (;;)
{
char buffer[2048];
socklen_t addr_len;
auto len = recvfrom(s, buffer, 2048, 0, (::sockaddr*) &sin6, &addr_len);
if (len <= 0)
{
perror("Receiving packet.");
return 1;
}
auto msg = string{buffer, string::size_type(len)};
auto V = proto::unserialize(msg);
for (auto v : V)
std::cout << v.data << " ";
std::cout << std::endl;
if (V.size() == 1 && V[0] == "DIE")
break;
}
return 0;
}
| true |
9002187e409f9c99f63ab6446d252e5c86a9c1b8 | C++ | smmahdad/Personal-Projects | /BioSeq/BioSeq/Chromosome.h | UTF-8 | 564 | 2.671875 | 3 | [] | no_license | #ifndef CHROMOSOME_H_
#define CHROMOSOME_H_
#include "DNA.h"
class Chromosome
{
public:
Chromosome();
Chromosome(DNA dna);
Chromosome(string str);
void addDNA(const DNA & dna);
void setDNA(string str);
DNA getDNAObj() const;
string getDNAStr() const;
void printChrom() const;
bool haveDis(const string disName);
void findDis(const string name, const string patt);
private:
list<DNA> strands;
string entireDNA;
list<string> diseases;
};
bool findDisHelper(const string patt, const string dna, int *line_number);
#endif | true |
ddbb64bd376de349eacad5fe1d6bdb449f20441d | C++ | bernardobreder/cgp | /demo4/compiler/cgToken.cpp | UTF-8 | 505 | 3 | 3 | [] | no_license | #include "cgUtil.h"
#include "cgToken.h"
cgToken::cgToken(unsigned char type, const char* word, size_t length, cgToken* next) {
_word = cgUtilCharsDup(word);
_length = length;
_type = type;
_next = next;
}
cgToken::~cgToken()
{
if (_word) delete _word;
if (_next) delete _next;
}
unsigned char cgToken::type() {
return _type;
}
const char* cgToken::word() {
return _word;
}
long cgToken::length() {
return _length;
}
bool cgToken::eof() {
return _type == 0;
} | true |
17a3ae7929a6bea6f2f62a70811df1c0efec3f64 | C++ | amartin11/robot-code-public | /muan/wpilib/motor_safety_test.cpp | UTF-8 | 3,608 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "muan/wpilib/motor_safety.h"
#include <math.h>
#include <limits>
#include "gtest/gtest.h"
TEST(MotorSafetyTest, NeverOverCurrentThresh) {
muan::wpilib::MotorSafety safety =
muan::wpilib::MotorSafety(100., 2., 2., 0.005);
for (double t = 0.005; t < 10; t += 0.005) {
double current = 30;
double voltage = 10;
double safe_voltage = safety.Update(voltage, current);
EXPECT_NEAR(voltage, safe_voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
}
}
TEST(MotorSafetyTest, GoesOverCurrentThresh) {
muan::wpilib::MotorSafety safety =
muan::wpilib::MotorSafety(100., 3., 2., 0.005);
for (double t = 0.005; t < 10.0; t += 0.005) {
double current = 200;
double voltage = 10;
double safe_voltage = safety.Update(voltage, current);
if (t < 3.0) {
EXPECT_NEAR(safe_voltage, voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
} else {
EXPECT_NEAR(safe_voltage, 0, 1e-5);
EXPECT_TRUE(safety.is_stalled());
}
}
}
TEST(MotorSafetyTest, TooShortStall) {
muan::wpilib::MotorSafety safety =
muan::wpilib::MotorSafety(100., 2., 2., 0.005);
for (double t = 0.005; t < 10; t += 0.005) {
double current = 120 * sin(t);
double voltage = 10;
double safe_voltage = safety.Update(voltage, current);
EXPECT_NEAR(voltage, safe_voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
}
}
TEST(MotorSafetyTest, CurrentSpikeThenDrop) {
muan::wpilib::MotorSafety safety =
muan::wpilib::MotorSafety(100., 3., 2., 0.005);
for (double t = 0.005; t < 10.0; t += 0.005) {
double current = t < 4 ? 200 : 90;
double voltage = 10;
double safe_voltage = safety.Update(voltage, current);
if (t < 3.0) {
EXPECT_NEAR(safe_voltage, voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
} else if (t < 6.090) { // Slightly more than 6 seconds to account for the
// moving average filter getting
// track of the sudden current change.
EXPECT_NEAR(safe_voltage, 0, 1e-5);
EXPECT_TRUE(safety.is_stalled());
} else {
EXPECT_NEAR(safe_voltage, voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
}
}
}
TEST(MotorSafetyTest, InfiniteReset) {
muan::wpilib::MotorSafety safety = muan::wpilib::MotorSafety(
100., 2., std::numeric_limits<int>::max(), 0.01);
for (double t = 0.01; t < 100; t += 0.01) {
double current = t < 4 ? 200 : 90;
double voltage = 10;
double safe_voltage = safety.Update(voltage, current);
if (t < 2.0) {
EXPECT_NEAR(safe_voltage, voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
} else {
EXPECT_NEAR(safe_voltage, 0, 1e-5);
EXPECT_TRUE(safety.is_stalled());
}
}
}
TEST(MotorSafetyTest, SlowStall) {
muan::wpilib::MotorSafety safety =
muan::wpilib::MotorSafety(100., 1., 1., 0.005);
for (double t = 0.005; t < 9; t += 0.005) {
// Makes the current fluctuate back above the threshold before it is done
// resetting
double current = t < 4 ? 200 : t < 4.5 ? 20 : t < 6 ? 200 : 20;
double voltage = 10;
double safe_voltage = safety.Update(voltage, current);
if (t < 1.0) {
EXPECT_NEAR(safe_voltage, voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
} else if (t < 7.050) { // A little more to allow the moving average to
// catch up on current
EXPECT_NEAR(safe_voltage, 0, 1e-5);
EXPECT_TRUE(safety.is_stalled());
} else {
EXPECT_NEAR(safe_voltage, voltage, 1e-5);
EXPECT_FALSE(safety.is_stalled());
}
}
}
| true |
a803da559e05bb7b6376f5ba34353a59225bc8bd | C++ | jehutymax/nikita-render | /main.cpp | UTF-8 | 855 | 2.515625 | 3 | [] | no_license | #include "core/nikita.h"
#include "util/sceneParser.h"
#include "core/renderer/renderer.h"
#include "version.h"
int main(int argc, char* argv[]) {
std::cout << "Nikita Renderer" << std::endl;
std::cout << "Version " << nikita::version << std::endl;
if (argc != 2)
{
std::cout <<
"Usage: " << argv[0] << " [filename]\n" <<
"Which: runs Nikita Render on the specified scene(s).\n" <<
"Mandatory parameters:\n" <<
" [filename] XML file containing the scene information.\n" << std::endl;
return 0;
}
nikita::sceneParser parser;
parser.loadFile(std::string(argv[1]));
nikita::ScenePtr scene = parser.getScene();
nikita::RendererPtr ssr = std::make_shared<nikita::SuperSamplerRenderer>(parser.getCamera());
ssr->render(scene);
return 0;
} | true |
bb43b532f2561b53283f032fd286e414555a0c06 | C++ | diedino/Algorithms | /Algorithms/KDZ/src/Dinic/Dinic.h | UTF-8 | 724 | 2.546875 | 3 | [] | no_license | //
// Created by krasn on 09.04.2019.
//
#ifndef MODULEHOMETASK_DINIC_H
#define MODULEHOMETASK_DINIC_H
#include <vector>
using namespace std;
struct Edge
{
int v ;
int flow ;
int C;
int rev ;
};
class Dinic
{
private:
int V; // вершины
int *level ; // уровень в ноде
vector<Edge> *adj;
vector<std::pair<int, int>> allPairs;
public:
Dinic(vector<vector<int>> matrix, int V, vector<std::pair<int, int>> pairs);
void runAlgorithm();
void readFromMatrix(vector<vector<int>> matrix);
void addEdge(int u, int v, int C);
bool BFS(int s, int t);
int dfs(int s, int flow, int t, int ptr[]);
int dinicMaxflow(int s, int t);
};
#endif //KDZ_DINIC_H
| true |
c67701b57f76ec41c454818046516382a86f2cd7 | C++ | procrastinationfighter/sik-http-server | /HttpRequest.cpp | UTF-8 | 5,165 | 2.796875 | 3 | [] | no_license | #include "HttpRequest.h"
#include "exceptions.h"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
namespace {
enum class Header {
CONNECTION,
CONTENT_LENGTH,
OTHER
};
std::regex &get_request_line_regex() {
static std::regex regex(R"(([a-zA-Z]+) (\/[^ ]*) )"
+ get_http_version_regex_str()
+ get_CRLF());
return regex;
}
bool is_target_file_correct(const std::string &target_file) {
static std::regex regex(R"([a-zA-Z0-9.\-\/]+)");
return std::regex_match(target_file, regex);
}
void make_string_lower(std::string &str) {
for (auto &c : str) {
c = static_cast<char>(tolower(c));
}
}
Header string_to_header(std::string &str) {
static const std::string serv = "server",
conn = "connection",
con_type = "content-type",
con_len = "content-length";
make_string_lower(str);
if (str == conn) {
return Header::CONNECTION;
} else if (str == con_len) {
return Header::CONTENT_LENGTH;
} else {
return Header::OTHER;
}
}
std::regex &get_header_regex() {
static std::regex regex(R"(([a-zA-Z0-9\-_]+):\s*([\ -~]*[!-~])\s*)"
+ get_CRLF());
return regex;
}
// Assumes that correct method is uppercase.
HttpRequest::Method string_to_method(const std::string &str) {
const static std::string get = "GET";
const static std::string head = "HEAD";
if (str == get) {
return HttpRequest::Method::GET;
} else if (str == head) {
return HttpRequest::Method::HEAD;
} else {
throw UnsupportedHttpMethod(str);
}
}
std::string read_line(FILE *file) {
char *line = nullptr;
size_t len = 0;
ssize_t read_res = getline(&line, &len, file);
if (read_res == EOF) {
throw ConnectionLost("EOF");
} else if (line == nullptr) {
throw ServerInternalError("getline");
} else {
std::string line_str(line, read_res);
free(line);
return line_str;
}
}
std::pair<HttpRequest::Method, std::string> parse_request_line(FILE *input_file) {
std::smatch match;
std::string line = read_line(input_file);
std::regex_match(line, match, get_request_line_regex());
if (match.empty()) {
throw IncorrectRequestFormat("request_line");
}
return {string_to_method(match[1]), match[2]};
}
// Returns true if Connection: Close header was included.
bool parse_headers(FILE *input_file) {
static const std::string CONNECTION_CLOSE = "close",
ZERO_VALUE_FIELD = "0";
bool finish = false,
close_connection = false,
was_connection = false,
was_content_length = false;
std::smatch match;
while(!finish) {
std::string line = read_line(input_file);
if (line == get_CRLF()) {
finish = true;
} else {
std::regex_match(line, match, get_header_regex());
if (match.empty()) {
throw IncorrectRequestFormat("header");
}
std::string field_name = match[1];
std::string field_value = match[2];
Header header_type = string_to_header(field_name);
switch (header_type) {
case Header::CONNECTION:
if (was_connection) {
throw IncorrectRequestFormat("double connection header");
} else {
was_connection = true;
make_string_lower(field_value);
if (field_value == CONNECTION_CLOSE) {
close_connection = true;
}
}
break;
case Header::CONTENT_LENGTH:
if (was_content_length) {
throw IncorrectRequestFormat("double content_length header");
} else {
was_content_length = true;
make_string_lower(field_value);
if(field_value != ZERO_VALUE_FIELD) {
throw IncorrectRequestFormat("content_length wrong value");
}
}
break;
case Header::OTHER:
// We ignore other headers.
break;
}
}
}
return close_connection;
}
}
HttpRequest::Method HttpRequest::get_method() const {
return method;
}
const std::string &HttpRequest::get_request_target() const {
return request_target;
}
bool HttpRequest::should_close_connection() const {
return close_connection;
}
HttpRequest parse_http_request(FILE *input_file) {
auto start_result = parse_request_line(input_file);
bool close_connection = parse_headers(input_file);
if (!is_target_file_correct(start_result.second)) {
throw TargetFileIncorrectCharacters(close_connection);
}
return HttpRequest(start_result.first, start_result.second, close_connection);
} | true |
4c36bc47f027dafcc55cdf7eb3c3c0037afd9ed3 | C++ | SemperParatusGithub/SemperEngine | /SemperEngine/Source/SemperEngine/Graphics/Backend/API/VertexBuffer.h | UTF-8 | 828 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "VertexBufferElement.h"
#include "SemperEngine/Core/Assert.h"
namespace SemperEngine
{
enum class VertexFormat
{
Float1,
Float2,
Float3,
Float4
};
enum class BufferUsage
{
Static,
Dynamic,
Stream
};
class VertexBuffer
{
public:
virtual ~VertexBuffer() = default;
static SharedPtr<VertexBuffer> Create(BufferUsage usage);
static SharedPtr<VertexBuffer> Create(const void *vertices, U32 size, BufferUsage usage);
virtual void SetData(const void *vertices, U32 size) = 0;
virtual void AddAttribute(const VertexAttribute &element) = 0;
virtual const std::vector<VertexAttribute> &GetElements() const = 0;
virtual U32 GetStride() const = 0;
virtual void Bind() const noexcept = 0;
virtual void UnBind() const noexcept = 0;
friend class VertexAttribute;
};
} | true |
b80237ac56a7fb62664d0d2668d40871bd8344fe | C++ | Ran-t/Euler | /C++/14/solution.cpp | UTF-8 | 1,104 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
using namespace std;
void compute_chain_length(const int&);
unordered_map<int, int> precomputed_chains;
int main()
{
int highest_length = 0;
int hl_key = 0; // highest-length key.
//generate an unordered_map of <starting number, collatz sequence length> pairs
for(int i = 2; i < 1000000; ++i)
compute_chain_length(i);
//find the highest value in the unordered_map.
for(auto it : precomputed_chains)
if(it.second > highest_length){
highest_length = it.second;
hl_key = it.first;
}
cout << hl_key << endl;
return 0;
}
void compute_chain_length(const int& head){
unsigned int n = head;
unsigned int length = 0;
while(n != 1){
if(precomputed_chains.count(n) > 0){
length += precomputed_chains[n];
n = 1;
}else if(n % 2 == 0){
n /= 2;
++length;
}else{
n = n*3+1;
++length;
}
}
precomputed_chains.insert(pair<int, int>(head, length));
}
| true |
aaf4c71e6cf14ed6e017006f226a6b5d230a384a | C++ | Ysoretarted/LeetCode | /Leetcode/C++/169求众数.cpp | GB18030 | 541 | 2.921875 | 3 | [] | no_license | class Solution {
public:
int majorityElement(vector<int>& nums) {
int len = nums.size();
int ans = nums[0];
int cnt = 1;
for(int i = 1; i < len; i++){
if(cnt == 0){
ans = nums[i];
cnt++;
continue;
}
if(ans == nums[i]){
cnt++;
}
else{
cnt--;
}
}
return ans;
}
};
/**
1.α
2.ӼӼIJ
*/ | true |
90636a9cc0821dff770eae0268df12d9d9ee6bbe | C++ | ashukla2003167/c-codes | /Reverse LL(Recursive Better in O(n)).cpp | UTF-8 | 1,722 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int d){
data = d;
next = NULL;
}
};
class Pair{
public:
Node * head;
Node * tail;
};
Node *takeinput(){
int data;
cin>>data;
Node *head = NULL;
Node *tail = NULL;
while(data != -1){
Node *newnode = new Node(data);
if(head ==NULL){
head = newnode;
tail = newnode;
}
else{
tail->next = newnode;
tail=tail->next;
}
cin>>data;
}
return head;
}
Node * midPoint(Node * head){
Node *slow = head;
Node *fast = head->next;
while(fast!=NULL && fast->next!=NULL){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
void print(Node *head){
Node*temp = head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
Node *reverseLL(Node *head){
if(head == NULL || head->next == NULL)
return head;
Node * h1 = reverseLL(head->next);
Node * temp = h1;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = head;
head->next = NULL;
return h1;
}
Pair reverseLL_2(Node *head){
if(head == NULL || head->next == NULL)
{
Pair ans;
ans.head = head;
ans.tail = head;
return ans;
}
Pair smallOutput = reverseLL_2(head->next);
smallOutput.tail->next = head;
head->next = NULL;
Pair ans;
ans.head = smallOutput.head;
ans.tail = head;
return ans;
}
int main(){
Node *head = takeinput();
Pair ans = reverseLL_2(head);
print(ans.head);
} | true |
72a943f26c371641044b268002ba4d8e13305b41 | C++ | NSDie/algorithm-design | /剑指offer(c++)/连续子数组的最大和.cpp | UTF-8 | 399 | 2.96875 | 3 | [] | no_license | class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
int count=0;
int Max=-9999999;
for(int i = 0 ;i<array.size();i++){
if(count<=0){
count=array[i];
}
else{
count+=array[i];
}
if(Max<count)
Max=count;
}
return Max;
}
}; | true |
201a9e143a5eaaaa2398c18d5d4a8d5c2d91f293 | C++ | shaunno94/MCompTeamProject_2016 | /Codebase/Rendering/AudioComponent.cpp | UTF-8 | 2,935 | 2.78125 | 3 | [] | no_license | #include "AudioComponent.h"
#include "GameObject.h"
// Base Audio
void AudioComponent::SetObject(GameObject* obj)
{
m_Object = obj;
}
void AudioComponent::AddEmitters()
{
for (auto emt : m_AudioList) {
SoundSystem::Instance()->AddSoundEmitter(emt);
}
}
void AudioComponent::SetPositions()
{
Vec3 pos = m_Object->GetWorldTransform().GetTranslation();
for (auto emt : m_AudioList) {
emt->SetPosition(pos);
}
}
Vec3 AudioComponent::GetVec3Velocity()
{
btVector3 vel = m_Object->GetPhysicsComponent()->GetPhysicsBody()->getInterpolationLinearVelocity();
Vec3 velProper = Vec3();
velProper.x = vel.x();
velProper.y = vel.y();
velProper.z = vel.z();
return velProper;
}
void AudioComponent::SetVelocities()
{
Vec3 vel = GetVec3Velocity();
for (auto emt : m_AudioList) {
emt->SetVelocity(vel);
}
}
void AudioComponent::SetRadius(float rad)
{
for (auto emt : m_AudioList) {
emt->SetRadius(rad);
}
}
// Car Audio
#define MAX_REV_VOL 0.3f
#define MIN_REV_VOL 0.1f
#define MAX_REV_PIT 1.4f
#define MIN_REV_PIT 0.1f
#define MAX_IDLE_VOL 0.15f
#define MIN_IDLE_VOL 0.0f
#define REV_SPEED_VOL 50.0f // degree of interpolation
#define REV_SPEED_PIT 120.0f
#define IDLE_SPEED_VOL 15.0f // lower = faster cut off
enum SoundHolder {
IDLE,
REV,
FAST
};
AudioCompCar::AudioCompCar(bool global) : AudioComponent()
{
// idle noise
SoundEmitter* emt = new SoundEmitter(SoundManager::GetSound(ENGINE_IDLE));
emt->SetIsGlobal(global);
m_AudioList.push_back(emt);
// engine noise
emt = new SoundEmitter(SoundManager::GetSound(ENGINE_REV));
emt->SetIsGlobal(global);
m_AudioList.push_back(emt);
// boost noise
emt = new SoundEmitter(SoundManager::GetSound(BOOST));
emt->SetIsGlobal(global);
emt->SetPitch(0.85f);
m_AudioList.push_back(emt);
m_Pitch = MIN_REV_PIT;
m_BoostVol = 0.0f;
AddEmitters();
SetRadius(300.0f);
}
void AudioCompCar::Update()
{
SetPositions();
SetVelocities();
// Handle volume
Vec3 vel = GetVec3Velocity();
float speed = vel.Length();
float revVol = fmin(MAX_REV_VOL, (speed / REV_SPEED_VOL)); // max vol
revVol = fmax(revVol, MIN_REV_VOL); // min vol
float idleVol = fmin(MAX_IDLE_VOL, (1 - (speed / IDLE_SPEED_VOL)) );
idleVol = fmax(idleVol, MIN_IDLE_VOL);
m_AudioList[REV]->SetVolume(revVol);
m_AudioList[IDLE]->SetVolume(idleVol);
// Handle pitch
float speedNorm = fmax(MIN_REV_PIT, (speed / REV_SPEED_PIT)); // min pitch
speedNorm = fmin(speedNorm, MAX_REV_PIT); // max pitch
// gear shift
m_Pitch += m_Pitch <= speedNorm ? 0.015f : -0.03f;
m_Pitch = fmin(MAX_REV_PIT, m_Pitch);
m_Pitch = fmax(MIN_REV_PIT, m_Pitch);
m_AudioList[REV]->SetPitch(m_Pitch);
m_AudioList[FAST]->SetVolume(m_BoostVol);
}
// Car Audio listener
void AudioCompCarLitener::Update()
{
SoundSystem::Instance()->SetListenerMatrix(m_Object->GetWorldTransform());
SoundSystem::Instance()->SetListenerVelocity(GetVec3Velocity());
AudioCompCar::Update();
}
| true |
142f9109acd045cfcd840e1c2943373c57a22888 | C++ | indianakernick/The-Machine | /The Machine/Game/level controller.cpp | UTF-8 | 1,636 | 2.953125 | 3 | [] | no_license | //
// level controller.cpp
// The Machine
//
// Created by Indi Kernick on 17/1/18.
// Copyright © 2018 Indi Kernick. All rights reserved.
//
#include "level controller.hpp"
#include <SDL2/SDL_events.h>
#include <Simpleton/SDL/events.hpp>
std::optional<ECS::Level> LevelController::getLevel(
const SDL_Event &e,
const ECS::Level current,
const ECS::Level progress
) {
// reload
if (SDL::keyDown(e, SDL_SCANCODE_R) && current != ECS::NULL_LEVEL) {
return current;
}
// next level
if (SDL::keyDown(e, SDL_SCANCODE_N)) {
if (current == ECS::NULL_LEVEL) {
return progress;
} else /* if (current + 1 <= progress) */ {
return current + 1;
}
}
// previous level
if (SDL::keyDown(e, SDL_SCANCODE_B)) {
if (current == ECS::NULL_LEVEL) {
return 0;
} else if (current != 0) {
return current - 1;
}
}
// start typing level
if (SDL::keyDown(e, SDL_SCANCODE_L)) {
choosingLevel = true;
}
// end typing level
if (SDL::keyUp(e, SDL_SCANCODE_L)) {
choosingLevel = false;
if (!enteredLevel.empty()) {
const ECS::Level level = enteredLevel.get();
enteredLevel.clear();
if (level < progress) {
return level;
}
}
}
// type level number
if (SDL::keyDown(e) && choosingLevel) {
const SDL_Scancode code = SDL::keyCode(e.key);
//Why did they put SDL_SCANCODE_0 after SDL_SCANCODE_9?
if (SDL_SCANCODE_1 <= code && code <= SDL_SCANCODE_9) {
enteredLevel.push(code - SDL_SCANCODE_1 + 1);
} else if (code == SDL_SCANCODE_0) {
enteredLevel.push(0);
}
}
return std::nullopt;
}
| true |
fb9f5f95e77186ed0ad61f4de753aac1a64bb3b8 | C++ | ehdgus8077/algorithm | /Algolab/숫자읽기.cpp | UTF-8 | 3,059 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
void num_one(string& result,int num){
switch(num){
case 1:
result.append("One_");
break;
case 2:
result.append("Two_");
break;
case 3:
result.append("Three_");
break;
case 4:
result.append("Four_");
break;
case 5:
result.append("Five_");
break;
case 6:
result.append("Six_");
break;
case 7:
result.append("Seven_");
break;
case 8:
result.append("Eight_");
break;
case 9:
result.append("Nine_");
break;
}
}
void num_to_string(string& result,int num){
if(num/100){
num_one(result,num/100);
result.append("Hundred_");
num%=100;
}
if(num/10==1){
switch(num){
case 10:
result.append("Ten_");
break;
case 11:
result.append("Eleven_");
break;
case 12:
result.append("Twelve_");
break;
case 13:
result.append("Thirteen_");
break;
case 14:
result.append("Fourteen_");
break;
case 15:
result.append("Fifteen_");
break;
case 16:
result.append("Sixteen_");
break;
case 17:
result.append("Seventeen_");
break;
case 18:
result.append("Eighteen_");
break;
case 19:
result.append("Nineteen_");
break;
}
}
else if(num/10>1){
switch(num/10){
case 2:
result.append("Twenty_");
break;
case 3:
result.append("Thirty_");
break;
case 4:
result.append("Forty_");
break;
case 5:
result.append("Fifty_");
break;
case 6:
result.append("Sixty_");
break;
case 7:
result.append("Seventy_");
break;
case 8:
result.append("Eighty_");
break;
case 9:
result.append("Ninety_");
break;
}
num_one(result,num%10);
}
else
num_one(result,num);
}
int main()
{
ifstream inStream;
int numTestCases,num;
inStream.open("input.txt");
inStream >> numTestCases;
for (int i = 0; i < numTestCases; i++)
{ string result;
inStream >> num;
if(num/1000000000){
num_to_string(result,num/1000000000);
num%=1000000000;
result.append("Billion_");
}
if(num/1000000){
num_to_string(result,num/1000000);
num%=1000000;
result.append("Million_");
}
if(num/1000){
num_to_string(result,num/1000);
num%=1000;
result.append("Thousand_");
}
num_to_string(result,num);
result.erase(result.size()-1,1);
cout<<result<<endl;
}
inStream.close();
return 0;
}
| true |
71038b79ecdead165abc681b489a273e007edc7d | C++ | 13isak37/cpp | /2018-02-07/�vning8.7.cpp | UTF-8 | 317 | 2.625 | 3 | [] | no_license |
#include <iostream>
using namespace std;
int main()
{
setlocale( LC_ALL, "");
int folk = 1000000;
int ar;
while( folk < 2000000 )
{
folk = folk * 1.05;
ar++;
}
cout << "Det tar " << ar << " år innan folkmängden är två miljoner" << endl;
return 0;
} | true |
20da300c80ebd1898cec90cc516e8dbaa39634e5 | C++ | merkys/libvoronota-perl | /src/externals/voronota/src/modescommon/ball_value.h | UTF-8 | 616 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef BALL_VALUE_H_
#define BALL_VALUE_H_
#include "properties_value.h"
namespace
{
struct BallValue
{
double x;
double y;
double z;
double r;
PropertiesValue props;
BallValue() : x(0.0), y(0.0), z(0.0), r(0.0)
{
}
};
inline std::ostream& operator<<(std::ostream& output, const BallValue& value)
{
output << value.x << " " << value.y << " " << value.z << " " << value.r << " " << value.props;
return output;
}
inline std::istream& operator>>(std::istream& input, BallValue& value)
{
input >> value.x >> value.y >> value.z >> value.r >> value.props;
return input;
}
}
#endif /* BALL_VALUE_H_ */
| true |
0076517cb9e57eaece50addcb1b187fbe78c6cfa | C++ | ahmadradmehr/Assorted-CPP-Problems | /LRUCache.cpp | UTF-8 | 2,063 | 3.921875 | 4 | [] | no_license | /* LRU Cache
*
* Design and implement a data structure for Least Recently Used (LRU) cache.
* It should support the following operations: get and put.
*
* get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
* put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
*
* The cache is initialized with a positive capacity.
*
* Follow up:
* Could you do both operations in O(1) time complexity?
*
* Example:
* LRUCache cache = new LRUCache( 2 );
*
* cache.put(1, 1);
* cache.put(2, 2);
* cache.get(1); // returns 1
* cache.put(3, 3); // evicts key 2
* cache.get(2); // returns -1 (not found)
* cache.put(4, 4); // evicts key 1
* cache.get(1); // returns -1 (not found)
* cache.get(3); // returns 3
* cache.get(4); // returns 4
*/
class LRUCache {
int size;
list<int> lru;
unordered_map<int, list<int>::iterator> mi;
unordered_map<int, int> kv;
public:
LRUCache(int capacity) : size {capacity} {
}
int get(int key) {
if (kv.count(key) == 0)
return -1;
updateLRU(key);
return kv[key];
}
void put(int key, int value) {
if (kv.count(key) == 0) {
if (lru.size() == size)
invalidate();
lru.insert(lru.begin(), key);
} else {
updateLRU(key);
}
mi[key] = lru.begin();
kv[key] = value;
}
void updateLRU(int key) {
lru.erase(mi[key]);
lru.insert(lru.begin(), key);
mi[key] = lru.begin();
}
void invalidate() {
mi.erase(lru.back());
kv.erase(lru.back());
lru.pop_back();
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/ | true |
e05db1380fcb4983decf959356900ec4cfe2b949 | C++ | Aditya2150/SDE-Questions | /Day 9 (Recursion)/combination_sum_2.cpp | UTF-8 | 1,113 | 3.296875 | 3 | [] | no_license | // Given a collection of candidate numbers (candidates) and a target number (target),
// find all unique combinations in candidates where the candidate numbers sum to target.
// Each number in candidates may only be used once in the combination.
// Note: The solution set must not contain duplicate combinations.
class Solution {
public:
void solve(int index,vector<int>& candidates, int target,vector<int>v,vector<vector<int>>& ans)
{
if(target==0)
{
ans.push_back(v);
return;
}
if(target<0)
return;
for(int i=index;i<candidates.size();i++)
{
if(i!=index && candidates[i]==candidates[i-1])continue;
v.push_back(candidates[i]);
solve(i+1,candidates,target-candidates[i],v,ans);
v.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>>ans;
vector<int>v;
sort(candidates.begin(),candidates.end());
solve(0,candidates,target,v,ans);
return ans;
}
}; | true |
8ec36f528702d48bb6ca1689cd86240ff3e7be59 | C++ | Glenn-S/Virtual-Orrery | /Scene.h | UTF-8 | 1,156 | 2.875 | 3 | [] | no_license | /*
* Scene.h
* Class for storing objects in a scene
* Created on: Sep 10, 2018
* Author: cb-ha
* Modified by: Glenn Skelton
*/
#ifndef SCENE_H_
#define SCENE_H_
#include <vector>
#include "Geometry.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "glm/gtx/string_cast.hpp"
//Forward declaration of classes
//(note this is necessary because these are pointers and it allows the #include to appear in the .cpp file)
class RenderingEngine;
class Camera;
class Scene {
public:
Scene(RenderingEngine* renderer, vector<Geometry>* sceneGraph, Camera *cam);
virtual ~Scene();
//Send geometry to the renderer
void displayScene();
void generateScene();
void traverseGraph(Geometry *obj, glm::mat4x4 parentTranslation, double time);
std::vector<Geometry> *sceneGraph = NULL; // for storing the objects of my scene
Camera *cam = NULL;
double time = 0.0f; // for rotational matrices
bool initiallized = false;
private:
RenderingEngine* renderer;
//list of objects in the scene
std::vector<Geometry> objects;
};
#endif /* SCENE_H_ */
| true |
aa2baa547cd97660482f5000af76d5a22ee24e47 | C++ | anshumanvarshney/CODE | /Level2/printpath.cpp | UTF-8 | 763 | 3.4375 | 3 | [] | no_license | /*
Example:
Input:
2
2
1 2 R 1 3 L
4
10 20 L 10 30 R 20 40 L 20 60 R
Output:
1 3 #1 2 #
10 20 40 #10 20 60 #10 30 #
*/
/* Structure of Node
struct Node
{
int data;
Node* left;
Node* right;
};*/
void print(int a[],int n)
{
int i;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"#";
}
void printpathutil(Node *root,int a[],int i)
{
if(root==NULL)
return;
a[i]=root->data;
i++;
if(root->left==NULL && root->right==NULL)
print(a,i);
else
{
printpathutil(root->left,a,i);
printpathutil(root->right,a,i);
}
}
void printPaths(Node* root)
{
int a[1000];
printpathutil(root,a,0);//pass by value
cout<<endl;
} | true |
f47bac5e5a6543d34ff3ef319eb39b9675678f88 | C++ | WalkOnxc/DataStructure | /LinkList/LinkList/LinkList.hpp | GB18030 | 6,394 | 3.609375 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<iostream>
using namespace std;
template<class T>
class LinkList;
//ڵ
template<class T>
class LinkNode
{
friend class LinkList<T>;
public:
LinkNode()
{
this->next = NULL;
}
~LinkNode()
{
}
private:
T data;
LinkNode<T>* next;
};
template<class T>
class LinkList
{
private:
//ͷ
LinkNode<T>* head;
public:
LinkList(); //캯
bool ListEmpty(); //жǷΪ
void ShowList(); //ӡ
int GetSize(); //ȡ
void GetElem(int index, T &e); //ȡindexλõĽڵԪأͨe
void PushBack(const T &e); //β
void PushFront(const T &e); //ͷ
void PopBack(); //βɾ
void PopFront(); //ͷɾ
void InsertPos(const int index, const T &e); //indexλòe
void DeletePos(const int index); //ɾindexλõĽڵ
LinkNode<T>* FindElem(const T &e); //ֵңҵظýڵĵַҲNULL
int FindLocateElem(const T &e); //ֵңҵظýڵλţҲ0
void ClearList(); //
void DestroyList(); //
~LinkList();
};
//LinkList(); //캯
template<class T>
LinkList<T>::LinkList()
{
this->head = new LinkNode<T>;//ͷڴ,ٽڵ㹹캯ѽͷָָNULL
}
//bool ListEmpty(); //жǷΪ
template<class T>
bool LinkList<T>::ListEmpty()
{
if (this->head->next == NULL)
{
return true;
}
else
{
return false;
}
}
//void ShowList(); //ӡ
template<class T>
void LinkList<T>::ShowList()
{
if (this->ListEmpty())
{
cout << "Ϊ" << endl;
return;
}
LinkNode<T>* p = this->head;
while (p = p->next)
{
cout << p->data << endl;
}
}
// int GetSize(); //ȡ
template<class T>
int LinkList<T>::GetSize()
{
int count = 0;
LinkNode<T>* p = this->head;
while (p = p->next)
{
count++;
}
return count;
}
// void GetElem(int index, T &e); //ȡindexλõĽڵԪأͨe
template<class T>
void LinkList<T>::GetElem(int index, T &e)
{
if (this->ListEmpty())
{
cout << "ȡʧܣΪ" << endl;
return;
}
//жindexλõЧ
if (index < 1 || index > this->GetSize())
{
cout << "λϢ" << endl;
return;
}
int pos = index;
LinkNode<T>* p = this->head;
while (pos--)
{
p = p->next;
}
e = p->data;
cout << "ҵ" << index << "ԪΪ" << e << endl;
}
// void PushBack(const T &e); //β
template<class T>
void LinkList<T>::PushBack(const T &e)
{
//ҵһڵ
LinkNode<T>* p = this->head;
while (p->next != NULL)
{
p = p->next;
}
//½ڵ㣬½ڵβ
LinkNode<T>* pNew = new LinkNode<T>;
pNew->data = e;
pNew->next = NULL;
p->next = pNew;
}
//void PushFront(const T &e); //ͷ
template<class T>
void LinkList<T>::PushFront(const T &e)
{
LinkNode<T>* pNew = new LinkNode<T>;
pNew->data = e;
pNew->next = this->head->next;
this->head->next = pNew;
}
//void PopBack(); //βɾ
template<class T>
void LinkList<T>::PopBack()
{
if (this->ListEmpty())
{
cout << "ɾʧܣΪ" << endl;
return;
}
LinkNode<T>* p = this->head;
//ҵڶڵ
while (p->next->next)
{
p = p->next;
}
//ͷһڵ
LinkNode<T>* pLast = p->next;
delete pLast;
pLast = NULL;
//delete p->next;
//ڶڵָΪ
p->next = NULL;
}
//void PopFront(); //ͷɾ
template<class T>
void LinkList<T>::PopFront()
{
if (this->ListEmpty())
{
cout << "ɾʧܣΪ" << endl;
return;
}
LinkNode<T>* p = this->head->next;
this->head->next = p->next;
delete p;
p = NULL;
}
//void InsertPos(const int index, const T &e); //indexλòe
template<class T>
void LinkList<T>::InsertPos(const int index, const T &e)
{
//жindexЧ
if (index < 1 || index > this->GetSize() + 1)
{
cout << "ʧܣλ" << endl;
return;
}
//ҵҪڵλõǰһڵ
int pos = index - 1;
LinkNode<T>* p = this->head;
while (pos--)
{
p = p->next;
}
//½ڵ
LinkNode<T>* pNew = new LinkNode<T>;
pNew->data = e;
//½ڵҪڵλõǰһڵĺ
pNew->next = p->next;
p->next = pNew;
}
//void DeletePos(const int index); //ɾindexλõĽڵ
template<class T>
void LinkList<T>::DeletePos(const int index)
{
//жindexЧ
if (index < 1 || index > this->GetSize())
{
cout << "ɾʧܣûе" << index << "ڵ" << endl;
return;
}
//ҵҪɾڵλõǰһڵ
int pos = index - 1;
LinkNode<T>* p = this->head;
while (pos--)
{
p = p->next;
}
//ҪɾĽڵ㸳q
LinkNode<T>* q = p->next;
p->next = q->next;
delete q;
q = NULL;
}
//LinkNode<T>* FindElem(const T &e); //ֵңҵظýڵĵַҲNULL
template<class T>
LinkNode<T>* LinkList<T>::FindElem(const T &e)
{
LinkNode<T>* findNode = NULL;
LinkNode<T>* p = this->head;
while (p = p->next)
{
if (p->data == e)
{
findNode = p;
break;
}
}
return findNode;
}
//int FindLocateElem(const T &e); //ֵңҵظýڵλţҲ0
template<class T>
int LinkList<T>::FindLocateElem(const T &e)
{
LinkNode<T>* p = this->head;
int count = 0;
while (p = p->next)
{
count++;
if (p->data == e)
{
break;
}
}
return count;
}
// void ClearList(); //
template<class T>
void LinkList<T>::ClearList()
{
//ֻͷ㣬Ľڵȫɾ
LinkNode<T> *p, *q;
p = this->head->next;
while (p)
{
q = p->next;
delete p;
p = q;
}
this->head->next = NULL;
}
//void DestroyList(); //
template<class T>
void LinkList<T>::DestroyList()
{
//ɾнڵ
LinkNode<T>* p = this->head;
while (p)
{
this->head = p->next;//ͷָָһڵ
delete p;//ͷͷ
p = this->head;//ָͷ
}
}
template<class T>
LinkList<T>::~LinkList()
{
LinkNode<T>* p = this->head;
while (p)
{
this->head = p->next;
delete p;
p = this->head;
}
} | true |
638cbb8f4fe3a0d8e7f1e1d348c2ca78c3e4786a | C++ | pradyotprakash/Chess | /chess.h | UTF-8 | 881 | 3.21875 | 3 | [] | no_license | class Piece{
public:
//4-pawn,1-rook,2-knight,3-bishop,5-queen,6-king
int identity;
int pieceValue;
int x,y;
bool alive;
bool allowedMoves[8][8];
Piece(int,int,int);//set identity,x,y
void reset();//set the allowedMoves matix to null
};
class Board{
public:
/*
* -1,-2,-3,-5,-6,-3,-2,-1
* -4,-4,-4,-4,-4,-4,-4,-4
* 4,4,4,4,4,4,4,4
* 1,2,3,5,6,3,2,1
*/
Piece *chessPiece[4][8];
int pieceColor[8][8];//white or black piece
int boardState[8][8];//pieces at different squares
Board();
void possibleMoves(Piece&);
//color denotes the color of the present piece
void rook(Piece&,int color);//finds and assigns all possible moves horizontally and vertically
void pawn(Piece&,int color);
void bishop(Piece&,int color);
void queen(Piece&,int color);
void knight(Piece&,int color);
void king(Piece&,int color);
bool isChecked(int i,int j,int color);
}; | true |
289e5bdb3de6a9e90612ac56b2646af742d13b81 | C++ | qazedcwsx4/PR_game | /Objects/Player.cpp | UTF-8 | 529 | 2.609375 | 3 | [] | no_license | //
// Created by qaze on 31/05/2019.
//
#include "Player.h"
#include "../Game/Textures.h"
Player::Player(sf::RenderWindow &renderWindow, float x, float y) : GameObject(renderWindow) {
shape = new sf::CircleShape(50);
shape->setTexture(Textures::getPlayerTexture());
shape->setOrigin(50, 50);
shape->setPosition(x, y);
shape->setScale(0.33, 0.33);
}
bool Player::collisionNarrow(GameObject &gameObject) {
return false;
}
void Player::render() {
renderWindow.draw(*shape);
}
Player::~Player() {
}
| true |
4118ad03ac2f94f8bc4d3f51407ef5f24b2ebaa4 | C++ | ElmiraTolstova/Cplus | /Исходник.cpp | WINDOWS-1251 | 1,012 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
/* 10 -5 5. .
. */
int main ()
{
const int size= 30;
int a[size];
srand(time(NULL));
for (int i = 0; i < size; i++)
a[i] = rand() % 11 - 5;
for (int i = 0; i < size; i++)
cout << a[i] << " ";
for (int i = 0; i < size; i++)
for (int j = i+1; j < size; j++)
if (a[i] < a[j])
{
int buf = a[i];
a[i] = a[j];
a[j] = buf;
}
cout << endl << endl;
for (int i = 0; i < size; i++)
cout << a[i] << " ";
system("PAUSE > NULL");
return 0;
}
| true |
f41015a462c5eedbfb3ac97dbc932f56ed86d886 | C++ | lArkl/Parallel_OMP_MPI | /MPI/IntegralPi.cpp | UTF-8 | 1,578 | 2.546875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
#define _PARALLEL
#define _SINGLE
#ifdef _PARALLEL
//#include <mpi.h>
#endif
int main(int argc, char *argv[]){
double res;
#ifdef _PARALLEL
int me, numprocs;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&me);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
if(me==0)
cout<<"n\tPI\tError\t\tTime"<<endl;
for(int n=100;n<1000000;n*=10){
double start;
double local=0;
int rounds = n/numprocs;
int extra = n%numprocs;
int count = me;
for(int i=0; i<rounds; i++){
double delta = (count+0.5)/n;
local += 4/(1+delta*delta);
//cout<<me<<"\t"<<i<<"\t"<<local<<endl;
//MPI_Barrier(MPI_COMM_WORLD);
count+=numprocs;
}
start = MPI_Wtime();
MPI_Barrier(MPI_COMM_WORLD);
MPI_Reduce(&local,&res,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if(me==0){
//Si existe extra
if( extra ){
for(int i=0;i<extra;i++){
double delta = (numprocs*rounds+i+0.5)/n;
res += 4/(1+delta*delta);
}
}
double time = (MPI_Wtime()-start)*1000;
double pi = res/n;
//cout<<time<<endl;
cout<<n<<"\t"<<pi<<"\t"<< pi-3.141592653589793238462643<<"\t"<<time<<endl;
}
MPI_Barrier(MPI_COMM_WORLD);
}
MPI_Finalize();
#endif
/*
#ifdef _SINGLE
cout<<"n\tPI"<<endl;
double start = clock();
for(int n=10000; n<=1000000; n*=10){
double sum = 0.0;
for(int i=0; i<=n; i++){
double delta = (i-0.5)/n;
sum += 4/(1+delta*delta);
}
double end = clock();
cout<<n<<"\t"<<sum/n<<"\ttime: "<<(end-start)/CLOCKS_PER_SEC<<endl;
}
#endif
*/
return 0;
}
| true |
924ed7b1c9b6a0ffa55e175dcbeef1b9aad2ae56 | C++ | concurTestFramework/concurTestFramework | /Source/concur/scheduler/utilities.cpp | UTF-8 | 797 | 3.640625 | 4 | [] | no_license | // Utility functions for scheduler.
#include <string>
#include <sstream>
using namespace std;
// Prototypes
extern "C" string boolToStr(const bool val);
extern "C" string intToStr(int num);
extern "C" void stoupper(std::string& s);
/*
* Returns integer to string
*/
extern "C" string intToStr(int num) {
stringstream numAsAlpha;
numAsAlpha << num;
return numAsAlpha.str();
}
/*
* Returns string s in all capital letters.
*/
extern "C" void stoupper(std::string& s) {
std::string::iterator i = s.begin();
std::string::iterator end = s.end();
while (i != end) {
*i = std::toupper((unsigned char)*i);
++i;
}
}
/*
* Converts bool to string.
*/
extern "C" string boolToStr(const bool b) {
ostringstream ss;
ss << boolalpha << b;
return ss.str();
}
| true |
124ec1dc42f48994c79905e471c7f83811eefc1e | C++ | mbambagini/mpSolver | /prog/solver.cpp | UTF-8 | 1,599 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <gflags/gflags.h>
#include <parser_standard.hpp>
#include <solution.hpp>
#include <sched_solver.hpp>
#include <gnuplot_printer.hpp>
DEFINE_string (taskGraphFile, "", "Problem description file - Task set [in]");
DEFINE_string (platformFile, "", "Problem description file - Hardware [in]");
DEFINE_string (gnuplotFile, "", "Gnuplot script with the schedule [out]");
DEFINE_int32 (print, 0, "After how many branches to print state [in]");
DEFINE_int32 (limit, 0, "Time limit for the searching (seconds) [in]");
void fatal_error (string str);
int main (int argc, char* argv[])
{
google::ParseCommandLineFlags(&argc, &argv, false);
srand(time(NULL));
//check arguments
if (FLAGS_taskGraphFile.compare("")==0 || FLAGS_platformFile.compare("")==0)
fatal_error("Wrong parameters");
//parse the problem
StandardParser parser;
if (!parser.load(FLAGS_taskGraphFile, FLAGS_platformFile))
fatal_error("Impossible to parse the models");
//find the optimal schedule
SchedulingSolver sol;
sol.setParser(&parser);
sol.setPrintRate(FLAGS_print);
sol.setTimeLimit(FLAGS_limit);
if (sol.solve()) {
//print the schedule
GnuplotPrinter p;
const Solution s = sol.getResult();
if (!s.validate(&parser))
fatal_error("Problems during the schedule check");
if (FLAGS_gnuplotFile.compare("")!=0) {
std::ofstream file(FLAGS_gnuplotFile.c_str());
p.print(s, file);
file.close();
}
} else
std::cout<<"Solution not found\n";
return 0;
}
void fatal_error (string str)
{
std::cerr<<"Error: "<<str<<std::endl;
exit(0);
}
| true |
72dd3d58dd044ab94eff577dfd209521b8facb62 | C++ | LeeviT/pipeaggrot | /cppsrc/io.hpp | UTF-8 | 1,983 | 2.609375 | 3 | [] | no_license | #ifndef CPPSRC_IO_HPP
#define CPPSRC_IO_HPP
using namespace std;
// Structure for handling input and returning it
struct input {
private:
// beta = v_d/v_c
// dp=pressure difference, l=length of the pipe, R=radius of the pipe
// nx=number of discretization points in x-direction, ny=same but in y-direction, t_max=max number of timesteps
double dp, l, visc0, R, dt, diff_coeff, aspect_ratio, beta, shear_rate_max, Np_max;
int theta_grid, phi_grid, classes, what_todo, s1, s2, ny, t0, t_max;
public:
// Setter functions for each variable
void setdp(double dp_);
void setl(double l_);
void setvisc0(double visc0_);
void setR(double R_);
void setdt(double dt_);
void setdiff_coeff(double diff_coeff_);
void setaspect_ratio(double aspect_ratio_);
void setbeta(double beta_);
void setshear_rate_max(double shear_rate_max_);
void setNp_max(double Np_max_);
void settheta_grid(int theta_grid_);
void setphi_grid(int phi_grid_);
void setclasses(int classes_);
void setwhat_todo(int what_todo_);
void sets1(int s1_);
void sets2(int s2_);
void setny(int ny_);
void sett0(int t0_);
void sett_max(int t_max_);
// Getter functions for each variable
double getdp() const;
double getl() const;
double getvisc0() const;
double getR() const;
double getdt() const;
double getdiff_coeff() const;
double getaspect_ratio() const;
double getbeta() const;
double getshear_rate_max() const;
double getNp_max() const;
int gettheta_grid() const;
int getphi_grid() const;
int getclasses() const;
int getwhat_todo() const;
int gets1() const;
int gets2() const;
int getny() const;
int gett0() const;
int gett_max() const;
// Function reading input values from the input file
void read_input_file();
};
// Function writing r and x-velo values to file
void write_r_vx(int ny_, int t_step_, vector<point> radius_);
#endif | true |
cafdb7c6ec8dbecc6ff5360ec348db9ace2363ec | C++ | NathanielBuchanan/cs2400 | /searching.cc | UTF-8 | 1,865 | 4.09375 | 4 | [
"MIT"
] | permissive | /*
* File: searching.cc
* Author: Nasseef Abukamail
* Date: March 27, 2020
* Description: Demonstarate sequential search and binary search.
*/
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
// function prototypes
int search(int data[], int count, int target);
//sequential search of unordered array
int binSearch(const int data[], int count, int target);
//binary search of an ordered array.
int main(int argc, char const *argv[]) {
int data[16] = {4, 9, 1, 10, 20, 50, 30, 55, 60, 45, 3, 12, 33, 44, 22, 15};
int data2[16] = {1, 3, 4, 9, 10, 12, 15, 20, 22, 30, 33, 44, 45, 50, 55, 60};
int size = 16;
int target;
cout << "Enter a value to search: ";
cin >> target;
int location = search(data, size, target);
if (location == -1) {
cout << target << " not found" << endl;
} else {
cout << target << " is located at position " << location << endl;
}
cout << "Searching a sorted array" << endl;
cout << "Enter a value to search: ";
cin >> target;
location = binSearch(data2, size, target);
if (location == -1) {
cout << target << " not found" << endl;
} else {
cout << target << " is located at position " << location << endl;
}
return 0;
}
int search(int data[], int count, int target) {
for (int i = 0; i < count; i++) {
if (target == data[i]) {
return i;
}
}
return -1; //target not found
}
int binSearch(const int data[], int count, int target) {
int first = 0, mid, last = count - 1;
while (first <= last) {
mid = (first + last) / 2;
if (target == data[mid])
return mid;
else if (target < data[mid])
last = mid - 1;
else
first = mid + 1;
}
return -1; // target not found
}
| true |
892e1fa386d028a56edea74f1069f83b0048d0e6 | C++ | sidmishraw/the-manipulator | /src/Canvas.hpp | UTF-8 | 2,499 | 3.25 | 3 | [
"BSD-3-Clause"
] | permissive | //
// Canvas.hpp
// the-manipulator
//
// Created by Sidharth Mishra on 2/18/18.
//
#ifndef Canvas_hpp
#define Canvas_hpp
#include <memory>
#include <map>
#include "Picture.hpp"
namespace Manipulator {
/**
* The canvas where the pictures are drawn.
*/
class Canvas {
/**
* All the pictures added to the canvas.
* I feel that having a map with Z-Index makes it easier for me to implement
* the selected image movement thingy!
*/
std::map<int,std::shared_ptr<Manipulator::Picture>> pictures;
// denotes the z-depth?
int currentDepth;
// pointer to the foreground picture.
std::shared_ptr<Manipulator::Picture> foregroundPic;
// the depth of the selected picture
int selectionDepth;
public:
/**
* Initializes the canvas with initial properties.
*/
Canvas();
/**
* Adds the picture at the filePath to the canvas, if not added returns false.
*/
bool addPicture(std::string filePath);
/**
* Renders the canvas, drawing the pictures, one at a time in the order they were added to it.
*/
void render();
/**
* Saves the canvas composition to disk with the provided fileName.
*/
bool saveToDisk(std::string fileName);
/**
* Scales/resizes the current - selected picture or the picture on the foreground.
*/
void scalePicture(float sx, float sy);
/**
* 2D translation of the foregroundPic. Does nothing if there is no foregroundPic or no selected pic.
*/
void translatePicture(float tx, float ty);
/**
* Selects the picture on the foreground.
*/
void selectForegroundPicture();
/**
* De-Selects the picture on the foreground.
*/
void deselectForegroundPicture();
/**
* Selects the picture at the specified (x,y) co-ordinate if possible.
*/
void selectPictureAt(int x, int y);
/**
* Moves the selected image up in the z. (-ve)
*/
void cyclePicturesUp();
/**
* Moves the selected image down in the z. (+ve)
*/
void cyclePicturesDown();
};
}
#endif /* Canvas_hpp */
| true |
bd5604be7dbdac71ad33941a9d34e812c69d5d64 | C++ | pilot1129/Algorithm-Study | /Search/DFS.cpp | UHC | 971 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
//Recursion
void dfs(int start, vector<int> graph[], bool check[])
{
check[start] = true;
int next_node = 0;
for (int i = 0; i < graph[start].size(); ++i)
{
next_node = graph[start][i];
/*
* ؾ ϴ ̰ ۼ
*/
if (!check[next_node])//̹湮
dfs(next_node, graph, check);
}
}
//Non-Recursion
void dfs_vector(int start, vector<int> graph[], bool check[])
{
vector<int> history;
history.push_back(start);
check[start] = true;
int cur_node = 0;
int next_node = 0;
while (!history.empty())
{
cur_node = history.back();
history.pop_back();
for (int i = 0; i < graph[cur_node].size(); ++i)
{
next_node = graph[cur_node][i];
/*
* ؾ ϴ ̰ ۼ
*/
if (!check[next_node])
{
check[next_node] = true;
history.push_back(cur_node);
history.push_back(next_node);
break;
}
}
}
}
| true |
a3e31abd2985f30d447c5c9c7931537e1df6e965 | C++ | dangxiaobin123/leetcodeAC | /leetcode/0004. 寻找两个有序数组的中位数/cpp/solution.h | UTF-8 | 904 | 3.21875 | 3 | [] | no_license | #include <vector>
using namespace std;
class Solution
{
public:
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)
{
int m = nums1.size(), n = nums2.size();
int l = (m + n + 1) / 2, r = (m + n + 2) / 2;
return (findKthNums(nums1, 0, nums2, 0, l) + findKthNums(nums1, 0, nums2, 0, r)) / 2.0;
}
double findKthNums(vector<int> &nums1, int i, vector<int> &nums2, int j, int k)
{
if (i >= nums1.size()) return nums2[j + k - 1];
if (j >= nums2.size()) return nums1[i + k - 1];
if (k == 1) return min(nums1[i], nums2[j]);
int l = i + k / 2 - 1 < nums1.size() ? nums1[i + k / 2 - 1] : INT_MAX;
int r = j + k / 2 - 1 < nums2.size() ? nums2[j + k / 2 - 1] : INT_MAX;
return l < r ? findKthNums(nums1, i + k / 2, nums2, j, k - k / 2) : findKthNums(nums1, i, nums2, j + k / 2, k - k / 2);
}
};
| true |
ae97e095b298651ccc73404b8bcd075d75d57d35 | C++ | jfelts1/AllegroProject | /Project1/Utils/StringUtils.h | UTF-8 | 729 | 3.171875 | 3 | [] | no_license | #ifndef STRINGUTILS_H
#define STRINGUTILS_H
#include <string>
#include <iostream>
#include <stdexcept>
#pragma once
namespace Utils
{
//removes all whitespace from the string and returns a new string
std::string removeWhiteSpace(std::string s);
//copys the string from start until the next white space and returns as a new string
std::string copyUntilNextWhiteSpace(std::string s, size_t start = 0);
//not templated because each function to turn a string into the various number type has
//a diffrent name would have meant lots of template specilization one for each number type
float getFloatFromStringWPrefix(std::string s, std::string preFix);
int getIntFromStringWPreFix(std::string s, std::string preFix);
}
#endif
| true |
adabb6a13b21f147e4dc02c50092a65faef32d07 | C++ | AlexBeloglazov/chatty | /src/commands.cpp | UTF-8 | 2,762 | 3.09375 | 3 | [] | no_license | /*
* commands.cpp : File contains handlers for the user commands for both Server and Client modes
* Created for CSE 589 Fall 2017 Programming Assignment 1
* @author Alexander Beloglazov
*/
#include "../include/commands.h"
/*
* Handler for user's AUTHOR command
*/
void cmd_author()
{
std::stringstream out;
out << "I, " << AUTHOR
<< ", have read and understood the course academic integrity policy.\n";
print_success(_CMD_AUTHOR, (char *)out.str().c_str());
}
/*
* Handler for user's IP command
* Prints external IP address on the screen
*/
void cmd_ip()
{
std::string ip = params->ip_address + "\n";
print_success(_CMD_IP, &ip[0], 1);
}
/*
* Handler for user's PORT command
* Prints external PORT on the screen
*
*/
void cmd_port()
{
std::string port = params->port + "\n";
print_success(_CMD_PORT, &port[0], 1);
}
/*
* Handler for user's LIST command
* Prints list of either clients or peers in the certain format
* @input ml Pointer to a vector of Machine objects
*/
void cmd_list(std::vector<Machine*> *ml) {
std::stringstream stream;
std::string out;
std::vector<Machine*>::iterator it;
int index = 0;
// sort the vector by machine port number
ml_sort_by_port(ml);
for (it = ml->begin(); it != ml->end(); ++it) {
if (!(*it)->is_logged) {
continue;
}
stream << std::left << std::setw(5) << ++index
<< std::setw(35) << (*it)->hostname
<< std::setw(20) << (*it)->ip
<< std::setw(8) << (*it)->port << "\n";
out += stream.str();
stream.clear();
stream.str(std::string());
}
print_success(_CMD_LIST, &out[0]);
}
/*
* Method uniquely identifies command
* @arg cmd C++ string contains command entered by user
* @return enum commands value
*/
int identify_cmd(std::string &cmd)
{
commands out;
if (cmd == _CMD_AUTHOR)
out = CMD_AUTHOR;
else if (cmd == _CMD_BLOCK)
out = CMD_BLOCK;
else if (cmd == _CMD_BLOCKED)
out = CMD_BLOCKED;
else if (cmd == _CMD_BROADCAST)
out = CMD_BROADCAST;
else if (cmd == _CMD_EXIT)
out = CMD_EXIT;
else if (cmd == _CMD_IP)
out = CMD_IP;
else if (cmd == _CMD_LIST)
out = CMD_LIST;
else if (cmd == _CMD_LOGIN)
out = CMD_LOGIN;
else if (cmd == _CMD_LOGOUT)
out = CMD_LOGOUT;
else if (cmd == _CMD_PORT)
out = CMD_PORT;
else if (cmd == _CMD_REFRESH)
out = CMD_REFRESH;
else if (cmd == _CMD_SEND)
out = CMD_SEND;
else if (cmd == _CMD_STATISTICS)
out = CMD_STATISTICS;
else if (cmd == _CMD_UNBLOCK)
out = CMD_UNBLOCK;
else
out = CMD_UNKNOWN;
return out;
} | true |
ed8a9f887764c82f6519533f1ff1cae7cb272221 | C++ | weekenlee/leetcode-c | /LeetCode/LeetCode/add_two_numbers.cc | UTF-8 | 1,770 | 3.796875 | 4 | [] | no_license | #include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode dummy{0};
auto curr = &dummy;
auto carry = 0;
while (l1 || l2 || carry) {
auto a = l1 ? l1->val:0;
auto b = l2 ? l2->val:0;
auto val = carry + a + b;
std::cout<<a<<b<<carry<<val<<std::endl;
curr->next = new ListNode(val % 10);
carry = val / 10;
l1 = l1 ? l1->next :nullptr;
l2 = l2 ? l2->next :nullptr;
curr = curr->next;
}
return dummy.next;
}
};
int main()
{
ListNode root = ListNode(1);
ListNode *prev = &root;
for (int i = 0; i < 2; ++i) {
ListNode *node = new ListNode(i);
prev->next = node;
prev = prev->next;
}
prev->next=nullptr;
ListNode *l1 = &root;
ListNode *pl1 = l1;
while(pl1!= nullptr) {
std::cout<<pl1->val<<" ";
pl1=pl1->next;
}
std::cout<<std::endl;
ListNode root2 = ListNode(2);
prev = &root2;
for (int i = 0; i < 2; ++i) {
ListNode *node = new ListNode(i+3);
prev->next = node;
prev = prev->next;
}
prev->next = nullptr;
ListNode *l2 = &root2;
ListNode *pl2 = l2;
while(pl2!= NULL) {
std::cout<<pl2->val<<" ";
pl2=pl2->next;
}
std::cout<<std::endl;
Solution s;
ListNode *result = s.addTwoNumbers(l1, l2);
while(result != NULL) {
std::cout<<result->val<<" ";
result=result->next;
}
std::cout<<std::endl;
return 0;
}
| true |
536e78211203ec44e38a6cf0378086ab1e6cf1ac | C++ | Owenyang1997/Cproject | /数据结构/drawFaction/drawFaction/drawLine.cpp | UTF-8 | 976 | 3.09375 | 3 | [] | no_license | #include "stdafx.h"
#include <cstdio>
#include <graphics.h>
int X(int x);
int Y(int y);
void draw(int x, int y);
void print();
int main()
{
print();
setlinecolor(0x55FFFF);
myline(-400, 20, 400, 20);
myline(20, -300, 20, 300);
}
void myline(int x1, int y1, int x2, int y2) {
float increx, increy, x, y, length;
int i;
if (abs(x2 - x1) > abs(y2 - y1)) {
length = abs(x2 - x1);
}
else {
length = abs(y2 - y1);
}
increx = (x2 - x1) / length;
increy = (y2 - y1) / length;
for (i = 1; i <= length; i++) {
draw(x + 0.5, y + 0.5);
x = x + increx;
y = y + increy;
}
}
void draw(int x, int y) {
setlinecolor(0x55FF55);
int x1 = X(x);
int y1 = Y(y);
line(x1, y1, x1, y1);
}
int X(int x) {
int x0 = 400;
return x + x0;
}
int Y(int y) {
int y0 = 300;
return y0 - y;
}
void print() {
initgraph(800, 600);
setbkcolor(0x555555);
cleardevice();
setlinecolor(0xFF5555);
line(0, 300, 800, 300);
line(400, 0, 400, 600);
setlinecolor(0xFF5555);
}
| true |
bdcb12512d7b2bc739d89d82be942b969b8cdbbf | C++ | microhlab/nnc | /GetTokens.cpp | UTF-8 | 193 | 2.53125 | 3 | [] | no_license | #include "Reader.h"
deque<char*> * Reader::getTokens()
{
deque<char*>* tokens = new deque<char*>();
char * token;
while (token = getToken())
tokens->push_back(token);
return tokens;
} | true |
9bc38235046e43162c0c207f81715b6d6937e3b2 | C++ | ttyang/sandbox | /sandbox/SOC/2007/geometry/libs/hdstl/dev/hds_archetypes/mutable_backward_hds_concept_archetype.hpp | UTF-8 | 8,624 | 2.5625 | 3 | [] | no_license | // mutable_backward_hds_concept_archetype.hpp -*- C++ -*-
//
//@PURPOSE: Provide a 'MutableBackwardHDS' concept archetype
//
//@DESCRIPTION: This file provides an archetype class for compile-time testing
// of the 'MutableBackwardHDSConcept' class. Namely, this class can be used
// wherever a template parameter of a class or of a function template is
// required to be a model of the 'MutableBackwardHDS' concept, in order to
// ensure that no further requirements are placed on the template parameter
// than are stated in the 'MutableBackwardHDS' concept.
//
///Archetype class
///---------------
//..
// template <typename BackwardCategory>
// struct hds_traits<MutableBackwardHDSConcept_archetype<BackwardCategory> > {
// typedef boost::default_constructible_archetype<
// boost::copy_constructible_archetype<
// boost::equality_comparable_archetype<
// boost::assignable_archetype<> > > > halfedge_descriptor;
// typedef boost::convertible_to_archetype<backward_traversal_tag>
// traversal_category;
// typedef BackwardCategory backward_category;
// enum {supports_vertices = false};
// enum {supports_facets = false};
// };
// template <typename BackwardCategory>
// class MutableBackwardHDSConcept_archetype
// : public BackwardHDSConcept_archetype<BackwardCategory>,
// public MutableHDSConcept_archetype {
// typedef typename hds_traits<MutableBackwardHDSConcept_archetype<
// BackwardCategory> >::halfedge_descriptor
// halfedge_descriptor;
// typedef typename hds_traits<MutableBackwardHDSConcept_archetype<
// BackwardCategory> >::traversal_category
// traversal_category;
// typedef BackwardCategory backward_category;
// public:
// void
// set_prev_in_facet(halfedge_descriptor h, halfedge_descriptor g,
// MutableBackwardHDSConcept_archetype& hds);
// void
// set_prev_at_source(halfedge_descriptor h, halfedge_descriptor g,
// MutableBackwardHDSConcept_archetype& hds);
// void
// set_prev_at_target(halfedge_descriptor h, halfedge_descriptor g,
// MutableBackwardHDSConcept_archetype& hds);
// };
//..
#ifndef BOOST_HDSTL_MUTABLE_BACKWARD_HDS_CONCEPT_ARCHETYPE_HPP
#define BOOST_HDSTL_MUTABLE_BACKWARD_HDS_CONCEPT_ARCHETYPE_HPP
#include <boost/hdstl/hds_archetypes/backward_hds_concept_archetype.hpp>
#include <boost/hdstl/hds_archetypes/mutable_hds_concept_archetype.hpp>
#include <boost/hdstl/hds_traits.hpp>
#include <boost/concept_archetype.hpp>
namespace boost {
namespace hdstl {
template <typename BackwardCategory>
class MutableBackwardHDSConcept_archetype; // forward declaration
template <typename BackwardCategory>
struct hds_traits<MutableBackwardHDSConcept_archetype<BackwardCategory> > {
// This template specialization of 'hds_traits' for the
// 'MutableBackwardHDSConcept_archetype' provides the 'halfedge_descriptor'
// and 'traversal_category' types.
// TYPES
typedef boost::default_constructible_archetype<
boost::copy_constructible_archetype<
boost::equality_comparable_archetype<
boost::assignable_archetype<> > > > halfedge_descriptor;
// Halfedge descriptor type for the 'MutableBackwardHDSConcept'
// archetype.
typedef boost::convertible_to_archetype<backward_traversal_tag>
traversal_category;
// This type, convertible to 'backward_traversal_tag', indicates that
// the 'MutableBackwardHDSConcept' archetype is a model of
// 'MutableBackwardHDSConcept'.
typedef BackwardCategory backward_category;
// This type, convertible to one or more of 'prev_in_facet_tag',
// 'prev_at_source_tag', or 'prev_at_target_tag', indicates which is
// the primary accessor(s) for which the 'set_...' methods are defined.
enum {supports_vertices = false};
enum {supports_facets = false};
};
template <typename BackwardCategory>
class MutableBackwardHDSConcept_archetype
: virtual public BackwardHDSConcept_archetype<BackwardCategory>,
virtual public MutableHDSConcept_archetype {
// This class provides an exact implementation (no more, no less) of the
// 'MutableBackwardHDS' concept. It can be used to instantiate class and
// function templates that require their template arguments to be a model
// of this concept in order to verify that there are no extra syntactic
// requirements.
// PRIVATE TYPES
typedef typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor
halfedge_descriptor;
//Halfedge descriptor type from 'MutableBackwardHDSConcept'
typedef typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::traversal_category
traversal_category;
//traversal category type from from 'MutableBackwardHDSConcept',
//has to be convertible to 'backward_traversal_tag'.
typedef BackwardCategory backward_category;
// This type, convertible to one or more of 'prev_in_facet_tag',
// 'prev_at_source_tag', or 'prev_at_target_tag', indicates which is
// the primary accessor(s) for which the 'set_...' methods are defined.
public:
// MANIPULATORS
void
set_prev_in_facet(halfedge_descriptor h, halfedge_descriptor g,
MutableBackwardHDSConcept_archetype<BackwardCategory>& hds);
// set 'g' as the halfedge preceding 'h' in the (counter-clockwise)
// facet cycle of 'h' in 'hds'.
void
set_prev_at_source(halfedge_descriptor h, halfedge_descriptor g,
MutableBackwardHDSConcept_archetype<BackwardCategory>& hds);
// set 'g' as the halfedge preceding 'h' in the (clockwise) vertex
// cycle of the source of 'h' in 'hds'.
void
set_prev_at_target(halfedge_descriptor h, halfedge_descriptor g,
MutableBackwardHDSConcept_archetype<BackwardCategory>& hds);
// set 'g' as the halfedge preceding 'h' in the (clockwise) vertex
// cycle of the target of 'h' in 'hds'.
};
// MANIPULATORS
template <typename BackwardCategory>
inline
void
set_prev_in_facet(typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor h,
typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor g,
MutableBackwardHDSConcept_archetype<BackwardCategory>& hds)
{
(void)hds; // eliminate unused variable warning
(void)h; // eliminate unused variable warning
(void)g; // eliminate unused variable warning
}
template <typename BackwardCategory>
inline
void
set_prev_at_source(typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor h,
typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor g,
MutableBackwardHDSConcept_archetype<BackwardCategory>& hds)
{
(void)hds; // eliminate unused variable warning
(void)h; // eliminate unused variable warning
(void)g; // eliminate unused variable warning
}
template <typename BackwardCategory>
inline
void
set_prev_at_target(typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor h,
typename hds_traits<MutableBackwardHDSConcept_archetype<
BackwardCategory> >::halfedge_descriptor g,
MutableBackwardHDSConcept_archetype<BackwardCategory>& hds)
{
(void)hds; // eliminate unused variable warning
(void)h; // eliminate unused variable warning
(void)g; // eliminate unused variable warning
}
} // end namespace hdstl
} // end namespace boost
#endif
| true |
6ce6cb525055800b2185bdbc51f83a8afb05a411 | C++ | wook2014/relate | /include/pipeline/ConvertFromGP.cpp | UTF-8 | 3,077 | 2.71875 | 3 | [] | no_license | /*! \file ConvertFromGP.cpp
* \brief Convert Data from GP format to custom format
*/
#include <iostream>
#include <sys/time.h>
#include <sys/resource.h>
#include "cxxopts.hpp"
#include "data.hpp"
int main(int argc, char* argv[]){
//////////////////////////////////
//Program options
cxxopts::Options options("ConvertFromGP");
options.add_options()
("help", "Print help")
("h,haps", "Filename of file containing haplotype data", cxxopts::value<std::string>()) //!option
("l,legend", "Filename of file containing legend", cxxopts::value<std::string>())
("m,map", "Filename of file containing recombination map", cxxopts::value<std::string>())
("f,fasta", "Filename of file containing ancestral genome as fasta", cxxopts::value<std::string>())
("s,samples", "Filename of file containing sample labels", cxxopts::value<std::string>())
("x,excluded_samples", "Filename of file containing excluded samples", cxxopts::value<std::string>())
("a,ancestral_state", "Filename of file containing ancestral states as fasta", cxxopts::value<std::string>())
("c,mask", "Filename of file containing mask as fasta", cxxopts::value<std::string>());
options.parse(argc, argv);
bool help = false;
if(!options.count("haps") || !options.count("legend") || !options.count("map") || !options.count("fasta") || !options.count("samples") || !options.count("excluded_samples") || !options.count("ancestral_state") || !options.count("mask")){
std::cout << "Not enough arguments supplied." << std::endl;
std::cout << "Needed: haps, legend, map, fasta, samples, excluded_samples, ancestral_state, mask." << std::endl;
help = true;
}
if(options.count("help") || help){
std::cout << options.help({""}) << std::endl;
std::cout << "Use to convert 1000 GP data to file format needed by Relate." << std::endl;
exit(0);
}
std::cerr << "############" << std::endl;
std::cerr << "Preparing Data..." << std::endl;
//////////////////////////////////
//Parse Data
GPData data; //struct data is defined in data.hpp
data.ReadGP(options["haps"].as<std::string>(),options["legend"].as<std::string>(),options["map"].as<std::string>(),options["ancestral_state"].as<std::string>(), options["mask"].as<std::string>(), options["excluded_samples"].as<std::string>());
data.PrepareMutationsFile(options["fasta"].as<std::string>(), options["samples"].as<std::string>(), options["excluded_samples"].as<std::string>());
/////////////////////////////////////////////
//Resource Usage
rusage usage;
getrusage(RUSAGE_SELF, &usage);
std::cerr << "CPU Time spent: " << usage.ru_utime.tv_sec << "." << std::setfill('0') << std::setw(6);
#ifdef __APPLE__
std::cerr << usage.ru_utime.tv_usec << "s; Max Memory usage: " << usage.ru_maxrss/1000000.0 << "Mb." << std::endl;
#else
std::cerr << usage.ru_utime.tv_usec << "s; Max Memory usage: " << usage.ru_maxrss/1000.0 << "Mb." << std::endl;
#endif
std::cerr << "---------------------------------------------------------" << std::endl << std::endl;
return 0;
}
| true |
66adaf1b63b15b2bf7c4663c6ef4d8a9e8742b35 | C++ | XiaotaoChen/coding-interview | /search_alg_impls/max_area_in_water_tank.cc | UTF-8 | 2,146 | 3.328125 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
#include "../search_algs.h"
int search::get_max_area(std::vector<int>& heights, std::vector<int>& idxs, int curr_idx) {
int result = 0;
for (int i=idxs.size()-1; i>=0; i--) {
// if (heights[curr_idx] <= heights[idxs[i]]) {
// int curr = (curr_idx - idxs[i]) * heights[curr_idx];
// result = result > curr ? result : curr;
// }
// else {
// break;
// }
int curr = (curr_idx - idxs[i]) * std::min(heights[curr_idx], heights[idxs[i]]);
result = std::max(result, curr);
}
return result;
}
int search::maxArea(std::vector<int>& heights) {
if(heights.size() < 2) return 0;
int result = 0;
std::vector<int> left_bar;
left_bar.push_back(0);
for (int i=1; i < heights.size(); i++) {
if (heights[i] > heights[left_bar.back()]) {
left_bar.push_back(i);
}
else {
int curr = get_max_area(heights, left_bar, i);
result = result>curr? result: curr;
}
}
for (int i=0; i<left_bar.size(); i++) {
int curr = heights[left_bar[i]] * (left_bar.back() - left_bar[i]);
result = result>curr?result:curr;
}
return result;
}
int search::maxArea_v2(std::vector<int>& height) {
if (height.size() < 2) return 0;
int res = 0;
for (int i=0, j=height.size()-1; i<j; ) {
int min_height = height[i] < height[j] ? height[i++] : height[j--];
int curr = min_height * (j - i +1);
res = res > curr ? res : curr;
}
return res;
}
int search::maxArea_v3(std::vector<int>& height) {
if (height.size()<2) return 0;
// if (height.size()==2) return std::min(height[0], height[1]);
int left = 0;
int right = height.size() -1;
int result = 0;
while(left < right) {
int curr_area = std::min(height[left], height[right]) * (right - left);
result = std::max(result, curr_area);
if (height[left] < height[right]) {
left++;
}
else {
right--;
}
}
return result;
} | true |
de083c49690621a0249168fbb4bc1413a5e90046 | C++ | samueljrz/Competitive-Programing | /NepsAcademy/Programação Básica - 1/Cadeia de Caracteres/Strings/Vestibular.cpp | UTF-8 | 239 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main () {
int n, count=0;
string gab, resp;
cin >> n;
cin >> gab;
cin >> resp;
for(int i=0; i<n; i++) {
if(gab[i] == resp[i]) {
count++;
}
}
cout << count << endl;
return 0;
} | true |
ebbe65d85a51377016a6946450fd5d4680e980ba | C++ | hanhongyuan/doc | /NiuKe-master/第二章_排序/排序(4)/三色排序练习题/ThreeColor.cpp | GB18030 | 669 | 3.765625 | 4 | [] | no_license | class ThreeColor {
public:
vector<int> sortThreeColor(vector<int> A, int n) {
int index_0=0;//0
int index_2=n-1;//2
int i=0;
while(i<=index_2){
if(A[i]==1){//1
i++;
}else if(A[i]==0){//0Ӧλϣi
swap(A,index_0,i);
index_0++;
i++;
}else if(A[i]==2){//2,Ӧλϣi䣬Ϊ֪Ƿ0ǻҪƶ
swap(A,index_2,i);
index_2--;
}
}
return A;
}
void swap(vector<int> &A,int a,int b){
int t=A[a];
A[a]=A[b];
A[b]=t;
}
}; | true |
c17fa4f7d31bf6e7173fc671799bb8e1f4240c47 | C++ | brentrwilliams/DistributedRaytracer | /serial/MeshBVHNode.cpp | UTF-8 | 2,978 | 3.203125 | 3 | [] | no_license | /**
* MeshBVHNode.cpp
*
* @author Brent Williams brent.robert.williams@gmail.com
*/
#include "MeshBVHNode.hpp"
MeshBVHNode::MeshBVHNode(std::vector<Triangle> triangles, int axis)
{
int numTris = triangles.size();
if (numTris == 1)
{
left = NULL;
right = NULL;
boundingBox = triangles[0].boundingBox;
triangle = triangles[0];
}
else
{
int nextAxis;
if (axis == X_AXIS)
{
sort(triangles.begin(), triangles.end(), xAxisSort);
nextAxis = Y_AXIS;
}
else if (axis == Y_AXIS)
{
sort(triangles.begin(), triangles.end(), yAxisSort);
nextAxis = Z_AXIS;
}
else
{
sort(triangles.begin(), triangles.end(), zAxisSort);
nextAxis = X_AXIS;
}
// Split vector into 2 parts
int half = triangles.size() / 2;
std::vector<Triangle> leftTris(triangles.begin(), triangles.begin() + half);
std::vector<Triangle> rightTris(triangles.begin() + half, triangles.end());
left = new MeshBVHNode(leftTris, nextAxis);
right = new MeshBVHNode(rightTris, nextAxis);
BoundingBox* boundingBoxPtr = new BoundingBox(left->boundingBox, right->boundingBox);
boundingBox = *boundingBoxPtr;
//triangle = NULL;
}
}
bool MeshBVHNode::intersect(Ray ray, float *t, Triangle* triangleHit)
{
bool leftBool, rightBool, leafBool;
float lt, rt;
Triangle lTri, rTri;
if (boundingBox.intersect(ray))
{
if (!(left == NULL && right == NULL)) //It is NOT a leaf node
{
if (left == NULL)
printf("NULL LEFT!\n");
if (left == NULL)
printf("NULL RIGHT!\n");
leftBool = left->intersect(ray, <, &lTri);
rightBool = right->intersect(ray, &rt, &rTri);
if (leftBool && rightBool)
{
if (lt < rt)
{
*t = lt;
*triangleHit = lTri;
}
else
{
*t = rt;
*triangleHit = rTri;
}
//cout << "\t" << *triangleHit << endl;
return true;
}
else if (leftBool)
{
*t = lt;
*triangleHit = lTri;
//cout << "\t" << *triangleHit << endl;
return true;
}
else if (rightBool)
{
*t = rt;
*triangleHit = rTri;
//cout << "\t" << *triangleHit << endl;
return true;
}
else
return false;
}
else //It is a leaf node
{
*triangleHit = triangle;
leafBool = triangle.intersect(ray, t);
//std::cout << "Leaf: " << leafBool << "\n";
//std::cout << triangle << "\n";
//if (leafBool)
// std::cout << "HIT!\n";
return leafBool;
}
}
else
return false;
return false;
}
| true |
a3b82ad961ad0f2bbc22e79acb28d4da68ed9feb | C++ | DeonPoncini/ygodeck-c | /test/FormatTest.cpp | UTF-8 | 3,101 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <boost/test/unit_test.hpp>
#include <ygo/deck/c/Format.h>
#include <ygo/deck/c/DB.h>
struct Format_Fixture
{
Format_Fixture()
{
DB_NAME(set_path)("test/card.db");
}
};
BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture)
BOOST_AUTO_TEST_CASE(Create)
{
int count;
auto formatDates = FORMAT_NAME(formatDates)(&count);
for (auto i = 0; i < count; i++) {
auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED,
formatDates[i]);
auto formatDateA = FORMAT_NAME(formatDate)(formatA);
auto formatFA = FORMAT_NAME(format)(formatA);
BOOST_CHECK_EQUAL(std::string(formatDateA), formatDates[i]);
BOOST_CHECK(formatFA == ygo_data_Format_ADVANCED);
FORMAT_NAME(delete_formatDate)(formatDateA);
auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL,
formatDates[i]);
auto formatDateT = FORMAT_NAME(formatDate)(formatT);
auto formatTA = FORMAT_NAME(format)(formatT);
BOOST_CHECK_EQUAL(std::string(formatDateT), formatDates[i]);
BOOST_CHECK(formatTA == ygo_data_Format_TRADITIONAL);
FORMAT_NAME(delete_formatDate)(formatDateT);
auto formatM = FORMAT_NAME(new)(ygo_data_Format_MEGABANNED,
formatDates[i]);
auto formatDateM = FORMAT_NAME(formatDate)(formatM);
auto formatMA = FORMAT_NAME(format)(formatM);
BOOST_CHECK_EQUAL(std::string(formatDateM), formatDates[i]);
BOOST_CHECK(formatMA == ygo_data_Format_MEGABANNED);
FORMAT_NAME(delete_formatDate)(formatDateM);
}
FORMAT_NAME(delete_formatDates)(formatDates, count);
}
BOOST_AUTO_TEST_CASE(Invalid)
{
auto format = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "InvalidFormat");
BOOST_CHECK(format == nullptr);
}
BOOST_AUTO_TEST_CASE(Limits)
{
auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "April 2004");
auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL, "April 2004");
auto formatM = FORMAT_NAME(new)(ygo_data_Format_MEGABANNED, "April 2004");
BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatA, "Change of Heart"));
BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Change of Heart"));
BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatM, "Change of Heart"));
BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatA, "Mage Power"));
BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Mage Power"));
BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatM, "Mage Power"));
BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatA, "Creature Swap"));
BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatT, "Creature Swap"));
BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatM, "Creature Swap"));
BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatA, "Kuriboh"));
BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatT, "Kuriboh"));
BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatM, "Kuriboh"));
FORMAT_NAME(delete)(formatA);
FORMAT_NAME(delete)(formatT);
FORMAT_NAME(delete)(formatM);
}
BOOST_AUTO_TEST_SUITE_END()
| true |
bc000daeece5756aef92cbc767b79863450ff16f | C++ | bhundar/Reversi | /textdisplay.cc | UTF-8 | 1,602 | 3.21875 | 3 | [] | no_license | #include "textdisplay.h"
TextDisplay::TextDisplay(int n): gridSize{n}{
for (size_t height = 0; height < n; ++height) {
std::vector<char> cell;
for (size_t width = 0; width < n; ++width) {
if (((height == (n /2) - 1) && (width == (n /2) - 1)) || (((height == (n /2)) && (width == (n /2))))) {
cell.emplace_back('B');
} else if (((height == (n/2)) && (width == (n /2) - 1)) || ((height == (n/2) - 1) && (width == (n /2)))){
cell.emplace_back('W');
} else {
cell.emplace_back('-');
}
}
theDisplay.emplace_back(cell);
}
}
void TextDisplay::notify(Subject<Info, State> &whoNotified) {
if ((whoNotified.getState().type == StateType::NewPiece) || (whoNotified.getState().type == StateType::Relay)) {
if (whoNotified.getState().colour == Colour::Black) {
this->theDisplay[whoNotified.getInfo().row][whoNotified.getInfo().col] = 'B';
} else if (whoNotified.getState().colour == Colour::White) {
this->theDisplay[whoNotified.getInfo().row][whoNotified.getInfo().col] = 'W';
} else {
this->theDisplay[whoNotified.getInfo().row][whoNotified.getInfo().col] = '-';
}
}
}
std::ostream & operator<<(std::ostream &out, const TextDisplay &td) {
for (int height = 0; height < td.theDisplay.size(); ++height) {
for (int width = 0; width < td.theDisplay.size(); ++width) {
std::cout << td.theDisplay[height][width];
}
std::cout << std::endl;
}
return out;
}
| true |
ecb61c94a484ecedd35f0a532528ad31393ee299 | C++ | MVinogradof/OOP_6 | /graph.cpp | UTF-8 | 337 | 3.015625 | 3 | [] | no_license | #include "graph.h"
graph::graph()
{
m = nullptr;
}
graph::~graph()
{
if (m != nullptr) delete m;
}
void graph::new_matrix(int size)
{
m = new matrix(size);
}
int graph::get_n()
{
return m->n;
}
int graph::get_a(int i, int j)
{
return m->a[i][j];
}
void graph::set_a(int a, int i, int j)
{
m->a[i][j] = a;
}
| true |
d22bf383d1b8c5eee7295ff9625c0d21c5021212 | C++ | n0bdy/OJcode | /template/BKDRhash.cpp | UTF-8 | 930 | 2.90625 | 3 | [] | no_license | #include <algorithm>
#include <cstdio>
#include <cstring>
const int MAXN = 1e6;
const int MOD = 1e18 + 3;
const int BASE = 1009;
int n; //length of string
char s[MAXN]; //input string
int h[MAXN], pow[MAXN];
long long norm(long long num)
{
while (num >= MOD)
{
num -= MOD;
}
while (num < 0)
{
num += MOD;
}
return num;
}
long long mul(long long a, long long b)
{
long long quotient = ((long double)a * b) / MOD;
return norm(a * b - quotient * MOD);
}
void preCalc()
{
n = std::strlen(s);
h[0] = 0;
for (int i = 0; i < n; i++)
{
h[i + 1] = norm(mul(h[i], BASE) + s[i] - 'a' + 1);
}
pow[0] = 1;
for (int i = 1; i < n; i++)
{
pow[i] = mul(pow[i - 1], BASE);
}
}
long long getHash(int l, int r) //l=left limit in string s(starting from 0),r=right limit add one in string s
{
return norm(h[r] - mul(h[l], pow[r - l]));
} | true |
c95f7b53d84dcfcc7963c234c12c5769869715fb | C++ | memo/ofxMSAControlFreakGui | /example/src/example-Gui.cpp | UTF-8 | 1,874 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "ofMain.h"
// This is a very minimal example that shows how to link the Parameters created in ofxMSAControlFreak to a GUI
// In this case using a simple custom opengl GUI
// include the ControlFreakGui
#include "ofxMSAControlFreakGui.h"
// Check the contents of ofxMSAControlFreakTutorial.h to see how to use ofxMSAControlFreak to create and use parameters
#include "ofxMSAControlFreakTutorial.h"
// Normally you wouldn't include this file, instead just define your own Parameters
// I just put everything in this file so I can keep this code separate and reuse it in different addons
class ofApp : public ofBaseApp {
public:
// declare a Gui
msa::controlfreak::gui::Gui gui;
// this is defined in ofxMSAControlFreakTutorial.h
TutorialModule tutorial;
void setup() {
// initialise all parameters
tutorial.setup();
// create a GUI out of the parameters. The GUI will constuct all the nessecary controls and link each one to the relevant parameters
// this is in effect duplicating the structure of the params in the GUI, so it isn't ideal
// this is why I now prefer ImGui (and ofxMSAControlFreakImGui https://github.com/memo/ofxMSAControlFreakImGui)
gui.addPage(tutorial.params);
// default keys are space (toggle show/hide)
gui.setDefaultKeys(true);
}
void draw() {
tutorial.draw();
}
void keyPressed(int key) {
switch (key) {
case 's': tutorial.params.saveXmlValues(); break;
case 'S': tutorial.params.saveXmlSchema(); break;
case 'l': tutorial.params.loadXmlValues(); break;
case 'L': tutorial.params.loadXmlSchema(); break;
}
}
};
//========================================================================
int main() {
ofSetupOpenGL(1100, 800, OF_WINDOW);
ofRunApp(new ofApp);
}
| true |
9405b2e3f63a9cd70571e01fd1e87fc50750e10a | C++ | clapmyhands/codeforces | /solutions/71A.cpp | UTF-8 | 359 | 3.015625 | 3 | [
"MIT"
] | permissive | #include <iostream>
int main() {
std::string word;
int n;
int len = 0;
std::cin >> n;
while(n--){
std::cin >> word;
len = word.length();
if(len<=10){
std::cout << word << std::endl;
} else {
std::cout << word[0] << len-2 << word[len-1] << std::endl;
}
}
return 0;
} | true |
5db5b1a57034f7ea9ad44e80ae2c57bfba3667dd | C++ | hlah/ReplicatorEngine | /include/replicator/engine.hpp | UTF-8 | 1,459 | 2.5625 | 3 | [] | no_license | #ifndef _REPLICATOR_ENGINE_HPP_
#define _REPLICATOR_ENGINE_HPP_
#include "state.hpp"
#include "input.hpp"
#include "window.hpp"
#include "spdlog/spdlog.h"
#include <string>
#include <cmath>
class Engine {
public:
// Constructor
Engine() : _running{false}, _width{512}, _height{512}, _title{} {}
// run engine
void run(State* state_ptr);
// stop engine
void stop();
// Setters
void set_window_size(unsigned int width, unsigned int height);
void set_window_title(const std::string& title);
void set_aa(unsigned int aa) { _aa = aa; };
ActionId get_action_id( const std::string& name );
void bind_button( std::variant<Key, MouseButton> button, const std::string& action_name );
private:
bool _running;
unsigned int _width, _height, _aa = 0;
std::string _title;
ActionId _next_action_id = 0;
std::unordered_map<ActionId, std::string> _actions;
std::unordered_map<std::variant<Key, MouseButton>, ActionId> _bindings;
// process actions
void _process_actions( entt::registry& registry, State* state_ptr, Window& window );
void _process_transition( State::Transition trans );
#ifdef DEBUG
spdlog::level::level_enum _loglevel = spdlog::level::debug;
#else
spdlog::level::level_enum _loglevel = spdlog::level::info;
#endif
};
#endif // _REPLICATOR_ENGINE_HPP_
| true |
de190627d87947d71af0ea8b4113e58c624c201e | C++ | stepan163/Lessons | /2/Examples/three_words.cpp | UTF-8 | 440 | 3.5 | 4 | [] | no_license | #include <std_lib.h>
int main()
{
string word1, word2, word3;
string temp;
cout << "Введите 3 слова\n";
cin >> word1 >> word2 >> word3;
if (word1 > word2) {
temp = word1;
word1 = word2;
word2 = temp;
}
if (word2 > word3) {
temp = word2;
word2 = word3;
word3 = temp;
}
if (word1 > word2) {
temp = word1;
word1 = word2;
word2 = temp;
}
cout << word1 << ", " << word2 << ", " << word3 << '\n';
}
| true |
ec96b025d0a8e2a6d1e2911164659e5b527f40b4 | C++ | moyaog/Lab3 | /old_keyboard/old_keyboard.ino | UTF-8 | 1,755 | 3.140625 | 3 | [] | no_license |
/* the tutorial code for 3x4 Matrix Keypad with Arduino is as
This code prints the key pressed on the keypad to the serial port*/
#include <Keypad.h>
#include <stdlib.h>
const byte Rows= 4; //number of rows on the keypad i.e. 4
const byte Cols= 3; //number of columns on the keypad i,e, 3
//we will definne the key map as on the key pad:
char keymap[Rows][Cols]=
{
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};
char buff[10];
// a char array is defined as it can be seen on the above
//keypad connections to the arduino terminals is given as:
byte rPins[Rows]= {A3,A4,A5,A6}; //Rows 0 to 3
byte cPins[Cols]= {A0,A1,A2}; //Columns 0 to 2
// command for library forkeypad
//initializes an instance of the Keypad class
Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);
void setup()
{
Serial.begin(9600); // initializing serail monitor
digitalWrite(LED_BUILTIN, HIGH);
}
//If key is pressed, this key is stored in 'keypressed' variable
//If key is not equal to 'NO_KEY', then this key is printed out
void loop()
{
int i = 0;
char keypressed=0;
Serial.println("starting main");
while(keypressed = kpd.getKey() != '#' && i < 10) {
if ((int)keypressed != 1) {
buff[i] = keypressed;
i++;
}
}
for(int l = 0; l < 10; l++) {
Serial.print(buff[l]);
Serial.print(',');
}
Serial.println("out");
int input = atoi(buff);
Serial.print("converted int ");
Serial.println(input);
for(int j = 0; j < input; j++) {
digitalWrite(LED_BUILTIN, LOW);
delay(10);
digitalWrite(LED_BUILTIN, HIGH);
delay(10);
}
for(int k = 0; k < 10; k++) {
buff[k] = 0;
}
}
| true |
5d0aac9caa735ae3f550bf35ae57155a47886769 | C++ | xinye83/leetcode | /Cpp/0257_Binary_Tree_Paths.cpp | UTF-8 | 1,149 | 3.5625 | 4 | [] | no_license | /*
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (root) {
if (!root->left && !root->right)
return {to_string(root->val)};
vector<string> ans = {};
vector<string> temp;
temp = binaryTreePaths(root->left);
ans.insert(ans.end(),temp.begin(),temp.end());
temp = binaryTreePaths(root->right);
ans.insert(ans.end(),temp.begin(),temp.end());
vector<string>::iterator it;
for (it = ans.begin(); it < ans.end(); it++)
*it = to_string(root->val)+"->"+*it;
return ans;
}
else
return {};
}
};
| true |
5e07393e45d369f92b0b74e6b0592a30e90be3aa | C++ | MiltonStanley/CPP_In_21_Days | /Week1/Day3/3_4.cpp | UTF-8 | 331 | 2.75 | 3 | [] | no_license | #include <iostream>
int main()
{
unsigned short int small_number;
small_number = 65535;
std::cout << "small number: " << small_number << std::endl;
small_number++;
std::cout << "small number: " << small_number << std::endl;
small_number++;
std::cout << "small number: " << small_number << std::endl;
return 0;
} | true |
6ff8161d551af7586c9c447c6582143e0f80d8dd | C++ | luoxz-ai/arduino-flight-controller | /src/Battery.cpp | UTF-8 | 1,143 | 2.59375 | 3 | [
"MIT"
] | permissive | // ---------------------------------------------------------------------------------------------
// Copyright (c) Akash Nag. All rights reserved.
// Licensed under the MIT License. See LICENSE.md in the project root for license information.
// ---------------------------------------------------------------------------------------------
#include "Battery.h"
Battery::Battery()
{
}
void Battery::init() const
{
analogReference(DEFAULT);
}
float Battery::getCellVoltage(const int cell) const
{
int v = analogRead(CELL_PINS[cell]);
int inpVolt = map(v, 0, 1023, 0, 500);
return(inpVolt / 100.0);
}
float Battery::getBatteryVoltage() const
{
float sum = 0;
for(int i=0; i<BATTERY_CELL_COUNT; i++) sum += getCellVoltage(i);
return sum;
}
int Battery::getPercentage() const
{
float voltage = getBatteryVoltage();
int p = ((voltage * 100) / (BATTERY_CELL_COUNT * BATTERY_CELL_FULL_THRESHOLD));
return(p < 0 ? 0 : (p > 100 ? 100 : p));
}
bool Battery::isLow() const
{
for(int i=0; i<BATTERY_CELL_COUNT; i++)
{
float cellVoltage = getCellVoltage(i);
if(cellVoltage < BATTERY_CELL_LOW_THRESHOLD) return true;
}
return false;
}
| true |