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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
eed0eafcf0d6591d78113aff4f29b2ee55edba4a | C++ | xiaji/noip-csp | /reference.cpp | UTF-8 | 849 | 3.734375 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
void times_ref(int& a, int& b) {
a *= 2;
b *= 2;
}
void times(int a, int b) {
a *= 2;
b *= 2;
}
void prevnext(int x, int& prev, int& next) {
prev = x * 2;
next = prev + 1;
}
int main() {
int a = 2, b = 3;
times(a, b);
cout << "call times method without ampersand sign (&): ";
cout << "a: " << a << " b: " << b << endl;
times_ref(a, b);
cout << "call times method with ampersand sign: ";
cout << "a: " << a << " b: "<< b << endl;
prevnext(0, a, b);
cout << "call prevnext(int x, int& prev, int& next): ";
cout << "a: " << a << " b: "<< b << endl;
int& temp = a;
int x = temp;
temp = 10;
cout << "x: " << x << " temp: " << temp << " a: " << a << endl;
cout << "x: " << &x << endl;
cout << "temp: " << &temp << endl;
cout << "a: " << &a << endl;
return 0;
}
| true |
fd4022ea2173832db22f3989704beba4ccc8eacf | C++ | Laci101/prog1 | /Drill19/main.cpp | UTF-8 | 1,825 | 3.765625 | 4 | [] | no_license | #include "../std_lib_facilities.h"
template <typename T>
struct S
{
private:
T val;
public:
S(T val){this->val=val;}
T& get();
T& get() const;
void set(const T&);
void operator= (const T&);
};
template <typename T>
T& S<T> :: get()
{
return this->val;
}
template <typename T>
T& S<T> :: get() const
{
return this->val;
}
template<typename T>
void S<T> :: set(const T& a)
{
val = a;
}
template<typename T>
void S<T> :: operator= (const T& a)
{
val = a;
}
template<typename T>
void read_val(T& v)
{
cin>>v;
}
template<typename T>
ostream& operator<<(ostream& os, vector<T>& v)
{
os << "{ ";
for (int i = 0; i < v.size(); ++i) {
os << v[i] << (i < v.size() - 1 ? ", " : " ");
}
os << "}";
return os;
}
int main()
{
S<int> i(1);
S<char> c('a');
S<double> d(1.23);
S<string> s("abcde");
S<vector<int>> v(vector<int>{1,2,3});
cout<<"Kiiras"<<endl;
cout<<i.get()<<endl;
cout<<c.get()<<endl;
cout<<d.get()<<endl;
cout<<s.get()<<endl;
for(int i : v.get())
cout<< i <<" ";
cout<<endl;
cout<<"Adj meg egy integert: ";
int ii;
read_val(ii);
i.set(ii);
cout<< i.get()<<endl;
cout<<"Adj meg egy karaktert: ";
char cc;
read_val(cc);
c.set(cc);
cout << c.get()<<endl;
cout<<"Adj meg egy doublet: ";
double dd;
read_val(dd);
d.set(dd);
cout << d.get() << endl;
cout << "Adj meg egy stringet: ";
string ss;
read_val(ss);
s.set(ss);
cout << s.get() << endl;
cout << "Adj meg 3 integert a vektorba: ";
vector<int> v2;
int temp;
for (int i = 0; i < 3; ++i)
{
read_val(temp);
v2.push_back(temp);
};
v.set(v2);
cout << "Vektor" << v.get() << endl;
return 0;
} | true |
16848b7bdbba7779e1e9b213abac9957ae1ed627 | C++ | Jason-zzzz/vscpp | /priority_queue容器适配器/priority_queue容器适配器/priority_queue容器适配器.cpp | GB18030 | 1,526 | 3.828125 | 4 | [] | no_license | #include <functional>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
//priority_queue
template<typename T>
void list_pq(priority_queue<T> pq, size_t count = 5)
{
size_t n{ count };
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
if (--n) continue;
cout << endl;//5ʱ
n = count;
}
cout << endl;
}
int main()
{
//һȶ
//priority_queue<string> words;
//ʼ
string wordss[]{ "one","two","three","four" };
priority_queue<string> words{ begin(wordss),end(wordss) };//
//
priority_queue<string> copy_words{ words };
//Զ
priority_queue<string, vector<string>, greater<string>> words1{ begin(wordss),end(wordss) };
priority_queue<string, deque<string>> words2{ begin(wordss),end(wordss) };//deque
//dequevectorʼpriority_queue
vector<int> values{ 21,22,12,3,24,54,56 };
priority_queue<int> numbers{ less<int>(),values };//ʼԪ)
//ʹ
priority_queue<string> inWords;
string word;
cout << "Enter words separated by spaces, enter Ctrl+Z on a separate line to end:\n";
while (true)
{
if ((cin >> word).eof())
break;
inWords.push(word);
}
//гݵͬʱݶʧ
priority_queue<string> inWords_copy{ inWords };
while (!inWords_copy.empty())
{
cout << inWords_copy.top() << endl;
inWords_copy.pop();
}
cout << endl;
list_pq(inWords);
system("pause");
return 0;
} | true |
2fee5307fc9ccdbb0921a27ccb5ff8fa3384ca46 | C++ | rabzgg/Random-Competitive-Programming | /Ngoding Seru Oktober 2015 Divisi Pejuang/Kisah Katak Dalam Sumur.cpp | UTF-8 | 409 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int max = 0, min = 1000000, hasil, x, y, i;
cin >> x >> y;
int arr[x];
for(i=0; i<x; i++){
cin >> arr[i];
if(arr[i] > max)
max = arr[i];
}
for(i=0; i<x; i++){
if(arr[i] < min && max + arr[i] >= y)
min = arr[i];
}
hasil = max + min;
cout << hasil << endl;
return 0;
}
| true |
698e39cf247d8df53a35bd60bbdbe9afb0595145 | C++ | yashsingla/UCA | /Greedy Algorithms/huffman_code.cpp | UTF-8 | 3,692 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<map>
#include<vector>
using namespace std;
struct node
{
int key;
char ch;
struct node *left;
struct node *right;
int b;
};
struct node *createNode(int k1,char c1,char p)
{
struct node *temp=new node;
temp->key=k1;
temp->ch=c1;
temp->left=NULL;
temp->right=NULL;
if(p=='l')
temp->b=0;
else if(p=='r')
temp->b=1;
else
temp->b=-1;
};
void swap1(char *x,char *y)
{
char temp= *x;
(*x) = (*y);
(*y) = temp;
}
void swap2(int *x,int *y)
{
int temp= *x;
(*x) = (*y);
(*y) = temp;
}
void min_heapify(map<char,int>&m,char arr[],int freq[],int n,int i)
{
int left=2*i+1;
int right=2*i+2;
int smallest;
if(left<n&& m[arr[i]]>m[arr[left]] )
smallest=left;
else
smallest=i;
if(right<n&& m[arr[smallest]]>m[arr[right]] )
smallest=right;
if(i!=smallest)
{
swap1(&arr[i],&arr[smallest]);
swap2(&freq[i],&freq[smallest]);
min_heapify(m,arr,freq,n,smallest);
}
}
char extractMin(char arr[],int freq[],int *n,map<char,int>&m)
{
char temp=arr[0];
arr[0]=arr[(*n)-1];
min_heapify(m,arr,freq,(*n)-1,0);
(*n)=(*n)-1;
return temp;
}
void bottom_to_up(int parent,int k,char arr[],int freq[],map<char,int>&m)
{
if( (m[arr[parent]]) > (m[arr[k]]) )
{
swap1(&arr[parent],&arr[k]);
swap2(&freq[parent],&freq[k]);
bottom_to_up( (parent-1)/2,parent,arr,freq,m);
}
}
void insert_min_heap(char ch,int val,char arr[],int freq[],map<char,int>&m,int *n)
{
int k=(*n);
arr[k]=ch;
freq[k]=val;
int parent=(k-1)/2;
bottom_to_up(parent,k,arr,freq,m);
(*n)=k+1;
}
struct node *createMinHeap(char arr[],int freq[],int n)
{
struct node *temp=NULL;
map<char,int> m;
map<int,struct node*> n1;
int i;
for(i=0;i<n;i++)
m[arr[i]] = freq[i];
for(i=(n-1)/2;i>=0;i--)
min_heapify(m,arr,freq,n,i);
int k=n;
for(i=0;i<n-1;i++)
{
char a=extractMin(arr,freq,&k,m);
char b=extractMin(arr,freq,&k,m);
int val=m[a]+m[b];
char ch=char(i+'0');
m[ch]=val;
insert_min_heap(ch,val,arr,freq,m,&k);
cout<<"val:"<<val<<endl;
temp=createNode(val,ch,'m');
n1[val]=temp;
if(n1[m[a]]==NULL){
temp->left=createNode(m[a],a,'l');
}
else{
temp->left=n1[m[a]];
temp->left->b=0;
}
if(n1[m[b]]==NULL){
temp->right=createNode(m[b],b,'r');
}
else{
temp->right=n1[m[b]];
temp->right->b=1;
}
m.erase(a);
m.erase(b);
}
return temp;
}
void printArr(int p[],int n)
{
int i;
for(i=0;i<n;i++)
cout<<p[i];
cout<<endl;
}
void traverse(struct node *root,int p[],int top)
{
if(root->left)
{
p[top]=0;
traverse(root->left,p,top+1);
}
if(root->right)
{
p[top]=1;
traverse(root->right,p,top+1);
}
if(!root->left&&!root->right)
{
cout<<root->ch<<":";
printArr(p,top);
}
}
void wrapper(char arr[],int freq[],int n)
{
struct node *root=createMinHeap(arr,freq,n);
//cout<<root->right->right->ch;
int p[15];
traverse(root,p,0);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
// int freq[] = {45, 9, 16, 13, 12, 5};
int freq[] = {5, 9, 12, 13, 16, 45};
int s = sizeof(arr)/sizeof(arr[0]);
wrapper(arr,freq,s);
}
| true |
214836f850b7cef1ca6c23912a57c9b031c7229a | C++ | marshal20/Sockets | /Examples/DomainNameToIP/main.cpp | UTF-8 | 670 | 2.890625 | 3 | [] | no_license | #include <Network/Network.hpp>
#include <iostream>
using namespace nt; // Not recommended.
int main(int argc, char* argv[]) try
{
if (argc != 2)
{
std::cout << "- Usage " << argv[0] << " <domain name>" << std::endl;
return 1;
}
char* domainName = argv[1];
std::vector<Address> addrs = Address::FromPresentationAll(domainName);
std::cout << "Addresses(" << addrs.size() << ") for " << domainName << ":" << std::endl;
for (auto addr : addrs)
std::cout << ProtocolToString(addr.GetFamily()) << ": " << addr.GetPresentation() << std::endl;
return 0;
}
catch (std::exception& e)
{
std::cout << "- Error:" << std::endl << e.what() << std::endl;
return 1;
}
| true |
1152838b3777b76f2d8613065bdf8cb54fe9c06e | C++ | AkiraGiShinichi/qt-cpp-tutorial | /x20TcpServerClient_QML/Client/backend.cpp | UTF-8 | 1,955 | 2.65625 | 3 | [] | no_license | #include "backend.h"
#include <QDataStream>
Backend::Backend(QObject *parent) : QObject(parent)
{
qDebug() << " * Backend::Backend";
client = new ClientStuff("localhost", 6547);
connect(client, &ClientStuff::statusChanged, this, &Backend::setStatus);
connect(client, &ClientStuff::hasReadSome, this, &Backend::receivedSomething);
connect(client->tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(gotError(QAbstractSocket::SocketError)));
}
bool Backend::getStatus()
{
qDebug() << " * Backend::getStatus";
return client->getStatus();
}
void Backend::setStatus(bool newStatus)
{
qDebug() << " * Backend::setStatus";
if (newStatus) emit statusChanged("CONNECTED");
else emit statusChanged("DISCONNECTED");
}
void Backend::receivedSomething(QString msg)
{
qDebug() << " * Backend::receivedSomething";
emit someMessage(msg);
}
void Backend::gotError(QAbstractSocket::SocketError err)
{
qDebug() << " * Backend::gotError";
QString strError = "unknown";
switch (err) {
case 0:
strError = "Connection was refused";
break;
case 1:
strError = "Remote host closed the connection";
break;
case 2:
strError = "Host address was not found";
break;
case 5:
strError = "Connection timed out";
break;
default:
strError = "Unknown error";
}
}
void Backend::connectClicked()
{
qDebug() << " * Backend::connectClicked";
client->connectToHost();
}
void Backend::disconnectClicked()
{
qDebug() << " * Backend::disconnectClicked";
client->closeConnection();
}
void Backend::sendClicked(QString msg)
{
qDebug() << " * Backend::sendClicked";
QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out << quint16(0) << msg;
out.device()->seek(0);
out << quint16(arrBlock.size() - sizeof(quint16));
client->tcpSocket->write(arrBlock);
}
| true |
d261bb608f9136d86aee52cd8eddf2dd2a496cc0 | C++ | FresBlueMan/EmployeeRecordSystem | /EmployeeRecordSystem/EmployeeRecordSystem.cpp | UTF-8 | 8,162 | 3.09375 | 3 | [] | no_license | // EmployeeRecordSystem.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 50
typedef struct Employee{
int Eid;
char Name[SIZE];
char Email[SIZE];
struct Employee *Next;
} Employee;
Employee *empHead= NULL;
FILE *file;
int fileOpen();
void fileStore(int);
// To open the file, return 0 if couldn't open the file else return 1
int fileOpen(){
file = fopen("data2.txt","a+");
if(file == NULL){
printf("\n\n\t Sorry! Unable to open/create the file");
return 0;
}
else{
return 1;
}
}
// Closing the file
void fileClose(){
fclose(file);
}
// Initializing the first node
void initialization(){
empHead = (Employee*)malloc(sizeof( Employee));
Employee *tempHead = ( Employee*)malloc(sizeof( Employee));
int Eid;
char Name[SIZE];
char Email[SIZE];
empHead->Next = NULL;
while(fscanf(file, "%d %s %s",&Eid,Name,Email) != EOF){
Employee *newEmployee = (Employee*)malloc(sizeof( Employee));
newEmployee->Eid = Eid;
strcpy(newEmployee->Name,Name);
strcpy(newEmployee->Email,Email);
newEmployee->Next = NULL;
if(empHead->Next == NULL){
empHead->Next = newEmployee;
}
else{
tempHead = empHead->Next;
while(tempHead != NULL){
if(tempHead->Next == NULL){
tempHead->Next = newEmployee;
break;
}
tempHead = tempHead->Next;
}
}
}
fileClose();
}
// To create a new node
void create(){
//system("cls");
int f = 0, Eid;
Employee *newEmployee = (Employee*)malloc(sizeof( Employee));
Employee *tempHead = ( Employee*)malloc(sizeof( Employee));
printf("\n\t ID :");
scanf("%d",&Eid);
tempHead = empHead->Next;
f = 0;
while(tempHead != NULL){
if(tempHead->Eid == Eid){
f = 1;
printf("\n\n\t Sorry! Employee with same ID already exists");
break;
}
tempHead = tempHead->Next;
}
if(f == 0){
newEmployee->Eid = Eid;
printf("\n\t Name :");
getchar();
gets(newEmployee->Name);
printf("\n\t Email :");
gets(newEmployee->Email);
newEmployee->Next = NULL;
if(empHead->Next == NULL){
empHead->Next = newEmployee;
}
else{
tempHead = empHead->Next;
while(tempHead != NULL){
if(tempHead->Next == NULL){
tempHead->Next = newEmployee;
break;
}
tempHead = tempHead->Next;
}
}
}
fileStore(newEmployee->Eid);
tempHead = NULL;
newEmployee = NULL;
fflush(stdin);
getchar();
}
// To update a particular Employee record
void update(){
system("cls");
Employee *tempHead = ( Employee*)malloc(sizeof( Employee));
int Eid, i = 0; // Taking Employee ID as input to search for the specific employee
printf("\nEnter Employee ID:");
scanf("%d",&Eid);
getchar();
tempHead = empHead->Next;
while(tempHead != NULL){
if(tempHead->Eid == Eid){ // If Employee ID is matched, showing the Employee record
printf("\nCurrent \t-\t ID : %d \t New \t-\t ID :",tempHead->Eid);
printf("%d",tempHead->Eid);
//getchar();
printf("\nCurrent \t-\t Name : %s \t New \t-\t Name :",tempHead->Name);
gets(tempHead->Name);
printf("\nCurrent \t-\t Email : %s \t New \t-\t Email :",tempHead->Email);
gets(tempHead->Email);
i = 1;
break;
} // Validating Employee ID
tempHead = tempHead->Next;
}
if(i == 0){
printf("\n\n\t Sorry! No matching record found.");
}
// Updating from file
file = fopen("data2.txt","w");
tempHead = empHead->Next;
while(tempHead != NULL){
fprintf(file,"%d %s %s \n",tempHead->Eid,tempHead->Name,tempHead->Email);
tempHead = tempHead->Next;
}
fileClose();
getchar();
}
// Display specific employee data
void displayOne(){
system("cls");
Employee *tempHead = ( Employee*)malloc(sizeof( Employee));
int Eid, f = 0; // Taking Employee ID as input to search for the specific employee
printf("\nEnter Employee ID:");
scanf("%d",&Eid);
tempHead = empHead->Next;
while(tempHead != NULL){
if(tempHead->Eid == Eid){ // If Employee ID is matched, showing the Employee record
printf("\n\t ID : %d",tempHead->Eid);
printf("\n\t Name : %s",tempHead->Name);
printf("\n\t Email : %s",tempHead->Email);
f = 1;
break;
} // Validating Employee ID
tempHead = tempHead->Next;
}
if(f == 0){
printf("\n\n\t Sorry! No matching record found.");
}
getchar();
}
// Display
void displayAll(){
system("cls");
Employee *tempHead = ( Employee*)malloc(sizeof( Employee));
tempHead = empHead->Next;
if(tempHead == NULL){
printf("\n\n\t Sorry! There is no record available");
}
else{
printf("\n\n\t List of all employees \n\n");
while(tempHead != NULL){
printf("\n\t ID : %d",tempHead->Eid);
printf("\n\t Name : %s",tempHead->Name);
printf("\n\t Email : %s",tempHead->Email);
tempHead = tempHead->Next;
}
}
getchar();
}
// Deallocating Memory
void dealloc(){
system("cls");
Employee *delEmployee = (Employee*)malloc(sizeof( Employee));
Employee *prevEmployee = (Employee*)malloc(sizeof( Employee));
int Eid;
printf("\n Enter Employee ID:");
scanf("%d",&Eid);
if(empHead->Next == NULL){
printf("\n No record found");
}
else{
delEmployee = empHead->Next;
prevEmployee = empHead;
while(delEmployee != NULL){
if(delEmployee->Eid == Eid){
prevEmployee->Next = delEmployee->Next;
free(delEmployee);
printf("\n\t Record has been deleted");
break;
}
prevEmployee = delEmployee;
delEmployee = delEmployee->Next;
}
}
// Deleting from file
file = fopen("data2.txt","w");
Employee *tempHead = (Employee*)malloc(sizeof( Employee));
tempHead = empHead->Next;
while(tempHead != NULL){
fprintf(file,"%d %s %s \n",tempHead->Eid,tempHead->Name,tempHead->Email);
tempHead = tempHead->Next;
}
fileClose();
getchar();
}
void fileDisplay(){
if(fileOpen()){
int Eid;
char Name[SIZE];
char Email[SIZE];
fseek(file,1,0);
while(fscanf(file,"%d %s %s",&Eid,Name,Email) != EOF){
printf("\n %d %s %s",Eid,Name,Email);
}
}
else{
system("cls");
printf("\n\n\t File could not be opened");
getchar();
}
fileClose();
}
// Strong into file
void fileStore(int Eid){
fileOpen();
Employee *tempHead = (Employee*)malloc(sizeof( Employee));
tempHead = empHead->Next;
while(tempHead != NULL){
if(tempHead->Eid == Eid){ // If Employee ID is matched, showing the Employee record
fprintf(file,"%d %s %s \n",tempHead->Eid,tempHead->Name,tempHead->Email);
system("cls");
//printf("\n\t %d",tempHead->Eid);
//printf("\n\t %s",tempHead->Name);
//printf("\n\t %s",tempHead->Email);
printf("\n\n Record has been saved");
break;
} // Validating Employee ID
tempHead = tempHead->Next;
}
fileClose();
}
int main()
{
int i = 0;
if(fileOpen()){
initialization();
while(i < 5 ){
system("cls");
printf("\n 1. Insert Record");
printf("\n 2. Update Record");
printf("\n 3. Delete Record");
printf("\n 4. Display Record");
printf("\n 5. Exit \n");
scanf(" %d",&i);
switch(i){
case 1: create(); break;
case 2: update(); break;
case 3: dealloc(); break;
case 4: system("cls");
printf("\n 1. Display One Record");
printf("\n 2. Display All \n");
scanf(" %d",&i);
if(i == 1) displayOne();
else displayAll();
break;
}
getchar();
}
}
/*
fileOpen();
initialization();
create();
create();
create();
displayAll();
*/
return 0;
} | true |
f131180fab2cf1575b1b6af2d301596a32f17a98 | C++ | Nickolas1987/simple_promise | /tests/promise_tests/main.cpp | UTF-8 | 1,360 | 2.921875 | 3 | [] | no_license | #include <promise.h>
#include <async_call.h>
#include <gtest/gtest.h>
#include <thread>
#include <iostream>
#include <chrono>
using namespace std::chrono_literals;
class TestLog : public ::testing::Test
{
protected:
void SetUp()
{
}
void TearDown()
{
}
};
TEST_F(TestLog, test1)
{
auto foo = [](int val)->int{
std::cout << "foo" <<std::endl;
return val*10;
};
auto bar = [](int in, int add)->int{
std::this_thread::sleep_for(5s);
std::cout << "bar" <<std::endl;
return in + add;
};
auto dom = []{
std::cout << "void func" << std::endl;
};
a_promise_namespace::async_call([&]()->int{
return foo(10);
}).then([&](int val)->int {
return bar(val,7);
}).then([](int res) {
std::cout << " result " << res << std::endl;
throw std::runtime_error("test exception");
}).then([]() {}, [](const std::exception_ptr& e) {
try {
std::rethrow_exception(e);
}
catch (std::runtime_error& ex) {
std::cout << ex.what() << std::endl;
}
catch (...) {
}
}).finish();
a_promise_namespace::async_call(dom).finish();
std::cout << "other action" << std::endl;
std::cin.get();
}
| true |
4e2c30161e9bef7e93e6d994d9de63b6b70a476e | C++ | OjusWiZard/CompetitiveProgramming | /CodeChef/CHFMOT18.cpp | UTF-8 | 438 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio( false ) ;
cin.tie( NULL ) ;
int t ;
cin>>t ;
while( t-- )
{
int s, n ;
cin>>s>>n ;
if( s<=n )
{
if( s%2==0 || s==1 ) cout<<1<<"\n" ;
else cout<<2<<"\n" ;
}
else
{
int ans = s/n ;
s = s%n ;
if( s%2&&s!=1 ) cout<<ans+2<<"\n" ;
else if( s!=0 ) cout<<ans+1<<"\n" ;
else cout<<ans<<"\n" ;
}
}
return 0 ;
} | true |
77075ff1f67a6d5784817876c4102435d6e6bd9c | C++ | mongobaba/learn_qt | /67_ExecuteCommand/mainwindow.cpp | UTF-8 | 1,404 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
command = new QLineEdit(this);
command->setText(tr("ipconfig"));
command->setGeometry(QRect(20, 20, 400, 25));
execute = new QPushButton(tr("执行"), this);
execute->setGeometry(QRect(430, 20, 90, 25));
connect(execute, SIGNAL(clicked()), this, SLOT(executeCommand()));
output = new QPlainTextEdit(this);
output->setGeometry(QRect(20, 60, 500, 400));
process = new QProcess();
connect(process, SIGNAL(readyRead()), this, SLOT(readOutput()));
// label是完全独立的演示,跟其他部分没关系
label = new QLabel(this);
label->setGeometry(QRect(30, 470, 200, 24));
label->setText(tr("<a href=\"http://www.baidu.com/s?wd=dos 命令大全\">命令 DOS 查阅</a>"));
label->setOpenExternalLinks(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::executeCommand()
{
// 执行前清空result和output内容,避免多次执行时信息叠加
result.clear();
output->setPlainText(result);
QString cmd = command->text();
process->start(cmd);
}
void MainWindow::readOutput()
{
// 进程输出为本地编码,需要转换
result += QString::fromLocal8Bit(process->readAll());
output->setPlainText(result);
}
| true |
622de720f02ea244f04226d9f4bc5e4b966bc8ad | C++ | JSYoo5B/TIL | /PS/BOJ/10845/10845_with_stl.cc | UTF-8 | 904 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <queue>
using namespace std;
int main(void) {
queue<int> my_queue;
int cases;
cin >> cases;
for (int i = 0; i < cases; i++) {
string operation;
int temp;
cin >> operation;
if (operation.compare("push") == 0) {
cin >> temp;
my_queue.push(temp);
}
else if (operation.compare("pop") == 0) {
if (my_queue.empty()) {
cout << -1 << '\n';
}
else {
cout << my_queue.front() << '\n';
my_queue.pop();
}
}
else if (operation.compare("size") == 0) {
cout << my_queue.size() << '\n';
}
else if (operation.compare("empty") == 0) {
cout << (my_queue.empty() ? 1 : 0) << '\n';
}
else if (operation.compare("front") == 0) {
cout << (my_queue.empty() ? -1 : my_queue.front()) << '\n';
}
else if (operation.compare("back") == 0) {
cout << (my_queue.empty() ? -1 : my_queue.back()) << '\n';
}
}
} | true |
61c46061e5e39f2ce57e56aac15bac39560d69ac | C++ | bananaappletw/online-judge | /codility/min_perimeter_rectangle.cpp | UTF-8 | 300 | 3 | 3 | [
"MIT"
] | permissive | // you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
#include<cmath>
int solution(int N) {
for(int i=sqrt(N); i>=1; i--)
{
if(N%i==0)
return 2*(N/i+i);
}
}
| true |
2057545d45ef009aa897845fe50685464fdc26a9 | C++ | shamrickus/ComputerVision | /src/Objects/Axis.h | UTF-8 | 1,674 | 2.84375 | 3 | [] | no_license | #ifndef _AXIS_H_
#define _AXIS_H_
#include "Object.h"
#include "../Buffer/DeviceBuffer.h"
#include "../Shaders/ShaderProgram.h"
#include <vector>
#include "../Colors.h"
class Axis : public Object
{
public:
Axis(glm::vec3 pBase) : Object(pBase)
{
program_ = new ShaderProgram();
auto vs = new Shader(v_passthru, Vertex);
auto fs = new Shader(f_passthru, Fragment);
program_->AttachShader(vs);
program_->AttachShader(fs);
program_->Link();
size_ = glm::vec3(1);
float line[3 * 2];
line[0] = 0;
line[1] = 0;
line[2] = 0;
for(int i = 0; i < 3; ++i)
{
int x = i == 0 ? 1 : 0;
int y = i == 1 ? 1 : 0;
int z = i == 2 ? 1 : 0;
line[3] = x;
line[4] = y;
line[5] = z;
auto vbo = new DeviceBuffer();
auto vao = new VertexBuffer(Line);
vbo->BindData(3 * 2 * sizeof(float), line);
auto tup = std::tuple<VertexBuffer*, DeviceBuffer*, float*> (vao, vbo, line);
buffers_.push_back(tup);
}
}
void Draw(glm::mat4 pMVP) override
{
program_->Activate();
auto mvpHandle = program_->GetHandle("MVP");
auto mvp = pMVP * GetScreenTransform();
glUniformMatrix4fv(mvpHandle, 1, GL_FALSE, &mvp[0][0]);
auto colorHandle = program_->GetHandle("nColor");
glm::vec3 color;
for(int i = 0; i < buffers_.size(); ++i)
{
auto buffer = buffers_[i];
auto vao = std::get<0>(buffer);
auto vbo = std::get<1>(buffer);
vao->Bind();
vao->BindAttrib(vbo, 0, 3);
color = i == 0 ? Red() : i == 1 ? Green() : Blue();
glUniform3fv(colorHandle, 1, &color[0]);
vao->Draw(3 * 2);
}
}
protected:
std::vector<std::tuple<VertexBuffer*, DeviceBuffer*, float*> > buffers_;
ShaderProgram* program_;
};
#endif | true |
6c8708b39264ebb2727bb2929a044bc9abbe9ca7 | C++ | AndyDentFree/oofile | /source/rep_char/oofrw.h | UTF-8 | 9,781 | 2.5625 | 3 | [] | no_license | #ifndef H_OOFRW
#define H_OOFRW
// COPYRIGHT 1994 A.D. Software, All rights reserved
/**
\file oofrw.h
Old simple character mode report-writer classes.
*/
/**
\defgroup oofCharRW OOFILE Character-mode simple report writer.
Simple reports that output just one table formatted as plain
text with spaces and returns or simple HTML.
Included in the Open Source OOFILE.
\ingroup Presentation
*/
// NOTE inline definitions included at end of this header file
#ifndef H_OOF2
#include "oof2.h"
#endif
#ifndef H_OOFVIEW
#include "oofview.h"
#endif
/**
Set of column widths as characters.
\ingroup oofCharRW
*/
class OOFILE_EXPORT dbRepColWidths : public OOF_ExpandableLongArray {
public:
// construction
dbRepColWidths (unsigned int defColWidth=20) :
OOF_ExpandableLongArray(defColWidth) {};
// use default copy ctor
dbRepColWidths& operator<<(unsigned int);
};
/**
Contains starting position of a new page within each dbRepLine.
\ingroup oofCharRW
*/
class OOFILE_EXPORT dbRepPageBreak : public OOF_ExpandableLongArray {
public:
// construction
dbRepPageBreak (unsigned int breakPos=0xFFFF) :
OOF_ExpandableLongArray(breakPos) {};
private:
dbRepPageBreak(const dbRepPageBreak&) { assert(0); };
void operator=(const dbRepPageBreak&) { assert(0); };
};
/**
Describe an over-run onto next page.
\ingroup oofCharRW
*/
class dbRepOverRun : public OOF_PublicBase{
public:
dbRepOverRun() :
OverRun(0),
DeleteMe(0) {};
~dbRepOverRun() {};
private:
dbRepOverRun(const dbRepOverRun&) { assert(0); };
void operator=(const dbRepOverRun&) { assert(0); };
public:
char* OverRun;
char* DeleteMe;
};
/**
Line of text to draw in simple character report.
\ingroup oofCharRW
*/
class dbRepLine : public OOF_PublicBase {
public:
dbRepLine() :
mLine(0) {};
~dbRepLine();
private:
dbRepLine(const dbRepLine&) { assert(0); };
void operator=(const dbRepLine&) { assert(0); };
public:
void prepare();
void clear();
void drawNCharsAt(unsigned int hPos, const char* theChars, unsigned int len);
void fillNCharsAt(unsigned int hPos, char theChar, unsigned int len);
void drawToStream(unsigned int hPos, unsigned int len, ostream& os);
char *mLine; // owned // for drawing onto
static unsigned int mWidth; // size of horizontal line - given to us by dbRepPage
};
/**
Report page dimensions & page title.
\ingroup oofCharRW
*/
class OOFILE_EXPORT dbRepSizer : public OOF_PublicBase {
public:
// construction
dbRepSizer (const OOF_String& reportTitle,
unsigned int pageHeight=70,
unsigned int pageWidth=80,
unsigned int leftMargin=0,
unsigned int rightMargin=0,
unsigned int topMargin=1,
unsigned int bottomMargin=1,
unsigned int colSepWidth=2,
unsigned int blockVertSep=1
) :
mReportTitle(reportTitle),
mPageHeight(pageHeight),
mPageWidth(pageWidth),
mLeftMargin(leftMargin),
mRightMargin(rightMargin),
mTopMargin(topMargin),
mBottomMargin(bottomMargin),
mColSepWidth(colSepWidth),
mBlockVertSep(blockVertSep) {};
dbRepSizer (const char * reportTitle="",
unsigned int pageHeight=70,
unsigned int pageWidth=80,
unsigned int leftMargin=0,
unsigned int rightMargin=0,
unsigned int topMargin=1,
unsigned int bottomMargin=1,
unsigned int colSepWidth=2,
unsigned int blockVertSep=1
) :
mReportTitle(reportTitle),
mPageHeight(pageHeight),
mPageWidth(pageWidth),
mLeftMargin(leftMargin),
mRightMargin(rightMargin),
mTopMargin(topMargin),
mBottomMargin(bottomMargin),
mColSepWidth(colSepWidth),
mBlockVertSep(blockVertSep) {};
// use default copy ctor
// setters for use in simulating keyword arguments
// eg dbRep( dbRepSizer("Andy's Report").pageHeight(80).DefColWidth(12) );
dbRepSizer& title(const OOF_String&);
dbRepSizer& title(const char*);
dbRepSizer& pageHeight(unsigned int);
dbRepSizer& pageWidth(unsigned int);
dbRepSizer& leftMargin(unsigned int);
dbRepSizer& rightMargin(unsigned int);
dbRepSizer& topMargin(unsigned int);
dbRepSizer& bottomMargin(unsigned int);
dbRepSizer& colSepWidth(unsigned int);
dbRepSizer& blockVertSep(unsigned int);
// presentation
OOF_String mReportTitle;
unsigned int mPageHeight, mPageWidth, mLeftMargin, mRightMargin, mTopMargin, mBottomMargin;
unsigned int mColSepWidth; // whitespace between columns
unsigned int mBlockVertSep; // whitespace between records on columnar and blocks on pagewise
};
/**
Page, containing lines..
\ingroup oofCharRW
*/
class OOFILE_EXPORT dbRepPage : public OOF_PublicBase {
public:
dbRepPage();
~dbRepPage();
private:
dbRepPage(const dbRepPage&) { assert(0); };
void operator=(const dbRepPage&) { assert(0); };
public:
void draw(dbRepSizer Sizer, ostream& os);
void clearLines(unsigned int start, unsigned int end);
void endPage(ostream& os);
dbRepLine* mPageMap; // array of horizontal bands // owned
unsigned int mWidth; // width of valid lines
unsigned int mNumLines; // number of prinatble lines
unsigned int mBodyStart; // position of data area under header
// to save redrawing the header
unsigned int mNumPages; // number of physical pages
unsigned int* mFieldPos; // starting position of each field // owned
// within each dbRepLine
dbRepPageBreak mPageBreak; // starting position of each new page
// within each dbRepLine
unsigned int* mPageStart; // starting Row on page below Header // owned
};
/**
early report writer providing character-based output.
Only reports a single dbTable - no nested data or graphs.
Has interesting pageWise format which puts field names
on left of wrapped field data.
Still useful for quick dump of a table, or writing simple HTML.
\ingroup oofCharRW
*/
class OOFILE_EXPORT dbRep : public OOF_PublicBase {
public:
enum ReportStyles {pageWise, columnar};
// construction
dbRep(const dbRepSizer& sizer, const dbView& fields, const ReportStyles style):
mSizer(sizer),
mFields(fields),
mReportStyle(style),
mBuilt(false) {};
dbRep(const dbRepSizer& sizer, const dbRepColWidths colWidths, const dbView& fields, const ReportStyles style):
mSizer(sizer),
mFields(fields),
mReportStyle(style),
mColWidths(colWidths),
mBuilt(false) {};
// use default copy ctor
virtual ~dbRep() {};
void setStyle(const ReportStyles);
// presentation
virtual void formatForCharStream() = 0;
virtual void draw(ostream&) = 0;
void extract(ostream&);
char *copyStr(const char *theString);
// accessors
const OOF_String& reportTitle();
protected:
dbRepSizer mSizer;
dbView mFields;
ReportStyles mReportStyle;
dbRepColWidths mColWidths;
bool mBuilt;
};
/**
Write simple text report wrapped with spaces and newlines.
\ingroup oofCharRW
*/
class OOFILE_EXPORT dbRepChar : public dbRep{
public:
// construction
dbRepChar(const dbRepSizer& sizer, const dbView& fields, const ReportStyles style=columnar):
dbRep(sizer, fields, style),
mPage() {};
dbRepChar(const dbRepSizer& sizer, const dbRepColWidths colWidths, const dbView& fields, const ReportStyles style=columnar):
dbRep(sizer, colWidths, fields, style),
mPage() {};
// use default copy ctor
virtual ~dbRepChar() {};
// presentation
virtual void formatForCharStream(); // may be others later
virtual void draw(ostream&);
unsigned int drawWrappedChars(unsigned int line,unsigned int hPos,unsigned int width,char **theString);
void drawColumnar(ostream&);
void drawPageWise(ostream&);
void drawHeader(ostream&);
private:
dbRepPage mPage;
};
// -------------------------------------------------------
// d b R e p
// -------------------------------------------------------
inline const OOF_String&
dbRep::reportTitle()
{
return mSizer.mReportTitle;
}
// -------------------------------------------------------
// d b R e p S i z e r
// -------------------------------------------------------
inline dbRepSizer&
dbRepSizer::title(const OOF_String& reportTitle)
{
mReportTitle = reportTitle;
return *this;
}
inline dbRepSizer&
dbRepSizer::title(const char* reportTitle)
{
mReportTitle = reportTitle;
return *this;
}
inline dbRepSizer&
dbRepSizer::pageHeight(unsigned int pageHeight)
{
mPageHeight = pageHeight;
return *this;
}
inline dbRepSizer&
dbRepSizer::pageWidth(unsigned int pageWidth)
{
mPageWidth = pageWidth;
return *this;
}
inline dbRepSizer&
dbRepSizer::leftMargin(unsigned int leftMargin)
{
mLeftMargin = leftMargin;
return *this;
}
inline dbRepSizer&
dbRepSizer::rightMargin(unsigned int rightMargin)
{
mRightMargin = rightMargin;
return *this;
}
inline dbRepSizer&
dbRepSizer::topMargin(unsigned int topMargin)
{
mTopMargin = topMargin;
return *this;
}
inline dbRepSizer&
dbRepSizer::bottomMargin(unsigned int bottomMargin)
{
mBottomMargin = bottomMargin;
return *this;
}
inline dbRepSizer&
dbRepSizer::colSepWidth(unsigned int colSepWidth)
{
mColSepWidth = colSepWidth;
return *this;
}
inline dbRepSizer&
dbRepSizer::blockVertSep(unsigned int blockVertSep)
{
mBlockVertSep = blockVertSep;
return *this;
}
// -------------------------------------------------------
// d b R e p C o l W i d t h s
// -------------------------------------------------------
// friend
/*inline dbRepColWidths&
operator<<(dbRepColWidths& lhs, unsigned int rhs)
{
lhs.append(rhs);
return lhs;
}
*/
inline dbRepColWidths&
dbRepColWidths::operator<<(unsigned int rhs)
{
append(rhs);
return *this;
}
#endif
| true |
3b2058f82f9c6bd0e1fa2ce4ab0cf9779de3e13e | C++ | DougHamil/WIT | /wit/src/WITApplication.h | UTF-8 | 2,402 | 3.109375 | 3 | [] | no_license | #ifndef WIT_APPLICATION_H
#define WIT_APPLICATION_H
// - Qt
#include <QtGui/QApplication>
// - WIT
#include "Controller/WITMainWindowController.h"
#include "Controller/PathwayController.h"
#include "Controller/SubjectDataController.h"
#include "Model/Undo/UndoSystem.h"
// - STL
#include <vector>
/**
WITApplication is the main application class for WIT. It initializes the models, controllers, and views.
It is a singleton which can be easily accessed using the getInstance() method. Various components can
access one another through this class.
@author Doug Hamilton
*/
class WITApplication
{
public:
/**
This method initializes the WITApplication with the given command line arguments
@param argc number of command line arguments
@param argv array of command line arguments
*/
void initialize(int argc, char *argv[]);
/**
Executes the WITApplication and returns the QApplication error code.
@return QApplication error code
*/
int exec();
/**
Returns a reference to the underlying QApplication
@return Reference to the underlying QApplication
*/
QApplication *getQApplication(){return qApplication;}
/**
Returns the WITMainWindowController object.
@return the WITMainWindowController object
*/
WITMainWindowController *getMainWindowController(){return mainWinController;}
/**
Return the collection of Group objects, each representing a pathway group
@return A GroupCollection object containing each of the pathway groups.
*/
PathwayController *getPathwayController(){return pathwayController;}
SubjectDataController *getSubjectDataController(){return subjectDataController;}
/**
Gets the UndoSystem for the application.
@return The UndoSystem object for the application
*/
UndoSystem *getUndoSystem(){return undoSystem;}
private:
QApplication *qApplication;
WITMainWindowController *mainWinController;
PathwayController *pathwayController;
SubjectDataController *subjectDataController;
UndoSystem *undoSystem;
/*
Singleton
*/
public:
/**
Returns the singleton instance of the WITApplication and creates one if
it isn't already created.
@return the WITApplication singleton instance
*/
static WITApplication& getInstance()
{
static WITApplication instance;
return instance;
}
private:
// - Singleton
WITApplication(){};
WITApplication(WITApplication const&);
void operator=(WITApplication const&);
};
#endif | true |
d5c35f0d7d433c07f33afda126e00a8c2e4ac17b | C++ | varunkverma/cpp-practice-questions | /10-power-of-number/main.cpp | UTF-8 | 853 | 3.828125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int find_powerOfNumber(int n, int p)
{
if (n < 1)
{
return 0;
}
int res = n;
for (int i = 1; i < p; i++)
{
res *= n;
}
return res;
}
int findPowerOfNumber(int n, int p)
{
if (p <= 0)
{
return 1;
}
if (p % 2 == 0)
{
int temp = findPowerOfNumber(n, p / 2);
return temp * temp;
}
return n * findPowerOfNumber(n, p - 1);
}
int findPowerOfNumber2(int n, int p)
{
if (p <= 0)
{
return 1;
}
int temp = findPowerOfNumber2(n, p / 2);
temp *= temp;
if (p % 2 == 0)
{
return temp;
}
return n * temp;
}
int main()
{
cout << find_powerOfNumber(2, 3) << endl;
cout << findPowerOfNumber(5, 3) << endl;
cout << findPowerOfNumber2(5, 3) << endl;
return 0;
} | true |
499652dc30ec8c9f8cf298278420616176de0539 | C++ | NilsHolger/cppplayground | /Documents/Visual Studio 2013/Projects/cppplayground/cppplayground/countfind.cpp | UTF-8 | 1,531 | 2.890625 | 3 | [] | no_license | #include "headers.h"
#include "address.h"
#include "technology.h"
#include "component.h"
#include "compfactory.h"
using namespace std;
//auto main() -> int
//{
// Technology t(80, "t", Technology::on);
// //Technology *t2 = new Technology(50, "t2", Technology::off);
//
// //t2->salute();
// //int v = t.getViability();
// //cout << v << '\n';
//
// //Technology *t3 = new Technology(70, "t3", Technology::off);
// //auto* address = new Address(100, "https", "www");
// //t3->address = address;
// //t3->salute();
//
// //Technology t4(*t3);
// //t3->address->url = "http";
// //cout << t4.address->url << '\n';
//
// Component c(90, "c", Technology::on,"a c c");
//
// auto d = [](const Technology& t)
// {
// cout << t.name << '\n';
// };
// d(c);
//
// Technology &tr = c;
// //Component& cr = static_cast<Component&>(tr);
// //cout << cr.description << '\n';
//
// Technology& tr2 = t;
// //access violation reading location, static_cast performs no checks
// //Component& cr2 = static_cast<Component&>(tr2);
// //cout << cr2.description << '\n';
//
// tr.salute();
// try
// {
// Component& cr2 = dynamic_cast<Component&>(tr2);
// cout << cr2.description << '\n';
// }
// catch (const bad_cast& e)
// {
// cout << "cannot cast this " << e.what() << '\n';
// }
//
// Technology *tt = &t;
// Component *cp = dynamic_cast<Component*>(tt);
// if (cp){
// cout << cp->description << '\n';
// }
// else {
// cout << "failed to cast pointer " << cp << '\n';
// }
//
//
// //delete t2;
// //delete t3;
// getchar();
//}
| true |
b9e24ef901fd725e2174507160ef0865839538f6 | C++ | Fen99/afina | /src/pipes/FIFOServer.h | UTF-8 | 1,017 | 2.546875 | 3 | [] | no_license | #ifndef AFINA_FIFO_SERVER_H
#define AFINA_FIFO_SERVER_H
#include <atomic>
#include <exception>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include "./../protocol/Executor.h"
#include "core/FIFO.h"
#include <afina/Storage.h>
namespace Afina {
namespace FIFONamespace {
class FIFOServer {
private:
std::shared_ptr<Storage> _storage;
std::atomic<bool> _is_running;
std::atomic<bool> _is_stopping;
FIFO _reading_fifo;
FIFO _writing_fifo;
bool _has_out;
std::thread _reading_thread;
Protocol::Executor _executor;
static const int _reading_timeout = 5;
void _ThreadWrapper();
void _ThreadFunction();
public:
FIFOServer(std::shared_ptr<Afina::Storage> storage);
~FIFOServer();
void Start(const std::string &reading_name, const std::string &writing_name);
void Stop();
void Join();
};
} // namespace FIFONamespace
} // namespace Afina
#endif // AFINA_FIFO_SERVER_H
| true |
b3d7147c0cc009db484a407f1f431c900f443d0b | C++ | Team-Jag/Do-or-die-fitness-tracker | /m5/Main/Timer.h | UTF-8 | 1,293 | 3.40625 | 3 | [
"MIT",
"CC0-1.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | #ifndef _TIMER_H
#define _TIMER_H
// A class to help us run code at specified
// time intervals. You might want to use this
// as a template to make your own arduino classes
class Timer {
private:
unsigned long period; // user requested time period
unsigned long last_ts; // saved time stamp
boolean READY = false; // flag if time has elapsed
public:
// Constructor, call with the number of milliseconds
// you wish to schedule some code on.
Timer( unsigned long period_ms , boolean startupState) {
period = period_ms;
READY = startupState;
last_ts = millis();
}
// Call to see if the time period has elapsed
// Note, only reset() will toggle the timer
// back to watching time again.
boolean isReady() {
// Check for elapsed time between system time
// millis and the last time stamp taken
if ( millis() - last_ts > period ) {
READY = true;
}
return READY;
}
// Use to reset your timer.
void reset() {
last_ts = millis(); // save current system time
READY = false; // reset flag to false
}
void setNewPeriod( unsigned long period_ms ) {
period = period_ms;
}
};
#endif
| true |
7becfac0b061e8e357b4da5688c93b5f4077bfe5 | C++ | sandro2112/Mainframes2_Trabajos_Semanales | /Semana 6/Arbol.h | UTF-8 | 1,097 | 3.28125 | 3 | [] | no_license | #include <stdio.h>
#ifndef __ARBOL_HPP__
#define __ARBOL_HPP__
template<typename X>
struct Nodo {
X e;//elemento
float p;//peso
Nodo<X>* hi;
Nodo<X>* hd;
Nodo(X e, float p) {
hi = nullptr;
hd = nullptr;
this->p = p;
this->e = e;
}
};
template<typename X>
struct Arbol {
Nodo<X>* r;//raiz
long nro;
Arbol() {
r = nullptr;
nro = 0;
}
void insertar(X e1, float p1, Nodo<X>*& n) {
if (n == nullptr)
n = new Nodo<X>(e1, p1);
else if (p1 <= n->p)
insertar(e1, p1, n->hi);
else if (p1 > n->p)
insertar(e1, p1, n->hd);
++nro;
}
void insertar(X e1, float p1) {
insertar(e1, p1, r);
}
void mostrar() {//en orden
mostrar(r);
}
void mostrar(Nodo<X>* n) {//en orden
if (n == nullptr) return;
else
{
mostrar(n->hi);
printf("Nodo: %i Peso: %f \n",n->e, n->p);
mostrar(n->hd);
}
}
float calcularPesos(){
return calcularPesos(r);
}
float calcularPesos(Nodo<X>* n){
float t=1;
if(n==nullptr)
return 1;
else
{
t=t*calcularPesos(r->hi);
printf("Totalizado: %f \n",t);
}
return t;
}
};
#endif | true |
b1b97c18049e1615ced35f5877a5fe2c9042d0cf | C++ | jteuber/blpl_old | /include/blpl/MultiFilter.h | UTF-8 | 3,055 | 3.078125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <thread>
#include <vector>
#include "Filter.h"
namespace blpl {
/**
* @brief This is the interface for all filters of the pipeline. It takes an
* input, processes it and produces an output to be processed by the next
* filter.
*/
template <class InData, class OutData>
class PIPELINE_EXPORT MultiFilter
: public Filter<std::vector<InData>, std::vector<OutData>>
{
public:
template <class Filter1, class Filter2>
MultiFilter(std::shared_ptr<Filter1> first,
std::shared_ptr<Filter2> second);
template <class ExtendingFilter>
MultiFilter<InData, OutData>&
operator&(std::shared_ptr<ExtendingFilter> filter);
[[nodiscard]] size_t size() const;
std::vector<OutData> process(std::vector<InData>&& in) override
{
// call process of all sub-filters in their own thread
std::vector<std::thread> threads;
std::vector<OutData> out(in.size());
for (size_t i = 0; i < in.size(); ++i)
threads.emplace_back(
[&, index = i, in = std::move(in[i])]() mutable {
out[index] = m_filters[index]->processImpl(std::move(in));
});
for (auto& thread : threads)
thread.join();
return out;
}
std::vector<OutData> processImpl(std::vector<InData>&& in) override
{
std::vector<OutData> out(in.size());
return out;
}
private:
std::vector<std::shared_ptr<Filter<InData, OutData>>> m_filters;
};
template <class InData, class OutData>
template <class Filter1, class Filter2>
MultiFilter<InData, OutData>::MultiFilter(std::shared_ptr<Filter1> first,
std::shared_ptr<Filter2> second)
{
static_assert(
std::is_base_of<Filter<InData, OutData>, Filter1>::value,
"First filter does not inherit from the correct Filter template");
static_assert(
std::is_base_of<Filter<InData, OutData>, Filter2>::value,
"Second filter does not inherit from the correct Filter template");
m_filters.push_back(
std::static_pointer_cast<Filter<InData, OutData>>(first));
m_filters.push_back(second);
}
template <class InData, class OutData>
template <class ExtendingFilter>
MultiFilter<InData, OutData>& MultiFilter<InData, OutData>::operator&(
std::shared_ptr<ExtendingFilter> filter)
{
static_assert(
std::is_base_of<Filter<InData, OutData>, ExtendingFilter>::value,
"Extending filter does not inherit from the correct Filter template");
m_filters.push_back(filter);
return *this;
}
template <class Filter1, class Filter2>
PIPELINE_EXPORT MultiFilter<typename Filter1::inType, typename Filter1::outType>
operator&(std::shared_ptr<Filter1> first, std::shared_ptr<Filter2> second)
{
return MultiFilter<typename Filter1::inType, typename Filter1::outType>(
first, second);
}
template <class InData, class OutData>
size_t MultiFilter<InData, OutData>::size() const
{
return m_filters.size();
}
} // namespace blpl
| true |
dc9c8bb7fa0c678d01605fd8a9ef9916878aee28 | C++ | jozi77/SuperComputing-HW3 | /2/b/2b.cpp | UTF-8 | 2,120 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<fstream.h>
#include<strstream.h>
using namespace std;
int min(int,int);
int min1(int,int,int);
int main()
{
int i,j,n,k,l;
char buffer1[2048]; //--- taking input from file
char buffer2[2048]; //--- n,s1,s2 are the corresponding three lines of input
char buffer3[2048];
istrstream str1(buffer1, 2048);
istrstream str2(buffer2, 2048);
istrstream str3(buffer3, 2048);
ifstream indata("rand-1024-in.txt");
indata.getline(buffer1, 2048);
indata.getline(buffer2, 2048);
indata.getline(buffer3, 2048);
str1>>n;
char* s1 = new char[n+1];
char* s2 = new char[n+1];
for(i=1;i<=n;i++)
{
str2>>s1[i];
str3>>s2[i];
} //--- end of input
/*cout<<"value of n: "<<n<<endl<<endl; //--- printing values of input
cout<<"string1: ";
for(i=0;i<n;i++)
{
cout<<s1[i];
}
cout<<endl<<endl<<"string2: ";
for(i=0;i<n;i++)
{
cout<<s2[i];
}
cout<<endl<<endl; //--- printing of i/p ends
*/
int D0[n+1],D1[n+1],D2[n+1],G0[n+1],G1[n+1],G2[n+1],I0[n+1],I1[n+1],I2[n+1],u[n+1],v[n+1],se[n+1]; //--- declaration of functions
int gi,ge,s,cost;
gi=2;ge=1;
G1[0]=0; //--- initialization
for(k=0;k<(2*n+1);k++)
{
l=0;
for(j=0;j<=k;j++) //--- calculation of D,I,G
{
for(i=0;i<=n;i++)
{
if(i+j==k)
{
if(i==0 && j>0)
{
G2[l]=gi+ge*j;
D2[l]=G2[l]+ge;
}
if(i>0 && j==0)
{
G2[l]=gi+ge*i;
I2[l]=G2[l]+ge;
}
if(i>0 && j>0)
{
D2[l]=min(D1[l],G1[l]+gi)+ge;
I2[l]=min(I1[l-1],G1[l-1]+gi)+ge;
if(s1[i]!=s2[j])
s=1;
else
s=0;
G2[l]=min1(D2[l],I2[l],G0[l-1]+s);
}
}
}
l++;
}
for(int t=0;t<=n;t++)
{
D0[t]=D1[t];
D1[t]=D2[t];
I0[t]=I1[t];
I1[t]=I2[t];
G0[t]=G1[t];
G1[t]=G2[t];
}
}
cost=min1(D1[n],I1[n],G1[n]); //--- allignment cost
cout<<"Optimal Allignment cost: "<<cost<<endl;
return 0;
}
int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
int min1(int a,int b,int c)
{
int m=a;
if(m>b)
m=b;
if(m>c)
m=c;
return m;
}
| true |
2dc37cf50463d5937b511b4fabd810d9a914a44d | C++ | wangrui22/mi-jpeg | /cjpegencoder/mi_jpeg_encoder.h | UTF-8 | 2,994 | 2.59375 | 3 | [] | no_license | #ifndef MI_JPEG_ENCODER_H
#define MI_JPEG_ENCODER_H
#include <vector>
#include <map>
#include <memory>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Image {
int width;
int height;
unsigned char* buffer;
Image():width(0),height(0),buffer(nullptr) {}
~Image() {
if (!buffer) {
delete [] buffer;
}
}
};
struct BitString {
int length;
int value;
};
struct Segment {
unsigned char rgb[64*3];
unsigned char y[64];
unsigned char u[64];
unsigned char v[64];
short quat_y[64];
short quat_u[64];
short quat_v[64];
BitString* huffman_code_y;
BitString* huffman_code_u;
BitString* huffman_code_v;
int huffman_code_y_count;
int huffman_code_u_count;
int huffman_code_v_count;
Segment():huffman_code_y(nullptr), huffman_code_u(nullptr), huffman_code_v(nullptr),
huffman_code_y_count(0),huffman_code_u_count(0),huffman_code_v_count(0) {
memset(rgb, 0, 64*3);
for (int i=0; i<64*3; ++i) {
rgb[i] = 128;
}
memset(y, 0, 64);
memset(u, 0, 64);
memset(v, 0, 64);
memset(quat_y, 0, 64*2);
memset(quat_u, 0, 64*2);
memset(quat_v, 0, 64*2);
}
~Segment() {
if (!huffman_code_y) {
delete [] huffman_code_y;
huffman_code_y = nullptr;
}
if (!huffman_code_u) {
delete [] huffman_code_u;
huffman_code_u = nullptr;
}
if (!huffman_code_v) {
delete [] huffman_code_v;
huffman_code_v = nullptr;
}
}
};
class JpegEncoder {
public:
JpegEncoder();
~JpegEncoder();
int compress(std::shared_ptr<Image> rgb, int quality, unsigned char*& compress_buffer, unsigned int& buffer_len);
public:
void init(int quality);
void rgb_2_yuv_segment(std::shared_ptr<Image> rgb, std::vector<Segment>& segments);
void dct_8x8(unsigned char* val, short* output, float* quant_table);
void huffman_encode_8x8(short* quant, short preDC, const BitString* HTDC, const BitString* HTAC, BitString* output, int& output_count);
void write_jpeg_header(std::shared_ptr<Image> rgb);
void write_word(unsigned short val);
void write_byte(unsigned char val);
void write_byte_array(const unsigned char* buf, unsigned int buf_len);
void write_bitstring(const BitString* bs, int counts, int& new_byte, int& new_byte_pos);
private:
unsigned char* _compress_buffer;
unsigned int _compress_capacity;
unsigned int _compress_byte;
unsigned char _quality_quantization_table_luminance[64];
unsigned char _quality_quantization_table_chrominance[64];
float _quantization_table_luminance[64];
float _quantization_table_chrominance[64];
BitString _huffman_table_Y_DC[12];
BitString _huffman_table_Y_AC[256];
BitString _huffman_table_CbCr_DC[12];
BitString _huffman_table_CbCr_AC[256];
};
#endif | true |
e89c92246fbf69922fe31f3917f47036e5412265 | C++ | bsaid/SensorBoard | /firmware/SensorBoard_orig/main/led.h | UTF-8 | 1,303 | 3.46875 | 3 | [] | no_license | #ifndef GLOBAL_LED_H
#define GLOBAL_LED_H
#include "driver/gpio.h"
class Led
{
gpio_num_t ledPin;
public:
/**
* LED constructor
* @param ledPin number of GPIO pin
*/
Led(gpio_num_t ledPin)
: ledPin(ledPin)
{
gpio_config_t io_conf;
io_conf.intr_type = (gpio_int_type_t)GPIO_PIN_INTR_DISABLE;
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pin_bit_mask = (1ULL<<ledPin);
io_conf.pull_down_en = (gpio_pulldown_t)0;
io_conf.pull_up_en = (gpio_pullup_t)0;
gpio_config(&io_conf);
}
/**
* Light on.
*/
void set()
{
gpio_set_level(ledPin, 1);
}
/**
* Light off.
*/
void reset()
{
gpio_set_level(ledPin, 0);
}
/**
* Blink count times and keep the light for delay_ms milliseconds.
* @param count blink how many times
* @param delay_ms how long keep the light on/off
*/
void blink(int count = 5, int delay_ms = 500)
{
for(int i=0; i<count; i++)
{
set();
vTaskDelay(delay_ms/portTICK_PERIOD_MS);
reset();
vTaskDelay(delay_ms/portTICK_PERIOD_MS);
}
}
};
#endif // GLOBAL_LED_H
| true |
ba1dabb29c627a4055c9aa67f6151f9fb6241da5 | C++ | TsubaMukku/CompetitiveProgramming | /1_LeetCode/1305_All-Elements-in-Two-Binary-Search-Trees.cc | UTF-8 | 2,791 | 3.609375 | 4 | [] | no_license | /*
2020-09-11
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
void inorderTraversal(TreeNode *root, vector<int> &num){
if (root == nullptr) return;
if (root->left != nullptr) inorderTraversal(root->left,num);
num.emplace_back(root->val);
if (root->right != nullptr) inorderTraversal(root->right,num);
}
public:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> num1;
vector<int> num2;
inorderTraversal(root1,num1);
inorderTraversal(root2,num2);
vector<int> ans;
int n1 = (int)num1.size();
int n2 = (int)num2.size();
int i = 0, j = 0;
while (i < n1 && j < n2){
if (num1[i] < num2[j]){
ans.emplace_back(num1[i]);
i++;
}
else{
ans.emplace_back(num2[j]);
j++;
}
}
while (i < n1){
ans.emplace_back(num1[i]);
i++;
}
while (j < n2){
ans.emplace_back(num2[j]);
j++;
}
return ans;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void dfs(TreeNode *root, vector<int> &v){
if (root->left != nullptr) dfs(root->left,v);
v.emplace_back(root->val);
if (root->right != nullptr) dfs(root->right,v);
}
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> res1, res2;
vector<int> ans;
if (root1 != nullptr) dfs(root1,res1);
if (root2 != nullptr) dfs(root2,res2);
int pos1 = 0, pos2 = 0;
while (pos1 < res1.size() && pos2 < res2.size()){
if (res1[pos1] < res2[pos2]) ans.emplace_back(res1[pos1++]);
else ans.emplace_back(res2[pos2++]);
}
while (pos1 < res1.size()) ans.emplace_back(res1[pos1++]);
while (pos2 < res2.size()) ans.emplace_back(res2[pos2++]);
return ans;
}
};
| true |
5bb61f07d93536030f2691cc97ff8e889df8f907 | C++ | MinhazRahman/CPPBasics | /IOStreams/writeFile.cpp | UTF-8 | 370 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << "Writing to a file" << endl;
//create a fstream object, it the file doesn't exist the it will create a file
fstream fileOut("example.txt", ios::app); //ios::trunc
//write to a file
fileOut << "First" << endl;
fileOut << 40;
//close the file
fileOut.close();
return 0;
} | true |
4434df22f56ef5516aa85fb1e5a29dcc285b0f55 | C++ | dnlsgv/ACM | /12583 - Memory Overflow.cpp | UTF-8 | 717 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
#define debug(x) cout << (#x) << " tiene el valor " << (x) << endl
int main(int argc, char const *argv[])
{
int T, n, k, reconocimientos, casos = 1;
char nombres[500 + 1];
cin >> T;
while(T--)
{
cin >> n >> k;
for(int i = 0; i < n; ++i)
{
cin >> nombres[i];
}
reconocimientos = 0;
for(int i = 0; i < n; ++i)
{
char personaActual = nombres[i];
for(int j = i - 1, diasTranscurridos = 0; j >= 0 && diasTranscurridos < k; --j, ++diasTranscurridos)
{
if(personaActual == nombres[j])
{
reconocimientos++;
break;
}
}
}
printf("Case %d: %d\n", casos, reconocimientos);
casos++;
}
return 0;
} | true |
8c49f8548dd2dd98508d5eaae481e988f65445df | C++ | Plypy/Lifestyle | /Hdu/5073.cpp | UTF-8 | 1,250 | 2.515625 | 3 | [] | no_license | /**
* Description:
* ProblemName:
* Source:
* Author: Ply_py
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
#include <ctime>
#include <map>
#include <set>
#include <iomanip>
#include <algorithm>
#include <bitset>
#include <stack>
using namespace std;
const int MAXN = 50005;
int n,k;
double x[MAXN];
void load() {
cin >> n >> k;
k = n-k;
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
}
double work() {
if (0 == k || 1 == k) {
return 0;
}
sort(x, x+n);
double ans = 0;
double s2 = 0;
double s = 0;
for (int i = 0; i < k; ++i) {
s += x[i];
s2 += x[i]*x[i];
}
ans = s2-s*s/k;
for (int i = k; i < n; ++i) {
s += x[i];
s2 += x[i]*x[i];
int t = i-k;
s -= x[t];
s2 -= x[t]*x[t];
double tans = s2-s*s/k;
if (tans < ans) {
ans = tans;
}
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
int T;
cin >> T;
while (T--) {
load();
cout << work() << endl;
}
}
| true |
33b191e94a749601f3de2c8e2d2091e3bc299216 | C++ | Lowest0ne/simutron | /src/libsimutron/budget.h | UTF-8 | 1,818 | 3.078125 | 3 | [
"MIT"
] | permissive | #ifndef SIMUTRON_BUDGET_H
#define SIMUTRON_BUDGET_H
#include <cstdint>
namespace Simutron
{
class City;
class Buyable;
/**
* @class Budget
* @brief Provide monetary functions
*/
class Budget
{
private:
std::uint16_t m_tax_rate;
std::int32_t m_treasury;
public:
/**
* @fn Budget( void )
* @brief Construct a default Budget
*/
Budget( void );
/**
* @fn Budget( const std::uint16_t, const std::int32_t )
* @brief Construct a Budget and set tax rate and treasury
*/
Budget( const std::uint16_t, const std::int32_t );
virtual ~Budget( void );
/**
* @fn std::uint16_t taxRate( void ) const
* @brief Return the current tax rate. Tax rate is a percent.
* @return The current tax rate
*/
std::uint16_t taxRate( void ) const;
/**
* @fn void taxRate( const std::uint16_t )
* @brief Set the tax rate
*/
void taxRate( const std::uint16_t );
/**
* @fn std::int32_t treasury( void ) const
* @brief Return the current treasury
* @return The current treasury
*/
std::int32_t treasury( void ) const;
/**
* @fn void update( const City& city )
* @brief Update the current treasury based on city's stats
* @param city The city to base updates upon
*/
void update( const City& );
/**
* @fn bool canAfford( const Buyable& buyable ) const
* @brief Determine if the Budget can afford the Buyable
* @return true if the Budget can afford the buyable
*/
bool canAfford( const Buyable& ) const;
/**
* @fn bool purchace( const Buyable& buyable )
* @brief Detract the Buyable's cost from treasury if it is affordable
* @param buyable The Buyable to purchace
*/
bool purchace( const Buyable& );
};
}
#endif
| true |
75f8d684bfa18d8b1e154c71968ce7621561f3be | C++ | ebadusb/Trima_12.4 | /engr_tools/datalog_tools/PredictUnitTest/TestBase.h | UTF-8 | 7,014 | 2.890625 | 3 | [] | no_license | /*
* TestBase.h
*
* Created on: May 19, 2012
* Author: allan
*/
#ifndef TESTBASE_H_
#define TESTBASE_H_
#include "TestResult.h"
#include "Assert.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <typeinfo>
#include <ctime>
#include <map>
#include <typeinfo>
namespace UnitTest {
using namespace std;
/*
* This is the abstract base class of the every test. This is necessary
* in order for the TestCollection class to iterate to a collections of
* typed tests defined by the template TestBase.
*/
class ITest
{
public:
ITest(){}
virtual ~ITest(){}
virtual const TestResult& Execute() = 0;
virtual void Initialize() = 0;
virtual void CleanUp() = 0;
};
/*
* This is the template class for every test that this framework will recognize.
*/
template <typename T>
class TestBase : public ITest {
public:
class MethodProperty;
typedef void (T::*MethodPtr)();
typedef typename vector<MethodProperty*>::const_iterator methodIter;
protected:
string m_name;
vector<MethodProperty*> m_methods;
MethodProperty* m_currentlyExecuting;
TestResult m_result;
public:
TestBase(string testName);
virtual ~TestBase();
virtual void Initialize();
virtual void CleanUp();
virtual const TestResult& Execute();
const TestResult& GetResult() const{ return m_result; }
void AddTestMethod( MethodPtr ptr, string methodName );
void AddTestMethod( MethodPtr ptr, string methodName, void* parameter );
void* GetParameter()const;
/* Assert Methods */
AssertResult* AssertIsTrue( bool data, string message);
AssertResult* AssertIsFalse( bool data, string message );
AssertResult* AssertIsNotNull(void* data, string message);
AssertResult* AssertIsNull(void* data, string message);
template <typename P>
AssertResult* AssertAreEqual( P& expected, P& actual, string message);
AssertResult* AssertAreEqual( T& expected, T& actual, string message);
template <typename P>
AssertResult* AssertAreNotEqual(P& expected, P& actual, string message);
///this encapsulates the representation
///of method to test
class MethodProperty
{
private:
MethodPtr m_ptr;
MethodResult m_result;
string m_name;
void* m_parameter;
public:
MethodProperty(MethodPtr ptr, string name) : m_ptr(ptr), m_result(name), m_name(name), m_parameter(NULL){}
MethodProperty(MethodPtr ptr, string name, void* parameter) : m_ptr(ptr), m_result(name), m_name(name), m_parameter(parameter){}
virtual ~MethodProperty();
const string& GetMethodName() const { return m_name; }
const MethodPtr& GetMethodPtr(){ return m_ptr;}
MethodResult& GetResult(){ return m_result; }
void AddAssertResult(AssertResult& result){ m_result.AddAssertResult(result);}
void SetResultMessage( string message ){ m_result.SetMessage(message);}
void* GetParameter() const { return m_parameter; }
};
};
template <typename T>
TestBase<T>::TestBase(string testName) :
m_name(testName),
m_result(testName)
{
}
template <typename T>
TestBase<T>::~TestBase() {
methodIter i = m_methods.begin();
for( ; i != m_methods.end() ; i++)
delete (*i);
}
template <typename T>
void TestBase<T>::Initialize()
{
m_result.Clear();
}
template <typename T>
void TestBase<T>::CleanUp()
{
m_currentlyExecuting = NULL;
}
template <typename T>
const TestResult& TestBase<T>::Execute()
{
T* athis = (T*)this;
methodIter i = m_methods.begin();
for( ; i != m_methods.end(); i++)
{
int start = clock();
MethodProperty* method = m_currentlyExecuting = (*i);
const MethodPtr& m = method->GetMethodPtr();
try{
(athis->*m)();
}
catch(exception e){
string message("Exception thrown: "); message.append(e.what());
method->SetResultMessage(message);
}
int end = clock();
double diff = (double)(end - start)/CLOCKS_PER_SEC;
method->GetResult().SetTime(diff);
m_result.AddMethodResult( method->GetResult() );
}
return m_result;
}
template <typename T>
void TestBase<T>::AddTestMethod(const MethodPtr ptr, string testMethodName)
{
MethodProperty* method = new MethodProperty(ptr, testMethodName);
m_methods.push_back(method);
}
template <typename T>
void TestBase<T>::AddTestMethod(const MethodPtr ptr, string testMethodName, void* parameter)
{
MethodProperty* method = new MethodProperty(ptr, testMethodName, parameter);
m_methods.push_back(method);
}
template <typename T>
void* TestBase<T>::GetParameter() const
{
if( m_currentlyExecuting != NULL )
return m_currentlyExecuting->GetParameter();
return NULL;
}
template <typename T>
template <typename P>
AssertResult* TestBase<T>::AssertAreEqual(P& expected, P& actual, string message)
{
AssertResult* result = Assert<P>::AreEqual(expected, actual, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
AssertResult* TestBase<T>::AssertAreEqual(T& expected, T& actual, string message)
{
AssertResult* result = Assert<const T>::AreEqual(expected, actual, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
template <typename P>
AssertResult* TestBase<T>::AssertAreNotEqual(P& expected, P& actual, string message)
{
AssertResult* result = Assert<P>::AreNotEqual(expected, actual, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
AssertResult* TestBase<T>::AssertIsTrue( bool data, string message)
{
AssertResult* result = Assert<T>::IsTrue(data, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
AssertResult* TestBase<T>::AssertIsFalse( bool data, string message)
{
AssertResult* result = Assert<bool>::IsFalse(data, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
AssertResult* TestBase<T>::AssertIsNotNull( void* data, string message)
{
AssertResult* result = Assert<T*>::IsNotNull(data, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
AssertResult* TestBase<T>::AssertIsNull( void* data, string message)
{
AssertResult* result = Assert<void*>::IsNull(data, message);
if( m_currentlyExecuting != NULL )
{
m_currentlyExecuting->AddAssertResult(*result);
}
return result;
}
template <typename T>
TestBase<T>::MethodProperty::~MethodProperty()
{
if( m_parameter != NULL )
delete m_parameter;
m_parameter = NULL;
}
}//namespace
#endif | true |
db611b8afd01d83a25394d52b7373a95a28e149c | C++ | avesus/hail | /libhail/src/hail/query/ir.cpp | UTF-8 | 5,361 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <exception>
#include "hail/format.hpp"
#include "hail/query/ir.hpp"
namespace hail {
IRContext::IRContext(HeapAllocator &heap)
: arena(heap) {}
IRContext::~IRContext() {}
Module *
IRContext::make_module() {
return arena.make<Module>(IRContextToken());
}
Function *
IRContext::make_function(Module *module,
std::string name,
std::vector<const Type *> parameter_types,
const Type *return_type) {
size_t n = parameter_types.size();
auto f = arena.make<Function>(IRContextToken(),
module,
std::move(name),
// don't move, used below
parameter_types,
return_type);
auto body = arena.make<Block>(IRContextToken(), *this, f, nullptr, 1, n);
for (size_t i = 0; i < n; ++i)
body->inputs[i] = arena.make<Input>(IRContextToken(), body, i);
f->set_body(body);
return f;
}
Module::Module(IRContextToken) {}
Module::~Module() {}
Function *
Module::get_function(const std::string &name) {
auto i = functions.find(name);
assert(i != functions.end());
return i->second;
}
void
Module::add_function(Function *f) {
f->remove();
f->module = this;
assert(!functions.contains(f->name));
functions.insert({f->name, f});
}
void
Module::pretty_self(FormatStream &s) {
format(s, FormatAddress(this), " module\n");
for (auto p : functions)
p.second->pretty_self(s, 4);
}
Function::Function(IRContextToken,
Module *module,
std::string name,
std::vector<const Type *> parameter_types,
const Type *return_type)
: module(module),
name(std::move(name)),
parameter_types(std::move(parameter_types)),
return_type(return_type) {
module->add_function(this);
}
Function::~Function() {}
void
Function::remove() {
if (!module)
return;
module->functions.erase(name);
module = nullptr;
}
void
Function::set_body(Block *new_body) {
if (body)
body->remove();
if (new_body)
new_body->remove();
body = new_body;
body->function_parent = this;
}
void
Function::pretty_self(FormatStream &s, int indent) {
format(s, FormatAddress(this), Indent(indent), "function ", return_type, " ", name, "(");
bool first = true;
for (auto pt : parameter_types) {
if (first)
first = false;
else
format(s, ", ");
format(s, pt);
}
format(s, ")\n");
pretty(s, get_body(), indent + 2);
format(s, "\n");
}
const std::vector<std::string> IR::tag_name = {
"block",
"input",
"literal",
"na",
"isna",
"mux",
"unary",
"binary",
"makearray",
"arraylen",
"arrayref",
"maketuple",
"gettupleelement",
"tostream",
"streammap",
"streamflatmap",
"streamfilter",
"streamfold"
};
IR::IR(Tag tag, Block *parent, size_t arity)
: tag(tag), parent(parent), children(arity) {}
IR::IR(Tag tag, Block *parent, std::vector<IR *> children)
: tag(tag), parent(parent), children(std::move(children)) {}
IR::~IR() {}
void
IR::add_use(IR *u, size_t i) {
auto p = uses.insert({u, i});
/* make sure the insert happened */
assert(p.second);
}
void
IR::remove_use(IR *u, size_t i) {
auto n = uses.erase({u, i});
/* make sure the removal happened */
assert(n == 1);
}
void
IR::set_child(size_t i, IR *x) {
IR *c = children[i];
if (c)
c->remove_use(this, i);
children[i] = x;
x->add_use(this, i);
}
void
IR::pretty_self(FormatStream &s, int indent) {
format(s, FormatAddress(this), Indent(indent), "(", tag_name[static_cast<int>(tag)], " ...)");
}
void
pretty(FormatStream &s, IR *x, int indent) {
if (x) {
x->pretty_self(s, indent);
return;
}
format(s, FormatAddress(nullptr), Indent(indent), "null");
}
Block::Block(IRContextToken, IRContext &xc, Function *function_parent, Block *parent, std::vector<IR *> children, size_t input_arity)
: IR(Tag::BLOCK, parent, std::move(children)),
xc(xc),
function_parent(function_parent),
inputs(input_arity) {}
Block::Block(IRContextToken, IRContext &xc, Function *function_parent, Block *parent, size_t arity, size_t input_arity)
: IR(Tag::BLOCK, parent, arity),
xc(xc),
function_parent(function_parent),
inputs(input_arity) {}
void
Block::remove() {
if (function_parent) {
function_parent->body = nullptr;
function_parent = nullptr;
}
}
Block *
Block::make_block(size_t arity, size_t input_arity) {
return xc.arena.make<Block>(IRContextToken(),
xc, nullptr, this, arity, input_arity);
}
Block *
Block::make_block(std::vector<IR *> children) {
return xc.arena.make<Block>(IRContextToken(),
xc, nullptr, this, children, 0);
}
Input *
Block::make_input(size_t index) {
return xc.arena.make<Input>(IRContextToken(), this, index);
}
Literal *
Block::make_literal(const Value &v) {
return xc.arena.make<Literal>(IRContextToken(), this, v);
}
NA *
Block::make_na(const Type *t) {
return xc.arena.make<NA>(IRContextToken(), this, t);
}
IsNA *
Block::make_is_na(IR *x) {
return xc.arena.make<IsNA>(IRContextToken(), this, x);
}
Mux *
Block::make_mux(IR *x, IR *true_value, IR *false_value) {
return xc.arena.make<Mux>(IRContextToken(), this, x, true_value, false_value);
}
MakeTuple *
Block::make_tuple(std::vector<IR *> elements) {
return xc.arena.make<MakeTuple>(IRContextToken(), this, std::move(elements));
}
GetTupleElement *
Block::make_get_tuple_element(IR *t, int i) {
return xc.arena.make<GetTupleElement>(IRContextToken(), this, t, i);
}
}
| true |
7840edc10387ed1dd50df8773bcd430e34362f7e | C++ | godot-extended-libraries/godot-sqlite | /sqlite.cpp | UTF-8 | 15,060 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "sqlite.h"
#include "core/core_bind.h"
#include "core/os/os.h"
#include "editor/project_settings_editor.h"
Array fast_parse_row(sqlite3_stmt *stmt) {
Array result;
// Get column count
const int col_count = sqlite3_column_count(stmt);
// Fetch all column
for (int i = 0; i < col_count; i++) {
// Value
const int col_type = sqlite3_column_type(stmt, i);
Variant value;
// Get column value
switch (col_type) {
case SQLITE_INTEGER:
value = Variant(sqlite3_column_int(stmt, i));
break;
case SQLITE_FLOAT:
value = Variant(sqlite3_column_double(stmt, i));
break;
case SQLITE_TEXT: {
int size = sqlite3_column_bytes(stmt, i);
String str =
String::utf8((const char *)sqlite3_column_text(stmt, i), size);
value = Variant(str);
break;
}
case SQLITE_BLOB: {
PackedByteArray arr;
int size = sqlite3_column_bytes(stmt, i);
arr.resize(size);
memcpy(arr.ptrw(), sqlite3_column_blob(stmt, i), size);
value = Variant(arr);
break;
}
case SQLITE_NULL: {
// Nothing to do.
} break;
default:
ERR_PRINT("This kind of data is not yet supported: " + itos(col_type));
break;
}
result.push_back(value);
}
return result;
}
SQLiteQuery::SQLiteQuery() {}
SQLiteQuery::~SQLiteQuery() { finalize(); }
void SQLiteQuery::init(SQLite *p_db, const String &p_query) {
db = p_db;
query = p_query;
stmt = nullptr;
}
bool SQLiteQuery::is_ready() const { return stmt != nullptr; }
String SQLiteQuery::get_last_error_message() const {
ERR_FAIL_COND_V(db == nullptr, "Database is undefined.");
return db->get_last_error_message();
}
Variant SQLiteQuery::execute(const Array p_args) {
if (is_ready() == false) {
ERR_FAIL_COND_V(prepare() == false, Variant());
}
// At this point stmt can't be null.
CRASH_COND(stmt == nullptr);
// Error occurred during argument binding
if (!SQLite::bind_args(stmt, p_args)) {
ERR_FAIL_V_MSG(Variant(),
"Error during arguments set: " + get_last_error_message());
}
// Execute the query.
Array result;
while (true) {
const int res = sqlite3_step(stmt);
if (res == SQLITE_ROW) {
// Collect the result.
result.append(fast_parse_row(stmt));
} else if (res == SQLITE_DONE) {
// Nothing more to do.
break;
} else {
// Error
ERR_BREAK_MSG(true, "There was an error during an SQL execution: " +
get_last_error_message());
}
}
if (SQLITE_OK != sqlite3_reset(stmt)) {
finalize();
ERR_FAIL_V_MSG(result, "Was not possible to reset the query: " +
get_last_error_message());
}
return result;
}
Variant SQLiteQuery::batch_execute(Array p_rows) {
Array res;
for (int i = 0; i < p_rows.size(); i += 1) {
ERR_FAIL_COND_V_MSG(p_rows[i].get_type() != Variant::ARRAY, Variant(),
"An Array of Array is exepected.");
Variant r = execute(p_rows[i]);
if (unlikely(r.get_type() == Variant::NIL)) {
// An error occurred, the error is already logged.
return Variant();
}
res.push_back(r);
}
return res;
}
Array SQLiteQuery::get_columns() {
if (is_ready() == false) {
ERR_FAIL_COND_V(prepare() == false, Array());
}
// At this point stmt can't be null.
CRASH_COND(stmt == nullptr);
Array res;
const int col_count = sqlite3_column_count(stmt);
res.resize(col_count);
// Fetch all column
for (int i = 0; i < col_count; i++) {
// Key name
const char *col_name = sqlite3_column_name(stmt, i);
res[i] = String(col_name);
}
return res;
}
bool SQLiteQuery::prepare() {
ERR_FAIL_COND_V(stmt != nullptr, false);
ERR_FAIL_COND_V(db == nullptr, false);
ERR_FAIL_COND_V(query == "", false);
// Prepare the statement
int result = sqlite3_prepare_v2(db->get_handler(), query.utf8().ptr(), -1,
&stmt, nullptr);
// Cannot prepare query!
ERR_FAIL_COND_V_MSG(result != SQLITE_OK, false,
"SQL Error: " + db->get_last_error_message());
return true;
}
void SQLiteQuery::finalize() {
if (stmt) {
sqlite3_finalize(stmt);
stmt = nullptr;
}
}
void SQLiteQuery::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_last_error_message"),
&SQLiteQuery::get_last_error_message);
ClassDB::bind_method(D_METHOD("execute", "arguments"), &SQLiteQuery::execute,
DEFVAL(Array()));
ClassDB::bind_method(D_METHOD("batch_execute", "rows"),
&SQLiteQuery::batch_execute);
ClassDB::bind_method(D_METHOD("get_columns"), &SQLiteQuery::get_columns);
}
SQLite::SQLite() {
db = nullptr;
memory_read = false;
}
/*
Open a database file.
If this is running outside of the editor, databases under res:// are
assumed to be packed.
@param path The database resource path.
@return status
*/
bool SQLite::open(String path) {
if (!path.strip_edges().length())
return false;
if (!Engine::get_singleton()->is_editor_hint() &&
path.begins_with("res://")) {
Ref<core_bind::File> dbfile;
dbfile.instantiate();
if (dbfile->open(path, core_bind::File::READ) != Error::OK) {
print_error("Cannot open packed database!");
return false;
}
int64_t size = dbfile->get_length();
PackedByteArray buffer = dbfile->get_buffer(size);
return open_buffered(path, buffer, size);
}
String real_path =
ProjectSettings::get_singleton()->globalize_path(path.strip_edges());
int result = sqlite3_open(real_path.utf8().get_data(), &db);
if (result != SQLITE_OK) {
print_error("Cannot open database!");
return false;
}
return true;
}
bool SQLite::open_in_memory() {
int result = sqlite3_open(":memory:", &db);
ERR_FAIL_COND_V_MSG(result != SQLITE_OK, false,
"Cannot open database in memory, error:" + itos(result));
return true;
}
/*
Open the database and initialize memory buffer.
@param name Name of the database.
@param buffers The database buffer.
@param size Size of the database;
@return status
*/
bool SQLite::open_buffered(String name, PackedByteArray buffers, int64_t size) {
if (!name.strip_edges().length()) {
return false;
}
if (!buffers.size() || !size) {
return false;
}
spmembuffer_t *p_mem = (spmembuffer_t *)calloc(1, sizeof(spmembuffer_t));
p_mem->total = p_mem->used = size;
p_mem->data = (char *)malloc(size + 1);
memcpy(p_mem->data, buffers.ptr(), size);
p_mem->data[size] = '\0';
//
spmemvfs_env_init();
int err = spmemvfs_open_db(&p_db, name.utf8().get_data(), p_mem);
if (err != SQLITE_OK || p_db.mem != p_mem) {
print_error("Cannot open buffered database!");
return false;
}
memory_read = true;
return true;
}
void SQLite::close() {
// Finalize all queries before close the DB.
// Reverse order because I need to remove the not available queries.
for (uint32_t i = queries.size(); i > 0; i -= 1) {
SQLiteQuery *query =
Object::cast_to<SQLiteQuery>(queries[i - 1]->get_ref());
if (query != nullptr) {
query->finalize();
} else {
memdelete(queries[i - 1]);
queries.remove_at(i - 1);
}
}
if (db) {
// Cannot close database!
if (sqlite3_close_v2(db) != SQLITE_OK) {
print_error("Cannot close database: " + get_last_error_message());
} else {
db = nullptr;
}
}
if (memory_read) {
// Close virtual filesystem database
spmemvfs_close_db(&p_db);
spmemvfs_env_fini();
memory_read = false;
}
}
sqlite3_stmt *SQLite::prepare(const char *query) {
// Get database pointer
sqlite3 *dbs = get_handler();
ERR_FAIL_COND_V_MSG(dbs == nullptr, nullptr,
"Cannot prepare query! Database is not opened.");
// Prepare the statement
sqlite3_stmt *stmt = nullptr;
int result = sqlite3_prepare_v2(dbs, query, -1, &stmt, nullptr);
// Cannot prepare query!
ERR_FAIL_COND_V_MSG(result != SQLITE_OK, nullptr,
"SQL Error: " + get_last_error_message());
return stmt;
}
bool SQLite::bind_args(sqlite3_stmt *stmt, Array args) {
// Check parameter count
int param_count = sqlite3_bind_parameter_count(stmt);
if (param_count != args.size()) {
print_error("SQLiteQuery failed; expected " + itos(param_count) +
" arguments, got " + itos(args.size()));
return false;
}
/**
* SQLite data types:
* - NULL
* - INTEGER (signed, max 8 bytes)
* - REAL (stored as a double-precision float)
* - TEXT (stored in database encoding of UTF-8, UTF-16BE or UTF-16LE)
* - BLOB (1:1 storage)
*/
for (int i = 0; i < param_count; i++) {
int retcode;
switch (args[i].get_type()) {
case Variant::Type::NIL:
retcode = sqlite3_bind_null(stmt, i + 1);
break;
case Variant::Type::BOOL:
case Variant::Type::INT:
retcode = sqlite3_bind_int(stmt, i + 1, (int)args[i]);
break;
case Variant::Type::FLOAT:
retcode = sqlite3_bind_double(stmt, i + 1, (double)args[i]);
break;
case Variant::Type::STRING:
retcode = sqlite3_bind_text(
stmt, i + 1, String(args[i]).utf8().get_data(), -1, SQLITE_TRANSIENT);
break;
case Variant::Type::PACKED_BYTE_ARRAY:
retcode =
sqlite3_bind_blob(stmt, i + 1, PackedByteArray(args[i]).ptr(),
PackedByteArray(args[i]).size(), SQLITE_TRANSIENT);
break;
default:
print_error(
"SQLite was passed unhandled Variant with TYPE_* enum " +
itos(args[i].get_type()) +
". Please serialize your object into a String or a PoolByteArray.\n");
return false;
}
if (retcode != SQLITE_OK) {
print_error(
"SQLiteQuery failed, an error occured while binding argument" +
itos(i + 1) + " of " + itos(args.size()) + " (SQLite errcode " +
itos(retcode) + ")");
return false;
}
}
return true;
}
bool SQLite::query_with_args(String query, Array args) {
sqlite3_stmt *stmt = prepare(query.utf8().get_data());
// Failed to prepare the query
ERR_FAIL_COND_V_MSG(stmt == nullptr, false,
"SQLiteQuery preparation error: " +
get_last_error_message());
// Error occurred during argument binding
if (!bind_args(stmt, args)) {
sqlite3_finalize(stmt);
ERR_FAIL_V_MSG(false,
"Error during arguments bind: " + get_last_error_message());
}
// Evaluate the sql query
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return true;
}
Ref<SQLiteQuery> SQLite::create_query(String p_query) {
Ref<SQLiteQuery> query;
query.instantiate();
query->init(this, p_query);
WeakRef *wr = memnew(WeakRef);
wr->set_obj(query.ptr());
queries.push_back(wr);
return query;
}
bool SQLite::query(String query) {
return this->query_with_args(query, Array());
}
Array SQLite::fetch_rows(String statement, Array args, int result_type) {
Array result;
// Empty statement
if (!statement.strip_edges().length()) {
return result;
}
// Cannot prepare query
sqlite3_stmt *stmt = prepare(statement.strip_edges().utf8().get_data());
if (!stmt) {
return result;
}
// Bind arguments
if (!bind_args(stmt, args)) {
sqlite3_finalize(stmt);
return result;
}
// Fetch rows
while (sqlite3_step(stmt) == SQLITE_ROW) {
// Do a step
result.append(parse_row(stmt, result_type));
}
// Delete prepared statement
sqlite3_finalize(stmt);
// Return the result
return result;
}
Dictionary SQLite::parse_row(sqlite3_stmt *stmt, int result_type) {
Dictionary result;
// Get column count
int col_count = sqlite3_column_count(stmt);
// Fetch all column
for (int i = 0; i < col_count; i++) {
// Key name
const char *col_name = sqlite3_column_name(stmt, i);
String key = String(col_name);
// Value
int col_type = sqlite3_column_type(stmt, i);
Variant value;
// Get column value
switch (col_type) {
case SQLITE_INTEGER:
value = Variant(sqlite3_column_int(stmt, i));
break;
case SQLITE_FLOAT:
value = Variant(sqlite3_column_double(stmt, i));
break;
case SQLITE_TEXT: {
int size = sqlite3_column_bytes(stmt, i);
String str =
String::utf8((const char *)sqlite3_column_text(stmt, i), size);
value = Variant(str);
break;
}
case SQLITE_BLOB: {
PackedByteArray arr;
int size = sqlite3_column_bytes(stmt, i);
arr.resize(size);
memcpy((void *)arr.ptr(), sqlite3_column_blob(stmt, i), size);
value = Variant(arr);
break;
}
default:
break;
}
// Set dictionary value
if (result_type == RESULT_NUM)
result[i] = value;
else if (result_type == RESULT_ASSOC)
result[key] = value;
else {
result[i] = value;
result[key] = value;
}
}
return result;
}
Array SQLite::fetch_array(String query) {
return fetch_rows(query, Array(), RESULT_BOTH);
}
Array SQLite::fetch_array_with_args(String query, Array args) {
return fetch_rows(query, args, RESULT_BOTH);
}
Array SQLite::fetch_assoc(String query) {
return fetch_rows(query, Array(), RESULT_ASSOC);
}
Array SQLite::fetch_assoc_with_args(String query, Array args) {
return fetch_rows(query, args, RESULT_ASSOC);
}
String SQLite::get_last_error_message() const {
return sqlite3_errmsg(get_handler());
}
SQLite::~SQLite() {
// Close database
close();
// Make sure to invalidate all associated queries.
for (uint32_t i = 0; i < queries.size(); i += 1) {
SQLiteQuery *query = Object::cast_to<SQLiteQuery>(queries[i]->get_ref());
if (query != nullptr) {
query->init(nullptr, "");
}
}
}
void SQLite::_bind_methods() {
ClassDB::bind_method(D_METHOD("open", "path"), &SQLite::open);
ClassDB::bind_method(D_METHOD("open_in_memory"), &SQLite::open_in_memory);
ClassDB::bind_method(D_METHOD("open_buffered", "path", "buffers", "size"),
&SQLite::open_buffered);
ClassDB::bind_method(D_METHOD("close"), &SQLite::close);
ClassDB::bind_method(D_METHOD("create_query", "statement"),
&SQLite::create_query);
ClassDB::bind_method(D_METHOD("query", "statement"), &SQLite::query);
ClassDB::bind_method(D_METHOD("query_with_args", "statement", "args"),
&SQLite::query_with_args);
ClassDB::bind_method(D_METHOD("fetch_array", "statement"),
&SQLite::fetch_array);
ClassDB::bind_method(D_METHOD("fetch_array_with_args", "statement", "args"),
&SQLite::fetch_array_with_args);
ClassDB::bind_method(D_METHOD("fetch_assoc", "statement"),
&SQLite::fetch_assoc);
ClassDB::bind_method(D_METHOD("fetch_assoc_with_args", "statement", "args"),
&SQLite::fetch_assoc_with_args);
}
| true |
be148008876410edbcbc3de78391dbe18d07c5c1 | C++ | dillu24/MiniLang_Compiler | /Visitors/Utilities/SymbolTable.cpp | UTF-8 | 1,988 | 3 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by Dylan Galea on 14/04/2018.
//
#include "SymbolTable.h"
#include "../../Exceptions/CompilingErrorException.h"
Visitors::SymbolTable::SymbolTable() {
contents = multimap<string,TypeBinder>();
}
void Visitors::SymbolTable::addToSymbolTable(string identifier, Visitors::TypeBinder type) {
contents.insert(std::pair<string,TypeBinder>(identifier,type)); //insert a whole pair in the hash map
}
bool Visitors::SymbolTable::checkIfInSymbolTable(string identifier,TypeBinder::IdentifierType identifierType) {
typedef std::multimap<string,TypeBinder>::iterator iterator1; //create an iterator type of the map
std::pair<iterator1,iterator1> answers = contents.equal_range(identifier); //get the range of values of the mapped key value
for(auto iterator = answers.first;iterator != answers.second;iterator++){
if(iterator->second.getIdentifierType() == identifierType){ //if we find a mapped value of type given in identifierType
return true; // we have found such a pair
}
}
return false; // if we do not find such a pair.
}
Visitors::TypeBinder Visitors::SymbolTable::getTypeBinder(string identifier,TypeBinder::IdentifierType identifierType) {
typedef std::multimap<string,TypeBinder>::iterator iterator1; //create an iterator type of the map
std::pair<iterator1,iterator1> answers = contents.equal_range(identifier); //get the range of values of the mapped key value
for(auto iterator = answers.first;iterator != answers.second;iterator++){
if(iterator->second.getIdentifierType() == identifierType){ //if we find a mapped value of type given in identifierType
return iterator->second; // we have found such a pair
}
}
throw Exception::CompilingErrorException("Did not find variable"); //else compiling error
}
multimap<string, TypeBinder> SymbolTable::getMultimap() {
return contents;
}
| true |
d8b03b44512f9166cef7ef8a4361e31d10399ac8 | C++ | siatwangmin/LeetCode | /leetcode/70ClimbingStairs.cpp | GB18030 | 1,101 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
//Descirption*************************************************************************************
//You are climbing a stair case. It takes n steps to reach to the top.
//
//Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
//*************************************************************************************************
//һõݹķTime Out
//class Solution {
//
//private:
// int step1 = 1;
// int step2 = 2;
//
// int DPSolve(int n)
// {
// if (n <= 0)
// return 0;
// if (n == 1)
// {
// return step1;
// }
// if (n == 2)
// {
// return step2;
// }
//
// return DPSolve(n - 1) + DPSolve(n - 2);
//
// }
//public:
// int climbStairs(int n) {
// return DPSolve(n);
// }
//};
//ѭķ
class Solution {
public:
int climbStairs(int n) {
vector<int> vec(n + 1, 0);
if (n <= 0)
return 0;
vec[1] = 1;
vec[2] = 2;
for (int i = 3; i < n + 1; i++)
{
vec[i] = vec[i - 1] + vec[i - 2];
}
return vec[n];
}
}; | true |
709d8794d3894f316f85a0c4015fda435319054f | C++ | borrislevin/TIL | /Cpp STL, Modern/DAY3/0_입출력4.cpp | UHC | 1,029 | 3.828125 | 4 | [] | no_license | // 0_4.cpp
#include <iostream>
#include <string>
#include <sstream>
int main()
{
double d = 3.141592;
// ڸ ڿ ϴ
// 1. std::to_string() Լ =>> C++11 ߰
// Ư¡ : " Ѱ" ڿ
// std::string s = std::to_string(d); // 3.141592 => "3.141592"
std::string s = "d = " + std::to_string(d) + " Դϴ."; // ok
// 2. osstringstream =>> C++ ʱ(C++98) ִ .
// Ư¡ : "ڸ " ڿ
std::ostringstream oss;
// oss << d;
oss << "d = " << d << " Դϴ";
std::string s2 = oss.str();
}
// cppreference.com std::to_string ˻ .
// ذϴ " "
// 1. .
// 2. ؾ Ѵ.
// Ѱ ڿ => to_string() .
// ȭ ڿ => ostringstream . | true |
c22abd7903e6551c7aad173cb9c2ede00bfcee89 | C++ | LeonMac/ecdsa-tv-gen | /open_ecdsa.cpp | UTF-8 | 7,849 | 2.84375 | 3 | [] | no_license | //compile: g++ open_ecdsa.cpp -o open -lssl -lcrypto -lstdc++
#include <openssl/ecdsa.h>
#include <openssl/sha.h>
#include <openssl/bn.h>
#include <stdlib.h> // for strtol
#include <math.h>
#include <string.h>
#include <cstdint>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
#define SIG_SIZE 64
#define PUB_KEY_SIZE 64
#define DIG_SIZE 32
#define PRIV_KEY_SIZE 32
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
// std::vector<uint8_t> Hash512(const std::string &str) {
// std::cout << "SHA512 is used" <<std::endl;
// std::cout << "Original Message is "<< STRING << std::endl;uint8_t>
// std::cout << "The message hash output:\n";
// std::cout << uint8_vector_to_hex_string(md) <<std::endl;
// return md;
// }
std::vector<uint8_t> Hash256(const std::string &str) {
// std::cout << "SHA256 is used" <<std::endl;
// std::cout << "Original Message is "<< STRING << std::endl;
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, str.c_str(), str.size());
std::vector<uint8_t> md(SHA256_DIGEST_LENGTH);
SHA256_Final(md.data(), &ctx);
// std::cout << "The message hash output:\n";
// std::cout << uint8_vector_to_hex_string(md) <<std::endl;
return md;
}
void char_array_display (const char* char_ptr, int size, const char* msg)
{ for(int i = 0; i < size; i++)
cout << std::setw(1) << std::setfill('0') << static_cast<char>(tolower(*(char_ptr+i)));
cout << " //" << msg << endl;
}
string sha256_string (const string str)
{ unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
std::stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
return ss.str();
}
// string uint8_vector_to_hex_string(const string name, const vector<uint8_t>& v) {
string uint8_vector_to_hex_string(const vector<uint8_t>& v) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
std::vector<uint8_t>::const_iterator it;
ss << "0x ";
for (it = v.begin(); it != v.end(); it++) {
ss << std::setw(2) << static_cast<unsigned>(*it);
}
return ss.str();
}
int main(int argc, char** argv)
{
if (argc != 2) {
printf("Wrong usage: %s number\n", argv[0]);
return 1;
}
char* argv_ptr;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &argv_ptr, 10); // string to long(string, endpointer, base)
if (*argv_ptr != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < 0 || arg > INT_MAX) {
return 1;
}
uint signature_number = arg;
printf("let us make %d test vectors\n", signature_number);
vector<uint8_t> Digest (DIG_SIZE, 0);
// vector<uint8_t> Signature_R (SIG_SIZE/2,0);
// vector<uint8_t> Signature_S (SIG_SIZE/2,0);
// vector<uint8_t> Pub_key_Qx (PUB_KEY_SIZE/2,0);
// vector<uint8_t> Pub_key_Qy (PUB_KEY_SIZE/2,0);
// vector<uint8_t> Private_key (PRIV_KEY_SIZE,0);
vector<uint8_t> Signature_R;
vector<uint8_t> Signature_S;
vector<uint8_t> Pub_key_Qx;
vector<uint8_t> Pub_key_Qy;
vector<uint8_t> Private_Key;
//const char *mesg_string = "Hello world!";
const char *mesg_string = "aaa";
cout << "Input Message is "<< mesg_string << std::endl;
Digest=Hash256(mesg_string);
cout << "Hash256(message) " << Digest.size() << " byte" <<endl;
std::cout << uint8_vector_to_hex_string(Digest) <<std::endl;
//9834876dcfb05cb167a5c24953eba58c4ac89b1adf57f28f2f9d09af107ee8f0
for (uint32_t i=0; i<signature_number; i++) {
printf("\n===========Signature body #%d of #%d ===============\n",i+1,signature_number);
EC_KEY *ec_key = EC_KEY_new();
if (ec_key == NULL) {
cout<< "Error happen for creating ECC key object!" <<endl;
return false;
}
EC_GROUP *ec_group = EC_GROUP_new_by_curve_name(714); //NID_secp256k1
EC_KEY_set_group(ec_key, ec_group);
int ret=EC_KEY_generate_key(ec_key);
if (ret == 0) {
cout<< "Error happen for creating ECC key pair!" <<endl;
return false;
}
const EC_POINT *pub = EC_KEY_get0_public_key(ec_key);
const BIGNUM *PRIV = EC_KEY_get0_private_key(ec_key);
BIGNUM *QX = BN_new();
BIGNUM *QY = BN_new();
//char *
if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, QX, QY, NULL)) {
cout << "Pub key generated:\n";
// cout << "QX : ";
// BN_print_fp(stdout, QX);
// putc('\n', stdout);
// cout << "QY : ";
// BN_print_fp(stdout, QY);
// putc('\n', stdout);
// cout << "Priv key: ";
// BN_print_fp(stdout, PRIV);
// cout <<"\n";
}
ECDSA_SIG *signature;
unsigned char *dig_ptr=Digest.data();
signature = ECDSA_do_sign(dig_ptr, SHA256_DIGEST_LENGTH, ec_key);
if (signature == NULL)
{cout <<"Signature generation fail!\n";
return false;
}
const BIGNUM *R = BN_new();
const BIGNUM *S = BN_new();
ret = ECDSA_do_verify(dig_ptr, SHA256_DIGEST_LENGTH, signature, ec_key);
// ret = ECDSA_verify(0, digest, 32, buffer, buf_len, ec_key);
if (ret == 1)
{cout << "The signature verified OK:\n" <<endl;
}
else if (ret == 0)
{cout << "The signature verified fail!:\n" <<endl;
return false;
}
else
{cout << "The signature verified unnormal, err code=" <<ret <<"/n";
return false;
}
ECDSA_SIG_get0(signature, &R, &S);
// cout << "Sig :\n";
// cout << "Sig.r : ";
// BN_print_fp(stdout, R);
// putc('\n', stdout);
// cout << "Sig.s : ";
// BN_print_fp(stdout, S);
// putc('\n', stdout);
// putc('\n', stdout);
//char *BN_bn2hex(const BIGNUM *a);
// Signature_R.data()= BN_bn2hex (R);
// Signature_S.data()= BN_bn2hex (S);
// char *BN_bn2dec(const BIGNUM *a);
// Convert from BIGNUM to Hex String.
//
// cout << "================ low case disply ===================\n";
// cout << "Input Message is "<< mesg_string << std::endl;
//cout << "Hash256(message) " << Digest.size() << " byte" <<endl;
// std::cout << uint8_vector_to_hex_string(Digest) <<" //Digest" <<std::endl;
char* Q_x = BN_bn2hex(QX);
char* Q_y = BN_bn2hex(QY);
char* sig_r = BN_bn2hex(R);
char* sig_s = BN_bn2hex(S);
char* priv_key = BN_bn2hex(PRIV);
char_array_display (sig_r,64,"sig.r");
char_array_display (sig_s,64,"sig.s");
char_array_display (Q_x, 64,"QX");
char_array_display (Q_y, 64,"QY");
printf("===============================================\n");
char_array_display (priv_key,64,"privkey");
// for(int i = 0; i < PRIV_KEY_SIZE; i++)
// {
// cout << std::setw(1) << std::setfill('0') << tolower(*(priv_key+i));
// }
// cout<< " //Priv Key" <<endl;
// int i=0;
// for(vector<uint8_t>::iterator it=Signature_R.begin(); it != Signature_R.end(); it++)
// {
// *it << *(sig_r+i);
// i++;
// }
//cout<<uint8_vector_to_hex_string(Signature_R);
OPENSSL_free(sig_r);
OPENSSL_free(sig_s);
OPENSSL_free(Q_x);
OPENSSL_free(Q_y);
sig_r = nullptr;
sig_s = nullptr;
Q_x = nullptr;
Q_y = nullptr;
}//end of iteration;
// BN_free(QX);
// BN_free(QY);
// BN_free(R);
// BN_free(S);
// BN_free(PRIV);
return 0;
}
| true |
8a83d6745e1f11139fd081c55b2067e84165029c | C++ | rocammo/object-oriented-programming-i | /ReservasHotel/sources/cliente.cpp | UTF-8 | 3,054 | 3.203125 | 3 | [
"MIT"
] | permissive | /**
* cliente.cpp
*
* @author: Rodrigo Casamayor <alu.89657@usj.es>
* @date: 14 ene. 2019
*/
#include "cliente.hpp"
#include <iostream>
#include <iomanip>
Cliente::~Cliente() {
reservas.clear();
}
void Cliente::agregarReserva(const Habitacion& habitacion) {
reservas.push_back(habitacion);
}
void Cliente::borrarReserva(const Habitacion& habitacion) {
int i = 0;
std::vector<Habitacion>::iterator it;
for (it = reservas.begin(); it != reservas.end(); it++, i++) {
if ((*it).getIdHabitacion() == habitacion.getIdHabitacion()) {
reservas.erase(reservas.begin() + i);
break;
}
}
}
void Cliente::verReservas() {
std::cout << "┌─────────────────────────────┐" << std::endl;
std::cout << "│ MIS RESERVAS │" << std::endl;
std::cout << "┌─────────────────────────────┐" << std::endl;
int i = 0;
std::vector<Habitacion>::iterator it;
for (it = reservas.begin(); it != reservas.end(); it++, i++) {
std::cout << "│[" << (*it).getIdHabitacion() << "] "
<< "Habitacion" << " " << std::setfill('0') << std::setw(3) << ((*it).getNumHabitacion() + 1) << " "
<< "(" << (*it).getPlazas() << "p.)" << "│"
<< std::endl;
}
if (i == 0) std::cout << " No tiene ninguna reserva." << std::endl;
else std::cout << "└─────────────────────────────┘" << std::endl;
std::cout << "\n" << std::endl;
}
std::ostream& operator<<(std::ostream& os, const Cliente& cliente) {
os << "┌─────────────────────────────┐" << "\n";
os << "│ MIS DATOS │" << "\n";
os << "┌─────────────────────────────┐" << "\n";
os << " · Nombre: " << cliente.nombre << "\n";
os << " · DNI: " << cliente.dni << "\n";
os << " · Telef.: "; if (cliente.telefono != -1) os << cliente.telefono; os << "\n";
os << "└─────────────────────────────┘" << "\n";
os << "\n\n";
return os;
}
std::istream& operator>>(std::istream& is, Cliente& cliente) {
std::cout << "┌─────────────────────────────┐" << "\n";
std::cout << "│ MIS DATOS │" << "\n";
std::cout << "┌─────────────────────────────┐" << "\n";
std::cout << " · Nombre: "; is >> cliente.nombre;
std::cout << " · DNI: "; is >> cliente.dni;
std::cout << " · Telef.: "; is >> cliente.telefono;
std::cout << "└─────────────────────────────┘" << "\n";
std::cout << "\n\n";
return is;
}
| true |
d2912d202ea5767548386cfb92e05793a8afe557 | C++ | muhammedzahit/CPP__Codes | /Compositon of Classes/employee.cpp | UTF-8 | 400 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "date.h"
#include "employee.h"
info::info(std::string n_name,std::string n_lastname,date n_birth)
: name(n_name) , lastname(n_lastname) , birth(n_birth)
{}
void info::printInfo(){
std::cout << "Name:" << name << std::endl;
std::cout << "Last Name:" << lastname << std::endl;
std::cout << "Birth Date:" << birth.getDay() << std::endl;
}
| true |
861137dce2393ae15a1529bb40b545d3f284287a | C++ | hychyc07/contrib_bk | /src/mobee/src/Apps/PoseFinder/matrix.cpp | UTF-8 | 11,043 | 3.25 | 3 | [] | no_license | #include "matrix.h"
#include <string.h>
#include <algorithm>
unsigned int rngState[3] = {0, 0, 0};
Matrix::CmpIndex::CmpIndex(const Matrix& lambda, std::vector<unsigned int>& index)
: m_lambda(lambda)
, m_index(index)
{
}
bool Matrix::CmpIndex::operator ()(unsigned int i1, unsigned int i2) const
{
return (m_lambda(i1) > m_lambda(i2));
}
////////////////////////////////////////////////////////////
Matrix::Matrix()
{
resize(0, 0);
}
Matrix::Matrix(unsigned int rows, unsigned int cols)
{
resize(rows, cols);
}
Matrix::Matrix(const Matrix& other)
{
operator = (other);
}
Matrix::Matrix(double* data, unsigned int rows, unsigned int cols)
{
resize(rows, cols);
if (size() > 0) memcpy(&m_data[0], data, size() * sizeof(double));
}
Matrix::Matrix(std::vector<double> &other)
{
resize(other.size(), 1);
if (size() > 0) memcpy(&m_data[0], &other[0], size() * sizeof(double));
}
Matrix::~Matrix()
{
}
Matrix::operator double() const
{
ASSERT(m_rows == 1 && m_cols == 1);
return m_data[0];
}
Matrix Matrix::row(unsigned int r) const
{
ASSERT(r < m_rows);
Matrix ret(1, m_cols);
unsigned int i;
for (i=0; i<m_cols; i++) ret(0, i) = operator () (r, i);
return ret;
}
Matrix Matrix::col(unsigned int c) const
{
ASSERT(c < m_cols);
Matrix ret(m_rows, 1);
unsigned int i;
for (i=0; i<m_rows; i++) ret(i, 0) = operator () (i, c);
return ret;
}
void Matrix::resize(unsigned int rows, unsigned int cols)
{
m_rows = rows;
m_cols = cols;
unsigned int sz = rows * cols;
m_data.resize(sz);
if (sz > 0) memset(&m_data[0], 0, sz * sizeof(double));
}
const Matrix& Matrix::operator = (const Matrix& other)
{
resize(other.rows(), other.cols());
if (size() > 0) memcpy(&m_data[0], &other[0], size() * sizeof(double));
return other;
}
bool Matrix::operator == (const Matrix& other)
{
return (m_rows == other.rows() && m_cols == other.cols() && memcmp(&m_data[0], &other[0], size() * sizeof(double)) == 0);
}
bool Matrix::operator != (const Matrix& other)
{
return (m_rows != other.rows() || m_cols != other.cols() || memcmp(&m_data[0], &other[0], size() * sizeof(double)) != 0);
}
Matrix Matrix::operator + (const Matrix& other) const
{
Matrix ret(*this);
ret += other;
return ret;
}
Matrix Matrix::operator - (const Matrix& other) const
{
Matrix ret(*this);
ret -= other;
return ret;
}
Matrix Matrix::operator * (const Matrix& other) const
{
unsigned int x, xc = other.m_cols;
unsigned int y, yc = m_rows;
unsigned int k, kc = m_cols;
ASSERT(other.m_rows == kc);
Matrix ret(yc, xc);
for (y=0; y<yc; y++)
{
for (x=0; x<xc; x++)
{
double v = 0.0;
for (k=0; k<kc; k++) v += operator () (y, k) * other(k, x);
ret(y, x) = v;
}
}
return ret;
}
void Matrix::operator += (const Matrix& other)
{
ASSERT(m_rows == other.rows());
ASSERT(m_cols == other.cols());
unsigned int i, ic = size();
for (i=0; i<ic; i++) m_data[i] += other[i];
}
void Matrix::operator -= (const Matrix& other)
{
ASSERT(m_rows == other.rows());
ASSERT(m_cols == other.cols());
unsigned int i, ic = size();
for (i=0; i<ic; i++) m_data[i] -= other[i];
}
void Matrix::operator *= (double scalar)
{
unsigned int i, ic = size();
for (i=0; i<ic; i++) m_data[i] *= scalar;
}
void Matrix::operator /= (double scalar)
{
unsigned int i, ic = size();
for (i=0; i<ic; i++) m_data[i] /= scalar;
}
// friend
Matrix operator * (double scalar, const Matrix& mat)
{
Matrix ret(mat.rows(), mat.cols());
unsigned int i, ic = mat.size();
for (i=0; i<ic; i++) ret[i] = scalar * mat[i];
return ret;
}
Matrix Matrix::operator / (double scalar) const
{
Matrix ret(*this);
ret /= scalar;
return ret;
}
// static
Matrix Matrix::zeros(unsigned int rows, unsigned int cols)
{
return Matrix(rows, cols);
}
// static
Matrix Matrix::ones(unsigned int rows, unsigned int cols)
{
ASSERT(rows && cols);
Matrix m(rows, cols);
unsigned int i, ic = rows * cols;
for (i=0; i<ic; i++) m[i] = 1.0;
return m;
}
// static
Matrix Matrix::eye(unsigned int n)
{
Matrix m(n, n);
unsigned int i;
for (i=0; i<n; i++) m(i, i) = 1.0;
return m;
}
// static
Matrix Matrix::fromEig(const Matrix& U, const Matrix& lambda)
{
return U * lambda.diag() * U.T();
}
// eigen-decomposition of a symmetric matrix
void Matrix::eig(Matrix& U, Matrix& lambda, unsigned int iter, bool ignoreError) const
{
ASSERT(isValid() && isSquare());
Matrix basic = *this;
Matrix eigenval(m_rows);
// 1-dim case
if (m_rows == 1) { basic(0, 0) = 1.0; eigenval(0) = m_data[0]; return; }
std::vector<double> oD(m_rows);
unsigned int i, j, k, l, m;
double b, c, f, g, h, hh, p, r, s, scale;
// reduction to tridiagonal form
for (i=m_rows; i-- > 1;)
{
h = 0.0;
scale = 0.0;
if (i > 1) for (k = 0; k < i; k++) scale += fabs(basic(i, k));
if (scale == 0.0) oD[i] = basic(i, i-1);
else
{
for (k = 0; k < i; k++)
{
basic(i, k) /= scale;
h += basic(i, k) * basic(i, k);
}
f = basic(i, i-1);
g = (f > 0.0) ? -::sqrt(h) : ::sqrt(h);
oD[i] = scale * g;
h -= f * g;
basic(i, i-1) = f - g;
f = 0.0;
for (j = 0; j < i; j++)
{
basic(j, i) = basic(i, j) / (scale * h);
g = 0.0;
for (k=0; k <= j; k++) g += basic(j, k) * basic(i, k);
for (k=j+1; k < i; k++) g += basic(k, j) * basic(i, k);
f += (oD[j] = g / h) * basic(i, j);
}
hh = f / (2.0 * h);
for (j=0; j < i; j++)
{
f = basic(i, j);
g = oD[j] - hh * f;
oD[j] = g;
for (k=0; k <= j; k++) basic(j, k) -= f * oD[k] + g * basic(i, k);
}
for (k=i; k--;) basic(i, k) *= scale;
}
eigenval(i) = h;
}
eigenval(0) = oD[0] = 0.0;
// accumulation of transformation matrices
for (i=0; i < m_rows; i++)
{
if (eigenval(i) != 0.0)
{
for (j=0; j < i; j++)
{
g = 0.0;
for (k = 0; k < i; k++) g += basic(i, k) * basic(k, j);
for (k = 0; k < i; k++) basic(k, j) -= g * basic(k, i);
}
}
eigenval(i) = basic(i, i);
basic(i, i) = 1.0;
for (j=0; j < i; j++) basic(i, j) = basic(j, i) = 0.0;
}
// eigenvalues from tridiagonal form
for (i=1; i < m_rows; i++) oD[i-1] = oD[i];
oD[m_rows - 1] = 0.0;
for (l=0; l < m_rows; l++)
{
j = 0;
do
{
// look for small sub-diagonal element
for (m=l; m < m_rows - 1; m++)
{
s = fabs(eigenval(m)) + fabs(eigenval(m + 1));
if (fabs(oD[m]) + s == s) break;
}
p = eigenval(l);
if (m != l)
{
if (j++ == iter)
{
// Too many iterations --> numerical instability!
if (ignoreError) break;
else throw("[Matrix::eig] numerical problems");
}
// form shift
g = (eigenval(l+1) - p) / (2.0 * oD[l]);
r = ::sqrt(g * g + 1.0);
g = eigenval(m) - p + oD[l] / (g + ((g > 0.0) ? fabs(r) : -fabs(r)));
s = 1.0;
c = 1.0;
p = 0.0;
for (i=m; i-- > l;)
{
f = s * oD[i];
b = c * oD[i];
if (fabs(f) >= fabs(g))
{
c = g / f;
r = ::sqrt(c * c + 1.0);
oD[i+1] = f * r;
s = 1.0 / r;
c *= s;
}
else
{
s = f / g;
r = ::sqrt(s * s + 1.0);
oD[i+1] = g * r;
c = 1.0 / r;
s *= c;
}
g = eigenval(i+1) - p;
r = (eigenval(i) - g) * s + 2.0 * c * b;
p = s * r;
eigenval(i+1) = g + p;
g = c * r - b;
for (k=0; k < m_rows; k++)
{
f = basic(k, i+1);
basic(k, i+1) = s * basic(k, i) + c * f;
basic(k, i) = c * basic(k, i) - s * f;
}
}
eigenval(l) -= p;
oD[l] = g;
oD[m] = 0.0;
}
}
while (m != l);
}
// normalize eigenvectors
for (j=m_rows; j--;)
{
s = 0.0;
for (i=m_rows; i--;) s += basic(i, j) * basic(i, j);
s = ::sqrt(s);
for (i=m_rows; i--;) basic(i, j) /= s;
}
// sort by eigenvalues
std::vector<unsigned int> index(m_rows);
for (i=0; i<m_rows; i++) index[i] = i;
CmpIndex cmpidx(eigenval, index);
std::sort(index.begin(), index.end(), cmpidx);
U.resize(m_rows, m_rows);
lambda.resize(m_rows);
for (i=0; i<m_rows; i++)
{
j = index[i];
lambda(i) = eigenval(j);
for (k=0; k<m_rows; k++) U(k, i) = basic(k, j);
}
}
Matrix Matrix::T() const
{
Matrix ret(m_cols, m_rows);
unsigned int r, c;
for (c=0; c<m_cols; c++)
{
for (r=0; r<m_rows; r++)
{
ret(c, r) = (*this)(r, c);
}
}
return ret;
}
Matrix Matrix::exp() const
{
ASSERT(isSquare());
Matrix U;
Matrix lambda;
eig(U, lambda);
unsigned int i;
for (i=0; i<m_rows; i++) lambda(i) = ::exp(lambda(i));
Matrix ret = fromEig(U, lambda);
return ret;
}
Matrix Matrix::log() const
{
ASSERT(isSquare());
Matrix U;
Matrix lambda;
eig(U, lambda);
unsigned int i;
for (i=0; i<m_rows; i++) lambda(i) = ::log(lambda(i));
return fromEig(U, lambda);
}
Matrix Matrix::pow(double e) const
{
ASSERT(isSquare());
Matrix U;
Matrix lambda;
eig(U, lambda);
unsigned int i;
for (i=0; i<m_rows; i++) lambda(i) = ::pow(lambda(i), e);
return fromEig(U, lambda);
}
double Matrix::det() const
{
Matrix U;
Matrix lambda;
eig(U, lambda);
double ret = 1.0;
unsigned int i, ic = lambda.size();
for (i=0; i<ic; i++) ret *= lambda(i);
return ret;
}
double Matrix::logdet() const
{
Matrix U;
Matrix lambda;
eig(U, lambda);
double ret = 0.0;
unsigned int i, ic = lambda.size();
for (i=0; i<ic; i++) ret += ::log(lambda(i));
return ret;
}
double Matrix::tr() const
{
ASSERT(isSquare());
double ret = 0.0;
unsigned int i;
for (i=0; i<m_rows; i++) ret += operator() (i, i);
return ret;
}
double Matrix::min() const
{
double ret = m_data[0];
unsigned int i, ic = size();
for (i=1; i<ic; i++) if (m_data[i] < ret) ret = m_data[i];
return ret;
}
double Matrix::max() const
{
double ret = m_data[0];
unsigned int i, ic = size();
for (i=1; i<ic; i++) if (m_data[i] > ret) ret = m_data[i];
return ret;
}
double Matrix::norm(double p) const
{
unsigned int i, ic = size();
double sum = 0.0;
for (i=0; i<ic; i++) sum += ::pow(fabs(m_data[i]), p);
return ::pow(sum, 1.0 / p);
}
double Matrix::onenorm() const
{
unsigned int i, ic = size();
double sum = 0.0;
for (i=0; i<ic; i++) sum += fabs(m_data[i]);
return sum;
}
double Matrix::twonorm() const
{
unsigned int i, ic = size();
double sum = 0.0;
for (i=0; i<ic; i++)
{
double v = m_data[i];
sum += v * v;
}
return ::sqrt(sum);
}
double Matrix::twonorm2() const
{
unsigned int i, ic = size();
double sum = 0.0;
for (i=0; i<ic; i++)
{
double v = m_data[i];
sum += v * v;
}
return sum;
}
double Matrix::maxnorm() const
{
unsigned int i, ic = size();
double m = fabs(m_data[0]);
for (i=1; i<ic; i++)
{
double v = fabs(m_data[i]);
if (v > m) m = v;
}
return m;
}
Matrix Matrix::diag() const
{
Matrix ret;
unsigned int i;
if (isSquare())
{
ret.resize(m_rows);
for (i=0; i<m_rows; i++) ret(i) = operator() (i, i);
}
else if (m_cols == 1)
{
ret.resize(m_rows, m_rows);
for (i=0; i<m_rows; i++) ret(i, i) = operator() (i);
}
else ASSERT(false);
return ret;
}
void Matrix::print() const
{
unsigned int r, c;
printf("%d x %d matrix:\n", m_rows, m_cols);
for (r=0; r<m_rows; r++)
{
for (c=0; c<m_cols; c++)
{
printf(" %10g\t", operator()(r, c));
}
printf("\n");
}
}
| true |
17064edaecba1653790dc129e0faa01cea087e5c | C++ | bikramjitdas/Daily-Data-Structure-and-Algorithm | /recursion/convert a string to integer using recursion/convert a string to integer using recursion.cpp | UTF-8 | 430 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<algorithm>
using namespace std;
int r = 0;
int stringtoint(string s, int len)
{
if (len == 0)
return r;
r = r * 10 + s[len - 1] - '0' ;
return stringtoint(s, len - 1);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("inputrecursion.txt", "r", stdin);
freopen("outputrecursion.txt", "w", stdout);
#endif
string s = "321";
int len = s.length();
cout << stringtoint(s, len);
return 0;
} | true |
5a7933f7d4ccf2b832e0f8875b91b58ad83f3e42 | C++ | valentin-mladenov/TU-CPP-programing | /graph-work/Ross_Boss_task.cpp | UTF-8 | 839 | 3.234375 | 3 | [] | no_license | //
// Created by hudson on 20.4.2016 г..
//
/*void showAllNodesWithMoreThan2OutboundArcs (node *graph[graphElements]) {
cout << "Nodes found: ";
bool setNone = true;
// first find all that have MORE than 2 arcs OUT.
for (int i = 0; i < graphElements; i++) {
// NO outbound arcs.
if (graph[i] == nullptr) {
continue;
}
// Only ONE outbound arc.
if (graph[i]->next == nullptr) {
continue;
}
// Only TWO outbound arc.
if (graph[i]->next->next == nullptr) {
continue;
}
// this means we find at least one NODE with 2 outbound arcs.
setNone = false;
cout << graph[i]->key << " ";
}
// print none if we does not found any.
if (setNone) {
cout << "NONE!" << endl;
}
}
| true |
21f6adbe3526afc5ee3776dc4a2e6a26bd65a660 | C++ | PLaSSticity/ce-arc-simulator-ipdps19 | /intel-pintool/Viser/microbenchmarks/test2.cpp | UTF-8 | 267 | 2.890625 | 3 | [] | no_license | #include <list>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a = 40, b = 10;
int *c = new int(999);
cout << a << " " << &a << endl;
cout << b << " " << &b << endl;
cout << *c << " " << c << " " << &c << endl;
return 0;
}
| true |
18115cfb212173e33a7d6673dc405dbab7127813 | C++ | kuldeep-singh-chouhan/interviewbit-solutions | /sub-matrices-with-sum-zero.cpp | UTF-8 | 2,389 | 3.234375 | 3 | [
"MIT"
] | permissive | // Time - O(N^2), Space - O(N)
// or Time - O(R^2 * C), Space - O(R * C)
// where R = number of rows and C = number of columns
int Solution::solve(vector<vector<int> > &A) {
const vector<vector<int>>& mat = A;
int r = mat.size();
if(r == 0) {
return 0;
}
int c = mat[0].size();
if(c == 0) {
return 0;
}
vector<vector<int>> sum(r + 1, vector<int>(c + 1, 0));
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
sum[i + 1][j + 1] = mat[i][j] + sum[i + 1][j] + sum[i][j + 1] - sum[i][j];
}
}
unordered_map<int, vector<int>> seen;
int count = 0;
for(int i = 0; i < r; i++) {
for(int j = i + 1; j <= r; j++) {
seen.clear();
seen[0].push_back(0);
int cur_count = 0;
for(int k = 1; k <= c; k++) {
int diff = sum[j][k] - sum[i][k];
seen[diff].push_back(k);
}
for(auto& d: seen) {
int d_count = d.second.size();
count = count + (d_count * (d_count - 1)) / 2;
}
}
}
return count;
}
// Time - O(N^2), Space - O(N)
// or Time - O(R^2 * C), Space - O(R * C)
// where R = number of rows and C = number of columns
int Solution::solve(vector<vector<int> > &A) {
const vector<vector<int>>& mat = A;
int r = mat.size();
if(r == 0) {
return 0;
}
int c = mat[0].size();
if(c == 0) {
return 0;
}
vector<vector<int>> sum(r + 1, vector<int>(c + 1, 0));
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
sum[i + 1][j + 1] = mat[i][j] + sum[i + 1][j] + sum[i][j + 1] - sum[i][j];
}
}
// This version just has a different way of calculating count. See Interviewbit notes.
unordered_map<int, int> seen;
int count = 0;
for(int i = 0; i < r; i++) {
for(int j = i + 1; j <= r; j++) {
seen.clear();
seen[0] = 1;
for(int k = 1; k <= c; k++) {
int diff = sum[j][k] - sum[i][k];
// This version just has a different way of calculating count. See Interviewbit notes.
count += seen[diff];
seen[diff]++;
}
}
}
return count;
}
| true |
224c815b4d1bc14fcc8d539d4f83ade6d585f540 | C++ | DicardoX/LeetCode_Daily_Problem | /Easy/0014_最长公共前缀.cpp | UTF-8 | 1,035 | 3.59375 | 4 | [] | no_license | /**
* 题目见:https://leetcode-cn.com/problems/longest-common-prefix/
**/
/** 方法:顺序遍历 **/
class Solution {
public:
void compare(string& str, string& part) {
int vis = -1;
for(int i = 0; i < part.size() && i < str.size(); i++) {
if(str[i] != part[i]) {
vis = i - 1;
break;
} else if(i == part.size() - 1 || i == str.size() - 1) {
vis = i;
break;
}
}
while(part.size() > vis + 1) part.pop_back();
}
string longestCommonPrefix(vector<string>& strs) {
string ret;
if(!strs.size()) return ret;
if(strs.size() == 1) return strs[0];
string str1 = strs[0], str2 = strs[1];
int vis = 0;
while(vis < str1.size() && vis < str2.size() && str1[vis] == str2[vis]) {
ret = ret + str1[vis++];
}
for(int i = 2; i < strs.size(); i++) {
compare(strs[i], ret);
}
return ret;
}
};
| true |
7e773999678e1931ef88ab5b7b748e52b90393ff | C++ | Alaxe/noi2-ranking | /2017/solutions/C/IPD-Varna/color.cpp | UTF-8 | 520 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int t, n, color[10][100003], number, br;
int main ()
{
cin>>t;
for (int ti=0; ti<t; ti++)
{
cin>>n;
br=0;
for (int i=0; i<n; i++)
{
cin>>number;
color[ti][number]++;
}
for (int i=1; i<=n; i++)
{
br = max(color[ti][i], br);
}
cout<<br+1<<endl;
}
}
/*
2
4
4 1 2 3
5
4 1 2 3 4
*/
| true |
665c3356317929b4795743fd7ddd51d97719b497 | C++ | 88soham/AVLRedBlackBTree | /ModeRandom/generate_random_inputs.cpp | UTF-8 | 523 | 2.828125 | 3 | [] | no_license | #include "header.h"
main()
{
int i,n,rand_pos;
int *input;
FILE* fp_out=fopen("random_input.txt","w");
srand((unsigned)(time(NULL)));
printf("\n Enter the number of keys:");
scanf("%d",&n);
input=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
input[i]=-1;
for(i=0;i<n;)
{
rand_pos=rand()%n;
if(input[rand_pos]==-1)
{
input[rand_pos]=i+1;
i++;
//printf("\n%d",i);
}
}
fprintf(fp_out,"%d",n);
for(i=0;i<n;i++)
fprintf(fp_out,"\n%d %d",input[i],2*input[i]);
fclose(fp_out);
}
| true |
248898e5fb6bbaa7285e6f64a274514b0b74a595 | C++ | arthurphilippe/zappy | /player/src/Socket.cpp | UTF-8 | 2,099 | 2.8125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** zappy
** File description:
** Socket
*/
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include "Socket.hpp"
#include "color.h"
namespace pl {
Socket::Socket(const int ac, char **av)
: _port(0), _machine("localhost"), _tv({1, 0})
{
if (ac >= 2)
_port = std::stoi(av[1]);
else
throw std::runtime_error("Not Enough Arguments");
createSocket();
connectSocket();
}
Socket::Socket()
: _port(0), _machine("localhost"), _tv({1, 0})
{
createSocket();
}
Socket::~Socket()
{
close(_socket);
}
void Socket::operator<<(const std::string &string)
{
std::cout << "Sending to server :" << ANSI_BOLD_COLOR_MAGENTA << string << ANSI_BOLD_COLOR_RESET << std::endl;
if (write(_socket, string.c_str(), string.length()) == -1)
throw std::runtime_error("Cannot write on socket");
}
void Socket::operator<<(const int i)
{
std::string str(std::to_string(i));
if (write(_socket, str.c_str(), str.length()) == -1)
throw std::runtime_error("Cannot write on socket");
}
void Socket::createSocket()
{
_socket = socket(AF_INET, SOCK_STREAM, 0);
if (!_socket)
throw std::runtime_error("Cannot create a socket");
}
void Socket::connectSocket()
{
struct sockaddr_in s_in;
struct hostent *h;
if ((h = gethostbyname(_machine.c_str())) == nullptr)
throw std::runtime_error("Cannot connect the machine");
struct in_addr **serv_char_ip;
char *ip;
serv_char_ip = (struct in_addr **) h->h_addr_list;
ip = inet_ntoa(*serv_char_ip[0]);
s_in.sin_family = AF_INET;
s_in.sin_port = htons(_port);
s_in.sin_addr.s_addr = inet_addr(ip);
if (connect(_socket, (const struct sockaddr *) &s_in,
sizeof(s_in)) == -1) {
throw std::runtime_error("Cannot connect the socket");
}
}
bool Socket::read(std::string &data)
{
static char buf[4096];
memset(buf, 0, 4096);
FD_ZERO(&_fd_read);
FD_SET(_socket, &_fd_read);
select(_socket + 1, &_fd_read, NULL, NULL, &_tv);
if (FD_ISSET(_socket, &_fd_read)) {
::read(_socket, buf, 4095);
data = buf;
return true;
};
return false;
}
}
| true |
edecd0e7b844d8fe462978c9f4d8a3d5793f94dc | C++ | NeXTormer/Uebungen | /Voltmeter-Java-Final/builds/voltmeter.ino | UTF-8 | 357 | 2.515625 | 3 | [] | no_license | //Arduino - Java Voltmeter
//Program needs Java Voltmeter desktop applictaion
//Created by Felix Holz on 14.11.2017
#define A0 PIN_POTI
int adcvalue = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available() > 0)
{
char in = Serial.read();
if(in == 'R')
{
adcvalue = analogRead(PIN_POTI);
Serial.println(adcvalue);
}
}
} | true |
0b490be99f6333e9afd9217ca7a4f080a16da620 | C++ | Assylzhan-Izbassar/Timus-Online-Judge | /volume4/1313.cpp | UTF-8 | 388 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(){
int n;
scanf("%d", &n);
vector<vector<int> > arr;
vector<int> temp;
int x;
for(size_t i=0; i < n; ++i){
temp.clear();
for(size_t j=0; j < n; ++j){
scanf("%d", &x);
temp.push_back(x);
}
arr.push_back(temp);
}
return 0;
} | true |
f12bdc6bf7ee1b9fc2e8cc921f42be9062041238 | C++ | msercheli/openexr | /docs/src/readDeepTiledFile.cpp | UTF-8 | 2,801 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | void
readDeepTiledFile(const char filename[],
Box2i& displayWindow,
Box2i& dataWindow,
Array2D< float* >& dataZ,
Array2D< half* >& dataA,
Array2D< unsigned int >& sampleCount)
{
DeepTiledInputFile file(filename);
int width = dataWindow.max.x - dataWindow.min.x + 1;
int height = dataWindow.max.y - dataWindow.min.y + 1;
sampleCount.resizeErase(height, width);
dataZ.resizeErase(height, width);
dataA.resizeErase(height, width);
DeepFrameBuffer frameBuffer;
frameBuffer.insertSampleCountSlice (Slice (UINT,
(char *) (&sampleCount[0][0]
- dataWindow.min.x
- dataWindow.min.y * width),
sizeof (unsigned int) * 1, // xStride
sizeof (unsigned int) * width)); // yStride
frameBuffer.insert ("Z",
DeepSlice (FLOAT,
(char *) (&dataZ[0][0]
- dataWindow.min.x
- dataWindow.min.y * width),
sizeof (float *) * 1, // xStride for pointer array
sizeof (float *) * width, // yStride for pointer array
sizeof (float) * 1)); // stride for samples
frameBuffer.insert ("A",
DeepSlice (HALF,
(char *) (&dataA[0][0]
- dataWindow.min.x
- dataWindow.min.y * width),
sizeof (half *) * 1, // xStride for pointer array
sizeof (half *) * width, // yStride for pointer array
sizeof (half) * 1)); // stride for samples
file.setFrameBuffer(frameBuffer);
int numXTiles = file.numXTiles(0);
int numYTiles = file.numYTiles(0);
file.readPixelSampleCounts(0, numXTiles - 1, 0, numYTiles - 1);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
dataZ[i][j] = new float[sampleCount[i][j]];
dataA[i][j] = new half[sampleCount[i][j]];
}
file.readTiles(0, numXTiles - 1, 0, numYTiles – 1);
// (after read data is processed, data must be freed:)
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
delete[] dataZ[i][j];
delete[] dataA[i][j];
}
}
}
| true |
5b1f3890aa331de70cc9eb7a3d1aea578106a3a9 | C++ | Arzana/Plutonium | /code/src/Streams/FileReader.cpp | UTF-8 | 7,966 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "Streams/FileReader.h"
#include "Core/EnumUtils.h"
#include "Core/Diagnostics/Logging.h"
#include "Core/Diagnostics/DbgUtils.h"
#include "Core/Platform/Windows/Windows.h"
#include <cstdio>
#include <cstring>
#include <filesystem>
using namespace Pu;
Pu::FileReader::FileReader(const wstring &path, bool log)
: fpath(path), open(false), hndlr(nullptr)
{
Open(log);
}
Pu::FileReader::FileReader(const FileReader & value)
: fpath(value.fpath), open(false), hndlr(nullptr)
{
/* Open a new file handle if needed. */
if (value.open) Open(false);
}
Pu::FileReader::FileReader(FileReader && value)
: fpath(std::move(value.fpath)), open(value.open), hndlr(value.hndlr)
{
/* Clear moved attributes. */
value.fpath.clear();
value.open = false;
value.hndlr = nullptr;
}
Pu::FileReader::~FileReader(void) noexcept
{
/* Closes the stream if it's still open. */
if (open) Close();
}
FileReader & Pu::FileReader::operator=(const FileReader & other)
{
if (this != &other)
{
/* Closes the stream if it's still open. */
if (open) Close();
/* Copy over new data. */
fpath = other.fpath;
/* Open file is needed. */
if (other.open) Open(false);
}
return *this;
}
FileReader & Pu::FileReader::operator=(FileReader && other)
{
if (this != &other)
{
/* Closes the stream if it's still open. */
if (open) Close();
/* Move file attributes and file handle. */
fpath = std::move(other.fpath);
open = other.open;
hndlr = other.hndlr;
/* Clear moved attributes. */
other.fpath.clear();
other.open = false;
other.hndlr = nullptr;
}
return *this;
}
wstring Pu::FileReader::GetCurrentDirectory(void)
{
#ifdef _WIN32
/* Get raw directory. */
WCHAR buffer[FILENAME_MAX];
const DWORD len = WinGetCurrentDirectory(FILENAME_MAX, buffer);
/* Error check. */
if (!len)
{
const wstring error = _CrtGetErrorString();
Log::Error("Failed to get working directory (%ls)!", error.c_str());
}
/* Return string varient for variable memory release. */
return wstring(buffer);
#else
Log::Warning("Cannot get working directory on this platform!");
return L"";
#endif
}
bool Pu::FileReader::FileExists(const wstring &path)
{
return std::filesystem::exists(path.c_str());
}
void Pu::FileReader::Close(void)
{
const wstring fname = fpath.fileName();
if (open)
{
/* Attempt to close the file. */
if (fclose(hndlr) == EOF) Log::Error("Unable to close file '%ls' (%ls)!", fname.c_str(), FileError().c_str());
else
{
open = false;
Log::Verbose("Closed file '%ls'.", fname.c_str());
}
}
else Log::Warning("Cannot close non-opened file '%ls'!", fname.c_str());
}
int32 Pu::FileReader::Read(void)
{
/* On debug check if file is open, and read from handler. */
FileNotOpen();
return fgetc(hndlr);
}
size_t Pu::FileReader::Read(byte * buffer, size_t offset, size_t amount)
{
/* On debug check if file is open. */
FileNotOpen();
return fread(buffer + offset, sizeof(byte), amount, hndlr);
}
string Pu::FileReader::ReadLine(void)
{
constexpr int BUFFER_SIZE = 256;
string result;
/* On debug check if file is open. */
FileNotOpen();
/*
We use fgets to read until either a newline or EOF.
The last character is used to determine whether the full buffer is used.
fgets will add a null terminator in the last slot if it hasn't read the whole line.
So if this marker is null then there is more content to read.
*/
char buffer[BUFFER_SIZE];
buffer[BUFFER_SIZE - 1] = ~0;
while (fgets(buffer, BUFFER_SIZE, hndlr))
{
/*
If the buffer was too small for the full line,
fgets will put a null-terminator at the end of the buffer.
*/
if (buffer[BUFFER_SIZE - 1] == '\0')
{
result += buffer;
buffer[BUFFER_SIZE - 1] = ~0;
}
else
{
result = buffer;
break;
}
}
/* The linefeed is always added at the end, we don't want to return this. */
return result.trim_back("\r\n");
}
string Pu::FileReader::ReadToEnd(void)
{
/* On debug check if file is open. */
FileNotOpen();
/* Get the remaining length of the file. */
const int64 pos = GetPosition();
SeekInternal(SeekOrigin::End, 0);
const size_t len = static_cast<size_t>(GetPosition());
SeekInternal(SeekOrigin::Begin, pos);
/* Allocate space for string and populate it. */
string result(len);
const size_t checkLen = fread(result.data(), sizeof(char), len, hndlr);
/* Check for errors. */
if (checkLen > len) Log::Fatal("Expected length of string doesn't match actual length!");
return result;
}
int32 Pu::FileReader::Peek(void)
{
/* On debug check if file is open. */
FileNotOpen();
/* Get current read position, read char and set read position back. */
const int64 pos = GetPosition();
const int32 result = Read();
SeekInternal(SeekOrigin::Begin, pos);
return result;
}
size_t Pu::FileReader::Peek(byte * buffer, size_t offset, size_t amount)
{
/* On debug check if file is open. */
FileNotOpen();
/* Get current read position, read buffer and set read position back. */
const int64 pos = GetPosition();
const size_t result = Read(buffer, offset, amount);
SeekInternal(SeekOrigin::Begin, pos);
return result;
}
void Pu::FileReader::Seek(SeekOrigin from, int64 amount)
{
/* On debug check if file is open. */
FileNotOpen();
SeekInternal(from, amount);
}
int64 Pu::FileReader::GetPosition(void) const
{
return ftell(hndlr);
}
int64 Pu::FileReader::GetSize(void) const
{
if (!open) return 0;
const int64 oldPos = GetPosition();
SeekInternal(SeekOrigin::End, 0);
const int64 size = GetPosition();
SeekInternal(SeekOrigin::Begin, oldPos);
return size;
}
size_t Pu::FileReader::GetCharacterCount(char value)
{
constexpr size_t BLOCK_SIZE = 4096;
constexpr size_t AVX_BLOCK_SIZE = BLOCK_SIZE / sizeof(int256);
/* Just early out if the file wasn't open. */
if (!open) return 0;
const int64 oldPos = GetPosition();
SeekInternal(SeekOrigin::Begin, 0);
/* Preset these values, loading into an AVX registry is slow. */
#pragma warning (push)
#pragma warning (disable:4309)
const int256 valueMask = _mm256_set1_epi8(value);
const int256 one = _mm256_set1_epi8(1);
const int256 andMask = _mm256_set1_epi8(0x80);
#pragma warning (pop)
/* Force allignment with an AVX buffer, but also make a byte buffer for ease of use. */
int256 memory[AVX_BLOCK_SIZE];
char *bytes = reinterpret_cast<char*>(memory);
/* Read in block increments (these should be the size of a memory page). */
size_t result = 0;
size_t bytesRead;
while ((bytesRead = fread(bytes, sizeof(char), BLOCK_SIZE, hndlr)) > 0)
{
/* Set any dangling values to zero, so they won't disturb the count. */
memset(bytes + bytesRead, 0, BLOCK_SIZE - bytesRead);
for (size_t i = 0; i < AVX_BLOCK_SIZE; i++)
{
/* Use SWAR to check 32 bytes at once. */
int256 data = _mm256_xor_si256(memory[i], valueMask);
data = _mm256_and_si256(_mm256_sub_epi8(data, one), _mm256_andnot_si256(data, andMask));
result += _mm_popcnt_u32(_mm256_movemask_epi8(data));
}
}
SeekInternal(SeekOrigin::Begin, oldPos);
return result;
}
void Pu::FileReader::SeekInternal(SeekOrigin from, int64 amount) const
{
if (fseek(hndlr, static_cast<long>(amount), _CrtEnum2Int(from))) Log::Fatal("Unable to seek to position %zd in file '%ls' (%ls)!", amount, fpath.fileName().c_str(), FileError().c_str());
}
void Pu::FileReader::Open(bool log)
{
const wstring fname = fpath.fileName();
if (!open)
{
/* Attempt to open the file in binary read mode. */
if (!_wfopen_s(&hndlr, fpath.c_str(), L"rb"))
{
open = true;
Log::Verbose("Successfully opened file '%ls'.", fname.c_str());
}
else if (log) Log::Error("Failed to open '%ls' (%ls)!", fpath.c_str(), _CrtGetErrorString().c_str());
}
else Log::Warning("Cannot open already opened file '%ls'!", fname.c_str());
}
wstring Pu::FileReader::FileError(void) const
{
return _CrtFormatError(ferror(hndlr));
}
void Pu::FileReader::FileNotOpen(void)
{
#ifdef _DEBUG
if (!open) Log::Fatal("File '%ls' isn't open!", fpath.fileName().c_str());
#endif
} | true |
0661dcd30b0e9494316af1616ed0eb19dc8591ca | C++ | adityasarvaiya/coding | /Crio/Array/14_SwapAllOddAndEvenBits/SwapAllOddAndEvenBits.cpp | UTF-8 | 441 | 3.03125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
unsigned int swapAllOddAndEvenBits(unsigned int n) {
// CRIO_SOLUTION_START_MODULE_L1_PROBLEMS
for(int i = 0 ; i < 32 ; i+=2) {
if((((n >> i)&1)^(n >> (i+1))&1) == 1) {
n ^= (1 << i);
n ^= (1 << (i+1));
}
}
return n;
// CRIO_SOLUTION_END_MODULE_L1_PROBLEMS
}
int main()
{
unsigned int n;
cin >> n;
unsigned int answer = swapAllOddAndEvenBits(n);
cout << answer;
return 0;
}
| true |
b05ec9f996c82c0e0effa5c095959322f1c01e8a | C++ | dark-w/algo-cloud | /src/heap.cpp | UTF-8 | 546 | 2.75 | 3 | [] | no_license | #include "heap.h"
#include "mm.h"
#include <iostream>
heap::heap(/* args */)
{
}
heap::~heap()
{
}
bool heap::heap_init(const int32_t config_heap_size) {
std::cout << __func__ << std::endl;
bool retbool = false;
if (my_heap_init(config_heap_size) != 0)
retbool = true;
return retbool;
}
int64_t heap::malloc(const int32_t size) {
std::cout << __func__ << std::endl;
return (int64_t)my_malloc(size);
}
void heap::free(const int64_t addr) {
std::cout << __func__ << std::endl;
my_free((void *)addr);
}
| true |
8b631816a2bac77c52740f4a1e0250624f67c812 | C++ | danieldc/newsbeuter | /test/rss.cpp | UTF-8 | 8,013 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "catch.hpp"
#include <rsspp.h>
#include <rsspp_internal.h>
TEST_CASE("Throws exception if file doesn't exist", "[rsspp::parser]") {
rsspp::parser p;
try {
rsspp::feed f = p.parse_file("data/non-existent.xml");
} catch (rsspp::exception e) {
REQUIRE(e.what() == std::string("could not parse file"));
}
}
TEST_CASE("Throws exception if file can't be parsed", "[rsspp::parser]") {
rsspp::parser p;
try {
rsspp::feed f = p.parse_file("data/empty.xml");
} catch (rsspp::exception e) {
REQUIRE(e.what() == std::string("could not parse file"));
}
}
TEST_CASE("Parsers behave correctly", "[rsspp::parser]") {
rsspp::parser p;
rsspp::feed f;
SECTION("RSS 0.91 is parsed correctly") {
REQUIRE_NOTHROW(f = p.parse_file("data/rss091_1.xml"));
REQUIRE(f.rss_version == rsspp::RSS_0_91);
REQUIRE(f.title == "Example Channel");
REQUIRE(f.description == "an example feed");
REQUIRE(f.link == "http://example.com/");
REQUIRE(f.language == "en");
REQUIRE(f.items.size() == 1u);
REQUIRE(f.items[0].title == "1 < 2");
REQUIRE(f.items[0].link == "http://example.com/1_less_than_2.html");
REQUIRE(f.items[0].description == "1 < 2, 3 < 4.\nIn HTML, <b> starts a bold phrase\nand you start a link with <a href=\n");
REQUIRE(f.items[0].author == "");
REQUIRE(f.items[0].guid == "");
}
SECTION("RSS 0.92 is parsed correctly") {
REQUIRE_NOTHROW(f = p.parse_file("data/rss092_1.xml"));
REQUIRE(f.rss_version == rsspp::RSS_0_92);
REQUIRE(f.title == "Example Channel");
REQUIRE(f.description == "an example feed");
REQUIRE(f.link == "http://example.com/");
REQUIRE(f.language == "en");
REQUIRE(f.items.size() == 3u);
REQUIRE(f.items[0].title == "1 < 2");
REQUIRE(f.items[0].link == "http://example.com/1_less_than_2.html");
REQUIRE(f.items[0].base == "http://example.com/feed/rss_testing.html");
REQUIRE(f.items[1].title == "A second item");
REQUIRE(f.items[1].link == "http://example.com/a_second_item.html");
REQUIRE(f.items[1].description == "no description");
REQUIRE(f.items[1].author == "");
REQUIRE(f.items[1].guid == "");
REQUIRE(f.items[1].base == "http://example.com/item/rss_testing.html");
REQUIRE(f.items[2].title == "A third item");
REQUIRE(f.items[2].link == "http://example.com/a_third_item.html");
REQUIRE(f.items[2].description == "no description");
REQUIRE(f.items[2].base == "http://example.com/desc/rss_testing.html");
}
SECTION("RSS 2.0 is parsed correctly") {
REQUIRE_NOTHROW(f = p.parse_file("data/rss20_1.xml"));
REQUIRE(f.title == "my weblog");
REQUIRE(f.link == "http://example.com/blog/");
REQUIRE(f.description == "my description");
REQUIRE(f.items.size() == 1u);
REQUIRE(f.items[0].title == "this is an item");
REQUIRE(f.items[0].link == "http://example.com/blog/this_is_an_item.html");
REQUIRE(f.items[0].author == "Andreas Krennmair");
REQUIRE(f.items[0].author_email == "blog@synflood.at");
REQUIRE(f.items[0].content_encoded == "oh well, this is the content.");
REQUIRE(f.items[0].pubDate == "Fri, 12 Dec 2008 02:36:10 +0100");
REQUIRE(f.items[0].guid == "http://example.com/blog/this_is_an_item.html");
REQUIRE_FALSE(f.items[0].guid_isPermaLink);
}
SECTION("RSS 1.0 is parsed correctly") {
REQUIRE_NOTHROW(f = p.parse_file("data/rss10_1.xml"));
REQUIRE(f.rss_version == rsspp::RSS_1_0);
REQUIRE(f.title == "Example Dot Org");
REQUIRE(f.link == "http://www.example.org");
REQUIRE(f.description == "the Example Organization web site");
REQUIRE(f.items.size() == 1u);
REQUIRE(f.items[0].title == "New Status Updates");
REQUIRE(f.items[0].link == "http://www.example.org/status/foo");
REQUIRE(f.items[0].guid == "http://www.example.org/status/");
REQUIRE(f.items[0].description == "News about the Example project");
REQUIRE(f.items[0].pubDate == "Tue, 30 Dec 2008 07:20:00 +0000");
}
SECTION("Atom 1.0 is parsed correctly") {
REQUIRE_NOTHROW(f = p.parse_file("data/atom10_1.xml"));
REQUIRE(f.rss_version == rsspp::ATOM_1_0);
REQUIRE(f.title == "test atom");
REQUIRE(f.title_type == "text");
REQUIRE(f.description == "atom description!");
REQUIRE(f.pubDate == "Tue, 30 Dec 2008 18:26:15 +0000");
REQUIRE(f.link == "http://example.com/");
REQUIRE(f.items.size() == 3u);
REQUIRE(f.items[0].title == "A gentle introduction to Atom testing");
REQUIRE(f.items[0].title_type == "html");
REQUIRE(f.items[0].link == "http://example.com/atom_testing.html");
REQUIRE(f.items[0].guid == "tag:example.com,2008-12-30:/atom_testing");
REQUIRE(f.items[0].description == "some content");
REQUIRE(f.items[0].base == "http://example.com/feed/atom_testing.html");
REQUIRE(f.items[1].title == "A missing rel attribute");
REQUIRE(f.items[1].title_type == "html");
REQUIRE(f.items[1].link == "http://example.com/atom_testing.html");
REQUIRE(f.items[1].guid == "tag:example.com,2008-12-30:/atom_testing1");
REQUIRE(f.items[1].description == "some content");
REQUIRE(f.items[1].base == "http://example.com/entry/atom_testing.html");
REQUIRE(f.items[2].title == "alternate link isn't first");
REQUIRE(f.items[2].title_type == "html");
REQUIRE(f.items[2].link == "http://example.com/atom_testing.html");
REQUIRE(f.items[2].guid == "tag:example.com,2008-12-30:/atom_testing2");
REQUIRE(f.items[2].description == "some content");
REQUIRE(f.items[2].base == "http://example.com/content/atom_testing.html");
}
}
TEST_CASE("W3CDTF parser behaves correctly", "[rsspp::rss_parser]") {
SECTION("W3CDTF year only") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008") == "Tue, 01 Jan 2008 00:00:00 +0000");
}
SECTION("W3CDTF year-month only") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12") == "Mon, 01 Dec 2008 00:00:00 +0000");
}
SECTION("W3CDTF year-month-day only") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30") == "Tue, 30 Dec 2008 00:00:00 +0000");
}
SECTION("W3CDTF with Z timezone") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30T13:03:15Z") == "Tue, 30 Dec 2008 13:03:15 +0000");
}
SECTION("W3CDTF with -08:00 timezone") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30T10:03:15-08:00") == "Tue, 30 Dec 2008 18:03:15 +0000");
}
SECTION("Invalid W3CDTF (foobar)") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("foobar") == "");
}
SECTION("Invalid W3CDTF (negative number)") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("-3") == "");
}
SECTION("Invalid W3CDTF (empty string)") {
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("") == "");
}
}
TEST_CASE("W3C DTF to RFC 822 conversion behaves correctly with different "
"local timezones", "[rsspp::rss_parser]") {
// There has been a problem in the C date conversion functions when the TZ is
// set to different locations, and localtime is in daylight savings. One of
// these two next tests sections should be in active daylight savings.
// https://github.com/akrennmair/newsbeuter/issues/369
char *tz = getenv("TZ");
std::string tz_saved_value;
if (tz) {
// tz can be null, and buffer may be reused. Save it if it exists.
tz_saved_value = tz;
}
SECTION("Timezone Pacific") {
setenv("TZ", "US/Pacific", 1);
tzset();
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30T10:03:15-08:00") == "Tue, 30 Dec 2008 18:03:15 +0000");
}
SECTION("Timezone Australia") {
setenv("TZ", "Australia/Sydney", 1);
tzset();
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30T10:03:15-08:00") == "Tue, 30 Dec 2008 18:03:15 +0000");
}
SECTION("Timezone Arizona") {
setenv("TZ", "US/Arizona", 1);
tzset();
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30T10:03:15-08:00") == "Tue, 30 Dec 2008 18:03:15 +0000");
}
SECTION("Timezone UTC") {
setenv("TZ", "UTC", 1);
tzset();
REQUIRE(rsspp::rss_parser::__w3cdtf_to_rfc822("2008-12-30T10:03:15-08:00") == "Tue, 30 Dec 2008 18:03:15 +0000");
}
// Reset back to original value
if (tz) {
setenv("TZ", tz_saved_value.c_str(), 1);
}
else {
unsetenv("TZ");
}
tzset();
}
| true |
e88a73b3ad0a8aab1e787b36b636e40f0b951f18 | C++ | haramakoto/MuseofJiyugaoka | /MuseJiyugaoka/src/cloths/Particle.cpp | UTF-8 | 1,795 | 3.09375 | 3 | [] | no_license | #include "Particle.h"
// Constructors
Particle::Particle(Vector3f position, Vector3f acceleration)
: m_position(position), m_velocity(0,0,0), m_acceleration(acceleration), m_forceAccumulated(0,0,0), m_normal(0,0,0), m_damping(0.86), m_inverseMass(3), m_stationary(false)
{
}
Particle::Particle(const Particle& particle)
: m_position(particle.getPosition()), m_velocity(particle.getVelocity()), m_acceleration(particle.getAcceleration()), m_forceAccumulated(particle.getForceAccumulated()),
m_normal(particle.getNormal()), m_damping(particle.getDamping()), m_inverseMass(particle.getInverseMass()), m_stationary(particle.getStationary())
{
}
Particle::Particle()
: m_position(0,0,0), m_velocity(0,0,0), m_acceleration(0,0,0), m_forceAccumulated(0,0,0), m_normal(0,0,0), m_damping(0.001), m_inverseMass(3), m_stationary(false)
{
}
Particle& Particle::operator= (const Particle& particle) {
m_position = particle.getPosition();
m_velocity = particle.getVelocity();
m_acceleration = particle.getAcceleration();
m_forceAccumulated = particle.getForceAccumulated();
m_normal = particle.getNormal();
m_damping = particle.getDamping();
m_inverseMass = particle.getInverseMass();
m_stationary = particle.getStationary();
return *this;
}
// Move the Particle forward in time by applying acceleration to the velocity and moving the position by the velocity
void Particle::integrate(float duration)
{
// If the object is moving forward in time and not stationary
if ((duration > 0) && (!m_stationary)){
// Move forward by the specified duration
m_position += m_velocity * duration;
m_velocity += (m_forceAccumulated * m_inverseMass) * duration;
m_forceAccumulated = Vector3f(0,0,0);
m_velocity *= pow(m_damping, duration);
}
} | true |
8a80fab5edc7bc0575151e9a41fe9bcdd01d64e8 | C++ | bunelr/dovl-assignment | /main.cpp | UTF-8 | 1,112 | 2.796875 | 3 | [] | no_license | #include "ioUtils.h"
#include "imageClass.h"
#include "problemStatic.h"
#include "trw.h"
#include <fstream>
#include <sstream>
int main(int argc, char * argv[]) {
image LImageContent;
image RImageContent;
getImage(LImageContent, "imL.png");
getImage(RImageContent, "imR.png");
cout<<"left is: "<<LImageContent.width<<"x"<<LImageContent.height<<endl;
cout<<"right is: "<<RImageContent.width<<"x"<<RImageContent.height<<endl;
printImage(LImageContent, "newImage.png");
vector<vector<int>> labels = vector<vector<int>>(LImageContent.height, vector<int>(LImageContent.width, NBR_CLASSES));
vector<float> dual_values;
vector<float> primal_values;
trw(LImageContent, RImageContent, labels, dual_values, primal_values);
image labelsImage = image(labels);
printImage(labelsImage, "labelsImage.png");
ofstream outfile("evolution.dat");
int nb_points = dual_values.size();
outfile<<"#Dual \t Primal"<<endl;
for(int i=0; i< nb_points; ++i) {
outfile<<dual_values[i]<<"\t"
<<primal_values[i]<<endl;
}
return 0;
}
| true |
e3697fe48b2794a7747464de0c036a9d8044696b | C++ | renyajie/Learning | /Algorithm/提高/图论/拓扑排序/可达性统计.cpp | GB18030 | 1,213 | 2.546875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<algorithm>
#include<bitset>
using namespace std;
const int N = 30010, M = 30010;
int h[N], e[N], ne[N], idx;
int q[N], d[N];
bitset<N> dp[N];
int n, m;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void topsort()
{
int hh = 0, tt = -1;
for(int i = 1; i <= n; i++)
{
if(!d[i])
{
q[++tt] = i;
}
}
while(hh <= tt)
{
int t = q[hh++];
for(int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if(--d[j] == 0)
{
q[++tt] = j;
}
}
}
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
for(int i = 0; i < m; i++)
{
int a, b; scanf("%d%d", &a, &b);
add(a, b);
d[b]++;
}
topsort();
for(int i = n - 1; i >= 0; i--)
{
int t = q[i]; // ǵôȡ
dp[t][t] = 1;
for(int j = h[t]; ~j; j = ne[j])
{
int k = e[j];
dp[t] |= dp[k];
}
}
for(int i = 1; i <= n; i++) printf("%d\n", dp[i].count());
return 0;
}
| true |
c4225a96414a269c840af1b207bd89df650044ea | C++ | wangxu989/study | /c++/c++11/tuple.cpp | UTF-8 | 663 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
template<typename... types >class my_tuple;//原始定义
template<>class my_tuple<>{};//无参特化
template<typename T,typename... T1>
class my_tuple<T,T1...>:public my_tuple<T1...> {//带参特化
typedef my_tuple<T1...> f_type;
public:
template<typename V,typename... types>
my_tuple<T,T1...>(const V& v,const types&... v2):val(v),f_type(v2...) {
}
T& get_val() {
return val;
}
f_type& get_f() {
return *static_cast<f_type*>(this);
}
private:
T val;
};
int main() {
my_tuple<string,int,double,float>a("hh",1,2.2,3.3);
std::cout<<a.get_val()<<a.get_f().get_val()<<endl;
}
| true |
34d48637dfb35f0fe0f25e29792621b799af2d19 | C++ | ahmorsi/Fast-Point-Feature-Histograms | /project/PointCloud.h | UTF-8 | 801 | 3.25 | 3 | [] | no_license | #ifndef POINTCLOUD_H_
#define POINTCLOUD_H_
#include <vector>
#include "Point.h"
/** \brief Implementation of a point cloud
*
* The point cloud stores a set of points and provides methods for sorting them
*
* \author mack
*/
class PointCloud {
std::vector<Point*> points;
unsigned int size;
public:
PointCloud();
PointCloud(std::vector<Point*>);
virtual ~PointCloud();
std::vector<Point*> getPoints() const;
unsigned int getSize() const;
Point* getCentroid() const;
//add point to point cloud
void addPoint(Point*);
void clear();
friend std::ostream& operator<<(std::ostream& out, const PointCloud& p) {
out.width(4);
out.precision(3);
for (unsigned int i = 0; i < p.getSize(); i++) {
out << *p.getPoints()[i];
}
return out;
}
};
#endif /* POINTCLOUD_H_ */
| true |
000abe4ac686902021d9b99b5e5fcea94e7574da | C++ | lauritsriple/EQ-Disco | /disco/io.cpp | UTF-8 | 4,155 | 2.65625 | 3 | [] | no_license | /*
* io.cpp
*
* Created: 09/06/2015 22:05:18
* Author: Lua
*/
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include "io.h"
#include <stdlib.h>
void pwm_init(void){
//OC0A -> PB2 -> RED
//OC0B -> PA7 -> GREEN
//OC1A -> PA6 -> BLUE
DDRB |= (1 << RED);
DDRA |= (1 << GREEN) | (1 << BLUE);
//****** COUNTER0 8-bit
// Counter 0B clear OC0B at bottom (counting up)
TCCR0A |= ( 1 << COM0B1);
TCCR0A |= ( 1 << COM0A1);
// Set 0xFF as top, update OCRx at bottom, TOV flag on max
TCCR0A |= ( 1 << WGM01) | ( 1 << WGM00);
// No prescaling
TCCR0B |= (1 << CS01);
//Both output compare already initialized as zero.
//****** COUNTER1 16-bit
//Counter 1A and 1B clear at bottom
TCCR1A |= ( 1 << COM1A1); //| ( 1 << COM1B1);
//TCCR1A &= ~(1 << COM1A0); //| (1 << COM1B0);
// Fast PWM 8-bit
TCCR1A |= ( 1 << WGM10);
TCCR1B |= ( 1 << WGM12);
// No prescaling
TCCR1B |= ( 1 << CS10);
}
void pwm_set(Color col,uint8_t val){
switch(col){
case r:
if (val>3){
TCCR0A |= ( 1 << COM0A1);
OCR0A=val;
}
else{
TCCR0A &= ~( 1 << COM0A1);
OCR0A=0;
}
break;
case g:
if (val>3){
TCCR0A |= ( 1 << COM0B1);
OCR0B=val;
}
else{
TCCR0A &= ~( 1 << COM0B1);
OCR0B=0;
}
break;
case b:
if (val>3){
TCCR1A |= ( 1 << COM1A1);
OCR1AL=val;
}
else{
TCCR1A &= ~( 1 << COM1A1);
OCRA1L=0;
}
break;
}
}
void adc_init(void){
DDRA&=~(1 << POT);
DDRA&=~(1 << MSGEQ7);
//Set ADC reference to VCC (00)
ADMUX &= ~( 1 << REFS0 );
ADMUX &= ~( 1 << REFS1 );
//Prescaler 64 -> 125kHz
//Recommended for 10bit -> 50-200kHz
ADCSRA |= (1 << ADPS1) | ( 1 << ADPS2);
ADCSRA &=~(1<<ADPS0);
//Enable ADC
ADCSRA |= ( 1 << ADEN);
}
void adc_setChannel(uint8_t channel){
//Wait for conversion too finish
while(ADCSRA & ( 1 << ADSC ));
//ADCSRA &=~(1<<ADEN);
//ADMUX = ((ADMUX) & 0b00000111) | channel;
ADMUX = (channel & 0b00000111);
//ADCSRA |= (1<<ADEN);
}
uint8_t adc_getChannel(void){
return (ADMUX & 0b00000111);
}
uint16_t adc_read(void){
//Start conversion
ADCSRA |= ( 1 << ADSC );
while(ADCSRA & ( 1 << ADSC )); //wait for full buffer
uint16_t adc_value = 0;
adc_value = ADCL; // reads 8 bit value
adc_value |= (ADCH << 8); // reads 8 bit and combines to 16bit
//result adc_value is 10bit (0-1023)
return adc_value;
}
void button_init(void){
DDRA &= ~(1 << BUTTON);
PORTA|=(1 << BUTTON);
}
void sw_init(void){
DDRA &= ~(1 << SW);
PORTA |= (1<<SW);
}
uint8_t sw_status(void){
uint8_t val = (PINA & (1<<SW));
return val;
}
uint8_t button_pressed(void){
static uint8_t pushed=0;
if (!(PINA & (1 << BUTTON)) & (!pushed)) { //PIN is low and not already pushed
pushed =1;
return 1;
}
if ((PINA & ( 1 << BUTTON)) && (pushed)){ //is pushed and goes high
pushed=0;
}
return 0;
}
void led_init(void){
DDRB |= (1 << LED1)|(1 << LED2); //Output
PORTB &=~(1 <<LED1) | ( 1 << LED2); //Off by default
}
void led_set(uint8_t led, uint8_t val){ //led should be LED1 og LED2
if (val==0){
PORTB &=~(1 << led);
}
else {
PORTB |= (1 << led);
}
}
void led_blink(uint8_t led,uint8_t num){
if ((num==0)|(num==1)){
PORTB|=(1 << led);
_delay_ms(40);
PORTB&=~(1 << led);
_delay_ms(10);
}
else {
for (int i=0;i<num;i++){
PORTB|=(1 << led);
_delay_ms(40);
PORTB&=~(1 << led);
_delay_ms(250);
}
}
}
void led_setMode(uint8_t mode){
switch (mode){
case 0:
led_set(LED1,0);
led_set(LED2,0);
break;
case 1:
led_set(LED1,0);
led_set(LED2,1);
break;
case 2:
led_set(LED1,1);
led_set(LED2,0);
break;
case 3:
led_set(LED1,1);
led_set(LED2,1);
break;
}
}
uint8_t led_getMode(void){
uint8_t retH = (PORTB & (1<<LED1));
uint8_t retL= (PORTB & (1<<LED2));
uint8_t ret = retH | retL;
return ret;
}
void msgeq7_init(void){
//Strobe and reset as outputs
DDRA |= (1 << RESET) | (1 << STROBE);
//DDRA &=~(1<<MSGEQ7); in adcread
//Reset chip
PORTA |= (1 << RESET);
//_delay_us(100);
PORTA &= ~(1 << RESET);
PORTA &= ~(1 << STROBE);
}
uint16_t msgeq7_read(void){
if (adc_getChannel()!=MSGEQ7){
adc_setChannel(MSGEQ7);
}
return adc_read();
} | true |
578b5357ea6c406face6e1574250bc2fa14fb5e4 | C++ | Jack-lss/LeetCode_method | /001Sum_of_two_numbers/Sum_of_two_numbers.cpp | WINDOWS-1252 | 622 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target);
void main() {
vector<int> nums{2, 11, 15, 2};
int target = 9;
vector<int> numbers = twoSum(nums, target);
if (numbers[0] == nums.size() && numbers[1] == nums.size())
cout << "Ҳ" << endl;
else
cout << "±꣺" << numbers[0] << "," << numbers[1] << endl;
}
vector<int> twoSum(vector<int>& nums, int target)
{
int i, j;
for (i = 0;i < nums.size();i++)
for (j = i + 1;j < nums.size();j++)
if (nums[i] + nums[j] == target)
return vector<int>{i, j};
return vector<int>{i, j};
} | true |
4f075bfb7d96b711d86f06206fe651dbc12c385f | C++ | beastieGer/schildt | /chapter01/gl01_ex6_queue.cpp | UTF-8 | 1,122 | 3.765625 | 4 | [] | no_license | /*
класс циклической очереди целых
*/
#include<iostream>
using namespace std;
#define SIZE 100
class Queue
{
int head, tail; // индекс вершины и хвоста
int queue[SIZE];
public:
void init();
void save(int n);
int deq();
};
void Queue::init()
{
head = tail = 0;
}
void Queue::save(int n)
{
if(tail + 1 == head || (tail + 1 == SIZE && !head)){
cout << "Очередь полна" << endl;
return;
}
tail++;
if(tail == SIZE)
tail = 0;
queue[tail] = n;
}
int Queue::deq()
{
if(head == tail){
cout << "Очередь пуста" << endl;
return 0;
}
head++;
if(head == SIZE)
head = 0;
return queue[head];
}
int main()
{
Queue q1, q2;
int i;
q1.init();
q2.init();
for(i=0; i<=10; i++){
q1.save(i);
q2.save(i*i);
}
for(i=0; i<=10; i++){
cout << "Элемент из очереди 1: " << q1.deq() << endl;
cout << "Элемент из очереди 2: " << q2.deq() << endl;
}
return 0;
}
| true |
88b96763db942053bc1c85d19248a8b7ffc836b3 | C++ | FaryalAjradh/Code-Practice | /Being-Zero/Bit-Manip/split-2.cpp | UTF-8 | 612 | 3.40625 | 3 | [] | no_license | // Given a number N, Split it to be represented as sum of powers of 2. N = 2i 2j 2k .... 1
#include<bits/stdc++.h>
using namespace std;
void printPowersOf2(long long int n) {
while(n != 0) {
// pos of leftmost set bit = log2n => log2n-1 is used for
int k = (int)log2(n);
cout << (1LL << k) << " ";
n = n & (~(1LL << k));
}
cout << endl;
return;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--) {
long long int n;
cin >> n;
printPowersOf2(n);
}
return 0;
} | true |
c6b44ff42790c95ddf68c228e01810dad4121ef6 | C++ | gbakkk5951/OI | /Test_18.4.17/source2/长乐-邱而沐/magic.cpp | UTF-8 | 1,813 | 2.734375 | 3 | [] | no_license | #include<ctime>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 400010
using namespace std;
typedef long long LL;
int n, p;
int jc[N], ie[N];
int f[100][100];
int a[N], b[N];
inline void Plus(int &x, int y)
{
x += y;
x = x >= p ? x - p : x;
}
inline int Ksm(int x, int y)
{
int ans = 1;
for(; y; x = (LL)x * x % p, y >>= 1)
if(y & 1) ans = (LL)ans * x % p;
return ans;
}
inline int C1(int n, int m)
{
return (LL)jc[n] * (LL)ie[m] % p * (LL)ie[n-m] % p;
}
inline int calc(int n, int m)
{
if(n < m) return 0;
else return f[n][m];
}
inline int C2(int n, int m) //Lucas
{
if(!n && !m) return 1;
return (LL)C2(n / p, m / p) * calc(n % p, m % p) % p;
}
int main()
{
freopen("magic.in", "r", stdin);
freopen("magic.out", "w", stdout);
for(int i=0; i<=10; ++i)
{
f[i][0] = 1;
for(int j=1; j<=i; ++j)
f[i][j] = f[i - 1][j] + f[i - 1][j - 1];
}
scanf("%d%d", &n, &p);
for(int i=1; i<=n; ++i) scanf("%d", &a[i]);
/*
for(;;)
{
int x, y;
scanf("%d%d", &x, &y);
cout << C2(x, y) << "\n";
}
*/
if(n <= 1000)
{
for(int i=1; i<n; ++i)
{
for(int j=1; j<n; ++j)
b[j] = (a[j] + a[j + 1]) % p;
for(int j=1; j<=n; ++j)
a[j] = b[j];
}
cout << a[1];
}
else if(p > 10)
{
jc[0] = 1;
for(int i=1; i<=n; ++i) jc[i] = (LL)jc[i - 1] * i % p;
// ie[n] = Ksm(jc[n], p - 2);
int flag = 0;
for(int i=n; i>=0; --i) //如果没有保证模数p > n,就要这么写
{
if(!flag)
{
if(jc[i]) ie[i] = Ksm(jc[i], p - 2);
flag = 1;
}
else ie[i] = (LL)ie[i + 1] * (i + 1) % p;
}
int ans = 0;
for(int i=1; i<=n; ++i)
Plus(ans, (LL)a[i] * C1(n - 1, i - 1) % p);
cout << ans;
}
else
{
int ans = 0;
for(int i=1; i<=n; ++i)
Plus(ans, (LL)a[i] * C2(n - 1, i - 1) % p);
cout << ans;
}
} | true |
4a6791c40a8a3d65ffabaa7c0fb2167256055830 | C++ | CheungKitLeong/Programming_practice | /C/Multimedia/Ascii_Art/ascii.cpp | UTF-8 | 3,237 | 2.828125 | 3 | [] | no_license | /*
CSCI 3280, Introduction to Multimedia Systems
Spring 2021
Assignment 01 Skeleton
ascii.cpp
*/
#include "stdio.h"
#include "malloc.h"
#include "memory.h"
#include "math.h"
#include "bmp.h" // Simple .bmp library
#include <string.h>
#include <stdlib.h>
#define MAX_SHADES 8
char shades[MAX_SHADES] = {'@','#','%','*','|','-','.',' '};
#define SAFE_FREE(p) { if(p){ free(p); (p)=NULL;} }
int main(int argc, char** argv)
{
//
// 1. Open BMP file
//
Bitmap image_data(argv[2]);
if(image_data.getData() == NULL)
{
printf("unable to load bmp image!\n");
return -1;
}
if (argv[1][0] != 'p' && argv[1][0]!= 's'){
printf("Task undefined!\n");
return -1;
}
int w = image_data.getWidth();
int h = image_data.getHeight();
unsigned char** luma = (unsigned char **)malloc(h * sizeof(unsigned char*));
unsigned char r;
unsigned char g;
unsigned char b;
for(int i=0; i<h; i++){
luma[i] = (unsigned char *)malloc(w * sizeof(unsigned char));
for (int j=0; j<w; j++){
image_data.getColor(j, i, r,g,b);
luma[i][j] = 0.299*r+0.587*g+0.114*b;
}
}
//
// 3. Resize image
//
if (argc > 3)
{
int lw = atoi(strtok(argv[3],","));
int lh = atoi(strtok(NULL, " "));
if(lh == 0){
lh = (int)(lw * ((float)h/(float)w));
}
if(lw<=w && lh<=h && lw > 0 && lh > -1){
float winc = (float)w/(float)lw;
float hinc = (float)h/(float)lh;
unsigned char** reluma = (unsigned char **)malloc(lh* sizeof(unsigned char*));
float sw;
float sh = 0;
int sum;
int bcount;
for(int i=0; i<lh; i++){
reluma[i] = (unsigned char *)malloc(lw* sizeof(unsigned char));
sw = 0;
for(int j = 0; j<lw; j++){
bcount = 0;
sum = 0;
for (int ii = (int)(sh+0.5); ii < (int)(sh+hinc+0.5); ii++){
for (int jj = (int)(sw+0.5); jj < (int)(sw+winc+0.5); jj++){
sum += luma[ii][jj];
bcount++;
}
}
reluma[i][j] = (unsigned char)(((float)sum / (float)bcount) +0.5);
sw += winc;
}
sh += hinc;
}
w = lw;
h = lh;
luma = (unsigned char **)malloc(h * sizeof(unsigned char*));
for(int i=0; i<h; i++){
luma[i] = (unsigned char *)malloc(w * sizeof(unsigned char));
for (int j=0; j<w; j++){
luma[i][j] = reluma[i][j];
}
}
for(int i=0; i<h; i++){
free(reluma[i]);
}
free (reluma);
}
}
//
// 4. Quantization
//
//
// 5. ASCII Mapping and printout
//
for (int i = 0; i < h; i++){
for(int j=0; j<w; j++){
luma[i][j] = (unsigned char)(luma[i][j] / 32);
}
}
if(argv[1][0] == 's'){
for(int i=0; i<h; i++){
for (int j=0; j<w; j++){
luma[i][j] = shades[7-luma[i][j]];
printf("%c ",luma[i][j]);
}
printf("\n");
}
}
//
// 6. ASCII art txt file
//
if (argv[1][0] == 'p')
{
if (argc < 5){
printf("Cannot find the output file!\n");
return -1;
}
FILE* fptr = fopen(argv[4],"w");
if (fptr == NULL){
printf("Unable to create file.\n");
return -1;
}
for(int i=0; i<h; i++){
for (int j=0; j<w; j++){
luma[i][j] = shades[luma[i][j]];
fprintf(fptr, "%c ", luma[i][j]);
}
fprintf(fptr,"\n");
}
fclose(fptr);
}
// free memory
for(int i=0; i<h; i++){
free(luma[i]);
}
free (luma);
return 0;
}
| true |
268c6500e348146c2ca4df4692b8a4fc1f2a1646 | C++ | blumchik/libIOStream | /src/EncryptedOutputStream.cpp | UTF-8 | 902 | 2.59375 | 3 | [] | no_license |
#include <sstream>
#include <bitset>
#include <unistd.h>
#include <openssl/evp.h>
#include <Util/ErrorHandler.hpp>
#include "EncryptedOutputStream.hpp"
namespace IOStream {
EncryptedOutputStream::EncryptedOutputStream(int socketfd, EVP_CIPHER_CTX *encryptor)
:socketfd(socketfd), encryptor(encryptor) {
}
ssize_t EncryptedOutputStream::write(const void *buf, size_t length) {
int outLength = length + encryptor->cipher->block_size - 1;
uint8_t *output = new uint8_t[outLength];
EVP_EncryptUpdate(encryptor, output, &outLength, static_cast<const uint8_t *>(buf), length);
ssize_t written = ::write(socketfd, output, outLength);
if (written < 0) {
throwException(errno);
}
delete[] output;
return written;
}
off_t EncryptedOutputStream::seek(off_t length, int whence) {
return 0;
}
void EncryptedOutputStream::close() {
::close(socketfd);
}
}
| true |
83df8cbacafd12eac2f7882550ee0eea38ea3538 | C++ | chin0/everydayalgo | /baekjoon/math/2745.cpp | UTF-8 | 529 | 2.734375 | 3 | [] | no_license | #include <locale>
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
unsigned long long int result = 0;
int b;
string s;
ios::sync_with_stdio(false);
cin >> s;
cin >> b;
unsigned long long int r = 1;
for(int i = s.size() - 1; i >= 0; i--) {
if('0' <= s[i] && s[i] <= '9') {
result += r * (s[i] - '0');
} else if (isupper(s[i])) {
result += r * (s[i] - 'A' + 10);
}
r *= b;
}
cout << result << endl;
} | true |
f54e4bc7a7e798e3f2850bd8f852c34e199c0675 | C++ | Yakumorin/Leetcode | /297. Serialize and Deserialize Binary Tree.cpp | UTF-8 | 1,369 | 3.453125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
void go_serialize(TreeNode* root, string &res) {
if(!root) {
res += "null,";
return;
}
res += to_string(root->val) + ',';
go_serialize(root->left, res);
go_serialize(root->right, res);
}
string serialize(TreeNode* root) {
if(!root) return "";
string res;
go_serialize(root, res);
return res;
}
// Decodes your encoded data to tree.
TreeNode* go_deserialize(string &data, int &k) {
int t = data.find(",", k);
string val = data.substr(k, t-k);
k = t+1;
if(val == "null") return NULL;
TreeNode* now = new TreeNode(stoi(val));
now->left = go_deserialize(data, k);
now->right = go_deserialize(data, k);
return now;
}
TreeNode* deserialize(string data) {
if(data.empty()) return NULL;
int k = 0;
TreeNode* root = go_deserialize(data, k);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
| true |
5aed3c75460e4cfc7a116a080fc10c709ff84bd5 | C++ | BackupTheBerlios/bmws-svn | /c++/nio/util/socket.h | ISO-8859-1 | 4,872 | 2.6875 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////
// socketclass.h
//
// (C)2000 by Axel Sammet
//
// Klasse fr einfache Socketverbindungen
//
// unter Win mit ws2_32.lib zu linken
//
////////////////////////////////////////////////////////////////////////
#ifndef SOCKETCL_H
#define SOCKETCL_H
#include "string.h"
#include "excclass.h"
//#include "bytearrayclass.h"
#ifdef UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <netdb.h>
#endif
#ifdef WIN32
#include <winsock2.h>
#endif
namespace util {
////////////////////////////////////////////////////////////////////////
class SocketException : public Exception
{
public:
SocketException(String met, String mes) {
method = met;
message = mes;
}
};
class SocketTimeoutException : public SocketException
{
public:
SocketTimeoutException(String met, String mes) :
SocketException(met,mes)
{
}
};
class SocketBrokenException : public SocketException
{
public:
SocketBrokenException(String met, String mes) :
SocketException(met,mes)
{
}
};
/////////////////////////////////////////////////////////////////////////
class Socket
{
protected: // Membervariablen
int m_Socket;
sockaddr_in m_Sockaddr;
static int s_NrOfInstances;
static int s_Initialized;
public: // Methoden
// Konstruktor / Destruktor
Socket();
virtual ~Socket();
static void Init();
static void Cleanup();
// initialize and cleanup winsocks
// only required for WIN32, calling doesn't harm though
void Connect(char* address, int port);
// connect to a listening server socket
// address : hostname or ip
// port : port number
void WriteString(String s);
// sends a String to the other side of the socket connection
// the String can contain \0. Thus the length is send first.
// Do not use to send ASCII, use Write(char*) instead.
// s : string to send
String ReadString(long timeout=-1);
// reads a String from the socket connection
// timeout : in msecs, -1 indefinetly
// returns : String read from socket
// throws : SocketException, SocketTimeoutException
String ReadLine(long timeout=-1);
// reads characters from the socket up to the next \n
// timeout : in msecs, -1 indefinetly
// returns : String read from socket
// throws : SocketException, SocketTimeoutException
void WriteLong(long nr);
long ReadLong(long timeout=-1);
/*
void Write(const ByteArray &ba);
// not yet implemented
ByteArray Read(long timeout=-1);
// not yet implemented
*/
void Write(char* pt,int len=-1);
// writes a character array with the given length.
// If no length is given, a String is assumed and strlen(pt)
// bytes will be send.
// pt : first character
// len : length of array
int Read(char* pt,int len, long timeout=-1);
// reads a charater array of a given length
// pt : first character of the array
// len : length of array
// timeout : in msec
int DataTransferred();
// checks if written data has been transmitted
int WaitForData(long wait=-1);
// checks if there is data available on the connection
// wait : time to wait in msec, if -1 wait indefinetly
// return : true if data available else false
int ConnectionBroken();
// returns true if the other side has disconnected.
// WORKS ONLY IF no more data in the queue is available.
// If data exists in the queue or connection is online
// returns false. Unfortunately breaking the connection looks
// like new data. Best method to check for broken connection is:
// try { WaitForData(100); Read??? } catch(SocketBrokenException exc)
String GetAddressString();
// returns ip-address of connected socket
// seems to have a bug sometimes
int GetSocket();
// returns socket handle
void SetSocket(int soc);
// sets a previous created socket
void SetSockAddr(sockaddr_in sa);
// sets an inet socket address
void Close();
// closes the socket (will also be called by destructor)
};
//////////////////////////////////////////////////////////////////////////
// class ServerSocket
class ServerSocket : public Socket
{
public:
ServerSocket(int port);
// creates a server socket which can accept connections on
// the given port
// port : number of the port
virtual ~ServerSocket();
// destructor
int Accept(Socket& soc, long wait=-1);
// waits for a client to connect
// soc : holds the socket for the accepted connection
// after Accept() returns
// wait : time the server waits for a client connection in msec
// returns : true if a new connection was accepted, false otherwise
};
}
#endif
| true |
5665ea07a680ee3ab55d83e1edb48c223c8505a4 | C++ | josephyan0816/pintiaC | /实验8-2-8 字符串排序.cpp | GB18030 | 658 | 3.28125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#define n 5
#define maxlen 81
void stringsort(char s[][maxlen],int N);
int main()
{
int i;
char s[n][maxlen];
for(i=0;i<n;i++)
scanf("%s",&s[i]); //scanfַոgetsس
stringsort(s,n);
printf("After sorted:\n");
for(i=0;i<n;i++)
printf("%s\n",s[i]);
}
void stringsort(char s[][maxlen],int N)
{
char temp[maxlen];
int i,j;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(strcmp(s[j],s[j+1])>0)
{
strcpy(temp,s[j]); //strcpyܸǰһ
strcpy(s[j],s[j+1]);
strcpy(s[j+1],temp);
}
}
}
}
| true |
6f0d97dce78c6aa0a0a73185c6003ac539fadc63 | C++ | jer22/templates | /RMQ.cpp | UTF-8 | 1,055 | 2.796875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define MAXN 1000
using namespace std;
int n;
int arr[MAXN];
int maxsum[MAXN][11];
int minsum[MAXN][11];
void RMQ() {
for (int j = 1; j <= 10; j++) {
for (int i = 1; i <= n; i++) {
if (i + (1 << j) - 1 <= n) {
maxsum[i][j] = max(maxsum[i][j - 1], maxsum[i + (1 << (j - 1))][j - 1]);
minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);
}
}
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
maxsum[i][0] = arr[i];
minsum[i][0] = arr[i];
}
RMQ();
// for (int i = 1; i <= n; i++) {
// for (int j = 0; i + (1 << j) - 1 <= n; j++) {
// printf("%d ", maxsum[i][j]);
// }
// printf("\n");
// }
int a, b;
scanf("%d %d", &a, &b);
int k = log(b - a + 1) / log(2);
int minAns = min(minsum[a][k], minsum[b - (1 << k) + 1][k]);
int maxAns = max(maxsum[a][k], maxsum[b - (1 << k) + 1][k]);
printf("%d %d\n", minAns, maxAns);
return 0;
}
| true |
71a5ba51a223fc00816b5a84eb9acb25c5e535fb | C++ | wayne-chen/RTNeural | /RTNeural/dense/dense.h | UTF-8 | 2,692 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef DENSE_H_INCLUDED
#define DENSE_H_INCLUDED
#include <algorithm>
#include <numeric>
#include <vector>
#if defined(USE_EIGEN)
#include "dense_eigen.h"
#elif defined(USE_XSIMD)
#include "dense_xsimd.h"
#elif defined(USE_ACCELERATE)
#include "dense_accelerate.h"
#else
#include "../Layer.h"
namespace RTNeural
{
template <typename T>
class Dense1
{
public:
Dense1(size_t in_size)
: in_size(in_size)
{
weights = new T[in_size];
}
~Dense1() { delete[] weights; }
inline T forward(const T* input)
{
return std::inner_product(weights, weights + in_size, input, (T)0) + bias;
}
void setWeights(const T* newWeights)
{
for(size_t i = 0; i < in_size; ++i)
weights[i] = newWeights[i];
}
void setBias(T b) { bias = b; }
T getWeight(size_t i) const noexcept { return weights[i]; }
T getBias() const noexcept { return bias; }
private:
const size_t in_size;
T bias;
T* weights;
};
template <typename T>
class Dense : public Layer<T>
{
public:
Dense(size_t in_size, size_t out_size)
: Layer<T>(in_size, out_size)
{
subLayers = new Dense1<T>*[out_size];
for(size_t i = 0; i < out_size; ++i)
subLayers[i] = new Dense1<T>(in_size);
}
Dense(std::initializer_list<size_t> sizes)
: Dense(*sizes.begin(), *(sizes.begin() + 1))
{
}
Dense(const Dense& other)
: Dense(other.in_size, other.out_size)
{
}
Dense& operator=(const Dense& other)
{
return *this = Dense(other);
}
virtual ~Dense()
{
for(size_t i = 0; i < Layer<T>::out_size; ++i)
delete subLayers[i];
delete[] subLayers;
}
inline void forward(const T* input, T* out) override
{
for(size_t i = 0; i < Layer<T>::out_size; ++i)
out[i] = subLayers[i]->forward(input);
}
void setWeights(const std::vector<std::vector<T>>& newWeights)
{
for(size_t i = 0; i < Layer<T>::out_size; ++i)
subLayers[i]->setWeights(newWeights[i].data());
}
void setWeights(T** newWeights)
{
for(size_t i = 0; i < Layer<T>::out_size; ++i)
subLayers[i]->setWeights(newWeights[i]);
}
void setBias(T* b)
{
for(size_t i = 0; i < Layer<T>::out_size; ++i)
subLayers[i]->setBias(b[i]);
}
T getWeight(size_t i, size_t k) const noexcept
{
return subLayers[i]->getWeight(k);
}
T getBias(size_t i) const noexcept { return subLayers[i]->getBias(); }
private:
Dense1<T>** subLayers;
};
} // namespace RTNeural
#endif // USE_EIGEN
#endif // DENSE_H_INCLUDED
| true |
586ab9e2072aea5da51152c40fb7439f1ed66f76 | C++ | wtrnash/LeetCode | /cpp/019删除链表的倒数第N个节点/019删除链表的倒数第N个节点.cpp | UTF-8 | 1,230 | 3.828125 | 4 | [] | no_license | /*
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
*/
//解答 先遍历一遍求出节点数,然后用倒数的和节点数计算出正数第几个,并做删除操作
# include<iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int count = 0;
ListNode* p = head, *q;
while(p != NULL)
{
p = p->next;
count++;
}
p = head;
for(int i = 0; i < count - n; i++)
{
q = p;
p = p->next;
}
if(p == head) //删除要删除节点为头结点的情况
{
head = head->next;
delete p;
}
else
{
q->next = p->next;
delete p;
}
return head;
}
}; | true |
836bc0795c2332824e49a649c1832a046fe50009 | C++ | phrz/HPSCProject1 | /src/proj1_a.cpp | UTF-8 | 2,753 | 2.84375 | 3 | [] | no_license | //
// proj1_a.cpp
// HPSCProject1
//
// Created by Paul Herz on 8/31/16.
// Copyright © 2016 Paul Herz. All rights reserved.
//
#include <iostream>
#include "Matrix.h"
#include "Vector.h"
#include "nest.cpp"
using namespace PH;
// generate n+1 coefficients
// for Taylor polynomial for e^x.
// 1/0!, 1/1!, 1/2!, etc. as a row matrix.
// N.B. 4th degree T.P. has 5 coefficients 0th...4th
Matrix eulerExponentialTaylorCoefficients(Index n) {
Matrix coefficients = Matrix(1, n+1);
// factorial accumulator, starts as 1!
int fact = 1;
// for the number of coefficients required,
// calculate 1/i! and set it in the row matrix.
for(Index i = 0; i < n+1; ++i) {
if(i != 0) {
fact *= i;
}
coefficients(i) = 1.0 / fact;
}
return coefficients;
}
int main(int argc, const char * argv[]) {
// use linSpace and nest to compute the following:
// create the row vector
// z = −1, −0.99, ... , 0.99, 1.0
auto z = Matrix::linSpace(-1, 1, 1, 201);
// Compute the vector p4 as the value of the
// Taylor polynomial p4(x) for all points x ∈ z.
// (ibid. for p8, p12)
// calculate 13 coefficients degrees 0...12 for p12 and truncate for the
// p8 and p4 calculation.
Matrix c12 = eulerExponentialTaylorCoefficients(12);
Matrix c8 = c12.range(0, 0, 0, 8);
Matrix c4 = c12.range(0, 0, 0, 4);
// create the result vectors, each of which will hold
// p?(x) for all x in z.
Vector p4(z.size()),
p8(z.size()),
p12(z.size());
// for each x value in the linspace,
// calculate p?(x), where ? iterates 4, 8, 12.
for(Index i = 0; i < z.size(); ++i) {
double x = z(i);
p4[i] = nest(c4, x);
p8[i] = nest(c8, x);
p12[i] = nest(c12, x);
}
// compute vector f by evaluating e^x at all x in z.
Vector f = z.copyRow(0);
f = M_E ^ f;
// compute the vector err4 as |e^x − p4(x)| for each x ∈ z.
Vector err4 = f - p4;
err4.mapElements([&](double& x, Index i) { x = std::abs(x); });
// compute the vector err8 as |e^x − p8(x)| for each x ∈ z.
Vector err8 = f - p8;
err8.mapElements([&](double& x, Index i) { x = std::abs(x); });
// compute the vector err12 as |e^x − p12(x)| for each x ∈ z.
Vector err12 = f - p12;
err12.mapElements([&](double& x, Index i) { x = std::abs(x); });
// Save the vectors z, p4, p8, p12, f, err4, err8 and err12
// to unique text files named z.txt, p4.txt, p8.txt, p12.txt,
// f.txt, err4.txt, err8.txt and err12.txt, respectively.
std::string prefix = "../data/a/";
z.saveTo(prefix + "z.txt");
p4.saveTo(prefix + "p4.txt");
p8.saveTo(prefix + "p8.txt");
p12.saveTo(prefix + "p12.txt");
f.saveTo(prefix + "f.txt");
err4.saveTo(prefix + "err4.txt");
err8.saveTo(prefix + "err8.txt");
err12.saveTo(prefix + "err12.txt");
return 0;
}
| true |
4e62d0f52fa0a580ae34cb4bf3a11728c0065690 | C++ | susantabiswas/interviewbit-solutions | /Binary search/rotated_sorted_array_search.cpp | UTF-8 | 2,134 | 4.28125 | 4 | [] | no_license | /*
Binary search in rotated sorted array
https://www.interviewbit.com/problems/rotated-sorted-array-search/
*/
// Solution 1
int Solution::search(const vector<int> &arr, int target) {
int left = 0, right = arr.size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(arr[mid] == target)
return mid;
// check if mid is in bigger subarray
if(arr[mid] >= arr[left]) {
// check if target lies in left or right
if(target >= arr[left] && target < arr[mid])
right = mid - 1;
else
left = mid + 1;
}
// mid is in smaller subarray
else {
// check if target lies in left or right
if(target <= arr[right] && target > arr[mid])
left = mid + 1;
else
right = mid - 1;
}
}
return -1;
}
// solution 2
int binSearch(const vector<int>& arr, int l, int h, int k) {
while(l <= h) {
int mid = l + (h - l) / 2;
if(arr[mid] == k)
return mid;
else if(arr[mid] < k)
l = mid + 1;
else
h = mid - 1;
}
return -1;
}
int rotatedSearch(const vector<int>& arr, int& k) {
int l = 0, h = arr.size() - 1;
while(l <= h) {
int mid = l + (h - l) / 2;
// if target is found
if(arr[mid] == k)
return mid;
// check if middle is pivot
else if(mid - 1 >= 0 && arr[mid - 1] > arr[mid]) {
// once the pivot is found we check, on which side
// of pivot can the target lie
if(arr[arr.size() - 1] >= k) {
return binSearch(arr, mid + 1, arr.size()-1 , k);
}
else if(arr[0] <= k) {
return binSearch(arr, 0, mid - 1, k);
}
}
else if(arr[h] < arr[mid])
l = mid + 1;
else
h = mid - 1;
}
return -1;
}
int Solution::search(const vector<int> &arr, int k) {
return rotatedSearch(arr, k);
}
| true |
866fec394d57bb1664550e6b70d8351e82bf707f | C++ | sasasao/of_imac | /pet02/src/MyMesh.cpp | UTF-8 | 740 | 2.703125 | 3 | [] | no_license | #include "MyMesh.hpp"
MyMesh::MyMesh(){
myMesh = ofSpherePrimitive(200,72).getMesh();
for (int i=0; i<myMesh.getVertices().size(); i++) {
myMesh.addColor(ofFloatColor(1.0,1.0,1.0,1.0));
}
}
void MyMesh::update(){
for(int i=0; i<myMesh.getVertices().size(); i++){
ofVec3f loc = myMesh.getVertices()[i] / 300.0;
float noise = ofMap(ofNoise(loc.x, loc.y, loc.z,ofGetElapsedTimef()), 0, 1, 80, 240);
ofVec3f newLoc = loc.normalize()*noise;
myMesh.setVertex(i, newLoc);
float c = ofMap(ofNoise(loc.x, loc.y, loc.z, ofGetElapsedTimef()), 0, 1, 0.5, 1.0);
myMesh.setColor(i, ofFloatColor(c,c,c,1.0));
}
}
void MyMesh::draw(){
myMesh.draw();
}
| true |
05f510756b3d2f813a408d7cd75456f32f3156bd | C++ | LauraDiosan-CS/lab8-11-polimorfism-pikachu2432 | /Marfa.h | UTF-8 | 2,525 | 3.265625 | 3 | [] | no_license | #pragma once
#include "Garnitura.h"
class Marfa : public Garnitura
{
private:
string continut;
public:
Marfa();
Marfa(string m, string p, int n, string c, int d, int r);
Marfa(const Marfa& m);
~Marfa();
Garnitura* clone();
void set_continut(string c);
string get_continut();
Marfa& operator=(const Marfa& p);
bool operator==(const Marfa& rhs) const;
string toString();
string toStringDelimiter(char delim);
//friend istream& operator>>(istream &is, Garnitura &v);
friend ostream& operator<<(ostream &os, Marfa &v);
};
Marfa::Marfa() :Garnitura() {}
Marfa::~Marfa() {}
Marfa::Marfa(string m, string p, int n, string c, int d, int r):Garnitura(m, p, n, d, r)
{
this->continut = c;
}
Marfa::Marfa(const Marfa& m) : Garnitura(m)
{
this->continut = m.continut;
}
Garnitura* Marfa::clone()
{
Marfa* nou = new Marfa();
nou->set_model(model);
nou->set_prod(prod);
nou->set_nr_vag(nr_vag);
nou->set_continut(this->continut);
nou->set_disp(disp);
nou->set_rez(rez);
return nou;
}
void Marfa::set_continut(string c)
{
this->continut = c;
}
string Marfa::get_continut()
{
return continut;
}
Marfa& Marfa::operator=(const Marfa& m)
{
Garnitura::operator=(m);
this->set_continut(m.continut);
return *this;
}
bool Marfa::operator==(const Marfa& rhs) const
{
return (model == rhs.model) && (prod == rhs.prod) && (nr_vag == rhs.nr_vag) && (continut == rhs.continut) && (disp == rhs.disp) && (rez == rhs.rez);
}
string Marfa::toString()
{
return model + ' ' + prod + ' ' + to_string(nr_vag) + ' ' + continut + ' ' + to_string(disp) + ' ' + to_string(rez);
}
string Marfa::toStringDelimiter(char delim)
{
return model + delim + prod + delim + to_string(nr_vag) + delim + continut + delim + to_string(disp) + delim + to_string(rez);
}
/*
istream& operator>>(istream &is, Marfa &m)
{
string model,prod, c;
int nr_vag, disp, rez;
cout << "Modelul: ";
is >> model;
cout << "Producatorul: ";
is >> prod;
cout << "Nr. de vagoane:";
is >> nr_vag;
cout << "Continut:";
is >> c;
cout << "Garnituri disponibile:";
is << disp;
cout << "Garnituri rezervate:";
is << rez;
m.set_model(model);
m.set_prod(prod);
m.set_nr_vag(nr_vag);
m.set_continut(c);
m.set_disp(disp);
m.set_rez(rez);
return is;
}
*/
ostream& operator<<(ostream &os, Marfa &m)
{
os << m.model << " " << m.prod << " " << m.nr_vag << " " << m.continut<<" " << m.disp << " " << m.rez << endl;
return os;
} | true |
ab67e20f1d5869a15852ace7510a8ac95e03f475 | C++ | eusgeka/XperimentalHashAlgorithm | /unordermap.hpp | UTF-8 | 2,191 | 3.4375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef UNORDERMAP_HPP
#define UNORDERMAP_HPP
#include <string>
#include <unordered_map>
#define A_PRIME 54059
#define B_PRIME 76963 /* another prime */
#define C_PRIME 86969 /* yet another prime */
using namespace std;
namespace std {
class Key {
private:
std::string m_strFirst;
std::string m_strSecond;
int m_intThird;
public:
bool operator==(const Key &k) const {
return (m_strFirst == k.m_strFirst
&& m_strSecond == k.m_strSecond
&& m_intThird == k.m_intThird);
}
void prepareKey(std::string kone, std::string ktwo, int kthree) {
m_strFirst.clear();
m_strFirst.append(kone.c_str());
m_strSecond.clear();
m_strSecond.append(ktwo.c_str());
m_intThird = kthree;
}
std::string getFirst() const {return m_strFirst;}
std::string getSecond() const {return m_strSecond;}
int getThird() const {return m_intThird;}
};
template <>
class hash<Key> {
public:
std::size_t operator()(const Key& k) const {
//using std::size_t;
//using std::hash;
//using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<std::string>()(k.getFirst())
^ (hash<std::string>()(k.getSecond()) << 1)) >> 1)
^ (hash<int>()(k.getThird()) << 1);
}
};
}
/**
* @brief The CUnOrderMap class
*/
class UnOrderMap {
private:
//std::unordered_map<Key, std::pair<std::string, std::string>> m_hMap;
int m_third;
public:
UnOrderMap();
~UnOrderMap();
std::unordered_map<Key, std::pair<std::string, std::string>> m_hMap;
void add(std::string strValueFname, std::string strValueLName);
unsigned int hash_str(const char* s) {
unsigned h = 31 /* also prime */;
while (*s) {
h = (h * A_PRIME) ^ (static_cast<unsigned int>(s[0]) * B_PRIME);
s++;
}
return h % C_PRIME;
}
};
#endif // UNORDERMAP_HPP
| true |
9ef5cf8d56086325e7eead262208d2fc8128d22f | C++ | bluarry/daily_problem | /算法学习/模拟/square.cpp | UTF-8 | 1,423 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int n,m;
int linkr[15][15],linkc[15][15];
int has(int s,int n)
{
int sum=0;
for(int i=1;i<=n-s+1;i++)
for(int j=1;j<=n-s+1;j++)
{
int k,ok=1;
for(k=i;k<i+s;k++) if(!linkc[j][k]||!linkc[j+s][k]) {ok=0;break;}
//枚举行
for(k=j;k<j+s;k++) if(!linkr[i][k] || !linkr[i+s][k]){ok=0;break;}
//枚举列
if(ok) sum++;
}
return sum;
}
int main()
{
int times=1,x,y;
char cmd;
while(cin >> n)
{
memset(linkr,0,sizeof(linkr));
memset(linkc,0,sizeof(linkc));
if(times-1) cout <<"\n**********************************\n\n";
cout << "Problem #"<< times++ <<"\n\n";
cin >> m;
while (m--) {
cin >> cmd >> x >> y;
if(cmd == 'H')linkr[x][y]=1;
else if(cmd == 'V') linkc[x][y]=1;
}
int s=1; //当前的枚举边长
int ok=0;
while(s<n)
{
if(has(s,n-1)) //枚举边长为s时可以构成的正方形个数,病返回
{
ok=1;
cout << has(s,n-1)<<" square (s) of size "<< s;
cout << "\n";
}
s++;
}
if(!ok) cout << "No completed squares can be found." <<endl;
}
return 0;
}
| true |
bcd1be39a7240e956df81924b1d605c9f9443632 | C++ | DancingOnAir/LeetCode | /Leetcode/HashTable/500_KeyboardRow.cpp | UTF-8 | 2,179 | 3.046875 | 3 | [] | no_license | //#include <iostream>
//#include <vector>
//#include <unordered_map>
//#include <unordered_set>
//#include <string>
//
//using namespace std;
//
//vector<string> findWords2(vector<string>& words)
//{
// if (words.empty())
// return vector<string>();
//
// unordered_map<int, unordered_set<char>> count{ {1, {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'}},
// {2, {'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L' }},
// {3, {'Z', 'X', 'C', 'V', 'B', 'N', 'M'}} };
// vector<string> res;
// int flag = 0;
// for (auto& word : words)
// {
// for (auto& iter : count)
// {
// if (iter.second.count(toupper(word[0])))
// flag = iter.first;
// }
//
// int i = 1;
// for (; i < word.size(); ++i)
// {
// char tmp = toupper(word[i]);
// if (!count[flag].count(tmp))
// break;
// }
//
// if (i == word.size())
// res.emplace_back(word);
// flag = 0;
// }
//
// return res;
//}
//
//vector<string> findWords(vector<string>& words)
//{
// if (words.empty())
// return vector<string>();
//
// vector<int> dict(26);
// vector<string> rows = { "QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM" };
// for (int i = 0; i < rows.size(); ++i)
// {
// for (char c : rows[i])
// dict[toupper(c) - 'A'] = 1 << i;
// }
//
// vector<string> res;
// for (auto& w : words)
// {
// int r = 7;
// for (char c : w)
// {
// r &= dict[toupper(c) - 'A'];
// if (!r)
// break;
// }
//
// if (r)
// res.emplace_back(w);
// }
//
// return res;
//}
//
//void display(const vector<string>& words)
//{
// for (auto& word : words)
// cout << word << ", ";
// cout << endl;
//}
//
//void testFindWords()
//{
// vector<string> words{ "Hello", "Alaska", "Dad", "Peace" };
// auto res = findWords(words);
// display(res);
//}
//
//int main()
//{
// testFindWords();
//
// getchar();
// return 0;
//} | true |
45a040d5852e6ef35ab28534c1d1eab3638f954d | C++ | pthiben/Helium | /Application/Inspect/Controls/Slider.cpp | UTF-8 | 7,252 | 2.546875 | 3 | [] | no_license | #include "Slider.h"
#include "Application/Inspect/Controls/Canvas.h"
using namespace Helium::Inspect;
///////////////////////////////////////////////////////////////////////////////
// Custom wrapper around wxSlider to interact with Slider.
//
class StdSlider : public wxSlider
{
public:
Slider* m_Slider;
bool m_Override;
// Constructor
StdSlider( wxWindow* parent, Slider* slider )
: wxSlider( parent, wxID_ANY, 0, 0, 1000 )
, m_Slider( slider )
{
}
// Callback every time a value changes on the slider.
void OnScroll( wxScrollEvent& e)
{
// NOTE: This skip is important. If you remove it,
// the EVT_SCROLL_CHANGED event will never get fired.
e.Skip();
if ( !m_Override )
{
m_Slider->Write();
}
}
// Callback when a mouse click occurs on the slider.
void OnMouseDown( wxMouseEvent& e )
{
e.Skip();
m_Slider->Start();
}
// Callback when a scroll operation has completed (such as
// when the user stops dragging the thumb).
void OnScrollChanged( wxScrollEvent& e )
{
e.Skip();
m_Slider->End();
}
DECLARE_EVENT_TABLE();
};
BEGIN_EVENT_TABLE( StdSlider, wxSlider )
EVT_SCROLL( StdSlider::OnScroll )
EVT_LEFT_DOWN( StdSlider::OnMouseDown )
EVT_SCROLL_CHANGED( StdSlider::OnScrollChanged )
END_EVENT_TABLE()
///////////////////////////////////////////////////////////////////////////////
// Constructor
//
Slider::Slider()
: m_Min( 0.0f )
, m_Max( 100.0f )
, m_CurrentValue( 0.0f )
, m_AutoAdjustMinMax( true )
{
}
///////////////////////////////////////////////////////////////////////////////
// Creates the control.
//
void Slider::Realize(Container* parent)
{
PROFILE_SCOPE_ACCUM( g_RealizeAccumulator );
if ( m_Window != NULL )
return;
StdSlider* slider = new StdSlider( parent->GetWindow(), this );
slider->ClearTicks();
m_Window = slider;
wxSize size( -1, m_Canvas->GetStdSize( Math::SingleAxes::Y ) );
m_Window->SetSize( size );
m_Window->SetMinSize( size );
m_Window->SetMaxSize( size );
__super::Realize( parent );
// Push the min and max values down to the slider.
SetRangeMin( m_Min, false );
SetRangeMax( m_Max, false );
}
///////////////////////////////////////////////////////////////////////////////
// Sets the UI to match the underlying data value.
//
void Slider::Read()
{
if ( IsBound() )
{
SetUIValue( GetValue() );
__super::Read();
}
}
///////////////////////////////////////////////////////////////////////////////
// Takes the value from the UI and pushes it down to the underlying data.
//
bool Slider::Write()
{
bool result = false;
if ( IsBound() )
{
// Get the float value from the UI
m_CurrentValue = GetUIValue();
// Write the value back into the data
tostringstream str;
str << m_CurrentValue;
result = WriteData( str.str(), m_Tracking );
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Indicates that the user is starting a click (possibly drag) operation within
// the UI.
//
void Slider::Start()
{
// Store the value when the user starts dragging the thumb
m_StartDragValue = GetUIValue();
m_Tracking = true;
}
///////////////////////////////////////////////////////////////////////////////
// Indicates that the user has completed a previously started user interaction.
//
void Slider::End()
{
// The user is done dragging around the thumb, so reset the
// value back to what it was when the drag began, then force
// an undoable command that jumps to the final value.
if ( m_Tracking )
{
Freeze();
float temp = GetUIValue();
SetValue( m_StartDragValue );
m_Tracking = false;
SetValue( temp );
Thaw();
}
}
///////////////////////////////////////////////////////////////////////////////
// Returns the value of the underlying data.
//
float Slider::GetValue()
{
if ( IsBound() )
{
tstring str;
ReadData( str );
if ( str != MULTI_VALUE_STRING && str != UNDEF_VALUE_STRING )
{
m_CurrentValue = static_cast< float >( _tstof( str.c_str() ) );
}
}
return m_CurrentValue;
}
///////////////////////////////////////////////////////////////////////////////
// Sets the underlying data and the UI to the specified value.
//
void Slider::SetValue(float value)
{
// Update our cached value
m_CurrentValue = value;
// If we have a data pointer, update it
if ( IsBound() )
{
tostringstream str;
str << m_CurrentValue;
WriteData( str.str() );
}
SetUIValue( m_CurrentValue );
}
///////////////////////////////////////////////////////////////////////////////
// Sets the minimum value allowed by the slider. If clamp is true and the
// current value is less than the min, the value will be set to the min.
//
void Slider::SetRangeMin(float min, bool clamp)
{
m_Min = min;
if ( clamp && GetValue() < m_Min )
{
SetValue( m_Min );
}
}
///////////////////////////////////////////////////////////////////////////////
// Sets the maximum value allowed by the slider. If clamp is true and the
// current value is greater than max, the value will be set to the max.
void Slider::SetRangeMax(float max, bool clamp)
{
m_Max = max;
if ( clamp && GetValue() > m_Max )
{
SetValue( m_Max );
}
}
///////////////////////////////////////////////////////////////////////////////
// If true and the value is set below the min or above the max, the slider
// will automatically adjust its min or max to include the new value.
//
void Slider::SetAutoAdjustMinMax( bool autoAdjust )
{
m_AutoAdjustMinMax = autoAdjust;
}
///////////////////////////////////////////////////////////////////////////////
// Process script commands.
//
bool Slider::Process( const tstring& key, const tstring& value )
{
if (__super::Process(key, value))
return true;
if (key == SLIDER_ATTR_MIN)
{
SetRangeMin( static_cast< float >( _tstof( value.c_str() ) ) );
return true;
}
else if (key == SLIDER_ATTR_MAX)
{
SetRangeMax( static_cast< float >( _tstof( value.c_str() ) ) );
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// Sets the UI to the specified value.
//
void Slider::SetUIValue( float value )
{
// If the control has been realized, update the UI
if ( IsRealized() )
{
if ( m_AutoAdjustMinMax )
{
if ( value > m_Max )
{
m_Max = value;
}
else if ( value < m_Min )
{
m_Min = value;
}
}
int val = static_cast< int >( 0.5f + ( ( (m_CurrentValue - m_Min ) / ( m_Max - m_Min ) ) * 1000.f ) );
if ( val < 0 )
{
val = 0;
}
if ( val > 1000 )
{
val = 1000;
}
StdSlider* slider = Control::Cast<StdSlider>( this );
slider->m_Override = true;
slider->SetValue( val );
slider->m_Override = false;
}
}
///////////////////////////////////////////////////////////////////////////////
// Returns the value currently displayed in the UI.
//
float Slider::GetUIValue() const
{
int val = Control::Cast< wxSlider >( this )->GetValue();
const float result = m_Min + ( ( m_Max - m_Min ) * ( static_cast< float >( val ) / 1000.f ) );
return result;
}
| true |
86687eb6fb5ffd5f75500d207d89713e8404defc | C++ | Izumemori/muscord-cpp | /src/main.cpp | UTF-8 | 3,191 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "muscord.h"
#include "common.h"
#include "log_message.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
#include <memory>
#include <csignal>
#include <stdio.h>
#include <string.h>
using namespace muscord;
std::map<int, std::string> signal_map {
{SIGTERM, "SIGTERM"},
{SIGINT, "SIGINT"},
{SIGSEGV, "SIGSEGV"},
{SIGABRT, "SIGABRT"}
};
std::shared_ptr<MuscordConfig> config;
std::unique_ptr<Muscord> muscord_client;
void log(const LogMessage& log) {
if (log.severity < config->min_log_level) return;
std::cout << "[" << severity_to_str(log.severity) << "] " << log.message << std::endl;
}
void handle_signal(int sig_num) {
LogMessage exit_message("Received signal '" + signal_map[sig_num] + "', exiting...", Severity::WARNING);
log(exit_message);
muscord_client->stop();
exit(0);
}
const char* allocate_dynamically(std::string& input) {
char* ptr = new char[input.size() + 1];
strcpy(ptr, input.c_str());
return ptr;
}
int main()
{
std::signal(SIGTERM, handle_signal);
std::signal(SIGINT, handle_signal);
std::signal(SIGSEGV, handle_signal);
std::signal(SIGABRT, handle_signal);
std::string config_dir_base = get_config_dir() + "/muscord";
ensure_config_dir_created(config_dir_base);
config = std::make_shared<MuscordConfig>(config_dir_base + "/config.yml");
std::unique_ptr<MuscordEvents> events = std::make_unique<MuscordEvents>();
events->log_received = static_cast<void(*)(const LogMessage&)>(log);
events->ready = [](const DiscordUser* user) {
LogMessage logged_in_msg("Logged in as " + std::string(user->username) + "#" + std::string(user->discriminator) + " (" + std::string(user->userId) + ")", Severity::INFO);
log(logged_in_msg);
};
events->play_state_change = [](const MuscordState& state, DiscordRichPresence* presence) {
// Player stuff
std::string player_icon = config->get_player_icon(state.player_name);
std::string play_state_icon = config->get_play_state_icon(state.status);
std::string player_name = config->fmt_player_str(state.player_name);
presence->largeImageKey = allocate_dynamically(player_icon);
presence->smallImageKey = allocate_dynamically(play_state_icon);
presence->largeImageText = allocate_dynamically(player_name);
std::string artist;
if (state.idle)
{
artist = config->get_idle_string();
presence->state = allocate_dynamically(artist);
return; // rest would be empty
}
// Song stuff
artist = config->fmt_artist_str(state.artist);
std::string title = config->fmt_title_str(state.title);
std::string album = config->fmt_album_str(state.album);
presence->state = allocate_dynamically(artist);
presence->details = allocate_dynamically(title);
presence->smallImageText = allocate_dynamically(album);
};
muscord_client = std::make_unique<Muscord>(config, events);
muscord_client->run();
std::promise<void>().get_future().wait(); // wait indefinitely
return 0;
}
| true |
f8eee4fec599e5c06befc3898f82afdee43730ae | C++ | tienit150198/ACM | /20181020/FIBO_HCMUP/main.cpp | UTF-8 | 919 | 2.78125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long int
using namespace std;
const ll MOD = 1e9 + 7;
struct MaTran{
ll c[2][2];
MaTran(){
c[0][0] = 0;
c[0][1] = 1;
c[1][0] = 1;
c[1][1] = 1;
}
};
MaTran operator* (MaTran a, MaTran b){
MaTran res;
for(ll i = 0 ; i <= 1; i++){
for(ll j = 0 ; j <= 1; j++){
res.c[i][j] = 0;
for(ll k = 0 ; k <= 1; k++){
res.c[i][j] = (res.c[i][j] + a.c[i][k] * b.c[k][j])%MOD;
}
}
}
return res;
}
MaTran powMod(MaTran a, ll n){
if(n == 1)
return a;
MaTran res = powMod(a,n/2);
res = res * res;
if(n%2 == 1){
res = res * a;
}
return res;
}
int main()
{
freopen("fibo.inp","r",stdin);
freopen("fibo.out","w",stdout);
ll n;
cin >> n;
MaTran A;
A = powMod(A,n);
cout << A.c[0][1];
return 0;
}
| true |
a25131a89abc8c92283da88372cb3475133cd1af | C++ | housengw/CS8-I-Love-Baseball | /app/baseball_gui/view_souvenir_list.cpp | UTF-8 | 3,914 | 2.515625 | 3 | [] | no_license | #include "view_souvenir_list.h"
#include "ui_view_souvenir_list.h"
#include "administrator_login.h"
/*****************************************************************
* CONSTRUCTOR
* view_souvenir_list::view_souvenir_list(Map* map, Stadium* stadium, QWidget *parent) :QDialog(parent)
*________________________________________________________________
* This constructor initializes variables to default values and display the
* list of souvenir
*________________________________________________________________
* PRE-CONDITIONS
* None
*
* POST-CONDITIONS
* None
*****************************************************************/
view_souvenir_list::view_souvenir_list(Map* map, //IN - map class
Stadium* stadium, //IN - stadium
QWidget *parent) : //IN - parent of the mainwindow
QDialog(parent),
ui(new Ui::view_souvenir_list),
_stadium(stadium)
{
ui->setupUi(this);
_map = map;
ui->display_souvenirs->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->display_souvenirs->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->display_souvenirs->setSelectionMode(QAbstractItemView::SingleSelection);
ui->display_souvenirs->setUpdatesEnabled(true);
ui->display_souvenirs->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->display_souvenirs->verticalHeader()->hide();
ui->display_souvenirs->setColumnCount(2);
QStringList tableHeaders;
tableHeaders <<"souvenir name"<<"souvenir price";
ui->display_souvenirs->setHorizontalHeaderLabels(tableHeaders);
display_List();
}
/*****************************************************************
* DESTRUCTOR
* view_souvenir_list::~view_souvenir_list(): Class view_souvenir_list
*________________________________________________________________
* This deallocates any dynamically allocated memory
*________________________________________________________________
* PRE-CONDITIONS
* none
*
* POST-CONDITIONS
* dynamic memory deallocated
*****************************************************************/
view_souvenir_list::~view_souvenir_list()
{
delete ui;
}
/*****************************************************************
* Method void view_souvenir_list::display_List()
*________________________________________________________________
* This function will display the souvenir information
*________________________________________________________________
* PRE-CONDITIONS
* none
*
* POST-CONDITIONS
* display souvenir information
*****************************************************************/
void view_souvenir_list::display_List()
{
SouvenirsContainer* list = &(_stadium->get_souvenir_list());
ui->display_souvenirs->setRowCount(list->size());
for (int i = 0; i < list->size(); i++){
ui->display_souvenirs->setItem(i, 0, new QTableWidgetItem ((*list)[i]._name.c_str()));
char number[20];
sprintf(number, "%4.2f", (*list)[i]._price);
string price = "$" + string(number);
ui->display_souvenirs->setItem(i, 1, new QTableWidgetItem(price.c_str()));
}
ui->display_souvenirs->resizeRowsToContents();
}
/*****************************************************************
* Method void view_souvenir_list::on_pushButton_clicked()
*________________________________________________________________
* This function creates an AdministratorLogin object to let administrator
* modify the souvenir information
*________________________________________________________________
* PRE-CONDITIONS
* button clicked
*
* POST-CONDITIONS
* None
*****************************************************************/
void view_souvenir_list::on_pushButton_clicked()
{
AdministratorLogin al(_map);
al.setModal(true);
al.exec();
}
| true |
1b031593773c87b99efc85eb0a3cd101f560b5b4 | C++ | ryanhaining/cppitertools | /internal/iter_tuples.hpp | UTF-8 | 1,977 | 2.9375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef ITERTOOLS_ITER_TUPLES_HPP_
#define ITERTOOLS_ITER_TUPLES_HPP_
#include "iterator_wrapper.hpp"
#include "iterbase.hpp"
#include <functional>
namespace iter {
namespace impl {
namespace detail {
template <typename... Ts>
std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(
const std::tuple<Ts...>&);
template <typename... Ts>
std::tuple<IteratorWrapper<Ts>...> iterator_tuple_type_helper(
const std::tuple<Ts...>&);
template <typename... Ts>
std::tuple<iterator_deref<const std::remove_reference_t<Ts>>...>
const_iterator_tuple_deref_helper(const std::tuple<Ts...>&);
template <typename... Ts>
std::tuple<IteratorWrapper<const std::remove_reference_t<Ts>>...>
const_iterator_tuple_type_helper(const std::tuple<Ts...>&);
}
// Given a tuple template argument, evaluates to a tuple of iterators
// for the template argument's contained types.
template <typename TupleType>
using iterator_tuple_type =
decltype(detail::iterator_tuple_type_helper(std::declval<TupleType>()));
template <typename TupleType>
using const_iterator_tuple_type = decltype(
detail::const_iterator_tuple_type_helper(std::declval<TupleType>()));
// Given a tuple template argument, evaluates to a tuple of
// what the iterators for the template argument's contained types
// dereference to
template <typename TupleType>
using iterator_deref_tuple = decltype(
detail::iterator_tuple_deref_helper(std::declval<TupleType>()));
template <typename TupleType>
using const_iterator_deref_tuple = decltype(
detail::const_iterator_tuple_deref_helper(std::declval<TupleType>()));
// function absorbing all arguments passed to it. used when
// applying a function to a parameter pack but not passing the evaluated
// results anywhere
template <typename... Ts>
void absorb(Ts&&...) {}
}
}
#endif
| true |
8996de9471985afe114e805900d5fbc8b0c8b7a1 | C++ | lehuyduc/BasicCppOOP | /Code/Labwork5/Labwork5/sheep/Graphic.hpp | UTF-8 | 763 | 3.359375 | 3 | [] | no_license | /*
* Graphic.hpp
* Labwork 5
*
* Created by Lilian Aveneau on 04/11/11.
* Copyright 2011 XLIM/SIC/IG. All rights reserved.
*
*/
#pragma once
using std::string;
class Graphic
{
protected:
const unsigned m_x; // we use Oxy coordinate, bottom left is 0 0
const unsigned m_y;
const string m_color;
public:
Graphic(const unsigned x, const unsigned y, const string c)
: m_x(x), m_y(y), m_color(c)
{}
Graphic(const Graphic& g)
: m_x(g.m_x), m_y(g.m_y), m_color(g.m_color)
{}
const string get_color() const {
return m_color;
}
// In fact, we cannot do it correctly: polymorphism is mandatory! -> virtual
virtual bool isPrint( unsigned x, unsigned y ) const {
return x == m_x && y == m_y; // actually, draw a Point!
}
};
| true |
c6df1ad8daa10a9df0aa1005a08e08ae8455f915 | C++ | TeamUnibuc/MusicalBash | /src/ui/u_dynamic_text_box.cpp | UTF-8 | 520 | 2.578125 | 3 | [] | no_license | #include "u_dynamic_text_box.hpp"
DynamicTextBox::DynamicTextBox(int posX, int posY, int sizeX, int sizeY, int alignment, std::string textInput,
std::function<std::string()> func) :
TextBox(posX, posY, sizeX, sizeY, alignment, textInput),
reloaded_text(func)
{}
void DynamicTextBox::Render(sf::RenderWindow& rw, int off_x, int off_y)
{
std::string time = reloaded_text();
SetText(time);
// Logger::Get() << "Set text: " << time << '\n';
TextBox::Render(rw, off_x, off_y);
} | true |
a6875142a45ac02693a7e0731454f9e999ee436f | C++ | PrathameshDhumal/Programming-in-C-Advance-C-and-java | /14_COUNTEVENDIGIT/dev.cpp | UTF-8 | 2,185 | 3.75 | 4 | [] | no_license |
#include<stdio.h> // REquired for printf and scanf
int CountEvenDigits(int);
#include "Header.h"
//////////////////////////////////////////////////////////////
//
// Function name : CountEvenDigits
// Input : Interger
// Output : Integer
// Description : It is used to count number of even digits
// Autor : Piyush Manohar Khairnar
// Date : 3rd August 2020
//
//////////////////////////////////////////////////////////////
int CountEvenDigits(int iNo) // 2547 254 25 2 0
{
int iCnt = 0; // 0 1 2
int iDigit = 0; // 7 4 5 2
while(iNo != 0)
{
iDigit = iNo % 10;
if((iDigit % 2) == 0)
{
iCnt++;
}
iNo = iNo / 10;
}
return iCnt;
}
/*
Problem statement :
Accept number from user and return the number of even digits from that numvber.
Input : 1278 Output : 2
Input : 127 Output : 1
Input : 27 Output : 1
Input : 2 Output : 1
Input : -56 Output : 1
Input : 0 Output : 1
Input : 1005 Output : 2
*/
/*
Algorithm:
START
Accept one number as no
Create one counter as cnt and initialise to 0
Iterate till the no is not equal to 0
Perform the mod operation to seperate out the digit
if the digit is even then
increament the counter by 1
divide the no by 10 and store the result in no itself
Continue
return the value of counter
END
*/
#include "Header.h"
// Entry point function
int main()
{
int iValue = 0;
int iRet = 0;
printf("Enter number\n");
scanf("%d",&iValue);
iRet = CountEvenDigits(iValue);
printf("Number of even digits are : %d\n",iRet);
return 0; // Sucess to OS
}
/*
Input : 1547
1547 / 10 -> 154 1
154 / 10 -> 15 2
15 / 10 -> 1 3
1 / 10 -> 0 4
*/
| true |
06c2f29e067047c577022c680824470c6e427f5f | C++ | shwenakak/CS100-Lab1 | /test.cpp | UTF-8 | 942 | 2.65625 | 3 | [] | no_license |
#include "c-echo.h"
#include "gtest/gtest.h"
TEST(EchoTest, HelloWorld) {
char* test_val[3]; test_val[0] = "./c-echo"; test_val[1] = "hello"; test_val[2] = "world";
EXPECT_EQ("hello world", echo(3,test_val));
}
TEST(ShwenaTest, ShwenaKak) {
char* test_val[3]; test_val[0] = "./c-echo"; test_val[1] = "shwena"; test_val[2] = "kak";
EXPECT_EQ("shwena kak", echo(3,test_val));
}
TEST(NumberTest, 12) {
char* test_val[3]; test_val[0] = "./c-echo"; test_val[1] = "1"; test_val[2] = "2";
EXPECT_EQ("1 2", echo(3,test_val));
}
TEST(helloTest, HelloHi) {
char* test_val[3]; test_val[0] = "./c-echo"; test_val[1] = "hello"; test_val[2] = "hi";
EXPECT_EQ("hello hi", echo(3,test_val));
}
TEST(EchoTest, EmptyString) {
char* test_val[1]; test_val[0] = "./c-echo";
EXPECT_EQ("", echo(1,test_val));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
3a2287ac5b84f4d24322fa9fccb6d7b85d3a2443 | C++ | ohughes343/1501project2 | /controller/controller.ino | UTF-8 | 1,356 | 2.65625 | 3 | [] | no_license | /*
* Code for controller
* By: Aryton Hoi
*/
#include <Servo.h>
#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
//Setup NRF
RF24 radio(7,8); // CE, CSN
const byte address[6] = "00001";
//Setup joysticks
const int joy1 = A0;//blue
const int joy2 = A1;//black
//Setup joystick position values (middle position)
int joy1Pos;
int joy2Pos;
//Setup buttons
const int button1 = A2;
int button1State;
//Setup vibrator
const int vibrator = 9;
int vibstate;
void setup()
{
Serial.begin(9600);
//Start wireless communication
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MIN);
//Set NRF as transmitter
radio.stopListening();
//setup button pins
pinMode(button1, INPUT);
//Setup vibrator pins
pinMode(vibrator, OUTPUT);
}
void loop()
{
//Read joystick positions
joy1Pos = analogRead(joy2); //change to joy1
joy2Pos = analogRead(joy2);
button1State = digitalRead(button1);
if(button1State == 1){
digitalWrite(vibrator, HIGH);
}else{
digitalWrite(vibrator, LOW);
}
//format and transmit input data
int transmit[3] = {joy1Pos, joy2Pos, button1State};
radio.write(&transmit, sizeof(transmit));
Serial.print(transmit[0]);
Serial.print(", ");
Serial.print(transmit[1]);
Serial.print(", ");
Serial.println(transmit[2]);
//Serial.println(button1State);
delay(10);
}
| true |
af07bac375a575467efa02cb4c60cdee0bcb8039 | C++ | ledrui/ELL | /libraries/model/tcc/OutputNode.tcc | UTF-8 | 2,423 | 2.796875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: OutputNode.tcc (model)
// Authors: Chuck Jacobs
//
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace ell
{
namespace model
{
template <typename ValueType>
OutputNode<ValueType>::OutputNode()
: OutputNodeBase(_input, _output, OutputShape{ 0, 0, 0 }), _input(this, {}, defaultInputPortName), _output(this, defaultOutputPortName, 0) {};
template <typename ValueType>
OutputNode<ValueType>::OutputNode(const model::PortElements<ValueType>& input)
: OutputNodeBase(_input, _output, OutputShape{ input.Size(), 1, 1 }), _input(this, input, defaultInputPortName), _output(this, defaultOutputPortName, input.Size()) {};
template <typename ValueType>
OutputNode<ValueType>::OutputNode(const model::PortElements<ValueType>& input, const OutputShape& shape)
: OutputNodeBase(_input, _output, shape), _input(this, input, defaultInputPortName), _output(this, defaultOutputPortName, input.Size()) {};
template <typename ValueType>
void OutputNode<ValueType>::Compute() const
{
_output.SetOutput(_input.GetValue());
}
template <typename ValueType>
void OutputNode<ValueType>::Copy(ModelTransformer& transformer) const
{
auto newPortElements = transformer.TransformPortElements(_input.GetPortElements());
auto newNode = transformer.AddNode<OutputNode<ValueType>>(newPortElements, GetShape());
transformer.MapNodeOutput(output, newNode->output);
}
template <typename ValueType>
void OutputNode<ValueType>::WriteToArchive(utilities::Archiver& archiver) const
{
Node::WriteToArchive(archiver);
archiver[defaultInputPortName] << _input;
archiver[shapeName] << static_cast<std::vector<size_t>>(GetShape());
}
template <typename ValueType>
void OutputNode<ValueType>::ReadFromArchive(utilities::Unarchiver& archiver)
{
Node::ReadFromArchive(archiver);
archiver[defaultInputPortName] >> _input;
std::vector<size_t> shapeVector;
archiver[shapeName] >> shapeVector;
_output.SetSize(_input.Size());
if (shapeVector.size() >= 3)
{
SetShape(OutputShape{ shapeVector });
}
}
}
}
| true |
0f1cfbb54874bcdd3cae1440d02353d77bee11b4 | C++ | jthornber/cache-simulator | /main.cc | UTF-8 | 17,454 | 2.71875 | 3 | [] | no_license | #include <cmath>
#include <iomanip>
#include <iostream>
#include <list>
#include <math.h>
#include <memory>
#include <vector>
#include <map>
#include <boost/optional.hpp>
#include <boost/intrusive/list.hpp>
#include <sequence.h>
#include <stdlib.h>
using namespace std;
using namespace boost;
//----------------------------------------------------------------
namespace {
typedef unsigned block;
//--------------------------------
// FIXME: these random generators are not good enough, use the
// Mersenne Twister from boost.
double rand01(void) {
return static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
}
block rand_block(block max) {
return rand() % max;
}
//--------------------------------
void renormalise(vector<double> &pdfs) {
double total = 0.0;
for (unsigned i = 0; i < pdfs.size(); i++)
total += pdfs[i];
if (total == 0.0)
return;
for (unsigned i = 0; i < pdfs.size(); i++)
pdfs[i] /= total;
}
template <typename T>
T square(T x) {
return x * x;
}
// probability density function
class pdf {
public:
typedef shared_ptr<pdf> ptr;
virtual ~pdf() {}
virtual void generate(vector<double> &pdfs) const = 0;
};
class uniform : public pdf {
public:
virtual void generate(vector<double> &pdfs) const {
if (pdfs.size() == 0)
return;
double value = 1.0 / static_cast<double>(pdfs.size());
for (unsigned i = 0; i < pdfs.size(); i++)
pdfs[i] = value;
}
};
class gaussian : public pdf {
public:
typedef shared_ptr<gaussian> ptr;
gaussian(double mean, double variance)
: mean_(mean),
variance_(variance) {
}
virtual void generate(vector<double> &pdfs) const {
double standard_deviation = sqrt(variance_);
for (unsigned i = 0; i < pdfs.size(); i++) {
double x = static_cast<double>(i);
double exponent = -1.0 * (square(x - mean_) / (2 * variance_));
pdfs[i] = (1.0 / (standard_deviation * sqrt(2.0 * M_PI))) *
exp(exponent);
}
renormalise(pdfs);
}
private:
double mean_;
double variance_;
};
class mixture : public pdf {
public:
typedef shared_ptr<mixture> ptr;
void add_component(double weight, pdf::ptr pdf) {
components_.push_back(make_pair(weight, pdf));
};
virtual void generate(vector<double> &pdfs) const {
vector<double> tmp(pdfs.size(), 0.0);
for (unsigned i = 0; i < pdfs.size(); i++)
pdfs[i] = 0.0;
for (auto cs = components_.begin(); cs != components_.end(); ++cs) {
cs->second->generate(tmp);
for (unsigned i = 0; i < pdfs.size(); i++)
pdfs[i] += cs->first * tmp[i];
}
renormalise(pdfs);
}
private:
typedef pair<double, pdf::ptr> component;
list<component> components_;
};
unsigned rand_pdf(vector<double> const &pdf) {
double n = rand01();
double total = 0.0;
unsigned i;
for (i = 0; i < pdf.size(); i++) {
total += pdf[i];
if (total >= n)
return i;
}
return i;
}
//--------------------------------
class cache {
public:
typedef shared_ptr<cache> ptr;
cache(unsigned size)
: hits_(0),
misses_(0),
evictions_(0),
cache_size_(size) {
}
block size() const {
return cache_size_;
}
void request(block origin_block) {
if (to_cache_.count(origin_block) > 0)
hits_++;
else
misses_++;
};
unsigned get_hits() const {
return hits_;
}
unsigned get_misses() const {
return misses_;
}
unsigned get_evictions() const {
return evictions_;
}
void insert(block cache_block, block origin_block) {
auto i = to_origin_.find(cache_block);
if (i != to_origin_.end()) {
if (i->second == origin_block)
return; // mapping hasn't changed
evictions_++;
to_cache_.erase(i->second);
to_origin_.erase(i->first);
}
to_cache_.insert(make_pair(origin_block, cache_block));
to_origin_.insert(make_pair(cache_block, origin_block));
}
private:
typedef map<block, block> block_map;
block_map to_cache_;
block_map to_origin_;
unsigned hits_;
unsigned misses_;
unsigned evictions_;
unsigned cache_size_;
};
//--------------------------------
class policy {
public:
typedef shared_ptr<policy> ptr;
policy(block origin_size, cache::ptr cache)
: origin_size_(origin_size),
cache_(cache) {
}
virtual ~policy() {}
virtual void map(block origin_block) = 0;
protected:
unsigned origin_size() const {
return origin_size_;
}
cache::ptr get_cache() {
return cache_;
}
private:
block origin_size_;
cache::ptr cache_;
};
// A silly little policy that gives us a baseline to compare the
// more sophisticated policies against. Actually it works quite
// well!
class random_policy : public policy {
public:
random_policy(double prob_of_promotion, block origin_size, cache::ptr cache)
: policy(origin_size, cache),
prob_(prob_of_promotion) {
}
virtual void map(block origin_block) {
double r = rand01();
if (r < prob_) {
cache::ptr c = get_cache();
c->insert(rand_block(c->size()), origin_block);
}
}
private:
double prob_;
};
class hash_policy : public policy {
public:
hash_policy(unsigned hash_size, double prob, block origin_size, cache::ptr cache)
: policy(origin_size, cache),
hash_(hash_size, 0),
prob_(prob) {
}
virtual void map(block origin_block) {
double p = prob_;
unsigned h = hash(origin_block);
if (hash_[h] > 0)
p *= 100;
double r = rand01();
if (r < p) {
cache::ptr c = get_cache();
c->insert(rand_block(c->size()), origin_block);
hash_[h] = 0;
} else
hash_[h]++;
}
private:
unsigned hash(block b) const {
const unsigned long BIG_PRIME = 4294967291UL;
uint64_t hash = b * BIG_PRIME;
return hash % hash_.size();
}
vector<unsigned> hash_;
double prob_;
};
class lru_policy : public policy {
public:
lru_policy(block origin_size, cache::ptr cache)
: policy(origin_size, cache),
entries_(cache->size()) {
}
virtual void map(block origin_block) {
optional<lru_policy::entry &> oe = find_by_origin(origin_block);
if (oe)
return;
// always promote if it's not in the cache
cache::ptr c = get_cache();
if (map_.size() < c->size()) {
// create a new entry
entry &e = entries_[map_.size()];
e.origin_ = origin_block;
e.cache_ = map_.size();
lru_.push_back(e);
map_.insert(make_pair(origin_block, ref(e)));
c->insert(e.cache_, e.origin_);
} else {
// overwrite the lru
entry &e = find_lru();
map_.erase(e.origin_);
e.origin_ = origin_block;
map_.insert(make_pair(origin_block, ref(e)));
mark_mru(e);
c->insert(e.cache_, e.origin_);
}
}
private:
struct entry {
intrusive::list_member_hook<> list_;
intrusive::list_member_hook<> hash_;
block origin_;
block cache_;
};
typedef intrusive::member_hook<entry, intrusive::list_member_hook<>, &entry::list_> lru_option;
typedef intrusive::list<entry, lru_option> lru_list;
typedef std::map<block, entry &> entry_map;
optional<entry &> find_by_origin(block origin) {
entry_map::iterator it = map_.find(origin);
if (it != map_.end())
return optional<entry &>(it->second);
return optional<entry &>();
}
entry &find_lru() {
entry &e = lru_.front();
return e;
}
void mark_mru(struct entry &e) {
lru_.erase(lru_.iterator_to(e));
lru_.push_back(e);
}
vector<entry> entries_;
entry_map map_;
lru_list lru_;
};
class arc_policy : public policy {
private:
enum entry_state {
T1,
T2,
B1,
B2
};
struct entry {
entry_state state_;
intrusive::list_member_hook<> list_;
block origin_;
block cache_;
};
typedef intrusive::member_hook<entry, intrusive::list_member_hook<>, &entry::list_> lru_option;
typedef intrusive::list<entry, lru_option> lru_list;
typedef std::map<block, entry &> entry_map;
public:
arc_policy(block origin_size, cache::ptr cache)
: policy(origin_size, cache),
entries_(cache->size() * 2),
p_(0),
allocated_(0),
allocated_entries_(0) {
}
virtual void map(block origin_block) {
cache::ptr c = get_cache();
optional<entry &> oe = find_by_origin(origin_block);
if (oe) {
entry &e = *oe;
block new_cache;
block delta;
block b1_size = b1_.size();
block b2_size = b2_.size();
switch (e.state_) {
case T1:
t1_.erase(t1_.iterator_to(e));
break;
case T2:
t2_.erase(t2_.iterator_to(e));
break;
case B1:
delta = (b1_size > b2_size) ? 1 : max<block>(b2_size / b1_size, 1);
p_ = min(p_ + delta, c->size());
new_cache = demote(optional<entry &>(e));
b1_.erase(b1_.iterator_to(e));
e.cache_ = new_cache;
e.origin_ = origin_block;
break;
case B2:
delta = b2_size >= b1_size ? 1 : max<block>(b1_size / b2_size, 1);
p_ = max(p_ - delta, static_cast<block>(0));
new_cache = demote(optional<entry &>(e));
b2_.erase(b2_.iterator_to(e));
e.cache_ = new_cache;
e.origin_ = origin_block;
break;
}
push(T2, e);
return;
}
if (!interesting_block(origin_block))
return;
entry *e;
block l1_size = t1_.size() + b1_.size();
block l2_size = t2_.size() + b2_.size();
if (l1_size == c->size()) {
if (t1_.size() < c->size()) {
e = &pop(B1);
block new_cache = demote();
e->cache_ = new_cache;
e->origin_ = origin_block;
} else {
e = &pop(T1);
e->origin_ = origin_block;
}
} else if (l1_size < c->size() && (l1_size + l2_size >= c->size())) {
if (l1_size + l2_size == 2 * c->size()) {
e = &pop(B2);
e->cache_ = demote();
e->origin_ = origin_block;
} else {
e = &alloc_entry();
e->cache_ = demote();
e->origin_ = origin_block;
}
} else {
BOOST_ASSERT(allocated_ < c->size());
e = &alloc_entry();
e->origin_ = origin_block;
e->cache_ = allocated_++;
}
push(T1, *e);
}
private:
virtual bool interesting_block(block origin) {
return true;
}
void insert(entry &e) {
map_.insert(make_pair(e.origin_, ref(e)));
get_cache()->insert(e.cache_, e.origin_);
}
optional<entry &> find_by_origin(block origin) {
entry_map::iterator it = map_.find(origin);
if (it != map_.end())
return optional<entry &>(it->second);
return optional<entry &>();
}
void push(entry_state s, entry &e) {
e.state_ = s;
switch (s) {
case T1:
t1_.push_back(e);
insert(e);
break;
case T2:
t2_.push_back(e);
insert(e);
break;
case B1:
b1_.push_back(e);
break;
case B2:
b2_.push_back(e);
break;
}
}
entry &pop(entry_state s) {
entry *e;
switch (s) {
case T1:
e = &t1_.front();
t1_.pop_front();
map_.erase(e->origin_);
break;
case T2:
e = &t2_.front();
t2_.pop_front();
map_.erase(e->origin_);
break;
case B1:
e = &b1_.front();
b1_.pop_front();
break;
case B2:
e = &b2_.front();
b2_.pop_front();
break;
}
return *e;
}
block demote(optional<entry &> oe = optional<entry &>()) {
entry *e;
if ((t1_.size() > 0) &&
((t1_.size() > p_) || (oe && oe->state_ == B2 && t1_.size() == p_))) {
e = &pop(T1);
push(B1, *e);
} else {
e = &pop(T2);
push(B2, *e);
}
return e->cache_;
}
entry &alloc_entry() {
BOOST_ASSERT(allocated_entries_ < 2 * get_cache()->size());
return entries_[allocated_entries_++];
}
vector<entry> entries_;
entry_map map_;
lru_list t1_, b1_, t2_, b2_;
block p_;
block allocated_;
block allocated_entries_;
};
class arc_window_policy : public arc_policy {
public:
arc_window_policy(block interesting_size, block origin_size, cache::ptr cache)
: arc_policy(origin_size, cache),
entries_(interesting_size),
allocated_(0) {
}
private:
virtual bool interesting_block(block origin) {
auto it = map_.find(origin);
if (it == map_.end()) {
if (allocated_ == entries_.size()) {
entry &e = lru_.front();
lru_.pop_front();
map_.erase(e.origin_);
e.origin_ = origin;
lru_.push_back(e);
map_.insert(make_pair(origin, ref(e)));
} else {
entry &e = entries_[allocated_++];
e.origin_ = origin;
lru_.push_back(e);
map_.insert(make_pair(origin, ref(e)));
}
return false;
}
// this block is interesting so we forget about it,
// relying on the arc policy to manage it.
map_.erase(it->second.origin_);
return true;
}
struct entry {
intrusive::list_member_hook<> list_;
block origin_;
};
typedef intrusive::member_hook<entry, intrusive::list_member_hook<>, &entry::list_> lru_option;
typedef intrusive::list<entry, lru_option> lru_list;
typedef std::map<block, entry &> entry_map;
vector<entry> entries_;
block allocated_;
lru_list lru_;
entry_map map_;
};
class arc_hash_policy : public arc_policy {
public:
arc_hash_policy(block interesting_size, block origin_size, cache::ptr cache)
: arc_policy(origin_size, cache),
table_(interesting_size, 0) {
}
private:
unsigned hash(block b) {
const block BIG_PRIME = 4294967291UL;
block h = b * BIG_PRIME;
return static_cast<unsigned>(h % table_.size());
}
virtual bool interesting_block(block origin) {
unsigned h = hash(origin);
if (table_[h] == origin)
return true;
table_[h] = origin;
return false;
}
vector<block> table_;
};
//--------------------------------
class pdf_sequence : public sequence<block> {
public:
pdf_sequence(pdf::ptr pdf, block size)
: probs_(size, 0.0) {
pdf->generate(probs_);
}
virtual block operator()() {
return rand_pdf(probs_);
}
private:
vector<double> probs_;
};
class linear_sequence : public sequence<block> {
public:
linear_sequence(block begin, block end)
: begin_(begin),
end_(end),
current_(begin_) {
}
virtual block operator()() {
block r = current_;
if (++current_ >= end_)
current_ = begin_;
return r;
}
private:
block begin_, end_, current_;
};
//--------------------------------
void
run_sequence(block run_length, sequence<block>::ptr seq, cache::ptr c, policy::ptr p) {
for (unsigned i = 0; i < run_length; i++) {
block b = (*seq)();
c->request(b);
p->map(b);
}
}
void
run_simulation(block run_length,
sequence<block>::ptr seq1,
sequence<block>::ptr seq2,
sequence<block>::ptr lseq,
cache::ptr c, policy::ptr p) {
run_sequence(run_length, seq1, c, p);
run_sequence(run_length, lseq, c, p);
run_sequence(run_length, seq1, c, p);
run_sequence(run_length, seq2, c, p);
run_sequence(run_length, lseq, c, p);
run_sequence(run_length, seq2, c, p);
}
template <typename T>
double percentage(T n, T tot) {
return (static_cast<double>(n) / static_cast<double>(tot)) * 100.0;
}
void
display_cache_stats(string const &label, cache::ptr c) {
block total = c->get_hits() + c->get_misses();
cout << label << ": "
<< setprecision(3) << percentage(c->get_hits(), total)
<< "% hits, "
<< setprecision(3) << percentage(c->get_evictions(), total)
<< "% evictions"
<< endl;
}
}
//----------------------------------------------------------------
int main(int argc, char **argv)
{
mixture::ptr blend1, blend2;
{
pdf::ptr g1(new gaussian(120.0, 40.0));
pdf::ptr g2(new gaussian(700.0, 100.0));
pdf::ptr u(new uniform);
blend1 = mixture::ptr(new mixture);
blend1->add_component(0.2, g1);
blend1->add_component(0.3, g2);
blend1->add_component(0.1, u);
}
{
pdf::ptr g1(new gaussian(500.0, 100.0));
pdf::ptr g2(new gaussian(900.0, 10.0));
pdf::ptr u(new uniform);
blend2 = mixture::ptr(new mixture);
blend2->add_component(0.4, g1);
blend2->add_component(0.5, g2);
blend2->add_component(0.1, u);
}
block origin_size = 1000;
block cache_size = 50;
block run_length = 100000;
sequence<block>::ptr seq1(new pdf_sequence(blend1, origin_size));
sequence<block>::ptr seq2(new pdf_sequence(blend2, origin_size));
sequence<block>::ptr lseq(new linear_sequence(0, origin_size));
{
cache::ptr c(new cache(cache_size));
policy::ptr p(new random_policy(0.01, origin_size, c));
run_simulation(run_length, seq1, seq2, lseq, c, p);
display_cache_stats("random", c);
}
{
cache::ptr c(new cache(cache_size));
policy::ptr p(new hash_policy(100, 0.01, origin_size, c));
run_simulation(run_length, seq1, seq2, lseq, c, p);
display_cache_stats("hash", c);
}
{
cache::ptr c(new cache(cache_size));
policy::ptr p(new lru_policy(origin_size, c));
run_simulation(run_length, seq1, seq2, lseq, c, p);
display_cache_stats("lru", c);
}
{
cache::ptr c(new cache(cache_size));
policy::ptr p(new arc_policy(origin_size, c));
run_simulation(run_length, seq1, seq2, lseq, c, p);
display_cache_stats("arc", c);
}
{
cache::ptr c(new cache(cache_size));
policy::ptr p(new arc_window_policy(c->size() / 2, origin_size, c));
run_simulation(run_length, seq1, seq2, lseq, c, p);
display_cache_stats("arc_window", c);
}
{
cache::ptr c(new cache(cache_size));
policy::ptr p(new arc_hash_policy(c->size() / 2, origin_size, c));
run_simulation(run_length, seq1, seq2, lseq, c, p);
display_cache_stats("arc_hash", c);
}
return 0;
}
//----------------------------------------------------------------
| true |
184306680f9bce3dcd140cca8bb62263bebadde6 | C++ | ECOM021/AlGi_Crypt0r | /Model/libs/libhuffman/inc/Node.hpp | UTF-8 | 476 | 2.9375 | 3 | [] | no_license | #ifndef NODE_HPP
#define NODE_HPP
using namespace std;
#include "Globals.hpp"
class Node {
public:
Node();
Node( uchar symb , int occur , Node *left , Node *right );
uchar getSymb();
int getOccur();
Node * getLeft();
Node * getRight();
bool isLeaf();
bool operator > (Node &other);
private:
uchar symb;
int occur;
Node *left;
Node *right;
};
#endif // !NODE_HPP | true |
75a7d473d194f6ba4b3ede61bb8ed90f361d2f29 | C++ | schrodinger/maeparser | /MaeBlock.hpp | UTF-8 | 15,339 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <boost/dynamic_bitset.hpp>
#include <cassert>
#include <cstring>
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
#include "MaeParserConfig.hpp"
namespace schrodinger
{
namespace mae
{
using BoolProperty = uint8_t;
template <typename T>
inline const T& get_property(const std::map<std::string, T>& map,
const std::string& name)
{
auto iter = map.find(name);
if (iter == map.end()) {
throw std::out_of_range("Key not found: " + name);
} else {
return iter->second;
}
}
// Forward declaration.
class IndexedBlockBuffer;
class IndexedBlock;
class EXPORT_MAEPARSER IndexedBlockMapI
{
public:
virtual ~IndexedBlockMapI() = default;
virtual bool hasIndexedBlock(const std::string& name) const = 0;
virtual std::shared_ptr<const IndexedBlock>
getIndexedBlock(const std::string& name) const = 0;
virtual std::vector<std::string> getBlockNames() const = 0;
bool operator==(const IndexedBlockMapI& rhs) const;
};
class EXPORT_MAEPARSER IndexedBlockMap : public IndexedBlockMapI
{
std::map<std::string, std::shared_ptr<IndexedBlock>> m_indexed_block;
public:
bool hasIndexedBlock(const std::string& name) const override;
std::shared_ptr<const IndexedBlock>
getIndexedBlock(const std::string& name) const override;
std::vector<std::string> getBlockNames() const override
{
std::vector<std::string> rval;
for (const auto& p : m_indexed_block) {
rval.push_back(p.first);
}
return rval;
}
/**
* Add an IndexedBlock to the map.
*/
void addIndexedBlock(const std::string& name,
std::shared_ptr<IndexedBlock> indexed_block)
{
m_indexed_block[name] = std::move(indexed_block);
}
};
class EXPORT_MAEPARSER BufferedIndexedBlockMap : public IndexedBlockMapI
{
private:
std::map<std::string, std::shared_ptr<IndexedBlock>> m_indexed_block;
std::map<std::string, std::shared_ptr<IndexedBlockBuffer>> m_indexed_buffer;
public:
bool hasIndexedBlock(const std::string& name) const override;
std::shared_ptr<const IndexedBlock>
getIndexedBlock(const std::string& name) const override;
std::vector<std::string> getBlockNames() const override
{
std::vector<std::string> rval;
for (const auto& p : m_indexed_buffer) {
rval.push_back(p.first);
}
return rval;
}
/**
* Add an IndexedBlockBuffer to the map, which can be used to retrieve an
* IndexedBlock.
*/
void addIndexedBlockBuffer(const std::string& name,
std::shared_ptr<IndexedBlockBuffer> block_buffer)
{
m_indexed_buffer[name] = std::move(block_buffer);
}
};
class EXPORT_MAEPARSER Block
{
private:
const std::string m_name;
std::map<std::string, BoolProperty> m_bmap;
std::map<std::string, double> m_rmap;
std::map<std::string, int> m_imap;
std::map<std::string, std::string> m_smap;
std::map<std::string, std::shared_ptr<Block>> m_sub_block;
std::shared_ptr<IndexedBlockMapI> m_indexed_block_map;
public:
// Prevent copying.
Block(const Block&) = delete;
Block& operator=(const Block&) = delete;
Block(std::string name)
: m_name(std::move(name)), m_bmap(), m_rmap(), m_imap(), m_smap(),
m_indexed_block_map(nullptr)
{
}
const std::string& getName() const { return m_name; }
std::string toString() const;
void write(std::ostream& out, unsigned int current_indentation = 0) const;
void setIndexedBlockMap(std::shared_ptr<IndexedBlockMapI> indexed_block_map)
{
m_indexed_block_map = std::move(indexed_block_map);
}
bool hasIndexedBlockData() const { return m_indexed_block_map != nullptr; }
bool hasIndexedBlock(const std::string& name)
{
return hasIndexedBlockData() &&
m_indexed_block_map->hasIndexedBlock(name);
}
std::shared_ptr<const IndexedBlock>
getIndexedBlock(const std::string& name) const;
void addBlock(std::shared_ptr<Block> b)
{
m_sub_block[b->getName()] = std::move(b);
}
/**
* Check whether this block has a sub-block of the provided name.
*/
bool hasBlock(const std::string& name)
{
std::map<std::string, std::shared_ptr<Block>>::const_iterator iter =
m_sub_block.find(name);
return (iter != m_sub_block.end());
}
/**
* Retrieve a shared pointer to the named sub-block.
*/
std::shared_ptr<Block> getBlock(const std::string& name) const
{
std::map<std::string, std::shared_ptr<Block>>::const_iterator iter =
m_sub_block.find(name);
if (iter == m_sub_block.end()) {
throw std::out_of_range("Sub-block not found: " + name);
} else {
return iter->second;
}
}
/**
* Get the names of all non-indexed sub-blocks
*/
std::vector<std::string> getBlockNames() const
{
std::vector<std::string> names;
for (auto& n : m_sub_block) {
names.push_back(n.first);
}
return names;
}
/**
* Get the names of all indexed sub-blocks
*/
std::vector<std::string> getIndexedBlockNames() const
{
return m_indexed_block_map->getBlockNames();
}
bool operator==(const Block& rhs) const;
bool hasRealProperty(const std::string& name) const
{
return (m_rmap.find(name) != m_rmap.end());
}
double getRealProperty(const std::string& name) const
{
return get_property<double>(m_rmap, name);
}
void setRealProperty(const std::string& name, double value)
{
m_rmap[name] = value;
}
bool hasIntProperty(const std::string& name) const
{
return (m_imap.find(name) != m_imap.end());
}
int getIntProperty(const std::string& name) const
{
return get_property<int>(m_imap, name);
}
void setIntProperty(const std::string& name, int value)
{
m_imap[name] = value;
}
bool hasBoolProperty(const std::string& name) const
{
return (m_bmap.find(name) != m_bmap.end());
}
bool getBoolProperty(const std::string& name) const
{
return 1u == get_property<BoolProperty>(m_bmap, name);
}
void setBoolProperty(const std::string& name, bool value)
{
m_bmap[name] = static_cast<BoolProperty>(value);
}
bool hasStringProperty(const std::string& name) const
{
return (m_smap.find(name) != m_smap.end());
}
const std::string& getStringProperty(const std::string& name) const
{
return get_property<std::string>(m_smap, name);
}
void setStringProperty(const std::string& name, std::string value)
{
m_smap[name] = std::move(value);
}
template <typename T> const std::map<std::string, T>& getProperties() const;
};
template <typename T> class IndexedProperty
{
private:
std::vector<T> m_data;
boost::dynamic_bitset<>* m_is_null;
public:
// Prevent copying.
IndexedProperty(const IndexedProperty<T>&) = delete;
IndexedProperty& operator=(const IndexedProperty<T>&) = delete;
using size_type = typename std::vector<T>::size_type;
/**
* Construct an IndexedProperty from a reference to a vector of data.
* This swaps out the data of the input vector.
*
* The optional boost::dynamic_bitset is owned by the created object.
*/
explicit IndexedProperty(std::vector<T>& data,
boost::dynamic_bitset<>* is_null = nullptr)
: m_data(), m_is_null(is_null)
{
m_data.swap(data);
}
~IndexedProperty()
{
if (m_is_null != nullptr) {
delete m_is_null;
}
}
bool operator==(const IndexedProperty<T>& rhs) const;
size_type size() const { return m_data.size(); }
bool hasUndefinedValues() const
{
return (m_is_null != NULL && m_is_null->any());
}
bool isDefined(size_type index) const
{
if (m_is_null == nullptr) {
// Use of assert matches out-of-bounds behavior for dynamic_bitset.
assert(index < m_data.size());
return true;
} else {
return !m_is_null->test(index);
}
}
void undefine(size_type index)
{
if (m_is_null == NULL) {
m_is_null = new boost::dynamic_bitset<>(m_data.size());
}
m_is_null->set(index);
}
inline T& operator[](size_type index)
{
if (m_is_null && m_is_null->test(index)) {
throw std::runtime_error("Indexed property value undefined.");
}
return m_data[index];
}
inline const T& operator[](size_type index) const
{
if (m_is_null && m_is_null->test(index)) {
throw std::runtime_error("Indexed property value undefined.");
}
return m_data[index];
}
inline T& at(size_type index) { return operator[](index); }
inline const T& at(size_type index) const { return operator[](index); }
inline const T& at(size_type index, const T& default_) const
{
if (m_is_null && m_is_null->test(index)) {
return default_;
}
return m_data[index];
}
void set(size_type index, const T& value)
{
m_data[index] = value;
if (m_is_null != NULL && m_is_null->test(index)) {
m_is_null->reset(index);
}
}
const std::vector<T>& data() const { return m_data; }
const boost::dynamic_bitset<>* nullIndices() const { return m_is_null; }
};
using IndexedRealProperty = IndexedProperty<double>;
using IndexedIntProperty = IndexedProperty<int>;
using IndexedBoolProperty = IndexedProperty<BoolProperty>;
using IndexedStringProperty = IndexedProperty<std::string>;
template <typename T>
inline std::shared_ptr<T>
get_indexed_property(const std::map<std::string, std::shared_ptr<T>>& map,
const std::string& name)
{
auto iter = map.find(name);
if (iter == map.end()) {
return std::shared_ptr<T>(nullptr);
} else {
return iter->second;
}
}
template <typename T>
inline void set_indexed_property(std::map<std::string, std::shared_ptr<T>>& map,
const std::string& name,
std::shared_ptr<T> value)
{
map[name] = std::move(value);
}
class EXPORT_MAEPARSER IndexedBlock
{
private:
const std::string m_name;
std::map<std::string, std::shared_ptr<IndexedBoolProperty>> m_bmap;
std::map<std::string, std::shared_ptr<IndexedIntProperty>> m_imap;
std::map<std::string, std::shared_ptr<IndexedRealProperty>> m_rmap;
std::map<std::string, std::shared_ptr<IndexedStringProperty>> m_smap;
public:
// Prevent copying.
IndexedBlock(const IndexedBlock&) = delete;
IndexedBlock& operator=(const IndexedBlock&) = delete;
/**
* Create an indexed block.
*/
IndexedBlock(std::string name)
: m_name(std::move(name)), m_bmap(), m_imap(), m_rmap(), m_smap()
{
}
size_t size() const;
const std::string& getName() const { return m_name; }
std::string toString() const;
void write(std::ostream& out, unsigned int current_indentation = 0) const;
bool operator==(const IndexedBlock& rhs) const;
bool operator!=(const IndexedBlock& rhs) const
{
return !(operator==(rhs));
}
template <typename T>
void setProperty(const std::string& name,
std::shared_ptr<IndexedProperty<T>> value);
bool hasBoolProperty(const std::string& name) const
{
return (m_bmap.find(name) != m_bmap.end());
}
std::shared_ptr<IndexedBoolProperty>
getBoolProperty(const std::string& name) const
{
return get_indexed_property<IndexedBoolProperty>(m_bmap, name);
}
void setBoolProperty(const std::string& name,
std::shared_ptr<IndexedBoolProperty> value)
{
set_indexed_property<IndexedBoolProperty>(m_bmap, name,
std::move(value));
}
bool hasIntProperty(const std::string& name) const
{
return (m_imap.find(name) != m_imap.end());
}
std::shared_ptr<IndexedIntProperty>
getIntProperty(const std::string& name) const
{
return get_indexed_property<IndexedIntProperty>(m_imap, name);
}
void setIntProperty(const std::string& name,
std::shared_ptr<IndexedIntProperty> value)
{
set_indexed_property<IndexedIntProperty>(m_imap, name,
std::move(value));
}
bool hasRealProperty(const std::string& name) const
{
return (m_rmap.find(name) != m_rmap.end());
}
std::shared_ptr<IndexedRealProperty>
getRealProperty(const std::string& name) const
{
return get_indexed_property<IndexedRealProperty>(m_rmap, name);
}
void setRealProperty(const std::string& name,
std::shared_ptr<IndexedRealProperty> value)
{
set_indexed_property<IndexedRealProperty>(m_rmap, name,
std::move(value));
}
bool hasStringProperty(const std::string& name) const
{
return (m_smap.find(name) != m_smap.end());
}
std::shared_ptr<IndexedStringProperty>
getStringProperty(const std::string& name) const
{
return get_indexed_property<IndexedStringProperty>(m_smap, name);
}
void setStringProperty(const std::string& name,
std::shared_ptr<IndexedStringProperty> value)
{
set_indexed_property<IndexedStringProperty>(m_smap, name,
std::move(value));
}
template <typename T>
const std::map<std::string, std::shared_ptr<IndexedProperty<T>>>&
getProperties() const;
};
// Template specializations
template <>
inline const std::map<std::string, BoolProperty>&
Block::getProperties<BoolProperty>() const
{
return m_bmap;
}
template <>
inline const std::map<std::string, int>& Block::getProperties<int>() const
{
return m_imap;
}
template <>
inline const std::map<std::string, double>& Block::getProperties<double>() const
{
return m_rmap;
}
template <>
inline const std::map<std::string, std::string>&
Block::getProperties<std::string>() const
{
return m_smap;
}
template <>
inline const std::map<std::string,
std::shared_ptr<IndexedProperty<BoolProperty>>>&
IndexedBlock::getProperties() const
{
return m_bmap;
}
template <>
inline const std::map<std::string, std::shared_ptr<IndexedProperty<int>>>&
IndexedBlock::getProperties() const
{
return m_imap;
}
template <>
inline const std::map<std::string, std::shared_ptr<IndexedProperty<double>>>&
IndexedBlock::getProperties() const
{
return m_rmap;
}
template <>
inline const std::map<std::string,
std::shared_ptr<IndexedProperty<std::string>>>&
IndexedBlock::getProperties() const
{
return m_smap;
}
} // namespace mae
} // namespace schrodinger
| true |
b0a7089aab8d3a4a519623bebab1b61afe968ded | C++ | Woffee/acm | /CPP/2013-2015/HDOJ/又见GCD.cpp | UTF-8 | 521 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
//最大公约数
int Gcd(int m, int n)
{
return m == 0 ? n : Gcd(n % m, m );
}
int main()
{
int ncase;
int a, b, c;
scanf("%d", &ncase);
while(ncase--)
{
scanf("%d%d", &a, &b);
int temp = a / b;
for(int i = 2; ; ++i)
{
if(Gcd(temp, i) == 1)
{
printf("%d\n", i * b);
break;
}
}
}
return 0;
} | true |
5052a9def9e5e651741940ba22a9a3a809be0d4d | C++ | Prajakta1798/EngineeringPracticals-SE | /DSF Assignment/1/conv_prefix1.cpp | UTF-8 | 2,260 | 3.328125 | 3 | [] | no_license |
/**************************************************************
ASSIGNMENT NO:
ROLL NO: BATCH :
TITTEL: conversion of infix to prefix expression.
***********************************************************/
#include<iostream>
#include"stack.h"
#include<string.h>
using namespace std;
stack ob;
class postfix
{
public:
char *s;
void set_exp(char *str)
{
s = str;
}
void convert()
{
char opr, p[50], q[50];
int i = 0;
while (*s)
{
if (isdigit(*s) || isalpha(*s))
{
p[i++] = *s;
s++;
}
else if (*s == ')')
{
ob.push(*s);
s++;
}
else if (*s == '+' || *s == '-' || *s == '*' || *s == '/' || *s == '%' || *s == '^')
{
if (ob.top == NULL)
{
ob.push(*s);
s++;
}
else
{
opr = ob.pop();
while (priority(opr) >= priority(*s))
{
p[i++] = opr;
opr = ob.pop();
}
ob.push(opr);
ob.push(*s);
s++;
}
}
else if (*s == '(')
{
opr = ob.pop();
while (opr != ')')
{
p[i++] = opr;
opr = ob.pop();
}
s++;
}
}
while (ob.top != NULL)
{
opr = ob.pop();
p[i++] = opr;
}
i--;
int len = strlen(p);
len--;
for (int i = 0; len >= 0; i++, len--)
{
q[i] = p[len];
}
cout<<q;
}
int priority(char c)
{
if (c == '^')
return 3;
else if (c == '*' || c == '/' || c == '%')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return 0;
}
};
int main()
{
char str[50], pqr[50];
postfix OB;
cout << "Enter the infix expression : ";
cin >> str;
//cout << str;
int len = strlen(str);
len--;
for (int i = 0; len >= 0; i++, len--)
{
pqr[i] = str[len];
}
OB.set_exp(pqr);
cout << "\nPrefix expression is : ";
OB.convert();
return 0;
}
/*************************************************
OUTPUT:
it@IT-PL-5:~/Desktop$ g++ conv_prefix1.cpp
it@IT-PL-5:~/Desktop$ ./a.out
Enter the infix expression : (a+b^c)*d+e^5
Prefix expression is : +*+a^bcd^e5it@IT-PL-5:~/Desktop$
********************************/
| true |
7dcd24bd78acbf9a4a6ac3acf63682a48ad9bd1e | C++ | TNTantoine/TextRPG | /TextRPG/Classes/Character.cpp | UTF-8 | 2,658 | 3.578125 | 4 | [] | no_license | #include "Character.h"
#include <stdlib.h>
#include <iostream>
#include <random>
using namespace std;
Character::Character () : m_name ("DefaultName"), m_HP (10)
{
}
Character::Character (string name) : m_name (name), m_HP (10)
{
}
Character::Character (string name, int hp)
{
m_name = name;
m_HP = hp;
}
Character::Character (string name, int hp,const Weapon &Weapon)
{
m_name = name;
m_HP = hp;
m_Weapon = Weapon;
}
Character::~Character ()
{
}
Character::Character (const Character &characterToCopy)
{
m_name = characterToCopy.m_name;
m_HP = characterToCopy.m_HP;
m_Weapon = characterToCopy.m_Weapon;
}
void Character::receiveDmg (int nbDegats)
{
m_HP -= nbDegats;
if (m_HP < 0)
{
m_HP = 0;
}
cout << m_name << " now has " << m_HP << " HP" << endl << endl;
}
void Character::addHP (int nbHP)
{
if (m_HP <= 0)
{
cout << m_name << " has been resurrected !" << endl;
}
m_HP += nbHP;
cout << m_name << " has been healed " << nbHP << "HP and now has " << m_HP << "HP" << endl;
}
void Character::attack (Character &cible) const
{
default_random_engine generator (random_device{}());
uniform_int_distribution<int> distributionRngMultiplier (0, 10);
int rngMultiplier = distributionRngMultiplier (generator);
int tempDmg = m_Weapon.getDegats () * rngMultiplier;
cout << m_name << " attacks " << cible.m_name << " with " << m_Weapon.getName () << " RNG = " << rngMultiplier << endl;
if (tempDmg <= 0)
{
cout << tempDmg << " : The attack missed !" << endl << endl;
}
else if (tempDmg > 0 && tempDmg <= 3)
{
cout << tempDmg << " : Its not really effective..." << endl << endl;
}
else if (tempDmg > 3 && tempDmg < 8)
{
cout << tempDmg << " : The strike landed !" << endl << endl;
}
else if (tempDmg >= 8)
{
cout << tempDmg << " : Critical strike !" << endl << endl;
}
else
{
cout << endl;
}
cible.receiveDmg (tempDmg);
}
void Character::changeWeapon (Weapon &nouvelleWeapon)
{
m_Weapon = nouvelleWeapon;
cout << m_name << " equips the weapon " << m_Weapon.getName () << endl << endl;
}
void Character::displayStats () const
{
cout << "-----------------------------------" << endl;
cout << "| Stats of " << m_name << endl;
cout << "| HP : " << m_HP << endl;
cout << "| Weapon : " << m_Weapon.getName () << endl;
cout << "-----------------------------------" << endl << endl;
}
string Character::getName () const
{
return m_name;
}
int Character::getHP () const
{
return m_HP;
}
string Character::getEquippedWeapon () const
{
return m_Weapon.getName ();
}
bool Character::isAlive () const
{
bool temp;
if (m_HP <= 0)
{
temp = false;
}
else
{
temp = true;
}
return temp;
} | true |
b1ae02251ac1a497159f831699d9cbec2ff7c8c2 | C++ | aliushn/stereo-vision-toolkit | /src/camera/cameracontrol/cameracontrol/cameracontrol.ino | UTF-8 | 1,380 | 2.796875 | 3 | [
"MIT"
] | permissive | /*
* Copyright I3D Robotics Ltd, 2020
* Author: Ben Knight (bknight@i3drobotics.com)
*/
#define CAMERA_TRIGGER_1 3 //Phobos USB uses pin 12 / Phobos GigE uses pin 3
#define CAMERA_TRIGGER_2 2 //Phobos USB uses pin 12 / Phobos GigE uses pin 2
double frame_delay; // amount of time between triggered (1/fps)
int trigger_time = 10; // time for trigger to be registered by camera
double fps = 5; // inital fps
String inString = ""; // string to hold input
void setup() {
Serial.begin(115200);
// put your setup code here, to run once:
pinMode(CAMERA_TRIGGER_1, OUTPUT);
pinMode(CAMERA_TRIGGER_2, OUTPUT);
pinMode(LED_BUILTIN,OUTPUT);
}
void loop() {
frame_delay = 1000/fps;
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(CAMERA_TRIGGER_1, HIGH);
digitalWrite(CAMERA_TRIGGER_2, HIGH);
delay(trigger_time);
digitalWrite(LED_BUILTIN, LOW);
digitalWrite(CAMERA_TRIGGER_1, LOW);
digitalWrite(CAMERA_TRIGGER_2, LOW);
delay(frame_delay-trigger_time);
while (Serial.available() > 0) {
int inChar = Serial.read();
if (isDigit(inChar)) {
// convert the incoming byte to a char and add it to the string:
inString += (char)inChar;
}
// if you get a newline, print the string, then the string's value:
if (inChar == '\n') {
fps = inString.toInt();
// clear the string for new input:
inString = "";
}
}
}
| true |
1cb45f93a90513875b20fd770b28baef9370f5ca | C++ | LookingforMind/MyMind | /C++/8. Massives/Project1.0/Project1/Source.cpp | WINDOWS-1251 | 704 | 3.34375 | 3 | [] | no_license | /*1. , . */
#include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
const int string = 10;
const int column = 10;
int massive[string][column];
for (int i = 0; i < column; i++)
{
// cout << i;
for (int j = 1; j < string; j++)
{
// cout << j; //
// cout << massive[string][column] << " "; //
massive[i][j] = i + j; //
cout << massive[i][j] << " "; //
}
cout << endl;
}
cout << endl;
system("pause");
return (0);
} | true |