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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
55adf32824451ed46b49d47af0f7e647975960d0 | C++ | SteveDCronin/NodeEmitterPublic | /node-steve.cc | UTF-8 | 2,025 | 2.53125 | 3 | [] | no_license | #include "node-steve.h" //interface file
#include <v8.h>
#include <node.h>
using namespace v8;
using namespace node;
static int showDebugMessages = 1;
static Persistent<String> sym_emit;
SteveNode::SteveNode() : ObjectWrap() {
if (showDebugMessages==1) printf("\nSteveNode - Constructor");
this->steve = new Steve();
this->steve->setSteveEmitter(this);
}
SteveNode::~ SteveNode() {
if (showDebugMessages==1) printf("\nSteveNode - Destructor");
delete steve;
steve = NULL;
}
void SteveNode::Initialize(Handle<Object> target) {
if (showDebugMessages==1) printf("\nSteveNode - Initialize");
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "Start", Start);
sym_emit = NODE_PSYMBOL("emit");
target->Set(String::NewSymbol("SteveNode"), t->GetFunction());
}
Handle<Value> SteveNode::New(const Arguments& args) {
if (showDebugMessages==1) printf("\nSteveNode - New()");
HandleScope scope;
SteveNode *localNode = new SteveNode(); //this calls the constructor
localNode->Wrap(args.This());
return args.This();
}
Handle<Value> SteveNode::Start(const Arguments& args) {
if (showDebugMessages==1) printf("\nSteveNode - Start()");
HandleScope scope;
SteveNode *localNode = ObjectWrap::Unwrap<SteveNode>(args.This());
localNode->steve->startHeartbeat(3);
}
void SteveNode::myEmit(int argc, Handle<Value> argv[]) {
char emitType[256];
argv[0]->ToString()->WriteAscii(emitType,0,-1);
if (showDebugMessages==1) printf("\nnode-steve.node - myEmit: %s", emitType);
HandleScope scope;
// ** complete this method such that the 'success' event is received in JavaScript by the registered listener **
}
extern "C" void init(Handle<Object> target) {
if (showDebugMessages==1) printf("node-steve.node - init");
HandleScope scope;
SteveNode::Initialize(target);
NODE_MODULE(SteveNode, init);
}
| true |
dab3f57799f61f575e7f779c0b37a91fdcf49f68 | C++ | xanatower/Ard | /joy_stick.ino | UTF-8 | 1,618 | 2.75 | 3 | [] | no_license | // Module KY023
// For more info see http://tkkrlab.nl/wiki/Arduino_KY-023_XY-axis_joystick_module
int JoyStick_X = A0; // x
int JoyStick_Y = A1; // y
int JoyStick_Z = 3; // key
int mapped_x = 0;
int mapped_y = 0;
//servo stuffs
#include <Servo.h>
Servo myservo;
Servo myservo1;// create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;
void setup ()
{
pinMode (JoyStick_X, INPUT);
pinMode (JoyStick_Y, INPUT);
pinMode (JoyStick_Z, INPUT_PULLUP);
Serial.begin (9600); // 9600 bps
myservo.attach(9);
myservo1.attach(10);
}
void loop ()
{
int x, y, z;
x = analogRead (JoyStick_X);
y = analogRead (JoyStick_Y);
z = digitalRead (JoyStick_Z);
Serial.print (x, DEC);
Serial.print (",");
Serial.print (y, DEC);
Serial.print (",");
Serial.print (z, DEC);
/*
if(z==0){
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}*/
pos = map(y,0,1024,180,0);
myservo1.write(x/5.69); // tell servo to go to position in variable 'pos'
// waits 15ms for the servo to reach the position
// myservo.write(y/5.69); // tell servo to go to position in variable 'pos'
myservo.write(pos);
// waits 15ms for the servo to reach the position
Serial.print (",");
Serial.println (pos, DEC);
//
}
| true |
5c59edfa64cc0647dd379b6cd9b501b072ed2cc5 | C++ | paul-hc/DevTools | /CommonUtl/utl/Registry.h | UTF-8 | 10,701 | 2.546875 | 3 | [] | no_license | #ifndef Registry_h
#define Registry_h
#pragma once
#include <atlbase.h>
#include "Registry_fwd.h"
#include "ErrorHandler.h"
namespace reg
{
bool WriteStringValue( HKEY hParentKey, const TKeyPath& keySubPath, const TCHAR* pValueName, const std::tstring& text );
bool DeleteKey( HKEY hParentKey, const TKeyPath& keySubPath, RecursionDepth depth = Deep ); // deletes the rightmost key (identified by 'filename')
class CKey;
bool OpenKey( CKey* pKey, const TCHAR* pKeyFullPath, REGSAM samDesired = KEY_READ | KEY_WRITE );
bool CreateKey( CKey* pKey, const TCHAR* pKeyFullPath );
bool KeyExist( const TCHAR* pKeyFullPath, REGSAM samDesired = KEY_READ );
bool IsKeyWritable( const TCHAR* pKeyFullPath, bool* pAccessDenied = nullptr );
}
namespace reg
{
class CKey : private utl::noncopyable
{
public:
explicit CKey( HKEY hKey = nullptr ) : m_key( hKey ) {}
CKey( CKey& rSrcMove ) : m_key( rSrcMove.m_key ) {} // move constructor
~CKey() { Close(); }
CKey& operator=( CKey& rSrcMove ) { m_key = rSrcMove.m_key; return *this; } // move assignment
bool Open( HKEY hParentKey, const TCHAR* pSubKeyPath, REGSAM samDesired = KEY_READ | KEY_WRITE ) throw()
{
return s_lastError.Store( m_key.Open( hParentKey, pSubKeyPath, samDesired ) );
}
bool Open( HKEY hParentKey, const TKeyPath& subKeyPath, REGSAM samDesired = KEY_READ | KEY_WRITE ) throw()
{
return s_lastError.Store( m_key.Open( hParentKey, subKeyPath.GetPtr(), samDesired ) );
}
bool Create( HKEY hParentKey, const TCHAR* pSubKeyPath, LPTSTR pClass = REG_NONE,
DWORD dwOptions = REG_OPTION_NON_VOLATILE, REGSAM samDesired = KEY_READ | KEY_WRITE, SECURITY_ATTRIBUTES* pSecAttr = nullptr, DWORD* pDisposition = nullptr ) throw()
{
return s_lastError.Store( m_key.Create( hParentKey, pSubKeyPath, pClass, dwOptions, samDesired, pSecAttr, pDisposition ) );
}
bool Create( HKEY hParentKey, const TKeyPath& subKeyPath, LPTSTR pClass = REG_NONE,
DWORD dwOptions = REG_OPTION_NON_VOLATILE, REGSAM samDesired = KEY_READ | KEY_WRITE, SECURITY_ATTRIBUTES* pSecAttr = nullptr, DWORD* pDisposition = nullptr ) throw()
{
return s_lastError.Store( m_key.Create( hParentKey, subKeyPath.GetPtr(), pClass, dwOptions, samDesired, pSecAttr, pDisposition ) );
}
HKEY Get( void ) const { return m_key.m_hKey; }
CRegKey& GetKey( void ) { return m_key; }
static const utl::CErrorCode& GetLastError( void ) { return s_lastError; } // last API call result
static utl::CErrorCode& RefLastError( void ) { return s_lastError; }
static bool IsLastError_AccessDenied( void ) { return ERROR_ACCESS_DENIED == s_lastError.Get(); }
bool IsOpen( void ) const { return Get() != nullptr; }
bool Close( void ) { return ERROR_SUCCESS == m_key.Close(); } // does not override s_lastError, for further inspection of the open error cause
void Reset( HKEY hKey = nullptr ) { Close(); m_key.Attach( hKey ); }
HKEY Detach( void ) { return m_key.Detach(); }
bool Flush( void ) { return s_lastError.Store( m_key.Flush() ); } // flush the key's data to disk - resource intensive!
static bool ParseFullPath( HKEY& rhHive, TKeyPath& rSubPath, const TCHAR* pKeyFullPath ); // full path includes registry hive (the root)
void DeleteAll( void ) { DeleteAllValues(); DeleteAllSubKeys(); }
// SUB-KEYS
bool HasSubKey( const TCHAR* pSubKeyName ) const;
void QuerySubKeyNames( std::vector<std::tstring>& rSubKeyNames ) const;
bool DeleteSubKey( const TCHAR* pSubKey, RecursionDepth depth = Shallow ) { return s_lastError.Store( Shallow == depth ? m_key.DeleteSubKey( pSubKey ) : m_key.RecurseDeleteKey( pSubKey ) ); }
void DeleteAllSubKeys( void );
// VALUES
bool HasValue( const TCHAR* pValueName ) const { return GetValueType( pValueName ) != REG_NONE; }
void QueryValueNames( std::vector<std::tstring>& rValueNames ) const;
bool DeleteValue( const TCHAR* pValueName ) { return s_lastError.Store( m_key.DeleteValue( pValueName ) ); }
void DeleteAllValues( void );
std::pair<DWORD, size_t> GetValueInfo( const TCHAR* pValueName ) const; // <Type, BufferSize>
DWORD GetValueType( const TCHAR* pValueName ) const { return GetValueInfo( pValueName ).first; }
size_t GetValueBufferSize( const TCHAR* pValueName ) const { return GetValueInfo( pValueName ).second; }
// string
bool WriteStringValue( const TCHAR* pValueName, const std::tstring& text );
bool QueryStringValue( const TCHAR* pValueName, std::tstring& rText ) const;
std::tstring ReadStringValue( const TCHAR* pValueName, const std::tstring& defaultText = str::GetEmpty() ) const { std::tstring text; return QueryStringValue( pValueName, text ) ? text : defaultText; }
// multi-string
template< typename StringyT >
bool WriteMultiString( const TCHAR* pValueName, const std::vector<StringyT>& values );
template< typename StringyT >
bool QueryMultiString( const TCHAR* pValueName, std::vector<StringyT>& rValues ) const;
// number
template< typename NumericT >
bool WriteNumberValue( const TCHAR* pValueName, NumericT value );
template< typename NumericT >
bool QueryNumberValue( const TCHAR* pValueName, NumericT& rNumber ) const;
template< typename NumericT >
NumericT ReadNumberValue( const TCHAR* pValueName, NumericT defaultNumber = NumericT() ) const { NumericT number; return QueryNumberValue( pValueName, number ) ? number : defaultNumber; }
// GUID (persisted as string)
bool WriteGuidValue( const TCHAR* pValueName, const GUID& value ) { return s_lastError.Store( m_key.SetGUIDValue( pValueName, value ) ); }
bool QueryGuidValue( const TCHAR* pValueName, GUID& rValue ) const { return s_lastError.Store( m_key.QueryGUIDValue( pValueName, rValue ) ); }
// binary structure
template< typename ValueT >
bool WriteBinaryValue( const TCHAR* pValueName, const ValueT& value );
template< typename ValueT >
bool QueryBinaryValue( const TCHAR* pValueName, ValueT* pValue ) const;
// binary buffer
template< typename ValueT >
bool WriteBinaryBuffer( const TCHAR* pValueName, const std::vector<ValueT>& bufferValue );
template< typename ValueT >
bool QueryBinaryBuffer( const TCHAR* pValueName, std::vector<ValueT>& rBufferValue ) const;
private:
mutable CRegKey m_key; // the ATL key; mutable for friendly Query... methods (declared non-const in CRegKey class)
static utl::CErrorCode s_lastError; // stores last API call result; not thread-safe, caller must serialize access for multi-threading
};
struct CKeyInfo
{
CKeyInfo( void ) { Clear(); }
CKeyInfo( HKEY hKey ) { Build( hKey ); }
CKeyInfo( const CKey& key )
{
if ( key.IsOpen() )
Build( key.Get() );
else
Clear();
}
void Clear( void );
bool Build( HKEY hKey );
public:
DWORD m_subKeyCount;
DWORD m_subKeyNameMaxLen;
DWORD m_valueCount;
DWORD m_valueNameMaxLen;
DWORD m_valueBufferMaxLen;
CTime m_lastWriteTime;
};
}
#include "Algorithms.h"
#include "StringUtilities.h"
namespace reg
{
// CKey template code
template< typename StringyT >
bool CKey::WriteMultiString( const TCHAR* pValueName, const std::vector<StringyT>& values )
{
ASSERT( IsOpen() );
std::vector<TCHAR> msData; // multi-string data: an array of zero-terminated strings, terminated by 2 zero characters
str::QuickTokenize( msData, str::JoinLines( values, _T("|") ).c_str(), _T("|") );
return s_lastError.Store( m_key.SetMultiStringValue( pValueName, &msData.front() ) );
}
template< typename StringyT >
bool CKey::QueryMultiString( const TCHAR* pValueName, std::vector<StringyT>& rValues ) const
{
ASSERT( IsOpen() );
std::vector<TCHAR> buffer( GetValueBufferSize( pValueName ) );
if ( buffer.empty() )
return false;
ULONG count = static_cast<ULONG>( buffer.size() );
s_lastError.Store( m_key.QueryMultiStringValue( pValueName, &buffer.front(), &count ) );
ASSERT( s_lastError.Get() != ERROR_MORE_DATA ); // GetValueBufferSize() sized the buffer properly?
if ( s_lastError.IsError() )
return false;
rValues.clear();
for ( const TCHAR* pItem = &buffer.front(); *pItem != _T('\0'); pItem += str::GetLength( pItem ) + 1 )
rValues.push_back( StringyT( pItem ) );
return true;
}
template< typename NumericT >
bool CKey::WriteNumberValue( const TCHAR* pValueName, NumericT value )
{
ASSERT( IsOpen() );
if ( sizeof( ULONGLONG ) == sizeof( NumericT ) )
return s_lastError.Store( m_key.SetQWORDValue( pValueName, static_cast<ULONGLONG>( value ) ) );
else
return s_lastError.Store( m_key.SetDWORDValue( pValueName, static_cast<DWORD>( value ) ) );
}
template< typename NumericT >
bool CKey::QueryNumberValue( const TCHAR* pValueName, NumericT& rNumber ) const
{
ASSERT( IsOpen() );
if ( sizeof( ULONGLONG ) == sizeof( NumericT ) )
{
ULONGLONG value;
if ( !s_lastError.Store( m_key.QueryQWORDValue( pValueName, value ) ) )
return false;
rNumber = static_cast<NumericT>( value );
}
else
{
DWORD value;
if ( !s_lastError.Store( m_key.QueryDWORDValue( pValueName, value ) ) )
return false;
rNumber = static_cast<NumericT>( value );
}
return true;
}
template< typename ValueT >
bool CKey::WriteBinaryValue( const TCHAR* pValueName, const ValueT& value )
{
ASSERT( IsOpen() );
return s_lastError.Store( m_key.SetBinaryValue( pValueName, &value, static_cast<ULONG>( sizeof( value ) ) ) );
}
template< typename ValueT >
bool CKey::QueryBinaryValue( const TCHAR* pValueName, ValueT* pValue ) const
{
ASSERT( IsOpen() );
ASSERT_PTR( pValue );
size_t byteSize = GetValueBufferSize( pValueName );
if ( 0 == byteSize || byteSize != sizeof( ValueT ) )
return false; // bad size or it doesn't line up with ValueT's storage size
ULONG count = static_cast<ULONG>( byteSize );
return s_lastError.Store( m_key.QueryBinaryValue( pValueName, pValue, &count ) );
}
template< typename ValueT >
bool CKey::WriteBinaryBuffer( const TCHAR* pValueName, const std::vector<ValueT>& bufferValue )
{
return s_lastError.Store( m_key.SetBinaryValue( pValueName, &bufferValue.front(), static_cast<ULONG>( utl::ByteSize( bufferValue ) ) ) );
}
template< typename ValueT >
bool CKey::QueryBinaryBuffer( const TCHAR* pValueName, std::vector<ValueT>& rBufferValue ) const
{
size_t byteSize = GetValueBufferSize( pValueName );
if ( 0 == byteSize )
return false;
if ( ( byteSize % sizeof( ValueT ) ) != 0 )
return false; // byte size doesn't line up with ValueT's storage size
rBufferValue.resize( byteSize / sizeof( ValueT ) );
ULONG count = static_cast<ULONG>( byteSize );
return s_lastError.Store( m_key.QueryBinaryValue( pValueName, &rBufferValue.front(), &count ) );
}
}
#endif // Registry_h
| true |
e8c4e78e359ca72abe0c5badbd9e0fad44061590 | C++ | jcstange/Arduino | /display7_pcf8574_banheira/display7_pcf8574_banheira.ino | UTF-8 | 3,456 | 2.546875 | 3 | [] | no_license | #include <Wire.h>
long cont = 0;
int tempsensor = 0;
int tempwanted = 25;
void setup() {
for (int i=2; i<=13; i++) {
pinMode(i, OUTPUT);
digitalWrite(i,0);
}
pinMode (A0,INPUT);
Serial.begin(9600);
Wire.begin(); // Join I2C bus
}
void loop() {
temp_sensor();
if (digitalRead(6)==HIGH || digitalRead(7)==HIGH) {
temp_wanted();
}
if (tempsensor<tempwanted) {
digitalWrite(8,1);
digitalWrite(9,1);
} else {
digitalWrite(8,0);
digitalWrite(9,0);
}
cont = millis();
while (millis()-cont < 1000) {
digit(1);
num (tempsensor / 10 % 10, 1);
delay(4);
num(tempsensor / 10 % 10, 0);
digit(2);
num(tempsensor % 10, 1);
delay(4);
num(tempsensor % 10, 0);
digit(3);
num (tempwanted / 10 % 10, 1);
delay(4);
num(tempwanted / 10 % 10, 0);
digit(4);
num(tempwanted % 10, 1);
delay(4);
num(tempwanted % 10, 0);
}
}
void temp_wanted() {
if (digitalRead(7)== HIGH) {
tempwanted++;
}
if (digitalRead(6) == HIGH) {
tempwanted--;
}
}
void temp_sensor() {
for(int i=0; i<10; i++) {
if(i<9) {
tempsensor = tempsensor+(analogRead(A0)*readVcc()/10230);
} else { tempsensor= tempsensor/9; }
}
}
long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(1); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}
void digit (int n) {
switch(n) {
case (0):
Wire.beginTransmission(56);
Wire.write(B00000000);
Wire.endTransmission();
break;
case (1):
Wire.beginTransmission(56);
Wire.write(B00000001);
Wire.endTransmission();
break;
case (2):
Wire.beginTransmission(56);
Wire.write(B00000010);
Wire.endTransmission();
break;
case (3):
Wire.beginTransmission(56);
Wire.write(B00000100);
Wire.endTransmission();
break;
case (4):
Wire.beginTransmission(56);
Wire.write(B00001000);
Wire.endTransmission();
break;
}
}
void num(int n, boolean on) {
switch(n){
case (0):
digitalWrite(3,on);
digitalWrite(11,on);
break;
case (1):
digitalWrite(3,on);
digitalWrite(4,on);
digitalWrite(5,on);
digitalWrite(11,on);
digitalWrite(12,on);
digitalWrite(13,on);
break;
case (2):
digitalWrite(2,on);
digitalWrite(5,on);
digitalWrite(11,on);
break;
case (3):
digitalWrite(5,on);
digitalWrite(13,on);
digitalWrite(11,on);
break;
case (4):
digitalWrite(4,on);
digitalWrite(12,on);
digitalWrite(13,on);
digitalWrite(11,on);
break;
case (5):
digitalWrite(10,on);
digitalWrite(13,on);
digitalWrite(11,on);
break;
case (6):
digitalWrite(10,on);
digitalWrite(11,on);
break;
case (7):
digitalWrite(3,on);
digitalWrite(5,on);
digitalWrite(11,on);
digitalWrite(12,on);
digitalWrite(13,on);
break;
case (8):
digitalWrite(11,on);
break;
case (9):
digitalWrite(13,on);
digitalWrite(11,on);
break;
}
}
| true |
5341e5abcc2c0787df5e02ab0d6e7ce0b783aa5c | C++ | harrynull/MemoryPool | /MemoryPool/src/Allocators.h | UTF-8 | 2,749 | 3.4375 | 3 | [
"MIT"
] | permissive | #ifndef ALLOCATORS_H__
#define ALLOCATORS_H__
class MemoryPool;
template <class T, size_t Size>
class FixedMemoryPool;
// Allocators for memory pools
template <class T>
class Allocator
{
public:
using value_type = T;
using pointer = T*;
using size_type = size_t;
using difference_type = ptrdiff_t;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using PoolType = MemoryPool;
template <class U>
struct rebind { typedef Allocator<U> other; };
Allocator(PoolType* pool) :m_pool(pool) {}
template <class U> Allocator(Allocator<U>& other) : m_pool(other.getPool()) {}
pointer allocate(std::size_t n)
{
return m_pool->allocate<value_type>(n*sizeof(value_type));
}
void deallocate(pointer p, std::size_t n)
{
m_pool->deallocate(p, n*sizeof(value_type));
}
template <class... Args>
void construct(pointer ptr, Args&&... args)
{
new(ptr) value_type(std::forward<Args>(args)...);
}
void destory(pointer ptr)
{
ptr->~value_type();
}
template <class... Args>
pointer newobj(Args&&... args)
{
auto ptr = allocate(1);
construct(ptr, std::forward<Args>(args)...);
return ptr;
}
void delobj(pointer ptr)
{
destory(ptr);
deallocate(ptr, 1);
}
PoolType* getPool() { return m_pool; }
private:
PoolType* m_pool;
};
template <class T, size_t Size>
class FixedAllocator
{
public:
using value_type = T;
using pointer = T*;
using size_type = size_t;
using difference_type = ptrdiff_t;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using PoolType = FixedMemoryPool<T, Size>;
template <class U>
struct rebind { typedef FixedAllocator<U, Size> other; };
FixedAllocator() = default;
template <class U> FixedAllocator(FixedAllocator<U, Size>&) {}
pointer allocate(std::size_t n)
{
return m_pool.allocate(n);
}
void deallocate(pointer p, std::size_t n)
{
m_pool.deallocate(p, n);
}
template <class... Args>
void construct(pointer ptr, Args&&... args)
{
new(ptr) value_type(std::forward<Args>(args)...);
}
void destory(pointer ptr)
{
ptr->~value_type();
}
template <class... Args>
pointer newobj(Args&&... args)
{
auto ptr = allocate(1);
construct(ptr, std::forward<Args>(args)...);
return ptr;
}
void delobj(pointer ptr)
{
destory(ptr);
deallocate(ptr, 1);
}
PoolType* getPool() { return m_pool; }
private:
PoolType m_pool;
};
#endif // ALLOCATORS_H__
| true |
54edf435f7c16a82d93f2482fb9fc048d738f23d | C++ | mepranav/OOPS_ONE_SHOT_REVISION | /CODE/constructor.cpp | UTF-8 | 595 | 3.78125 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
class student
{
public:
string name;
int age;
int roll_no;
student(string s , int a , int r)
{
name = s;
age = a;
roll_no = r;
}
//parameterized constructors
void print_info()
{
cout<<"name: "<<name<<" age: "<<age<<" roll_no: "<<roll_no<<endl;
}
};
int main()
{
student o1("harsh",89,90); //harsh = name , 89 = age , 90 = rollno
o1.print_info();
// name: harsh age: 89 roll_no: 90
return 0;
} | true |
22775f123e9ea5a3f725ae91cdb752d4fb516c9c | C++ | heldercostaa/lab-programacao-course | /classes/class-11/main.cpp | UTF-8 | 1,676 | 3.328125 | 3 | [] | no_license | //
// main.cpp
// class-11
//
// Created by Helder Costa (github: heldercostaa) on 30/04/19.
// Copyright © 2019. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <random>
void printar_array(const char* i, int tam) {
for (const char* q = i; q != i + tam; q++) {
*q < 10 ? std::cout << " " : std::cout << "";
std::cout << *q << " ";
}
std::cout << "\n";
}
char* texto_aleatorio(int tam) {
srand(static_cast<unsigned int>(time(NULL)));
char* texto = new char[tam];
const char alfabeto[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"!@#$%&*()_-+=,./\\|'\"";
for(int i = 0; i < tam; i++) {
int indice_aleatorio = rand() % (sizeof(alfabeto) - 1);
texto[i] = alfabeto[indice_aleatorio];
}
return texto;
}
void subseq_intuitivo(const char* texto, const char* padrao, int* saida) {
int s = 0;
for (int i = 0; texto[i] != '\0'; i++) {
bool achou = true;
for (int j = 0; padrao[j] != '\0'; j++) {
if (texto[i+j] != padrao[j]) {
achou = false;
break;
}
}
if (achou) {
saida[s] = i;
s++;
}
}
saida[s] = -1;
}
int main() {
int tam = 10;
const char* texto = texto_aleatorio(tam);
const char* padrao = "a";
std::cout << "Texto aleatório: ";
printar_array(texto, tam);
std::cout << "Padrão: " << padrao << std::endl;
int* saida = new int[tam+1];
subseq_intuitivo(texto, padrao, saida);
bool achou_padrao = false;
for(int i = 0; saida[i] != -1; i++) {
std::cout << "Padrão encontrado no índice: " << saida[i] << std::endl;
achou_padrao = true;
}
if(!achou_padrao) { std::cout << "Padrão não encontrado no texto informado."; }
}
| true |
34cd06fa65d7cd035897e1ab08892af5a809a34f | C++ | Anatoliuz/Dijkstra | /Dijkstra.cpp | UTF-8 | 976 | 2.578125 | 3 | [] | no_license | //
// Dijkstra.cpp
// Dijkstra(version 2)
//
// Created by fix on 13/12/15.
// Copyright (c) 2015 Anatoly Filinov. All rights reserved.
//
#include "Dijkstra.h"
void Dijkstra( char* argv[])
{
int vertextNum = 0;
int s = 0;
T_vec vec;
std::ofstream fout(argv[2]);
vec = ReadData(argv, &vertextNum, &s);
double d[vertextNum];
for (int i = 0; i < vertextNum; ++i) {
d[i] = INF;
}
d[s] = 0;
PriorityQueue queue;
queue.enqueue(0, s);
while (!queue.isEmpty()) {
int v = queue.top('v');
int cur_d = queue.top('l');
queue.dequeue();
if(cur_d > d[v]) continue;
for(size_t j = 0; j < vec[v].size(); ++j)
{
int len = vec[v][j].first;
int to = vec[v][j].second;
if( d[v] + len < d[to] )
{
d[to] = d[v] + len;
queue.enqueue(d[to], to);
}
}
}
Printf(vertextNum, s, d, fout);
} | true |
944abef64f9d9afe1a2c8977a1055337a2653056 | C++ | mansi35/Programmers-Community | /Data Structure/Array Or Vector/Find the Missing Number/SolutionByAditya.cpp | UTF-8 | 517 | 3.25 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int findMissingNumber(vector<int> inputArray, int numberOfElements) {
int missingNumber = numberOfElements + 1;
for(int i = 0; i < numberOfElements; i++)
missingNumber ^= inputArray[i] ^ (i + 1);
return missingNumber;
}
int main() {
int numberOfElements = 0;
cin>>numberOfElements;
vector<int> inputArray(numberOfElements);
for(int i = 0; i < numberOfElements; i++)
cin>>inputArray[i];
cout<<findMissingNumber(inputArray, numberOfElements);
return 0;
}
| true |
00e2ec96c33c3b626e361051a91b34293c5d0eba | C++ | miselaytes-anton/electro-pumpkin | /src/dsp/Smooth.cpp | UTF-8 | 542 | 3.171875 | 3 | [] | no_license | // Exponential smoothing filter
// init with coeff, for me 0.05 is normal
// set initial value via setValue(some reading from sensor)
// in update loop call updateValue and folowing getValue for filtered
class Smooth {
private:
float _value;
float _coeff;
public:
// coeff [0..1] if near to zero filter more inert
Smooth(float coeff = 0.001) {
_value = 0.0;
_coeff = coeff;
}
// update inernal value of filter
float process(float value) {
_value = value * _coeff + _value * (1 - _coeff);
return _value;
}
}; | true |
7c81e4b2aa1978de2d7719e59299189a8b756f63 | C++ | shivral/cf | /0800/90/894a.cpp | UTF-8 | 598 | 3.09375 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
#include <string>
#include <vector>
void answer(size_t v)
{
std::cout << v << '\n';
}
void solve(const std::string& s)
{
const size_t n = s.length();
std::vector<size_t> pf(n);
for (size_t i = 0; i < n; ++i) {
if (i > 0)
pf[i] = pf[i-1];
if (s[i] == 'Q')
++pf[i];
}
size_t count = 0;
for (size_t i = 0; i < n; ++i) {
if (s[i] == 'A')
count += pf[i] * (pf.back() - pf[i]);
}
answer(count);
}
int main()
{
std::string s;
std::cin >> s;
solve(s);
return 0;
}
| true |
408465ad55ca928831eb7259e99116440ea95a16 | C++ | RohitKumar-200/CompetitiveProgramming | /LoveBabbarList/13_Kadane_algorithm.cpp | UTF-8 | 847 | 3.984375 | 4 | [] | no_license | // Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
// https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1
#include <bits/stdc++.h>
using namespace std;
// Function to find subarray with maximum sum
// arr: input array
// n: size of array
int maxSubarraySum(int arr[], int n)
{
int localS = arr[0], i, globalS = arr[0];
for (i = 1; i < n; i++)
{
localS = max(arr[i], arr[i] + localS);
globalS = max(globalS, localS);
}
return globalS;
}
int main()
{
int t, n;
cin >> t; //input testcases
while (t--) //while testcases exist
{
cin >> n; //input size of array
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i]; //inputting elements of array
cout << maxSubarraySum(a, n) << endl;
}
} | true |
b58758054a3e9c0862400c3243a5760ff497969d | C++ | NNikonov/MAI_OOP | /Lab2/TBinTree.cpp | UTF-8 | 3,090 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
//#define DEBUG 1
#include "TBinTree.h"
TBinTree::TBinTree()
{
root = nullptr;
}
void TBinTree::Insert(const TItem& val)
{
if (root == nullptr)
root = new TNode(val);
else
{
TNode *currNode = root;
TNode *leafNode = nullptr;
while (currNode != nullptr)
{
leafNode = currNode;
if (val < currNode->data)
currNode = currNode->left;
else
currNode = currNode->right;
}
if (val < leafNode->data)
leafNode->left = new TNode(val);
else
leafNode->right = new TNode(val);
}
}
TItem *TBinTree::Find(size_t side)
{
if (root == nullptr)
return nullptr;
else
{
Quadratum quad_search(side);
TNode *currNode = root;
while (currNode != nullptr)
{
if (quad_search < currNode->data)
currNode = currNode->left;
else if (quad_search > currNode->data)
currNode = currNode->right;
else
return &(currNode->data);
}
}
return nullptr;
}
TBinTree::TNode *TBinTree::MinValueTNode(TNode *node)
{
TNode *current = node;
while (current->left != nullptr)
current = current->left;
return current;
}
void TBinTree::DeleteNode(TNode *node)
{
if (node == nullptr)
return;
DeleteNode(node->left);
DeleteNode(node->right);
delete node;
}
TBinTree::TNode *TBinTree::deleteTNode(TNode *_root, TItem& key)
{
if (_root == nullptr) return _root;
if (key < _root->data)
_root->left = deleteTNode(_root->left, key);
else if (key > _root->data)
_root->right = deleteTNode(_root->right, key);
else {
if (_root->left == nullptr)
{
TNode *temp = _root->right;
delete _root;
return temp;
}
else if (_root->right == nullptr)
{
TNode *temp = _root->left;
delete _root;
return temp;
}
TNode *temp = MinValueTNode(_root->right);
_root->data = temp->data;
_root->right = deleteTNode(_root->right, temp->data);
}
return _root;
}
bool TBinTree::Delete(size_t side)
{
Quadratum quad_search(side);
root = deleteTNode(root, quad_search);
return false;
}
std::ostream& TBinTree::InOrderPrint(std::ostream& os, TNode *node, size_t level) const
{
if (node != nullptr)
{
InOrderPrint(os, node->left, level + 1);
for (size_t i = 0; i < level; i++)
os << '\t';
os << node->data;
InOrderPrint(os, node->right, level + 1);
}
return os;
}
std::ostream& operator<<(std::ostream& os, const TBinTree& bintree)
{
if (bintree.IsEmpty())
os << "Empty tree\n";
else
os << "===============================================\n";
bintree.InOrderPrint(os, bintree.root, 0);
os << "===============================================\n\n";
return os;
}
bool TBinTree::IsEmpty() const
{
return (root == nullptr);
}
TBinTree::~TBinTree()
{
DeleteNode(root);
root = nullptr;
#ifdef DEBUG
std::cout << "Tree deleted\n";
#endif // DEBUG
}
TBinTree::TNode::TNode()
{
#ifdef DEBUG
std::cout << "TNode constructor (default)\n";
#endif // DEBUG
left = nullptr;
right = nullptr;
}
TBinTree::TNode::TNode(const TItem& data)
{
#ifdef DEBUG
std::cout << "TNode constructor (data)\n";
#endif // DEBUG
left = nullptr;
right = nullptr;
this->data = data;
} | true |
2a2361f6d2ee557cc8041f97e143c800c4d899a5 | C++ | bestyuan/Chest-CAD | /cadx/src/util/Boundary.cpp | UTF-8 | 3,758 | 2.71875 | 3 | [] | no_license |
#include "Boundary.h"
using namespace CADX_SEG;
void Boundary::initialize() {
boundaryList.clear();
imgCols = 0;
imgRows = 0;
minCol = LONG_MAX;
maxCol = LONG_MIN;
minRow = LONG_MAX;
maxRow = LONG_MIN;
}
void Boundary::mapToBoundary(IemTImage<unsigned char>& img) {
boundaryList.clear();
imgCols = img.cols();
imgRows = img.rows();
long colLimit = imgCols - 1;
long rowLimit = imgRows - 1;
for(long r = 0; r <= rowLimit; r++) {
for(long c = 0; c <= colLimit; c++) {
if(img[0][r][c] != 0) {
short isBoundary = 0;
// Region boundary limited by ROI size.
if(r == 0 || c == 0 || r == rowLimit || c == colLimit) {isBoundary = 1;}
// Real region boundary.
else if((img[0][r-1][c] == 0) || (img[0][r+1][c] == 0)
|| (img[0][r][c-1] == 0) || (img[0][r][c+1] == 0)) {
isBoundary = 1;
}
if(isBoundary) {
Point point(c, r);
boundaryList.push_back(point);
}
}
}}
setBoundingBox();
}
void Boundary::setBoundingBox() {
minCol = minRow = LONG_MAX;
maxCol = maxRow = LONG_MIN;
list<Point>::iterator iter;
for(iter = boundaryList.begin(); iter != boundaryList.end(); iter++) {
long col = (*iter).x;
long row = (*iter).y;
if(col < minCol) minCol = col;
if(col > maxCol) maxCol = col;
if(row < minRow) minRow = row;
if(row > maxRow) maxRow = row;
}
}
bool Boundary::isInsideBoundary(long col, long row) {
if(col < minCol || col > maxCol) return false;
if(row < minRow || row > maxRow) return false;
long minC = LONG_MAX, maxC = LONG_MIN;
long minR = LONG_MAX, maxR = LONG_MIN;
list<Point>::iterator iter;
for(iter = boundaryList.begin(); iter != boundaryList.end(); iter++) {
if((*iter).y == row) {
long c = (*iter).x;
if(c < minC) minC = c;
if(c > maxC) maxC = c;
}
if((*iter).x == col) {
long r = (*iter).y;
if(r < minR) minR = r;
if(r > maxR) maxR = r;
}
}
if(col >= minC && col <= maxC && row >= minR && row <= maxR) return true;
return false;
}
bool Boundary::isBoundary(long col, long row) {
if(col < minCol || col > maxCol) return false;
if(row < minRow || row > maxRow) return false;
long minC = LONG_MAX, maxC = LONG_MIN;
long minR = LONG_MAX, maxR = LONG_MIN;
list<Point>::iterator iter;
for(iter = boundaryList.begin(); iter != boundaryList.end(); iter++) {
if((*iter).y == row) {
long c = (*iter).x;
if(c < minC) minC = c;
if(c > maxC) maxC = c;
}
if((*iter).x == col) {
long r = (*iter).y;
if(r < minR) minR = r;
if(r > maxR) maxR = r;
}
}
if(col == minC || col == maxC || row == minR || row == maxR) return true;
return false;
}
void Boundary::removeInnerBoundary() {
list<Point>::iterator iter;
for(iter = boundaryList.begin(); iter != boundaryList.end();) {
long col = (*iter).x;
long row = (*iter).y;
if(!isBoundary(col, row)) boundaryList.erase(iter++);
else ++iter;
}
}
IemTImage<unsigned char> Boundary::boundaryToMap() {
IemTImage<unsigned char> imgBoundary(1, imgRows, imgCols);
imgBoundary = 0;
for(long c = 0; c < imgCols; c++) {
for(long r = 0; r < imgRows; r++) {
if(isInsideBoundary(c, r)) imgBoundary[0][r][c] = 255;
}}
return imgBoundary;
}
IemTImage<unsigned char> Boundary::getBoundaryImage() {
IemTImage<unsigned char> imgBoundary(1, imgRows, imgCols);
imgBoundary = 0;
for(list<Point>::iterator iter = boundaryList.begin(); iter != boundaryList.end(); iter++) {
long col = (*iter).x;
long row = (*iter).y;
imgBoundary[0][row][col] = 255;
}
return imgBoundary;
}
| true |
e8ffe807ff7d352a06de680ead129b90d1430d1b | C++ | WIZARD-CXY/pp | /1035.cpp | UTF-8 | 1,755 | 3.015625 | 3 | [] | no_license | /*************************************************************************
> File Name: 1035.cpp
> Author:
> Mail:
> Created Time: Tue 28 Oct 2014 09:35:34 PM CST
************************************************************************/
#include<iostream>
#include<cstdio>
using namespace std;
#include<vector>
struct record{
string account;
string password;
};
int main(){
freopen("1035.txt","r",stdin);
int n;
cin>>n;
int modifycount=0;
vector<record> modi;
for(int i=0; i<n; i++ ){
string account,password;
cin>>account>>password;
bool modified = false;
for(int j=0; j<password.size(); j++){
if(password[j] == '1'){
password[j] = '@';
modified = 1;
} else if(password[j] == '0'){
password[j] = '%';
modified = 1;
} else if (password[j] == 'O'){
password[j]='o';
modified =1 ;
} else if( password[j] == 'l'){
password[j]='L';
modified =1 ;
} else {
}
}
if(modified){
modifycount++;
record temp;
temp.account = account;
temp.password = password;
modi.push_back(temp);
}
}
if(modifycount == 0){
if(n == 1){
cout<<"There is 1 account and no account is modified"<<endl;
}else{
cout<<"There are "<<n<<" accounts and no account is modified"<<endl;
}
} else {
cout<<modifycount<<endl;
for(int i=0; i<modi.size(); i++){
cout<<modi[i].account<<" "<<modi[i].password<<endl;
}
}
}
| true |
95b2b34fd532336015494e836c6f6a473943e435 | C++ | FakeEngine/FakeMath | /FakeMath/FakeMath/tests/Vec2/Vector2LengthTest.cpp | UTF-8 | 1,153 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | #include "Vector2LengthTest.h"
#include "../../src/Core/Test.h"
namespace FakeVector2Tests
{
int test_length()
{
FakeVec2f v(32.0f, 23.0f);
float expectedLength = 39.4081f; // sqrt(32 * 32 + 23 * 23) -> sqrt(1553) -> 39.40812099047606
FakeTimer timer("FakeVector2Tests::test_length");
float result = v.Length();
timer.Stop();
if (!assert_equal(timer, result, expectedLength))
return -1;
return 0;
}
int test_squared_length()
{
FakeVec2f v(12.0f, 21.4f);
float expectedLength = 601.96f; // 12 * 12 + 21,4 * 21,4 -> 601,96
FakeTimer timer("FakeVector2Tests::test_squared_length");
float result = v.LengthSquared();
timer.Stop();
if (!assert_equal(timer, result, expectedLength))
return -1;
return 0;
}
int test_inverse_length()
{
FakeVec2f v(58.3f, 25.6f);
float expectedLength = 0.0157052f; // 1 / (58,3 * 58,3 + 25,6 * 25,6) -> 1 / (3.398,89 + 655,36) -> 1 / 4.054,25 -> 2,466547450206573e-4
FakeTimer timer("FakeVector2Tests::test_inverse_length");
float result = v.InverseLength();
timer.Stop();
if (!assert_equal(timer, result, expectedLength))
return -1;
return 0;
}
} | true |
ebcda43b1731545c57da79fc189d3cac39445ff1 | C++ | EldelPelo/Ciencias1 | /ArbolArreglo.cpp | UTF-8 | 2,072 | 3.625 | 4 | [] | no_license | //Arbol binario como arreglo
#include <iostream>
using namespace std;
struct Nodo{
int dato;
int izq,der;
};
class ArbolBinOrd{
int tamanio;
Nodo *nodo;
//Metodos
public:
ArbolBinOrd(int);
int getRaiz();
void setRaiz(int);
int nuevo();//Crea un nodo
void libre(int);//Libera una posicion
int agregar(int,int);
void mostrarInorden(int);
void mostrarPreorden(int);
void mostrarPosorden(int);
void mostrarNiveles(int);
int buscar(int);//Retorna posicion elemento;
int contarNodos(int);
int contarHojas(int);
};
ArbolBinOrd::ArbolBinOrd(int tamanio){
int i;
this->tamanio = tamanio;
nodo = new Nodo[tamanio];
nodo[0].izq=-1;
nodo[0].der=1;
for(i=1;i<tamanio-1;i++){
nodo[i].der=i+1;
}
nodo[i].der=-1;
};
int ArbolBinOrd::getRaiz(){
return nodo[0].izq;
}
void ArbolBinOrd::setRaiz(int raiz){
nodo[0].izq=raiz;
}
int ArbolBinOrd::nuevo(){
int k= nodo[0].der;
nodo[0].der=nodo[nodo[0].der].der;
return k;
}
void ArbolBinOrd::libre(int k){
nodo[k].der=nodo[0].der;
nodo[0].der=k;
}
int ArbolBinOrd::agregar(int raiz,int dato){
if(raiz!=-1){
if(nodo[raiz].dato>dato){
nodo[raiz].izq=agregar(nodo[raiz].izq,dato);
}else{
nodo[raiz].der=agregar(nodo[raiz].der,dato);
}
}else{
raiz = nuevo();
nodo[raiz].dato = dato;
nodo[raiz].izq = -1;
nodo[raiz].der = -1;
}
return raiz;
}
void ArbolBinOrd::mostrarInorden(int raiz){
if(raiz!=-1){
mostrarInorden(nodo[raiz].izq);
cout<<nodo[raiz].dato<<" ";
mostrarInorden(nodo[raiz].der);
}
}
char menu(){
char opcion;
cout<<"\n(A)gregar\n";
cout<<"(E)liminar\n";
cout<<"(P)rofundidad\n";
cout<<"(B)uscar\n";
cout<<"(I)norden\n";
cin>>opcion;
return opcion;
}
int main(){
char opcion;
ArbolBinOrd arbol(50);
int raiz;
int elemento;
do{
opcion=menu();
switch(opcion){
case'a':
case'A':
raiz = arbol.getRaiz();
cout<<"\nElemento: ";
cin>>elemento;
arbol.agregar(raiz,elemento);
break;
case'i':
case'I':
raiz = arbol.getRaiz();
arbol.mostrarInorden(raiz);
break;
}
}while(opcion!='s'&&opcion!='S');
}
| true |
0c14a02588d79b72460f77228b4effd43439d705 | C++ | brinkqiang2cpp/douzero_cpp | /cpp/train.cpp | UTF-8 | 16,894 | 2.59375 | 3 | [] | no_license | #include <csignal>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <ctime>
#include <cmath>
#include "data_loop.h"
using std::printf;
namespace fs = std::filesystem;
struct Config {
string xpid = "douzero";
int save_interval = 30;
string objective = "adp";
vector<string> actor_device = {"cuda:0"};
string training_device = "cuda:0";
int num_actors = 5;
bool load_model = false;
bool disable_checkpoint = false;
string savedir = "checkpoints";
long long total_frames = 100000000000;
float exp_epsilon = 0.01;
int batch_size = 32;
int unroll_length = 100;
int num_buffers = 50;
// int num_threads = 4;
float max_grad_norm = 40.;
float learning_rate = 0.0001;
float alpha = 0.99;
float momentum = 0;
float epsilon = 1e-5;
};
void parse_device(const vector<string>& vec, int offset, vector<string>& device) {
device.clear();
int n = vec.size();
for(; offset < n; offset++) {
if(vec[offset] == "cpu") device.push_back("cpu");
else device.push_back("cuda:"+vec[offset]);
}
}
void parse_config(const char* cfg_path, Config& cfg) {
ifstream file(cfg_path, ios::in);
if(!file) {
printf("%s doesn't exist\n", cfg_path);
exit(-1);
}
else {
string line;
while(getline(file, line)) {
if(line.empty() || line[0] == '#' || line[0] == ' ') continue;
vector<string> vec = split(line, " =,");
if(vec.size() < 2) continue;
string& key = vec[0], & val = vec[1];
if(key == "xpid") cfg.xpid = val;
else if(key == "save_interval") cfg.save_interval = stoi(val);
else if(key == "objective") cfg.objective = val;
else if(key == "actor_device") parse_device(vec, 1, cfg.actor_device);
else if(key == "training_device") cfg.training_device = val == "cpu" ? val : "cuda:"+val;
else if(key == "num_actors") cfg.num_actors = stoi(val);
else if(key == "load_model" && val == "true") cfg.load_model = true;
else if(key == "disable_checkpoint" && val == "true") cfg.disable_checkpoint = true;
else if(key == "savedir") cfg.savedir = val;
else if(key == "total_frames") cfg.total_frames = stoll(val);
else if(key == "exp_epsilon") cfg.exp_epsilon = stof(val);
else if(key == "batch_size") cfg.batch_size = stoi(val);
else if(key == "unroll_length") cfg.unroll_length = stoi(val);
else if(key == "num_buffers") cfg.num_buffers = stoi(val);
// else if(key == "num_threads") cfg.num_threads = stoi(val);
else if(key == "max_grad_norm") cfg.max_grad_norm = stof(val);
else if(key == "learning_rate") cfg.learning_rate = stof(val);
else if(key == "alpha") cfg.alpha = stof(val);
else if(key == "momentum") cfg.momentum = stof(val);
else if(key == "epsilon") cfg.epsilon = stof(val);
}
}
file.close();
if(cfg.num_buffers < cfg.batch_size) {
printf("<num_buffers> must be no less than <batch_size>.");
exit(-1);
}
assert(cfg.actor_device.size() && cfg.num_actors > 0 && cfg.total_frames > 0);
}
void print_help(const char *exe) {
printf("%s [config_path]\n", exe);
printf("xpid, default=douzero, type=str\n");
printf("save_interval, default=30, type=int\n");
printf("objective, default=adp, type=str, choices=[adp, wp, logadp]\n");
printf("actor_device, default=0, type=str\n");
printf("training_device, default=0, type=str\n");
printf("gpu_devices, default=0, type=str\n");
printf("num_actors, default=5, type=int\n");
printf("load_model, default=false\n");
printf("disable_checkpoint, default=false\n");
printf("savedir, default=checkpoints\n");
printf("total_frames, default=100000000000, type=int\n");
printf("exp_epsilon, default=0.01, type=float\n");
printf("batch_size, default=32, type=int\n");
printf("unroll_length, default=100, type=int\n");
printf("num_buffers, default=50, type=int\n");
printf("num_threads, default=4, type=int\n");
printf("max_grad_norm, default=40., type=float\n");
printf("learning_rate, default=0.0001, type=float\n");
printf("alpha, default=0.99, type=float\n");
printf("momentum, default=0, type=float\n");
printf("epsilon, default=1e-5, type=float\n");
exit(-1);
}
Context ctx;
deque<deque<Buffer>> buffers;// [num_devices,PLAYER_CNT]
atomic_bool stop_sig = false;
void signal_handle(int signal) {
if(signal == SIGINT || signal == SIGTERM) {
stop_sig.store(true);
ctx.stop();
for (auto& vec : buffers) {
for (auto& buffer : vec) buffer.stop();
}
}
}
template<class T, uint16_t N>
class DataStreamMean {// 数据流中最近N个数的均值
public:
T add(T val) {
if (n >= N) out = nums[i];
else out = 0, n++;
nums[i] = val;
sum += (val - out);
if ((++i) == N) i = 0;
return sum / n;
}
private:
uint16_t i = 0, n = 0;
T nums[N] = { 0 };
T sum = 0, out = 0;
};
void update_model(LstmModel& model, uint16_t p, vector<vector<ModelLocker>>& mlockers) {
StateDict params = model->named_parameters(true);
StateDict buffers = model->named_buffers(true);
uint16_t m = mlockers.size(), n = mlockers[0].size();
for (uint16_t i = 0; i < m; i++) {
for (uint16_t j = 0; j < n; j++) mlockers[i][j].update(p, params, buffers);
}
}
class TrainLoop : public ThreadLoop {
public:
TrainLoop(uint16_t player, atomic_llong& frame, float* stat, DataStreamMean<float, 100>& mean_episode_return, mutex& lock, Config& cfg,
LstmModel& model, torch::optim::RMSprop& optim, Buffer& buffer, vector<vector<ModelLocker>>& mlockers) :
player(player), frame(frame), stat(stat), mean_episode_return(mean_episode_return), lock(lock), cfg(cfg),
model(model), optim(optim), device(c10::Device(cfg.training_device)), buffer(buffer), mlockers(mlockers) {}
virtual void loop() {
//uint16_t n = mlockers.size();
while (run && frame < cfg.total_frames) {
vector<vector<at::Tensor>> batchs(FIELDS);
vector<at::Tensor>& done = batchs[0];
while (run && done.size() < cfg.batch_size) {
vector<at::Tensor> temp = buffer.pop();
if (temp.size() == FIELDS) {
for (uint16_t i = 0; i < FIELDS; i++) batchs[i].push_back(temp[i]);
}
}
if (!run) break;
vector<at::Tensor> cat_batch;
for (uint16_t i = 0; i < FIELDS; i++)
cat_batch.push_back(torch::cat(batchs[i]).to(device));
at::Tensor x = torch::cat({ cat_batch[3],cat_batch[4] }, 1).to(torch::kF32);
at::Tensor z = cat_batch[5].to(torch::kF32);
float episode_return = cat_batch[1].index({ cat_batch[0] }).mean().item<float>();
try {
lock_guard<mutex> lk(lock);
at::Tensor out = model->forward(z, x);
at::Tensor loss = (out.flatten() - cat_batch[2]).square().mean();
stat[0] = loss.item<float>();
if (!isnan(episode_return)) {
stat[1] = mean_episode_return.add(episode_return);
}
optim.zero_grad();
loss.backward();
torch::nn::utils::clip_grad_norm_(model->parameters(), cfg.max_grad_norm);
optim.step();
//for (uint16_t i = 0; i < n; i++) mlockers[i]->update(model);
update_model(model, player, mlockers);
frame.fetch_add(x.size(0));
} catch (exception& e) {
cout << e.what() << endl;
}
}
}
private:
uint16_t player;
atomic_llong& frame;
float* stat;
mutex& lock;
Config& cfg;
LstmModel& model;
c10::Device device;
torch::optim::RMSprop& optim;
Buffer& buffer;
vector<vector<ModelLocker>>& mlockers;
DataStreamMean<float, 100>& mean_episode_return;
};
void write_log(ofstream& log, double t0, double t1, atomic_llong frames[PLAYER_CNT], at::Tensor& frame0, at::Tensor& frame1, float stats[PLAYER_CNT][2]) {
static char str[300] = "";
at::Tensor avg = (frame1 - frame0) / (t1 - t0);
long long f0 = frames[0], f1 = frames[1], f2 = frames[2];
float* avg_f = avg.data_ptr<float>();
time_t now = time(0);
tm* local = localtime(&now);
int n = sprintf(str, "[%d/%02d/%02d %02d:%02d:%02d]", local->tm_year+1900, local->tm_mon+1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);
n += sprintf(str+n, "loss: L:%.6f D:%.6f U:%.6f mean_episode_return: L:%.6f D:%.6f U:%.6f frame: L:%lld D:%lld U:%lld avg: L:%.2f D:%.2f U:%.2f\n",
stats[0][0], stats[1][0], stats[2][0], stats[0][1], stats[1][1], stats[2][1], f0, f1, f2, avg_f[0], avg_f[1], avg_f[2]);
log.write(str, n);
log.flush();
cout << str;
}
void checkpoint(string& dir, vector<LstmModel>& models, vector<torch::optim::RMSprop>& optims, mutex locks[PLAYER_CNT], at::Tensor& stats, atomic_llong frames[PLAYER_CNT], at::Tensor& frames_tensor) {
torch::serialize::OutputArchive archive;
for (uint16_t p = 0; p < PLAYER_CNT; p++) locks[p].lock();
for (uint16_t p = 0; p < PLAYER_CNT; p++) {
auto params = models[p]->named_parameters(true);
auto buffers = models[p]->named_buffers(true);
string prefix = to_string(p) + '_';
for (auto& val : params) archive.write(prefix + val.key(), val.value());
for (auto& val : buffers) archive.write(prefix + val.key(), val.value(), true);
torch::save(models[p], dir + "cppmodel_" + prefix + to_string(frames[p]) + ".pt");
torch::save(optims[p], dir + prefix + "optim.tar");
}
archive.write("stats", stats, true);
archive.write("frames", frames_tensor, true);
for (uint16_t p = 0; p < PLAYER_CNT; p++) locks[p].unlock();
string checkpoint_path = dir + "model.tar";
archive.save_to(checkpoint_path);
cout << "Saving checkpoint to " << checkpoint_path << endl;
}
bool keep_run(atomic_llong frames[PLAYER_CNT], long long total_frames) {
for (uint16_t p = 0; p < PLAYER_CNT; p++)
if (frames[p] < total_frames) return true;
return false;
}
int main(int argc, const char* argv[]) {
if(argc > 2) print_help(argv[0]);
try {
std::signal(SIGINT, signal_handle);
std::signal(SIGTERM, signal_handle);
Config cfg;
if(argc == 2) parse_config(argv[1], cfg);
torch::manual_seed(time(0));
// 训练线程模型
vector<LstmModel> train_model;
torch::optim::RMSpropOptions rms_options(cfg.learning_rate);
rms_options.alpha(cfg.alpha);
rms_options.momentum(cfg.momentum);
rms_options.eps(cfg.epsilon);
vector<torch::optim::RMSprop> optims;
mutex locks[PLAYER_CNT];
c10::Device training_device(c10::Device(cfg.training_device));
int lstm_input = 162, lstm_hidden = 128;
int dim[PLAYER_CNT] = {373, 484, 484};
for (uint16_t p = 0; p < PLAYER_CNT; p++) {
train_model.emplace_back(lstm_input, lstm_hidden, dim[p] + lstm_hidden);
train_model[p]->to(training_device);
// train_model[p]->train();
optims.emplace_back(train_model[p]->parameters(), rms_options);
}
// 记录训练状态
atomic_llong frames[PLAYER_CNT] = { 0,0,0 };
float stats[PLAYER_CNT][2] = { {0.0,0.0},{0.0,0.0},{0.0,0.0} };// loss,mean_episode_return
string checkpoint_dir = cfg.savedir + '/' + cfg.xpid + '/';
if (!fs::exists(checkpoint_dir)) fs::create_directories(checkpoint_dir);
string checkpoint_path = checkpoint_dir + "model.tar";
at::Tensor stats_tensor = torch::from_blob(stats, { PLAYER_CNT,2 }, torch::kF32);
at::Tensor frames_tensor = torch::from_blob(frames, { PLAYER_CNT }, torch::kLong);
vector<DataStreamMean<float, 100>> mean_episode_returns(PLAYER_CNT);
if (cfg.load_model && fs::exists(checkpoint_path)) {// 载入训练状态
torch::serialize::InputArchive archive;
archive.load_from(checkpoint_path, training_device);
for (uint16_t p = 0; p < PLAYER_CNT; p++) {
auto params = train_model[p]->named_parameters(true);
auto buffers = train_model[p]->named_buffers(true);
string prefix = to_string(p) + '_';
for (auto& val : params) archive.read(prefix + val.key(), val.value());
for (auto& val : buffers) archive.read(prefix + val.key(), val.value(), true);
torch::serialize::InputArchive optim_archive;
optim_archive.load_from(checkpoint_dir + prefix + "optim.tar", training_device);
optims[p].load(optim_archive);
}
at::Tensor temp1, temp2;
archive.read("stats", temp1, true);
stats_tensor.copy_(temp1);
cout << stats_tensor << endl;
archive.read("frames", temp2, true);
frames_tensor.copy_(temp2);
cout << frames_tensor << endl;
for (uint16_t p = 0; p < PLAYER_CNT; p++) mean_episode_returns[p].add(stats[p][1]);
cout << "Load checkpoint " << checkpoint_path << endl;
}
for (uint16_t p = 0; p < PLAYER_CNT; p++) train_model[p]->train();
// 模拟线程模型
int n = cfg.actor_device.size();// gpu/cpu设备数量
buffers.resize(n);
vector<vector<vector<LstmModel>>> models(n, vector<vector<LstmModel>>(cfg.num_actors));
vector<vector<ModelLocker>> mlockers(n);
for (uint16_t i = 0; i < n; i++) {
c10::Device device = c10::Device(cfg.actor_device[i]);
for (uint16_t p = 0; p < PLAYER_CNT; p++)
buffers[i].emplace_back(cfg.num_buffers);
for (uint16_t j = 0; j < cfg.num_actors; j++) {
vector<LstmModel>& models_i_j = models[i][j];
for (uint16_t p = 0; p < PLAYER_CNT; p++) {
models_i_j.emplace_back(lstm_input, lstm_hidden, dim[p] + lstm_hidden);
models_i_j[p]->to(device);
models_i_j[p]->train(false);
}
mlockers[i].emplace_back(models_i_j);
}
}
// 复制模型参数
for (uint16_t p = 0; p < PLAYER_CNT; p++) update_model(train_model[p], p, mlockers);
// 创建线程
uint16_t player = 0, T = cfg.unroll_length;
double epsilon = cfg.exp_epsilon;
string& objective = cfg.objective;
for (uint16_t i = 0; i < n; i++) {
for (uint16_t j = 0; j < cfg.num_actors; j++) {
shared_ptr<ThreadLoop> loop = make_shared<DataLoop>(player, T, epsilon, objective, cfg.actor_device[i],
mlockers[i][j], buffers[i]);
ctx.push(loop);
player = next_player(player);
}
for (uint16_t p = 0; p < PLAYER_CNT; p++) {
shared_ptr<ThreadLoop> loop = make_shared<TrainLoop>(p, frames[p], stats[p], mean_episode_returns[p], locks[p], cfg, train_model[p],
optims[p], buffers[i][p], mlockers);
ctx.push(loop);
}
}
Timer timer;
ofstream log_file(checkpoint_dir + "train_log.txt", ios::app);
log_file << "time loss mean_episode_return frame avg_speed\n";
double t0 = timer.duration(), t1, last_save, interval = cfg.save_interval * 60.0;
at::Tensor frame0 = frames_tensor.clone();
last_save = t0;
ctx.start();
long long total_frames = cfg.total_frames;
while (!stop_sig && keep_run(frames, total_frames)) {
this_thread::sleep_for(5s);
t1 = timer.duration();
write_log(log_file, t0, t1, frames, frame0, frames_tensor, stats);
if (t1 - last_save >= interval) {
if(!cfg.disable_checkpoint)
checkpoint(checkpoint_dir, train_model, optims, locks, stats_tensor, frames, frames_tensor);
last_save = t1;
}
}
ctx.join();
write_log(log_file, t0, timer.duration(), frames, frame0, frames_tensor, stats);
log_file << endl;
log_file.close();
if(!cfg.disable_checkpoint)
checkpoint(checkpoint_dir, train_model, optims, locks, stats_tensor, frames, frames_tensor);
exit(0);
} catch(exception& e) {
printf("%s\n", e.what());
exit(-1);
}
} | true |
4e4306c316a43120d4fb1595d7848530fcfd801a | C++ | harskish/Doodle | /src/Optimizer.h | UTF-8 | 684 | 2.765625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <fstream>
#include "SDL.h"
#include "Utils.h"
/*
Base class for an optimization algorithm
*/
class Optimizer
{
public:
Optimizer(SDL_Surface const *reference);
~Optimizer();
// Run optimizer for one iteration
virtual bool step() = 0;
// Poll (and eventually show) current progress
SDL_Surface* getCurrentBest() { return currentBest; }
// Write to stdout and progress file (csv)
virtual void writeProgress() = 0;
virtual void writeParameters() = 0;
protected:
SDL_Surface* currentBest;
double bestSeenFitness;
SDL_Surface const* target; // target of optimization
std::ofstream progressStream;
};
| true |
a6e36689e20e3060fd2d58c210ca9db3bf85a104 | C++ | darkhader/LTU15 | /20201/data-structure-and-algorithm/fibo.cpp | UTF-8 | 247 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int fibo(int n)
{
if (n == 1 || n == 2)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
for (int i = 1; i < 10; i++)
{
int fi = fibo(i);
printf("%d ", fi);
}
} | true |
8493401d31f72b603f67f89902bdc109aef44405 | C++ | markus456/peliohjelmointi | /defenceSolution/defence/Bullet.h | UTF-8 | 514 | 2.75 | 3 | [] | no_license | #ifndef BULLET_H
#define BULLET_H
#include "SDL.h"
#include "Sprite.h"
class Bullet : public Sprite {
private:
double dir, speed;
unsigned int damage;
public:
Bullet(void);
~Bullet(void);
virtual void draw(SDL_Renderer* rndr);
virtual void update();
void setDirection(double direction, double speed);
void dirTo(Location point, double speed);
void setStartLocation(Location point);
void setSpeed(double speed);
unsigned int getDamage();
void setDamage(unsigned int);
};
#endif | true |
033a197cdfb24cadc3d60dea2a69b988e3b47271 | C++ | PawelAdamczuk/pooker | /utils.h | UTF-8 | 821 | 3.09375 | 3 | [] | no_license | //
// Created by Janusz Grzesik on 01.02.2017.
//
#ifndef POOKER_CONSTANTS_H
#define POOKER_CONSTANTS_H
#include <vector>
using namespace std;
enum RoundPhase {
preflop = 0, flop, turn, river
};
template<class T>
class CyclicIterator{
private:
vector<T> *vec;
typename vector<T>::iterator it;
public:
CyclicIterator(vector<T> *vec) : vec(vec) {
this->it = vec->begin();
}
CyclicIterator& operator++() {
it++;
if (isEnd()) {
it = vec->begin();
}
return *this;
}
CyclicIterator& operator--() {
it++;
if (isEnd()) {
it = vec->begin();
}
return *this;
}
bool isEnd() {
return it == vec->end();
}
T &operator*() {
return *it;
}
};
#endif //POOKER_CONSTANTS_H
| true |
6d5eebfb54081cd7f78ea9ddc163bc34d0f24a64 | C++ | pavluntiy/Third-Attempt | /data.cpp | UTF-8 | 3,653 | 2.953125 | 3 | [] | no_license | #include "data.hpp"
Data::Data(istream &in):
in(in)
{
//wasEof = false;
ready = false;
currentPosition = -1;
previousPosition.push(0);
currentChar = '\n';
badCharacters = "";
errorOccured = false;
}
bool Data::wasError(){
return this->errorOccured;
}
string Data::getErrorReport(){
this->errorOccured = false;
string tmp = this->badCharacters;
this->badCharacters = "";
return tmp;
}
char Data::pop(){
if(str.size() == 0){
return '\0';
}
char tmp = '\0';
sourcePosition.linePosition++;
tmp = *(end(str) - 1);
this->str.pop_back();
return tmp;
}
void Data::push(char c){
this->str.push_back(c);
}
void Data::recover (){
while(!eof() && !Alphabet::is<Alphabet::NEWLINE>(this->currentChar)){
badCharacters += currentChar;
consume();
}
}
int Data::getSize(){
return this->str.size();
}
bool Data::eof(){
return this->in.eof() && currentPosition >= static_cast<int>(str.size()) - 1;
}
Position Data::getSourcePosition(){
return this->sourcePosition;
}
int Data::getPosition (){
return this->currentPosition;
}
char Data::charAt(int index){
if(eof() && index >= static_cast<int>(this->str.size())){
throw DataException("Invalid index of input");
}
if(index >= static_cast<int>(this->str.size())){
while (!eof() && index >= static_cast<int>(this->str.size())) {
// cout << "!!!";
char c = static_cast<char>(in.get());
this->push(c);
// cout << c;
}
}
return str[index];
}
char Data::operator [] (int index){
return this->charAt(index);
}
void Data::consume(int n){
for(int i = 0; i < n; ++i){
consume();
}
}
void Data::consumeNewlineTabs(){
}
void Data::makeReady(){
this->ready = true;
myIgnore(this->charAt(currentPosition + 1));
}
void Data::pushCharToStream(char c){
this->push(c);
}
void Data::isReady(){
if(eof()){
throw DataException("Stream is closed!");
return;
}
if(!ready){
makeReady();
}
return;
}
void Data::lock(){
this->previousSourcePosition.push(sourcePosition);
this->previousPosition.push(currentPosition);
}
void Data::restore(){
if(this->previousPosition.size() > 0){
this->currentPosition = this->previousPosition.top();
this->previousPosition.pop();
}
else{
this->currentPosition = 0;
}
this->currentChar = this->charAt(currentPosition);
}
Position Data::getPreviousSourcePosition(){
if(this->previousSourcePosition.size() == 0){
return Position();
}
return this->previousSourcePosition.top();
}
string Data::dataDump(){
return this->str;
}
void Data::consume(){
if (Alphabet::is<Alphabet::NEWLINE>(currentChar)){
sourcePosition.line ++;
sourcePosition.linePosition = 0;
}
else {
sourcePosition.linePosition++;
}
if (eof()){
throw DataException("Unexpected end of file on " + sourcePosition.toString() + "\n");
}
currentPosition++;
if (eof()){
currentChar = EOF;
}
else {
currentChar = this->charAt(currentPosition);
}
}
bool Data::get(std::string text){
for (int i = 0; i < (int) text.size(); i++){
if (text[i] != this->charAt(currentPosition + i)){
return false;
}
}
for (int i = 0; i < (int) text.size(); i++){
consume();
}
return true;
}
bool Data::get(char c){
if(currentChar == c){
consume();
return true;
}
return false;
}
bool Data::find(char c){
if(currentChar == c){
return true;
}
return false;
}
bool Data::find(std::string text){
for (int i = 0; i < (int) text.size(); i++){
if (text[i] != this->charAt(currentPosition + i)){
return false;
}
}
return true;
}
| true |
95a66710c490258930afe74ad1c324ec07238510 | C++ | Merci24Dec/unitech_cpp_with_oops-course | /programs_AtoZ/Bubble Sort/Array_after_Each_Sort.cpp | UTF-8 | 601 | 3.515625 | 4 | [
"Unlicense"
] | permissive | // Print Array after Each Sort
#include<iostream>
using namespace std;
int main()
{
int i, arr[10], j, temp;
cout<<"Enter 10 Elements: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<endl;
for(i=0; i<9; i++)
{
for(j=0; j<(10-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
cout<<"Step "<<i+1<<": ";
for(j=0; j<10; j++)
cout<<arr[j]<<" ";
cout<<endl;
}
cout<<endl;
return 0;
}
| true |
13e34e3f95fe65fd61ca1768f3623b2e3b5bc430 | C++ | octopus0110/Products | /calculator.cpp | UTF-8 | 11,057 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#define REP(i, n) for (int i = 0; i < (int)(n); ++i)
#define REP2(i, m, n) for (int i = (m); i < (int)(n); ++i)
#define REPR(i, n) for (int i = (n)-1; i >= 0; --i)
#define REPR2(i, m, n) for (int i = (n)-1; i >= (m); --i)
#define REPx(x, a) for(auto x : a)
#define ALL(a) a.begin(), a.end()
#define REVERSE(a) reverse(ALL(a))
#define ENDL cout << endl;
using namespace std;
using ULL = unsigned long long;
using VI = vector<int>;
using VS = vector<string>;
// 文字列を利用した整数の四則演算、累乗、階乗、素数判定、素因数分解
string hm(string a, string b);
string hp(string a, string b);
clock_t st, en;
// 2数の引き算
string hm(string a, string b)
{
bool fa = false, fb = false;
if (a[0] == '-')
{
fa = true;
a.erase(a.begin());
}
if (b[0] == '-')
{
fb = true;
b.erase(b.begin());
}
if (!fa && fb) return hp(a, b);
else if (fa && !fb)
{
string res = hp(a, b);
return "-" + res;
}
else if (fa && fb) swap(a, b);
short int len_a = a.size(), len_b = b.size();
bool flg = false;
if (len_a < len_b)
{
flg = true;
swap(a, b);
swap(len_a, len_b);
}
else if (len_a == len_b)
{
REP(i, len_a)
{
if (a[i] < b[i])
{
flg = true;
swap(a, b);
swap(len_a, len_b);
break;
}
else if (a[i] > b[i]) break;
}
}
string res = "";
REP(i, len_a)
{
char ai = a[len_a-i-1];
if (i < len_b)
{
char bi = b[len_b-i-1];
if (ai >= bi) res = to_string(ai-bi) + res;
else
{
res = to_string(10-(bi-'0')+(ai-'0')) + res;
bool con = true;
short int idx = len_a-i-2;
while(con && idx >= 0)
{
if(a[idx] != '0')
{
a[idx] = a[idx] - 1;
con = false;
}
else a[idx] = '9';
idx--;
}
}
}
else res = ai + res;
}
REVERSE(res);
REPR2(i, 1, res.size())
{
if (res[i]-'0') break;
else res.pop_back();
}
REVERSE(res);
if (flg) res = "-" + res;
return res;
}
// 2数の足し算
string hp(string a, string b)
{
bool fa = false, fb = false, flg = false;
if (a[0] == '-')
{
fa = true;
a.erase(a.begin());
}
if (b[0] == '-')
{
fb = true;
b.erase(b.begin());
}
if (!fa && fb) return hm(a, b);
else if (fa && !fb)
{
swap(a, b);
return hm(a, b);
}
else if (fa && fb) flg = true;
short int len_a = a.size(), len_b = b.size();
string res = "";
short int rr = 0;
REP(i, max(len_a, len_b))
{
short int aa = 0, bb = 0, ss;
char ai = a[len_a-i-1], bi = b[len_b-i-1];
if (i < len_a) aa = ai - '0';
if (i < len_b) bb = bi - '0';
ss = aa + bb + rr;
string ad = to_string(ss % 10);
rr = (ss - ss % 10) / 10;
res = ad + res;
}
if (rr) res = to_string(rr) + res;
if (flg) res = '-' + res;
return res;
}
// aに10^digを掛けた数を計算する
string zero;
string tc(int dig, string a)
{
if (a == "0") return "0";
a += zero.substr(0, dig);
return a;
}
// 一桁の数(a)と複数桁の数(b)との掛け算
string mc(char a, string b)
{
if (a == '0' || b == "0") return "0";
string res = "0";
REP(i, b.size()) res = hp(res, tc(i, to_string((a-'0')*(b[b.size()-i-1]-'0'))));
return res;
}
// 2数の掛け算
string hc(string a, string b)
{
if (a == "0" || b == "0") return "0";
bool fa = false, fb = false;
if (a[0] == '-')
{
fa = true;
a.erase(a.begin());
}
if (b[0] == '-')
{
fb = true;
b.erase(b.begin());
}
string res = "0";
REP(i, a.size()) res = hp(res, tc(i, mc(a[a.size()-i-1], b)));
if ((fa && !fb) || (!fa && fb)) res = "-" + res;
return res;
}
// m^eを計算する
string ex(string m, string e)
{
bool flg = false;
if(m[0] == '-')
{
m.erase(m.begin());
flg = true;
}
if (e == "0") return "1";
string a = "1";
if (stoi(e) % 2) a = m;
string b = ex(m, to_string(stoi(e)/2));
string res = hc(a, hc(b, b));
if (flg) res = "-" + res;
return res;
}
// 2数の割り算(商と余りを計算する)
string hd(string& a, string b)
{
if (b == "0")
{
cout << endl << "Calculation error" << endl;
exit(0);
}
string res = "", tmp;
int roop = a.size();
REPR(i, roop)
{
REPR(j, 10)
{
tmp = hm(a, hc(b, hc(to_string(j), ex("10", to_string(i)))));
if (tmp[0] != '-')
{
if (res != "") res += to_string(j);
else if (j != 0) res += to_string(j);
a = tmp;
break;
}
}
}
if (res == "") res = "0";
return res;
}
// 素数判定。整数型で扱える場合はこちらで計算する。
bool primarity_testi(ULL a, bool output=false)
{
if (a < 2) return false;
else if (a == 2) return true;
else if (a % 2 == 0)
{
if (output) cout << "2 を素因数にもちます" << endl;
return false;
}
for (ULL i = 3; i*i <= a; i += 2)
{
if (a % i == 0)
{
if (output) cout << i << " を素因数にもちます" << endl;
return false;
}
}
return true;
}
// 素数判定。64bitを超えても時間が無限にあるならこちらで計算できる。とんでもなく遅い上に、1e8までの素因数しか使えないので精度も低い。
short int primarity_test(string n, bool output=false)
{
const clock_t TIME_LIMIT = 60;
string rem = n;
hd(rem, "2");
if (hm(n, "2")[0] == '-') return 0;
else if (n == "2") return 1;
else if (rem == "0")
{
if (output) cout << "2 を素因数にもちます" << endl;
return 0;
}
st = clock();
for(int i = 3;i < 1e8; i += 2)
{
en = clock();
if ((double)(en-st)/CLOCKS_PER_SEC >= TIME_LIMIT)
{
if (output) cout << "計算時間が " << TIME_LIMIT << "s を超えました.少なくとも " << i-2 << " までの素因数は存在しません." << endl;
return -1;
}
if (!primarity_testi(i)) continue;
string p = to_string(i);
if (hm(n, p)[0] == '-') return 1;
rem = n;
hd(rem, p);
if (rem == "0")
{
if (output) cout << p << " を素因数にもちます" << endl;
return 0;
}
}
return 2;
}
// 素因数分解
void prime_factorize(ULL n, vector<pair<ULL, ULL>> &res)
{
for (ULL s = 2; n >= s * s; s += 2)
{
ULL e = 0;
if (n % s == 0)
{
while(n % s == 0)
{
n /= s;
e++;
}
res.emplace_back(s, e);
}
if (s == 2) s--;
}
if (n != 1) res.emplace_back(n, 1);
}
// 階乗
string factorial(string n)
{
bool flg = false;
if (n[0] == '-')
{
flg = true;
n.erase(n.begin());
}
string res = "1";
REP2(i, 2, stoi(n)+1) res = hc(res, to_string(i));
if (flg) res = "-" + res;
return res;
}
// 階乗の素因数分解
vector<pair<ULL, ULL>> A;
void pff(ULL N)
{
for(ULL i = 1; i < N+1; i++)
{
vector<pair<ULL, ULL>> result;
prime_factorize(i, result);
REP(i, result.size())
{
bool flg = false;
REP(j, A.size())
{
if (result[i].first == A[j].first)
{
A[j].second += result[i].second;
flg = true;
break;
}
}
if (!flg) A.emplace_back(result[i]);
}
}
}
////////////////////////////////////////////////////////////////////////////
// main
int main()
{
ifstream fin("zero.txt");
if (!fin)
{
cout << "'zero.txt' does not exist" << endl;
return -1;
}
getline(fin, zero);
string s;
short int flg = 0;
cin >> s;
// 数字の末尾がpなら素数判定をする
if (s.back() == 'p')
{
ENDL
s.pop_back();
if (hm("18446744073709551615", s)[0] == '-')
{
cout << "ullを超えました" << endl;
flg = primarity_test(s, true);
}
else flg = primarity_testi(stoull(s), true);
if (flg == 1) cout << "素数です" << endl;
else if (flg == 0) cout << "素数ではありません" << endl;
else if (flg == 2) cout << "少なくとも1e8までの素因数は存在しません" << endl;
else cout << "TLE" << endl;
return 0;
}
// 数字の末尾がfなら素因数分解をする
else if(s.back() == 'f')
{
ENDL
s.pop_back();
if(s.back() == '!') // 階乗の素因数分解
{
s.pop_back();
pff(stoull(s));
cout << "= ";
REP(i, (int)A.size())
{
cout << A[i].first;
if (A[i].second != 1) cout << "^" << A[i].second;
if (i < (int)A.size()-1) cout << "*";
if (i == (int)A.size() - 1) ENDL
}
return 0;
}
if (hm("18446744073709551615", s)[0] == '-')
{
cout << "ullを超えました" << endl;
return 0;
}
vector<pair<ULL, ULL>> res;
prime_factorize(stoull(s), res);
if (res.size() == 1 && res[0].second == 1) cout << "素数です" << endl;
else
{
REP(i, (int)res.size())
{
if (i == 0) cout << "= ";
cout << res[i].first;
if (res[i].second != 1) cout << "^" << res[i].second;
if(i < (int)res.size()-1) cout << "*";
if (i == (int)res.size() - 1) ENDL
}
}
return 0;
}
string num = "", num2;
VI symn(100, -1);
VS syms(100, "0");
int idx = 0, ct = 0;
bool exp = false;
REPx(x, s)
{
if ((x == '*' || x == '+' || x == '-' || x == '/') && exp)
{
num = ex(num2, num);
exp = false;
}
else if (x == '^' && exp)
{
cout << "^ は続けて入力できません" << endl;
return 0;
}
else if (x == '!')
{
num = factorial(num);
continue;
}
if (x != '*' && x != '+' && x != '-' && x != '^' && x != '/') num += x;
else if (x == '*')
{
syms[idx] = num;
symn[ct] = idx;
num = "";
idx++;
ct++;
}
else if (x == '+')
{
syms[idx] = num;
num = "";
idx++;
}
else if (x == '-')
{
if (num == "") num += "-";
else
{
syms[idx] = num;
num = "-";
idx++;
}
}
else if (x == '^')
{
num2 = num;
num = "";
exp = true;
}
else if (x == '/')
{
syms[idx] = num;
num = "";
idx++;
flg = true;
}
}
if (exp) syms[idx] = ex(num2, num);
else syms[idx] = num;
if (flg) // 割り算
{
if (hm("18446744073709551615", syms[0])[0] == '-')
{
cout << "ullを超えました" << endl;
string quo = hd(syms[0], syms[1]);
cout << endl << "= " << quo << endl;
if (syms[0] != "0") cout << "... " << syms[0] << endl;
}
else
{
if (syms[1] == "0")
{
cout << endl << "Calculation Error" << endl;
return 0;
}
cout << endl << "= " << stoull(syms[0]) / stoull(syms[1]) << endl;
ULL rem = stoull(syms[0]) % stoull(syms[1]);
if (rem) cout << "... " << rem << endl;
}
return 0;
}
REPx(x, symn)
{
if (x == -1) break;
syms[x+1] = hc(syms[x], syms[x+1]);
syms[x] = "0";
}
string res = "0";
REPx(x, syms) res = hp(res, x);
cout << endl << "= " << res << endl;
return 0;
} | true |
c2306d650f1b31753fa157a84fcc169b024033d6 | C++ | lx999/Plurinote | /relations/bidirectionalrelationship.h | UTF-8 | 2,403 | 3.09375 | 3 | [] | no_license | #ifndef BIDIRECTIONALRELATION_H
#define BIDIRECTIONALRELATION_H
#include <QString>
#include "relationship.h"
#include "relationsmanager.h"
#include "association.h"
template<typename T> class Relationship;
template<typename T> class Association;
template<typename T>
class BidirectionalRelationship : public Relationship<T>
{
template<typename> friend class RelationsManager;
BidirectionalRelationship(const QString& title) : Relationship<T>(title){}
virtual Association<T>* getAssociation(const T& ref1, const T& ref2);
virtual const Association<T>* getConstAssociation(const T& ref1, const T& ref2) const;
virtual QVector<const Association<T>*>* getChildren(const T& ref) const;
virtual QVector<const Association<T>*>* getParents(const T& ref) const;
public:
};
template<typename T>
Association<T>* BidirectionalRelationship<T>::getAssociation(const T& ref1, const T& ref2) {
Association<T>** i;
for(i = this->associations.begin(); i != this->associations.end(); i++){
if(((*i)->getRelatedFrom() == ref1 && (*i)->getRelatedTo() == ref2) || ((*i)->getRelatedFrom() == ref2 && (*i)->getRelatedTo() == ref1)){
return *i;
}
}
return nullptr;
}
template <typename T>
const Association<T>* BidirectionalRelationship<T>::getConstAssociation(const T& ref1, const T& ref2) const {
Association<T>* const * i;
for(i = this->associations.constBegin(); i != this->associations.constEnd(); i++){
if(((*i)->getRelatedFrom() == ref1 && (*i)->getRelatedTo() == ref2) || ((*i)->getRelatedFrom() == ref2 && (*i)->getRelatedTo() == ref1)){
return *i;
}
}
return nullptr;
}
template <typename T>
QVector<const Association<T>*>* BidirectionalRelationship<T>::getChildren(const T& ref) const{
QVector<const Association<T>*>* children = new QVector<const Association<T>*>;
for(typename QVector<Association<T>*>::const_iterator t = this->associations.constBegin(); t != this->associations.constEnd(); t++){
if((*t)->getRelatedFrom() == ref){
children->push_back(*t);
}else if((*t)->getRelatedTo() == ref){
children->push_back(*t);
}
}
return children;
}
template <typename T>
QVector<const Association<T>*>* BidirectionalRelationship<T>::getParents(const T& ref) const{
return getChildren(ref);
}
#endif // BIDIRECTIONALRELATION_H
| true |
dcdab1a13cd6304f2eb43303d7ba25c9cd210dea | C++ | bonventre/BTrk | /BTrk/Dch/DchGeomBase/include/DchCellAddr.hh | UTF-8 | 1,646 | 2.5625 | 3 | [] | no_license | #ifndef DCHCELLADDR_HH
#define DCHCELLADDR_HH
//--------------------------------------------------------------------------
//
// Environment:
// This software was developed for the BaBar collaboration. If you
// use all or part of it, please give an appropriate acknowledgement.
//
// Copyright Information:
// Copyright (C) 1999 <INFN>
//
//------------------------------------------------------------------------
// ---------------------
// -- Class Interface --
// ---------------------
/**
* C++ source file code DchCellAddr.
* This class is only a container for three static functions to map a Dch
* cell address to its layer/wire numbers. Needed to break some circular
* dependency within the Dch code
*
* This software was developed for the BaBar collaboration. If you
* use all or part of it, please give an appropriate acknowledgement.
*
* Copyright (C) 1999 [INFN & Padova University]
*
* @see DchCellAddrDchCellAddr
*
* @version $Id: DchCellAddr.hh 92 2010-01-14 12:38:30Z stroili $
*
* @author (R. Stroili) (originator);
*
*/
class DchCellAddr {
//--------------------
// Instance Members --
//--------------------
public:
// Constructors
DchCellAddr( void );
// Destructor
virtual ~DchCellAddr( ) {;}
// Operators
//------------------
// Static Members --
//------------------
public:
// Selectors (const)
static int wireIs(const int &cell) { return cell%1000; }
static int layerIs(const int &cell) { return cell/1000; }
static int cellIs(const int &wire, const int &layer) { return
layer*1000+wire; }
};
#endif // DCHCELLADDR_HH
| true |
9063ee2701e66e574bbb1a656f0bdb15a8c1bfd0 | C++ | team-compilers/compilers | /homework1/inc/Expression.h | UTF-8 | 2,066 | 2.96875 | 3 | [
"MIT"
] | permissive | // Author: Alexey Zhuravlev
// Description: Expression Interface and it's implementations
#pragma once
#include <Visitor.h>
#include <VisitorTarget.h>
#include <string>
class IExpression : public IVisitorTarget {
};
//-----------------------------------------------------------------------------------------------//
enum class TOperandType : char {
OT_Plus,
OT_Minus,
OT_Times,
OT_Div,
OT_Count
};
struct CBinaryExpression: public IExpression {
TOperandType Operation;
IExpression* LeftOperand;
IExpression* RightOperand;
void Accept( IVisitor* visitor ) override { visitor->Visit( this ); }
};
//-----------------------------------------------------------------------------------------------//
struct CNumberExpression : public IExpression {
int Value;
void Accept( IVisitor* visitor ) override { visitor->Visit( this ); }
};
//----------------------------------------------------------------------------------------------//
// Expression for identities (variables)
struct CIdExpression : public IExpression {
std::string Name; // name of the variable
void Accept( IVisitor* visitor ) override { visitor->Visit( this ); }
};
//-----------------------------------------------------------------------------------------------//
// Interface for list expressions
class IListExpression : public IExpression {
};
//-----------------------------------------------------------------------------------------------//
// Expression for list of more than two elements
struct CPairListExpression : public IListExpression {
IExpression* Head; // First element of the list
IListExpression* Tail; // All other elements
void Accept( IVisitor* visitor ) override { visitor->Visit( this ); }
};
//-----------------------------------------------------------------------------------------------//
// Expression for list of single element
struct CSingleElementListExpression : public IListExpression {
IExpression* Element;
void Accept( IVisitor* visitor ) override { visitor->Visit( this ); }
};
| true |
ac3e9d34ee01a050537e05917699d6aaf43f1a86 | C++ | httpc/hw | /ControlStructures/Power/main.cpp | WINDOWS-1251 | 585 | 2.84375 | 3 | [] | no_license | #include<iostream>
using namespace std;
//#define POWER
void main()
{
setlocale(LC_ALL, "");
#ifdef POWER
double a; //
int n; //
double N = 1;//
/*unsigned int b = -3;
cout << b << endl;
cout << UINT_MAX << endl;*/
cout << " c : "; cin >> a;
cout << " : "; cin >> n;
if (n < 0)
{
a = 1 / a;
n = -n;
}
for (int i = 0; i < n; i++)
{
N *= a;
}
cout << N << endl;
#endif // POWER
} | true |
c7eee9e81285f9824631347d797d1a8ec2aefdc7 | C++ | ThorStark/ROSPong | /src/pong_ball/src/pong_ball.cpp | UTF-8 | 4,513 | 2.578125 | 3 | [
"MIT"
] | permissive | /*****************************************************************************
* @file pong_main.cpp
*
* @author Thor Stark Stenvang
* thor.stark.stenvang@gmail.com
* @version 0.00
* @date 2017-09-07 YYYY-MM-DD
******************************************************************************/
#include<cmath>
#include <chrono>
// ROS
#include <pong_ball/pong_ball.h>
// Topics
#include <pong_ball/Pose.h>
#include <visualization_msgs/Marker.h>
pong::PongBall::PongBall():PongBall(ros::NodeHandle(), ros::NodeHandle("~"))
{
}
pong::PongBall::PongBall(ros::NodeHandle globalHandle, ros::NodeHandle privateHandle):
nh_(globalHandle),
pnh_(privateHandle),
rand_mt_(std::random_device{}())
{
// Get parameters from Global namespace
nh_.param<int>("pong_area_width", pong_area_.width, 10);
nh_.param<int>("pong_area_height", pong_area_.height, 10);
// Get parameters from private namespace
std::lock_guard<std::mutex> guard(poseMutex_);
{
pnh_.param<float>("start_pos_x", pose_.x, 0.0);
pnh_.param<float>("start_pos_y", pose_.y, 0.0);
pnh_.param<float>("start_vel_x", pose_.vx, 0.0);
pnh_.param<float>("start_vel_y", pose_.vy, 0.0);
}
// Publishers:
pub_pose_ = pnh_.advertise<pong_ball::Pose>("pongballPose",1);
pub_viz_ = pnh_.advertise<visualization_msgs::Marker>("ball_visualization",1);
// Services:
srv_reset_ = pnh_.advertiseService("reset", &PongBall::resetCallback, this);
srv_setpose_ = pnh_.advertiseService("setPose", &PongBall::setPoseCallback, this);
}
pong::PongBall::~PongBall()
{
runUpdateThread_ = false;
if(updatePoseThread_.joinable())
updatePoseThread_.join();
}
bool pong::PongBall::spin()
{
pong_ball::Pose pose_msg;
visualization_msgs::Marker point;
point.header.frame_id = "/ball_frame";
point.header.stamp = ros::Time::now();
point.ns = "ball";
point.id = 0;
point.action = visualization_msgs::Marker::ADD;
point.pose.orientation.w = 1.0;
point.type = visualization_msgs::Marker::POINTS;
point.scale.x = point.scale.y = 0.1;
point.color.g = 1.0f; point.color.a = 1.0f;
geometry_msgs::Point p;
p.z = 1.0;
{
std::lock_guard<std::mutex> guard(poseMutex_);
p.x = pose_msg.x = pose_.x;
p.y = pose_msg.y = pose_.y;
pose_msg.vel_x = pose_.vx;
pose_msg.vel_y = pose_.vy;
}
point.points.push_back(p);
pub_pose_.publish(pose_msg);
pub_viz_.publish(point);
return true;
}
/***************************************************************************
* Service callbacks
***************************************************************************/
bool pong::PongBall::resetCallback(pong_ball::Reset::Request &req, pong_ball::Reset::Response &res)
{
std::lock_guard<std::mutex> guard(poseMutex_);
pose_.x = 0.0;
pose_.y = 0.0;
if(req.random_vel_init){
//Generate random velocity vector with size 1
std::uniform_real_distribution<float> dist(0.0,1.0);
pose_.vx = dist(rand_mt_);
pose_.vy = std::sqrt(1-pose_.vx*pose_.vx);
}else{
pose_.vx = 0.0;
pose_.vy = 0.0;
}
return true;
}
bool pong::PongBall::setPoseCallback(pong_ball::SetPose::Request &req, pong_ball::SetPose::Response& res)
{
std::lock_guard<std::mutex> guard(poseMutex_);
pose_.x = req.pos.x;
pose_.y = req.pos.y;
pose_.vx = req.pos.vel_x;
pose_.vy = req.pos.vel_y;
return true;
}
/***************************************************************************
* Threads
***************************************************************************/
void pong::PongBall::updatePose()
{
int delta = 20;
while(runUpdateThread_){
std::this_thread::sleep_for(std::chrono::milliseconds(delta));
std::lock_guard<std::mutex> guard(poseMutex_);
Pose new_pose = pose_;
new_pose.x += new_pose.vx * (float)delta/1000.0;
new_pose.y += new_pose.vy * (float)delta/1000.0;
// Reflect direction if outside area
if(std::abs(new_pose.x) > pong_area_.width/2)
new_pose.vx = -new_pose.vx;
if(std::abs(new_pose.y) > pong_area_.height/2)
new_pose.vy = -new_pose.vy;
pose_ = new_pose;
}
}
void pong::PongBall::startUpdateThread()
{
runUpdateThread_ = true;
updatePoseThread_ = std::thread(&PongBall::updatePose, this);
}
void pong::PongBall::stopUpdateThread()
{
runUpdateThread_ = false;
updatePoseThread_.join();
}
| true |
f5a878e55c1a697d2b69d30af99e0e3f4c3d9181 | C++ | mylvoh0714/BOJ | /13415.cpp | UTF-8 | 1,222 | 2.765625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <queue>
#include <utility>
using namespace std;
int arr[100004];
int ans[100004];
int main()
{
int n; scanf("%d", &n);
for ( int i = 0; i < n; i++ ) scanf("%d", arr + i);
int k; scanf("%d", &k);
int max_v = 0;
deque<pair<int, int>> dq;
for ( int i = 0; i < k; i++ )
{
int up, down;
scanf("%d %d", &up, &down);
while ( !dq.empty() && dq.back().first <= up ) dq.pop_back();
if ( max_v <= up ) max_v = up;
dq.push_back({ up,1 }); // {value, up} = {value,1} <--> {value,down} = {value,2}
while ( !dq.empty() && dq.back().first <= down ) dq.pop_back();
if ( max_v <= down ) max_v = down;
dq.push_back({ down,2 });
}
sort(arr, arr + max_v);
// for answer arr
for ( int i = max_v; i < n; i++ ) ans[i] = arr[i];
int itr1 = 0;
int itr2 = --max_v;
while ( !dq.empty() )
{
int val = dq.front().first;
int type = dq.front().second;
dq.pop_front();
int cnt = val;
if(!dq.empty()) cnt -= dq.front().first;
if ( type == 1 ) {
for ( int i = 0; i < cnt; i++ ) ans[max_v--] = arr[itr2--];
}
else {
for ( int i = 0; i < cnt; i++ ) ans[max_v--] = arr[itr1++];
}
}
for ( int i = 0; i < n; i++ ) printf("%d ", ans[i]);
} | true |
5b29315456e37e195f904846b90943f1fdc2c580 | C++ | akshatdevp/Competitive | /HditDistance.cpp | UTF-8 | 654 | 3.171875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
if(word1.empty()||word2.empty())return max(word1.size(),word2.size());
int x=word1.size();
int y=word2.size();
int dp[x+1][y+1];
for(int i=0;i<x+1;i++)
for(int j=0;j<y+1;j++)
{
if(i==0||j==0)dp[i][j]=i+j;
else dp[i][j]=(word1[i-1]==word2[j-1]?dp[i-1][j-1]:min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1);
}
return dp[x][y];
}
};
/*
h o r s e
0 1 2 3 4 5
r 1 1 2 2 3 4
o 2 2 1 2
s 3
replace coming from diagonal
insert coming from above
delete coming from left
*/
| true |
41099f3b2bb8ef568a81cc65cda31ad685ef5bc0 | C++ | steplee/matching-benchmarks | /src/quad/quad.h | UTF-8 | 1,190 | 2.890625 | 3 | [] | no_license | #pragma once
#include <Eigen/StdVector>
#include <Eigen/Core>
template <int Cap, class V>
struct Leaf {
int occupancy;
Eigen::Vector2f keys[Cap];
V vals[Cap];
void init();
};
template<int Cap, class V>
class Quad {
private:
// Top left and bot right
Eigen::Vector2f tl;
Eigen::Vector2f br;
Eigen::Vector2f mid;
// Quadrants in order: 0 = tl, 1 = tr, 2 = bl, 3 = br
Quad<Cap,V>* next[4];
Leaf<Cap,V>* leaves[4];
public:
Quad(Eigen::Vector2f tl, Eigen::Vector2f br);
~Quad();
bool insert(Eigen::Vector2f key, V val);
// returns num written to buf.
// Does not get in order, nor the closest (but any closest *enough*)
int searchDist(Eigen::Vector2f key, float dist, V* buf, int bufN);
// There are keysN keys and keysN bufs, each of length bufLen.
void searchNN_cuda(Eigen::Vector2f* keys, int keysN,
int* bufs, int bufLen);
// does a 1:1 matching.
void searchDist_cpu_cuda(Eigen::Vector2f outerKey, float dist,Eigen::Vector2f* keys, int keysN,
V* buf);
};
| true |
d8c3003ec1a34f4e9ee09f6e74231d7eece59003 | C++ | daBisNewBee/NativeProject | /cpp/basic.cpp | UTF-8 | 8,558 | 3.375 | 3 | [] | no_license | //
// Created by Salmon on 2018/11/18.
//
extern "C"{
#include "xinda.h"
}
#include <iostream>
using namespace std;
namespace com_xmly_native {
class Person {
public:
Person() {
name = new char[16];
cout << "Person构造" << endl;
}
virtual ~Person() {
delete []name;
cout << "Person析构" << endl;
}
/*
* virtual在修饰方法时,可以实现多态:
* 即,子类有复写时,优先调用子类实现
* */
virtual void display() {
cout << "Person display. " << endl;
}
/*
* 考虑 "&"的作用?
* */
void swap(int &a, int &b){
cout<< "int swap....." << endl;
cout<< "a addr:" << &a <<endl;
cout<< "b addr:" << &b <<endl;
int tmp = a;
a = b;
b = tmp;
}
/*
* 值传递不如地址传递高效?
* 因为值传递先从实参的地址中取出值,再赋值给形参代入函数计算;
* 而指针则把形参的地址直接指向实参地址,使用时直接取出数据,效率提高,特别在频繁赋值等情况下(注意:形参的改变会影响实参的值!)
*
* */
private:
char* name;
};
/*
* 虚基类:
* virtual 修饰继承父类
* 可以解决"二义性"的问题 ,就是解决多重多级继承造成的二义性问题。
*
* 二义性的根源:
* C++支持多继承。
* 若不使用virtual,会构造子类时,会多次构造、多次析构父类。
* 比如,在实例TS时,会多次构造Person,无法区分Person中的属性属于Teacher还是Student的。
*
* */
class Teacher : virtual public Person {
public:
Teacher() {
cout << "Teacher构造" << endl;
}
virtual ~Teacher() {
cout << "Teacher析构" << endl;
}
void display() {
cout << "Teacher display." << endl;
}
};
class Student : virtual public Person {
public:
Student() {
cout << "Student构造" << endl;
}
virtual ~Student() {
cout << "Student析构" << endl;
}
// 纯虚函数的定义. 必须被子类实现
virtual void chunxufunc() = 0;
};
/*
* C++支持多继承(不推荐,会增加代码复杂度)
*
* 构造顺序(多个父类时):
* 继承时的父类顺序
*
* 析构顺序:
* 与构造顺序相反
*
* 比如:
* Person构造
Teacher构造
Student构造
TS构造
TS析构
Student析构
Teacher析构
Person析构
*/
class TS:public Teacher, public Student{
public:
TS() {
cout << "TS构造" << endl;
}
virtual ~TS() {
cout << "TS析构" << endl;
}
void chunxufunc() override {
cout << "这里是纯虚函数的实现。子类继承父类纯虚函数,必须实现." << endl;
}
};
}
using namespace com_xmly_native;
void doDisplay(Person* person){
person->display();
}
void virtualTest(){
/*
* 1. 多态:(virtual修饰方法时)
* 有virtual修饰"display()":
* Teacher display.
* 无virtual:
* Person display.
* */
Person* person = new Teacher();
doDisplay(person);
delete(person);
// 2. 虚继承:(virtual修饰继承父类时)
TS ts;
ts.chunxufunc();
// TS* pointer = new TS;
// delete pointer;
}
/*
* "*&i"表示"指针的引用传递"。即:
* 1. 传递的是一个指针:可以修改指针指向的对象
* 2. 该指针的一个引用:可以修改指针本身
*
* 与"*i"区分:
* 仅传递指针值,指针本身不可修改!
* */
void referTrans(int *&i){
i = new int;
*i = 10;
}
void paramsTransTest(){
// 1. "&a"形参的用法
Person* person1 = new Person;
int a = 10;
int b = 20;
cout << "a addr:" << &a << endl;
cout << "b addr:" << &b << endl;
person1->swap(a, b);
cout<< "a:"<<a<<endl;
cout<< "b:"<<b<<endl;
// 2. 引用传递. c与a具有相同的地址,形式上类似"值传递"
int &c = a;
cout << "c addr:" << &c << endl;
assert(&c == &a);
c = 100;
cout << "a:" << a << endl;
cout << "c:" << c << endl;
// 3. "*&a"形参的用法
int* p ;
referTrans(p);
cout << "*p:" << *p << endl;
delete p;
/*
* 4. 指针和引用的区别:("引用可以被认为是不能改变的指针")
* a. 是否可变。指针可以被重新赋值指向另一个对象,引用初始化后始终指向原对象,只能改变对象值,无法改变指向关系,相当于"const类型"
* b. 是否需要内存。指针变量需要内存,引用不占用内存。因此引用声明时必须初始化,且不能为空值
* c. 效率不同。引用的效率更高。指针可能非法,使用前需要校验合法性;而不存在指向空值的引用,不需要校验合法性
* d. 理论上,对于指针的级数没有限制,但是引用只能是一级。
* */
int m = 10, l = 20;
int &n = m;
// int &n = l; // 失败,引用在初始化与对象绑定,无法改变
}
// 声明可以"形参名"
int add(int=3, int=5);
void basicTest();
int add(int x, int y){
return x + y;
}
class A{
public:
A(){
cout << "A()" << endl;
}
A(int i):a(i){
cout << "A(int i)" << endl;
};
void print(){
cout << "a:" << a << endl;
}
private:
int a;
};
/*
* 参考:
* C++中创建对象的时候加括号和不加括号的区别:
* https://blog.csdn.net/spaceyqy/article/details/22730939
* */
void basicTest() {
/*
* 在"栈"上创建对象的特点:
* 速度快;
* 生命周期短;(系统自动执行析构)
* */
A a1; // 不打印. 表示使用不带参数的构造函数,或者有默认参数值的构造函数
a1.print(); // -335541872:
A a2(); // A()
A a3(1); // A(int i)
a3.print();
/*
* 在"堆"上创建对象的特点:
* 速度慢;
* 生命周期长;(手动delete才执行析构)
* */
/*
* 对于new关键字加括号和不加括号的区别:
* 对于"自定义类型"来说没有区别,都是使用默认构造函数
* */
cout << endl << "start use new.." << endl;
A* a4 = new A;
a4->print();
A* a5 = new A();
a5->print();
A* a6 = new A(5);
a6->print();
// 对于"内置类型"来说加括号会初始化
cout << endl << "new int:" << endl;
int* i1 = new int(1);
int* i2 = new int();
int* i3 = new int;
cout << "i1:" << *i1 << endl;
cout << "i2:" << *i2 << endl;
cout << "i3:" << *i3 << endl;
/*
*
* i1:1
i2:0 // 加括号会初始化
i3:0 // TODO: 网上打印出的是乱码,不加括号不初始化
* */
}
void defaultParamTest(){
cout << add() << endl; // 8
cout << add(10) << endl; // 15
cout << add(10,20) << endl; // 30
}
void enumTest(){
/*
* 语法结构:
enum [枚举名] {e1[=Value1], e2[=Value2] ,… …};
*
* 默认枚举值为:
* 0,1,2....递增
*
* 枚举值注意:
* 1. 不能为负数!
* 2. 可以重复。比如,enum weeks {mon=1,tue=1,wed=1,thu=1,fri=1,sat=2,sun=2};
*
* */
enum weekday {mon=1,tru,wed,thu,fri,sat,sun} day;
// enum weekday {mon=1,tru,wed,thu=9,fri,sat,sun} day;
// 此时 fri为10,依上个成员的枚举值依次递增的
int k;
printf("please input day num:");
scanf("%d",&k);
day = (weekday)k; // 整数需要"强制类型转换"才能赋值给枚举值
cout << day << endl; // 输出:1、2、。。。,输出枚举值,而不是枚举常量名称
switch (day){
case mon:
case tru:
case wed:
case thu:
case fri:
printf("今天上班.\n");
break;
case sat:
case sun:
printf("今天休息.\n");
break;
default:
printf("错误的日期\n");
break;
}
}
void invokeBasic(){
virtualTest();
paramsTransTest();
enumTest();
defaultParamTest();
basicTest();
} | true |
a9287f1dee8d45a75fa27e26939a05570e1519ee | C++ | gsz/codejam | /cj2010/3-A/DeRNGed.cpp | UTF-8 | 2,378 | 2.75 | 3 | [] | no_license | #include <everything.h>
using namespace std;
struct Eratosthenes {
vector<i64> ps;
Eratosthenes(int upto);
};
Eratosthenes::Eratosthenes(int upto) {
vector<bool> sieve(upto+1, true);
int max_relevant = static_cast<int>(floor(sqrt(upto)));
for (int p = 2; p <= max_relevant; ++p) {
if (!sieve[p])
continue;
for (int n = 2 * p; n <= upto; n += p)
sieve[n] = false;
}
for (int n = 2; n <= upto; ++n) {
if (sieve[n])
ps.push_back(n);
}
}
Eratosthenes primes(1000000);
i64 normalize(i64 n, i64 M) {
return (n + M) % M;
}
i64 modular_inverse(i64 n, i64 M) {
i64 A = n, B = M;
i64 x1 = 1, y1 = 0, x2 = 0, y2 = 1;
while (B > 0) {
i64 q = A / B;
i64 r = A % B;
i64 nx2 = x1 - q * x2;
i64 ny2 = y1 - q * y2;
A = B;
x1 = x2;
y1 = y2;
B = r;
x2 = nx2;
y2 = ny2;
}
return normalize(x1, M);
}
string read_solve_case() {
int D, K;
cin >> D >> K;
vector<i64> S(K);
for (int k = 0; k < K; ++k)
cin >> S[k];
if (K == 1 || (K == 2 && S[0] != S[1])) {
return "I don't know.";
} else if (S[0] == S[1]) {
return to_string(S[1]);
}
i64 maxP = 1;
while (D-- > 0)
maxP *= 10;
i64 maxS = *max_element(S.begin(), S.end());
vector<i64> possible_Ps;
copy_if(primes.ps.begin(), primes.ps.end(), back_inserter(possible_Ps),
[=](i64 p) { return p <= maxP && p > maxS; });
unordered_set<i64> candidates;
for (i64 P : possible_Ps) {
i64 A = normalize(S[2] - S[1], P) *
modular_inverse(normalize(S[1] - S[0], P), P) % P;
i64 B = normalize(S[1] - (A * S[0] % P), P);
bool matches = true;
for (u32 i = 1; i < S.size(); ++i) {
if ((S[i-1] * A + B) % P != S[i])
matches = false;
}
if (matches) {
candidates.insert((S.back() * A + B) % P);
if (candidates.size() > 1)
return "I don't know.";
}
}
return to_string(*candidates.begin());
}
int main(int argc, char *argv[]) {
ios_base::sync_with_stdio(false);
int T;
cin >> T;
for (int ci = 1; ci <= T; ++ci) {
cout << "Case #" << ci << ": " << read_solve_case() << endl;
}
return 0;
}
| true |
ebef2a5c15a8d2c52702fee3cb11b3d24b52c273 | C++ | wgfi110/cpp-playground | /cpp-htp/standard/ch21solutions/Ex21_10/Ex21_10.cpp | UTF-8 | 2,329 | 3.0625 | 3 | [
"Apache-2.0"
] | permissive | // Exercise 21.10 Solution: ex21_10.cpp
#include <iostream>
#include <iomanip>
using namespace std;
void displayBits( unsigned ); // prototype
unsigned power2( unsigned, unsigned ); // prototype
int main()
{
unsigned number;
unsigned pow;
unsigned result;
cout << "Enter two integers: ";
cin >> number >> pow;
cout << "\nnumber:\n";
displayBits( number );
cout << "\npower:\n";
displayBits( pow );
result = power2( number, pow );
cout << '\n' << number << " * 2^" << pow << " = " << result << '\n';
displayBits( result );
} // end main
// shifting n
unsigned power2( unsigned n, unsigned p )
{
return n << p; // shift n to the left p times
} // end function power2
// display the bits of value
void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw( 7 ) << value << " = ";
for ( unsigned c = 1; c <= SHIFT + 1; c++ )
{
cout << ( value & MASK ? '1' : '0' );
value <<= 1; // shift value left by 1
if ( c % 8 == 0 ) // output a space after 8 bits
cout << ' ';
} // end for
cout << endl;
} // end function displayBits
/**************************************************************************
* (C) Copyright 1992-2010 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
| true |
96430b5af5b778abfc96b1b4ce04e9548ecc53eb | C++ | Susuo/rtilabs | /files/asobiba/Banana/RNeoIFStreamUtil.h | SHIFT_JIS | 2,933 | 2.53125 | 3 | [] | no_license | // RNeoIFStreamUtil.h: RNeoIFStreamUtil NX̃C^[tFCX
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_RNEOIFSTREAMUTIL_H__99BC3921_D3F0_4FA2_BEDD_93AA770FD785__INCLUDED_)
#define AFX_RNEOIFSTREAMUTIL_H__99BC3921_D3F0_4FA2_BEDD_93AA770FD785__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "RNeoIStreamble.h"
class RNeoIFStreamUtilChecker
{
public:
virtual bool Check(const char* inBuffer , int inAllReadyRead , int inNowRead) = 0;
virtual int getSeparater() const = 0;
virtual int getNext() const = 0;
};
//AsR[h܂
class RNeoIFStreamUtilForSecutiveReturnCode : public RNeoIFStreamUtilChecker
{
public:
RNeoIFStreamUtilForSecutiveReturnCode()
{
Separater = 0;
ConectStart = 0;
}
~RNeoIFStreamUtilForSecutiveReturnCode()
{
}
virtual bool Check(const char* inBuffer , int inAllReadyRead , int inNowRead)
{
if (inAllReadyRead -4 < 0) inAllReadyRead = 0;
for (int i = inAllReadyRead; i < (inNowRead-3) ; i ++)
{
if ( (inBuffer[i] == '\r' && inBuffer[i+1] == '\n' && inBuffer[i+2] == '\r' && inBuffer[i+3] == '\n') )
{
ConectStart = i + 4;
Separater = i;
return false;
}
else if ( (inBuffer[i] == '\r' && inBuffer[i+1] == '\r') ||
(inBuffer[i] == '\r' && inBuffer[i+1] == '\r') )
{
ConectStart = i + 2;
Separater = i;
return false;
}
}
return true;
}
virtual int getSeparater() const
{
return Separater;
}
virtual int getNext() const
{
return ConectStart;
}
private:
int Separater;
int ConectStart;
};
//sR[h܂
class RNeoIFStreamUtilForReturnCode : public RNeoIFStreamUtilChecker
{
public:
RNeoIFStreamUtilForReturnCode()
{
Separater = 0;
ConectStart = 0;
}
~RNeoIFStreamUtilForReturnCode()
{
}
virtual bool Check(const char* inBuffer , int inAllReadyRead , int inNowRead)
{
for (int i = inAllReadyRead; i < inNowRead ; i ++)
{
if ( inBuffer[i] == '\n' )
{
Separater = i - 1;
ConectStart = i;
return false;
}
}
return true;
}
virtual int getSeparater() const
{
return Separater;
}
virtual int getNext() const
{
return ConectStart;
}
private:
int Separater;
int ConectStart;
};
class RNeoIFStreamUtil
{
public:
RNeoIFStreamUtil()
{
Buffer = NULL;
Stream = NULL;
}
~RNeoIFStreamUtil()
{
delete [] Buffer;
}
void Create(RNeoIStreamble* ioStream , int inTotalBufer = 65535)
{
ASSERT(Buffer == NULL);
Buffer = new char[inTotalBufer];
BufferLength = inTotalBufer;
BufferUse = 0;
Stream = ioStream;
}
int Read(char *outBuffer ,int inBufferSize,RNeoIFStreamUtilChecker* inStreamChecker) throw(RException);
static void test();
private:
RNeoIStreamble* Stream;
char * Buffer;
int BufferLength;
int BufferUse;
};
#endif // !defined(AFX_RNEOIFSTREAMUTIL_H__99BC3921_D3F0_4FA2_BEDD_93AA770FD785__INCLUDED_)
| true |
72ca7dbf85278f0817ede9002dad483eb1651b2f | C++ | anthony-leclerc/arcade | /include/loader/DLLoader.hpp | UTF-8 | 3,782 | 2.546875 | 3 | [] | no_license | /*
** DLLoader.hpp for in /home/anthony/documents/repository/cpp/cpp_arcade
**
** Made by Anthony LECLERC
** Login <anthony.leclerc@epitech.net>
**
** Started on Mon Mar 6 15:26:39 2017 Anthony LECLERC
** Last update Sun Apr 9 17:22:22 2017 Sylvain Chaugny
*/
#ifndef ARCADE_BOOTSTRAP_DLLOADER_HPP
# define ARCADE_BOOTSTRAP_DLLOADER_HPP
# include <dlfcn.h>
#include <iostream>
#include <sstream>
#include "loader/DLInterface.hpp"
#include "exceptions/loaderExceptions.hpp"
#include <cstring>
namespace utl {
template<typename T, template <typename> class _loader = DLInterface_basic>
class DLLoader {
private:
void *_handler;
typedef _loader<T> Loader;
typedef typename Loader::init_t ctor;
typedef typename Loader::delete_t dtor;
typedef typename Loader::pointer pointer;
ctor *_instance_ctor;
dtor *_instance_dtor;
pointer instance;
std::string _file;
template<typename U>
U *loadFunction(const char *symbolName)
{
U *function;
function = (U *)dlsym(_handler, symbolName);
if (!function)
{
std::stringstream err;
err << "Failed to load symbol: [" << symbolName << "]:";
throw utl::dlError(std::string(err.str().c_str()).c_str(), std::string(dlerror()).c_str());
}
return function;
}
void delete_instance()
{
if (_instance_dtor)
{
_instance_dtor(instance);
}
}
public:
DLLoader() : _handler(0), _instance_ctor(NULL), _instance_dtor(NULL), instance(0) {}
DLLoader(DLLoader const& other) = delete;
DLLoader& operator=(DLLoader const& other) = delete;
DLLoader(DLLoader &&other) :
_handler(other._handler),
_instance_ctor(other._instance_ctor),
_instance_dtor(other._instance_dtor),
instance(other.instance),
_file(other._file)
{
other._handler = 0;
other._instance_ctor = 0;
other._instance_dtor = 0;
other.instance = 0;
other._file = "";
}
DLLoader& operator=(DLLoader &&other)
{
if (this != &other)
{
_handler = other._handler;
_instance_ctor = other._instance_ctor;
_instance_dtor = other._instance_dtor;
instance = other.instance;
_file = other._file;
other._handler = 0;
other._instance_ctor = 0;
other._instance_dtor = 0;
other.instance = 0;
other._file = "";
}
return (*this);
}
int load(char const *libname) {
try
{
_handler = dlopen(libname, RTLD_NOW | RTLD_LOCAL);
if (!_handler)
{
std::stringstream err;
err << "Failed to load library: [" << libname << "]:";
throw utl::dlOpenError(std::string(err.str().c_str()).c_str(), std::string(dlerror()).c_str());
}
_instance_ctor = loadFunction<ctor>(Loader::ctor_sym.c_str());
_instance_dtor = loadFunction<dtor>(Loader::dtor_sym.c_str());
}
catch (utl::dlOpenError const& e)
{
std::cerr << "DLloader error: " << e.what() << " : " << e.dlerror() <<std::endl;
return 1;
}
catch (utl::dlError const& e)
{
std::cerr << "DLLoader error: " << e.what() << " : " << e.dlerror() << std::endl;
std::cerr << "Closing library..." << std::endl;
dlclose(_handler);
_handler = NULL;
return 1;
}
_file = libname;
return 0;
}
inline std::string const& getFileName() const
{ return _file; }
pointer getInstance() {
if (_instance_ctor)
{
if (!instance)
instance = _instance_ctor();
return instance;
}
else
{
std::cerr
<< "Error: Can't construct instance, entry point is not loaded."
<< std::endl;
return 0;
}
}
void unload() {
delete_instance();
if (_handler)
dlclose(_handler);
_handler = 0;
_file = "";
}
virtual ~DLLoader() {
unload();
}
};
} // namespace utl
#endif /* !ARCADE_BOOTSTRAP_DLLOADER_HPP */
| true |
babebafaa2fb2dfbf96a3a2f6f6fb982f1581026 | C++ | gaopj/leetcode | /leetcode101_150/107_Binary Tree Level Order Traversal II/源.cpp | UTF-8 | 1,022 | 2.796875 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> res;
vector<int> res0;
queue<TreeNode*> q;
queue<int> l;
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if (!root)
return res;
TreeNode* T;
int level = 0;
int nowlevel = 0;
q.push(root);
l.push(0);
while (!q.empty())
{
T = q.front();
level = l.front();
q.pop();
l.pop();
if (level == nowlevel)
res0.push_back(T->val);
else
{
nowlevel = level;
//res.push_back(res0);
res.insert(res.begin(), res0);
res0.clear();
res0.push_back(T->val);
}
if (T->left)
{
q.push(T->left);
l.push(level + 1);
}
if (T->right)
{
q.push(T->right);
l.push(level + 1);
}
}
if (res0.size() > 0)
res.insert(res.begin(), res0);
//res.push_back(res0);
return res;
}
}; | true |
6f6ba5982fbcbeb2352e1af324087c66a95e36f2 | C++ | ysun94/myQuantLib | /Matrix.h | UTF-8 | 378 | 2.953125 | 3 | [] | no_license | #pragma once
#include <iostream>
class Matrix
{
private:
int nrows;
int ncols;
double* data;
double* endPointer;
public:
Matrix();
Matrix(int nrows, int ncols);
Matrix(const Matrix& other);
~Matrix();
inline int nRows() const;
inline int nCols() const;
inline double get(int i, int j) const;
inline int offset(int i, int j) const;
}; | true |
a024ab12fcd8dc2567111fe75a2673708ee6ff64 | C++ | ellismi/C-labs | /C++ labs (base)/lab4_gr/Animal.h | UTF-8 | 161 | 2.546875 | 3 | [] | no_license | #pragma once
class Animal
{
public:
int age;
char name[20];
int weight;
Animal();
Animal(int age, char* name, int weight);
void voice();
void info();
};
| true |
170dda2e2fc6c683566e996e9e0dde804119d98f | C++ | Sayardiss/arduino-projects | /Le grand livre d'Arduino - Eyrolles/Fichiers de travail/Montage10/DetecteursLumiere/DetecteursLumiere.ino | UTF-8 | 961 | 3.03125 | 3 | [] | no_license | /*
Auteur : Erik Bartmann
Nom : Des détecteurs de lumière
Version : 1.0
Références : http://arduino.cc/en/Reference/PinMode
http://arduino.cc/en/Reference/Constants
http://arduino.cc/en/Reference/For
http://arduino.cc/en/Reference/DigitalWrite
http://arduino.cc/en/Reference/Array
http://arduino.cc/en/Reference/Map
*/
int pin[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // Tableau des broches
int analogPin = 0; // Broche de l'entrée analogique
int analogValue = 0; // Stocke la valeur analogique mesurée
void setup(){
for(int i = 0; i < 10; i++)
pinMode(pin[i], OUTPUT);
}
void loop(){
analogValue = analogRead(analogPin);
controlLEDs(analogValue);
}
// Fonction pour commander les LED
void controlLEDs(int value){
int bargraphValue = map(value, 0, 1023, 0, 9);
for(int i = 0; i < 10; i++)
digitalWrite(pin[i], (bargraphValue >= i)?HIGH:LOW);
}
| true |
30159d4fb8ce06aaf73f11e3c897b199b8ba4d2d | C++ | Dchment/Data-Structure | /树.cpp | GB18030 | 962 | 3.609375 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *lchild;
struct node *rchild;
}*tree;
int count=0;
void createtree(tree &t){//һҪ&ΪҪtĵֵַָֹиı䣡
int i;
scanf("%d",&i);
if(i==0){
t=NULL;
}
else{
t=(tree)malloc(sizeof(node));
t->data=i;
count++;
createtree(t->lchild);
createtree(t->rchild);
}
}//ʽ
void fot(tree t){//
if(t!=NULL){
printf("%d ",t->data);
fot(t->lchild);
fot(t->rchild);
}
}
void mot(tree t){//
if(t!=NULL){
mot(t->lchild);
printf("%d ",t->data);
mot(t->rchild);
}
}
void pot(tree t){//
if(t!=NULL){
pot(t->lchild);
pot(t->rchild);
printf("%d ",t->data);
}
}
int main(){
tree t;
createtree(t);
fot(t);
printf("\n");
mot(t);
printf("\n");
pot(t);
printf("\n");
return 0;
}
| true |
6b9951ba48baca030e93d88b916a7a4dc72e0d84 | C++ | griby/ray-tracing-series | /ray-tracing-series/src/camera.cpp | UTF-8 | 1,693 | 3.03125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* MIT License
* Copyright (c) 2019 Guillaume Riby <guillaumeriby@gmail.com>
*
* GitHub repository - https://github.com/griby/ray-tracing-series
*
* A ray tracer implementation based on the Ray Tracing in One Weekend Book Series by Peter Shirley - https://raytracing.github.io/
*/
#include "camera.h"
#include "defines.h"
#include "random.h"
#include "utils.h"
namespace rts
{
Camera::Camera(vec3 lookFrom, vec3 lookAt, vec3 vUp, float vFov, float aspectRatio, float aperture, float focusDist)
: m_origin(lookFrom)
, m_lensRadius(aperture / 2.f)
{
float theta = vFov * static_cast<int>(M_PI) / 180.f; // the FOV converted in radian
float halfHeight = tan(theta / 2.f);
float halfWidth = aspectRatio * halfHeight;
// Compute the orthonormal basis (u, v, w)
// where w is aligned with the camera direction and the plane (u, v) is orthogonal to it
w = unitVector(lookFrom - lookAt);
u = unitVector(cross(vUp, w));
v = cross(w, u);
// Determine a point in space which corresponds to the lower-left corner of our screen
// along with the screen's horizontal and vertical axes
m_lowerLeftCorner = m_origin - halfWidth * focusDist * u - halfHeight * focusDist * v - focusDist * w;
m_horizontal = 2.f * halfWidth * focusDist * u;
m_vertical = 2.f * halfHeight * focusDist * v;
}
Ray Camera::getRay(float s, float t, Random& random) const
{
vec3 rd = m_lensRadius * getRandomPointInUnitDisk(random);
vec3 offset = u * rd.x() + v * rd.y();
return Ray(m_origin + offset, m_lowerLeftCorner + s * m_horizontal + t * m_vertical - m_origin - offset);
}
}
| true |
8078c8b61a2659e3d1474746f5ff327b6f6a5956 | C++ | mvodya/big-sort-collection | /cocktail-sort/cocktail.cpp | UTF-8 | 1,535 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <ctime>
#include <iostream>
#include <random>
#include "bigsortlib/visualm.h"
using namespace sortlib;
// Elements count
#define N 200
// Array
int arr[N];
// Swaping two elements
void swap(int a, int b, int* m) {
int tmp = m[a];
m[a] = m[b];
m[b] = tmp;
}
// Cocktail sorting
void cocktail(int* m) {
int left = 0, right = N - 1;
while (left <= right) {
for (int i = left; i < right; i++) {
if (m[i] > m[i + 1]) swap(i, i + 1, arr);
// Delay
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
right--;
for (int i = right; i > left; i--) {
if (m[i] < m[i - 1]) swap(i, i - 1, arr);
// Delay
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
left++;
std::cout << left << " - " << right << std::endl;
}
}
// Thread function
void thread() {
// Fill array
for (int i = 0; i < N; i++) arr[i] = i * ((float)PALETTE / N);
// Wait 2s
std::this_thread::sleep_for(std::chrono::seconds(2));
// Random seed
std::srand(unsigned(std::time(0)));
// Random swap
for (int i = 0; i < N; i++) {
int a = rand() % (N - 1);
int b = rand() % (N - 1);
swap(a, b, arr);
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
// Wait 2s
std::this_thread::sleep_for(std::chrono::seconds(2));
// Cocktail sorting
std::cout << "Sorting started\n";
cocktail(arr);
std::cout << "Sorting done\n";
}
VisualModule* vm;
int main() {
vm = new VisualModule("Cocktail sort", thread, arr, N);
return 0;
} | true |
398ced47ffc14fc9a16f83200eac5f6138e884cf | C++ | ElMurte/MCBURGER | /Model/database.h | UTF-8 | 2,503 | 2.6875 | 3 | [] | no_license | #ifndef DATABASE_H
#define DATABASE_H
#include "Model/product.h"
#include "Model/burger.h"
#include "Model/sweet.h"
#include "Model/patatine.h"
#include "Model/drink.h"
#include "Model/manager.h"
#include "Model/menu.h"
#include<vector>
#include "Model/Dlist.h"
#include<QJsonObject>
#include<QJsonArray>
#include<QJsonDocument>
#include<QFile>
#include<QDir>
#include<QString>
#include "Model/order.h"
using std::vector;using std::cout;
class Database{
private:
static QString dirproducts;
static QString diremployees;
static QJsonObject docprod;
static QJsonObject docempl;
public:
void write(QJsonObject &json) const;
template <class P,class C>
static void readV(const QJsonArray &json,vector<P*>&);//utility function for readV()
template<class P,class C>
static void ReadProductfromJson(const QString & s, vector<P*>&v,const QJsonObject &json=docprod);
template <class P,class C>
static void readL(const QJsonArray &json, Dlist<P*>&v);
template<class P,class C>
static void ReadEmployeefromJson(const QString & s, Dlist<P*>&v,const QJsonObject &json=docempl);
/*********/
//function to push C (concrtete class) into polimorf P* vector of type P
static QJsonObject JsonreadFile(const QString& qs);
template<class T> T whatis(const QJsonObject&);
};
template <class P,class C>
void Database::readV(const QJsonArray &json, vector<P*>&v){
P*prod;
for (int Index = 0; Index < json.size(); ++Index) {
QJsonObject jsonObj = json[Index].toObject();
prod=new C();
prod->readInfoFromJson(jsonObj);/*chiamata polimorfa*/
v.push_back(prod);
}
}
template<class P,class C>
void Database::ReadProductfromJson(const QString & s, vector<P*>&v,const QJsonObject &json){
if (json.contains(s) && json[s].isArray()) {
QJsonArray jsonar = json[s].toArray();
readV<P,C>(jsonar,v);
}
}
template <class P,class C>
void Database::readL(const QJsonArray &json, Dlist<P*>&v){
P*prod;
for (int Index = 0; Index < json.size(); ++Index) {
QJsonObject jsonObj = json[Index].toObject();
prod=new C();
prod->readInfoFromJson(jsonObj);/*chiamata polimorfa*/
v.push_back(prod);
}
}
template<class P,class C>
void Database::ReadEmployeefromJson(const QString & s, Dlist<P*>&v,const QJsonObject &json){
if (json.contains(s) && json[s].isArray()) {
QJsonArray jsonar = json[s].toArray();
readL<P,C>(jsonar,v);
}
}
#endif // DATABASE_H
| true |
e4f8f3e2b46a8c3d90fc1a77e2b6291e581a996c | C++ | Thecarisma/serenity | /Libraries/LibCore/CSocket.cpp | UTF-8 | 3,774 | 2.640625 | 3 | [
"BSD-2-Clause"
] | permissive | #include <LibCore/CNotifier.h>
#include <LibCore/CSocket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
CSocket::CSocket(Type type, CObject* parent)
: CIODevice(parent)
, m_type(type)
{
}
CSocket::~CSocket()
{
close();
}
bool CSocket::connect(const String& hostname, int port)
{
auto* hostent = gethostbyname(hostname.characters());
if (!hostent) {
dbg() << "CSocket::connect: Unable to resolve '" << hostname << "'";
return false;
}
IPv4Address host_address((const u8*)hostent->h_addr_list[0]);
dbg() << "CSocket::connect: Resolved '" << hostname << "' to " << host_address;
return connect(host_address, port);
}
void CSocket::set_blocking(bool blocking)
{
int flags = fcntl(fd(), F_GETFL, 0);
ASSERT(flags >= 0);
if (blocking)
flags = fcntl(fd(), F_SETFL, flags | O_NONBLOCK);
else
flags = fcntl(fd(), F_SETFL, flags & O_NONBLOCK);
ASSERT(flags >= 0);
}
bool CSocket::connect(const CSocketAddress& address, int port)
{
ASSERT(!is_connected());
ASSERT(address.type() == CSocketAddress::Type::IPv4);
dbg() << *this << " connecting to " << address << "...";
ASSERT(port > 0 && port <= 65535);
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
auto ipv4_address = address.ipv4_address();
memcpy(&addr.sin_addr.s_addr, &ipv4_address, sizeof(IPv4Address));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
m_destination_address = address;
m_destination_port = port;
return common_connect((struct sockaddr*)&addr, sizeof(addr));
}
bool CSocket::connect(const CSocketAddress& address)
{
ASSERT(!is_connected());
ASSERT(address.type() == CSocketAddress::Type::Local);
dbg() << *this << " connecting to " << address << "...";
sockaddr_un saddr;
saddr.sun_family = AF_LOCAL;
strcpy(saddr.sun_path, address.to_string().characters());
return common_connect((const sockaddr*)&saddr, sizeof(saddr));
}
bool CSocket::common_connect(const struct sockaddr* addr, socklen_t addrlen)
{
int rc = ::connect(fd(), addr, addrlen);
if (rc < 0) {
if (errno == EINPROGRESS) {
dbg() << *this << " connection in progress (EINPROGRESS)";
m_notifier = CNotifier::construct(fd(), CNotifier::Event::Write, this);
m_notifier->on_ready_to_write = [this] {
dbg() << *this << " connected!";
m_connected = true;
m_notifier->set_event_mask(CNotifier::Event::None);
if (on_connected)
on_connected();
};
return true;
}
perror("CSocket::common_connect: connect");
return false;
}
dbg() << *this << " connected ok!";
m_connected = true;
if (on_connected)
on_connected();
return true;
}
ByteBuffer CSocket::receive(int max_size)
{
auto buffer = read(max_size);
if (eof()) {
dbg() << *this << " connection appears to have closed in receive().";
m_connected = false;
}
return buffer;
}
bool CSocket::send(const ByteBuffer& data)
{
int nsent = ::send(fd(), data.pointer(), data.size(), 0);
if (nsent < 0) {
set_error(errno);
return false;
}
ASSERT(nsent == data.size());
return true;
}
void CSocket::did_update_fd(int fd)
{
if (fd < 0) {
m_read_notifier = nullptr;
return;
}
m_read_notifier = CNotifier::construct(fd, CNotifier::Event::Read, this);
m_read_notifier->on_ready_to_read = [this] {
if (on_ready_to_read)
on_ready_to_read();
};
}
| true |
39953c6b085fc4d9a8f5d937ba12e298fd7c63bc | C++ | MartinMedek/reversible-sketch | /src/Sketch.h | UTF-8 | 2,830 | 2.90625 | 3 | [] | no_license | //
// Created by medek on 7.3.17.
//
#ifndef SKETCH_SKETCH_TABLE_H
#define SKETCH_SKETCH_TABLE_H
#include <array>
#include <algorithm>
#include <list>
#include <cstdint>
#include "SketchTable.h"
#include "BIV.h"
#include "misc_functions.h"
class Sketch
{
public:
std::array<SketchTable *, TABLE_COUNT> tables;
std::list<uint64_t> reversed_hashes;
std::array<std::map<uint8_t, HeavyBuckets>, WORD_COUNT> modular_potentials;
/** simple constructor **/
Sketch();
/** create empty sketch with same hashing functions **/
Sketch(const Sketch &sketch);
virtual ~Sketch();
/**
* insert
* inserts given value to all tables
* @param src Value to be inserted
*/
void insert(uint32_t src, uint32_t dst);
/**
* insert
* inserts given value to all tables
* @param src Value to be inserted
*/
void insert_size(uint32_t src, uint32_t dst, uint32_t size);
/**
* compute_all_biv
* initializes all possible BIVs and extends them in all possible ways. Should compute all reverse hashes
*/
void compute_reverse_hashes();
/**
* print_reverse_hashes
* if reverse hashes of heavy buckets were computed, prints them
*/
void print_reverse_hashes();
/**
* compute_modular_potentials
* saves modular potentials on given word index
* @param index Word index of potentials
*/
void compute_modular_potentials(unsigned word_index);
/**
* get_modular_potentials
* @param index Word index of potentials
* @return modular potentials on given word index
*/
const std::map<uint8_t, HeavyBuckets> & get_modular_potentials(unsigned index) const;
/**
* get_buckets
* @param index Index of given table
* @return heavy buckets of given table
*/
const std::vector<uint32_t> & get_buckets(unsigned index) const;
/**
* compute_buckets
* in every hash table calls compute_buckets method
*/
void compute_buckets();
/** debug outputs **/
void print_buckets();
/** debug outputs **/
void print_statistics();
/**
* init_biv
* first step in creating bucket index vector. Creates BIV with length 1 and given word of index 0
*/
BIV init_biv(uint8_t word);
/**
* init_table_stats
* computes all heavy buckets and modular potentials
*/
void init_table_stats();
/**
* extend_biv_recursive
* extends given BIV by 1, intersecting its bucket maps for all modular potentials on given index.
* Recursively calls itself with incremented index. Values from finished vectors are stored at reverse_hashes
*/
void extend_biv_recursive(const BIV & biv, unsigned word_index);
// Sketch operator+(const Sketch &another);
};
#endif //SKETCH_SKETCH_TABLE_H
| true |
77e3a4823163967aa6bde9f5beb4103d87fb4655 | C++ | ravikishore1993/Spoj | /EQBOX.cpp | UTF-8 | 504 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
main()
{long long int a,b,c,d,e,f,g;
scanf("%lld",&g);
while(g>0)
{
scanf("%lld %lld %lld %lld",&a,&b,&c,&d);
if((c*d)>=(a*b))
printf("Box cannot be dropped.\n");
else
if((c>=b && c>=a) || (d>=b && d>=a))
{if((a*a+b*b)<=(c*c+d*d))
printf("Box cannot be dropped.\n");
else printf("Escape is possible.");
}
else printf("Escape is possible.");
g--;
}
}
| true |
fbe08e685bdd12de465e4508cec5137ddbc3b64b | C++ | PavloNaichuk/Projects | /AirHockey/EnemyStrikerRenderer.cpp | UTF-8 | 1,123 | 2.515625 | 3 | [] | no_license | #include "pch.h"
#include "EnemyStrikerRenderer.h"
#include "GameObject.h"
#include "PositionComponent.h"
#include "RadiusComponent.h"
EnemyStrikerRenderer::EnemyStrikerRenderer(SharedRenderer renderer, SharedResourceManager resourceManager)
: mRenderer(renderer)
, mTexture(resourceManager->GetTexture(ResourceManager::ENEMY_STRIKER_ID))
{
assert(mTexture);
}
Component::ComponentId EnemyStrikerRenderer::GetId() const
{
return RenderComponent::COMPONENT_ID;
}
void EnemyStrikerRenderer::Render(GameObject& gameObject)
{
const PositionComponent* positionComponent = gameObject.GetComponent<PositionComponent>(PositionComponent::COMPONENT_ID);
const RadiusComponent* radiusComponent = gameObject.GetComponent<RadiusComponent>(RadiusComponent::COMPONENT_ID);
Point topLeft = positionComponent->GetCenter() - radiusComponent->GetRadius();
SDL_Rect destRect = {int(topLeft.mX), int(topLeft.mY), int(2.0f * radiusComponent->GetRadius()), int(2.0f * radiusComponent->GetRadius())};
SDL_SetTextureBlendMode(mTexture.get(), SDL_BLENDMODE_ADD);
SDL_RenderCopy(mRenderer.get(), mTexture.get(), nullptr, &destRect);
}
| true |
c8f5192bdd7211b6f3b67c62b93f013cbc41c0d6 | C++ | lordjaxom/schlazicontrol | /trackable.cpp | UTF-8 | 2,291 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include "trackable.hpp"
using namespace std;
namespace sc {
namespace detail {
/**
* class TrackableTracker
*/
void TrackableTracker::announce()
{
++count_;
}
void TrackableTracker::forget()
{
--count_;
}
void TrackableTracker::increase( size_t allocated )
{
allocated_ += allocated;
}
void TrackableTracker::decrease( std::size_t allocated )
{
allocated_ -= allocated;
}
void TrackableTracker::statistics( std::ostream& os ) const
{
os << "\n\tChannelBuffer : count: " << count_ << ", allocated: " << allocated_;
}
/**
* class TrackableBase
*/
TrackableBase::TrackableBase( TrackableTracker& tracker )
: tracker_( &tracker )
{
tracker_->announce();
}
TrackableBase::TrackableBase( TrackableBase const& other )
: tracker_( other.tracker_ )
{
increase( other.allocated_ );
}
TrackableBase::TrackableBase( TrackableBase&& other )
{
swap( allocated_, other.allocated_ );
}
TrackableBase::~TrackableBase()
{
decrease( allocated_ );
tracker_->forget();
}
TrackableBase& TrackableBase::operator=( TrackableBase const& other )
{
decrease( allocated_ );
increase( other.allocated_ );
return *this;
}
TrackableBase& TrackableBase::operator=( TrackableBase&& other )
{
swap( allocated_, other.allocated_ );
return *this;
}
void TrackableBase::increase( std::size_t allocated )
{
allocated_ += allocated;
tracker_->increase( allocated );
}
void TrackableBase::decrease( std::size_t allocated )
{
allocated_ -= allocated;
tracker_->decrease( allocated );
}
void TrackableBase::statistics( std::ostream& os ) const
{
os << "allocated: " << allocated_;
}
} // namespace detail
} // namespace sc | true |
8214649936224bfdcdff8af32d050293779bac7d | C++ | flpdsc/basic_algorithm | /cpp/30.cpp | UTF-8 | 433 | 2.734375 | 3 | [] | no_license | //3의 개수는? (large)
#include <iostream>
using namespace std;
int main()
{
int n, lt, cur, rt, k=1, res=0;
cin >> n;
while(lt != 0){
lt = n/(k*10);
cur = n/k%10;
rt = n%k;
if(cur > 3){
res += (lt+1)*k;
}
else if(cur < 3){
res += lt*k;
}
else res += (lt*k)+(rt+1);
k *= 10;
}
cout << res << endl;
return 0;
} | true |
7c0335017188d76f879d4ea1695f34f4de4728c7 | C++ | pureexe/SCSU-compro1 | /exercise/mid56_1/p3_3_best_avail_box.cpp | UTF-8 | 1,009 | 2.640625 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int in[3],n,i,sum[] = {0,0,0,0},cnt[] = {0,0,0,0},remain[4],cType;
cin >> n;
cin >> remain[1] >> remain[2] >> remain[3];
for(i=0;i<n;i++){
cin >> in[0] >> in[1] >> in[2];
sort(in,in+3);
if(in[0]<=8 && in[1]<=10 && in[2]<=15){
cType = 1;
}else if(in[0]<=12 && in[1]<=15 && in[2]<=25){
cType = 2;
}else if(in[0]<=20 && in[1]<=40 && in[2]<=50){
cType = 3;
}else{
cType = 4;
}
if(cType<=1 && remain[1]>0){
cout << "1\n";
remain[1]--;
}else if(cType<=2 && remain[2]>0){
cout << "2\n";
remain[2]--;
}else if(cType <=3 && remain[3]>0){
cout << "3\n";
remain[3]--;
}else if(cType == 4){
cout << "Oversize product\n" ;
}else{
cout << "Box not available\n";
}
}
return 0;
}
| true |
2ece93608908e63e881a7b734207d9fea5fba351 | C++ | sssrdezh/Cpp-Primer | /Chapter 003/Exercise 011/main.cpp | GB18030 | 371 | 3.640625 | 4 | [] | no_license | /*
ϰ3.11ķΧforϷϷcʲô
*/
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
int main()
{
const string s = "Keep out!";
for (auto &c : s)
{
cout << c;
}
cout << endl;
return 0;
}
/*
cõֵϷcģΪconst char &.
*/ | true |
e8dd11aa36436d25e411af18434a3f535da2277d | C++ | kittu9999/CPU-schedules-and-N-process | /kittu os project.cpp | UTF-8 | 11,662 | 2.84375 | 3 | [] | no_license | //MULTILEVEL FEEDBACK QUEUE
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
struct process
{
int processid;
int arrival_time;
int burst_time;
int priority;
int time_left;
int starting_time;
int end_time;
};
//returns true if process2 is priority is greater than process1 priority
//returns true if process2 is earlier than process1
class compare_arrivaltime
{
public:
bool operator()(const process& process1, const process& process2) const
{
if ( process1.priority >process2.priority)
return true;
if(process1.priority==process2.priority && process1.arrival_time>process2.arrival_time)
return true;
if(process1.priority==process2.priority && process1.arrival_time==process2.arrival_time && process1.processid>process2.processid)
return true;
return false;
}
};
int i,j,no_of_process,minimum,completion_time=0;
int processid,arrival_time,burst_time,priority;
int temp_processid,temp_arrivaltime,temp_bursttime,temp_priority,temp_remainingtime,temp_startingtime,temp_endtime;
int gannt_chart[1000];
int time=0,turn=0;
int priority_quantum=4,roundrobin_quantum=4;
int status=0;
void Initialize_gannt_chart(int t);
void print_gannt_chart();
void sort_according_to_arrivaltime(struct process *p);
void sort_according_to_processid(struct process *p);
void print_result(struct process p[],int store_pids[]);
void implement_queue2_IS_NOT_EMPTY();
void implement_queue1_IS_NOT_EMPTY();
priority_queue<process, vector<process>, compare_arrivaltime> queue1;
queue<process> queue2;
int main()
{
printf("no of processes");
scanf("%d",&no_of_process);
int store_pids[no_of_process];
struct process p=(struct process)malloc((no_of_process+1)*sizeof(struct process));
for( i=0;i<no_of_process;i++)
{
printf("\nenter processid , arr, burst , priority ");
scanf("%d %d %d %d",&processid,&arrival_time,&burst_time,&priority);
p[i].processid = processid;
store_pids[i]=processid;
p[i].arrival_time=arrival_time;
p[i].burst_time=burst_time;
p[i].priority=priority;
p[i].time_left=burst_time;
completion_time = completion_time + burst_time;
}
Initialize_gannt_chart(completion_time);
//Sorting of processes according to arrival time
sort_according_to_arrivaltime(p);
while((!queue1.empty())||(!queue2.empty())||(status==0)||(turn<no_of_process))
{
while((turn<no_of_process) && (p[turn].arrival_time==time))
{
if(priority_quantum!=4 && (p[turn].priority<queue1.top().priority))
{
queue2.push(queue1.top());
queue1.pop();
priority_quantum=4;
}
status=1;
queue1.push(p[turn]);
turn = turn +1;
}
if(!queue1.empty())
{
implement_queue1_IS_NOT_EMPTY();
}
else if(!queue2.empty())
{
implement_queue2_IS_NOT_EMPTY();
}
time= time+1;
}
//print_gannt_chart();
for(i=0;i<no_of_process;i++)
{
int flag=0;
int current_processid = p[i].processid;
for(j=0;j<time;j++)
{
if(gannt_chart[j]==current_processid)
{
if(flag==0)
{
p[i].starting_time=j;
flag=1;
}
else
p[i].end_time=j+1;
}
}
}
// sorting of processes according to processid-lower to higher
sort_according_to_processid(p);
//print the result
print_result(p,store_pids);
return 0;
}
void print_gannt_chart()
{
printf("\nGannt Chart of the processes is : ");
for(i=0;i<time;i++)
printf("%d",gannt_chart[i]);
printf("\n");
}
//
void print_result(struct process p[])
{
int i;
printf("\n");
int new_processid,response_time,waiting_time,finish_time;
for(i=0;i<no_of_process;i++)
{
new_processid = p[i].processid;
response_time = p[i].starting_time - p[i].arrival_time;
waiting_time = p[i].end_time - p[i].arrival_time - p[i].burst_time;
finish_time=p[i].end_time;
printf("%d %d %d %d\n",new_processid,response_time,finish_time,waiting_time);
}
}
//
void print_result(struct process p[],int store_pids[])
{
int i,j;
printf("\n");
int new_processid,response_time,waiting_time,finish_time;
printf("\nprocess id || respone time || finish time || waiting time");
for(i=0;i<no_of_process;i++)
{
for(j=0;j<no_of_process;j++)
{
if(store_pids[i]==p[j].processid)
{
new_processid = p[j].processid;
response_time = p[j].starting_time - p[j].arrival_time;
waiting_time = p[j].end_time - p[j].arrival_time - p[j].burst_time;
finish_time=p[j].end_time;
printf("\n%d %d %d %d\n",new_processid,response_time,finish_time,waiting_time);
}
}
}
}
void Initialize_gannt_chart(int t)
{
for(i=0;i<=t;i++)
gannt_chart[i]=0;
}
void implement_queue1_IS_NOT_EMPTY()
{
if((roundrobin_quantum!=4)&&(!queue2.empty()))
{
queue2.push(queue2.front());
queue2.pop();
roundrobin_quantum=4;
}
process cur = queue1.top();
gannt_chart[time]=cur.processid;
cur.time_left = cur.time_left-1;
queue1.push(cur);
queue1.pop();
priority_quantum=priority_quantum-1;
if(queue1.top().time_left==0)
{
queue1.pop();
priority_quantum=4;
}
else if(priority_quantum==0)
{
if(queue1.top().time_left>0)
queue2.push(queue1.top());
queue1.pop();
priority_quantum=4;
}
}
void implement_queue2_IS_NOT_EMPTY()
{
queue2.front().time_left = queue2.front().time_left-1;
gannt_chart[time]=queue2.front().processid;
roundrobin_quantum--;
if(queue2.front().time_left==0)
{
queue2.pop();
roundrobin_quantum=4;
}
else if(roundrobin_quantum==0)
{
queue2.push(queue2.front());
queue2.pop();
roundrobin_quantum=4;
}
}
void sort_according_to_arrivaltime(struct process p[])
{
for(i=0;i<no_of_process-1;i++)
{
minimum=i;
for(j=i+1;j<no_of_process;j++)
{
if(p[j].arrival_time<p[minimum].arrival_time)
{
minimum=j;
}
}
if(i!=minimum)
{
temp_processid=p[minimum].processid;
temp_arrivaltime=p[minimum].arrival_time;
temp_bursttime=p[minimum].burst_time;
temp_priority=p[minimum].priority;
temp_remainingtime=p[minimum].time_left;
p[minimum].processid=p[i].processid;
p[minimum].arrival_time=p[i].arrival_time;
p[minimum].burst_time=p[i].burst_time;
p[minimum].priority=p[i].priority;
p[minimum].time_left=p[i].time_left;
p[i].processid=temp_processid;
p[i].arrival_time=temp_arrivaltime;
p[i].burst_time=temp_bursttime;
p[i].priority=temp_priority;
p[i].time_left=temp_remainingtime;
}
}
}
void sort_according_to_processid(struct process p[])
{
for(i=0;i<no_of_process-1;i++)
{
minimum=i;
for(j=i+1;j<no_of_process;j++)
{
if(p[j].processid<p[minimum].processid)
{
minimum=j;
}
}
if(i!=minimum)
{
temp_processid=p[minimum].processid;
temp_arrivaltime=p[minimum].arrival_time;
temp_bursttime=p[minimum].burst_time;
temp_priority=p[minimum].priority;
temp_remainingtime=p[minimum].time_left;
temp_startingtime=p[minimum].starting_time;
temp_endtime=p[minimum].end_time;
p[minimum].processid=p[i].processid;
p[minimum].arrival_time=p[i].arrival_time;
p[minimum].burst_time=p[i].burst_time;
p[minimum].priority=p[i].priority;
p[minimum].time_left=p[i].time_left;
p[minimum].starting_time=p[i].starting_time;
p[minimum].end_time=p[i].end_time;
p[i].processid=temp_processid;
p[i].arrival_time=temp_arrivaltime;
p[i].burst_time=temp_bursttime;
p[i].priority=temp_priority;
p[i].time_left=temp_remainingtime;
p[i].starting_time=temp_startingtime;
p[i].end_time=temp_endtime;
}
}
}
| true |
a378beced171c9d6dfee43576aea8d18d499b1c9 | C++ | ruogudu/pagelevelcache | /scripts/tochart.cpp | UTF-8 | 1,206 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <algorithm>
using namespace std;
int main(int argc, char **argv) {
string curType = string(argv[2]);
string curAlgo = string(argv[3]);
ifstream fin;
fin.open(argv[1]);
string type;
string algo;
long size;
int samples;
double ratio;
map<long, map<int, double> > m;
while (fin >> type >> algo >> size >> samples >> ratio) {
if (type != curType || algo != curAlgo) {
continue;
}
if (m.find(size) == m.end()) {
m[size] = map<int, double>();
}
m[size][samples] = ratio;
}
bool titlePrinted = false;
for (auto const& t1 : m) {
if (!titlePrinted) {
cout << curType << "_" << curAlgo << '\t';
for (auto const& t2 : t1.second) {
cout << t2.first << '\t';
}
cout << endl;
titlePrinted = true;
}
cout << t1.first << '\t'; // string (key)
for (auto const& t2 : t1.second) {
cout << t2.second << '\t';
}
cout << std::endl ;
}
return 0;
}
| true |
5f68eed37aa4fd93a278f4f013dd076dffc6cc3c | C++ | vespa-engine/vespa | /vdslib/src/vespa/vdslib/state/state.h | UTF-8 | 2,992 | 3.234375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
* @class vdslib::State
*
* Defines legal states for various uses. Split this into its own class such
* that we can easily see what states are legal to use in what situations.
* They double as node states nodes report they are in, and
* wanted states set external sources.
*/
#pragma once
#include "nodetype.h"
#include <vespa/vespalib/util/printable.h>
#include <vespa/vespalib/stllike/string.h>
#include <vector>
namespace storage::lib {
class State : public vespalib::Printable {
vespalib::string _name;
vespalib::string _serialized;
uint8_t _rankValue;
std::vector<bool> _validReportedNodeState;
std::vector<bool> _validWantedNodeState;
bool _validClusterState;
State(const State&);
State(vespalib::stringref name, vespalib::stringref serialized,
uint8_t rank,
bool validDistributorReported, bool validStorageReported,
bool validDistributorWanted, bool validStorageWanted,
bool validCluster);
~State();
State& operator=(const State&);
public:
static const State UNKNOWN;
static const State MAINTENANCE;
static const State DOWN;
static const State STOPPING;
static const State INITIALIZING;
static const State RETIRED;
static const State UP;
/** Throws vespalib::IllegalArgumentException if invalid state given. */
static const State& get(vespalib::stringref serialized);
const vespalib::string& serialize() const { return _serialized; }
bool validReportedNodeState(const NodeType& node) const { return _validReportedNodeState[node]; }
bool validWantedNodeState(const NodeType& node) const { return _validWantedNodeState[node]; }
bool validClusterState() const { return _validClusterState; }
bool maySetWantedStateForThisNodeState(const State& wantedState) const {
return (wantedState._rankValue <= _rankValue);
}
/**
* Get a string that represents a more human readable version of
* the state than what can be provided through the single-character
* serialized representation.
*
* Example: State::RETIRED.getName() -> "Retired"
*/
const vespalib::string& getName() const noexcept {
return _name;
}
void print(std::ostream& out, bool verbose, const std::string& indent) const override;
bool operator==(const State& other) const { return (&other == this); }
bool operator!=(const State& other) const { return (&other != this); }
/**
* Utility function to check whether this state is one of the given
* states, given as the single character they are serialized as.
* For instance, "um" will check if this state is up or maintenance.
*/
bool oneOf(const char* states) const {
for (const char* c = states; *c != '\0'; ++c) {
if (*c == _serialized[0]) return true;
}
return false;
}
};
}
| true |
043e6c6a8d443f93e182fcc7e6f6b183ae47d546 | C++ | sologyan/CPP | /area_of_circle.cpp | UTF-8 | 209 | 3.171875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
float a, radius;
cout<<"enter the radius";
cin>>radius;
a = 3.14 * radius * radius;
cout<<"Area of circle ="<<a;
return 0;
} | true |
98a2178e91069d8ab08d3cfc256a502ba499feaf | C++ | wowangki/Study | /Game/Puzzle/D2DFramework_v0.0006/Module/Timer/TimerModule.h | UTF-8 | 655 | 2.5625 | 3 | [] | no_license | #pragma once
class TimerModule
{
private:
bool isHardware;
float timeScale;
float timeElapsed;
__int64 _periodTime;
__int64 _lastTime;
__int64 _curTime;
unsigned long frameRate;
unsigned long FPSFrameCount;
float FPSTimeElapsed;
float worldTime;
public:
TimerModule();
~TimerModule();
void UpdateTime(float frameLock = 60.0f);
void RenderTime(void);
inline float GetElapsedTime(void) const { return timeElapsed; }
inline float GetTime(void) const { return worldTime; }
inline float GetFPSTime(void) { return (float)frameRate; }
public:
static TimerModule* GetInstance() {
static TimerModule instance;
return &instance;
}
};
| true |
c8865dab91cfc98b3c65f44552a343f2931b7a4d | C++ | yalaudah/CtCI-6th-Edition-cpp | /Ch 1.Arrays And Strings/isUnique.cpp | UTF-8 | 587 | 3.59375 | 4 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
bool isUnique(const std::string &word)
{
if (word.size() > 127)
return 0;
std::vector<bool> char_set(128); //
for(const char c: word)
{
if (char_set[static_cast<int>(c)])
return false;
else
char_set[c] = true;
}
return true;
}
int main(std::vector<std::string> &args)
{
std::vector<std::string> words = {"abcde", "hello", "apple", "kite", "padle"};
for (auto word : words)
{
std::cout << word << std::string(": ") << isUnique(word) << std::endl;
}
return 0;
}
| true |
624a90d2335f4d83655ed4becf6adca778691145 | C++ | kiselyovanat/Haffman | /haffman.cpp | UTF-8 | 3,439 | 3.21875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <fstream>
#include <list>
#include <iterator>
#include <vector>
using namespace std;
struct Node
{
int pos;//вероятность символа
char c;//cам символ
Node *left;//указатель на левого сына(для дерева)
Node *right;//указатель на правого сына(для дерева)
};
struct Code
{
char smbl;//символ
vector<int> cd;//его код
};
struct CompNode
{
bool operator() (Node* l, Node* r)
{
return (l->pos<r->pos);
}
};
void print(Node* root,int k=0)
{
if(root!=NULL)
{
print(root->left,k+3);
for(int i=0;i<k;i++)
{
cout<<" ";
}
if (root->c) cout<<root->pos<<" ("<<root->c<<")"<<endl;
else cout<<root->pos<<endl;
print(root->right,k+3);
}
}
void CreateList(list <Node*>& t,int* a)
{
Node *p=new Node;
for(int j=0;j<256;j++)
{
if (a[j]!=0)
{
Node *p=new Node;
p->pos=a[j];
p->c=j;
p->left=p->right=NULL;
t.push_back(p);
}
}
}
void CreateTree(list<Node*>& t)
{
while(t.size()!=1)
{
t.sort(CompNode());
Node *ls=t.front();
t.pop_front();
Node *rs=t.front();
t.pop_front();
Node *p=new Node;
p->pos=ls->pos+rs->pos;
p->left=ls;
p->right=rs;
t.push_back(p);
}
Node *root=t.front();
print(root);
}
void CreateCode(Node* root, char b, Code& code, ofstream& codes)
{
if(root->left!=NULL)
{
code.cd.push_back(0);
CreateCode(root->left,b,code,codes);
}
if(root->right!=NULL)
{
code.cd.push_back(1);
CreateCode(root->right,b,code,codes);
}
if ((root->left==NULL) && (root->right==NULL) && (root->c==b))
{
cout<<b<<" ";
for(int i=0; i<code.cd.size(); i++)
{
cout<<code.cd[i];
codes<<code.cd[i];
}
cout<<endl;
}
code.cd.pop_back();
}
void encode(ifstream& in, Node* root,ofstream& out)
{
char b;
Code code;
in.get(b);
while(!(in.eof()))
{
CreateCode(root,b,code,out);
in.get(b);
code.cd.clear();
}
}
void decode(ifstream& in,Node* root, Node* startroot,char x,ofstream& out)
{
if(x != EOF)
{
if((x=='0') && (root->left!=NULL))
{
x=in.get();
decode(in,root->left,startroot,x,out);
}
if((x=='1') && (root->right!=NULL))
{
x=in.get();
decode(in,root->right,startroot,x,out);
}
if ((root->left==NULL) && (root->right==NULL))
{
out<<root->c;
decode(in,startroot,startroot,x,out);
//сout<<root->c;
}
}
}
void CreateArray(int a[], ifstream& in)
{
int i=0;
char b;
for (i=0;i<256;i++)
{
a[i]=0;
}
for(i=0;!in.eof();i++)
{
in.get(b);
a[b]++;
}
}
int main()
{
int j;
int p[256]; //массив с вероятностями символов
list <Node*> tree;
Code* code;
ifstream in("in.txt");
CreateArray(p,in);
in.close();
CreateList(tree,p);
int size=tree.size();//количество различных символов в тексте
CreateTree(tree);
Node *root=tree.front();
ifstream inn("in.txt");
ofstream out("out.txt");
encode(inn,root,out);//кодирование файла
out.close();
inn.close();
ifstream oout("out.txt");//открываем на чтение файл с кодом
ofstream in2("in2.txt");
char x=oout.get();
decode(oout,root,root,x,in2);
in2.close();
oout.close();
}
| true |
aded8558abc8f9e6153862594b53b251d0bcd742 | C++ | juseqidai/Make-Wearable-Electronics | /MWE_Ch06_AnalogInput/MWE_Ch06_AnalogInput.ino | UTF-8 | 522 | 3.140625 | 3 | [] | no_license | /*
Make: Wearable Electronics
Analog Input example
*/
// initialize variable for light sensor reading
int lightSensorValue = 0;
// initialize variable for light sensor pin
int lightSensorPin = A2;
void setup() {
// initialize serial communication at 9600 bps
Serial.begin(9600);
}
void loop() {
// read pin and store value in a variable:
lightSensorValue = analogRead(lightSensorPin);
// print the light sensor value:
Serial.println(lightSensorValue);
// delay between readings:
delay(100);
}
| true |
85f0a2ace55deb0d8a1630ac030bcb3f9e85f158 | C++ | RobbeVG/SeaCore | /SeaCore/Source/Resources/Loaders/FontManager.cpp | UTF-8 | 707 | 2.5625 | 3 | [] | no_license | #include "SeaCore_pch.h"
#include "FontManager.h"
#include <SDL_ttf.h>
FontManager::FontManager()
: m_FontSize(12)
{
// load support for fonts, this takes a while!
if (TTF_Init() != 0)
throw std::runtime_error(std::string("Failed to load support for fonts: ") + SDL_GetError());
}
FontManager::~FontManager()
{
for (const std::pair<size_t, sea_core::Font*> reference : m_References)
{
TTF_CloseFont(reference.second->GetFont());
}
}
sea_core::Font* FontManager::LoadContent(const std::string& path)
{
sea_core::Font* pFont = new sea_core::Font(path, m_FontSize);
if (pFont == nullptr)
{
throw std::runtime_error(std::string("Failed to load font: ") + SDL_GetError());
}
return pFont;
}
| true |
e0bc119e4eb9868b5f17729f2c5ea510660afd09 | C++ | neattools/neattools | /util/JDate.h | UTF-8 | 2,381 | 2.546875 | 3 | [] | no_license | #if !defined( _JDate_h )
#define _JDate_h
#include "JObject.h"
#include "JDate.hpp"
class
#include "JBase.hpp"
JDate : public JObject {
protected:
virtual void writeContent(class JOutputStream& os);
virtual void readContent(class JDictionary& dict);
public:
static double constant;
static char* weekTag[];
static char* monthTag[];
static JString toJString(double value);
static JDate parse(JString str);
static double DtoR(int year, int month, int date, int hour, int min, int sec, int msec);
static void RtoD(double value, int& year, int& month, int& date,
int& hour, int& min, int& sec, int& msec, int& yday, int& wday);
virtual const char* className() const;
virtual int hashCode() const;
virtual JObject* clone() const;
virtual int compareTo(const JObject& s) const;
JDate();
JDate(int year, int month, int date,
int hour = 0, int min = 0, int sec = 0, int msec = 0);
JDate(double rval, int msec = 0);
JDate(JString str);
operator double&();
JString toJString();
int getYear();
void setYear(int year);
int getMonth(); /* 0-11 */
void setMonth(int month);
int getDate(); /* 1-31 */
void setDate(int date);
int getYDay(); /* 0-365 */
int getWDay(); /* 0-6 */
int getHours();
void setHours(int hours);
int getMinutes();
void setMinutes(int minutes);
int getSeconds();
void setSeconds(int seconds);
int getMillis();
void setMillis(int millis);
double getTime();
void setTime(double time);
int getITime();
void setITime(int time);
int getTimezone();
int getTimeDelta();
int isDST();
JDate UTC();
private:
double value;
int tm_msec; /* mili-seconds */
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
int tm_tDelta;
boolean valueValid, expanded;
void expand();
void compute();
int compareTime(SYSTEMTIME t);
};
#endif
| true |
7e1684a9eec876753bfb59109792cb0b8621f0bd | C++ | leejinho/c-language | /private/test.cpp | UTF-8 | 236 | 2.90625 | 3 | [] | no_license | #include <stdio.h>
void main()
{
int time, fare;
printf("주차시간(분)을 입력하고 Enter>");
scanf("%d", &time);
if(time%10==0)
{
fare=(time/10)*1000;
}
else
{
fare=(time/10+1)*1000;
}
printf("주차요금= %d원",fare);
}
| true |
9eb0fa5d2fa2fd70a107b5b22c0c2f47f5b13a0a | C++ | polezhaev-ds/made_2019_cpp | /04/Matrix.h | UTF-8 | 2,880 | 3.09375 | 3 | [] | no_license | //
// Created by admin2 on 08.11.2019.
//
#ifndef HW4_MATRIX_H
#define HW4_MATRIX_H
#include <cstdlib>
#include <stdexcept>
#include <cstring>
#include <vector>
#include <iostream>
class Matrix {
public:
class MatrixRowProxy {
public:
const int& operator [] (std::size_t column) const {
return matrix.getValueBy(row, column);
}
int& operator [] (std::size_t column) {
return matrix.getValueBy(row, column);
}
private:
Matrix& matrix;
std::size_t row;
explicit MatrixRowProxy(Matrix& matrix, std::size_t row):
matrix(matrix),
row(row)
{
}
explicit MatrixRowProxy(const Matrix& matrix, std::size_t row):
MatrixRowProxy(const_cast<Matrix&>(matrix), row)
{
}
MatrixRowProxy(const MatrixRowProxy& matrixRow) = default;
MatrixRowProxy(MatrixRowProxy&& matrixRow) noexcept = default;
friend Matrix;
};
explicit Matrix(const std::vector<std::vector<int>>& vector2d);
explicit Matrix(std::size_t rows = 0, std::size_t columns = 0):
rows(rows),
columns(columns),
values(nullptr)
{
AllocateMemory();
}
Matrix(const Matrix& matrix):
rows(matrix.rows),
columns(matrix.columns),
values(nullptr)
{
AllocateMemory();
CopyFrom(matrix.values);
}
Matrix(Matrix&& matrix) noexcept:
rows(matrix.rows),
columns(matrix.columns),
values(matrix.values)
{
matrix.Reset();
}
~Matrix() {
FreeMemory();
}
[[nodiscard]] std::size_t getRows() const {
return rows;
}
[[nodiscard]] std::size_t getColumns() const {
return columns;
}
[[nodiscard]] const int& getValueBy(std::size_t row, std::size_t column) const;
int& getValueBy(std::size_t row, std::size_t column);
MatrixRowProxy operator [] (std::size_t row) {
return MatrixRowProxy(*this, row);
}
MatrixRowProxy operator [] (std::size_t row) const {
return MatrixRowProxy(*this, row);
}
bool operator == (const Matrix& matrix) const;
bool operator != (const Matrix& matrix) const;
Matrix& operator = (const Matrix& matrix);
Matrix& operator = (Matrix&& matrix) noexcept;
Matrix operator * (int multiplier) const;
Matrix& operator *= (int multiplier);
private:
size_t rows;
size_t columns;
int** values;
void AllocateMemory();
template <typename T>
void CopyFrom(const T& data);
void FreeMemory();
void Reset();
};
Matrix operator * (int multiplier, const Matrix& b);
#endif //HW4_MATRIX_H
| true |
af8c856f5b7534787af63b366c91a95e32b8b6af | C++ | casaletto/alby.bigmath | /albybigmath/include/albybigmath/pi.h | UTF-8 | 1,732 | 2.859375 | 3 | [
"MIT"
] | permissive | #pragma once
namespace alby::bigmath
{
class pi
{
protected:
class nonic_term_t
{
public:
R a ;
R r ;
R s ;
R t ;
R u ;
R v ;
R w ;
virtual ~nonic_term_t()
{}
nonic_term_t()
{}
nonic_term_t( const nonic_term_t& rhs )
{
*this = rhs ;
}
nonic_term_t& operator=( const nonic_term_t& rhs )
{
if ( this != &rhs )
{
a = rhs.a ;
r = rhs.r ;
s = rhs.s ;
t = rhs.t ;
u = rhs.u ;
v = rhs.v ;
w = rhs.w ;
}
return *this ;
}
std::string toString()
{
auto dp = 20 ;
return stringcat
(
"t = ", t.toDecimalPlaces ( dp ), "\n",
"u = ", u.toDecimalPlaces ( dp ), "\n",
"v = ", v.toDecimalPlaces ( dp ), "\n",
"w = ", w.toDecimalPlaces ( dp ), "\n",
"a = ", a.toDecimalPlaces ( dp ), "\n",
"s = ", s.toDecimalPlaces ( dp ), "\n",
"r = ", r.toDecimalPlaces ( dp ), "\n"
"pi = ", a.inv().toDecimalPlaces( dp ), "\n"
) ;
}
} ;
protected:
static R nilakantha_term( unsigned long n ) ;
static R ramanujan_term ( unsigned long n, std::map<unsigned long, R>& factorial ) ;
static nonic_term_t nonic_term ( unsigned long n, nonic_term_t& prev ) ;
public:
virtual ~pi() ;
pi() ;
pi( const pi& rhs ) ;
pi& operator=( const pi& rhs ) ;
static R nilakantha( unsigned long n ) ;
static R ramanujan ( unsigned long n ) ;
static R nonic ( unsigned long n ) ;
} ;
}
| true |
8d89a9f4e96b0a2beac95370fa09a4d43bca7da4 | C++ | kamyu104/LeetCode-Solutions | /C++/contains-duplicate-iii.cpp | UTF-8 | 928 | 2.984375 | 3 | [
"MIT"
] | permissive | // Time: O(nlogk)
// Space: O(k)
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (k < 0 || t < 0) {
return false;
}
queue<int64_t> window;
multiset<int64_t> bst;
for (int i = 0; i < nums.size(); ++i) {
// Only keep at most k elements.
if (bst.size() > k) {
int num = window.front();
window.pop();
bst.erase(bst.find(num));
}
// Every search costs time: O(logk).
const auto it = bst.lower_bound(static_cast<int64_t>(nums[i]) - t);
if (it == bst.cend() || (*it - nums[i]) > t) {
// Not found.
window.emplace(nums[i]);
bst.emplace(nums[i]);
} else {
return true;
}
}
return false;
}
};
| true |
fb46dc419bc86db3796c866d8361a5366e376d7b | C++ | joabda/Robot | /Project/code/codeEmeteur/communication.h | UTF-8 | 2,033 | 3 | 3 | [
"MIT"
] | permissive | /*
* Classe permettant de faire communiquer nos 2 robots, soit en mode émission soit en mode réception.
*
* En mode emission : appeler getPressionsBouton(), puis emettreSignal().
* 1) Détection du nombre de pressions du bouton
* 2) Emission selon SIRC :
* - signal d'initialisation : une émission de 2.4ms, puis un blanc de 0.6 ms
* - emission de la commande : 7 bits, un 1 correspond à une émission de 1.2ms, un 0 correspond à une émission de 0.6ms - si on a appuyé 1 fois sur le bouton, on envoie 1000 0000, 2 on envoie 010 0000...
* - emission de l'adresse : 5 bits, un 1 correspond à une émission de 1.2ms, un 0 correspond à une émission de 0.6ms - note : l'adresse est toujours la même à savoir 1, donc on transmettra toujours 1 0000
*
*
* Exemple de 5 appuis sur le bouton :
* Après sequenceInit, on enverra 1010 0001 0000 (12 bits)
* * Note : ici on utilise le transmetteur uniquement en SIRC 12 bits car pas besoin de +, mais il existe aussi des versions 15 et 20 bits
* Reception sur PORTA 1 (1 sur carte)
* Se référer au pdf "SIRC.pdf"
*
* Ecole Polytechnique de Montreal
* Departement de genie informatique
* Cours inf1900
*
* Joe Abdo, Mathurin Critin, Teo Quiquempoix et Philippe Babin,
* 2019
*
* Code qui n'est sous aucune license.
*
*/
#ifndef COMMUNICATION_H
#define COMMUNICATION_H
#ifndef F_CPU
#define F_CPU 8000000
#endif
#include <util/delay.h>
#include "minuterie.h"
enum ER {emission = 0, reception = 1};
class Communication
{
public:
Communication(const ER& type);
void setCommande(uint8_t nbPressionsTest);
void getPressionsBouton();
void emettreSignal();
uint16_t getSignal();
private:
ER type_;
uint8_t commande_[7];
uint8_t adresse_[5]; // l'adresse est toujours la même
uint8_t reception_[12];
void sequenceInit() const;
void emettre_0() const;
void emettre_1() const;
void emettreCommande();
void emettreAdresse();
};
void resetVaribles();
#endif | true |
f0160797657d8548027ad693f3632f61e4916cd9 | C++ | Parfenoff/HW_cpp | /#SimpleCode_lessons/switch.cpp | UTF-8 | 308 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
setlocale(LC_ALL,"RU");
int a;
cin >> a;
switch(a) {
case 1:
cout << "Вы ввели 1" << endl;
break;
case 2:
cout << "Вы ввели 2" << endl;
break;
default:
cout << "Я не знаю этого числа!" << endl;
break;
}
}
| true |
a2436c8dc5a7c1f6e9d963801cf83e7e4815c78a | C++ | gregshin/workout-tracker | /Cardio.h | UTF-8 | 598 | 3.03125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "BaseExercise.h"
// abstract class definition for Cardio. Inherits from BaseExercise
class Cardio : public BaseExercise
{
public:
// Cardio class constructor
Cardio(double time, double dist, double lbs);
// procedure to set distance
void setDistance(double dist);
// procedure to set speed
void setSpeed(double rate);
// function to return distance
double getDistance();
// function to return speed
double getSpeed();
// virtual fuction for calculating rate
virtual void calcSpeed() = 0;
private:
// provate data memebers
double distance;
double speed;
}; | true |
f50a6292174419318f353edc73946b2ed58c6640 | C++ | mukhoplus/Mukho | /source/repos/DataStructure_UnsortedArrayList/UnsortedArrayList.cpp | UTF-8 | 2,175 | 2.96875 | 3 | [] | no_license | #include "UnsortedArrayList.h"
UnsortedArrayList::UnsortedArrayList()
{
ArrayList = new UserType[MAXSIZE];
Length = 0;
ResetIterator();
}
UnsortedArrayList::~UnsortedArrayList()
{
if (ArrayList)
delete[] ArrayList;
}
void UnsortedArrayList::MakeEmpty()
{
Length = 0;
}
int UnsortedArrayList::GetLength()
{
return Length;
}
bool UnsortedArrayList::isFull()
{
if (Length > MAXSIZE - 1)
return true;
else
return false;
}
int UnsortedArrayList::Insert(UserType user)
{
if (Length == 0)
{
ArrayList[Length] = user;
}
else
{
if (Length >= MAXSIZE)
{
MAXSIZE++;
UserType* temp;
temp = new UserType[Length];
for (int i = 0; i < Length; i++)
temp[i] = ArrayList[i];
ArrayList = new UserType[Length + 1];
for (int i = 0; i < Length; i++)
ArrayList[i] = temp[i];
delete[] temp;
}
ArrayList[Length] = user;
}
Length++;
return 1;
}
int UnsortedArrayList::Delete(UserType user)
{
for (int i = 0; i < Length; i++)
{
if (ArrayList[i].GetId() == user.GetId())
{
for (int j = i; j < Length - 1; j++)
ArrayList[j] = ArrayList[j + 1];
Length--;
return 1;
}
}
return 0;
}
int UnsortedArrayList::Update(UserType user)
{
for (int i = 0; i < Length; i++)
{
if (ArrayList[i].GetId() == user.GetId())
{
ArrayList[i].SetAllFromKB();
return 1;
}
}
return 0;
}
int UnsortedArrayList::Get(UserType& user)
{
for (int i = 0; i < Length; i++)
{
if (ArrayList[i].GetId() == user.GetId())
{
user = ArrayList[i];
return 1;
}
}
return 0;
}
void UnsortedArrayList::ResetIterator()
{
CurPointer = -1;
}
int UnsortedArrayList::GetNextUser(UserType& user)
{
CurPointer++;
if (CurPointer == MAXSIZE)
return -1;
user = ArrayList[CurPointer];
return CurPointer;
}
int UnsortedArrayList::GetByBinarySearch(UserType& user)
{
int first = 0;
int last = Length - 1;
bool found = false;
while (first <= last && !found)
{
int mid = (first + last) / 2;
switch (user.ConpareById(ArrayList[mid]))
{
case LESS:
last = mid - 1;
break;
case GREATER:
first = mid + 1;
break;
case EQUAL:
user = ArrayList[mid];
found = 1;
return found;
break;
}
}
return 0;
} | true |
9d94b6cd05c7ff88d1b62287b78e195b1a5a240b | C++ | The-atama/Library | /String/wavelet_matrix.cpp | UTF-8 | 11,024 | 2.921875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct FullyIndexableDictionary {
static const int smallBlockSize = 16;
static const int bigBlockSize = 1024;
static constexpr int smallInBig = bigBlockSize / smallBlockSize;
vector<uint16_t> bit; // raw data
vector<uint32_t> bigBlockAcc; // not succinct, optimal : 22 bit
vector<vector<uint16_t>> smallBlockAcc; // not succinct, optimal : 10 bit
int length;
int bigBlockNum;
int smallBlockNum;
bool is_built;
FullyIndexableDictionary() {}
FullyIndexableDictionary(int len) : length(len), is_built(false) {
bigBlockNum = (length + bigBlockSize - 1) / bigBlockSize;
smallBlockNum = bigBlockNum * smallInBig;
bit.assign(smallBlockNum, 0);
bigBlockAcc.assign(bigBlockNum + 1, 0);
smallBlockAcc.assign(bigBlockNum, vector<uint16_t>(smallInBig, 0));
}
void set(int id) {
int sid = id / smallBlockSize;
int offset = id % smallBlockSize;
bit[sid] |= (uint16_t)(1u << offset);
}
void unset(int id) {
int sid = id / smallBlockSize;
int offset = id % smallBlockSize;
bit[sid] &= (uint16_t)(~(1u << offset));
}
bool operator[](int id) {
int sid = id / smallBlockSize;
int offset = id % smallBlockSize;
return (bool)((bit[sid] >> offset) & 1u);
}
void build() {
is_built = true;
bigBlockAcc[0] = 0;
for (int i = 0; i + 1 < bigBlockAcc.size(); i++) {
smallBlockAcc[i][0] = 0;
for (int j = 0; j + 1 < smallBlockAcc[i].size(); j++) {
smallBlockAcc[i][j + 1] =
smallBlockAcc[i][j] + __builtin_popcount(bit[i * smallInBig + j]);
}
bigBlockAcc[i + 1] = bigBlockAcc[i] + smallBlockAcc[i].back() +
__builtin_popcount(bit[(i + 1) * smallInBig - 1]);
}
}
int rank(int id) const {
assert(is_built);
int bid = id / bigBlockSize;
int sid = (id % bigBlockSize) / smallBlockSize;
int offset = id % smallBlockSize;
uint16_t rem = bit[bid * smallInBig + sid] & ((1u << offset) - 1u);
return bigBlockAcc[bid] + smallBlockAcc[bid][sid] + __builtin_popcount(rem);
}
// number of b in [0,id)
int rank(int b, int id) const {
if (b == 1)
return rank(id);
else
return id - rank(id);
}
// return the position of num-th b
// namely, the minimum id that holds rank(b,id+1) = num+1
// attention : num is 0-indexed
int select(int b, int num) const {
assert(is_built);
if (num < 0 || num >= rank(b, length)) return -1;
int l = 0, r = length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (rank(b, mid) >= num + 1)
r = mid;
else
l = mid;
}
return l;
}
int select(int num) { return select(1, num); }
int select(int b, int num, int l) { return select(b, num + rank(b, l)); }
};
// T must be unsigned type
template <class T, int LOG>
struct WaveletMatrix {
int length;
FullyIndexableDictionary mat[LOG];
int zeroNum[LOG];
int buf1[LOG], buf2[LOG];
WaveletMatrix(vector<T> data) {
length = data.size();
vector<T> lv(length), rv(length);
for (int i = 0; i < LOG; i++) {
mat[i] = FullyIndexableDictionary(length + 1);
int lp = 0, rp = 0;
for (int j = 0; j < length; j++) {
int bit = (data[j] >> (LOG - i - 1)) & (T(1));
if (bit == 1) {
rv[rp++] = data[j];
mat[i].set(j);
} else {
lv[lp++] = data[j];
}
}
mat[i].build();
zeroNum[i] = lp;
// cout << lp << ' ' << rp << endl;
for (int j = 0; j < rp; j++) lv[lp + j] = rv[j];
swap(data, lv);
/*cout << zeroNum[i] << endl;
for(int j=0;j<length;j++){
cout << data[j] << ' ';
}
cout << endl; */
}
}
// get id-th element
T access(int id) {
T res = T(0);
for (int i = 0; i < LOG; i++) {
int bit = mat[i][id];
res = (res << 1) | bit;
id = mat[i].rank(bit, id) + zeroNum[i] * bit;
}
return res;
}
// number of v in [0,id)
int rank(T v, int id) {
int l = 0, r = id;
for (int i = 0; i < LOG; i++) {
buf1[i] = l;
buf2[i] = r;
int bit = (v >> (LOG - i - 1)) & (T(1));
l = mat[i].rank(bit, l) + zeroNum[i] * bit;
r = mat[i].rank(bit, r) + zeroNum[i] * bit;
}
return r - l;
}
// position of num-th v
// id is 0-indexed
int select(T v, int num) {
rank(v, length); // store path in buf
for (int i = LOG - 1; i >= 0; i--) {
int bit = (v >> (LOG - i - 1)) & (T(1));
num = mat[i].select(bit, num, buf1[i]);
if (num >= buf2[i] || num < 0) return -1;
num -= buf1[i];
}
return num;
}
int select(T v, int k, int l) { return select(v, k + rank(v, l)); }
// k-th largest value
T quantile(int l, int r, int k) {
if (r - l <= k || k < 0) return -1;
T res = T(0);
for (int i = 0; i < LOG; i++) {
int lp = mat[i].rank(1, l);
int rp = mat[i].rank(1, r);
if (rp - lp > k) {
l = lp + zeroNum[i];
r = rp + zeroNum[i];
res |= (T(1) << (LOG - i - 1));
} else {
k -= (rp - lp);
l -= lp;
r -= rp;
}
}
assert(k == 0);
return res;
}
T kth_max(int l, int r, int k) { return quantile(l, r, k); }
T kth_min(int l, int r, int k) { return quantile(l, r, r - l - 1 - k); }
// auxiliary function for range_freq
int freq_dfs(int depth, int l, int r, T val, T low, T high) {
if (l == r) return 0;
if (depth == LOG) return (low <= val && val < high) ? r - l : 0;
T right_val = ((T(1) << (LOG - depth - 1)) | val);
T right_most = (((T(1) << (LOG - depth - 1)) - 1) | right_val);
if (right_most < low || high <= val) return 0;
if (low <= val && right_most < high) return r - l;
int lp = mat[depth].rank(1, l);
int rp = mat[depth].rank(1, r);
int lch = freq_dfs(depth + 1, l - lp, r - rp, val, low, high);
int rch = freq_dfs(depth + 1, lp + zeroNum[depth], rp + zeroNum[depth],
right_val, low, high);
return lch + rch;
}
// occurence of value of [low,high) in [l,r)
int rangefreq(int l, int r, T low, T high) {
return freq_dfs(0, l, r, T(0), low, high);
}
pair<int, int> less_equal(int l, int r, T v) {
int lessNum = 0;
for (int i = 0; i < LOG; i++) {
buf1[i] = l;
buf2[i] = r;
int bit = (v >> (LOG - i - 1)) & (T(1));
if (bit) lessNum += (r - mat[i].rank(bit, r)) - (l - mat[i].rank(bit, l));
l = mat[i].rank(bit, l) + zeroNum[i] * bit;
r = mat[i].rank(bit, r) + zeroNum[i] * bit;
}
return make_pair(lessNum, r - l);
}
int less_freq(int l, int r, T v) { return less_equal(l, r, v).first; }
int less_equal_freq(int l, int r, T v) {
pair<int, int> res = less_equal(l, r, v);
return res.first + res.second;
}
int next_value(int l, int r, T v) {
int k = less_equal_freq(l, r, v);
if (k == r - l)
return -1;
else
return kth_min(l, r, k);
}
int prev_value(int l, int r, T v) {
int k = less_freq(l, r, v);
if (k == 0)
return -1;
else
return kth_min(l, r, k - 1);
}
};
struct SuffixArray {
string s;
vector<int> sa;
vector<int> rank;
vector<int> lcp;
explicit SuffixArray(string s) : s(s) {
int n = s.size();
sa.resize(n + 1);
rank.resize(n + 1);
vector<int> tmp(n + 1);
for (int i = 0; i <= n; i++) {
rank[i] = (i < n) ? s[i] : -1;
sa[i] = i;
}
for (int k = 1; k <= n; k *= 2) {
auto compare_sa = [&](const int &i, const int &j) {
if (rank[i] != rank[j])
return rank[i] < rank[j];
else {
int ri = (i + k <= s.size()) ? rank[i + k] : -1;
int rj = (j + k <= s.size()) ? rank[j + k] : -1;
return ri < rj;
}
};
sort(sa.begin(), sa.end(), compare_sa);
tmp[sa[0]] = 0;
for (int i = 1; i <= n; i++)
tmp[sa[i]] = tmp[sa[i - 1]] + (compare_sa(sa[i - 1], sa[i]) ? 1 : 0);
for (int i = 0; i <= n; i++) rank[i] = tmp[i];
}
}
size_t size() const { return s.size(); }
int operator[](int id) const { return sa[id]; }
bool contain(string t) {
int l = 0, r = s.size() + 1;
while (r - l > 1) {
int mid = (l + r) / 2;
if (s.compare(sa[mid], t.size(), t) < 0) {
l = mid;
} else {
r = mid;
}
}
return s.compare(sa[r], t.size(), t) == 0;
}
};
struct LongestCommonPrefix {
const SuffixArray &sa;
vector<int> lcp, rank;
explicit LongestCommonPrefix(const SuffixArray &sa) : sa(sa) {
int n = sa.size();
lcp.resize(sa.size() + 1);
rank.resize(sa.size() + 1);
for (int i = 0; i <= sa.size(); i++) { rank[sa[i]] = i; }
int h = 0;
lcp[0] = 0;
for (int i = 0; i < sa.size(); i++) {
int j = sa[rank[i] - 1];
if (h > 0) h--;
for (; i + h < n && j + h < n; h++)
if (sa.s[i + h] != sa.s[j + h]) break;
lcp[rank[i] - 1] = h;
}
}
int operator[](int id) const {
assert(id >= 0 && id < lcp.size());
return lcp[id];
}
};
struct BurrowsWheelerTransform {
vector<char> bwt;
const SuffixArray &sa;
explicit BurrowsWheelerTransform(const SuffixArray &sa) : sa(sa) {
bwt.resize(sa.size() + 1);
for (int i = 0; i < bwt.size(); i++) {
if (sa[i] == 0)
bwt[i] = (char)7; // dummy
else
bwt[i] = sa.s[sa[i] - 1];
}
}
char operator[](int id) const { return bwt[id]; }
size_t size() { return bwt.size(); }
};
pair<int, int> searchFMIndex(SuffixArray &sa,
WaveletMatrix<unsigned char, 8> &wm,
vector<int> &lessCount, string t) {
int l = 0, r = sa.size() + 1; // because of dummy character
for (int i = 0; i < t.size(); i++) {
unsigned char c = t[t.size() - 1 - i];
// cout << wm.rank(c,l) << ' ' << wm.rank(c,r) << endl;
l = lessCount[c] + wm.rank(c, l);
r = lessCount[c] + wm.rank(c, r);
// cout << "wavelet " << l << ' ' << r << endl;
if (l >= r) return make_pair(-1, -1);
}
return make_pair(l, r - 1);
}
pair<int, int> contain(string s, string t) {
SuffixArray sa(s);
BurrowsWheelerTransform bwt(sa);
vector<unsigned char> bw;
for (int i = 0; i < bwt.size(); i++) { bw.push_back((unsigned char)bwt[i]); }
WaveletMatrix<unsigned char, 8> wm(bw);
s += ((char)7); // dummy
vector<int> lessCount(256);
for (int i = 0; i < s.size(); i++) { lessCount[s[i] + 1]++; }
for (int i = 1; i < lessCount.size(); i++) {
lessCount[i] += lessCount[i - 1];
}
return searchFMIndex(sa, wm, lessCount, t);
}
int main() {
FullyIndexableDictionary FID(10000);
FID.set(12);
FID.set(21);
FID.set(33);
FID.build();
cout << FID.select(1, 2) << endl;
string s = "abracadabra";
vector<unsigned char> v;
for (int i = 0; i < s.size(); i++) v.push_back((unsigned char)s[i]);
WaveletMatrix<unsigned char, 8> wm(v);
cout << wm.rangefreq(2, 8, 'b', 'r') << endl;
cout << contain("abra", "br").first << endl;
return 0;
}
| true |
b8113616298933336f71a3892e23fcd11f1bbfe0 | C++ | sunmangul/TIL | /C++/basic/code/06auto.cpp | UTF-8 | 322 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
auto add(int x, int y)
{
return x+y;
}
int main()
{
auto num1 = 5.1234;
cout << "num1(" << num1 << ")의 타입은 " << typeid(num1).name() << endl;
auto sum = add(5, 6);
cout << "sum("<< sum << ")의 타입은 " << typeid(sum).name() << endl;
return 0;
} | true |
80908b6bbff38249dfd1638168b44f386c75c15d | C++ | amjadtbssm/TGE | /InverseWayLiberation/src/Entities/EntityManager.h | UTF-8 | 1,744 | 2.78125 | 3 | [] | no_license | #pragma once
#include <boost/bimap.hpp>
#include <SFML/Graphics.hpp>
#include "../Tools/Singleton.h"
class Entity;
class EntityManager : public Singleton<EntityManager>, public sf::Drawable
{
protected:
friend class Singleton<EntityManager>;
// Ctor & dtor
EntityManager();
virtual ~EntityManager();
public:
// Mise à jour
void Update();
// Gestion des Entities
void RegisterEntity(Entity *entity); // Les Entities s'enregistrent toutes seules
void DestroyEntity(Entity *entity);
void DestroyAllEntities();
void SortByLayer();
// Accès aux Entities
Entity* GetEntity(unsigned int id);
Entity* GetEntity(const std::string &name);
std::list<Entity*>& GetEntities();
const std::list<Entity*>& GetEntities() const;
// Gestion des IDs
// Le système actuel garanti qu'il n'y a pas deux fois le même ID lors d'une session
// sauf si DestroyAllEntities() est appelé
unsigned int GetNewID();
void RemoveID(unsigned int id);
// Gestion des noms
bool Name(const std::string &name, Entity *entity); // true if already exists
void Anonymize(const std::string &name);
std::string GetName(Entity *const entity) const;
protected:
// Pour le rendu
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
// Changement d'ID pendant le chargement de niveau
friend class LevelLoader;
void ChangeID(unsigned int id, unsigned int newID);
private:
// Liste des Entities
std::list<Entity*> mEntities;
// Liste des IDs
std::set<unsigned int> mIDs;
unsigned int mLastId;
// Liste des noms
typedef boost::bimap<std::string, Entity*> name_bimap;
typedef name_bimap::value_type name_bimap_position;
name_bimap mNames;
}; | true |
23168d4e15daffe353c504af25840086a5113cce | C++ | ElliottWaterman/Individual-Project | /ArduinoCode/Examples/DS3231RTC/SetupDateTime.ino | UTF-8 | 3,275 | 3.078125 | 3 | [] | no_license | /**
Author: Elliott Waterman
Date: 09/01/2019
Description: Program to setup the date and time
of an RTC module.
Hardware:
Arduino Uno, DS3231 RTC.
Connect RTC SDA to Arduino pin A4.
Connect RTC SCL to Arduino pin A5.
*/
/* INCLUDES */
#include <DS3232RTC.h> //RTC library used to control the RTC module
#include <Streaming.h> //Used to make print statements easier to write
/* DEFINES */
/* INSTANTIATE LIBRARIES */
/* VARIABLES */
void setup() {
Serial.begin(9600); //Start serial communication
// Initialise the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
RTC.alarm(ALARM_1);
RTC.alarm(ALARM_2);
RTC.alarmInterrupt(ALARM_1, false);
RTC.alarmInterrupt(ALARM_2, false);
RTC.squareWave(SQWAVE_NONE);
/* METHOD 1*/
// Serial.println("Method 1: ");
// // Set date and time of the RTC module
// tmElements_t tm;
// tm.Hour = 12;
// tm.Minute = 00;
// tm.Second = 00;
// tm.Day = 14;
// tm.Month = 1;
// tm.Year = 2019 - 1970; //tmElements_t.Year is offset from 1970
// RTC.write(tm); //Set the RTC from the tm structure
/* METHOD 2 */
Serial.println("Method 2: ");
time_t t = processSyncMessage();
if (t != 0) {
// Set the RTC and the system time to the received value
RTC.set(t);
setTime(t);
}
setSyncProvider(RTC.get); // the function to get the time from the RTC
if (timeStatus() != timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
}
void loop() {
Serial.println("Loop: ");
// Using time_t structure
time_t checkTimeT;
checkTimeT = RTC.get(); //Get the current time of the RTC
printDateTime(checkTimeT);
// Using tmElements_t structure
tmElements_t checkTimeTmElement;
RTC.read(checkTimeTmElement); //Read the current time of the RTC
printDateTimeTmElement(checkTimeTmElement);
delay(1000);
}
/* code to process time sync messages from the serial port */
#define TIME_HEADER "T" // Header tag for serial time sync message
unsigned long processSyncMessage() {
unsigned long pctime = 0L;
const unsigned long DEFAULT_TIME = 1549666800; // Fri, 08 Feb 2019 23:00:00 GMT
if(Serial.find(TIME_HEADER)) {
pctime = Serial.parseInt();
return pctime;
if (pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
pctime = 0L; // return 0 to indicate that the time is not valid
}
}
return pctime;
}
void printDateTime(time_t t)
{
Serial << ((day(t) < 10) ? "0" : "") << _DEC(day(t));
Serial << monthShortStr(month(t)) << _DEC(year(t)) << ' ';
Serial << ((hour(t) < 10) ? "0" : "") << _DEC(hour(t)) << ':';
Serial << ((minute(t) < 10) ? "0" : "") << _DEC(minute(t)) << ':';
Serial << ((second(t) < 10) ? "0" : "") << _DEC(second(t));
}
void printDateTimeTmElement(tmElements_t t)
{
Serial.print(t.Day, DEC);
Serial.print(' ');
Serial.print(t.Month, DEC);
Serial.print(' ');
Serial.print((t.Year + 1970), DEC);
Serial.print(t.Hour, DEC);
Serial.print(':');
Serial.print(t.Minute, DEC);
Serial.print(':');
Serial.println(t.Second, DEC);
}
| true |
a2df18ec798afd9ef68f95f548ac7af169e72fa4 | C++ | WhiteNeo135/SIAOD_Baloons | /main.cpp | UTF-8 | 992 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include "Ballon.h"
using namespace std;
int main()
{
srand(time(nullptr));
int amount;
int arrow;
int count=0;
int temp=0;
vector<ballon> ballons;
cout << "Введите кол-во шаров"<< endl;
cin >> amount;
for (int i=0; i<amount; i++)
{
ballons.push_back(ballon::generator());
}
ballon::sort(ballons);
cout<< "Сгенерированные шары: ";
for (auto i: ballons)
cout << i.getStart() <<" "<< i.getEnd()<< "; ";
cout<<endl;
while(temp!=ballons.size()-1)
{
arrow = ballons[temp].getEnd();
while(arrow>=ballons[temp].getStart() && arrow<=ballons[temp].getEnd())
{
temp++;
if (temp==ballons.size()-1)
break;
}
count++;
}
cout<<"Минимальное еоличество стрел: "<< count;
return 0;
}
| true |
c482ab51a1bda5ee5f418c1012e7985cb32299c3 | C++ | asifikbalpro/Binary-Search-Trees | /main.cpp | UTF-8 | 1,077 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include "src/BST.h" /// including a .cpp file ????
using namespace std;
int main() {
int TreeKeys[] = {50, 76, 21, 4, 32, 64, 15, 52, 14, 100, 83, 2, 3, 70, 87, 80, 1};
BST myTree;
int input = 0;
cout << "Printing the tree in order" << endl;
cout << "Before Adding Number " << endl;
myTree.PrintInOrder();
for (int i = 0; i < 17; ++i) {
myTree.AddLeaf(TreeKeys[i]);
}
cout << "Printing the tree in order" << endl;
cout << "After Adding Number " << endl;
myTree.PrintInOrder();
myTree.PrintChildren(myTree.RetrunRootKey());
cout << "the smallest value is in the tree " << myTree.FindSmallest() << endl;
cout << "Enter a key value to delete. Enter -1 to stop to process" << endl;
while(input != -1){
cout << "delete Node: ";
cin >> input;
{
if(input != -1){
cout << endl;
myTree.RemoveNode(input);
myTree.PrintInOrder();
cout << endl;
}
}
}
return 0;
} | true |
9ad96711d050839a31bfdb84ded46598c0cfbf52 | C++ | ajayhegde96/Competitive-Coding | /DA Lab/part_test.cpp | UTF-8 | 931 | 3.21875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int sum(int arr[],int n)
{
int sum =0;
for(int i=0;i<n;i++)
sum+=arr[i];
return sum;
}
void display(int arr[] ,int c)
{
int j;
for(j=0;j<c;j++)
if(arr[j])
printf("%d ",arr[j]);
printf("\n");
}
int main(int argc, char const *argv[])
{
//int set[]={1,2,3,4,5,9};
int set[] = {1,2,3,5,4,9};
int size = sizeof(set)/sizeof(int);
int psize = pow(2,size);
int i,j;
int s = sum(set,size);
if(s%2!=0)
printf("Partition not possible\n");
else
{
int part_sum = s/2;
int pow_set[psize][size]={0};
for(i=0;i<psize;i++)
{
for(j=0;j<size;j++)
{
if(i & (1<<j))
pow_set[i][j] = set[j];
}
int d = psize-i-1;
if(sum(pow_set[d],size)==part_sum)
{
printf("SUM = %d\n",sum(pow_set[d],size));
printf("SET 1\n");
display(pow_set[d],size);
printf("SET 2\n");
display(pow_set[i],size);
}
}
}
return 0;
}
| true |
9a1b9d5c71e73c1c617eb3144666663f49135c9c | C++ | FiftyBillion/C-plus-plus | /HW3-5/HW3-5/HW3-5.cpp | UTF-8 | 1,401 | 3.71875 | 4 | [] | no_license | // HW3-5 Mobile Service Provider
// this program calculate the amount that the user should pay for different data
// created by Po-I Wu on 01/29/2018
#include <iostream>
using namespace std;
int main()
{
char choice;
double min;
cout << "Please choice the package you purchased.\n" << endl;
cout << "Package A: For $39.99 per month 450 minutes are provided. Additional minutes are $ 0.45 per minute." << endl;
cout << "Package B: For $59.99 per month 900 minutes are provided. Additional minutes are $ 0.40 per minute." << endl;
cout << "Package C: For $69.99 per month unlimited minutes provided." << endl;
cout << "Your choice (Enter A, B, C): ";
cin >> choice;
switch (choice)
{
case 'a':
case 'A':
// base $39.99
cout << "Please enter how many minute you used: ";
cin >> min;
if (min > 450)
cout << "Total Bill: $ " << 39.99 + 0.45 * (min - 450) << endl;
else
cout << "Total Bill: $ " << 39.99 << endl;
break;
case 'b':
case 'B':
// base $59.99
cout << "Please enter how many minute you used: ";
cin >> min;
if (min > 900)
cout << "Total Bill: $ " << 59.99 + 0.4 * (min - 900) << endl;
else
cout << "Total Bill: $ " << 59.99 << endl;
break;
case 'c':
case 'C':
// $69.99
cout << "This is unlimited minutes.\nYour Bill: $ " << 69.99 << endl;
break;
default:
cout << "Please enter A, B or C" << endl;
}
system("pause");
return 0;
} | true |
0e1fa728519fe64a5a26c443e0277f9d149e7f5f | C++ | prestocore/browser | /modules/webgl/src/wgl_string.cpp | UTF-8 | 2,687 | 2.515625 | 3 | [] | no_license | /* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 2010 - 2011
*
* WebGL compiler -- string representations (JString derived.)
*
*/
#include "core/pch.h"
#ifdef CANVAS3D_SUPPORT
#include "modules/webgl/src/wgl_string.h"
#include "modules/webgl/src/wgl_context.h"
/* static */ WGL_String *
WGL_String::Make(WGL_Context *context, const uni_char *s, unsigned l)
{
unsigned position;
if (context->GetStrings()->IndexOf(s, l, position))
{
WGL_String *obj = NULL;
#ifdef DEBUG_ENABLE_OPASSERT
BOOL found =
#endif // DEBUG_ENABLE_OPASSERT
context->GetStrings()->Lookup(position, obj);
OP_ASSERT(found);
return obj;
}
WGL_String *obj = OP_NEWGRO_L(WGL_String, (), context->Arena());
obj->value = const_cast<uni_char *>(s);
obj->length = l;
uni_char *str = OP_NEWGROA_L(uni_char, (l + 1), context->Arena());
op_memcpy(str, s, l * sizeof(uni_char));
str[l] = 0;
obj->value = str;
obj->length = l;
#ifdef DEBUG_ENABLE_OPASSERT
BOOL was_added =
#endif // DEBUG_ENABLE_OPASSERT
context->GetStrings()->AppendL(context, obj, position);
OP_ASSERT(was_added);
return obj;
}
/* static */ uni_char *
WGL_String::Storage(WGL_Context *context, WGL_String *s)
{
return s->value;
}
/* static */ unsigned
WGL_String::Length(const WGL_String *s)
{
return s->length;
}
/* static */ WGL_String *
WGL_String::CopyL(WGL_String *s)
{
WGL_String *obj = OP_NEW_L(WGL_String, ());
uni_char *str = OP_NEWA(uni_char, (s->length + 1));
if (!str)
{
OP_DELETE(obj);
LEAVE(OpStatus::ERR_NO_MEMORY);
}
op_memcpy(str, s->value, s->length * sizeof(uni_char));
str[s->length] = 0;
obj->value = str;
obj->length = s->length;
return obj;
}
/* static */ void
WGL_String::Clear(WGL_String *s)
{
OP_DELETEA(s->value);
s->value = NULL;
s->length = 0;
}
/* static */ void
WGL_String::Release(WGL_String *s)
{
WGL_String::Clear(s);
OP_DELETE(s);
}
/* static */ WGL_String *
WGL_String::AppendL(WGL_Context *context, WGL_String *&s1, WGL_String *s2)
{
// Note: not intended for repetitive building of string values.
unsigned int len = s1->length + s2->length;
uni_char *str = OP_NEWGROA_L(uni_char, (len + 1), context->Arena());
op_memcpy(str, s1->value, s1->length * sizeof(uni_char));
op_memcpy(str + s1->length, s2->value, s2->length * sizeof(uni_char));
str[len] = 0;
s1->value = str;
s1->length = len;
return s1;
}
#ifdef _DEBUG
# include "modules/webgl/src/wgl_string_inlines.h"
#endif // _DEBUG
#endif // CANVAS3D_SUPPORT
| true |
bc28438fbd013bd1c1ccd31291b56776043bfc44 | C++ | gateway-services/chipdna-winlin-client-cpp | /CppLib/include/paymentdeviceconfigurationstate.h | UTF-8 | 1,349 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef PAYMENTDEVICECONFIGURATIONSTATE_H
#define PAYMENTDEVICECONFIGURATIONSTATE_H
#include <map>
namespace ChipDnaClientLib {
namespace ParameterTokens {
/**
* \brief
* Payment device configuration state.
**/
enum PaymentDeviceConfigurationState {
/**
* \brief
* Payment device is not configured.
*/
NotConfigured,
/**
* \brief
* Payment device configuration is in progress.
*/
ConfigurationInProgress,
/**
* \brief
* Payment device firmware update is in progress.
*/
FirmwareUpdateInProgress,
/**
* \brief
* Payment device is configured.
**/
Configured
};
struct PaymentDeviceConfigurationStateMapGenerator {
static std::map<std::string, PaymentDeviceConfigurationState> CreateMap() {
std::map<std::string, PaymentDeviceConfigurationState> map;
map["NotConfigured"] = NotConfigured;
map["ConfigurationInProgress"] = ConfigurationInProgress;
map["FirmwareUpdateInProgress"] = FirmwareUpdateInProgress;
map["Configured"] = Configured;
return map;
}
};
/**
* \brief
* Converts a string to a {@link PaymentDeviceConfigurationState} value.
**/
const std::map<std::string, PaymentDeviceConfigurationState> StringToPaymentDeviceConfigurationState = PaymentDeviceConfigurationStateMapGenerator::CreateMap();
}
}
#endif
| true |
490f7d078fd95d20f270c02e2ff1ad93f2c2c5ff | C++ | nkvelkov/OOP2018 | /exercise3/SmartHouse.h | UTF-8 | 1,027 | 2.96875 | 3 | [] | no_license | #ifndef SMARTHOUSE_H
#define SMARTHOUSE_H
#include "Robot.h"
const int MAX_NUM_ROBOTS = 20;
const int ADDRESS_MAX_LEN = 11;
class SmartHouse
{
public:
SmartHouse();
SmartHouse(const char* address,
int numRooms,
int numPeople,
int robotsCount,
const Robot* robots);
const char* getAddress() const;
int getNumRooms() const;
int getNumPeople() const;
int getNumRobots() const;
const Robot* getRobots() const;
void setAddress(const char* address);
void setNumRooms(int numRooms);
void setNumPeople(int numPeople);
void setRobots(int robotsCount, const Robot* robots);
void print() const;
void sortById();
void sortByProductivity();
private:
char _address[ADDRESS_MAX_LEN];
int _numRooms;
int _numPeople;
int _robotsCount;
Robot _robots[MAX_NUM_ROBOTS];
};
#endif // SMARTHOUSE_H
| true |
747f750f4333871996225b5800341fdde923ec6b | C++ | seguijoaquin/tp-datos-kika | /src/Capa Fisica/AdministradorEntidades.h | UTF-8 | 1,603 | 2.5625 | 3 | [] | no_license | #ifndef ADMIN_ENTIDADES
#define ADMIN_ENTIDADES
#include <iostream>
#include <list>
#include <sstream>
#include "../Capa Fisica/Entidad.h"
#include "../Capa Fisica/Archivos/Archivo.h"
#include <cstring>
#include <cstdlib>
using namespace std;
struct Eliminados{
int idEntidad;
vector<int>* idInstancias;
};
class AdministradorEntidades {
private:
list<Entidad>* listaEntidades;
int ultimoID;
std::fstream archivo;
void finalizarEntidad();
void agregarDato(string buffer);
void agregarDato(int buffer);
void agregarAtributo(metaDataAtributo atributo);
bool validarCreacionInstancia(Entidad* ent);
bool validarIdCreacionInstancia(Entidad* ent,int id_instancia,string nombreAtributo);
vector<Eliminados>* informarEliminacion(Entidad* ent,unsigned int id_instancia);
vector<Eliminados>* eliminacionDirecta(Entidad* ent,int id_instancia);
vector<Eliminados>* eliminacionIndirecta(Entidad* ent,int id_instancia);
vector<Eliminados>* eliminacionInIndirecta(Entidad* ent,int id_instancia);
public:
AdministradorEntidades();
~AdministradorEntidades();
void menuUsuario();
void leerArchivoEntidades();
//void crearEntidad(Entidad* entidad);
Instancia* crearInstancia(int id);
int getUltimoID();
int getID(int x);
void listarEntidades();
void listarInstancias(int id);
Entidad* getEntidad(int id);
Instancia* eliminarInstancia(unsigned int id, unsigned int id_instancia);
void modificarInstancia(unsigned int id, unsigned int id_instancia,Instancia** instanciaVieja, Instancia** instanciaNueva);
void eliminarInstancias(int id);
bool entidadExistente(string nombre);
};
#endif
| true |
2c29912fd17f1072a72d6862c0f06dd5727156a1 | C++ | martinnj/GOD | /data/StudentProject/src/solution/edge_rasterizer.h | UTF-8 | 14,343 | 3.1875 | 3 | [] | no_license | #ifndef EDGE_RASTERIZER_H
#define EDGE_RASTERIZER_H
//
// Graphics Framework.
// Copyright (C) 2010 Department of Computer Science, University of Copenhagen
//
#include <iostream>
#include <iomanip>
#include <cmath>
#include "graphics/graphics.h"
#include "solution/linear_interpolator.h"
namespace graphics {
// Draws an edge from V1 to V2, or two edges - one from V1 to V2 and one from V2 to V3.
// Edges are assumed NOT to be horizontal!
template<typename math_types>
class MyEdgeRasterizer
{
public:
typedef typename math_types::real_type real_type;
typedef typename math_types::vector3_type vector3_type;
public:
/*******************************************************************\
* *
* M y E d g e R a s t e r i z e r ( ) *
* *
\*******************************************************************/
MyEdgeRasterizer() : valid(false), twoedges(false)
{}
/*******************************************************************\
* *
* ~ M y E d g e R a s t e r i z e r ( ) *
* *
\*******************************************************************/
virtual ~MyEdgeRasterizer()
{}
/*******************************************************************\
* *
* i n i t ( " o n e e d g e " ) *
* *
\*******************************************************************/
void init(vector3_type const& in_vertex1,
vector3_type const& in_normal1,
vector3_type const& in_worldpoint1,
vector3_type const& in_color1,
vector3_type const& in_vertex2,
vector3_type const& in_normal2,
vector3_type const& in_worldpoint2,
vector3_type const& in_color2)
{
// Save the original parameters
// Do your own magic here.
// There is only one edge
this->twoedges = false;
this->initialize_current_edge(0, 1);
}
/*******************************************************************\
* *
* i n i t ( ! " t w o e d g e s " ) *
* *
\*******************************************************************/
void init(vector3_type const& in_vertex1,
vector3_type const& in_normal1,
vector3_type const& in_worldpoint1,
vector3_type const& in_color1,
vector3_type const& in_vertex2,
vector3_type const& in_normal2,
vector3_type const& in_worldpoint2,
vector3_type const& in_color2,
vector3_type const& in_vertex3,
vector3_type const& in_normal3,
vector3_type const& in_worldpoint3,
vector3_type const& in_color3)
{
// Save the original parameters
// Do your own magic here.
// There are two edges! One edge from (x1, y1) to (x2, y2),
// and the other edge going from (x2, y2) to (x3, y3)
// The assumption is that the triangle is NOT degenerate, which means that not all
// vertices are co-linear.
// This is taken care of in the triangle_rasterizer.
// But there can still be a horizontal edge.
// So, there are two edges, except if one of them is horizontal
bool edge1_is_horizontal = this->horizontal_edge(0, 1);
bool edge2_is_horizontal = this->horizontal_edge(1, 2);
if ((!edge1_is_horizontal) && (!edge2_is_horizontal)) {
//std::cout << " no horizontal edges" << std::endl;
this->twoedges = true;
this->initialize_current_edge(0, 1);
}
else {
if (edge1_is_horizontal && (!edge2_is_horizontal)) {
//std::cout << " edge 1 is horizontal, so throw it away" << std::endl;
this->twoedges = false;
this->initialize_current_edge(1, 2);
}
if ((!edge1_is_horizontal) && edge2_is_horizontal) {
//std::cout << " edge 2 is horizontal, so throw it away" << std::endl;
this->twoedges = false;
this->initialize_current_edge(0, 1);
}
}
}
/*******************************************************************\
* *
* x ( ) *
* *
\*******************************************************************/
int x() const
{
//if (!this->valid) {
// throw std::runtime_error("MyEdgeRasterizer::x(): Invalid State/Not Initialized");
//}
return this->x_current;
}
/*******************************************************************\
* *
* y ( ) *
* *
\*******************************************************************/
int y() const
{
//if (!this->valid) {
// throw std::runtime_error("MyEdgeRasterizer::y(): Invalid State/Not Initialized");
//}
return this->y_current;
}
/*******************************************************************\
* *
* d e p t h ( ) *
* *
\*******************************************************************/
real_type depth() const
{
//if (!this->valid) {
// throw std::runtime_error("MyEdgeRasterizer::depth(): Invalid State/Not Initialized");
//}
//if (!this->depth_interpolator.more_values()) {
// throw std::runtime_error("MyEdgeRasterizer::depth(): Invalid depth_interpolator");
////}
return this->depth_interpolator.value();
}
/*******************************************************************\
* *
* p o s i t i o n ( ) *
* *
\*******************************************************************/
vector3_type position() const
{
//if (!this->valid) {
// throw std::runtime_error("MyEdgeRasterizer::position():Invalid State/Not Initialized");
//}
//if (!this->worldpoint_interpolator.more_values()) {
// throw std::runtime_error("MyEdgeRasterizer::position(): Invalid worldpoint_interpolator");
//}
return this->worldpoint_interpolator.value();
}
/*******************************************************************\
* *
* n o r m a l ( ) *
* *
\*******************************************************************/
vector3_type normal() const
{
//if (!this->valid) {
// throw std::runtime_error("MyEdgeRasterizer::normal():Invalid State/Not Initialized");
//}
//if (!this->normal_interpolator.more_values()) {
// throw std::runtime_error("MyEdgeRasterizer::normal(): Invalid normal_interpolator");
//}
return this->normal_interpolator.value();
}
/*******************************************************************\
* *
* c o l o r ( ) *
* *
\*******************************************************************/
vector3_type color() const
{
//if (!this->valid) {
// throw std::runtime_error("MyEdgeRasterizer::color():Invalid State/Not Initialized");
//}
//return this->color_current;
//if (!this->color_interpolator.more_values()) {
// throw std::runtime_error("MyEdgeRasterizer::color(): Invalid color_interpolator");
//}
return this->color_interpolator.value();
}
/*******************************************************************\
* *
* p r i n t _ v a r i a b l e s ( ) *
* *
\*******************************************************************/
void print_variables()
{
std::cout << "MyEdgeRasterizer: local variables" << std::endl;
std::cout << "=================================" << std::endl;
std::cout << "\tvalid == " << this->valid << std::endl;
std::cout << std::endl;
std::cout << "\tV1 = [" << this->org_vertex[0] << "]" << std::endl;
std::cout << "\tV2 = [" << this->org_vertex[1] << "]" << std::endl;
if (this->twoedges) {
std::cout << "\tV3 = [" << this->org_vertex[2] << "]" << std::endl;
}
std::cout << std::endl;
std::cout << "\tx_start == " << this->x_start << std::endl;
std::cout << "\ty_start == " << this->y_start << std::endl;
std::cout << std::endl;
std::cout << "\tx_current == " << this->x_current << std::endl;
std::cout << "\ty_current == " << this->y_current << std::endl;
std::cout << std::endl;
std::cout << "\tx_stop == " << this->x_stop << std::endl;
std::cout << "\ty_stop == " << this->y_stop << std::endl;
std::cout << std::endl;
std::cout << "\tDeltaX == " << this->DeltaX << std::endl;
std::cout << "\tDeltaY == " << this->DeltaY << std::endl;
std::cout << std::endl;
std::cout << "\tNumerator == " << this->Numerator << std::endl;
std::cout << "\tDenominator == " << this->Denominator << std::endl;
std::cout << "\tAccumulator == " << this->Accumulator << std::endl;
std::cout << std::endl;
}
/*******************************************************************\
* *
* m o r e _ f r a g m e n t s ( ) *
* *
\*******************************************************************/
bool more_fragments() const
{
//return this->valid;
return false;
}
/*******************************************************************\
* *
* n e x t _ f r a g m e n t ( ) *
* *
\*******************************************************************/
void next_fragment()
{
// Do your own magic here.
}
protected:
private:
/*******************************************************************\
* *
* i n i t i a l i z e _ c u r r e n t _ e d g e ( i n t , i n t ) *
* *
\*******************************************************************/
void initialize_current_edge(int start_index, int stop_index)
{
// Ensure that the edge has its first vertex lower than the second one
int Ystart = static_cast<int>(round(this->org_vertex[start_index][2]));
int Ystop = static_cast<int>(round(this->org_vertex[stop_index][2]));
// Do your own magic here.
this->valid = true;
}
/*******************************************************************\
* *
* h o r i z o n t a l _ e d g e ( i n t , i n t ) *
* *
\*******************************************************************/
bool horizontal_edge(int start_index, int stop_index) {
if (static_cast<int>(round(this->org_vertex[start_index][2]))
==
static_cast<int>(round(this->org_vertex[stop_index][2])))
{
// The edge is horizontal
return true;
}
}
/*******************************************************************\
* *
* P r i v a t e V a r i a b l e s *
* *
\*******************************************************************/
bool valid;
bool twoedges;
// Original vertices
vector3_type org_vertex[3];
// Original normals
vector3_type org_normal[3];
// Original worldpoint[3]
vector3_type org_worldpoint[3];
//Original colors
vector3_type org_color[3];
// Work variables
int x_start;
int y_start;
real_type z_start;
int x_stop;
int y_stop;
real_type z_stop;
int x_current;
int y_current;
real_type z_current;
int DeltaX;
int DeltaY;
int Numerator;
int Denominator;
int Accumulator;
vector3_type Nstart;
vector3_type Nstop;
vector3_type Ncurrent;
vector3_type WorldPointstart;
vector3_type WorldPointstop;
vector3_type WorldPointcurrent;
vector3_type color_start;
vector3_type color_stop;
vector3_type color_current;
// The LinearInterpolator is hard-coded into this rasterizer -- must be changed!
LinearInterpolator<math_types, typename math_types::real_type> depth_interpolator;
// The LinearInterpolator is hard-coded into this rasterizer -- must be changed!
LinearInterpolator<math_types, typename math_types::vector3_type> normal_interpolator;
// The LinearInterpolator is hard-coded into this rasterizer -- must be changed!
LinearInterpolator<math_types, typename math_types::vector3_type> worldpoint_interpolator;
// The LinearInterpolator is hard-coded into this rasterizer -- must be changed!
LinearInterpolator<math_types, typename math_types::vector3_type> color_interpolator;
};
}// end namespace graphics
// EDGE_RASTERIZER_H
#endif
| true |
0f3075af4416acfb7a6f9efd720308e023a48b90 | C++ | SlavaX/SimpleClientServer | /Src/ClientServer/Internal/ClientWinAPI.cpp | UTF-8 | 1,782 | 2.875 | 3 | [] | no_license | //------------------------------
#include "..\Public\ClientWinAPI.h"
//------------------------------
#include <iostream>
#include <ws2tcpip.h>
//------------------------------
ClientWinAPI::ClientWinAPI() :
ConnectSocket(INVALID_SOCKET)
{
}
void ClientWinAPI::GetConnectSocket(PCSTR Port)
{
addrinfo *addrInfoList = 0;
//Получить список возможных соединений
this->AddrInfoForPort(Port, &addrInfoList);
//В соответствии с полученным списком пробуем соединитья к серверу
//до первого успешного
for (addrinfo* ptr = addrInfoList; ptr != NULL; ptr = ptr->ai_next)
{
//Создать сокет для соединения с сервером
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
std::wcout << L"socket failed with error: " << WSAGetLastError() << "\n";
//Соединиться к серверу
int connectResult = connect(ConnectSocket, ptr->ai_addr, static_cast<int>(ptr->ai_addrlen));
if (connectResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(addrInfoList);
if (ConnectSocket == INVALID_SOCKET)
std::wcout << L"Соединиться с сервером не удалось!\n";
}
int ClientWinAPI::GetState()
{
return ConnectSocket == INVALID_SOCKET ? 0 : 1;
}
ClientWinAPI::~ClientWinAPI()
{
//Закрытие соединения с сервером
if (shutdown(ConnectSocket, SD_SEND) == SOCKET_ERROR)
std::wcout << L"Закрытие соединения не удалось. Код ошибки: " << WSAGetLastError() << "\n";
closesocket(ConnectSocket);
}
| true |
d46b213a74aca50ea7d484c238d66dba4e6f410e | C++ | 2015cnugithub/2151002050MengQianQian | /Third Mycar/mycar.cpp | GB18030 | 7,576 | 3.03125 | 3 | [] | no_license | #include <graphics.h>
#include <conio.h>
#include <dos.h>
#include <time.h>
#include <windows.h>
#include <iostream>
using namespace std;
class Figure{
friend class FigureLink;//FigureLinkӲͬͼλ
friend class Vehicle;
protected:
int cx,cy; // ͼελ
Figure *ptr;// ָҪͼλƶ
Figure *next;// ָһͼλƶ
public:
Figure(int x,int y)
{
cx=x;
cy=y;
next=0;
}
virtual ~Figure(){}
virtual void Draw()=0;//ͼλƲӿ
void operator()(int dx,int dy);// Ϊƶͼͼλ
};
void Figure::operator() (int dx,int dy)
{
cx+=dx;
cy+=dy;
}
class Triangle:public Figure
{
int rightAngleFlag;//жǷΪֱ
int bottomSide; //ױ߳
int height;//εĸ
public:
Triangle(int b,int h,int f,int x,int y):Figure(x,y)
{
bottomSide=b;
height=h;
rightAngleFlag=f;
}
~Triangle(){}
void Draw();
Figure *Insert();
};
//////////////////////////////////////
void Triangle::Draw()
{
if(rightAngleFlag==1)
{
int points[6]={cx-bottomSide/2,cy+height/2,cx+bottomSide/2,cy+height/2,cx+bottomSide/2,cy-height/2};
drawpoly(3,points);//κ
}
else
{
int points[6]={cx-bottomSide/2,cy+height/2,cx+bottomSide/2,cy+height/2,cx-bottomSide/2,cy-height/2};
drawpoly(3,points);
}
}
Figure *Triangle::Insert()
{
ptr=new Triangle(bottomSide,height,rightAngleFlag,cx,cy);
return ptr;
}
////////////////////////////////////////
class Circle:public Figure
{
int diameter;//ֱ
public:
Circle(int d,int x,int y):Figure(x,y)
{
diameter=d;
}
~Circle(){}
void Draw();
Figure * Insert();
};
void Circle::Draw()
{
circle(cx,cy,diameter/2);
}
Figure* Circle::Insert()
{
ptr=new Circle(diameter,cx,cy);
return ptr;
}
////////////////////////////////////
class myRectangle:public Figure
{
int width;
int length;
public:
myRectangle(int w,int l,int x,int y):Figure(x,y)
{
width=w;
length=l;
}
virtual ~myRectangle(){}
void Draw();
Figure *Insert();
};
void myRectangle::Draw()
{
rectangle(cx-width/2,cy-length/2,cx+width/2,cy+length/2);
}
Figure *myRectangle::Insert()
{
ptr=new myRectangle(width,length,cx,cy);
return ptr;
}
/////////////////////////////////////////////////
class FigureLink{
friend class Vehicle;
Figure * head;
public:
FigureLink();
~FigureLink();
bool Empty();
void Insert(Figure *FigureNode);
};
FigureLink::FigureLink()
{
head=NULL;
}
FigureLink::~FigureLink()
{
Figure *p=head->next;
Figure *q;
while(p!=0)
{
q=p->next;
delete p;
p=q;
}
head=NULL;
}
bool FigureLink::Empty()
{
if(head==0)
return TRUE;
else
return FALSE;
}
void FigureLink::Insert(Figure *FigureNode)
{
Figure *p=head;
if(p==0)
head=FigureNode;
else
{
while(p->next!=NULL)
p=p->next;
p->next=FigureNode;
FigureNode->next=NULL;
}
}
/////////////////////////////////////////////////////
class Vehicle //
{
friend class FigureLink;
protected:
FigureLink contents;
int xstart,ystart;
int wheel_size;
public:
Vehicle(){}
virtual ~Vehicle(){}
virtual void Draw();
virtual void Hide();
virtual void Move(int dx,int dy);
};
void Vehicle::Draw()
{
if(!contents.Empty())
{
Figure *p=contents.head;
while(p!=0)
{
p->Draw();
p=p->next;
}
}
}
void Vehicle::Hide()
{
Figure *p=contents.head;
while(p!=0)
{
unsigned int sc=getcolor(); //صǰͼǰɫ
setcolor(getbkcolor()); //ȡǰͼɫΪǰͼǰɫ
p->Draw();
setcolor(sc);
p=p->next;
}
}
void Vehicle::Move(int dx,int dy)
{
Figure *p=contents.head;
if(!contents.Empty())
{
while(p)
{
unsigned int sc=getcolor();
setcolor(getbkcolor());
p->Draw();
setcolor(sc);
p->operator()(dx,dy);
p->Draw();
p=p->next;
}
}
}
/////////////////////////////////////////////////////
class Car:public Vehicle
{
public:
Car(int wheel,int x,int y):Vehicle()
{
wheel_size=wheel;
xstart=x;ystart=y;
Figure *p;
int d=wheel_size;
Triangle tri1(d,d,1,xstart,ystart);p=tri1.Insert();contents.Insert(p);
Triangle tri2(d,d,0,xstart+4.5*d,ystart);p=tri2.Insert();contents.Insert(p);
myRectangle rec1(3.5*d,d,xstart+2.25*d,ystart);p=rec1.Insert();contents.Insert(p);
myRectangle rec2(8*d,d,xstart+2.25*d,ystart+d);p=rec2.Insert();contents.Insert(p);
Circle cir1(d,xstart,ystart+2*d);p=cir1.Insert();contents.Insert(p);
Circle cir2(d,xstart+4.5*d,ystart+2*d);p=cir2.Insert();contents.Insert(p);
}
~Car(){}
};
class Truck:public Vehicle
{
public:
Truck(int wheel,int x,int y):Vehicle()
{
wheel_size=wheel;
xstart=x;ystart=y;
Figure *p;
int d=wheel_size;
myRectangle rec1(9*d,4*d,xstart,ystart);p=rec1.Insert();contents.Insert(p);
myRectangle rec2(2*d,3*d,xstart+5.5*d+2,ystart+0.5*d);p=rec2.Insert();contents.Insert(p);
Circle cir1(d,xstart-3.5*d,ystart+2.5*d);p=cir1.Insert();contents.Insert(p);
Circle cir2(d,xstart-2.25*d,ystart+2.5*d);p=cir2.Insert();contents.Insert(p);
Circle cir3(d,xstart+2.25*d,ystart+2.5*d);p=cir3.Insert();contents.Insert(p);
Circle cir4(d,xstart+3.5*d,ystart+2.5*d);p=cir4.Insert();contents.Insert(p);
Circle cir5(d,xstart+5.5*d+2,ystart+2.5*d);p=cir5.Insert();contents.Insert(p);
}
~Truck(){}
};
///////////////////////////////////////////////////////////
char mainscreen()
{
cout<<"================Mainscreen================"<<endl;
cout<<"1. Car"<<endl;
cout<<"2. Truck"<<endl;
cout<<"3. Exit"<<endl;
char choice;
choice=getche();
cout<<endl;
return choice;
}
void subscreen()
{
char *s1="Press <S> key to start moving.";
char *s2="Press <P> key to pause/continue moving.";
char *s3="Press <E> key to end moving.";
char *s4="Press <+> key to speed up.";
char *s5="Press <-> key to speed down.";
outtextxy(0,10,s1);
outtextxy(0,30,s2);
outtextxy(0,50,s3);
outtextxy(0,70,s4);
outtextxy(0,90,s5);
}
static int speed=1000;
void speed_up(int x)
{
speed-=x;
}
void speed_down(int x)
{
speed+=x;
}
void delay()
{
for(int i=0;i<speed;i++)
for(int j=0;j<1000;j++)
{}
}
void choose(char c1,int sign,Vehicle *x)
{
if(c1=='p'||c1=='P')
{
if(sign==0)
{
sign=1;
while(!kbhit()){} //طֵ0ļ include<conio.h>
char c2=getch();
choose(c2,sign,x);
}
else
{
sign=0;
while(!kbhit())
{
delay();
x->Move(1,0);
}
char c2=getch();
choose(c2,sign,x);
}
}
if(c1=='+')
{
speed_up(200);
while(!kbhit())
{
delay();
x->Move(1,0);
}
char c2=getch();
choose(c2,sign,x);
}
if(c1=='-')
{
speed_down(200);
while(!kbhit())
{
delay();
x->Move(1,0);}
char c2=getch();
choose(c2,sign,x);
}
if(c1=='E'||c1=='e')
{
closegraph();
}
}
void car()
{
// int gdriver=DETECT,gmode;
initgraph(1024,728);
Vehicle *p;
char c1,c2;
int sign=0;
subscreen();
Car c(20,50,300);
c.Draw();
p=&c;
c1=getch();
if(c1=='S'||c1=='s')
{
while(!kbhit()){delay();p->Move(1,0);}
c2=getch();
choose(c2,sign,p);
}
}
void truck()
{
// int gdriver=DETECT,gmode;
initgraph(1024,728);
Vehicle *p;
char c1,c2;
int sign=0;
int x,y;
int w;
subscreen();
Truck t(20,100,300);
t.Draw();
p=&t;
c1=getch();
if(c1=='S'||c1=='s')
{
while(!kbhit()){delay();p->Move(1,0);}
c2=getch();
choose(c2,sign,p);
}
}
int main()
{
char choice;
while((choice=mainscreen())!='3')
{
switch(choice)
{
case '1' : car();break;
case '2' : truck();break;
}
}
return 0;
}
| true |
e9659802dd339719f3bb3efe67b49f37123856c0 | C++ | MykolaNemo/AdventOfCode | /2019/Day-9/main.cpp | UTF-8 | 643 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include "../Computer.h"
using namespace std;
#define PART1
int main()
{
std::ifstream infile("input.txt");
std::vector<long long> program;
std::string code;
while(std::getline(infile, code, ','))
{
program.push_back(std::stol(code));
}
#ifdef PART1
std::vector<long long> input = {1};
#else
std::vector<long long> input = {2};
#endif
std::vector<long long> output;
Computer m(0);
m.setProgram(program);
m.start(input, output);
for(auto c : output)
{
std::cout<<c<<",";
}
std::cout<<std::endl;
return 0;
}
| true |
ce10e0347e92c47f95d51129996ef2a8816a4299 | C++ | JanessaMunt/BlackJack | /dealer.cpp | UTF-8 | 3,047 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <time.h>
#include <unistd.h>
using namespace std;
#include "./card.h"
#include "deck.h"
#include "./hand.h"
#include "./player.h"
#include "./dealer.h"
dealer::dealer(){
}
dealer::~dealer(){
}
/*********************************************************************
** Function: d_get_card
** Description: adds a new card to d_hand
** Parameters: card
** Pre-Conditions: All parameters are valid
** Post-Conditions: d_card gets a new card
*********************************************************************/
void dealer::d_get_card(card newcard){
d_hand.draw_card(newcard); //draws card
}
/*********************************************************************
** Function: d_hand_value
** Description: gets value of dealers hand
** Parameters: int
** Pre-Conditions: All parameters are valid
** Post-Conditions: returns value of dealers hand
*********************************************************************/
int dealer::d_hand_value(int start) const{
return d_hand.hand_val(start); //returns hand value
}
/*********************************************************************
** Function: show_hidden
** Description: prints dealers hand with option of hiding first card
** Parameters: bool
** Pre-Conditions: All parameters are valid
** Post-Conditions: dealers hand is printed
*********************************************************************/
void dealer::show_hidden(bool hidden) const{
if(hidden == true)
d_hand.ascii_hand_d(); //calls function to print hand with hidden card
else
d_hand.ascii_hand(); //calls function to print hand and show hidden card
}
/*********************************************************************
** Function: dealer_turn
** Description: reveals dealer's hidden card and draws a card if total is less than 17
** Parameters: deck
** Pre-Conditions: All parameters are valid
** Post-Conditions: dealers hand and value is printed
*********************************************************************/
void dealer::dealer_turn(deck * pack){
cout << " ○ Dealer's hand total: " << d_hand.hand_val(1) << " ○" << endl; //prints hand value
show_hidden(1); //prints dealers hand with hidden card
cout << endl;
cout << " ○ Dealer's hand total: " << d_hand.hand_val(0) << " ○" << endl; //prints hand value
show_hidden(0); //prints dealers full hand
while(d_hand_value(0) < 17){ //draws another card while hand total is under 17
d_hand.draw_card(pack->next_card()); //draws card
cout << " ○ Dealer's hand total: " << d_hand.hand_val(0) << " ○" << endl; //prints hand value
show_hidden(0); //prints hand
}
}
/*********************************************************************
** Function: reset_d_hand
** Description: calls function to reset d_hand
** Parameters: none
** Pre-Conditions: All parameters are valid
** Post-Conditions: d_hand is reset
*********************************************************************/
void dealer::reset_d_hand(){
d_hand.reset(); //calls function to reset hand
}
| true |
5c945c158332c010e65cfa1c77c92a1d7ab09219 | C++ | suyuan945/LeetCode | /292_NimGame/292_NimGame.cpp | UTF-8 | 244 | 2.9375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Solution {
public:
bool canWinNim(int n) {
return (n & 3);
}
};
int main(int argc, char *argv[]){
Solution s;
cout << s.canWinNim(3) << endl;
system("pause");
return 0;
} | true |
76e481e3373a49f49ccd5a9cb14ab90639075234 | C++ | honglion/NewRepo | /Project1/include.h | UHC | 1,326 | 2.59375 | 3 | [] | no_license | #pragma once
#include <iostream> /// input output , std::cout , std::cin
#include <cstdio> /// printf
#include <algorithm> /// std::max(a,b) , std::sort(a, b) 迭 a° Һ b° ұ , for_each
#include <limits> //// std::numeric_limits<int>::max(),lowest()
#include <cmath> /// std::pow(2,3) 2 3 , std::abs(-123) 밪
#include <typeinfo> /// typeid( ).name() ˷
#include <string> /// std::string
#include <cstring> /// strcpy(, ); strcat(destination, source) Ʈ ڿ ̱; strcmp(a, b) ab 0
#include <cstddef> /// std::nullptr_t
#include <array> /// std::array
#include <vector> /// std::vector
#include <tuple> /// std::tuple<ڷ, ڷ> getTuple()
#include <functional> /// std::function
#include <cassert> /// assert
#include <cstdarg> /// for ellipsis
#include <fstream> ///
#include <random> /// std::shuffle(arr.begin(), arr.end(), g);
#include <memory> /// std::unique_ptr
#include <thread>
#include <chrono>
#include <mutex> /// mutex thread lock Ŵ°
#include <atomic> /// thread lock Ŵ°
#include <future> /// async, future, promise
#include <numeric> /// std::inner_product
#include <utility> /// std::forward | true |
5f8020e892c907030a9cf3939945ad42d3adedf2 | C++ | danielmonr/Estructura-de-datos | /Tarea4Ejercicio4/Tarea4Ejercicio4/Pantalla.cpp | UTF-8 | 4,475 | 2.921875 | 3 | [] | no_license | //
// Pantalla.cpp
// Tarea4Ejercicio4
//
// Created by Daniel on 18/10/14.
// Copyright (c) 2014 Gotomo. All rights reserved.
//
#include "Pantalla.h"
bool Pantalla::curses_ON = false;
void Pantalla::print(ListaDoblementeEnlazada<ListaDoblementeEnlazada<char> *> *texto){
std::cout<<"------------- Editor de Texto ------------\n";
for (int i = 0; i < texto->size(); ++i){
std::cout<<*(texto->At(i)->getInfo());
std::cout<<std::endl;
}
}
void Pantalla::printMenu(){
std::cout<<"------------- Editor de Texto ------------\n";
std::cout<<"Menu: "<<std::endl;
std::cout<<"Para abrir el menu de ocpiones una vez ingresado al editor presione ESC"<<std::endl;
std::cout<<"1) Nuevo Documento\n2) Abrir Documento\n0) Salir"<<std::endl;
}
void Pantalla::printOpciones(){
std::cout<<"Opciones:\n1) Salvar el documento\n2) Cerrar documento\n";
}
ListaDoblementeEnlazada<ListaDoblementeEnlazada<char> *> * Pantalla::editor(ListaDoblementeEnlazada<ListaDoblementeEnlazada<char> *> * texto){
int row, col;
row = 0;
col = 0;
bool activo = true;
if(texto->size() == 1 && texto->At(0)->getInfo()->size() == 0){
row = 0;
col = 0;
}
else{
row = texto->size() -1;
col = texto->At(row-1)->getInfo()->size();
}
startCurses();
for (int i = 0; i< texto->size(); ++i){
for (int j = 0; j < texto->At(i)->getInfo()->size(); ++j){
addch(texto->At(i)->getInfo()->At(j)->getInfo());
}
addch('\n');
}
move(row, col);
while (activo) {
// getyx(stdscr, row, col);
int ch = getch();
switch (ch) {
case ESC:
activo = false;
break;
case '\n':
addch(ch);
texto->insertAt(nuevaLinea(texto->At(row)->getInfo(), col), row+1);
clear();
return editor(texto);
break;
case BACKSPACE:
if (col > 0) {
texto->At(row)->getInfo()->deleteAt(col-1);
col--;
move(row, col);
for (int i = col; i < texto->At(row)->getInfo()->size(); ++i){
addch(texto->At(row)->getInfo()->At(i)->getInfo());
}
addch(' ');
move(row, col);
}
else{
for (int j = 0; j < texto->At(row)->getInfo()->size(); ++j) {
texto->At(row-1)->getInfo()->insertBack(texto->At(row)->getInfo()->deleteAt(j)->getInfo());
}
texto->deleteAt(row);
return editor(texto);
}
break;
case LEFT:
if (col >0) {
col--;
move(row, col);
}
break;
case RIGHT:
if(col < texto->At(row)->getInfo()->size()){
col++;
move(row, col);
}
break;
case UP:
if (row > 0) {
row--;
move(row, col);
}
break;
case DOWN:
if(row < texto->size()-1){
row++;
move(row, col);
}
break;
default:
addch(ch);
texto->At(row)->getInfo()->insertAt(ch, col);
col++;
break;
}
}
endCurses();
return texto;
}
void Pantalla::endCurses(){
if (curses_ON && !isendwin())
clear();
endwin();
}
void Pantalla::startCurses(){
if (curses_ON) {
refresh();
}
else {
initscr();
cbreak();
noecho();
intrflush(stdscr, false);
keypad(stdscr, true);
atexit(endCurses);
curses_ON = true;
}
}
ListaDoblementeEnlazada<char> * Pantalla::nuevaLinea(ListaDoblementeEnlazada<char> * vieja, int c){
ListaDoblementeEnlazada<char> * nueva = new ListaDoblementeEnlazada<char>;
if(c != vieja->size()){
for (int i = c-1; i < vieja->size(); ++i) {
nueva->insertBack(vieja->deleteAt(c)->getInfo());
}
}
return nueva;
} | true |
fd4479e823ee0c3d54ff9b4d0e9c092c1afbb82d | C++ | jnf611/cpp_initobjprog | /cpp/s05-e18-puissance4.cpp | UTF-8 | 2,042 | 3.484375 | 3 | [] | no_license | /* s05e18 Puissance 4*/
#include <iostream>
#include <vector>
using namespace std;
enum Couleur
{
VIDE,
JAUNE,
ROUGE
};
class Jeu
{
public:
Jeu(size_t largeur = 8) : largeur(max(largeur, largeur_min)), plateau(8) {}
size_t getLargeur() { return largeur; }
bool jouer(Couleur couleur, size_t colonne)
{
bool ok = false;
if (colonne < largeur && plateau[colonne].size() < largeur)
{
plateau[colonne].push_back(couleur);
ok = true;
}
return ok;
}
Couleur gagnant()
{
if (estRempli())
return VIDE;
}
static const size_t largeur_min;
private:
bool estRempli()
{
size_t total = 0;
for (auto c : plateau)
{
total += c.size();
}
return (total == largeur*largeur);
}
size_t largeur;
vector<vector<Couleur>> plateau;
};
const size_t Jeu::largeur_min = 8;
class Joueur
{
public:
Joueur(const string& nom, Couleur couleur) : nom(nom), couleur(couleur) {}
virtual void jouer(Jeu& jeu) = 0;
protected:
const string nom;
Couleur couleur;
};
class JoueurHumain : public Joueur
{
public:
using Joueur::Joueur;
virtual void jouer(Jeu& jeu)
{
bool ok = false;
do
{
size_t colonne;
cout << "Joueur " << nom << ", entrez un numéro de colonne" << endl
<< "(entre 1 et " << jeu.getLargeur() << ") :";
cin >> colonne;
ok = jeu.jouer(couleur, colonne);
}
while(!ok);
}
};
class JoueurOrdinateur : public Joueur
{
public:
using Joueur::Joueur;
virtual void jouer(Jeu& jeu)
{
size_t colonne = 0;
bool ok = false;
do
{
ok = jeu.jouer(couleur, colonne);
colonne ++;
}
while (!ok && colonne < jeu.getLargeur());
}
};
class Partie()
{
public:
void addJoueur(Joueur* j)
{
if (joueurs.size() < 2)
{
joueurs.push_back(j);
}
}
void jouer()
{
if (joueur.size() != 2)
return;
Jeu jeu(8);
size_t idx
while (!jeu.estTermine())
{
}
}
private:
vector<Joueur*> joueurs;
};
int main()
{
string nom;
cout << "Quel est votre nom ?";
cin >> nom;
JoueurHumain j1(nom, JAUNE);
JoueurOrdinateur("ordinateur", ROUGE);
return 0;
}
| true |
82fbef35cac4a42c1c31d6da7d170f0e710f8a10 | C++ | Dicksonlab/MateBook | /grapher/source/ContinuousGraph.cpp | UTF-8 | 1,978 | 2.53125 | 3 | [] | no_license | /*
* continuousgraphdata.cpp
* grapher
*
* Created by Herbert Grasberger on 15.11.10.
* Copyright 2010 by grasberger.org. All rights reserved.
*
*/
#include "ContinuousGraph.hpp"
#include <QGLWidget>
#include <math.h>
#include <limits>
#define SIGN(_a) ((_a) > 0 ? 1 : (_a) < 0 ? -1 : 0)
size_t ContinuousGraph::splitThreshold = 1000000;
/**
* we need this constructor since the unit graph derives from ContinuousGraph and
* depends on this way to construct the graph
*/
ContinuousGraph::ContinuousGraph(const fPoint * data,
size_t dataSize,
QVector4D color,
float lineWidth,
QVector3D offset,
const std::string& unit
) :
AbstractGraph(offset),
indices_(),
positions_(),
unit_(unit),
colors_(),
maxValue_(-std::numeric_limits<fPoint>::infinity()),
minValue_(std::numeric_limits<fPoint>::infinity()),
vertexBuffers_(),
lineWidth_(lineWidth)
{
convert(data, data + dataSize, &color, 1);
calculateExtremeValues();
}
ContinuousGraph::~ContinuousGraph()
{
indices_.clear();
positions_.clear();
colors_.clear();
for(size_t i = 0; i < vertexBuffers_.size(); ++i)
{
if(vertexBuffers_[i])
{
delete vertexBuffers_[i];
vertexBuffers_[i] = NULL;
}
}
vertexBuffers_.clear();
}
const QVector3D * ContinuousGraph::getDataPtr() const
{
return & positions_[0];
}
fPoint ContinuousGraph::getMaxValue() const
{
return maxValue_;
}
fPoint ContinuousGraph::getMinValue() const
{
return minValue_;
}
std::string ContinuousGraph::getUnits() const
{
return unit_;
}
size_t ContinuousGraph::getSize() const
{
return positions_.size();
}
void ContinuousGraph::calculateExtremeValues()
{
maxValue_ = std::numeric_limits<fPoint>::min();
minValue_ = std::numeric_limits<fPoint>::max();
for(size_t i = 0; i < positions_.size(); ++i)
{
if(positions_[i].y() > maxValue_)
{
maxValue_ = positions_[i].y();
}
if(positions_[i].y() < minValue_)
{
minValue_ = positions_[i].y();
}
}
}
| true |
cd5f2afc428ec7dfa7079a7282fadc7f7d227489 | C++ | jjmmg/Project-Euler | /problem_21.cpp | UTF-8 | 2,834 | 3.40625 | 3 | [] | no_license | // Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
// If d(a) = b and d(b) = a, where a ? b, then a and b are an amicable pair and each of a and b are called amicable numbers.
// For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
// Evaluate the sum of all the amicable numbers under 10000.
#include <iostream>
#include <vector>
#include <numeric>
#include <chrono>
template <typename T>
inline int factor_rep(T& nbr, T factor)
{
int times{0};
for (; !(nbr%factor); ++times) nbr /= factor;
return times;
}
template <typename T>
inline std::vector<T> get_factors(T nbr)
{
T itself{nbr};
std::vector<T> result{T{1}};
auto check_factor = [&result](T& n, const T& f) {
int reps{factor_rep(n, f)};
for (int rep{0}; rep<reps; ++rep)
result.push_back(f);
};
if (nbr>2) check_factor(nbr, T{2});
if (nbr>3) check_factor(nbr, T{3});
// 6k +- 1
for (T i{5}; i*i<=nbr; i+=6)
{
check_factor(nbr, i);
check_factor(nbr, i+2);
}
// one last prime factor
if (nbr!=1 && nbr!=itself)
result.push_back(nbr);
return result;
}
template <typename T>
inline std::vector<T> get_divisors(T nbr)
{
std::vector<T> res(get_factors(nbr));
std::vector<T> aux;
int len;
do
{
len = res.size();
aux.clear();
for (auto it=res.begin()+1; it!=res.end(); ++it)
{
for (auto it_int=it; it_int!=res.end(); ++it_int)
{
T mul{*it * *it_int};
if (mul<nbr && nbr%mul==0)
aux.push_back(mul);
}
}
std::copy(aux.begin(), aux.end(), std::back_inserter(res));
std::sort(res.begin(), res.end());
res.erase(std::unique(res.begin(), res.end()), res.end());
} while (len!=res.size());
return res;
}
template <typename T>
inline bool is_amicable(const T& a, T& b)
{
std::vector<T> a_div{get_divisors(a)};
b = std::accumulate(a_div.begin(), a_div.end(), T{0});
std::vector<T> b_div{get_divisors(b)};
long b_div_sum{std::accumulate(b_div.begin(), b_div.end(), T{0})};
return (b>a && a==b_div_sum);
}
int main()
{
auto start = std::chrono::steady_clock::now();
typedef long type;
std::vector<type> r;
type b;
for (type a{1}; a<10000; ++a)
if (is_amicable(a, b))
{
r.push_back(a);
r.push_back(b);
}
std::cout << "Sum: " << std::accumulate(r.begin(), r.end(), type{0}) << "\n";
std::cout << std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - start).count() << " ms\n";
} | true |
1631e73c5fa35873bbc4f72fbfa7746003bf4a17 | C++ | keangnage/Nibbler | /sfmllib/sfmllib.cpp | UTF-8 | 4,671 | 2.65625 | 3 | [] | no_license | #include "sfmllib.hpp"
Sfmllib::Sfmllib(void) : window(sf::VideoMode(640, 480), "snake")
{
}
Sfmllib::~Sfmllib(void)
{
}
int Sfmllib::userResponse()
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
return (1);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
return (2);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
return (3);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
return (4);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
return (-1);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num1))
return (5);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num2))
return (6);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num3))
return (7);
}
return (0);
}
void Sfmllib::printPlayer(std::list<Vector> snakePoints)
{
head.setSize(sf::Vector2f(10,10));
head.setOutlineColor(sf::Color::Red);
head.setOutlineThickness(2);
body.setSize(sf::Vector2f(10,10));
body.setOutlineColor(sf::Color::Cyan);
body.setOutlineThickness(2);
std::list<Vector>::iterator next;
for (std::list<Vector>::iterator point = snakePoints.begin(); point != snakePoints.end(); ++point) {
next = point;
next++;
if (next != snakePoints.end()) {
if (next->x > point->x) {
for (int x = point->x; x != next->x; x++)
{
body.setPosition(((x + 1) << 3) + ((x + 1) << 1),((point->y + 1) << 3) + ((point->y + 1) << 1));
window.draw(body);
}
}
else if (next->x < point->x) {
for (int x = next->x; x != point->x + 1; x++)
{
body.setPosition(((x + 1) << 3) + ((x + 1) << 1),((point->y + 1) << 3) + ((point->y + 1) << 1));
window.draw(body);
}
}
else if (next->y > point->y) {
for (int y = point->y; y != next->y; y++)
{
body.setPosition(((point->x + 1) << 3) + ((point->x + 1) << 1),((y + 1) << 3) + ((y + 1) << 1));
window.draw(body);
}
}
else if (next->y < point->y) {
for (int y = next->y; y != point->y + 1; y++)
{
body.setPosition(((point->x + 1) << 3) + ((point->x + 1) << 1),((y + 1) << 3) + ((y + 1) << 1));
window.draw(body);
}
}
}
else {
head.setPosition((((point->x + 1) << 3) + ((point->x + 1) << 1)),(((point->y + 1) << 3) + ((point->y + 1) << 1)));
window.draw(head);
}
}
}
void Sfmllib::drawFrame(Vector mapsize, std::list<Vector> apples, std::list<Vector> playerCords, int)
{
int y = ((mapsize.y + 2) << 3) + ((mapsize.y + 2) << 1);
int x = ((mapsize.x + 2) << 3) + ((mapsize.x + 2) << 1);
frame.setSize(sf::Vector2f(7,7));
frame.setOutlineColor(sf::Color::Blue);
frame.setOutlineThickness(2);
food.setSize(sf::Vector2f(10,10));
food.setOutlineColor(sf::Color::Green);
food.setOutlineThickness(2);
window.clear();
for (int i = 0; i != x + 1; i++) {
frame.setPosition(i, 0);
window.draw(frame);
frame.setPosition(i, y);
window.draw(frame);
}
for (int i = 0; i != y; i++) {
frame.setPosition(0, i);
window.draw(frame);
frame.setPosition(x, i);
window.draw(frame);
}
for (std::list<Vector>::iterator apple = apples.begin(); apple != apples.end() ; ++apple) {
food.setPosition((((apple->x + 1) << 3) + ((apple->x + 1) << 1)),(((apple->y + 1) << 3) + ((apple->y + 1) << 1)));
window.draw(food);
}
printPlayer(playerCords);
window.display();
}
extern "C" Sfmllib *create_gl() {
Sfmllib *lib = new Sfmllib;
return (lib);
}
extern "C" void destroy_gl(Sfmllib *lib) {
delete lib;
}
// Canonical stuff
Sfmllib::Sfmllib(Sfmllib const & copy) {
*this = copy;
}
Sfmllib& Sfmllib::operator=(Sfmllib const & copy) {
if ( this != © ) {
Sfmllib new_gui(copy);
set_body(new_gui.get_body());
set_food(new_gui.get_food());
set_frame(new_gui.get_frame());
set_head(new_gui.get_head());
}
return *this;
}
std::ostream & operator<<(std::ostream & o, Sfmllib const & rhs) {
Sfmllib copy(rhs);
o << "This lib is working";
return o;
}
sf::RectangleShape Sfmllib::get_body() { return body; }
sf::RectangleShape Sfmllib::get_food() { return food; }
sf::RectangleShape Sfmllib::get_frame() { return frame; }
sf::RectangleShape Sfmllib::get_head() { return head; }
void Sfmllib::set_body(sf::RectangleShape new_body) { body = new_body; }
void Sfmllib::set_food(sf::RectangleShape new_food) { food = new_food; }
void Sfmllib::set_frame(sf::RectangleShape new_frame) { frame = new_frame; }
void Sfmllib::set_head(sf::RectangleShape new_head) { head = new_head; }
| true |
70c0214b01b399adfea0fb8c67f9a16339fba5a2 | C++ | karolmorawski-AGH/AGH_Metody-Numeryczne2019 | /mnumeryczne/diffeq.cpp | UTF-8 | 2,293 | 3.296875 | 3 | [] | no_license | #include "diffeq.h"
#include "Point.h"
#include <vector>
#include "MnMath.h"
#include "newton-cotes.h"
//Euler
double euler(double x, double y0, double h, double(*fun)(double, double)) {
double n = x / h;
double result = 0;
if (h == 0) {
return 0;
}
double prevx = 0;
double prevy = y0;
double x1, y1;
for (double i = 0; i < x; i=i+h) {
x1 = prevx + h;
y1 = prevy + h * fun(prevx, prevy);
prevx = x1;
prevy = y1;
}
return y1;
}
//Heuna
double heune(double x, double y0, double h, double(*fun)(double, double)) {
double n = x / h;
double result = 0;
if (h == 0) {
return 0;
}
double prevx = 0;
double prevy = y0;
double x1, y1;
for (double i = 0; i < x; i = i + h) {
x1 = prevx + h;
y1 = prevy + h * 0.5 * (fun(prevx, prevy) + fun(prevx + h, prevy + h*fun(prevx, prevy)));
prevx = x1;
prevy = y1;
}
return y1;
}
//Modified Euler
double euler_mod(double x, double y0, double h, double(*fun)(double, double))
{
double n = x / h;
double result = 0;
if (h == 0) {
return 0;
}
double prevx = 0;
double prevy = y0;
double x1, y1;
for (double i = 0; i < x; i = i + h) {
x1 = prevx + h;
y1 = prevy + h * fun(prevx + 0.5 * h, prevy + 0.5 * h * fun(prevx, prevy));
prevx = x1;
prevy = y1;
}
return y1;
}
//Runge-Kutta 4th degree
double runge_kutta(double x, double y0, double h, double(*fun)(double, double))
{
double n = x / h;
double result = 0;
if (h == 0) {
return 0;
}
double prevx = 0;
double prevy = y0;
double x1, y1;
double k1, k2, k3, k4;
for (double i = 0; i < x; i = i + h) {
k1 = fun(prevx, prevy);
k2 = fun(prevx + (0.5 * h), prevy + (0.5 * k1 * h));
k3 = fun(prevx + (0.5 * h), prevy + (0.5 * k2 * h));
k4 = fun(prevx + h, prevy + (k3 * h));
x1 = prevx + h;
y1 = prevy + (h * (k1 + k4 + 2.0 * (k2 + k3)) / 6.0);
prevx = x1;
prevy = y1;
}
return y1;
}
//Main
void diffeq_main() {
std::cout << "Euler: " << std::endl << euler(300., 1200., 0.01, p_ciepln) << std::endl;
std::cout << "Heune: " << std::endl << heune(300., 1200., 0.01, p_ciepln) << std::endl;
std::cout << "Modified Euler: " << std::endl << euler_mod(300., 1200., 0.01, p_ciepln) << std::endl;
std::cout << "Runge-Kutta: " << std::endl << runge_kutta(300., 1200., 0.01, p_ciepln) << std::endl;
} | true |
fa5e8b5f985ae1ccdece55304aa1266528c65431 | C++ | demidko/filemap | /src/Main.cpp | UTF-8 | 1,038 | 2.84375 | 3 | [
"MIT"
] | permissive | #include "Telegram.h"
#include <spdlog/spdlog.h>
#include <mutex>
#include <unordered_map>
using Database = std::unordered_map<int64_t, std::unordered_map<std::string, std::string>>;
Telegram::FileHandler saveFileTo(Database &db, std::mutex &m) {
return [&](const auto &bot, const auto &file) {
spdlog::info("chat id {} saved file id {} with key {}", file.chatId, file.fileId, file.key);
std::lock_guard guard{m};
db[file.chatId][file.key] = file.fileId;
};
}
Telegram::RequestHandler readFileFrom(Database &db) {
return [&](const auto &bot, const auto &req) {
spdlog::info("chat id {} requested file with key {}", req.chatId, req.key);
if (auto file = db[req.chatId][req.key]; !file.empty()) {
bot.reply(req.chatId, req.messageId, file);
spdlog::info("chat id {} found file id {} by key {}", req.chatId, file, req.key);
}
};
}
int main() {
Database db;
std::mutex mutex;
Telegram::Bot(getenv("TOKEN"))
.onFile(saveFileTo(db, mutex))
.onRequest(readFileFrom(db))
.run();
} | true |
4fdeaf25124ad9410aacc36dcf926592e83f26d8 | C++ | soarhigh03/baekjoon-solutions | /solutions/prob1520/solution_c++.cc | UTF-8 | 1,157 | 2.921875 | 3 | [] | no_license | /*
* Baekjoon Online Judge #1520
* https://www.acmicpc.net/problem/1520
*/
#include <cstdio>
#include <cstring>
using namespace std;
int in_m, in_n, in_grid[501][501], cache[501][501];
bool range_check(int y, int x) {
bool result = y >= 0 && y < in_m && x >= 0 && x < in_n;
return result;
}
int pathfind(int y, int x) {
if (y == in_m - 1 && x == in_n - 1) return 1;
if (!range_check(y, x)) return 0;
int &ret = cache[y][x];
if (ret != -1) return ret;
int result = 0;
if (in_grid[y][x] > in_grid[y + 1][x])
result += pathfind(y + 1, x);
if (in_grid[y][x] > in_grid[y - 1][x])
result += pathfind(y - 1, x);
if (in_grid[y][x] > in_grid[y][x + 1])
result += pathfind(y, x + 1);
if (in_grid[y][x] > in_grid[y][x - 1])
result += pathfind(y, x - 1);
ret = result;
return ret;
}
int main() {
scanf("%d %d", &in_m, &in_n);
memset(in_grid, 0, sizeof(in_grid));
for (int y = 0; y < in_m; ++y)
for (int x = 0; x < in_n; ++x)
scanf("%d", &in_grid[y][x]);
memset(cache, -1, sizeof(cache));
printf("%d\n", pathfind(0, 0));
return 0;
}
| true |
4da44e1446aefb639475837be5fab147c9111b22 | C++ | rodrigosetti/centurion | /test/interactive/audio/music/interactive_music.cpp | UTF-8 | 5,005 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <utility> // move
#include "centurion.hpp"
#include "event.hpp"
#include "music.hpp"
#include "renderer.hpp"
#include "texture.hpp"
#include "window.hpp"
namespace {
inline constexpr cen::iarea windowSize{800, 600};
inline constexpr auto msgZero = "\"0\" to play the click one time.";
inline constexpr auto msgOne = "\"1\" to play the click one time.";
inline constexpr auto msgTwo = "\"2\" to play the click two times.";
inline constexpr auto msgNine = "\"9\" to play the click forever.";
inline constexpr auto msgFadeIn = "\"F\" to fade in the music over 5 seconds.";
inline constexpr auto msgEsc = "\"ESC\" to halt the music.";
inline constexpr auto msgPlayingMusic = "Music is playing!";
inline constexpr auto msgFadingMusic = "Music is fading!";
inline constexpr auto msgNoMusic = "No music is playing";
struct messages final
{
cen::texture infoZero;
cen::texture infoOne;
cen::texture infoTwo;
cen::texture infoNine;
cen::texture infoFadeIn;
cen::texture infoEsc;
cen::texture playingMusic;
cen::texture fadingMusic;
cen::texture noMusic;
[[nodiscard]] static auto make(cen::renderer& renderer, cen::font& font)
-> messages
{
renderer.set_color(cen::colors::white);
renderer.set_color(cen::colors::green);
auto playing = renderer.render_blended_latin1(msgPlayingMusic, font);
renderer.set_color(cen::colors::magenta);
auto fading = renderer.render_blended_latin1(msgFadingMusic, font);
renderer.set_color(cen::colors::red);
auto paused = renderer.render_blended_latin1(msgNoMusic, font);
return messages{renderer.render_blended_latin1(msgZero, font),
renderer.render_blended_latin1(msgOne, font),
renderer.render_blended_latin1(msgTwo, font),
renderer.render_blended_latin1(msgNine, font),
renderer.render_blended_latin1(msgFadeIn, font),
renderer.render_blended_latin1(msgEsc, font),
std::move(playing),
std::move(fading),
std::move(paused)};
}
};
class interactive_music final
{
public:
interactive_music()
: m_window{}
, m_renderer{m_window}
, m_song{"resources/hiddenPond.mp3"}
, m_click{"resources/click.wav"}
, m_font{"resources/fira_code.ttf", 14}
{
m_window.set_size(windowSize);
m_window.set_title("Interactive music test");
}
void run()
{
const auto msgs = messages::make(m_renderer, m_font);
m_window.show();
bool running = true;
while (running)
{
running = handle_input();
render(msgs);
}
m_window.hide();
}
private:
cen::window m_window;
cen::renderer m_renderer;
cen::music m_song;
cen::music m_click;
cen::font m_font;
[[nodiscard]] auto handle_input() -> bool
{
cen::event event;
while (event.poll())
{
if (event.is<cen::quit_event>())
{
return false;
}
if (const auto* key = event.try_get<cen::keyboard_event>();
key && key->released())
{
if (key->is_active(cen::scancodes::zero))
{
m_click.play(0);
}
else if (key->is_active(cen::scancodes::one))
{
m_click.play(1);
}
else if (key->is_active(cen::scancodes::two))
{
m_click.play(2);
}
else if (key->is_active(cen::scancodes::nine))
{
m_click.play(cen::music::forever);
}
else if (key->is_active(cen::scancodes::f))
{
m_song.fade_in(cen::seconds<int>{5});
}
else if (key->is_active(cen::scancodes::escape))
{
cen::music::halt();
}
}
}
return true;
}
void render(const messages& msgs)
{
auto nextPos = [y = 50](const cen::texture& texture) mutable {
const auto x = (windowSize.width - texture.width()) / 2;
const auto tmpY = y;
y += 25;
return cen::ipoint{x, tmpY};
};
m_renderer.clear_with(cen::colors::black);
m_renderer.render(msgs.infoZero, nextPos(msgs.infoZero));
m_renderer.render(msgs.infoOne, nextPos(msgs.infoOne));
m_renderer.render(msgs.infoTwo, nextPos(msgs.infoTwo));
m_renderer.render(msgs.infoNine, nextPos(msgs.infoNine));
m_renderer.render(msgs.infoFadeIn, nextPos(msgs.infoFadeIn));
m_renderer.render(msgs.infoEsc, nextPos(msgs.infoEsc));
constexpr cen::ipoint offset{0, 25};
if (cen::music::is_playing() && !cen::music::is_fading())
{
m_renderer.render(msgs.playingMusic, nextPos(msgs.playingMusic) + offset);
}
else if (cen::music::is_fading())
{
m_renderer.render(msgs.fadingMusic, nextPos(msgs.fadingMusic) + offset);
}
else
{
m_renderer.render(msgs.noMusic, nextPos(msgs.noMusic) + offset);
}
m_renderer.present();
}
};
} // namespace
int main(int, char**)
{
const cen::library lib;
interactive_music im;
im.run();
return 0;
} | true |