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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1b8a31a97a0326e9054a59ce4c73bf3a82fddeee | C++ | antoniofrigo/ssf | /src/scenario/falling_object_scenario.cpp | UTF-8 | 1,600 | 3.1875 | 3 | [] | no_license | #include "scenario/falling_object_scenario.hpp"
FallingObjectScenario::FallingObjectScenario(int iterations, double timestep)
: s_rows(iterations),
s_cols(4),
s_set_initial(false),
h(timestep),
model(1, s_cols),
integrator(&model, s_cols),
window() {
// Allocate memory for state and initial conditions
state = new double *[s_rows + 1];
for (int i = 0; i < s_rows + 1; ++i) {
state[i] = new double[s_cols];
}
initial = new double[s_cols];
}
FallingObjectScenario::~FallingObjectScenario() {
for (int i = 0; i < s_rows + 1; ++i) {
delete[] state[i];
}
delete[] state;
delete[] initial;
}
void FallingObjectScenario::SetInitial(double *initial_cond) {
// Set values of initial_cond array to state
for (int i = 0; i < s_cols; ++i) {
initial[i] = initial_cond[i];
state[0][i] = initial_cond[i];
}
model.SetInitial(initial_cond);
integrator.SetStepSize(h);
s_set_initial = true;
}
void FallingObjectScenario::Run() {
// Run simulation
if (s_set_initial == false) {
throw std::runtime_error("Initial condition not set in window.");
}
for (int i = 1; i < s_rows + 1; ++i) {
integrator.ComputeStep(state[i - 1], state[i]);
}
window.SetWindowDimension(1000, 1000);
window.SetWindowFPS(40);
window.SetWindowIterations(s_rows + 1);
window.SetState(state);
window.CreateWindow();
}
void FallingObjectScenario::PrintState() const {
for (int i = 0; i < s_rows + 1; ++i) {
for (int j = 0; j < s_cols; ++j) {
std::cout << state[i][j] << " ";
}
std::cout << std::endl;
}
} | true |
ff9caf5c8cc53e37b728f08e456e05afe88a55f4 | C++ | tonyxwz/leetcode | /9.Graph/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.cc | UTF-8 | 1,094 | 2.984375 | 3 | [] | no_license | #include "leetcode.h"
// all pairs shortest path
// floyd warshall
class Solution
{
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold)
{
// Matrix
vector<vector<int>> M(n, vector<int>(n, INT_MAX));
for (int i = 0; i < n; ++i)
M[i][i] = 0;
for (const auto& e : edges)
M[e[0]][e[1]] = M[e[1]][e[0]] = e[2];
// Floyd-Warshall, x: proxy node
for (int x = 0; x < n; ++x) {
for (int u = 0; u < n; ++u) {
if (u == x || M[u][x] == INT_MAX)
continue;
for (int v = 0; v < n; ++v) {
if (v == x || M[x][v] == INT_MAX)
continue;
if (M[u][v] > M[u][x] + M[x][v]) // relax if find a better route
M[u][v] = M[u][x] + M[x][v];
}
}
}
int ans = 0;
int num_reachable = INT_MAX;
for (int i = 0; i < n; ++i) {
int _num = 0;
for (const auto d : M[i])
if (d <= distanceThreshold)
_num++;
if (_num <= num_reachable) {
ans = i;
num_reachable = _num;
}
}
return ans;
}
};
| true |
a3b7238903ce9677a87e76091de3b1ca2181f90b | C++ | luckhoi56/girsLabBackEndEngine | /src/global/MetropolisGenerator.h | UTF-8 | 1,504 | 2.71875 | 3 | [] | no_license | // MetropolisGenerator.h: interface for the MetropolisGenerator class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_METROPOLISGENERATOR_H__2BDE07A9_4FBF_11D4_9894_002018557056__INCLUDED_)
#define AFX_METROPOLISGENERATOR_H__2BDE07A9_4FBF_11D4_9894_002018557056__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Parameters.h"
/* Super class for Metropolis sampling candidate generators. Generators
* support two functions:
* - generation of the candidate, conditional on the previous sample.
* - computation of transition density, conditional on the previous sample.
* These two results are used by the MetropolisSampler to generate candidates
* and to decide on acceptance or rejection of the candidate.
*/
class MetropolisGenerator
{
public:
MetropolisGenerator();
virtual ~MetropolisGenerator();
virtual bool increaseVariation() = 0;
virtual bool decreaseVariation() = 0;
virtual void setMinimumVariation() = 0;
virtual void setMaximumVariation() = 0;
virtual void init(int dimension) = 0;
/* Computes transition density from x to y. */
virtual double computeLogDensity(const Parameters & x, const Parameters & y) = 0;
/* Generates a candidate sample, conditional on previous sample. */
virtual Parameters generateCandidate(const Parameters & sample) = 0;
};
#endif // !defined(AFX_METROPOLISGENERATOR_H__2BDE07A9_4FBF_11D4_9894_002018557056__INCLUDED_)
| true |
110600495c95b2bf5a2cd82620f0842d05736c28 | C++ | Christinekrm02/c-learning | /foundations/conditionals/loops/while-loop.cpp | UTF-8 | 378 | 3.625 | 4 | [] | no_license | //while loops loops UNTIL the condition is false
#include <iostream>
using namespace std;
int main(){
int password;
int tries = 0;
cout << "Enter password \n";
cin >> password;
while(password != 54321 && tries < 2){
cout << "Try again: ";
cin >> password;
tries++;
}
if(password == 54321){
cout << "Access granted";
}
} | true |
7667bb69b38c7af98864da9b9a2b569c68185e50 | C++ | ansiwen/chromiumos-platform2 | /debugd/src/dbus_utils_unittest.cc | UTF-8 | 4,968 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "debugd/src/dbus_utils.h"
#include <limits>
#include <memory>
#include <vector>
#include <base/strings/string_number_conversions.h>
#include <dbus/dbus.h>
#include <dbus-c++/dbus.h>
#include <gtest/gtest.h>
using base::DictionaryValue;
using base::ListValue;
using base::Value;
class DBusUtilsTest : public testing::Test {
protected:
void ConvertDBusMessageToValues() {
ASSERT_TRUE(debugd::DBusMessageToValue(message_, &raw_value_));
ASSERT_NE(nullptr, raw_value_);
ASSERT_EQ(Value::TYPE_LIST, raw_value_->GetType());
ListValue* list_values = nullptr;
ASSERT_TRUE(raw_value_->GetAsList(&list_values));
values_.clear();
for (size_t i = 0; i < list_values->GetSize(); i++) {
Value* element = nullptr;
ASSERT_TRUE(list_values->Get(i, &element));
values_.push_back(element);
}
}
DBus::CallMessage message_;
std::unique_ptr<Value> raw_value_;
std::vector<Value*> values_;
};
TEST_F(DBusUtilsTest, DBusMessageToValueEmpty) {
ConvertDBusMessageToValues();
EXPECT_EQ(0, values_.size());
}
TEST_F(DBusUtilsTest, DBusMessageToValueOnePrimitive) {
DBus::MessageIter iter = message_.writer();
iter.append_bool(true);
ConvertDBusMessageToValues();
ASSERT_EQ(1, values_.size());
Value* v = values_[0];
EXPECT_EQ(Value::TYPE_BOOLEAN, v->GetType());
bool b = false;
EXPECT_TRUE(v->GetAsBoolean(&b));
EXPECT_TRUE(b);
}
TEST_F(DBusUtilsTest, DBusMessageToValueMultiplePrimitives) {
DBus::MessageIter iter = message_.writer();
int v0_old = -3;
int v1_old = 17;
iter.append_int32(v0_old);
iter.append_int32(v1_old);
ConvertDBusMessageToValues();
ASSERT_EQ(2, values_.size());
int v0_new = 0;
EXPECT_TRUE(values_[0]->GetAsInteger(&v0_new));
EXPECT_EQ(v0_old, v0_new);
int v1_new = 0;
EXPECT_TRUE(values_[1]->GetAsInteger(&v1_new));
EXPECT_EQ(v1_old, v1_new);
}
TEST_F(DBusUtilsTest, DBusMessageToValueArray) {
DBus::MessageIter iter = message_.writer();
DBus::MessageIter subiter = iter.new_array(DBUS_TYPE_INT32_AS_STRING);
int v0_old = 7;
int v1_old = -2;
subiter.append_int32(v0_old);
subiter.append_int32(v1_old);
iter.close_container(subiter);
ConvertDBusMessageToValues();
ASSERT_EQ(1, values_.size());
Value* v = values_[0];
ASSERT_EQ(Value::TYPE_LIST, v->GetType());
ListValue* lv = nullptr;
ASSERT_TRUE(v->GetAsList(&lv));
ASSERT_NE(nullptr, lv);
ASSERT_EQ(2, lv->GetSize());
Value* v0 = nullptr;
ASSERT_TRUE(lv->Get(0, &v0));
ASSERT_NE(nullptr, v0);
int v0_new;
EXPECT_TRUE(v0->GetAsInteger(&v0_new));
EXPECT_EQ(v0_old, v0_new);
Value* v1 = nullptr;
ASSERT_TRUE(lv->Get(1, &v1));
ASSERT_NE(nullptr, v1);
int v1_new;
EXPECT_TRUE(v1->GetAsInteger(&v1_new));
EXPECT_EQ(v1_old, v1_new);
}
TEST_F(DBusUtilsTest, DBusMessageToValueDictionary) {
char entry_type[5] = {
DBUS_DICT_ENTRY_BEGIN_CHAR,
DBUS_TYPE_STRING,
DBUS_TYPE_INT32,
DBUS_DICT_ENTRY_END_CHAR,
'\0'
};
DBus::MessageIter iter = message_.writer();
DBus::MessageIter subiter = iter.new_array(entry_type);
DBus::MessageIter subsubiter = subiter.new_dict_entry();
int foo_old = 17;
subsubiter.append_string("foo");
subsubiter.append_int32(foo_old);
subiter.close_container(subsubiter);
subsubiter = subiter.new_dict_entry();
int bar_old = 12;
subsubiter.append_string("bar");
subsubiter.append_int32(bar_old);
subiter.close_container(subsubiter);
iter.close_container(subiter);
ConvertDBusMessageToValues();
ASSERT_EQ(1, values_.size());
Value* v = values_[0];
EXPECT_EQ(Value::TYPE_DICTIONARY, v->GetType());
DictionaryValue* dv = nullptr;
ASSERT_TRUE(v->GetAsDictionary(&dv));
int foo_new;
ASSERT_TRUE(dv->GetInteger("foo", &foo_new));
EXPECT_EQ(foo_old, foo_new);
int bar_new;
ASSERT_TRUE(dv->GetInteger("bar", &bar_new));
EXPECT_EQ(bar_old, bar_new);
}
TEST_F(DBusUtilsTest, DBusMessageToValueIntTypes) {
DBus::MessageIter iter = message_.writer();
uint32_t uint32_max_old = std::numeric_limits<uint32_t>::max();
iter.append_uint32(uint32_max_old);
int64_t int64_min_old = std::numeric_limits<int64_t>::min();
iter.append_int64(int64_min_old);
uint64_t uint64_max_old = std::numeric_limits<uint64_t>::max();
iter.append_uint64(uint64_max_old);
ConvertDBusMessageToValues();
ASSERT_EQ(3, values_.size());
std::string uint32_max_new;
std::string int64_min_new;
std::string uint64_max_new;
ASSERT_TRUE(values_[0]->GetAsString(&uint32_max_new));
EXPECT_EQ(base::UintToString(uint32_max_old), uint32_max_new);
ASSERT_TRUE(values_[1]->GetAsString(&int64_min_new));
EXPECT_EQ(base::Int64ToString(int64_min_old), int64_min_new);
ASSERT_TRUE(values_[2]->GetAsString(&uint64_max_new));
EXPECT_EQ(base::Uint64ToString(uint64_max_old), uint64_max_new);
}
| true |
9d0c15ca880ad1154bab75fdc575a6e9255586df | C++ | vayupranaditya/data-structure-final-task | /app.cpp | UTF-8 | 21,531 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include "main.h"
#include "app.h"
#include "customer.h"
#include "product.h"
#include "rate.h"
using namespace std;
string GetOsName(){
#ifdef _WIN32
return "Windows 32-bit";
#elif _WIN64
return "Windows 64-bit";
#elif __unix || __unix__
return "Unix";
#elif __APPLE__ || __MACH__
return "macOS";
#elif __linux__
return "Linux";
#elif __FreeBSD__
return "FreeBSD";
#else
return "Other";
#endif
}
void ClearScreen(){
string os=GetOsName();
if((os=="Windows 32-bit") || (os=="Windows 64-bit")){
system("cls");
}else if(os!="macOS"){
system("clear");
}
}
string StrToLower(string str){
for(int i=0; i<str.length(); i++){
str[i]=tolower(str[i]);
}
return str;
}
vector <string> GetCommandInput(){
string input;
vector <string> commands {};
cout<<"> ";
getline(cin,input);
input=StrToLower(input);
unsigned int i,j;
i=0;
j=0;
while(i<input.length()){
if(input[i]==' '){
commands.push_back(input.substr(j,i-j));
j=i+1;
}
i++;
}
commands.push_back(input.substr(j,i-j));
return commands;
}
void HomePage(CustomerList &customer_list,
ProductList &product_list,
RateList &rate_list){
cout<<"Rate the Product v1.0\n";
cout<<"By I Gusti Bagus Vayupranaditya Putraadinatha (1301174029) and\n";
cout<<"I Gusti Bagus Agung Bayu Pramana Yudha (1301174144).\n\n";
cout<<"Type 'help' to see command list.\n\n";
vector <string> command {};
while(command.size() == 0){
command=GetCommandInput();
if(command[0]=="see"){
//see top / all
if(command.size()>1){
if(command[1]=="-all"){
//see all
ViewProductRate(product_list,rate_list);
}else if(command[1]=="-top"){
//see top
TopTenProduct(product_list);
}else{
cout<<"Usage: see filter [-all | -top]\n";
cout<<"Type 'help -see' for more info\n";
command.clear();
}
}else{
cout<<"Usage: see filter [-all | -top]\n";
cout<<"Type 'help -see' for more info\n";
command.clear();
}
}else if(command[0]=="signin"){
//signin
CustomerPointer customer=SignIn(customer_list, product_list, rate_list, NULL);
if(customer!=NULL){
Menu(customer, customer_list, product_list, rate_list);
}
break;
}else if(command[0]=="signup"){
//sign up
CustomerPointer customer=SignUp(customer_list, product_list, rate_list);
if(customer!=NULL){
Menu(customer, customer_list, product_list, rate_list);
}
break;
}else if(command[0]=="clear"){
ClearScreen();
}else if(command[0]=="help"){
//help
if(command.size()==1){
cout<<"clear\n";
cout<<" clear the screen.\n";
cout<<"exit\n";
cout<<" exit of the program.\n";
cout<<"help\n";
cout<<" see command list and description.\n";
cout<<"see object [-all | -top]\n";
cout<<" -all: see all products.\n";
cout<<" -top: see maximum 10 products with highest rate.\n";
cout<<"signin\n";
cout<<" sign into an account.\n";
cout<<"signup\n";
cout<<" sign up an account.\n";
}else{
if(command[1]=="-see"){
cout<<"see object [-all | -top]\n";
cout<<" -all: see all products.\n";
cout<<" -top: see maximum 10 products with highest rate.\n";
}else{
cout<<"Command not found. Type 'help' to see command list.\n";
}
}
}else if(command[0]=="exit"){
//exit
cout<<"See you\n";
break;
}else{
//reset
cout<<"Command not found. Type 'help' to see command list.\n";
}
if(command[0]!="exit"){
command.clear();
}
}
}
CustomerPointer SignUp(CustomerList &customer_list,
ProductList &product_list,
RateList &rate_list){
cout<<"Sign Up\n";
cout<<"Please type your credential below\n";
cout<<"Or enter '!cancel' to cancel.\n";
cout<<"User ID: ";
string user_id, user_name;
while(user_id==""){
getline(cin,user_id);
if(StrToLower(user_id)=="!cancel"){
cout<<"Sign up canceled.\n\n";
HomePage(customer_list, product_list, rate_list);
return NULL;
}
if(FindCustomerId(user_id, customer_list)!=NULL){
cout<<"User ID has been taken. Please choose a different user ID\n";
user_id="";
}
}
cout<<"User name: ";
getline(cin, user_name);
if(StrToLower(user_name)=="!cancel"){
cout<<"Sign up canceled.\n\n";
HomePage(customer_list, product_list, rate_list);
return NULL;
}
CustomerPointer customer=CreateNewCustomer(user_id, user_name);
InsertCustomer(customer, customer_list);
cout<<"Sign up as "<<INFO(customer).customer_name<<" success!\n";
//auto login
customer=SignIn(customer_list, product_list, rate_list, customer);
return customer;
}
CustomerPointer SignIn(CustomerList customer_list,
ProductList &product_list,
RateList &rate_list,
CustomerPointer customer){
if(customer==NULL){
string user_id="";
cout<<"Sign In\n";
cout<<"Please enter your credential below\n";
cout<<"Or enter '!cancel' to cancel.\n";
while(user_id==""){
cout<<"User ID: ";
getline(cin, user_id);
if(StrToLower(user_id)=="!cancel"){
cout<<"Sign in canceled.\n\n";
HomePage(customer_list, product_list, rate_list);
return NULL;
}
customer=FindCustomerId(user_id,customer_list);
if(customer==NULL){
cout<<"User ID not found. Please try again.\n";
user_id="";
}
}
}else{
customer=FindCustomerId(INFO(customer).customer_id, customer_list);
}
cout<<"Signed in as "<<INFO(customer).customer_name<<"!\n\n";
return customer;
}
void Menu(CustomerPointer user,
CustomerList &customer_list,
ProductList &product_list,
RateList &rate_list){
vector <string> command {};
cout<<"Hi, "<<INFO(user).customer_name<<"!\n";
if(INFO(user).customer_id=="admin"){
//admin list
while(command.size()==0){
command=GetCommandInput();
if(command[0]=="help"){
//help
if(command.size()==1){
cout<<"add\n";
cout<<" add a product.\n";
cout<<"clear\n";
cout<<" clear the screen.\n";
cout<<"delete object [-customer | -product]\n";
cout<<" -customer: delete a customer.\n";
cout<<" -product: delete a product.\n";
cout<<"exit\n";
cout<<" exit of the program.\n";
cout<<"help\n";
cout<<" see command list and description.\n";
cout<<"see object [-customer | -products | -rates]\n";
cout<<" -customer: see all customers.\n";
cout<<" -products: see all products.\n";
cout<<" -rates: see all rates.\n";
cout<<"signout\n";
cout<<" sign out of your account.\n";
cout<<"update\n";
cout<<" update a product data.\n";
}else{
if((command[0]=="help")&&(command[1]=="-see")){
cout<<"see -rates filter [-customer | -product]\n";
cout<<" -customer: see all rates made with a customer.\n";
cout<<" -product: see all rates to a product.\n";
}else{
cout<<"Command not found. Type 'help' to see command list.\n";
}
}
}else if(command[0]=="see"){
//see
if(command.size()>1){
if(command[1]=="-customers"){
//see customers
ViewCustomer(customer_list);
}else if(command[1]=="-products"){
//see products
ViewProduct(product_list);
}else if(command[1]=="-rates"){
//see rates
if(command.size()>2){
//see rates by
if(command[2]=="-customer"){
//see rates by customer X
AdminSeeRateByCustomer(customer_list,rate_list);
}else if(command[2]=="-product"){
//see rates by product X
AdminSeeRateByProduct(product_list,rate_list);
}else{
//wrong input
cout<<"Usage: see -rates filter [-customer | -product]\n";
cout<<"Type 'help -see' for more info\n";
}
}else{
ViewAllRate(rate_list);
}
}else{
//wrong input
cout<<"Usage: see object [-customers | -products | -rates] filter [-customer | -product]\n";
cout<<"Type 'help -see' for more info\n";
}
}else{
cout<<"Usage: see object [-customers | -products | -rates] filter [-customer | -product]\n";
cout<<"Type 'help -see' for more info\n";
}
}else if(command[0]=="add"){
//add product
AdminAddProduct(product_list);
}else if(command[0]=="delete"){
//delete
if(command.size()>1){
if(command[1]=="-customer"){
//delete customer
AdminDeleteCustomer(customer_list,rate_list);
}else if(command[1]=="-product"){
//delete product
AdminDeleteProduct(product_list,rate_list);
}else{
//wrong input
cout<<"Usage: delete object [-customer | -product]\n";
cout<<"Type 'help -delete' for more info\n";
}
}else{
//wrong input
cout<<"Usage: delete object [-customer | -product]\n";
cout<<"Type 'help -delete' for more info\n";
}
}else if(command[0]=="clear"){
ClearScreen();
}else if(command[0]=="update"){
//update product
AdminUpdateProduct(product_list);
}else if(command[0]=="signout"){
//sign out
HomePage(customer_list,product_list,rate_list);
break;
}else if(command[0]=="exit"){
//exit
cout<<"See you\n";
break;
}else{
cout<<"Command not found. Type 'help' to see command list.\n";
}
command.clear();
}
}else{
//customer list
while(command.size()==0){
command=GetCommandInput();
if(command[0]=="help"){
//help
if(command.size()==1){
cout<<"clear\n";
cout<<" clear the screen.\n";
cout<<"delete\n";
cout<<" delete your rate.\n";
cout<<"exit\n";
cout<<" exit of the program.\n";
cout<<"help\n";
cout<<" see command list and description.\n";
cout<<"rate\n";
cout<<" rate a product.\n";
cout<<"see\n";
cout<<"signout\n";
cout<<" sign out of your account.\n";
cout<<"udate\n";
cout<<" update your account.\n";
}else{
if(command[0]=="help"){
if(command[1]=="-see"){
cout<<"see object [-products | -rates]\n";
cout<<" -products: see all your rated products.\n";
cout<<" -rates: see all your rates.\n";
}else{
cout<<"Command not found. Type 'help' to see command list.\n";
}
}else{
cout<<"Command not found. Type 'help' to see command list.\n";
}
}
}else if(command[0]=="rate"){
//input rate
UserInputRate(user,product_list,rate_list);
}else if(command[0]=="delete"){
//delete rate
UserDeleteRate(user,product_list,rate_list);
}else if(command[0]=="see"){
//view
if(command.size()==2){
if(command[1]=="-products"){
//see products
ViewProduct(product_list);
}else if(command[1]=="-rates"){
//see my rates
ViewRateByCustomer(user,rate_list);
}else{
cout<<"Usage: see object [-products | -rates]\n";
cout<<"Type 'help -see' for more info\n";
}
}else{
cout<<"Usage: see object [-products | -rates]\n";
cout<<"Type 'help -see' for more info\n";
}
}else if(command[0]=="update"){
//update account
UserUpdate(user,customer_list);
}else if(command[0]=="clear"){
ClearScreen();
}else if(command[0]=="signout"){
//signout
HomePage(customer_list,product_list,rate_list);
break;
}else if(command[0]=="exit"){
cout<<"See you\n";
break;
}else{
if(command[0]!=""){
cout<<"Command not found. Type 'help' to see command list.\n";
}
}
command.clear();
}
}
}
void TopTenProduct(ProductList product_list){
if(FIRST(product_list)!=NULL){
ProductPointer product,max;
int nums=CountProduct(product_list);
if(nums>10){
for(int i=1;i<=10;i++){
product=FIRST(product_list);
max=product;
while(product!=NULL){
if(INFO(product).average_product>INFO(max).average_product){
max=product;
}
product=NEXT(product);
}
DeleteProduct(max,product_list);
cout<<INFO(max).product_name<<": "<<INFO(max).average_product<<endl;
}
}else{
for(int i=1;i<=nums;i++){
product=FIRST(product_list);
max=product;
while(product!=NULL){
if(INFO(product).average_product>INFO(max).average_product){
max=product;
}
product=NEXT(product);
}
DeleteProduct(max,product_list);
cout<<INFO(max).product_name<<": "<<INFO(max).average_product<<endl;
}
}
}
}
void AdminAddProduct(ProductList &product_list){
string product_name;
ProductPointer product;
do{
cout<<"Enter new product name (or type '!cancel' to cancel): ";
getline(cin,product_name);
if(product_name=="!cancel"){
cout<<"Add product canceled.\n";
break;
}
product=FindProduct(product_name, product_list);
if(product!=NULL){
cout<<"Product has already registered. Please try a new one.\n";
}
}while(product!=NULL);
if(product_name!="!cancel"){
product=CreateNewProduct(product_name);
InsertProduct(product,product_list);
cout<<"You have successfully added "<<product_name<<endl;
}
}
void AdminDeleteCustomer(CustomerList &customer_list,
RateList &rate_list){
string customer_id;
CustomerPointer customer;
ViewCustomer(customer_list);
do{
cout<<"Enter customer ID (or type '!cancel' to cancel): ";
getline(cin,customer_id);
if(customer_id=="!cancel"){
cout<<"Delete customer canceled.\n";
break;
}
customer=FindCustomerId(customer_id,customer_list);
if(customer==NULL){
cout<<"Customer ID not found.\n";
}
}while(customer==NULL);
if(customer_id!="!cancel"){
DeleteCustomer(customer,customer_list);
cout<<"auu\n";
DeleteRateByCustomer(customer,rate_list);
cout<<INFO(customer).customer_name<<" ("<<INFO(customer).customer_id<<") has been deleted.\n";
}
}
void AdminDeleteProduct(ProductList &product_list,
RateList &rate_list){
string product_name;
ProductPointer product;
ViewProduct(product_list);
do{
cout<<"Enter product name (or type '!cancel' to cancel): ";
getline(cin,product_name);
if(product_name=="!cancel"){
cout<<"Delete product canceled.\n";
break;
}
product=FindProduct(product_name,product_list);
if(product==NULL){
cout<<"Product not found.\n";
}
}while(product==NULL);
if(product_name!="!cancel"){
DeleteProduct(product,product_list);
DeleteRateByProduct(product,rate_list);
cout<<INFO(product).product_name<<" has been deleted.\n";
}
}
void AdminSeeRateByCustomer(CustomerList customer_list,
RateList rate_list){
string customer_id;
CustomerPointer customer;
ViewCustomer(customer_list);
do{
cout<<"Enter customer ID (or type '!cancel' to cancel): ";
getline(cin,customer_id);
if(customer_id=="!cancel"){
cout<<"See rate by customer canceled.\n";
break;
}
customer=FindCustomerId(customer_id,customer_list);
if(customer==NULL){
cout<<"Customer ID not found.\n";
}
}while(customer==NULL);
if(customer_id!="!cancel"){
ViewRateByCustomer(customer,rate_list);
}
}
void AdminSeeRateByProduct(ProductList product_list,
RateList rate_list){
string product_name;
ProductPointer product;
ViewProduct(product_list);
do{
cout<<"Enter product name (or type '!cancel' to cancel): ";
getline(cin,product_name);
if(product_name=="!cancel"){
cout<<"See rate by product canceled.\n";
break;
}
product=FindProduct(product_name,product_list);
if(product==NULL){
cout<<"Product name not found.\n";
}
}while(product==NULL);
if(product_name!="!cancel"){
ViewRateByProduct(product,rate_list);
}
}
void AdminUpdateProduct(ProductList product_list){
string product_name,new_product_name;
ProductPointer product,new_product;
ViewProduct(product_list);
do{
cout<<"Enter product name (or type '!cancel' to cancel): ";
getline(cin,product_name);
if(product_name=="!cancel"){
cout<<"Update product canceled.\n";
break;
}
product=FindProduct(product_name,product_list);
if(product==NULL){
cout<<"Product name not found.\n";
}
}while(product==NULL);
if(product_name!="!cancel"){
do{
cout<<"Enter new product name (or type '!cancel' to cancel): ";
getline(cin,new_product_name);
if(new_product_name=="!cancel"){
cout<<"Update product canceled.\n";
break;
}
new_product=FindProduct(new_product_name,product_list);
if(new_product!=NULL){
cout<<"Product name has been used. Please try again with different one.\n";
}
}while(new_product!=NULL);
}
if((product_name!="!cancel")&&(new_product_name!="!cancel")){
UpdateProduct(product,new_product_name);
}
}
void UserInputRate(CustomerPointer user,
ProductList product_list,
RateList &rate_list){
if(!IsProductListEmpty(product_list)){
string product_name,point_string;
int point;
ProductPointer product;
RatePointer rate;
ViewProduct(product_list);
do{
cout<<"Enter product name (or type '!cancel' to cancel): ";
getline(cin,product_name);
if(product_name=="!cancel"){
cout<<"Rate canceled.\n";
break;
}
product=FindProduct(product_name, product_list);
if(product==NULL){
cout<<"Product not found. Please try again.\n";
}
}while(product==NULL);
if(product_name!="!cancel"){
do{
cout<<"Score for "<<product_name<<"(0-5): ";
getline(cin,point_string);
if((point_string.length()!=1) || (point_string[0]<48) || (point_string[0]>53)){
cout<<"Score range is 0-5. Please try again.\n";
}
}while((point_string.length()!=1) || (point_string[0]<48) || (point_string[0]>53));
point=stoi(point_string);
rate=CreateNewRate(point,user,product);
InsertRate(rate,rate_list);
cout<<"You have successfully rated "<<product_name<<endl;\
}
}else{
cout<<"There is no product at this time.\n";
}
}
void UserDeleteRate(CustomerPointer user,
ProductList product_list,
RateList &rate_list){
string product_name;
ProductPointer product;
RatePointer rate;
ViewRateByCustomer(user,rate_list);
do{
cout<<"Enter product name (or type '!cancel' to cancel): ";
getline(cin,product_name);
if(product_name=="!cancel"){
cout<<"Delete rate canceled.\n";
break;
}
product=FindProduct(product_name,product_list);
if(product==NULL){
cout<<"Product not found. Please try again.\n";
}
rate=FindRate(user,product,rate_list);
if((product!=NULL) && (rate==NULL)){
cout<<"You did not rate "<<product_name<<". Please try again.\n";
}
}while((product==NULL) || (rate==NULL));
if(product_name!="!cancel"){
DeleteRate(rate,rate_list);
cout<<"Delete rate of "<<INFO(PRODUCT(rate)).product_name<<" success!\n";
}
}
void UserUpdate(CustomerPointer &customer,
CustomerList &customer_list){
string customer_id,customer_name;
CustomerPointer check_customer;
cout<<"Your customer ID: "<<INFO(customer).customer_id<<endl;
cout<<"Your customer name: "<<INFO(customer).customer_name<<endl;
do{
cout<<"Enter new ID (type your existing id to keep it or type '!cancel' to cancel): ";
getline(cin,customer_id);
if(customer_id=="!cancel"){
cout<<"Update account canceled.\n";
break;
}
check_customer=FindCustomerId(customer_id,customer_list);
if((check_customer!=customer) && (check_customer!=NULL)){
cout<<"User ID has been used. Please try another one.\n";
}
}while((check_customer!=customer) && (check_customer!=NULL));
if(customer_id!="!cancel"){
cout<<"Enter new name (type your existing name to keep it or type '!cancel' to cancel): ";
getline(cin,customer_name);
if(customer_name=="!cancel"){
cout<<"Update account canceled.\n";
}else{
UpdateCustomer(customer,customer_id,customer_name,customer_list);
}
}
} | true |
3d71d7dc5ab0e0458beceee3000f4f795a26836c | C++ | alexdreamwalker/qt-graph-builder | /graph.cpp | UTF-8 | 5,540 | 2.765625 | 3 | [] | no_license | #include "graph.h"
#include <QDebug>
Graph::Graph(QGraphicsItem *parent) :
QGraphicsObject(parent)
{
nodes.clear();
relations.clear();
setFlag(QGraphicsItem::ItemHasNoContents,true);
}
QRectF Graph::boundingRect() const
{
return childrenBoundingRect();
}
void Graph::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(painter);
Q_UNUSED(option);
Q_UNUSED(widget);
}
void Graph::calculateTrn(int index)
{
float result=0;
Node *node = nodeAt(index);
int number=node->number();
if(number==0) result=0;
else
{
float max=0;
for(int i=0;i<relations.count();i++)
if(relations.at(i)->_to->number()==number) {
float trn = relations.at(i)->_from->trn()+relations.at(i)->Length();
if(trn>max) max=trn;
}
result=max;
}
qDebug() <<"trn" <<number <<result;
node->setTrn(result);
}
void Graph::calculateTpo(int index)
{
float result=0;
Node *node = nodeAt(index);
int number=node->number();
if(number==nodes.count()-1) result=node->trn();
else
{
float min=999;
for(int i=0;i<relations.count();i++)
if(relations.at(i)->_from->number()==number) {
float tpo = relations.at(i)->_to->tpo()-relations.at(i)->Length();
if(tpo<min) min=tpo;
}
result=min;
}
if(result<0) result=0;
qDebug() <<"tpo" <<index <<result;
node->setTpo(result);
}
void Graph::calculateTpn(int index)
{
float result=0;
Relation *relation = relations.at(index);
result=relation->_to->tpo()-relation->Length();
relation->setTpn(result);
}
void Graph::calculateTro(int index)
{
float result=0;
Relation *relation = relations.at(index);
result=relation->_from->trn()+relation->Length();
relation->setTro(result);
}
void Graph::calculateRp(int index)
{
float result=0;
Relation *relation = relations.at(index);
result=relation->_to->tpo()-relation->Length()-relation->_from->trn();
relation->setRp(result);
}
void Graph::calculateRsv(int index)
{
float result=0;
Relation *relation = relations.at(index);
result=relation->_to->trn()-relation->Length()-relation->_from->trn();
relation->setRsv(result);
}
void Graph::findCritical()
{
_minLength = 0;
for(int i=0;i<nodes.count();i++) {
calculateTrn(i);
}
for(int i=nodes.count()-1;i>-1;i--) {
calculateTpo(i);
}
for(int i=0;i<relations.count();i++)
{
bool okay = true;
if(relations.at(i)->_from->trn()!=relations.at(i)->_from->tpo()) okay=false;
if(relations.at(i)->_to->trn()!=relations.at(i)->_to->tpo()) okay=false;
if((relations.at(i)->_to->trn()-relations.at(i)->_from->trn())!=relations.at(i)->Length()) okay=false;
relations.at(i)->setCritical(okay);
if(okay) _minLength=_minLength+relations.at(i)->Length();
}
}
QTableWidget* Graph::makeTable()
{
for(int i=0;i<relations.count();i++) calculateTpn(i);
for(int i=0;i<relations.count();i++) calculateTro(i);
for(int i=0;i<relations.count();i++) calculateRp(i);
for(int i=0;i<relations.count();i++) calculateRsv(i);
QTableWidget * table = new QTableWidget(relations.count(),9);
table->setHorizontalHeaderItem(0, new QTableWidgetItem("Работа"));
table->setHorizontalHeaderItem(1, new QTableWidgetItem("Время t[i][j]"));
table->setHorizontalHeaderItem(2, new QTableWidgetItem("Начало t[i][рн]"));
table->setHorizontalHeaderItem(3, new QTableWidgetItem("Окончание t[ij][po]"));
table->setHorizontalHeaderItem(4, new QTableWidgetItem("Начало t[ij][пн]"));
table->setHorizontalHeaderItem(5, new QTableWidgetItem("Окончание t[j][по]"));
table->setHorizontalHeaderItem(6, new QTableWidgetItem("Полный резерв R[ij][п]"));
table->setHorizontalHeaderItem(7, new QTableWidgetItem("Свободный резерв R[ij][св]"));
table->setHorizontalHeaderItem(8, new QTableWidgetItem("Принадл. крит. пути"));
for(int i=0;i<relations.count();i++)
for(int j=0;j<9;j++)
table->setItem(i,j,new QTableWidgetItem());
for(int i=0;i<relations.count();i++)
{
Relation *relation = relations.at(i);
TimeLine line;
char c = 'A'+relation->number();
table->item(i,0)->setText(QString(c));
table->item(i,1)->setText(QString::number(relation->Length()));
line.length=relation->Length();
table->item(i,2)->setText(QString::number(relation->_from->trn()));
line.trn=relation->_from->trn();
table->item(i,3)->setText(QString::number(relation->tro()));
line.tro=relation->tro();
table->item(i,4)->setText(QString::number(relation->tpn()));
line.tpn=relation->tpn();
table->item(i,5)->setText(QString::number(relation->_to->tpo()));
line.tpo=relation->_to->tpo();
table->item(i,6)->setText(QString::number(relation->Rp()));
line.rp=relation->Rp();
table->item(i,7)->setText(QString::number(relation->Rsv()));
line.rsv=relation->Rsv();
if(relation->critical()) table->item(i,8)->setText("+");
else table->item(i,8)->setText("-");
line.critical=relation->critical();
line.number=i;
timetable->addLine(line);
}
table->resizeColumnsToContents();
table->resizeRowsToContents();
return table;
}
| true |
507a167026752273703f8a7dba986d1ad6511eed | C++ | rishabh26malik/Karumanchi-Codes | /Linked lists/y_in_list_way_1.cpp | UTF-8 | 2,137 | 3.734375 | 4 | [] | no_license | /*
Suppose there are two singly linked lists both of which intersect at some point
and become a single linked list. The head or start pointers of both the lists are known, but
the intersecting node is not known. Also, the number of nodes in each of the lists before
they intersect is unknown and may be different in each list. List1 may have n nodes before
it reaches the intersection point, and List2 might have m nodes before it reaches the
intersection point where m and n may be m = n,m < n or m > n. Give an algorithm for
finding the merging point.
*/
#include<bits/stdc++.h>
#include<iostream>
#include<stack>
using namespace std;
class node
{
public:
int data,flag=0;
node *next;
};
void printList(node *head)
{
while(head!=NULL)
{
cout<<(head->data)<<" ";
head=head->next;
}
cout<<endl;
}
void insert_at_end(node **head, int value)
{
node *tmp=new node();
tmp->data=value;
tmp->next=NULL;
if(*head==NULL)
{
*head=tmp;
return ;
}
node *ptr=*head;
while(ptr->next != NULL)
{
ptr=ptr->next;
}
ptr->next=tmp;
return ;
}
void detect_y(node *head1, node *head2)
{
stack <node*>s1;
stack <node*>s2;
node *tmp=head1,*prev;
while(tmp!=NULL)
{
s1.push(tmp);
tmp=tmp->next;
}
tmp=head2;
while(tmp!=NULL)
{
s2.push(tmp);
tmp=tmp->next;
}
if(s1.top()==s2.top())
{
prev=s1.top();
s1.pop();
s2.pop();
while(!s1.empty() && !s2.empty() )
{
if(s1.top()==s2.top())
{
prev=s1.top();
s1.pop();
s2.pop();
}
else
break;
}
cout<<"y detected at node "<<(prev->data)<<endl;
return ;
}
cout<<"y not found"<<endl;
}
int main()
{
node *head1=NULL, *head2=NULL,*tmp;
int n;
cout<<"enter numbers to insert into list 1, -1 to stop : ";
while(1)
{
cin>>n;
if(n==-1)
break;
insert_at_end(&head1,n);
}
printList(head1);
cout<<"enter numbers to insert into list 2, -1 to stop : ";
while(1)
{
cin>>n;
if(n==-1)
break;
insert_at_end(&head2,n);
}
printList(head2);
tmp=head1;
while(tmp->next != NULL)
{
tmp=tmp->next;
}
tmp->next=head2->next->next;
printList(head1);
printList(head2);
detect_y(head1, head2);
return 0;
}
| true |
51fa26be8de51ac4775a83f5a2de52fc2ec5c580 | C++ | superrabbit11223344/c--Tutorial | /src/operators/arrowOperator2.cpp | UTF-8 | 556 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <string>
class Entity
{
public:
int x;
void Print() const { std::cout << "Hello!" << std::endl; }
};
class ScopedPtr
{
private:
Entity* m_Obj;
public:
ScopedPtr(Entity* entity)
: m_Obj(entity)
{
}
~ScopedPtr()
{
delete m_Obj;
}
Entity* operator->()
{
return m_Obj;
}
const Entity* operator->() const
{
return m_Obj;
}
};
int main()
{
const ScopedPtr entity = new Entity();
entity->Print();
std::cin.get();
} | true |
78dfc87c458f13dbaeee69b0f9aad75c16639ff6 | C++ | shruti-2522/c- | /OOPS/Inheritancee/multiple_inheeritance.cpp | UTF-8 | 624 | 3.9375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a=n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b=n;
}
};
class C:public A,public B
{
public:
void display()
{
cout<<"The value of a="<<a<<endl;
cout<<"Thee value of b="<<b<<endl;
cout<<"Sum="<<a+b;
}
};
int main()
{
C a1;
a1.get_a(10);
a1.get_b(20);
a1.display();
}
/*OUTPUT:
The value of a=10
Thee value of b=20
Sum=30
*/ | true |
bb65753564ba5646f0da6bf1ead13ae30065b959 | C++ | masmowa/samples | /JobSearchLog1/include/EmployerContact.h | UTF-8 | 3,282 | 3.328125 | 3 | [] | no_license | #ifndef EMPLOYERCONTACT_H
#define EMPLOYERCONTACT_H
#include <string>
class EmployerContact
{
public:
EmployerContact(unsigned int type=0, const char* position="", unsigned int howcontacted=0, const char* employername="");
EmployerContact(const EmployerContact &other);
EmployerContact& operator=(const EmployerContact &other);
virtual ~EmployerContact();
unsigned int GetCounter() { return m_Counter; }
void SetCounter(unsigned int val) { m_Counter = val; }
unsigned int Gettype() { return m_type; }
void Settype(unsigned int val) { m_type = val; }
unsigned int Gethowcontacted() { return m_howcontacted; }
void Sethowcontacted(unsigned int val) { m_howcontacted = val; }
std::string Getposition() { return m_position; }
void Setposition(std::string val) { m_position = val; }
std::string Getemployername() { return m_employername; }
void Setemployername(std::string val) { m_employername = val; }
std::string Getaddress() { return m_address; }
void Setaddress(std::string val) { m_address = val; }
std::string Getstate() { return m_state; }
void Setstate(std::string val) { m_state = val; }
std::string Getcity() { return m_city; }
void Setcity(std::string val) { m_city = val; }
std::string Gettelephone() { return m_telephone; }
void Settelephone(std::string val) { m_telephone = val; }
std::string Getfax() { return m_fax; }
void Setfax(std::string val) { m_fax = val; }
std::string Getname_or_position_of_person_contacted() { return m_name_or_position_of_person_contacted; }
void Setname_or_position_of_person_contacted(std::string val) { m_name_or_position_of_person_contacted = val; }
std::string Getemail() { return m_email; }
void (std::string val) { m_email = val; }
std::string Getweb_site() { return m_web_site; }
void Setweb_site(std::string val) { m_web_site = val; }
std::string Getjob_reference_number() { return m_job_reference_number; }
void Setjob_reference_number(std::string val) { m_job_reference_number = val; }
std::string Getagency_name() { return m_agency_name; }
void Setagency_name(std::string val) { m_agency_name = val; }
std::string Getagency_contact() { return m_agency_contact; }
void Setagency_contact(std::string val) { m_agency_contact = val; }
std::string Getnews_paper_name() { return m_news_paper_name; }
void Setnews_paper_name(std::string val) { m_news_paper_name = val; }
protected:
private:
unsigned int m_Counter;
unsigned int m_type;
unsigned int m_howcontacted;
std::string m_position;
std::string m_employername;
std::string m_address;
std::string m_state;
std::string m_city;
std::string m_telephone;
std::string m_fax;
std::string m_name_or_position_of_person_contacted;
std::string m_email;
std::string m_web_site;
std::string m_job_reference_number;
std::string m_agency_name;
std::string m_agency_contact;
std::string m_news_paper_name;
};
#endif // EMPLOYERCONTACT_H
| true |
1fbe69ed5c81af27862a6a790d1a533b30c3f7ba | C++ | thaarres/ExoDiBosonAnalysis | /src/BinomialEff.cc | UTF-8 | 1,941 | 2.796875 | 3 | [] | no_license | #include "Analysis/PredictedDistribution/interface/BinomialEff.h"
#include <cmath>
double BinomialEff::eup() const
{
double upper;
int imax = (int) std::floor(Np);
double CL = 0.1585;
if ( Np == Nt ) {
upper = 1.0;
} else {
double d = 1.0;
double p = 1.0;
double s = 0.0;
double diff = 999.0;
double eps = std::sqrt( (Np*(Nt-Np))/(Nt*Nt*Nt) )/10.0;
for (int j=0; diff > eps ; ++j ) {
double pold = p;
((s-CL) > 0.0) ? d = std::abs(d/2.0) : d = -1.0*std::abs(d/2.0);
p += d;
double r = std::log(p/(1.0-p));
double term = Nt*std::log(1.0-p);
s = std::exp(term);
for (int i=0; i!=imax ; ++i) {
double temp = (Nt - float(i))/float(i+1);
term = term + r + std::log(temp);
s += std::exp(term);
}
if ( pold != 0.0 ) diff = std::abs(pold-p)/std::abs(pold);
}
upper = p;
} // --- endif
return (upper - eff());
} // --- eup()
// ===========================
// --- ELO
// ===========================
double BinomialEff::elo() const
{
double lower;
int imax = (int) std::floor(Np)-1;
double CL = 0.8415;
if ( Np == 0.0 ) {
lower = 1.0;
} else {
double d = 1.0;
double p = 1.0;
double s = 0.0;
double diff = 999.0;
double eps = std::sqrt( (Np*(Nt-Np))/(Nt*Nt*Nt) )/10.0;
for (int j=0; diff > eps ; ++j ) {
double pold = p;
((s-CL) > 0.0) ? d = std::abs(d/2.0) : d = -1.0*std::abs(d/2.0);
p += d;
double r = std::log(p/(1.0-p));
double term = Nt*std::log(1.0-p);
s = std::exp(term);
for (int i=0; i!=imax ; ++i) {
double temp = (Nt - float(i))/float(i+1);
term = term + r + std::log(temp);
s += std::exp(term);
}
if ( pold != 0.0 ) diff = std::abs(pold-p)/std::abs(pold);
}
lower = p;
} // --- endif
return (eff() - lower);
} // --- elo()
// ===========================
| true |
de2a5c1afd1352392488c2616f030e18dfc4cd71 | C++ | joshuaba/CPSC350 | /Assignment1.cpp | UTF-8 | 11,277 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(int argc, char** argv)
{
string inputFile;
if (argc > 1)
{
inputFile = argv[1];
}
else
{
cout << "Need an input, please!" << endl;
exit(1);
}
//declare inputStream -- reading from file
ifstream inputStream;
inputStream.open(inputFile);
if(inputStream.fail())
{
cout << "Problem opening the file!" << endl;
exit(1);
}
ofstream outputStream;
outputStream.open("Joshua.out", ios::app);
if(outputStream.fail())
{
cout << "Problem creating or opening the output file!" << endl;
exit(1);
}
//set the file output to 2 decimal places for float or double values
outputStream.setf(ios::fixed);
outputStream.setf(ios::showpoint);
outputStream.precision(2);
//Set the console output to 2 decimal places for float or double values
outputStream.setf(ios::fixed);
outputStream.setf(ios::fixed);
outputStream.precision(2);
//print out header information in output file
outputStream << "Joshua Barrs" << endl
<< "002294736" << endl
<< "barrs@chapman.edu" << endl
<< "CPSC350 -- 01" << endl
<< "Assignment1" << endl << endl;
//read the lines of the file to determine the mean string length
int stringCount = 0; //number of strings in the file
int sizeOfAllStrings = 0; //the total size of all the string lengths
string allDNASequences; //a string containing all of the valid DNA sequences from the various lines of the file
while(!inputStream.eof())
{
string sequence;
getline(inputStream, sequence);
stringCount++;
for(int i = 0; i < sequence.size(); ++i)
{
if(sequence[i]=='A' || sequence[i] == 'a' || sequence[i]=='C' || sequence[i] == 'c' || sequence[i]=='T' || sequence[i] == 't' || sequence[i] == 'G' || sequence[i] == 'g')
{
sizeOfAllStrings++;
allDNASequences += sequence[i];
}
}
}
//capitalize all the sequences passed into allDNASequences
for (int i = 0; i <= allDNASequences.size(); ++i)
{
toupper(allDNASequences[i]);
}
outputStream << "All DNA sequences: " << allDNASequences << endl;
double stringSizeMean = static_cast<double>(sizeOfAllStrings) / stringCount;
outputStream << "Mean string size: " << stringSizeMean << endl;
inputStream.close();
//Now find the variance (mean had to be computed first)
inputStream.open("inputFile.txt");
double sumOfVarianceComponents;
double varianceComponent;
while(!inputStream.eof())
{
string sequence;
int sizeOfThisString;
getline(inputStream,sequence);
for(int i = 0; i < sequence.size(); ++i)
{
if(sequence[i]=='A' || sequence[i] == 'a' || sequence[i]=='C' || sequence[i] == 'c' || sequence[i]=='T' || sequence[i] == 't' || sequence[i] == 'G' || sequence[i] == 'g')
{
sizeOfThisString++;
}
}
varianceComponent = pow((sizeOfThisString - stringSizeMean), 2);
sumOfVarianceComponents += varianceComponent;
}
double variance = sumOfVarianceComponents / stringCount;
double stDev = sqrt(variance);
outputStream << "Variance is: " << variance << endl
<< "Standard deviation is: " << stDev << endl;
//code to calculate probabilities of nucleotides
double probOfA = 0, probOfG = 0, probOfT = 0, probOfC = 0;
int countOfA = 0, countOfT = 0, countOfG = 0, countOfC = 0;
for (int i = 0; i <= allDNASequences.size(); ++i)
{
if(allDNASequences[i] == 'A' || allDNASequences[i] == 'a')
{
countOfA++;
}
else if(allDNASequences[i] == 'G' || allDNASequences[i] == 'g')
{
countOfG++;
}
else if(allDNASequences[i] == 'T' || allDNASequences[i] == 't')
{
countOfT++;
}
else if(allDNASequences[i] == 'C' || allDNASequences[i] == 'c')
{
countOfC++;
}
}
outputStream << "total size of all strings: " << allDNASequences.size() << endl;
probOfA = static_cast<double>(countOfA) / sizeOfAllStrings;
probOfG = static_cast<double>(countOfG) / sizeOfAllStrings;
probOfT = static_cast<double>(countOfT) / sizeOfAllStrings;
probOfC = static_cast<double>(countOfC) / sizeOfAllStrings;
outputStream << "Probability of A: " << probOfA << endl
<< "Probability of G: " << probOfG << endl
<< "Probability of T: " << probOfT << endl
<< "Probability of C: " << probOfC << endl;
//probabilities of bigrams
int countOfAA = 0;
double probOfAA = 0;
int countOfAC = 0;
double probOfAC = 0;
int countOfAT = 0;
double probOfAT = 0;
int countOfAG = 0;
double probOfAG = 0;
int countOfCA = 0;
double probOfCA = 0;
int countOfCC = 0;
double probOfCC = 0;
int countOfCT = 0;
double probOfCT = 0;
int countOfCG = 0;
double probOfCG = 0;
int countOfTA = 0;
double probOfTA = 0;
int countOfTC = 0;
double probOfTC = 0;
int countOfTT = 0;
double probOfTT = 0;
int countOfTG = 0;
double probOfTG = 0;
int countOfGA = 0;
double probOfGA = 0;
int countOfGC = 0;
double probOfGC = 0;
int countOfGT = 0;
double probOfGT = 0;
int countOfGG = 0;
double probOfGG = 0;
int totalBigramsPossible = sizeOfAllStrings / 2;
//count number of bigrams in allDNASequences
for (int i = 0; i <= allDNASequences.size(); i+=2)
{
if(allDNASequences[i] == 'A' && allDNASequences[i+1] == 'A')
{
countOfAA++;
}
else if(allDNASequences[i] == 'A' && allDNASequences[i+1] == 'C')
{
countOfAC++;
}
else if(allDNASequences[i] == 'A' && allDNASequences[i+1] == 'T')
{
countOfAT++;
}
else if(allDNASequences[i] == 'A' && allDNASequences[i+1] == 'G')
{
countOfAG++;
}
else if(allDNASequences[i] == 'C' && allDNASequences[i+1] == 'A')
{
countOfCA++;
}
else if(allDNASequences[i] == 'C' && allDNASequences[i+1] == 'C')
{
countOfCC++;
}
else if(allDNASequences[i] == 'C' && allDNASequences[i+1] == 'T')
{
countOfCT++;
}
else if(allDNASequences[i] == 'C' && allDNASequences[i+1] == 'G')
{
countOfCG++;
}
else if(allDNASequences[i] == 'T' && allDNASequences[i+1] == 'A')
{
countOfTA++;
}
else if(allDNASequences[i] == 'T' && allDNASequences[i+1] == 'C')
{
countOfTC++;
}
else if(allDNASequences[i] == 'T' && allDNASequences[i+1] == 'T')
{
countOfTT++;
}
else if(allDNASequences[i] == 'T' && allDNASequences[i+1] == 'G')
{
countOfTG++;
}
else if(allDNASequences[i] == 'G' && allDNASequences[i+1] == 'A')
{
countOfGA++;
}
else if(allDNASequences[i] == 'G' && allDNASequences[i+1] == 'C')
{
countOfGC++;
}
else if(allDNASequences[i] == 'G' && allDNASequences[i+1] == 'T')
{
countOfGT++;
}
else if(allDNASequences[i] == 'G' && allDNASequences[i+1] == 'G')
{
countOfGG++;
}
}
//compute the probabilities
probOfAA = static_cast<double>(countOfAA) / totalBigramsPossible;
probOfAC = static_cast<double>(countOfAC) / totalBigramsPossible;
probOfAT = static_cast<double>(countOfAT) / totalBigramsPossible;
probOfAG = static_cast<double>(countOfAG) / totalBigramsPossible;
probOfCA = static_cast<double>(countOfCA) / totalBigramsPossible;
probOfCC = static_cast<double>(countOfCC) / totalBigramsPossible;
probOfCT = static_cast<double>(countOfCT) / totalBigramsPossible;
probOfCG = static_cast<double>(countOfCG) / totalBigramsPossible;
probOfTA = static_cast<double>(countOfTA) / totalBigramsPossible;
probOfTC = static_cast<double>(countOfTC) / totalBigramsPossible;
probOfTT = static_cast<double>(countOfTT) / totalBigramsPossible;
probOfTG = static_cast<double>(countOfTG) / totalBigramsPossible;
probOfGA = static_cast<double>(countOfGA) / totalBigramsPossible;
probOfGC = static_cast<double>(countOfGC) / totalBigramsPossible;
probOfGT = static_cast<double>(countOfGT) / totalBigramsPossible;
probOfGG = static_cast<double>(countOfGG) / totalBigramsPossible;
outputStream << "Probabilities of various bigrams follow: " << endl
<< "AA: " << probOfAA << endl
<<"AC: " << probOfAC << endl
<<"AT: " << probOfAT << endl
<< "AG: " << probOfAG << endl
<< "CA: " << probOfCA << endl
<<"CC: " << probOfCC << endl
<<"CT: " << probOfCT << endl
<< "CG: " << probOfCG << endl
<< "TA: " << probOfTA << endl
<<"TC: " << probOfTC << endl
<<"TT: " << probOfTT << endl
<< "TG: " << probOfTG << endl
<< "GA: " << probOfGA << endl
<<"GC: " << probOfGC << endl
<<"GT: " << probOfGT << endl
<< "GG: " << probOfGG << endl;
//generate the 1000 DNA strings adhering to the statistics calculated above
int printedStrings = 0;
int countOfAInCollection = 0;
int countOfTInCollection = 0;
int countOfCInCollection = 0;
int countOfGInCollection = 0;
int totalNucleotidesInCollection = 1;
int i = 0; //needed to set the seed for outer while loop random variable generation
int j = 0; //needed to set the seed value for inner while loop random variable generation
while(printedStrings < 1000)
{
srand(i);
//Compute the Gaussian distribution
double a = (RAND_MAX - rand()) / static_cast<double>(RAND_MAX);
double b = (RAND_MAX - rand()) / static_cast<double>(RAND_MAX);
if(a == 1.0)
{
a = (RAND_MAX - rand()) / static_cast<double>(RAND_MAX);
}
if(b == 1.0)
{
b = (RAND_MAX - rand()) / static_cast<double>(RAND_MAX);
}
double radianForCalculation = (2 * 3.14159 * b * (3.14159 / 180)); //formula to convert degrees to radians is PI/180
double C = sqrt(-2 * log(a)) * cos(radianForCalculation);
double D = (stDev * C) + stringSizeMean;
int integerD = static_cast<int>(D);
//finished computing Gaussian distribution
//cout << D << endl;
string stringToPrint;
int stringLength = integerD;
int nucleotidesInString = 0;
while(nucleotidesInString <= stringLength)
{
srand(j);
int randomNumber = rand() % 4;
if(randomNumber == 0)
{
if ((countOfAInCollection/totalNucleotidesInCollection) <= probOfA)
{
stringToPrint += 'A';
countOfAInCollection++;
totalNucleotidesInCollection++;
nucleotidesInString++;
}
else
{
continue;
}
}
else if(randomNumber == 1)
{
if((countOfCInCollection/totalNucleotidesInCollection) <= probOfC)
{
stringToPrint += 'C';
countOfCInCollection++;
totalNucleotidesInCollection++;
nucleotidesInString++;
}
else
{
continue;
}
}
else if(randomNumber == 2)
{
if((countOfTInCollection/totalNucleotidesInCollection) <= probOfT)
{
stringToPrint += 'T';
countOfTInCollection++;
totalNucleotidesInCollection++;
nucleotidesInString++;
}
else
{
continue;
}
}
else if(randomNumber == 3)
{
if((countOfGInCollection/totalNucleotidesInCollection) <= probOfG)
{
stringToPrint += 'G';
countOfGInCollection++;
totalNucleotidesInCollection++;
nucleotidesInString++;
}
else
{
continue;
}
}
j++;
}
outputStream << stringToPrint << endl;
printedStrings++;
i++;
}
}
| true |
6f832a7c8d5c71ba81489d4834a3bf2233266405 | C++ | bholst/OceanVisServer | /src/lib/DimensionTrim.cpp | UTF-8 | 2,579 | 2.65625 | 3 | [] | no_license | //
// Copyright 2011 Bastian Holst <bastianholst@gmx.de>
//
// Qt
#include <QtCore/QDebug>
#include <QtCore/QVariant>
// Project
#include "DimensionSubset_p.h"
// Self
#include "DimensionTrim.h"
class DimensionTrimPrivate : public DimensionSubsetPrivate {
public:
DimensionTrimPrivate(Dimension dimension)
: DimensionSubsetPrivate(dimension),
m_trimLow(0.0),
m_trimHigh(0.0)
{
}
DimensionTrimPrivate(QString dimension)
: DimensionSubsetPrivate(dimension),
m_trimLow(0.0),
m_trimHigh(0.0)
{
}
DimensionTrimPrivate(const DimensionTrimPrivate& other)
: DimensionSubsetPrivate(other),
m_trimLow(other.m_trimLow),
m_trimHigh(other.m_trimHigh)
{
}
~DimensionTrimPrivate()
{
}
DimensionTrimPrivate& operator=(const DimensionTrimPrivate &other)
{
DimensionSubsetPrivate::operator=(other);
m_trimLow = other.m_trimLow;
m_trimHigh = other.m_trimHigh;
return *this;
}
bool operator==(const DimensionTrimPrivate &other)
{
return DimensionSubsetPrivate::operator==(other)
&& m_trimLow == other.m_trimLow
&& m_trimHigh == other.m_trimHigh;
}
QVariant m_trimLow;
QVariant m_trimHigh;
};
DimensionTrim::DimensionTrim(Dimension dimension)
: DimensionSubset(new DimensionTrimPrivate(dimension))
{
}
DimensionTrim::DimensionTrim(QString dimension) throw (BadDimensionString)
: DimensionSubset(new DimensionTrimPrivate(dimension))
{
}
DimensionTrim::DimensionTrim(const DimensionTrim &other)
: DimensionSubset(other)
{
}
DimensionTrim::~DimensionTrim()
{
}
void DimensionTrim::setTrimLow(QVariant trimLow) throw(BadDimensionTypeException)
{
ensureDimensionType(trimLow);
detach();
p()->m_trimLow = trimLow;
}
QVariant DimensionTrim::trimLow() const
{
return p()->m_trimLow;
}
void DimensionTrim::setTrimHigh(QVariant trimHigh) throw(BadDimensionTypeException)
{
ensureDimensionType(trimHigh);
detach();
p()->m_trimHigh = trimHigh;
}
QVariant DimensionTrim::trimHigh() const
{
return p()->m_trimHigh;
}
DimensionTrim& DimensionTrim::operator=(const DimensionTrim &other)
{
return (DimensionTrim &) DimensionSubset::operator=(other);
}
bool DimensionTrim::operator==(const DimensionTrim &other) const
{
return p() == other.p();
}
void DimensionTrim::detach()
{
qAtomicDetach((DimensionTrimPrivate *&) d);
}
DimensionTrimPrivate *DimensionTrim::p() const
{
return (DimensionTrimPrivate *) d;
}
| true |
78501e105c761b52aa6d343fa2123a093acec43e | C++ | trxo/cpp_study_notes | /chapter3-Function and function template/3.10函数返回对象的例子/main.cpp | UTF-8 | 442 | 3.453125 | 3 | [
"AFL-3.0"
] | permissive | #include <iostream>
#include <string>
using namespace std;
string input(const int);
int main()
{
int n;
cout << "Input n = ";
cin >> n;
string str = input(n);
cout << str << endl;
}
string input(const int n)
{
string s1,s2;
for(int i = 0; i < n; i++)
{
cin >> s1;
s2 = s2 + s1 + " ";
}
return s2; //返回string对象
}
//print
// Input n = 3
// zhang san feng
// zhang san feng | true |
e4b949836fe32c8280064cf0ecd2da415e20bbe1 | C++ | asad14053/My-Online-Judge-Solution | /All code of my PC/operator_overloading(-).cpp | UTF-8 | 363 | 3.25 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class my
{
public:
int x,y;
my()
{
}
my(int a,int b)
{
x=a,y=b;
}
my operator-(my);
};
my my::operator-(my p)
{
my t;
t.x=x-p.x;
t.y=y-p.y;
return t;
}
int main()
{
my a(20,30);
my b( 10,10);
my c=a-b;
cout<<c.x<<" "<<c.y<<endl;
return 0;
}
| true |
0fa24afef131afd14526af91937327dcd7600560 | C++ | azhe12/LeetCode | /InsertInterval.cpp | UTF-8 | 2,089 | 3.3125 | 3 | [] | no_license | //azhe
//2014/6/22
/**
* Definition for an interval.
*/
#include <iostream>
#include <vector>
using namespace std;
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
bool insertFlag = false;
vector<Interval>::iterator it;
vector<Interval> res;
for (it = intervals.begin(); it != intervals.end(); it++) {
if (!insertFlag) { //未插入
if (it->start > newInterval.end) { //new在it左边, 直接插入new和*it
insertFlag = true; //插入
res.push_back(newInterval);
res.push_back(*it);
} else if (newInterval.start > it->end) { //new在it右边, 不断插入*it
res.push_back(*it);
} else { //new和it有重合的地方, 重新计算new的start和end
newInterval.start = min(it->start, newInterval.start);
newInterval.end = max(it->end, newInterval.end);
}
} else { //new已插入,接着在末尾插入余下it
res.push_back(*it);
}
}
if (!insertFlag) //new始终未插入,那么最终放置到末尾
res.push_back(newInterval);
return res;
}
};
int main()
{
vector<Interval> v;
#if 0
Interval in1(1,3);
Interval in2(6,9);
Interval newIn(2,5);
v.push_back(in1);
v.push_back(in2);
#endif
Interval in1(1,2);
Interval in2(3,5);
Interval in3(6,7);
Interval in4(8,10);
Interval in5(12,16);
//Interval newIn(4,9);
Interval newIn(0,1);
v.push_back(in1);
v.push_back(in2);
v.push_back(in3);
v.push_back(in4);
v.push_back(in5);
vector<Interval> res;
Solution so;
res = so.insert(v, newIn);
for (int i = 0; i < res.size(); i++)
cout<<res[i].start<<" "<<res[i].end<<endl;
}
| true |
19584262fdb2b43765cd9947b2c00b0a8da6df8d | C++ | Pi0trS/ConfigReader | /ConfigReader/ConfigReader.h | UTF-8 | 685 | 2.78125 | 3 | [
"MIT"
] | permissive | #pragma once
#include<map>
class ConfigReader
{
public:
ConfigReader();
ConfigReader(std::string path);
ConfigReader(std::istream &stream);
void checkData();
std::string getHash();
std::string getHashType();
std::string getSalt();
std::string getDictionaryPath();
int getNumberOfThrede();
private:
std::map<std::string, std::string>config;
const char separator = ':';
std::string hash, hashType, salt, dictionaryPath;
int numberOfThreads;
void setHash(std::string hash_);
void setHashType(std::string hsahType_);
void setSalt(std::string salt_);
void setDictionaryPath(std::string path);
void setNumberOfThrede(int number);
std::string trim(std::string s);
}; | true |
67f2368c728cf00987a21ba5e1d3b6deceb6e550 | C++ | pgonzbecer/snippet-training | /cpp/snippet-training/BinaryTree.cpp | UTF-8 | 1,806 | 3.640625 | 4 | [] | no_license | // Created by Paul Gonzalez Becerra
#include<iostream>
#include<stdio.h>
#include<ctime>
#define SIZE(a) (sizeof(a)/sizeof(*a));
using namespace std;
class Node
{
public:
// Variables
int id;
Node* left;
Node* right;
// Constructors
Node(int n)
{
id= n;
left= (Node*)0;
right= (Node*)0;
}
// Methods
// Inserts the given key into the nodes
void insert(int key)
{
if(key== id) // No duplicates
return;
if(key< id)
{
if(left== (Node*)0)
left= new Node(key);
else
(*left).insert(key);
}
else
{
if(right== (Node*)0)
right= new Node(key);
else
(*right).insert(key);
}
}
// Displays the node
void display(int index, char type)
{
for(int i= 0; i< index; i++)
cout<< " |";
cout<< "+"<< id<< " : ";
switch(type)
{
case 0: cout<< "ROOT\n"; break;
case 1: cout<< "RIGHT\n"; break;
case 2: cout<< "LEFT\n"; break;
}
if(left!= (Node*)0)
(*left).display(index+1, 2);
if(right!= (Node*)0)
(*right).display(index+1, 1);
}
};
class BinaryTree
{
public:
Node* root;
// Constructors
BinaryTree()
{
root= (Node*)0;
}
// Methods
// Populates the tree with the given array
void populateTree(int a[], int asize)
{
for(int i= 0; i< asize; i++)
{
if(root== (Node*)0)
root= new Node(a[i]);
else
(*root).insert(a[i]);
}
}
// Displays the tree
void displayTree()
{
if(root== (Node*)0)
cout<< "--- Tree is empty ---";
else
(*root).display(0, 0);
}
};
/*
// Starts up the app
void main()
{
// Variables
BinaryTree tree= BinaryTree();
int asize= 20;
int a[20];
srand(time(0));
for(int i= 0; i< asize; i++)
a[i]= i+(rand()%132);
tree.populateTree(a, asize);
tree.displayTree();
}*/
// End of File | true |
3f021d9276524305a575685629f7add98741ed28 | C++ | DahaiXiao/BCIT-COMP-2618-Assignment- | /Assign 01 Solution/Shape.cpp | UTF-8 | 876 | 3.328125 | 3 | [] | no_license | // Assignment 1 Solution: Shape.cpp
// Member-function definitions for class Shape.
// Author: Bob Langelaan
// Date: Sept. 20th, 2014
#include "Shape.h"
int Shape::mObjectCount = 0; // init. static member
const double Shape::pi = 3.141592654; // init. static member
// constructor
Shape::Shape(void)
:mNoOfSides(1)
{
++Shape::mObjectCount;
}
// desstructor
Shape::~Shape(void)
{
--Shape::mObjectCount;
}
// used to set mNoOfSides member
void Shape::setNoOfSides(const int & setVal)
{
if (setVal > 0 )
{
this->mNoOfSides = setVal;
}
// otherwise just leave set to original value
}
// used to return current value of mNoOfSides member
int Shape::getNoOfSides() const
{
return this->mNoOfSides;
}
// used to return current value of mObjectCount static member
int Shape::getObjectCount()
{
return Shape::mObjectCount;
}
| true |
b6980559d847872d456281a39019df9cdedecbbb | C++ | cocahack/Missions | /algorithm/may-19/190508/1194.cpp | UTF-8 | 2,599 | 2.953125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
char board[51][51];
int n, m, s_y, s_x;
struct node{
int y, x, move;
string keys;
node(int y_, int x_, int move_):y(y_),x(x_),move(move_),keys(""){}
node(int y_, int x_, int move_, string keys_):y(y_),x(x_),move(move_),keys(keys_){}
bool operator == (const node &n) const {
return y == n.y && x == n.x && keys == n.keys;
}
bool operator < (const node& n) const {
if(y != n.y) return y < n.y;
if(x != n.x) return x < n.x;
return keys < n.keys;
}
};
set<node> visited;
int valid_position(int y, int x)
{
return (y >=0 && y < n) && (x >= 0 && x < m);
}
int dydx[4][2] = {
0,1,
1,0,
0,-1,
-1,0
};
bool have_key(const string& keys, char lock)
{
for(char k : keys){
if(k == lock + ('a' - 'A')){
return true;
}
}
return false;
}
bool is_lock(char c)
{
return c >= 'A' && c <= 'F';
}
bool is_key(char c)
{
return c >= 'a' && c <= 'f';
}
void add_key(string& s, char c)
{
for(char k : s){
if(k == c) return;
}
s += c;
sort(s.begin(), s.end());
}
int bfs()
{
queue<node> q;
q.push(node{s_y, s_x, 0});
while(q.size()){
auto n = q.front();
q.pop();
if(visited.find(n) != visited.end()) continue;
visited.insert(n);
for(int i=0; i<4; ++i){
int next_y = n.y + dydx[i][0], next_x = n.x + dydx[i][1];
if(valid_position(next_y, next_x)){
if(board[next_y][next_x] == '1'){
return n.move + 1;
}
if(board[next_y][next_x] == '#'){
continue;
}
node new_node{next_y, next_x, n.move + 1, n.keys};
if(is_key(board[next_y][next_x])){
add_key(new_node.keys, board[next_y][next_x]);
}
if(visited.find(new_node) != visited.end()) continue;
if(is_lock(board[next_y][next_x])){
if(have_key(n.keys, board[next_y][next_x])) {
q.push(new_node);
}
continue;
}
q.push(new_node);
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for(int i=0; i<n; ++i){
for(int j=0; j<m; ++j){
cin >> board[i][j];
if(board[i][j] == '0') s_y = i, s_x = j;
}
}
cout << bfs();
return 0;
}
| true |
cad13004a9cae3defbb1b4acc102b8e9ddd40967 | C++ | jwebb68/nel | /src/nel/test_manual.cc | UTF-8 | 6,674 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | // -*- mode: c++; indent-tabs-mode: nil; tab-width: 4 -*-
#include "manual.hh"
#include <catch2/catch.hpp>
namespace test
{
namespace manual
{
struct Stub
{
static int instances;
static int move_ctor;
static int move_assn;
static void reset()
{
instances = 0;
move_ctor = 0;
move_assn = 0;
}
int val;
bool valid;
~Stub()
{
if (valid) { instances -= 1; }
}
Stub(int v)
: val(v)
, valid(true)
{
instances += 1;
}
Stub(Stub &&o)
: val(nel::move(o.val))
, valid(nel::move(o.valid))
{
o.valid = false;
move_ctor += 1;
}
Stub &operator=(Stub &&o)
{
val = nel::move(o.val);
valid = nel::move(o.valid);
o.valid = false;
move_assn += 1;
return *this;
}
Stub(Stub const &o) = delete;
// no default ctor..
};
int Stub::instances = 0;
int Stub::move_ctor = 0;
int Stub::move_assn = 0;
TEST_CASE("manual::dtor", "[manual]")
{
Stub::reset();
{
// creating a manual<T> does not create a T.
nel::Manual<Stub> m;
nel::unused(m);
// no Ts are created
REQUIRE(Stub::instances == 0);
}
// no Ts are destructed
REQUIRE(Stub::instances == 0);
Stub::reset();
{
nel::Manual<Stub> m(Stub(1));
REQUIRE(Stub::instances == 1);
}
// no Ts are destructed
REQUIRE(Stub::instances == 1);
}
TEST_CASE("manual::move-tor", "[manual]")
{
{
Stub::reset();
// creating a manual<T> does not create a T.
auto m1 = nel::Manual<Stub>();
auto m2 = nel::move(m1);
// no Ts are created
REQUIRE(Stub::instances == 0);
// no T moves are performed
REQUIRE(Stub::move_ctor == 0);
REQUIRE(Stub::move_assn == 0);
}
{
Stub::reset();
auto m1 = nel::Manual<Stub>(Stub(1));
auto m2 = nel::move(m1);
REQUIRE(Stub::instances == 1);
// no T moves are performed
// note: the move into the container will count as 1 move.
REQUIRE(Stub::move_ctor == 1);
REQUIRE(Stub::move_assn == 0);
}
}
TEST_CASE("manual::move-assgn", "[manual]")
{
{
// move empty onto empty
Stub::reset();
// creating a manual<T> does not create a T.
auto m1 = nel::Manual<Stub>();
auto m2 = nel::Manual<Stub>();
m2 = nel::move(m1);
// no Ts are created
REQUIRE(Stub::instances == 0);
// no T moves are performed
REQUIRE(Stub::move_ctor == 0);
REQUIRE(Stub::move_assn == 0);
}
{
// move containing onto empty
Stub::reset();
auto m1 = nel::Manual<Stub>(Stub(1));
auto m2 = nel::Manual<Stub>();
m2 = nel::move(m1);
REQUIRE(Stub::instances == 1);
// no T moves are performed
// note the move into the container will count as 1 move
REQUIRE(Stub::move_ctor == 1);
REQUIRE(Stub::move_assn == 0);
}
{
// move containing onto containing
Stub::reset();
auto m1 = nel::Manual<Stub>(Stub(1));
auto m2 = nel::Manual<Stub>(Stub(2));
m2 = nel::move(m1);
REQUIRE(Stub::instances == 2);
// no extra T moves are performed
// note: the move into the container will count as 1 move
REQUIRE(Stub::move_ctor == 2);
REQUIRE(Stub::move_assn == 0);
REQUIRE((*m1).val == 1);
// and m2 has old value, not new..
REQUIRE((*m2).val == 2);
}
{
// move empty onto containing
Stub::reset();
auto m1 = nel::Manual<Stub>();
auto m2 = nel::Manual<Stub>(Stub(2));
m2 = nel::move(m1);
REQUIRE(Stub::instances == 1);
// no T moves are performed
// note: the move into the container will count as 1 move
REQUIRE(Stub::move_ctor == 1);
REQUIRE(Stub::move_assn == 0);
// and m2 has old value, not new..
REQUIRE((*m2).val == 2);
}
}
TEST_CASE("manual::destroy", "[manual]")
{
{
// deletes contained value
// UB if no value contained.
// UB if value already deleted.
Stub::reset();
auto m1 = nel::Manual<Stub>();
m1 = nel::move(Stub(2));
REQUIRE(Stub::instances == 1);
m1.destroy();
REQUIRE(Stub::instances == 0);
}
}
TEST_CASE("manual::move-in", "[manual]")
{
{
// value can be moved in.
Stub::reset();
auto m1 = nel::Manual<Stub>();
m1 = nel::move(Stub(2));
REQUIRE(Stub::instances == 1);
REQUIRE(Stub::move_ctor == 0);
REQUIRE(Stub::move_assn == 1);
REQUIRE((*m1).val == 2);
}
{
// value can be moved out.
Stub::reset();
auto m1 = nel::Manual<Stub>();
m1 = nel::move(Stub(2));
auto t = nel::move(*m1);
REQUIRE(Stub::instances == 1);
// move-assn of stub into m1.
REQUIRE(Stub::move_assn == 1);
// move-ct of value in m1 to t.
REQUIRE(Stub::move_ctor == 1);
REQUIRE(t.val == 2);
REQUIRE(t.valid);
// value in m1 invalidated by move-out
REQUIRE(!(*m1).valid);
}
{
// value can be moved in.
// moving in twice does not cause the old value dtor to be called
Stub::reset();
auto m1 = nel::Manual<Stub>();
m1 = nel::move(Stub(2));
m1 = nel::move(Stub(3));
// note: move-in overwrites and causes leaks..
// so remember to delete any previous value.
REQUIRE(Stub::instances == 2);
// move-assn of stubs into m1.
REQUIRE(Stub::move_assn == 2);
// not moved out
REQUIRE(Stub::move_ctor == 0);
REQUIRE((*m1).valid);
REQUIRE((*m1).val == 3);
}
{
// value can be moved in.
// moving in twice does not cause the old value dtor to be called
// call .destroy() first..
Stub::reset();
auto m1 = nel::Manual<Stub>();
m1 = nel::move(Stub(2));
m1.destroy();
m1 = nel::move(Stub(3));
REQUIRE(Stub::instances == 1);
// move-assn of stubs into m1.
REQUIRE(Stub::move_assn == 2);
// not moved out.
REQUIRE(Stub::move_ctor == 0);
REQUIRE((*m1).valid);
REQUIRE((*m1).val == 3);
}
}
}; // namespace manual
}; // namespace test
| true |
457bf1fa1c0dbc60b16feb9612e54df1b0c5b4fe | C++ | dnfwlq8054/coding_test | /baekjoon/Silver/Binary_Search_Tree_5639.cpp | UTF-8 | 948 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <random>
#include <map>
#include <set>
#pragma warning(disable: 4996)
using namespace std;
class tree {
public:
tree() {}
tree(int _num) : num(_num) {
left = NULL;
right = NULL;
}
void insert(int n) {
if (n < num) {
if (left == NULL) {
left = new tree(n);
return;
}
else {
return left->insert(n);
}
}
else {
if (right == NULL) {
right = new tree(n);
return;
}
else {
return right->insert(n);
}
}
}
void find() {
if (left != NULL)
left->find();
if (right != NULL)
right->find();
cout << num << endl;
}
private:
int num;
tree* left;
tree* right;
};
int main() {
int N, a, b, M, c, d, T, K, W;
int x, y, node_cost;
int flag = 1;
int answer = 0;
cin >> N;
tree t(N);
while (cin >> N) {
if (N == EOF) break;
t.insert(N);
}
t.find();
return 0;
} | true |
f465cd415f2dbe10ee92ada33449104205bd4bf4 | C++ | looke/CPP_Projects | /GeneralMatrix/src/matrix/basic/util/MatrixTransposer.cpp | GB18030 | 971 | 2.703125 | 3 | [] | no_license | /*
* MatrixTransposer.cpp
*
* Created on: 2017225
* Author: looke
*/
#include "MatrixTransposer.h"
#include <iostream>
using namespace std;
MatrixTransposer::MatrixTransposer(BasicMatrix* input_matrix)
{
this->init(input_matrix);
};
void MatrixTransposer::init(BasicMatrix* input_matrix)
{
};
void MatrixTransposer::reload(BasicMatrix* input_matrix)
{
};
/*
* ת
*/
void MatrixTransposer::transposeMatrix()
{
int rowNumber = p_opMatrix->rowNum;
int columnNumber = p_opMatrix->columnNum;
//loat** matrixPointer = opMatrix.getMatrixPointer();
for(int i=0; i<columnNumber; i++)
{
for(int j=0; j<rowNumber; j++)
{
p_opMatrixTransposed->setMatrixElement(i, j, p_opMatrix->getMatrixElement(j,i));
}
}
};
/*
* ӡתõľ
*/
void MatrixTransposer::printMatrixTranspose()
{
p_opMatrixTransposed->printMatrix();
};
BasicMatrix* MatrixTransposer::getTransposeMatrix()
{
return this->p_opMatrixTransposed;
};
| true |
c839f6112da08156d39e0836b174cad9f53d6dae | C++ | Yotta2/Stanford_CS106B | /Assignment3-vs2008/0B Random Subsets/Random Subsets/RandomSubsets.cpp | UTF-8 | 875 | 3.53125 | 4 | [] | no_license | /*
* File: RandomSubsets.cpp
* ----------------------
* Name: [TODO: enter name here]
* Section: [TODO: enter section leader here]
* This file is the starter project for the Random Subsets problem
* on Assignment #3.
* [TODO: extend the documentation]
*/
#include <iostream>
#include "set.h"
#include "random.h"
#include "console.h"
using namespace std;
/* Given a set of integers, returns a uniformly-random subset of that
* set.
*/
Set<int> randomSubsetOf(Set<int>& s) {
if (s.isEmpty())
return s;
Set<int> rest = s - s.first();
Set<int> ans;
if (randomChance(.5))
ans += s.first();
ans += randomSubsetOf(rest);
return ans;
}
int main() {
// [TODO: fill with your code]
Set<int> s;
s += 1, 2, 3, 4;
Set<int> sub = randomSubsetOf(s);
for (Set<int>::iterator itr = sub.begin(); itr != sub.end(); itr++)
cout << *itr << endl;
return 0;
}
| true |
2d564f0bb07bab7ef86b38d97963ae76aaa991f2 | C++ | pkubik/tin | /targets/Network/Abortable.hpp | UTF-8 | 2,231 | 2.984375 | 3 | [] | no_license | /*
* TIN 2015
*
* Pawel Kubik
*/
#pragma once
#include "Socket.hpp"
namespace network {
/**
* @brief abortableRead Reads specified amount from the socket and allow aborting
*
* Blocks if there is nothing to read. Might return less then required number of bytes.
*
* @param socket socket object
* @param buffer buffer to which the data is read
* @param size number of bytes to read
* @param pipeEnd fd which must be written to in order to abort
* @param timeout timeout
* @return number of bytes read, and information if it was aborted
*/
std::pair<size_t, bool> abortableRead(Socket& socket,
char* buffer,
const size_t size,
const short pipeEnd,
const int timeout = -1);
/**
* @brief abortableWrite Writes specified amount to the socket and allow aborting
*
* Returns only after all data has been written or after it was aborted
*
* @param socket socket object
* @param buffer buffer to which the data is read
* @param size number of bytes to read
* @param pipeEnd fd which must be written to in order to abort
* @param timeout timeout
* @return information whether the function was aborted
*/
bool abortableWriteAll(Socket& socket,
const char* buffer,
const size_t size,
const short pipeEnd,
const int timeout = -1);
/**
* @see abortableWriteAll
*/
bool abortableReadAll(Socket& socket,
char* buffer,
const size_t size,
const short pipeEnd,
const int timeout = -1);
/**
* @brief abortableWaitForConnection Wait until the socket is ready to accept
* @param socket Socket object
* @param pipeEnd fd which must be written to in order to abort
* @param timeout timeout
* @return true if there was a timeout or call has been aborted
*/
bool abortableWaitForConnection(Socket& socket, const int pipeEnd, const unsigned timeout = -1);
}
| true |
eb1d88d2d8cf024a472290767af625254f43e5e3 | C++ | rortian/oldjava | /JCppXref/WinNTCpp/Microsoft/IOSDemo/IOSDemo.cpp | UTF-8 | 7,569 | 2.765625 | 3 | [] | no_license | #include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
const char * filenameA [] = {
"",
"OS01A.TXT", "OS02A.TXT", "OS03A.TXT", "OS04A.TXT",
"OS05A.TXT", "OS06A.TXT", "OS07A.TXT", "OS08A.TXT",
"OS09A.TXT", "OS10A.TXT"
};
const char * filenameB [] = {
"",
"OS01B.TXT", "OS02B.TXT", "OS03B.TXT", "OS04B.TXT",
"OS05B.TXT", "OS06B.TXT", "OS07B.TXT", "OS08B.TXT"
};
// Custom manipulators for left and right justification
ostream & left(ostream & os) {
return os<<resetiosflags(ios::right)<<setiosflags(ios::left);
}
ostream & right(ostream & os) {
return os<<resetiosflags(ios::left)<<setiosflags(ios::right);
}
void Test01() {
ofstream os1A(filenameA[1], ios::out);
char * bird = "penguin";
char * fish = "rock cod";
char * tree = "maple";
os1A.fill('~');
os1A.width(12);
os1A<<bird<<endl;
os1A.width(12);
os1A<<fish<<endl;
os1A<<tree<<endl;
os1A.close();
ofstream os1B(filenameB[1], ios::out);
os1B<<setfill('~')<<setw(12)<<bird<<endl;
os1B<<setw(12)<<fish<<endl;
os1B<<tree<<endl;
os1B.close();
}
void Test02() {
ofstream os2A(filenameA[2], ios::out);
double num1 = 17.7875678;
os2A.precision(8);
os2A<<num1<<endl;
os2A.close();
ofstream os2B(filenameB[2], ios::out);
os2B<<setprecision(8)<<num1<<endl;
os2B.close();
}
void Test03() {
ofstream os3A(filenameA[3], ios::out);
int num1 = 160;
os3A<<oct<<"Octal = "<<num1<<endl;
os3A<<setiosflags(ios::showbase)<<"Octal = "<<num1<<endl;
os3A<<hex<<"Hexadecimal = "<<num1<<endl;
os3A<<setiosflags(ios::uppercase)<<"Hexadecimal = "<<num1<<endl;
os3A<<dec<<"Decimal = "<<num1<<endl;
os3A.close();
}
void Test04() {
ofstream os4A(filenameA[4], ios::out);
char * feline = "bob cat";
long lnum = 757905;
double dnum = 2345070.00915756;
os4A.setf(ios::left, ios::adjustfield);
os4A.fill('#');
os4A.width(12);
os4A.precision(14);
os4A<<feline<<endl;
os4A.width(12);
os4A<<lnum<<endl;
os4A.width(12);
os4A<<dnum<<endl;
os4A.unsetf(ios::left); // equivalent to os4A.setf(ios::right, ios::adjustfield);
os4A.fill('*');
os4A.width(12);
os4A.precision(14);
os4A<<feline<<endl;
os4A.width(12);
os4A<<lnum<<endl;
os4A.width(12);
os4A<<dnum<<endl;
os4A.close();
ofstream os4B(filenameB[4], ios::out);
os4B<<setiosflags(ios::left)<<setfill('#')<<setw(12)<<setprecision(14)<<feline<<endl;
os4B<<setw(12)<<lnum<<endl;
os4B<<setw(12)<<dnum<<endl;
os4B<<resetiosflags(ios::left)<<setfill('*')<<setw(12)<<setprecision(14)<<feline<<endl;
os4B<<setw(12)<<lnum<<endl;
os4B<<setw(12)<<dnum<<endl;
os4B.close();
}
void Test05() {
ofstream os5A(filenameA[5], ios::out);
char * bird = "penguin";
char * fish = "rock cod";
char * tree = "maple";
os5A.setf(ios::left, ios::adjustfield);
os5A.fill('*');
os5A.width(12);
os5A<<bird<<endl;
os5A.width(12);
os5A<<fish<<endl;
os5A.setf(ios::right, ios::adjustfield);
os5A.width(12);
os5A<<tree<<endl;
os5A.close();
ofstream os5B(filenameB[5], ios::out);
os5B<<setiosflags(ios::left)<<setfill('*')<<setw(12)<<bird<<endl;
os5B<<setw(12)<<fish<<endl;
os5B<<resetiosflags(ios::left)<<setw(12)<<tree<<endl;
os5B.close();
}
void Test06() {
ofstream os6A(filenameA[6], ios::out);
int int1 = 34950;
int int2 = -int1;
float flt1 = 17.5829f;
float flt2 = -flt1;
os6A.setf(ios::internal, ios::adjustfield);
os6A.fill('^');
os6A.width(16);
os6A<<int1<<endl;
os6A.width(16);
os6A<<int2<<endl;
os6A.width(16);
os6A<<flt1<<endl;
os6A.width(16);
os6A<<flt2<<endl;
os6A.unsetf(ios::internal);
os6A.width(16);
os6A<<flt2<<endl;
os6A.close();
ofstream os6B(filenameB[6], ios::out);
os6B<<setiosflags(ios::internal)<<setfill('^')<<setw(16)<<int1<<endl;
os6B<<setw(16)<<int2<<endl;
os6B<<setw(16)<<flt1<<endl;
os6B<<setw(16)<<flt2<<endl;
os6B<<resetiosflags(ios::internal)<<setw(16)<<flt2<<endl;
os6B.close();
}
void Test07() {
ofstream os7A(filenameA[7], ios::out);
long lng1 = 875090406;
double dbl1 = 395.0;
double dbl2 = 7693.8356;
double dbl3 = 3409.958;
os7A<<dbl1<<endl;
os7A.setf(ios::showpos | ios::showpoint);
os7A<<dbl1<<endl;
os7A.setf(ios::scientific, ios::floatfield);
os7A<<lng1<<endl;
os7A<<dbl2<<endl;
os7A<<dbl3<<endl;
os7A.unsetf(ios::showpos | ios::showpoint | ios::scientific);
os7A<<lng1<<endl;
os7A<<dbl1<<endl;
os7A<<dbl2<<endl;
os7A<<dbl3<<endl;
os7A.close();
ofstream os7B(filenameB[7], ios::out);
os7B<<dbl1<<endl;
os7B<<setiosflags(ios::showpos | ios::showpoint)<<dbl1<<endl;
os7B<<setiosflags(ios::scientific)<<lng1<<endl;
os7B<<dbl2<<endl;
os7B<<dbl3<<endl;
os7B<<resetiosflags(ios::showpos | ios::showpoint | ios::scientific)<<lng1<<endl;
os7B<<dbl1<<endl<<dbl2<<endl<<dbl3<<endl;
os7B.close();
}
void Test08() {
ofstream os8A(filenameA[8], ios::out);
int num1 = 160;
os8A.setf(ios::oct, ios::basefield);
os8A<<"Octal = "<<num1<<endl;
os8A.setf(ios::showbase);
os8A<<"Octal = "<<num1<<endl;
os8A.setf(ios::hex, ios::basefield);
os8A<<"Hexadecimal = "<<num1<<endl;
os8A.setf(ios::uppercase);
os8A<<"Hexadecimal = "<<num1<<endl;
os8A.setf(ios::dec, ios::basefield);
os8A<<"Decimal = "<<num1<<endl;
os8A.close();
ofstream os8B(filenameB[8], ios::out);
os8B<<setiosflags(ios::oct)<<"Octal = "<<num1<<endl;
os8B<<setiosflags(ios::showbase)<<"Octal = "<<num1<<endl;
os8B<<resetiosflags(ios::oct)<<setiosflags(ios::hex)<<"Hexadecimal = "<<num1<<endl;
os8B<<setiosflags(ios::uppercase)<<"Hexadecimal = "<<num1<<endl;
os8B<<resetiosflags(ios::hex)<<setiosflags(ios::dec)<<"Decimal = "<<num1<<endl;
os8B.close();
}
void Test09() { // This test uses the custom-designed manipulators: left and right
char * feline = "bob cat";
long lnum = 757905;
double dnum = 2345070.00915756;
ofstream os9A(filenameA[9], ios::out);
os9A<<left<<setfill('#')<<setw(12)<<setprecision(14)<<feline<<endl;
os9A<<setw(12)<<lnum<<endl;
os9A<<setw(12)<<dnum<<endl;
os9A<<right<<setfill('*')<<setw(12)<<setprecision(14)<<feline<<endl;
os9A<<setw(12)<<lnum<<endl;
os9A<<setw(12)<<dnum<<endl;
os9A.close();
}
void Test10() {
double dbl3[] = {
0.123456, 1.123456, 12.123456, 123.123456, 1234.123456, 12345.123456, 123456.123456,
12345.6123456, 1234.56123456, 123.456123456, 12.3456123456, 1.23456123456,
1234561.23456, 12345612.3456, 123456123.456, 1234561234.56, 12345612345.6, 1234567.123456,
12345678.123456, 123456789.123456, 1234567891.123456, 12345678912.123456, 123456789123.123456,
1234567891234.123456
};
ofstream os10A(filenameA[10], ios::out);
os10A.precision(20);
os10A.width(30);
os10A.setf(ios::right, ios::adjustfield);
os10A<<"Fixed Format - Positive"<<endl;
os10A.width(30);
for(int index = 0; index < 24; index++) {
os10A<<dbl3[index]<<endl;
os10A.width(30);
}
os10A.width(30);
os10A<<"Fixed Format - Negative"<<endl;
os10A.width(30);
for(index = 0; index < 24; index++) {
os10A<<-dbl3[index]<<endl;
os10A.width(30);
}
os10A.setf(ios::scientific, ios::floatfield);
os10A.width(30);
os10A<<"Scientific Format - Positive"<<endl;
os10A.width(30);
for(index = 0; index < 24; index++) {
os10A<<dbl3[index]<<endl;
os10A.width(30);
}
os10A.width(30);
os10A<<"Scientific Format - Negative"<<endl;
os10A.width(30);
for(index = 0; index < 24; index++) {
os10A<<-dbl3[index]<<endl;
os10A.width(30);
}
os10A.close();
}
void main()
{
Test01();
Test02();
Test03();
Test04();
Test05();
Test06();
Test07();
Test08();
Test09();
Test10();
}
| true |
3fdde3db15c8220216612f84265bfca1e5596a20 | C++ | Jorjatorz/LastStand | /LastStand/FRenderer.h | UTF-8 | 1,344 | 2.65625 | 3 | [] | no_license | #pragma once
#include "Singleton.h"
#include "FDeferredFrameBuffer.h"
#include "FStaticMesh.h"
#include <gl/glew.h>
class FWorld;
class Matrix4;
class FScene;
class FCameraComponent;
//Class incharge of rendering all the FObjects in the world.
class FRenderer : public Singleton<FRenderer>
{
public:
FRenderer(unsigned short int width, unsigned short int height);
~FRenderer();
FScene* getCurrentFScene();
//Main function. Renders all the objects in the worlds that are visible.
void renderObjectsInTheWorld();
const Matrix4& getCurrentFrameProjectionMatrix();
const Matrix4& getCurrentFrameViewMatrix();
const Vector3& getCurrentRenderingCameraWPosition();
private:
//Deferred framebuffer
FDeferredFrameBuffer* _gBuffer;
//Do a normal deferred pass and fills the buffers and the rendering targets of the camera
void doDeferredPass(FCameraComponent* currentCamera);
void geometryPass();
void lightPass();
void UIPass();
void finalPass();
//Rendenders a Quad (with desired dimensions) and writes there the result of the deferred pass
void drawToScreenQuad();
FStaticMesh _screenQuadMesh;
//Current frame matrix (updates per frame)
const Matrix4* _currentFrameProjectionM;
const Matrix4* _currentFrameViewM;
const Vector3* _currentRenderingCameraWPosition;
//Current Scene to render
FScene* _sceneToRender;
};
| true |
caeda5e7dabf67a30365175f977f7aa8c0795ee9 | C++ | anilsevici/Cpp | /Ogrenci.cpp | UTF-8 | 1,409 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include "String.h"
#include "Tarih.h"
#include "Bilgisayar.h"
#include "Ogrenci.h"
using namespace std;
Ogrenci::Ogrenci(int no,String ogr_ad,String ogr_soyad,Tarih ogr_dogum,Tarih ogr_kayit,
Bilgisayar tasinabilir,int ogr_sinif,float ogrenci_ort):ogr_no(no),ad(ogr_ad),soyad(ogr_soyad),dogum_tarihi(ogr_dogum),kayit_tarihi(ogr_kayit),tasinabilir_bilgisayar(tasinabilir)
{
sinifAyarla(ogr_sinif);
notortAyarla(ogrenci_ort);
}
Ogrenci::~Ogrenci()
{
//dtor
}
void Ogrenci::sinifAyarla(int sinifval)
{
sinif=sinifval;
}
void Ogrenci::notortAyarla(float notval)
{
not_ort=notval;
}
int Ogrenci::noOku()const
{
return ogr_no;
}
String Ogrenci::adOku()const
{
return ad;
}
String Ogrenci::soyadOku()const
{
return soyad;
}
Tarih Ogrenci::dogum_tarihOku()const
{
return dogum_tarihi;
}
Tarih Ogrenci::kayit_tarihOku()const
{
return kayit_tarihi;
}
Bilgisayar Ogrenci::bilgisayarOku()const
{
return tasinabilir_bilgisayar;
}
int Ogrenci::sinifOku()const
{
return sinif;
}
float Ogrenci::ortalamaOku()const
{
return not_ort;
}
ostream &operator<<(ostream &output,const Ogrenci *obj)
{
output<<obj->noOku()<<'\t'<<obj->adOku()<<'\t'<<obj->soyadOku()<<'\t'<<'\t'<<obj->sinifOku()<<'\t'<<obj->ortalamaOku()<<'\t'<<obj->dogum_tarihOku()<<'\t'<<obj->kayit_tarihOku()<<endl;
return output;
}
| true |
2b914919f004b46e58622f8185a74f24970a1a40 | C++ | pcw109550/problem-solving | /LeetCode/minimum-number-of-removals-to-make-mountain-array.cpp | UTF-8 | 936 | 3.21875 | 3 | [] | no_license | // 1671. Minimum Number of Removals to Make Mountain Array
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minimumMountainRemovals(vector<int>& nums) {
// O(N ** 2) LIS
int N = nums.size();
int result = N;
vector<int> D1(N, 1), D2(N, 1);
D1[0] = 1;
for (int i = 1; i < N; i++)
for (int j = 0; j < i; j++)
if (nums[j] < nums[i])
D1[i] = max(D1[i], 1 + D1[j]);
D2[N - 1] = 1;
for (int i = N - 2; i >= 0; i--)
for (int j = N - 1; j > i; j--)
if (nums[i] > nums[j])
D2[i] = max(D2[i], 1 + D2[j]);
for (int i = 1; i < N - 1; i++)
if (D1[i] > 1 && D2[i] > 1)
result = min(result, N - D1[i] - D2[i] + 1);
return result;
}
};
int main(void) {
Solution s;
}
| true |
7756f25f2fb096ca4e1d11bfb279a4fd625950a2 | C++ | shang766/multiview | /multiview/multiview_cpp/src/testcases/file-io/file-system_tc.cpp | UTF-8 | 3,202 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive |
#include <algorithm>
#include <filesystem>
#include <iterator>
#define CATCH_CONFIG_PREFIX_ALL
#include "perceive/contrib/catch.hpp"
#include "perceive/utils/file-system.hpp"
namespace perceive
{
static std::string sentence = "The quick brown fox jumped over the lazy dog.";
// Data for test cases
static std::vector<char> bin_data0(0);
static std::vector<char> bin_data1(1);
static std::vector<char> bin_data2(512);
static std::vector<char> bin_data3(512); // ASCII string data
static std::vector<char> bin_data4;
// Method to access all test cases
static std::vector<const decltype(bin_data0)*> all_data{
{&bin_data0, &bin_data1, &bin_data2, &bin_data3, &bin_data4}};
static void init_testcase_data()
{
static bool done = false;
if(done) return;
// Initialize these data buckets
bin_data1[0] = '\0';
std::iota(begin(bin_data2), end(bin_data2), 0);
for(auto i = 0u; i < bin_data3.size(); ++i) bin_data3[i] = 1 + (i % 127);
bin_data4.resize(sentence.size());
std::copy(cbegin(sentence), cend(sentence), begin(bin_data4));
done = true;
}
static string as_string(const vector<char>& data)
{
string ret;
ret.resize(data.size());
std::copy(cbegin(data), cend(data), begin(ret));
return ret;
}
template<typename U, typename V> static bool is_equal(const U& s, const V& data)
{
if(s.size() != data.size()) return false;
for(auto i = 0u; i < s.size(); ++i)
if(s[i] != data[i]) return false;
return true;
}
// ----------------------------------------------------- Point in/out of Polygon
CATCH_TEST_CASE("file-get/put-contents binary safe", "[file_getput_contents]")
{
// Sometimes we want a string version of the data
CATCH_SECTION("file-putget-contents_string_binary-safe")
{
init_testcase_data();
vector<string> fnames;
auto counter = 0;
for(const auto& data : all_data) {
string fname = format("/tmp/file-contents.test-{}", counter++);
file_put_contents(fname, as_string(*data));
fnames.emplace_back(std::move(fname));
}
for(auto i = 0u; i < all_data.size(); ++i) {
const auto& data = *all_data[i];
string fdat = file_get_contents(fnames[i]);
CATCH_REQUIRE(is_equal(fdat, data));
}
// Cleanup
for(const auto& fname : fnames) delete_file(fname);
fnames.clear();
}
// Sometimes we want a string version of the data
CATCH_SECTION("file-putget-contents_vector_binary-safe")
{
init_testcase_data();
vector<string> fnames;
auto counter = 0;
for(const auto& data : all_data) {
string fname = format("/tmp/file-contents.test-{}", counter++);
file_put_contents(fname, *data);
fnames.emplace_back(std::move(fname));
}
for(auto i = 0u; i < all_data.size(); ++i) {
const auto& data = *all_data[i];
vector<char> out;
file_get_contents(fnames[i], out);
CATCH_REQUIRE(is_equal(out, data));
}
// Cleanup
for(const auto& fname : fnames) {
auto p = std::filesystem::path(fname);
std::filesystem::remove(p);
}
fnames.clear();
}
}
} // namespace perceive
| true |
ce08b819b07156ad8dd8565c6be85341373c9b17 | C++ | kaurgurpal/AirlineReservationSystem | /AirlineReservationSystem/FlightScheduleDatabase.cpp | UTF-8 | 2,298 | 2.625 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include "FlightScheduleDatabase.h"
#include <Windows.h>
using namespace std;
namespace ARS
{
FlightScheduleDatabase::FlightScheduleDatabase()
{
Flight f1{ "AA001", "American Airline", "Seattle SEA", "NEW York JFK", 0700, 1500, 380};
Flight f2{ "ALK001", "Alaska Airline", "Seattle SEA", "Alaska HWE", 0600, 1000, 282 };
Flight f3{ "SW929", "Southwest Airline", "Dallas DSF", "NEW York JFK", 0700, 1500, 380 };
Flight f4{ "SP636", "Spirit Airline", "Chicago OHO", "NEW York JFK", 0700, 1500, 380 };
Flight f5{ "DL772", "Delta Airline", "Houstan HOU", "San Francisco SFO", 0700, 1500, 380 };
Flight f6{ "SUN737", "Sun Airline", "Arizona ARI", "Seattle SEA", 0700, 1500, 380 };
Flight f7{ "JET111", "Jet Airline", "Portland POR", "Los Angeles LAX", 0700, 1500, 380 };
Flight f8{ "IND838", "Indigo Airline", "Las Vegas LAS", "Detroit DTW", 0700, 1500, 380 };
Flight f9{ "JBL729", "JetBlue Airline", "WashingtonDC WDC", "Miami MIA", 0700, 1500, 380 };
Flight f10{ "FRN101", "Frontier Airline", "New York LGA", "Bostan BST", 0700, 1500, 380 };
Flight f11{ "UNI919", "United Airline", "Louisville LSV", "Dallas DSF", 0700, 1500, 380 };
Flight f12{ "HWI999", "Hawaiian Airline", "Seattle SEA", "Denver DNE", 0700, 1500, 380 };
mFlights.push_back(f1);
mFlights.push_back(f2);
mFlights.push_back(f3);
mFlights.push_back(f4);
mFlights.push_back(f5);
mFlights.push_back(f6);
mFlights.push_back(f7);
mFlights.push_back(f8);
mFlights.push_back(f9);
mFlights.push_back(f10);
mFlights.push_back(f11);
mFlights.push_back(f12);
}
void FlightScheduleDatabase::displayFlightsSchedule() const
{
printf("|%4s|%12s|%20s|%20s|%20s|%10s|%10s|%10s|", "Item", "Flight#", "Airline", "Source", "Destination", "Departure","Arrival" , "$ Price");
printf("\n");
cout << "============================================================================" << endl;
int counter = 1;
for (const auto& flight : mFlights) {
flight.displayFlightInfo(counter);
counter++;
}
//for (auto it = begin(mFlights); it != end(mFlights); ++it)
//{
// Flight f;
// f.displayFlightInfo(it - mFlights.begin());
//}
}
Flight FlightScheduleDatabase::getFlight(int itemNumber) const
{
return mFlights.at(itemNumber - 1);
}
} | true |
65339b12a47651230598c9bc86cab408e37fe02c | C++ | funeralbot/sanchezkalonnie_CSC5_fall2017 | /hmwk/Assignment 1/Sales Tax/main.cpp | UTF-8 | 1,350 | 3.84375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Kalonnie Sanchez
* Created on September 14, 2017, 12:00 AM
* Purpose: Determine sales tax based off state and county.
*/
//System Libraries
#include <iostream> //Input/Output Stream Library
using namespace std; //The Standard namespace for system libraries
//User Libraries
//Global Constants - Not only variables Physics/Math/Conversations only
//Functions Prototypes
//Executions Begins Here!
int main(int argc, char** argv) {
//Declare Variables
float price,total,total2; // declaring the variables as floats
float stax=4, ctax=2; //state and county tax as whole numbers
//Initialize Variables
cout<<"Enter Price $"<<endl; //for user to enter price
cin>>price;
cout<<"State tax is "<<stax<<"%"<<endl; //displays the current state tax
cout<<"County tax is "<<ctax<<"%"<<endl; //displays the current county tax
//Process or map the inputs to the outputs
total=price * stax*.01 + ctax*.01; //multiplies the price by the tax
total2 = price + total; //adds the tax to the price
//Display/Output all pertinent variables
cout<<"The total tax is $"<<total<<endl; //displays the amount of tax based off price
cout<<"Your total is $"<<total2<<endl; //displays the total amount for user
//Exit the program
return 0;
}
| true |
0eff3d1d85ef77e68fac30d09b8448769f95cd6b | C++ | bartoszstelmaszuk/SPOJ | /PA05_POT/PA05_POT/Source.cpp | UTF-8 | 631 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main (void)
{
long int a, b, c, l, e, x, result;
int tab[29];
int n;
for(int i=0; i<30; i++)
{
tab[i]=0;
}
cin >> n;
for (int i=0; i<n; i++)
{
cin >> a;
cin >> b;
l=0;
for (int j = 1; j*2<=b; j=j*2)
{
l++;
e=j*2;
}
for(int j=l;j>=0;j--)
{
if(b>=e)
{
b=b-e;
tab[j]=1;
}
else
{
tab[j]=0;
}
e=e/2;
}
a=a%10;
result=1;
x=a;
for (int j=0; j<=l; j++)
{
if (tab[j]==1)
{
result*=x;
result=result%10;
}
x*=x;
x=x%10;
}
cout << result << endl;
}
return 0;
} | true |
f034787a951bdb0b9b85662312ff59114404fce9 | C++ | VeniVidiReliqui/LinkedList | /main.cpp | UTF-8 | 1,234 | 3.125 | 3 | [] | no_license | /*
* main.cpp
* Name: Benjamin Hunt
*
* This file has NO PURPOSE, other than allowing you to 'play'
* with your List(s) and verify operation. What you do here
* will probably be what you should put in your unit tests!
*
* Nov 19 ,2013
*/
#include <iostream>
#include "List.h"
using namespace std;
int main(int argc, char* argv[]){
List l;
l.pushEnd(5);
l.pushEnd(6);
l.pushEnd(7);
l.pushFront(4);
l.pushFront(42);
l.pushEnd(90);
l.printList();
cout << l.size() << endl;
cout << l.getFirst() << " " << l.getLast() << endl;
cout << l.at(4) << " " << l.at(-4) << endl;
cout << l.contains(90) << " " << l.contains(43) << endl;
cout << endl << l.popFront() << endl;
cout << endl << l.size() << endl;
l.printList();
cout << l.popEnd() << endl;
cout << endl << l.size() << endl;
l.printList();
cout << l.popEnd() << endl;
cout << endl << l.size() << endl;
l.printList();
l.deleteNth(1);
cout << endl << l.size() << endl;
l.printList();
cout << endl << "test contains all";
List p;
p.pushEnd(5);
p.pushEnd(6);
List k;
k.pushEnd(7);
l.append(p);
l.printList();
List y(5000,7);
List r(y);
List w(l.mesh(p));
l.printList();
p.printList();
w.printList();
return 0;
}
| true |
3537fd1d342a471b9c6ed582a7498eb0260301b2 | C++ | Soonwook34/My-Baekjoon-Code | /18258.cpp | UTF-8 | 980 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int main() {
int N;
scanf("%d", &N);
char cmd[6];
vector<int> myQueue; //큐 구현
int front = 0, back = 0;
for (int i = 0; i < N; i++) {
scanf("%s", cmd);
//push
if (strcmp(cmd, "push") == 0) {
int x;
scanf("%d", &x);
myQueue.push_back(x);
back++;
}
//pop
else if (strcmp(cmd, "pop") == 0) {
if (back - front == 0)
printf("-1\n");
else {
printf("%d\n", myQueue[front]);
front++;
}
}
//size
else if (strcmp(cmd, "size") == 0) {
printf("%d\n", back - front);
}
//empty
else if (strcmp(cmd, "empty") == 0) {
printf("%d\n", back - front == 0 ? 1 : 0);
}
//front
else if (strcmp(cmd, "front") == 0) {
if (back - front == 0)
printf("-1\n");
else
printf("%d\n", myQueue[front]);
}
//back
else {
if (back - front == 0)
printf("-1\n");
else
printf("%d\n", myQueue[back-1]);
}
}
return 0;
}
| true |
3b4b7f58d970e93cc64e73514337a60bcd45d6f3 | C++ | cerww/tictactoe | /include/ticTacToeAI.h | UTF-8 | 896 | 2.734375 | 3 | [] | no_license | #ifndef TICTACTOEAI_H
#define TICTACTOEAI_H
#include "tictactoe.h"
#include <vector>
#include <unordered_map>
#include "vecFuncs.h"
struct tictactoeBoard{
friend class tictactoe;
tictactoeBoard(){};
tictactoeBoard(tictactoe b){
Xs = b.m_Xs;
Os = b.m_Os;
};
~tictactoeBoard(){};
short Xs = 0;
short Os = 0;
};//Os|Xs gives board
namespace std{
template<>
class hash<tictactoeBoard>{
public:
size_t operator()(const tictactoeBoard& board)const{
return board.Xs^board.Os;
}
};
};
class ticTacToeAI{
public:
friend class tictactoe;
ticTacToeAI();
virtual ~ticTacToeAI();
int getBest(tictactoeBoard,int);
static int OWins;
static int XWins;
static int ties;
private:
float getBoardValue(tictactoeBoard,int,int&);
};
#endif // TICTACTOEAI_H
| true |
87392a9dea1b223d10daec702451e33846444415 | C++ | frenchjam/CodaRTnetExamples | /CodaRTnetSDK/examples/rtnetdemo/Alignment.cpp | UTF-8 | 5,073 | 2.734375 | 3 | [] | no_license | #include <conio.h>
#include <iostream>
#include <strstream>
#include <iomanip>
#include "codaRTNetProtocolCPP/RTNetClient.h"
#include "codaRTNetProtocolCPP/DeviceOptionsAlignment.h"
#include "codaRTNetProtocolCPP/DeviceInfoAlignment.h"
#include "Alignment.h"
Alignment::Alignment()
{
RegisterParameter("origin", origin);
RegisterParameter("x0", x0);
RegisterParameter("x1", x1);
RegisterParameter("xy0", xy0);
RegisterParameter("xy1", xy1);
RegisterParameter("expected_result", expected_result);
RegisterParameter("allow_retry", allow_retry);
RegisterParameter("allow_cancel", allow_cancel);
}
void Alignment::RunRTNet() throw(TracedException, codaRTNet::NetworkException, codaRTNet::DeviceStatusArray)
{
// loop to allow multiple tries when retry is enabled
while (true)
{
// prompt user
Comment("Prompting user to perform alignment");
std::cerr << "Press Y to perform alignment, any other key to cancel..." << std::endl;
int ch = _getch();
if(tolower(ch) != 'y')
{
if (allow_cancel.Value())
{
// merely log the fact that alignment was cancelled but it's not an error
Comment("Alignment cancelled");
break;
}
else
{
// allow_cancel is disabled by the parameters so we must report this as an error and quit
COMMAND_STOP("Alignment cancelled");
}
}
// make alignment structure with specified marker options
// these will have been filled in from the command file
codaRTNet::DeviceOptionsAlignment align(origin.Value(), x0.Value(), x1.Value(), xy0.Value(), xy1.Value());
// perform alignment
// this will cause system to look for alignment markers
// - they must be in position by this time
Client().setDeviceOptions(align);
// retrieve information
codaRTNet::DeviceInfoAlignment info;
Client().getDeviceInfo(info);
// print alignment diagnostics
LogStatus(align, info);
// look to see if got the result we expected
if ((long)info.dev.dwStatus == expected_result.Value())
{
// expected value found
Comment("Result as expected");
break;
}
else
{
// unexpected value found
std::ostrstream formattedmessage;
formattedmessage << "Expected result " << expected_result.Value() << " but got " << info.dev.dwStatus;
Comment(formattedmessage);
if (allow_retry.Value())
{
// if retry enabled, just log the retry and loop around for another go
Comment("Retry enabled");
}
else
{
// if retry disabled, call Fail() to produce an exception and quit this method
COMMAND_STOP("Unexpected alignment result and retry disabled");
}
}
}
}
void Alignment::LogStatus(const codaRTNet::DeviceOptionsAlignment& align, const codaRTNet::DeviceInfoAlignment& info)
{
unsigned long marker_id_array[5] =
{
align.opt.dwMarkerOrigin,
align.opt.dwMarkerX0,
align.opt.dwMarkerX1,
align.opt.dwMarkerXY0,
align.opt.dwMarkerXY1
};
const char* marker_label_array[5] =
{
"origin",
"x0 ",
"x1 ",
"xy0 ",
"xy1 "
};
const char* camera_label_array[3] =
{
"A",
"B",
"C"
};
// print alignment status value
Comment1("Alignment result", info.dev.dwStatus);
switch (info.dev.dwStatus)
{
case 0:
Comment("success");
break;
case CODANET_ALIGNMENTERROR_SYSTEM:
Comment("system error");
break;
case CODANET_ALIGNMENTERROR_ALREADY_ACQUIRING:
Comment("already acquiring (is another program running?");
break;
case CODANET_ALIGNMENTERROR_OCCLUSIONS:
Comment("occlusions");
break;
case CODANET_ALIGNMENTERROR_XTOOCLOSE:
Comment("x-axis markers too close");
break;
case CODANET_ALIGNMENTERROR_XYTOOCLOSE:
Comment("xy-plane markers too close");
break;
case CODANET_ALIGNMENTERROR_NOTPERP:
Comment("marked axes not sufficiently perpendicular");
break;
default:
Comment1("unknown alignment status error code", info.dev.dwStatus);
break;
}
// number of CX1 units
DWORD nunits = info.dev.dwNumUnits;
// frame count
DWORD nframes = info.dev.dwNumFrames;
// print visibility information
for (DWORD icoda = 0; icoda < nunits; icoda++)
{
// index of Codamotion CX1 unit
Comment1("CODA", icoda+1);
// data from each marker
for (DWORD imarker = 0; imarker < 5; imarker++)
{
// actual marker identity
DWORD marker_identity = marker_id_array[imarker];
for (DWORD icam = 0; icam < 3; icam++)
{
std::ostrstream formattedmessage;
// build label for this marker and camera combination
formattedmessage
<< marker_label_array[imarker]
<< " (Marker " << std::setw(2) << marker_identity << ") "
<< camera_label_array[icam]
<< ": ";
// print visibility graph for frames of data
// show a 1 for visible and _ for occluded
// (show alternate frames only to save screen space)
for (DWORD iframe = 0; iframe < nframes; iframe+=2)
{
BYTE flag = info.dev.camera_flag[3*nframes*5*icoda + 3*nframes*imarker + 3*iframe + icam];
if (flag <= 10)
formattedmessage.put('_');
else
formattedmessage.put('1');
}
// show
Comment(formattedmessage);
}
}
}
}
| true |
7f34ba7c557baa645c7795b50049e3340aaf92a3 | C++ | Masters-Akt/CS_codes | /leetcode_sol/223-Rectangle_Area.cpp | UTF-8 | 420 | 3.15625 | 3 | [] | no_license | class Solution {
public:
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int area1 = (ax2-ax1)*(ay2-ay1), area2 = (bx2-bx1)*(by2-by1);
if(!(max(ax1, bx1)<min(ax2, bx2) && max(ay1, by1)<min(ay2, by2))) return area1+area2;
int common_area = (min(ax2, bx2)-max(ax1, bx1)) * (min(ay2, by2)-max(ay1, by1));
return area1+area2-common_area;
}
}; | true |
e68fbb116ff2cba0ec39232196a2bd7e3efdcd03 | C++ | lzgjxh/SpaceWireRMAPLibrary | /source_IPSocketLibrary/t-kernel/IPSocket.cc | UTF-8 | 1,444 | 2.953125 | 3 | [] | no_license | #include "IPSocket.hh"
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
using namespace std;
///////////////////////////////////
//IPSocket
///////////////////////////////////
IPSocket::IPSocket(){
status=IPSocketInitialized;
timeoutDurationInMilliSec=0;
setPort(-1);
}
IPSocket::~IPSocket(){}
int IPSocket::getStatus(){
return status;
}
bool IPSocket::isConnected(){
if(status==IPSocketConnected){
return true;
}else{
return false;
}
}
int IPSocket::send(void* data,unsigned int length) throw(IPSocketException){
int result=::so_send(socketdescriptor,(char*)data,length,0);
if(result<0){
throw IPSocketException("IPSocket::send() exception");
}
return result;
}
int IPSocket::receive(void* data,unsigned int length) throw(IPSocketException){
int result=::so_recv(socketdescriptor,(char*)data,length,0);
if(result<=0){
cout << "TCP/IP Connection closed" << endl;
throw IPSocketException("IPSocket::receive() connection closed");
}
return result;
}
void IPSocket::setSocketDescriptor(int newsocketdescriptor){
socketdescriptor=newsocketdescriptor;
}
void IPSocket::setPort(unsigned short newport){
port=newport;
}
int IPSocket::getPort(){
return port;
}
void IPSocket::setTimeout(unsigned int durationInMilliSec){
timeoutDurationInMilliSec=durationInMilliSec;
struct timeval tv;
tv.tv_sec = (unsigned int)(durationInMilliSec/1000.);
tv.tv_usec = (int)((durationInMilliSec/1000.)*1000);
}
| true |
24471f7918f32d1f7e35f86b9925df6919345555 | C++ | lexingsen/Data-Structure | /Algorithm/Greedy/452.cc | UTF-8 | 545 | 2.8125 | 3 | [] | no_license | /*
* @Description
* @Language:
* @Author:
* @Date: 2020-10-28 10:51:11
*/
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
bool cmp(const pii &a, const pii &b) {
return a.second < b.second;
}
int findMinArrowShots(vector<pii> &points) {
sort(points.begin(), points.end(), cmp);
int res = 0, r = INT_MIN;
if (points.size() >= 1 && points[0].first == INT_MIN) res ++;
for (auto p:points) {
if (p.first > r) {
r = p.second;
res ++;
}
}
return res;
}
| true |
427c9d031a6861868eac1fe0485ca49cfb7734e3 | C++ | Yancyzhan/lab2 | /square.cpp | UTF-8 | 839 | 2.96875 | 3 | [] | no_license | // square.cpp
// ENSF 480 - Lab2 - Exercise A
// Author: Yanzhao Zhang 30031217 and Kazi Ashfaq 30021563
//
// Date: Sept 21, 2018
#include "square.h"
#include <string.h>
#include <iostream>
using namespace std;
/*Square::Square(double x, double y, double side,char* name):Shape(x,y,name){
side_a = side;
}*/
double Square::getArea(){
return Square::calculateArea();
}
double Square::calculateArea(){
return side_a * side_a;
}
double Square::getPerimeter(){
return calculatePer();
}
double Square::calculatePer(){
return (4 * side_a);
}
void Square::display(){
cout<<"square name: "<<getName() << endl;
cout<<"X-coordinate: "<< origin.getX() <<endl;
cout<<"Y-coordinate: "<< origin.getY() <<endl;
cout<<"Side a: "<< getSide()<<endl;
cout<<"Area: "<< getArea()<<endl;
cout<<"Perimeter: "<< getPerimeter() <<endl;
} | true |
89ed6ca02f1a3113f2fb3416e3e67714299092e7 | C++ | Woloda/Lab_5_1_F | /Lab_5.1(F)/Triad.cpp | UTF-8 | 2,484 | 3.5625 | 4 | [] | no_license | #include <stdexcept>
#include <iostream>
#include <string>
#include "My_Error_Range.h"
#include "Triad.h"
Triad::Triad() { x = 3; y = 4; z = 5; } //конструктор за умовчанням(без параметрів)
Triad::Triad(const number v_x, const number v_y, const number v_z) throw(My_Error_Range) { //конструктор ініціалізації
if ((v_z > (v_x + v_y)) || (v_x > (v_z + v_y)) || (v_y > (v_x + v_z)))
throw new My_Error_Range("\n\n!!!Incorrectly entered data!!!"); //генерування об'єкта винятка
x = v_x;
y = v_y;
z = v_z;
}
Triad::Triad(const Triad& obj) { //конструктор копіювання
x = obj.x;
y = obj.y;
z = obj.z;
}
std::ostream& operator << (std::ostream& out, Triad& obj) { //операції виводу
out << "\n\nEnter the number x: " << obj.x;
out << "\nEnter the number y: " << obj.y;
out << "\nEnter the number z: " << obj.z;
return out;
}
std::istream& operator >> (std::istream& in, Triad& obj) throw(std::out_of_range) { //операції вводу
number a, b, c;
std::cout << "\n\nEnter the side: ";
std::cout << "\n\nEnter the number x: "; in >> a;
std::cout << "Enter the number y: "; in >> b;
std::cout << "Enter the number z: "; in >> c;
/*Використання стандартного винятка
Успадкований від std :: logic_error.
Визначає виняток, яке повинно бути кинуто в тому випадку,
коли відбувається вихід за межі допустимого діапазону значень об'єкта*/
if ((c > (a + b)) || (a > (c + b)) || (b > (a + c)))
throw std::out_of_range{ "\n\n!!!Data entered incorrectly!!!" }; //генерування об'єкта винятка
obj.Set_x(a);
obj.Set_y(b);
obj.Set_z(c);
return in;
}
Triad& Triad::operator =(const Triad& obj) { //перевантаження операції "присвоєння"
x = obj.x;
y = obj.y;
z = obj.z;
return *this;
}
Triad::operator std::string() const { //перетворення до літерного рядку --- "операції приведення типу"
std::string str;
std::stringstream sout;
sout << "\n\ncoordinate x: " << x;
sout << "\ncoordinate y: " << y;
sout << "\ncoordinate z: " << z;
return sout.str();
}
number Triad::Addition() { //обчислення суми чисел
return x + y + z;
} | true |
b761b331a3896584ae88c34dc62db7ac27f9fdd3 | C++ | harrywhite-sd/TCPIP | /TCPIP/ServerSocket.cpp | UTF-8 | 1,451 | 2.796875 | 3 | [] | no_license | #include "ServerSocket.h"
#pragma warning(disable:4996)
int ServerSocket::ServerThread()
{
cout << "Starting up TCP server\r\n";
WSADATA wsaData;
sockaddr_in local;
int wsaret = WSAStartup(0x101, &wsaData);
if (wsaret != 0)
{
return 0;
}
//Now we populate the sockaddr_in structure
local.sin_family = AF_INET; //Address family
local.sin_addr.s_addr = INADDR_ANY; //Wild card IP address
local.sin_port = htons((u_short)20248); //port to use
//the socket function creates our SOCKET
server = socket(AF_INET, SOCK_STREAM, 0);
//If the socket() function fails we exit
if (server == INVALID_SOCKET)
{
return 0;
}
if (bind(server, (sockaddr*)&local, sizeof(local)) != 0)
{
return 0;
}
if (listen(server, 10) != 0)
{
return 0;
}
return 0;
}
UINT ServerSocket::acceptClient() {
//we will need variables to hold the client socket.
//thus we declare them here.
SOCKET client;
sockaddr_in from;
int fromlen = sizeof(from);
client = accept(server, (struct sockaddr*) & from, &fromlen);
cout << "ACCEPTED" << endl;
char temp[512];
recv(client, temp, strlen(temp), 0);
cout << "Message recieved: " << temp << endl;
closesocket(client);
closesocket(server);
//originally this function probably had some use
//currently this is just for backward compatibility
//but it is safer to call it as I still believe some
//implementations use this to terminate use of WS2_32.DLL
WSACleanup();
return 0;
}
| true |
d0ab21733264d430f99b81b3d17184466a234797 | C++ | shacl/optional | /include/shacl/optional/Type/test/equality.test.cpp | UTF-8 | 8,819 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | #include "shacl/optional.hpp"
#include "catch2/catch.hpp"
struct RightFalseEquality {};
template<typename T,
std::enable_if_t
<not shacl::optional::IsInstance_v<T>, bool> = true>
bool operator==(const T&, RightFalseEquality){ return false; }
struct RightTrueEquality {};
template<typename T,
std::enable_if_t
<not shacl::optional::IsInstance_v<T>, bool> = true>
bool operator==(const T&, RightTrueEquality){ return true; }
struct LeftFalseEquality {};
template<typename T,
std::enable_if_t
<not shacl::optional::IsInstance_v<T>, bool> = true>
bool operator==(LeftFalseEquality, const T&){ return false; }
struct LeftTrueEquality {};
template<typename T,
std::enable_if_t
<not shacl::optional::IsInstance_v<T>, bool> = true>
bool operator==(LeftTrueEquality, const T&){ return true; }
SCENARIO("equality"){
GIVEN("a type with an equality operator which returns a boolean"){
struct EqualityComparable {
bool operator==(const EqualityComparable&) const { return true; }
};
GIVEN("an instance of an optional instantiation of the type"){
shacl::Optional<EqualityComparable> oe;
GIVEN("the instance is disengaged"){
WHEN("equality compared to a right nullopt"){
THEN("the operation returns true"){
REQUIRE(oe == shacl::optional::nullopt);
}
}
WHEN("equality compared to a right instance of the type"){
THEN("the operation returns false"){
REQUIRE_FALSE(oe == EqualityComparable{});
}
}
WHEN("equality compared to a right instance of"
" a distinct (but equality comparable) type"){
GIVEN("the equality would return true with an instance of the left type"){
THEN("the operation returns false"){
REQUIRE_FALSE(oe == RightTrueEquality{});
}
}
GIVEN("the equality would return false with an instance of the left type"){
THEN("the operation returns false"){
REQUIRE_FALSE(oe == RightFalseEquality{});
}
}
}
WHEN("equality compared to a right optional instance of the type"){
shacl::Optional<EqualityComparable> other;
GIVEN("the right optional is disengaged"){
THEN("the operation returns true"){
REQUIRE(oe == other);
}
}
GIVEN("the right optional is engaged"){
other = EqualityComparable{};
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
}
WHEN("equality compared to a right optional instance of"
" a distinct (but equality comparable) type"){
GIVEN("the right optional is disengaged"){
GIVEN("the equality would return true with an instance of the left type"){
shacl::Optional<RightTrueEquality> other;
THEN("the operation returns true"){
REQUIRE(oe == other);
}
}
GIVEN("the equality would return false with an instance of the left type"){
shacl::Optional<RightFalseEquality> other;
THEN("the operation returns true"){
REQUIRE(oe == other);
}
}
}
GIVEN("the right optional is engaged"){
GIVEN("the equality would return true with an instance of the left type"){
shacl::Optional<RightTrueEquality> other = RightTrueEquality{};
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
GIVEN("the equality would return false with an instance of the left type"){
shacl::Optional<RightFalseEquality> other = RightFalseEquality{};
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
}
}
WHEN("equality compared to a left nullopt"){
THEN("the operation returns true"){
REQUIRE(shacl::optional::nullopt == oe);
}
}
WHEN("equality compared to a left instance of the type"){
THEN("the operation returns false"){
REQUIRE_FALSE(EqualityComparable{} == oe);
}
}
WHEN("equality compared to a left instance of"
" a distinct (but equality comparable) type"){
GIVEN("the equality would return true with an instance of the right type"){
THEN("the operation returns false"){
REQUIRE_FALSE(LeftTrueEquality{} == oe);
}
}
GIVEN("the equality would return false with an instance of the right type"){
THEN("the operation returns false"){
REQUIRE_FALSE(LeftFalseEquality{} == oe);
}
}
}
}
GIVEN("the instance is engaged"){
oe = EqualityComparable{};
WHEN("equality compared to a right nullopt"){
THEN("the operation returns false"){
REQUIRE_FALSE(oe == shacl::optional::nullopt);
}
}
WHEN("equality compared to a right instance of the type"){
THEN("the operation returns true"){
REQUIRE(oe == EqualityComparable{});
}
}
WHEN("equality compared to a right instance of"
" a distinct (but equality comparable) type"){
GIVEN("the equality would return true with an instance of the left type"){
THEN("the operation returns true"){
REQUIRE(oe == RightTrueEquality{});
}
}
GIVEN("the equality would return false with an instance of the left type"){
THEN("the operation returns false"){
REQUIRE_FALSE(oe == RightFalseEquality{});
}
}
}
WHEN("equality compared to a right optional instance of the type"){
shacl::Optional<EqualityComparable> other;
GIVEN("the right optional is disengaged"){
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
GIVEN("the right optional is engaged"){
other = EqualityComparable{};
THEN("the operation returns true"){
REQUIRE(oe == other);
}
}
}
WHEN("equality compared to a right optional instance of"
" a distinct (but equality comparable) type"){
GIVEN("the right optional is disengaged"){
GIVEN("the equality would return true with an instance of the left type"){
shacl::Optional<RightTrueEquality> other;
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
GIVEN("the equality would return false with an instance of the left type"){
shacl::Optional<RightFalseEquality> other;
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
}
GIVEN("the right optional is engaged"){
GIVEN("the equality would return true with an instance of the left type"){
shacl::Optional<RightTrueEquality> other = RightTrueEquality{};
THEN("the operation returns true"){
REQUIRE(oe == other);
}
}
GIVEN("the equality would return false with an instance of the left type"){
shacl::Optional<RightFalseEquality> other = RightFalseEquality{};
THEN("the operation returns false"){
REQUIRE_FALSE(oe == other);
}
}
}
}
WHEN("equality compared to a left nullopt"){
THEN("the operation returns false"){
REQUIRE_FALSE(shacl::optional::nullopt == oe);
}
}
WHEN("equality compared to a left instance of the type"){
THEN("the operation returns true"){
REQUIRE(EqualityComparable{} == oe);
}
}
WHEN("equality compared to a left instance of"
" a distinct (but equality comparable) type"){
GIVEN("the equality would return true with an instance of the right type"){
THEN("the operation returns true"){
REQUIRE(LeftTrueEquality{} == oe);
}
}
GIVEN("the equality would return false with an instance of the right type"){
THEN("the operation returns false"){
REQUIRE_FALSE(LeftFalseEquality{} == oe);
}
}
}
}
}
}
}
| true |
c0c7f5bfb46980c31c63791d13f4334e7c6bfecc | C++ | ssehuun/langStudy | /data_structure/stack/stack_stl.cpp | UTF-8 | 564 | 3.3125 | 3 | [] | no_license | /*
19.02.14
<Stack implemented with STL>
input value
8
size
push 4
push 3
top
size
pop
top
size
output value
0
3
2
4
1
*/
#include <stack>
#include <iostream>
#include <string>
using namespace std;
int N, val;
string cmd;
int main(){
stack<int> st;
cin >> N;
for(int i=0; i<N; i++){
cin >> cmd;
if(cmd[0] == 's'){
cout << st.size() << endl;
}else if(cmd[0] == 'p'){
if(cmd[1] == 'u'){
cin >> val;
st.push(val);
}else if(cmd[1] == 'o'){
st.pop();
}
}else if(cmd[0] == 't'){
cout << st.top() << endl;
}
}
return 0;
}
| true |
db7ec73179d90f6061733ca1816fe7368aa8e31b | C++ | cjmms/MimicEngine | /Mimic/Mimic/src/Core/Model.h | UTF-8 | 1,170 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Mesh.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
/*
* .obj model file
* Architecture of Model:
* Each model contains a tree of nodes
* Each node contains meshes
* Each mesh contain vertices, indices, Material(textures)
*/
class Model
{
public:
Model(const char* path);
void Draw(Shader& shader) const;
private:
std::vector<Mesh> meshes;
std::vector<Texture> textures_loaded;
// path to current model object
std::string directory;
// Entry point of loading a model
void loadModel(std::string path);
// loading a tree of nodes recursives, for each node, load its mesh
void processNode(aiNode* node, const aiScene* scene);
// load vertices, indices and material(textures) from mesh
Mesh processMesh(aiMesh* mesh, const aiScene* scene);
std::vector<Vertex> processVertices(aiMesh* mesh) const;
std::vector<unsigned int> processIndices(aiMesh* mesh) const;
// helper function, convert aiVector3D to glm::vec3
void setVec3(glm::vec3& des, aiVector3D& source) const;
std::vector<Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName);
};
| true |
3b445f17fb6d1933233b868395cf90b138011c7c | C++ | C-mmon/Ray_Tracer | /skeleton.cpp | UTF-8 | 536 | 2.796875 | 3 | [] | no_license | #include <iostream>
const int image_width=256;
const int image_height=256;
using namespace std;
int main()
{
cout<<"P3"<<endl;
cout<<image_width<<" "<<image_height<<endl;
for(int j=image_height-1;j>=0;--j)
{
for(int i=0;i<image_width;i++)
{
auto r=double(i)/(image_width-1);
auto g=double(i)/(image_width-1);
auto b=0.25;
int ir=static_cast<int>(r;
int ig=static_cast<int>(g)
int ib=static_cast<int>(b)
cout<<ir<<' '<<ig<<' '<<ib<<'\n';
}
}
return 0;
}
| true |
61f37ac4387c06772c3ed686d656a6934cf311c7 | C++ | jinyung2/csci-140 | /Lab_6/quartsal.cpp | UTF-8 | 3,458 | 3.8125 | 4 | [] | no_license | /* Program: quartsal.cpp
Author: Jin Choi
Class: CSCI 140
Date: 10/10/2018
Description: Program that prints 2d array but with different values for first col of table.
I certify that the code below is my own work.
Exception(s): book code, editted to fill out function calls.
*/
#include <iostream>
#include <iomanip>
using namespace std;
const int MAXYEAR = 10;
const int MAXCOL = 5;
typedef int SalesType[MAXYEAR][MAXCOL]; // creates a new 2D integer data type
void getSales(SalesType, int&); // places sales figures into the array
void printSales(SalesType, int); // prints data as a table
void printTableHeading(); // prints table heading
int main()
{
int yearsUsed; // holds the number of years used
SalesType sales; // 2D array holding
// the sales transactions
getSales(sales, yearsUsed); // calls getSales to put data in array
printTableHeading(); // calls procedure to print the heading
printSales(sales, yearsUsed); // calls printSales to display table
return 0;
}
//*****************************************************************************
// printTableHeading
//
// task: This procedure prints the table heading
// data in: none
// data out: none
//
//*****************************************************************************
void printTableHeading()
{
cout << setw(30) << "YEARLY QUARTERLY SALES" << endl << endl << endl;
cout << setw(10) << "YEAR" << setw(10) << "Quarter 1"
<< setw(10) << "Quarter 2" << setw(10) << "Quarter 3"
<< setw(10) << "Quarter 4" << endl;
}
//*****************************************************************************
// getSales
//
// task: This procedure asks the user to input the number of years.
// For each of those years it asks the user to input the year
// (e.g. 2004), followed by the sales figures for each of the
// 4 quarters of that year. That data is placed in a 2D array
// data in: a 2D array of integers
// data out: the total number of years
//
//*****************************************************************************
void getSales(SalesType table, int& numOfYears)
{
cout << "Please input the number of years (1-" << MAXYEAR << ')' << endl;
cin >> numOfYears;
for (int i = 0; i < numOfYears; i++){
for (int j = 0; j < MAXCOL; j++){
if (j == 0) {
cout << "Input year " << endl;
cin >> table[i][j];
}
else{
cout << "Please input the quarterly sales" << endl;
cin >> table[i][j];
}
}
}
// Fill in the code to read and store the next value
}
//*****************************************************************************
// printSales
//
// task: This procedure prints out the information in the array
// data in: an array containing sales information
// data out: none
//
//*****************************************************************************
void printSales(SalesType table, int numOfYears)
{
for (int i = 0; i < numOfYears; i++){
for (int j = 0; j < MAXCOL; j++){
cout << setw(10) << table[i][j];
}
cout << endl;
}
// Fill in the code to print the table
} | true |
2dcfdbb2c0d76589f732b433f8b039f63457062e | C++ | guyueshui/JianZhiOffer | /ReversePrint.cpp | UTF-8 | 1,846 | 3.703125 | 4 | [] | no_license | // Problem: print from the end to begining of
// a given linked list.
/*
* 1. use stack
* 2. use recursion
*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class ListNode {
public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
// boundary case
if (head == nullptr) return ret;
stack<int> s;
for (auto p = head; p != nullptr; p = p -> next) {
s.push(p -> val);
}
while (!s.empty()) {
ret.push_back(s.top());
s.pop();
}
return ret;
}
// recursive needs a member variable
// use recursion stack, tricky
vector<int> arr;
vector<int> reversePrint(ListNode* head) {
if (head) {
reversePrint(head -> next);
arr.push_back(head -> val);
}
return arr;
}
/*
* Consider the closure, at one recursive step,
* what I should do? Let's drop all the details,
* just look one recursive step.
* What had I done?
* Oh gee, I see if the head is not null,
* I must push the value to the vector,
* but before this, I should take a look at
* `head -> next`, since I have to push
* the tail first. So which one can help me
* do this? Yes, the function itself! Then
* after I have addressed the tail, now I'm
* going to push current value to the vector.
* That's all I need!
* The key is you work in one recursive step, and
* form a closure for the next, and do not forget
* the base case (stopping rules). That how
* recursion runs! And you are free of those
* confusing details.
*/
};
| true |
f48ed94bda0cd5c14a6e00d8826b9847102f0322 | C++ | MLambeva/Raster-graphics | /RGB.h | WINDOWS-1251 | 692 | 2.9375 | 3 | [] | no_license | #ifndef RGB_H
#define RGB_H
#include<string>
#include<iostream>
#include<cassert>
#include "Formats.h"
// .ppm , .
class RGB
{
private:
int red;
int green;
int blue;
public:
RGB() :red(0), green(0), blue(0) {};
int getRed() const;
int getGreen() const;
int getBlue() const;
void setRed(const int &red);
void setGreen(const int &green);
void setBlue(const int &blue);
RGB setColor(int red, int green, int blue);
friend std::ostream& operator << (std::ostream& out, const RGB& other);
};
#endif | true |
e4458dd2df4da2ad14c7af4b30fe6d423ad71d6b | C++ | WhiZTiM/coliru | /Archive2/26/207a256baf3eb2/main.cpp | UTF-8 | 1,260 | 2.96875 | 3 | [] | no_license | #include <math.h>
#include <stdio.h>
#include <emmintrin.h>
#include <xmmintrin.h>
__m128 my_exp2(__m128 x){
/* x = u + n where u in [0, 1] */
__m128i n = _mm_cvttps_epi32(x);
__m128 d, u = _mm_sub_ps(x, _mm_cvtepi32_ps(n));
/* taylor series for 2^u */
d = _mm_set1_ps(0.013670309453328856f);
d *= u;
d += _mm_set1_ps(0.05174499776416041f);
d *= u;
d += _mm_set1_ps(0.24160435727005664f);
d *= u;
d += _mm_set1_ps(0.6929729221730601f);
d *= u;
d += _mm_set1_ps(1.000003492907698f);
/* use floating point representation to calculate 2^n */
/* _mm_shl_epi32 only available with XOP instruction set */
n = _mm_add_epi32(n, _mm_set1_epi32(127));
n = _mm_slli_epi32(n, 23);
/* 2^x = 2^(u + n) = 2^u * 2^n */
return _mm_mul_ps(d, *(__m128*)&n);
}
__m128 my_exp(__m128 x){
/* e^x = 2^(x/log(2)) */
return my_exp2(_mm_mul_ps(x, _mm_set1_ps(1.4426950408889634f)));
}
int main(){
__m128 a;
float *f = (float*)&a;
f[0] = 0.1f;
f[1] = 1.0f;
f[2] = 6.66f;
f[3] = 13.37f;
printf("expected: %f %f %f %f\n", expf(f[0]), expf(f[1]), expf(f[2]), expf(f[3]));
a = my_exp(a);
printf("result : %f %f %f %f\n", f[0], f[1], f[2], f[3]);
return 0;
}
| true |
d8a52742c478e37c3fd520d8772c8f110b8eaa58 | C++ | shashank9aug/DSA_CB | /Dynamic_Programming/DP_Base/count_subset_with_given_diff.cpp | UTF-8 | 1,175 | 3.203125 | 3 | [] | no_license | /*
$ ./a.exe
4
1
1 1 2 3
3
*/
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int countSubsetSum(vector<int>arr, int sum, int n)
{
int t[n + 1][sum + 1];
//Initialization :
for (int i = 0; i <= n; i++)
{
t[i][0] = 1;
}
for (int i = 1; i <= sum; i++)
{
t[0][i] = 0;
}
//Smaller Input :
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if (arr[i - 1] <= j)
{
t[i][j] = t[i - 1][j - arr[i - 1]] + t[i - 1][j];
}
else
t[i][j] = t[i - 1][j];
}
}
// for(int i=0;i<(n+1);i++){
// for(int j=0;j<(sum+1);j++){
// cout<<t[i][j]<<", ";
// }
// cout<<endl;
// }
return t[n][sum];
}
int main(){
int n;
cin>>n;
int diff;
cin>>diff;
vector<int>vec;
for(int i=0;i<n;i++){
int d;
cin>>d;
vec.emplace_back(d);
}
int svec=accumulate(vec.begin(),vec.end(),0);
int sum=(diff+svec)/2;
cout<<countSubsetSum(vec,sum,n)<<endl;
return 0;
} | true |
84a65dbbf2ef4af2113f532eda23db600bd39d44 | C++ | pauek/ccjs | /tests/aprox_e.cc | UTF-8 | 325 | 3.046875 | 3 | [] | no_license |
#include <iostream>
using namespace std;
// e^x: 1 + x + x^2/2! + x^3/3! + x^4/4! + ...
// en nmax = 35 --> inf...
int main()
{
int nmax, fact = 1, i = 1;
double e = 1.0;
cin >> nmax;
while ( i < nmax )
{
e += 1.0 / float(fact);
i++;
fact *= i;
}
cout.precision(15);
cout << e << endl;
}
| true |
e712d8628d37f90b707069a95901ec355eb220b3 | C++ | cdsupina/Arduino-Examples | /Arduino Uno/Gripper_Control/Gripper_Control.ino | UTF-8 | 942 | 2.890625 | 3 | [] | no_license | /* Sweep
by BARRAGAN <http://barraganstudio.com>
This example code is in the public domain.
modified 8 Nov 2013
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Sweep
*/
#include <Servo.h>
Servo myservo;
char val;
boolean opened;
boolean closed;
int openSpeed = 30;
void setup() {
myservo.attach(8); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
openGripper();
}
void loop() {
if(Serial.available()){
val = Serial.read();
}
if(val == '1'){
openGripper();
}
if(val == '2'){
closeGripper();
}
Serial.println(myservo.read());
}
void closeGripper(){
for (int pos = myservo.read(); pos >= 61; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos);
delay(openSpeed);
}
}
void openGripper(){
for (int pos = myservo.read(); pos <= 143; pos += 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos);
delay(openSpeed);
}
}
| true |
63d6190b65cd4389791d169e5d9a651a30560e83 | C++ | keineahnung2345/cpp-code-snippets | /time_t(long_int)_to_and_from_string.cpp | UTF-8 | 564 | 3.3125 | 3 | [] | no_license | #include <time.h>
#include <string>
#include <iostream>
//https://stackoverflow.com/questions/37505001/how-do-i-convert-a-unix-timestamp-string-to-time-t-in-c11
int main()
{
time_t timer;
std::string timer_str;
time_t timer_back;
time(&timer);
std::cout << "time_t: " << (long int)timer << std::endl;
timer_str = std::to_string((long int)timer);
std::cout << "convert to string: " << timer_str << std::endl;
timer_back = (time_t)stol(timer_str);
std::cout << "back to time_t: " << timer_back << std::endl;
return 0;
}
| true |
0c3ee8e5eef9c48c92e633b7b0bdc3e2ac6fb8b7 | C++ | ab4295/C_plusplus_Training | /Cpp(6)/exercise/pe12/pe12-2/pe12-02.cpp | UHC | 1,317 | 3.8125 | 4 | [] | no_license | // pe12-02.cpp -- 12 α 2
// string2.cpp Բ Ѵ
#include <iostream>
using namespace std;
#include "string2.h"
int main()
{
String s1(" and I am a C++ student.");
String s2 = " ̸ ԷϽʽÿ: ";
String s3;
cout << s2; // ε <<
cin >> s3; // ε >>
s2 = "My name is " + s3; // ε =, +
cout << s2 << ".\n";
s2 = s2 + s1;
s2.stringup(); // ڿ 빮ڷ ȯѴ
cout << " ڿ\n" << s2 << "\n 'A' "
<< s2.has('A') << " ֽϴ.\n";
s1 = "red"; // String(const char *),
// String & operator=(const String &) Ѵ
String rgb[3] = { String(s1), String("green"), String("blue") };
cout << " ̸ ϳ ԷϽʽÿ: ";
String ans;
bool success = false;
while (cin >> ans)
{
ans.stringlow(); // ڿ ҹڷ ȯѴ
for (int i = 0; i < 3; i++)
{
if (ans == rgb[i])
{
cout << "¾ҽϴ!\n";
success = true;
break;
}
}
if (success)
break;
else
cout << "ٽ ԷϽʽÿ: ";
}
cout << "α մϴ.\n";
return 0;
}
| true |
6b978887a11ee6df03e6670c3a5c8dfa0b71201f | C++ | CodeOpsTech/DesignPatternsCpp | /dp/cpp/dps/decorator/visualcomponent/DecoratorMain.cpp | UTF-8 | 806 | 2.890625 | 3 | [] | no_license | #include "DecoratorMain.h"
VisualComponent::~VisualComponent() { }
void TextView::draw()
{
std::cout << std::string("Calling TextView.draw()") << std::endl;
}
Decorator::Decorator(VisualComponent *component)
{
this->component = component;
}
void Decorator::draw()
{
if (component != nullptr)
{
component->draw();
}
}
ScrollDecorator::ScrollDecorator(VisualComponent *component) : Decorator(component)
{
}
void ScrollDecorator::draw()
{
Decorator::draw();
std::cout << std::string("Calling ScrollDecorator.draw()") << std::endl;
}
BorderDecorator::BorderDecorator(VisualComponent *component) : Decorator(component)
{
}
void BorderDecorator::draw()
{
Decorator::draw();
std::cout << std::string("Calling BorderDecorator.draw()") << std::endl;
}
| true |
b483f5e6a5a91bdf7745400cba825c83b1fc061e | C++ | charles-pku-2013/CodeRes_Cpp | /Templates/Example_Code/examples/meta/sqrt4.hpp | UTF-8 | 1,099 | 2.875 | 3 | [] | no_license | /* The following code example is taken from the book
* "C++ Templates - The Complete Guide"
* by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002
*
* (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#ifndef SQRT_HPP
#define SQRT_HPP
#include "ifthenelse.hpp"
// template to yield template argument as result
template<int N>
class Value {
public:
enum { result = N };
};
// template to compute sqrt(N) via iteration
template <int N, int I=1>
class Sqrt {
public:
// instantiate next step or result type as branch
typedef typename IfThenElse<(I*I<N),
Sqrt<N,I+1>,
Value<I>
>::ResultT
SubT;
// use the result of branch type
enum { result = SubT::result };
};
#endif // SQRT_HPP
| true |
ca24246da83ee4ea52192f4419fd5ace8f1aba1a | C++ | keisuke-kanao/my-UVa-solutions | /Problem Set Volumes/Volume 13 (1300-1399)/UVa_1347_Tour.cpp | UTF-8 | 1,442 | 3.203125 | 3 | [] | no_license |
/*
UVa 1347 - Tour
To build using Visual Studio 2012:
cl -EHsc -O2 UVa_1347_Tour.cpp
*/
#include <algorithm>
#include <vector>
#include <utility>
#include <limits>
#include <cstdio>
#include <cmath>
using namespace std;
const double infinite = numeric_limits<double>::max();
int main()
{
int n;
while (scanf("%d", &n) != EOF) {
vector< pair<double, double> > points(n);
for (int i = 0; i < n; i++)
scanf("%lf %lf", &points[i].first, &points[i].second);
vector< vector<double> > distances(n, vector<double>(n));
for (int i = 0; i < n - 1; i++) {
distances[i][i] = 0.0;
for (int j = i + 1; j < n; j++)
distances[i][j] = distances[j][i] = hypot(points[i].first - points[j].first, points[i].second - points[j].second);
}
vector< vector<double> > bitonic_tsp(n, vector<double>(n));
bitonic_tsp[0][0] = 0.0;
bitonic_tsp[0][1] = distances[0][1];
// fill the first row
for (int j = 2; j < n; j++)
bitonic_tsp[0][j] = bitonic_tsp[0][j - 1] + distances[j - 1][j];
// fill the remaining rows
for (int i = 1; i < n; i++) {
for (int j = i; j < n; j++) {
if (i == j || i == j - 1) {
bitonic_tsp[i][j] = infinite;
for (int k = 0; k < i; k++)
bitonic_tsp[i][j] = min(bitonic_tsp[i][j], bitonic_tsp[k][i] + distances[k][j]);
}
else
bitonic_tsp[i][j] = bitonic_tsp[i][j - 1] + distances[j - 1][j];
}
}
printf("%.2lf\n", bitonic_tsp[n - 1][n - 1]);
}
return 0;
}
| true |
66b599dc8b14a8c8851851e6c5bdb030951ba0b9 | C++ | shaylagrymaloski/CodingProjects | /CSC 226/Lab3.cpp | UTF-8 | 1,739 | 3.5 | 4 | [] | no_license | // Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int calcHashVal(std::string str, int n){
int result = 0;
for(char& c : str) {
result = int(c) + result;
}
return result%11;
}
void insertHash(std::vector<std::vector<std::string> > &vec, std::string str, int n){
std::string temp;
for(int i = 0; i< str.length()-n; i ++ ){
std::string substring = str.substr(i, i+n);
int val = calcHashVal(substring, n);
vec[val].push_back(substring);
}
}
std::string mostOccuringString(std::vector<std::vector<std::string> > &vec,int n){
// sort all of the "chains"
int maxStringCount;
std::string currMaxString;
for(int i = 0; i< sizeof(vec); i ++ ){
std::sort(vec[i].begin(), vec[i].end());
}
for(int i = 0; i< sizeof(vec); i ++ ){
if(sizeof(vec[i]) == 0 ){
continue;
}
int count = 0;
for(int j = 0; j< sizeof(vec[i]); j++ ){
count ++;
if(vec[i][j] != vec[i][j+1]){
if(count > maxStringCount){
maxStringCount = count;
currMaxString = vec[i][j];
}
count = 0;
}
}
}
return currMaxString;
}
int main()
{
int i,j,n;
std::string str;
// Taking input
std::cin>>n;
std::cin>>str;
std::vector<std::vector<std::string> > vec(7);
// Write your hash function and calculate hash for each index
insertHash(vec, str, n);
// Determine which hash appears the most, save it's starting index
str = mostOccuringString(vec,n);
// Output the result
std::cout << str;
return 0;
} | true |
05a5ec4ec5d312335fafe48afbfbc683f784f5e1 | C++ | DanyilSomin/Somin_Tetris | /Somin_Tetris/Button.cpp | UTF-8 | 2,270 | 3.078125 | 3 | [] | no_license | #include "Button.h"
bool Button::lastUpdateMouseDown = false;
Button::Button(const sf::Vector2f &position,
const std::string &text,
const std::function<void(void)> &onClickEvent)
: m_position{ position }, m_onClickEvent{ onClickEvent }, m_text{ text }
{
m_font.loadFromFile(FONT_PATH);
m_texts.resize(ButtonState::BTN_STATES_COUNT);
for (auto &txt : m_texts)
{
defaultTextInit(txt);
}
m_texts[ButtonState::NORMAL].setFillColor(sf::Color::White);
m_texts[ButtonState::HOWERED].setFillColor(sf::Color(200, 200, 200, 255));
m_texts[ButtonState::CLICKED].setFillColor(sf::Color(160, 160, 160, 255));
}
void Button::setText(const std::string &text)
{
m_text = text;
for (auto &txt : m_texts)
{
txt.move(txt.getGlobalBounds().width / 2, 0);
txt.setString(text);
txt.move(-txt.getGlobalBounds().width / 2, 0);
}
}
void Button::draw(sf::RenderWindow & window)
{
window.draw(getText());
update(window);
}
void Button::update(sf::RenderWindow &window)
{
if (!window.hasFocus()) { return; }
if (m_texts[m_state].getGlobalBounds().contains(
static_cast<sf::Vector2f>(window.mapPixelToCoords(sf::Mouse::getPosition(window)))))
{
if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left))
{
if (!Button::lastUpdateMouseDown)
{
Button::lastUpdateMouseDown = true;
MusicManager::playClick();
m_state = ButtonState::CLICKED;
m_onClickEvent();
}
}
else if (m_state != ButtonState::HOWERED)
{
if (m_state == ButtonState::NORMAL)
{
MusicManager::playSelect();
}
m_state = ButtonState::HOWERED;
Button::lastUpdateMouseDown = false;
}
else
{
lastUpdateMouseDown = false;
}
}
else if (m_state == ButtonState::CLICKED)
{
m_state = ButtonState::HOWERED;
}
else
{
m_state = ButtonState::NORMAL;
}
}
void Button::defaultTextInit(sf::Text &txt)
{
txt.setCharacterSize(m_fontSize);
txt.setFont(m_font);
txt.setString(m_text);
txt.setPosition(m_position);
txt.setFillColor(sf::Color::White);
txt.move(-txt.getGlobalBounds().width / 2, 0);
}
void Button::setPosition(const sf::Vector2f &m_position)
{
for (auto &text : m_texts)
{
text.setPosition(m_position);
}
}
void Button::move(const sf::Vector2f & delta)
{
for (auto &text : m_texts)
{
text.move(delta);
}
}
| true |
e179ecc2f4b445c9b3ca9e91a5e010dabfc9353b | C++ | TheAlgorithms/C-Plus-Plus | /geometry/graham_scan_algorithm.cpp | UTF-8 | 3,473 | 3.3125 | 3 | [
"MIT",
"CC-BY-SA-4.0"
] | permissive | /******************************************************************************
* @file
* @brief Implementation of the [Convex
* Hull](https://en.wikipedia.org/wiki/Convex_hull) implementation using [Graham
* Scan](https://en.wikipedia.org/wiki/Graham_scan)
* @details
* In geometry, the convex hull or convex envelope or convex closure of a shape
* is the smallest convex set that contains it. The convex hull may be defined
* either as the intersection of all convex sets containing a given subset of a
* Euclidean space, or equivalently as the set of all convex combinations of
* points in the subset. For a bounded subset of the plane, the convex hull may
* be visualized as the shape enclosed by a rubber band stretched around the
* subset.
*
* The worst case time complexity of Jarvis’s Algorithm is O(n^2). Using
* Graham’s scan algorithm, we can find Convex Hull in O(nLogn) time.
*
* ### Implementation
*
* Sort points
* We first find the bottom-most point. The idea is to pre-process
* points be sorting them with respect to the bottom-most point. Once the points
* are sorted, they form a simple closed path.
* The sorting criteria is to use the orientation to compare angles without
* actually computing them (See the compare() function below) because
* computation of actual angles would be inefficient since trigonometric
* functions are not simple to evaluate.
*
* Accept or Reject Points
* Once we have the closed path, the next step is to traverse the path and
* remove concave points on this path using orientation. The first two points in
* sorted array are always part of Convex Hull. For remaining points, we keep
* track of recent three points, and find the angle formed by them. Let the
* three points be prev(p), curr(c) and next(n). If the orientation of these
* points (considering them in the same order) is not counterclockwise, we
* discard c, otherwise we keep it.
*
* @author [Lajat Manekar](https://github.com/Lazeeez)
*
*******************************************************************************/
#include <cassert> /// for std::assert
#include <iostream> /// for IO Operations
#include <vector> /// for std::vector
#include "./graham_scan_functions.hpp" /// for all the functions used
/*******************************************************************************
* @brief Self-test implementations
* @returns void
*******************************************************************************/
static void test() {
std::vector<geometry::grahamscan::Point> points = {
{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
std::vector<geometry::grahamscan::Point> expected_result = {
{0, 3}, {4, 4}, {3, 1}, {0, 0}};
std::vector<geometry::grahamscan::Point> derived_result;
std::vector<geometry::grahamscan::Point> res;
derived_result = geometry::grahamscan::convexHull(points, points.size());
std::cout << "1st test: ";
for (int i = 0; i < expected_result.size(); i++) {
assert(derived_result[i].x == expected_result[i].x);
assert(derived_result[i].y == expected_result[i].y);
}
std::cout << "passed!" << std::endl;
}
/*******************************************************************************
* @brief Main function
* @returns 0 on exit
*******************************************************************************/
int main() {
test(); // run self-test implementations
return 0;
}
| true |
e85c9f57128634ed2edf3ffcfe4f66af972f91fd | C++ | HelenaGD/AEDA_Tema_2_Busqueda | /P6_Tabla_Hash_con_dispersion_cerrada/src/main.cpp | UTF-8 | 2,986 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include "tablahash.hpp"
#include "vector.hpp"
//#include "funciondispersion.hpp"
#include "fdmodulo.hpp"
#include "fdpseudoaleatoria.hpp"
//#include "funcionexploracion.hpp"
#include "felineal.hpp"
#include "fecuadratica.hpp"
#include "fedobledispersion.hpp"
#include "feredispersion.hpp"
#define INFINITO 999999
using Clave = int;
int RecogerCantidadPositiva(int cantidad_max = INFINITO) {
int cantidad = 0;
do {
std::cout << "\nInput: ";
std::cin >> cantidad;
} while ((cantidad <= 0) && (cantidad > cantidad_max));
return cantidad;
}
int main() {
FuncionDispersion<Clave> *fd;
FuncionExploracion<Clave> *fe;
TablaHash<Clave> *tabla;
int size_tabla = 0;
int tipo_dispersion = 0;
int tipo_exploracion = 0;
int opcion = 0;
int cantidad_sinonimos = 0;
// int cantidad_iteraciones = 0;
Clave elemento;
std::cout << "\nIndique el tamaño de la tabla: ";
size_tabla = RecogerCantidadPositiva();
std::cout << "\nIndique la cantidad de sinonimos que se permiten en la tabla: ";
cantidad_sinonimos = RecogerCantidadPositiva();
// std::cout << "\nIndique la cantidad de iteraciones maximas: ";
// cantidad_iteraciones = RecogerCantidadPositiva();
std::cout << "\nIndique el tipo de función de dispersión a utilizar:\n"
<< "(1) Función módulo\n(2) Función pseudoaleatoria\nOpción: ";
tipo_dispersion = RecogerCantidadPositiva(2);
switch (tipo_dispersion) {
case 1:
fd = new fdModulo<Clave>(size_tabla);
break;
case 2:
fd = new fdPseudoaleatoria<Clave>(size_tabla);
}
std::cout << "\nIndique el tipo de función de exploración a utilizar:\n"
<< "(1) Exploración Lineal\n(2) Exploración Cuadrática\n"
<< "(3) Doble dispersión\n(4) Redispersión\nOpción: ";
tipo_exploracion = RecogerCantidadPositiva(4);
switch (tipo_exploracion) {
case 1:
fe = new feLineal<Clave>;
break;
case 2:
fe = new feCuadratica<Clave>;
break;
case 3:
fe = new feDobleDispersion<Clave>(fd);
break;
case 4:
fe = new feReDispersion<Clave>;
break;
}
tabla = new TablaHash<Clave>(size_tabla, cantidad_sinonimos, fd, fe);
do {
std::cout << "\nElija una opción: \n" <<
"(0) Terminar programa\n(1) Insertar nuevo elemento\n" <<
"(2) Buscar elemento\nOpción: ";
std::cin >> opcion;
switch (opcion) {
case 1:
std::cout << "\nIntroduzca el elemento a insertar: ";
std::cin >> elemento;
if (tabla->Insertar(elemento)) {
std::cout << "\nSe ha insertado el elemento\n";
} else {
std::cout << "\nEl elemento no se ha podido insertar en la tabla\n";
}
break;
case 2:
std::cout << "\nIntroduzca el elemento a buscar: ";
std::cin >> elemento;
if (tabla->Buscar(elemento)) {
std::cout << "\nSe ha encontrado una coincidencia\n";
} else {
std::cout << "\nNo se ha encontrado coincidencias\n";
}
break;
default:
break;
}
tabla->printTabla();
} while (opcion != 0);
//delete fd;
delete tabla;
//system("clear");
} | true |
c719008d8cf53fbdf2a307c24b6f98a432c255ce | C++ | igortakeo/Competitive-Programing | /Laboratório de Algoritmos Avançados 1/29/ex29.cpp | UTF-8 | 950 | 2.671875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
#define pii pair<int,int>
using namespace std;
vector<tuple<int, int, int>>v;
vector<int> lis(int n){
vector<pii>dp[n];
vector<int>ans;
dp[0].push_back({get<1>(v[0]), get<2>(v[0])});
for(int i=1; i<n; i++){
for(int j=0; j < i; j++){
if(get<1>(v[i]) > get<1>(v[j]) and dp[i].size() < dp[j].size() + 1 and get<0>(v[i]) < get<0>(v[j])){
dp[i] = dp[j];
}
}
dp[i].push_back({get<1>(v[i]), get<2>(v[i])});
}
int m = 0;
for(int i=1; i<n; i++){
if(dp[i].size() > dp[m].size())m=i;
}
for(auto a : dp[m])ans.push_back(a.second);
return ans;
}
int main(){
int x, y;
int i=1;
while(scanf("%d %d",&x, &y) != EOF){
v.push_back(make_tuple(x, y, i));
i++;
}
sort(v.rbegin(), v.rend());
vector<int> ans = lis(i-1);
reverse(ans.begin(), ans.end());
cout << ans.size() << endl;
for(auto a: ans) cout << a << endl;
return 0;
}
| true |
dddd4d731c75cf09de8b859ea70c1b601f450322 | C++ | pijastrzebski/DesignPatternsBattlefield | /Behavioral/Visitor/Visitor/Triangle.h | UTF-8 | 314 | 2.65625 | 3 | [] | no_license | #pragma once
#include "IShape.h"
#include "IVisitor.h"
class Triangle : public IShape
{
public:
virtual void acceptVisitor(IVisitor* visitor) override
{
visitor->visitTriangle(this);
}
virtual void draw() override
{
std::cout << "Draw Triangle\n";
}
}; | true |
483ad620865bc024a50da442aae763bf0c378721 | C++ | shuvra-mbstu/Uva-problems | /acm.11417 - GCD.cpp | UTF-8 | 503 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int GCD(int b, int a )
{
int t;
while(b!=0)
{
t=b;
b = a%b;
a=t;
}
return a;
}
int main()
{
int a, b, i, j, g, num;
while(scanf("%d",&num)==1)
{ g = 0;
if(num == 0)
break;
for(i=1; i<num; i++)
{
for(j=i+1; j<=num; j++)
{
g += GCD(i,j);
}
}
printf("%d\n",g);
}
}
| true |
eeab2815df39266188f2ac604d4e033e6fc75c3a | C++ | Wicho1313/Estructuras-de-datos | /1 parcial/Evidencia/cola/cola.cpp | UTF-8 | 1,030 | 3.25 | 3 | [] | no_license | #include <iostream.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct cola {
int dato;
struct cola *s;
};
struct cola *p,*aux,*u;
void push (int dat)
{
aux=(struct cola *)malloc(sizeof(cola));
aux->dato=dat;
if(u)
{
u->s=aux;
aux->s=NULL;
u=aux;
}
else
{
p=u=aux;
}
}
void pop()
{
if(p)
{
aux=p;
cout<<"\nElimino a " <<p->dato;
p=aux->s;
free (aux);
}
else
{
printf("\n No hay datos");
}
}
void mostrar()
{
int i;
if(!u)
{
printf("\n No hay datos en la cola");
return;
}
aux=p;
while(aux)
{
cout<<"\n"<<++i<<" - "<<aux->dato;
aux=aux->s;
}
}
int main()
{
int opc,y;
do
{
printf("\n 1. Meter ");
printf("\n 2. sacar ");
printf("\n 3. mostrar ");
printf("\n 4. Salir ");
scanf("%d",&opc);
switch(opc)
{
case 1: printf("Ingrese dato: ");
scanf("%d",&y);
push(y);
printf("\n Dato insertado!!");
break;
case 2: pop();
break;
case 3: mostrar(); break;
case 4:
system("pause");
system("cls");
default: printf("\n Opcion no valida!!"); break;
}
}while(opc!=4);
return 0;
}
| true |
45fc125af7ab039a0c948e4bbbd9f8721b7d9d86 | C++ | nerissa123456/IndoorPaperSim | /index_operator.inl | UTF-8 | 1,154 | 2.765625 | 3 | [] | no_license | #include "ParticleFilter.h"
#define TYPE vector<ParticleFilter::index>
inline TYPE operator + (const TYPE& lo,const TYPE& ro){
TYPE result(lo);
for(int i = 0; i < ro.size(); i++){
bool flag = false;
for(int j = 0; j < result.size(); j++){
if (result[j].tagID == ro[i].tagID){
flag = true;
result[j].p += ro[i].p;
}
}
if (!flag){
result.push_back(ro[i]);
}
}
return result;
}
inline void operator += (TYPE& lo, const TYPE& ro){
for(int i = 0; i < ro.size(); i++){
bool flag = false;
for(int j = 0; j < lo.size(); j++){
if (lo[j].tagID == ro[i].tagID){
flag = true;
lo[j].p += ro[i].p;
}
}
if (!flag){
lo.push_back(ro[i]);
}
}
}
inline void operator *= (TYPE& lo, double d){
for (int i = 0; i<lo.size(); i++){
lo[i].p *= d;
}
}
inline TYPE operator * (const TYPE& lo, double d){
TYPE result(lo);
for(int i = 0; i<lo.size(); i++){
result[i].p *= d;
}
return result;
}
| true |
8db75810022b29baa661d8b72301b545f05ba67e | C++ | drb8w/StereoVision2015 | /StereoMatcher/StereoMatcher/SelectDisparity.cpp | UTF-8 | 1,477 | 2.78125 | 3 | [] | no_license | #include "SelectDisparity.h"
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#include <opencv2\opencv.hpp>
void _selectDisparity(cv::Mat &display, std::vector<cv::Mat> &costVolume)
{
int maxDisp = costVolume.size();
for(int rowNr = 0; rowNr < display.rows; rowNr++ )
for(int columnNr = 0; columnNr < display.cols; columnNr++ ){
float minCost = costVolume[0].at<float>(rowNr, columnNr);
for(int disp=0; disp<maxDisp; disp++)
if (minCost > costVolume[disp].at<float>(rowNr, columnNr)){
display.at<uchar>(rowNr, columnNr) = (uchar)disp;
//display.at<uchar>(rowNr, columnNr) = (uchar)costVolume[disp].at<float>(rowNr, columnNr);
minCost = costVolume[disp].at<float>(rowNr, columnNr);
}
}
}
void _scaleDisplay(cv::Mat &display, int scaleDispFactor)
{
for(int rowNr = 0; rowNr < display.rows; rowNr++ )
for(int columnNr = 0; columnNr < display.cols; columnNr++ )
display.at<uchar>(rowNr, columnNr) = display.at<uchar>(rowNr, columnNr) * scaleDispFactor;
}
void selectDisparity(cv::Mat &displayLeft, cv::Mat &displayRight, std::vector<cv::Mat> &costVolumeLeft, std::vector<cv::Mat> &costVolumeRight, int scaleDispFactor=16)
{
// select min disparity per pixel
_selectDisparity(displayLeft, costVolumeLeft);
_selectDisparity(displayRight, costVolumeRight);
// scale the result
_scaleDisplay(displayLeft, scaleDispFactor);
_scaleDisplay(displayRight, scaleDispFactor);
}
| true |
2a5fb795d7c63883abd6d41ede77d48113cb0dcb | C++ | to0d/leetcode | /LT014001/LT014001.cpp | UTF-8 | 2,041 | 2.921875 | 3 | [] | no_license | #include <lt_help/lt.h>
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> rst;
m_wordSet.clear();
m_maxWordLen = -1;
static char buf1[26], buf2[26], buf3[26];
cal(buf1, s);
memset(buf3, 0, 26);
for(auto w : wordDict)
{ cal(buf2, w);
bool match = true;
for(int i = 0;i < 26; ++i)
{ if( buf2[i] > buf1[i] )
match = false;
buf3[i] += buf2[i];
}
if( !match )
continue;
m_wordSet.insert(w);
int wlen = w.length();
m_maxWordLen = std::max(m_maxWordLen, wlen);
}
for(int i = 0;i < 26; ++i)
{ if( buf1[i] > 0 && buf3[i] == 0)
return rst;
}
static char buf[40];
int buf_len = 0;
_wordBreak(s.c_str(), s.length(), buf, buf_len, rst);
return rst;
}
void _wordBreak(const char* p, int len, char* buf, int buf_len, vector<string>& rst) {
if( len == 0 )
{ string w(buf, buf_len);
rst.push_back(w);
return;
}
int len2 = std::min(len, m_maxWordLen);
if( buf_len > 0 )
buf[buf_len++] = ' ';
for(int i = len2; i > 0; --i)
{ string w(p, i);
//cout << "w: " << w << endl;
if( m_wordSet.count(w) == 0 )
continue;
memcpy(buf+buf_len, p, i);
_wordBreak(p+i, len-i, buf, buf_len+i, rst);
}
}
void cal(char* buf, string& s)
{ int size = s.length();
memset(buf, 0, 26);
for(int i = 0; i < size; ++i)
buf[s.at(i)-'a']++;
}
unordered_set<string> m_wordSet;
int m_maxWordLen;
};
void test(string s, vector<string> wordDict)
{
cout << "input: s=" << s << ", dict=";
outputVector(wordDict);
vector<string> r = Solution().wordBreak(s, wordDict);
cout << "; output: ";
outputVector(r);
cout << ";" << endl;
}
int main(void)
{
test("catsanddog", {"cat","cats","and","sand","dog"});
}
// Result
//
// 2023-01-03: Runtime 0ms 100% Memory 7.2MB 85.60%, https://leetcode.com/problems/word-break/submissions/870119684/
| true |
9cc089cd33c096aa441d9a1fa3dac66741173b07 | C++ | ElickC/Older-Projects | /C++/Comp4/Project Portfolio/PS3b/main.cpp | UTF-8 | 3,234 | 2.65625 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <memory>
#include <cmath>
#include <fstream>
#include "Body.hpp"
using namespace std;
using namespace sf;
const double gravity = 6.67 * 1e-11;
float findRadius(float dX, float dY);
float calculateForce(float massA, float massB, float radius);
int main(int argc, char** argv) {
float T = atoi(argv[1]);
float dT = atoi(argv[2]);
int currentT = 0;
int numBodies;
float radiusUniverse;
cin >> numBodies >> radiusUniverse;
sf::Vector2f windowSize(500, 500);
sf::RenderWindow window(sf::VideoMode(windowSize.x, windowSize.y), "Solar System Simulation");
vector<shared_ptr<Body>> bodies(numBodies);
for (int i = 0; i < numBodies; i++) {
bodies[i] = make_shared<Body>(Body(radiusUniverse, windowSize));
cin >> *bodies[i];
}
for (int i = 0; i < numBodies; i++) {
bodies[i]->setSprite();
}
for (int i = 0; i < numBodies; i++) {
bodies[i]->setPosition();
}
sf::Texture textureBackground;
textureBackground.loadFromFile("starfield.jpg");
sf::Sprite spriteBackground(textureBackground);
sf::Font font;
if (!font.loadFromFile("Walkway_Bold.ttf")) {
cerr << "Failed to load Font File" << endl;
}
sf::Text time;
time.setFont(font);
time.setString(to_string(currentT));
time.setCharacterSize(28);
time.setFillColor(sf::Color::White);
sf::Music music;
if (music.openFromFile("2001.wav")) {
music.play();
} music.play();
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
double radius = 0;
double force = 0;
double netXForce = 0;
double netYForce = 0;
double dX = 0;
double dY = 0;
if (currentT < T) {
for (int i = 0; i < numBodies; i++) {
for (int j = 0; j < numBodies; j++) {
if (i != j) {
dX = bodies[j]->xpos - bodies[i]->xpos;
dY = bodies[j]->ypos - bodies[i]->ypos;
radius = findRadius(dX, dY);
force = calculateForce(bodies[i]->mass, bodies[j]->mass, radius);
netXForce += force * (dX / radius);
netYForce += force * (dY / radius);
bodies[i]->xForce = netXForce;
bodies[i]->yForce = netYForce;
}
}
netXForce = 0;
netYForce = 0;
}
for (int i = 0; i < numBodies; i++) {
bodies[i]->step(dT);
}
for (int i = 0; i < numBodies; i++) {
bodies[i]->setPosition();
}
window.clear();
window.draw(spriteBackground);
for (int i = 0; i < numBodies; i++) {
window.draw(*bodies[i]);
}
window.draw(time);
window.display();
currentT = currentT + dT;
time.setString(to_string(currentT));
}
}
std::ofstream out("output.txt");
out.precision(4);
out << numBodies << endl;
out << radiusUniverse << endl;
for (int i = 0; i < numBodies; i++) {
out << std::scientific << " " << bodies[i]->xpos << " " << bodies[i]->ypos << " " << bodies[i]->xvel <<
" " << bodies[i]->yvel << " " << bodies[i]->mass << " " << bodies[i]->filename << endl;
}
return 0;
}
float findRadius(float dX, float dY) {
return sqrt(pow(dX, 2) + pow(dY, 2));
}
float calculateForce(float massA, float massB, float radius) {
return (gravity * massA * massB) / pow(radius, 2);
}
| true |
ec3e1ca6fdb947368375676309e52cff0032ed97 | C++ | liquidmetalcobra/shittyshooter | /testgame/gameObject.cpp | UTF-8 | 1,975 | 2.78125 | 3 | [] | no_license | //
// gameObject.cpp
// testgame
//
// Created by Sasha Han on 10/14/17.
// Copyright © 2017 __. All rights reserved.
//
#include "gameObject.hpp"
void gameobject::collide(gameobject *go)
{
// std::cout << "oops";
}
void gameobject::update()
{
}
void gameobject::draw(ALLEGRO_DISPLAY *display)
{
}
void gameobject::init()
{
}
void gameobject::destroy()
{
}
void gameobject::addChild(gameobject * newChild)
{
_children.push_back(newChild);
newChild->parent = this;
std::cout << newChild->getAbsoluteLocation().toString();
newChild->Transform(Sub2DV(newChild->location,this->location));
}
void gameobject::removeChild(gameobject * child)
{
_children.erase(std::remove(_children.begin(), _children.end(), child), _children.end());
child->parent = NULL;
child->localLocation = Vector_2D(0,0);
child->Transform(Add2DV(child->getLocalLocation(), this->location));
}
void gameobject::removeAllChildren()
{
for ( int i = 0; i < _children.size(); i++)
{
_children[i]->parent = NULL;
_children[i]->localLocation = Vector_2D(0,0);
_children[i]->Transform(Add2DV(_children[i]->getLocalLocation(), this->location));
}
_children.clear();
}
bool gameobject::isParentOf(gameobject * child)
{
std::vector<gameobject *>::iterator it = std::find(_children.begin(), _children.end(), child);
if (it == _children.end())
return false;
return true;
}
bool gameobject::isChildOf(gameobject * parent)
{
if (this->parent == parent)
return true;
return false;
}
void gameobject::Transform(Vector_2D delta)
{
if (this->parent != NULL)
{
// std::cout << delta.toString() << localLocation.toString() << "\n";
localLocation = Add2DV(localLocation, delta);
}
else
{
location = Add2DV(location, delta);
}
/*for (unsigned i=0; i < _children.size(); i++) {
_children[i]->Transform(delta);
}*/
} | true |
d597db9e49e279837a3b8235a379be1f2cd781cf | C++ | hislittlecuzin/TopDownEngine | /AnimationSystem.h | UTF-8 | 1,123 | 2.9375 | 3 | [] | no_license | #pragma once
#include "Globals.h"
#include <SFML/Graphics.hpp>
class AnimationSystem {
public:
/// Used for Constructor to define what animations will exist.
enum AnimatedType { wall, person };
enum Animations { inPlace, idle, walking, };
void Setup(sf::Texture &texture, AnimatedType typeOfAnimated, int posX, int poY);
void PlayAnimation();
void SetAnimationFrame(int xCoordinate, int yCoordinate);
void ChangeAnimation(Animations newAnimation);
#pragma region Getters Setters
void setRotation(float rot) {
sprite.setRotation(rot);
}
void setPosition(int posX, int posY) {
sprite.setPosition(posX, posY);
}
sf::Sprite GetSprite() {
return sprite;
}
Animations GetCurrentAnimation() {
return currentAnimation;
}
#pragma endregion
private:
AnimatedType animationType;
Animations currentAnimation;
int frameChangeDelayCounter = 0;
const int frameChangeDelay = 5;
int animationFrame = 0;
const int framesPerInPlace = 1;
const int framesPerIdle = 10;
const int framesPerWalking = 10;
int DetermineFrame();
sf::Sprite sprite;
};
| true |
987e3f6ac373f3f8599b1e53090c4a758ce59f84 | C++ | Cryptogroup/universalcircuit | /src/Eu/EugNode.h | UTF-8 | 1,377 | 2.609375 | 3 | [] | no_license |
//#pragma once
#ifndef _EugNode_h_
#define _EugNode_h_
#include "EugComponent.h"
#include <iostream>
#include <cstdint>
#include "../Simple/SimpleGate.h"
#include "../Dag/DagNode.h"
using namespace std;
class SimpleGate;
class EugComponent;
enum EugNodeType
{
EUG_NODE_POLE,
EUG_NODE_NORMAL,
EUG_NODE_IN, // Has no unified code
EUG_NODE_OUT, // Has no unified code
EUG_NODE_DEFAULT,
};
//class SimpleGate;
class EugNode
{
public:
EugNodeType type;
uint32_t id;
uint32_t poleId;
EugComponent* component;
size_t fanIn;
size_t fanOut;
EugNode** posts; // Post-nodes in EUG
EugNode** pres; // Pre-nodes in EUG
EugNode* nextPole;
EugNode* lastPole;
DagNodeType dagNodeType;
// variabls for exact circuit file type
SimpleGate* controlledGate;
// variable for computation after edge embedding
bool control;
uint32_t gateType;
static uint32_t idCounter;
static uint32_t getNextId();
EugNode(EugNodeType type, EugComponent* component, uint32_t poleId);
~EugNode();
bool linkTo(EugNode* post);
bool unlink();
bool unlink(size_t which);
static EugNode* getInNode(uint32_t inId, EugComponent* component);
static EugNode* getOutNode(uint32_t outId, EugComponent* component);
static EugNode* getNormalNode(EugComponent* component);
static EugNode* getPoleNode(EugComponent* component, uint32_t poleId);
};
#endif
| true |
50404d8765492956c93825bd677558ef47b82a1d | C++ | zhouxiaoy/pat | /第四届决赛/猜灯谜.cpp | UTF-8 | 578 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int check(int a[],int n){
int i=5;
int b[10]={0};
while(n>0){
if(i==1){
if(b[n%10]==1)
b[n%10]++;
else
return 0;
}
else{
if(b[n%10]!=0)
return 0;
else
b[n%10]++;
}
a[i--]=n%10;
n/=10;
}
return 1;
}
int main(){
for(int i=100;i<=999;i++){
int a,b,c;
a=i/100,b=(i/10)%10,c=i%10;
if(a!=b&&b!=c&&a!=c){
if(i*i>=100000&&i*i<=999999){
//cout<<i<<endl;
int num[6]={0};
if(check(num,i*i)){
if(a==num[0]&&b==num[5]){
cout<<i;
}
}
}
}
}
return 0;
}
| true |
34286ed29ced885b1b90ea130908f5758b2e1995 | C++ | RedYurii/CrazyTanks | /battleCityConsole/GameObjectBase.h | UTF-8 | 527 | 2.859375 | 3 | [] | no_license | #pragma once
enum direction { LEFT= 27, RIGHT = 26, UP = 24, DOWN = 25
};
class GameObjectBase
{
float xPos_;
float yPos_;
int velocity_;
char sprite_;
short color_;
direction dir_;
public:
GameObjectBase(float x, float y, int v, char sp, direction dr, short color);
~GameObjectBase();
float getXPos();
float getYPos();
char getSprite();
int getVelocity();
direction GetDirection();
void setDirection(direction dr);
void setXPos(float x);
void setYPos(float y);
void setSprite(char s);
short getColor();
};
| true |
feed3c2992f87bfa055cf031f9276e1beabc8514 | C++ | xTunqki/VariadicTemplateAlgorithms | /tests/algorithms.cpp | UTF-8 | 18,419 | 3.125 | 3 | [
"BSL-1.0"
] | permissive | #include "vta/algorithms.hpp"
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <iostream>
#include <type_traits>
#include <string>
namespace {
struct printer {
printer(std::ostream& str)
: m_str{&str} {
}
template <typename T>
void operator()(T const& obj) {
*m_str << obj;
}
std::ostream* m_str;
};
struct string_concat {
template <typename LHS, typename RHS>
std::string operator()(LHS const& lhs, RHS const& rhs) const {
std::stringstream ss;
ss << lhs << rhs;
return ss.str();
}
};
struct is_positive_int {
bool operator()(int x) const {
return x > 0;
}
template <typename T>
bool operator()(T const&) const {
return false;
}
};
bool is_true(bool p) {
return p;
}
struct adjacent_printer {
adjacent_printer(std::string& str)
: m_str{&str} {
}
void operator()(int i, int j) {
std::stringstream ss;
ss << i * j;
*m_str += ss.str();
}
std::string* m_str;
};
}
BOOST_AUTO_TEST_SUITE(algorithms)
BOOST_AUTO_TEST_CASE(are_same) {
static_assert(vta::are_same<>::value, "");
static_assert(vta::are_same<int>::value, "");
static_assert(vta::are_same<int, int>::value, "");
static_assert(vta::are_same<int, int, int>::value, "");
static_assert(!vta::are_same<int, float>::value, "");
static_assert(!vta::are_same<int&, int>::value, "");
static_assert(!vta::are_same<int const&, int&>::value, "");
static_assert(!vta::are_same<int&&, int&>::value, "");
static_assert(!vta::are_same<const int, int>::value, "");
static_assert(!vta::are_same<volatile int, int>::value, "");
}
BOOST_AUTO_TEST_CASE(are_same_after) {
static_assert(vta::are_same_after<std::remove_reference>::value, "");
static_assert(vta::are_same_after<std::remove_reference, int>::value, "");
static_assert(vta::are_same_after<std::remove_reference, int&&, int&>::value, "");
static_assert(!vta::are_same_after<std::remove_reference, int, float>::value, "");
}
BOOST_AUTO_TEST_CASE(are_unique_ints) {
static_assert(vta::are_unique_ints<>::value, "");
static_assert(vta::are_unique_ints<1>::value, "");
static_assert(vta::are_unique_ints<1, 2>::value, "");
static_assert(!vta::are_unique_ints<1, 1>::value, "");
static_assert(vta::are_unique_ints<1, -1>::value, "");
static_assert(vta::are_unique_ints<1, 2, 3, 4, 5>::value, "");
static_assert(!vta::are_unique_ints<1, 2, 3, 1, 5>::value, "");
static_assert(!vta::are_unique_ints<2, 3, 4, 5, 6, 5>::value, "");
}
BOOST_AUTO_TEST_CASE(are_unique) {
static_assert(vta::are_unique<>::value, "");
static_assert(vta::are_unique<int>::value, "");
static_assert(vta::are_unique<int, float>::value, "");
static_assert(!vta::are_unique<int, int>::value, "");
static_assert(vta::are_unique<int, int&>::value, "");
static_assert(vta::are_unique<int&&, int&>::value, "");
static_assert(vta::are_unique<int, float>::value, "");
static_assert(!vta::are_unique<int, float, int>::value, "");
static_assert(vta::are_unique<int, float, char>::value, "");
}
BOOST_AUTO_TEST_CASE(are_unique_after) {
static_assert(vta::are_unique_after<std::remove_reference>::value, "");
static_assert(vta::are_unique_after<std::remove_reference, int>::value, "");
static_assert(!vta::are_unique_after<std::remove_reference, int&&, int&>::value, "");
static_assert(vta::are_unique_after<std::remove_reference, int, float>::value, "");
}
BOOST_AUTO_TEST_CASE(head) {
BOOST_CHECK_EQUAL(vta::head(0), 0);
BOOST_CHECK_EQUAL(vta::head(std::string{"1"}), "1");
BOOST_CHECK_EQUAL(vta::head(0, 1, 2), 0);
BOOST_CHECK_EQUAL(vta::head(1, "2", 3), 1);
}
BOOST_AUTO_TEST_CASE(last) {
BOOST_CHECK_EQUAL(vta::last(0), 0);
BOOST_CHECK_EQUAL(vta::last(std::string{"1"}), "1");
BOOST_CHECK_EQUAL(vta::last(0, 1), 1);
BOOST_CHECK_EQUAL(vta::last(0, 1, 2), 2);
BOOST_CHECK_EQUAL(vta::last(1, "2", 3), 3);
}
BOOST_AUTO_TEST_CASE(at) {
BOOST_CHECK_EQUAL(vta::at<0>(0), 0);
BOOST_CHECK_EQUAL(vta::at<-1>(0), 0);
BOOST_CHECK_EQUAL(vta::at<0>(1, '2', 3u, 4.5, "six"), 1);
BOOST_CHECK_EQUAL(vta::at<-5>(1, '2', 3u, 4.5, "six"), 1);
BOOST_CHECK_EQUAL(vta::at<3>(1, '2', 3u, 4.5, "six"), 4.5);
BOOST_CHECK_EQUAL(vta::at<-2>(1, '2', 3u, 4.5, "six"), 4.5);
BOOST_CHECK_EQUAL(vta::at<4>(1, '2', 3u, 4.5, "six"), std::string{"six"});
BOOST_CHECK_EQUAL(vta::at<-1>(1, '2', 3u, 4.5, "six"), std::string{"six"});
}
BOOST_AUTO_TEST_CASE(head_t) {
static_assert(std::is_same<int, vta::head_t<int>>::value, "");
static_assert(std::is_same<int, vta::head_t<int, char>>::value, "");
static_assert(std::is_same<float, vta::head_t<float, char>>::value, "");
static_assert(!std::is_same<float, vta::head_t<int, char>>::value, "");
}
BOOST_AUTO_TEST_CASE(last_t) {
static_assert(std::is_same<int, vta::last_t<int>>::value, "");
static_assert(std::is_same<char, vta::last_t<int, char>>::value, "");
static_assert(std::is_same<char, vta::last_t<float, char>>::value, "");
static_assert(!std::is_same<int, vta::last_t<int, char>>::value, "");
}
BOOST_AUTO_TEST_CASE(at_t) {
static_assert(std::is_same<int, vta::at_t<0>::type<int>>::value, "");
static_assert(std::is_same<int, vta::at_t<0>::type<int, char>>::value, "");
static_assert(std::is_same<char, vta::at_t<1>::type<int, char>>::value, "");
static_assert(std::is_same<char, vta::at_t<-1>::type<int, char>>::value, "");
static_assert(std::is_same<int, vta::at_t<2>::type<float, char, int>>::value, "");
static_assert(!std::is_same<int, vta::at_t<-2>::type<float, char, int>>::value, "");
}
/**************************************************************************************************
* Transformations *
**************************************************************************************************/
BOOST_AUTO_TEST_CASE(flip) {
{
std::stringstream ss;
vta::forward_after<vta::flip>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "2134.5six");
}
}
BOOST_AUTO_TEST_CASE(left_shift) {
{
std::stringstream ss;
vta::forward_after<vta::left_shift<0>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::left_shift<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::left_shift<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "234.5six1");
}
{
std::stringstream ss;
vta::forward_after<vta::left_shift<4>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "six1234.5");
}
}
BOOST_AUTO_TEST_CASE(right_shift) {
{
std::stringstream ss;
vta::forward_after<vta::right_shift<0>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::right_shift<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::right_shift<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "six1234.5");
}
{
std::stringstream ss;
vta::forward_after<vta::right_shift<4>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "234.5six1");
}
}
BOOST_AUTO_TEST_CASE(shift) {
{
std::stringstream ss;
vta::forward_after<vta::shift<0>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::shift<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::shift<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "234.5six1");
}
{
std::stringstream ss;
vta::forward_after<vta::shift<-2>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "4.5six123");
}
}
BOOST_AUTO_TEST_CASE(left_shift_tail) {
{
std::stringstream ss;
vta::forward_after<vta::left_shift_tail<0>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::left_shift_tail<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::left_shift_tail<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "134.5six2");
}
{
std::stringstream ss;
vta::forward_after<vta::left_shift_tail<2>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "14.5six23");
}
}
BOOST_AUTO_TEST_CASE(right_shift_tail) {
{
std::stringstream ss;
vta::forward_after<vta::right_shift_tail<0>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::right_shift_tail<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::right_shift_tail<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1six234.5");
}
{
std::stringstream ss;
vta::forward_after<vta::right_shift_tail<2>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "14.5six23");
}
}
BOOST_AUTO_TEST_CASE(shift_tail) {
{
std::stringstream ss;
vta::forward_after<vta::shift_tail<0>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::shift_tail<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::shift_tail<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "134.5six2");
}
{
std::stringstream ss;
vta::forward_after<vta::shift_tail<-1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1six234.5");
}
}
BOOST_AUTO_TEST_CASE(drop) {
{
BOOST_CHECK_EQUAL(vta::forward_after<vta::drop<0>>([](){ return 1; })(), 1);
}
{
std::stringstream ss;
vta::forward_after<vta::drop<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::drop<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::drop<2>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "34.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::drop<5>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::drop<-5>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::drop<-3>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "34.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::drop<-1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "six");
}
}
BOOST_AUTO_TEST_CASE(take) {
{
std::stringstream ss;
vta::forward_after<vta::take<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::take<1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1");
}
{
std::stringstream ss;
vta::forward_after<vta::take<2>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "12");
}
{
std::stringstream ss;
vta::forward_after<vta::take<4>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5");
}
{
std::stringstream ss;
vta::forward_after<vta::take<-5>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::take<-3>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "12");
}
{
std::stringstream ss;
vta::forward_after<vta::take<-1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5");
}
}
BOOST_AUTO_TEST_CASE(cycle) {
{
std::stringstream ss;
vta::forward_after<vta::cycle<>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<-3>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "1234.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<0, 1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "2134.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<0, 1, 2>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "3124.5six");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<-1, 0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "six234.51");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<0, 2, 4>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "six214.53");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<4, 1, 2, 0>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "3six24.51");
}
{
std::stringstream ss;
vta::forward_after<vta::cycle<0, 4, 2, 3, 1>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "24.5six31");
}
}
BOOST_AUTO_TEST_CASE(reverse) {
{
std::stringstream ss;
vta::forward_after<vta::reverse>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::reverse>(vta::map(printer{ss}))(1);
BOOST_CHECK_EQUAL(ss.str(), "1");
}
{
std::stringstream ss;
vta::forward_after<vta::reverse>(vta::map(printer{ss}))(1, '2');
BOOST_CHECK_EQUAL(ss.str(), "21");
}
{
std::stringstream ss;
vta::forward_after<vta::reverse>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "six4.5321");
}
}
BOOST_AUTO_TEST_CASE(filter) {
{
std::stringstream ss;
vta::forward_after<vta::filter<std::is_integral>>(vta::map(printer{ss}))();
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::filter<std::is_integral>>(vta::map(printer{ss}))(1);
BOOST_CHECK_EQUAL(ss.str(), "1");
}
{
std::stringstream ss;
vta::forward_after<vta::filter<std::is_integral>>(vta::map(printer{ss}))("1");
BOOST_CHECK_EQUAL(ss.str(), "");
}
{
std::stringstream ss;
vta::forward_after<vta::filter<std::is_integral>>(vta::map(printer{ss}))(1, "2", 3.0);
BOOST_CHECK_EQUAL(ss.str(), "1");
}
{
std::stringstream ss;
vta::forward_after<vta::filter<std::is_integral>>(vta::map(printer{ss}))(1, '2', 3u, 4.5, "six");
BOOST_CHECK_EQUAL(ss.str(), "123");
}
}
// Functions
BOOST_AUTO_TEST_CASE(map) {
std::stringstream ss;
vta::map(printer{ss})(1, 2, 3u, ' ', 4.5, " hello", " world!");
BOOST_CHECK_EQUAL(ss.str(), "123 4.5 hello world!");
}
BOOST_AUTO_TEST_CASE(adjacent_map) {
std::string s;
adjacent_printer printer{s};
vta::adjacent_map<2>(std::ref(printer))(1, 2, 3, 4, 5, 6);
BOOST_CHECK_EQUAL(s, "26122030");
}
BOOST_AUTO_TEST_CASE(foldl) {
auto s = string_concat{};
auto const result = vta::foldl(s)(1, 2, 3);
BOOST_CHECK_EQUAL(result, "123");
}
BOOST_AUTO_TEST_CASE(foldr) {
auto minus = [](auto l, auto r){ return l - r; };
BOOST_CHECK_EQUAL(vta::foldr(minus)(1), 1);
BOOST_CHECK_EQUAL(vta::foldr(minus)(1, 2), -1);
BOOST_CHECK_EQUAL(vta::foldr(minus)(1, 2, 3), 2);
}
BOOST_AUTO_TEST_CASE(compose) {
{
std::stringstream ss;
vta::forward_after<vta::compose<vta::left_shift<1>>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "12340");
}
{
std::stringstream ss;
vta::forward_after<vta::compose<vta::left_shift<1>, vta::flip>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "21340");
}
}
BOOST_AUTO_TEST_CASE(swap) {
{
std::stringstream ss;
vta::forward_after<vta::swap<2, 4>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "01432");
}
{
std::stringstream ss;
vta::forward_after<vta::swap<2, -1>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "01432");
}
{
std::stringstream ss;
vta::forward_after<vta::swap<0, 2>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "21034");
}
{
std::stringstream ss;
vta::forward_after<vta::swap<1, 1>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "01234");
}
{
std::stringstream ss;
vta::forward_after<vta::swap<2, -3>>(vta::map(printer{ss}))(0, 1, 2, 3, 4);
BOOST_CHECK_EQUAL(ss.str(), "01234");
}
}
BOOST_AUTO_TEST_CASE(all_of) {
auto const all_positive_int = vta::all_of(is_positive_int{});
BOOST_CHECK_EQUAL(all_positive_int(1, 2), true);
BOOST_CHECK_EQUAL(all_positive_int("hello", 2), false);
BOOST_CHECK_EQUAL(all_positive_int(0u, 2), false);
BOOST_CHECK_EQUAL(all_positive_int(-2), false);
BOOST_CHECK_EQUAL(all_positive_int(), true);
BOOST_CHECK_EQUAL(vta::all_of(&is_true)(), true);
BOOST_CHECK_EQUAL(vta::all_of(&is_true)(true), true);
BOOST_CHECK_EQUAL(vta::all_of(&is_true)(false), false);
BOOST_CHECK_EQUAL(vta::all_of(&is_true)(true, false), false);
}
BOOST_AUTO_TEST_CASE(any_of) {
BOOST_CHECK_EQUAL(vta::any_of(is_positive_int{})(1, 2), true);
BOOST_CHECK_EQUAL(vta::any_of(is_positive_int{})("hello", 2), true);
BOOST_CHECK_EQUAL(vta::any_of(is_positive_int{})(0u, 2), true);
BOOST_CHECK_EQUAL(vta::any_of(is_positive_int{})(-2), false);
BOOST_CHECK_EQUAL(vta::any_of(is_positive_int{})(), false);
}
BOOST_AUTO_TEST_CASE(none_of) {
BOOST_CHECK_EQUAL(vta::none_of(is_positive_int{})(1, 2), false);
BOOST_CHECK_EQUAL(vta::none_of(is_positive_int{})("hello", 2), false);
BOOST_CHECK_EQUAL(vta::none_of(is_positive_int{})(0u, 2), false);
BOOST_CHECK_EQUAL(vta::none_of(is_positive_int{})(-2), true);
BOOST_CHECK_EQUAL(vta::none_of(is_positive_int{})(), true);
}
BOOST_AUTO_TEST_CASE(macro) {
BOOST_CHECK_EQUAL(vta::foldl(VTA_FN_TO_FUNCTOR(std::max))(0, 1, 4, 2), 4);
}
BOOST_AUTO_TEST_SUITE_END()
| true |
c32c944f22606023fcceef9d06c71ff8ea1d538c | C++ | unixpickle/anarch | /src/memory/malloc.cpp | UTF-8 | 2,258 | 2.796875 | 3 | [] | no_license | #include "malloc.hpp"
#include <anarch/api/panic>
#include <anarch/critical>
#include <anarch/align>
namespace anarch {
Malloc::Malloc(size_t pool, Allocator & _allocator, bool _bigPages)
: poolSize(pool), bigPages(_bigPages), allocator(_allocator) {
}
Malloc::~Malloc() {
AssertNoncritical();
while (firstSegment) {
Segment * next = firstSegment->next;
allocator.FreeAndUnmap((PhysAddr)next, poolSize);
firstSegment = next;
}
}
bool Malloc::Alloc(void *& addr, size_t size) {
if (size >= poolSize / 2) return false;
if (!AllocNoNewSegment(addr, size)) {
if (!CreateSegment()) return false;
return AllocNoNewSegment(addr, size);
}
return true;
}
void Malloc::Free(void * addr) {
AssertNoncritical();
firstLock.Seize();
Segment * segment = firstSegment;
firstLock.Release();
while (segment) {
ScopedLock scope(segment->lock);
if (segment->allocator->OwnsPointer(addr)) {
segment->allocator->Free(addr);
return;
}
}
Panic("Malloc::Free() - unowned memory region");
}
bool Malloc::Owns(void * ptr) {
AssertNoncritical();
firstLock.Seize();
Segment * segment = firstSegment;
firstLock.Release();
while (segment) {
ScopedLock scope(segment->lock);
if (segment->allocator->OwnsPointer(ptr)) {
return true;
}
}
return false;
}
// PRIVATE //
bool Malloc::AllocNoNewSegment(void *& addr, size_t size) {
AssertNoncritical();
firstLock.Seize();
Segment * segment = firstSegment;
firstLock.Release();
while (segment) {
ScopedLock scope(segment->lock);
addr = segment->allocator->Alloc(size);
if (addr) return true;
segment = segment->next;
}
return false;
}
bool Malloc::CreateSegment() {
VirtAddr freshMemory;
if (!allocator.AllocAndMap(freshMemory, poolSize, bigPages)) {
return false;
}
assert(!(freshMemory % ANARCH_OBJECT_ALIGN));
Segment * segPtr = new((Segment *)freshMemory) Segment();
// I *hate* when function names get this big
segPtr->allocator = ANAlloc::Malloc::WrapRegion<ANAlloc::BBTree>
((uint8_t *)freshMemory, poolSize, 6, sizeof(Segment));
ScopedLock scope(firstLock);
segPtr->next = firstSegment;
firstSegment = segPtr;
return true;
}
}
| true |
8656a9de6404e54ce84f670f860074f060e4208e | C++ | yagi2/Competitive_programming | /AOJ/Vol.100/Solved/10020.cpp | UTF-8 | 342 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main(void){
int i,num;
char ch;
int count[26]={0};
while(cin >> ch){
if(ch>='A' && ch<='Z'){
ch += 0x20;
}
num = ch-'a';
count[num]++;
}
ch = 'a';
for(i=0;i<26;i++){
cout << ch << " : " << count[i] << endl;
ch++;
}
return 0;
}
| true |
2d0b022f081314d970e449db63a77c301c4c6f01 | C++ | zauberfuchs/OpenGLCherno | /OpenGL/src/tests/Test.cpp | ISO-8859-1 | 487 | 2.890625 | 3 | [] | no_license | #include "Test.h"
#include "imgui/imgui.h"
namespace test {
TestMenu::TestMenu(Test*& currentTestPointer)
: m_CurrentTest(currentTestPointer)
{
}
void TestMenu::OnImGuiRender() // erzeugt die buttons fr jeden test im Vector m_Tests
{
for (auto& test : m_Tests)
{
if (ImGui::Button(test.first.c_str())) // holt sich aus dem paar die erste Variable und holt sich den str ptr
m_CurrentTest = test.second(); // setzt den aktuellen test auf die zweite variable
}
}
} | true |
68c9227a64c993692fc0235a4752fc2fc5af6a4b | C++ | JGonzalezRodriguez/prog4 | /src/clase.cpp | UTF-8 | 3,008 | 2.671875 | 3 | [] | no_license | #include "../include/clase.h"
int Clase::seed = 0;
int Clase::getSeed() {
return seed;
}
void Clase::incSeed() {
seed = seed + 1;
}
void Clase::setDocente(Docente* doc){
this->doc = doc;
}
Docente* Clase::getDocente(){
return this->doc;
}
DtFecha *Clase::getFechayhoracomienzo(){
return this->fechayhoracomienzo;
}
void Clase::setFechayhoracomienzo(DtFecha *fecha){
this->fechayhoracomienzo = fecha;
}
std::string Clase::getId(){
return this->id;
}
void Clase::setId(std::string id){
this->id = id;
}
bool Clase::getEnVivo(){
return this->envivo;
}
void Clase::setEnVivo(bool b){
this->envivo = b;
}
DtFecha* Clase::getFechayhorafinal(){
return this->fechayhorafinal;
}
void Clase::setFechayhorafinal(DtFecha *fecha){
this->fechayhorafinal = fecha;
}
std::string Clase::getUrl(){
return this->url;
}
void Clase::setUrl(std::string url){
this->url = url;
}
std::string Clase::getNombre(){
return this->nombre;
}
void Clase::setNombre(std::string nombre){
this->nombre = nombre;
}
std::set<ClaseEstudiante*> Clase::getClaseEstudiantes() {
return this->claseestudiantes;
}
//Docente* Clase::getDoc() {
// return this->doc;
//}
//metodos de las operaciones de la clase
Asignatura *Clase::getAsignatura(){
return asig;
}
void Clase::finalizar(){
std::set<ClaseEstudiante*> colce = claseestudiantes;
for (std::set<ClaseEstudiante*>::iterator it=colce.begin(); it!=colce.end(); ++it) {
ClaseEstudiante* ce = *it;
ce->finalizarVisualizacionesVivo();
}
}
bool Clase::tieneClaseEst(Estudiante *est){
std::set<ClaseEstudiante*>::iterator it = claseestudiantes.begin();
for (it = claseestudiantes.begin(); it != claseestudiantes.end(); it++){
if ((*it)->getEstudiante() == est){
return true;
}
}
return false;
}
ClaseEstudiante *Clase::crearClaseEst(Estudiante *est, Clase *c){
ClaseEstudiante* ce = new ClaseEstudiante(c, est);
this->claseestudiantes.insert(ce);
est->addClaseEstudiante(ce);
return ce;
}
ClaseEstudiante *Clase::getClaseEstExistente(Estudiante* est){
std::set<ClaseEstudiante*>::iterator it;
for (it = claseestudiantes.begin(); it != claseestudiantes.end(); it++){
if ((*it)->getEstudiante() == est){
return (*it);
}
}
return NULL;
}
std::set<Mensaje*> Clase::getMensajes(){
return this->mensajes;
}
Mensaje* Clase::seleccionarMensaje(std::string idmensaje){
return NULL;
}
void Clase::agregarPadre(Mensaje *m){
this->mensajes.insert(m);
}
Clase::Clase(std::string nombre, DtFecha *fecha, Asignatura *asignatura, Docente *doc){
this->nombre = nombre;
this->fechayhoracomienzo = fecha;
this->fechayhorafinal = NULL;
this->asig = asignatura;
this->doc = doc;
this->envivo = true;
}
bool Clase::estaHabilitado(Estudiante* est) {
return true;
}
void Clase::deslinkear(ClaseEstudiante* ce) {
claseestudiantes.erase(ce);
}
Clase::~Clase(){
}
| true |
b352f180afb949766322866f35c2054bf3d94863 | C++ | Paulels/Unistuff | /2015/s2/oop/practical-01/program1-1.cpp | UTF-8 | 279 | 3.265625 | 3 | [] | no_license | #include <iostream>
int sum_array(int array[], int n){
int number=0;
int i=0;
for(i=0;i<n;i++){
number=number+array[i];
}
return number;
}
#ifndef WEBSUBMIT
int main(){
int array[5] = {7,6,2,10,7};
std::cout << sum_array(array,5) << std::endl;
}
#endif //WEBSUBMIT
| true |
d920d6635259ab321234c9ef2d78fa1c69d642a3 | C++ | karlhickel/Data-Structures | /Data Structures/Assignment5/faculty.h | UTF-8 | 1,391 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include "student.h"
#include "doubleLinkedList.h"
//faculty class
using namespace std;
class Faculty
{
public:
//Faculty constructor
Faculty();
Faculty(int facultyID1, string facultyName1, string facultyJob1, string facultyDepartment1);
Faculty(int facultyID1);
~Faculty();
//Variables
int facultyID;
string facultyName;
string facultyJob;
string facultyDepartment;
DoublyLinkedList<int> listOfStudents; //Ids
//Make an instance of a linked list for storing list of students
//overload operators for faculty objects
bool operator < (const Faculty &facu)
{
return this->facultyID < facu.facultyID;
}
bool operator == (const Faculty &facu)
{
return this->facultyID == facu.facultyID;
}
bool operator != (const Faculty &facu)
{
return this->facultyID != facu.facultyID;
}
bool operator > (const Faculty &facu)
{
return this->facultyID > facu.facultyID;
}
friend ostream & operator << (ostream &out, const Faculty &facu) //for some reason it would not work without using the friend key word which we research from stack overflow
{
out << "Faculty id: "<<facu.facultyID << endl;
out <<"Faculty Name: " << facu.facultyName << endl;
out <<"Faculty Job: " << facu.facultyJob << endl;
out <<"Faculty Department: " << facu.facultyDepartment << endl;
return out;
}
};
| true |
0ff0d7f9f94495a605ebed3e837df5e7bd9557ab | C++ | leslier94/RodriguezLeslie_CSC17A_42824 | /homework/Assignment 5/ch16_problem2/main.cpp | UTF-8 | 1,053 | 3.421875 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Ariana & Gilbert
*
* Created on May 31, 2016, 1:25 AM
*/
#include <cstdlib>
#include <iostream>
#include "Time.h"
#include "MilTime.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
int hour;
int sec;
char choice;
cout << "Enter hour " << endl;
cin >> hour;
cout << "Enter seconds " << endl;
cin >> sec;
cout << "Enter am or pm " << endl;
cin >> choice;
try {
Time stand(hour, sec);
MilTime mil(hour, sec);
if (choice=='a')
{
cout << "In military time that is " << stand.getHour()/100;
cout << stand.getHour()%100 <<":"<< stand.getSec() << endl;
}
else if (choice=='p'){
cout <<"In military time that is " << mil.getMilHour();
cout << stand.getHour()%100 << ":" << mil.getMilSec() << endl;
}
}
catch (MilTime::BadHour)
{
cout << "Invalid time " << endl;
}
catch (MilTime::BadSeconds)
{
cout << "Invalid time " << endl;
}
return 0;
}
| true |
8045fc1071264ad4f3de1b25b1776d8a06217619 | C++ | JaniTomati/programmiersprachen-raytracer | /framework/sdfloader.cpp | UTF-8 | 11,337 | 2.703125 | 3 | [
"MIT"
] | permissive | // SDFloader.cpp (Ray-Tracer 7.1)
#include "sdfloader.hpp"
#include <map>
Scene loadSDF(std::string const& fileIn) {
std::ifstream file;
std::string line;
file.open(fileIn); // opens input file
std::map<std::string, std::shared_ptr<Shape>> findeShape; // added with 7.2 composite
Scene loadedScene;
if (file.is_open()) {
// std::cout << "The file is open." << std::endl;
while (std::getline(file, line)) {
// std::cout << line << std::endl;
// keyword
std::stringstream ss;
std::string keyword;
ss << line;
ss >> keyword;
if (keyword == "define") {
ss >> keyword;
// Loads Material # materials
if (keyword == "material") {
Material mat;
ss >> mat.name_;
ss >> mat.ka_.r;
ss >> mat.ka_.g;
ss >> mat.ka_.b;
ss >> mat.kd_.r;
ss >> mat.kd_.g;
ss >> mat.kd_.b;
ss >> mat.ks_.r;
ss >> mat.ks_.g;
ss >> mat.ks_.b;
ss >> mat.m_;
ss >> mat.ri_;
loadedScene.materials_[mat.name_] = mat;
std::cout << "Added Material: " << mat << std::endl;
}
// Loads Shapes # geometry
else if (keyword == "shape") {
ss >> keyword;
unsigned int vectorSizeShapes = 0;
if (keyword == "box") {
std::string boxName;
glm::vec3 boxMin;
glm::vec3 boxMax;
std::string boxClrName;
ss >> boxName;
ss >> boxMin.x;
ss >> boxMin.y;
ss >> boxMin.z;
ss >> boxMax.x;
ss >> boxMax.y;
ss >> boxMax.z;
ss >> boxClrName;
Material boxMat = loadedScene.materials_.find(boxClrName) -> second;
// new entry in shapes_ (ptr)
// loadedScene.shapes_.push_back(std::make_shared<Box>(boxName, boxMat, boxMin, boxMax));
// ++vectorSizeShapes;
auto box = std::make_shared<Box>(boxName, boxMat, boxMin, boxMax);
findeShape[boxName] = box;
// std::cout << "Added Box: " << *loadedScene.shapes_[vectorSizeShapes - 1] << std::endl;
std::cout << "Added Box: " << *box << std::endl;
}
else if (keyword == "sphere") {
std::string sphereName;
glm::vec3 sphereCtr;
float sphereRad;
std::string sphereClrName;
ss >> sphereName;
ss >> sphereCtr.x;
ss >> sphereCtr.y;
ss >> sphereCtr.z;
ss >> sphereRad;
ss >> sphereClrName;
// find() points from Name to Material (http://en.cppreference.com/w/cpp/container/map/find)
Material sphereMat = loadedScene.materials_.find(sphereClrName) -> second;
// new entry in shapes_ (ptr)
// loadedScene.shapes_.push_back(std::make_shared<Sphere>(sphereName, sphereMat, sphereCtr, sphereRad));
// ++vectorSizeShapes;
auto sphere = std::make_shared<Sphere>(sphereName, sphereMat, sphereCtr, sphereRad);
findeShape[sphereName] = sphere;
// std::cout << "Added Sphere: " << *loadedScene.shapes_[vectorSizeShapes - 1] << std::endl;
std::cout << "Added Sphere: " << *sphere << std::endl;
}
// loads composites # composites
else if (keyword == "composite") {
std::string compositeName;
std::string shapeName;
ss >> compositeName;
loadedScene.composite_ = std::make_shared<Composite>(compositeName);
while (!ss.eof()) {
ss >> shapeName;
auto foundShape = findeShape.find(shapeName);
if (foundShape != findeShape.end()) {
loadedScene.composite_ -> addShape(foundShape -> second);
}
else {
std::cerr << "ERROR! Shape " << shapeName << " could not be found! \n" << std::endl;
}
}
std::cout << "Added Composite: \n" << *loadedScene.composite_ << std::endl;
}
else {
std::cerr << "ERROR! Shape keyword " << keyword << " could not be found! \n" << std::endl;
}
}
// Loads Light # light
else if (keyword == "light") {
unsigned int vectorSizeLight = 0;
std::string lightName;
glm::vec3 lightPos;
Color diffuseLight;
Color ambientLight;
ss >> lightName;
ss >> lightPos.x;
ss >> lightPos.y;
ss >> lightPos.z;
ss >> diffuseLight.r;
ss >> diffuseLight.g;
ss >> diffuseLight.b;
ss >> ambientLight.r;
ss >> ambientLight.g;
ss >> ambientLight.b;
// new entry in light_ (ptr)
LightSource newLight {lightName, lightPos, diffuseLight, ambientLight};
loadedScene.lights_.push_back(newLight);
++vectorSizeLight;
std::cout << "Added Light: " << newLight << std::endl;
}
// Loads Camera # camera
else if (keyword == "camera") {
std::string cameraName;
double cameraAoV;
glm::vec3 cameraPos;
glm::vec3 cameraDir;
glm::vec3 cameraUp;
ss >> cameraName;
ss >> cameraAoV;
ss >> cameraPos.x;
ss >> cameraPos.y;
ss >> cameraPos.z;
ss >> cameraDir.x;
ss >> cameraDir.y;
ss >> cameraDir.z;
ss >> cameraUp.x;
ss >> cameraUp.y;
ss >> cameraUp.z;
loadedScene.cam_ = Camera {cameraName, cameraAoV, cameraPos, cameraDir, cameraUp};
std::cout << "Added Camera: " << loadedScene.cam_ << std::endl;
}
}
// transform Object # transform <name> <transformation> <parameter>
else if (keyword == "transform") {
std::string shapeName;
ss >> shapeName;
auto foundShape2 = findeShape.find(shapeName);
if(foundShape2 != findeShape.end()) {
ss >> keyword;
if (keyword == "scale") {
glm::vec3 s;
ss >> s.x;
ss >> s.y;
ss >> s.z;
(foundShape2 -> second) -> scale(s);
std::cout << "Scaling shape: " << shapeName << "\n" << "Scaling point" << "\n"
<< "(" << s.x << ", " << s.y << ", " << s.z << ")" << " relativ to origin! \n"<< std::endl;
}
else if (keyword == "translate") {
glm::vec3 v;
ss >> v.x;
ss >> v.y;
ss >> v.z;
(foundShape2 -> second) -> translate(v);
std::cout << "Translating shape: " << shapeName << "\n" << "Shifting around Vector "
<< "(" << v.x << ", " << v.y << ", " << v.z << ")! \n" << std::endl;
}
else if (keyword == "rotate") {
float phi;
glm::vec3 axis;
ss >> phi;
ss >> axis.x;
ss >> axis.y;
ss >> axis.z;
if (axis == glm::vec3 {1.0f, 0.0f, 0.0f}) {
(foundShape2 -> second) -> rotateX(phi);
std::cout << "Rotating shape: " << shapeName << "\n" << "Rotation along x-axis" << "\n"
<< "Phi: " << phi << "°! \n" << std::endl;
}
else if (axis == glm::vec3 {0.0f, 1.0f, 0.0f}) {
(foundShape2 -> second) -> rotateY(phi);
std::cout << "Rotating shape: " << shapeName << "\n" << "Rotation along y-axis" << "\n"
<< "Phi: " << phi << "°! \n" << std::endl;
}
else if (axis == glm::vec3 {0.0f, 0.0f, 1.0f}) {
(foundShape2 -> second) -> rotateZ(phi);
std::cout << "Rotating shape: " << shapeName << "\n" << "Rotation along z-axis" << "\n"
<< "Phi: " << phi << "°! \n" <<std::endl;
}
else {
std::cerr << "ERROR! Please enter a coordinate axis! \n" << std::endl;
}
}
}
else if (shapeName == loadedScene.cam_.name_) {
ss >> keyword;
if (keyword == "translate") {
glm::vec3 v;
ss >> v.x;
ss >> v.y;
ss >> v.z;
loadedScene.cam_.translate(v);
std::cout << "Translating camera: " << loadedScene.cam_.name_ << "\n" << "Shifting around Vector "
<< "(" << v.x << ", " << v.y << ", " << v.z << ")! \n" << std::endl;
}
else if (keyword == "rotate") {
float phi;
glm::vec3 axis;
ss >> phi;
ss >> axis.x;
ss >> axis.y;
ss >> axis.z;
if (axis == glm::vec3 {1.0f, 0.0f, 0.0f}) {
loadedScene.cam_.rotateX(phi);
std::cout << "Rotating camera: " << loadedScene.cam_.name_ << "\n" << "Rotation along x-axis" << "\n"
<< "Phi: " << phi << "°! \n" <<std::endl;
}
else if (axis == glm::vec3 {0.0f, 1.0f, 0.0f}) {
loadedScene.cam_.rotateY(phi);
std::cout << "Camera: " << loadedScene.cam_.name_ << "\n" << "Rotation along y-axis" << "\n"
<< "Phi: " << phi << "°! \n" <<std::endl;
}
else if (axis == glm::vec3 {0.0f, 0.0f, 1.0f}) {
loadedScene.cam_.rotateZ(phi);
std::cout << "Camera: " << loadedScene.cam_.name_ << "\n" << "Rotation along z-axis" << "\n"
<< "Phi: " << phi << "°! \n" << std::endl;
}
else {
std::cerr << "ERROR! Please enter a coordinate axis! \n" << std::endl;
}
}
else {
std::cerr << "ERROR! Transformation keyword " << keyword << " could not be found! \n" << std::endl;
}
}
else {
std::cerr << "ERROR! Shape / Camera " << shapeName << " could not be found!" << "\n" << std::endl;
}
}
// renders Scene # render
else if (keyword == "render") {
std::string camName;
ss >> camName;
// checks whether camera exists so the frame can be rendered
if (camName == loadedScene.cam_.name_) {
ss >> loadedScene.fileOut_;
ss >> loadedScene.width_;
ss >> loadedScene.height_;
std::cout << "Camera: " << loadedScene.cam_.name_ << "\n" << "Output File: " << loadedScene.fileOut_
<< "\n" << "Resolution: " << loadedScene.width_ << " x " << loadedScene.height_ << "\n" <<std::endl;
}
else {
// else camera object doesn't exist yet
std::cerr << "ERROR! Camera " << camName << " could not be found! \n" << std::endl;
}
}
// Prints Comment Line #
else if (keyword == "#") {
std::cout << line << std::endl;
}
// in case of wrong syntax
else {
std::cerr << "ERROR! The following line: '" << line << "' could not be parsed! \n" << std::endl;
}
}
file.close();
}
else {
std:: cerr << "ERROR! The document " << fileIn << "could not be opened! \n" << std::endl;
}
return loadedScene;
} | true |
12de1d536058f4a053d02067bcac415f5aa6133e | C++ | baiwei1106/BTTC-Online-Judge | /problem/2018夏·西北工业大学”字节跳动杯“程序设计竞赛/C.董与黑的碰撞-侵入/main.cpp | UTF-8 | 1,073 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int indegree[1005];
int n, m, T, a, b;
vector <int> Map[1005];
int main()
{
ifstream fin("in.txt");
ofstream fout("out.txt");
fin>>T;
int Case = 0;
while (T--){
int flag = 1;
fin>>n>>m;
for (int i=1; i<=n; i++){
Map[i].clear();
}
memset(indegree,0,sizeof(indegree));
for (int i=0; i<m; i++){
fin>>a>>b;
Map[a].push_back(b);
indegree[b]++;
}
for (int i=0; i<n; i++){
int pos = -1;
for (int j=1; j<=n; j++){
if (indegree[j] == 0){
pos = j;
break;
}
}
if (pos == -1){
flag = 0;
break;
}
indegree[pos] = -1;
for (int j=0; j<Map[pos].size(); j++) indegree[Map[pos][j]]--;
}
if (flag)
fout<<"No Deadlock\n";
else
fout<<"Deadlock Occurs\n";
}
return 0;
}
| true |
d023237133014f4c89dc9e008bae9df8a7a960d2 | C++ | Michaelborsellino/Postfix-to-Infix | /bet.h | UTF-8 | 1,100 | 2.890625 | 3 | [] | no_license | #ifndef BET_H
#define BET_H
#include<iostream>
#include<string>
#include<stack>
#include<vector>
class BET{
private:
struct BinaryNode{
std::string data;
BinaryNode * left;
BinaryNode * right;
BinaryNode(const std::string & d = std::string{}, BinaryNode *p = nullptr, BinaryNode *n = nullptr)
: data{d}, left{p}, right{n} {}
BinaryNode(std::string && d, BinaryNode *p = nullptr, BinaryNode *n = nullptr)
: data{std::move(d)}, left{p}, right{n} {}
};
public:
BET();
BET(const std::string);
BET(const BET&);
~BET();
bool buildFromPostfix(const std::string postfix);
const BET& operator=(const BET&);
void printInfixExpression();
void printPostfixExpression();
size_t size();
size_t leaf_nodes();
bool empty();
private:
void printInfixExpression(BinaryNode *n);
void makeEmpty(BinaryNode *&t);
BinaryNode * clone(BinaryNode*t)const;
void printPostfixExpression(BinaryNode *n);
size_t size(BinaryNode *t);
size_t leaf_nodes(BinaryNode *t);
BinaryNode * rootnode;
};
#include "bet.cpp"
#endif
| true |
0045e41de00b8f91387c2c7aae145adf67ce7e64 | C++ | RiyaGupta89/C-Coding-problems-for-beginners | /2D Arrays/spiralPrint.cpp | UTF-8 | 985 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
void spiralprint(int a[1000][1000], int m, int n)
{
int startRow = 0;
int endRow = m - 1;
int startCol = 0;
int endCol = n - 1;
while (startRow <= endRow && startCol <= endCol)
{
for (int i = startCol; i <= endCol; i++)
{
cout << a[startRow][i] << " ";
}
startRow++;
for(int i=startRow; i<=endRow; i++) {
cout<<a[i][endCol]<<" ";
}
endCol--;
for(int i=endCol; i>=startCol; i--) {
cout<<a[endRow][i]<<" ";
}
endRow--;
for(int i=endRow; i>=0; i--) {
cout<<a[i][startCol]<<" ";
}
startCol++;
}
}
int main()
{
int m;
int n;
cin >> m;
cin >> n;
int a[1000][1000];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
spiralprint(a, m, n);
return 0;
} | true |
600c0250f12402c24eb2bfe11518cec013a36c59 | C++ | Hongze-Wang/TargetOffer | /Tencent09062.cpp | UTF-8 | 1,410 | 3.0625 | 3 | [] | no_license | // 求解多项式方程 模拟
// 就是一个一个试 取x范围[-5000, 5000] 每次间隔 eps = 0.0005
// 如果当前多项式接近0(取+-1e-8) 那我就认为是解
// 为了提高精度 求 f(i+eps) 和 f(eps) 如果两者符号相反 一个在坐标轴上 一个在坐标轴下
// 则i+eps/2 是一个精度更高的解 i+eps/2能大致将其定位到坐标轴上 即是解
// 这是一个加速的trick
// 如果不使用这个trick 你可以把eps取更小 但这样你可能会超时
// [-1000, 1000]貌似也行 笔试的时候可以试试
#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[10];
double eps = 0.0005;
double f(double x) {
double t = x;
double ans = a[n];
for(int i=n-1; i >= 0; i--) {
ans += t*a[i];
t *= x;
}
return ans;
}
int main() {
scanf("%d", &n);
for(int i=0; i<=n; i++) {
scanf("%d", &a[i]);
}
vector<double> ans;
for(double i=-5000; i<5000; i+= eps) {
double p = f(i);
if(fabs(p) < 1e-8) {
ans.push_back(i);
continue;
}
double q = f(i+eps);
if(p*q <= 0) {
ans.push_back(i + eps/2);
}
}
if(ans.size() == 0) {
printf("No\n");
} else {
for(int i=0; i<ans.size(); i++) {
printf("%.2f ", ans[i]);
}
printf("\n");
}
return 0;
}
| true |
f3812f9bff83e5b08ca319a63964a4ba29c337d8 | C++ | piotrek-szczygiel/cpp | /lab6/main.cpp | UTF-8 | 2,544 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
#include <map>
#include <iomanip>
#include "Person.h"
#include "Random.h"
int main() {
random_seed();
const int size = 5;
std::vector<Person> v_people;
std::set<Person> s_people;
std::map<std::string, Person> m_people;
for (int i = 0; i < size - 1; ++i) {
v_people.emplace_back();
}
// create duplicate
v_people.push_back(v_people[0]);
for (auto it = v_people.begin(); it != v_people.end(); ++it) {
std::cout << "vector: " << it->info() << std::endl;
}
for (auto const &p : v_people) {
if (!s_people.insert(p).second) {
std::cout << "set duplicate: " << p.info() << std::endl;
}
}
for (auto &v_tree : v_people) {
m_people[v_tree.get_key()] = v_tree;
}
for (auto const&[key, val] : m_people) {
std::cout << "map[" << key << "]: " << val.info() << std::endl;
}
std::vector<Person> g(20);
std::generate(g.begin(), g.end(), Person::generator);
for (auto const &p : g) {
std::cout << "gen: " << p.info() << std::endl;
}
auto find_result = std::find_if(g.begin(), g.end(),
[](const Person &p) { return p.birth_year == 2000; });
if (find_result != g.end()) {
std::cout << "find_if: " << find_result->info() << std::endl;
} else {
std::cout << "find_if: no results" << std::endl;
}
std::cout << "enter birth year to count: ";
int birth_year;
std::cin >> birth_year;
std::cout << "people born in " << birth_year << ": "
<< std::count_if(g.begin(), g.end(), [birth_year](const Person &p) { return p.birth_year == birth_year; })
<< std::endl;
std::sort(g.begin(), g.end(), [](const Person &a, const Person &b) {
if (a.birth_year != b.birth_year) {
return a.birth_year < b.birth_year;
}
return a.last_name < b.last_name;
});
std::cout << "sorted: " << std::endl;
for (auto const &p : g) {
std::cout << p.info() << std::endl;
}
std::sort(g.begin(), g.end(), [](const Person &a, const Person &b) {
return a.last_name < b.last_name;
});
auto last = std::unique(g.begin(), g.end(), [](const Person &a, const Person &b) {
return a.last_name == b.last_name;
});
g.erase(last, g.end());
std::cout << "unique: " << std::endl;
for (auto const &p : g) {
std::cout << p.info() << std::endl;
}
return 0;
} | true |
641ff831f6c55d1634c2381bd1499467f9572a81 | C++ | mariokonrad/marnav | /include/marnav/nmea/zdl.hpp | UTF-8 | 1,661 | 3.140625 | 3 | [
"BSD-3-Clause",
"BSD-4-Clause"
] | permissive | #ifndef MARNAV_NMEA_ZDL_HPP
#define MARNAV_NMEA_ZDL_HPP
#include <marnav/nmea/sentence.hpp>
#include <marnav/nmea/time.hpp>
#include <marnav/units/units.hpp>
#include <optional>
namespace marnav::nmea
{
/// @brief ZDL - Time and Distance to Variable Point
///
/// @code
/// 1 2 3
/// | | |
/// $--ZDL,hhmmss.ss,x.x,a*hh<CR><LF>
/// @endcode
///
/// Field Number:
/// 1. Time to Point, hh=00..99
/// 2. Distance to Point, nautical miles
/// 3. Type of Point, see below
///
/// Type of Point:
/// - C = Collision
/// - T = Turning Point
/// - R = Reference (general)
/// - W = Wheelover
///
class zdl : public sentence
{
friend class detail::factory;
public:
constexpr static sentence_id ID = sentence_id::ZDL;
constexpr static const char * TAG = "ZDL";
zdl();
zdl(const zdl &) = default;
zdl & operator=(const zdl &) = default;
zdl(zdl &&) = default;
zdl & operator=(zdl &&) = default;
protected:
zdl(talker talk, fields::const_iterator first, fields::const_iterator last);
void append_data_to(std::string &, const version &) const override;
private:
duration time_to_point_;
units::nautical_miles distance_;
type_of_point type_point_ = type_of_point::reference;
public:
duration get_time_to_point() const { return time_to_point_; }
units::length get_distance() const { return {distance_}; }
type_of_point get_type_point() const { return type_point_; }
void set_time_to_point(const duration & t) noexcept { time_to_point_ = t; }
void set_distance(units::length t) noexcept { distance_ = t.get<units::nautical_miles>(); }
void set_type_point(type_of_point t) noexcept { type_point_ = t; }
};
}
#endif
| true |
9c035692413a08f9e4440dd8aa56eb7665094759 | C++ | seanemo/arcadesystem | /GUI_files/headers/OptionsButton.h | UTF-8 | 1,920 | 3.21875 | 3 | [] | no_license |
// OptionsButton.h
// This is a specific type of button
// Abstractly, the OptionsButton class is a way to customize the screen view
// The main purpose of the OptionsButton is customizability
#ifndef OPTIONS_BUTTON_H
#define OPTIONS_BUTTON_H
#include "Button.h"
class OptionsButton : public Button
{
public:
// override constructor
OptionsButton(std::string texturePath_in);
virtual ~OptionsButton();
// method to update, more for options button but can be for simple button gifs
Action update(SDL_Event* event);
// method to render the current Buttons
void render(SDL_Renderer* renderer);
void setButtonPosition(int x_in, int y_in)
{
setX(x_in);
setY(y_in);
if (optionTexture != nullptr)
{
optionTexture->setPosition(x_in, y_in);
}
}
void addOption(Action* buttonAction_in, ArcadeTexture* buttonTexture_in)
{
//printf("\n add option\n");
buttonActionList.push_back(buttonAction_in);
buttonTextureList.push_back(buttonTexture_in);
}
Action* getButtonAction() { return buttonActionList[currentIndex]; }
ArcadeTexture* getButtonTexture() { return buttonTextureList[currentIndex]; }
std::vector<ArcadeTexture*>* getButtonTextureList() { return &buttonTextureList; }
std::vector<Action*>* getButtonActionList() { return &buttonActionList; }
void setCurrentTextureIndex(int currentButtonIndex_in) { currentIndex = currentButtonIndex_in; }
int getCurrentButtonIndex() { return currentIndex; }
ArcadeTexture* getOptionTexture() { return optionTexture; }
void setOptionTexture(ArcadeTexture* optionTexture_in) { optionTexture = optionTexture_in; }
private:
// button texture
ArcadeTexture* optionTexture;
// holds a vector of arcade textures to iterate through
std::vector<ArcadeTexture*> buttonTextureList;
// holds the index of the current button texture
int currentIndex;
// holds a vector of button actions
std::vector<Action*> buttonActionList;
};
#endif
| true |
3b295cbdea91463fef2ded00303ba216882b5ca5 | C++ | coding-blocks-archives/vmc-codingblocks-2017 | /17-11-29/twoDFunc.cpp | UTF-8 | 234 | 2.53125 | 3 | [] | no_license | // Deepak Aggarwal, Coding Blocks
// deepak@codingblocks.com
#include <iostream>
using namespace std;
void display(int arr[100][10], int nr, int nc){
}
int main() {
int arr[10][10];
int nr, nc;
cin >> nr >> nc;
display(arr, nr, nc);
} | true |
6d773882bc1cbee85ec06ee12b93461733879e55 | C++ | toblich/UDrive | /include/server.h | UTF-8 | 2,922 | 2.625 | 3 | [] | no_license | #ifndef SERVER_H_
#define SERVER_H_
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include "logger.h"
#include "profile.h"
#include "session.h"
#include "metadata.h"
#include "folder.h"
#include "file.h"
#include "mongoose.h"
#include "bd.h"
#include "parserURI.h"
#include <thread>
#include <stdarg.h>
#define NOTFOUND 404
using namespace std;
/**
* @brief Se encarga del manejo del Servidor y de la redirección de los request hacia las clases de la API REST.
*/
class Server {
public:
/**
* @brief Constructor: Crea un Servidor.
*
* @param portNumber string con el puerto a traves del cual se va a comunicar el servidor.
* @param perfiles BD* a una base de datos de perfiles.
* @param sesiones BD* a una base de datos de sesiones.
* @param passwords BD* a una base de datos de passwords.
* @param metadatos BD* a una base de datos de metadatos.
* @param conf Configuracion con los datos de configuracion leidos del archivo.
*
*/
Server(string portNumber, BD* perfiles, BD* sesiones, BD* passwords, BD* metadatos, Configuracion conf);
virtual ~Server();
/**
* @brief Función que se utiliza para redirigir el comportamiento del Servidor dependiendo el
* evento que le llegó.
*
* @param connection mg_connection* con la conexion Cliente-Servidor.
* @param event mg_event con el evento que le llegó al Servidor a partir de un request
*
* @retval MG_TRUE en caso de que el evento sea correcto
* @retval MG_FALSE en caso de que el evento no se pueda procesar
*/
mg_result eventHandler(mg_connection *connection, mg_event event);
/**
* @brief Función estática que usa el mg_create_server para redirigir las conexiones.
*
* @param connection mg_connection* con la conexion Cliente-Servidor.
* @param event mg_event con el evento que le llegó al Servidor a partir de un request
*
*/
static int mgEventHandler(mg_connection *connection, mg_event event);
/**
* @brief Función que realiza el poll en el Server para recibir las requests.
*
* @param server mg_server* con el server que se está utilizando
*
*/
static void pollServer(mg_server* server);
bool isRunning() { return running; }
static void close(int signal) { running = false; };
private:
static bool running;
map<string, RealizadorDeEventos*> mapaURI; ///< Mapa que se utiliza para redirigir hacia la API REST
vector<mg_server*> servers; ///< Vector de servers utilizados (existe uno por cada thread)
vector<thread*> threads; ///< Vector de threads corriendo
ManejadorDeUsuarios* manejadorUsuarios;
ManejadorArchivosYMetadatos* manejadorAYM;
BD* perfiles;
BD* sesiones;
BD* passwords;
BD* metadatos;
mg_result closeHandler(mg_connection* connection);
mg_result requestHandler(mg_connection* connection);
int cantThreads;
static int pollMilisec;
};
#endif /* SERVER_H_ */
| true |
5ca9682dbf08350e5711cc88d3b16a86b5a3012a | C++ | diziqian/tinyBind | /tinytest.cpp | UTF-8 | 3,474 | 2.765625 | 3 | [] | no_license | #include "tinybind.cpp"
#include <stdio.h>
#include <vector>
#include <list>
struct MyData
{
int i;
double d;
char const * s;
std::vector<int> vec;
int iref;
void setIntvalue( int in ) {
i = in;
}
int intvalue() {
return i;
}
int & getIRef() {
return iref;
}
};
TiXmlBinding<MyData> const *
GetTiXmlBinding( MyData const &, Identity<MyData> )
{
static MemberTiXmlBinding<MyData> binding;
if( binding.empty() ) {
binding.AddMember( "ITAG", Member(&MyData::i) );
binding.AddMember( "ITAGGETSET", Member(&MyData::intvalue, &MyData::setIntvalue) );
binding.AddMember( "DTAG", Member(&MyData::d) );
binding.AddMember( "STAG", Member(&MyData::s) );
binding.AddMember( "VEC", Member(&MyData::vec) );
binding.AddMember( "IREF", Member(&MyData::getIRef) );
}
return &binding;
}
#if 0
typedef std::vector<int> VecT;
TiXmlBinding<VecT> const *
GetTiXmlBinding( VecT const & )
{
static StlContainerTiXmlBinding<int, VecT> binding(true, "INT");
return &binding;
}
typedef std::list<MyData> VecT2;
TiXmlBinding<VecT2> const *
GetTiXmlBinding( VecT2 const & )
{
static StlContainerTiXmlBinding<MyData, VecT2> binding(false, "DATAVECENTRY");
return &binding;
}
#endif
struct MyData2
{
MyData dataOne;
std::list<MyData> dataVec;
int xyz;
};
TiXmlBinding<MyData2> const *
GetTiXmlBinding( MyData2 const &, Identity<MyData2> )
{
static MemberTiXmlBinding<MyData2> binding;
if( binding.empty() ) {
binding.AddMember( "XYZ", MemberAttribute(&MyData2::xyz ))->setFlags(MemberOptional);
binding.AddMember( "DATAONE", Member(&MyData2::dataOne) );
binding.AddMember( "DATAVEC", MemberPeer(&MyData2::dataVec) );
}
return &binding;
}
//int main()
//{
// MyData testData;
// testData.i = 100;
// testData.iref = 52;
// testData.d = 42.3;
// testData.s = "hello world";
// testData.vec.push_back(1);
// testData.vec.push_back(1);
// testData.vec.push_back(2);
// testData.vec.push_back(3);
// testData.vec.push_back(5);
// printf( "\nTestData: %d %d %g %s %d\n", testData.i, testData.iref, testData.d, testData.s, testData.vec[0] );
// TiXmlElement test("TESTDATA");
// BindToXml( &test, testData );
// test.Print( stdout, 0 );
// MyData testData2;
// BindFromXml( test, &testData2 );
// printf( "\nTestData2: %d %d %g %s %d\n", testData2.i, testData2.iref, testData2.d, testData2.s, testData2.vec[0] );
// TiXmlElement testAgain("AGAIN");
// BindToXml( &testAgain, testData2 );
// testAgain.Print( stdout, 0 );
// MyData2 testData3;
// testData3.xyz = 10342;
// testData3.dataOne = testData2;
// testData3.dataVec.push_back(testData2);
// testData3.dataVec.push_back(testData2);
// printf( "\nTestData3: %i %i %g %s %s\n", testData3.xyz, testData3.dataOne.i,
// testData3.dataOne.d, testData3.dataOne.s, testData3.dataVec.front().s );
// TiXmlElement test2("TEST2");
// BindToXml( &test2, testData3 );
// test2.Print( stdout, 0 );
// MyData2 testData4;
// BindFromXml( test2, &testData4 );
// printf( "\nTestData4: %i %i %g %s %s\n", testData4.xyz, testData4.dataOne.i, testData4.dataOne.d,
// testData4.dataOne.s, testData4.dataVec.front().s );
// MyData2 testData5;
// test2.SetAttribute("XYZ", "");
// testData5.xyz = 0;
// BindFromXml( test2, &testData5 );
// printf( "\nTestData5: %i %i %g %s %s\n", testData5.xyz, testData5.dataOne.i, testData5.dataOne.d,
// testData5.dataOne.s, testData5.dataVec.front().s );
// return 0;
//}
| true |
1304a45db34974c9fe9d84e1a73959a1d333f7dc | C++ | jramosss/Codeforces | /122A-LuckyDivision/luckydivision.cpp | UTF-8 | 1,668 | 4.1875 | 4 | [] | no_license | /*
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose
decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4
are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number.
Help him find out if the given number n is almost lucky.
Input
The single line contains an integer n (1 ≤ n ≤ 1000) — the number that needs to be checked.
Output
In the only line print "YES" (without the quotes), if number n is almost lucky.
Otherwise, print "NO" (without the quotes).
*/
#include <iostream>
using namespace std;
static int is_a_lucky_number (int n){
std::string str = to_string(n);
bool flag1 = false;
bool flag2 = false;
for (char c : str){
if (c == '4' && !flag1){
flag1 = true;
}
else if (c == '7' && !flag2){
flag2 = true;
}
}
return flag1 && flag2;
}
int main () {
int n; //Number
cin >> n;
if (n % 7 == 0 || n % 4 == 0 || is_a_lucky_number(n)){
printf("YES");
}
else{
printf("NO");
}
return 0;
}
/*
En realidad el que publique fue este que es choreado pq el otro me fallaba en el test 19
#include <iostream>
using namespace std;
int a;
int main() {
cin >> a;
if (a % 4 == 0 || a % 7 == 0 || a % 44 == 0 || a % 47 == 0 ||
a % 74 == 0 || a % 77 == 0 || a % 444 == 0 || a % 447 == 0
|| a % 474 == 0 || a % 477 == 0 || a % 744 == 0 || a % 747 == 0
|| a % 774 == 0 || a % 777 == 0) {
cout << "YES";
} else {
cout << "NO";
}
}
*/ | true |
eeb0f24c64629abc6c3637831a489256d265a012 | C++ | theVelislavKolesnichenko/CPlusPlusOOP | /Overloading/Point.cpp | UTF-8 | 800 | 3.5625 | 4 | [] | no_license | #include "Point.h"
Point::Point()
{
num_x = Num();
num_y = Num();
}
Point::Point(Num x, Num y)
{
num_x = x;
num_y = y;
}
Num Point::get_x()
{
return num_x;
}
Num Point::get_y()
{
return num_y;
}
Point Point::operator++()
{
this->num_x = Num(this->num_x.getNum() + 1);
this->num_y = Num(this->num_y.getNum() + 1);
return Point(this->get_x(), this->get_y());
}
Point Point::operator++(int)
{
Point obj = Point(this->num_x, this->num_y);
this->num_x = Num(this->num_x.getNum() + 1);
this->num_y = Num(this->num_y.getNum() + 1);
return obj;
}
ostream& operator<<(ostream& output, const Point& point)
{
Point obj = point;
output << "Point (x, y): (" << obj.get_x().getNum() << ", " << obj.get_y().getNum() << ")";
return output;
}
| true |
f19391c159e15d27f77f7f2dd98884e8163c6f4c | C++ | diogoesnog/MIEI | /3rd Year/2nd Semester/Computação Gráfica/Aulas/Aula 2/main.cpp | UTF-8 | 2,555 | 3.03125 | 3 | [] | no_license | // Aula 2
#include <GL/glut.h>
#include <math.h>
void changeSize(int w, int h) {
// Prevent a divide by zero, when window is too short
// (you cant make a window with zero width).
if(h == 0)
h = 1;
// compute window's aspect ratio
float ratio = w * 1.0 / h;
// Set the projection matrix as current
glMatrixMode(GL_PROJECTION);
// Load Identity Matrix
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set perspective
gluPerspective(45.0f ,ratio, 1.0f ,1000.0f);
// return to the model view matrix mode
glMatrixMode(GL_MODELVIEW);
}
void renderScene(void) {
// clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// set the camera
glLoadIdentity();
gluLookAt(5.0, 5.0, 5.0,
0.0,0.0,0.0,
0.0f,1.0f,0.0f);
// put the geometric transformations here
// put drawing instructions here
// Eixo x verde
glColor3f(0, 1, 0);
glBegin(GL_LINES);
glVertex3f(-20.0f, 0.0f, 0.0f);
glVertex3f(20.0f, 0.0f, 0.0f);
glEnd();
// Eixo y azul
glColor3f(0, 0, 1);
glBegin(GL_LINES);
glVertex3f(0.0f, -20.0f, 0.0f);
glVertex3f(0.0f, 20.0f, 0.0f);
glEnd();
// Eixo z vermelho
glColor3f(1, 0, 0);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, -20.0f);
glVertex3f(0.0f, 0.0f, 20.0f);
glEnd();
// Base
glColor3f(1, 0, 0);
glBegin(GL_TRIANGLES);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 0.0f, 0.0f);
glEnd();
glColor3f(1, 0, 0);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f);
glEnd();
// Triangulo esquerda
glColor3f(1, 0, 1);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(0.5f, 1.0f, 0.5f);
glEnd();
// Triangulo direita
glColor3f(1, 1, 0);
glBegin(GL_TRIANGLES);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.5f, 1.0f, 0.5f);
glEnd();
// End of frame
glutSwapBuffers();
}
// write function to process keyboard events
int main(int argc, char **argv) {
// init GLUT and the window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(800,800);
glutCreateWindow("CG@DI-UM");
// Required callback registry
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
// put here the registration of the keyboard callbacks
// OpenGL settings
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
// enter GLUT's main cycle
glutMainLoop();
return 1;
}
| true |
37b1d1dcf71e645a2278ad7e7b104fa8414fc6da | C++ | yuan-luo/Leetcode-2 | /Leetcode/字符串/0005_longestPalindrome.cpp | UTF-8 | 2,157 | 3.546875 | 4 | [] | no_license | // https://leetcode-cn.com/problems/longest-palindromic-substring/
#include <string>
#include <iostream>
using namespace std;
int is_Palindrome(const string &s, int &left, int right)
{
while (left >=0 && right < s.size() && s[left] == s[right]) {
left--;
right++;
}
// [left, right)
left++;
return right - left;
}
//������ɢ��������һ���ַ�����������������Ϊ������ɢ
string longestPalindrome(string s) {
if (s.empty())
return "";
int max_len = 1;
int start_pos = 0;
// ����Ϊn���ַ���
for (int i = 0; i < s.size(); i++) {
int left = i;
// �ҵ���iλ��Ϊ���ĵ�������Ӵ�
int len = is_Palindrome(s, left, i);
if (len > max_len) {
max_len = len;
start_pos = left;
}
// �ҵ�i�Ҳ��϶Ϊ���ĵ�������Ӵ�
left = i;
len = is_Palindrome(s, left, i + 1);
if (len > max_len) {
max_len = len;
start_pos = left;
}
}
return s.substr(start_pos, max_len);
}
// dp[i][j]: [i, j] : [i, j)�Dz��ǻ����Ӵ��� ����j >=i
string longestPalindrome2(string s)
{
if (s.empty())
return "";
auto count = s.size();
bool dp[count][count];
int max = 1;
int begin = 0;
// [i,j] = [i+1, j-1] && s[i] == s[j]
for (int i = count - 1; i >= 0; i--) {
for (int j = i; j <= count -1; ++j) {
dp[i][j] = false;
if (j - i + 1 <= 2) {
dp[i][j] = s[i] == s[j];
} else if (dp[i+1][j-1] == true && s[i] == s[j])
// [i,j] : [i+1, j-1] �����������һ���ַ� s[i] == s[j]
dp[i][j] = true;
if (dp[i][j] && (j- i + 1) > max) {
max = j - i + 1;
begin = i;
}
}
}
return s.substr(begin, max);
}
int main()
{
std::string s("bb");
std::cout << longestPalindrome2(s);
}
| true |