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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
487cb24ee814a57bfbf21e83bfca78889c3636e1 | C++ | ArthurLCastro/ModulosGSM | /examples/Envio-SMS/Envio-SMS.ino | UTF-8 | 1,479 | 2.890625 | 3 | [] | no_license | // Envio de SMS
// Arthur L. Castro
// Abril de 2019
// INCLUSÃO DE BIBLIOTECAS:
#include <ModulosGSM.h>
// DEFINIÇÕES:
#define RX_GSM1 8 // ligar o Pino 8 do Arduino no TX do Módulo "SIM808 EVB-V3.2"
#define TX_GSM1 7 // ligar o Pino 7 do Arduino no RX do Módulo "SIM808 EVB-V3.2"
#define intervalo 20000 // Intervalo entre os envios de SMS
// CRIAÇÃO DE OBJETOS - Para emular as comunicações Seriais nos pinos digitais definidos acima:
ModulosGSM meuGSM1;
SoftwareSerial serialGSM1(RX_GSM1, TX_GSM1);
// DECLARAÇÕES DE VARIÁVEIS GLOBAIS:
String numero = "Insira_aqui_o_numero_que_receberá_o_SMS"; // Define o numero que receberá o SMS
String msg = "Mensagem SMS enviada do Modulo GSM!"; // Define a Mensagem a ser transmitida
bool estadoSMS = false; // Indica se a Mensagem foi enviada com Sucesso
void setup(){
Serial.begin(9600); // Inicia a comunicação Serial a uma taxa de transmissão de 9600
serialGSM1.begin(9600); // Inicia a comunicação Serial Emulada a uma taxa de transmissão de 9600
meuGSM1.setupGSM(serialGSM1);
}
void loop(){
estadoSMS = meuGSM1.enviarSMS(numero, msg);
if(estadoSMS == true){
Serial.println("Mensagem enviada para " + numero + " :");
Serial.println(" -> " + msg);
} else {
Serial.println("[ERRO] Erro ao enviar SMS para " + numero);
}
delay(intervalo); // Intevalo entre envios
} | true |
ee7422b4bc0e5904f449ec789f253bb588cce363 | C++ | k-dx2/OOPs_lab_4thsem | /day3/graphadjlist.cpp | UTF-8 | 1,527 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct SubListNode{
int des;
SubListNode *next = NULL;
};
struct MainListNode{
SubListNode *head = NULL;
SubListNode *tail;
};
int main(void){
int V, E;
cout << "Enter the no. of vertices\n";
cin >> V;
cout << "Enter the no. of edges\n";
cin >> E;
int src,des;
MainListNode *srcList = new MainListNode[V];
for(int i=0; i<E; i++)
{
cin >> src >> des;
if(srcList[src].head == NULL){
srcList[src].head = new SubListNode;
srcList[src].head -> des = des;
srcList[src].tail = srcList[src].head;
}
else
{
srcList[src].tail -> next = new SubListNode;
srcList[src].tail = srcList[src].tail -> next;
srcList[src].tail -> des = des;
}
}
cout << "Displaying the List\n";
for(int i=0; i<V; i++)
{
cout << i << " ";
SubListNode *temp = srcList[i].head;
while(temp!=NULL)
{
cout << temp -> des << " ";
temp = temp -> next;
}
cout << "-" << endl;
}
return 0;
}
| true |
0181cc8428f965dc1aadf7f7e4f2fe6c7af598cf | C++ | baarmaley/bug-free-chainsaw | /src/lib/include/journal/journal_entry.hpp | UTF-8 | 843 | 2.640625 | 3 | [] | no_license | #pragma once
#include <journal/journal_entry_id.hpp>
#include <common/common_type.hpp>
#include <chrono>
#include <string>
namespace barmaley {
namespace lib {
enum class JournalEntryType
{
device_detected,
connection_lost,
connection_restored,
reconnect_detected,
bad_protocol,
ip_changed,
reboot_detect,
successful_request,
failed_request
};
std::string toString(JournalEntryType type);
class JournalEntry
{
public:
explicit JournalEntry(JournalEntryId id, JournalEntryType type, std::string text)
: id(id), type(type), text(std::move(text))
{
}
~JournalEntry() {}
JournalEntryId id;
JournalEntryType type;
std::chrono::system_clock::time_point createdDate = std::chrono::system_clock::now();
std::string text;
};
} // namespace lib
} // namespace barmaley
| true |
a3b9ad9813348ab94346faea289f42e0906fab45 | C++ | chuxuantinh/C-PLUS | /SuperEggDrop.cpp | UTF-8 | 390 | 2.8125 | 3 | [] | no_license | class Solution {
public:
int superEggDrop(int K, int N) {
vector<int> floors(K,1);
int counter = 2;
while (N > 1) {
for (int j = K - 1; j > 0; --j) floors[j] += floors[j-1] + 1;
floors[0] = counter;
if (floors[K-1] >= N) return counter;
++counter;
}
return counter-1;
}
};
| true |
a5971bc0d91c9b57ea911f8f77e626719cafa6c7 | C++ | RustamSafiulin/mnemo_designer | /elementsimplelistwidget.cpp | UTF-8 | 2,007 | 2.703125 | 3 | [] | no_license | #include "elementsimplelistwidget.h"
#include <QMimeData>
#include <QDrag>
#include <QApplication>
ElementSimpleListWidget::ElementSimpleListWidget(QListWidget *parent) :
QListWidget(parent)
{
setSpacing(5);
addElements();
}
void ElementSimpleListWidget::addElements() {
QListWidgetItem *lineItem = new QListWidgetItem(QIcon(":/images/lineitem.png"),trUtf8("Линия"));
QListWidgetItem *rectItem = new QListWidgetItem(QIcon(":/images/rectitem.png"),trUtf8("Прямоугольник"));
QListWidgetItem *ellipseItem = new QListWidgetItem(QIcon(":/images/ellipseitem.png"),trUtf8("Эллипс"));
QListWidgetItem *arrowItem = new QListWidgetItem(QIcon(":/images/arrowitem.png"),trUtf8("Стрелка"));
QListWidgetItem *polygonItem = new QListWidgetItem(QIcon(":/images/polygon.png"),trUtf8("Полигон"));
QListWidgetItem *textItem = new QListWidgetItem(QIcon(":/images/textitem.png"),trUtf8("Текст"));
addItem(lineItem);
addItem(rectItem);
addItem(ellipseItem);
addItem(arrowItem);
addItem(polygonItem);
addItem(textItem);
}
void ElementSimpleListWidget::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
startPos = event->pos();
}
QListWidget::mousePressEvent(event);
}
void ElementSimpleListWidget::mouseMoveEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton) {
int distance = (event->pos() - startPos).manhattanLength();
if (distance >= QApplication::startDragDistance())
startDrag();
}
QListWidget::mouseMoveEvent(event);
}
void ElementSimpleListWidget::startDrag() {
QListWidgetItem *item = currentItem();
if (item) {
QMimeData *mimeData = new QMimeData;
mimeData->setText(item->text());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(QPixmap(currentItem()->icon().pixmap(50,50)));
drag->start(Qt::MoveAction);
}
}
| true |
b639643bb825d1819fd1c33c83033f2705e829df | C++ | biprodas/OJ-Solutions | /UVa/10420 - List of Conquests.cpp | UTF-8 | 336 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
map<string, int> country;
int main(){
int t;
scanf("%d", &t);
while(t--){
string name, line;
cin>>name; getline(cin, line);
country[name]++;
}
for(auto a : country) printf("%s %d\n", a.first.c_str(), a.second);
return 0;
} | true |
9418973db9f695dec755ecc5a3f881da37fb510c | C++ | BruceKen2014/Dex | /DexBase/DexVertex.h | UTF-8 | 1,373 | 2.71875 | 3 | [] | no_license |
#ifndef _DEX_VERTEX_H
#define _DEX_VERTEX_H
#include <d3dx9math.h>
#include "../DexMath/DexVector3.h"
#include "DexColor.h"
typedef struct _stVertex0
{
D3DXVECTOR3 m_pos;
D3DCOLOR m_color;
public:
_stVertex0();
void SetColor(const DexColor& color);
void SetPos(const DexVector3& pos);
} stVertex0;
typedef struct _stVertex1
{
D3DXVECTOR3 m_pos;
D3DCOLOR m_color;
float m_u, m_v;
public:
_stVertex1();
_stVertex1(D3DXVECTOR3 pos, DexColor color, float u, float v);
void SetUV(float u, float v);
void SetColor(const DexColor& color);
void SetPos(const DexVector3& pos);
} stVertex1;
struct stVertex2
{
D3DXVECTOR3 m_pos;
D3DXVECTOR3 m_normal;
float m_u, m_v;
public:
stVertex2();
void SetUV(float u, float v);
void SetPos(const DexVector3& pos);
void SetNormal(const DexVector3& normal);
};
struct stVertex3
{
DexVector3 m_pos;
DexVector3 m_normal;
D3DCOLOR color;
float m_u, m_v;
public:
stVertex3();
stVertex3(const DexVector3& pos, const DexVector3& normal, float u, float v);
void SetColor(const DexColor& _color);
void SetUV(float u, float v);
void SetPos(const DexVector3& pos);
void SetNormal(const DexVector3& normal);
bool operator == (const stVertex3& p) const;
bool operator != (const stVertex3& p)const;
bool operator > (const stVertex3& p)const;
bool operator < (const stVertex3& p)const;
};
#endif // !_DEX_VERTEX_H
| true |
9d9c16a79f92ae463b0a05677faa071297e49fdb | C++ | R41fK/kuehmayer_project_1 | /src/MessageQueue.cpp | UTF-8 | 468 | 2.953125 | 3 | [
"BSL-1.0"
] | permissive | #include "Message.h"
#include "MessageQueue.h"
using namespace std;
void MessageQueue::push(Message message) {
lock_guard<mutex> lg{this->m};
this->message_queue.push(message);
this->empty.notify_one();
}
Message MessageQueue::pop() {
unique_lock<mutex> ul{this->m};
empty.wait(ul, [this]{return this->message_queue.size();});
Message return_message = this->message_queue.front();
this->message_queue.pop();
return return_message;
} | true |
76dafb4e370166b920058c18e5a7b5f8af7cf09a | C++ | yandayixia/Chamber_Crawler | /Source_Code/Goblin.cc | UTF-8 | 847 | 2.90625 | 3 | [] | no_license | #include "Enemy.h"
#include "Goblin.h"
#include "helper.h"
//The BeenStruck(Enemy Attacker)functions are VIRTUAL so that
//they can be overrided by the subclasses. It will ALWAYS be calling
//an Attack(...) function in the Enemy class and its subclasses.
void Goblin::BeenStruck(Enemy* Attacker) { Attacker->Attack(this); }
//Goblin's constructor. It will not take in a MyTile argument.
//If want to specify MyTile, call ModifyTile(Tile*) to do so.
Goblin::Goblin(int HP, int ATK, int DEF):
Hero("Goblin", HP, HP, ATK, DEF) {}
//Goblin's concrete constructor. It doesn't do anything special.
Goblin::~Goblin(){}
/*OnSlay() is overrided to +5 gold per kill.*/
void Goblin::OnSlay(){
int goldbonus = 5;
std::string gold = NumberToString(goldbonus);
ActionMsg += " PC earns " + gold + " pieces of bonus gold.";
ModifyGoldStash(goldbonus);
}
| true |
8701897a673e5294cfe211131a5404d451b13f19 | C++ | VladimirSlavic/NeuralEvolution | /genetics/mutation_operators/add_mutation.h | UTF-8 | 900 | 2.953125 | 3 | [] | no_license | //
// Created by elrond on 1/17/18.
//
#ifndef NEUROEVOLUTION_ADD_MUTATION_H
#define NEUROEVOLUTION_ADD_MUTATION_H
#include "abstract_mutation.h"
class AddMutator : public AbstractMutator {
public:
AddMutator(double sigma1, double sigma2):AbstractMutator(sigma1, sigma2), rng{rd()}{
}
void mutate(Chromosome &child, double probability) override {
std::normal_distribution<double> gaus_mutat(0.0,get_sig1());
std::uniform_real_distribution<double> random_mutat_prob(0.0, 1.0);
for (int i = 0; i < child.get_size(); i++) {
bool pass_ = random_mutat_prob(rng) <= probability;
if (pass_) {
double factor = gaus_mutat(rng);
child[i] += factor * get_sig1();
}
}
}
private:
std::random_device rd;
std::default_random_engine rng;
};
#endif //NEUROEVOLUTION_ADD_MUTATION_H
| true |
94172288e6ab11cd6e27ed513111c1346587536c | C++ | TrickyFatCat/beginning-cpp-course | /l233-challenge/l233-challenge.cpp | UTF-8 | 942 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
std::ifstream in_file {};
std::ofstream out_file {};
in_file.open("./files/romeoandjuliet.txt");
if(!in_file)
{
std::cerr << "Error! Couldn't open the file." << std::endl;
return 1;
}
out_file.open("./files/romeoandjuliet_v2.txt");
if(!out_file)
{
std::cerr << "Error! Couldn't create the file." << std::endl;
}
std::string line {};
size_t line_number {1};
const int line_number_width {8};
while(std::getline(in_file, line))
{
if(line.size() != 1)
{
out_file << std::setw(line_number_width) << std::left << line_number
<< line << std::endl;
line_number++;
}
else
{
out_file << line << std::endl;
}
}
in_file.close();
out_file.close();
return 0;
} | true |
853a8f2886a9d14b70944c466461dcd1b3f65304 | C++ | zhuhr213/a_c_shell_homework | /c_program_homework .cpp | UTF-8 | 14,044 | 2.78125 | 3 | [] | no_license | #include <fstream>
#include <string>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <pwd.h>
#include <memory.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
//Header files might be used
using namespace std;
#define MAX_LINE 80//longest cmd
#define MAX_NAME_LEN 100//longest username
#define MAX_PATH_LEN 1000//longest path
//declare global variabless
char *cmd_array[MAX_LINE/2+1];//inputing cmd
int cmd_cnt;//the number of strings in each cmd
//declare functions
//basic functions
void readcommand();//read cmd
int is_internal_cmd();//internal cmd
//self defined functions
void weicome();//welcome screen
void printprompt();//print cmd with path
int getcommandlen();//calculate the length of each cmd
void myquit();//just quit this shell
void myexit();//exit directly
void myclear();//like clear in bash
void mypwd();//like pwd in bash
void myecho();//like echo in bash
void mytime();//like time in bash
void mycd();//like cd in bash
void myhelp();//iike..help
void print_manual();//print user nanual,the son of help()
void mybatch();//sth like bat
void mydir();
void myls();//like ls in bash
void mycat();
void mymkdir();
void mywordcount();//print the number of charactors of files
void myrm();//
void myrmdir();//
void mytime();//
void mybatch();//i dont wanna do this
void myll();
void mypanel();
void myhelp();
//functions realised
void readcommand()//to read input cmd
{
int cnt = 0;//record the number of strings in cmd_array[]
char str[MAX_LINE];
char *helper;
memset(cmd_array,0,MAX_LINE/2+1);//clear it each times
fgets(str,MAX_LINE,stdin);
//fgets is safer cuz it checks for overflow
if(str[strlen(str)-1]=='\n')
{
str[strlen(str)-1]='\0';//replace'\n'with '\0'
}
helper=strtok(str," ");//use space to takeapart cmd
//function strtok is used to devide str into pieces with " "
//returns a pointer towards the first str
//returns null at the last one
while(helper!=NULL)//write into cmd_array
{
cmd_array[cnt]=(char*)malloc(sizeof(*helper));//havent initialize it so malloc it
strcpy(cmd_array[cnt++],helper);
helper=strtok(NULL," ");
//there are two pointers in this function
//the first one pointera points to the first str
//the second one points two the place where " " exists
//if the first parameter is NULL,begin checking from pointerb,not the begining
//so,the first time use it is to get the pointer poingting at the first str
//and then use it in the loops to get the latter strs
}
cmd_cnt=cnt;
}
int is_internal_cmd()//to check if the cmd belongs to this shell
//and use different function
{
if(cmd_array[0]==NULL)
{
return 0;//if no cmd inputs,do nothing
}
else if(strcmp(cmd_array[0],"bye")==0)
{
myquit();
}
else if(strcmp(cmd_array[0],"exit")==0)
{
myexit();
}//quit and exit
else if(strcmp(cmd_array[0],"cat")==0)
{
mycat();
return 1;
}
else if(strcmp(cmd_array[0],"clear")==0)
{
myclear();
return 1;
}
//else if(strcmp(cmd_array[0],"continue")==0)
//{
//print_continue_info();
//return 1;
//}//the continue cmd only works in loops
else if(strcmp(cmd_array[0],"pwd")==0)
{
mypwd();
return 1;
}
else if(strcmp(cmd_array[0],"echo")==0)
{
//check redirection option work on it later
myecho();
return 1;
}
else if(strcmp(cmd_array[0],"time")==0)
{
mytime();
return 1;
}
//else if(strcmp(cmd_array[0],"fenviron")==0)
else if(strcmp(cmd_array[0],"cd")==0)
{
mycd();
return 1;
}
else if(strcmp(cmd_array[0],"dir")==0)
{
mydir();
//return 1;
}
//else if(strcmp(cmd_array[0],"help")==0)
//else if(strcmp(cmd_array[0],"exec")==0)
//else if(strcmp(cmd_array[0],"umask")==0)
//else if(strcmp(cmd_array[0],"fg")==0)
//else if(strcmp(cmd_array[0],"bg")==0)
else if(strcmp(cmd_array[0],"myshell")==0)//bat(pi chu li)
{
if(cmd_cnt==1)//only one cmd input
{
printf("myshell: myshell: too few arguments\n");
return 1;
}
else if (cmd_cnt==2)
{
mybatch();
return 1;
}
else
{
printf("myshell: myshell: too many arguments\n");
return 0;
}
}
else if(strcmp(cmd_array[0],"help")==0)
{
mypanel();
return 1;
}
else if(strcmp(cmd_array[0],"ls")==0)
{
myls();
return 1;
}
else if(strcmp(cmd_array[0],"mkdir")==0)
{
mymkdir();
return 1;
}
else if(strcmp(cmd_array[0],"wc")==0)
{
mywordcount();
return 1;
}
else if(strcmp(cmd_array[0],"rm")==0)
{
myrm();
return 1;
}
else if(strcmp(cmd_array[0],"rmdir")==0)
{
myrmdir();
return 1;
}
else
{
printf("myshell: command not found\n");
return 0;
}
}
int getcommandlen()
{
int tot_len = 0;
for (int i = 0 ; i<cmd_cnt;i++)
{
tot_len+=strlen(cmd_array[i]);//spaces not counted in
}
return tot_len+cmd_cnt-1;//count in spaces,returns -1 when a single space inputs
}
void printprompt()
{
char hostname[MAX_NAME_LEN];
char pathname[MAX_PATH_LEN];
struct passwd *pwd;
pwd=getpwuid(getuid());
gethostname(hostname,MAX_NAME_LEN);
getcwd(pathname,MAX_PATH_LEN);
printf("myshell>\e[032m%s@%s:\e[0m",pwd->pw_name,hostname);
if (strncmp(pathname,pwd->pw_dir,strlen(pwd->pw_dir))==0)
{
printf("\e[036m~%s\e[0m",pathname+strlen(pwd->pw_dir));
}
else {
printf("\e[036m%s\e[0m",pathname);
}
if (geteuid()==0) {
printf("# ");
}
else {
printf("$ ");
}
}
void welcome()//weicome screen
{
printf("\e[35m welcome to myshell\e[0m\n");
printf("\e[35m it's a unix-like shell program made by Max.C\e[0m\n");
printf("\e[35m hope you enjoy it :)\e[0m\n");
}
void myquit()//friendly quit
{
printf("\e[33mThanks for using my shell!bye-bye!\e[0m\n");
sleep(1);
exit(0);
}
void myexit()//just exit
{
exit(0);
}
void myclear()
{
printf("\033[2J");//clear
printf("\033[H");//move the mouse to a proper positoin
}
//void print_continue_info()
//{
// printf("myshell: continue: only works in a 'for','while' or 'until' loop\n");
//}
void mypwd()//pwd
{
char pathname[MAX_PATH_LEN];
if(getcwd(pathname,MAX_PATH_LEN))//get the path
{
printf("%s\n",pathname);
}
else//if sth goes wrong
{
perror("myshell: getcwd");//report bug
exit(1);
}
}
void myecho()//如果输入太多字符会报错
{
char *variable = NULL;
char environment[MAX_PATH_LEN];
for(int i=1;i<cmd_cnt;i++)
{
variable = cmd_array[i];
if(variable[0] == '$')
{
strcpy(environment,variable+1);
char *buff=getenv(environment);
if(buff)
{
cout<<buff<<endl;
}
else
{
cout<<endl;
}
}
else
{
printf("%s\n",*(cmd_array+i));
}
}
}
//void echo_redirect()
void mydir()
{
char pathname[MAX_PATH_LEN];//save current path
DIR *dir;
struct dirent *dp;
if(!getcwd(pathname,MAX_PATH_LEN))//get path successfully or not
{
perror("myshell: getcwd");
exit(1);
}
dir=opendir(pathname);
//not sorted yet
char dname[1000];
string ntemp[1000];
int tok=0;
while((dp=readdir(dir))!=NULL)
{
strcpy(dname,dp->d_name);
ntemp[tok]=dname;
tok++;
}
sort(ntemp,ntemp+tok);
for(int i=0;i<tok;i++)
{
cout<<ntemp[i]<<"\n";
}
tok = 0;
}
void myls()
{
struct stat s;
char pathname[MAX_PATH_LEN];//save current path
DIR *dir;
struct dirent *dp;
if(!getcwd(pathname,MAX_PATH_LEN))//get path successfully or not
{
perror("myshell: getcwd");
exit(1);
}
dir=opendir(pathname);
char temp[1000];
while((dp=readdir(dir))!=NULL)
{
strcpy(temp,dp->d_name);
if(temp[0]!='.')
{
if(stat(dp->d_name,&s)==0)
{
if(s.st_mode&S_IFDIR)
{
printf("\e[34m%s \e[0m",dp->d_name);
}
else
{
printf("%s ",dp->d_name);
}
}
}
}
cout<<endl;
}
void mycd()
{
struct passwd *pwd;
//the passwd structure is defined in <pwd.h> as follows
//struct passwd{
//char *pw_name;//user name
//char *pw_passwd;//user password
//uid_t pw_uid;//user id
//gid_t pw_gid;//group id
//char *pw_gecos;//real name
//char *pw_dir;//home directory
//char *pw_shell;//shell program
char pathname[MAX_PATH_LEN];//save path
pwd=getpwuid(getuid());//getuid means get user's id
//getpwuid means get passwd of this user's id
if(cmd_cnt==1)//if there's only one cd cmd
{
strcpy(pathname,pwd->pw_dir);//get homepath from pw_dir in pwd
if(chdir(pathname)==-1)//if there's sth goes wrong
{
perror("myshell: chdir");
exit(1);
}
}
else if(cmd_cnt>2)
{
cout<<"myshell: cd: what are you,ninja?"<<endl;
}
else//if there's a directory
{
if(chdir(cmd_array[1])==-1)//if something wrong happends in chdir
{
perror("myshell: cd: ");
}
}
}//so a single cd makes it back to home directory
void mycat()
{
if(cmd_cnt==1)//only one single input
{
cout<<"myshell: cat: please input at least one file!\n";
}
else
{
struct stat s;
char buff;
int flag[cmd_cnt-1]={0},ifexists=0;
int frd;//file open index
for(int i=1;i<cmd_cnt;i++)
{
if(stat(cmd_array[i],&s)==0)
{
if(s.st_mode&S_IFDIR)
{
flag[i-1]=2;
continue;
}
else
{
if((frd=open(cmd_array[i],O_RDONLY))!=-1)
{
printf("%s:\n",cmd_array[i]);
while(read(frd,&buff,sizeof(char))!=0)
{
printf("%c",buff);//print characters
}
printf("\n");
flag[i-1]=1;
ifexists++;
}
}
}
}
if(ifexists<cmd_cnt-1)//check if there's unexisting one when multiple inputs
{
for(int j=0;j<cmd_cnt-1;j++)
{
if(flag[j]==0)
{
cout<<"myshell: cat: file "<<cmd_array[j+1]<<" does not exist"<<endl;
}
if(flag[j]==2)
{
cout<<"myshell: cat: "<<cmd_array[j+1]<<" is a directory"<<endl;
}
}
}
}
}
void mymkdir()
{
for(int i=1;i<cmd_cnt;i++)
{
if(mkdir(cmd_array[i],0744)==-1)
{
perror("myshell: mkdir: ");
}
}
}
void mywordcount()
{
if(cmd_cnt==1)
{
cout<<"myshell: wc: what do you wanna know?\n";
}
else
{
struct stat s;
char buff;
int flag[cmd_cnt-1]={0},ifexists=0,count=0;
int frd;
for(int i=1;i<cmd_cnt;i++)
{
if(stat(cmd_array[i],&s)!=0)
{
cout<<"myshell: wc: file "<<cmd_array[i]<<" does not exist"<<endl;
continue;
}
else
{
if(s.st_mode&S_IFDIR)
{
cout<<"myshell: wc: "<<cmd_array[i]<<" is a directory"<<endl;
}
else
{
if((frd=open(cmd_array[i],O_RDONLY))!=-1)
{
while(read(frd,&buff,sizeof(char))!=0)
{
count++;
}
cout<<"myshell: wc: "<<count<<" characters in "<<cmd_array[i]<<endl;
}
}
}
}
}
}
void myrm()
{
for(int i=1;i<cmd_cnt;i++)
{
if(remove(cmd_array[i])!=0)
{
perror("myshell: rm ");
}
}
}
void myrmdir()
{
for(int i=1;i<cmd_cnt;i++)
{
if((rmdir(cmd_array[i]))!=0)
{
perror("myshell: rmdir ");
}
}
}
void mytime()
{
int weekday;
int month;
time_t tvar;
struct tm *tp;
time(&tvar);//time_t time(time_t *t)
tp=localtime(&tvar);//get local time struct tm *localtime(const time_t *timer)
weekday=tp->tm_wday;
switch(weekday)
{
case 1:
cout<<"Mon ";
break;
case 2:
cout<<"Tue ";
break;
case 3:
cout<<"Wed ";
break;
case 4:
cout<<"Thu ";
break;
case 5:
cout<<"Fri ";
break;
case 6:
cout<<"Sat ";
break;
case 7:
cout<<"Sun ";
break;
}
month=1+tp->tm_mon;//the month in the structs begin with 0
switch(month)
{
case 1:
printf("Jan ");
break;
case 2:
printf("Feb ");
break;
case 3:
printf("Mar ");
break;
case 4:
printf("Apr ");
break;
case 5:
printf("May ");
break;
case 6:
printf("Jun ");
break;
case 7:
printf("Jul ");
break;
case 8:
printf("Aug ");
break;
case 9:
printf("Sep ");
break;
case 10:
printf("Oct ");
break;
case 11:
printf("Nov ");
break;
case 12:
printf("Dec ");
break;
}
printf("%d ",tp->tm_mday);
printf("%d:",tp->tm_hour);
printf("%d:",tp->tm_min);
printf("%d ",tp->tm_sec);
printf("CST ");
printf("%d\n",1900+tp->tm_year);
}
void mypanel()
{
printf("welcome to the panel of myshell, hope this works for you\n");
printf("\n");
printf("NAMES FORMATS DESCRIPTIONS\n");
printf("cd: cd [dir] go to a specified directory\n");
printf("echo: echo [args] or $[arg] print strings after echo,environment variables avaliable\n");
printf("exit: exit quit the shell directly\n");
printf("pwd: pwd print the current working directory\n");
printf("time: time show the current time in an elegant format\n");
printf("clear: clear clear the screen\n");
printf("dir: dir [dir] list the file names in the target directory\n");
printf("ls: ls list the files\n");
printf("help: help show the panel\n");
printf("bye: bye quit the shell with thank-you information\n");
printf("mkdir: mkdir [filename] create a directory in current directory\n");
printf("cat: cat [filename] show contents of files\n");
printf("wc: wc [filename] show the number of characters\n");
printf("rm: rm [file || directory name] remove it\n");
printf("rmdir: rmdir [directory] remove it\n");
fflush(stdout);
}
void mybatch()
{
cout<<"I haven't and don't want to and won't do this part.."<<endl;
}
int main()
{
int should_run=1;//when to end the outest loop
int cmd_len=0;//record the length of cmd
//int pos_after_pipe;//the position of pipe
//int bg;//the mark of bg
welcome();
while(should_run)
{
printprompt();
readcommand();
cmd_len=getcommandlen();
if(cmd_len>MAX_LINE)
{
printf("your command is too long!");
exit(1);
}
if(is_internal_cmd())
{
continue;
}
}
return 0;
}
| true |
a31cdffd06008a3f228fbd623239dabd1560edc4 | C++ | malvasan/aed-lab1 | /ordenacion/functores.cpp | UTF-8 | 1,003 | 3.6875 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*
class ascendente
{
public:
bool ordenar(int a, int b)
{
return a>b;
}
};
class descendente
{
public:
bool ordenar(int a, int b)
{
return a<b;
}
};
void cambiar(int* ptr1,int* ptr2)
{
int c=*ptr1;
*ptr1=*ptr2;
*ptr2=c;
}
template <class T,class O>
void ordn(T* arr,int tam)
{
--tam;
int i;
O objeto;
int *ptr;
while(tam!=0)
{
ptr=arr;
i=tam;
while(i!=0){
if(objeto.ordenar(*ptr,*(ptr+1))== true){
cambiar(ptr,ptr+1);
}
ptr++;
i--;
}
tam--;
}
}
void imprimir(int* arr,int tam)
{
for(int i=0;i<tam;i++)
cout<<arr[i]<<" ";
}
int main()
{
int arreglo[]={5,8,7,3,1,9,2,4,11,19};
ordn<int,ascendente>(arreglo,sizeof(arreglo)/4);
imprimir(arreglo,sizeof(arreglo)/4);
return 0;
}
*/
| true |
8e45021acc67c27240349d75b61235af6abac00c | C++ | Litao439420999/LeetCodeAlgorithm | /C++/MyQueue.cpp | UTF-8 | 1,210 | 3.609375 | 4 | [] | no_license | /**
* @File : MyQueue.cpp
* @Brief : 用栈实现队列
* @Link : https://leetcode-cn.com/problems/implement-queue-using-stacks/
* @Author : Wei Li
* @Date : 2021-07-25
*/
#include <iostream>
#include <stack>
class MyQueue
{
std::stack<int> in, out;
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x)
{
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
in2out();
int x = out.top();
out.pop();
return x;
}
/** Get the front element. */
int peek()
{
in2out();
return out.top();
}
void in2out()
{
if (out.empty())
{
while (!in.empty())
{
int x = in.top();
in.pop();
out.push(x);
}
}
}
/** Returns whether the queue is empty. */
bool empty()
{
return in.empty() && out.empty();
}
};
// --------------------------------
int main(int argc, char **argv)
{
// test on LeetCode online.
return 0;
}
| true |
84103e7188c0bc1f02246b3f885342671130265e | C++ | DavidPetr/Internship_Tasks | /STL_Algorithms/STL_Algorithms/Source.cpp | UTF-8 | 2,619 | 3.3125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ctime>
bool isPrime(int x)
{
if (x < 2)return false;
if (x == 2)return true;
if ((x & 1) == 0)return false;
for (int i = 3; i*i <= x; i += 2)
{
if (x%i == 0)return false;
}
return true;
}
int main(int argc, char** argv)
{
std::vector<int> V1 = { 1,2,3,4,5,6,7,8,9,10 };
std::vector<int> V2 = { 10,10,5,5,3,10,8,0,0,0 };
std::vector<int> V3;
/* Task 1
* Copy all odd numbers from V1 to V3
*/
//std::copy_if(V1.begin(), V1.end(), std::back_inserter(V3), [](int i) {return (i & 1) == 1; });
/* Task 2
* Copy V1 to V3 in reverse order
*/
//std::copy(V1.rbegin(), V1.rend(), std::back_inserter(V3));
/* Task 3 ???
* Replace elements from V1 to '$', if element value is 5
*/
//auto it = std::find(V1.begin(), V1.end(), 8);
//std::fill_n(it, V1.end() - it, 0);
/* Task 4
* V3[i]=V1[i]+1
*/
//std::transform(V1.begin(), V1.end(), std::back_inserter(V3), [](int i) {return i + 1; });
/* Task 5
* V3[i]=V1[i]+V2[i]
*/
//std::transform(V1.begin(), V1.end(),V2.begin(), std::back_inserter(V3), std::plus<int>());
/* Task 6
* Replace elements from V2 to 8, if element value is 5
*/
//std::replace(V2.begin(), V2.end(), 5, 8);
/* Task 7
* Replace elements from V2 to 4, if element value is prime
*/
//std::replace_if(V2.begin(), V2.end(), isPrime, 4);
/* Task 8
* Copy V1 to V3 in reverse order, without using std::copy_backward
*/
//std::reverse_copy(V1.begin(), V1.end(), std::back_inserter(V3));
/* Task 9
* Delete from V2 all repeated neighbors
*/
//auto ptr = std::unique(V2.begin(), V2.end(), [](int a, int b) {return a == b; });
//V2.erase(ptr, V2.end());
/* Task 10
* Generate random numbers in V2
*/
//std::srand(std::time(nullptr));
//std::generate(V2.begin(), V2.end(), std::rand);
/* Task 11 not done
* Delete from V2 all repeated neighbors, without using std::unique
*/
/* New version
auto it = V2.begin();
V2.erase(std::remove_if((it = std::adjacent_find(it, V2.end())), V2.end() - 1, [&it](int iter) { return iter == *(++it); }), V2.end() - 1);
*/
/* Old version
int i = 0;
auto ptr = V2.begin();
std::remove_if(V2.begin(), V2.end()-1,
[V2,&i,&ptr](int a)
{
if (a == V2[++i])
{
return 1;
}
else
{
ptr++;
return 0;
}
}
);
V2.erase(ptr, V2.end()-1);
*/
std::cout << "V1 elements ";
for (auto i : V1)
{
std::cout << i << " ";
}
std::cout << "\nV2 elements ";
for (auto i : V2)
{
std::cout << i << " ";
}
std::cout << "\nV3 elements ";
for (auto i : V3)
{
std::cout << i << " ";
}
getchar();
return 0;
}
| true |
a548a2f8350db854cfbeb4c8768d5c1de88e4aca | C++ | AndrewWayne/OI_Learning | /个位数计算.cpp | UTF-8 | 2,001 | 3.21875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
char in[30],stack[30],out[30];
int stop=0;
int outtop=-1;
void spush(int &top,char a){
stack[++top]=a;
}
void pop(int &top){
out[++outtop]=stack[top];
top--;
}
int pow(int di,int mi){
int outs=1;
for(int i=1;i<=mi;i++){
outs*=di;
}
return outs;
}
int hahahaha(char* func){
int s,f,stacks[30],top=0;
for(int i=0;i<strlen(func);i++){
if(func[i]-'0'>=0&&func[i]-'9'<=0){
stacks[++top]=func[i]-'0';continue;}
s=stacks[top];
f=stacks[--top];
if(func[i]=='+')
stacks[top]=f+s;
if(func[i]=='-')
stacks[top]=f-s;
if(func[i]=='*')
stacks[top]=f*s;
if(func[i]=='/')
stacks[top]=f/s;
if(func[i]=='^')
stacks[top]=pow(f,s);
}
printf("%d",stacks[1]);
return 0;
}
void Calc(int begin,int end){
for (int i=begin+1; i<end; i++) {
if (in[i]=='{') for (int j=i; j<=end; j++) if (in[j]=='}')Calc(i,j);
if (in[i]=='[') for (int j=i; j<=end; j++) if (in[j]==']')Calc(i,j);
if (in[i]=='(') for (int j=i; j<=end; j++) if (in[j]==')')Calc(i,j);
if (in[i]=='^') spush(stop,in[i]);
if (in[i]=='+'){
while(stop>0)
pop(stop);
spush(stop,in[i]);
}
if (in[i]=='-'){
while(stop>0)
pop(stop);
spush(stop,in[i]);
}
if (in[i]=='*'){
while(stop>0||(stack[stop]!='+'&&stack[stop]!='-'))
pop(stop);
spush(stop,in[i]);
}
if (in[i]=='/'){
while(stop>0||(stack[stop]!='+'&&stack[stop]!='-'))
pop(stop);
spush(stop,in[i]);
}
if (in[i]-'0'>=0&&in[i]-'9'<=0) out[++outtop]=in[i];
}
while(stop>0)
pop(stop);
}
int main(){
scanf("%s",in);
Calc(-1,strlen(in));
hahahaha(out);
}
| true |
2e41e38607863610bbdb466ad00e8a2647cc1728 | C++ | chirag-gurumurthy/Learning_C_plus_plus | /Exercise_Files/Chap02_Basic_Syntax/conditionals.cpp | UTF-8 | 285 | 3.265625 | 3 | [] | no_license | /* conditionals.cpp by Chirag
updated 2021-09-16 */
#include <cstdio>
int main()
{
int x = 42;
int y=7;
printf("value is %d\n", x<y);
if(x>y)
{
printf("condition is true");
}
else
{
puts("condition is false");
}
return 0;
}
| true |
9ef9e2255ff27f56f5fddb5c915d858c657e04fb | C++ | julien1619/MultiPong | /MultiPong/Balle.h | UTF-8 | 365 | 2.703125 | 3 | [] | no_license | #pragma once
class Balle
{
public:
Balle(void);
Balle(int masse, int rayon);
virtual ~Balle(void);
void update(int x, int y, int speed, int dirX, int dirY);
int getX();
int getY();
int getSpeed();
int getDirX();
int getDirY();
int getMasse();
int getRayon();
private:
int posX;
int posY;
int speed;
int masse;
int dirX;
int dirY;
int rayon;
};
| true |
8b2362bc34d3451311a18e2576755ae09202ce0a | C++ | zetarus/Americano | /Server/CGSF/Sample/SevenGameServer/SGTable.h | UTF-8 | 1,024 | 2.859375 | 3 | [] | no_license | // SGTable.h: interface for the SGTable class.
//
//////////////////////////////////////////////////////////////////////
#pragma once
class SGTable
{
public:
SGTable();
virtual ~SGTable();
EdgeCard CheckBoundary(int iCardType);
void InitializeTable();
void UpdateTableState(int iCardNum, int iCardType);
void SetSevenCard();
void SetSpadeCard(int iCard, int index){SpadeCardArray[index] = iCard;};
void SetHeartCard(int iCard, int index){HeartCardArray[index] = iCard;};
void SetDiamondCard(int iCard, int index){DiamondCardArray[index] = iCard;};
void SetCloverCard(int iCard, int index){CloverCardArray[index] = iCard;};
int * GetSpadeTableArray(){return SpadeCardArray;};
int * GetHeartTableArray(){return HeartCardArray;};
int * GetDiamondTableArray(){return DiamondCardArray;};
int * GetCloverTableArray(){return CloverCardArray;};
private:
int SpadeCardArray[MAX_CARD_NUM+1];
int HeartCardArray[MAX_CARD_NUM+1];
int DiamondCardArray[MAX_CARD_NUM+1];
int CloverCardArray[MAX_CARD_NUM+1];
}; | true |
1cd64c4cc7875e34e4db07aae7d3b30834c8213f | C++ | Arkadijus/OS | /OS/Process.h | UTF-8 | 3,844 | 2.9375 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <vector>
#include <string>
#include <memory>
#include "Kernel.h"
#include "Resource.h"
#include "CPU.h"
struct SavedRegisters
{
std::uint8_t SF = 0;
std::uint32_t AX = 0;
std::uint32_t BX = 0;
std::uint32_t PTR = 0;
std::uint16_t IC = 0;
};
enum class ProcessState
{
Running,
Ready,
Blocked,
Stopped,
BlockedStopped,
ReadyStopped
};
class Process
{
public:
Process(Process* parent, ProcessState initialState,
std::uint8_t priority, const std::string& name);
void saveRegisters();
void restoreRegisters();
virtual void run() = 0;
static void createProcess(Process* process, Process* parent, Element* element = nullptr);
static void destroyProcess(int ID);
static void stopProcess(const std::string& name);
static void activateProcess(const std::string& name);
static Process* getProcess(int ID);
static Process* getProcess(const std::string& name);
static void stopProcess(int ID);
static void activateProcess(int ID);
Process* getParent() { return m_parent; }
std::uint32_t getID() const { return m_ID; }
std::string getName() const { return m_name; }
ProcessState getState() const { return m_state; }
void setState(ProcessState state);
int getPriority() const { return m_priority; }
void setPriority(int priority) { m_priority = priority; }
void addElement(Element* element) { m_elementList.push_back(element); }
void deleteElements(Resource* resource);
std::vector<Resource*>& getCreatedResList() { return m_createdResList; }
void deleteResource(int ID);
protected:
std::uint32_t m_ID;
std::string m_name;
SavedRegisters m_savedRegisters;
std::uint8_t m_priority;
CPU* m_processor;
ProcessState m_state;
std::vector<Resource*> m_createdResList;
std::vector<Element*> m_elementList;
// owned elements
Process* m_parent;
std::vector<Process*> m_childProcesses;
Kernel& m_kernel;
};
class StartStopProcess : public Process
{
public:
StartStopProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "StartStop") {}
virtual void run() override;
};
class IdleProcess : public Process
{
public:
IdleProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "Idle") {}
virtual void run() {};
};
class ReadFromInterfaceProcess : public Process
{
public:
ReadFromInterfaceProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "ReadFromInterface") {}
virtual void run() override;
private:
std::string m_fileName;
Memory* m_memory = nullptr;
};
class MainProcProcess : public Process
{
public:
MainProcProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "MainProc") {}
virtual void run() override;
private:
Element* m_element = nullptr;
};
class VirtualMachineProcess : public Process
{
public:
VirtualMachineProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "VirtualMachine") {}
virtual void run() override;
private:
void executeInstruction();
bool test();
Element* m_element = nullptr;
VM* m_vm = nullptr;
};
class InterruptProcess : public Process
{
public:
InterruptProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "Interrupt") {}
virtual void run() override;
Element* m_element = nullptr;
};
class JobGovernorProcess : public Process
{
public:
JobGovernorProcess(Process* parent, ProcessState initialState,
std::uint8_t priority)
: Process(parent, initialState, priority, "JobGovernor") {}
virtual void run() override;
private:
Element* m_element = nullptr;
std::string* m_interrupt = nullptr;
};
| true |
362e1c3bb8e88444867f1d0a9934e032cd68afe7 | C++ | RishikaGhosh/ProjectEuler | /projecteuler_4.cpp.cpp | UTF-8 | 445 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool ispal(int n)
{
long long num,digit,rev=0;
num=n;
while(num!=0)
{
digit=num%10;
rev=(rev*10)+digit;
num/=10;
}
if(n==rev)
{
return true;
}
else
return false;
}
int main()
{
long long n;
long long max=0;
for(int i=999;i>=100;i--)
{
for(int j=999;j>=100;j--)
{
n=i*j;
if(ispal(n)&&n>max)
{
max=n;
}
}
}
cout<<max<<endl;
} | true |
200dbfd38004b6f532e333d271e60300906342d0 | C++ | tiny656/PAT | /PAT (Advanced Level) Practice/1013_Battle Over Cities (25).cpp | UTF-8 | 1,335 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define N 1005
int matrix[N][N];
int tmp[N][N];
int vis[N];
int partNum;
void dfs(int x,int n)
{
if(!vis[x])
{
//cout << x << endl;
vis[x] = 1;
for(int i = 1; i <= n; i++)
{
if(tmp[x][i] && !vis[i])
{
dfs(i,n);
}
}
}
}
void f(int x,int n)
{
int i,j;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
if(i == x || j == x) tmp[i][j] = 0;
else tmp[i][j] = matrix[i][j];
}
}
partNum = 0;
memset(vis,0,sizeof(vis));
for(i = 1; i <= n; i++)
{
if(!vis[i])
{
dfs(i,n);
//cout << "ok" << endl;
partNum++;
}
}
cout << partNum-2 << endl;
}
int main()
{
int n,m,k,i,j,a,b,c;
while(cin >> n >> m >> k)
{
for(i = 1; i <= n; i++,matrix[i][i] = 1)
for(j = 1; j <= n; j++)
{
matrix[i][j] = 0;
}
for(i = 0; i < m; i++)
{
cin >> a >> b;
matrix[a][b] = matrix[b][a] = 1;
}
for(i = 1; i <= k; i++)
{
cin >> c;
f(c,n);
}
}
return 0;
}
| true |
8e0847ec03bd07f123df2671a1fb2eb115778d10 | C++ | ydakoukn/StrongBox | /EnvironmentMap/EnvironmentMap/CharacterBase.cpp | SHIFT_JIS | 4,743 | 2.953125 | 3 | [] | no_license | #include "CharacterBase.h"
namespace Character{
// 摜̑
const int CharacterBase::m_numberOfImage = 4;
// ړ̘Azz
std::unordered_map< MyApplication::AppController::Input, CharacterBase::Position> CharacterBase::m_inputMove;
CharacterBase::CharacterBase():
m_size(20),
m_waitMove(0){
// Azz̓o^ //
// ړp //
//
m_inputMove[MyApplication::AppController::Input::eKeyUp].x = 0.0f;
m_inputMove[MyApplication::AppController::Input::eKeyUp].y = -0.1f;
m_inputMove[MyApplication::AppController::Input::eKeyUp].direction = CharacterBase::Direction::eUp;
//
m_inputMove[MyApplication::AppController::Input::eKeyDown].x = 0.0f;
m_inputMove[MyApplication::AppController::Input::eKeyDown].y = 0.1f;
m_inputMove[MyApplication::AppController::Input::eKeyDown].direction = CharacterBase::Direction::eDown;
//
m_inputMove[MyApplication::AppController::Input::eKeyLeft].x = -0.1f;
m_inputMove[MyApplication::AppController::Input::eKeyLeft].y = 0.0f;
m_inputMove[MyApplication::AppController::Input::eKeyLeft].direction = CharacterBase::Direction::eLeft;
// E
m_inputMove[MyApplication::AppController::Input::eKeyRight].x = 0.1f;
m_inputMove[MyApplication::AppController::Input::eKeyRight].y = 0.0f;
m_inputMove[MyApplication::AppController::Input::eKeyRight].direction = CharacterBase::Direction::eRight;
// ͂Ȃ
m_inputMove[MyApplication::AppController::Input::eNull].x = 0.0f;
m_inputMove[MyApplication::AppController::Input::eNull].y = 0.0f;
m_inputMove[MyApplication::AppController::Input::eNull].direction = CharacterBase::Direction::eNull;
}
//
///
float CharacterBase::GetX()const{
return m_position.x;
}
//
///
float CharacterBase::GetY()const{
return m_position.y;
}
//
///
void CharacterBase::SetX(const float xx){
m_position.x = xx;
}
//
///
void CharacterBase::SetY(const float yy){
m_position.y = yy;
}
CharacterBase::Position CharacterBase::GetPostion()const{
return m_position;
}
//
///
//
void CharacterBase::SetStartPosition(const CharacterBase::Position position){
m_position = position;
}
//
///
// ړp
void CharacterBase::Move(const Position position){
m_position.x += position.x;
m_position.y += position.y;
m_direction = position.direction;
}
//
///
// Aj[VĐ //
void CharacterBase::AnimationRender(){
// Aj[Vp
m_waitAnimation++;
if (m_waitAnimation > 20)
{
m_animationCount++;
// ۂ0Ԗڂ琔̂1}CiXl
if (m_animationCount > m_numberOfImage - 1)
{
m_animationCount = 0;
}
m_waitAnimation = 0;
}
const float x = GetX()*m_size;
const float y = GetY()*m_size;
const float width = (GetX()+1) * m_size;
const float height = (GetY()+1) * m_size;
if (m_direction == Direction::eNull) m_direction = m_prevDirection;
switch (m_direction)
{
case Direction::eUp:
DrawExtendGraph(x, y,
width, height, GetUpImage(m_animationCount), TRUE);
m_prevDirection = Direction::eUp;
break;
case Direction::eDown:
DrawExtendGraph(x, y,
width, height, GetDownImage(m_animationCount), TRUE);
m_prevDirection = Direction::eDown;
break;
case Direction::eLeft:
DrawExtendGraph(x, y,
width, height, GetLeftImage(m_animationCount), TRUE);
m_prevDirection = Direction::eLeft;
break;
case Direction::eRight:
DrawExtendGraph(x, y,
width, height, GetRightImage(m_animationCount), TRUE);
m_prevDirection = Direction::eRight;
break;
default:
break;
}
}
//
///
// ړ //
void CharacterBase::MoveDirection(const MyApplication::AppController::Input input){
this->Move(m_inputMove[input]);
}
// 摜̃Qb^[ //
//
///
int CharacterBase::GetUpImage(const int number)const{
return m_imageTable[number].m_upImage;
}
//
///
int CharacterBase::GetDownImage(const int number)const{
return m_imageTable[number].m_downImage;
}
//
///
int CharacterBase::GetLeftImage(const int number)const{
return m_imageTable[number].m_leftImage;
}
//
///
int CharacterBase::GetRightImage(const int number)const{
return m_imageTable[number].m_rightImage;
}
// 摜ǂݍ //
void CharacterBase::SetImage(const CharacterBase::ImagePassTable& pass, const int number){
m_imageTable[number].m_upImage = LoadGraph(pass.m_upImagePass.c_str()); //
m_imageTable[number].m_downImage = LoadGraph(pass.m_downImagePass.c_str()); //
m_imageTable[number].m_rightImage = LoadGraph(pass.m_rightImagePass.c_str()); // E
m_imageTable[number].m_leftImage = LoadGraph(pass.m_leftImagePass.c_str()); //
}
} | true |
23eae06314c934f864901943f73e385b86d5e3b3 | C++ | avnat/gsoc2012-kdiamond | /src_qml/board.cpp | UTF-8 | 11,074 | 3.0625 | 3 | [] | no_license | #include "board.h"
#include <QGraphicsObject>
// Defining the number of rows and columns in the grid
int ROWS =8;
int COLUMNS=8;
int BOARD_ITEMS =ROWS*COLUMNS;
int DIAMOND_COUNT = 5;
#define MIN_MATCHES 3
#define MAX_MATCHES 5
Board::Board(QObject *parent) :
QObject(parent),
iDifficultyLevel(Medium)
{
// Empty the string lists
iBoarditemList.clear();
iBoarditemList_int.clear();
changeTheme(3);
// Initializing iBoarditemList with diamonds
setDiamonds();
}
Board::~Board()
{
}
void Board::setDiamonds()
{
/* Setting up the iBoarditemList, iBoarditemList_int such
that no 3 similar diamonds are adjacent */
// Keeping track of past 3 generated diamonds
int random_number = -1;
int last_random_number = -1;
int pre_last_random_number = -1;
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
while(iBoarditemList_int.length()<BOARD_ITEMS)
{
// Generating random diamonds
random_number = qrand()%DIAMOND_COUNT;
// Conditions checking that no 3 similar diamonds should be adjacent
// checking rows
if(iBoarditemList_int.length()>1)
{
if(random_number == last_random_number && last_random_number == pre_last_random_number)
continue;
}
// checking columns
if(getRow(iBoarditemList_int.length())>1)
{
if(random_number == iBoarditemList_int[iBoarditemList_int.length()-COLUMNS] && random_number == iBoarditemList_int[iBoarditemList_int.length()-(2*COLUMNS)])
continue;
}
// Appending image source to iBoarditemList according to the random_number generated
iBoarditemList.append(diamondList.at(random_number));
// Appending random number to iBoarditemList_int
iBoarditemList_int.append(random_number);
pre_last_random_number = last_random_number;
last_random_number = random_number;
}
}
QStringList Board::getModel()
{
/* Returns list of image sources of diamonds */
return iBoarditemList;
}
void Board::makeMove(int prev_diamond, int current_diamond)
{
/* Swaping positions of 2 diamonds after user's move */
iPreDiamond = prev_diamond;
iCurrDiamond = current_diamond;
iBoarditemList.swap(prev_diamond, current_diamond);
iBoarditemList_int.swap(prev_diamond, current_diamond);
//Updating gridView model
updateModel(iBoarditemList);
}
void Board::check_move()
{
/* Checking if it is row move or a column move */
// Stores the row and column index of previous diamond and current diamond
int pre_row, pre_col, curr_row, curr_col;
pre_row = getRow(iPreDiamond);
pre_col = getColumn(iPreDiamond);
curr_row = getRow(iCurrDiamond);
curr_col = getColumn(iCurrDiamond);
// Stores 1 if similar diamonds were found during row or column move else 0
int tmp1 = 0, tmp2 = 0, tmp3 = 0;
// Row operation
if (pre_row == curr_row)
{
tmp1=rowMove(pre_row);
tmp2=colMove(pre_col);
tmp3=colMove(curr_col);
// Swap diamonds only if there are 3 similar diamonds adjacent
if(tmp1==1 && tmp2==1 && tmp3==1)
{
iBoarditemList.swap(iCurrDiamond,iPreDiamond);
iBoarditemList_int.swap(iCurrDiamond,iPreDiamond);
//Updating gridView model
updateModel(iBoarditemList);
}
}
// Column operation
else if (pre_col == curr_col)
{
tmp1=colMove(pre_col);
tmp2=rowMove(curr_row);
tmp3=rowMove(pre_row);
// Swap diamonds only if there are similar diamonds adjacent
if(tmp1==1 && tmp2==1 && tmp3==1)
{
iBoarditemList.swap(iCurrDiamond,iPreDiamond);
iBoarditemList_int.swap(iCurrDiamond,iPreDiamond);
//Updating gridView model
updateModel(iBoarditemList);
}
}
}
void Board::fillGaps_rows(QList<int> aSameList)
{
/* Fill gaps from top in rows */
QList<int> empty_diamonds_List, zero_row_List;
for (int i=0; i<aSameList.count(); i++)
{
if (getRow(aSameList.at(i)) != 0)
{
iBoarditemList_int[aSameList.at(i)] = iBoarditemList_int[aSameList.at(i)-COLUMNS];
iBoarditemList[aSameList.at(i)] = iBoarditemList[aSameList.at(i)-COLUMNS];
if (aSameList.at(i)-COLUMNS>=0)
{
empty_diamonds_List.append(aSameList.at(i)-COLUMNS);
}
}
else if (getRow(aSameList.at(i)) == 0)
{
zero_row_List.append(aSameList.at(i));
}
}
updateModel(iBoarditemList);
if (empty_diamonds_List.length()>0)
{
fillGaps_rows(empty_diamonds_List);
}
// Generating new diamonds for the 0th row of the grid
if (zero_row_List.length()>0)
{
generateDiamonds(zero_row_List);
}
}
void Board::fillGaps_columns(QList<int> aSameList)
{
/* Fill gaps from top in columns */
QList<int> zero_row_List;
for (int i=0; i<aSameList.count(); i++)
{
if (aSameList.at(i)-(COLUMNS*aSameList.length())>=0)
{
iBoarditemList_int[aSameList.at(i)] = iBoarditemList_int[aSameList.at(i)-(COLUMNS*aSameList.length())];
iBoarditemList[aSameList.at(i)] = iBoarditemList[aSameList.at(i)-(COLUMNS*aSameList.length())];
zero_row_List.append(aSameList.at(i)-(COLUMNS*aSameList.length()));
}
else
{
zero_row_List.append(aSameList.at(i));
}
}
updateModel(iBoarditemList);
// Generating new diamonds for the top most diamonds in columns
if (zero_row_List.length()>0)
{
generateDiamonds(zero_row_List);
}
}
int Board::rowMove(int row_index)
{
/* Checking similar diamonds for row move */
// Stores indices of similar diamonds
QList<int> SameList;
int count=0; int index =-1;
for (int i =(row_index*COLUMNS)+1; i<(row_index+1)*COLUMNS; i++)
{
if (iBoarditemList_int.at(i-1)==iBoarditemList_int.at(i))
{
index = i;
count++;
}
else{
if (count>=MIN_MATCHES-1)
{
for (int i=0; count>-1; count--, i++)
{
SameList.append(index-i);
}
}
count =0;
}
}
// for the last element in the row
if (count>=MIN_MATCHES-1)
{
for (int i=0; count>-1; count--, i++)
{
SameList.append(index-i);
}
}
if (SameList.count()>=MIN_MATCHES){
// emit signal for adding score to gamestate in the parent
emit addPoints(SameList.count());
}
else
{
// No 3 similar diamonds found adjacent return 1 else 0
return 1;
}
fillGaps_rows(SameList);
return 0;
}
int Board::colMove(int col_index)
{
/* Checking similar diamonds for column move */
// Stores indices of similar diamonds
QList<int> SameList;
int count=0; int index =-1;
for (int i = col_index+COLUMNS; i<=col_index+COLUMNS*(COLUMNS-1); i=i+COLUMNS)
{
if (iBoarditemList_int.at(i-COLUMNS)==iBoarditemList_int.at(i))
{
index = i;
count++;
}
else{
if (count>=MIN_MATCHES-1)
{
for (int i=0; count>-1; count--, i=i+COLUMNS)
{
SameList.append(index-i);
}
}
count =0;
}
}
// for the last element in the row
if (count>=MIN_MATCHES-1)
{
for (int i=0; count>-1; count--, i=i+COLUMNS)
{
SameList.append(index-i);
}
}
if (SameList.count()>=MIN_MATCHES){
// Emit signal for adding score to gamestate in the parent
emit addPoints(SameList.count());
}
else
{
// No 3 similar diamonds found adjacent return 1 else 0
return 1;
}
fillGaps_columns(SameList);
return 0;
}
void Board::generateDiamonds(QList<int> aList)
{
/* Generating new diamonds at given list of indices */
int last_random_number = -1;
int random_number = -1;
int i =0;
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
while(i<aList.length())
{
last_random_number = random_number;
random_number = qrand()%DIAMOND_COUNT;
if (random_number != last_random_number)
{
iBoarditemList[aList.at(i)] = diamondList.at(random_number);
iBoarditemList_int[aList.at(i)] = random_number;
i++;
}
}
updateModel(iBoarditemList);
// Rechecking rows for similar diamonds after generation
for (int i=ROWS-1; i>=0; i--)
{
rowMove(i);
}
// Rechecking columns for similar diamonds after generation
for(int i=COLUMNS-1;i>=0;i--)
{
colMove(i);
}
}
int Board::getRow(int diamondIndex)
{
/* Returns row number of diamond */
return diamondIndex/COLUMNS;
}
int Board::getColumn(int diamondIndex)
{
/* Returns column number of diamond */
return diamondIndex%COLUMNS;
}
void Board::InitializeNewGame()
{
/* Initializes a new game, clear all the previous lists and variables*/
iBoarditemList.clear();
iBoarditemList_int.clear();
iPreDiamond = -1;
iCurrDiamond = -1;
setDiamonds();
updateModel(iBoarditemList);
}
void Board::ChangeDifficultlyLevel(int difficultyLevel)
{
/* Change the difficulty level of the game*/
iDifficultyLevel = DifficultyLevel(difficultyLevel);
ROWS = boardSizes[difficultyLevel];
COLUMNS = boardSizes[difficultyLevel];
BOARD_ITEMS = ROWS * COLUMNS;
DIAMOND_COUNT = diamondCount[difficultyLevel];
InitializeNewGame();
}
QString Board::getBoardBg()
{
/* Return the background of the theme */
return iBoardBg;
}
void Board::changeTheme(int theme)
{
/* Change Theme */
diamondList.clear();
// Theme - Egyptian
if (theme==1)
{
diamondList<<"images/egyptian/1.png"
<<"images/egyptian/2.png"
<<"images/egyptian/3.png"
<<"images/egyptian/4.png"
<<"images/egyptian/5.png"
<<"images/egyptian/6.png";
iBoardBg = "images/egyptian/egyptian_bg.png";
}
// Theme - Funny zoo
else if (theme==2)
{
diamondList<<"images/zoo/1.png"
<<"images/zoo/2.png"
<<"images/zoo/3.png"
<<"images/zoo/4.png"
<<"images/zoo/5.png"
<<"images/zoo/6.png";
iBoardBg = "images/zoo/zoo_bg.png";
}
// Theme - Diamonds
else{
diamondList<<"images/diamonds/1.png"
<<"images/diamonds/2.png"
<<"images/diamonds/3.png"
<<"images/diamonds/4.png"
<<"images/diamonds/5.png"
<<"images/diamonds/6.png";
iBoardBg = "images/diamonds/diamond_bg.png";
}
}
| true |
590f432d02433d71cdc16c70d161dde84a11a0e7 | C++ | linxin8/OS | /disk/directory.cpp | UTF-8 | 4,400 | 3.125 | 3 | [
"MIT"
] | permissive | #include "disk/directory.h"
#include "disk/file.h"
#include "disk/inode.h"
#include "kernel/memory.h"
#include "lib/debug.h"
#include "lib/stdio.h"
#include "lib/string.h"
DirectoryEntry::DirectoryEntry() : name(""), inode_no(-1), type(none) {}
DirectoryEntry::DirectoryEntry(const char* name, int32_t inode_no, Type type)
{
ASSERT(name != nullptr);
ASSERT(strlen(name) <= MAX_FILE_NAME_LEN);
memset((void*)this->name, 0, sizeof(this->name));
strcpy(this->name, name);
this->inode_no = inode_no;
this->type = type;
}
bool DirectoryEntry::is_valid() const
{
return type != none;
}
bool DirectoryEntry::is_directory() const
{
return type == directory;
}
bool DirectoryEntry::is_file() const
{
return type == file;
}
DirectoryEntry::Type DirectoryEntry::get_type() const
{
return type;
}
int32_t DirectoryEntry::get_inode_no() const
{
return inode_no;
}
const char* DirectoryEntry::get_name() const
{
return name;
}
DirectoryEntry Directory::find_entry(const char* name)
{
uint32_t count = get_entry_count();
for (uint32_t i = 0; i < count; i++)
{
auto entry = read_entry(i);
if (entry.is_directory())
{ //是目录
if (strcmp(entry.get_name(), name) == 0)
{
return entry;
}
}
}
return DirectoryEntry();
}
const uint32_t Directory::index_max = 140 * 512 / sizeof(DirectoryEntry);
Directory::Directory(Inode* inode) : inode(Inode::copy_instance(inode)) {}
Directory Directory::open_root_directory(Partition* partition)
{
return Directory(partition, 0);
}
Directory::Directory(Partition* partition, int32_t inode_no) : inode(Inode::get_instance(partition, inode_no)) {}
Directory::Directory() : inode(nullptr) {}
Directory::Directory(const Directory& directory) : inode(Inode::copy_instance(directory.inode)) {}
Directory::~Directory()
{
if (inode != nullptr)
{
Inode::remove_instance(inode);
inode = nullptr;
}
}
void Directory::insert_directory(const char* name)
{
if (find_entry(name).is_valid())
{
printk("%s is already exist\n", name);
}
else
{
auto no = inode->get_partition()->alloc_inode();
insert_entry(DirectoryEntry{name, no, DirectoryEntry::directory});
auto directory = open_directory(name);
ASSERT(directory.is_valid());
directory.insert_entry(DirectoryEntry{".", no, DirectoryEntry::directory});
directory.insert_entry(DirectoryEntry{"..", inode->get_no(), DirectoryEntry::directory});
}
}
void Directory::insert_file(const char* name)
{
if (find_entry(name).is_valid())
{
printk("%s is already exist\n", name);
}
else
{
insert_entry(DirectoryEntry{name, inode->get_partition()->alloc_inode(), DirectoryEntry::file});
}
}
bool Directory::is_empty()
{
return get_entry_count() != 2;
}
bool Directory::is_valid() const
{
return inode != nullptr;
}
Partition* Directory::get_partition() const
{
return inode->get_partition();
}
uint32_t Directory::get_entry_count() const
{
ASSERT(inode != nullptr);
ASSERT(inode->get_size() % sizeof(DirectoryEntry) == 0);
return inode->get_size() / sizeof(DirectoryEntry);
}
DirectoryEntry Directory::read_entry(uint32_t index)
{
ASSERT(index < get_entry_count());
DirectoryEntry entry;
uint32_t byte_offset = sizeof(DirectoryEntry) * index;
inode->read(byte_offset, &entry, sizeof(DirectoryEntry));
ASSERT(entry.is_valid()); //确保目录项存在
return entry;
}
void Directory::write_entry(uint32_t index, const DirectoryEntry& entry)
{
ASSERT(index < get_entry_count());
ASSERT(entry.is_valid()); //确保目录项存在
uint32_t byte_offset = sizeof(DirectoryEntry) * index;
inode->write(byte_offset, &entry, sizeof(DirectoryEntry));
}
void Directory::insert_entry(const DirectoryEntry& entry)
{
ASSERT(entry.is_valid());
uint32_t index = get_entry_count();
uint32_t byte_offset = sizeof(DirectoryEntry) * index;
inode->write(byte_offset, &entry, sizeof(DirectoryEntry));
}
Directory Directory::open_directory(const char* name)
{
auto entry = find_entry(name);
if (entry.is_valid() && entry.is_directory())
{
return Directory(inode->get_partition(), entry.get_inode_no());
}
return Directory();
}
| true |
00e662f9da37e921fa616cdec77f0db09712e7f4 | C++ | codinglq/Html_Analyse | /FilterTagMore.cpp | GB18030 | 4,466 | 2.515625 | 3 | [] | no_license | #include "HtmlAnalyse.h"
/*20131130ʮһ㶨 ҿ
*coding by lq
*һ ҵ 㷨Че㡣еͰ عŻһ°20131201 write by lq
**/
char * FilterTagMore(int * i_TagArray,char *c_buf,char *c_Tag){
string s_buf=c_buf;
char *c_r_buf=(char *)malloc(sizeof(char)*s_buf.length());
if (!i_TagArray)
{
cout<<"Ĵǿյİ"<<endl;
exit(-1);
}
else
{
cout<<"ʼ"<<endl;
int i_TagPos=0;
int i_Filter=0;
int i_LastLen=0;
//λ˵
while(i_TagArray[i_TagPos]!=-2){//ƥн -2
// cout<<strlen(c_Tag)<<endl;
int j=s_buf.find('>',i_TagArray[i_TagPos]);
if (s_buf.find('>',(i_TagArray[i_TagPos]-i_LastLen))==(i_TagArray[i_TagPos]-i_LastLen+strlen(c_Tag)))
{
i_TagPos++;//λòù //˵
}else{
//Ҫ˲ҹ˵
i_Filter=s_buf.find('>',i_TagArray[i_TagPos]-i_LastLen);
s_buf=s_buf.replace(i_TagArray[i_TagPos]-i_LastLen+strlen(c_Tag),i_Filter-(i_TagArray[i_TagPos]-i_LastLen)-strlen(c_Tag),"");
/* i_LastLen=i_LastLen+i_Filter-i_TagArray[i_TagPos]-strlen(c_Tag);*/
i_LastLen=i_LastLen+i_Filter-(i_TagArray[i_TagPos]-i_LastLen)-strlen(c_Tag);
i_TagPos++;
}
/* s_buf=s_buf.replace(i_TagArray[i_TagPos]+4);*/
}
// i_TagPos++;
}
strcpy(c_r_buf,s_buf.c_str());
return c_r_buf;
}
/************************************************************************/
/* FileterTagOther˼ ԼҪıǩ */
/************************************************************************/
int FilterTagOther(string & s_buf,int &i_StartPos,int &i_EndPos){
if((i_StartPos<i_EndPos)&&(s_buf.size())){
s_buf.replace(i_StartPos,(i_EndPos-i_StartPos)+1,"");
//i_StartPos++;// i_StartPosԼѾһ
i_EndPos=i_StartPos;
}else{
cout<<"i_StartPos>=i_EndPos ERROR!!!!"<<endl;
}
return i_StartPos;
}
/************************************************************************/
/* жs_TagǷڶ ȻͿԾǷ */
/************************************************************************/
int b_FindQueue(vector<string> OtherTagQueue,string s_Tag){
int i_QueueSize=0;
while (i_QueueSize<OtherTagQueue.size())
{
if (s_Tag==OtherTagQueue.at(i_QueueSize))
{
return 1;
break;
}else{
i_QueueSize++;
}
}
return 0;
}
/***************************************************************************************************************************************************************/
/* int JudgeFilterPoint(int &i_Start,int &i_End,string s_buf,vector<string>OtherTagQueue);//жs_bufдi_StartʼҶλǷҪ */
/***************************************************************************************************************************************************************/
int JudgeFilterPoint(int &i_StartPos,int &i_EndPos,string &s_buf,vector<string>OtherTagQueue){
if (s_buf.size()&&(i_StartPos>=0))
{
//int i_bufSize=0;
while(i_StartPos!=-1&&i_EndPos!=-1){
int i_QueueSize=0;
if (s_buf.substr(i_StartPos,1)!="<")
{
i_EndPos=s_buf.find('<',i_StartPos);
s_buf.replace(i_StartPos,i_EndPos-i_StartPos,"");
}else{
i_StartPos=s_buf.find('<',i_StartPos);//Ҷλ
i_EndPos=s_buf.find('>',i_StartPos);//涨λ
if (i_StartPos==-1&&i_EndPos==-1)
{
break;//ѯλ涨λɣ
}
if (!b_FindQueue(OtherTagQueue,s_buf.substr(i_StartPos,i_EndPos-i_StartPos+1)))
{
FilterTagOther(s_buf,i_StartPos,i_EndPos);
//i_bufSize++;
}else{
//i_bufSize++;
//i_StartPos++;
i_StartPos=i_StartPos=s_buf.find('<',i_StartPos+1);
}
}
}
}
else{
cout<<"еŶ JudgeFilterPoint"<<endl;
}
return i_StartPos;
}
/************************************************************************/
/*ڹ˵ֻʣ±ˣӦܹõ㴦˰ */
/************************************************************************/ | true |
1a66f0f7df6b9f19ccb22cae0299ebb5d57447b7 | C++ | emmabh/Space-Race | /Oxygen_Depot.cpp | UTF-8 | 1,638 | 3.234375 | 3 | [] | no_license | #include "Oxygen_Depot.h"
#include "Game_Object.h"
#include "Cart_Point.h"
#include <iostream>
using namespace std;
Oxygen_Depot:: Oxygen_Depot():Game_Object('O')
{
state = 'f';
cout << "Oxygen_Depot default constructed." << endl;
amount_oxygen = 50;
}
Oxygen_Depot::Oxygen_Depot(Cart_Point inputLoc, int inputId):Game_Object('O')
{
id_num = inputId;
location = inputLoc;
amount_oxygen = 50;
display_code = 'O';
state = 'f';
cout << "Oxygen_Depot constructed." << endl;
}
bool Oxygen_Depot::is_empty()
{
if (amount_oxygen == 0){
return true;
}else{
return false;
}
}
double Oxygen_Depot::extract_oxygen(double amount_to_extract)
{
//If the amount they want to extract is greater than the amount the depot has, just deplete
if (amount_oxygen >= amount_to_extract){
amount_oxygen -= amount_to_extract;
return amount_to_extract;
}else{
amount_oxygen = 0;
return amount_oxygen;
}
}
//Default extraction
double Oxygen_Depot::extract_oxygen()
{
double amount_to_extract = 20;
if (this->amount_oxygen >= amount_to_extract){
amount_oxygen -= amount_to_extract;
return amount_to_extract;
}else{
amount_oxygen = 0;
return amount_oxygen;
}
}
bool Oxygen_Depot::update()
{
if (amount_oxygen == 0 && state != 'e'){
state = 'e';
display_code = 'o';
cout << "Oxygen_Depot " << id_num << " has been depleted." << endl;
return true;
}else{
return false;
}
}
void Oxygen_Depot::show_status()
{
cout << "Oxygen Depot status: ";
Game_Object::show_status();
cout << " contains " << amount_oxygen << "." << endl;
}
Oxygen_Depot::~Oxygen_Depot()
{
cout << "Oxygen_Depot destructed." << endl;
} | true |
a5e9d29730202a70fe8ee5ae6b50b72b6cb6d050 | C++ | mihirmpatil/interview-prep | /interviewbit/add-binary-strings.cpp | UTF-8 | 771 | 3.015625 | 3 | [] | no_license | #include <string>
string Solution::addBinary(string A, string B) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int len_a = A.size();
int len_b = B.size();
string result;
int a,b;
int sum, carry=0;
int i,j;
i = A.size()-1;
j = B.size()-1;
while (i>=0 || j>=0) {
if (i>=0)
a = A[i] - '0';
else
a = 0;
if (j>=0)
b = B[j] - '0';
else
b = 0;
sum = (a+b+carry)%2;
carry = (a+b+carry)/2;
result += to_string(sum);
--i;
--j;
}
if (carry)
result += to_string(carry);
reverse(result.begin(), result.end());
return result;
}
| true |
ac50dd3bd344fa5e197e79a7b18b59e008db8ab2 | C++ | manzmvp/Cpp_practice_questions | /Important/ChildrenGrandchildren.cpp | UTF-8 | 1,656 | 3.375 | 3 | [] | no_license | // Assume a two dimensional string array. Each array contains child and father details. '0'th
// element is the child and '1'st is the parent. Write a program to accept a name and find the
// number of children and grand children he has. Don't use any brute force methods.
// Assume names are unique.
// Example:
// Data:
// [
// [Surya, Sivakumar],
// [Karthi, Sivakumar],
// [Sivakumar, Rakkaiya],
// [Dev, Surya],
// [Umayaal, Karthi],
// [Diya, Surya],
// [Prabu, Sivaji],
// [Vikram, Prabu]
// ]
// Input: Surya, 1 // 1 indicates the number of children Surya has
// Output: 2
// Input: Karthi, 1
// Output: 1
// Input: Sivakumar, 2 // 2 indicates the number of grandchildren Sivakumar has
// Output: 3
//13:36
#include <bits/stdc++.h>
using namespace std;
int findNumOfChildren(string name, vector<vector<string>>arr){
int count=0;
for(int i=0;i<arr.size();i++){
if(arr[i][1]==name){
// cout<<arr[i][0];
count++;
}
}
return count;
}
int findNumOfGrandChildren(string name, vector<vector<string>>arr){
int count=0;
for(int i=0;i<arr.size();i++){
if(arr[i][1]==name){
count+=findNumOfChildren(arr[i][0],arr);
}
}
return count;
}
int main(){
vector<vector<string>> arr={{"Surya", "Sivakumar"},{"Karthi", "Sivakumar"},{"Sivakumar", "Rakkaiya"},{"Dev", "Surya"},{"Umayaal", "Karthi"},{"Diya", "Surya"},{"Prabu", "Sivaji"},{"Vikram", "Prabu"}};
string name;
int op;
cin>>name>>op;
if(op==1){
cout<<findNumOfChildren(name,arr)<<endl;
}
else{
cout<<findNumOfGrandChildren(name,arr)<<endl;
}
return 0;
} | true |
757f439dc0073965cdf1455d96bc067d90777626 | C++ | chromium/chromium | /ppapi/examples/url_loader/streaming.cc | UTF-8 | 5,717 | 2.59375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-khronos"
] | permissive | // Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This example shows how to use the URLLoader in streaming mode (reading to
// memory as data comes over the network). This example uses PostMessage between
// the plugin and the url_loader.html page in this directory to start the load
// and to communicate the result.
//
// The other mode is to stream to a file instead. See stream_to_file.cc
#include <stdint.h>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/url_response_info.h"
#include "ppapi/utility/completion_callback_factory.h"
// When compiling natively on Windows, PostMessage can be #define-d to
// something else.
#ifdef PostMessage
#undef PostMessage
#endif
// Buffer size for reading network data.
const int kBufSize = 1024;
class MyInstance : public pp::Instance {
public:
explicit MyInstance(PP_Instance instance)
: pp::Instance(instance) {
factory_.Initialize(this);
}
virtual ~MyInstance() {
// Make sure to explicitly close the loader. If somebody else is holding a
// reference to the URLLoader object when this class goes out of scope (so
// the URLLoader outlives "this"), and you have an outstanding read
// request, the URLLoader will write into invalid memory.
loader_.Close();
}
// Handler for the page sending us messages.
virtual void HandleMessage(const pp::Var& message_data);
private:
// Called to initiate the request.
void StartRequest(const std::string& url);
// Callback for the URLLoader to tell us it finished opening the connection.
void OnOpenComplete(int32_t result);
// Starts streaming data.
void ReadMore();
// Callback for the URLLoader to tell us when it finished a read.
void OnReadComplete(int32_t result);
// Forwards the given string to the page.
void ReportResponse(const std::string& data);
// Generates completion callbacks scoped to this class.
pp::CompletionCallbackFactory<MyInstance> factory_;
pp::URLLoader loader_;
pp::URLResponseInfo response_;
// The buffer used for the current read request. This is filled and then
// copied into content_ to build up the entire document.
char buf_[kBufSize];
// All the content loaded so far.
std::string content_;
};
void MyInstance::HandleMessage(const pp::Var& message_data) {
if (message_data.is_string() && message_data.AsString() == "go")
StartRequest("./fetched_content.html");
}
void MyInstance::StartRequest(const std::string& url) {
content_.clear();
pp::URLRequestInfo request(this);
request.SetURL(url);
request.SetMethod("GET");
loader_ = pp::URLLoader(this);
loader_.Open(request,
factory_.NewCallback(&MyInstance::OnOpenComplete));
}
void MyInstance::OnOpenComplete(int32_t result) {
if (result != PP_OK) {
ReportResponse("URL could not be requested");
return;
}
response_ = loader_.GetResponseInfo();
// Here you would process the headers. A real program would want to at least
// check the HTTP code and potentially cancel the request.
// Start streaming.
ReadMore();
}
void MyInstance::ReadMore() {
// Note that you specifically want an "optional" callback here. This will
// allow Read() to return synchronously, ignoring your completion callback,
// if data is available. For fast connections and large files, reading as
// fast as we can will make a large performance difference. However, in the
// case of a synchronous return, we need to be sure to run the callback we
// created since the loader won't do anything with it.
pp::CompletionCallback cc =
factory_.NewOptionalCallback(&MyInstance::OnReadComplete);
int32_t result = PP_OK;
do {
result = loader_.ReadResponseBody(buf_, kBufSize, cc);
// Handle streaming data directly. Note that we *don't* want to call
// OnReadComplete here, since in the case of result > 0 it will schedule
// another call to this function. If the network is very fast, we could
// end up with a deeply recursive stack.
if (result > 0)
content_.append(buf_, result);
} while (result > 0);
if (result != PP_OK_COMPLETIONPENDING) {
// Either we reached the end of the stream (result == PP_OK) or there was
// an error. We want OnReadComplete to get called no matter what to handle
// that case, whether the error is synchronous or asynchronous. If the
// result code *is* COMPLETIONPENDING, our callback will be called
// asynchronously.
cc.Run(result);
}
}
void MyInstance::OnReadComplete(int32_t result) {
if (result == PP_OK) {
// Streaming the file is complete.
ReportResponse(content_);
} else if (result > 0) {
// The URLLoader just filled "result" number of bytes into our buffer.
// Save them and perform another read.
content_.append(buf_, result);
ReadMore();
} else {
// A read error occurred.
ReportResponse("A read error occurred");
}
}
void MyInstance::ReportResponse(const std::string& data) {
PostMessage(pp::Var(data));
}
// This object is the global object representing this plugin library as long
// as it is loaded.
class MyModule : public pp::Module {
public:
MyModule() : pp::Module() {}
virtual ~MyModule() {}
// Override CreateInstance to create your customized Instance object.
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new MyInstance(instance);
}
};
namespace pp {
// Factory function for your specialization of the Module object.
Module* CreateModule() {
return new MyModule();
}
} // namespace pp
| true |
860ee5220db037a49fd391ff00ba64056beb4815 | C++ | clouduol/misc | /detectproblem2018/detect.cpp | UTF-8 | 2,380 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
void int2array(int, int*);
void sync2stdout(int*);
bool islegal(int*);
int p2[4]={2,3,0,1};
int p3[4]={2,5,1,3};
int p4[4][2]={{0,4},{1,6},{0,8},{5,9}};
int p5[4]={7,3,8,6};
int p6[4][2]={{1,3},{0,5},{2,9},{4,8}};
int p7[4]={2,1,0,3};
int p8[4]={6,4,1,9};
int p9[4]={5,9,1,8};
int p10[4]={3,2,4,1};
int main() {
int Min=0,Max=pow(4,10);
int ans[10],n;
int count=0;
for(n=Min; n<Max; n++){
int2array(n,ans);
if (islegal(ans)){
sync2stdout(ans);
count++;
}
}
if(count==0)
cout<<"no answer found"<<endl;
else
cout<<"count: "<<count<<endl;
}
void int2array(int n,int* ans){
// clear ans
for(int i=0;i<10;i++)
ans[i]=0;
int c=0;
while(n) {
ans[c++]=n%4;
n=n/4;
}
}
void sync2stdout(int* ans){
for(int i=0;i<10;i++)
cout<<char('A'+ans[i]);
cout<<endl;
}
bool islegal(int* ans) {
//p2
//cout<<"p2"<<endl;
if(p2[ans[1]] != ans[4])
return false;
//p3
//cout<<"p3"<<endl;
int o1,o2,o3;
switch(ans[2]){
case 0: o1=1,o2=2,o3=3; break;
case 1: o1=0,o2=2,o3=3; break;
case 2: o1=0,o2=1,o3=3; break;
case 3: o1=0,o2=1,o3=2; break;
}
//cout<<ans[2]<<"\t"<<o1<<"\t"<<o2<<"\t"<<o3<<endl;
//cout<<ans[p3[ans[2]]]<<"\t"<<ans[p3[o1]]<<"\t"<<ans[p3[o2]]<<"\t"<<ans[p3[o3]]<<endl;
if(!( ans[p3[o1]] == ans[p3[o2]] && ans[p3[o2]] == ans[p3[o3]] ))
return false;
if( ans[p3[ans[2]]] == ans[p3[o1]] )
return false;
//p4
//cout<<"p4"<<endl;
if( ans[p4[ans[3]][0]] != ans[p4[ans[3]][1]] )
return false;
//p5
//cout<<"p5"<<endl;
if( ans[4] != ans[p5[ans[4]]] )
return false;
//p6
//cout<<"p6"<<endl;
if(!( ans[7] == ans[p6[ans[5]][0]] && ans[7] == ans[p6[ans[5]][1]] ))
return false;
//p7
//cout<<"p7"<<endl;
int c[4]={0,0,0,0};
for(int i=0;i<10;i++){
c[ans[i]]++;
}
if(!( c[p7[ans[6]]] <= c[0] && c[p7[ans[6]]] <= c[1] && c[p7[ans[6]]] <= c[2] && c[p7[ans[6]]] <=c[3] ))
return false;
//p8
//cout<<"p8"<<endl;
if( abs(ans[0]-ans[p8[ans[7]]])==1 )
return false;
//p9
//cout<<"p9"<<endl;
int t1=0,t2=0;
if( ans[0]==ans[5] )
t1=1;
else
t1=-1;
if( ans[p9[ans[8]]] == ans[4] )
t2=1;
else
t2=-1;
if(t1*t2==1)
return false;
//p10
//cout<<"p10"<<endl;
int m1=0,m2=10;
for(int i=0;i<4;i++){
m1=max(m1,c[i]);
m2=min(m2,c[i]);
}
if( m1-m2 != p10[ans[9]] )
return false;
return true;
}
| true |
9d8ecd6b85eb85e4e40b3818e7260f76f2ed6ca1 | C++ | usherfu/zoj | /zju.finished/2286.cpp | UTF-8 | 987 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
enum {
Size = 1000001,
};
int save[Size] = {0};
int Lim = 1 + (int)sqrt((double)Size);
void init(){
int i,j, t;
for(i=2;i<Lim;i++){
j = i * i; // 特殊处理i * i == j的情况,防止i多加一次
t = i + i;
save[j] += i;
for(j+=i,t ++;j<Size;j+=i,t++){
save[j]+= t;
}
}
save[0] = -1;
sort(save, save+Size);
}
int find(int v){
int low = 0, high = Size, mid = (low + high)/2;
while(low < high){
if(save[mid] <= v){
low = mid + 1;
} else {
high = mid;
}
mid = (low + high)/2;
}
return mid;
}
int main(){
int n;
init();
while(scanf("%d",&n)>=0){
n --;
if(n < 0){
printf("0\n");
} else if(n >= save[Size-1]){
printf("%d\n", Size -1);
} else {
n = find( n );
n --;
printf("%d\n", n);
}
}
return 0;
}
| true |
5b0d3ce4d0ece1693398731a0bece415ad3cb377 | C++ | MartinFlores751/VorteX | /Project X/Project X/Ship.cpp | UTF-8 | 2,979 | 3.28125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include "core.h"
#include "Ship.h"
using std::vector;
using std::string;
Ship::Ship(int special){
// Initialize all variables
xCord = yCord = xVel = yVel = 0;
numSpecial = special;
}
bool Ship::init(SDL_Renderer* renderer, string file) {
bool isGood = true;
if (!mShip.loadFromFile(renderer, file.c_str())) {
printf("An error has occured trying to render the ship! ending ship now!");
isGood = false;
}
return isGood;
}
void Ship::setXY(int x, int y) {
xCord = x;
yCord = y;
}
void Ship::fire(vector<Bullets> *bullets, bool isPlayer) {
for (Bullets &bullet : *bullets) {
if (!bullet.isOnScreen()) {
if (isPlayer)
bullet.setXY(xCord, yCord - LEN_HEIGHT, true);
else
bullet.setXY(xCord, yCord + LEN_HEIGHT, false);
break;
}
}
}
void Ship::fireSpecial() {
if (numSpecial-- > 0) {
printf("Special attack go!!!");
}
}
void Ship::handleInput(SDL_Event& e, vector<Bullets> *bullets, bool isPlayer) {
if (e.type == SDL_KEYDOWN && e.key.repeat == 0) {
switch (e.key.keysym.sym) {
case SDLK_UP: yVel -= VELOCITY; break;
case SDLK_DOWN: yVel += VELOCITY; break;
case SDLK_LEFT: xVel-= VELOCITY; break;
case SDLK_RIGHT: xVel += VELOCITY; break;
case SDLK_z: this->fire(bullets, isPlayer); break;
case SDLK_x: fireSpecial(); break;
}
}
else if (e.type == SDL_KEYUP && e.key.repeat == 0) {
switch (e.key.keysym.sym) {
case SDLK_UP: yVel += VELOCITY; break;
case SDLK_DOWN: yVel -= VELOCITY; break;
case SDLK_LEFT: xVel += VELOCITY; break;
case SDLK_RIGHT: xVel -= VELOCITY; break;
}
}
}
void Ship::move() {
// Move the xCords of the ship first
xCord += xVel;
if (xCord < 0) {
xCord = 0;
}
else if (xCord + mShip.getWidth() > SCREEN_WIDTH) {
xCord -= xVel;
}
// Move the yCords of the ship there after
yCord += yVel;
if (yCord < 0) {
yCord = 0;
}
else if (yCord + mShip.getHeight() > SCREEN_HEIGHT) {
yCord -= yVel;
}
}
bool Ship::hasCollided(vector<Bullets> *bullets) {
int xBullet, yBullet;
for (Bullets &bullet : *bullets) {
xBullet = bullet.getXCord();
yBullet = bullet.getYCord();
// If the bullet is not outisde the ship, woe to ye
if (!(xCord > xBullet || (xCord + LEN_HEIGHT) < xBullet))
if (!(yCord > yBullet || (yCord + LEN_HEIGHT < yBullet)))
return true;
}
return false;
}
bool Ship::hasCollided(vector<Ship> *gShips) {
int xShip, yShip;
for (Ship &ship : *gShips) {
xShip, yShip;
xShip = ship.getXCords();
yShip = ship.getYCords();
// If the ship is not outside of you, woe to both
if (!(xCord > xShip || (xCord + LEN_HEIGHT) < xShip))
if (!(yCord > yShip || (yCord + LEN_HEIGHT) < yShip))
return true;
}
return false;
}
int* Ship::getXVel() {
return &xVel;
}
int* Ship::getYVel() {
return &yVel;
}
int Ship::getXCords() {
return xCord;
}
int Ship::getYCords() {
return yCord;
}
void Ship::render(SDL_Renderer* renderer) {
mShip.render(renderer, xCord, yCord);
}
Ship::~Ship(){
mShip.freeTexture();
}
| true |
fdee51199863f7e49b7114d5d4839847bf740e05 | C++ | dhanendraverma/Daily-Coding-Problem | /Day348.cpp | UTF-8 | 2,330 | 4 | 4 | [] | no_license | /******************************************************************************************************************************
This problem was asked by Zillow.
A ternary search tree is a trie-like data structure where each node may have up to three children. Here is an example which
represents the words code, cob, be, ax, war, and we.
c
/ | \
b o w
/ | | |
a e d a
| / | | \
x b e r e
The tree is structured according to the following rules:
left child nodes link to words lexicographically earlier than the parent prefix
right child nodes link to words lexicographically later than the parent prefix
middle child nodes continue the current word
For instance, since code is the first word inserted in the tree, and cob lexicographically precedes cod, cob is represented as
a left child extending from cod.
Implement insertion and search functions for a ternary search tree.
******************************************************************************************************************************/
#include <iostream>
using namespace std;
class Node{
public:
char data;
Node *left, *center, *right;
bool isEnd;
Node(char data){
this->data = data;
this->left = this->right = this->center = NULL;
this->isEnd = false;
}
};
bool search(Node* node,string word,int i){
if(!node)
return false;
if(word[i] < node->data)
return search(node->left,word,i);
else if(word[i] > node->data)
return search(node->right,word,i);
else{
if(i==word.length()-1)
return node->isEnd;
return search(node->center,word,i+1);
}
}
void insert(Node** node,string word,int i){
if(!(*node))
*node = new Node(word[i]);
if(word[i] < (*node)->data)
insert(&((*node)->left),word,i);
else if(word[i] > (*node)->data)
insert(&((*node)->right),word,i);
else{
if(i < word.length()-1)
insert(&((*node)->center),word,i+1);
else
(*node)->isEnd = true;
}
}
int main() {
Node* root = NULL;
insert(&root,"code",0);
insert(&root,"cob",0);
insert(&root,"be",0);
insert(&root,"ax",0);
insert(&root,"war",0);
insert(&root,"we",0);
cout<<search(root,"war",0)<<endl;
return 0;
}
| true |
cbf3e73fdcbdb8e0915cca5e4ead9cf8ce6d313d | C++ | amareshkumar/integration | /source/gc.cpp | UTF-8 | 417 | 3.15625 | 3 | [] | no_license | #include "MyGC.hpp"
gc :: gc (){
cout << "Constructor of gc is called\n";
}
gc ::~ gc (){
cout << "Destructor of gc is called\n";
}
void* gc::operator new(size_t size){
void* storage = malloc(size);
if (storage == NULL){
cout << "no memory left to be allocated\n\n";
EXIT_FAILURE;
}
return storage;
}
void gc::operator delete (void* vp){
cout << "my delete is being called\n";
free(vp);
}
| true |
8fbdf5ac9178aeea34ad999835f505843aef6f68 | C++ | Wylie-Modro/Skynet | /Skynet/OCR/Auvsi_Recognize.cpp | UTF-8 | 21,475 | 2.84375 | 3 | [] | no_license | #include "Auvsi_Recognize.h"
#include "BlobResult.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
#include "Auvsi_cvUtil.h"
// Whether we want to use just color channels or not
#define TWO_CHANNEL 1
cv::Mat
Auvsi_Recognize::SegmentLetter(cv::Mat colorImg, cv::Mat binaryShapeImg)
{
Auvsi_Recognize *recognize = new Auvsi_Recognize(colorImg);
recognize->_shape = recognize->resizeAndPadImage(binaryShapeImg);
recognize->extractLetter<float>();
cv::Mat letter = recognize->_letter;
letter = recognize->centerBinary(letter);
cv::resize(letter, letter, cv::Size(IMAGE_WIDTH, IMAGE_HEIGHT));
letter = letter > 128;
delete recognize;
return letter;
}
cv::Mat
Auvsi_Recognize::ProcessShape(cv::Mat shape)
{
shape = Auvsi_Recognize::centerBinary(shape);
cv::resize(shape, shape, cv::Size(IMAGE_WIDTH, IMAGE_HEIGHT));
shape = shape > 128; // threshold
return shape;
}
/**
* Constructor for testing using a cv::Mat
*/
Auvsi_Recognize::Auvsi_Recognize( cv::Mat img )
{
setImage(img);
// std::printf("begining recognize constructor\n");
/*// Set equal to image
cv::Mat _input = img ;
cv::Mat temp2( _input.size(), CV_32F );
_image = cv::Mat( IMAGE_HEIGHT, IMAGE_WIDTH, CV_32F );
_input.convertTo( temp2, _image.type(), 1.0/255.0f );
//cv::imshow( "Input", _input ); // DEBUG
cv::resize(temp2, _image, _image.size() );
//cv::imshow( "_image", _image ); // DEBUG
//cv::waitKey(10); // DEBUG
cv::cvtColor( _image, _image, CV_RGB2Lab );
//std::printf("converted color in constructor\n");
// Only use A and B channels
#ifdef TWO_CHANNEL
std::vector<cv::Mat> splitData;
cv::split( _image, splitData );
splitData.erase( splitData.begin() );
cv::merge( splitData, _image );
#endif*/
}
/**
* Constructor for using a data buffer
*
* Input:
* height - image height
* width - image width
* type - OpenCV image type (typically for us this will be CV_32FC3)
* data - Pointer to data
*/
Auvsi_Recognize::Auvsi_Recognize( int height, int width, int type, void * data )
{
// Load image and resize
cv::Mat temp( height, width, type, data );
_image = cv::Mat( IMAGE_HEIGHT, IMAGE_WIDTH, type );
setImage(_image);
//cv::resize(temp, _image, _image.size() );
// Convert to LAB
//cv::cvtColor( _image, _image, CV_RGB2Lab );
}
// default constructor. Before starting compuation, user must call setImage
Auvsi_Recognize::Auvsi_Recognize()
{
}
bool Auvsi_Recognize::checkAll()
{
bool result = true;
if (checkImage(_shape))
;//printf("Shape is good");
else {
result = false;
printf("Shape is bad");
}
if (checkImage(_letter))
;//printf("Letter is good\n");
else {
result = false;
printf("Letter is bad\n");
}
return result;
}
bool Auvsi_Recognize::checkImage( cv::Mat img )
{
typedef cv::Vec<unsigned char, 1> VT;
bool status = true;
unsigned char value;
for (int r = 0; r < img.rows; r++)
for (int c = 0; c < img.cols; c++) {
VT pixel = img.at<VT>(r, c);
value = pixel[0];
//for (int p = 0; p < 3; p++)
if (value != 255 && value != 0) {
printf("pixel:%d", value);
return false;
}
}
return status;
}
// set image so that we can start computation
void
Auvsi_Recognize::setImage( cv::Mat img )
{
// Set equal to image
cv::Mat _input( img );
cv::Mat temp2( _input.size(), CV_32F );
if (_input.type() != CV_32FC3)
_input.convertTo( temp2, _image.type());//, 1.0/255.0f );
else
temp2 = _input.clone();
_image = resizeAndPadImage(temp2);
// do color conversion
//cv::cvtColor( _image, _image, CV_RGB2Lab ); // DEBUG
/*cv::imshow( "Input", img ); // DEBUG
cv::imshow( "temp2", temp2 ); // DEBUG
cv::imshow( "_image", _image ); // DEBUG
cv::waitKey(10);*/
//std::printf("converted color in set image \n");
// Only use A and B channels
#ifdef TWO_CHANNEL
std::vector<cv::Mat> splitData;
cv::split( _image, splitData );
splitData.erase( splitData.begin() );
cv::merge( splitData, _image );
#endif
}
cv::Mat
Auvsi_Recognize::resizeAndPadImage(cv::Mat input)
{
cv::Mat result = cv::Mat( IMAGE_HEIGHT, IMAGE_WIDTH, input.type() );
// pad image to square
int outH, outW;
outH = input.rows;
outW = input.cols;
cv::Mat padded;
if( outH < outW ) // pad height
cv::copyMakeBorder( input, padded, (outW-outH)/2, (outW-outH)/2, 0, 0, cv::BORDER_REPLICATE);//, cvScalar(0) );
else // pad width
cv::copyMakeBorder( input, padded, 0, 0, (outH-outW)/2, (outH-outW)/2, cv::BORDER_REPLICATE);//, cvScalar(0) );
// Make sure output is desired width
//cv::resize( retVal, buffered, input.size(), 0, 0, cv::INTER_NEAREST );
// resize image if it is too big for proper computation
if (padded.size().width > MAX_IMAGE_SIZE || padded.size().height > MAX_IMAGE_SIZE )
cv::resize(padded, result, cv::Size(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE) );
else
result = padded;
//cv::imshow("result", result); // DEBUG
return result;
}
template<typename T>
bool
tEquals(T a, T b)
{
return abs(a - b) < 0.001;
}
void
Auvsi_Recognize::runComputation( std::string imgPath )
{
bool pathIsValid = imgPath.length() > 0;
// extract shape and letter from _image (large, LAB)
extractShape<float>();
extractLetter<float>();
//erodeLetter<float>(); // this doesn't improve accuracy, so don't do it
// center _shape and _letter (both large, binary)
_shape = centerBinary(_shape);
_letter = centerBinary(_letter);
if (pathIsValid)
{
IplImage letterIpl = _letter;
IplImage shapeIpl = _shape;
cvSaveImage((imgPath + "_letter_acenter_debug.jpg").c_str(), &letterIpl);
cvSaveImage((imgPath + "_shape_acenter_pre_debug.jpg").c_str(), &shapeIpl);
}
// resize _shape and _letter to proper size for OCR
cv::resize(_letter, _letter, cv::Size(IMAGE_WIDTH, IMAGE_HEIGHT));
cv::resize(_shape, _shape, cv::Size(IMAGE_WIDTH, IMAGE_HEIGHT));
_letter = _letter > 128;
if (pathIsValid)
{
IplImage letterIpl = _letter;
IplImage shapeIpl = _shape;
cvSaveImage((imgPath + "_letter_bpre_debug.jpg").c_str(), &letterIpl);
cvSaveImage((imgPath + "_shape_bpre_debug.jpg").c_str(), &shapeIpl);
}
// convert shape to an outline
_shape = takeImageGradient(_shape);
//_letter = takeImageGradient(_letter);
//cv::imshow("ShapePre", _shape ); // DEBUG
//cv::imshow("LetterPre", _letter ); // DEBUG
//cv::waitKey(10); // DEBUG
if (pathIsValid)
{
IplImage letterIpl = _letter;
IplImage shapeIpl = _shape;
cvSaveImage((imgPath + "_letter_cgrad_debug.jpg").c_str(), &letterIpl);
cvSaveImage((imgPath + "_shape_cgrad_debug.jpg").c_str(), &shapeIpl);
}
checkAll();
}
/**
* doClustering
* Performs k-means clustering on a two channel input, clustering to numClusters.
* Can either return the newly colored image or just the labels.
*
* Template:
* T - The type of data our matrices hold (int, float, etc)
*
* Input:
* input - Two channel matrix to cluster.
* numClusters - Choice of k.
* colored - Whether we want the colored image (true) or the labels (false)
*
* Output:
* Either the colored input or the labels. Colored input has same size and type as the input.
* Label output is a (input_size) column vector of CV_32S containing labels.
*/
template <typename T>
cv::Mat
Auvsi_Recognize::doClustering( cv::Mat input, int numClusters, bool colored = true, cv::Mat & centers = cv::Mat() )
{
#ifdef TWO_CHANNEL
typedef cv::Vec<T, 2> VT;
#else
typedef cv::Vec<T, 3> VT;
#endif
typedef cv::Vec<int, 1> IT;
const int NUMBER_OF_ATTEMPTS = 5;
int inputSize = input.rows*input.cols;
// Create destination image
cv::Mat retVal( input.size(), input.type() );
// Format input to k-means
cv::Mat kMeansData( input );
kMeansData = kMeansData.reshape( input.channels(), inputSize );
// For the output of k-means
cv::Mat labels( inputSize, 1, CV_32S );
centers = cv::Mat( numClusters, 1, input.type() );
// Perform the actual k-means clustering
// POSSIBLE FLAGS: KMEANS_PP_CENTERS KMEANS_RANDOM_CENTERS
auto criteria = cv::TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 );
cv::kmeans( kMeansData, numClusters, labels, criteria , NUMBER_OF_ATTEMPTS, cv::KMEANS_RANDOM_CENTERS /*KMEANS_RANDOM_CENTERS*/, centers );
// Label the image according to the clustering results
cv::MatIterator_<VT> retIterator = retVal.begin<VT>();
cv::MatIterator_<VT> retEnd = retVal.end<VT>();
cv::MatIterator_<IT> labelIterator = labels.begin<IT>();
for( ; retIterator != retEnd; ++retIterator, ++labelIterator )
{
VT data = centers.at<VT>( cv::saturate_cast<int>((*labelIterator)[0]), 0);
#ifdef TWO_CHANNEL
*retIterator = VT( cv::saturate_cast<T>(data[0]), cv::saturate_cast<T>(data[1]) );//, cv::saturate_cast<T>(data[2]) );
#else
*retIterator = VT( cv::saturate_cast<T>(data[0]), cv::saturate_cast<T>(data[1]), cv::saturate_cast<T>(data[2]) );
#endif
}
if( colored )
return retVal;
else
return labels;
}
Auvsi_Recognize::~Auvsi_Recognize(void)
{
}
/**
* convertToGray
* Converts a two channel matrix to some grayscale version that is one channel
*
* Input:
* input - Two channel matrix to convert.
*
* Output:
* A single channel matrix of the same type as the input that has been "grayscaled"
* Note that this will not look visually correct; it is just for processing purposes.
*/
cv::Mat
Auvsi_Recognize::convertToGray( cv::Mat input )
{
cv::Mat retVal;
cv::Mat zeros( input.rows, input.cols, CV_32F );
std::vector<cv::Mat> splitData;
cv::split( input, splitData );
splitData.push_back( zeros );
cv::merge( splitData, zeros );
cv::cvtColor( zeros, retVal, CV_RGB2GRAY );
return retVal;
}
template <typename T>
T
Auvsi_Recognize::getVectorMean( std::vector<T> input )
{
T sum = 0;
for( typename std::vector<T>::iterator it = input.begin(); it != input.end(); ++it )
{
sum += *it;
}
sum = sum / (int)input.size();
return sum;
}
cv::Mat
Auvsi_Recognize::padImageToSquare(cv::Mat img)
{
int maxDimension = (int)(std::max(img.rows, img.cols)*1.1);
cv::Mat padded;//(cv::Size(maxDimension, maxDimension), img.type());
int vertPadding = (maxDimension-img.rows)/2;
int horizPadding = (maxDimension-img.cols)/2;
cv::copyMakeBorder( img, padded, vertPadding, vertPadding, horizPadding, horizPadding, cv::BORDER_CONSTANT, cvScalar(0) );
return padded;
}
cv::Mat
Auvsi_Recognize::centerBinary( cv::Mat input )
{
typedef cv::Vec<unsigned char, 1> VT_binary;
input = padImageToSquare(input);
cv::Mat buffered = cv::Mat( input.rows * 2, input.cols * 2, input.type() );
cv::Mat retVal;
int centerX, centerY;
int minX, minY, maxX, maxY;
//int radiusX, radiusY;
std::vector<int> xCoords;
std::vector<int> yCoords;
// Get centroid
cv::Moments imMoments = cv::moments( input, true );
centerX = (int) (imMoments.m10 / imMoments.m00) - buffered.cols / 2;
centerY = (int) (imMoments.m01 / imMoments.m00) - buffered.rows / 2;
// Get centered x and y coordinates
cv::MatIterator_<VT_binary> inputIter = input.begin<VT_binary>();
cv::MatIterator_<VT_binary> inputEnd = input.end<VT_binary>();
for( ; inputIter != inputEnd; ++inputIter )
{
unsigned char value = (*inputIter)[0];
if( value )
{
xCoords.push_back( inputIter.pos().x - centerX );
yCoords.push_back( inputIter.pos().y - centerY );
}
}
if( xCoords.size() <= 0 || yCoords.size() <= 0 ) // nothing in image
{
return input;
}
// Get min and max x and y coords (centered)
minX = *std::min_element( xCoords.begin(), xCoords.end() );
minY = *std::min_element( yCoords.begin(), yCoords.end() );
maxX = *std::max_element( xCoords.begin(), xCoords.end() );
maxY = *std::max_element( yCoords.begin(), yCoords.end() );
// Get new centroids
centerX = getVectorMean<int>( xCoords );
centerY = getVectorMean<int>( yCoords );
// Get radius from center in each direction
//radiusX = std::max( abs(maxX - centerX), abs(centerX - minX) );
//radiusY = std::max( abs(maxY - centerY), abs(centerY - minY) );
// Center image in temporary buffered array
buffered = cvScalar(0);
std::vector<int>::iterator iterX = xCoords.begin();
std::vector<int>::iterator endX = xCoords.end();
std::vector<int>::iterator iterY = yCoords.begin();
int radius = 0;
for( ; iterX != endX; ++iterX, ++iterY )
{
int x = *iterX, y = *iterY;
// update radius
int dist = (int) sqrt((float)(x - centerX)*(x - centerX) + (y - centerY)*(y - centerY));
radius = std::max(radius, dist);
// store pixels into image
buffered.at<VT_binary>( y, x ) = VT_binary(255);
}
// Center image
const int border = (int) (radius*.2);
buffered = buffered.colRange( centerX - radius - border, centerX + radius + border );
buffered = buffered.rowRange( centerY - radius - border, centerY + radius + border );
// Add extra padding to make square
int outH, outW;
outH = buffered.rows;
outW = buffered.cols;
if( outH < outW ) // pad height
cv::copyMakeBorder( buffered, retVal, (outW-outH)/2, (outW-outH)/2, 0, 0, cv::BORDER_CONSTANT, cvScalar(0) );
else // pad width
cv::copyMakeBorder( buffered, retVal, 0, 0, (outH-outW)/2, (outH-outW)/2, cv::BORDER_CONSTANT, cvScalar(0) );
// resize to same as input only if input was square! otherwise this will distort shapes
//cv::resize( retVal, buffered, input.size(), 0, 0, cv::INTER_NEAREST );
return buffered;
}
/**
* extractShape
* Extracts a binary image containing just the shape.
*
* Template:
* T - The type of data our matrices hold (int, float, etc)
*
* Input:
* void
*
* Output:
* void
*/
template <typename T>
void
Auvsi_Recognize::extractShape( void )
{
typedef cv::Vec<T, 1> VT;
#ifdef TWO_CHANNEL
typedef cv::Vec<T, 2> VTTT;
const int numChannels = 2;
#else
typedef cv::Vec<T, 3> VTTT;
const int numChannels = 3;
#endif
// Reduce input to two colors
cv::Mat shapeColors;
cv::Mat reducedColors = doClustering<T>( _image, 2, true, shapeColors );
cv::Mat grayScaled, binary;
//cv::imshow("_image",_image);
//cv::imshow("imgMed",imgMed);
//cv::waitKey(10);
// Make output grayscale
grayScaled = convertToGray( reducedColors );
//cv::cvtColor( reducedColors, grayScaled, CV_RGB2GRAY );
// Make binary
double min, max;
cv::minMaxLoc( grayScaled, &min, &max );
cv::threshold( grayScaled, binary, min, 1.0, cv::THRESH_BINARY );
// ensure that background is black, image white
if( binary.at<VT>(0, 0)[0] > 0.0f )
cv::threshold( grayScaled, binary, min, 1.0, cv::THRESH_BINARY_INV );
binary.convertTo( binary, CV_8U, 255.0f );
// Fill in all black regions smaller than largest black region with white
CBlobResult blobs;
CBlob * currentBlob;
IplImage binaryIpl = binary;
blobs = CBlobResult( &binaryIpl, NULL, 255 );
// Get area of biggest blob
CBlob biggestBlob;
blobs.GetNthBlob( CBlobGetArea(), 0, biggestBlob );
// Remove all blobs of smaller area
blobs.Filter( blobs, B_EXCLUDE, CBlobGetArea(), B_GREATER_OR_EQUAL, biggestBlob.Area() );
for (int i = 0; i < blobs.GetNumBlobs(); i++ )
{
currentBlob = blobs.GetBlob(i);
currentBlob->FillBlob( &binaryIpl, cvScalar(255));
}
// Fill in all small white regions black
blobs = CBlobResult( &binaryIpl, NULL, 0 );
blobs.GetNthBlob( CBlobGetArea(), 0, biggestBlob );
blobs.Filter( blobs, B_EXCLUDE, CBlobGetArea(), B_GREATER_OR_EQUAL, biggestBlob.Area() );
for (int i = 0; i < blobs.GetNumBlobs(); i++ )
{
currentBlob = blobs.GetBlob(i);
currentBlob->FillBlob( &binaryIpl, cvScalar(0));
}
binary = cv::Scalar(0);
biggestBlob.FillBlob( &binaryIpl, cvScalar(255));
_shape = binary;
}
cv::Mat
Auvsi_Recognize::takeImageGradient(cv::Mat img)
{
cv::Mat thresholdedImage = img > 0;
cv::Mat imgFloat;
thresholdedImage.convertTo(imgFloat, CV_32F);
// take gradient of image using Sobel operator
cv::Mat gradX;
cv::Mat gradY;
cv::Mat derivativeKernel = cv::Mat::ones(2,1,CV_32FC1);
derivativeKernel.at<cv::Vec<float, 1>>(1,0)[0] = -1;
cv::Point anchor = cv::Point(0,0);
cv::filter2D(imgFloat, gradX, -1, derivativeKernel.t(), anchor);
cv::filter2D(imgFloat, gradY, -1, derivativeKernel, anchor);
// take abs of gradient to get edges
cv::Mat grad = cv::abs(gradX) + cv::abs(gradY); // DEBUG
//grad = grad > 0.1f;
// save result
grad.convertTo(img, CV_8U);
return img;
}
template <typename T>
cv::Mat
Auvsi_Recognize::customErode(cv::Mat input)
{
typedef cv::Vec<T, 1> VT;
// erode + top hat
cv::Mat kern = cv::Mat(cv::Size(3,3), CV_8U);
kern.setTo(255);
kern.at<VT>(0,0)[0] = 0;
kern.at<VT>(0,2)[0] = 0;
kern.at<VT>(2,0)[0] = 0;
kern.at<VT>(2,2)[0] = 0;
//cv::dilate(input, input, kern);
//cv::dilate(input, input, kern);
for (int i=0; i < 1; ++i)
{
cv::Mat eroded;
cv::erode(input, eroded, kern);
cv::Mat topHat;
cv::morphologyEx(input, topHat, cv::MORPH_TOPHAT, kern);
cv::bitwise_or(eroded, topHat, input);
//cv::imshow("_letter", _letter);
//cv::waitKey(500);
}
/*for (int x = 0; x < input.cols; ++x)
{
for (int y = 0; y < input.rows; ++y)
{
bool thisPixel = pixelIsValid<T>(input,x,y);
bool rightNeighbor = pixelIsValid<T>(input,x+1,y);
bool bottomNeighbor = pixelIsValid<T>(input,x,y+1);
bool leftNeighbor = pixelIsValid<T>(input,x-1,y);
//if (thisPixel && rightNeighbor && bottomNeighbor)
bool isSkinnyLine = !leftNeighbor && !rightNeighbor;
if (bottomNeighbor && !isSkinnyLine)
input.at<VT>(y,x)[0] = 0;
}
}*/
return input;
}
template <typename T>
bool
Auvsi_Recognize::pixelIsValid(cv::Mat img, int x, int y)
{
typedef cv::Vec<T, 1> VT;
bool pointIsWithinImage = ((x >= 0) && (y >= 0) && (x < img.cols) && (y < img.rows));
if (pointIsWithinImage)
if (img.at<VT>(y,x)[0] > 0)
return true;
return false;
}
template <typename T>
void
Auvsi_Recognize::takeShapeBorder( void )
{
// this takes _shape, extracts the border, and stores it back in _shape
_shape = takeImageGradient(_shape);
}
bool
Auvsi_Recognize::hasGoodLetter()
{
return cv::sum(_letter)[0]/255.0f > 10.0f;
}
template <typename T>
void
Auvsi_Recognize::erodeLetter( void )
{
typedef cv::Vec<unsigned char, 1> VT;
// NOTE: this isn't used. it was a failed experiment
// erode _letter such that every line is one pixel thick
// assume every letter is no more than 20 pixels thick
cv::imshow("orig", _letter.clone());
// erode + top hat
cv::Mat kern = cv::Mat(cv::Size(3,3), CV_8U);
kern.setTo(255);
kern.at<VT>(0,0)[0] = 0;
kern.at<VT>(0,2)[0] = 0;
kern.at<VT>(2,0)[0] = 0;
kern.at<VT>(2,2)[0] = 0;
cv::dilate(_letter, _letter, kern);
cv::dilate(_letter, _letter, kern);
for (int i=0; i < 7; ++i)
{
cv::Mat eroded;
cv::erode(_letter, eroded, kern);
cv::Mat topHat;
cv::morphologyEx(_letter, topHat, cv::MORPH_TOPHAT, kern);
cv::bitwise_or(eroded, topHat, _letter);
cv::imshow("_letter", _letter);
cv::waitKey(500);
}
}
/**
* extractLetter
* Extracts a binary image containing just the letter. Must be run after extractShape.
*
* Template:
* T - The type of data our matrices hold (int, float, etc)
*
* Input:
* void
*
* Output:
* void
*/
template <typename T>
void
Auvsi_Recognize::extractLetter( void )
{
typedef cv::Vec<unsigned char, 1> VT_binary;
#ifdef TWO_CHANNEL
typedef cv::Vec<T, 2> VT;
const int numChannels = 2;
#else
typedef cv::Vec<T, 3> VT;
const int numChannels = 3;
#endif
typedef cv::Vec<int, 1> IT;
if (_image.type() != CV_32FC3)
_image.convertTo(_image, CV_32FC3);
// make shape extended - color image where bg is same color as shape
cv::Scalar shapeColorScalar = cv::mean(_image, _shape);
VT shapeColor((float)shapeColorScalar[0], (float)shapeColorScalar[1], (float)shapeColorScalar[2]);
_shapeExtended = cv::Mat( _image.size(), _image.type() );
_shapeExtended.setTo(shapeColor);
_image.copyTo(_shapeExtended,_shape);
//_letter = _image; // DEBUG
// do blob detection on shapeExtended
//if (false) // DEBUG
{
// subtract shape color
cv::add(_shapeExtended, -shapeColor, _shapeExtended);
// abs
_shapeExtended = cv::abs(_shapeExtended);
// split channels
std::vector<cv::Mat> shapeChannels;
cv::split(_shapeExtended, shapeChannels);
// calc distance of each pixel from 0 (0 is shape color) ...
// get sum**2 channels
cv::Mat total = cv::Mat(_shapeExtended.size(), CV_32FC1);
for (int i = 0; i < numChannels; ++i)
{
cv::Mat chn = shapeChannels[i];
// chn = chn**2
cv::multiply(chn, chn, chn);
// total += chn
cv::add(chn, total, total);
}
// total = sqrt(channels**2)
cv::sqrt(total, total);
// threshold
double minDist, maxDist;
cv::minMaxIdx(total, &minDist, &maxDist);
maxDist = std::max(maxDist, 5.0);
float threshold = (float)(maxDist/3.0);
cv::threshold(total, total, threshold, 255.0, cv::THRESH_BINARY);
total.convertTo(_letter, CV_8U);
}
// get blob
//if (false) // DEBUG
{
// Remove any small white blobs left over
CBlobResult blobs;
//CBlob * currentBlob;
CBlob biggestBlob;
IplImage binaryIpl = _letter;
blobs = CBlobResult( &binaryIpl, NULL, 0 );
blobs.GetNthBlob( CBlobGetArea(), 0, biggestBlob );
//blobs.Filter( blobs, B_EXCLUDE, CBlobGetArea(), B_GREATER_OR_EQUAL, biggestBlob.Area() );
//for (int i = 0; i < blobs.GetNumBlobs(); i++ )
//{
// currentBlob = blobs.GetBlob(i);
// currentBlob->FillBlob( &binaryIpl, cvScalar(0));
//}
// set everything outside the letter to 0
cv::Mat letterMask = cv::Mat(_letter.size(), _letter.type());
letterMask.setTo(255);
binaryIpl = letterMask;
biggestBlob.FillBlob(&binaryIpl, cvScalar(0));
_letter.setTo(0.0, letterMask);
}
}
| true |
1ff2012e4f73b65c25fa488ed5d81e44bab47f5b | C++ | pratzl/csv_reader | /csv_reader.cpp | UTF-8 | 11,893 | 3.0625 | 3 | [] | no_license | // csv_reader.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "csv_reader.hpp"
#include <iostream>
#include <charconv>
#include <concepts>
#include <string_view>
#include <type_traits>
#include <limits>
#include <cassert>
#include "util.hpp"
using std::is_same_v;
using std::string;
using std::string_view;
using std::numeric_limits;
using std::forward_iterator;
using std::random_access_iterator;
using std::from_chars_result;
using std::from_chars;
using std::ranges::forward_range;
using std::ranges::random_access_range;
using std::ranges::begin;
using std::ranges::end;
using std::size;
using namespace std::literals;
/**
* Types
* 1. Boolean: true/false, yes/no, integer
* 2. Integer: int8, int16, int32, int64, uint8, uint16, uint32, uint64
* 3. Floating Point: float32, float64, float80
* 4. String
*
* Features / Boundary Cases:
* 1. Empty lines
* 2. Lines with varying number of column values
* 3. 0-n header row(s)
* 4. Caller override of column types
*
* Design Notes
* 1. While it's possible to determine if a floating point value will fit in a float32, it
* doesn't have the same precision fidelity that float64 has and may not be the best
* choice. For this reason, type detection will only identify floating point as float64.
* The caller can override this to select float32 or float80.
* 2. Empty column values are igored when determining column types, and are assigned the
* default of their type when reading rows: 0 for numeric types, false for boolean,
* empty string for string.
*/
//csv_flags& operator&=(csv_flags& lhs, csv_flags rhs) {
//static_cast<int8_t&>(lhs) &= static_cast<int8_t>(rhs);
//}
csv_flags operator&(csv_flags lhs, csv_flags rhs) {
return static_cast<csv_flags>(static_cast<int8_t>(lhs) & static_cast<int8_t>(rhs));
}
csv_flags operator|(csv_flags lhs, csv_flags rhs) {
return static_cast<csv_flags>(static_cast<int8_t>(lhs) | static_cast<int8_t>(rhs));
}
bool is_dec_digit(char ch) { return ch >= '0' && ch <= '9'; }
bool is_hex_digit(char ch) { return is_dec_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); }
int_type eval_int_type(const char* first, const char* last) {
// Leading + or -: decimal
if (last - first >= 2 && (first[0] == '+' || first[0] == '-')) {
for (++first; first != last && is_dec_digit(*first); ++first);
if(first == last) // all decimal digits?
return int_type::decimal;
}
// Leading 0x or 0X: hexidecimal
else if (last - first >= 3 && (first[0] == '0' && (first[1] == 'x' || first[1] == 'X'))) {
for (first += 2; first != last && is_hex_digit(*first); ++first);
if(first == last)
int_type::hexidecimal;
}
// No leading character hints; examine chars for decimal & hexidecimal digits
else if (last - first >= 1) {
for (; first != last && is_dec_digit(*first); ++first);
if (first == last) // all decimal digits?
return int_type::decimal;
for (; first != last && is_hex_digit(*first); ++first);
if (first == last) // all hexidecimal digits?
return int_type::hexidecimal;
}
return int_type::undefined;
}
struct csv_value_type {
csv_type type = csv_type::unknown;
int radix = 10;
csv_value value;
};
csv_type smallest_int_type(const char* first, const char* last) {
int64_t val;
from_chars_result result = from_chars(first, last, val);
if (result.ptr != last)
return csv_type::unknown;
if (val >= numeric_limits<int8_t>::min() && val <= numeric_limits<int8_t>::max())
return csv_type::int8;
else if (val >= numeric_limits<int16_t>::min() && val <= numeric_limits<int16_t>::max())
return csv_type::int16;
else if (val >= numeric_limits<int32_t>::min() && val <= numeric_limits<int32_t>::max())
return csv_type::int32;
else
return csv_type::int64;
}
csv_type smallest_uint_type(const char* first, const char* last, int base) {
uint64_t val;
from_chars_result result = from_chars(first, last, val, base);
if (result.ptr != last)
return csv_type::unknown;
if (val <= numeric_limits<uint8_t>::max())
return csv_type::uint8;
else if (val <= numeric_limits<uint16_t>::max())
return csv_type::uint16;
else if (val <= numeric_limits<uint32_t>::max())
return csv_type::uint32;
else
return csv_type::uint64;
}
csv_type smallest_float_type(const char* first, const char* last) {
double val;
from_chars_result result = from_chars(first, last, val);
if (result.ptr != last)
return csv_type::unknown;
return csv_type::float64;
}
template<char_range Rng1, char_range Rng2>
bool match_symbol(Rng1 const& line, Rng2 const& symbol) {
auto ln = begin(line);
auto sy = begin(symbol);
for (; ln != end(line) && sy != end(symbol) && *ln == *sy; ++ln, ++sy);
return ln == end(line) || sy == end(symbol);
}
template<typename CharIter>
bool match_any_char(CharIter it, string const& charset) {
for (auto ch : charset)
if (*it == ch)
return true;
return false;
}
csv_type_vector eval_line_types( string_view const& rng
, string const& sep_charset
, string const& quote_lead_symbol
, string const& quote_trail_symbol
, string const& whitesp_charset
, csv_flags flags) {
csv_type_vector type_vec;
// empty line
if (rng.empty()) {
type_vec.push_back(csv_type::unknown);
return type_vec;
}
for (auto fld = begin(rng); fld != end(rng); ) {
// advance past leading whitespace
while (fld != end(rng) && match_any_char(fld, whitesp_charset))
++fld;
// blank entry
if (fld == end(rng)) {
type_vec.push_back(csv_type::unknown);
break;
}
// quoted value
if (match_symbol(make_subrange2(fld, end(rng)), quote_lead_symbol)) {
fld += size(quote_lead_symbol);
auto first = fld;
for (; fld != end(rng) && !match_symbol(make_subrange2(fld, end(rng)), quote_trail_symbol); ++fld); // find trailing quote
type_vec.push_back(match_type(make_subrange2(first, fld), flags));
if (fld == end(rng)) // trailing quote not found
break;
fld += size(quote_trail_symbol); // advance past quote
for (; fld != end(rng) && !match_any_char(fld, sep_charset); ++fld); // advance to next sep_charset or eol
if (fld != end(rng)) // move to start of next fld
++fld;
}
// unquoted value
else {
auto first = fld;
auto last = fld;
for (; fld != end(rng) && !match_any_char(fld, sep_charset); ++fld) {
if (!match_any_char(fld, whitesp_charset))
last = fld + 1;
}
type_vec.push_back(match_type(make_subrange2(first, last), flags));
if (fld != end(rng)) // move to start of next fld
++fld;
}
}
return type_vec;
}
int sint_bits(csv_type ct) {
switch (ct) {
case csv_type::int8: return 8;
case csv_type::int16: return 16;
case csv_type::int32: return 32;
case csv_type::int64: return 64;
default: return 0;
}
}
int uint_bits(csv_type ct) {
switch (ct) {
case csv_type::uint8: return 8;
case csv_type::uint16: return 16;
case csv_type::uint32: return 32;
case csv_type::uint64: return 64;
default: return 0;
}
}
int int_bits(csv_type ct) { return std::max(sint_bits(ct), uint_bits(ct)); }
bool is_sint(csv_type ct) { return sint_bits(ct) > 0; }
bool is_uint(csv_type ct) { return uint_bits(ct) > 0; }
bool is_int(csv_type ct) { return int_bits(ct) > 0; }
bool is_boolean(csv_type ct) { return ct == csv_type::boolean; }
bool is_float(csv_type ct) { return ct == csv_type::float32 || ct == csv_type::float64 || ct == csv_type::float80; }
bool is_string(csv_type ct) { return ct == csv_type::string; }
bool is_unknown(csv_type ct) { return ct == csv_type::unknown; }
csv_type make_sint(int bits) {
switch (bits) {
case 8: return csv_type::int8;
case 16: return csv_type::int16;
case 32: return csv_type::int32;
case 64: return csv_type::int64;
default: assert(false); return csv_type::unknown;
}
}
csv_type make_uint(int bits) {
switch (bits) {
case 8: return csv_type::uint8;
case 16: return csv_type::uint16;
case 32: return csv_type::uint32;
case 64: return csv_type::uint64;
default: assert(false); return csv_type::unknown;
}
}
void accum_line_types(csv_type_vector& accum_types, csv_type_vector const& line_types) {
for (size_t i = 0; i < std::min(accum_types.size(), line_types.size()); ++i) {
csv_type const afld = accum_types[i];
csv_type const lfld = line_types[i];
if (is_int(afld)) {
if (is_int(lfld)) {
// larger signed int?
if (is_sint(afld) && is_sint(lfld)) {
if (sint_bits(afld) < sint_bits(lfld))
accum_types[i] = lfld;
}
// larger unsigned int?
else if (is_uint(afld) && is_uint(lfld)) {
if (uint_bits(afld) < uint_bits(lfld))
accum_types[i] = lfld;
}
// mixed signed & unsigned
else {
// make it signed, with enough bits for both
accum_types[i] = make_sint(std::max(sint_bits(afld), uint_bits(lfld)));
}
}
else if (is_boolean(lfld)) {
accum_types[i] = csv_type::string;
}
else if (is_float(lfld)) {
accum_types[i] = lfld; // float overrides int
}
else if (is_string(lfld)) {
accum_types[i] = lfld; // string overrides int
}
else if (is_unknown(lfld)) {
// leave as-is
}
else {
assert(false); // unexpected
}
}
else if (is_boolean(afld)) {
if (is_boolean(lfld) || is_unknown(lfld)) {
// leave as-is
}
else {
accum_types[i] = csv_type::string;
}
}
else if (is_float(afld)) {
if (is_string(lfld))
accum_types[i] = lfld; // string overrides float
else if (is_boolean(lfld))
accum_types[i] = csv_type::string;
}
else if (is_string(afld)) {
// once a string, always a string
}
else if (is_unknown(afld)) {
accum_types[i] = lfld;
}
else {
assert(false); // unexpected
}
}
// append new columns, if any
for (size_t i = accum_types.size(); i < line_types.size(); ++i)
accum_types.push_back(line_types[i]);
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
9a2a40f6dd0779deb8269a9ab0ab0162620bfddf | C++ | lPrimemaster/VectorLite | /src/SVGWriter.h | UTF-8 | 816 | 2.890625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <filesystem>
#include <iostream>
#include <unordered_map>
class SVGObject;
struct SVGStyle
{
friend class SVGWriter;
SVGStyle(std::string name) : name(name) {};
SVGStyle() {};
std::string& operator[](std::string val)
{
return styles[val];
}
std::string name;
private:
std::unordered_map<std::string, std::string> styles;
};
class SVGWriter
{
public:
SVGWriter(const std::string& fp);
~SVGWriter();
void storeObject(SVGObject* obj);
void storeObjects(std::initializer_list<SVGObject*> list);
void addStyle(SVGStyle style);
bool write() const noexcept;
private:
std::string concatAll() const;
std::string allStyles() const;
private:
std::vector<SVGObject*> objects;
std::vector<std::string> styles;
std::filesystem::path fp;
FILE* f_ptr;
};
| true |
3a7145d424f2c9f2d3aee410a7298b1f33f53fa2 | C++ | lukaszkurantdev/Object-Oriented-Programming | /6. 5 kwiecień 2018/zad1.cpp | UTF-8 | 1,894 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Polygon {
public:
struct Point {
float x,y;
};
protected:
Point *tab;
int ilePunktow;
int ileKomorek;
public:
Polygon() {
tab = new Point[4];
ilePunktow = 0;
ileKomorek = 4;
}
Polygon(int x) {
if(x%4 != 0) x+=4-(x%4);
tab = new Point[x];
ilePunktow = 0;
ileKomorek = x;
}
Polygon(Polygon &old) {
ilePunktow = old.ilePunktow;
ileKomorek = old.ileKomorek;
tab = new Point[ileKomorek];
for(int i = 0;i<ilePunktow;i++)
tab[i] = old.tab[i];
}
~Polygon() {
//for(int i = 0;i<ilePunktow;i++)
// delete tab[i];
delete tab;
}
void show() {
for(int i = 0;i<ilePunktow;i++)
cout<<tab[i].x<<" "<<tab[i].y<<endl;
}
void AddPoint(Point x) {
if(ilePunktow == ileKomorek) {
ileKomorek+=4;
Point *tmptab = new Point[ileKomorek];
for(int i = 0;i<ilePunktow;i++)
tmptab[i] = tab[i];
delete [] tab;
tab = tmptab;
}
tab[ilePunktow] = x;
ilePunktow++;
}
Point &GetPoint(int x) {
return tab[x];
}
};
int main()
{
Polygon pol;
Polygon pol2(pol);
Polygon::Point p = Polygon::Point();
p.x = 3;
p.y = 5;
pol.AddPoint(p);
pol.AddPoint(p);
pol.AddPoint(p);
pol.AddPoint(p);
pol.show();
cout<<""<<endl;
pol.AddPoint(p);
pol.show();
Polygon::Point p2 = Polygon::Point();
p2 = pol.GetPoint(2);
cout<<endl<<p2.x<<" "<<p2.y<<endl;
return 0;
}
| true |
75e87391b9d6ff9bae214f4eda3d64edaccbf214 | C++ | Joco223/Simple2D | /inc/Simple2D_Text.h | UTF-8 | 1,853 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <SDL.h>
#include <SDL_ttf.h>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include "Simple2D.h"
struct font_colour {
unsigned char red;
unsigned char green;
unsigned char blue;
unsigned char alpha;
};
namespace Simple2D {
extern void error_out(const std::string& error);
void error_ttf_out(const std::string& error);
class Text_context {
private:
std::unique_ptr<TTF_Font, decltype(&TTF_CloseFont)> font;
int space_width;
std::string font_path;
struct word_identifier {
std::string word;
int size;
word_identifier(std::string word_, int size_)
:
word(word_),
size(size_) {}
bool operator == (const word_identifier& p) const {
return word == p.word && size == p.size;
}
};
struct cached_word {
std::string word;
int width, height, size;
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> texture;
cached_word(std::string word_, int width_, int height_, int size_, SDL_Texture* texture_)
:
word(word_),
width(width_),
height(height_),
size(size_),
texture(nullptr, SDL_DestroyTexture) {
texture.reset(texture_);
}
};
struct cached_word_hash {
size_t operator() (const Text_context::word_identifier& word) const{
return std::hash<std::string>{}(word.word) ^ (std::hash<int>{}(word.size) << 1);
}
};
std::unordered_map<Text_context::word_identifier, Text_context::cached_word, cached_word_hash> cached_words;
std::vector<std::string> split(const std::string& input);
public:
Text_context(const char* font_path);
void draw_text(const Context& ctx, int x, int y, const std::string& text, int size);
void draw_text(const Context& ctx, int x, int y, const std::string& text, int size, font_colour c);
};
} | true |
242c1e3e8b1661775c8d80e27a635542565a3021 | C++ | Fibird/Rectangle2.0 | /rectangle.h | UTF-8 | 821 | 2.953125 | 3 | [] | no_license | #ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED
#include <iostream>
#include "point.h"
using namespace std;
class CRectangle
{
CPoint p1;
CPoint p2;
public:
CRectangle(double x1 = 0, double y1 = 200, double x2 = 324, double y2 = 0);
double Area(void); //computes the area of the rectangle
double Circumference(void); //computes the circumference of the rectangle
void LeftMove(double a); //moves the rectangle left
void RightMove(double d); //moves the rectangle right
void UpMove(double w); //moves the rectangle up
void DownMove(double s); //moves the rectangle down
void draw(void);
CPoint GetP1(void);
CPoint GetP2(void);
~CRectangle(){};
};
#endif // RECTANGLE_H_INCLUDED
| true |
4e1e67729af0858afbe77f62941cc633d8d2014d | C++ | iassasin/wschatserver | /regex/regex.hpp | UTF-8 | 1,268 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef SINLIB_REGEX_HPP
#define SINLIB_REGEX_HPP
#include <string>
#include <regex>
#include <vector>
#include <sstream>
namespace sinlib {
using std::regex;
using std::string;
using std::vector;
using std::istringstream;
using std::smatch;
using std::regex_search;
vector<string> regex_split(string input, const regex &rx, int max = 0);
bool regex_match_utf8(const string &input, const string &rx);
class regex_parser {
private:
int _iter;
string _input;
string _next_input;
smatch _match;
template<typename T>
void read_element(int el, T &val) {
istringstream param(_match[el].str());
param >> val;
}
void read_element(int el, string &val) {
val = _match[el].str();
}
public:
regex_parser();
regex_parser(const string &input);
bool next(const regex &rx);
bool valid();
operator bool () { return valid(); }
void set_input(const string &input);
inline string suffix() { return _match.suffix(); }
template<typename T>
regex_parser &operator >> (T &val) {
if (valid()) {
++_iter;
return read(_iter, val);
}
return *this;
}
template<typename T>
regex_parser &read(int el, T &val) {
if (_iter >= 0 && el >= 0 && el < (int) _match.size()) {
read_element(el, val);
}
return *this;
}
};
}
#endif
| true |
7acd7c358795a8b91a08753d3caadd35fb9b49c6 | C++ | frank-pian/Laser_Test | /code/ArduTest1.0/ArduTest1.0.ino | UTF-8 | 1,424 | 2.515625 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
SoftwareSerial senSerial(8,9); //软串口RX,TX
//******laserSensor模块,strDistance(),Proof_Test()******
const uint8_t CONT_MEASURE[4]={0x80,0x06,0x03,0x77}; //定义发送连续测量命令
uint8_t count[11]={0}; //接收传感器11位数据
//****** 用于SD卡设置******
const int chipSelect = 10;//设置片选CS,MEGA 53,NANO 10
String dataString = "";
void setup() {
//打开串口调试
Serial.begin(9600);//打开调试串口
senSerial.begin(9600);//打开传感器串口
while(!Serial){
;//等待调试串口连接
}
//******SD卡初始化******
Serial.print("Initializing SD card...");
//判断SD卡是否正常
if (!SD.begin(chipSelect)){
Serial.println("Card failed, or not present");
return;
}
Serial.println("card initialized.");
}
void loop() {
dataString = strDistance();//调用激光传感器函数
//打开创建一个文件,因此需要关闭之前打开的另一个
File dataFile =SD.open("datalog.txt",FILE_WRITE);
//如果文件可用,开始写入
if(dataFile){
dataFile.println(dataString);
dataFile.close();
//在调试串口打印相同内容
Serial.println(dataString);
}
//如果文件不能打开,提示Erro
else {
Serial.println("error opening datalog.txt");
}
}
| true |
3e338b76dee3ec421c80148532705581c30c8004 | C++ | biebipan/coding | /algorithm/leetcode/longest_valid_parentheses/code.cc | UTF-8 | 3,158 | 3.65625 | 4 | [] | no_license | // Copyright 2013 Jike Inc. All Rights Reserved.
// Author: Liqiang Guo(guoliqiang@jike.com)
// I just want to GH to hss~
// Date : 2013-09-24 10:12:00
// File : code.cc
// Brief :
/*
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
*/
#include <algorithm>
#include <vector>
#include <stack>
#include "base/public/logging.h"
/*
* Run Status: Accepted!
* Program Runtime: 12 milli secs
* Progress: 16/16 test cases passed.
* Run Status: Accepted!
* Program Runtime: 96 milli secs
* Progress: 229/229 test cases passed.
*
* */
namespace algorithm {
int LongestValidParentheses(std::string & str) {
int begin = 0;
int end = 0;
int max = 0;
int left_count = 0;
int right_count = 0;
while (end < str.size()) {
if (str[end] == '(') left_count++;
if (str[end] == ')') right_count++;
if (left_count >= right_count && str[end] == ')') {
int t_e = end;
int t_l = 0;
int t_r = 0;
while (t_e >= begin) {
if (str[t_e] == '(') t_l++;
if (str[t_e] == ')') t_r++;
if (t_l == t_r) {
if (end - t_e + 1> max) max = end - t_e + 1;
}
if (t_l > t_r) break;
t_e--;
}
}
if (right_count > left_count) {
end++;
begin = end;
left_count = 0;
right_count = 0;
} else {
end++;
}
// LOG(INFO) << "begin:" << begin << " end:" << end
// << " left:" << left_count
// << " right:" << right_count;
}
return max;
}
} // namespace algorithm
/*
* Run Status: Accepted!
* Program Runtime: 4 milli secs
* Progress: 16/16 test cases passed.
* Run Status: Accepted!
* Program Runtime: 40 milli secs
* Progress: 229/229 test cases passed.
* http://discuss.leetcode.com/questions/212/longest-valid-parentheses
*
* 这种题目解决方法一定是基于栈的
*
* */
namespace other {
int LongestValidParentheses(std::string & str) {
std::stack<int> foo;
int max = 0;
int last = -1;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '(') foo.push(i);
else {
if (foo.empty()) {
last = i;
} else {
foo.pop();
if (foo.empty()) max = std::max(max, i - last);
else max = std::max(max, i - foo.top());
}
}
}
return max;
}
}
namespace twice {
int Longest(std::string s) {
std::stack<int> stack;
int max = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ')') {
if (stack.empty() || s[stack.top()] != '(') stack.push(i);
else {
stack.pop();
int foo = stack.empty() ? i + 1 : i - stack.top();
max = std::max(max, foo);
}
} else stack.push(i);
}
return max;
}
} // namesapce twice
using namespace algorithm;
int main(int argc, char** argv) {
std::string str = "(())()(()((";
LOG(INFO) << LongestValidParentheses(str);
LOG(INFO) << other::LongestValidParentheses(str);
return 0;
}
| true |
5832ba2e9a13fedd9b99af441d694b41bda42a43 | C++ | poojashree/GraphicsAssignment3 | /GraphicsAssignment3/OverlayPlane.cpp | UTF-8 | 1,735 | 2.625 | 3 | [] | no_license | /* OverlayPlane CLASS
* AUTHOR: STEWART TAYLOR
*------------------------------------
* Generates a plane in which to provide overlay effects
* Uses fragment shader to enable this
*
* Last Updated: 30/11/2012
*/
#include <glew.h>
#include <freeglut.h>
#include "OverlayPlane.h"
#include "ShaderLoader.h"
OverlayPlane::OverlayPlane(void)
{
xPosition = 0;
yPosition = 8.2;
zPosition = 0;
scale = 1;
timer = 0;
}
OverlayPlane::~OverlayPlane(void)
{
}
void OverlayPlane::setShader(void)
{
char *vs = NULL,*fs = NULL,*fs2 = NULL;
fragShader = glCreateShader(GL_FRAGMENT_SHADER);
fs = ShaderLoader::textFileRead("Shaders/Overlay.frag");
const char * ff = fs;
glShaderSource(fragShader, 1, &ff,NULL);
free(vs);
free(fs);
glCompileShader(fragShader);
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram,fragShader);
glLinkProgram(shaderProgram);
timerUniform = glGetUniformLocation(shaderProgram, "timer");
resXUniform = glGetUniformLocation(shaderProgram, "resX");
resYUniform = glGetUniformLocation(shaderProgram, "resY");
}
void OverlayPlane::display(GLfloat resX , GLfloat resY)
{
timer += 1.0f;
glUseProgram(shaderProgram);
glUniform1f(timerUniform, timer);
glUniform1f(resXUniform, resX);
glUniform1f(resYUniform, resY);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glDisable(GL_LIGHTING);
glPopMatrix(); // Required
glPushMatrix();
glMatrixMode (GL_PROJECTION);
glColor3f( 0.0 ,0.0, 0.0 );
glTranslated(0 ,0 ,0);
glBegin(GL_POLYGON);
glVertex3f( -19.5, -19.5, 29.5);
glVertex3f( -14.5, 19.5, 15.5);
glVertex3f( 19.5, 19.5, 15.5);
glVertex3f( 23.5, -19.5, 29.5);
glEnd();
glPopMatrix();
glEnable(GL_LIGHTING);
glUseProgram(0);
}
| true |
89071236466717d28deb01350cd31ce1ddce1414 | C++ | leoongit/EC544_Group9 | /challenge_1/thermistor.ino | UTF-8 | 1,271 | 3.203125 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <math.h>
int pin = 0;
SoftwareSerial XBee(2, 3); // RX, TX
void setup() {
// put your setup code here, to run once:
XBee.begin(9600);
Serial.begin(9600);
}
void loop() {
int temperature = getTemp();
String mytemp = String(temperature);
String mymessage = String("D," + mytemp);
XBee.print(mymessage);
//XBee.print(temperature);
XBee.write("\n");
Serial.print(temperature);
Serial.println("*C");
delay(10000);
// put your main code here, to run repeatedly:
// XBee.write("Hello, World!\n");
// Serial.write("Sent a message...\n");
// delay(2000);
}
//
int getTemp(){
int RawADC = analogRead(pin);
long Resistance;
double Temp;
Resistance=((10240000/RawADC) - 10000);
/******************************************************************/
/* Utilizes the Steinhart-Hart Thermistor Equation: */
/* Temperature in Kelvin = 1 / {A + B[ln(R)] + C[ln(R)]^3} */
/* where A = 0.001129148, B = 0.000234125 and C = 8.76741E-08 */
/******************************************************************/
Temp = log(Resistance);
Temp = 1 / (0.001129148 + (0.000234125 * Temp) + (0.0000000876741 * Temp * Temp * Temp));
Temp = Temp - 273.15; // Convert Kelvin to Celsius
return Temp;
}
| true |
89ba7c4c7afcf485ac1e29a4dec63f81ce5c847a | C++ | jitongming/Memory-server | /public/footprint/data_process/StatisticWeiboNumAndSexProp.cpp | GB18030 | 2,167 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
#include<map>
using namespace std;
map<string, int> my_map;
struct Area
{
string name;
int user_num,man,woman,vip;
long weibo_num,fans_num,atten_num;
};
void ReadFile(Area *area,char *path,int count)
{
ifstream fin(path);
int i = 0,area_num;
string sex,is_vip,address;
int atten_num,fans_num,weibo_num;
while(fin>>sex>>is_vip>>address)
{
count ++;
area_num = my_map[address];
if(sex == "m")
area[area_num].man ++;
else
area[area_num].woman ++;
if(is_vip == "TRUE")
area[area_num].vip ++;
fin>>atten_num>>fans_num>>weibo_num;
area[area_num].atten_num += atten_num;
area[area_num].fans_num += fans_num;
area[area_num].weibo_num += weibo_num;
area[area_num].user_num ++;
}
fin.close();
}
void WriteFile(Area *area,char *path)
{
ofstream fout;
fout.open(path,ios::trunc);
fout<<"user_address,user_num,user_man,user_woman,weibo_num,fans_num,atten_num"<<endl;
for(int i=0;i<36;i++)
{
fout<<area[i].name<<","<<area[i].user_num<<","<<area[i].man<<","<<area[i].woman<<","<<area[i].weibo_num<<","<<area[i].fans_num<<","<<area[i].atten_num<<endl;
}
fout.close();
}
int main()
{
string state[36]={"ӱ","ɽ","","","","","㽭","","","","ɽ","","","","㶫","","Ĵ","","","","","ຣ","̨","ɹ","","","","½","","","","","","Ϻ","",""};
Area area[36];
int i,count;
count = 0;
for(i=0;i<36;i++)
my_map[state[i]] = i;
for(i=0;i<36;i++)
{
area[i].name = state[i];
area[i].user_num = 0;
area[i].man = 0;
area[i].woman = 0;
area[i].vip = 0;
area[i].weibo_num = 0;
area[i].fans_num = 0;
area[i].atten_num = 0;
}
ReadFile(area,"dataset_statistic.csv",count);
WriteFile(area,"data_area_statistics.csv");
return 0;
}
| true |
7e6e1536b53c095e556c41d4a3d1cbcb566943d1 | C++ | ivanfeliciano/UVa-Solutions | /820 - Internet Bandwidth.cpp | UTF-8 | 1,912 | 2.71875 | 3 | [] | no_license | #include <algorithm>
#include <bitset>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
typedef vector<int> vi;
#define MAX_V 120
#define INF 1000000000
int res[MAX_V][MAX_V], mf, f, s, t; // global variables
vi p;
vector<vi> AdjList;
void augment(int v, int minEdge) { // traverse BFS spanning tree from s to t
if (v == s) { f = minEdge; return; } // record minEdge in a global variable f
else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); // recursive
res[p[v]][v] -= f; res[v][p[v]] += f; } // update
}
int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int V, vertex_a, vertex_b, weight, numberConnections, tc = 0;
while(scanf("%d", &V) == 1 && V > 0){
scanf("%d %d %d", &s, &t, &numberConnections);
--s, --t;
memset(res, 0, sizeof res);
AdjList.assign(V, vi());
for (int i = 0; i < numberConnections; i++) {
scanf("%d %d %d", &vertex_a, &vertex_b, &weight);
vertex_a--;
vertex_b--;
res[vertex_a][vertex_b] += weight;
res[vertex_b][vertex_a] += weight;
AdjList[vertex_a].push_back(vertex_b);
AdjList[vertex_b].push_back(vertex_a);
}
mf = 0;
while (1) { // now a true O(VE^2) Edmonds Karp's algorithm
f = 0;
bitset<MAX_V> vis; vis[s] = true; // we change vi dist to bitset!
queue<int> q; q.push(s);
p.assign(MAX_V, -1);
while (!q.empty()) {
int u = q.front(); q.pop();
if (u == t) break;
for (int j = 0; j < (int)AdjList[u].size(); j++) { // we use AdjList here!
int v = AdjList[u][j];
if (res[u][v] > 0 && !vis[v])
vis[v] = true, q.push(v), p[v] = u;
}
}
augment(t, INF);
if (f == 0) break;
mf += f;
}
printf("Network %d\nThe bandwidth is %d.\n", ++tc, mf); // this is the max flow value
}
return 0;
}
| true |
b4840be09526706d2377ed7bdb99db210e051984 | C++ | ARNFRIED/DetourExample | /Injected/Detour.hpp | UTF-8 | 1,253 | 3.015625 | 3 | [] | no_license | #pragma once
#include <vector>
class Detour
{
public:
Detour(int target_func, int hook_func)
: target{ (byte*)target_func }
, hook{ hook_func }
{
new_bytes.push_back(0x68); // push (the address provided through hook)
new_bytes.resize(5);
*(int*)(new_bytes.data() + 1) = hook; // dirty hack
new_bytes.push_back(0xc3); // return
original_bytes.resize(6);
MemCpyProtect(original_bytes.data(), target, 6);
Apply();
}
~Detour()
{
Restore();
}
void Apply()
{
MemCpyProtect(target, new_bytes.data(), 6);
}
void Restore()
{
MemCpyProtect(target, original_bytes.data(), 6);
}
template<typename T, typename... Args >
decltype(auto) Call(Args... args)
{
Restore();
VirtualProtect(target, 6, PAGE_EXECUTE_READWRITE, &old_protection);
auto ret = ((T*)target)(args...);
VirtualProtect(target, 6, old_protection, 0);
Apply();
return ret;
}
void MemCpyProtect(byte* dest, byte* source, int lenght)
{
VirtualProtect(dest, lenght, PAGE_EXECUTE_READWRITE, &old_protection);
memcpy(dest, source, lenght);
VirtualProtect(dest, lenght, old_protection, 0);
}
std::vector<byte> original_bytes{};
std::vector<byte> new_bytes{};
byte* target{};
private:
int hook{};
DWORD old_protection;
}; | true |
1b3cd16d2c75827ef47bb3cb23c82ba29752afcc | C++ | cenariusxz/ACM-Coding | /homework/CandC++/1427405052-E12.cpp | UTF-8 | 3,407 | 3.859375 | 4 | [] | no_license | /*修改:LendMoney函数:添加日期参数以及修改返回值类型为double
* CalcInterest函数:添加金额参数以便LendMoney函数调用
* 主函数中增加取出金额输出,利息计算与结算时间修改
*/
#include<iostream>
using namespace std;
//日期
struct Date
{
int year; //年
int month; //月
int day; //日
Date(){}
Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
};
//账户类
class CAount
{
private:
double m_Money; //余额
Date m_Date; //存款日期
static double m_InterestRate; //年利率
int NumOfDays(const Date &date) const; //计算天数,内部计算调用
public:
static void SetInterestRate(double interest){ //设置年利率
m_InterestRate=interest;
}
static double GetInterestRate(){ //获取年利率
return m_InterestRate;
}
void SaveMoney(double money, const Date &date); //存款函数
double LendMoney(const Date &date, double money); //取款函数
double CalcInterest(const Date &date, double money) const; //计算利息
void SaveInterest(const Date &date); //结算利息
double GetBalance(); //获取余额
Date GetDate(); //获取存款日期
};
double CAount::m_InterestRate = 0.0;
int CAount::NumOfDays(const Date &date) const{ //计算天数,内部计算调用
int day1=(m_Date.year-1)*360+(m_Date.month-1)*30+m_Date.day;
int day2=(date.year-1)*360+(date.month-1)*30+date.day;
return day2-day1;
}
void CAount::SaveMoney(double money, const Date &date){ //存款函数
m_Money=money;
m_Date=date;
}
double CAount::LendMoney(const Date &date, double money){ //取款函数
if(money<=m_Money){
m_Money-=money;
int d=NumOfDays(date);
double inter=GetInterestRate();
return money+money*inter*d/360;
}
return m_Money-money;
}
double CAount::CalcInterest(const Date &date, double money) const{ //计算利息
int d=NumOfDays(date);
double inter=GetInterestRate();
return money*inter*d/360;
}
void CAount::SaveInterest(const Date &date){ //结算利息
int d=NumOfDays(date);
double inter=GetInterestRate();
m_Date=date;
m_Money=m_Money+m_Money*inter*d/360;
}
double CAount::GetBalance(){ //获取余额
return m_Money;
}
Date CAount::GetDate(){ //获取存款日期
return m_Date;
}
int main()
{
double lendMoney;
CAount account;
CAount::SetInterestRate(0.036);//设置年利率
account.SaveMoney(200000.0, Date(2015, 4, 22));//存款
//输出年利率
cout<<"设置的年利率为:"<<CAount::GetInterestRate()<<endl;
cout<<endl;
//取款
cout<<"取款210000元:"<<endl;
if ((lendMoney = account.LendMoney(Date(2015, 4, 22), 210000.0)) < 0)
{
cout<<"余额不足!"<<endl;
}
else
{
cout<<"取款成功!"<<endl;
}
cout<<endl;
//利息计算与结算
cout<<"到2016年6月1日,利息为:"<<account.CalcInterest(Date(2016, 6, 1), account.GetBalance())<<"元"<<endl;
account.SaveInterest(Date(2016, 6, 1));
//取款
cout<<"2016年12月1日取款100000元:"<<endl;
if ((lendMoney = account.LendMoney(Date(2016, 12, 1), 100000.0)) < 0)
{
cout<<"余额不足!"<<endl;
}
else
{
cout<<"取款成功!"<<endl;
cout<<"您取出的金额为:"<<lendMoney<<"元"<<endl;
cout<<"您的余额为:"<<account.GetBalance()<<"元"<<endl;
cout<<"存款日期(或上次利息结算日期)为:"<<account.GetDate().year<<"年"
<<account.GetDate().month<<"月"<<account.GetDate().day<<"日"<<endl;
}
}
| true |
77f319944c28f2678244de62af573cd56cfb7c66 | C++ | ismael-wael/solution-to-most-exercises-of-C-how-to-program-book | /ch.17/studying trials/17.11 composition - objects as members of classes/Date.cpp | UTF-8 | 1,036 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <array>
#include <stdexcept>
#include "Date.h"
using namespace std;
Date::Date(int mn, int dy, int yr)
{
if(mn > 0 && mn <= monthsPerYear)
month = mn;
else
{
throw invalid_argument("months must be 1-12");
}
year = yr;
day = checkDay(dy);
cout << "Date object constructor for date ";
print();
cout << endl;
}
void Date::print() const
{
cout << month << '/' << day << '/' << year;
}
Date::~Date()
{
cout << "Date object destructor for date ";
print();
cout << endl;
}
unsigned int Date::checkDay(int testDay) const
{
static const array <int, monthsPerYear + 1> daysPerMonth =
{0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31};
if(testDay > 0 && testDay <= daysPerMonth[month])
return testDay;
if( month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)))
return testDay;
throw invalid_argument("Invalid day for current month and year");
} | true |
8db5a30451cc1190a599c201ad26739ec63b9fdf | C++ | BartoszGancza/Game_of_Ships | /main.cpp | UTF-8 | 10,137 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <chrono>
#include <vector>
#include <string>
#include <sstream>
#include <utility>
using namespace std;
default_random_engine generator; // generator is being seeded with time since epoch at every roll of the dice
uniform_int_distribution<int> direction(1,4);
uniform_int_distribution<int> coordinate(0,9);
vector<vector<int>> enemyBoard(10, vector<int> (10, 0));
vector<vector<int>> playerBoard(10, vector<int> (10, 0));
vector<vector<int>> attackVector;
static int enemyHits, playerHits;
enum Direction {up = 1, down = 2, left = 3, right = 4};
enum FieldState {water, ship, hit, miss, attacked};
enum Turn {player, enemy};
class Ship {
public:
Ship();
int shipDirection; // 1 - up, 2 - down, 3 - left, 4 - right
};
Ship::Ship() {
shipDirection = 0;
}
void RollTheDice(int &directionRoll, int &x, int &y) {
unsigned seed = unsigned(chrono::system_clock::now().time_since_epoch().count());
generator.seed(seed);
directionRoll = direction(generator);
x = coordinate(generator);
y = coordinate(generator);
}
// set up ships on boards randomly
void SetUpBoards(vector<vector<int>> &board, vector<Ship> &shipsArray) {
int directionRoll = 0; // decides the direction the ship is going to face
int x = 0, y = 0; // coordinates on the board
int numberOfShips = int(shipsArray.size()); // easily change the number of ships on the board by only changing initializer in main()
for (int i = 1; i<=numberOfShips; i++) {
bool shipSet, overlap;
do {
RollTheDice(directionRoll, x, y);
shipsArray[i-1].shipDirection = directionRoll;
shipSet = false; // reset the values at every run of the loop
overlap = false;
switch (shipsArray[i-1].shipDirection) {
case Direction::up: // up
// these first check for bounds, then if there is any ship in the way
if ((y-(i-1)) >= 0 && board[x][y] == water) {
for (int j = 1; j < i; j++) {
if (board[x][y - j] == ship) {
overlap = true;
}
}
if (!overlap) { // if nothing overlaps, proceed to set up the ship
for (int j = 0; j < i; j++) {
board[x][y - j] = ship;
}
shipSet = true; // ship is set, ready to sail, proceed to the next loop run (next ship)
}
}
break;
case Direction::down: // down
if ((y+(i-1)) <= 9 && board[x][y] == water) {
for (int j = 1; j < i; j++) {
if (board[x][y + j] == ship) {
overlap = true;
}
}
if (!overlap) {
for (int j = 0; j < i; j++) {
board[x][y + j] = ship;
}
shipSet = true;
}
}
break;
case Direction::left: // left
if ((x-(i-1)) >= 0 && board[x][y] == water) {
for (int j = 1; j < i; j++) {
if (board[x - j][y] == ship) {
overlap = true;
}
}
if (!overlap) {
for (int j = 0; j < i; j++) {
board[x - j][y] = ship;
}
shipSet = true;
}
}
break;
case Direction::right: // right
if ((x+(i-1)) <= 9 && board[x][y] == water) {
for (int j = 1; j < i; j++) {
if (board[x + j][y] == ship) {
overlap = true;
}
}
if (!overlap) {
for (int j = 0; j < i; j++) {
board[x + j][y] = ship;
}
shipSet = true;
}
}
break;
}
} while(!shipSet || overlap);
}
}
// sets up the vector of all enemy attacks and shuffles it to randomize them
void SetUpEnemyAttacks(vector<vector<int>> &attackVector) {
int x = 0, y = 0;
unsigned seed = unsigned(chrono::system_clock::now().time_since_epoch().count());
generator.seed(seed);
for (int i = 0; i < 100; ++i) {
attackVector.push_back({x, y});
++y;
if (y == 10) {
y = 0;
++x;
}
}
shuffle(attackVector.begin(), attackVector.end(), generator);
}
// prints the boards out in a visual format
void PrintBoards() {
stringstream boards;
string toPrint;
boards << " Player Board Enemy Board" << endl;
boards << " 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10" << endl;
for (int i = 0; i < 10; i++) {
if (i == 9) {
boards << i + 1 << " ";
} else {
boards << i + 1 << " ";
}
for (int j = 0; j < 10; j++) {
if (playerBoard[i][j] == ship) {
boards << "S ";
} else if (playerBoard[i][j] == hit){
boards << "X ";
} else if (playerBoard[i][j] == miss) {
boards << "* ";
} else {
boards << "~ ";
}
}
boards << " ";
if (i == 9) {
boards << i + 1 << " ";
} else {
boards << i + 1 << " ";
}
for (int n = 0; n < 10; n++) {
if (enemyBoard[i][n] == ship) {
boards << "S ";
} else if (enemyBoard[i][n] == hit){
boards << "X ";
} else if (enemyBoard[i][n] == miss) {
boards << "* ";
} else {
boards << "~ ";
}
}
boards << endl;
}
boards << endl;
toPrint = boards.str();
cout << toPrint;
}
// evaluates the effect of an attack
int AttackEffect(vector<vector<int>> &board, int &x, int &y) {
if (board[x][y] == ship) {
return hit;
} else if (board[x][y] == water) {
return miss;
} else if (board[x][y] == hit || board[x][y] == miss) {
return attacked;
} else {
return 5; // this should absolutely never happen - it's here to disable the end of non-void function warning
}
}
// pulls a set of coordinates from the end of vector and removes it after to avoid repeating attacks
void EnemyAttack(vector<vector<int>> &attackVector, int &x, int &y) {
auto currEnd = attackVector.back();
x = currEnd[0];
y = currEnd[1];
attackVector.pop_back();
}
// after the hit moves attacks on four adjacent fields to the end of the vector (simulating more intelligent attacking pattern)
void SwapForAttack(vector<vector<int>> &attackVector, int &x, int &y) {
auto pointInVector = attackVector.end()-1;
for (auto attack : attackVector) {
if ((attack[0] == x-1 && attack[1] == y) || (attack[0] == x+1 && attack[1] == y) ||
(attack[1] == y-1 && attack[0] == x) || (attack[1] == y+1 && attack[0] == x)) {
swap(attack, *pointInVector);
--pointInVector;
}
}
}
// "Main logic" of the game
void Turn(int whoseTurn) {
int x = 0;
int y = 0;
int attackEffect = 0;
int *fieldAddress = nullptr;
// depending on who's attacking, make a random roll or let the player choose the field
if (whoseTurn == enemy) {
EnemyAttack(attackVector, x, y);
attackEffect = AttackEffect(playerBoard, x, y); // checks the field status and returns an attack effect
if (attackEffect == hit) {
SwapForAttack(attackVector, x, y);
}
fieldAddress = &playerBoard[x][y]; // sets the pointer to appropriate field on player board
} else if (whoseTurn == player) {
do {
cout << "Input attack coordinates (Y then X separated by space):";
cin >> x >> y;
cout << endl;
} while (!(x > 0 && x < 11) || !(y > 0 && y < 11));
x -= 1;
y -= 1;
attackEffect = AttackEffect(enemyBoard, x, y); // checks the field status and returns an attack effect
fieldAddress = &enemyBoard[x][y]; // sets the pointer to appropriate field on enemy board
}
if (attackEffect == attacked) { // if that field already attacked before
Turn(whoseTurn); // recursively call the function until a field not attacked before is chosen
} else if (attackEffect == hit) { // if it's a hit
*fieldAddress = hit; // set the field to a hit status
(whoseTurn == player ? playerHits += 1 : enemyHits += 1); // add 1 to the appropriate counter
cout << (whoseTurn == player ? "You" : "Enemy") << " hit in the " << x + 1 << "," << y + 1 << " field." << endl;
cout << endl;
} else if (attackEffect == miss) { // if it's a miss
*fieldAddress = miss; // set the field to a miss status
cout << (whoseTurn == player ? "You" : "Enemy") << " missed in the " << x + 1 << "," << y + 1 << " field." << endl;
cout << endl;
}
}
int main(int argc, char **argv)
{
enemyHits = 0, playerHits = 0;
vector<Ship> enemyShips(4);
vector<Ship> playerShips(4);
SetUpEnemyAttacks(attackVector);
SetUpBoards(enemyBoard, enemyShips);
SetUpBoards(playerBoard, playerShips);
//cout << "\x1B[2J\x1B[H";
do {
PrintBoards();
Turn(player);
Turn(enemy);
} while (playerHits != 10 && enemyHits != 10);
return 0;
}
| true |
71c39592213a77bd28c6c6ef706deb7f924f2a79 | C++ | kalina559/codility-lessons | /3.Time Complexity/FrogJmp/solution.cpp | UTF-8 | 113 | 2.515625 | 3 | [] | no_license | #include <algorithm>
#include<cmath>
int solution(int X, int Y, int D)
{
return ceil((Y - X) / double(D));
} | true |
389aa46eae09ce40ec3be94e3120feecf84fda9b | C++ | SusmoyBarman1/DS-and-Algorithm-Analysis-Design | /DFS_algo.cpp | UTF-8 | 1,697 | 3.1875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* next;
};
void init();
void DFS(int source);
void Insert(int j,int x);
int Input();
void Print();
bool isvisited(int data);
Node *head[100],*temp_head;
int Stack[100],top=-1,n=-1,arr[100] = {0};
int main()
{
int source;
cout<<"Put the source: ";
cin>>source;
DFS(source);
return 0;
}
void Print()
{
int totalnode = Input();
cout<<"\nPrinting the list: "<<endl;
for(int j=0;j<totalnode;j++)
{
Node* temp = head[j];
cout<<j<<" -> ";
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
}
int Input()
{
ifstream input("input.txt");;
int node1,node2,totalnode;
input>>totalnode;
while(input>>node1>>node2)
{
Insert(node1,node2);
}
input.close();
return totalnode;
}
void init()
{
for(int j=0;j<100;j++)
{
head[j] = NULL;
}
}
void Insert(int j,int x){
Node* temp = new Node();
if(head[j]==NULL)
head[j] = temp;
else
temp_head->next = temp;
temp->data = x;
temp->next = NULL;
temp_head = temp;
return;
}
void DFS(int source)
{
init();
Print();
cout<<"\nThe adjacency list is: "<<endl;
Stack[++top] = source;
arr[source] = 1;
while(top!=-1)
{
cout<<Stack[top]<<" ";
Node* temp = head[Stack[top]];
top--;
while(temp!=NULL)
{
if(arr[temp->data]==0)
{
Stack[++top] = temp->data;
arr[temp->data] = 1;
}
temp = temp->next;
}
}
cout<<endl<<endl;
} | true |
b247091de4f4ab63f5c6d3ead7b6b1e67d1398dd | C++ | Hansum/Hacktoberfest-2k18 | /algorithms/binary_search/c/pramathabhat.c | UTF-8 | 787 | 3.28125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
| true |
3e65f21dddc237f81fde4c40ba208d918ff57750 | C++ | p-lots/exercism | /cpp/clock/clock.cpp | UTF-8 | 1,631 | 3.453125 | 3 | [] | no_license | #include <iomanip>
#include <sstream>
#include <string>
#include "clock.h"
namespace date_independent {
clock clock::at(int h, int m)
{
return clock(h, m);
}
clock::operator std::string() const
{
std::stringstream ret;
ret << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) << std::setfill('0') << minutes;
return ret.str();
}
clock& clock::plus(int m)
{
if (m > 60) {
hours += m / 60;
minutes += m % 60;
}
else if (((minutes + m) / 60 + hours) > 23) {
hours = (hours + (minutes + m) / 60) % 24;
minutes += m;
minutes = minutes % 60;
}
else {
minutes += m;
}
return *this;
}
clock& clock::minus(int m)
{
if (minutes - m < 0) {
hours = hours - ((minutes + m) / 60 + 1);
if (hours < 0) {
while (hours < 0) {
hours += 24;
}
}
minutes -= m;
if (minutes < 0) {
while (minutes < 0) {
minutes += 60;
}
}
}
else {
minutes -= m;
}
return *this;
}
bool clock::operator==(const clock right) const
{
return hours == right.hours && minutes == right.minutes;
}
bool clock::operator!=(const clock right) const
{
return !(*this == right);
}
} | true |
d33692993935c9fa124b3467a3d6008d6d5c48a5 | C++ | jianminfly/learnopengl | /pcm_visual/Complex.h | UTF-8 | 1,084 | 2.546875 | 3 | [] | no_license | //
// Complex.h
// FFT
//
// Created by boone on 2018/7/17.
// Copyright © 2018年 boone. All rights reserved.
//
#ifndef Complex_h
#define Complex_h
#ifndef BOOLEAN_VAL
#define BOOLEAN_VAL
typedef int BOOL;
#define TRUE 1
#define FALSE 0
#endif
class Complex
{
public:
Complex();
Complex(double re, double im);
Complex operator=(double v);
Complex operator+(double v);
Complex operator-(double v);
Complex operator*(double v);
Complex operator/(double v);
Complex operator+=(double v);
Complex operator-=(double v);
Complex operator*=(double v);
Complex operator/=(double v);
Complex operator=(Complex c);
Complex operator+(Complex c);
Complex operator-(Complex c);
Complex operator*(Complex c);
Complex operator/(Complex c);
Complex operator+=(Complex c);
Complex operator-=(Complex c);
Complex operator*=(Complex c);
Complex operator/=(Complex c);
BOOL operator==(Complex c);
BOOL operator!=(Complex c);
double real;
double imag;
};
#endif /* Complex_h */
| true |
679539dd0582fa2fd80d232cbdfc0a169fdab96d | C++ | ChhYoung/Coding_Diary | /LeetCode&PAT/PAT/ad_1059.cpp | UTF-8 | 867 | 3.25 | 3 | [] | no_license | #include<cstdio>
#include<vector>
using namespace std;
// 用来存储质数的表
// 素数筛选法
vector<int> prime(500000,1);
int main(){
for(int i=2; i*i < 500000; ++i){
for(int j=2; j*i < 500000; ++j){
prime[j*i] = 0;
}
}
long int a;
scanf("%ld",&a);
printf("%ld=",a);
if(a == 1) {
printf("1");
return 0;
}
// 利用 state 将乘号交由前面 的来输出,
// 利用 flag 来输出质数
bool state = false;
for(int i=2;a>=2; ++i){
int cnt = 0,flag=0;
while(prime[i] == 1 && a % i == 0){
cnt++;
a /= i;
flag = 1;
}
if(flag){
if(state) printf("*");
printf("%d",i);
state = true;
}
if(cnt >= 2)
printf("^%d",cnt);
}
return 0;
} | true |
1a8127c71666a899a37a5d1c6783b48fbd334242 | C++ | meretciel/leet_code | /reverse_bit.cpp | UTF-8 | 579 | 2.90625 | 3 | [] | no_license | //
// reverse_bit.cpp
// leet_code
//
// Created by Ruikun Hong on 7/21/15.
// Copyright (c) 2015 Ruikun Hong. All rights reserved.
//
#include <stdio.h>
#include <cstdint>
using namespace std;
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t m = n;
uint32_t res =0;
uint32_t x;
while (m > 0) {
cout << x << endl;
x = 1 & m;
res = ((res << 1) | x) ;
m = m >> 1;
}
return res;
}
}; | true |
d2a7119738e28b51897dc05486a2e5bc3da704ff | C++ | codenm007/basiccprog | /home unit calculator_v2.cpp | UTF-8 | 1,403 | 3.234375 | 3 | [] | no_license | #include<stdio.h>
main()
{//codenm
float unt,amt,finalamt;
float a,b,c,d,base,tax;
printf("\nHome Unit Calculator");
printf("\n-------------------------------------------------\n");
printf("\nEnter base rate:");
scanf("%f",&base);
printf("\nEnter tax rate in percentage:");
scanf("%f",&tax);
printf("\n Enter rate for first 100 units: RS ");
scanf("%f",&a);
printf("\n Enter rate for next 200 units after:RS ");
scanf("%f",&b);
printf("\n Enter rate for next 300 units after:RS ");
scanf("%f",&c);
// printf("\n Enter rate for next units:RS ");
// scanf("%f",&d);
// units input
printf(" \n\n Enter units consumed:");
scanf("%f",&unt);
printf("\n-------------------------------------------------\n");
//unit calculation
if(unt<100)
{
amt = base;
finalamt= amt + ((amt*tax)/100);
printf("BILL AMOUNT : RS %f",finalamt);
}
else if(unt>=100 && unt<200)
{
amt = 100*a+(unt-100)*a+base;
finalamt= amt + ((amt*tax)/100);
printf("BILL AMOUNT : RS %f",finalamt);
}
else if(unt>=200 && unt<=300)
{
amt = 100*a+100*b+(unt-200)*b+base;
finalamt= amt + ((amt*tax)/100);
printf("BILL AMOUNT : RS %f",finalamt);
}
else if(unt>=300)
{
amt = 100*a+200*b+(unt-300)*c+base;
finalamt= amt + ((amt*tax)/100);
printf("BILL AMOUNT : RS %f",finalamt);
}
else
printf("Invalid input !!");
printf("\n-------------------------------------------------\n");
}
| true |
5f57cb180604caa3c9adeb08984921f1c6557626 | C++ | rtrochim/zpr-agario | /src/server/c/seasocks/ToString.h | UTF-8 | 777 | 2.90625 | 3 | [] | no_license | #pragma once
#include <sstream>
#include <string>
#include <type_traits>
namespace seasocks {
template <typename T, typename std::enable_if<!std::is_integral<typename std::decay<T>::type>::value, int>::type = 0>
std::string toString(const T& obj) {
std::stringstream str;
str.imbue(std::locale("C"));
str << obj;
return str.str();
}
template <typename T, typename std::enable_if<std::is_integral<typename std::decay<T>::type>::value, int>::type = 0>
inline std::string toString(T&& value) {
return std::to_string(std::forward<T>(value));
}
inline std::string toString(const char* str) {
return str;
}
inline std::string toString(const std::string& str) {
return str;
}
inline std::string toString(char c) {
return std::string(1, c);
}
}
| true |
5e6000037194f36bda29967969ee79ab6f0665a4 | C++ | Woloda/Lab_4_1 | /Lab_4.1/Figure.h | UTF-8 | 1,111 | 3.4375 | 3 | [] | no_license | #pragma once
#include <sstream>
class Figure { //абстрактний клас(базовий клас) "figure"(фігура)
private:
double a; //поле "a" --- відповідає за одну зі сторін прямокутника, трапеції і радіус кола
public:
Figure(); //конструктор за умовчанням(без параметрів)
Figure(double); //конструктор ініціалізації
void Set_a(double); //встановлення значення поля "a"
double Get_a() const; //отримання значення поля "a"
virtual double Square() = 0; //віртуальний метод --- відповідає за обчислення площі фігури
virtual double Perimeter() = 0; //віртуальний метод --- відповідає за обчислення периметра фігури
//віртуальний метод --- відповідає за виведення на екран даних фігури
virtual std::ostream& Display(std::ostream& out) const = 0;
}; | true |
51c5167e1dc97db0641cd4862fa0a42ed0d2fa82 | C++ | figueiredods/EstruturaDeDados_PSC_2019 | /Tema2/BubbleSortCresc/BubbleSortCresc/Origem.cpp | ISO-8859-1 | 977 | 3.28125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void BubbleSort(int vet[]);
#define TAMANHOVETOR 10
int main()
{
int vet[TAMANHOVETOR] = { 0 };
srand(time(NULL));
//INSERO DE DADOS
for (int i = 0; i < TAMANHOVETOR; i++)
vet[i] = rand() % 100;
printf("VETOR NAO ORDENADO:\n");
for (int i = 0; i < TAMANHOVETOR; i++) //IMPRIME NO ORDENADO
printf("%d\n", vet[i]);
BubbleSort(vet);
//IMPRESSO DE RESULTADOS
printf("VETOR ORDENADO:\n");
for (int i = 0; i < TAMANHOVETOR; i++) //IMPRIME ORDENADO
printf("%d\n", vet[i]);
printf("\n");
system("pause");
return 0;
}
void BubbleSort(int vet[])
{
int aux;
for (int n = 1; n <= TAMANHOVETOR; n++) //Lao para o tamanho do vetor
{
for (int i = 0; i < (TAMANHOVETOR - 1); i++) //Lao da 1 at a penultima posio
{
if (vet[i] > vet[i + 1])
{
aux = vet[i];
vet[i] = vet[i + 1];
vet[i + 1] = aux;
}
}
}
} | true |
fcadc0b97f74e2baed909f3b202a72b581e3829b | C++ | UncleRoel/O_C-Hemisphere | /software/o_c_REV/HEM_ClockDivider.ino | UTF-8 | 5,986 | 2.859375 | 3 | [] | no_license | #define HEM_CLOCKDIV_MAX 8
class ClockDivider : public HemisphereApplet {
public:
const char* applet_name() {
return "Clock Div";
}
void Start() {
ForEachChannel(ch)
{
div[ch] = ch + 1;
count[ch] = 0;
next_clock[ch] = 0;
}
last_clock = OC::CORE::ticks;
cycle_time = 0;
selected = 0;
}
void Controller() {
int this_tick = OC::CORE::ticks;
// Set division via CV
ForEachChannel(ch)
{
if (DetentedIn(ch)) {
div[ch] = Proportion(In(ch), HEMISPHERE_MAX_CV / 2, 8);
div[ch] = constrain(div[ch], -8, 8);
if (div[ch] == 0 || div[ch] == -1) div[ch] = 1;
}
}
if (Clock(1)) { // Reset
ForEachChannel(ch) count[ch] = 0;
}
if (Clock(0)) {
// The input was clocked; set timing info
cycle_time = this_tick - last_clock;
// At the clock input, handle clock division
ForEachChannel(ch)
{
count[ch]++;
if (div[ch] > 0) { // Positive value indicates clock division
if (count[ch] >= div[ch]) {
count[ch] = 0; // Reset
ClockOut(ch);
}
} else {
// Calculate next clock for multiplication on each clock
int clock_every = (cycle_time / -div[ch]);
next_clock[ch] = this_tick + clock_every;
ClockOut(ch); // Sync
}
}
last_clock = this_tick;
}
// Handle clock multiplication
ForEachChannel(ch)
{
if (div[ch] < 0) { // Negative value indicates clock multiplication
if (this_tick >= next_clock[ch]) {
int clock_every = (cycle_time / -div[ch]);
next_clock[ch] += clock_every;
ClockOut(ch);
}
}
}
}
void View() {
gfxHeader(applet_name());
DrawSelector();
}
void ScreensaverView() {
DrawSelector();
}
void OnButtonPress() {
selected = 1 - selected;
ResetCursor();
}
void OnEncoderMove(int direction) {
div[selected] += direction;
if (div[selected] > HEM_CLOCKDIV_MAX) div[selected] = HEM_CLOCKDIV_MAX;
if (div[selected] < -HEM_CLOCKDIV_MAX) div[selected] = -HEM_CLOCKDIV_MAX;
if (div[selected] == 0) div[selected] = direction > 0 ? 1 : -2; // No such thing as 1/1 Multiple
if (div[selected] == -1) div[selected] = 1; // Must be moving up to hit -1 (see previous line)
count[selected] = 0; // Start the count over so things aren't missed
}
uint32_t OnDataRequest() {
uint32_t data = 0;
Pack(data, PackLocation {0,8}, div[0] + 32);
Pack(data, PackLocation {8,8}, div[1] + 32);
return data;
}
void OnDataReceive(uint32_t data) {
div[0] = Unpack(data, PackLocation {0,8}) - 32;
div[1] = Unpack(data, PackLocation {8,8}) - 32;
}
protected:
void SetHelp() {
help[HEMISPHERE_HELP_DIGITALS] = "1=Clock 2=Reset";
help[HEMISPHERE_HELP_CVS] = "Div/Mult Ch1,Ch2";
help[HEMISPHERE_HELP_OUTS] = "Clk A=Ch1 B=Ch2";
help[HEMISPHERE_HELP_ENCODER] = "Div,Mult";
}
private:
int div[2]; // Division data for outputs. Positive numbers are divisions, negative numbers are multipliers
int count[2]; // Number of clocks since last output (for clock divide)
int next_clock[2]; // Tick number for the next output (for clock multiply)
int last_clock; // The tick number of the last received clock
int selected; // Which output is currently being edited
int cycle_time; // Cycle time between the last two clock inputs
void DrawSelector() {
ForEachChannel(ch)
{
int y = 16 + (ch * 25);
if (ch == selected) {
gfxCursor(0, y + 9, 63);
}
if (div[ch] > 0) {
gfxPrint(2, y, "1/");
gfxPrint(div[ch]);
gfxPrint(" Div");
}
if (div[ch] < 0) {
gfxPrint(2, y, -div[ch]);
gfxPrint("/1");
gfxPrint(" Mult");
}
}
}
};
////////////////////////////////////////////////////////////////////////////////
//// Hemisphere Applet Functions
///
/// Once you run the find-and-replace to make these refer to ClockDivider,
/// it's usually not necessary to do anything with these functions. You
/// should prefer to handle things in the HemisphereApplet child class
/// above.
////////////////////////////////////////////////////////////////////////////////
ClockDivider ClockDivider_instance[2];
void ClockDivider_Start(int hemisphere) {
ClockDivider_instance[hemisphere].BaseStart(hemisphere);
}
void ClockDivider_Controller(int hemisphere, bool forwarding) {
ClockDivider_instance[hemisphere].BaseController(forwarding);
}
void ClockDivider_View(int hemisphere) {
ClockDivider_instance[hemisphere].BaseView();
}
void ClockDivider_Screensaver(int hemisphere) {
ClockDivider_instance[hemisphere].BaseScreensaverView();
}
void ClockDivider_OnButtonPress(int hemisphere) {
ClockDivider_instance[hemisphere].OnButtonPress();
}
void ClockDivider_OnEncoderMove(int hemisphere, int direction) {
ClockDivider_instance[hemisphere].OnEncoderMove(direction);
}
void ClockDivider_ToggleHelpScreen(int hemisphere) {
ClockDivider_instance[hemisphere].HelpScreen();
}
uint32_t ClockDivider_OnDataRequest(int hemisphere) {
return ClockDivider_instance[hemisphere].OnDataRequest();
}
void ClockDivider_OnDataReceive(int hemisphere, uint32_t data) {
ClockDivider_instance[hemisphere].OnDataReceive(data);
}
| true |
54c288743667f9ba7b67b206f798a7fc33eac5d9 | C++ | buyulian/Six-chess-AI-cpp | /六子棋2.cpp | GB18030 | 15,521 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <vector>
#include <queue>
#include <string.h>
#include <windows.h>
#include <fstream>
using namespace std;
enum paint_char{black=1,white=2,empty=-1,nempty=-2,side=3,sum=3};
enum vertion{player,computer};
const int chessbored_size=21;//̳ߴ
int chessbored[chessbored_size][chessbored_size];//
int cursor_x,cursor_y;//
int player_color=black;//ɫ
int computer_color=white; //ɫ
const int max2=2147483647,fen_max=99999999;
const int min2=-2147483647,fen_min=-99999999;
int wide=4,depth=6;//Ⱥ
int regret_array[180][chessbored_size][chessbored_size],regret_num;//¼
struct node
{
int i,j;
int value;
int c[2][4];//γɵӵ
friend bool operator < (node a,node b)
{
return a.value<b.value;
}
friend bool operator > (node a,node b)
{
return a.value>b.value;
}
} ;
struct sixnode
{
int x1,y1,x2,y2;
};
//priority_queue< node,vector<node>,less<node> > empty_player;
//priority_queue< node,vector<node>,less<node> > empty_player;
vector<node> empty_node;
vector<node> regret_empty_node[180];//
int szfz(int a[chessbored_size][chessbored_size],int b[chessbored_size][chessbored_size])
{
int i,j;
for(i=0;i<chessbored_size;i++)
for(j=0;j<chessbored_size;j++)
b[i][j]=a[i][j];
return 0;
}
int ini_chessbored()//ʼ
{
memset(chessbored,-1,sizeof(chessbored));
int i;
for(i=0;i<chessbored_size;i++)
{
chessbored[i][0]=side;
chessbored[0][i]=side;
chessbored[chessbored_size-1][i]=side;
chessbored[i][chessbored_size-1]=side;
}
return 0;
}
string get_style(int i,int j)//õַ
{
int a=chessbored[i][j];
if(i==cursor_x&&j==cursor_y)return " ";
if(a==black)return "";
if(a==white)return "";
if(i>1)
{
if(i<chessbored_size-2)
{
if(j>1)
{
if(j<chessbored_size-2)
{
return "";
}
else
{
return "";
}
}
else
{
return "";
}
}
else
{
if(j>1)
{
if(j<chessbored_size-2)
{
return "";
}
else
{
return "";
}
}
else
{
return "";
}
}
}
else
{
if(j>1)
{
if(j<chessbored_size-2)
{
return "";
}
else
{
return "";
}
}
else
{
return "";
}
}
}
int paint()//ͼ
{
string canvas[chessbored_size];
int i,j;
for(i=1;i<chessbored_size-1;i++)
{
canvas[i]=canvas[i]+" ";
for(j=1;j<chessbored_size-1;j++)
canvas[i]=canvas[i]+get_style(i,j);
canvas[i]=canvas[i]+" ";
}
for(i=0;i<chessbored_size;i++)
{
canvas[0]=canvas[0]+" ";
canvas[chessbored_size-1]=canvas[chessbored_size-1]+" ";
}
system("cls");
for(i=0;i<chessbored_size;i++)
cout<<canvas[i]<<endl;
return 0;
}
int near_num(int x,int y)//ش˵γɵ
{
int s,m,k,n=chessbored[x][y];
s=1;
for(k=1;k<6&&chessbored[x][y-k]==n;k++)s++;
for(k=1;k<6&&chessbored[x][y+k]==n;k++)s++;
m=s;
s=1;
for(k=1;k<6&&chessbored[x-k][y]==n;k++)s++;
for(k=1;k<6&&chessbored[x+k][y]==n;k++)s++;
if(s>m)m=s;
s=1;
for(k=1;k<6&&chessbored[x-k][y-k]==n;k++)s++;
for(k=1;k<6&&chessbored[x+k][y+k]==n;k++)s++;
if(s>m)m=s;
s=1;
for(k=1;k<6&&chessbored[x-k][y+k]==n;k++)s++;
for(k=1;k<6&&chessbored[x+k][y-k]==n;k++)s++;
if(s>m)m=s;
return m;
}
int empty_value_sub(node e,int a)//aʾӽһǵ ոֺ
{
int temp=chessbored[e.i][e.j];
chessbored[e.i][e.j]=a;
if(near_num(e.i,e.j)>5)
{
chessbored[e.i][e.j]=temp;
return fen_max;
}
chessbored[e.i][e.j]=temp;
int b=1,i,j,k,s=0,n,fa=black+white-a,b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i][e.j-k]==a)b*=4;
else if(chessbored[e.i][e.j-k]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i][e.j+k]==a)b*=4;
else if(chessbored[e.i][e.j+k]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
n=0;
for(k=1;k<6&&chessbored[e.i][e.j-k]!=fa&&chessbored[e.i][e.j-k]!=side;k++)
n++;
for(k=1;k<6&&chessbored[e.i][e.j+k]!=fa&&chessbored[e.i][e.j+k]!=side;k++)
n++;
if(n<5)b=0;
if(n==5&&b==512)b=1024;
s=s+b;
b=1;b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i-k][e.j]==a)b*=4;
else if(chessbored[e.i-k][e.j]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i+k][e.j]==a)b*=4;
else if(chessbored[e.i+k][e.j]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
n=0;
for(k=1;k<6&&chessbored[e.i-k][e.j]!=fa&&chessbored[e.i-k][e.j]!=side;k++)
n++;
for(k=1;k<6&&chessbored[e.i+k][e.j]!=fa&&chessbored[e.i+k][e.j]!=side;k++)
n++;
if(n<5)b=0;
if(n==5&&b==512)b=1024;
s=s+b;
b=1;b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i-k][e.j-k]==a)b*=4;
else if(chessbored[e.i-k][e.j-k]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i+k][e.j+k]==a)b*=4;
else if(chessbored[e.i+k][e.j+k]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
n=0;
for(k=1;k<6&&chessbored[e.i-k][e.j-k]!=fa&&chessbored[e.i-k][e.j-k]!=side;k++)
n++;
for(k=1;k<6&&chessbored[e.i+k][e.j+k]!=fa&&chessbored[e.i+k][e.j+k]!=side;k++)
n++;
if(n<5)b=0;
if(n==5&&b==512)b=1024;
s=s+b;
b=1;b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i-k][e.j+k]==a)b*=4;
else if(chessbored[e.i-k][e.j+k]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
b2=0;
for(k=1;k<6;k++)
{
if(chessbored[e.i+k][e.j-k]==a)b*=4;
else if(chessbored[e.i+k][e.j-k]<0)
{
b2++;
if(b2>1)
{
break;
}
b*=2;
}
else
break;
}
n=0;
for(k=1;k<6&&chessbored[e.i-k][e.j+k]!=fa&&chessbored[e.i-k][e.j+k]!=side;k++)
n++;
for(k=1;k<6&&chessbored[e.i+k][e.j-k]!=fa&&chessbored[e.i+k][e.j-k]!=side;k++)
n++;
if(n<5)b=0;
if(n==5&&b==512)b=1024;
s=s+b;
return s;
}
int empty_value(node &e,int a)
{
int my,you;
my=empty_value_sub(e,a);
you=empty_value_sub(e,player_color+computer_color-a);
e.value=my+you;
return my+you;
}
int empty_value2(node &e,int a)//ֺ
{
int my,you;
my=empty_value_sub(e,a);
you=empty_value_sub(e,player_color+computer_color-a);
e.value=my-you/2;
return my-you/2;
}
int pingfen(int pc)//
{
vector<node>::iterator the_iterator;
node e;
int max3=fen_min;
the_iterator = empty_node.begin();
while( the_iterator != empty_node.end() )
{
e=*the_iterator;
empty_value2(e,pc);
if(e.value>max3)
max3=e.value;
the_iterator++;
}
return max3;
}
int display()
{
vector<node>::iterator the;
the=empty_node.begin();
while(the!=empty_node.end())
{
cout<<(*the).i<<" "<<(*the).j<<" "<<(*the).value<<endl;
the++;
}
return 0;
}
int before_move(int x,int y)
{
if(chessbored[x][y]==nempty)
{
vector<node>::iterator the_iterator;
node e;
the_iterator = empty_node.begin();
while( the_iterator != empty_node.end() )
{
e=*the_iterator;
if(e.i==x&&e.j==y)
{
empty_node.erase(the_iterator);
break;
}
the_iterator++;
}
}
return 0;
}
int updata_empty_node(int x,int y)//ΧĿյ
{
int i,j;
for(i=-3;i<4;i++)
for(j=-3;j<4;j++)
if(chessbored[x+i][y+j]==empty&&x+i>0&&x+i<20&&y+j>0&&y+j<20)
{
node e;
e.i=x+i;
e.j=y+j;
empty_node.push_back(e);
//cout<<e.i<<" "<<e.j<<endl;
chessbored[x+i][y+j]=nempty;
}
return 0;
}
int youfen(int pc,int depth2,int jz);
int myfen(int pc,int depth2,int jz)//ҵķ
{
if(depth2>=depth)
{
int a=pingfen(pc);
return a;
}
int fa=player_color+computer_color-pc,c;
int n=empty_node.size();
int i,j;
vector<node> en;
en=empty_node;
node e,e2;
priority_queue< node ,vector<node> ,less<node> > pen;
for(i=0;i<n;i++)
{
e=en.back();
en.pop_back();
empty_value(e,pc);
pen.push(e);
}
int max_value=min2;
int wide2=wide;
if(wide2>n)wide2=n;
node te[50];
for(i=0;i<wide2;i++)
{
te[i]=pen.top();
pen.pop();
}
sixnode se[20];
int secnt=0;
for(i=0;i<wide2;i++)
for(j=i+1;j<wide2;j++)
{
se[secnt].x1=te[i].i;
se[secnt].y1=te[i].j;
se[secnt].x2=te[j].i;
se[secnt].y2=te[j].j;
secnt++;
}
int chessbored2[chessbored_size][chessbored_size];
szfz(chessbored,chessbored2);
for(i=0;i<secnt;i++)
{
vector<node> empty_node2;
empty_node2=empty_node;
before_move(se[i].x1,se[i].y1);
before_move(se[i].x2,se[i].y2);
chessbored[se[i].x1][se[i].y1]=pc;
chessbored[se[i].x2][se[i].y2]=pc;
if(near_num(se[i].x1,se[i].y1)>5)
{
empty_node=empty_node2;
szfz(chessbored2,chessbored);
return fen_max;
}
if(near_num(se[i].x2,se[i].y2)>5)
{
empty_node=empty_node2;
szfz(chessbored2,chessbored);
return fen_max;
}
updata_empty_node(se[i].x1,se[i].y1);
updata_empty_node(se[i].x2,se[i].y2);
int fenshu;
fenshu=youfen(pc,depth2+1,max_value);
if(fenshu>max_value)
{
max_value=fenshu;
}
empty_node=empty_node2;
szfz(chessbored2,chessbored);
}
return max_value;
}
int youfen(int pc,int depth2,int jz)//ķ ,jz֦
{
int fa=player_color+computer_color-pc;
int n=empty_node.size();
int i,j,i2;
vector<node> en;
en=empty_node;
node e,e2;
priority_queue< node ,vector<node> ,less<node> > pen;
for(i=0;i<n;i++)
{
e=en.back();
en.pop_back();
empty_value(e,fa);
pen.push(e);
}
int min_value=max2,c;
int wide2=wide;
if(wide2>n)wide2=n;
node te[50];
for(i=0;i<wide2;i++)
{
te[i]=pen.top();
pen.pop();
}
sixnode se[20];
int secnt=0;
for(i=0;i<wide2;i++)
for(j=i+1;j<wide2;j++)
{
se[secnt].x1=te[i].i;
se[secnt].y1=te[i].j;
se[secnt].x2=te[j].i;
se[secnt].y2=te[j].j;
secnt++;
}
int chessbored2[chessbored_size][chessbored_size];
szfz(chessbored,chessbored2);
for(i=0;i<secnt;i++)
{
vector<node> empty_node2;
empty_node2=empty_node;
before_move(se[i].x1,se[i].y1);
before_move(se[i].x2,se[i].y2);
chessbored[se[i].x1][se[i].y1]=fa;
chessbored[se[i].x2][se[i].y2]=fa;
if(near_num(se[i].x1,se[i].y1)>5)
{
empty_node=empty_node2;
szfz(chessbored2,chessbored);
return fen_min;
}
if(near_num(se[i].x2,se[i].y2)>5)
{
empty_node=empty_node2;
szfz(chessbored2,chessbored);
return fen_min;
}
updata_empty_node(se[i].x1,se[i].y1);
updata_empty_node(se[i].x2,se[i].y2);
int fenshu;
fenshu=myfen(pc,depth2+1,min_value);
if(fenshu<min_value)
{
min_value=fenshu;
}
empty_node=empty_node2;
szfz(chessbored2,chessbored);
}
return min_value;
}
sixnode get_bestnode(int pc)//õŵ ,pcʾһΪԼ
{
int n=empty_node.size();
int i,c1,c2,j,i2;
vector<node> en;
en=empty_node;
sixnode se2;
node e;
priority_queue< node ,vector<node> ,less<node> > pen;
for(i=0;i<n;i++)
{
e=en.back();
en.pop_back();
empty_value(e,pc);
pen.push(e);
}
int max_value=min2;
// display();
int wide2=wide;
if(wide2>n)wide2=n;
node te[50];
for(i=0;i<wide2;i++)
{
te[i]=pen.top();
pen.pop();
}
sixnode se[20];
int secnt=0;
for(i=0;i<wide2;i++)
for(j=i+1;j<wide2;j++)
{
se[secnt].x1=te[i].i;
se[secnt].y1=te[i].j;
se[secnt].x2=te[j].i;
se[secnt].y2=te[j].j;
secnt++;
}
int chessbored2[chessbored_size][chessbored_size];
szfz(chessbored,chessbored2);
for(i=0;i<secnt;i++)
{
vector<node> empty_node2;
empty_node2=empty_node;
before_move(se[i].x1,se[i].y1);
before_move(se[i].x2,se[i].y2);
chessbored[se[i].x1][se[i].y1]=pc;
chessbored[se[i].x2][se[i].y2]=pc;
if(near_num(se[i].x1,se[i].y1)>5)
{
empty_node=empty_node2;
szfz(chessbored2,chessbored);
return se[i];
}
if(near_num(se[i].x2,se[i].y2)>5)
{
empty_node=empty_node2;
szfz(chessbored2,chessbored);
return se[i];
}
updata_empty_node(se[i].x1,se[i].y1);
updata_empty_node(se[i].x2,se[i].y2);
int fenshu;
fenshu=youfen(pc,1,max_value);
if(fenshu>max_value)
{
i2=i;
max_value=fenshu;
}
empty_node=empty_node2;
szfz(chessbored2,chessbored);
}
return se[i2];
}
int computer_move(int pc)
{
sixnode se;
se=get_bestnode(pc);
before_move(se.x1,se.y1);
before_move(se.x2,se.y2);
chessbored[se.x1][se.y1]=pc;
chessbored[se.x2][se.y2]=pc;
paint();
if(near_num(se.x1,se.y1)>5)
return 1;
if(near_num(se.x2,se.y2)>5)
return 1;
updata_empty_node(se.x1,se.y1);
updata_empty_node(se.x2,se.y2);
return 0;
}
int regret_save() //Ϣ
{
regret_num++;
szfz(chessbored,regret_array[regret_num]);
regret_empty_node[regret_num]=empty_node;
return 0;
}
int regret()//
{
regret_num--;
if(regret_num<0)return 0;
szfz(regret_array[regret_num],chessbored);
empty_node=regret_empty_node[regret_num];
return 0;
}
int player_move()
{
int key,i;
while(1)
{
key=getch();
if(key==224)//µǷ
{
key=getch();
if(key==72)//
{
cursor_x--;
if(cursor_x<1)
cursor_x=chessbored_size-2;
}
else if(key==80)//
{
cursor_x++;
if(cursor_x>chessbored_size-2)
cursor_x=1;
}
else if(key==75)//
{
cursor_y--;
if(cursor_y<1)
cursor_y=chessbored_size-2;
}
else if(key==77)//
{
cursor_y++;
if(cursor_y>chessbored_size-2)
cursor_y=1;
}
paint();
}
else if(key==32&&chessbored[cursor_x][cursor_y]<0)//µǿո
{
before_move(cursor_x,cursor_y);
chessbored[cursor_x][cursor_y]=player_color;
paint();
if(near_num(cursor_x,cursor_y)>5)
return 1;
updata_empty_node(cursor_x,cursor_y);
return 0;
}
else if(key==27)
{
regret();
paint();
}
}
}
int main()
{
system("title ");//ñ
// system("mode con cols=45 lines=24");//ôڴС
system("color b0");//ɫ
while(1)
{
ini_chessbored();
regret_num=-1;
cursor_x=chessbored_size/2;
cursor_y=chessbored_size/2;
// cursor_x=2;
// cursor_y=2;
empty_node.clear();
cout<<"1֣2"<<endl;
int cnt;
cin>>cnt;
if(cnt==2)
{
int f=chessbored_size/2;
before_move(f,f);
chessbored[f][f]=computer_color;
updata_empty_node(f,f);
paint();
}
else
{
paint();
player_move();
computer_move(computer_color);
}
while(1)
{
int a;
// a=computer_move(player_color);
regret_save();
player_move();
a=player_move();
if(a)
{
cout<<"ʤ"<<endl;
int temp=1;
if(getch()==27)
{
regret();
paint();
player_move();
temp=0;
}
if(temp)
break;
}
// system("pause");
a=computer_move(computer_color);
if(a)
{
cout<<"ʤ"<<endl;
int temp=1;
if(getch()==27)
{
regret();
paint();
temp=0;
}
if(temp)
break;
}
// system("pause");
}
}
return 0;
} | true |
8c253f61213d029947ec7372fd00dbfa8b79d91a | C++ | PrajwalaTM/accepted | /Templates/Number Theory/inclusion-exclusion.cpp | UTF-8 | 1,240 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long int intersectionCardinality(vector<long long int>v,long long n)
{
long long s=v.size(),ans=1,i;
for(i=0;i<s;i++)
ans*=v[i];
return (n/ans);
}
long long int GCD(long long int A, long long int B) {
if(B==0)
return A;
else
return GCD(B, A % B);
}
int main()
{
long long int n,b,result=0,p,q,g,cardinality;
//long long s,ans=1,i,cardinality;
scanf("%lld",&n);
long long set[4];
set[0]=2;set[1]=3;set[2]=11;set[3]=13;
for(b = 0; b < (1 << 4); ++b)
{
vector<long long int> indices;
for(int k = 0; k < 4; ++k)
{
if(b & (1 << k))
{
indices.push_back(set[k]);
//printf("%lld ",set[k]);
}
}
//printf("\n");
if(!indices.empty())
cardinality = intersectionCardinality(indices,n);
else
cardinality=0;
/* s=indices.size();
for(i=0;i<s;i++)
ans*=indices[i];
cardinality=n/ans;*/
//printf("%lld ",cardinality);
if(indices.size() % 2 == 1) result += cardinality;
else result -= cardinality;
}
p=result;
q=n;
g=GCD(p,q);
//printf("%lld ",p);
printf("%lld %lld",p/g,q/g);
return 0;
}
| true |
ab25d2d22aee0b9bd1148fa40efb18c8ff08f542 | C++ | lh123cha/my_leveldb | /test/db_test1.cc | UTF-8 | 1,087 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "leveldb/db.h"
#include <cstdio>
#include <iostream>
using namespace std;
using namespace leveldb;
int main() {
DB *db = nullptr;
Options op;
op.create_if_missing = true;
op.use_hash_table= true;
Status status = DB::Open(op, "testdb", &db);
assert(status.ok());
string s[100];
int i = 0;
// ColumnFamilyHandler cfh=ColumnFamilyHandler("test1");
// db->Put(WriteOptions(), "1",cfh,"111");
db->PutWithIndex(WriteOptions(), "3","333");
Iterator* iter1 = db->NewIndexIterator(ReadOptions());
// std::string empty_value;
// std::string key="1";
// status = db->Get(ReadOptions(), cfh,key, &empty_value);
// if (!status.ok()) {
// printf("%s\n","faild get");
// printf("%s\n", status.ToString().c_str());
// }
// std::cout<<empty_value<<std::endl;
// Iterator* iter1 = db->NewColumnFamilyIterator(ReadOptions(),cfh);
i = 0;
for(iter1->SeekToFirst(); iter1->Valid(); iter1->Next()){
s[i] += iter1->key().ToString()+" : "+iter1->value().ToString();
i ++;
}
for(i;i>=0;i--){
cout<<s[i]<<endl;
}
delete iter1;
return 0;
}
| true |
ffc33c3d7e54c1a7514b5eac7f7421c6b1e3ff15 | C++ | TimoLoomets/TeamSuccessRobotex2018Taxify | /v_0_2/util_functions/geodesic.cpp | UTF-8 | 7,101 | 2.921875 | 3 | [] | no_license | #ifndef GEODESIC_CPP
#define GEODESIC_CPP
#include <bits/stdc++.h>
#include "util_functions.hpp"
#include "data_types.h"
double hav(double i){
return sin(i/2)*sin(i/2);
}
//double hav_dist(
std::pair<double, double> lineLineIntersection(std::pair<double, double> A, std::pair<double, double> B, std::pair<double, double> C, std::pair<double, double> D)
{
// Line AB represented as a1x + b1y = c1
double a1 = B.second - A.second;
double b1 = A.first - B.first;
double c1 = a1*(A.first) + b1*(A.second);
// Line CD represented as a2x + b2y = c2
double a2 = D.second - C.second;
double b2 = C.first - D.first;
double c2 = a2*(C.first)+ b2*(C.second);
double determinant = a1*b2 - a2*b1;
if (determinant == 0)
{
// The lines are parallel. This is simplified
// by returning a pair of FLT_MAX
return make_pair(FLT_MAX, FLT_MAX);
}
else
{
double x = (b2*c1 - b1*c2)/determinant;
double y = (a1*c2 - a2*c1)/determinant;
return make_pair(x, y);
}
}
std::pair<double, double> get_closest_point(double Ax, double Ay, double Bx, double By, double Px, double Py){
if(Ax != Ax){
std::cout << "Ax NAN \n";
while(true){}
}
if(Ay != Ay){
std::cout << "Ay NAN \n";
while(true){}
}
double APx = Px - Ax;
double APy = Py - Ay;
double ABx = Bx - Ax;
if(ABx != ABx){
std::cout << "ABx NAN \n";
while(true){}
}
double ABy = By - Ay;
if(ABy != ABy){
std::cout << "ABy NAN \n";
while(true){}
}
double magAB2 = ABx*ABx + ABy*ABy;
if(magAB2 != magAB2){
std::cout << "magAB2 NAN \n";
while(true){}
}
double ABdotAP = ABx*APx + ABy*APy;
if(ABdotAP != ABdotAP){
std::cout << "ABdotAP NAN \n";
while(true){}
}
double t = ABdotAP / magAB2;
if(t != t){
//std::cout << "ABdotAP: " << ABdotAP << "\n";
//std::cout << "magAB2: " << magAB2 << "\n";
//std::cout << "ABx: " << ABx << "\n";
//std::cout << "ABy: " << ABy << "\n";
//std::cout << "Ax: " << Ax << "\n";
//std::cout << "Bx: " << Bx << "\n";
//std::cout << "Ay: " << Ay << "\n";
//std::cout << "By: " << By << "\n";
std::cout << "t NAN \n";
while(true){}
}
if ( t < 0){
//std::cout << "t < 0 \n";
return std::make_pair(Ax, Ay);
}
else if (t > 1){
//std::cout << "t > 1 \n";
return std::make_pair(Bx, By);
}
else{
//std::cout << "0 < t < 1 \n";
return std::make_pair(Ax + ABx*t, Ay + ABy*t);
}
}
double distance_on_line( double hypotenuse, double side){
//std::cout << "hypotenuse: " << hypotenuse << " cos: " << cos(hypotenuse) << "\n";
//std::cout << "side: " << side << " cos: " << cos(side) << "\n";
return acos(cos(hypotenuse) / cos(side));//sqrt((hypotenuse+1)*(hypotenuse-1)/(1-side)/(1+side)+1);////asin(sin(hypotenuse)*sin(acos(tan(side)/tan(hypotenuse))));//Napier's rules
}
double calculate_heading(double lat1, double long1, double lat2, double long2)
{
double a = lat1 * M_PI / 180;
double b = long1 * M_PI / 180;
double c = lat2 * M_PI / 180;
double d = long2 * M_PI / 180;
if (cos(c) * sin(d - b) == 0)
if (c > a)
return 0;
else
return 180;
else
{
double angle = atan2(cos(c) * sin(d - b), sin(c) * cos(a) - sin(a) * cos(c) * cos(d - b));
return std::fmod((angle * 180 / M_PI + 360), 360);
}
}
std::set<std::pair<double, double> > geodesic_intersections(std::pair<double, double> depo_loc, road my_road){
//std::cout << "cp5\n";
std::set<std::pair<double, double> > output;
//road my_road = std::make_pair()
//std::pair<double, double> depo_loc = std::make_pair(59.372877000, 24.641514000);
std::pair<double, double> road_A = my_road.first;//std::make_pair(59.373220858, 24.643245935);
std::pair<double, double> road_B = my_road.second;//std::make_pair(59.372310801, 24.640451074);
//std::cout << my_road.first.first << " , " << my_road.first.second << " - " << my_road.second.first << " , " << my_road.second.second << "\n";
//std::cout << "cp6\n";
std::pair<double, double> my_point = get_closest_point(road_A.first, road_A.second, road_B.first, road_B.second, depo_loc.first, depo_loc.second);//24.640451074, 59.372310801, 24.643245935, 59.373220858, 24.641514000,59.372877000);
//std::cout << "point: " << my_point.first << " , " << my_point.second << "\n";
//std::pair<double, double> n_my_point = std::make_pair(my_point.second, my_point.first);
double earth_radius = 6378137;
//std::cout << "cp7\n";
//std::cout << my_point.first << " , " << my_point.second << "\n";
if(vincenty_distance(depo_loc, my_point) <= 50){
//std::cout << "cp8\n";
double distance_to_line = vincenty_distance(depo_loc, my_point) / earth_radius;
double radius = 50 / earth_radius;
//double n_radius = radius/earth_radius;
//double n_dtl = distance_to_line/earth_radius;
//std::cout << "dist to line: " << distance_to_line << " dtl: " << n_dtl << "\n";
//double line_distance = distance_on_line(radius, distance_to_line);
//std::cout << "cp9\n";
double my_heading_1 = calculate_heading(my_point.first, my_point.second, road_A.first, road_A.second);
//std::cout << "cp10\n";
double my_heading_2 = calculate_heading(my_point.first, my_point.second, road_B.first, road_B.second);
//std::cout << "cp11\n";
double line_distance = distance_on_line(radius, distance_to_line) * earth_radius;
//std::cout << "distance on line: " << line_distance << "\n";
//std::cout << "headings: " << my_heading_1 << " , " << my_heading_2 << "\n";
//std::cout << "cp12\n";
const double halfC = M_PI / 180;
//std::cout << "cp13\n";
std::pair<double, double> n_my_point = std::make_pair(my_point.first*halfC, my_point.second*halfC);
//std::cout << "cp14\n";
std::pair<double, double> circle_point_1 = vincenty_location(n_my_point, my_heading_1*halfC, line_distance);
//std::cout << "cp15\n";
std::pair<double, double> circle_point_2 = vincenty_location(n_my_point, my_heading_2*halfC, line_distance);
//std::cout << "circle point 1: " << circle_point_1.first/halfC << " , " << circle_point_1.second/halfC << "\n";
//std::cout << "circle point 2: " << circle_point_2.first/halfC << " , " << circle_point_2.second/halfC << "\n";
//std::cout << "cp16\n";
output.insert(std::make_pair(circle_point_1.first/halfC, circle_point_1.second/halfC));
//std::cout << "cp17\n";
output.insert(std::make_pair(circle_point_2.first/halfC, circle_point_2.second/halfC));
}
//std::cout << "cp18\n";
return output;
}
/*
int main(){
road test_road = std::make_pair(std::make_pair(59.373220858, 24.643245935), std::make_pair(59.372310801, 24.640451074));
std::pair<double, double> test_depo = std::make_pair(59.372877000, 24.641514000);
vector<std::pair<double, double> > points = geodesic_intersections(test_depo, test_road);
for(auto point : points){
std::cout << "output points: " << point.first << " , " << point.second << "\n";
}
}*/
#endif
| true |
823f56261a4227bf0b74bda8244672ab74c68c32 | C++ | Lewons/PersonalProjects | /include/MyVector.h | UTF-8 | 7,410 | 3.5 | 4 | [
"MIT"
] | permissive | //
// Created by Lewon Simonian on 2019-05-21.
//
// using C++11
#ifndef GITHUB_PERSONALPROJECTS_MYVECTOR_H
#define GITHUB_PERSONALPROJECTS_MYVECTOR_H
template <class T>
class MyVector {
public:
using size_type = int32_t;
using iterator = T*;
MyVector(); //default constructor
explicit MyVector(size_type size); //create vector with size default inserted instances of T
MyVector(size_type size, const T& value); //Constructs the container with count copies of elements with value value
MyVector(iterator first, iterator last); //copy elements within range into new vector
MyVector(const MyVector& other); //copy constructor
MyVector(MyVector&& other) noexcept ; //move constructor
MyVector(std::initializer_list<T> init); //initializer list
~MyVector(); //destructor
MyVector& operator= (const MyVector& other); //copy assignment operator
MyVector& operator= (MyVector&& other) noexcept ; //move assignment operator
T& operator[] (int index) const;
void reserve(int n, bool copy = false);
iterator insert(iterator pos, const T& value);
template <typename... Args> iterator emplace(iterator pos, Args&& ...args);
void push_back(const T& item);
template <typename... Args> void emplace_back(Args&& ...args);
void pop_back();
iterator erase(iterator pos);
iterator erase(iterator first, iterator last);
bool empty() const { return m_size == 0; }
iterator begin() const {return m_arr; }
iterator end() const { return m_arr + m_size; }
T& front() const { return m_arr[0]; }
T& back() const { return m_arr[m_size - 1]; }
size_type size() const { return m_size; }
size_type capacity() const { return m_capacity; }
iterator data() const { return m_arr; }
T& at(int index) const;
void clear();
void shrink_to_fit();
void swap(MyVector& other);
private:
size_type m_size;
size_type m_capacity;
T* m_arr;
};
template <typename T>
MyVector<T>::MyVector() : m_size(0), m_capacity(0), m_arr(nullptr) { }
template <typename T>
MyVector<T>::MyVector(const size_type size)
: m_size(size)
, m_capacity(0)
, m_arr(nullptr)
{
reserve(size);
for (int i = 0; i < size; ++i) {
m_arr[i] = T();
}
}
template <typename T>
MyVector<T>::MyVector(const size_type size, const T& value)
: m_size(size)
, m_capacity(0)
, m_arr(nullptr)
{
reserve(size);
for (int i = 0; i < size; ++i) {
m_arr[i] = value;
}
}
template <typename T>
MyVector<T>::MyVector(const MyVector<T>::iterator first, const MyVector<T>::iterator last)
: m_size(last - first)
, m_capacity(0)
, m_arr(nullptr)
{
reserve(m_size);
for (int i = 0; i < m_size; ++i) {
m_arr[i] = *(first + i);
}
}
template <typename T>
MyVector<T>::MyVector(const MyVector<T>& other)
: m_size(other.m_size)
, m_capacity(other.m_capacity)
, m_arr(nullptr)
{
reserve(m_size);
for (int i = 0; i < m_size; ++i) {
m_arr[i] = other.m_arr[i];
}
}
template <typename T>
MyVector<T>::MyVector(MyVector<T>&& other) noexcept
: m_size(other.m_size)
, m_capacity(other.m_capacity)
, m_arr(other.m_arr)
{
other.m_arr = nullptr;
}
template <typename T>
MyVector<T>::MyVector(std::initializer_list<T> init) {
for(const T& element : init) {
push_back(element);
}
}
template <typename T>
MyVector<T>::~MyVector() {
delete[] m_arr;
}
template <typename T>
MyVector<T>& MyVector<T>::operator=(const MyVector& other) {
if(this == &other) {
return *this;
}
reserve(other.m_size);
m_size = other.m_size;
m_capacity = other.m_capacity;
for (int i = 0; i < m_size; ++i) {
m_arr[i] = other.m_arr[i];
}
return *this;
}
template <typename T>
MyVector<T>& MyVector<T>::operator=(MyVector&& other) noexcept {
if(this == &other) {
return *this;
}
delete[] m_arr;
m_arr = other.m_arr;
m_size = other.m_size;
m_capacity = other.m_capacity;
other.m_arr = nullptr;
return *this;
}
template <typename T>
T& MyVector<T>::operator[](int index) const {
return m_arr[index];
}
template <typename T>
void MyVector<T>::reserve(int n, bool copy) {
T* newArr = n ? new T[n] : nullptr;
if(copy) {
for(int i = 0; i < m_size; ++i) {
newArr[i] = m_arr[i];
}
}
if(m_arr != nullptr) {
delete[] m_arr;
}
m_arr = newArr;
m_capacity = n;
}
template <typename T>
void MyVector<T>::push_back(const T& item) {
if(m_size == m_capacity) {
if(m_capacity == 0) {
reserve(1);
}
else {
reserve(m_capacity * 2, true);
}
}
m_arr[m_size] = item;
m_size++;
}
template <typename T>
template <typename... Args>
void MyVector<T>::emplace_back(Args&& ...args) {
if(m_size == m_capacity) {
if(m_capacity == 0) {
reserve(1);
}
else {
reserve(m_capacity * 2, true);
}
}
m_arr[m_size] = T(std::forward<Args>(args)...);
m_size++;
}
template <typename T>
void MyVector<T>::pop_back() {
m_size--;
}
template <typename T>
typename MyVector<T>::iterator MyVector<T>::erase(MyVector::iterator pos) {
if(m_capacity == 0) {
return m_arr;
}
for (int i = pos - m_arr; i < m_size - 1; ++i) {
m_arr[i] = m_arr[i + 1];
}
m_size--;
return pos;
}
template <typename T>
typename MyVector<T>::iterator MyVector<T>::erase(MyVector::iterator first, MyVector::iterator last) {
if(m_capacity == 0) {
return m_arr;
}
uint32_t count = last - first;
for (int i = first - m_arr; i < m_size - count; ++i) {
m_arr[i] = m_arr[i + count];
}
m_size-=count;
return first;
}
template <typename T>
typename MyVector<T>::iterator MyVector<T>::insert(MyVector::iterator pos, const T& value) {
uint32_t index = pos - m_arr;
if(m_size == m_capacity) {
if(m_capacity == 0) {
reserve(1);
}
else {
reserve(m_capacity * 2, true);
}
}
for (int i = m_size; i > index; --i) {
m_arr[i + 1] = m_arr[i];
}
m_size++;
return &(m_arr[index] = value);
}
template <typename T>
template <typename... Args>
typename MyVector<T>::iterator MyVector<T>::emplace(MyVector::iterator pos, Args&& ...args) {
uint32_t index = pos - m_arr;
if(m_size == m_capacity) {
if(m_capacity == 0) {
reserve(1);
}
else {
reserve(m_capacity * 2, true);
}
}
for (int i = m_size; i > index; --i) {
m_arr[i + 1] = m_arr[i];
}
m_arr[index] = T(std::forward<Args>(args)...);
m_size++;
return &m_arr[index];
}
template <typename T>
T& MyVector<T>::at(int index) const {
if(index < 0 || index > m_size) {
//throw exception
}
else {
return m_arr[index];
}
}
template <typename T>
void MyVector<T>::clear() {
m_size = 0;
}
template <typename T>
void MyVector<T>::shrink_to_fit() {
m_capacity = m_size;
}
template <typename T>
void MyVector<T>::swap(MyVector<T>& other) {
std::swap(m_arr,other.m_arr);
std::swap(m_size,other.m_size);
std::swap(m_capacity,other.m_capacity);
}
#endif //GITHUB_PERSONALPROJECTS_MYVECTOR_H
| true |
3cb69fea0016af139494bdf5d05bff3b17011f69 | C++ | dradgun/C- | /New folder/calbase.cpp | UTF-8 | 534 | 3.375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int x;
int width,length,Rectsngle_Area;
int base,height,Triangle_Area;
cout << "Select 1.(Rectangle) or 2.(Triangle) : ";cin >> x;
if(x == 1){
cout << "Enter width, length = ";cin >> width >> length;
Rectsngle_Area = width*length;
cout << "Rectsngle Area = " << Rectsngle_Area;
}else if(x == 2){
cout << "Enter base, height = ";cin >> base >> height;
Triangle_Area = 0.5*base*height;
cout << "Triangle Area = " << Triangle_Area;
}else {
cout << "Error";
}
}
| true |
95aaa0235e53b8c13b49187b7843d73c954be1dd | C++ | jkowalski96093/MinesweeperGameSFML | /main.cpp | UTF-8 | 1,196 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include "MinesweeperBoard.h"
#include "MSBoardTextView.h"
#include "MSTextController.h"
#include "MSBoardViewSFML.h"
#include <SFML/Graphics.hpp>
int main()
{
int board_width = 10;
int board_height = 10;
GameMode mode = EASY;
MinesweeperBoard board(board_width, board_height, mode);
board.debug_display();
const int screen_width = 850;
const int screen_height = 650;
sf::RenderWindow window(sf::VideoMode(screen_width, screen_height), "My application");
window.setVerticalSyncEnabled(true);
MSBoardViewSFML SFMLboard(board, window, screen_width, screen_height);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::MouseButtonPressed)
{
SFMLboard.buttonControl(event.mouseButton.x, event.mouseButton.y, event.mouseButton.button);
}
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::R)
{
SFMLboard.restart(board_width, board_height, mode);
}
}
}
window.clear(sf::Color(0,0,0)); //tylko raz
SFMLboard.boardControl();
window.display(); //tylko raz
}
}
| true |
d5d31ae0ec6d33d8dbc9c6d448cd497f408499eb | C++ | tayloryoung6396/BullCooler | /Code/PWM_Test/PWM_Test/PWM_Test.ino | UTF-8 | 3,173 | 2.59375 | 3 | [] | no_license | double freq = 100.0;
double peltier = 80.0; // Duty cycle for the peltier
double fan = 100.0; // Duty cycle for the fan
double pump = 50.0; // Duty cycle for the pump
int aPin1 = A7;
int aPin2 = A6;
int aPin3 = A5;
int aPin4 = A4;
int aPin5 = A3;
int aPin6 = A2;
int aPin7 = A1;
int aPin8 = A0;
int aVal1 = 0;
int aVal2 = 0;
int aVal3 = 0;
int aVal4 = 0;
int aVal5 = 0;
int aVal6 = 0;
int aVal7 = 0;
int aVal8 = 0;
void setup() {
// PWM Set-up on pin: DAC1
REG_PMC_PCER1 |= PMC_PCER1_PID36; // Enable PWM
REG_PIOB_ABSR |= PIO_ABSR_P16;
REG_PIOB_ABSR |= PIO_ABSR_P17;
REG_PIOB_ABSR |= PIO_ABSR_P18; // Set PWM pin perhipheral type A or B, in this case B
REG_PIOB_PDR |= PIO_PDR_P16;
REG_PIOB_PDR |= PIO_PDR_P17;
REG_PIOB_PDR |= PIO_PDR_P18; // Set PWM pin to an output
REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1); // Set the PWM clock rate to 84MHz (84MHz/1)
REG_PWM_CMR0 = PWM_CMR_CPRE_CLKA; // Enable single slope PWM and set the clock source as CLKA
REG_PWM_CMR3 = PWM_CMR_CPRE_CLKA; // Enable single slope PWM and set the clock source as CLKA
REG_PWM_CPRD0 = 2100; // Set the PWM frequency 84MHz/40kHz = 2100
REG_PWM_CDTY0 = 1050; // Set the PWM duty cycle 50% (2100/2=1050)
REG_PWM_CPRD3 = 2100; // Set the PWM frequency 84MHz/40kHz = 2100
REG_PWM_CDTY3 = 1050; // Set the PWM duty cycle 50% (2100/2=1050)
REG_PWM_ENA = PWM_ENA_CHID0 | PWM_ENA_CHID1 | PWM_ENA_CHID2; // Enable the PWM channel
Serial.begin(115200); // open the serial port at 115200 bps:
REG_PWM_CPRD0 = (int)(84.0/0.001/freq);
REG_PWM_CPRD1 = (int)(84.0/0.001/freq);
REG_PWM_CPRD2 = (int)(84.0/0.001/freq);
REG_PWM_CDTY0 = (int)(84.0/0.001/freq/100.0*peltier);
pump = constrain(pump, 0, 25.0);
REG_PWM_CDTY1 = (int)(84.0/0.001/freq/100.0*pump);
REG_PWM_CDTY2 = (int)(84.0/0.001/freq/100.0*fan);
for(double i = 0; i < peltier; i++){
REG_PWM_CDTY0 = (int)(84.0/0.001/freq/100.0*i);
delay(10);
}
}
void loop() {
aVal5 = analogRead(aPin5);
aVal6 = analogRead(aPin6);
aVal7 = analogRead(aPin7);
aVal8 = analogRead(aPin8);
// aVal5 = map(analogRead(aPin5), 0, 1023, 0, 330);
// aVal6 = map(analogRead(aPin6), 0, 1023, 0, 330);
// aVal7 = map(analogRead(aPin7), 0, 1023, 0, 330);
// aVal8 = map(analogRead(aPin8), 0, 1023, 0, 330);
Serial.print("Temp1:");
Serial.print(aVal5);
Serial.print(", ");
Serial.print("Temp2:");
Serial.print(aVal6);
Serial.print(", ");
Serial.print("Temp3:");
Serial.print(aVal7);
Serial.print(", ");
Serial.print("Temp4:");
Serial.print(aVal8);
Serial.print(", ");
Serial.print("pump:");
Serial.print(pump);
Serial.print(", ");
Serial.print("fan:");
Serial.print(fan);
Serial.print(", ");
Serial.print("peltier:");
Serial.println(peltier);
delay(100);
}
| true |
8e4a7024527f42c190e579f5e62a02211344b9ae | C++ | varun-sundar-rabindranath/Programming | /hacker-rank/dp/longest_increasing_sunsequence/bst_dm.cpp | UTF-8 | 1,520 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <cassert>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct bst_node {
int element;
int lis;
bst_node *left;
bst_node *right;
bst_node() {
left = NULL;
right = NULL;
element = 0;
lis = 0;
}
}bst_node;
bst_node *create_bst_node() {
bst_node *bn = NULL;
bn = (bst_node *)calloc(1, sizeof(bst_node));
assert(bn != NULL);
bn->left = NULL;
bn->right = NULL;
bn->element = 0;
bn->lis = 0;
return bn;
}
typedef struct bst {
int num_elements;
bst_node *root;
bst() {
num_elements = 0;
root = NULL;
}
}bst;
void bst_insert(bst *b, int element, int lis) {
bst_node *bn = create_bst_node();
bn->element = element;
bn->lis = lis;
if(b->root == NULL) {
b->root = bn;
return;
}
bst_node *p = b->root;
bool element_added = false;
while(!element_added) {
assert(p != NULL);
if(element >= p->element) {
if(p->right == NULL) {
p->right = bn;
element_added = true;
} else {
p = p->right;
}
} else {
if(p->left == NULL) {
p->left = bn;
element_added = true;
} else {
p = p->left;
}
}
}
}
void inorder_rec(bst_node *bn) {
if(bn != NULL) {
inorder_rec(bn->left);
fprintf(stderr, " %d ", bn->element);
inorder_rec(bn->right);
}
}
void inorder(bst *b) {
inorder_rec(b->root);
cout<<endl;
}
int main() {
bst b;
for(int i = 1000; i > 0; i--) {
bst_insert(&b, i, i * 10);
}
inorder(&b);
return 0;
}
| true |
385c6ec5dc039afc2fce6204d40b53266a328758 | C++ | namvietanh1902/Coffee-Management-System | /Item.h | UTF-8 | 937 | 2.5625 | 3 | [] | no_license | #ifndef ITEM_H
#define ITEM_H
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<stdlib.h>
#include<iomanip>
#include "Hoadon.h"
using namespace std;
class Item{
private:
string maItem;
string tenItem;
int price;
public:
Item(){}
friend std::ostream& operator <<(std::ostream & ,const Item &);
friend std::istream& operator >>(std::istream &,Item &);
void setmaItem(string maIteam);
string getmaItem();
void setTenItem(string tenItem);
string getTenItem();
void setPrice(int price);
int getprice();
friend bool check_exist(const Item &x);
friend int getInfo(Item*);
friend void displayx(Item*p,string x);
friend void display(Item*);
friend void Add(Item*);
friend void Delete(Item*);
friend int check_maItem(Item *p,string ma);
};
#endif | true |
4f0954aa85748609fec7d7ff11423b2331a387b6 | C++ | gods-mack/Workspace | /dblylist.cpp | UTF-8 | 1,723 | 3.328125 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
int data;
node *prv;
node *next;
};
class list
{
node *t,*h;
public:
list() { t=NULL; h=NULL; }
void add(int x)
{
node *n=new node;
n->data=x;
if(h==NULL)
{ t=h=n; }
else
{
n->next=NULL;
n->prv=t;
t->next=n;
t=n;
}
}
void add_front(int x)
{
node *n=new node;
n->prv=NULL;
n->data=x;
h->prv=n;
n->next=h;
h=n;
}
void add_after(int after,int item)
{ node *tmp;
tmp=h;
//node *n= new node;
while(tmp!=NULL)
{
if(tmp->data==after)
break;
tmp=tmp->next; }
if(tmp==NULL)
{ cout<<"item not present"<<endl; }
else
{ node *n= new node;
n->data=item;
n->prv=tmp;
// cout<<tmp->data<<" "<<endl;
n->next=tmp->next ;
(tmp->next)->prv=n;
// cout<<(tmp->next)->data<<" "<<endl;
tmp->next=n;
// cout<<(tmp->next)->data<<" "<<endl;
}
}
void reverse()
{
node *tmp;
tmp=t;
while(tmp!=NULL)
{
cout<<tmp->data<<" ";
tmp=tmp->prv;
}
}
void del_front()
{
node *tmp;
tmp=h; h=h->next;
(tmp->next)->prv=NULL;
h=tmp->next; delete tmp;
}
void print()
{
node *tmp;
tmp=h;
while(tmp!=NULL)
{
cout<<tmp->data<<" ";
tmp=tmp->next;
}
}
};
int main()
{
list a;
a.add(33);
a.add(24);
a.add(100);
a.add_front(1000);
a.add_front(1001);
a.add_front(1002);
a.add(999);
//a.add_after(1002,99899);
//a.add_after(100,100238);
a.add_after(33,111111);
a.del_front();
a.print(); cout<<endl;
a.reverse();
}
| true |
7d52087c999518ac826a69d871530ee01a7e6592 | C++ | rudyekoprasetya/LearningArduino | /belajar1/belajar1.ino | UTF-8 | 742 | 2.875 | 3 | [] | no_license | int lampukuning=2; //saya menggunakan pin digital no 2
void setup() {
// put your setup code here, to run once:
pinMode(lampukuning, OUTPUT); //ini kode untuk setting pin tersebut mengeluarkan listrik
//aktifkan serial monitor
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0 ) { //jika ada tombol yang ditekan maka
int tombol=Serial.read(); //simpan kode tombol ke dalam variabel
Serial.println(tombol); //cetak kodenya ke layar
if(tombol=='1') {
Serial.println("Lampu Menyala");
digitalWrite(lampukuning, HIGH);
} else if (tombol=='2') {
Serial.println("Lampu Mati");
digitalWrite(lampukuning, LOW);
}
}
}
| true |
11c1fc4cb20ce8996a8152230fe58ab342fcd041 | C++ | lilmuggle/leetcode | /longestCommonPrefix.cpp | UTF-8 | 960 | 3.0625 | 3 | [] | no_license | //Original
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string s, tmp;
int i = 0, j, k, len = strs.size(), len2;
if(len == 0)
return s;
if(len == 1)
return strs[0];
while(strs[0][i]!='\0'&&strs[1][i]!='\0'&&strs[0][i]==strs[1][i])
s += strs[0][i++];
for(i = 2; i < len; i++)
{
len2 = s.size();
for(j=0;strs[i][j]!='\0'&&j<len2&&strs[i][j]==s[j];j++){}
k = 0;
while(k < j)
tmp += s[k++];
s = tmp;
tmp.clear();
}
return s;
}
};
//After improvement
string longestCommonPrefix(vector<string>& strs) {
string s="";
int len = strs.size();
for(int i=0;len>0;s+=strs[0][i++])
for(int j=0;j<len;j++)
if(i>=strs[j].size()||(j>0&&strs[j-1][i]!=strs[j][i]))
return s;
return s;
}
| true |
0392af8f952a4a6f0b33d40fb0cb31d43c3c5ba2 | C++ | YaMaks666/Bambooster | /app/core/bencodevalue.cpp | UTF-8 | 11,953 | 3.09375 | 3 | [] | no_license | #include "bencodevalue.h"
#include <QDataStream>
#include <QDebug>
BencodeValue::BencodeValue(Type type)
: m_type(type)
, m_dataPosBegin(0)
, m_dataPosEnd(0)
, m_bencodeData(nullptr)
{
}
BencodeValue::~BencodeValue()
{
}
BencodeValue::Type BencodeValue::type() const
{
return m_type;
}
bool BencodeValue::isInteger() const
{
return m_type == Type::Integer;
}
bool BencodeValue::isString() const
{
return m_type == Type::String;
}
bool BencodeValue::isList() const
{
return m_type == Type::List;
}
bool BencodeValue::isDictionary() const
{
return m_type == Type::Dictionary;
}
BencodeInteger *BencodeValue::toBencodeInteger()
{
if (!isInteger()) {
QString errorString;
QTextStream err(&errorString);
err << "BencodeValue::toBencodeInteger(): Value is not an integer: ";
print(err);
throw BencodeException(errorString);
}
return static_cast<BencodeInteger *>(this);
}
BencodeString *BencodeValue::toBencodeString()
{
if (!isString()) {
QString errorString;
QTextStream err(&errorString);
err << "bencodeValue::toBencodeString(): Value is not an string: ";
print(err);
throw BencodeException(errorString);
}
return static_cast<BencodeString *>(this);
}
BencodeList* BencodeValue::toBencodeList()
{
if (!isList()) {
QString errorString;
QTextStream err(&errorString);
err << "BencodeValue::toBencodeList(): Value is not an list: ";
print(err);
throw BencodeException(errorString);
}
return static_cast<BencodeList *>(this);
}
BencodeDictionary *BencodeValue::toBencodeDictionary()
{
if (!isDictionary()) {
QString errorString;
QTextStream err(&errorString);
err << "BencodeValue::toBencodeDictionary(): Value is not an dictionary";
print(err);
throw BencodeException(errorString);
}
return static_cast<BencodeDictionary *>(this);
}
qint64 BencodeValue::toInt()
{
return toBencodeInteger()->toInt();
}
QByteArray BencodeValue::toByteArray()
{
return toBencodeString()->toByteArray();
}
QList<BencodeValue *> BencodeValue::toList()
{
return toBencodeList()->toList();
}
QByteArray BencodeValue::getRawBencodeData(bool includeMetadata)
{
QByteArray returnData;
int begin = m_dataPosBegin;
int end = m_dataPosEnd;
if (!includeMetadata) {
begin++;
end--;
}
for (int i = begin; i < end; i++) {
returnData.push_back(m_bencodeData->at(i));
}
return returnData;
}
BencodeValue *BencodeValue::createFromByteArray(const QByteArray &data, int &position)
{
BencodeException ex("BencodeValue::createFromByteArray(): ");
if (position >= data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
BencodeValue *value;
char firstByte = data[position];
if (firstByte == 'i') {
value = new BencodeInteger;
} else if (firstByte >= '0' && firstByte <= '9') {
value = new BencodeString;
} else if (firstByte == 'l') {
value = new BencodeList;
} else if (firstByte == 'd') {
value = new BencodeDictionary;
} else {
throw ex << "Invalid begining character for bencode value: "
<< "'" << firstByte << "'."
<< "Expected 'i', 'l', 'd' or a digit.";
}
try {
value->loadFromByteArray(data, position);
} catch (BencodeException &ex2) {
delete value;
throw ex << "Failed to load value" << endl
<< ex2.what();
}
return value;
}
BencodeInteger::BencodeInteger() : BencodeValue(Type::Integer)
{
}
BencodeInteger::BencodeInteger(qint64 value)
: BencodeValue(Type::Integer)
, m_value(value)
{
}
BencodeInteger::~BencodeInteger()
{
}
qint64 BencodeInteger::toInt()
{
return m_value;
}
void BencodeInteger::loadFromByteArray(const QByteArray &data, int &position)
{
BencodeException ex("BencodeInteger::loadFromByteArray(): ");
m_bencodeData = &data;
m_dataPosBegin = position;
int &i = position;
if(i >= data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char firstByte = data[i++];
if(firstByte != 'i') {
throw ex << "First byte of Integer must be 'i', insted got '" << firstByte << "'";
}
QString valueString;
for(;;) {
if(i == data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char byte = data[i++];
if(byte == 'e') {
break;
}
if((byte < '0' || byte > '9') && byte != '-') {
throw ex << "Illegal character: '" << byte << "'";
}
valueString += byte;
}
bool ok;
m_value = valueString.toLongLong(&ok);
m_dataPosEnd = i;
if(!ok) {
throw ex << "Value not an integer: '" << valueString << "'";
}
}
BencodeString::BencodeString() : BencodeValue(Type::String)
{
}
BencodeString::BencodeString(const QByteArray& value)
: BencodeValue(Type::String)
, m_value(value)
{
}
BencodeString::~BencodeString()
{
}
QByteArray BencodeString::toByteArray()
{
return m_value;
}
void BencodeString::loadFromByteArray(const QByteArray &data, int &position)
{
BencodeException ex("BencodeString::loadFromByteArray(): ");
m_bencodeData = &data;
m_dataPosBegin = position;
int& i = position;
if(i >= data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char firstByte = data[i];
if(firstByte < '0' || firstByte > '9') {
throw ex << "First byte must be a digit, but got '" << firstByte << "'";
}
QString lengthString;
for(;;) {
if(i == data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char byte = data[i++];
if(byte == ':') {
break;
}
if((byte < '0' || byte > '9') && byte != '-') {
throw ex << "Illegal character: '" << byte << "'";
}
lengthString += byte;
}
bool ok;
int length = lengthString.toInt(&ok);
if(!ok) {
throw ex << "Length not an integer: '" << lengthString << "'";
}
for(int j = 0; j < length; j++) {
if(i == data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char byte = data[i++];
m_value += byte;
}
m_dataPosEnd = i;
}
BencodeList::BencodeList() : BencodeValue(Type::List)
{
}
BencodeList::~BencodeList()
{
for(auto value : m_values) {
delete value;
}
}
QList<BencodeValue*> BencodeList::toList()
{
return m_values;
}
void BencodeList::loadFromByteArray(const QByteArray &data, int &position)
{
BencodeException ex("BencodeList::loadFromByteArray(): ");
m_bencodeData = &data;
m_dataPosBegin = position;
int& i = position;
if(i >= data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char firstByte = data[i++];
if(firstByte != 'l') {
throw ex << "First byte of list must be 'l', instead got '" << firstByte << "'";
}
for(;;) {
if(i >= data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
if(data[i] == 'e') {
i++;
break;
}
BencodeValue* element;
try {
element = BencodeValue::createFromByteArray(data, i);
} catch(BencodeException& ex2) {
throw ex << "Failed to create element" << endl << ex2.what();
}
m_values.push_back(element);
}
m_dataPosEnd = i;
}
BencodeDictionary::BencodeDictionary() : BencodeValue(Type::Dictionary)
{
}
BencodeDictionary::~BencodeDictionary()
{
for(BencodeValue* value : m_values.values()) {
delete value;
}
}
QList<QByteArray> BencodeDictionary::keys() const
{
return m_values.keys();
}
QList<BencodeValue*> BencodeDictionary::values() const
{
return m_values.values();
}
bool BencodeDictionary::keyExists(const QByteArray& key) const
{
return m_values.keys().contains(key);
}
BencodeValue* BencodeDictionary::value(const QByteArray& key) const
{
if(keyExists(key)) {
return m_values.value(key);
}
throw BencodeException("BencodeDictionary::value(): No such key: '" + key + "'");
}
void BencodeDictionary::loadFromByteArray(const QByteArray &data, int &position)
{
BencodeException ex("BencodeDictionary::loadFromByteArray(): ");
m_bencodeData = &data;
m_dataPosBegin = position;
int& i = position;
if(i == data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
char firstByte = data[i++];
if(firstByte != 'd') {
throw ex << "First byte of a dictionary must be 'd', instead got '" << firstByte << "'";
}
for(;;) {
if(i >= data.size()) {
throw ex << "Unexpectedly reached end of the data stream";
}
if(data[i] == 'e') {
i++;
break;
}
BencodeValue* key = nullptr;
QByteArray keyString;
BencodeValue* value;
try {
key = BencodeValue::createFromByteArray(data, i);
keyString = key->toByteArray();
delete key;
key = nullptr;
} catch(BencodeException& ex2) {
if(key) {
delete key;
}
throw ex << "Failed to load key" << endl << ex2.what();
}
try {
value = BencodeValue::createFromByteArray(data, i);
} catch(BencodeException& ex2) {
throw ex << "Failed to load value" << endl << ex2.what();
}
m_values[keyString] = value;
}
m_dataPosEnd = i;
}
void BencodeInteger::setValue(qint64 value)
{
m_value = value;
}
void BencodeString::setValue(const QByteArray &value)
{
m_value = value;
}
void BencodeList::setValues(const QList<BencodeValue *> &values)
{
m_values = values;
}
void BencodeList::add(BencodeValue *value)
{
m_values.push_back(value);
}
void BencodeDictionary::add(const QByteArray& key, BencodeValue* value)
{
m_values[key] = value;
}
QByteArray BencodeInteger::bencode(bool includeMetadata) const
{
QByteArray data;
if(includeMetadata) {
data.append('i').append(QString::number(m_value)).append('e');
} else {
data.append(QString::number(m_value));
}
return data;
}
QByteArray BencodeString::bencode(bool includeMetadata) const
{
QByteArray data;
if(includeMetadata) {
data.append(QString::number(m_value.size())).append(':').append(m_value);
} else {
data.append(m_value);
}
return data;
}
QByteArray BencodeList::bencode(bool includeMetadata) const
{
QByteArray data;
if(includeMetadata) {
data.append('l');
}
for(BencodeValue* value : m_values) {
data.append(value->bencode());
}
if(includeMetadata) {
data.append('e');
}
return data;
}
QByteArray BencodeDictionary::bencode(bool includeMetadata) const
{
QByteArray data;
if(includeMetadata) {
data.append('d');
}
for(const QByteArray& key : m_values.keys()) {
BencodeString bkey(key);
data.append(bkey.bencode()).append(m_values.value(key)->bencode());
}
if(includeMetadata) {
data.append('e');
}
return data;
}
void BencodeInteger::print(QTextStream& out) const
{
out << m_value;
}
void BencodeString::print(QTextStream& out) const
{
out << m_value;
}
void BencodeList::print(QTextStream& out) const
{
out << "List {" << endl;
for(auto v : m_values) {
QString s;
QTextStream stream(&s);
v -> print(stream);
while(!stream.atEnd()) {
QString line = stream.readLine();
out << '\t' << line << endl;
}
}
out << "}";
}
void BencodeDictionary::print(QTextStream& out) const
{
out << "Dictionary {" << endl;
for(const QByteArray& key : m_values.keys()) {
out << key;
out << " : ";
QString s;
QTextStream stream(&s);
m_values[key] -> print(stream);
out << stream.readLine() << endl;
while(!stream.atEnd()) {
out << '\t' << stream.readLine() << endl;
}
}
out << "}";
}
bool BencodeInteger::equalTo(BencodeValue *other) const
{
try {
return other->toInt() == m_value;
} catch(BencodeException& ex) {
return false;
}
}
bool BencodeString::equalTo(BencodeValue *other) const
{
try {
return other->toByteArray() == m_value;
} catch(BencodeException& ex) {
return false;
}
}
bool BencodeList::equalTo(BencodeValue *other) const
{
try {
auto list = other->toList();
if(list.size() != m_values.size()) {
return false;
}
for(int i = 0; i < list.size(); i++) {
if(!list[i]->equalTo(m_values[i])) {
return false;
}
}
return true;
} catch(BencodeException& ex) {
return false;
}
}
bool BencodeDictionary::equalTo(BencodeValue *other) const
{
try {
BencodeDictionary* otherDict = other->toBencodeDictionary();
if(keys() != otherDict->keys()) {
return false;
}
if(values() != otherDict->values()) {
return false;
}
return true;
} catch(BencodeException& ex) {
return false;
}
}
| true |
88b53b3cdc6f1cef7f767e4c8e60dce53f9da6d3 | C++ | Zigje9/Algorithm_study | /c++/1449.cpp | UTF-8 | 567 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> v;
int N, L;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> L;
if(L==1){
cout << N;
return 0;
}
int a;
for(int i=0 ; i<N ; i++){
cin >> a;
v.push_back(a);
}
sort(v.begin(),v.end());
int cnt = 1;
int tmp = v[0]+L-1;
for(int i=1 ; i<N ; i++){
if(v[i]>tmp){
tmp = v[i]+L-1;
cnt += 1;
}
}
cout << cnt << endl;
return 0;
}
| true |
bd76fa7fb928fdffbb1bbe498553805b8c62429b | C++ | moble/SphericalFunctions | /WignerDMatrices.hpp | UTF-8 | 3,413 | 3.015625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2014, Michael Boyle
// See LICENSE file for details
#ifndef WIGNERDMATRICES_HPP
#define WIGNERDMATRICES_HPP
#include "Quaternions.hpp"
#include "Combinatorics.hpp"
namespace SphericalFunctions {
/// Object for pre-computing and retrieving coefficients for the Wigner D matrices
class WignerCoefficientSingleton {
private:
static const WignerCoefficientSingleton* WignerCoefficientInstance;
std::vector<double> CoefficientTable;
WignerCoefficientSingleton()
: CoefficientTable(ellMax*(ellMax*(4*ellMax + 12) + 11)/3 + 1)
{
const FactorialSingleton& Factorial = FactorialSingleton::Instance();
unsigned int i=0;
for(int ell=0; ell<=ellMax; ++ell) {
for(int mp=-ell; mp<=ell; ++mp) {
for(int m=-ell; m<=ell; ++m) {
CoefficientTable[i++] =
std::sqrt( Factorial(ell+m)*Factorial(ell-m)
/ double(Factorial(ell+mp)*Factorial(ell-mp)) );
}
}
}
}
WignerCoefficientSingleton(const WignerCoefficientSingleton& that) {
WignerCoefficientInstance = that.WignerCoefficientInstance;
}
WignerCoefficientSingleton& operator=(const WignerCoefficientSingleton& that) {
if(this!=&that) WignerCoefficientInstance = that.WignerCoefficientInstance;
return *this;
}
~WignerCoefficientSingleton() { }
public:
static const WignerCoefficientSingleton& Instance() {
static const WignerCoefficientSingleton Instance;
WignerCoefficientInstance = &Instance;
return *WignerCoefficientInstance;
}
inline double operator()(const int ell, const int mp, const int m) const {
#ifdef DEBUG
if(ell>ellMax || std::abs(mp)>ell || std::abs(m)>ell) {
std::cerr << "\n\n(ell, mp, m) = (" << ell << ", " << mp << ", " << m << ")\tellMax = " << ellMax
<< "\nWignerCoefficientSingleton is only implemented up to ell=" << ellMax
<< ".\nTo increase this bound, edit 'ellMax' in " << __FILE__ << " and recompile." << std::endl;
throw(IndexOutOfBounds);
}
#endif
return CoefficientTable[ell*(ell*(4*ell + 6) + 5)/3 + mp*(2*ell + 1) + m];
}
};
/// Object for computing the Wigner D matrices as functions of quaternion rotors
class WignerDMatrix {
/// Note that this object is a functor. The rotation should be
/// set, and then components can be taken by calling the object
/// with arguments (ell,mp,m). The rotation can then be set to
/// another value, and the process repeated. Evaluation in this
/// order is more efficient than the other way around.
public:
bool ErrorOnBadIndices;
private:
const BinomialCoefficientSingleton& BinomialCoefficient;
const WignerCoefficientSingleton& WignerCoefficient;
std::complex<double> Ra, Rb;
double absRa, absRb, absRRatioSquared;
int intlog10absRa, intlog10absRb;
public:
WignerDMatrix(const Quaternions::Quaternion& iR=Quaternions::Quaternion(1,0,0,0));
WignerDMatrix& SetRotation(const Quaternions::Quaternion& iR);
WignerDMatrix& SetRotation(const double alpha, const double beta, const double gamma) { SetRotation(Quaternions::Quaternion(alpha, beta, gamma)); return *this; }
std::complex<double> operator()(const int ell, const int mp, const int m) const;
};
} // namespace SphericalFunctions
#endif // WIGNERDMATRICES_HPP
| true |
175ef6716085a1e5da2181af369efe16fa5ec0d2 | C++ | samiksjsu/CLionProjects | /leetcode/253. Meeting Rooms II/main.cpp | UTF-8 | 274 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> arr {{7,10},{2,4}};
sort(arr.begin(), arr.end(), [] (vector<int> a, vector<int>b) {
return a.at(0) < b.at(0);
});
cout << "Hello";
} | true |
30afeee3ff51d9686e4f3d99b1fb9578c307840c | C++ | MrDolph/Competitive_Programming | /Project_Euler/Toolkit/biginteger.cpp | UTF-8 | 6,303 | 3.09375 | 3 | [] | no_license | //
// Created by Jan Krepl on 08.01.17.
//
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <cctype>
#include <math.h>
#include <set>
#include <vector>
#include "Toolkit_classes.h"
using namespace std;
biginteger biginteger::operator+(biginteger rhs) {
vector<int> smaller, bigger;
if(rhs.a.size()>= this->a.size()){
smaller = this->a;
bigger = rhs.a;
}else{
smaller = rhs.a;
bigger = this->a;
}
biginteger temp;
int remainder = 0;
int sum = 0;
vector<int>::iterator it_big = bigger.end() - 1;
for(vector<int>::iterator it = smaller.end() - 1; it >= smaller.begin(); it--){
sum = (*it + *it_big + remainder) % 10;
remainder = (*it + *it_big + remainder) / 10;
temp.a.push_back(sum);
if(it_big != bigger.begin()) {
it_big--;
}
}
if (bigger.size() == smaller.size() && remainder == 0){
}else if(bigger.size() == smaller.size() && remainder > 0){
temp.a.push_back(remainder);
}else{
while (it_big >= bigger.begin()) {
sum = (*it_big + remainder) % 10; // % 10 added
remainder = (*it_big + remainder) / 10;
temp.a.push_back(sum);
// remainder = 0;
if(it_big == bigger.begin()){
if(remainder > 0){
temp.a.push_back(remainder);
break;
}else{
break;
}
}else{
it_big--;
}
}
}
reverse(temp.a.begin(),temp.a.end());
return temp;
}
void biginteger::print() {
for(vector<int>::iterator it = this->a.begin(); it < this->a.end(); it++){
cout << *it << " ";
}
cout << endl;
}
biginteger::biginteger(const vector<int> &a) : a(a) {}
biginteger::biginteger() {
a = {};
}
int biginteger::size() {
return a.size();
}
biginteger biginteger::concatenate(biginteger rhs) {
biginteger temp;
temp = *this;
temp.a.insert(temp.a.end(),rhs.a.begin(),rhs.a.end());
return temp;
}
bool biginteger::operator>(biginteger rhs) {
if (this->size() > rhs.size()) {
return true;
} else if (this->size() < rhs.size()) {
return false;
} else {
for(int i = 0; i < rhs.size(); i++){
if(this->a.at(i) > rhs.a.at(i)){
return true;
}else if(this->a.at(i) < rhs.a.at(i)){
return false;
}else{
continue;
}
}
}
return false;
}
bool biginteger::operator<(biginteger rhs) {
return rhs>*this;
}
bool biginteger::operator==(biginteger rhs) {
return (!(*this>rhs)&&!(*this<rhs));
}
bool biginteger::is_pandi_9() {
biginteger m = *this;
if (m.a.size() != 9){
return false;
}
for(int i = 0; i < 9; i++){
if(find(m.a.begin(), m.a.end(), i + 1) == m.a.end()){
return false;
}
}
return true;
}
biginteger biginteger::multiply(int m) {
biginteger copy = *this;
biginteger result = copy;
for (int i = 1; i < m; i++){
result = result + copy;
}
return result;
}
bool biginteger::is_pandi_any() {
vector<int> digits;
digits = this->a;
if (digits.size() > 9){
return false;
}
for(int i = 0; i < digits.size(); i++){
if(find(digits.begin(), digits.end(), i + 1) == digits.end()){
return false;
}
}
return true;
}
biginteger biginteger::operator^(int rhs) {
biginteger copy = *this;
biginteger temp = copy;
for(int i = 1; i < rhs; i++){
temp = temp*copy;
}
return temp;
}
biginteger biginteger::operator*(biginteger rhs) {
biginteger up;
biginteger down;
if(this->size() >= rhs.size()){
up = *this;
down = rhs;
}else{
down = *this;
up = rhs;
}
vector<int> up_vector = up.a;
vector<int> down_vector = down.a;
biginteger overall_sum({0});
for(vector<int>::iterator it_down = down_vector.end() - 1; it_down >= down_vector.begin(); it_down-- ){
vector<int>::iterator it_up = up_vector.end() - 1;
int remainder = 0;
int to_add = 0;
biginteger temp_sum({0});
vector<int> temp_sum_vector;
while(it_up >= up_vector.begin()) {
to_add = (*it_down * (*it_up) + remainder) % 10;
temp_sum_vector.push_back(to_add);
remainder = (*it_down * (*it_up) + remainder) / 10;
if(it_up == up_vector.begin()) {
break;
}else{
it_up--;
}
}
if(remainder > 0){
temp_sum_vector.push_back(remainder);
}
reverse(temp_sum_vector.begin(),temp_sum_vector.end());
for(int i = 1; i < distance(it_down,down_vector.end()); i++){
temp_sum_vector.push_back(0);
}
temp_sum.a = temp_sum_vector;
overall_sum = overall_sum + temp_sum;
}
return overall_sum;
}
int biginteger::sum_digits() {
int output = 0;
for(vector<int>::iterator it = a.begin(); it < a.end(); it++){
output += *it;
}
return output;
}
biginteger biginteger:: reverse_me() {
biginteger output = *this;
reverse(output.a.begin(),output.a.end());
return output;
}
bool biginteger::is_palindrome() {
int my_vector_size = this->a.size();
vector<int> r_copy = this->a;
reverse(r_copy.begin(),r_copy.end());
for(int i = 0; i < my_vector_size/2; i++ ){
if(r_copy[i] != this->a[i]){
return false;
}
}
return true;
}
biginteger biginteger::last_digits(int digits) {
if(this->size()<= digits){
return *this;
}else{
vector<int>::iterator finish = this->a.end();
vector<int>::iterator start = this->a.end() - digits;
vector<int> output(start,finish);
biginteger output_bi(output);
return output_bi;
}
}
vector<int> biginteger::export_odd_digits() {
vector<int> temp;
for(int i = 0; i < this->size(); i += 2){
temp.push_back(a[i]);
}
return temp;
}
| true |
b18e2f756757dc8e5ad26d44b90ab3fd1e72fb4f | C++ | rishabhtyagi2306/Competitive-Programming | /Striver SDE SHEET/Day 4 (Hashing)/Longest substring without repeating character.cpp | UTF-8 | 672 | 2.78125 | 3 | [] | no_license | class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> cnt;
int n = s.size(), i, j;
i = j = 0;
int ans = 0;
while(i < n)
{
cnt[s[i]]++;
if(cnt.size() == (i-j+1))
{
ans = max(ans, i-j+1);
}
else
{
while(cnt.size() < (i - j + 1))
{
cnt[s[j]]--;
if(cnt[s[j]] == 0)
cnt.erase(s[j]);
j++;
}
}
i++;
}
return ans;
}
}; | true |
a264ef71475e160ff1e4c841270f17aa537e20a3 | C++ | teptind/Huffman_compression | /Huffman/HuffmanCompression/tree/trees.cpp | UTF-8 | 5,073 | 2.625 | 3 | [] | no_license | //
// Created by daniil on 20.06.19.
//
#include <algorithm>
#include <queue>
#include "trees.h"
/*ENCODING_PART*//*ENCODING_PART*//*ENCODING_PART*//*ENCODING_PART*//*ENCODING_PART*/
TreeEncoder::TreeEncoder(EntryCounter const &counter) {
auto entries = counter.get_res();
for (size_t i = 0; i < consts::ALPH_SIZE; ++i) {
if (entries[i] > 0) {
table.emplace_back(entries[i], (uint8_t)i);
}
}
std::sort(table.begin(), table.end());
auto comp = [](Node const* a, Node const* b) { return a->w > b->w; };
std::priority_queue<Node*, std::vector<Node*>, decltype(comp)> Q(comp);
for (auto p : table) {
Node *node = new Node(p.first, p.second);
Q.push(node);
}
while (Q.size() > 1) {
Node* u = Q.top();
Q.pop();
Node* v = Q.top();
Q.pop();
Node *uv = new Node(u, v);
Q.push(uv);
}
if (!Q.empty()) {
ROOT.reset(Q.top());
Q.pop();
BitSet bitSet;
make_code(ROOT, bitSet);
} else {
ROOT = nullptr;
}
}
void TreeEncoder::make_code(std::unique_ptr<Node> const &v, BitSet &curr) {
if (v == nullptr) { return; }
if (v->is_leaf()) {
symb_code[v->val] = curr;
alph_code.concat(BitSet(v->val));
} else {
tree_code.push_back(true);
curr.push_back(true);
make_code(v->left, curr);
curr.pop_back();
tree_code.push_back(false);
curr.push_back(false);
make_code(v->right, curr);
curr.pop_back();
}
}
string TreeEncoder::sizet_to_str(size_t sz) {
string res;
res.resize(consts::SIZET_SIZE);
for (size_t i = 0; i < consts::SIZET_SIZE; ++i) {
res[i] = (uint8_t)(sz >> ((consts::SIZET_SIZE - 1 - i) * 8));
}
return res;
}
string TreeEncoder::get_serve_code() const {
if (ROOT == nullptr) {
return "";
}
string res;
auto alph_data = alph_code.show_data();
auto tree_data = tree_code.show_data();
string alph_sz = sizet_to_str(alph_data.size());
string tree_sz = sizet_to_str(tree_code.get_size());
res.resize(consts::SIZET_SIZE * 2 + alph_data.size() + tree_data.size());
auto currInserter = res.begin();
std::copy(alph_sz.begin(), alph_sz.end(), currInserter);
currInserter += consts::SIZET_SIZE;
std::copy(alph_data.begin(), alph_data.end(), currInserter);
currInserter += alph_data.size();
std::copy(tree_sz.begin(), tree_sz.end(), currInserter);
currInserter += consts::SIZET_SIZE;
std::copy(tree_data.begin(), tree_data.end(), currInserter);
return res;
}
/*DECODING_PART*//*DECODING_PART*//*DECODING_PART*//*DECODING_PART*//*DECODING_PART*/
void TreeDecoder::build_tree() { // throws runtime
if (tree_code.get_size() == 1) {
ROOT = std::make_unique<Node>(2019, alph_bytes.front());
alph_bytes.pop();
return;
}
ROOT = std::make_unique<Node>();
Node *v = ROOT.get();
size_t tree_sz = tree_code.get_size();
for (size_t i = 0; i < tree_sz; ++i) {
if (tree_code.at(i)) {
v->left = std::make_unique<Node>();
v->left->parent = v;
v = v->left.get();
} else {
if (alph_bytes.empty()) {
throw std::runtime_error("incorrect alphabet");
}
v->val = alph_bytes.front();
alph_bytes.pop();
v = v->parent;
while (v->parent != nullptr && v->right != nullptr) {
v = v->parent;
}
if (v->right != nullptr) {
throw std::runtime_error("incorrect tree code");
} else {
v->right = std::make_unique<Node>();
v->right->parent = v;
v = v->right.get();
}
}
}
if (v->is_leaf()) {
if (alph_bytes.empty()) {
throw std::runtime_error("incorrect alphabet");
}
v->val = alph_bytes.front();
alph_bytes.pop();
} else {
throw std::runtime_error("incorrect tree code");
}
}
void TreeDecoder::decode_data_block(BitSet const &block) {
size_t block_sz = block.get_size();
if (tree_code.get_size() == 1) {
for (size_t i = 0; i < block_sz; ++i) {
if (block.at(i)) {
decoded_part += static_cast<char>(ROOT->val);
} else {
throw std::runtime_error("incorrect data block");
}
}
} else {
Node* v = (decoderState.curr_v == nullptr) ? ROOT.get() : decoderState.curr_v;
for (size_t i = 0; i < block_sz; ++i) {
if (block.at(i)) {
v = v->left.get();
} else {
v = v->right.get();
}
if (v == nullptr) {
throw std::runtime_error("incorrect data block");
}
if (v->is_leaf()) {
decoded_part += static_cast<char>(v->val);
v = ROOT.get();
}
}
decoderState.curr_v = v;
}
}
| true |
e9ecc1f43760f120f17f1dec4d926dfe18de5e86 | C++ | rushingJustice/C-programming-and-matlab-projects | /Finite Elements - Direct Sitffness Methods/Programs from E-book/Example3_3_2/main.cpp | UTF-8 | 3,607 | 3.59375 | 4 | [] | no_license | /* EXAMPLE 3.3.2
Copyright(c) 2001-09, S. D. Rajan
Object-Oriented Numerical Analysis
OBJECTIVES
(1) Illustrate the use of different control statements.
(2) Show healthy programming styles.
*/
#include <iostream>
#include <iomanip>
#include <ios>
#include <cmath>
#include <string>
int main ()
{
const int MAXVALUES = 11; // maximum # of storage locations
// for load and deflection values
double dVLoadData[MAXVALUES];
double dVDeflectionData[MAXVALUES];
double dVSlopes[MAXVALUES];
std::string szVPrompts[] = {"first", "second", "third", "fourth",
"fifth", "sixth", "seventh", "eighth",
"ninth", "tenth"};
// obtain user input
double dLoad;
double dDeflection;
// initialize
int nPoint=0; // number of data points
dVLoadData[nPoint] = 0.0; // first point at (0,0)
dVDeflectionData[nPoint++] = 0.0;
// loop until no more input
for (;;)
{
std::cout << "Input " << szVPrompts[nPoint-1] <<
" load and deflection values (0 load to end): ";
std::cin >> dLoad >> dDeflection;
// zero load signifies end of input
if (dLoad == 0.0)
break;
// load or deflection cannot be negative or zero
else if (dLoad < 0.0 || dDeflection <= 0.0)
std::cout << "Load and deflection values must be positive.\n";
// ordered input?
else if (dLoad <= dVLoadData[nPoint-1])
std::cout << "Load values must be in ascending order.\n";
else
{
// save the values and update counter
dVLoadData[nPoint] = dLoad;
dVDeflectionData[nPoint++] = dDeflection;
// no more storage space?
if (nPoint == (MAXVALUES-1))
break;
}
}
// compute slope of each segment
int i; // loop index
int nSegments = nPoint-1;
for (i=0; i < nSegments; i++)
{
dVSlopes[i] = (dVLoadData[i+1] - dVLoadData[i]) /
(dVDeflectionData[i+1] - dVDeflectionData[i]);
}
// find first load level at which response is nonlinear
double dTolerance = 1.0e-3; // tolerance
double dNonlinLoadValue = 0.0; // (nonlinear) load level
for (i=0; i < nSegments-1; i++)
{
if (fabs(dVSlopes[i+1] - dVSlopes[i]) > dTolerance)
{
dNonlinLoadValue = dVLoadData[i+1];
break;
}
}
// output the results
std::cout << std::endl <<" FINAL REPORT";
std::cout << std::endl <<" ------------" << std::endl;
std::cout << "Load " << " " << "Deflection" << " "
<< "Slope\n";
std::cout << "---- " << " " << "----------" << " "
<< "-----\n";
std::cout << std::setiosflags(std::ios::left)
<< std::setw(7) << dVLoadData[0] << " "
<< std::setw(10) << dVDeflectionData[0]
<< std::endl;
for (i=1; i < nPoint; i++)
{
std::cout << std::setiosflags(std::ios::left)
<< std::setw(7) << dVLoadData[i] << " "
<< std::setw(10) << dVDeflectionData[i] << " "
<< std::setw(10) << dVSlopes[i-1] << std::endl;
}
if (dNonlinLoadValue == 0.0)
std::cout << "\nResponse is entirely linear.\n";
else
std::cout << "\nResponse becomes nonlinear at " <<
dNonlinLoadValue << std::endl;
return 0;
} | true |
3d7bb1be7c887770f1f81ab703bb9a9787ec0f56 | C++ | sepalani/WiiTools | /source/functions.cpp | UTF-8 | 14,742 | 2.546875 | 3 | [] | no_license | #include "functions.hh"
vector<u32> GetU32Vector( string code )
{
vector<u32> binary;
for(u32 ii = 0; ii < code.length(); ii+=8)
{
string sub = code.substr(ii, 8);
#ifdef DEBUG_BINARY
cout << sub << endl;
#endif
const char * codeptr = sub.c_str();
u32 dword = strtoul(codeptr, NULL, 16);
#ifdef DEBUG_BINARY
cout << "0x" << hex << dword << endl;
#endif
binary.push_back( dword );
}
#ifdef DEBUG_BINARY
cout << endl;
#endif
return binary;
}
void* FindFunction(char* buffer, u32 length, vector<u32> findme)
{
u32 findme_length = findme.size();
for (u32* location = (u32*)buffer; (u8*)location < (u8*)buffer + length - findme_length * 4; location++)
{
u32 i = 0;
for (u32* check = location; check < location + findme_length; check++, i++) {
if ((findme[i] > 0x10) && (be32(*check) != findme[i]))
break;
}
if (i == findme_length)
return (void*)location;
}
return NULL;
}
char * FindFunction( char * start , char * end , const u32 * binary , u32 length )
{
if( length > (u32)( end - start ) ) return NULL;
for( char * search = start ; search < ( end - length ) ; search++ )
{
u32 * check = (u32*)search;
u32 i = 0;
for( i = 0 ; i < (length / 4) ; i++ )
{
if(*(binary+i) < 0x10)
continue;
if( Big32(binary+i) != check[i] )
break;
}
if ( i == (length / 4) )
return search;
}
return NULL;
}
char* FindFunction(char* buffer, u32 length, const u32* findme, u32 findme_length)
{
for (u32* location = (u32*)buffer; (u8*)location < (u8*)buffer + length - findme_length * 4; location++)
{
u32 i = 0;
for (u32* check = location; check < location + findme_length; check++, i++) {
if((findme[i]>0x10) && (be32(*check) != findme[i]))
break;
}
if (i == findme_length)
return (char*)location;
}
return NULL;
}
char* CheckFunction(char* buffer, u32 length, const u32* findme, u32 findme_length)
{
u32 i = 0;
for(u32* check = (u32*)buffer; check < (u32*)buffer + findme_length; check++, i++)
{
cout << hex << be32(*check)
<< "\t" << hex << findme[i];
if ((findme[i] > 0x10) && (be32(*check) != findme[i]))
cout << " NOT MATCHING!!!";
cout << endl;
}
if (i == findme_length)
return (char*)buffer;
else
cout << "missed at insn " << i << endl;
return NULL;
}
void FindSig( char* buffer, u32 length, string sig, bool dol )
{
if ( sig.length() < 5 )
return;
//FIXME
if ( sig == "---" )
return;
stringstream ss(sig);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
if ( FUNCTION_NAME_LIMIT < funcName.length() )
return;
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
#ifdef DEBUG
cout << "Size of refs: " << dec << refs.size() << endl;
cout << funcName << endl;
#endif
vector<u32> binary = GetU32Vector( code );
void * func = NULL;
func = FindFunction( buffer , length , binary );
if ( func )
{
u32 offs = 0;
u32 file_offs = (u32)((char*)func - buffer);
if ( dol )
offs = GetMemoryAddressDol(buffer, file_offs);
else
offs = file_offs + 0x80000000;
cout << funcName;
cout << " at ";
cout << "0x" << hex << offs;
cout << endl;
for(u32 ii=0; ii < refs.size(); ii++)
{
cout << dec << refs[ii].first << "\t"
<< refs[ii].second;
char* ref_offs = (char*)func + refs[ii].first;
u32 insn = Big32(ref_offs);
u32 b_amt = insn ^ 0x48000000;
if ( b_amt & 0x2000000 )
b_amt = b_amt | 0xfd000000;
b_amt &= 0xfffffffe;
u32 ref_address = offs + refs[ii].first;
ref_address += b_amt;
if ( ( insn & 0x48000000 ) == 0x48000000 )
cout << "\t" << hex << ref_address;
//u32 val = GetFileOffsetDol(buffer, address);
cout << endl;
}
/* show xrefs */
}
#ifdef QUITME
exit(1);
#endif
}
int CompareSigs( string sig1, string sig2 )
{
//FIXME
if ( sig1 == "---" )
return CMP_BAD_SIG;
if ( sig2 == "---" )
return CMP_BAD_SIG;
// SIG1
stringstream ss(sig1);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
// SIG2
stringstream ss2(sig2);
string code2 , unk12 , funcName2;
getline( ss2 , code2 , space );
getline( ss2 , unk12 , space );
getline( ss2 , funcName2 , space );
stripCarriageReturns( funcName2 );
vector< pair<int, string> > refs2;
while( !ss2.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss2 , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss2 , tempString , space );
stripCarriageReturns( tempString );
refs2.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
if(code != code2)
return CMP_BAD_CODE;
for(u32 ii=0; ii < refs.size(); ii++)
{
if(funcName != funcName2)
return CMP_BAD_NAME;
if(refs[ii].first != refs2[ii].first)
return CMP_BAD_REFNAMES;
if(refs[ii].second != refs2[ii].second)
return CMP_BAD_REFOFFS;
}
return CMP_MATCHING;
}
void ShowSigCodeDiff(string sig1, string sig2, bool stop)
{
//FIXME
if ( sig1 == "---" )
return;
if ( sig2 == "---" )
return;
// SIG1
stringstream ss(sig1);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
// SIG2
stringstream ss2(sig2);
string code2 , unk12 , funcName2;
getline( ss2 , code2 , space );
getline( ss2 , unk12 , space );
getline( ss2 , funcName2 , space );
stripCarriageReturns( funcName2 );
vector< pair<int, string> > refs2;
while( !ss2.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss2 , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss2 , tempString , space );
stripCarriageReturns( tempString );
refs2.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
vector<u32> vec1 = GetU32Vector( code );
vector<u32> vec2 = GetU32Vector( code2 );
#if 0
cout << "\t\tin:" << endl;
#endif
for(u32 ii = 0; ii < vec1.size(); ii++)
{
#if 0
cout << "\t\t\tchecked" << hex << vec1[ii] <<
"\t" << vec2[ii] << endl;
#endif
if(vec1[ii] != vec2[ii])
{
cout << "\t" << hex << ii <<
" doesn't match " <<
vec1[ii] << "\t" << vec2[ii] << endl;
if(stop)
return;
}
}
return;
}
void DumpSigInfo( string sig )
{
//FIXME
if ( sig == "---" )
return;
stringstream ss(sig);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
if ( FUNCTION_NAME_LIMIT < funcName.length() )
return;
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
#ifdef DEBUG
cout << "Size of refs: " << dec << refs.size() << endl;
#endif
cout << funcName << endl;
for(u32 ii=0; ii < refs.size(); ii++)
{
cout << "\t" << dec << refs[ii].first << "\t"
<< refs[ii].second << endl;
}
}
string GetSigName( string sig )
{
if ( sig == "---" )
return "---";
stringstream ss(sig);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
return funcName;
}
bool FindSigByName( string sig, string sigName )
{
if ( sig == "---" )
return false;
stringstream ss(sig);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
if(sigName == funcName)
return true;
else
return false;
}
char * FindBinary( char * start , u32 buffer_len , char * binary , u32 length )
{
for ( u32 i = 0 ; i < ( buffer_len - length ) ; i++ )
if ( !memcmp( start + i , binary , length ) )
return start + i;
return NULL;
}
char * FindBinary( char * start , u32 buffer_len , const u32 * binary , u32 length )
{
for ( u32 i = 0 ; i < ( buffer_len - length ) ; i++ )
{
u32 * check = (u32*)(start + i);
u32 j = 0;
for ( j = 0 ; j < length / 4 ; j++ )
if ( check[j] != Big32(binary + j) )
break;
if ( j == length / 4 )
return (start + i);
}
return NULL;
}
void CreateIDC( char* buffer, u32 length, string sig, bool dol )
{
if ( sig.length() < 5 )
return;
//FIXME
if ( sig == "---" )
return;
stringstream ss(sig);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
if ( FUNCTION_NAME_LIMIT < funcName.length() )
return;
vector< pair<int, string> > refs;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
#ifdef DEBUG
cout << "Size of refs: " << dec << refs.size() << endl;
cout << funcName << endl;
#endif
vector<u32> binary = GetU32Vector( code );
void * func = NULL;
func = FindFunction( buffer , length , binary );
if ( func )
{
u32 offs = 0;
u32 file_offs = (u32)((char*)func - buffer);
if ( dol )
offs = GetMemoryAddressDol(buffer, file_offs);
else
offs = file_offs + 0x80000000;
cout << "MakeFunction(0x" << hex << offs <<
", BADADDR); MakeName(0x" << hex << offs <<
", \"" << funcName << "\");" << endl;
for(u32 ii=0; ii < refs.size(); ii++)
{
/*
cout << dec << refs[ii].first << "\t"
<< refs[ii].second;
*/
char* ref_offs = (char*)func + refs[ii].first;
u32 insn = Big32(ref_offs);
u32 b_amt = insn ^ 0x48000000;
if ( b_amt & 0x2000000 )
b_amt = b_amt | 0xfd000000;
b_amt &= 0xfffffffe;
u32 ref_address = offs + refs[ii].first;
ref_address += b_amt;
if ( ( insn & 0x48000000 ) == 0x48000000 )
{
//cout << "\t" << hex << ref_address;
cout << "MakeFunction(0x" << hex <<
ref_address << ", BADADDR); MakeName(0x" <<
hex << ref_address << ", \"" <<
refs[ii].second << "\");" << endl;
}
//u32 val = GetFileOffsetDol(buffer, address);
//cout << endl;
}
/* show xrefs */
}
#ifdef QUITME
exit(1);
#endif
}
m_sig ParseMegaLine(string sig)
{
m_sig msig;
msig.code = "";
msig.unk1 = "0000:";
msig.funcName = "";
vector< pair<int, string> > refs;
msig.refs = refs;
if ( sig.length() < 5 )
return msig;
//FIXME
if ( sig == "---" )
return msig;
stringstream ss(sig);
string code , unk1 , funcName;
char space = ' ';
getline( ss , code , space );
getline( ss , unk1 , space );
getline( ss , funcName , space );
stripCarriageReturns( funcName );
msig.code = code;
msig.unk1 = unk1;
msig.funcName = funcName;
while( !ss.eof() )
{
//FIXME
string tempNum, tempString;
getline( ss , tempNum , space );
u32 num = strtoul(tempNum.c_str() + 1, NULL, 16);
getline( ss , tempString , space );
stripCarriageReturns( tempString );
refs.push_back( pair<int, string>(num, tempString) );
//refs.push_back( tempString );
}
msig.refs = refs;
return msig;
}
function_instance FindMSig(char* buffer, u32 length, u32 offset, m_sig sig, bool dol)
{
#if 0
cout << "buffer: " << hex << (u32)buffer << " [DEBUG]" << endl
<< "length: " << hex << length << " [DEBUG]" << endl
<< "offset: " << hex << offset << " [DEBUG]" << endl
<< "code: " << sig.code << " [DEBUG]" << endl;
#endif
function_instance instance;
instance.sig = sig;
instance.buffer_location = NULL;
instance.memory_address = 0;
vector<u32> binary = GetU32Vector( sig.code );
void * func = NULL;
func = FindFunction( buffer , length , binary );
#if 0
cout << sig.funcName << ": " << hex << (u32)func
<< " [DEBUG]" << endl;
#endif
if ( func )
{
instance.buffer_location = (char*)func;
u32 offs = 0;
u32 file_offs = (u32)((char*)func - buffer) + offset;
if ( dol )
offs=GetMemoryAddressDol(buffer-offset, file_offs);
else
offs = file_offs + 0x80000000;
instance.memory_address = offs;
}
return instance;
}
| true |
9de2c2cbb5ef2852d25aca24c90d7f2c7a822628 | C++ | kuku20/qttodolist | /queryoption.cpp | UTF-8 | 17,545 | 2.640625 | 3 | [] | no_license | #include "queryoption.h"
#include <QMessageBox>
#include <QDebug>
QSqlDatabase queryOption::dbConnection;
QString queryOption::sqlQuery;
QString queryOption::currentID,queryOption::inputNumber,queryOption::currentUser;
QSqlQuery queryOption::qry;
/**
* @brief setCon A static funciton to connect to the database
* @param none
*/
void queryOption::setCon() {
dbConnection = QSqlDatabase::addDatabase("QMYSQL");
dbConnection.setHostName("127.0.0.1");
dbConnection.setDatabaseName("test");
dbConnection.setUserName("root");
dbConnection.setPassword("");
dbConnection.setPort(3306);
if(dbConnection.open()) {
qDebug() << "Database connected!";
QSqlQuery q(dbConnection);
qry.operator=(q);
}
else {
qDebug() << "ERROR: setCon could not connect to database.";
qDebug() << "ERROR: " << dbConnection.lastError().text();
}
}
/**
* @brief queryOption::setCon set connection to the database
* @param conn
*/
void queryOption::setCon(QSqlDatabase conn) {
if(conn.open()) {
dbConnection = conn;
qDebug() << "Database connected!";
QSqlQuery q(dbConnection);
qry.operator=(q);
}
else
qDebug() << "ERROR: " << conn.lastError().text();
}
// create users table in mysql database, it will also create catalog and task table
// id is the primary key of this table
// @param none
// @return none
void queryOption::createUser() {
sqlQuery = "CREATE TABLE IF NOT EXISTS users ("
"email varchar(50) NOT NULL, password varchar(50) NOT NULL, username VARCHAR(50) NOT NULL, id int(11) NOT NULL AUTO_INCREMENT, "
"PRIMARY KEY(id))";
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "User table created!";
else {
qDebug() << "ERROR: createUser query failed.";
qDebug() << "ERROR: " << qry.lastError().text();
}
//create catalog table
createCatalog();
}
// create catalog table for all the todo list, it will also create task table
// list_no is the primary key of this table
// @param none
// @return none
void queryOption::createCatalog() {
sqlQuery = "CREATE TABLE IF NOT EXISTS Catalog ("
"id INT NOT NULL, list_no INT NOT NULL, list_name VARCHAR(50) NOT NULL, time DATE NOT NULL,"
"PRIMARY KEY(list_no));";
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "Catalog table created!";
else
qDebug() << "ERROR: createCatalog query failed.";
//create task table
createTaskTable();
}
// create task table for all the tasks inside todo lists
// task_no is the primary key of this table
// @param none
void queryOption::createTaskTable() {
sqlQuery = "CREATE TABLE IF NOT EXISTS Task ("
"list_no INT NOT NULL, task_no INT NOT NULL, task_name VARCHAR(50) NOT NULL,"
"status VARCHAR(3) NOT NULL, PRIMARY KEY(task_no));";
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "Task table created!";
else
qDebug() << "ERROR: createTaskTable query failed.";
}
// create a new todo list in catalog table
// @param list_name the name of the todo list that input by user
// @param dateInsert the date that user choose
void queryOption::newList(QString list_name, QString dateInsert) {
QString listNo = genListNo();
sqlQuery = "INSERT INTO Catalog (id, list_no, list_name, time) VALUES(:id, :no, :name, :date)";
qry.prepare(sqlQuery);
qry.bindValue(":id", getID());
qry.bindValue(":no", listNo);
qry.bindValue(":name", list_name);
qry.bindValue(":date", dateInsert);
if(qry.exec())
qDebug() << "new to-do list created!";
else {
qDebug() << "ERROR: newList function failed to create the to-do list.";
qDebug() << "ERROR:" << qry.lastError().text();
}
}
// create a new task in the task table
// @param task_name the name of the task input by user
void queryOption::newTask(QString task_name) {
QString taskNo = genTaskNo();
sqlQuery = "INSERT INTO Task VALUES(:listNo, :taskNo, :name, :stat)";
qry.prepare(sqlQuery);
qry.bindValue(":listNo", getInputNo());
qry.bindValue(":taskNo", taskNo);
qry.bindValue(":name", task_name);
qry.bindValue(":stat", "NO");
if(qry.exec())
qDebug() << "new task created!";
else {
qDebug() << "ERROR: newTask function failed to create the task.";
qDebug() << "ERROR: " << qry.lastError().text();
}
}
// generate the list number which has not been used in the catalog table, and always check the available number from 0
// @return the generated number
QString queryOption::genListNo() {
int genNo = 0;
do {
genNo++;
sqlQuery = "SELECT list_no FROM Catalog where list_no = :bNum";
qry.prepare(sqlQuery);
qry.bindValue(":bNum", genNo);
if(qry.exec())
qDebug() << "Generating list_no...";
else {
qDebug() << "ERROR: genListNo function failed.";
qDebug() << "ERROR: " << qry.lastError().text();
}
} while (qry.next());
return QString::number(genNo);
}
// generate the task number which has not been used in the task table, and always check the available number from 0
// @param none
// @return the generated number
QString queryOption::genTaskNo() {
int genNo = 0;
do {
genNo++;
sqlQuery = "SELECT task_no FROM Task where task_no = :bNum";
qry.prepare(sqlQuery);
qry.bindValue(":bNum", genNo);
if(qry.exec())
qDebug() << "Generating task_no...";
else {
qDebug() << "ERROR: genTaskNo function failed.";
qDebug() << "ERROR: " << qry.lastError().text();
}
} while (qry.next());
return QString::number(genNo);
}
// A static function that set and store the current user id to the system
// @param user_id the current user id
// @return none
void queryOption::accessID(QString user_id) {
currentID = user_id;
}
// A static function that return the user id to identify the current user
// @param none
// @return temp current user id
QString queryOption::getID() {
QString temp = currentID;
return temp;
}
// display all the todo list the current user has in the catalog table
// @param none
// @return sqlQuery for geting list table
QString queryOption::getLists() {
sqlQuery = "SELECT list_no, list_name, time "
"FROM Catalog "
"WHERE id = :userID";
qry.prepare(sqlQuery);
qry.bindValue(":userID", getID());
if(qry.exec())
qDebug() << "Displaying the catalog table...";
else {
qDebug() << "ERROR: getLists failed to display the catalog table.";
qDebug() << "ERROR: " << qry.lastError().text();
return "";
}
qDebug() << "list_no\nlist_name\ntime\n";
while (qry.next()) {
for (int i = 0; i < 3; i++) {
qDebug() << qry.value(i).toString();
}
qDebug() << "";
}
qDebug() << "Finished displaying the catalog table.";
sqlQuery = "SELECT list_no, list_name, time "
"FROM Catalog "
"WHERE id = " + getID();
return sqlQuery;
}
// display all the task inside the todo list that current user has in the task table
// @return sqlQuery for getting the task table
QString queryOption::getTasks() {
sqlQuery = "SELECT task.list_no, task.task_no, task.task_name, task.status, catalog.id "
"FROM catalog "
"JOIN task "
"ON catalog.list_no = task.list_no "
"AND task.list_no = :listNo "
"AND catalog.id = :userID";
qry.prepare(sqlQuery);
qry.bindValue(":listNo", getInputNo());
qry.bindValue(":userID", getID());
if(qry.exec())
qDebug() << "Displaying the task table...";
else {
qDebug() << "ERROR: getTasks failed to display the task table.";
qDebug() << "ERROR: " << qry.lastError().text();
return "";
}
qDebug() << "list_no\ntask_no\ntask_name\nuser_id";
while (qry.next()) {
for (int i = 0; i < 5; i++) {
qDebug() << qry.value(i).toString();
}
qDebug() << "";
}
sqlQuery = "SELECT task.list_no, task.task_no, task.task_name, task.status, catalog.id "
"FROM catalog "
"JOIN task "
"ON catalog.list_no = task.list_no "
"AND task.list_no = " + getInputNo();
return sqlQuery;
}
// delete one task in the list table
// @param taskNo the specific item that current user want to delete
// @return none
void queryOption::delTask(QString taskNo) {
sqlQuery = "DELETE FROM task WHERE task_no = :taskNo";
qry.prepare(sqlQuery);
qry.bindValue(":taskNo", taskNo);
if(qry.exec())
qDebug() << "One task has been deleted";
else {
qDebug() << "ERROR: delTask failed to delete a task in task table.";
qDebug() << "ERROR: " << qry.lastError().text();
}
}
//delete the todo list including the task inside the list
//@param listNo the specific todo list number that current user want to delete
//@return none
void queryOption::delList(QString listNo) {
//disable safe mode
sqlQuery = "SET SQL_SAFE_UPDATES = 0;";
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "The safe mode has been turned off";
else {
qDebug() << "ERROR: delList failed to turn off the safe mode.";
qDebug() << "ERROR: " << qry.lastError().text();
}
//delete the items
sqlQuery = "DELETE FROM task WHERE list_no = " + listNo;
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "The list has been deleted from the catalog table";
else {
qDebug() << "ERROR: delList failed to delete the list.";
qDebug() << "ERROR: " << qry.lastError().text();
}
sqlQuery = "DELETE FROM catalog WHERE list_no = " + listNo;
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "The tasks inside the list are deleted from the task table";
else {
qDebug() << "ERROR: delList failed to delete the tasks.";
qDebug() << "ERROR: " << qry.lastError().text();
}
//enable safe mode
sqlQuery = "SET SQL_SAFE_UPDATES = 1;";
qry.prepare(sqlQuery);
if(qry.exec())
qDebug() << "The safe mode has been turned on.";
else {
qDebug() << "ERROR: delList failed to turn on the safe mode.";
qDebug() << "ERROR: " << qry.lastError().text();
}
}
// update a task's name in the task table
// @param newUpdate the name to replace the old name as new name for item name
// @param taskNo the target task item number that needs to update
// @param kindof update either the task name or task status
// @return none
void queryOption::updateTask(QString newUpdate, QString taskNo,QString kindof) {
if(kindof=="name"){
sqlQuery = "UPDATE task SET task_name = :update WHERE task_no = :num";
}
else{
sqlQuery = "UPDATE task SET status = :update WHERE task_no = :num";
}
qry.prepare(sqlQuery);
qry.bindValue(":update", newUpdate);
qry.bindValue(":num", taskNo);
if(qry.exec())
qDebug() << "The task name has been changed.";
else {
qDebug() << "ERROR: updateTask failed to update the task name.";
qDebug() << "ERROR: " << qry.lastError().text();
}
}
// update a todo list name in the catalog table
// @param newUpdate the name to replace the old name as new name for todo list name
// @param listNo the taget todo list number that needs to update
// @return none
void queryOption::updateList(QString newUpdate, QString listNo) {
sqlQuery = "UPDATE catalog SET list_name = :update WHERE list_no = :num";
if(newUpdate=="YES" || newUpdate=="NO"){
sqlQuery = "UPDATE catalog SET noti = :update WHERE list_no = :num";
}
qry.prepare(sqlQuery);
qry.bindValue(":update", newUpdate);
qry.bindValue(":num", listNo);
if(qry.exec())
qDebug() << "The catalog_database has been changed.";
else {
qDebug() << "ERROR: updateList failed to update the task name.";
qDebug() << "ERROR: " << qry.lastError().text();
}
}
/**
* @brief queryOption::accessUser store the current user in the variable
* @param user_name current user name
*/
void queryOption::accessUser(QString user_name) {
currentUser = user_name;
qDebug()<< "current user: " << currentUser;
}
/**
* @brief queryOption::getUser return current user name
* @return temp as the current user
*/
QString queryOption::getUser() {
QString temp = currentUser;
return temp;
}
/**
* @brief queryOption::setInputNo set the listNo or taskNo for action
* @param inNum user input either the listNo or taskNo
*/
void queryOption::setInputNo(QString inNum) {
inputNumber = inNum;
}
/**
* @brief queryOption::getInputNo get the inputnumber that user typed
* @return temp as inputNumber
*/
QString queryOption::getInputNo() {
QString temp = inputNumber;
return temp;
}
//* check if the user, email, or catalog name exist
//* @param location
//* @param option
//* @return exist
int queryOption::checkIfExist(QString option, QString table) {
sqlQuery="SELECT * FROM " + table;
//depend on the table to select
//if table is user sqlQuery.length()==19
//if table is catalog sqlQuery.length()==21
qry.prepare(sqlQuery);
qry.exec();
int exist = 0;
while (qry.next()) {
QString usernamedb = qry.value(2).toString();
QString emaildb = qry.value(0).toString();
QString test = qry.value(1).toString();
if(option==usernamedb ||
sqlQuery.length()==19 && option==emaildb ||
sqlQuery.length()>25 && option==test){
exist -= 1;
return exist;
}
}
return exist;
}
// return the specific tasks lists
// @param key the input to search for specific tasks
// @param kindof search the list either by date or by name
// @return sqlQuery to search the lists
QString queryOption::searchCata(QString keys,QString kindof){
//this is for the sqlQuery when the user insert to seach cata
if(kindof=="type"){
sqlQuery = "SELECT * "
"FROM catalog "
"WHERE catalog.list_name LIKE :key AND catalog.id = :id";
qry.prepare(sqlQuery);
qry.bindValue(":key", "%" + keys + "%");
qry.bindValue(":id", getID());
}
else{
//this is for the sqlQuery when the user click the calendar
sqlQuery = "SELECT * "
"FROM catalog "
"WHERE catalog.time = :key "
"AND catalog.id = :id";
qry.prepare(sqlQuery);
qry.bindValue(":key", keys);
qry.bindValue(":id", getID());
}
if(qry.exec()){
qDebug() << "Display the Results";
}
else{
qDebug() << "ERROR: Failed to find any tasks";
qDebug() << "ERROR: " << qry.lastError().text();
}
while (qry.next()) {
for(int i = 0; i < 4; i++){
qDebug() << qry.value(i).toString();
}
qDebug() << "";
}
//this is for the sqlQuery when the user insert to seach cata
if(kindof=="type"){
sqlQuery = "SELECT * "
"FROM catalog "
"WHERE catalog.list_name LIKE '%" + keys +
"%' AND catalog.id = " + getID();
qDebug() << "second query sent: " << sqlQuery;
}
else{
//this is for the sqlQuery when the user click the calendar
sqlQuery = "SELECT * "
"FROM catalog "
"WHERE catalog.time = '" + keys +
"' AND catalog.id = " + getID();
}
return sqlQuery;
}
/**
* @brief queryOption::searchTasks search the specific task that contain the key
* @param keys the keywords search in the table
* @return sqlQuery to search the tasks
*/
QString queryOption::searchTasks(QString keys){
//make query for search key from table
sqlQuery = "SELECT catalog.id, task.list_no, task.task_no, task.task_name, task.status "
"FROM catalog, task "
"WHERE task.task_name LIKE :key "
"AND catalog.id = :id "
"AND catalog.list_no = task.task_no";
qry.prepare(sqlQuery);
qry.bindValue(":key", "%" + keys + "%");
qry.bindValue(":id", getID());
if(qry.exec()){
qDebug() << "Display the Results";
}
else{
qDebug() << "ERROR: Failed to find any list in task";
qDebug() << "ERROR: " << qry.lastError().text();
}
while (qry.next()) {
for(int i = 0; i < 4; i++){
qDebug() << qry.value(i).toString();
}
qDebug() << "";
}
sqlQuery = "SELECT catalog.id, task.list_no, task.task_no, task.task_name, task.status "
"FROM catalog, task "
"WHERE task.task_name LIKE '%" + keys +
"%' AND catalog.id = " + getID() +
" AND catalog.list_no = task.task_no";
return sqlQuery;
}
| true |
dee1e9e6cee915db61a60fd9698883282c2aae5c | C++ | AkashVD/CPP_Datastructures | /ll_del_nth.cpp | UTF-8 | 1,363 | 4.25 | 4 | [] | no_license | /*Deleting of Nodes from nth position*/
#include<iostream>
using namespace std;
class ll{
struct Node{
int data;
Node* next;
}*head;
public: ll(){
head = NULL;
}
void insert(int);
void display();
void delete_Node(int);
};
void ll::insert(int data){
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
if(head == NULL)
{
temp->next = head;
head = temp;
//cout<<"first node"<<endl;
}
else{
Node* temp1 = head;
while(temp1->next != NULL)
{
temp1 = temp1->next;
}
temp1->next=temp;
}
}
void ll::display(){
Node* temp = head;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
void ll::delete_Node(int pos){
Node* temp = head;
if(pos == 1)
{
head = temp->next;
delete temp;
return;
}
for(int i = 0; i < pos-2; i++)
{
temp = temp->next;
}
Node* temp1 = temp->next;
temp->next = temp1->next;
delete temp1;
}
int main()
{
ll obj;
int pos;
obj.insert(10);
obj.insert(12);
obj.insert(23);
obj.insert(37);
obj.display();
cout<<"Enter the position of element you want to delete : ";
cin>>pos;
obj.delete_Node(pos);
cout<<endl;
obj.display();
return 0;
} | true |
4452b7bc5f72b497b92ec845ddd11074d77a23a4 | C++ | lu-225/As-before | /2018212212124 陆家辉 实践大作业/圆排列问题.cpp | GB18030 | 1,728 | 3.09375 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
const int inf = 0x3f3f3f3f;
int n=3;
double x[110];//ÿԲĺ
double r[110];//ÿԲİ뾶
double minnr[110];//Բеİ뾶
double minn=inf;//Բг
double calCenter(int k){//Բ
double temp=0;
for(int i=1;i<k;i++){
double c=x[i]+2.0*sqrt(r[i]*r[k]);
temp=max(c,temp);
}
return temp;
}
void calLength(){//Բеܳ
double low=inf,high=0;
for(int i=1;i<=n;i++){
if(x[i]-r[i]<low){
low=x[i]-r[i];
}
if(x[i]+r[i]>high){
high=x[i]+r[i];
}
}
if(high-low<minn){
minn=high-low;
for(int i=1;i<=n;i++){
minnr[i]=r[i];
}
}
}
void backtrack(int k){ //Բ
if(k>n){//Уг
calLength();
return ;
}
for(int i=k;i<=n;i++){
swap(r[k],r[i]);
double center=calCenter(k);//ȡԲǰĺ
if(center+r[1]+r[k]<minn){//֦
x[k]=center;
backtrack(k+1);//¼
}
swap(r[k],r[i]);//
}
}
int main() {
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
scanf("%d",&n);
printf("%dԲÿԲİ뾶ֱΪ",n);
for(int i=1;i<=n;i++){
scanf("%lf",&r[i]);
printf("%f ",r[i]);
}
puts("");
backtrack(1);
printf("СԲгΪ%f\n",minn);
printf("Բ:\n");
for(int i=1;i<=n;i++){//Բ
printf("%f ",minnr[i]);
}
puts("");
return 0;
}
| true |
b9349ca9b5763189f47ee422c6e5eba011a8e00e | C++ | bakerpcc/eoj | /obj/2976 考试1.cpp | GB18030 | 766 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
int main2976() {
int a[5][5];
int i, j, k, g, groups;
int op;
scanf("%d", &groups);
for (g = 0; g < groups; g++) {
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
a[i][j] = 1;
for (i = 1; i <= 3; i++)
for (j = 1; j <= 3; j++) {
scanf("%d", &op);
// żηתûκηתηת1Ρ
if (op % 2 == 1) {
// һֿȡ0/1ֵķ!1=0, !0=1, !8=0, !!8=1
a[i][j] = !a[i][j];
a[i+1][j] = !a[i+1][j];
a[i][j+1] = !a[i][j+1];
a[i-1][j] = !a[i-1][j];
a[i][j-1] = !a[i][j-1];
}
}
for (i = 1; i <= 3; i++)
printf("%d %d %d\n", a[i][1], a[i][2], a[i][3]);
}
return 0;
} | true |
cfdce28309753685e660dc4fbcc09862877af95e | C++ | dronDrew/lab_work_week_7 | /lab_work_week_7/List_two_direction.h | UTF-8 | 5,115 | 3.703125 | 4 | [] | no_license | #pragma once
#include "List_two_direction.h"
namespace List_two_dicert {
template<typename T>
class list_two_direcktion
{
class Element {
public:
T data;
Element* privios;
Element* next;
Element(T data);
};
public:
Element* elem;
list_two_direcktion();
void Add_to_head(T data);//done
void Add_to_tail(T data);//done
void Add_to_position(int position, T data);//done
void Delete_from_head();//done
void Delete_from_tail();//done
void Delete_from_position(int position);//done
void Delete_all();//done
int Search(T key);//done
int Search_and_replace(int position, T key, T keyforreplace);//done
void Direction_swap();//done
void Show();//done
};
}
template<typename T>
List_two_dicert::list_two_direcktion<T>::Element::Element(T data) {
this->data = data;
this->next = nullptr;
this->privios = nullptr;
}
template<typename T>
List_two_dicert::list_two_direcktion<T>::list_two_direcktion() {
this->elem = nullptr;
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Show() {
if (this->elem != nullptr) {
Element* temp = this->elem;
while (temp != nullptr)
{
std::cout << temp->data << std::endl;
temp = temp->next;
}
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Add_to_head(T data) {
if (this->elem == nullptr) {
this->elem = new Element(data);
}
else
{
Element* temp = this->elem;
temp->privios = new Element(data);
temp->privios->next = this->elem;
this->elem = temp->privios;
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Add_to_tail(T data) {
if (this->elem == nullptr) {
this->elem = new Element(data);
}
else
{
Element* temp = this->elem;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = new Element(data);
temp->next->privios = temp;
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Add_to_position(int position, T data) {
if (position == 0) {
this->Add_to_head(data);
}
else
{
int place{ 0 };
Element* temp = this->elem;
while ((place + 1) < position)
{
temp = temp->next;
place++;
}
Element* temp2 = temp;
temp = temp->next;
if (temp == nullptr) {
this->Add_to_tail(data);
}
else {
Element* New_Node = new Element(data);
New_Node->privios = temp2;
New_Node->next = temp;
temp->privios = New_Node;
temp2->next = New_Node;
}
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Delete_from_head() {
if (this->elem->next == nullptr) {
Element* temp = this->elem;
delete temp;
temp = nullptr;
this->elem = temp;
}
else {
Element* temp = this->elem;
temp = temp->next;
delete temp->privios;
this->elem = temp;
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Delete_from_tail() {
if (this->elem->next == nullptr) {
Element* temp = this->elem;
delete temp;
temp = nullptr;
this->elem = temp;
}
else
{
Element* temp = this->elem;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp = temp->privios;
delete temp->next;
temp->next = nullptr;
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Delete_all() {
while (this->elem != nullptr)
{
this->Delete_from_head();
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Delete_from_position(int position) {
if (position == 0) {
this->Delete_from_head();
}
else
{
int place{ 0 };
Element* temp = this->elem;
while ((place + 1) < position)
{
temp = temp->next;
place++;
}
Element* temp2 = temp;
temp = temp->next->next;
if (temp == nullptr) {
this->Delete_from_tail();
}
else {
delete temp2->next;
temp2->next = temp;
temp->privios = temp2;
}
}
}
template<typename T>
int List_two_dicert::list_two_direcktion<T>::Search(T key) {
Element* temp = this->elem;
int posis{ 0 };
while (temp != nullptr)
{
if (temp->data == key) {
return posis;
}
posis++;
temp = temp->next;
}
return -1;
}
template<typename T>
int List_two_dicert::list_two_direcktion<T>::Search_and_replace(int position, T key, T keyforreplace) {
int how_many_replaced{ 0 };
int pos{ 0 };
Element* temp = this->elem;
while (temp != nullptr)
{
if (pos > position) {
if (temp->data == key)
{
temp->data = keyforreplace;
how_many_replaced++;
}
}
pos++;
temp = temp->next;
}
if (how_many_replaced == 0) {
return -1;
}
else
{
return how_many_replaced;
}
}
template<typename T>
void List_two_dicert::list_two_direcktion<T>::Direction_swap() {
Element* temp = this->elem;
Element* newlist;
while (temp->next != nullptr)
{
temp = temp->next;
}
newlist = new Element(temp->data);
this->Delete_from_tail();
Element* point_to_new_list = newlist;
while (this->elem != nullptr)
{
temp = this->elem;
while (temp->next != nullptr)
{
temp = temp->next;
}
point_to_new_list->next = new Element(temp->data);
point_to_new_list->next->privios = point_to_new_list->next;
point_to_new_list = point_to_new_list->next;
this->Delete_from_tail();
}
this->elem = newlist;
newlist = nullptr;
} | true |
cffabb7cacbf95395613a0327f4c31e1b48504a4 | C++ | boroppi/Cpp-Demonstration | /CPP_PERSON_TEST/Person.cpp | UTF-8 | 702 | 2.828125 | 3 | [] | no_license | #include "stdafx.h"
#include "Person.h"
#include <iostream>
using namespace std;
Person::Person(string first,string last,int arbitrary) :
firstname(first), lastname(last), arbitrarynumber(arbitrary)
{
// cout << "Constructing " << GetName() << endl;
}
string Person::GetName() const
{
return firstname + " " + lastname;
}
bool Person::operator<(Person & p)
{
return arbitrarynumber < p.arbitrarynumber;
}
bool Person::operator<(int i)
{
return arbitrarynumber < i;
}
bool operator<(int i, Person& p)
{
return i < p.arbitrarynumber;
}
void Person::AddResource()
{
pResource.reset();
pResource = make_shared<Resource>("Resource for " + GetName());
} | true |
ecc402b0a2114ba412ba439ec7f64fdc5cafb500 | C++ | hhyuanhh/First | /代码作业/广义表/广义表/GenerList.h | UTF-8 | 2,827 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<assert.h>
using namespace std;
enum Type
{
HEAD,
VALUE,
SUB,
};
struct GeneralListNode
{
Type _type;
GeneralListNode* next;
union
{
char _value;
GeneralListNode* _sublink;
};
GeneralListNode(Type type=VALUE, char value = 0) :_type(type), next(NULL)
{
if (_type == VALUE)
{
_value = value;
}
else if (_type == SUB)
{
_sublink = NULL;
}
}
};
class Generalist
{
public:Generalist() :_head(NULL) {}
~Generalist()
{
_Destory(_head);
}
Generalist(char* s) :_head(NULL)
{
_head = _CreateGeneraList(s);
}
size_t size()
{
return _size(_head);
}
size_t Depth()
{
return _Depth(_head);
}
void Print()
{
_Print(_head);
cout << endl;
}
protected:
GeneralListNode* _CreateGeneraList(char*& s)
{
assert(*s =='(');
GeneralListNode* head = new GeneralListNode(HEAD);
++s;
GeneralListNode* cur = head;
while (*s)
{
if (*s == '(')
{
GeneralListNode* subNode = new GeneralListNode(SUB);
cur->next = subNode;
cur = cur->next;
subNode->_sublink = _CreateGeneraList(s);
}
else if (*s == ')')
{
++s;
break;
}
else if (ISvalue(*s))
{
GeneralListNode* valueNode = new GeneralListNode(VALUE, *s);
cur->next = valueNode;
cur = cur->next;
++s;
}
else
{
++s;
}
}
return head;
}
protected:
void _Destory(GeneralListNode* head)
{
GeneralListNode* cur = head;
while (cur)
{
GeneralListNode* del = cur;
cur = cur->next;
if (del->_type == SUB)
{
_Destory(del->_sublink);
}
delete del;
}
}
size_t _size(GeneralListNode* head)
{
GeneralListNode*cur = head;
size_t size = 0;
while (cur)
{
if (cur->_type = VALUE)
{
++size;
}
else if (cur->_type = SUB)
{
size += _size(cur->_sublink);
}
cur = cur->next;
}
return size;
}
void _Print(GeneralListNode* head)
{
GeneralListNode*cur = head;
while (cur)
{
if (cur->_type = HEAD)
{
cout << "(";
}
else if (cur->_type = VALUE)
{
cout << cur->_value;
if (cur->next)
{
cout << ",";
}
}
else
{
_Print(cur->_sublink);
if (cur->next)
{
cout << ",";
}
}
cur = cur->next;
}
cout << ")";
}
size_t _Depth(GeneralListNode* head)
{
size_t depth = 1;
GeneralListNode* cur = head;
while (cur)
{
if (cur->_type == SUB)
{
size_t subDepth = _Depth(cur->_sublink);
if (subDepth + 1 > depth)
{
depth = subDepth + 1;
}
}
cur = cur->next;
}
return depth;
}
public:
bool ISvalue(char ch)
{
if ((ch >= '0'&&ch <= '9') || (ch >= 'a'&&ch <= 'z') || (ch >= 'A'&&ch <= 'Z'))
{
return true;
}
else
{
return false;
}
}
protected:
GeneralListNode* _head;
};
| true |
7bc152eadc1d12f12ba85b3b16cc71a1b7facec2 | C++ | himanshuParashar0101/Data-Structure-and-Algorithms | /000_BASICS/015_Pythogorean_Triplet/main.cpp | UTF-8 | 761 | 3.90625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
bool pythogorean(int max, int n1, int n2)
{
if(max*max = n1*n1 + n2*n2)
{
return true;
}
return false;
}
bool checkPythogoreanTriplet(int n1, int n2, int n3)
{
bool result;
if(n1>n2 && n1>n3)
{
result = pythogorean(n1, n2, n3);
}
else if(n2>n3)
{
result = pythogorean(n2, n1, n3);
}
else
{
result = pythogorean(n3, n1, n2);
}
return result;
}
int main()
{
int n1, n2, n3;
cin>>n1>>n2>>n3;
bool result = checkPythogoreanTriplet(n1, n2, n3);
if(result)
{
cout<<"The triplet is pythogorean"<<endl;
}
else
{
cout<<"The triplet is not pythogorean"<<endl;
}
return 0;
} | true |
73da948df75df1dccea6043e0395bdbf0565229a | C++ | Konard/TasksAndSolutions | /cpp/T5_1/T5_1.cpp | UTF-8 | 2,043 | 3.5625 | 4 | [
"Unlicense"
] | permissive | #include <iostream>
using namespace std;
bool getBit(unsigned int n, int i)
{
return (n & (1 << i)) > 0;
}
bool isPowerOfTwo(int x)
{
return (x & (x - 1)) == 0;
}
int getFirstRightBitPosition(int n)
{
int position = 1;
while (!getBit(n, position))
{
position++;
}
return position;
}
int multiply(int first, int second)
{
int result = 0;
while (second > 0)
{
result += first;
second--;
}
return result;
}
int bitwiseTransform(int x, int y)
{
int term;
if (isPowerOfTwo(x))
{
term = 27 << getFirstRightBitPosition(x);
}
else
{
term = multiply(27, x);
}
return (term + (y >> 3)) & 3;
}
int referenceTransform(int x, int y)
{
return (27 * x + (y / 8)) % 4;
}
void printBinary(unsigned int n)
{
int totalBits = sizeof(unsigned int) * 8;
bool nonZeroDigitFound = false;
for (int i = totalBits - 1; i >= 0; i--)
{
bool bitIsSet = getBit(n, i);
if (nonZeroDigitFound || bitIsSet)
{
cout << (bitIsSet ? '1' : '0');
nonZeroDigitFound = true;
}
}
}
void printHex(unsigned int n)
{
int totalHexDigits = sizeof(unsigned int) * 2;
bool nonZeroDigitFound = false;
for (int i = totalHexDigits - 1; i >= 0; i--)
{
unsigned int digit = (n & (15 << (i * 4))) >> (i * 4);
if (nonZeroDigitFound || (digit > 0))
{
cout << (char)((digit < 10) ? ('0' + digit) : ('A' + digit - 10));
nonZeroDigitFound = true;
}
}
}
int main()
{
int x, y, z;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
z = bitwiseTransform(x, y);
cout << "Z = " << z << endl;
cout << "Z = ";
printHex(z);
cout << endl;
cout << "Z = ";
printBinary(z);
cout << endl;
z = referenceTransform(x, y);
cout << "Z = " << z << endl;
cout << "Z = ";
printHex(z);
cout << endl;
cout << "Z = ";
printBinary(z);
cout << endl;
} | true |
15803eb2115d12267e41440b6c26b5ba5b2848f0 | C++ | jinsoojeong/ServerFrameworkProject2 | /Server/ServerLibrary/Database/Database.h | UHC | 534 | 2.625 | 3 | [] | no_license | #pragma once
// DB ۾ Ѱϴ Ŭ
//
#include "stdafx.h"
typedef enum
{
DB_WAIT,
DB_READY,
DB_RUNNING,
}DB_STATE;
class Database
{
public:
Database() {}
virtual ~Database() {}
virtual bool Connect(const WCHAR *serverName, const WCHAR *dbName, const WCHAR *id, const WCHAR *password) = 0;
virtual bool Connect() = 0;
virtual bool Connected() = 0;
virtual bool Disconnect() = 0;
virtual void Run() = 0;
DB_STATE &state() { return state_; }
protected:
DB_STATE state_;
};
| true |
0d88cf253729b1e3c0b1e5de10353481b0702e94 | C++ | KautzA/TeensyWalker | /HexapodCodeV4/g_servocontrol.ino | UTF-8 | 1,788 | 2.671875 | 3 | [] | no_license | //servocontrol
//map values to the servos, test for boundries and write to servos
void DXLServoMap(){
for (int i = 0; i < NUM_LEGS; i++){//Iterate through the legs
for (int j = 0; j < NUM_SERVOS_PER_LEG; j++){//Iterate through the servos on each leg
int degree_angle = leg_dynamixels[i][j] * (180.0/PI);
int servo_pos = map(degree_angle, -150, 150, 0, 1024);
if ((servo_pos > kDXLServoLimits[i][j][0])&&(servo_pos < kDXLServoLimits[i][j][1])){// Servo is within limits
ServoWrite(kDXLServoLimits[i][j][2],servo_pos);
#if defined(USER_SERIAL_TRANSMIT)
USER_SERIAL.print(kDXLServoLimits[i][j][2]);
USER_SERIAL.print("G");
#endif
}
else{//Servo not in limits
//Do nothing
#if defined(USER_SERIAL_TRANSMIT)
USER_SERIAL.print(kDXLServoLimits[i][j][2]);
USER_SERIAL.print("B");
USER_SERIAL.print(servo_pos);
USER_SERIAL.print("--");
#endif
}
//USER_SERIAL.print(ServoLimits[i][j][2]);
//USER_SERIAL.print(" ");
//USER_SERIAL.println(ServoPos);
}
#if defined(USER_SERIAL_TRANSMIT)
USER_SERIAL.println();
#endif
}
}
//-----------------------------------------------------------------
//Querry Servo
//Querry's position of a servo, if no response or response times out returns -1
//#define AX_PRESENT_POSITION_L
int ServoPosQuerry(int servo_id){
return (ax12GetRegister(servo_id,AX_PRESENT_POSITION_L,2));
}
//-----------------------------------------------------------------
//Write to Servos
void ServoWrite(int servo_id, int target_position){
SetPosition(servo_id,target_position);
/*USER_SERIAL.print(ServoID);
USER_SERIAL.print(",");
USER_SERIAL.println(Position);
*/
//Code Here
}
| true |
a3f45a8f088cd30feb4596ff221f4b0e1a7aad42 | C++ | anirudhtopiwala/Flycycle | /flight_simulator/flight_simulator.ino | UTF-8 | 1,833 | 3.09375 | 3 | [
"BSD-3-Clause"
] | permissive | /* Sense the Tilting action of an rotary potentiometer and
outputs the data on the Serial port (USB).
(c) Anthony Kelly, 2013 */
/*
A0 : X-Axis
A1 : Y-Axis
A2 : Z-Axis
*/
int pitchpin = A0,rollpin= A1;
int controllerpitch = A4;
int controllerroll = A5;
int pitchavg, rollavg;
int pitchtilt, rolltilt;
int l1 = 6;
int l2 = 7;
int r1 = 9;
int r2 = 10;
int swpin = 0;
int l1button = 0;
int r1button = 0;
int trigger = 0;
int pitchvalue = 0 ; int rollvalue = 0;
void setup() {
Serial.begin(9600); // Fast Baud rate to reduce lag
// pinMode(swpin, INPUT);
// digitalWrite(swpin, HIGH); // Enable Pullup on Switch Pin
// Calibrate the sensor for LEVEL position by taking the Average of 8 readings
pitchavg = average(pitchpin);
rollavg = average(rollpin);
pinMode(l1, INPUT);
pinMode(l2, INPUT);
pinMode(r1, INPUT);
pinMode(r2, INPUT);
digitalWrite(l1, HIGH);
digitalWrite(l2, HIGH);
digitalWrite(r1, HIGH);
digitalWrite(r2, HIGH);
}
void loop() {
pitchtilt = (analogRead(pitchpin)-pitchavg);
rolltilt = (analogRead(rollpin)-rollavg);
l1button = digitalRead(l1);
r1button = digitalRead(r1);
// Send the Data as a Serial String as follows:
// "pitchtilt, rolltilt \n"
// This String will be read by Python with lines separated by '\n'
Serial.print(pitchtilt, DEC);
Serial.print(",");
Serial.print(rolltilt, DEC);
Serial.print(",");
Serial.print(digitalRead(l1), DEC);
Serial.print(",");
Serial.print(digitalRead(l2), DEC);
Serial.print(",");
Serial.print(digitalRead(r1), DEC);
Serial.print(",");
Serial.print(digitalRead(r2), DEC);
Serial.println();
// delay(100);
}
// Get the Average of 8 readings from 'pin'
int average(int pin) {
int Ave = 0;
for (int i=0; i<8; i++) {
Ave = Ave + analogRead(pin);
}
return Ave/8;
}
| true |
4ccad61b1d0f7882e23fc292e00dfb1791d506dd | C++ | OOP2019lab/lab11-180915hassanAli | /personImp.cpp | UTF-8 | 678 | 3.8125 | 4 | [] | no_license | #include "person.h"
#include <iostream>
person::person(std::string first_name,std::string last_name,std::string age):first_name(first_name),last_name(last_name),age(age){
std::cout<<"constructor of person called"<<std::endl;
}
person::~person(){
std::cout<<"destructor of person called"<<std::endl;
}
std::string person::getfirst_name(){
return first_name;
}
std::string person::getlast_name(){
return last_name;
}
void person::setfirst_name(std::string str){
first_name=str;
}
void person::setlast_name(std::string str){
last_name=str;
}
void person::printInformation(){
std::cout<<first_name<<" "<<last_name<<" is "<<age<<" years old";
} | true |
586d77b841479d532abf33555d524d4300cace58 | C++ | htraut/css343assingment4 | /customer.h | UTF-8 | 909 | 2.890625 | 3 | [] | no_license | #ifndef CUSTOMER_H
#define CUSTOMER_H
#include <string>
#include <queue>
#include "transaction.h"
#include "history.h"
#include "borrow.h"
#include "return.h"
#include <iostream>
using namespace std;
//---------------------------------------------------------------------------
// Customer class: Customers are used to keep track of the
// processed transactions.
// Features:
// -- this class formats its own output
// -- this class allows transactions be added to its history
class Customer{
friend ostream& operator<<(ostream&, const Customer&);
public:
Customer(int, string, string);
~Customer();
int getID();
string getFirst();
string getLast();
bool checkReturn(Return*&);
bool addToHistory(Transaction*);
void getHistory();
private:
struct Node{
Transaction* data;
Node* next;
};
struct List{
Node*front;
};
int id;
string first;
string last;
List history;
};
#endif | true |