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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8edafe31e74867dd0b0450de1b05b78a39052380 | C++ | tvrandhavane/cs293Project | /finalCode.cpp | UTF-8 | 20,282 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <list>
#include <string>
#include "block.h"
#include "complex.h"
#define PI 3.14159265
#define Flow 40
#define Fhigh 15000
using namespace std;
//Little endian means to store data with least significance first
//Big endian means to store data with most significance first
//this function actually reverses the bit order from LSB to MSB
//this is for unsigned output
unsigned int UnsignedLittleToBigEndianConvert( char input[], int start, int length){
unsigned int answer = 0;
unsigned int help = 0;
unsigned int help2 = 1;
for (int n=0; n<length; n++) {
help = (int)(unsigned char)input[start+n];
answer += (help*help2);
help2 *= 256;
}
return answer;
}
// this is for signed output
//we need this function as data can have positive as well as negative amplitude from sound wave
int SignedLittleToBigEndianConvert( char input[], int start, int length){
int answer = 0;
int help = 0;
int help2 = 1;
for (int n=0; n<length-1; n++){
help = (int)(unsigned char)input[start+n];
answer += (help*help2);
help2 *= 256;
}
answer += (int)input[start+length-1]*help2;
return answer;
}
int main(){
string fname;
cout << "Enter the path of recorded file: ";
cin >> fname;
FILE *fp;
fp = fopen(fname.c_str(),"rb");
//a wave file has a structure to recognise whether it actually is a wave file.
//first "RIFF" tag is written at the top
//then size of the next part
//then it has "WAVE" written
//after that it has descriptions about format of the file
// (its not important to our code but we need to remove it as sound data is at the end)
//then it checks for the number of channels
//then comes the sample rate
//then avg bytes per sec followed by block alignment, bits per sample
//after that comes the size of the data
//finally the little endian data
if (fp)
{
char id[4], *sound_buffer; //four bytes to hold 'RIFF'
int size; //32 bit value to hold file size
size_t result;
short format_tag, channels, block_align, bits_per_sample,j; //our 16 values
int format_length, sample_rate, avg_bytes_sec, data_size, i; //our 32 bit values
fread(id, sizeof(char), 4, fp); //read in first four bytes
//if (strcmp(id, "RIFF"))
//{
fread(&size, sizeof(int), 1, fp); //read in size value
fread(id, sizeof(char), 4, fp); //read in 4 byte string now
//if (strcmp(id,"WAVE"))
//{
fread(id, sizeof(char), 4, fp);
fread(&format_length, sizeof(int),1,fp);
fread(&format_tag, sizeof(short), 1, fp);
fread(&channels, sizeof(short),1,fp); //1 mono, 2 stereo
//cout << channels << endl;
fread(&sample_rate, sizeof(int), 1, fp); //like 44100, 22050,etc
//cout << sample_rate<<endl;
fread(&avg_bytes_sec, sizeof(int), 1, fp);
//cout << avg_bytes_sec << endl;
fread(&block_align, sizeof(short), 1, fp);
//cout << block_align << endl;
fread(&bits_per_sample, sizeof(short), 1, fp); //8 bit or 16 bit file
//cout << bits_per_sample << endl;
fread(id, sizeof(char), 4, fp); //read in 'data'
fread(&data_size, sizeof(int), 1, fp); //how many bytes of sound data we have
//cout<<"Data Size: " << data_size<<endl;
sound_buffer = (char *) malloc (sizeof(char) * data_size); //set aside sound buffer space
fread(sound_buffer, sizeof(char), data_size, fp); //read in our whole sound data chunk
int t = bits_per_sample/8;
//if mono input
if(channels == 1) {
float sound_buf[data_size/t];
complex a;
//size reduces because if bits per sample more than 8 than data actually needs to be combined
for(int i=0;i<data_size;i+=t)
sound_buf[i/t]=SignedLittleToBigEndianConvert(sound_buffer,i,t)/32727.0;//endian conversion
vector<block> blocks(86);//dividing the whole data into 86 blocks on which independently
vector<bool> validBlocks(86, true);//fast fourier transform will be applied
float energySum = 0;
int zeroCrossingsSum = 0;
int blockSize = 512;//number of data elements in the block
int soundBufSize = data_size/t;
int k = 0;
//zero crossing means the numebr of times the data changes sign
//this is important in analysing data
for(int i = 0; i + 512 <= data_size/t; i+=512){
block a(sound_buf, i, i + 512);
blocks[k] = a;
zeroCrossingsSum += blocks[k].getZeroCrossings();
energySum += blocks[k].getEnergy();
k++;
}
float energyThreshold = energySum;
energyThreshold /= 86;
energyThreshold *= 0.5;//this is done to reduce the noise
//below the threshold, the data is neglected as it is noise
float zeroCrossingsThreshold = zeroCrossingsSum;
zeroCrossingsThreshold /= 86;
zeroCrossingsThreshold *= 0.5;
//noise is identified by low energy and low frequency
for(int i = 0; i < 86; i++){
if(blocks[i].getEnergy() < energyThreshold && blocks[i].getZeroCrossings() < zeroCrossingsThreshold){
validBlocks[i] = false;
}
}
int j=0;
list<block> fftBlocks;
//merge blocks which have neither low energy nor low frequency for fft
while(j < 85){
if(validBlocks[j] && validBlocks[j+1]){
block b = blocks[j].mergeBlock(blocks[j+1]);
fftBlocks.push_back(b);
}
j++;
}
vector<block> fftBlockVector(fftBlocks.size());
list<block>::iterator it;
j = 0;
for(it = fftBlocks.begin(); it != fftBlocks.end(); it++){
fftBlockVector[j] = *it;
j++;
}
//fft and peak finding
double rmean=0.0;int count =0;
vector<complex*> complexVec(fftBlocks.size());
for(j = 0; j < fftBlocks.size(); j++){
count = 0;
rmean = 0.0;
complexVec[j] = fftBlockVector[j].FFT_simple();//doing fft on data
for(int i=0; i<1024 ;i++) {
if(complexVec[j][i].get_real()>0.0){
rmean+=complexVec[j][i].get_real();
count++;
}
}
rmean/=count;
/*for(int i=0; i<1024 ;i++) {
if(abs(complexVec[j][i].get_real()) >=10*rmean && (i+1)/3 > Flow && (i+1)/3 < Fhigh)
//cout << complexVec[j][i].get_real() <<"\t"<< (i+1)/3<< endl;
else
continue;
*/
//cout << rmean << endl;
}
}
else {
//in stereo input even numbered data belong to one channel and the rest to the other
char sound_buffer1[data_size/2];
char sound_buffer2[data_size/2];
//size reduces because if bits per sample more than 8 than data actually needs to be combined
for(int i = 0;i+1<data_size;i+=2) {
sound_buffer1[i/2] = sound_buffer[i];
sound_buffer2[i/2] = sound_buffer[i+1];
}
float sound_buf1[data_size/(2*t)];
float sound_buf2[data_size/(2*t)];
complex a;
for(int i=0;i< data_size/2;i+=t) {
sound_buf1[i/t]=SignedLittleToBigEndianConvert(sound_buffer1,i,t)/32727.0;
sound_buf2[i/t]=SignedLittleToBigEndianConvert(sound_buffer2,i,t)/32727.0;
}
int blockSize = 512; //number of data elements in the block
// for channel 1
vector<block> blocks1(86); //dividing the whole data into 86 blocks on which independently
vector<bool> validBlocks1(86, true); //fft will be applied
float energySum1 = 0;
int zeroCrossingsSum1 = 0;
//zero crossing means the numebr of times the data changes sign
//this is important in analysing data as it is directly proportional to the frequency
int soundBufSize1 = data_size/(2*t);
// for channel 2
vector<block> blocks2(86); //dividing the whole data into 86 blocks on which independently
vector<bool> validBlocks2(86, true); //fft will be applied
float energySum2 = 0;
int zeroCrossingsSum2 = 0;
int soundBufSize2 = data_size/(2*t);
int k = 0;
//create blocks
for(int i = 0; i + 512 <= data_size/(2*t); i+=512){
block a(sound_buf1, i, i + 512);
block b(sound_buf2, i, i + 512);
blocks1[k] = a;
blocks2[k] = b;
zeroCrossingsSum1 += blocks1[k].getZeroCrossings();
energySum1 += blocks1[k].getEnergy();
zeroCrossingsSum2 += blocks2[k].getZeroCrossings();
energySum2 += blocks2[k].getEnergy();
k++;
}
float energyThreshold1 = energySum1;
energyThreshold1 /= 86;
energyThreshold1 *= 0.5;
//this is done to reduce the noise
//below the threshold, the data is neglected as noise
float zeroCrossingsThreshold1 = zeroCrossingsSum1;
zeroCrossingsThreshold1 /= 86;
zeroCrossingsThreshold1 *= 0.5;
float energyThreshold2 = energySum2;
energyThreshold2 /= 86;
energyThreshold2 *= 0.5;
float zeroCrossingsThreshold2 = zeroCrossingsSum2;
zeroCrossingsThreshold2 /= 86;
zeroCrossingsThreshold2 *= 0.5;
//noise is identified by low energy and low frequency
for(int i = 0; i < 86; i++){
if(blocks1[i].getEnergy() < energyThreshold1 && blocks1[i].getZeroCrossings() < zeroCrossingsThreshold1){
validBlocks1[i] = false;
}
if(blocks2[i].getEnergy() < energyThreshold2 && blocks2[i].getZeroCrossings() < zeroCrossingsThreshold2){
validBlocks2[i] = false;
}
}
int j = 0;
list<block> fftBlocks1;
list<block> fftBlocks2;
//merge blocks which have neither low energy nor low frequency for fft
while(j < 85){
if(validBlocks1[j] && validBlocks1[j+1]){
block a = blocks1[j].mergeBlock(blocks1[j+1]);
fftBlocks1.push_back(a);
}
if(validBlocks2[j] && validBlocks2[j+1]){
block b = blocks2[j].mergeBlock(blocks2[j+1]);
fftBlocks2.push_back(b);
}
j++;
}
vector<block> fftBlockVector1(fftBlocks1.size());
list<block>::iterator it;
j = 0;
for(it = fftBlocks1.begin(); it != fftBlocks1.end(); it++){
fftBlockVector1[j] = *it;
j++;
}
vector<block> fftBlockVector2(fftBlocks2.size());
j = 0;
for(it = fftBlocks2.begin(); it != fftBlocks2.end(); it++){
fftBlockVector2[j] = *it;
j++;
}
double rmean1=0.0;int count1 =0;
double rmean2=0.0;int count2 =0;
vector<complex*> complexVec1(fftBlocks1.size());
vector<complex*> complexVec2(fftBlocks2.size());
//cout << "Channel 1: "<<endl;
//apply fft and find peaks for channel 1
for(j = 0; j < fftBlocks1.size(); j++){
count1 = 0;
rmean1 = 0.0;
complexVec1[j] = fftBlockVector1[j].FFT_simple();
for(int i=0; i<1024 ;i++) {
if(complexVec1[j][i].get_real()>0.0){
rmean1+=complexVec1[j][i].get_real();
count1++;
}
}
rmean1/=count1;
/*for(int i=0; i<1024 ;i++) {
if(abs(complexVec1[j][i].get_real()) >=3*rmean1 && (i+1)/3 > Flow && (i+1)/3 < Fhigh)
cout << complexVec1[j][i].get_real() <<"\t"<< (i+1)/3<< endl;
//cout << "checkpoint 8" << endl;
else
continue;
}*/
//cout << rmean1 << endl;
}
//apply fft and find peaks for channel 1
//cout << "Channel 2: "<<endl;
for(j = 0; j < fftBlocks2.size(); j++){
count2 = 0;
rmean2 = 0.0;
complexVec2[j] = fftBlockVector2[j].FFT_simple();
//cout << "checkpoint 6" << endl;
for(int i=0; i<1024 ;i++) {
if(complexVec2[j][i].get_real()>0.0){
rmean2+=complexVec2[j][i].get_real();
count2++;
}
}
rmean2/=count2;
}
int zeroCrossingsSumC1 = 0;
int zeroCrossingsSumC2 = 0;
float energyC1 = 0.0;
float energyC2 = 0.0;
int countC1 = 0;
int countC2 = 0;
//cout << "Peaks Channel2: "<< endl;
for(int i = 0; i < fftBlockVector2.size(); i++){
fftBlockVector2[i].getVectorForPeaks();
fftBlockVector2[i].findPeaks();
list<int> peaks = fftBlockVector2[i].getPeaks();
list<int>::iterator it;
vector<float> vec = fftBlockVector2[i].getVec();
/*cout << "block index: " << i << endl;
for(it = peaks.begin(); it != peaks.end(); it++){
cout << vec[*it]<< " " << ((*it) * sample_rate) / 2048.0 << "\t";
}
cout << endl;*/
}
//calculate the charasteristics of the sound
int countPeaks2 = 0;int num2 = 0;
for(j = (int) fftBlocks2.size()*0.6; j < fftBlocks2.size(); j++){
energyC2 += fftBlockVector2[j].getEnergy();
zeroCrossingsSumC2 += fftBlockVector2[j].getZeroCrossings();
countC2++;
}
float avgCrossC2 = (float) zeroCrossingsSumC2/countC2;
float avgEnergyC2 = energyC2/countC2;
zeroCrossingsSumC2 = 0; countC2 = 0; energyC2 = 0.0;
for(j = 0; j < fftBlocks2.size()*0.01; j++){
energyC2 += fftBlockVector2[j].getEnergy();
zeroCrossingsSumC2 += fftBlockVector2[j].getZeroCrossings();
countC2++;
}
float avgCrossI2 = (float) zeroCrossingsSumC2/countC2;
float avgEnergyI2 = energyC2/countC2;
zeroCrossingsSumC2 = 0; countC2 = 0; energyC2 = 0.0;
float totalEnergy = 0.0;
for(j = 0; j < fftBlocks2.size(); j++){
totalEnergy += fftBlockVector2[j].getEnergy();
}
for(j = fftBlocks2.size()*0.3; j < fftBlocks2.size()*0.5; j++){
energyC2 += fftBlockVector2[j].getEnergy();
zeroCrossingsSumC2 += fftBlockVector2[j].getZeroCrossings();
countC2++;
}
float avgCrossM2 = (float) zeroCrossingsSumC2/countC2;
float avgEnergyM2 = energyC2/countC2;
float fracEnergyM2 = energyC2/totalEnergy;
//cout << "Channel2 0.01 : " << avgEnergyI2 << "\t" << avgCrossI2 << endl;
//cout << "Channel2 0.2 : " << avgEnergyM2 << "\t" << avgCrossM2 << "\t" << fracEnergyM2 << endl;
//cout << "Channel2 0.6 : " << avgEnergyC2 << "\t" << avgCrossC2 << endl;
//matching of enrgies and frequencies for variety of phonemes,
//according to that output the word spoken
if((avgEnergyI2 < 1350000.0 && avgEnergyI2 > 1200000.0) || (avgCrossI2 < 55.0 && avgCrossI2 > 50.0) || avgEnergyI2 < 3000.0)
cout << "close" << endl;
else if((avgCrossC2 < 50.0 && avgCrossC2 > 40.0) || (avgEnergyC2 < 4000.0 && avgEnergyC2 > 3400.0) || ((avgCrossC2-51.0) < 1.0 && (avgCrossC2-51.0) > 0.0))
cout << "save" << endl;
else if(avgCrossC2 < 70.0 || avgEnergyC2 < 5000.0)
cout << "no" << endl;
else
cout << "yes" << endl;
//------------------------------------------------------------
}
//}
//else
// printf("Error: RIFF file but not a wave file\n");
//}
//else
// printf("Error: not a RIFF file\n");
}
return 0;
}
| true |
9fab14dfa5afd95dd3bfd348af3dfe1f272918e9 | C++ | mPorst/cppGameEngine | /sdlBlubb/forces.cpp | UTF-8 | 375 | 2.765625 | 3 | [] | no_license | #include "forces.h"
void applyForce(physicsObject object, glm::vec3 force) // make object move
{
object.setSpeed( object.getSpeed() + accelerationFromForce(object, force) ); // acceleration from force needs to be multiplied by frametime ! Frametimemanager !!!
}
glm::vec3 accelerationFromForce(physicsObject object, glm::vec3 force)
{
return force / object.getMass();
}
| true |
00362bf080e17bba53a2600a389d122101f3ddca | C++ | p-robot/gridsim | /include/Node.h | UTF-8 | 3,160 | 3.40625 | 3 | [
"CC-BY-4.0"
] | permissive | #ifndef NODE_H
#define NODE_H
#include "Point.h"
#include "Config.h"
class Cell;
class Grid;
/**
Describes one node in the landscape. Status is described
as an integer, 0 = susceptible, 1 = exposed, 2 = infectious,
3 = detected, 4 = removed.
*/
class Node
{
public:
/**
Construct using x and y coordinates, number of animals, id and config object.
*/
Node(double x, double y, unsigned int num_sp1, unsigned int num_sp2, unsigned int id,
unsigned int group, const Config& C, Grid* G);
~Node();
Point get_position(); ///Returns the position of this node. Inlined
unsigned int get_num_sp1(); ///Returns the number of animals of species 1 of this node.
unsigned int get_num_sp2(); ///Returns the number of animals of species 2 of this node.
unsigned int get_id(); ///Returns the node's id.
unsigned int get_group(); ///Returns the node's group.
double get_susceptibility(); ///Returns node's normalized susceptibility.
double get_infectiousness(); ///Returns node's normalized infectiousness.
int get_status(); ///Returns the current status of this node.
int get_time_of_infection(); ///Returns the time step that this node got infected. Returns -1 if not infected.
Cell* get_parent(); ///Returns the parent cell of this node.
void set_susceptibility(double s); ///Sets the total normalized susceptibility of this node.
void set_infectiousness(double i); ///Sets the total normalized infectiousness of this node.
void set_status(int val); ///Sets the infections status of this node.
void set_parent(Cell* in_parent); ///Sets the parent cell of this noe to arg.
void update(); ///Update status for this timestep.
void reset(); ///Reset this node to its original state (susceptible).
void become_seeded(); ///Seed this node.
void become_exposed(); ///Expose this node to infection.
void become_infectious(); ///Turns this node infectious.
void become_detected(); ///Turns this node into detected.
void become_removed(); ///Turns this node into removed.
private:
Point position; ///Position.
unsigned int num_sp1 = 0; ///Number of animals of species 1 of this node.
unsigned int num_sp2 = 0; ///Number of animals of species 2 of this node.
unsigned int id; ///Identifier for this node.
unsigned int group; ///Which group does this node belong to. Eg. county.
const Config& C; ///Config parameters.
Grid* parent_grid; ///Pointer back to the grid object that the node belongs to.
double susceptibility = 1.0; ///Total normalized susceptibility of this node.
double infectiousness = 1.0; ///Total normalized infectiousness of this node.
double current_cell_p_over = 1.0;
unsigned int status = 0; ///Current status of node.
int infection_time = -1;
int countdown = 0; ///Keeps track of when its time for transition.
Cell* parent; ///Parent cell.
};
inline Point Node::get_position()
{
return position;
}
#endif // NODE_H
| true |
ab7024035c69db34f0fcc315000897764330b16b | C++ | R4GH4V/geeksforgeeks-Practise | /School/Print 1 to n without using loops.cpp | UTF-8 | 544 | 3.484375 | 3 | [] | no_license | /*
Print numbers from 1 to n without the help of loops.
Input:
The first line of the input contains T denoting the number of testcases. First line of test case contain number n.
Output:
Numbers from 1 to n will be printed.
Constraints:
1 <=T<= 100
1 <=N<= 990
Example:
Input:
1
10
Output:
1 2 3 4 5 6 7 8 9 10
*/
#include<iostream>
using namespace std;
int main()
{
int t,n,i;
cin>>t;
while(t--)
{
i=1;
cin>>n;
start:
cout<<i<<" ";
i++;
if(i<=n)
goto start;
cout<<endl;
}
return 0;
}
| true |
28fd2baf6bae8698188e1d9ae22b7ad929c40274 | C++ | cauassa/AED1_2016-2 | /equipe3/Eqp3_q8.cpp | ISO-8859-1 | 1,148 | 3.375 | 3 | [] | no_license | //Lista 1 - Reviso
//Questo 8 - Dada uma matriz real Amxn, verificar se existem elementos repetidos em A.
using namespace std;
#include <cstdlib>
#include <iostream>
#include <iomanip>
#define MAX 100
main(){
int matriz[2][2], i, j, k, elementos[MAX], repetidos[MAX], cont1, cont2;
cout << "Dada uma Matriz 2x2 entre com os valores de linhaXcoluna \n\n";
for(i=0;i<2;i++){
for(j=0;j<2;j++){
cout << "Insira ["<<i<<"]["<<j<<"]: ";
cin >> matriz[i][j];
}
}
cout << "\n\nMatriz digitada: \n" <<endl;
for(i=0;i<2;i++){
for(j=0;j<2;j++){
cout << matriz[i][j];
cout << "\t";
}
cout << "\t" <<endl;
}
k=0;
for(i=0;i<2;i++){
for(j=0;j<2;j++){
k++;
}
}
cont1=0;
for(i=0;i<2;i++){
for(j=0;j<2;j++){
elementos[cont1] = matriz[i][j];
cont1++;
}
}
cont2=0;
for(i=0;i<k;i++){
if(elementos[i] == elementos[i+1])//se tiver elementos iguais
repetidos[i] = elementos[i];
cont2++;
}
cout << "\nElementos repetidos: \n\n";
for(i=0;i<cont2;i++){
cout <<repetidos[i]<<"\n";
}
}
| true |
3e7f34ae7e35348ef3f35e0aa42088587166ce15 | C++ | daniil6/RBKLib | /src/read_file.cpp | UTF-8 | 964 | 3.234375 | 3 | [] | no_license | #include <fstream>
#include <vector>
std::string ReadFileS(std::string line)
{
setlocale(LC_ALL, "Russian");
std::ifstream in(line); // Open file for read
if(in.is_open())
getline(in, line);
in.close(); // Close file
return line;
}
std::string ReadFileL(std::string line)
{
setlocale(LC_ALL, "Russian");
FILE* file;
file = fopen(&line[0], "r");
line.clear();
if(file == nullptr)
return line;
char ch = 0;
while(ch != EOF || feof(file) == false || ferror(file) == true) {
ch = fgetc(file);
line.push_back(ch);
}
line.pop_back(); // delete last excess symbol // why?
fclose(file);
return line;
}
char* ReadFileZ(std::string line, int& size)
{
std::string t_line = ReadFileL(line);
size = t_line.size();
char* result = new char[size];
for(int i = 0; i < size; i++)
result[i] = t_line.at(i);
return result;
}
void ReadFileA()
{
} | true |
bf3493489ead4d218443135ebc20060c57b8c826 | C++ | GiovanniMarchetto/advanced_programming_exam_2020 | /src/bst.cpp | UTF-8 | 11,731 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <utility> // std::forward, move
#include <string>
#include <sstream>
#include "Node.h"
#include "Iterator.h"
#include "ap_error_ext.h"
#include "bst.h"
#ifndef ADVANCED_PROGRAMMING_EXAM_2020_BST_CPP
#define ADVANCED_PROGRAMMING_EXAM_2020_BST_CPP
template <typename value_type, typename key_type, typename OP>
Node<value_type, key_type, OP>* bst<value_type, key_type, OP>::
release_node(const Node<value_type, key_type, OP>* const node_to_release)
{
AP_ERROR_IF_NULLPTR(node_to_release, "node_to_release", false);
if (node_to_release->get_parent() == nullptr)
return this->release_tree_root_node();
if (node_to_release->get_parent()->get_left() == node_to_release)
return node_to_release->get_parent()->release_left();
return node_to_release->get_parent()->release_right();
}
template <typename value_type, typename key_type, typename OP>
Node<value_type, key_type, OP>* bst<value_type, key_type, OP>::
get_minimum_left_node_in_subtree(Node<value_type, key_type, OP>* node) noexcept
{
while (node && node->get_left())
node = node->get_left();
return node;
}
template <typename value_type, typename key_type, typename OP>
bst<value_type, key_type, OP>::
bst(const bst& other) : size{ other.size }, node_key_compare{ other.node_key_compare }
{
if (other.get_tree_root_node())
set_tree_root_node(new node{ *(other.get_tree_root_node()) });
}
template <typename value_type, typename key_type, typename OP>
bst<value_type, key_type, OP>& bst<value_type, key_type, OP>::
operator=(const bst& other)
{
auto tmp{ bst(other) }; // invoke the copy ctor
*this = std::move(tmp); // move assignment
return *this;
}
template <typename value_type, typename key_type, typename OP>
template <typename K, typename V>
std::pair<typename bst<value_type, key_type, OP>::iterator, bool> bst<value_type, key_type, OP>::
private_insert(K&& k, V&& v)
{
AP_ERROR_IF_NULLPTR(k, "k", false);
node* prev{ nullptr };
node* curr = get_tree_root_node();
while (curr)
{
prev = curr;
if (node_key_compare(k, curr->key))
curr = curr->get_left();
else if (node_key_compare(curr->key, k))
curr = curr->get_right();
else // key already present in the bst
return std::make_pair<iterator, bool>(iterator{ prev }, false);
}
node* n = new node{ std::forward<K>(k), std::forward<V>(v) };
n->set_parent(prev);
if (!prev) // if the tree was empty
set_tree_root_node(n);
else if (*n < *prev) // operator overloading of <
prev->set_left(n);
else
prev->set_right(n);
++size;
return std::make_pair<iterator, bool>(iterator{ n }, true);
}
template <typename value_type, typename key_type, typename OP>
inline std::pair<typename bst<value_type, key_type, OP>::iterator, bool> bst<value_type, key_type, OP>::
insert(const std::pair<key_type, value_type>& x)
{
AP_ERROR_IF_NULLPTR(x.first, "x.first", true);
return private_insert(x.first, x.second);
}
template <typename value_type, typename key_type, typename OP>
inline std::pair<typename bst<value_type, key_type, OP>::iterator, bool> bst<value_type, key_type, OP>::
insert(std::pair<key_type, value_type>&& x)
{
AP_ERROR_IF_NULLPTR(x.first, "x.first", true);
return private_insert(std::move(x.first), std::move(x.second));
}
template <typename value_type, typename key_type, typename OP>
template <class... Types>
inline std::pair<typename bst<value_type, key_type, OP>::iterator, bool> bst<value_type, key_type, OP>::
emplace(Types &&...args)
{
return private_insert(std::forward<Types>(args)...);
}
template <typename value_type, typename key_type, typename OP>
inline void bst<value_type, key_type, OP>::
clear() noexcept
{
set_tree_root_node();
size = 0;
}
template <typename value_type, typename key_type, typename OP>
void bst<value_type, key_type, OP>::
unbalance()
{
if (get_size())
{
bst tmp{};
for (node& el : *this)
tmp.emplace(std::move(el.key), std::move(el.value));
*this = std::move(tmp);
}
}
template <typename value_type, typename key_type, typename OP>
void bst<value_type, key_type, OP>::
recursive_balance(const size_t start, const size_t stop, bst<value_type, key_type, OP>& balanced, Node<value_type, key_type, OP>* const arr[])
{
if (start != stop)
{
size_t mid{ (start + stop) / 2 };
balanced.emplace(std::move(arr[mid]->key), std::move(arr[mid]->value));
recursive_balance(start, mid, balanced, arr);
recursive_balance(mid + 1, stop, balanced, arr);
}
}
template <typename value_type, typename key_type, typename OP>
void bst<value_type, key_type, OP>::
balance()
{
if (get_size())
{
bst tmp{};
node* nodes[get_size()];
size_t i{ 0 };
for (auto& el : *this)
{
nodes[i] = ⪙
++i;
}
recursive_balance(0, get_size(), tmp, nodes);
*this = std::move(tmp);
}
}
template <typename value_type, typename key_type, typename OP>
template <typename key_type_>
value_type& bst<value_type, key_type, OP>::
subscripting(key_type_&& x)
{
AP_ERROR_IF_NULLPTR(x, "x", false);
auto iter = find(std::forward<key_type_>(x));
if (iter == end())
{
auto from_insert = emplace(std::forward<key_type_>(x), value_type{});
return from_insert.first->value; // from_insert.first is the iterator
}
return iter->value;
}
template <typename value_type, typename key_type, typename OP>
inline value_type& bst<value_type, key_type, OP>::
operator[](const key_type& x)
{
AP_ERROR_IF_NULLPTR(x, "x", true);
return subscripting(x);
}
template <typename value_type, typename key_type, typename OP>
inline value_type& bst<value_type, key_type, OP>::
operator[](key_type&& x)
{
AP_ERROR_IF_NULLPTR(x, "x", true);
return subscripting(std::move(x));
}
template <typename value_type, typename key_type, typename OP>
Node<value_type, key_type, OP>* bst<value_type, key_type, OP>::
private_find(const key_type& key_to_find) const
{
AP_ERROR_IF_NULLPTR(key_to_find, "key_to_find", false);
node* node{ get_tree_root_node() }; // search starts from the root
while (node)
{
if (node_key_compare(key_to_find, node->key))
node = node->get_left();
else if (node_key_compare(node->key, key_to_find))
node = node->get_right();
else
break;
}
return node;
}
template <typename value_type, typename key_type, typename OP>
typename bst<value_type, key_type, OP>::iterator bst<value_type, key_type, OP>::
find(const key_type& x)
{
AP_ERROR_IF_NULLPTR(x, "x", true);
node* node{ private_find(x) };
if (node)
return iterator{ node };
return end();
}
template <typename value_type, typename key_type, typename OP>
typename bst<value_type, key_type, OP>::const_iterator bst<value_type, key_type, OP>::
find(const key_type& x) const
{
AP_ERROR_IF_NULLPTR(x, "x", true);
const node* node{ private_find(x) };
if (node)
return const_iterator{ node };
return cend();
}
template <typename value_type, typename key_type, typename OP>
void bst<value_type, key_type, OP>::
erase(const key_type& x)
{
AP_ERROR_IF_NULLPTR(x, "x", true);
node* to_erase = private_find(x);
if (to_erase == nullptr) // case 0: node to delete does not exist (wrong key provided)
return;
enum class to_remove_child_type { left, right, root };
auto get_child_type = [this](node* child) {
node* parent = child->get_parent();
if (parent == nullptr) // if child hasn't parent node => child is the root
return to_remove_child_type::root;
else if (child == parent->get_left()) // if child is the left child of its parent
return to_remove_child_type::left;
else // if child is the right child of its parent
return to_remove_child_type::right;
};
// Erases to_remove (and its children if it has any and they are managed smart pointers)
auto transpose_subtree = [this](node* to_remove, to_remove_child_type ct, node* to_transplant) {
node* parent = to_remove->get_parent();
if (ct == to_remove_child_type::root) // if to_remove is the root
set_tree_root_node(to_transplant);
else if (ct == to_remove_child_type::left) // if to_remove is the left child of its parent
parent->set_left(to_transplant);
else // if to_remove is the right child of its parent
parent->set_right(to_transplant);
if (to_transplant)
to_transplant->set_parent(parent);
};
if (to_erase->get_left() == nullptr) // case 1: node to_erase has only the right child
transpose_subtree(to_erase, get_child_type(to_erase), to_erase->release_right());
else if (to_erase->get_right() == nullptr) // case 2: node to_erase has only the left child
transpose_subtree(to_erase, get_child_type(to_erase), to_erase->release_left());
else // case 3: node to_erase has both left and right children
{
node* min = get_minimum_left_node_in_subtree(to_erase->get_right());
to_remove_child_type min_ct = get_child_type(min); // We need to know the type (of child) of the min node before releasing it
release_node(min);
if (min->get_parent() != to_erase) // case 3ext: min is in the right subtree of node to_erase but is not its right child
{
transpose_subtree(min, min_ct, min->release_right());
min->set_right(to_erase->release_right());
min->get_right()->set_parent(min);
}
node* left_child_of_to_erase = to_erase->release_left(); // Save the left child because transpose_subtree is going to erase to_erase
transpose_subtree(to_erase, get_child_type(to_erase), min);
min->set_left(left_child_of_to_erase);
min->get_left()->set_parent(min);
}
--size;
}
template <typename value_type, typename key_type, typename OP>
inline const std::string& bst<value_type, key_type, OP>::
tree_structure_to_string(std::string& str_buffer) const
{
return subtree_structure_to_string(get_tree_root_node(), str_buffer);
}
template <typename value_type, typename key_type, typename OP>
std::string& bst<value_type, key_type, OP>::
subtree_structure_to_string(const Node<value_type, key_type, OP>* subtree_root_node,
std::string& str_buffer)
{
str_buffer.append(" "); // each level of the tree implies an indentation
if (!subtree_root_node) // empty subtree
return str_buffer.append("|--[]");
std::string str_left_buff{ str_buffer },
str_right_buff{ str_buffer };
subtree_structure_to_string(subtree_root_node->get_left(), str_left_buff);
subtree_structure_to_string(subtree_root_node->get_right(), str_right_buff);
std::stringstream os{};
os << "|--" << *subtree_root_node; //save info of current node into the stream
// Buffer to return
str_buffer.append(os.str()); // append info of current node
if (subtree_root_node->get_left() ||
subtree_root_node->get_right()) // if at least one child is defined, then print
{
str_buffer.append("\n")
.append(str_left_buff) // append info of left child node
.append("\n")
.append(str_right_buff); // append info of right child node
}
return str_buffer;
}
#endif //ADVANCED_PROGRAMMING_EXAM_2020_BST_CPP | true |
f67d116c632c7118e49989c7068076c0aad1bbe8 | C++ | ZhenyingZhu/ClassicAlgorithms | /src/CPP/src/epi/chapter17/LongestNondecreasingSubsequenceLength.cpp | UTF-8 | 1,698 | 3.375 | 3 | [] | no_license | #include "LongestNondecreasingSubsequenceLength.hpp"
#include <vector>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include "../../MyUtils.h"
using std::vector;
using std::cout;
using std::endl;
namespace epi {
namespace chapter17 {
int LongestNondecreasingSubsequenceLength::findNextIdxOfLastNotGreater(vector<int> &tails, int ed, int value) {
int st = 0;
while (st < ed - 1) {
int md = st + (ed - st) / 2;
if (tails[md] == value) {
return md + 1;
} else if (tails[md] < value) {
st = md;
} else {
ed = md;
}
}
if (tails[st] > value) {
return st;
}
return ed;
}
int LongestNondecreasingSubsequenceLength::longestNDSLen(const vector<int> &array) {
if (array.empty())
return 0;
vector<int> tails(array.size(), 0);
tails[0] = array[0];
int len = 1;
for (size_t i = 1; i != array.size(); ++i) {
if (array[i] >= tails[len - 1]) {
tails[len++] = array[i];
} else {
int idx = findNextIdxOfLastNotGreater(tails, len - 1, array[i]);
tails[idx] = array[i];
}
}
return len;
}
bool LongestNondecreasingSubsequenceLength::test() {
vector<int> array = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9};
int res = longestNDSLen(array);
if (res != 4) {
cout << "Should be: 4" << endl;
cout << "Result: " << res << endl;
return false;
}
return true;
}
} // chapter17
} // epi
| true |
6d32d2c2ec3da1dbc2dff502f621b0ff878647fd | C++ | alanrpfeil/Tic-Tac-Toe-OpenGL- | /Rect.h | UTF-8 | 750 | 3.078125 | 3 | [] | no_license | #ifndef Rect_h
#define Rect_h
#include <iostream>
using namespace std;
struct Rect{
float x, y, w, h;
bool isused;
char occupied;
Rect() {
x = 0.0, y = 0.0, w = 0.0, h = 0.0, isused = 0, occupied = ' ';
}
void Rec(float xcoord, float ycoord, float wcoord, float hcoord) {
x = xcoord, y = ycoord, w = wcoord, h = hcoord, isused = 0, occupied = ' ';
}
bool getused() {return isused;}
float getX() {return x;}
float getY() {return y;}
float getW() {return w;}
float getH() {return h;}
bool contains(float testx, float testy) {
if (testx > x && testx < (x + w) && testy < y && testy > (y - h)) {
return true;
}
else {
return false;
}
}
~Rect() {
}
};
#endif | true |
82ab67b8ae0d3456e91041515a930d21a623352d | C++ | Weinsen/neurotick | /source/connector.cpp | UTF-8 | 2,474 | 2.53125 | 3 | [] | no_license | #include "connector.hpp"
namespace neurotick {
// void Connector::connect(Model& model, std::string receptor, std::string layer)
// {
// std::vector<NeuronBase *>* neurons1 = model.getLayer(receptor).getNeurons();
// std::vector<NeuronBase *>* neurons2 = model.getLayer(layer).getNeurons();
// for (auto n : *neurons1) {
// for (auto i : *neurons2) {
// n->addInput(i);
// }
// }
// }
// void Connector::connect(Model& model, const char *receptor, const char *layer)
// {
// std::vector<NeuronBase *>* neurons1 = model.getLayer(std::string(receptor)).getNeurons();
// std::vector<NeuronBase *>* neurons2 = model.getLayer(std::string(layer)).getNeurons();
// for (auto n : *neurons1) {
// for (auto i : *neurons2) {
// n->addInput(i);
// }
// }
// }
// void Connector::connect(Model& model, const char *receptor, const char *layer, std::vector<double> *weights)
// {
// std::vector<NeuronBase *>* neurons1 = model.getLayer(std::string(receptor)).getNeurons();
// std::vector<NeuronBase *>* neurons2 = model.getLayer(std::string(layer)).getNeurons();
// for (auto n : *neurons1) {
// int i=0;
// for (auto w : *weights) {
// n->addInput((*neurons2)[i], w);
// i++;
// }
// }
// }
// void Connector::connect(Model& model, const char *receptor, const char *layer, std::vector<std::vector<double>> *weights)
// {
// std::vector<NeuronBase *>* neurons1 = model.getLayer(std::string(receptor)).getNeurons();
// std::vector<NeuronBase *>* neurons2 = model.getLayer(std::string(layer)).getNeurons();
// int i=0;
// for (auto n : *weights) {
// int j=0;
// for (auto w : n) {
// if (w != 0) {
// (*neurons1)[i]->addInput((*neurons2)[j], w);
// }
// j++;
// }
// i++;
// }
// }
void Connector::connect(Model& model)
{
auto weights = model.getConnections();
std::vector<double>::iterator w = weights.begin();
std::vector<Layer *>::iterator l = model.getLayers().begin();
// Check vector size
if (weights.size() < model.parameters()) {
throw std::invalid_argument("Vector smaller than necessary!");
}
model.resetConnections();
while (l != std::prev(model.getLayers().end(), 1)) {
auto layer1 = *l++;
auto layer2 = *l;
auto neurons1 = layer1->getNeurons();
auto neurons2 = layer2->getNeurons();
for (auto n2 : neurons2) {
for (auto n1 : neurons1) {
n2->addInput(n1, *w++);
}
}
}
}
}
| true |
3227ba6ac30faae21b0bc8252f342ba3b233a12c | C++ | schlomer/ripper | /rips/rip_data_database.cpp | UTF-8 | 1,126 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /**************************************
Rip Server (C) 2019 Shannon Schlomer
**************************************/
#include "pch.h"
using namespace rip;
using namespace rip::data;
// database
database::database(std::string name) : name(name)
{
}
std::shared_ptr<container> database::add_container(std::string _name, std::string partition_key_path, std::string id_path)
{
std::lock_guard lg(mtx_containers);
auto i = containers.find(_name);
if (i != containers.end())
return i->second;
auto c = std::make_shared<container>(_name, partition_key_path, id_path);
containers.insert(std::make_pair(_name, c));
return c;
}
std::shared_ptr<container> database::get_container(std::string _name) const
{
std::lock_guard lg(mtx_containers);
auto i = containers.find(_name);
if (i == containers.end())
return nullptr;
return i->second;
}
std::string database::get_name() const
{
return name;
}
std::vector<std::shared_ptr<container>> database::get_containers() const
{
std::lock_guard lg(mtx_containers);
std::vector<std::shared_ptr<container>> r;
for (auto& i : containers)
r.push_back(i.second);
return r;
} | true |
0cea3b0e2b0aada29a575dadd9dbbe26b3b102ed | C++ | jgilbertfpv/rcjoy | /RCJoy/STM32F407DISC_RC_JOY/EEPRom.cpp | UTF-8 | 3,830 | 2.828125 | 3 | [] | no_license | #include "EEPRom.h"
static inline int16_t changeEndianness(int16_t val)
{
return (val << 8) | ((val >> 8) & 0x00ff);
}
static inline uint16_t changeEndianness(uint16_t val)
{
return (val << 8) | ((val >> 8) & 0x00ff);
}
static inline int32_t changeEndianness(int32_t val)
{
return (val << 24) |
((val << 8) & 0x00ff0000) |
((val >> 8) & 0x0000ff00) |
((val >> 24) & 0x000000ff);
}
static inline uint32_t changeEndianness(uint32_t val)
{
return (val << 24) |
((val << 8) & 0x00ff0000) |
((val >> 8) & 0x0000ff00) |
((val >> 24) & 0x000000ff);
}
union SendBuffer16Bit
{
uint8_t arr[4];
struct
{
uint16_t addr;
int16_t val;
};
};
union SendBuffer32Bit
{
uint8_t arr[6];
struct
{
uint16_t addr;
int32_t val;
};
};
union DataBuffer16BitU
{
uint8_t arr[2];
uint16_t val;
};
union DataBuffer16Bit
{
uint8_t arr[2];
int16_t val;
};
union DataBuffer32Bit
{
uint8_t arr[4];
int32_t val;
};
static bool EEPRomReady = false;
bool EEPRom::Init(I2C* port, uint8_t addr, EEPRomAddressing addmode)
{
__I2CPort = port;
__Addr = addr;
__AddrMode = addmode;
if(EEPRomReady = __I2CPort->StartWrite(__Addr))
__I2CPort->Stop();
return EEPRomReady;
}
bool EEPRom::Write(uint16_t addr, int16_t val)
{
if(!EEPRomReady) return false;
if(__AddrMode == A16Bit)
{
SendBuffer16Bit buffer;
buffer.addr = changeEndianness(addr);
buffer.val = val;
return __I2CPort->Transmit(__Addr, buffer.arr, 4);
}
else
{
SendBuffer16Bit buffer;
buffer.addr = changeEndianness((uint16_t)addr);
buffer.val = val;
return __I2CPort->Transmit(__Addr | (addr >> 8), buffer.arr+1, 3);
}
}
bool EEPRom::Write(uint16_t addr, int32_t val)
{
if(!EEPRomReady) return false;
if(__AddrMode == A16Bit)
{
SendBuffer32Bit buffer;
buffer.addr = changeEndianness(addr);
buffer.val = val;
return __I2CPort->Transmit(__Addr, buffer.arr, 6);
}
else
{
SendBuffer32Bit buffer;
buffer.addr = changeEndianness((uint16_t)addr);
buffer.val = val;
return __I2CPort->Transmit(__Addr | (addr >> 8), buffer.arr+1, 5);
}
}
bool EEPRom::Read(uint16_t addr, int16_t *val)
{
if(!EEPRomReady) return false;
if(__AddrMode == A16Bit)
{
DataBuffer16BitU baddr;
baddr.val = changeEndianness(addr);
if(!(__I2CPort->StartWrite(__Addr) && __I2CPort->Write(baddr.arr,2)))
{
__I2CPort->Stop();
return false;
}
DataBuffer16Bit bval;
if(!(__I2CPort->StartRead(__Addr) && __I2CPort->Receive(bval.arr, 2)))
{
__I2CPort->Stop();
return false;
}
__I2CPort->Stop();
*(val) = bval.val;
return true;
}
else
{
if(!(__I2CPort->StartWrite(__Addr | (addr >> 8)) && __I2CPort->Write((uint8_t)addr)))
{
__I2CPort->Stop();
return false;
}
DataBuffer16Bit bval;
if(!(__I2CPort->StartRead(__Addr | (addr >> 8)) && __I2CPort->Receive(bval.arr, 2)))
{
__I2CPort->Stop();
return false;
}
__I2CPort->Stop();
*(val) = bval.val;
return true;
}
}
bool EEPRom::Read(uint16_t addr, int32_t *val)
{
if(!EEPRomReady) return false;
if(__AddrMode == A16Bit)
{
DataBuffer16BitU baddr;
baddr.val = changeEndianness(addr);
if(!(__I2CPort->StartWrite(__Addr) && __I2CPort->Write(baddr.arr,2)))
{
__I2CPort->Stop();
return false;
}
DataBuffer32Bit bval;
if(!(__I2CPort->StartRead(__Addr) && __I2CPort->Receive(bval.arr, 4)))
{
__I2CPort->Stop();
return false;
}
*(val) = bval.val;
return true;
}
else
{
DataBuffer16BitU baddr;
baddr.val = changeEndianness(addr);
if(!(__I2CPort->StartWrite(__Addr | (addr >> 8)) && __I2CPort->Write((uint8_t)addr)))
{
__I2CPort->Stop();
return false;
}
DataBuffer32Bit bval;
if(!(__I2CPort->StartRead(__Addr | (addr >> 8)) && __I2CPort->Receive(bval.arr, 4)))
{
__I2CPort->Stop();
return false;
}
*(val) = bval.val;
return true;
}
} | true |
c81fa5c3f6732635f46c86d19bf746773620746f | C++ | nuts4nuts4nuts/CSI281 | /Practice Project 2 - LLs/term.h | UTF-8 | 1,232 | 3.40625 | 3 | [] | no_license | /*Author: David Johnston
Class: CSI-281-01
Assignment: pa 2
Date Assigned: 9/5/13
Due Date: 9/12/13 - 12:30
Description: The purpose of this program is to recieve two polynomials from the user and add them together using a linkedlist backbone.
Certification of Authenticity:
I certify that this assignment is entirely my own work, with collaboration from West Hall study group*/
#ifndef TERM_H
#define TERM_H
#include <iostream>
using namespace std;
class Term
{
friend ostream& operator<<(ostream& out, Term theTerm);
friend istream& operator>>(istream& in, Term& theTerm);
private:
int mCoefficient;
int mExponent;
char mVariable;
public:
Term();
Term(int coefficient, int exponent, char variable);
~Term();
inline int getCoefficient(){ return mCoefficient; }
inline int getExponent(){ return mExponent; }
inline char getVariable(){ return mVariable; }
inline void setCoefficient(int coeffecient){ mCoefficient = coeffecient; }
inline void setExponent(int exponent){ mExponent = exponent; }
inline void setVariable(char variable){ mVariable = variable; }
Term operator+(Term& rhs);
bool operator<(Term& rhs);
bool operator>(Term& rhs);
bool operator<=(Term& rhs);
bool operator>=(Term& rhs);
};
#endif TERM_H | true |
57f47fc15547408d825d65fb9b79d3d3f44fdf91 | C++ | TapanManu/cprogs | /cpp/math/trailzeros.cpp | UTF-8 | 225 | 3.171875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int trailzeroes(int n){
return n==0?0:n/5+trailzeroes(n/5);
}
int main(){
//no of trailing zeros in factorial of number
int factnum = 9;
cout<<trailzeroes(factnum);
}
| true |
3789a2d7b3548d8e988eda55b5afec195a02bed1 | C++ | idontknoooo/my-code | /advanced-cpp/lec/Exception_examplecode/numeric_example1.cpp | UTF-8 | 2,877 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<numeric>
#include<cmath>
#include<ctype.h>
using namespace std;
struct CalcResult{
double ret1, ret2;
double vol1, vol2, corr;
};
double ret_calc(const double& p1, const double& p2);
void read_stock_px(vector<double>&,vector<double>&);
CalcResult getCalcResult(const vector<double>&, const vector<double>&);
int main()
{
vector<double> aapl, goog;
read_stock_px(aapl,goog);
vector<double> ret_aapl(aapl.size()), ret_goog(goog.size());
adjacent_difference(aapl.begin(),aapl.end(),ret_aapl.begin(),ret_calc);
adjacent_difference(goog.begin(),goog.end(),ret_goog.begin(),ret_calc);
ret_aapl.erase(ret_aapl.begin());
ret_goog.erase(ret_goog.begin());
CalcResult result = getCalcResult(ret_aapl,ret_goog);
cout << "ret(aapl) = " << result.ret1 << "\nvol(aapl) = " << result.vol1 << '\n';
cout << "ret(goog) = " << result.ret2 << "\nvol(goog) = " << result.vol2 << '\n';
cout << "corr(aapl,goog)=" << result.corr <<'\n';
}
double ret_calc(const double& p1, const double& p2) { return (p2/p1-1);}
CalcResult getCalcResult(const vector<double>& s1, const vector<double>& s2)
{
double avg1 = accumulate(s1.begin(),s1.end(),0.)/s1.size();
double avg2 = accumulate(s2.begin(),s2.end(),0.)/s2.size();
double var1 = inner_product(s1.begin(),s1.end(),s1.begin(),0.0)/s1.size() - avg1*avg1;
double var2 = inner_product(s2.begin(),s2.end(),s2.begin(),0.0)/s2.size() - avg2*avg2;
double covar = inner_product(s1.begin(),s1.end(),s2.begin(),0.0)/s1.size();
CalcResult a;
a.ret1 = avg1*252;
a.ret2 = avg2*252;
a.vol1 = sqrt(var1*252);
a.vol2 = sqrt(var2*252);
a.corr = covar/sqrt(var1*var2);
return a;
}
int parse_two_stock_price_series_with_date(stringstream& ss, double& px1, double& px2)
{
string a;
getline(ss,a,',');
if(getline(ss,a,',')) {
if(isdigit(a[0]))
px1 = stod(a);
else {
cerr << "not a valid field. exiting parse..\n"; return -1; }
}
else {
cerr << "wrong format. exiting parse...\n"; return -2;}
if(getline(ss,a,'\n')) {
if (isdigit(a[0]))
px2 = stod(a);
else {
cerr << "not a valid field. exiting parse..\n"; return -1; }
}
else {
cerr << "wrong format. exiting parse...\n"; return -2;}
return 0;
}
void read_stock_px(vector<double>& stock1,vector<double>& stock2)
{
ifstream infile("stock_px.csv");
if (!infile.is_open()) {
cerr<< "can't open stock_px.csv to read. exiting...\n"; exit(-1); }
string line;
if(!getline(infile,line)) {
cerr<< "file stock_px.csv contains no data...\n"; exit(-2);}
while(getline(infile,line)) {
stringstream ss(line);
double px1,px2;
if (parse_two_stock_price_series_with_date(ss,px1,px2)==0) {
stock1.push_back(px1);
stock2.push_back(px2);
}
};
}
| true |
9c157022ae3d359574c163e33a67a0bbf22ceb6d | C++ | DaniSchechter/Protobuf-Stripper | /src/ftpBridge.hpp | UTF-8 | 990 | 2.515625 | 3 | [] | no_license | #ifndef FTP_BRIDGE_HPP_
#define FTP_BRIDGE_HPP_
#define SECURE_UPGRADE_MESSAGE "234 Proceed with negotiation"
#include "bridge.hpp"
#include "ftpsBridge.hpp"
class FtpBridge: public Bridge<HttpSocketType>
{
public:
// Construct an Http bridge with a given client socket
// On which the bridge connector accepted connection
explicit FtpBridge(std::shared_ptr<boost::asio::io_context> io_context,
HttpSocketType& client_socket,
const std::string& domain);
/* Override functions */
virtual void handle_server_read(std::shared_ptr<HttpSocketType> server_socket,
const boost::system::error_code& error,
const size_t& bytes_transferred,
const std::string& server_host);
virtual std::shared_ptr<HttpSocketType> create_new_server_socket();
private:
std::string domain_;
};
#endif // HTTP_BRIDGE_HPP_ | true |
ee665cb87a80f5f03a107107678614c717100690 | C++ | JoselingFH/Estructuras-repetitivas | /Seccion 4 ejercicio 6.cpp | WINDOWS-1250 | 530 | 3.875 | 4 | [] | no_license | //6.Escriba un programa que calcule X elevado a Y, donde tanto x como y son enteros positivos, sin utilizar la funcin pow.
#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){
int x,y,i,solucion = 1;
cout<<"\tPrograma para hacer potencias.\n";
cout<<"Introduce la base de la potencia x: "; cin>>x;
cout<<"Introduce el exponente de la potencia y: "; cin>>y;
for(i=1;i<=y;i++){
solucion = solucion * x;
}
cout<<"\nResultado: "<<solucion<<endl;
system("pause");
return 0;
}
| true |
2f3a3ee7bf36b30410e0f4dcbfdafc855c09fbe6 | C++ | NikDelhi/Carrom | /src/walls.cpp | UTF-8 | 767 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "header.h"
using namespace std;
int Wall :: getPos()
{
return no;
}
Hole Wall :: getHole1()
{
return hole1;
}
Hole Wall :: getHole2()
{
return hole2;
}
double Wall :: getLength()
{
return length;
}
double Wall :: getWidth()
{
return width;
}
double Wall :: getHeight()
{
return height;
}
double Wall :: getX()
{
return x;
}
double Wall :: getY()
{
return y;
}
double Wall :: getZ()
{
return z;
}
void Wall :: setZ(double c)
{
z = c;
}
void Wall :: createWall(int p,Hole h1,Hole h2,double len,double w,double h,double c1,double c2,double c3,double c4)
{
no = p;
hole1 = h1;
hole2 = h2;
length = len;
width = w;
height = h;
if(p==0 || p==2)
{
x = -1;
y = (p?c3:c1);
}
else
{
y = -1;
x = (p==1?c2:c4);
}
}
| true |
f384416d0323a224d0abe9926ad540c95ca858c0 | C++ | ShnapDozer/LB4 | /LR4/LR4.cpp | UTF-8 | 1,409 | 3.21875 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <stdio.h>
using namespace System;
const int n = 5, m = 5;
void input(array<int, 2>^ a, Random^ rnd)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
a[i, j] = rnd->Next() / 10000000 -
100;
Console::Write(L"{0,4} ", a[i, j]);
}
Console::WriteLine();
}
}
void printMatr(array<int, 2>^ a)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++) { Console::Write(L"{0,4} ", a[i, j]); }
Console::WriteLine();
}
}
void printMass(array<int>^ b, size_t k = m)
{
for (int i = 0; i < k; i++) { Console::Write(L"{0,4} ", b[i]); }
Console::WriteLine();
}
void form(array<int, 2>^ MATR, array<int>^ MASS)
{
int k = 0;
for (int i = 0; i < n; i++)
{
MASS[i] = 0;
for (int j = 0; j < m; j++)
{
if (MATR[i, j] > 0)
{
MASS[i] += MATR[i, j];
}
}
}
}
int main(array<System::String^>^ args)
{
Random^ rnd = gcnew Random;
array<int, 2>^ C = gcnew array<int, 2>(n, m);
array<int, 2>^ D = gcnew array<int, 2>(n, m);
array<int>^ X = gcnew array<int>(n * m);
array<int>^ Y = gcnew array<int>(n * m);
Console::WriteLine("Матрица C:");
input(C, rnd);
form(C, X);
Console::WriteLine("Массив X:");
printMass(X);
Console::WriteLine();
Console::WriteLine("Матрица D:");
input(D, rnd);
form(D, Y);
Console::WriteLine("Массив Y:");
printMass(Y);
return 0;
}
| true |
eceed460941acb55ccbac47e553a1dd87a542eb2 | C++ | fulstock/prak4sem | /up09-1.cpp | UTF-8 | 860 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
// S -> XY
// X -> aXb | ab
// Y -> PY1 | P1
// bP -> Pb
// aP -> a0
// 0P -> 00
int check (std::string str)
{
size_t idx = 0;
int flag = 1;
size_t len = str.length();
int n = 0;
int m = 0;
while (idx < len && str[idx] == 'a') {
idx++;
n++;
}
while (idx < len && str[idx] == '0') {
idx++;
m++;
}
int count_n = 0;
int count_m = 0;
while (idx < len && str[idx] == 'b') {
idx++;
count_n++;
}
while (idx < len && str[idx] == '1') {
idx++;
count_m++;
}
if (idx < len || n == 0 || m == 0 || count_n != n || count_m != m) {
flag = 0;
}
return flag;
}
int main()
{
std::string str;
while (std::cin >> str) {
std::cout << check(str) << std::endl;
}
return 0;
} | true |
1ed57c1e4ad4882fb9523c252b9d5054fbd433f3 | C++ | rahulsoibam/freenexus | /src/base/settingsstorage.h | UTF-8 | 767 | 2.546875 | 3 | [] | no_license | #ifndef SETTINGSSTORAGE_H
#define SETTINGSSTORAGE_H
#include <QObject>
#include <QVariantHash>
#include <QTimer>
#include <QReadWriteLock>
class SettingsStorage: public QObject
{
Q_OBJECT
SettingsStorage();
~SettingsStorage();
public:
static void initInstance();
static void freeInstance();
static SettingsStorage* instance();
QVariant loadValue(const QString &key, const QVariant &defaultValue = QVariant()) const;
void storeValue(const QString &key, const QVariant &value);
void removeValue(const QString &key);
public slots:
bool save();
private:
static SettingsStorage *m_instance;
QVariantHash m_data;
bool m_dirty;
QTimer m_timer;
mutable QReadWriteLock m_lock;
};
#endif // SETTINGSSTORAGE_H
| true |
5c130ad6640b317e375b8414efe1fcc3e2ff1a1d | C++ | LBONTEN/LNJ_DREAMTEAMFEVER | /src/Tests/XMLParserTests.h | UTF-8 | 5,353 | 2.546875 | 3 | [] | no_license | /* Created by Joren Van Borm & Lenny Bontenakel
*/
#ifndef LNJPSE_PROJECT_XMLPARSERTESTS_H
#define LNJPSE_PROJECT_XMLPARSERTESTS_H
#include "../RoadSystem.h"
#include "../XMLParser.h"
#include "../Output.h"
#include "fileHelpers.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <fstream>
/**
* Test fixture for input parsing
*/
class ParseTest: public testing::Test {
protected:
ParseTest() :
system(NULL),
parser(new XmlParser()),
printer(NULL),
testOut(new ofstream()),
basePath("../src/Tests/"),
outPath("test_out_real/"),
checkPath("test_out_expected/"),
prefix("PARSE_")
{
}
virtual void SetUp()
{
ASSERT_TRUE(DirectoryExists(basePath+outPath));
ASSERT_TRUE(DirectoryExists(basePath+checkPath));
}
~ParseTest() {
delete system;
delete parser;
delete printer;
}
RoadSystem* system;
XmlParser* parser;
Output* printer;
ofstream* testOut;
std::string basePath;
std::string outPath;
std::string checkPath;
std::string prefix;
};
///--- Basic parsing ---///
TEST_F(ParseTest, BASE_Road)
{
system = parser->parseRoadSystem("../src/Tests/test_in/disconnected_roads_empty.xml");
ASSERT_FALSE(system == (RoadSystem*) NULL) << "Failed to open file, please check path";
printer = new Output(system);
testOut->open((basePath + outPath + prefix + "BASE_Road.txt").c_str());
*testOut << *printer;
testOut->close();
EXPECT_TRUE(FileCompare(basePath+checkPath+prefix+"BASE_Road.txt", basePath + outPath + prefix + "BASE_Road.txt"));
}
TEST_F(ParseTest, BASE_Car)
{
system = parser->parseRoadSystem("../src/Tests/test_in/disconnected_roads.xml");
ASSERT_FALSE(system == (RoadSystem*) NULL) << "Failed to open file, please check path";
printer = new Output(system);
testOut->open((basePath + outPath + prefix + "BASE_Car.txt").c_str());
*testOut << *printer;
testOut->close();
EXPECT_TRUE(FileCompare(basePath+checkPath+prefix+"BASE_Car.txt", basePath + outPath + prefix + "BASE_Car.txt"));
}
///--- Road network parsing ---///
TEST_F(ParseTest, NETWORK_Tree)
{
system = parser->parseRoadSystem("../src/Tests/test_in/tree_connection.xml");
ASSERT_FALSE(system == (RoadSystem*) NULL) << "Failed to open file, please check path";
printer = new Output(system);
testOut->open((basePath + outPath + prefix + "NETWORK_Tree.txt").c_str());
*testOut << *printer;
testOut->close();
EXPECT_TRUE(FileCompare(basePath+checkPath+prefix+"NETWORK_Tree.txt", basePath + outPath + prefix + "NETWORK_Tree.txt"));
}
TEST_F(ParseTest, NETWORK_Loop)
{
system = parser->parseRoadSystem("../src/Tests/test_in/loop_connection.xml");
ASSERT_FALSE(system == (RoadSystem*) NULL) << "Failed to open file, please check path";
printer = new Output(system);
testOut->open((basePath + outPath + prefix + "NETWORK_Loop.txt").c_str());
*testOut << *printer;
testOut->close();
EXPECT_TRUE(FileCompare(basePath+checkPath+prefix+"NETWORK_Loop.txt", basePath + outPath + prefix + "NETWORK_Loop.txt"));
}
///--- Typed vehicles parsing ---///
TEST_F(ParseTest, TYPES_All)
{
system = parser->parseRoadSystem("../src/Tests/test_in/linear_types.xml");
ASSERT_FALSE(system == (RoadSystem*) NULL) << "Failed to open file, please check path";
printer = new Output(system);
testOut->open((basePath + outPath + prefix + "TYPES_All.txt").c_str());
*testOut << *printer;
testOut->close();
EXPECT_TRUE(FileCompare(basePath+checkPath+prefix+"TYPES_All.txt", basePath + outPath + prefix + "TYPES_All.txt"));
}
///--- Traffic signal parsing ---///
TEST_F(ParseTest, SIGNAL_All)
{
system = parser->parseRoadSystem("../src/Tests/test_in/linear_signs.xml");
ASSERT_FALSE(system == (RoadSystem*) NULL) << "Failed to open file, please check path";
printer = new Output(system);
testOut->open((basePath + outPath + prefix + "SIGNAL_All.txt").c_str());
*testOut << *printer;
testOut->close();
EXPECT_TRUE(FileCompare(basePath+checkPath+prefix+"SIGNAL_All.txt", basePath + outPath + prefix + "SIGNAL_All.txt"));
}
TEST_F(ParseTest, false1Test)
{
system = parser->parseRoadSystem("../src/Tests/test_in/false1.xml");
EXPECT_TRUE(system->getVectorOfRoads().empty());
}
TEST_F(ParseTest, false2Test)
{
system = parser->parseRoadSystem("../src/Tests/test_in/false2.xml");
EXPECT_EQ(system->getVectorOfRoads().size(), (unsigned int) 1);
EXPECT_EQ(system->getVectorOfVehicles().size(), (unsigned int) 1);
for(std::vector<Vehicle*>::const_iterator i = system->getVectorOfVehicles().begin(), end = system->getVectorOfVehicles().end(); i < end; i++)
{
EXPECT_NE((*i)->getLicensePlate(), "1THK180");
EXPECT_NE((*i)->getLicensePlate(), "651BUF");
}
}
TEST_F(ParseTest, false3Test)
{
system = parser->parseRoadSystem("../src/Tests/test_in/false3.xml");
EXPECT_TRUE(system->getVectorOfRoads().empty());
EXPECT_TRUE(system->getVectorOfVehicles().empty());
}
TEST_F(ParseTest, false4Test)
{
ASSERT_DEATH(system = parser->parseRoadSystem("../src/Tests/test_in/false4.xml"), ".*(Xml file must have leading ROOT tag.).*");
}
#endif //LNJPSE_PROJECT_XMLPARSERTESTS_H | true |
344f912af2ebb9af97f16735df0a50a642ef4d74 | C++ | manofmountain/LeetCode | /236_LowestCommonAncestorOfABinaryTree.cpp | UTF-8 | 2,445 | 3.515625 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//3.39%
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q)
return root;
bool withinLeftP(false), withinLeftQ(false);
isExist(root -> left, p, q, withinLeftP, withinLeftQ);
if(withinLeftP && withinLeftQ)
return lowestCommonAncestor(root -> left, p, q);
bool withinRightP(false), withinRightQ(false);
isExist(root -> right, p, q, withinRightP, withinRightQ);
if(withinRightP && withinRightQ)
return lowestCommonAncestor(root -> right, p, q);
return root;
}
private:
void isExist(TreeNode *root, TreeNode *p, TreeNode *q, bool& withinP, bool& withinQ){
if(!root)
return;
if(!withinP && p == root)
withinP = true;
if(!withinQ && q == root)
withinQ = true;
if(withinP && withinQ)
return;
isExist(root -> left, p, q, withinP, withinQ);
isExist(root -> right, p, q, withinP, withinQ);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//53.1%
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == p || root == q)
return root;
if(p == q)
return p;
vector<TreeNode *> pathP, pathQ;
TreeNode *res;
findPath(root, p, pathP);
findPath(root, q, pathQ);
int i, j;
for(i = pathP.size() - 1, j = pathQ.size() - 1; i > 0 && j > 0; --i, --j){
if(pathP[i - 1] != pathQ[j - 1])
break;
}
return pathP[i];
}
private:
bool findPath(TreeNode *curr, TreeNode *p, vector<TreeNode *>& path){
if(!curr)
return false;
if(curr == p || findPath(curr -> left, p, path) || findPath(curr -> right, p, path)){
path.push_back(curr);
return true;
}else
return false;
}
};
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
return !left ? right : !right ? left : root;
} | true |
9fc37af357d625d376a715e050bdd9406723e96d | C++ | azurite/numCSE18-code | /final_exam_fs18/1/1.cpp | UTF-8 | 3,237 | 2.90625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <chrono>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Sparse>
using namespace Eigen;
MatrixXd quadraticSpline(const VectorXd &x, const VectorXd &y) {
int N = x.size()-1;
MatrixXd out(N, 3);
VectorXd delta_x = x.tail(N) - x.head(N);
VectorXd delta_x2 = (delta_x.array() * delta_x.array()).matrix();
MatrixXd A = MatrixXd::Zero(3*N, 3*N);
A.block(0, 2*N, N, N) = MatrixXd::Identity(N, N);
A.block(N, 2*N, N, N) = MatrixXd::Identity(N, N);
A.block(N, 0, N, N) = delta_x2.asDiagonal();
A.block(N, N, N, N) = delta_x.asDiagonal();
A.block(2*N, 0, N, N) = (2 * delta_x).asDiagonal();
MatrixXd M = MatrixXd::Identity(N, N);
for(int i = 0; i < N; i++) {
M(i, (i + 1) % N) = -1;
}
A.block(2*N, N, N, N) = M;
VectorXd rhs = VectorXd::Zero(3*N);
rhs.segment(0, N) = y.head(N);
rhs.segment(N, N) = y.tail(N);
VectorXd sol = A.fullPivLu().solve(rhs);
out.col(0) = sol.segment(0, N);
out.col(1) = sol.segment(N, N);
out.col(2) = sol.segment(2*N, N);
return out;
}
MatrixXd quadraticSplineFast(const VectorXd &x, const VectorXd &y) {
int N = x.size()-1;
MatrixXd out(N, 3);
VectorXd delta_x = x.tail(N) - x.head(N);
VectorXd delta_x2 = (delta_x.array() * delta_x.array()).matrix();
std::vector<Triplet<double>> triplets(7*N);
for(int i = 0; i < N; i++) {
triplets.push_back(Triplet<double>(i, 2*N + i, 1));
triplets.push_back(Triplet<double>(N + i, 2*N + i, 1));
triplets.push_back(Triplet<double>(2*N + i, N + i, 1));
triplets.push_back(Triplet<double>(2*N + i, N + ((i + 1) % N), -1));
triplets.push_back(Triplet<double>(N + i, i, delta_x2(i)));
triplets.push_back(Triplet<double>(N + i, N + i, delta_x(i)));
triplets.push_back(Triplet<double>(2*N + i, i, 2 * delta_x(i)));
}
SparseMatrix<double> A(3*N, 3*N);
A.setFromTriplets(triplets.begin(), triplets.end());
A.makeCompressed();
SparseLU<SparseMatrix<double>> splu;
splu.compute(A);
VectorXd rhs = VectorXd::Zero(3*N);
rhs.segment(0, N) = y.head(N);
rhs.segment(N, N) = y.tail(N);
VectorXd sol = splu.solve(rhs);
out.col(0) = sol.segment(0, N);
out.col(1) = sol.segment(N, N);
out.col(2) = sol.segment(2*N, N);
return out;
}
/***** TESTING ******/
int main() {
const double TOL = 10e-5;
int testnum;
std::cin >> testnum;
for(int i=1; i<testnum; i++){
int N;
std::cin >> N;
VectorXd x(N+1), y(N+1);
MatrixXd ans(N,3);
for(int j=0; j<N+1; j++)
std::cin >> x(j);
for(int j=0; j<N+1; j++)
std::cin >> y(j);
for(int j=0; j<N; j++){
std::cin >> ans(j,0);
std::cin >> ans(j,1);
std::cin >> ans(j,2);
}
int flag;
std::cin >> flag;
auto start = std::chrono::steady_clock::now();
MatrixXd test;
if(flag)
test = quadraticSpline(x,y);
else
test = quadraticSplineFast(x,y);
auto end = std::chrono::steady_clock::now();
double difftime = std::chrono::duration<double,std::milli>(end-start).count();
if((test-ans).norm() > TOL * ans.norm()){
std::cout << "Test " << i << " INCORRECT.\n";
std::cerr << "Your answer:\n" << test << "\n\n" << "Correct answer:\n" << ans << "\n\n";
break;
}
else
std::cout << "Test " << i << " with N=" << N << " correct in " << difftime << "ms.\n";
}
}
| true |
ae62a33053771dd70d26c03d94a43e692b37ec90 | C++ | nandita-manchikanti/DAA-lab-codes | /WEEK2/Ques3.cpp | UTF-8 | 2,213 | 3.578125 | 4 | [] | no_license | #include<iostream>
#include <bits/stdc++.h>
using namespace std;
void pattern1(int n)
{
cout<<"Pattern-1"<<endl;
int i;
int j;
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
{
cout<<j<<" ";
}
cout<<"\n";
}
cout<<"\n";
}
void pattern2(int n)
{
cout<<"Pattern-2"<<endl;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(j>=i)
{
cout<<j<<" ";
}
else
{
cout<<" ";
}
}
cout<<"\n";
}
cout<<"\n";
}
void pattern3(int n)
{
cout<<"Pattern-3"<<endl;
int i;
int j;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<j<<" ";
}
cout<<"\n";
}
cout<<"\n";
}
int pattern4(int n)
{
cout<<"Pattern-4"<<endl;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(j>=n+1-i)
{
cout<<j<<" ";
}
else
{
cout<<" ";
}
}
cout<<"\n";
}
cout<<"\n";
return 0;
}
void pattern5(int n)
{
cout<<"Pattern 5"<<endl;
int i;
int j;
int maxrows;
if(n%2==0 )
maxrows=n/2;
else
maxrows=(n/2)+1;
for(i=1;i<=maxrows;i++)
{
for(j=1;j<=n;j++)
{
if(j>=i && j<=n-i+1)
{
cout<<j<<" ";
}
else
{
cout<<" ";
}
}
cout<<"\n";
}
for(i=n/2;i>=1;i--)
{
for(j=1;j<=n;j++)
{
if(j>=i && j<=n-i+1)
{
cout<<j<<" ";
}
else
{
cout<<" ";
}
}
cout<<"\n";
}
}
int main()
{
int n;
int p;
cout<<"Enter a number : ";
cin>>n;
pattern1(n);
pattern2(n);
pattern3(n);
pattern4(n);
pattern5(n);
return 0;
}
| true |
b4a0a733191694e8d04c0fa1760c8438210dcecb | C++ | samueljrz/Competitive-Programing | /NepsAcademy/Programação Básica - 1/Controlando Código/Repetição/Todos Div.cpp | UTF-8 | 306 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
int main () {
int x=0, *v, count=0;
cin >> x;
v = (int *) malloc(x*sizeof(int));
for(int i=1; i<=x; i++){
if((x % i) == 0){
v[count] = i;
count++;
}
}
for(int i=0; i<count; i++){
cout << v[i];
cout << " ";
}
return 0;
} | true |
6de1ce3a3e07e1604be194bdf3af260609884363 | C++ | OIdiotLin/problemset | /BZOJ/3240.cpp | UTF-8 | 1,942 | 2.609375 | 3 | [] | no_license | /*
Machine: Class4_B2
System: Windows7 SP1 32bit
*/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <ctime>
#include <algorithm>
typedef long long LL;
using namespace std;
#define SpeedUp ios::sync_with_stdio(false)
#define Judge
//#define Debug
#define MAXN (1000005)
#define INF ()
const double PI=acos(-1);
const int ZCY=1000000007;
const double eps=1e-8;
inline int getint(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline void outputint(int x){
char ch[12];
int cnt=0;
if(x==0) {putchar('0'); putchar(10);return;}
if(x<0) {putchar('-'); x=-x;}
while(x) ch[++cnt]=x%10,x/=10;
while(cnt) putchar(ch[cnt--]+48);
putchar(10);
}
#define print(x) outputint(x)
#define read(x) x=getint()
struct Matrix{
LL a,b;
Matrix(){}
Matrix(LL x,LL y):
a(x),b(y){}
Matrix operator * (const Matrix &T) const{
return Matrix(a*T.a%ZCY,(b*T.a%ZCY+T.b)%ZCY);
}
Matrix operator *=(const Matrix &T){
return (*this = *this *T);
}
}A,B;
char N[MAXN],M[MAXN];
LL r1,r2,r3,r4,p,q;
LL get(char *s,LL p){
LL res=0;
for(char *c=s;*c;c++)
res=(res*10LL+(*c)-'0')%p;
return (res-1+p)%p;
}
Matrix qPow(Matrix x,LL k){
Matrix res=Matrix(1,0);
while(k){
if(k&1) res*=x;
k>>=1;
x*=x;
}
return res;
}
void init(){
#ifdef Judge
freopen("3240.in","r",stdin);
freopen("3240.out","w",stdout);
// SpeedUp;
#endif
scanf("%s%s%lld%lld%lld%lld",N,M,&r1,&r2,&r3,&r4);
A=Matrix(r1,r2),B=Matrix(r3,r4);
p=get(N,ZCY-(r1!=1));
q=get(M,ZCY-(r3!=1));
}
void work(){
Matrix S=qPow(A,q);
B*=S;
Matrix T=qPow(B,p);
S*=T;
printf("%lld\n",(S.a+S.b)%ZCY);
}
int main(){
init();
work();
#ifdef Debug
cout<<"Time Used : "<<(double)clock()/CLOCKS_PER_SEC<<" s."<<endl;
cout<<"Memory Used : "<<(double)(sizeof())/1048576<<" MB."<<endl;
#endif
return 0;
}
| true |
cf5a519231a3502b0f791d1542eb2734d62f0b7f | C++ | lede701/yaag | /TheArena/AIMonster.cpp | UTF-8 | 2,708 | 2.921875 | 3 | [] | no_license | #include "AIMonster.h"
#include "CharacterData.h"
namespace Game{ namespace Entity{ namespace Monsters{ namespace AI
{
AIMonster::AIMonster(LPVECTOR2D player, LPVECTOR2D me, LPVECTOR2D exit)
{
_player = player;
_me = me;
_attackPos = me->Clone();
_exit = exit;
_doIFlee = false; // Of course I don't flee what kind of monster to you take me for?
}
AIMonster::~AIMonster()
{
}
void AIMonster::Update()
{
}
bool AIMonster::ChkInput(int vk)
{
LPVECTOR2D goal = _player->Clone();
if (_doIFlee)
{
goal = _exit->Clone();
int dx = abs(_me->x - goal->x);
if (dx > 1)
{
// Goal needs to be a little lower then the exit so we don't walk on the fence
goal->y++;
}
}
// Calculate the distance from player
int deltaX = abs(_me->x - goal->x);
int deltaY = abs(_me->y - goal->y);
int dist = deltaX + deltaY;
int AttackDistance = 2;
if (deltaX > 1 || deltaY > 1 || dist > AttackDistance || _doIFlee)
{
// Handle X movement
if (_me->x > goal->x && vk == 'A')
{
return true;
}
if (_me->x < goal->x && vk == 'D')
{
return true;
}
// Handle Y Movement
if (_me->y > goal->y && vk == 'W')
{
return true;
}
if (_me->y < goal->y && vk == 'S')
{
return true;
}
}
else if (dist < AttackDistance && vk == VK_SHIFT)
{
// Need to figure out if we can attack on the grid based on the 8 directions
bool bRetVal = deltaX == deltaY || (deltaX > 0 && deltaY == 0) || (deltaY > 0 && deltaX == 0);
_attackPos->x = _player->x;
_attackPos->y = _player->y;
return bRetVal;
}
// Clean up my memory mess err sorry mom!
delete goal;
return false;
}
char AIMonster::GetInput()
{
return 0;
}
// Something to do when I get attacked
void AIMonster::ProcessAttack()
{
}
LPVECTOR2D AIMonster::GetAttackPos()
{
return _attackPos;
}
bool AIMonster::DoIFlee(LPATTACKER enemy, LPATTACKER me)
{
_doIFlee = false;
// Need to figure out if I can beat this enemy
LPCHARACTER enemyChar = enemy->GetCharacter();
LPCHARACTER meChar = me->GetCharacter();
int enemyScore = enemyChar->GetScore();
// This score is not calulating properly need to step into this line
int meScore = meChar->GetScore();
float myLifePercent = static_cast<float>(meChar->Health) / static_cast<float>(meChar->MaxHealth);
float ourDiffernce = static_cast<float>(meScore) / static_cast<float>(enemyScore);
// Check if we have a tough enemy
if ((myLifePercent < 0.50f && ourDiffernce < 0.50f) || (ourDiffernce < 0.40))
{
// Yikes this enemy is to tough for me so I need to run away
_doIFlee = true;
}
return _doIFlee;
}
} } } } // End namespace Game::Entity::Monsters::AI
| true |
4ce1231ae894e89b4c5474c47e0688ef7c1462e2 | C++ | rlaxoghd94/Algorithm_Study | /backup-old_study/Baekjoon/DFS/10026.cpp | UTF-8 | 1,745 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define MAX_N 101
int N;
char map[MAX_N][MAX_N];
bool visited[MAX_N][MAX_N] = { false };
int dy[] = {1, 0, -1, 0};
int dx[] = {0, 1, 0, -1};
int cntBefore = 0, cntAfter = 0;
bool isColorBlind = false;
void resetVisited(){
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
visited[i][j] = false;
}
void DFS(int yy, int xx, char refVal) {
visited[yy][xx] = true;
int ny, nx;
for (int i = 0; i < 4; i++){
ny = yy + dy[i];
nx = xx + dx[i];
if (ny < 0 || nx < 0 || ny >= N || nx >= N)
continue;
if (visited[ny][nx])
continue;
if (!isColorBlind){
if (map[ny][nx] == refVal){
DFS(ny, nx, refVal);
}
} else {
/*
* if colorblind, 'R' and 'G' is dealt as if they're the same
* which means as long as (char: map[ny][nx]) is not 'B',
* all values should be dealt the same
*/
if (refVal == 'B'){
if (map[ny][nx] == 'B')
DFS(ny, nx, refVal);
} else {
if (map[ny][nx] != 'B')
DFS(ny, nx, refVal);
}
}
}
}
int main(){
cin >> N;
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
cin >> map[i][j];
}
}
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
if (!visited[i][j]){
cntBefore++;
DFS(i, j, map[i][j]);
}
}
}
resetVisited();
isColorBlind = true;
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
if (!visited[i][j]){
cntAfter++;
DFS(i, j, map[i][j]);
}
}
}
cout << cntBefore << " " << cntAfter << endl;
return 0;
}
| true |
94b7872f743f1a823b3dddacc394099bb19a34f5 | C++ | ArnabBir/interviewbit-solutions | /ListCycle.cpp | UTF-8 | 863 | 3.28125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode * getStartNode(ListNode * ptr , ListNode * A){
ListNode * temp1 = ptr;
ListNode * temp2 = ptr;
int k = 1;
while(temp1->next != temp2){
k++;
temp1 = temp1->next;
}
temp1 = A;
temp2 = A;
for(int i = 0 ; i < k ; ++i){
temp2 = temp2->next;
}
while(temp2!=temp1){
temp2 = temp2->next;
temp1 = temp1->next;
}
return temp2;
}
ListNode* Solution::detectCycle(ListNode* A) {
ListNode * ptr1 = A;
ListNode * ptr2 = A;
while(ptr1 && ptr2 && ptr2->next) {
ptr1 = ptr1->next;
ptr2 = ptr2->next->next;
if(ptr1 == ptr2) return getStartNode(ptr1, A);
}
return NULL;
}
| true |
3a163fd7ea6d14334e2600c0fe990b12eb69613f | C++ | Py-Contributors/AlgorithmsAndDataStructure | /C++/Algorithms/Maths/maxPairwiseProduct.cpp | UTF-8 | 2,648 | 4.125 | 4 | [
"MIT"
] | permissive | /*
Find the maximum product of two distinct numbers in a sequence of non-negative integers
Input: A sequence of non-negative integers
Output: The maximum value that can be obtained by multiplying two different elements from the sequence.
Input format. The first line contains an integer n. The next line contains n non-negative integers a1, . . . , an (separated by spaces).
Output format. The maximum pairwise product
Constraints. 2 ≤ n ≤ 2·10^5 ; 0 ≤ a1, . . . , an ≤ 2·10^5.
Time limit: 1 sec
Memory Limit: 512 Mb
Sample Input 1:
3
1 2 3
Sample Output 1:
6
Sample Input 2:
10
7 5 14 2 8 8 10 1 2 3
Sample Output 2:
140
*/
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::max;
// Naive algorithm to find the Maximum Pairwise Product. Takes O(n^2)
int64_t MaxPairwiseProductNaive(const std::vector<int64_t>& numbers) {
int64_t max_product = 0;
int n = numbers.size();
for (int first = 0; first < n; ++first) {
for (int second = first + 1; second < n; ++second) {
max_product = std::max(max_product,
(int64_t)( numbers[first] * numbers[second]));
}
}
return max_product;
}
// Faster solution to the Maximum Pairwise Product Problem. Takes O(nlogn)
int64_t MaxPairwiseProduct(std::vector<int64_t>& numbers) {
int n = numbers.size();
sort(numbers.begin(), numbers.end());
return numbers[n - 1] * numbers[n - 2];
}
// Function to stress test the problem
void stressTest(int64_t N, int64_t M) {
while(true) {
int64_t n = rand() % (N - 1) + 2;
std::cout << "\n" << n << "\n";
vector<int64_t> A(n);
for (int64_t i = 0; i < n; i++) {
A[i] = rand() % (M + 1);
}
for (int64_t i = 0; i < n; i++) {
cout << A[i] << " ";
}
int64_t result1 = MaxPairwiseProductNaive(A);
int64_t result2 = MaxPairwiseProduct(A);
if (result1 == result2) {
cout << "\nOK" << "\n";
} else {
cout << "\nWrong Answer: " << result1 << " " << result2 << "\n";
return;
}
}
}
int main() {
// To test the code, uncomment the following line and comment rest of the code in the main function.
// Feel free to play around with the values in the parameter
// stressTest(1000, 200000);
int n;
std::cin >> n;
std::vector<int64_t> numbers(n);
for (int i = 0; i < n; ++i) {
std::cin >> numbers[i];
}
std::cout << MaxPairwiseProduct(numbers) << "\n";
return 0;
} | true |
488d8c8d0e216d8f0057a4bf79c255afb2a42726 | C++ | eedowdy/Choreograph | /samples/src/pockets/cobweb/ButtonBase.cpp | UTF-8 | 2,685 | 2.640625 | 3 | [
"BSD-2-Clause"
] | permissive | //
// ButtonBase.cpp
// WordShift
//
// Created by David Wicks on 4/24/13.
// Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//
#include "ButtonBase.h"
using namespace cinder;
using namespace pockets;
using namespace cobweb;
ButtonBase::ButtonBase( const Rectf &bounds ):
mHitBounds( bounds )
{}
ButtonBase::~ButtonBase()
{}
void ButtonBase::expandHitBounds( float horizontal, float vertical )
{
mHitBounds.x1 -= horizontal;
mHitBounds.x2 += horizontal;
mHitBounds.y1 -= vertical;
mHitBounds.y2 += vertical;
}
void ButtonBase::cancelInteractions()
{
mTrackedTouch = 0;
endHovering( false );
}
void ButtonBase::endHovering( bool selected )
{
if( mHovering )
{
mHovering = false;
hoverEnd();
}
}
void ButtonBase::setHovering()
{
if( !mHovering )
{
mHovering = true;
hoverStart();
}
}
bool ButtonBase::mouseDown(ci::app::MouseEvent &event)
{
if( contains( event.getPos() ) )
{
mTrackedTouch = std::numeric_limits<uint32_t>::max();
setHovering();
return true;
}
return false;
}
bool ButtonBase::mouseDrag(ci::app::MouseEvent &event)
{
if( contains( event.getPos() ) )
{
setHovering();
}
else
{
endHovering( false );
}
return false;
}
bool ButtonBase::mouseUp(ci::app::MouseEvent &event)
{
bool selected = false;
mTrackedTouch = 0;
if( contains( event.getPos() ) )
{ selected = true; }
endHovering( selected );
if( selected )
{ emitSelect(); }
return selected;
}
bool ButtonBase::touchesBegan(ci::app::TouchEvent &event)
{
for( auto &touch : event.getTouches() )
{
if( contains( touch.getPos() ) )
{
mTrackedTouch = touch.getId();
setHovering();
return true;
}
}
return false;
}
bool ButtonBase::touchesMoved(ci::app::TouchEvent &event)
{
for( auto &touch : event.getTouches() )
{
if( touch.getId() == mTrackedTouch )
{ // sliding a finger into a button won't trigger it
if( contains( touch.getPos() ) )
{ setHovering(); }
else
{ endHovering( false ); }
}
}
return false;
}
bool ButtonBase::touchesEnded(ci::app::TouchEvent &event)
{
bool selected = false;
for( auto &touch : event.getTouches() )
{
if( touch.getId() == mTrackedTouch )
{
mTrackedTouch = 0;
if( contains( touch.getPos() ) )
{
selected = true;
break;
}
endHovering( selected ); // only end hovering if it was our tracked touch that ended
}
}
if( selected )
{ // in case of side effects in select function, emit selection last
// e.g. if button navigates to a new screen, it will destroy itself
emitSelect();
}
return selected;
}
| true |
2510622a7f35cabeb327dcf52b16c24338da409a | C++ | TDCRanila/IGART-BT | /AI/BT/Nodes/composite_node.cpp | UTF-8 | 684 | 2.6875 | 3 | [] | no_license | #include <AI\BT\Nodes/composite_node.h>
CEREAL_REGISTER_TYPE(iga::bt::CompositeNode)
CEREAL_REGISTER_POLYMORPHIC_RELATION(iga::bt::BaseNode, iga::bt::CompositeNode)
/**
* igart namespace
*/
namespace iga {
namespace bt {
CompositeNode::CompositeNode() {
this->node_type_ = NodeType::COMPOSITE;
}
CompositeNode::~CompositeNode() { /* EMPTY */ }
void CompositeNode::AddChild(BaseNode* a_child) {
this->children_.push_back(a_child);
}
std::vector<BaseNode*> CompositeNode::GetChildren() const {
return this->children_;
}
} // End of namespace ~ bt;
} // End of namespcae ~ iga
| true |
56c45000e0f1eeca5476d96a530916e141ace1d4 | C++ | 0x1un/wintools | /wintools/utils.cpp | UTF-8 | 2,335 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #include "utils.h"
#include <iostream>
using namespace std;
string get_md5(LPCWSTR filename);
string Utils::md5sum_file(LPCWSTR in)
{
return get_md5(in);
}
string get_md5(LPCWSTR filename)
{
DWORD dwStatus = 0;
BOOL bResult = FALSE;
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
HANDLE hFile = NULL;
BYTE rgbFile[BUFSIZE];
DWORD cbRead = 0;
BYTE rgbHash[MD5LEN];
DWORD cbHash = 0;
CHAR rgbDigits[] = "0123456789abcdef";
// Logic to check usage goes here.
hFile = CreateFile(filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
dwStatus = GetLastError();
cout << "Error opening file " << filename << "\nError: " << dwStatus << endl;
return string();
}
// Get handle to the crypto provider
if (!CryptAcquireContext(&hProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
dwStatus = GetLastError();
cout << "CryptAcquireContext failed: " << dwStatus << endl;
CloseHandle(hFile);
return string();
}
if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
{
dwStatus = GetLastError();
cout << "CryptAcquireContext failed: " << dwStatus << endl;
CloseHandle(hFile);
CryptReleaseContext(hProv, 0);
return string();
}
while (bResult = ReadFile(hFile, rgbFile, BUFSIZE,
&cbRead, NULL))
{
if (0 == cbRead)
{
break;
}
if (!CryptHashData(hHash, rgbFile, cbRead, 0))
{
dwStatus = GetLastError();
cout << "CryptHashData failed: " << dwStatus << endl;
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
return string();
}
}
if (!bResult)
{
dwStatus = GetLastError();
cout << "ReadFile failed: " << dwStatus << endl;
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
return string();
}
cbHash = MD5LEN;
vector<CHAR> hash_str;
if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
{
for (DWORD i = 0; i < cbHash; i++)
{
hash_str.push_back(rgbDigits[rgbHash[i] >> 4]);
hash_str.push_back(rgbDigits[rgbHash[i] & 0xf]);
}
}
else
{
dwStatus = GetLastError();
cout << "CryptGetHashParam failed: " << dwStatus << endl;
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
CloseHandle(hFile);
string str(hash_str.begin(), hash_str.end());
return str;
}
| true |
5ffa4d89d394e56a8360e3f9dad18cf785d2620b | C++ | shivammaheshwari9837/Data-Structures-and-Algorithms-C-plus-plus | /Linked List/Multiply two linked list.cpp | UTF-8 | 416 | 3.109375 | 3 | [] | no_license | /*
Ques :- Multiply two linked list in O(1) space..
*/
long long multiplyTwoLists (Node* l1, Node* l2)
{
//Your code here
Node *p = l1;
ll n1 = 0,n2 = 0;
while(p!=NULL)
{
n1 = ((n1*10)%mod + (p->data)%mod)%mod;
p = p->next;
}
p = l2;
while(p!=NULL)
{
n2 = ((n2*10)%mod + (p->data)%mod)%mod;
p = p->next;
}
ll val = (n1%mod * n2%mod)%mod;
return val;
}
| true |
a4b0edf61a107135e14528e79e1106056843bcb5 | C++ | GuilhermeWillahelm/DataStructure | /SelectionSort/SelectionSort/SelectionSort.cpp | ISO-8859-1 | 2,120 | 3.203125 | 3 | [] | no_license | // SelectionSort.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <locale>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
void selectionSort(int vet[], int tam);
void printVector(int vet[], int tam);
int main()
{
setlocale(LC_ALL, "ptb");
int vetor[5] = { 13, 23, 3, 8, 1 };
int i;
// Antes da troca;
printVector(vetor, 5);
cout << "\n\n";
//==================================//
/* SelectionSort */
selectionSort(vetor, 5);
cout << "\n\n";
printVector(vetor, 5);
cout << "\n\n";
}
void selectionSort(int vet[], int tam)
{
int indexMin, i, j;
// Percorrer todos os nmeros
for (i = 0; i < tam - 1; i++)
{
// Define o elemento atual com o menor
indexMin = i;
//Encontra o menor valr aps "i + 1"
for (j = i + 1; j < tam; j++)
{
if (vet[j] < vet[indexMin])
{
indexMin = j;
}
}
cout << "Troca: " << vet[i] << " <= " << vet[indexMin] << endl;
if (indexMin != i)
{
//troca os nmeros
int temp = vet[indexMin];
vet[indexMin] = vet[i];
vet[i] = temp;
}
}
}
void printVector(int vet[], int tam)
{
int i;
cout << vet[0];
// Aps a troca
for (i = 1; i < 5; i++)
{
cout << ", " << vet[i];
}
cout << endl;
}
// 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 |
b3f5d7d0863e47bc01fb80bc710becd02cfc04bf | C++ | eujuu/Algorithm | /baekjoon/백준 1011 Fly me to the Alpha Centauri.cpp | UTF-8 | 442 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
int main() {
using namespace std;
long long T, x, y, cnt, i, length;
cin >> T;
for (int j = 0; j < T; j++) {
cin >> x >> y;
i = 1;
length = y - x;
for (;; i++) {
if (i * i > length)
break;
}
if ((i - 1)*(i - 1) == length)
cnt = 2 * (i - 1) - 1;
else if ((pow(i, 2) + pow(i - 1, 2)) / 2 >= length)
cnt = 2 * (i - 1);
else
cnt = 2 * i - 1;
cout << cnt << "\n";
}
} | true |
af3bec03371f5e7e064dfd5c12afbf679c942fe6 | C++ | Anthonykung/KidSpirit-Coding-In-Action-Intro | /terminal.cpp | UTF-8 | 1,956 | 2.734375 | 3 | [] | no_license | /***********************************************************************
* ** Program Filename: terminal.cpp
* ** Author: Anthony Kung (Anthony.lol)
* ** Date: 14 April 2019
* ** Description: Key logger
* ** Have an awesome day!
* ** Input: User input, numbers/strings, text files
* ** Output: Numbers/strings
* *********************************************************************/
#include <iostream> // cout and cin
#include <string> // string
#include <cstring> // cstring
#include <cmath> // pow() and math stuff
#include <stdlib.h> // rand() and srand()
#include <time.h> // time()
#include <climits> // long max
#include <fstream> // file stream
#include <ncurses.h>
#include "resources.hpp" // wait(), kill(), clearstd()...
#include "terminal.hpp" // header file
using namespace std;
/*********************************************************************
** Function: string getchar()
** Description: Get single char from input
** Parameters: None
** Pre-Conditions: None
** Post-Conditions: None
***********************************************************************/
string get1char() {
initscr();
cbreak();
string str = "";
char temp;
int first;
first = getchar();
temp = first;
str += temp;
endwin();
return str;
}
/*********************************************************************
** Function: string getchar()
** Description: Get single char from input
** Parameters: None
** Pre-Conditions: None
** Post-Conditions: None
***********************************************************************/
string get2char() {
initscr();
cbreak();
//noecho();
string str = "";
char temp;
int first, second;
first = getchar();
//cout << first << endl;
//wait(3000);
if (first != 32) {
temp = first;
//cout << temp << endl;
str += temp;
}
else {
second = getchar();
temp = first;
str += temp;
temp = second;
str += temp;
}
endwin();
return str;
}
| true |
6dadd1c970ea29c582dded2a4ff5c223a3cfceb0 | C++ | salom12/google-hashcode | /PracticeRound/pizza.cpp | UTF-8 | 6,145 | 3.46875 | 3 | [] | no_license | /*
* Google HashCode 2017
* Practice Problem - Pizza
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
using namespace std;
typedef unsigned int uint;
/* Finds all ordered pairs of numbers whose product is n
*/
vector<pair<uint, uint>> find_products(uint n) {
vector<pair<uint, uint>> result;
for (uint k = 1; k <= n; ++k) {
if (k * (n / k) == n) { // integer division resulted in correct pair?
result.push_back(make_pair(k, n / k));
}
}
return result;
}
/* Finds all ordered pairs of numbers whose product is in range [min, max]
*/
vector<pair<uint, uint>> find_all_products(uint min, uint max) {
vector<pair<uint,uint>> result;
for (uint i = max; i >= min; --i) {
auto tmp = find_products(i);
// Thin and Stretched slices last ?
/* This is actually worse
sort(tmp.begin(), tmp.end(), [](pair<int,int> p1, pair<int,int> p2) {
return pow(p1.first - p1.second, 2) < pow(p2.first - p2.second, 2);
} );
*/
//result.insert(result.begin(), tmp.begin(), tmp.end());
result.insert(end(result), begin(tmp), end(tmp));
}
return result;
}
class Slice {
public:
pair<uint, uint> rows;
pair<uint, uint> cols;
Slice(uint row_i, uint row_f, uint col_i, uint col_f) : rows(make_pair(row_i, row_f)), cols(make_pair(col_i, col_f)) {}
friend ostream & operator<<(ostream & out, const Slice & s) {
out << s.rows.first << " " << s.cols.first << " " << s.rows.second << " " << s.cols.second;
return out;
}
};
class Pizza {
private:
uint rows;
uint cols;
uint min_ings; // minimum number of ingredients per slice
uint max_cells; // maximum number of cells per slice
vector<string> contents; // Matrix of ingredients
vector<Slice> slices;
vector< vector<bool> > visited;
void markVisited(uint ri, uint rf, uint ci, uint cf) {
for (uint row = ri; row <= rf; ++row) {
for (uint col = ci; col <= cf; ++col) {
visited[row][col] = true;
}
}
}
bool isValid(uint ri, uint rf, uint ci, uint cf) const {
if (ri > rf || ci > cf || rf >= rows || cf >= cols)
return false;
uint tomatoes = 0, mushrooms = 0;
for (uint row = ri; row <= rf; ++row) {
for (uint col = ci; col <= cf; ++col) {
if (visited[row][col]) {
return false;
}
if (contents[row][col] == 'T')
tomatoes++;
else if (contents[row][col] == 'M')
mushrooms++;
}
}
return (tomatoes >= min_ings && mushrooms >= min_ings);
}
public:
Pizza(ifstream & ifs) {
ifs >> rows >> cols >> min_ings >> max_cells;
ifs.ignore(3, '\n');
string line;
for (uint i = 0; i < rows; ++i) {
getline(ifs, line);
contents.push_back(line);
}
visited = vector<vector<bool>>(rows, vector<bool>(cols, false));
}
friend ostream & operator<<(ostream & out, const Pizza & p) {
out << p.slices.size() << endl;
for (const Slice & s : p.slices)
out << s << endl;
return out;
}
/* Divides the pizza in slices so as to minimize unsliced area
* Naive approach -- to be improved.
*/
void divide() {
slices.clear();
auto sizes = find_all_products(min_ings * 2, max_cells);
bool finished = false, inner_finished = false;
uint row = 0, col = 0;
while (! finished) {
while (! inner_finished) {
if (col < cols && row < rows && visited[row][col] == false) {
inner_finished = true;
break;
}
if (col < cols)
col++;
else if (row < rows) {
row++;
col = 0;
}
else {
finished = inner_finished = true;
break;
}
}
for (auto choice : sizes) {
if (! isValid(row, row + choice.first - 1, col, col + choice.second - 1))
continue;
slices.emplace_back(row, row + choice.first - 1, col, col + choice.second - 1);
markVisited(row, row + choice.first - 1, col, col + choice.second - 1);
break;
}
col++;
inner_finished = false;
}
}
void printMetrics() const {
uint score = 0;
for (uint r = 0; r < rows; ++r) {
for (uint c = 0; c < cols; ++c) {
if (visited[r][c])
score++;
}
}
uint sliced = 0;
for (const auto & s : slices) {
sliced += (s.rows.second - s.rows.first + 1) * (s.cols.second - s.cols.first + 1);
}
cout << "**SCORE** " << score << endl;
cout << "**SLICED** " << score << endl;
cout << "**TOTAL - SLICED** " << rows * cols - sliced << endl;
cout << "**TOTAL** " << rows * cols << endl << endl;
cout << "Rows: " << rows << ". Cols: " << cols << ". MinIngs: " << min_ings << ". Max cells: " << max_cells << endl;
}
};
int main ( int argc, char * argv[] ) {
if (argc != 1 + 2) {
cout << "Incorrect number of arguments. Usage: ./pizza input_file_path output_file" << endl;
return 0;
}
string input (argv[1]);
string output (argv[2]);
ifstream ifs (input);
if (! ifs.is_open()) {
cout << "Input file not found! Was \"" << input << "\"" << endl;
return 0;
}
Pizza pizza(ifs);
pizza.divide();
ofstream ofs (output);
ofs << pizza;
pizza.printMetrics();
return 0;
}
| true |
b3768d36e8c188d33ff6f1242939eea12ee4a04a | C++ | qsnake/deal.II | /include/deal.II/integrators/local_integrators.h | UTF-8 | 5,608 | 2.6875 | 3 | [] | no_license | //---------------------------------------------------------------------------
// $Id: local_integrators.h 24574 2011-10-07 23:03:53Z bangerth $
//
// Copyright (C) 2010, 2011 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#ifndef __deal2__integrators_local_integrators_h
#define __deal2__integrators_local_integrators_h
// This file only provides definition and documentation of the
// namespace LocalIntegrators. There is no necessity to include it
// anywhere in a C++ code. Only doxygen will make use of it.
#include <deal.II/base/config.h>
DEAL_II_NAMESPACE_OPEN
/**
* @brief Library of integrals over cells and faces
*
* This namespace contains application specific local integrals for
* bilinear forms, forms and error estimates. It is a collection of
* functions organized into namespaces devoted to certain
* applications. For instance, the namespace Laplace contains
* functions for computing cell matrices and cell residuals for the
* Laplacian operator, as well as functions for the weak boundary
* conditions by Nitsche or the interior penalty discontinuous
* Galerkin method. The namespace Maxwell does the same for
* curl-curl type problems.
*
* The namespace L2 contains functions for mass matrices and
* <i>L<sup>2</sup></i>-inner products.
*
* <h3>Notational conventions</h3>
*
* In most cases, the action of a function in this namespace can be
* described by a single integral. We distinguish between integrals
* over cells <i>Z</i> and over faces <i>F</i>. If an integral is
* denoted as
* @f[
* \int_Z u \otimes v \,dx,
* @f]
* it will yield the following results, depending on the type of
* operation
* <ul>
* <li> If the function returns a matrix, the entry at
* position <i>(i,j)</i> will be the integrated product of test function
* <i>v<sub>i</sub></i> and trial function <i>u<sub>j</sub></i> (note
* the reversion of indices)</li>
* <li> If the function returns a vector, then the vector
* entry at position <i>i</i> will be the integrated product of the
* given function <i>u</i> with the test function <i>v<sub>i</sub></i>.</li>
* <li> If the function returns a number, then this number is the
* integral of the two given functions <i>u</i> and <i>v</i>.
* </ul>
*
* We will use regular cursive symbols $u$ for scalars and bold
* symbols $\mathbf u$ for vectors. Test functions are always <i>v</i>
* and trial functions are always <i>u</i>. Parameters are Greek and
* the face normal vectors are $\mathbf n = \mathbf n_1 = -\mathbf
* n_2$.
*
* <h3>Signature of functions</h3>
*
* Functions in this namespace follow a generic signature. In the
* simplest case, you have two related functions
* @code
* template <int dim>
* void
* cell_matrix (
* FullMatrix<double>& M,
* const FEValuesBase<dim>& fe,
* const double factor = 1.);
*
* template <int dim>
* void
* cell_residual (
* BlockVector<double>* v,
* const FEValuesBase<dim>& fe,
* const std::vector<Tensor<1,dim> >& input,
* const double factor = 1.);
* @endcode
*
* There is typically a pair of functions for the same operator, the
* function <tt>cell_residual</tt> implementing the mapping of the
* operator from the finite element space into its dual, and the
* function <tt>cell_matrix</tt> generating the bilinear form
* corresponding to the Frechet derivative of <tt>cell_residual</tt>.
*
* The first argument of these functions is the return type, which is
* <ul>
* <li> FullMatrix<double> for matrices
* <li> BlockVector<double> for vectors
* </ul>
*
* The next argument is the FEValuesBase object representing the
* finite element for integration. If the integrated operator maps
* from one finite element space into the dual of another (for
* instance an off-diagonal matrix in a block system), then first the
* FEValuesBase for the trial space and after this the one for the
* test space are specified.
*
* This list is followed by the set of required data in the order
* <ol>
* <li> Data vectors from finite element functions
* <li> Data vectors from other objects
* <li> Additional data
* <li> A factor which is multiplied with the whole result
* </ol>
*
* <h3>Usage</h3>
*
* The local integrators can be used wherever a local integration loop
* would have been implemented instead. The following example is from
* the implementation of a Stokes solver, using
* MeshWorker::Assembler::LocalBlocksToGlobalBlocks. The matrices are
* <ul>
* <li> 0: The vector Laplacian for the velocity (here with a vector valued element)
* <li> 1: The divergence matrix
* <li> 2: The pressure mass matrix used in the preconditioner
* </ul>
*
* With these matrices, the function called by MeshWorker::loop()
* could be written like
* @code
using namespace ::dealii:: LocalIntegrators;
template <int dim>
void MatrixIntegrator<dim>::cell(
MeshWorker::DoFInfo<dim>& dinfo,
typename MeshWorker::IntegrationInfo<dim>& info)
{
Laplace::cell_matrix(dinfo.matrix(0,false).matrix, info.fe_values(0));
Divergence::cell_matrix(dinfo.matrix(1,false).matrix, info.fe_values(0), info.fe_values(1));
L2::cell_matrix(dinfo.matrix(2,false).matrix, info.fe_values(1));
}
* @endcode
*
* @ingroup Integrators
*/
namespace LocalIntegrators
{
}
DEAL_II_NAMESPACE_CLOSE
#endif
| true |
d9379d5f7e69d65f91ba8768d5d9ab5ac5164668 | C++ | arnabxero/online-judges-problem-solutions | /Codeforces/Contests/0935/D-2.cpp | UTF-8 | 1,468 | 2.65625 | 3 | [] | no_license | // Problem name: Fafa and Ancient Alphabet
// Problem link: https://codeforces.com/contest/935/problem/D
// Submission link: https://codeforces.com/contest/935/submission/35504187
#include <bits/stdc++.h>
#define MAX ((int)100000)
#define MOD ((ll)1000000007)
#define endl '\n'
using namespace std;
typedef long long ll;
ll Pow(ll a, ll b){
ll ans = 1LL;
while(b){
if(b & 1LL)
ans = (ans * a) % MOD;
a = (a * a) % MOD;
b >>= 1LL;
}
return ans;
}
int s1[ MAX ], s2[ MAX ];
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m, zeroes = 0;
cin >> n >> m;
for(int i = 0 ; i < n ; i++)
cin >> s1[ i ], zeroes += (s1[ i ] == 0);
for(int i = 0 ; i < n ; i++)
cin >> s2[ i ], zeroes += (s2[ i ] == 0);
ll ans = 0, inv = Pow(Pow(m, zeroes), MOD - 2), f = 1, s = (m * (m - 1LL) / 2LL) % MOD;
for(int i = 0 ; i < n ; i++){
if(s1[ i ] != 0 && s2[ i ] != 0){
if(s1[ i ] < s2[ i ])
break;
if(s1[ i ] > s2[ i ]){
ans = (ans + (f * Pow(m, zeroes)) % MOD) % MOD;
break;
}
}
else if(s1[ i ] == 0 && s2[ i ] == 0){
zeroes -= 2;
ans = (ans + ((f * ((s * Pow(m, zeroes)) % MOD)) % MOD)) % MOD;
f = (f * m) % MOD;
}
else if(s1[ i ] == 0){
zeroes--;
ans = (ans + ((f * (((m - s2[ i ]) * Pow(m, zeroes)) % MOD)) % MOD)) % MOD;
}
else{
zeroes--;
ans = (ans + ((f * (((s1[ i ] - 1) * Pow(m, zeroes)) % MOD)) % MOD)) % MOD;
}
}
cout << ((ans * inv) % MOD) << endl;
return 0;
} | true |
dd904de6914408d8f281f3ca57a21e397e30181c | C++ | phoenix76/final_project | /calculate/oop_calculate/WinForm_old.cpp | WINDOWS-1251 | 9,255 | 2.5625 | 3 | [] | no_license | #include "WinForm.h"
void cWinForm::Run()
{
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnregisterClass("Calculator", m_hInstance);
DestroyWindow(m_mainWnd);
}
bool cWinForm::Initialize()
{
m_mainWnd = NULL;
test = "test";
for(short count = 0; count < 21; count++)
m_buttonHandles[count] = NULL;
m_textField = NULL;
m_hInstance = NULL;
m_backgroundMainWnd = CreateSolidBrush(RGB(219, 215, 210));
m_pInfoHandler = new cCalcInfoHandler;
if(!InitializeWindows())
{
MessageBox(m_mainWnd, "Error Initialize()", "Error", MB_OK);
return false;
}
return true;
}
bool cWinForm::InitializeWindows()
{
ApplicationHandle = this;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(wc));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.cbSize = sizeof(wc);
wc.lpszClassName = "Calculator";
wc.lpszMenuName = NULL;
wc.hbrBackground = m_backgroundMainWnd;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hIconSm = wc.hIcon;
wc.hInstance = m_hInstance;
wc.lpfnWndProc = WndProc;
if(!RegisterClassEx(&wc))
{
MessageBox(m_mainWnd, "Error register class", "Error", MB_OK);
return false;
}
m_mainWnd = CreateWindowEx(NULL, "Calculator", "", WS_VISIBLE | WS_OVERLAPPEDWINDOW, 870, 400, 190, 360, NULL, NULL, m_hInstance, NULL);
if(!m_mainWnd)
{
MessageBox(m_mainWnd, "Error create main window", "Error", MB_OK);
return false;
}
m_buttonHandles[0] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "EX", WS_VISIBLE | WS_CHILD, 10, 120, 30, 30, m_mainWnd, (HMENU)BUTTON_EXIT, m_hInstance, NULL);
if(!m_buttonHandles[0])
{
MessageBox(m_mainWnd, "Error create BUTTON_EXIT", "Error", MB_OK);
return false;
}
m_buttonHandles[1] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "CA", WS_VISIBLE | WS_CHILD, 50, 120, 30, 30, m_mainWnd, (HMENU)BUTTON_REMOVEALL, m_hInstance, NULL);
if(!m_buttonHandles[1])
{
MessageBox(m_mainWnd, "Error create BUTTON_REMOVEALL", "Error", MB_OK);
return false;
}
m_buttonHandles[2] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "C", WS_VISIBLE | WS_CHILD, 90, 120, 30, 30, m_mainWnd, (HMENU)BUTTON_DELETESYMBOL, m_hInstance, NULL);
if(!m_buttonHandles[2])
{
MessageBox(m_mainWnd, "Error create BUTTON_DELETESYMBOL", "Error", MB_OK);
return false;
}
m_buttonHandles[3] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "+", WS_VISIBLE | WS_CHILD, 130, 120, 30, 30, m_mainWnd, (HMENU)BUTTON_SUM, m_hInstance, NULL);
if(!m_buttonHandles[3])
{
MessageBox(m_mainWnd, "Error create BUTTON_SUM", "Error", MB_OK);
return false;
}
m_buttonHandles[4] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "0", WS_VISIBLE | WS_CHILD, 10, 160, 30, 30, m_mainWnd, (HMENU)BUTTON_0, m_hInstance, NULL);
if(!m_buttonHandles[4])
{
MessageBox(m_mainWnd, "Error create BUTTON_0", "Error", MB_OK);
return false;
}
m_buttonHandles[5] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "1", WS_VISIBLE | WS_CHILD, 50, 160, 30, 30, m_mainWnd, (HMENU)BUTTON_1, m_hInstance, NULL);
if(!m_buttonHandles[5])
{
MessageBox(m_mainWnd, "Error create BUTTON_1", "Error", MB_OK);
return false;
}
m_buttonHandles[6] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "2", WS_VISIBLE | WS_CHILD, 90, 160, 30, 30, m_mainWnd, (HMENU)BUTTON_2, m_hInstance, NULL);
if(!m_buttonHandles[6])
{
MessageBox(m_mainWnd, "Error create BUTTON_2", "Error", MB_OK);
return false;
}
m_buttonHandles[7] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "-", WS_VISIBLE | WS_CHILD, 130, 160, 30, 30, m_mainWnd, (HMENU)BUTTON_DIFFERENCE, m_hInstance, NULL);
if(!m_buttonHandles[7])
{
MessageBox(m_mainWnd, "Error create BUTTON_DIFFERENCE", "Error", MB_OK);
return false;
}
m_buttonHandles[8] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "3", WS_VISIBLE | WS_CHILD, 10, 200, 30, 30, m_mainWnd, (HMENU)BUTTON_3, m_hInstance, NULL);
if(!m_buttonHandles[8])
{
MessageBox(m_mainWnd, "Error create BUTTON_3", "Error", MB_OK);
return false;
}
m_buttonHandles[9] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "4", WS_VISIBLE | WS_CHILD, 50, 200, 30, 30, m_mainWnd, (HMENU)BUTTON_4, m_hInstance, NULL);
if(!m_buttonHandles[9])
{
MessageBox(m_mainWnd, "Error create BUTTON_4", "Error", MB_OK);
return false;
}
m_buttonHandles[10] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "5", WS_VISIBLE | WS_CHILD, 90, 200, 30, 30, m_mainWnd, (HMENU)BUTTON_5, m_hInstance, NULL);
if(!m_buttonHandles[10])
{
MessageBox(m_mainWnd, "Error create BUTTON_5", "Error", MB_OK);
return false;
}
m_buttonHandles[11] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "*", WS_VISIBLE | WS_CHILD, 130, 200, 30, 30, m_mainWnd, (HMENU)BUTTON_PRODUCT, m_hInstance, NULL);
if(!m_buttonHandles[11])
{
MessageBox(m_mainWnd, "Error create BUTTON_PRODUCT", "Error", MB_OK);
return false;
}
m_buttonHandles[12] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "6", WS_VISIBLE | WS_CHILD, 10, 240, 30, 30, m_mainWnd, (HMENU)BUTTON_6, m_hInstance, NULL);
if(!m_buttonHandles[12])
{
MessageBox(m_mainWnd, "Error create BUTTON_6", "Error", MB_OK);
return false;
}
m_buttonHandles[13] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "7", WS_VISIBLE | WS_CHILD, 50, 240, 30, 30, m_mainWnd, (HMENU)BUTTON_7, m_hInstance, NULL);
if(!m_buttonHandles[13])
{
MessageBox(m_mainWnd, "Error create BUTTON_7", "Error", MB_OK);
return false;
}
m_buttonHandles[14] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "8", WS_VISIBLE | WS_CHILD, 90, 240, 30, 30, m_mainWnd, (HMENU)BUTTON_8, m_hInstance, NULL);
if(!m_buttonHandles[14])
{
MessageBox(m_mainWnd, "Error create BUTTON_8", "Error", MB_OK);
return false;
}
m_buttonHandles[15] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "/", WS_VISIBLE | WS_CHILD, 130, 240, 30, 30, m_mainWnd, (HMENU)BUTTON_QUOTIENT, m_hInstance, NULL);
if(!m_buttonHandles[15])
{
MessageBox(m_mainWnd, "Error create BUTTON_QUOTIENT", "Error", MB_OK);
return false;
}
m_buttonHandles[16] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "9", WS_VISIBLE | WS_CHILD, 10, 280, 30, 30, m_mainWnd, (HMENU)BUTTON_9, m_hInstance, NULL);
if(!m_buttonHandles[16])
{
MessageBox(m_mainWnd, "Error create BUTTON_9", "Error", MB_OK);
return false;
}
m_buttonHandles[17] = CreateWindowEx(WS_EX_STATICEDGE, "Button", ".", WS_VISIBLE | WS_CHILD, 50, 280, 30, 30, m_mainWnd, (HMENU)BUTTON_POINT, m_hInstance, NULL);
if(!m_buttonHandles[17])
{
MessageBox(m_mainWnd, "Error create BUTTON_POINT", "Error", MB_OK);
return false;
}
m_buttonHandles[18] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "=", WS_VISIBLE | WS_CHILD, 90, 280, 30, 30, m_mainWnd, (HMENU)BUTTON_RESULT, m_hInstance, NULL);
if(!m_buttonHandles[18])
{
MessageBox(m_mainWnd, "Error create BUTTON_RESULT", "Error", MB_OK);
return false;
}
m_buttonHandles[19] = CreateWindowEx(WS_EX_STATICEDGE, "Button", "%", WS_VISIBLE | WS_CHILD, 130, 280, 30, 30, m_mainWnd, (HMENU)BUTTON_MODULE, m_hInstance, NULL);
if(!m_buttonHandles[19])
{
MessageBox(m_mainWnd, "Error create BUTTON_MODULE", "Error", MB_OK);
return false;
}
m_buttonHandles[20] = CreateWindowEx(WS_EX_STATICEDGE, "Button", " ...", WS_VISIBLE | WS_CHILD, 10, 80, 150, 30, m_mainWnd, (HMENU)BUTTON_ABOUT, m_hInstance, NULL);
if(!m_buttonHandles[20])
{
MessageBox(m_mainWnd, "Error create BUTTON_ABOUT", "Error", MB_OK);
return false;
}
m_textField = CreateWindowEx(WS_EX_CLIENTEDGE, "Static", "", WS_VISIBLE | WS_CHILD, 10, 10, 150, 60, m_mainWnd, (HMENU)TEXTFIELD_ELEMENT, m_hInstance, NULL);
if(!m_textField)
{
MessageBox(m_mainWnd, "Error create TEXTFIELD_ELEMENT", "Error", MB_OK);
return false;
}
ShowWindow(m_mainWnd, SW_SHOW);
UpdateWindow(m_mainWnd);
return true;
}
LRESULT CALLBACK cWinForm::MessageHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_COMMAND:
switch(wParam)
{
case BUTTON_0:
break;
case BUTTON_1:
break;
case BUTTON_2:
return 0;
case BUTTON_3:
return 0;
case BUTTON_4:
return 0;
case BUTTON_5:
return 0;
case BUTTON_6:
return 0;
case BUTTON_7:
return 0;
case BUTTON_8:
return 0;
case BUTTON_9:
return 0;
case BUTTON_RESULT:
break;
case BUTTON_DELETESYMBOL:
break;
case BUTTON_REMOVEALL:
break;
case BUTTON_SUM:
break;
case BUTTON_DIFFERENCE:
break;
case BUTTON_PRODUCT:
break;
case BUTTON_QUOTIENT:
break;
case BUTTON_MODULE:
break;
case BUTTON_POINT:
break;
case BUTTON_EXIT:
PostQuitMessage(0);
return 0;
case BUTTON_ABOUT:
MessageBox(hwnd, "Calculator v1.01\nCreated by DSOFT 22.10.2015\nAll rights reserved", "About", MB_OK);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
void cWinForm::Shutdown()
{
delete m_pInfoHandler;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wParam, LPARAM lParam)
{
switch(umessage)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
default:
return ApplicationHandle->MessageHandler(hwnd, umessage, wParam, lParam);
}
} | true |
78bed2a730e61eb05070c3b07efa8975cda468a1 | C++ | iShubhamRana/DSA-Prep | /DP-patterns/Decision-Making/02-house-robber-2.cpp | UTF-8 | 1,276 | 2.828125 | 3 | [] | no_license | class Solution
{
int HouseRobberOne(vector<int> &A, int start, int end)
{
if (start > end)
return 0;
int robPrev = A[start], doNotRobPrev = 0;
for (int i = start + 1; i <= end; ++i)
{
int robCurr = A[i] + doNotRobPrev;
int doNotRobCurr = max(robPrev, doNotRobPrev);
robPrev = robCurr;
doNotRobPrev = doNotRobCurr;
}
return max(robPrev, doNotRobPrev);
}
public:
int rob(vector<int> &A)
{
if (A.size() == 1)
return A[0];
return max(HouseRobberOne(A, 0, A.size() - 2), HouseRobberOne(A, 1, A.size() - 1));
// int dp[101][2][2] = {}, n = A.size();
// if(n == 1) return A[0];
// dp[0][0][0] = 0;
// dp[0][1][1] = A[0];
// for(int i = 1; i < n; ++i) {
// dp[i][1][0] = A[i] + dp[i - 1][0][0];
// dp[i][1][1] = A[i] + dp[i - 1][0][1];
// dp[i][0][0] = max(dp[i - 1][1][0], dp[i - 1][0][0]);
// dp[i][0][1] = max(dp[i - 1][1][1], dp[i - 1][0][1]);
// }
// return max(max(dp[n - 1][0][0], dp[n - 1][0][1]), dp[n - 1][1][0]);
}
}; | true |
da217ba73b4311c38e7b064125a1610203b7c71e | C++ | arieshan/OperatingSystem | /Bus_Simulation/projects/BUSSIMULATION_Optimization/CS520_HomeWork2_BUSSIMULATION/Event.h | UTF-8 | 1,349 | 3 | 3 | [] | no_license | /* * * * * * * * * * * * * * * * * * * * * * * * *
* course : CS_520 *
* First Name : Xiao *
* Second Name : Li *
* CWID : 10409766 *
* Subject : Home_work_2 Bus_Simulation *
* * * * * * * * * * * * * ** * * * * * * * * * * */
#pragma once
#include <iostream>
#include <queue>
using namespace std;
class Event { // define the event structure. Main simulation object
private:
int event_type; // define event type
double time; // define the event time
int stop_number; // record the current event stop number
int bus_number; // record the current bus number
int event_count; // record the current event number
public:
Event(int type, double system_time, int stop_number, int bus_number, int event_counter); // constructor for bus event
Event(int type, double system_time, int stop_number,int event_counter); // constructor for person event
int get_Type(); // get the event type
double get_time(); // get the event time
int get_Stop_Number(); // get the event stop number
int get_Bus_Number(); // get the event bus number
double update(double increase_time); // update the event time
int get_Event_Count(); // get the event number
}; | true |
71a6505a4ad351dc077e602882a6f3d166238fd5 | C++ | musakhan18/OOP | /OOP Assignment 2/OPP Assignment 2/Task 1/Date.cpp | UTF-8 | 2,278 | 3.515625 | 4 | [] | no_license | #include "Date.h"
Date::Date()
{
Day = 01;
Month = 01;
Year = 2000;
}
Date::Date(int D, int M, int Y)
{
Day = D;
Month = M;
Year = Y;
}
Date::Date(const Date& other)
{
Day=other.Day;
Month=other.Month;
Year=other.Year;
}
bool Date::validatedate()const
{
bool Valid;
if (Day <= 0 || Day > 31 || Month <= 0 || Month > 12 || Year < 1900 && Year > 2100)
{
Valid = 0;
}
else
{
Valid = 1;
}
return Valid;
}
bool Date::InputDate()
{
cout << "Enter Day: "; cin >> Day;
cout << "Enter Month: "; cin >> Month;
cout << "Enter Year: "; cin >> Year;
bool f = validatedate();
if (!f)
{
Day = 01;
Month = 01;
Year = 2000;
}
return f;
}
void Date::SetDay(int d)
{
Day = d;
}
void Date::SetMonth(int m)
{
Month = m;
}
void Date::SetYear(int y)
{
Year = y;
}
int Date::GetDay()const
{
return Day;
}
int Date::GetMonth()const
{
return Month;
}
int Date::GetYear()const
{
return Year;
}
bool Date::InputCompleteDate(int d, int m, int y)
{
Day = d;
Month = m;
Year = y;
bool Valid = validatedate();
if (!Valid)
{
Day = 01;
Month = 01;
Year = 2000;
}
return Valid;
}
Date& Date::GetDate()const
{
Date temp;
temp.Day = Day;
temp.Month = Month;
temp.Year = Year;
return temp;
}
void Date::ShowDate()const
{
cout << "Date is: " << Day << "-" << Month << "-" << Year << endl;
cout << endl;
}
bool Date::IsEqual(Date& other)
{
bool Equal;
if (other.Day != Day || other.Month != Month || other.Year != Year)
{
Equal = 0;
}
else
{
Equal = 1;
}
return Equal;
}
bool Date::IsLeap()
{
bool Leap;
if (Year % 4 == 0)
{
if (Year % 100 == 0)
{
if (Year % 400 == 0)
{
Leap=1;
}
else
{
Leap = 0;
}
}
else
{
Leap = 1;
}
}
else
{
Leap = 0;
}
return Leap;
}
bool Date:: CopyDate(Date& other)
{
bool F;
bool Valid= validatedate();
if (!Valid)
{
F = 0;
}
else
{
Day = other.Day;
Month = other.Month;
Year = other.Year;
F = 1;
}
return F;
}
void Date::RetriveDate(int& d, int& m, int& y)
{
Day = d;
Month = m;
Year = y;
}
Date::~Date()
{
Day = 0;
Month = 0;
Year = 0;
} | true |
d7f2f2d7b45e4de31e178573090a28488fed2d81 | C++ | Skr1mpl/Voenkomat | /Checks.cpp | WINDOWS-1251 | 9,093 | 2.78125 | 3 | [] | no_license | #include "Checks.h"
void setColor(int text, int background) {
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
}
string encryptPass(string pass) {
string encrypt;
for (int i = 0; i < pass.length(); i++) {
char c = pass[i];
c = c + '*' + ')';
encrypt.push_back(c);
}
return encrypt;
}
string deencryptPass(string encrypt) {
string deencrypt;
for (int i = 0; i < encrypt.length(); i++) {
char c = encrypt[i];
c = c - '*' - ')';
deencrypt.push_back(c);
}
return deencrypt;
}
string writeLoginAndPass(string& login, string& password, string reg_or_signin) {
int schet = 0;
string password1 = "";
writeRegOrLog(0, login, password1, reg_or_signin);
while (true) {
int keyboard_button;
char symbol;
keyboard_button = _getch();
if (keyboard_button == 224) {
keyboard_button = _getch();
if ((keyboard_button == 80 && schet == 2)) {
writeRegOrLog(3, login, password1, reg_or_signin);
while (true) {
keyboard_button = _getch();
if (keyboard_button == 224) {
keyboard_button = _getch();
if (keyboard_button == 72) {
writeRegOrLog(1, login, password1, reg_or_signin);
break;
}
}
else
if (keyboard_button == 13) {
login = "-1";
password = "-1";
system("cls");
return "-1";
}
}
}
else
if (keyboard_button == 80 && schet == 0) {
writeRegOrLog(1, login, password1, reg_or_signin);
schet = 1;
}
else
if (keyboard_button == 72 && schet == 1) {
writeRegOrLog(0, login, password1, reg_or_signin);
schet = 0;
}
else
if ((keyboard_button == 80 && schet == 1) || (keyboard_button == 72 && schet == 3)) {
writeRegOrLog(2, login, password1, reg_or_signin);
schet = 2;
while (true) {
keyboard_button = _getch();
if (keyboard_button == 13) {
system("cls");
return "1";
}
else
if (keyboard_button == 224) {
keyboard_button = _getch();
if (keyboard_button == 72) { writeRegOrLog(1, login, password1, reg_or_signin); schet = 1; break; }
else
if (keyboard_button == 80) { writeRegOrLog(3, login, password1, reg_or_signin); schet = 3; break; }
}
}
}
}
else
if ((keyboard_button == 8 && login.length() > 0 && schet == 0) || (keyboard_button == 8 && password.length() > 0 && schet == 1)) {
system("cls");
if (schet == 0 && login.length() != 0) {
login.erase(login.length() - 1);
writeRegOrLog(0, login, password1, reg_or_signin);
}
else
if (schet == 1 && password.length() != 0) {
password.erase(password.length() - 1);
password1.erase(password1.length() - 1);
writeRegOrLog(1, login, password1, reg_or_signin);
}
}
else
if (keyboard_button == 13 && schet == 3) { system("cls"); return "-1"; }
else
if (keyboard_button == 13 && schet == 2) { system("cls"); return "1"; }
else
if (schet != 3 && schet != 2)
if ((keyboard_button >= 'a' && keyboard_button <= 'z') || (keyboard_button >= 'A' && keyboard_button <= 'Z') || (keyboard_button >= '0' && keyboard_button <= '9')) {
if (schet == 0) {
symbol = (char)keyboard_button;
login = login + symbol;
writeRegOrLog(0, login, password1, reg_or_signin);
}
else {
symbol = (char)keyboard_button;
password = password + symbol;
password1 = password1 + "*";
writeRegOrLog(1, login, password1, reg_or_signin);
}
}
}
}
void writeRegOrLog(int n, string login, string password, string reg_or_signin) {
system("cls");
if (n == 0) {
cout << " " << endl;
setColor(2, 0);
cout << " -> : " << login << endl;
setColor(15, 0);
cout << " : " << password << endl;
cout << reg_or_signin << endl;
cout << " " << endl;
}
else
if (n == 1) {
cout << " " << endl;
cout << " : " << login << endl;
setColor(2, 0);
cout << " -> : " << password << endl;
setColor(15, 0);
cout << reg_or_signin << endl;
cout << " " << endl;
}
else
if (n == 2) {
cout << " " << endl;
cout << " : " << login << endl;
cout << " : " << password << endl;
setColor(2, 0);
cout << " -> " << reg_or_signin << endl;
setColor(15, 0);
cout << " " << endl;
}
else
if (n == 3) {
cout << " " << endl;
cout << " : " << login << endl;
cout << " : " << password << endl;
cout << reg_or_signin << endl;
setColor(2, 0);
cout << " -> " << endl;
setColor(15, 0);
}
}
string writeEngWords() {
string str;
while (true) {
int key;
key = _getch();
if (key == 224) {
key = _getch();
}
else
if (key == 8) {
if (str.length() != 0) {
cout << '\b' << " " << '\b';
str.erase(str.length() - 1);
}
}
else
if (key == 13 && str.length() != 0) break;
else
if ((key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key >= '0' && key <= '9')) {
str = str + (char)key;
cout << (char)key;
}
}
return str;
}
int godOrNot() {
int choose_menu = 0, keyboard_button = 0;
while (true) {
cout << " " << endl;
choose_menu = (choose_menu + 2) % 2;
if (choose_menu == 0) { setColor(2, 0); cout << " -> " << endl; setColor(15, 0); }
else cout << " " << endl;
if (choose_menu == 1) { setColor(2, 0); cout << " -> " << endl; setColor(15, 0); }
else cout << " " << endl;
keyboard_button = _getch();
if (keyboard_button == 224) {
keyboard_button = _getch();
if (keyboard_button == 72) choose_menu--;
if (keyboard_button == 80) choose_menu++;
}
if (keyboard_button == 13) { system("cls"); return choose_menu; }
system("cls");
}
}
| true |
8c215c0908949286e2edd3fed5f44e21a4b66eab | C++ | SilverHL/Leetcode | /931.下降路径最小和.cpp | UTF-8 | 1,210 | 2.6875 | 3 | [] | no_license | #include <vector>
#include <climits>
using namespace std;
/*
* @lc app=leetcode.cn id=931 lang=cpp
*
* [931] 下降路径最小和
*/
// @lc code=start
class Solution {
public:
int minFallingPathSum(vector<vector<int>>& A) {
if (A.empty()) return 0;
int n = A.size();
if (n == 1)
return A[0][0];
vector<vector<int>> dp(n, vector<int>(n, INT_MAX));
for (int i = 0; i < n; ++i) {
dp[0][i] = A[0][i];
}
for (int i = 1; i < n; ++i)
for (int j = 0; j < n; ++j) {
int t1 = dp[i-1][j];
if (j == 0 && j < n-1) {
dp[i][j] = min(t1, dp[i-1][j+1]);
} else if (j == n-1 && j > 0) {
dp[i][j] = min(t1, dp[i-1][j-1]);
} else{
int t2 = dp[i-1][j+1];
int t3 = dp[i-1][j-1];
dp[i][j] = min(t1, min(t2, t3));
}
dp[i][j] += A[i][j];
}
int res = INT_MAX;
for (auto i : dp[n-1]) {
if (i < res)
res = i;
}
return res;
}
};
// @lc code=end
| true |
8688896e5b12d75a84f5860e8ca9087b5b580c94 | C++ | d-nalbandian0329/cpp | /normal/test3_28.cpp | UTF-8 | 610 | 3.546875 | 4 | [] | no_license | // コンテナを継承してパラメータ化継承によってメンバを追加する
#include <iostream>
#include <vector>
#include <list>
template <class Base>
class Printable : public Base {
public:
using Base::Base;
std::ostream& print_on(std::ostream& stream,
const char* delim = " ") const {
for (const auto& x : *this) {
stream << x << delim;
}
return stream;
}
};
int main() {
using namespace std;
Printable<vector<int>> pv { 1, 2, 3 };
Printable<list<int>> pl { 4, 3, 2 };
pv.print_on(std::cout) << std::endl;
pl.print_on(std::cout, ",") << std::endl;
return 0;
}
| true |
cb2c9ae7a12d13ec2b5f4639a4ad21b4df033e26 | C++ | GenguoWang/CppLib | /test/testSegTree.cpp | UTF-8 | 702 | 2.546875 | 3 | [] | no_license | #include "../SegTree.h"
void testSegTree()
{
int pos[10001];
memset((void*)pos,0,sizeof(pos));
pos[0] = 1;
pos[10000] = 1;
kingo::SegTree st(0,10000);
st.insert(0);
st.insert(10000);
int tests = 1000,l,r;
while(tests--)
{
int num = rand()%9000+1;
if(pos[num]) continue;
cout << "find " << num << endl;
st.find(num,l,r);
cout << "find " << num << endl;
int ll = num,rr=num;
while(pos[ll]==0)ll--;
while(pos[rr]==0)rr++;
st.insert(num);
pos[num] = 1;
assert(l==ll&&r==rr);
}
}
int main()
{
testSegTree();
cout << "Passed " << endl;
return 0;
}
| true |
2a84a7a7f287f496017b868dd079fcbdc7cca6d7 | C++ | abonifacio/juego-sensor-mov | /sensor/sensor.ino | UTF-8 | 2,020 | 2.984375 | 3 | [
"MIT"
] | permissive | /*
Sensor de proximidad y al ser inferior a 10cm
envia un pulso de alarma por el pin 13
HC-SR04 conexiones:
VCC al arduino 5v
GND al arduino GND
Echo al Arduino pin 6
Trig al Arduino pin 7
Descargar planos de conexiones en http://elprofegarcia.com/
*/
#define Pecho 6
#define Ptrig 7
#define CANT_MUESTRAS 7
#define MEDIO 3
#define DELAY 8
long duracion,espera;
long distancia,suma;
int efectivas,vueltas;
long historicas[CANT_MUESTRAS];
void bubble_sort(long list[], long n);
void setup() {
Serial.begin (9600); // inicializa el puerto seria a 9600 baudios
pinMode(Pecho, INPUT); // define el pin 6 como entrada (echo)
pinMode(Ptrig, OUTPUT); // define el pin 7 como salida (triger)
pinMode(13, 1); // Define el pin 13 como salida
suma = 0;
efectivas = 0;
vueltas = 0;
for(int i;i<CANT_MUESTRAS;i++){
historicas[i]=0;
}
}
void loop() {
digitalWrite(Ptrig, LOW);
delayMicroseconds(2);
digitalWrite(Ptrig, HIGH); // genera el pulso de triger por 10ms
delayMicroseconds(10);
digitalWrite(Ptrig, LOW);
duracion = pulseIn(Pecho, HIGH); // calcula la distancia en mm
if(duracion<2321){
distancia = (duracion/2) / 29 ;
espera = DELAY - duracion / 1000;
suma+=distancia;
efectivas++;
historicas[vueltas]=distancia;
}else{
espera = 1;
}
vueltas++;
if(vueltas==CANT_MUESTRAS){
bubble_sort(historicas,CANT_MUESTRAS);
Serial.println(historicas[MEDIO]);
for(int i;i<CANT_MUESTRAS;i++){
historicas[i]=0;
}
suma = 0;
efectivas = 0;
vueltas = 0;
}
digitalWrite(13, 0);
delay(espera);
}
void bubble_sort(long list[], long n)
{
long c, d, t;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
t = list[d];
list[d] = list[d+1];
list[d+1] = t;
}
}
}
}
| true |
28e5572edd292526ac7fd4899e148f8473d8006b | C++ | curtisbright/swinekeeper | /minesolver/CInputField.cpp | UTF-8 | 1,552 | 2.9375 | 3 | [] | no_license |
#include "StdAfx.h"
#include "CInputField.h"
#include "CMineArray.h"
std::string CInputField::toString() const {
if (m_nIsKnownBomb)
return std::string("B");
else if (m_bCovered)
return std::string("C");
else
{
char str[2];
str[0] = '0' + m_nCount;
str[1] = 0;
return std::string(str);
}
}
bool CInputField::fromString(const std::string& str) {
if (str.length() != 1)
return false;
if (str[0] == 'B')
{
setKnownBomb();
return true;
}
if (str[0] == 'C')
{
setCovered();
return true;
}
else if (str[0] >= '0' && str[0] <= '9')
{
setUncovered(str[0]-'0');
return true;
}
else
{
return false;
}
}
/**
* Creates a CFieldValue (type used by the algos) from CInputField
*/
static CFieldValue inputFieldToSolve(CInputField src)
{
CFieldValue dst;
if (src.isKnownBomb())
{
dst.makeSolveCovered();
dst.setResolvedAs(true);
}
else if (src.isCovered())
dst.makeSolveCovered();
else
dst.makeSolveCount(src.getCount());
return dst;
}
void inputArrayToSolveArray(CMineArray &dst, const CMineArrayBase<CInputField> &inputArray)
{
dst.resize(inputArray.range());
CMethodOp0<CFieldValue> makeMarginOp(&CFieldValue::makeSolveMargin);
dst.doWithArrayAndMargin(makeMarginOp);
for(CRangeIterator iter(inputArray.range()); iter.isValid(); iter++)
{
dst[iter.curPos()] = inputFieldToSolve(inputArray[iter.curPos()]);
}
}
| true |
26a2cbb44b621c4558377bdba3302d63c9ea5300 | C++ | MTASZTAKI/ApertusVR | /include/apeQuaternion.h | UTF-8 | 8,394 | 2.640625 | 3 | [
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | /*MIT License
Copyright (c) 2018 MTA SZTAKI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#ifndef APE_QUATERNION_H
#define APE_QUATERNION_H
#include <cmath>
#include <sstream>
#include <vector>
#include "apeDegree.h"
#include "apeMatrix3.h"
#include "apeRadian.h"
#include "apeVector3.h"
namespace ape
{
struct Quaternion
{
float w, x, y, z;
Quaternion() :
w(1.0f), x(0.0f), y(0.0f), z(0.0f)
{}
Quaternion(float _w, float _x, float _y, float _z) :
w(_w), x(_x), y(_y), z(_z)
{}
Quaternion(const ape::Degree& _degRot, const ape::Vector3& _axRot)
{
FromAngleAxis(ape::Radian(_degRot.toRadian()), _axRot);
}
Quaternion(const ape::Radian& _radRot, const ape::Vector3& _axRot)
{
FromAngleAxis(_radRot, _axRot);
}
Quaternion(const ape::Matrix3& m3x3)
{
FromRotationMatrix(m3x3);
}
Quaternion operator+ (const Quaternion& rkQ) const
{
return Quaternion(w + rkQ.w, x + rkQ.x, y + rkQ.y, z + rkQ.z);
}
Quaternion operator- (const Quaternion& rkQ) const
{
return Quaternion(w - rkQ.w, x - rkQ.x, y - rkQ.y, z - rkQ.z);
}
Quaternion operator- () const
{
return Quaternion(-w, -x, -y, -z);
}
Quaternion operator / (const float fScalar) const
{
return Quaternion(
w / fScalar,
x / fScalar,
y / fScalar,
z / fScalar);
}
ape::Vector3 operator* (const ape::Vector3& v) const
{
ape::Vector3 uv, uuv;
ape::Vector3 qvec(x, y, z);
uv = qvec.crossProduct(v);
uuv = qvec.crossProduct(uv);
uv = uv * (2.0f * w);
uuv = uuv * 2.0f;
return v + uv + uuv;
}
bool operator < (const Quaternion& rkQ) const
{
return (w < rkQ.w && x < rkQ.x && y < rkQ.y && z < rkQ.z);
}
bool operator > (const Quaternion& rkQ) const
{
return (w > rkQ.w && x > rkQ.x && y > rkQ.y && z > rkQ.z);
}
Quaternion product(const Quaternion& rkQ) const
{
return Quaternion(
w * rkQ.w - x * rkQ.x - y * rkQ.y - z * rkQ.z,
w * rkQ.x + x * rkQ.w + y * rkQ.z - z * rkQ.y,
w * rkQ.y + y * rkQ.w + z * rkQ.x - x * rkQ.z,
w * rkQ.z + z * rkQ.w + x * rkQ.y - y * rkQ.x);
}
Quaternion operator* (const Quaternion& rkQ) const
{
return product(rkQ);
}
void FromAngleAxis(ape::Radian _angleRadian, const ape::Vector3& _axis)
{
float fHalfAngle((float)(0.5 * _angleRadian.radian));
float fSin = std::sin(fHalfAngle);
w = std::cos(fHalfAngle);
x = fSin * _axis.x;
y = fSin * _axis.y;
z = fSin * _axis.z;
}
void FromRotationMatrix(const ape::Matrix3& kRot)
{
float fTrace = kRot[0][0] + kRot[1][1] + kRot[2][2];
float fRoot;
if (fTrace > 0.0)
{
fRoot = std::sqrt(fTrace + 1.0f);
w = 0.5f * fRoot;
fRoot = 0.5f / fRoot;
x = (kRot[2][1] - kRot[1][2]) * fRoot;
y = (kRot[0][2] - kRot[2][0]) * fRoot;
z = (kRot[1][0] - kRot[0][1]) * fRoot;
}
else
{
static size_t s_iNext[3] = { 1, 2, 0 };
size_t i = 0;
if (kRot[1][1] > kRot[0][0])
i = 1;
if (kRot[2][2] > kRot[i][i])
i = 2;
size_t j = s_iNext[i];
size_t k = s_iNext[j];
fRoot = std::sqrt(kRot[i][i] - kRot[j][j] - kRot[k][k] + 1.0f);
float* apkQuat[3] = { &x, &y, &z };
*apkQuat[i] = 0.5f * fRoot;
fRoot = 0.5f / fRoot;
w = (kRot[k][j] - kRot[j][k]) * fRoot;
*apkQuat[j] = (kRot[j][i] + kRot[i][j]) * fRoot;
*apkQuat[k] = (kRot[k][i] + kRot[i][k]) * fRoot;
}
}
bool equals(const ape::Quaternion& _q2, ape::Radian _tolerance)
{
/*float fCos = w * _q2.w + x * _q2.x + y * _q2.y + z * _q2.z;
float angle = std::acos(fCos);
return (abs(angle) <= _tolerance.radian) || abs(angle - ape_PI) <= _tolerance.radian;*/
return (_q2.x == x) && (_q2.y == y) && (_q2.z == z) && (_q2.w == w);
}
float Norm() const
{
return w * w + x * x + y * y + z * z;
}
float normalise()
{
float len = Norm();
float factor = 1.0f / std::sqrt(len);
w = w * factor;
x = x * factor;
y = y * factor;
z = z * factor;
return len;
}
Quaternion Inverse() const
{
float fNorm = w * w + x * x + y * y + z * z;
if (fNorm > 0.0)
{
float fInvNorm = 1.0f / fNorm;
return Quaternion(w * fInvNorm, -x * fInvNorm, -y * fInvNorm, -z * fInvNorm);
}
else
{
return Quaternion(0, 0, 0, 0);
}
}
float Dot(const Quaternion& rkQ) const
{
return w * rkQ.w + x * rkQ.x + y * rkQ.y + z * rkQ.z;
}
static Quaternion Slerp(float fT, const Quaternion& rkP,
const Quaternion& rkQ, bool shortestPath)
{
float fCos = rkP.Dot(rkQ);
Quaternion rkT;
if (fCos < 0.0f && shortestPath)
{
fCos = -fCos;
rkT = -rkQ;
}
else
{
rkT = rkQ;
}
if (abs(fCos) < 1 - 1e-03)
{
float fSin = std::sqrt(1 - std::pow(fCos, 2));
Radian fAngle = std::atan2(fSin, fCos);
float fInvSin = 1.0f / fSin;
float fCoeff0 = std::sin((1.0f - fT) * fAngle.radian) * fInvSin;
float fCoeff1 = std::sin(fT * fAngle.radian) * fInvSin;
return Quaternion(fCoeff0 * rkP.w, fCoeff0 * rkP.x, fCoeff0 * rkP.y, fCoeff0 * rkP.z) + Quaternion(fCoeff1 * rkT.w, fCoeff1 * rkT.x, fCoeff1 * rkT.y, fCoeff1 * rkT.z);
}
else
{
float fScalar0 = (1.0f - fT);
Quaternion t = Quaternion(fScalar0 * rkP.w, fScalar0 * rkP.x, fScalar0 * rkP.y, fScalar0 * rkP.z) + Quaternion(fT * rkT.w, fT * rkT.x, fT * rkT.y, fT * rkT.z);
t.normalise();
return t;
}
}
void ToRotationMatrix(ape::Matrix3& kRot) const
{
float fTx = x + x;
float fTy = y + y;
float fTz = z + z;
float fTwx = fTx * w;
float fTwy = fTy * w;
float fTwz = fTz * w;
float fTxx = fTx * x;
float fTxy = fTy * x;
float fTxz = fTz * x;
float fTyy = fTy * y;
float fTyz = fTz * y;
float fTzz = fTz * z;
kRot[0][0] = 1.0f - (fTyy + fTzz);
kRot[0][1] = fTxy - fTwz;
kRot[0][2] = fTxz + fTwy;
kRot[1][0] = fTxy + fTwz;
kRot[1][1] = 1.0f - (fTxx + fTzz);
kRot[1][2] = fTyz - fTwx;
kRot[2][0] = fTxz - fTwy;
kRot[2][1] = fTyz + fTwx;
kRot[2][2] = 1.0f - (fTxx + fTyy);
}
float getW() { return w; }
float getX() { return x; }
float getY() { return y; }
float getZ() { return z; }
std::string toString() const
{
std::ostringstream buff;
buff << w << ", " << x << ", " << y << ", " << z;
return buff.str();
}
std::string toJsonString() const
{
std::ostringstream buff;
buff << "{ \"w\": " << w << ", \"x\": " << x << ", \"y\": " << y << ", \"z\": " << z << " }";
return buff.str();
}
std::vector<float> toVector() const
{
std::vector<float> vec{ w, x, y, z };
return vec;
}
void write(std::ofstream& fileStreamOut, bool writeSize = true)
{
if (writeSize)
{
long sizeInBytes = 16;
fileStreamOut.write(reinterpret_cast<char*>(&sizeInBytes), sizeof(long));
}
fileStreamOut.write(reinterpret_cast<char*>(&w), sizeof(float));
fileStreamOut.write(reinterpret_cast<char*>(&x), sizeof(float));
fileStreamOut.write(reinterpret_cast<char*>(&y), sizeof(float));
fileStreamOut.write(reinterpret_cast<char*>(&z), sizeof(float));
}
void read(std::ifstream& fileStreamIn)
{
fileStreamIn.read(reinterpret_cast<char*>(&w), sizeof(float));
fileStreamIn.read(reinterpret_cast<char*>(&x), sizeof(float));
fileStreamIn.read(reinterpret_cast<char*>(&y), sizeof(float));
fileStreamIn.read(reinterpret_cast<char*>(&z), sizeof(float));
}
};
}
#endif
| true |
da77b32949ef4aca7bc56eee4fbbc94c81103ca8 | C++ | emilymye/shippingnetwork | /Instance.cpp | UTF-8 | 28,005 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | #include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <cctype>
#include "Nominal.h"
#include "Instance.h"
#include "ActivityImpl.h"
#include "Engine.h"
#include "Entity.h"
#include "Reactors.h"
//#include "EntityReactor.h"
using namespace std;
namespace Shipping {
class ManagerImpl : public Instance::Manager {
public:
ManagerImpl();
Ptr<Instance> instanceNew(const string& name, const string& type);
Ptr<Instance> instance(const string& name);
void instanceDel(const string& name);
private:
bool statsCreated;
bool connCreated;
bool fleetCreated;
ShippingNetwork::Ptr network_;
ShippingNetworkReactor* reactor_;
Ptr<Activity::Manager> activityManager_;
enum InstanceType {
None,
Location,
Segment,
Fleet,
Stats,
Connection,
};
struct InstanceStore{
Ptr<Instance> instance;
InstanceType type;
InstanceStore() : instance(0), type(None) {}
InstanceStore(Ptr<Instance> p, InstanceType t):
instance(p), type(t) {}
};
map<string, InstanceStore> instance_;
};
/* ====== | STATIC STRINGS | ====================*/
//STATS - ASSN 3:
static const string simulationStr = "Simulation";
// INSTANCE & STATS TYPES
static const string customerStr = "Customer";
static const string portStr = "Port";
static const string truckTerminalStr = "Truck terminal";
static const string boatTerminalStr = "Boat terminal";
static const string planeTerminalStr = "Plane terminal";
static const string truckSegmentStr = "Truck segment";
static const string boatSegmentStr = "Boat segment";
static const string planeSegmentStr = "Plane segment";
static const string statsStr = "Stats";
static const string connStr = "Conn";
static const string fleetStr = "Fleet";
static const string segmentStr = "segment"; //LOCATION
static const unsigned int segmentStrlen = segmentStr.length();
//Customer only:
static const string transferRateStr = "Transfer Rate";
static const string shipmentSizeStr = "Shipment Size";
static const string destinationStr = "Destination";
static const string shipmentsRecievedStr = "Shipments Received";
static const string latencyStr = "Average Latency";
static const string totalCostStr = "Total Cost";
static const string sourceStr = "source"; //SEGMENT
static const string lengthStr = "length";
static const string returnSegStr = "return segment";
static const string difficultyStr = "difficulty";
static const string expSupportStr = "expedite support";
static const string shipmentsRefusedStr = "Shipments Refused";
static const string shipmentCapacityStr = "Capacity";
static const string speedStr = "speed"; //FLEET
static const string capacityStr = "capacity";
static const string expPercentStr = "expedite percentage"; //STATS (ASSN2)
static const string exploreStr = "explore"; //CONNECTION
static const string connectStr = "connect";
static const string distanceStr = "distance";
static const string costStr = "cost";
static const string timeStr = "time";
static const string expeditedStr = "expedited";
static const unsigned int connTypeStrLen = exploreStr.length();
// =========== | LOCATION INSTANCES |==========================
class LocationRep : public Instance {
public:
LocationRep(const string& name, ManagerImpl* manager, ShippingNetwork::Ptr network):
Instance(name), manager_(manager), network_(network){}
virtual string attribute(const string& name);
virtual void attributeIs(const string& name, const string& v);
protected:
Ptr<Location> loc_;
Ptr<ManagerImpl> manager_;
Ptr<ShippingNetwork> network_;
int segmentNumber(const string& name) {
if (name.substr(0, segmentStrlen) == segmentStr) {
const char* t = name.c_str() + segmentStrlen;
return atoi(t);
}
return 0;
}
};
string LocationRep::attribute(const string& name) {
if (name.length() > segmentStrlen) {
int idx = segmentNumber(name);
if (idx) {
Segment::Ptr s = loc_->segment(idx);
if (s) return s->name();
}
}
cerr << "Location - Invalid attribute/segment " << name << endl;
return "";
}
void LocationRep::attributeIs(const string& name, const string& v) {
throw Fwk::AttributeNotSupportedException("Invalid attribute: Location does not allow attributeIs \n");
}
//LOCATION INSTANCES SUBCLASSES
class CustomerRep : public LocationRep {
public:
CustomerRep(const string& name, ManagerImpl *manager, ShippingNetwork::Ptr network, Fwk::Ptr<Activity::Manager> am) :
LocationRep(name, manager, network) {
loc_ = CustomerLocation::CustomerLocationNew(name);
network_->locationNew(loc_);
loc_->lastNotifieeIs( new CustomerReactor(loc_.ptr(), am, network) );
}
string attribute(const string& name);
void attributeIs(const string& name, const string& v);
private:
CustomerLocation::Ptr loc_;
};
string CustomerRep::attribute(const string& name) {
try {
stringstream ss;
if (name == destinationStr) {
return (loc_->destination()) ? loc_->destination()->name() : "";
} else if (name == transferRateStr) {
ss << loc_->transferRate().value();
return ss.str();
} else if (name == shipmentSizeStr) {
ss << loc_->shipmentSize().value();
return ss.str();
} else if (name == shipmentsRecievedStr) {
ss << loc_->recieved().value();
return ss.str();
} else if (name == latencyStr) {
ss.precision(2);
ss << fixed << loc_->latency().value();
return ss.str();
} else if (name == totalCostStr) {
ss.precision(2);
ss << fixed << loc_->totalCost().value();
return ss.str();
}
throw Fwk::AttributeNotSupportedException("Invalid Customer Location attribute :" + name);
} catch (Fwk::Exception &e) {
cerr << e.what() << endl;
} catch (...) { }
return "";
}
void CustomerRep::attributeIs(const string& name, const string& v) {
if (name == transferRateStr) {
loc_->transferRateIs(atoi(v.c_str()));
} else if (name == shipmentSizeStr) {
loc_->shipmentSizeIs(atoi(v.c_str()));
} else if (name == destinationStr) {
if (v.empty()) loc_->destinationIs(NULL);
else {
CustomerLocation* d = dynamic_cast<CustomerLocation*>(network_->location(v));
if (d == NULL)
throw Fwk::EntityNotFoundException("Customer destination does not exist: " + v);
else
loc_->destinationIs(d);
}
} else {
throw Fwk::AttributeNotSupportedException("Invalid Customer Location attribute :" + name);
}
}
class PortRep : public LocationRep {
public:
PortRep(const string& name, ManagerImpl *manager, ShippingNetwork::Ptr network,Fwk::Ptr<Activity::Manager> am ) :
LocationRep(name, manager, network) {
loc_ = PortLocation::PortLocationNew(name);
network_->locationNew(loc_);
loc_ -> lastNotifieeIs( new LocationReactor(loc_.ptr(), am));
}
};
class TruckTerminalRep : public LocationRep {
public:
TruckTerminalRep(const string& name, ManagerImpl *manager, ShippingNetwork::Ptr network, Fwk::Ptr<Activity::Manager> am ) :
LocationRep(name, manager, network) {
loc_ = TruckTerminal::TruckTerminalNew(name);
network_->locationNew(loc_);
loc_ -> lastNotifieeIs( new LocationReactor(loc_.ptr(), am));
}
};
class BoatTerminalRep : public LocationRep {
public:
BoatTerminalRep(const string& name, ManagerImpl *manager, ShippingNetwork::Ptr network, Fwk::Ptr<Activity::Manager> am ) :
LocationRep(name, manager, network) {
loc_ = BoatTerminal::BoatTerminalNew(name);
network_->locationNew(loc_);
loc_ -> lastNotifieeIs( new LocationReactor(loc_.ptr(), am));
}
};
class PlaneTerminalRep : public LocationRep {
public:
PlaneTerminalRep(const string& name, ManagerImpl *manager, ShippingNetwork::Ptr network, Fwk::Ptr<Activity::Manager> am ) :
LocationRep(name, manager, network) {
loc_ = PlaneTerminal::PlaneTerminalNew(name);
network_->locationNew(loc_);
loc_ -> lastNotifieeIs( new LocationReactor(loc_.ptr(), am));
}
};
// SEGMENT INSTANCE ==========================
class SegmentRep : public Instance {
public:
SegmentRep(const string& name, ManagerImpl* manager, ShippingNetwork::Ptr sn, ShippingNetworkReactor::Ptr snr)
: Instance(name), manager_(manager), sn_(sn), snreactor_(snr){}
string attribute(const string& name);
void attributeIs(const string& name, const string& v);
protected:
Segment::Ptr seg_;
Ptr<ManagerImpl> manager_;
ShippingNetwork::Ptr sn_;
ShippingNetworkReactor::Ptr snreactor_;
};
string SegmentRep::attribute(const string& name) {
stringstream ss;
if (name == sourceStr){
return (seg_->source()) ?
seg_->source()->name() : "";
} else if (name == lengthStr) {
stringstream ss;
ss.precision(2);
ss << fixed << seg_->length().value();
return ss.str();
} else if (name == returnSegStr) {
return (seg_->returnSegment()) ?
seg_->returnSegment()->name() : "";
} else if (name == difficultyStr) {
stringstream ss;
ss.precision(2);
ss << fixed << seg_->difficulty().value();
return ss.str();
} else if (name == expSupportStr) {
return (seg_->expediteSupport()) ? "yes" : "no";
} else if (name == shipmentsRecievedStr) {
ss << seg_->receivedShipments().value();
return ss.str();
} else if (name == shipmentsRefusedStr) {
ss << seg_->refusedShipments().value();
return ss.str();
} else if (name == shipmentCapacityStr) {
ss << seg_->shipmentCapacity().value();
return ss.str();
}
cerr << "invalid Segment attribute: " << name << endl;
return "";
}
void SegmentRep::attributeIs(const string& name, const string& v){
try {
if (!name.compare(sourceStr)) { //setting source
Location* l = sn_->location(v);
if (!l && !v.empty()){
throw Fwk::EntityNotFoundException("invalid source " + v + " for Segment");
}
if (v.empty()) {
if (seg_->source())
seg_->source()->segmentDel(seg_);
seg_->sourceIs(0);
} else if ( l->type() <= Location::port() || l->type() == Location::terminalIdx() + seg_->mode()) {
if (seg_->source())
seg_->source()->segmentDel(seg_);
seg_->sourceIs(l);
l->segmentNew(seg_);
} else {
throw Fwk::IllegalNameException("cannot attach segment of this mode to location " + v);
return;
}
} else if (!name.compare(returnSegStr)) { //set return segment
if (!v.compare(seg_->name()))
throw Fwk::AttributeNotSupportedException("Cannot set return segment to be same segment");
Segment::Ptr rSeg = sn_->segment(v);
if (!rSeg && !v.empty()) {
throw Fwk::EntityNotFoundException("Segment returnSegment: Invalid segment name");
}
if (seg_->returnSegment()) {
seg_->returnSegment()->returnSegmentIs(0);
}
if (rSeg) {
seg_->returnSegmentIs(rSeg.ptr());
rSeg->returnSegmentIs(seg_.ptr());
} else {
seg_->returnSegmentIs(0);
}
} else if (!name.compare(lengthStr)) {
seg_->lengthIs(atof(v.c_str()));
} else if (!name.compare(difficultyStr)) {
seg_->difficultyIs( atof(v.c_str()));
} else if (!name.compare(expSupportStr)){
if (!v.compare("yes")){
if (seg_->expediteSupport()) return;
seg_->expediteSupportIs(true);
if (sn_->notifiee() != NULL)
sn_->notifiee()->onSegmentExpediteChange(true);
} else if (!v.compare("no")){
if (!seg_->expediteSupport()) return;
seg_->expediteSupportIs(false);
if (sn_->notifiee())
sn_->notifiee()->onSegmentExpediteChange(false);
}
} else if (name == shipmentCapacityStr) {
seg_->shipmentCapacityIs(atoi(v.c_str()));
} else {
throw Fwk::AttributeNotSupportedException("Invalid segment attribute: Segment " + name);
}
} catch (Fwk::RangeException & e) {
throw Fwk::RangeException("Segment attribute value out of range: " + name + v);
} // Passes all but RangeExceptions back to client without editing
}
class TruckSegmentRep : public SegmentRep {
public:
TruckSegmentRep(const string& name, ManagerImpl* manager, ShippingNetwork::Ptr sn, ShippingNetworkReactor::Ptr snr, Fwk::Ptr<Activity::Manager> am) : SegmentRep(name, manager, sn, snr) {
seg_ = TruckSegment::TruckSegmentNew(name);
sn_->segmentNew(seg_);
seg_->lastNotifieeIs( new SegmentReactor(seg_.ptr(),sn->fleet(),am) );
}
};
class BoatSegmentRep : public SegmentRep {
public:
BoatSegmentRep(const string& name, ManagerImpl* manager, ShippingNetwork::Ptr sn, ShippingNetworkReactor::Ptr snr, Fwk::Ptr<Activity::Manager> am) :
SegmentRep(name, manager, sn, snr) {
seg_ = BoatSegment::BoatSegmentNew(name);
sn_->segmentNew(seg_);
seg_->lastNotifieeIs( new SegmentReactor(seg_.ptr(),sn->fleet(),am) );
}
};
class PlaneSegmentRep : public SegmentRep {
public:
PlaneSegmentRep(const string& name, ManagerImpl* manager, ShippingNetwork::Ptr sn, ShippingNetworkReactor::Ptr snr, Fwk::Ptr<Activity::Manager> am) :
SegmentRep(name, manager, sn, snr) {
seg_ = PlaneSegment::PlaneSegmentNew(name);
sn_->segmentNew(seg_);
seg_->lastNotifieeIs( new SegmentReactor(seg_.ptr(),sn->fleet(),am) );
}
};
class StatsRep : public Instance {
public:
StatsRep(const string& name, ManagerImpl* manager, ShippingNetworkReactor* reactor) :
Instance(name), manager_(manager), reactor_(reactor) {}
string attribute(const string& name);
void attributeIs(const string& name, const string& v);
private:
Ptr<ManagerImpl> manager_;
ShippingNetworkReactor* reactor_;
};
string StatsRep::attribute(const string& name) {
stringstream ss;
if (!name.compare(expPercentStr)) {
ss.precision(2);
ss << fixed << reactor_->expeditedPercent().value();
} else if (name == customerStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::customer() );
} else if (name == portStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::port() );
} else if (name == truckTerminalStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::truckTerminal() );
} else if (name == boatTerminalStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::boatTerminal() );
} else if (name == planeTerminalStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::planeTerminal() );
} else if (name == truckSegmentStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::truckSegment() );
} else if (name == boatSegmentStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::boatSegment() );
} else if (name == planeSegmentStr) {
ss << reactor_->shippingEntities( ShippingNetworkReactor::planeSegment() );
} else {
cerr << "Invalid Statistics attribute: " << name << endl;
return "";
}
return ss.str();
}
void StatsRep::attributeIs(const string& name, const string& v) {
cerr << "cannot set attribute for Statistics" << endl;
throw Fwk::AttributeNotSupportedException("Statistics " + name);
}
/* =========== | CONNECTION REP | =======================*/
class ConnRep : public Instance {
public:
ConnRep(const string& name, ManagerImpl* manager, ShippingNetwork::Ptr sn) :
Instance(name), manager_(manager), network_(sn) {}
string attribute(const string& name);
void attributeIs(const string& name, const string& v);
private:
Ptr<ManagerImpl> manager_;
ShippingNetwork::Ptr network_;
};
string ConnRep::attribute(const string& name) {
if (name.length() <= connTypeStrLen){
cerr << "Invalid Connection attribute: " << name << endl;
return "";
}
string connType = name.substr(0,connTypeStrLen);
stringstream ss;
ss << name.substr(connTypeStrLen + 1);
string startLoc;
string token;
ss >> startLoc >> token;
try {
if (!connType.compare(exploreStr)) {
ShippingNetwork::ExplorationQuery q;
while (!ss.eof()){
ss >> token;
if (!token.compare(distanceStr)){
float dist;
ss >> dist;
q.maxDist = dist;
} else if (!token.compare(costStr)){
float cost;
ss >> cost;
q.maxCost = cost;
} else if (!token.compare(timeStr)){
float time;
ss >> time;
q.maxTime = time;
} else if (!token.compare(expeditedStr)){
q.expedited = true;
}
else {
cerr << "Invalid explore query attribute" << token << endl;
return "";
}
}
return network_->path(startLoc, q);
} else if (!connType.compare(connectStr)) {
string endLoc;
ss >> endLoc;
return network_->path(startLoc, endLoc);
} else {
cerr << "Invalid Connection attribute" << endl;
}
} catch (...) {
cerr << "Error finding connection: " << name << endl;
return "";
}
return "";
}
void ConnRep::attributeIs(const string& name, const string& v) {
throw Fwk::AttributeNotSupportedException("Invalid Connection attribute " + name);
}
/* =========== | FLEET REP | =======================*/
class FleetRep : public Instance {
public:
FleetRep(const string& name, ManagerImpl* manager, Fleet::Ptr f) :
Instance(name), manager_(manager), fleet_(f){ }
string attribute(const string& name);
void attributeIs(const string& name, const string& v);
private:
Ptr<ManagerImpl> manager_;
Fleet::Ptr fleet_;
};
string FleetRep::attribute(const string& name) {
size_t idx = name.find(',');
if (idx==std::string::npos) {
cerr << "invalid Fleet attribute: " << name << endl;
return "";
}
string mode = name.substr(0, idx);
string property = name.substr(idx + 2);
ShippingMode m;
if (!mode.compare("Truck")){
m = Fleet::truck();
} else if (!mode.compare("Boat")){
m = Fleet::boat();
} else if (!mode.compare("Plane")){
m = Fleet::plane();
} else {
cerr << "invalid mode - Fleet attribute" << mode << endl;
return "";
}
stringstream ss;
string str = "";
if (!property.compare(speedStr)){
ss.precision(2);
ss << fixed << fleet_->speed(m).value();
} else if (!property.compare(costStr)){
ss.precision(2);
ss << fixed << fleet_->cost(m).value();
} else if (!property.compare(capacityStr)){
ss << fleet_->capacity(m).value();
} else {
cerr << "invalid property for Fleet attribute" << endl;
}
ss >> str;
return str;
}
void FleetRep::attributeIs(const string& name, const string& v) {
size_t idx = name.find(',');
if (idx==std::string::npos) {
throw Fwk::AttributeNotSupportedException("invalid Fleet attribute: " + name);
}
string mode = name.substr(0, idx);
string property = name.substr(idx + 2);
ShippingMode m;
if (!mode.compare("Truck")){
m = Fleet::truck();
} else if (!mode.compare("Boat")){
m = Fleet::boat();
} else if (!mode.compare("Plane")){
m = Fleet::plane();
} else {
throw Fwk::AttributeNotSupportedException("invalid Fleet mode: " + mode);
}
try{
if (!property.compare(speedStr)){
fleet_->speedIs(m,atof(v.c_str()));
} else if (!property.compare(costStr)){
fleet_->costIs(m,atof(v.c_str()));
} else if (!property.compare(capacityStr)){
fleet_->capacityIs(m,atoi(v.c_str()));
} else {
throw Fwk::AttributeNotSupportedException("invalid Fleet property: " + property);
}
} catch (Fwk::RangeException & e) {
throw Fwk::RangeException("Fleet attribute value out of range: " + name + v);
}
}
/* =========== | INSTANCE MANAGER IMPLEMENTATION | ======================= */
ManagerImpl::ManagerImpl() : statsCreated(false),connCreated(false),fleetCreated(false) {
network_ = ShippingNetwork::ShippingNetworkNew("network");
reactor_ = new ShippingNetworkReactor(network_.ptr());
network_->lastNotifieeIs(reactor_);
activityManager_ = activityManagerInstance();
}
Ptr<Instance> ManagerImpl::instance(const string& name) {
map<string,InstanceStore>::const_iterator t = instance_.find(name);
if (t == instance_.end()) {
cerr << name << " does not exist as an instance\n";
return NULL;
}
return (t->second).instance;
}
Ptr<Instance> ManagerImpl::instanceNew (const string& name, const string& type) {
if (instance_.find(name) != instance_.end()){
cerr << "Instance with name already exists" << endl;
return NULL;
}
if (type == customerStr) {
Ptr<CustomerRep> t = new CustomerRep(name, this, network_,activityManager_);
instance_[name] = InstanceStore(t, Location);
return t;
} else if (type == portStr) {
Ptr<PortRep> t = new PortRep(name, this, network_, activityManager_);
instance_[name] = InstanceStore(t,Location);
return t;
} else if (type == truckTerminalStr) {
Ptr<TruckTerminalRep> t = new TruckTerminalRep(name, this, network_, activityManager_);
instance_[name] = InstanceStore(t,Location);
return t;
}
else if (type == boatTerminalStr) {
Ptr<BoatTerminalRep> t = new BoatTerminalRep(name, this, network_, activityManager_);
instance_[name] = InstanceStore(t,Location);
return t;
}
else if (type == planeTerminalStr) {
Ptr<PlaneTerminalRep> t = new PlaneTerminalRep(name, this, network_, activityManager_);
instance_[name] = InstanceStore(t,Location);
return t;
}
else if (type == truckSegmentStr) {
Ptr<TruckSegmentRep> t = new TruckSegmentRep(name, this, network_, reactor_,activityManager_);
instance_[name] = InstanceStore(t,Segment);
return t;
}
else if (type == boatSegmentStr) {
Ptr<BoatSegmentRep> t = new BoatSegmentRep(name, this, network_,reactor_,activityManager_);
instance_[name] = InstanceStore(t,Segment);
return t;
}
else if (type == planeSegmentStr) {
Ptr<PlaneSegmentRep> t = new PlaneSegmentRep(name, this, network_,reactor_,activityManager_);
instance_[name] = InstanceStore(t,Segment);
return t;
}
else if (type == fleetStr) {
if (fleetCreated) return NULL;
Ptr<FleetRep> t = new FleetRep(name, this, network_->fleetNew(name));
fleetCreated = true;
instance_[name] = InstanceStore(t,Fleet);
return t;
} else if (type == statsStr) {
if (statsCreated) return NULL;
Ptr<StatsRep> t = new StatsRep(name, this, reactor_);
statsCreated = true;
instance_[name] = InstanceStore(t,Stats);
return t;
}
else if (type == connStr) {
if (connCreated) return NULL;
Ptr<ConnRep> t = new ConnRep(name, this, network_);
connCreated = true;
instance_[name] = InstanceStore(t,Connection);
return t;
return NULL;
}
return NULL;
}
void ManagerImpl::instanceDel(const string& name) {
map<string,InstanceStore>::iterator t = instance_.find(name);
if (t == instance_.end()) {
cerr << name << " does not exist as an instance\n";
return;
}
switch( t->second.type ){
case Location: network_->locationDel( name ); break;
case Segment: network_->segmentDel( name ); break;
case Fleet: network_->fleetDel( name ); fleetCreated = false; break;
case Stats: statsCreated = false; break;
case Connection: connCreated = false; break;
default: break;
}
instance_.erase(t->first);
}
}
/*
* This is the entry point for your library.
* The client program will call this function to get a handle
* on the Instance::Manager object, and from there will use
* that object to interact with the middle layer (which will
* in turn interact with the engine layer).
*/
Ptr<Instance::Manager> shippingInstanceManager() {
return new Shipping::ManagerImpl();
} | true |
2239cb8b1473fecd4b2494af65ce763c789a3cb5 | C++ | ramsharan072011/arduino-sketches | /UtraSonicSensor/UtraSonicSensor.ino | UTF-8 | 1,541 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #include <Servo.h>
int trigger = 4;
int echo = 3;
int time=0;
int distance = 7;
float speed;
Servo servo1;
void setup() {
Serial.begin(9600);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
pinMode(2,OUTPUT);//Red
pinMode(6,OUTPUT);//Yellow
pinMode(5,OUTPUT);//Green
pinMode(8,OUTPUT);//Buzzer
servo1.attach(A0);
servo1.write(0);
}
void loop()
{
time = pulseIn(echo,LOW);
digitalWrite(trigger,LOW); //dont send a wave
delay(5);
digitalWrite(trigger,HIGH); // send out a wave for
delay(10); // 10 milliseconds
//delayMicroseconds(10);
digitalWrite(trigger,LOW);
//delay(10);
time = pulseIn(echo,HIGH);
Serial.println(time);
speed = (time*.0343)/2;
delay(100);
digitalWrite(5,HIGH);
tone(8,100);
if (time < 750)
{
noTone(8);
digitalWrite(5,LOW);
digitalWrite(6,HIGH);
tone(8,3000,1000);
Serial.println('wash');
for(int i = 0;i<90;i++)
{
servo1.write(i);
delay(25);
}
for(int i = 90;i>=0;i--)
{
servo1.write(i);
delay(50);
}
digitalWrite(6,LOW);
digitalWrite(2,HIGH);
tone(8,3000,500);
delay(10000);
digitalWrite(2,LOW);
digitalWrite(5,HIGH);
}
}
| true |
8d3aa27effdcfece9db78b8d419b88b8368d93b1 | C++ | sulicat/graphics | /ray_tracer_03/src/projectile.cpp | UTF-8 | 284 | 2.75 | 3 | [] | no_license | #include "../include/projectile.h"
Projectile::Projectile( Tuple _pos, Tuple _vel ){
pos = _pos;
vel = _vel;
}
std::string Projectile::toString(){
std::cout << "Projectile:\n";
std::cout << " pos:\t" << pos << "\n";
std::cout << " vel:\t" << vel << "\n";
return "";
}
| true |
384a84671da4639802d31b94ee650a7e5a8c6973 | C++ | zhangsj1007/leetcode | /210_CourseScheduleII/Solution.hpp | UTF-8 | 1,457 | 3.203125 | 3 | [] | no_license | class Solution {
public:
//1.需要检查dfs是否有环
//2.onpath的使用
//3.reverse的使用
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph = makeGraph(numCourses, prerequisites);
//stack<int> toposort;
vector<bool> visited(numCourses, false);
vector<bool> onpath(numCourses, false);
vector<int> toposort;
for (int i = 0; i < numCourses; i++){
if (!visited[i] && dfs(graph, i, onpath, visited, toposort)){
return {};
}
}
reverse(toposort.begin(), toposort.end());
return toposort;
}
private:
vector<unordered_set<int>> makeGraph(int numCourses, vector<pair<int, int>>& prerequisites){
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites){
graph[pre.second].insert(pre.first);
}
return graph;
}
bool dfs(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited, vector<int>& toposort){
if (visited[node]){
return false;
}
onpath[node] = visited[node] = true;
for (auto link : graph[node]){
if (onpath[link] || dfs(graph, link, onpath, visited, toposort)){
return true;
}
}
toposort.push_back(node);
return onpath[node] = false;
}
};
| true |
fe2e9ffc43f19dadd5c1a6e4b74666900170e4ff | C++ | dingxuan2000/cse100-pa1 | /test/bst/test_BST.cpp | UTF-8 | 7,681 | 3.4375 | 3 | [] | no_license | #include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "BST.hpp"
#include "util.hpp"
using namespace std;
using namespace testing;
/* Empty BST test starts here */
TEST(BSTTests, EMPTY_TREE_HEIGHT_TEST) {
BST<int> bst;
ASSERT_EQ(bst.height(), -1);
}
/* Small BST test starts here */
/**
* A simple test fixture from which multiple tests
* can be created. All fixture tests (denoted by the
* TEST_F macro) can access the protected members of this
* fixture. Its data is reset after every test.
*
* Builds the following BST:
* 3
* / \
* 1 4
* / \
* -33 100
*/
class SmallBSTFixture : public ::testing ::Test {
protected:
BST<int> bst;
public:
SmallBSTFixture() {
// initialization code here
vector<int> input{3, 4, 1, 100, -33};
insertIntoBST(input, bst);
}
// code in SetUp() will execute just before the test ensues
// void SetUp() {}
};
TEST_F(SmallBSTFixture, SMALL_SIZE_TEST) {
// assert that the small BST has the correct size
ASSERT_EQ(bst.size(), 5);
}
TEST_F(SmallBSTFixture, SMALL_INSERT_DUPLICATES_TEST) {
// assert failed duplicate insertion
ASSERT_FALSE(bst.insert(3));
}
//----------------------------------------------------------
// TODO : add more BST tests here
TEST(BSTTests, EMPTY_HEIGHT) {
BST<int> bst;
ASSERT_EQ(bst.height(), -1) << "Before inserting, the height is -1.";
}
TEST(BSTTests, EMPTY_SIZE) {
BST<int> bst;
ASSERT_EQ(bst.size(), 0) << "Before inserting, the size is 0.";
}
TEST(BSTTests, EMPTY_ROOT) {
BST<int> bst;
ASSERT_EQ(bst.empty(), true) << "Before inserting, the tree is empty.";
}
TEST(BSTTests, EMPTY_INSERT) {
BST<int> bst;
ASSERT_EQ(bst.insert(7), true);
}
TEST(BSTTests, EMPTY_FIND) {
BST<int> bst;
ASSERT_EQ(bst.find(7), nullptr);
}
TEST(BSTTests, EMPTY_BEGIN) {
BST<int> bst;
ASSERT_EQ(bst.begin(), nullptr);
}
TEST(BSTTests, EMPTY_INORDER) {
BST<int> bst;
vector<int> vtr{};
ASSERT_EQ(bst.inorder(), vtr);
}
class TestBSTFixture : public ::testing::Test {
protected:
BST<int> bst;
// BST<int> newbst(*bst);
public:
TestBSTFixture() {
bst.insert(7);
bst.insert(12);
bst.insert(5);
bst.insert(18);
bst.insert(6);
// newbst.insert(7);
// newbst.insert(12);
// newbst.insert(5);
// newbst.insert(18);
// newbst.insert(6);
}
~TestBSTFixture() {}
};
TEST_F(TestBSTFixture, NON_EMPTY_ROOT) { ASSERT_EQ(bst.empty(), false); }
TEST_F(TestBSTFixture, NON_EMPTY_Size) {
ASSERT_EQ(bst.size(), 5) << "After inserting, the size is 5.";
}
TEST_F(TestBSTFixture, NON_EMPTY_Height) {
ASSERT_EQ(bst.height(), 2) << "After inserting, the height is 2.";
}
TEST_F(TestBSTFixture, CHECK_INSERT) {
EXPECT_FALSE(bst.insert(7));
// bst.insert(4);
EXPECT_TRUE(bst.insert(4));
EXPECT_EQ(bst.height(), 2);
// bst.insert(19);
EXPECT_TRUE(bst.insert(19));
EXPECT_EQ(bst.height(), 3);
}
TEST_F(TestBSTFixture, CHECK_FIND) {
EXPECT_EQ(bst.find(4), nullptr);
EXPECT_EQ(*(bst.find(7)), 7);
EXPECT_EQ(*(bst.find(12)), 12);
EXPECT_EQ(*(bst.find(5)), 5);
EXPECT_EQ(*(bst.find(18)), 18);
ASSERT_EQ(*(bst.find(6)), 6);
}
TEST_F(TestBSTFixture, CHECK_INORDER) {
vector<int> vtr{5, 6, 7, 12, 18};
ASSERT_EQ(bst.inorder(), vtr);
}
TEST_F(TestBSTFixture, CHECK_BEGIN) { ASSERT_EQ(*(bst.begin()), 5); }
TEST_F(TestBSTFixture, CHECK_END) { ASSERT_EQ(bst.end(), nullptr); }
TEST_F(TestBSTFixture, CHECK_PRINT) { bst.print(&cout); }
TEST(BSTTests, DELETENODE_RIGHT_LINKEDLIST) {
BST<int> bstr;
bstr.insert(2);
bstr.insert(3);
bstr.insert(6);
bstr.insert(12);
bstr.insert(18);
bstr.insert(50);
// vector<int> vtr = bstr.inorder();
EXPECT_TRUE(bstr.deleteNode(2));
ASSERT_EQ(bstr.size(), 5);
}
TEST(BSTTests, DELETENODE_LEFT_LINKEDLIST) {
BST<int> bstr;
bstr.insert(50);
bstr.insert(18);
bstr.insert(12);
bstr.insert(6);
bstr.insert(3);
bstr.insert(2);
// vector<int> vtr = bstr.inorder();
EXPECT_TRUE(bstr.deleteNode(50));
ASSERT_EQ(bstr.size(), 5);
}
TEST(BSTTests, DELETENODE_LEAFNODE_ROOT) {
BST<int> bstr;
bstr.insert(2);
ASSERT_TRUE(bstr.deleteNode(2));
}
TEST(BSTTests, DELETENODE_RIGHT_LEAFNODE) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(5);
bstr.insert(10);
bstr.insert(20);
EXPECT_TRUE(bstr.deleteNode(20));
ASSERT_EQ(bstr.size(), 3);
}
TEST(BSTTests, DELETENODE_LEFT_LEAFNODE) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(5);
bstr.insert(10);
bstr.insert(8);
EXPECT_TRUE(bstr.deleteNode(8));
ASSERT_EQ(bstr.size(), 3);
}
TEST(BSTTests, DELETENODE_NODE_TWOCHILD_CASE1) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(5);
bstr.insert(20);
EXPECT_TRUE(bstr.deleteNode(7));
ASSERT_EQ(bstr.size(), 2);
}
TEST(BSTTests, DELETENODE_NODE_TWOCHILD_CASE2) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(5);
bstr.insert(20);
bstr.insert(15);
EXPECT_TRUE(bstr.deleteNode(15));
ASSERT_EQ(bstr.size(), 3);
}
TEST(BSTTests, DELETENODE_NODE_TWOCHILD_CASE3) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(5);
bstr.insert(10);
bstr.insert(8);
bstr.insert(9);
EXPECT_TRUE(bstr.deleteNode(7));
ASSERT_EQ(bstr.size(), 4);
}
TEST(BSTTests, DELETENODE_NODE_TWOCHILD_CASE4) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(5);
bstr.insert(20);
bstr.insert(25);
bstr.insert(21);
bstr.insert(30);
EXPECT_TRUE(bstr.deleteNode(7));
ASSERT_EQ(bstr.size(), 5);
}
TEST(BSTTests, DELETENODE_NODE_SINGLECHILD_CASE1) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(3);
bstr.insert(2);
bstr.insert(5);
EXPECT_TRUE(bstr.deleteNode(7));
ASSERT_EQ(bstr.size(), 3);
}
TEST(BSTTests, DELETENODE_NODE_SINGLECHILD_CASE2) {
BST<int> bstr;
bstr.insert(7);
bstr.insert(10);
bstr.insert(8);
bstr.insert(15);
EXPECT_TRUE(bstr.deleteNode(7));
ASSERT_EQ(bstr.size(), 3);
}
TEST(BSTTests, DELETENODE_NODE_SINGLECHILD_CASE3) {
BST<int> bstr;
bstr.insert(10);
bstr.insert(5);
bstr.insert(3);
bstr.insert(1);
bstr.insert(4);
EXPECT_TRUE(bstr.deleteNode(5));
ASSERT_EQ(bstr.size(), 4);
}
TEST(BSTTests, DELETENODE_NODE_SINGLECHILD_CASE4) {
BST<int> bstr;
bstr.insert(5);
bstr.insert(15);
bstr.insert(10);
bstr.insert(9);
bstr.insert(12);
EXPECT_TRUE(bstr.deleteNode(15));
ASSERT_EQ(bstr.size(), 4);
}
TEST(BSTTests, DELETENODE_NODE_SINGLECHILD_CASE5) {
BST<int> bstr;
bstr.insert(20);
bstr.insert(10);
bstr.insert(25);
bstr.insert(15);
bstr.insert(13);
bstr.insert(17);
EXPECT_TRUE(bstr.deleteNode(10));
ASSERT_EQ(bstr.size(), 5);
}
TEST(BSTTests, DELETENODE_NODE_SINGLECHILD_CASE6) {
BST<int> bstr;
bstr.insert(10);
bstr.insert(5);
bstr.insert(20);
bstr.insert(30);
bstr.insert(25);
bstr.insert(35);
EXPECT_TRUE(bstr.deleteNode(20));
ASSERT_EQ(bstr.size(), 5);
}
TEST(BSTTests, CHECK_BALANCING) {
BST<int> bstr = BST<int>();
bstr.insert(7);
bstr.insert(5);
bstr.insert(12);
bstr.insert(4);
bstr.insert(6);
bstr.insert(18);
bstr.insert(17);
bstr.insert(20);
BST<int> copy = BST<int>(bstr);
BST<int>::iterator it = copy.begin();
vector<int> vtr{4, 5, 6, 7, 12, 17, 18, 20};
for (int i = 0; i < bstr.size(); i++) {
ASSERT_EQ(*it, vtr[i]);
it++;
}
}
| true |
8fa2fa57d7e2a0f5204ba07212d7307caca43103 | C++ | delefme/Algorismia | /1. Backtracking-Permutations/EspeciesIncompatibles.cc | UTF-8 | 1,202 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef vector<char> CharVec;
typedef vector<int> Vec;
typedef vector<Vec> Taula;
int n, incomp;
CharVec especies;
Taula compatibles;
Vec posats, V;
void escriu() {
for (int i = 0; i < n; ++i) cout << especies[V[i]];
cout << endl;
}
void f(int p) {
if(p == n) return escriu();
for (int i = 0; i < n; ++i) {
if(not posats[i]) {
if(p == 0 or compatibles[i][V[p-1]]) {
posats[i] = true;
V[p] = i;
f(p+1);
posats[i] = false;
}
}
}
}
int main() {
cin >> n;
especies = CharVec(n);
compatibles = Taula(n, Vec(n, true));
posats = Vec(n, false);
V = Vec(n);
for(int i = 0; i < n; ++i) cin >> especies[i];
cin >> incomp;
char esp1, esp2;
int e1, e2;
for(int i = 0; i < incomp; ++i) {
cin >> esp1 >> esp2;
for (int j = 0; j < n; ++j)
{
if(esp1 == especies[j]) e1 = j;
if(esp2 == especies[j]) e2 = j;
}
compatibles[e1][e2] = false;
compatibles[e2][e1] = false;
}
f(0);
}
| true |
d4b436dac55037ecf109ce5bee9a221a88316604 | C++ | soplist/study-c-cpp | /c++/day02/11 time.cpp | GB18030 | 774 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <ctime>
#include <iomanip>//ʽĿͷļ
using namespace std;
class Time{
public:
int h;
int m;
int s;
//1
void dida(){
s++;
if(s==60){ s=0; m++; }
if(m==60){ m=0; h++; }
if(h==24){ h=0;}
}
//ʾʱ
void show(){
cout<<setfill('0');//˼˵0հλ
cout<<setw(2)<<h<<":"<<setw(2)
<<m<<":"<<setw(2)<<s<<flush<<"\r";//setw(2),˼λflushˢ» ""\r"
}
//,ÿ1,ʾһ
void run(){
while(1){//ʾͣߣѭ
show();
dida();
time_t cur = time(0);//time(0)ʾǰʱ
while(time(0)==cur);
}
}
};
int main()
{
Time t;
t.h=0; t.m=0; t.s=0;
t.run();
}
| true |
5a4947b03fa58cb0735505556eb57dbe56fc3a8b | C++ | CraigSanto/225Examples | /225examples/arrays/example2.cpp | UTF-8 | 1,091 | 3.796875 | 4 | [] | no_license | #include <iostream>
using namespace std;
/* Declaring DYNAMIC (heap) arrays:
* Note that the initial values of the arrays are 0, and not garbage
* The print method still doesn't like taking in these values.
*
* K: I don't think this is true ^. I ran the code and added a printArr before the for loop
* and the output was : 0: 0 1: 268435456 2: 0 3: 268435456 4: 2084896784.
* I think we should just encourage them to never assume memory is 0ed out for them.
* That way they'll never get into trouble :p
*
* Note the slight difference in the delete call for arrays.
* Otherewise, there is nothing else special about an int* assigned to an array.
* Once freed, it can just as easily point to a single int.
* But this is most likely bad form.
*/
void printArr(int * x, int len){
for(int i = 0; i < len; i++){
cout << i << ": " << x[i] << " ";
}
cout << endl;
}
int main(){
int * x = new int[5];
int xLen = 5;
for(int i = 0; i < xLen; i++) x[i] = i*i;
printArr(x, xLen);
delete[] x;
x = NULL;
x = new int(5);
cout << *x << endl;
delete x;
x = NULL;
return 0;
}
| true |
a9f7c2de869a8d765e503bab52dc42bff5059036 | C++ | Antecarlo/CursoC | /modulo3/eclipse/factura_llamadas/Factura.cpp | UTF-8 | 1,854 | 2.96875 | 3 | [] | no_license | /*
* Factura.cpp
*
* Created on: 2 oct. 2019
* Author: antonio
*/
#include "Factura.h"
#include <iostream>
#include <memory>
long Factura::NUM_FACT =1;
Factura::Factura(){
this->numeroFact=0;
this->baseImp=0;
this->iva=0;
}
Factura::Factura(Fecha f, Cliente c,float iva){
this->fecha=f;
this->numeroFact=Factura::NUM_FACT;
this->cliente=c;
this->baseImp=baseImp;
this->iva=iva;
Factura::NUM_FACT++;
}
void Factura::imprimir() {
double aux=this->calcular();
std::cout << "FACTURA Nº: "<< this->numeroFact << std::endl;
std::cout << "Fecha: "<< this->fecha << std::endl;
std::cout <<std::endl;
std::cout << "Cliente: "<<std::endl;
std::cout << this->cliente << std::endl;
std::cout <<std::endl;
std::cout << "Servicios: "<<std::endl;
if(this->eventos.size()!=0){
for(unsigned int i=0; i<this->eventos.size(); i++){
const std::type_info & info = typeid(* eventos[i]);
std::cout <<info.name() << " ";
(this->eventos[i])->imprimir();
//std::cout << *(this->eventos[i]) <<std::endl;
//for(auto & i:this->eventos)
//i->imprimir();
}
}else{
std::cout << "No hay servicios"<<std::endl;
}
std::cout << std::endl << "BASE IMPONIBLE : " << this->baseImp << std::endl;
std::cout<< "IVA. : "<< this->iva/100 * this->baseImp <<std::endl;
std::cout<< "TOTAL: "<< aux <<std::endl;
std::cout <<std::endl;
std::cout <<std::endl;
}
double Factura::calcular() {
this->baseImp=0;
if(this->eventos.size()!=0){
for(auto & i:this->eventos)
this->baseImp+=i->calcular();
//for(unsigned int i=0; i<this->eventos.size(); i++)
//this->baseImp+=(this->eventos[i])->calcular();
}
return this->baseImp*(1+(this->iva/100));
}
void Factura::addServicio(std::unique_ptr<Evento> evento) {
this->eventos.push_back(std::move(evento));
}
Factura::~Factura() {
// TODO Auto-generated destructor stub
}
| true |
810aa86b09cbee1254b1478f9fad5c70be24033d | C++ | ryyyyan-taylor/csci2270 | /HW/Assignment6/MovieTree.cpp | UTF-8 | 4,323 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include "MovieTree.hpp"
using namespace std;
MovieTree::MovieTree(){
root = NULL;
}
MovieTree::~MovieTree(){
}
void print(TreeNode *x){
if(x==NULL) {
return;
}
print(x->leftChild);
cout<<"Movies starting with letter:"<< x->titleChar<<endl;
LLMovieNode *n = new LLMovieNode;
n = x->head;
while(n!=NULL){
cout<<">>"<<n->title<<" "<<n->rating<<endl;
n = n->next;
}
print(x->rightChild);
}
void MovieTree::printMovieInventory(){
TreeNode *x = new TreeNode();
x = root;
print(x);
return;
}
LLMovieNode* newLLNode(int ranking, string title, int year, float rating, LLMovieNode *next){
LLMovieNode *temp = new LLMovieNode;
temp->ranking = ranking;
temp->title = title;
temp->year = year;
temp->rating = rating;
temp->next = next;
return temp;
}
TreeNode* newTreeNode(char titleChar){
TreeNode *temp = new TreeNode;
temp->titleChar = titleChar;
temp->parent = temp->leftChild = temp->rightChild = NULL;
temp->head = NULL;
return temp;
}
TreeNode* insertNewBranch(TreeNode* root, char titleChar){
if(root==NULL) return newTreeNode(titleChar);
if(titleChar<root->titleChar) root->leftChild = insertNewBranch(root->leftChild, titleChar);
else if(titleChar>root->titleChar) root->rightChild = insertNewBranch(root->rightChild, titleChar);
return root;
}
TreeNode* insert(int ranking, string title, int year, float rating, TreeNode* x, TreeNode* root){
if(x==NULL){
x = newTreeNode(title[0]);
LLMovieNode *u = new LLMovieNode;
u = newLLNode(ranking, title, year, rating, NULL);
x->head = u;
if(root==NULL) root=x;
else insertNewBranch(root, title[0]);
}
else if(x->titleChar == title[0]){
LLMovieNode *p = new LLMovieNode;
p = x->head;
LLMovieNode *n = new LLMovieNode;
here:
if(title.compare(p->title) < 0){
n = newLLNode(ranking, title, year, rating, p);
x->head = n;
return x;
}
if(p->next == NULL){
p->next = newLLNode(ranking, title, year, rating, NULL);
return x;
}
if(title.compare(p->next->title) < 0){
n = newLLNode(ranking, title, year, rating, p->next);
p->next = n;
return x;
}
else{
p = p->next;
goto here;
}
}
else if(title[0]<x->titleChar){
x->leftChild = insert(ranking, title, year, rating, x->leftChild, root);
}
else if(title[0]>x->titleChar){
x->rightChild = insert(ranking, title, year, rating, x->rightChild, root);
}
return x;
}
void MovieTree::addMovie(int ranking, string title, int year, float rating){
root=insert(ranking, title, year, rating, root, root);
return;
}
TreeNode* minValueNode(TreeNode *node){
TreeNode *current = node;
while(current->leftChild != NULL){
current = current->leftChild;
}
return current;
}
TreeNode* deleteM(string title, TreeNode *x, TreeNode *root){
if(root==NULL){
cout<<"Movie: "<<title<<" not found, cannot delete."<<endl;
return root;
}
if(x->titleChar==title[0]){
cout<<"MADE IT IN"<<endl;
if(x->head->next==NULL){
cout<<"OH SHIT"<<endl;
if(x->leftChild==NULL){
TreeNode* temp = x->rightChild;
delete(x);
return temp;
}
else if(x->rightChild==NULL){
TreeNode* temp = x->leftChild;
delete(x);
return temp;
}
TreeNode* temp = minValueNode(root->rightChild);
root->titleChar = temp->titleChar;
root->head = temp->head;
root->rightChild = deleteM(title, x->rightChild, root);
}
LLMovieNode *entry = new LLMovieNode;
LLMovieNode *prev = new LLMovieNode;
LLMovieNode *nextOne = new LLMovieNode;
entry = x->head;
while(entry!=NULL){
cout<<"WHILE"<<endl;
if(entry->title==title) break;
prev = entry;
entry = nextOne;
nextOne = entry->next;
}
cout<<"HERE"<<endl;
if(entry->title==title){
if(entry==x->head) x->head=entry->next;
else prev->next = nextOne;
delete entry;
cout<<"DID IT"<<endl;
return root;
}
else{
cout<<"Movie: "<<title<<" not found, cannot delete."<<endl;
return root;
}
}
deleteM(title, x->leftChild, root);
deleteM(title, x->rightChild, root);
return root;
}
void MovieTree::deleteMovie(string title){
TreeNode *x = new TreeNode();
x = root;
TreeNode* temp = deleteM(title, root, x);
root=temp;
cout<<"ALMOST THERE"<<endl;
return;
} | true |
f814b33010531aa53316543c0fc39cbe1d0e1e44 | C++ | mehdithreem/sharifcup | /robotic_logic/Tests/MovingObjTest.cpp | UTF-8 | 714 | 2.578125 | 3 | [] | no_license | #include "../Include/MovingObj.h"
#include "../Include/geometry.h"
void testUpdate() {
MovingObj testObj;
geometry::Vector v(10,10);
std::vector<geometry::Vector> vertices;
// vertices.push_back(geometry::Vector(10,10));
// vertices.push_back(geometry::Vector(0,0));
// vertices.push_back(geometry::Vector(10,4));
// vertices.push_back(geometry::Vector(2,7));
vertices.push_back(geometry::Vector(1,0));
vertices.push_back(geometry::Vector(-1,0));
vertices.push_back(geometry::Vector(0,-1));
vertices.push_back(geometry::Vector(0,1));
vertices.push_back(geometry::Vector(0,2));
testObj.update(v, vertices);
testObj.print();
//sort by correct order
}
int main() {
testUpdate();
return 0;
} | true |
116d80d07be42d9dbe8b6bb08bd804329ca06587 | C++ | mandemeskel/CSE180-Robotics-Final | /src/cse180final/make_plan.cpp | UTF-8 | 3,320 | 2.5625 | 3 | [] | no_license | // http://wiki.ros.org/map_server?distro=kinetic
#include <ros/ros.h>
#include <ros/console.h>
#include <nav_msgs/OccupancyGrid.h>
#include <nav_msgs/MapMetaData.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <typeinfo>
#include <fstream>
using namespace std;
#define NODE_NAME "make_plan"
// the occupancy grid of the map
// #define TOPIC_MAP "/move_base/global_costmap/costmap"
#define TOPIC_MAP "map"
// map metadata
#define TOPIC_MAP_META "/map_metadata"
bool DEBUGGING = true;
int * cost_map;
// mapCallback function
void mapCallback( const nav_msgs::OccupancyGrid & msg );
// mapMetaCallback function
void mapMetaCallback( const nav_msgs::MapMetaData & msg );
int main( int argc, char ** argv ) {
// init ros
ros::init( argc, argv, NODE_NAME );
ros::NodeHandle nh;
// create the Subscriber and set the topic to listen to
ros::Subscriber sub_map = nh.subscribe( TOPIC_MAP, 1000, &mapCallback );
// ros::Subscriber sub_map_meta = nh.subscribe( TOPIC_MAP_META, 1000, &mapMetaCallback );
// listen to topic
ros::spin();
return 0;
}
// get map's occupancy grid, -1 - unkown 0 - 100 p of occupancy
// http://docs.ros.org/api/nav_msgs/html/msg/OccupancyGrid.html
void mapCallback( const nav_msgs::OccupancyGrid & msg ) {
// if( DEBUGGING ) {
// ROS_ERROR_STREAM( setprecision(2) << msg );
// }
int width = msg.info.width;
int height = msg.info.height;
int size = width * height;
bool is_first_open = false;
// First map cell: 1582129
// End map cell: 2387754
int first_open = 0;
int last_open = 0;
int unknowns = 0;
if( DEBUGGING ) {
ROS_ERROR_STREAM( setprecision(2) << width );
ROS_ERROR_STREAM( setprecision(2) << height );
// 3936256 size of msg.data
ROS_ERROR_STREAM( setprecision(2) << msg.data.size() );
}
// get first and last cells of map
for( int y = 0; y < size; y++ ) {
if( (int)msg.data[y] != -1 && !is_first_open && first_open == 0 ) {
is_first_open = true;
first_open = y;
} else if ( (int)msg.data[y] != -1 && !is_first_open ) {
is_first_open = true;
} else if( (int)msg.data[y] != -1 && is_first_open ) {
last_open = y;
is_first_open = false;
}
}
if( DEBUGGING )
ROS_ERROR_STREAM( "first " << first_open << " last " << last_open );
// create our copy of the costmap
if( cost_map == NULL )
cost_map = new int[last_open - first_open];
// ofstream file;
// file.open( "map.txt" );
int x = 0;
for( int y = first_open; y <= last_open; y++ ) {
if( (int)msg.data[y] == -1 )
unknowns++;
else if( unknowns > 20 )
unknowns = 0;
if( unknowns < 20 ) {
// ROS_ERROR_STREAM( "Cell: " << y << " " << (int)msg.data[y] );
// file << "Cell: " << y << " " << (int)msg.data[y] << endl;
// add cells to cost_map
cost_map[x] = (int)msg.data[y];
x++;
}
}
// file.close();
}
// get map meta data of the form:
// http://docs.ros.org/api/nav_msgs/html/msg/MapMetaData.html
/**
[ERROR] [1492465743.173240642, 2576.940000000]: map_load_time: 1986.160000000
resolution: 0.05
width: 1984
height: 1984
origin:
position:
x: -50
y: -50
z: 0
orientation:
x: 0
y: 0
z: 0
w: 1
**/
void mapMetaCallback( const nav_msgs::MapMetaData & msg ) {
if( DEBUGGING ) {
ROS_ERROR_STREAM( setprecision(2) << msg );
}
}
| true |
a46f8a1f4bbb5897d76f81b2d1dd60a183bd738f | C++ | Abiduddin/Competitive-Programming-Codes | /All ACM Codes/net/practice_recursion_5.cpp | UTF-8 | 252 | 2.9375 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
int sum(int i,int j, int k)
{
if(j==0)
return 1;
k=k+pow(i,j)+sum(i,j-1,k);
return k;
}
int main()
{
int i,j,k;
scanf("%d %d",&i,&j);
k=sum(i,j-1,0);
printf("%d\n",k);
}
| true |
1a0545c513048ce0cc0192a711fc3e63e2f93ed3 | C++ | tectronics/diesel2d | /Diesel/collision/CharBuffer.h | UTF-8 | 577 | 2.609375 | 3 | [] | no_license | #ifndef CHARBUFFER_H
#define CHARBUFFER_H
#include <stdio.h>
#include "..\dxstdafx.h"
namespace ds {
class CharBuffer {
public:
CharBuffer(uint32 size);
virtual ~CharBuffer();
void reset() {
m_Index = 0;
m_Total = 0;
}
uint32 size() const {
return m_Total;
}
void write(const void* p, uint32 size);
uint32 read(void* p, size_t size,uint32 index);
private:
CharBuffer(const CharBuffer& orig) {}
char* m_Buffer;
uint32 m_Index;
uint32 m_Total;
uint32 m_Size;
};
}
#endif /* CHARBUFFER_H */
| true |
78817bd9e6377566f373dc00e65a41217e52c729 | C++ | YanMario/coding | /code_ping/大数据/bitmap.cpp | UTF-8 | 6,379 | 3.28125 | 3 | [] | no_license | //
// Created by yanpan on 2019/8/11.
//
#if 0
#include <iostream>
using namespace std;
char *g_bitmap = NULL;
int g_size = 0;
int g_base = 0;
//功能:初始化bitmap
//参数: size:bitmap的大小,即bit位的个数
// start:起始值
//返回值:0表示失败,1表示成功
int bitmap_init(int size, int start)
{
g_size = size/8+1; //100个位/8 就是 100/8 + 1 个字节
g_base = start;
g_bitmap = new char[g_size];
if(g_bitmap == NULL)
{
return 0;
}
memset(g_bitmap, 0x0, g_size); //每个位都是0
return 1;
}
//功能:将值index的对应位设为1
//index:要设的值
//返回值:0表示失败,1表示成功
int bitmap_set(int index)
{
int quo = (index-g_base)/8 ; //确定所在的字节 a[i] - 0 / 8 看看在哪个字节 值 <= 7 在第一字节
cout << "quo: " << quo << endl;
int remainder = (index-g_base)%8; //字节内的偏移 //%8 看看在第一个字节的哪一个位
unsigned char x = (0x1<<remainder); //将这个字节的位置为1
if( quo > g_size) //如果字节大于申请的字节 则直接返回0 fail
return 0;
g_bitmap[quo] |= x; //所在字节内的特定位置为1 //将该字节直接或等1 0|0=0 0|1=1 1|0=1 1|1=1
return 1;
}
//功能:取bitmap第i位的值
//i:待取位
//返回值:-1表示失败,否则返回对应位的值
int bitmap_get(int i)
{
int quo = (i)/8 ;
int remainder = (i)%8;
unsigned char x = (0x1<<remainder); //将0x1 在二进制中左移 i%8 位
unsigned char res;
if( quo > g_size)
return -1;
res = g_bitmap[quo] & x; //
return res > 0 ? 1 : 0;
}
//功能:返回index位对应的值
int bitmap_data(int index)
{
return (index + g_base);
}
//释放内存
int bitmap_free()
{
delete [] g_bitmap;
return 0;
}
int main(int argc, char* argv[])
{
int a[] = {5,8,7,6,3,1,10,78,56,34,23,12,43,54,65,76,87,98,89,100};
int i;
bitmap_init(100, 0);
for(i=0; i<20; i++)
{
bitmap_set(a[i]);
}
for(i=0; i<=100; i++)
{
if(bitmap_get(i) > 0 )
cout << bitmap_data(i)<< " ";
}
cout << endl;
bitmap_free();
return 0;
}
#endif
#if 0
#include<iostream>
#include<vector>
using namespace std;
class BitMap {
public:
BitMap(int num):n(num), mask(0x1F), shift(5),pos(1<<mask),a(1+n/32,0){}
void set(int i) {
a[i>>shift] |= (pos>>(i & mask));
}
int get(int i) {
return a[i>>shift] & (pos>>(i & mask));
}
void clr(int i) {
a[i>>shift] &= ~(pos>>(i & mask));
}
private:
int n;
const int mask;
const int shift;
const unsigned int pos;
vector<unsigned int> a;
};
int main() {
BitMap bitmap(100);
bitmap.set(27);
bitmap.set(29);
bitmap.set(131);
int res = bitmap.get(27);
cout<<res<<endl;
return 0;
}
#endif
#if 0
#include <iostream>
#include <vector>
using namespace std;
int MinCoin(vector<int>& vec)
{
int len = vec.size();
if(len <= 0)
return 0;
vector<int> res(len, 100);
for(int i = 1; i < len; i++)
{
if(vec[i] > vec[i-1])
res[i] = res[i-1]+100;
}
for(int i = len-2; i >= 0; i--)
{
if(vec[i] > vec[i+1] && res[i] < res[i+1] + 100)
res[i] = res[i+1] + 100;
}
int sum = 0, i = 0;
while(i < len)
{
sum += res[i];
i++;
}
return sum;
}
int main()
{
int n;
cin >> n;
vector<int> vec;
int val;
for(int i = 0; i < n; i++)
{
cin >> val;
vec.push_back(val);
}
cout << MinCoin(vec) << endl;
return 0;
}
#endif
#if 0
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int len, x, y, j, k, ans;
int vec[256];
cin >> len;
for(int i = 0; i < len; i++)
{
cin >> x >> y;
// vec.push_back(x*60+y);
vec[i] = x*60 + y;
}
cin >> j >> x >> y;
k = x*60+y;
int i = 0;
while(i < len)
{
if(vec[i] + j <= k && vec[i] > ans)
{
ans = vec[i];
}
i++;
}
cout << ans / 60 << ' ' << ans % 60;
return 0;
}
#endif
#if 0
#include <iostream>
#include <vector>
using namespace std;
vector<int> Fun(vector<int>& vec, int len, int k)
{
if(len <= 0) return {};
int x;
vector<vector<int>> res1(len, vector<int>(k));
vector<int> res(len - k + 2);
for(int i = 0; i < k - 1; i++)
{
res[0] = vec[0] ^ 0;
}
for(int i = 1; i < len - k + 2; i++) {
for(int j = 0; j < i; j++) {
res[i] = vec[i] ^ res[j];
vec[i] = res[i];
}
}
for(int j = 0; j < len; j++)
{
if(j == 0)
if(j == 1)
{
for(int i = 0; i < k - 2; i++)
{
res[j] = vec[0] ^ 0;
}
res[j] ^= res[j-1];
}
}
}
int main()
{
int len, k;
cin >> len >> k;
int val;
vector<int> vec;
for(int i = 0; i < k; i++)
{
cin >> val;
vec.push_back(val);
}
}
//
}
#endif
//字节笔试 加密
#if 0
#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<int> func(string &str, int N, int K)
{
int size = str.size();
vector<int> nums;
for (int i = 0; i < size; i++)
{
nums.push_back(str[i] - '0');
}
vector<int> res;
res.push_back(nums[0]);
int tmp_sum = nums[0];
for (int i = 1; i < K; i++)
{
if (tmp_sum ^ 1 == nums[i])
{
res.push_back(1);
}
else
{
res.push_back(0);
}
tmp_sum = tmp_sum ^ res[i];
}
if (K > N)
{
res.erase(res.begin() + N, res.end());
}
for (int i = K; i < N; i++)
{
tmp_sum = tmp_sum ^ res[i - K];
if (tmp_sum ^ 1 == nums[i])
{
res.push_back(1);
}
else
{
res.push_back(0);
}
tmp_sum = tmp_sum ^ res[i];
}
return res;
}
int main()
{
int N, K;
string str;
cin >> N >> K;
cin >> str;
vector<int> res = func(str, N, K);
for (int val : res)
{
cout << val;
}
cout << endl;
return 0;
}
#endif | true |
2dcd6617f88334881217603a3b8832c65ae735b2 | C++ | JohnnyGuye/ArenIA | /Prototypes/Base Ogre/Ogre1Test/Gauge.h | UTF-8 | 3,963 | 3.625 | 4 | [] | no_license | #pragma once
/**
* @file Gauge.h
* @author Samory Ka
* @summary : This class represents a simple gauge.
*/
class Gauge
{
//----------------------------------------------------------------- PUBLIC
public:
//-------------------------------------------- Constructors - destructor
/** @brief Copy constructor
* @param otherGauge Gauge that we want to copy*/
Gauge ( const Gauge & otherGauge )
: max_(otherGauge.max_),
min_(otherGauge.min_),
current_(otherGauge.current_),
modifier_(otherGauge.modifier_)
{
}
/**
* Initiates a not necessarily filled gauge.
* gauge.
* @param borne1 Maximum value of the gauge
* @param borne2 Minimum value of the gauge
* @param current Current value of the gauge
* @param modifier Modifier of the gauge
*/
Gauge ( int borne1 = 100, int borne2 = 0, float current = 100, float modifier = 0.0)
: modifier_(modifier)
{
max_ = (borne1 >= borne2 ? borne1 : borne2);
min_ = (borne1 <= borne2 ? borne1 : borne2);
setCurrent(current);
}
/**
* Destructor
* Destroys an instance of Gauge
*/
virtual ~Gauge ()
{
}
Gauge& operator+=(Gauge const& rhs);
Gauge& operator-=(Gauge const& rhs);
//------------------------------------------------- Public methods
/// Tells if the Gauge is fullfilled
/// @return true if fullfilled
inline bool IsFull() const{ return current_ == (double)max_; }
/// Tells if the Gauge is empty
/// @return true if empty
inline bool IsEmpty() const { return current_ == (double)min_; }
//--------------------------------------GETTERS
/**
* Max getter
* Returns the maximum value reachable by the gauge
* @return max_ of the gauge
*/
inline int getMax() const{ return max_; }
/**
* Min getter
* Returns the minimum value reachable by the gauge
* @return min_ of the gauge
*/
inline int getMin() const { return min_; }
/**
* Current getter
* Returns the current value value the gauge
* @return current_ of the gauge
*/
inline float getCurrent() const { return current_; }
/** @return the the filled portion of the gauge **/
inline float getFilledAbsolute() const { return current_-min_; }
/** @return the notfilled portion of the gauge **/
inline float getNotFilledAbsolute() const { return max_-current_; }
/** @return the filled percent of the gauge **/
inline float getRatio() const { return current_ / (float)(max_-min_); }
/**
* Modifier getter
* Returns the modifier the gauge
* @return modifier_ of the gauge
*/
inline float getModifier() const { return modifier_; }
//--------------------------------------SETTERS
///Current setter
///Sets current_ to value
///@param value The value that you want current to become
inline void setCurrent( float value )
{
if(value > max_) current_ = (float)max_;
else if(value < min_) current_ = (float)min_;
else current_ = value;
}
///Modifier setter
///Sets modifier_ to value
///@param value The value that you want modifier_ to become
inline void setModifier( float value = 0.0)
{
modifier_ = value;
}
///Fills the gauge (sets current_ to max_)
inline void fill()
{
current_ = (float)max_;
}
///Empties the gauge (sets current_ to min_)
inline void empty()
{
current_ = (float)min_;
}
///Updates the current value of the gauge.
inline void update()
{
setCurrent(current_ + modifier_);
}
//----------------------------------------------------------------- PROTECTED
protected:
//------------------------------------------------------- Protected attributes
int max_; ///< Maximum value of the gauge
int min_; ///< Minimum value of the gauge
float current_; ///< Current value of the gauge
float modifier_; ///< Modifier of the current gauge : value of the evolution
///< of current_ at the beginning of a round
};
Gauge operator+(Gauge const& lhs, Gauge const& rhs);
Gauge operator-(Gauge const& lhs, Gauge const& rhs);
| true |
c3113a77889e2f848148f197705b67aaf0bd8c30 | C++ | lafreak/design-patterns | /include/observer.hpp | UTF-8 | 517 | 3.21875 | 3 | [] | no_license | #pragma once
#include <functional>
#include <list>
template <typename T>
class observable
{
std::list<std::function<void(const T&)>> m_observers;
public:
void attach(const std::function<void(const T&)>&);
void notify();
};
template<typename T>
void observable<T>::attach(const std::function<void(const T&)>& observer)
{
m_observers.push_back(observer);
}
template<typename T>
void observable<T>::notify()
{
for (auto& observer : m_observers)
observer((const T&)*this);
}
| true |
5ca87d9b0a37cd2e3f5b348506666898b2112a7e | C++ | projectsf/snippets | /cpp/examples/gridNetExamples/smartnos-developer-platform/smartnosapplicationframework/include/ApplicationEnforcementScheduler.hpp | UTF-8 | 647 | 2.515625 | 3 | [] | no_license | #ifndef APPLICATION_ENFORCEMENT_SCHEDULER_HPP_
#define APPLICATION_ENFORCEMENT_SCHEDULER_HPP_
#include <string>
#include <boost/property_tree/ptree.hpp>
class SmartNosApplication;
class ApplicationEnforcementScheduler
{
public :
enum ScheduleType
{
OneTime,
Periodic,
Unknown
};
ApplicationEnforcementScheduler(SmartNosApplication* smartNosApplication, const std::string& schedule);
void run();
void enforce();
private :
SmartNosApplication* smartNosApplication;
ScheduleType scheduleType;
unsigned int period;
bool done;
boost::property_tree::ptree schedule;
};
#endif //APPLICATION_ENFORCEMENT_SCHEDULER_HPP_
| true |
ff6fab87cda6e41df8666c355a7796186ba97aaa | C++ | jpoirier/x-gauges | /Nesis/Instruments/src/Scale.h | UTF-8 | 3,905 | 2.59375 | 3 | [] | no_license | #ifndef INSTRUMENT_SCALE_H
#define INSTRUMENT_SCALE_H
/***************************************************************************
* *
* Copyright (C) 2009 by Kanardia d.o.o. [see www.kanardia.eu] *
* Writen by: *
* Ales Krajnc [ales.krajnc@kanardia.eu] *
* *
* Status: Open Source *
* *
* License: GPL - GNU General Public License *
* See 'COPYING.html' for more details about the license. *
* *
***************************************************************************/
#include <QDomElement>
#include <cmath>
#include "Parameter.h"
namespace instrument {
/** \brief The class is used to handle the basic scale parameters.
The scale is constructed from XML file.
*/
class Scale
{
protected:
enum LimitType {
ltNone,
ltTick,
ltArc
};
public:
//! Constructor from QDomElement XML.
Scale(const QDomElement& el);
//! Constructor which only takes start and end scale value.
Scale(float fS, float fE);
//! Destructor.
virtual ~Scale();
//! Get Parameter object.
const Parameter* GetParameter() const
{ return m_pPar; }
//! Set scale limits
void SetScaleLimits(float fS, float fE);
//! Set scale limits
void SetScaleLimits(const QPair<float,float> rSE)
{ SetScaleLimits(rSE.first, rSE.second); }
//! Get the scale start.
float GetStart() const
{ return m_fS; }
//! Get the scale end.
float GetEnd() const
{ return m_fE; }
//! Return the major tick scale step.
float GetMajorTickStep() const
{ return m_fMajorTickStep; }
//! Return number of minor intervals between the major step.
int GetMinorIntervalCount() const
{ return m_iMinorIntervalCount; }
//! Return the label scale step.
float GetLabelStep() const
{ return m_fLabelStep; }
//! Return true if there is low limit (red) active.
bool IsLowLimit() const
{ return m_bLowLimit; }
//! Return true if there is high limit (red) active.
bool IsHighLimit() const
{ return m_eHighLimit != ltNone; }
//! Convert a system value into scale value.
virtual float ConvertToScale(float fS) const;
//! Convert pair of system values into scale value.
QPair<float,float> ConvertToScale(const QPair<float,float>& P);
//! Set the scale bound parameter.
void EnableBoundScale(bool bBound)
{ m_bBoundScale = bBound; }
//! Update values from Parameter object and dump them.
void UpdateValue();
//! Get dumping value.
float GetDumpingCoefficient() const
{ return m_fDumping; }
//! Get dumped system value.
float GetDumpedSystemValue(int i=0) const
{ return m_vDump[i]; }
protected:
//! The scale parameter.
const Parameter* m_pPar;
//! Draw yellow arc?
bool m_bYellow;
//! Draw green arc?
bool m_bGreen;
//! Draw high limit?
LimitType m_eHighLimit;
//! Draw low limit?
bool m_bLowLimit;
//! Number of decimals shown on scale.
int m_iDecimals;
//! Value at the start of the scale.
float m_fS;
//! Value at the end of the scale.
float m_fE;
//! Major tick step in the scale units.
float m_fMajorTickStep;
//! Number of minor intervals inside a major interval.
int m_iMinorIntervalCount;
//! Label step in the scale units.
float m_fLabelStep;
//! Multiplier used to get scale value from the real value.
float m_fMultiplier;
//! Should we bound the scale?
bool m_bBoundScale;
//! The scale dumping parameter.
float m_fDumping;
//! Dump values.
QVector<float> m_vDump;
};
// --------------------------------------------------------------------------
} // namespace
#endif
| true |
1324d910ca4d15f916d4764a4928c96fd7100810 | C++ | lagoon9024/problem-solving | /BOJ/boj16234.cpp | UTF-8 | 1,559 | 2.609375 | 3 | [] | no_license | //boj16234
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
#include <cmath>
int N, L, R;
int map[50][50];
int dr[4] = { -1, 0, 1, 0 };
int dc[4] = { 0, -1, 0, 1 };
int flag = 0;
int check[50][50];
typedef struct {
int r, c;
}pos;
using namespace std;
void movemove(int r, int c) {
queue<pos> q;
vector<pos> v;
check[r][c] = 1;
v.push_back({ r,c });
q.push({ r,c });
int total = 0;
total += map[r][c];
while (!q.empty()) {
pos tmp = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nr = tmp.r + dr[i];
int nc = tmp.c + dc[i];
if (nr < 0 || nc < 0 || nr >= N || nc >= N || check[nr][nc] == 1) continue;
if (abs(map[nr][nc] - map[tmp.r][tmp.c]) >= L && abs(map[nr][nc] - map[tmp.r][tmp.c]) <= R) {
check[nr][nc] = 1;
v.push_back({ nr,nc });
total += map[nr][nc];
q.push({ nr,nc });
}
}
}
int uvalue = total / v.size();
for (int i = 0; i < v.size(); i++) {
map[v[i].r][v[i].c] = uvalue;
}
}
int main(void) {
cin >> N >> L >> R;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
cin >> map[i][j];
int ans = 0;
for (int cnt = 0; cnt <= 2000; cnt++) {
memset(check, 0, sizeof(check));
int tcnt = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (check[i][j] == 0) {
tcnt++;
movemove(i, j);
}
}
if (tcnt == N * N) flag = 1;
}
if (flag == 1) { ans = cnt; break; }
}
/*for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << map[i][j] << " ";
}
cout << '\n';
}*/
cout << ans;
} | true |
14465b0c401a51d946b25a47bd5101b297e0c415 | C++ | lmarent/EconomicSimulator | /network_agents_ver2/foundation/src/Provider.cpp | UTF-8 | 9,837 | 2.734375 | 3 | [
"MIT"
] | permissive |
#include <Poco/Util/ServerApplication.h>
#include "FoundationException.h"
#include "Provider.h"
#include <limits>
namespace ChoiceNet
{
namespace Eco
{
Provider::Provider(std::string id, ProviderCapacityType capacity_type):
_id(id), _type(capacity_type)
{
}
Provider::~Provider()
{
std::map<std::string, ResourceAvailability *>::iterator it;
it = _resources.begin();
while (it != _resources.end())
{
delete it->second;
_resources.erase(it);
++it;
}
}
void Provider::addResourceAvailability(std::string resourceId)
{
std::map<std::string, ResourceAvailability *>::iterator it;
it = _resources.find(resourceId);
if (it == _resources.end())
{
ResourceAvailability * resourcePtr = new ResourceAvailability(resourceId);
_resources.insert(std::pair<std::string, ResourceAvailability *>(resourceId,resourcePtr));
}
else
{
throw FoundationException("Resource already registered in the provider", 313);
}
}
void Provider::setInitialAvailability(Resource *resource, double quantity)
{
#ifndef TEST_ENABLED
Poco::Util::Application& app = Poco::Util::Application::instance();
app.logger().debug("Entering provider setInitialAvailability");
#endif
std::map<std::string, ResourceAvailability *>::iterator it;
it = _resources.find(resource->getId());
if (it != _resources.end())
{
(*(it->second)).setInitialAvailability(quantity);
}
else
{
addResourceAvailability(resource->getId());
it = _resources.find(resource->getId());
(*(it->second)).setResource(resource);
(*(it->second)).setInitialAvailability(quantity);
}
#ifndef TEST_ENABLED
app.logger().debug("Ending provider setInitialAvailability");
#endif
}
void Provider::deductResourceAvailability(unsigned period,
std::string resourceId,
DecisionVariable *variable,
double level,
double quantity )
{
Poco::Util::Application& app = Poco::Util::Application::instance();
app.logger().information(Poco::format("starting deduct resource availability - level:%f -quantity:%f", level, quantity) );
double endAvailability = 0;
ResourceMap::iterator it;
it = _resources.find(resourceId);
// when the resourceId is not found the system, it assumes unlimited capacity
if (it != _resources.end()){
endAvailability = (*(it->second)).deductAvailability(period, variable, level,quantity);
app.logger().information(Poco::format("provider:%s end availability %f", getId(), endAvailability));
}
}
void Provider::deductAvailability(unsigned period,
Service * service,
Purchase * purchase,
Bid * bid)
{
std::map<std::string, DecisionVariable *>::iterator it;
for (it=(service->_decision_variables.begin()); it!=(service->_decision_variables.end()); ++it)
{
DecisionVariable *variable = it->second;
if (variable->getModeling() == MODEL_QUALITY)
{
deductResourceAvailability(period,
variable->getResource(),
variable,
bid->getDecisionVariable(variable->getId()),
purchase->getQuantity() );
}
}
}
double Provider::getResourceAvailability(unsigned period,
std::string resourceId)
{
ResourceMap::iterator it;
it = _resources.find(resourceId);
// When the resourceId is not found the system, it assumes not capacity
if (it != _resources.end()){
return (it->second)->getAvailability(period);
}
else{
return false;
}
}
double Provider::getUnitaryRequirement(unsigned period,
std::string resourceId,
DecisionVariable *variable,
double level)
{
ResourceMap::iterator it;
it = _resources.find(resourceId);
// When the resourceId is not found the system, it assumes not capacity
if (it != _resources.end()){
return (it->second)->getUnitaryRequirement(period, variable, level );
}
else{
return -1; // An the resource was not found.
}
}
bool Provider::checkResourceAvailability(unsigned period,
std::string resourceId,
DecisionVariable *variable,
double level,
double quantity )
{
ResourceMap::iterator it;
it = _resources.find(resourceId);
// When the resourceId is not found the system, it assumes not capacity
if (it != _resources.end()){
return (it->second)->checkAvailability(period, variable, level,quantity);
}
else{
return false;
}
}
bool Provider::isBulkAvailable(unsigned period, Service * service, Purchase * purchase, Bid * bid)
{
#ifndef TEST_ENABLED
Poco::Util::Application& app = Poco::Util::Application::instance();
app.logger().debug("Entering provider isAvailable");
#endif
bool available = true;
if (service->hasQualityVariables() == true)
{
std::map<std::string, DecisionVariable *>::iterator it;
for (it=(service->_decision_variables.begin()); it!=(service->_decision_variables.end()); ++it)
{
DecisionVariable *variable = it->second;
if (variable->getModeling() == MODEL_QUALITY)
{
#ifndef TEST_ENABLED
app.logger().debug("Checking resource availability for resource" + variable->getResource());
#endif
available = available && checkResourceAvailability(period,
variable->getResource(),
variable,
bid->getDecisionVariable(variable->getId()),
purchase->getQuantity() );
}
}
}
else {
std::map<std::string, DecisionVariable *>::iterator it;
for (it=(service->_decision_variables.begin()); it!=(service->_decision_variables.end()); ++it)
{
DecisionVariable *variable = it->second;
if (variable->getModeling() == MODEL_PRICE )
{
#ifndef TEST_ENABLED
app.logger().debug("Checking resource availability for resource" + variable->getResource());
#endif
available = available && checkResourceAvailability(period,
variable->getResource(),
variable,
bid->getDecisionVariable(variable->getId()),
purchase->getQuantity() );
}
}
}
#ifndef TEST_ENABLED
app.logger().debug(Poco::format("Ending provider isAvailable %b", available ));
#endif
return available;
}
double Provider::getBulkAvailability(unsigned period, Service * service, Bid * bid)
{
#ifndef TEST_ENABLED
Poco::Util::Application& app = Poco::Util::Application::instance();
app.logger().debug("Entering provider getBulkAvailability");
#endif
double availabilityResource = 0;
bool enter = false;
double availabilityTmp;
double availability;
double requirement;
if (service->hasQualityVariables() == true)
{
std::map<std::string, DecisionVariable *>::iterator it;
for (it=(service->_decision_variables.begin()); it!=(service->_decision_variables.end()); ++it)
{
DecisionVariable *variable = it->second;
if (variable->getModeling() == MODEL_QUALITY)
{
app.logger().debug("Getting resource availability - Resource:" + variable->getResource());
requirement = getUnitaryRequirement(period,variable->getResource(), variable, bid->getDecisionVariable(variable->getId()) );
if (requirement < 0){
app.logger().error("The resource was not found, which means it has no capacity");
return 0; // The resource was not found, which means it has no capacity.
}
else{
if (enter == false)
{
availabilityResource = getResourceAvailability(period,variable->getResource() );
if (requirement > 0) {
availability = availabilityResource / requirement;
enter = true;
}
else{
// It puts the maximum availability
availability = std::numeric_limits<double>::max();
enter = true;
}
}
else
{
// The assumption here is that every resource can be compared in terms of capacity.
availabilityResource = getResourceAvailability(period,variable->getResource() );
if (requirement > 0) {
availabilityTmp = availabilityResource / requirement;
if (availabilityTmp <availability){
availability = availabilityTmp;
}
}
else {
availabilityTmp = std::numeric_limits<double>::max();
if (availabilityTmp <availability){
availability = availabilityTmp;
}
}
}
}
app.logger().information(Poco::format("resource: %s - Requirement:%f - Availability:%f", variable->getResource(), requirement, availability) );
}
}
}
else {
std::map<std::string, DecisionVariable *>::iterator it;
for (it=(service->_decision_variables.begin()); it!=(service->_decision_variables.end()); ++it)
{
DecisionVariable *variable = it->second;
if (variable->getModeling() == MODEL_PRICE )
{
#ifndef TEST_ENABLED
app.logger().debug("Getting resource availability - Resource:" + variable->getResource());
#endif
requirement = getUnitaryRequirement(period,variable->getResource(), variable, bid->getDecisionVariable(variable->getId()) );
if (enter == false)
{
availabilityResource = getResourceAvailability(period,variable->getResource() );
availability = availabilityResource / requirement;
enter = true;
}
else
{
// The assumption here is that every resource can be compared in terms of capacity.
availabilityResource = getResourceAvailability(period,variable->getResource() );
availabilityTmp = availabilityResource / requirement;
if (availabilityTmp < availability){
availability = availabilityTmp;
}
}
app.logger().information(Poco::format("resource: %s - Requirement:%f - Availability:%f", variable->getResource(), requirement, availability) );
}
}
}
#ifndef TEST_ENABLED
app.logger().debug(Poco::format("Ending provider getBulkAvailability %d", availability ));
#endif
return availability;
}
ProviderCapacityType Provider::getCapacityType(void)
{
return _type;
}
std::string Provider::getId()
{
return _id;
}
} /// End Eco namespace
} /// End ChoiceNet namespace
| true |
711d4afd311592febef48e68e039c57f3f6f1285 | C++ | scruffymcnunchuck/Sort_Project | /bubble-sort.cpp | UTF-8 | 746 | 3.25 | 3 | [] | no_license | //============================================================================
// Name : bubble-sort.cpp
// Author :
// Date :
// Copyright :
// Description : Implementation of bubble sort in C++
//============================================================================
#include "sort.h"
void
BubbleSort::sort(int A[], int size) // main entry point
{
num_cmps = 0;
for(int k=1; k<size; k++){
for(int i =0; i<size-k; i++){
if(A[i]>A[i+1]){
num_cmps++;
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}else{
num_cmps++;
}
}
}
/* Complete this function with the implementation of bubble sort algorithm
Record number of comparisons in variable num_cmps of class Sort
*/
}
| true |
657c32aefded9c534e2b69d70d2fc0aa72a2d119 | C++ | ferluque/TDAImagen | /src/1umbralizar.cpp | UTF-8 | 3,472 | 3.609375 | 4 | [] | no_license | /**
* @file 1umbralizar.cpp
* @brief Fichero con la función umbralizar y su prueba
* @author Fernando Luque (fl1562001@correo.ugr.es)
* @date Octubre 2020
*
* Para llamar al ejecutable correspondiente <ejecutable> <imagen_origen> <umbral_min> <umbral_max> <imagen_destino>
*/
#include "Imagen.h"
#include "imagenES.h"
#include <iostream>
using namespace std;
/**
* @brief Umbralizar
* @param original La imagen a umbralizar
* @param T_1 El umbral inferior (cualquier pixel por debajo se establece a 255)
* @param T_2 El umbral superior (cualquier pixel por encima se establece a 255)
* @return La imagen umbralizada
* @pre T_1 < T_2
*
* Función que establece los valores de los píxeles más extremos tanto inferior(por debajo del umbral
* inferior), como superiormente (por encima del umbral superior) al nivel máximo de luminosidad (blanco)
*/
Imagen umbralizar(const Imagen &original, const byte T_1, const byte T_2);
/**
* @brief main de umbralización
* @param nargs El número de argumentos
* @param args Un vector de cadenas de caracteres (argumentos)
*
* En este main usamos la función LeerImagenPGM del módulo imagenES, y leemos la imagen indicada, usamos el constructor de la clase Imagen con el array generado
* y usamos la función umbralizar sobre ese objeto de la clase Imagen. Posteriormente, usamos la función de la clase Imagen convertir_a_Array(byte*)
* para transformarla en un tipo de dato válido para la función de imagenES EscribirImagenPGM(...), liberamos la memoria del array y el destructor de
* la clase Imagen se encarga de liberar la memoria ocupadas por las imágenes creadas.
*/
int main(int nargs, char *args[])
{
// Comprobar validez de la llamada (Gestión de errores tomada del fichero negativo.cpp)
if (nargs != 5)
{
cerr << "Error: Numero incorrecto de parametros.\n";
cerr << "Uso: bin/1umbralizar <FichImagenOriginal> <T_1> <T_2> <FichImagenDestino>\n";
exit(1);
}
char* origen = args[1];
char* destino = args[4];
cout << endl;
cout << "Fichero origen: " << args[1] << endl;
cout << "Fichero resultado: " << args[4] << endl;
// Leer la imagen del fichero de entrada
int filas = 0, columnas = 0;
byte *array = LeerImagenPGM(origen, filas, columnas);
if (!array)
{
cerr << "Error: No pudo leerse la imagen." << endl;
cerr << "Terminando la ejecucion del programa." << endl;
exit(1);
}
Imagen original(filas, columnas, array);
delete[] array;
Imagen umbralizada = umbralizar(original, atoi(args[2]), atoi(args[3]));
array = new byte[umbralizada.num_columnas() * umbralizada.num_filas()];
umbralizada.convertir_a_Array(array);
if (EscribirImagenPGM(destino, array, umbralizada.num_filas(), umbralizada.num_columnas()))
cout << "La imagen se guardo en " << destino << endl;
else
{
cerr << "Error: No pudo guardarse la imagen." << endl;
cerr << "Terminando la ejecucion del programa." << endl;
exit(2);
}
delete[] array;
return 0;
}
Imagen umbralizar(const Imagen &original, const byte T_1, const byte T_2)
{
Imagen umbralizada(original);
for (int i = 0; i < original.num_filas(); i++)
for (int j = 0; j < original.num_columnas(); j++)
if (original.valor_pixel(i, j) <= T_1 || original.valor_pixel(i, j) >= T_2)
umbralizada.asigna_pixel(i, j, 255);
return umbralizada;
}
| true |
5b8a385c8b7cc02ab81be5a90413e4272238c9ef | C++ | josealeixopc/AEDA-Part2 | /Código/Servico.cpp | WINDOWS-1252 | 3,569 | 3.0625 | 3 | [] | no_license | /*
* Servico.cpp
*
* Created on: 27/10/2015
* Author: ASUS
*/
#include "Camiao.h"
#include "Cliente.h"
#include "Empresa.h"
#include "Frota.h"
#include "Servico.h"
#include "sequentialSearch.h"
/**
* \brief Cria um Servio usando os parmetros para definir as sua caracteristicas
* \param id ID do Servio
* \param preco Preo do Servio em custo por quilograma de carga (/kg)
* \param distancia Distncia que o camio vai percorrer durante o servio (km)
* \return Esta funo no possui retorno
*/
Servico::Servico(int id, float preco, float distancia)
{
this->id = id;
this->preco = preco;
this->distancia = distancia;
status = false;
}
/**
* \brief Atribui um status a um Servio, ativo(true) ou inativo(false)
* \param status Status a atribuir
* \return Esta funo no possui retorno
*/
void Servico::setStatus(bool status)
{
this->status = status;
}
/**
* \brief Obtm o ID de um Servio
* \return Retorna o ID de um Servio
*/
int Servico::getId() const
{
return id;
}
/**
* \brief Verifica se um Servio est ou no ativo
* \return Retorna o valor lgico do status
*/
bool Servico::getStatus() const
{
return status;
}
/**
* \brief Averigua o valor lgico do status
* \return Retorna o status de um Servio, ativo ou inativo
*/
string Servico::printStatus()
{
if (this->status)
return "Ativo";
else
return "Inativo";
}
/**
* \brief Obtm o Preo de um Servio
* \return Retorna o Preo de um Servio
*/
float Servico::getPreco() const
{
return preco;
}
/**
* \brief Altera, se necessrio, o preo de um Servio
* \param preco Novo valor (em /kg) do servio
* \return Esta funo no possui retorno
*/
void Servico::updatePreco(float preco)
{
this->preco = preco;
}
/**
* \brief Obtm o vetor que guarda todos os Clientes
* \return Retorna o vetor
*/
vector<Cliente*> Servico::getClientes() const
{
return clientes;
}
/**
* \brief Obtm a distncia necessria para executar o servio
* \return Retorna o valor em km
*/
float Servico::getDistancia() const
{
return distancia;
}
/**
* \brief Adiciona um Cliente ao vetor
* \param j1 Cliente a adicionar
* \return Esta funo no possui retorno
*/
void Servico::adicionaCliente(Cliente *j1)
{
clientes.push_back(j1);
this->setStatus(true);
}
/**
* \brief Retira um Cliente do vetor, caso este l esteja, caso contrrio lana a excesso ClienteInexistente
* \param j1 Cliente a retirar
* \return Esta funo no possui retorno
*/
void Servico::retiraCliente(Cliente *j1)
{
int index = sequentialSearch(clientes, j1);
if (index == -1)
throw ClienteInexistente(j1->getNif());
else
clientes.erase(clientes.begin() + index);
if (this->clientes.size() == 0)
this->setStatus(false);
}
/**
* \brief Imprime todas as informaes dos clientes do vetor
* \return Esta funo no possui retorno
*/
void Servico::readClientes() const
{
cout << setw(20) << "Nome" << setw(15) << "NIF" << endl;
for (unsigned int i = 0; i < clientes.size(); i++)
{
cout << setw(20) << clientes[i]->getNome() << setw(15) << clientes[i]->getNif() << endl;
}
}
/**
* \brief Operador utilizado para verificar se dois servios so iguais
* \param s1 Servio a comparar
* \return Retorna true se os Servios forem iguais e false se no forem
*/
bool Servico::operator==(const Servico& s1)
{
if (s1.id == this->id)
return true;
else
return false;
}
| true |
845cf7fba19ddf571c5d7f1f1721a1e0e9107488 | C++ | mbaluda/GLCAlib | /GLblur.cpp | UTF-8 | 2,860 | 3 | 3 | [] | no_license | ///\file GLblur.cpp
///\brief GPGPU-based blur convolution filter.
///
///Realizes a convolution using the GLCAlib library.\n
// includes
#include <iostream>
#include "GLCAlib.h"
///\brief Implements in GLSL the convolution for blurring images
///
///Convolution Matrix 3x3\n
///0.1 0.1 0.1\n
///0.1 0.2 0.1\n
///0.1 0.1 0.1\n
char* shader="uniform sampler2DRect texture_A;" \
"void main(void) {" \
" gl_FragColor = texture2DRect(texture_A, gl_TexCoord[0].st)*0.2+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(-1.0, -1.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(0.0, -1.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(1.0, -1.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(-1.0, 0.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(1.0, 0.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(-1.0, 1.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(0.0, 1.0))*0.1+" \
" texture2DRect(texture_A, gl_TexCoord[0].st + vec2(1.0, 1.0))*0.1;" \
"}";
///The input image filename
char* infilename;
///The output image filename
char* outfilename;
///Width of the image
int x;
///Height of the image
int y;
///Size of the image (4*x*y being RGBA)
int N;
///\brief Just reads input and calls GLCAlib functions
///
///Images are read in RGBA format to avoid extra depandencies,
///Cimg or Imagemagick could be used to load images in other formats
///@param[in] argc: nuber of parameters on th ecommand line:\n
///@param[in] argv: holds parameters passed on the commend line:\n
///Param 1: Filename of the input RGBA image\n
///Param 2: Filename of the output RGBA image\n
///Param 3: problem size x\n
///Param 4: problem size y\n
int main(int argc, char** argv) {
//cerr<<"main"<<endl;
// parse command line
if (argc < 5) {
std::cout<<"Command line parameters:\n";
std::cout<<"Param 1: Filename of the input RGBA image\n";
std::cout<<"Param 2: Filename of the input RGBA image\n";
std::cout<<"Param 3: problem size x\n";
std::cout<<"Param 4: problem size y\n";
exit(0);
} else {
infilename = argv[1];
outfilename = argv[2];
x = atoi(argv[3]);
y = atoi(argv[4]);
}
//cerr<<"calc texture dimensions"<<endl;
//textureParameters.texFormat == GL_RGBA
N=4*x*y;
float* image = new float[N];
GLCAlib::loadImage(image, infilename, N);
GLCAlib::init(argc, argv, image, x, y, shader, false, 1);
//std::cout<<"save"<<std::endl;
GLCAlib::saveImage(image, outfilename, N);
return 0;
}
| true |
ac1f85b310352efa91823214c9f55ba20c10c8e4 | C++ | thecodingwizard/competitive-programming | /POI/POI16-Not_Nim.cpp | UTF-8 | 10,819 | 3.484375 | 3 | [] | no_license | /*
* Same solution as editorial
*
* Player A wants to end game in fewest moves, player B wants to stall
* - With pen and paper we get that if player A repeatedly removes stones from one pair until it's gone,
* a pair of n stones will take him floor(log2(n))*2 + 4 steps
* - However, after one stack of stones is gone, player B will have to "upset" the balance of one stack of stones.
* This can reduce the number of moves it takes to remove that stack of stones. For example, if our
* stones was (1 1) (1 1) it would take only 5 moves, not 7, because after the first pair of stones is gone
* Player B will be forced to change the second set from (1 1) to (2 0) reducing the answer by 2
* - Our strategy is: Create a "base" answer by summing floor(log2(A_i))*2 + 4 for all A_i. Subtract one from
* this base answer since player A gets the last move. Then we need to figure out how many moves we can subtract from
* this base answer.
* - If there's a pair of 1 stone (1 1) and player B is forced to rebalance it, then we can subtract two from our answer.
* - Note that prior to the first rebalancing, player A can remove stones s.t. each stack's new value is just
* the leading ones. ie if the original number was 111001101 in base 2, player A can remove stones from that stack
* until the number is just 111 in base 2. Therefore the only important part about each stack's number is the
* number of leading ones in that number.
* - Now consider a rebalancing. Let's take the number 7 as an example. If player B rebalances (7 7), then it will
* eventually become (3 3): (7 7) -> (8 6) -> (0 6) -> (3 3) In other words, rebalancing a stack of stones with n
* leading ones will result in a new stack with (n-1) leading stacks. However, if there is only one leading one (ie
* if player B is rebalancing a stack with only one stone) then we can subtract two from the answer.
* - Player B must rebalance once after each stack of stones is removed completely.
* - Note that Player B will always rebalance the stack of stones with the most number of leading ones since that
* prolongs the time until it reaches (1 1)
* - Note that Player A will always choose to remove the stack of stone with the most number of leading ones since
* that stack takes lots of rebalancings before it reaches (1 1)
*
* Therefore, our solution is:
* 1. Calculate the base answer
* 2. Create a priority queue. Each stack is represented as the number of leading ones of the number of stones in that stack.
* Pop the biggest number from the priority queue since player A must remove one stack of stones before player B does
* the first rebalancing.
* 3. While the priority queue is not empty, take the pair of stones with the most number of leading ones and process it:
* 3a. If that pair of stones has one leading ones, then the rebalancing will lead 2 fewer moves. answer -= 2.
* 3b. If the pair of stones has more than one leading ones, then the rebalancing will result in a new stack with
* one fewer leading one. Insert a new element into the priority queue with value n-1. Then, pop the biggest
* element from the priority queue since player A will have to remove another set of stones before the next rebalancing.
*
* Also see code comments
*/
//#pragma GCC optimize ("O3")
//#pragma GCC target ("sse4")
#include <bits/stdc++.h>
using namespace std;
template<class T> using min_heap = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i, a, b) for (int i=a; i<(b); i++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define F0R1(i, a) for (int i=1; i<=(a); i++)
#define FORd(i, a, b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--)
#define trav(a, x) for (auto& a : x)
#define MIN(a, b) a = min(a, b)
#define MAX(a, b) a = max(a, b)
#define INF 1000000010
#define LL_INF 4500000000000000000LL
#define LSOne(S) (S & (-S))
#define EPS 1e-9
#define pA first
#define pB second
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
#define PI acos(-1.0)
// #define MOD (int)(2e+9+11)
#define MOD (int)(1e+9+7)
#define SET(vec, val, size) for (int i = 0; i < size; i++) vec[i] = val;
#define SET2D(arr, val, dim1, dim2) F0R(i, dim1) F0R(j, dim2) arr[i][j] = val;
#define SET3D(arr, val, dim1, dim2, dim3) F0R(i, dim1) F0R(j, dim2) F0R(k, dim3) arr[i][j][k] = val;
#define SET4D(arr, val, dim1, dim2, dim3, dim4) F0R(i, dim1) F0R(j, dim2) F0R(k, dim3) F0R(l, dim4) arr[i][j][k][l] = val;
#define lb lower_bound
#define ub upper_bound
#define sz(x) (int)x.size()
#define beg(x) x.begin()
#define en(x) x.end()
#define all(x) beg(x), en(x)
#define resz resize
#define SORT(vec) sort(all(vec))
#define RSORT(vec) sort(vec.rbegin(),vec.rend())
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<ll> vl;
// @formatter:off
// Source: Benq (https://github.com/bqi343/USACO) [Modified]
namespace input {
template<class T> void re(complex<T>& x);
template<class T1, class T2> void re(pair<T1,T2>& p);
template<class T> void re(vector<T>& a);
template<class T, size_t SZ> void re(array<T,SZ>& a);
template<class T> void reA(T A[], int sz);
template<class T> void re(T& x) { cin >> x; }
void re(double& x) { string t; re(t); x = stod(t); }
void re(ld& x) { string t; re(t); x = stold(t); }
template<class Arg, class... Args> void re(Arg& first, Args&... rest) {
re(first); re(rest...);
}
template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.pA,p.pB); }
template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
template<class T> void reA(T A[], int sz) { F0R(i, sz) re(A[i]); }
void setupIO(const string &PROB = "") {
ios::sync_with_stdio(false);
cin.tie(nullptr);
if (PROB.length() != 0) {
ifstream infile(PROB + ".in");
if (infile.good()) {
freopen((PROB + ".in").c_str(), "r", stdin);
freopen((PROB + ".out").c_str(), "w", stdout);
}
}
}
}
using namespace input;
namespace output {
template<class T1, class T2> void prD(const pair<T1,T2>& x);
template<class T, size_t SZ> void prD(const array<T,SZ>& x);
template<class T> void prD(const vector<T>& x);
template<class T> void prD(const set<T>& x);
template<class T1, class T2> void prD(const map<T1,T2>& x);
template<class T1, class T2> void pr(const pair<T1,T2>& x);
template<class T, size_t SZ> void pr(const array<T,SZ>& x);
template<class T> void pr(const vector<T>& x);
template<class T> void pr(const set<T>& x);
template<class T1, class T2> void pr(const map<T1,T2>& x);
template<class T> void prD(const T& x) { cout << x; cout.flush(); }
template<class Arg, class... Args> void prD(const Arg& first, const Args&... rest) {
prD(first); prD(rest...);
}
template<class T1, class T2> void prD(const pair<T1,T2>& x) {
prD("{",x.pA,", ",x.pB,"}");
}
template<class T> void prDContain(const T& x) {
prD("{");
bool fst = 1; for (const auto& a: x) prD(!fst?", ":"",a), fst = 0; // const needed for vector<bool>
prD("}");
}
template<class T, size_t SZ> void prD(const array<T,SZ>& x) { prDContain(x); }
template<class T> void prD(const vector<T>& x) { prDContain(x); }
template<class T> void prD(const set<T>& x) { prDContain(x); }
template<class T1, class T2> void prD(const map<T1,T2>& x) { prDContain(x); }
void psD() { prD("\n"); }
template<class Arg> void psD(const Arg& first) {
prD(first); psD(); // no space at end of line
}
template<class Arg, class... Args> void psD(const Arg& first, const Args&... rest) {
prD(first," "); psD(rest...); // print w/ spaces
}
template<class T> void pr(const T& x) { cout << x; }
template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) {
pr(first); pr(rest...);
}
template<class T1, class T2> void pr(const pair<T1,T2>& x) {
pr(x.pA, " ", x.pB);
}
template<class T> void prContain(const T& x) {
bool fst = 1; for (const auto& a: x) pr(!fst?" ":"",a), fst = 0; // const needed for vector<bool>
}
template<class T, size_t SZ> void pr(const array<T,SZ>& x) { prContain(x); }
template<class T> void pr(const vector<T>& x) { prContain(x); }
template<class T> void pr(const set<T>& x) { prContain(x); }
template<class T1, class T2> void pr(const map<T1,T2>& x) { prContain(x); }
void ps() { pr("\n"); }
template<class Arg> void ps(const Arg& first) {
pr(first); ps(); // no space at end of line
}
template<class Arg, class... Args> void ps(const Arg& first, const Args&... rest) {
pr(first," "); ps(rest...); // print w/ spaces
}
}
using namespace output;
// @formatter:on
/* ============================ */
int main() {
setupIO();
int n; re(n);
ll A[n]; reA(A, n);
/* Generate the base answer */
ll ans = -1; // Since player A gets the last move we subtract one from the base answer
F0R(i, n) {
ans += floor(log2(A[i])) * 2 + 4;
}
priority_queue<int> pq;
// For each input number, insert the number of leading ones into the priority queue
F0R(i, n) {
int numLeading = 0;
F0Rd(j, 32) {
if (A[i] & (1 << j)) {
numLeading++;
} else if (numLeading > 0) {
break;
}
}
pq.push(numLeading);
}
pq.pop(); // Remove the first stack in order to trigger the first rebalancing
while (!pq.empty()) {
// Within this loop, player B must rebalance one stack, and player A must completely remove one stack.
// This continues until there are no more stacks.
int u = pq.top(); pq.pop();
if (u == 1) {
// If the only stack player B can rebalance are stacks with one leading one, then we can subtract
// 2 from the answer
ans -= 2;
} else {
// Otherwise, player B will rebalance the stack with the most number of leading ones,
// leading to a new stack with one less leadnig one
pq.push(u - 1);
// Then player A will have to completely remove one stack in order to trigger the next rebalancing.
// Obviously player A will choose to remove the stack with the most number of leading ones.
pq.pop();
}
}
ps(ans);
return 0;
} | true |
5f5978f4afdaee653d959f07dba01a53c41891d7 | C++ | daffafzn/latihan | /3 jarak antara tanggal.cpp | UTF-8 | 1,208 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
char opsi;
do
{
system("cls");
struct {
int hari, bulan, tahun;
} pertama, kedua;
struct {
int hari, bulan, tahun;
} selisih;
cout << "Masukkan Tanggal Pertama (dd:mm:yy) \n\n";
cout << "Hari = ";
cin >> pertama.hari;
cout << "Bulan = ";
cin >> pertama.bulan;
cout << "Tahun = ";
cin >> pertama.tahun;
cout << "\n\nMasukkan Tanggal Kedua (dd:mm:yy) \n\n";
cout << "Hari = ";
cin >> kedua.hari;
cout << "Bulan = ";
cin >> kedua.bulan;
cout << "Tahun = ";
cin >> kedua.tahun;
selisih.tahun = pertama.tahun - kedua.tahun;
selisih.bulan = pertama.bulan - kedua.bulan;
selisih.hari = pertama.hari - kedua.hari;
if (selisih.tahun < 0) {
selisih.tahun = selisih.tahun * -1;
}
else if (selisih.bulan < 0) {
selisih.bulan = selisih.bulan * -1;
}
else if (selisih.hari < 0) {
selisih.hari = selisih.hari * -1;
}
cout << "\nSelisih = " << selisih.tahun << " Tahun " << selisih.bulan << " Bulan " << selisih.hari << " Hari ";
cout << "\n\nApakah Anda Ingin Keluar ? " << endl;
cout << "Ketik y atau n ";
cin >> opsi;
}while(opsi == 'n' || opsi == 'N');
}
| true |
b1dbbe0986fdc94468e0cf3aea428d065bd5657b | C++ | reginabezhanyan/study_tasks_contests | /2kurs/IV sem/7k/7-1.cpp | UTF-8 | 514 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <string>
struct MyException
{
std::string str;
public:
MyException(std::string str_) : str(str_) {}
~MyException()
{
std::cout << str << std::endl;
}
};
void f(std::string str)
{
if(str == "\0") {
throw -1;
}
MyException exp(str);
std::string nstr;
std::cin >> nstr;
f(nstr);
}
int main()
{
try {
std::string str;
std::cin >> str;
f(str);
} catch (...) {
}
} | true |
9f0a56118ff1a30af63bf051e448ff1422c67d9e | C++ | vbtang/DevSoft | /Src/Edislab/Edislab Pro/DataDefine.h | UTF-8 | 1,924 | 3.3125 | 3 | [] | no_license | #pragma once
struct CMeColor
{
CMeColor()
: red(0)
, green(0)
, blue(0)
, alpha(1.0)
{
}
CMeColor(double r, double g, double b, double a = 1.0)
: red(r)
, green(g)
, blue(b)
, alpha(a)
{
}
void setColor(double r, double g, double b, double a = 1.0)
{
red = r;
green = g;
blue = b;
alpha = a;
}
double getRed(){ return min(max(red, 0.), 1.);}
double getGreen(){ return min(max(green, 0.), 1.);}
double getBlue(){ return min(max(blue, 0.), 1.);}
double getAlpha(){ return min(max(alpha, 0.), 1.);}
private:
double red;
double green;
double blue;
double alpha;
};
struct CMeDPoint
{
CMeDPoint()
: x(0.0)
, y(0.0)
{}
CMeDPoint(double xx, double yy)
: x(xx)
, y(yy)
{}
CMeDPoint(const CPoint &pt)
: x(static_cast<double>(pt.x))
, y(static_cast<double>(pt.y))
{}
CPoint Point() const
{
CPoint pt;
pt.x = static_cast<int>(x);
pt.y = static_cast<int>(y);
return pt;
}
bool operator == (const CMeDPoint &other) const
{
return (x == other.x && y == other.y);
}
CMeDPoint operator - (const CMeDPoint &other) const
{
CMeDPoint pt(x-other.x, y-other.y);
return pt;
}
CMeDPoint operator -= (const CMeDPoint &other)
{
x -= other.x;
y -= other.y;
return *this;
}
CMeDPoint operator + (const CMeDPoint &other) const
{
CMeDPoint pt(x+other.x, y+other.y);
return pt;
}
CMeDPoint operator += (const CMeDPoint &other)
{
x += other.x;
y += other.y;
return *this;
}
CMeDPoint operator * (const double lfPar) const
{
CMeDPoint pt(x*lfPar, y*lfPar);
return pt;
}
CMeDPoint operator / (const double lfPar) const
{
CMeDPoint pt(x/lfPar, y/lfPar);
return pt;
}
CMeDPoint operator *= (const double lfPar)
{
x *= lfPar;
y *= lfPar;
return *this;
}
CMeDPoint operator /= (const double lfPar)
{
x /= lfPar;
y /= lfPar;
return *this;
}
operator CPoint() { return CPoint(int(x), int(y));}
double x;
double y;
}; | true |
61e90dce7468d78b95e4278dff528284224a9d0b | C++ | lhgcs/linuxProjectDemo | /util/jsonUtil.h | UTF-8 | 4,270 | 2.921875 | 3 | [] | no_license | /*
* @Description: cjson生成和解析
* @Version: 1.0
* @Autor: lhgcs
* @Date: 2019-10-20 13:14:10
* @LastEditors: lhgcs
* @LastEditTime: 2019-10-29 17:43:14
*/
class jsonUtil {
public:
/**
* @brief cjson_parse_string
* @param str json字符串
* @param key 键
* @return 值(字符串)
* 解析JSON包
*/
/**
* @description: json字符串解析成json对象
* @param {type}
* @return:
*/
int jsonStr2JsonObject(const char *str, cJSON *root) {
int res = -1;
cJSON *root= cJSON_Parse(str); //字符串解析成json结构体
if(NULL == root) {
printf("json error\n");
} else {
res = 0;
printf("json: %s\n",cJSON_Print(root)); //json结构体转换成字符串;
}
return res;
}
/**
* @description: json字符串解析成json对象
* @param {type}
* @return:
*/
int getJsonObject(const char *str, cJSON *root) {
int res = -1;
cJSON *root= cJSON_Parse(str); // 字符串解析成json结构体
if(NULL == root) {
printf("json error\n");
} else {
res = 0;
printf("json: %s\n",cJSON_Print(root)); // json结构体转换成字符串;
}
return res;
}
/**
* @description: 获取键值
* @param {type}
* @return:
*/
int getJsonValue(cJSON *root, const char *key, cJSON *temp) {
int res = -1;
if (NULL == root || NULL == key) {
return -1;
}
cJSON *temp = cJSON_GetObjectItem(root, key);
if(NULL == temp) {
printf("json not key:%s",key);
}
res = (NULL == temp) ? -1 : 0;
return res;
}
/**
* @description: 获取键值String
* @param {type}
* @return:
*/
int getJsonValueStr(cJSON *root, const char *key, char *value) {
int res = -1;
if (NULL == root || NULL == key) {
return -1;
}
cJSON *temp;
if(0 == getJsonValue(root, key, temp)) {
if(temp->type == cJSON_String) {
// 获取某个元素
value = temp->valuestring;
res = 0;
}
}
return res;
}
/**
* @description: 获取键值Int
* @param {type}
* @return:
*/
int getJsonValueInt(cJSON *root, const char *key, char *value) {
int res = -1;
if (NULL == root || NULL == key) {
return -1;
}
cJSON *temp;
if(0 == getJsonValue(root, key, temp)) {
if(temp->type == cJSON_Number) {
// 获取某个元素
value = temp->valueint;
res = 0;
}
}
return res;
}
/**
* @description: json数组大小
* @param {type}
* @return:
*/
int getJsonArraySize(cJSON *arrayObject) {
return cJSON_GetArraySize(arrayObject);
}
/**
* @description: json数组元素
* @param {type}
* @return:
*/
int getJsonArrayItem(cJSON *arrayObject, int index) {
cJSON* temp = cJSON_GetArrayItem(arrayObject, index);
if (NULL == temp){
}else{
res = 0;
}
return res;
}
/**
* @description: 释放json对象
* @param {type}
* @return:
*/
void freeJson(cJSON *root) {
if (NULL != root) {
cJSON_Delete(root);
}
}
/**
* @description: 生成json字符串
* @param {type}
* @return:
*/
int setJson(const char *key, const int value, char *str) {
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, key, value);
char *s = cJSON_Print(root);
// 在运行cJSON_Print(root);后务必要要进行释放操作
cJSON_Delete(root);
char *t = s;
while( *s != '\0' ){
// 如果当前字符不是要删除的,则保存到目标串中
if ( *s != '\n' && *s != '\t' ){
*t++ = *s;
}
s++ ;
}
*t='\0';
strcpy(str, t);
return 0;
}
};
| true |
f5dd24c553f567e92afd0ffb949e1b69c54e780f | C++ | Audrie8a/Arqui-1 | /Practicas/Practica1/Cartel/Cartel/Cartel.ino | UTF-8 | 3,540 | 2.625 | 3 | [] | no_license |
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
//Aclaraciones: Modulo 0= Matriz 2 ; Modulo 1= Matriz 1
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 2
#define CP_PIN 10 //LOAD
#define DATA_PIN 11 //DIN
#define CLE_PIN 13 //CLK
MD_Parola myDisplay = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLE_PIN, CP_PIN, MAX_DEVICES);
const int buttonPin0 = 7; //Modo Texto
const int buttonPin1 = 6; //Dirección
const int buttonPin2 = 5; //Velocidad
int velocidad=100;
int retardo=800;
int curText=0;
//0 a 21 Cadenas
const char *pc[]=
{
"TP1-GRUPO 4-SECCION B",
"T", "P", "1", "-",
"G", "R", "U", "P", "O",
" ", "4", "-", "S", "E",
"C", "C", "I", "O", "N",
" ", "B"
};
// Global variables
typedef struct
{
uint8_t spacing; // character spacing
const char *msg; // message to display
} msgDef_t;
msgDef_t M[] =
{
{ 1, "TP1-GRUPO 4-SECCION B"},
//1 a 19 Va de derecha a izquierda
{ 0, " T"}, { 1, "T P" }, { 0, "P 1" }, { 1, "1 -" }, { 0, "- G" },
{ 1, "G R" }, { 0, "R U" }, { 1, "U P" }, { 0, "P O" }, { 1, "O 4" },
{ 0, "4 S" }, { 1, "S E" }, { 0, "E C" }, { 1, "C C" }, { 0, "C I" },
{ 1, "I O" }, { 0, "O N" }, { 1, "N B" }, { 0, "B " },
//20 a 30 Va de izquierda a derecha
{ 1, "B "}, { 0, "N B" }, { 1, "O N" }, { 0, "I O" }, { 1, "C I" },
{ 0, "C C" }, { 1, "E C" }, { 0, "S E" }, { 1, "- S" }, { 1, "4 -" },
{ 0, "O 4" }, { 1, "P O" }, { 0, "U P" }, { 1, "R U" }, { 0, "G R" },
{ 1, "- G" }, { 0, "1 -" }, { 1, "P 1" }, { 0, "T P" }, { 1, " T"},
};
#define PAUSE_TIME 1000
#define MAX_STRINGS (sizeof(M)/sizeof(M[0]))
int modoStatic(int cont){
int n=cont;
if (digitalRead(buttonPin1)==HIGH){
if(n<20){
myDisplay.setTextEffect(PA_NO_EFFECT,PA_NO_EFFECT );
myDisplay.setTextBuffer(M[n].msg);
myDisplay.displayReset();
delay(retardo);
myDisplay.displayReset();
n = (n + 1) % MAX_STRINGS;
}else{
n=1;
myDisplay.displayReset();
}
}else{
if (n<20){
n=20;
}
myDisplay.setTextAlignment(PA_RIGHT,PA_LEFT);
myDisplay.setTextEffect(PA_NO_EFFECT,PA_NO_EFFECT );
myDisplay.setTextBuffer(M[n].msg);
myDisplay.displayReset();
delay(retardo);
myDisplay.displayReset();
n = (n + 1) % MAX_STRINGS;
}
return n;
}
void modoAnimado(){
myDisplay.setTextEffect(PA_SCROLL_LEFT,PA_SCROLL_LEFT);
myDisplay.setTextBuffer(M[0].msg);
if (digitalRead(buttonPin1)==HIGH) {
myDisplay.setTextEffect(PA_SCROLL_LEFT , PA_SCROLL_LEFT);
}else{
myDisplay.setTextEffect(PA_SCROLL_RIGHT, PA_SCROLL_RIGHT);
}
int slide_scroll_speed = map(velocidad, 1023, 0, 400, 15);
myDisplay.setSpeed(slide_scroll_speed);
}
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin0, INPUT);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
myDisplay.begin();
myDisplay.displayClear();
myDisplay.setIntensity(5);
myDisplay.displayText(M[0].msg, PA_LEFT, velocidad, 0, PA_SCROLL_LEFT , PA_SCROLL_LEFT );
}
void loop() {
// put your main code here, to run repeatedly:
static uint8_t n = 1;
if (digitalRead(buttonPin0)==HIGH){
n=modoStatic(n);
} else{
modoAnimado();
n=1;
}
if (digitalRead(buttonPin2)==HIGH) {
velocidad = 80;
retardo= 600;
}else{
velocidad = 1000;
retardo=1000;
}
if (myDisplay.displayAnimate())
{
myDisplay.displayReset();
}
}
| true |
e923fbc3e34a3a5f1dcbe4dab5851ec7775d8302 | C++ | sigmafx/DotClk | /DmdFrame.cpp | UTF-8 | 1,456 | 3.125 | 3 | [] | no_license | #include <Arduino.h>
#include "DmdFrame.h"
DmdFrame::DmdFrame()
{
width = 128;
height = 32;
Clear();
}
byte DmdFrame::GetDot(int x, int y)
{
if(!CheckRange(x, y))
{
return 0x00;
}
return frame.dots[y][x];
}
void DmdFrame::SetDot(int x, int y, byte value)
{
if(!CheckRange(x, y))
{
return;
}
frame.dots[y][x] = value & 0x0F;
return;
}
void DmdFrame::Clear(byte value)
{
memset(frame.dots, value & 0x0F, sizeof(frame.dots));
}
void DmdFrame::DotBlt(Dotmap& dmp, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int destX, int destY)
{
int bltSrcX, bltSrcY, bltDestX, bltDestY;
for (bltSrcX = sourceX, bltDestX = destX; bltSrcX < (sourceX + sourceWidth); bltSrcX++, bltDestX++)
{
for(bltSrcY = sourceY, bltDestY = destY; bltSrcY < (sourceY + sourceHeight); bltSrcY++, bltDestY++)
{
byte bltDot ;
// Apply mask
if(dmp.GetMask(bltSrcX, bltSrcY))
{
bltDot = frame.dots[bltDestY][bltDestX];
}
else
{
bltDot = dmp.GetDot(bltSrcX, bltSrcY);
}
// Set dot
frame.dots[bltDestY][bltDestX] = bltDot;
}
}
}
//--------
//--------
// PRIVATE
//--------
//--------
//---------------------
// Function: CheckRange
//---------------------
bool DmdFrame::CheckRange(int x, int y)
{
if(x < 0 || y < 0 || x >= width || y >= height)
{
// Out of range, return
return false;
}
else
{
return true;
}
}
| true |
4f265e0d8de2cd1bd74d87c549f4721a35cc4597 | C++ | MateusAttie/C | /Matriz/Exercicio6.cpp.cpp | UTF-8 | 701 | 2.75 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ordem 4
int main ()
{
int tabela[ordem][ordem],i,j,maior = 0;
srand(time(0));
for(i = 0; i < ordem;i++)
{
for(j = 0 ; j < ordem;j++)
{
tabela[i][j] = rand()%(ordem*ordem);
printf("%d\t",tabela[i][j]);
if(tabela[i][j] > maior)
maior = tabela[i][j];
}
printf("\n");
}
printf("maior valor = %d\n",maior);
for(i = 0;i < ordem;i++)
for(j = 0; j < ordem ; j++)
if(tabela[i][j] == maior)
printf("linha = %d coluna = %d\n",i,j);
system("pause");
}
| true |
96edb6448259083d564ce610aa763f2cd5a2d1a2 | C++ | samuelbearman/TheGarage | /DataStructures341/projects/project5/ProbeHashTable.cpp | UTF-8 | 5,922 | 3.3125 | 3 | [] | no_license | #ifndef PROBE_HASH_TABLE_CPP
#define PROBE_HASH_TABLE_CPP
#include "ProbeHashTable.h"
#include <iostream>
// Overloaded Constructor
template <typename T>
ProbeHashTable<T>::ProbeHashTable(unsigned int (*hashFunc)(const T&), int n) {
m_table = new HashTableEntry<T>[n];
m_capacity = n;
m_size = 0;
this->hashFunc = hashFunc;
}
// Destructor
template <typename T>
ProbeHashTable<T>::~ProbeHashTable() {
delete [] m_table;
m_table = NULL;
}
// Copy Constructor
template <typename T>
ProbeHashTable<T>::ProbeHashTable(ProbeHashTable& rhs) {
m_capacity = rhs.m_capacity;
m_size = rhs.m_size;
this->hashFunc = rhs.hashFunc;
m_table = new HashTableEntry<T>[m_capacity];
for (int i = 0; i < m_capacity; i++) {
m_table[i].m_flag = rhs.m_table[i].m_flag;
m_table[i].m_data = rhs.m_table[i].m_data;
m_table[i].m_hash = rhs.m_table[i].m_hash;
}
}
// Overloaded '=' operator
template <typename T>
const ProbeHashTable<T>& ProbeHashTable<T>::operator=(ProbeHashTable<T>& rhs) {
m_capacity = rhs.m_capacity;
m_size = rhs.m_size;
this->hashFunc = rhs.hashFunc;
m_table = new HashTableEntry<T>[m_capacity];
for (int i = 0; i < m_capacity; i++) {
m_table[i].m_flag = rhs.m_table[i].m_flag;
m_table[i].m_data = rhs.m_table[i].m_data;
m_table[i].m_hash = rhs.m_table[i].m_hash;
}
}
// insert
// inserts new data into hash table using the linear probing technique
template <typename T>
bool ProbeHashTable<T>::insert(const T &data) {
// insertion process
// start by hashing data value
// try and insert at hashed point
// if empty, insert into spot
// if not loop and probe until spot is found
if (m_size == m_capacity) {
throw std::out_of_range("Hash table is FULL");
}
unsigned int hashCode = this->hashFunc(data) % m_capacity;
if (m_table[hashCode].m_flag == FLAG_EMPTY || m_table[hashCode].m_flag == FLAG_DELETE) {
m_table[hashCode].m_data = data;
m_table[hashCode].m_flag = FLAG_FULL;
m_table[hashCode].m_hash = hashCode;
m_size++;
return true;
}
if(m_table[hashCode].m_flag == FLAG_FULL) {
bool stillProbing = true;
int incrementer = (int) hashCode;
incrementer = (incrementer + 1) % m_capacity;
while (stillProbing) {
if (m_table[incrementer].m_flag == FLAG_EMPTY || m_table[incrementer].m_flag == FLAG_DELETE) {
m_table[incrementer].m_data = data;
m_table[incrementer].m_flag = FLAG_FULL;
m_table[incrementer].m_hash = hashCode;
m_size++;
return true;
stillProbing = false;
}
incrementer = (incrementer + 1) % m_capacity;
}
}
}
// find
// finds given data, returns true if found, false if not
template <typename T>
bool ProbeHashTable<T>::find(const T &data) {
unsigned int hashCode = this->hashFunc(data) % m_capacity;
if (m_table[hashCode].m_flag == FLAG_EMPTY)
return false;
if (m_table[hashCode].m_data == data)
return true;
bool stillProbing = true;
int incrementer = (int) hashCode;
incrementer = (incrementer + 1) % m_capacity;
while (stillProbing) {
if (m_table[incrementer].m_flag == FLAG_EMPTY)
return false;
if (m_table[incrementer].m_data == data)
return true;
incrementer = (incrementer + 1) % m_capacity;
}
}
// remove
// removes items from hash table, sets boolean 'found' to true if found, false if not
// returns back the data
template <typename T>
T ProbeHashTable<T>::remove(const T &data, bool &found) {
unsigned int hashCode = this->hashFunc(data) % m_capacity;
if (m_table[hashCode].m_data == data) {
m_table[hashCode].m_flag = FLAG_DELETE;
found = true;
m_size--;
return m_table[hashCode].m_data;
} else {
bool stillProbing = true;
int incrementer = (int) hashCode;
incrementer = (incrementer + 1) % m_capacity;
while (stillProbing) {
if (m_table[incrementer].m_flag == FLAG_EMPTY) {
found = false;
return data;
}
if (m_table[incrementer].m_data == data) {
m_table[incrementer].m_flag = FLAG_DELETE;
found = true;
m_size--;
return m_table[incrementer].m_data;
}
incrementer = (incrementer + 1) % m_capacity;
}
}
}
// dump
// dumps contents of the hash table, used for debugging only
template <typename T>
void ProbeHashTable<T>::dump() {
std::cout << "ProbeHashTable dump; size: " << m_capacity << " buckets" << std::endl;
for (int i = 0; i < m_capacity; i++) {
std::cout << "[" << i << "]: ";
if (m_table[i].m_flag == FLAG_FULL) {
std::cout << m_table[i].m_data << " (" << m_table[i].m_hash << ")" << std::endl;
} else if (m_table[i].m_flag == FLAG_DELETE) {
std::cout << "DELETED" << std::endl;
} else if (m_table[i].m_flag == FLAG_EMPTY) {
std::cout << "EMPTY" << std::endl;
} else {
std::cout << std::endl;
}
}
std::cout << "Total items: " << m_size << std::endl;
}
// at
// given a specific index, finds if there is a value at that index
// returns 1 if there is data, 0 if not
// pushes all data found at given index to 'contents' vector
template <typename T>
int ProbeHashTable<T>::at(int index, std::vector<T> &contents) {
if (index < 0 || index > m_capacity) {
throw std::out_of_range ("Index is too big or too small");
}
if (m_table[index].m_flag == FLAG_FULL) {
contents.push_back(m_table[index].m_data);
return 1;
} else {
return 0;
}
}
#endif
| true |
b423d29017a9137c1d916a8c8c5692c20416e13b | C++ | yuchenguangfd/Arena | /poj/P2075.cpp | UTF-8 | 3,383 | 3.515625 | 4 | [] | no_license | /*
* Problem: Tangled in Cables
* http://poj.org/problem?id=2075
*/
#include <vector>
#include <string>
#include <limits>
#include <algorithm>
#include <cstdio>
template <class T>
class WeightedDirectedGraphAsAdjMatrix {
public:
typedef T WeightType;
WeightedDirectedGraphAsAdjMatrix(int numVertex, WeightType initWeight = WeightType()) :
mNumVertex(numVertex), mWeights(numVertex * numVertex) {
std::fill(mWeights.begin(), mWeights.end(), initWeight);
}
int NumVertex() const { return mNumVertex; }
WeightType GetWeight(int u, int v) const { return mWeights[u * mNumVertex + v]; }
void AddEdge(int u, int v, WeightType weight) { mWeights[u * mNumVertex + v] = weight; }
protected:
int mNumVertex;
std::vector<WeightType> mWeights;
};
template <class GraphType>
class Prim {
private:
typedef typename GraphType::WeightType WeightType;
public:
Prim(const GraphType *graph) : mGraph(graph), mDistances(graph->NumVertex()), mStates(graph->NumVertex()),
mTotalWeight(0) { }
void Compute() {
int source = 0;
for (int u = 0; u < mGraph->NumVertex(); ++u) {
mDistances[u] = mGraph->GetWeight(source, u);
mStates[u] = false;
}
mDistances[source] = 0;
mStates[source] = true;
mTotalWeight = 0;
for (int i = 1; i < mGraph->NumVertex(); ++i) {
WeightType min = std::numeric_limits<WeightType>::max();
int k;
for (int j = 0; j < mGraph->NumVertex(); ++j) {
if (!mStates[j] && min > mDistances[j]) {
min = mDistances[j];
k = j;
}
}
mStates[k] = true;
mDistances[k] = min;
mTotalWeight += min;
for (int j = 0; j < mGraph->NumVertex(); ++j) {
if (!mStates[j] && mGraph->GetWeight(k, j) < mDistances[j]) {
mDistances[j] = mGraph->GetWeight(k, j);
}
}
}
}
WeightType TotalWeight() const {
return mTotalWeight;
}
private:
const GraphType *mGraph;
std::vector<WeightType> mDistances;
std::vector<bool> mStates;
WeightType mTotalWeight;
};
int main() {
double cableLength;
scanf("%lf", &cableLength);
int n;
scanf("%d", &n);
std::vector<std::string> names(n);
for (int i = 0; i < n; ++i) {
char buff[32];
scanf("%s", buff);
names[i] = std::string(buff);
}
WeightedDirectedGraphAsAdjMatrix<double> graph(n, 1e100);
int m;
scanf("%d", &m);
for (int i = 0; i < m; ++i) {
char buff[32];
scanf("%s", buff);
int u = std::find(names.begin(), names.end(), std::string(buff)) - names.begin();
scanf("%s", buff);
int v = std::find(names.begin(), names.end(), std::string(buff)) - names.begin();
double w;
scanf("%lf", &w);
graph.AddEdge(u, v, w);
graph.AddEdge(v, u, w);
}
Prim<WeightedDirectedGraphAsAdjMatrix<double> > prim(&graph);
prim.Compute();
if (prim.TotalWeight() > cableLength) {
printf("Not enough cable\n");
} else {
printf("Need %0.1f miles of cable\n", prim.TotalWeight());
}
}
| true |
d5fab21a7b37030d64aae043db5b8c21ce8ce812 | C++ | AlinGeorgescu/HackerRank-Solutions | /HR - Problem Solving/DiagonalDifference.cpp | UTF-8 | 914 | 3.875 | 4 | [
"MIT"
] | permissive | /**
* Copyright 2018
* Diagonal Difference
*/
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
int diagonalDifference(vector< vector<int> > a, int n) {
/**
* PD = primary diagonal
* SD = secondary diagonal
*/
int sumPD = 0, sumSD = 0;
for (int i = 0; i < n; ++i) {
sumPD += a[i][i];
sumSD += a[i][n - i - 1];
}
// reuse of sumPD variable as the wanted difference
sumPD = sumPD - sumSD;
if (sumPD > 0) {
return sumPD;
} else {
return sumPD * (-1);
}
}
int main() {
int n;
cin >> n;
// Matrix as vector of vectors.
vector< vector<int> > a(n, vector<int>(n));
// Reading the matrix.
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
cin >> a[i][j];
}
}
cout << diagonalDifference(a, n) << '\n';
return 0;
}
| true |
a027035ed703963d83a878c09be9350cfdd4c4cc | C++ | Gonghaoran7719/QT_Demo | /MD5/widget.cpp | UTF-8 | 2,305 | 2.625 | 3 | [] | no_license | #include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowTitle(QString("MD5"));
ValInit();
}
Widget::~Widget()
{
md5Thread.exit();
md5Thread.wait(10*1000);
delete ui;
}
void Widget::ValInit()
{
/*设置进度条进度为0*/
ui->progressBar->setValue(0);
/*将IO操作放到线程中去执行,防止文件过大卡界面*/
mMd5CheckSum.moveToThread(&md5Thread); /*从一个object 移动到 一个thread*/
md5Thread.start(); /*开启线程*/
/* 绑定信号与槽 */
/* 关联MD5计算槽函数 让Md5Check对象开始计算MD5值 */
connect(this,SIGNAL(checkMd5SumSignal(QString)),&mMd5CheckSum,SLOT(getMd5CheckSumSlot(QString)));
/*关联MD5结果返回信号,将MD5计算结果传递给Widget定义的槽函数recvMd5CheckSumSlot*/
connect(&mMd5CheckSum, SIGNAL(sendMd5CheckSumSignal(QByteArray)),this, SLOT(recvMd5CheckSumSlot(QByteArray)));
/*关联MD5计算进度,将进度返回给Widget定义的槽函数recvProgressBarSlot*/
connect(&mMd5CheckSum, SIGNAL(sendProgressBarSignal(int,int)),this, SLOT(recvProgressBarSlot(int,int)));
}
void Widget::recvMd5CheckSumSlot(QByteArray result)
{
ui->textEdit->setText(result); /*将MD5计算结果显示到主界面*/
}
void Widget::recvProgressBarSlot(int total, int current)
{
ui->progressBar->setMaximum(total); /* 设置进度条最大值 */
ui->progressBar->setValue(current); /* 设置当前进度 */
}
void Widget::on_pushButton_clicked()
{
QFileInfo MD5Fileinfo; /* 文件信息 */
QString md5Filename = QFileDialog::getOpenFileName(this,"open");
MD5Fileinfo = QFileInfo(md5Filename);
ui->lineEdit->clear(); /*清空Edit*/
ui->textEdit->clear();
if(MD5Fileinfo.exists())
{
ui->lineEdit->setText(MD5Fileinfo.fileName());
emit checkMd5SumSignal(md5Filename); /*将打开的文件路径通过信号传递给Md5Check对象*/
}
}
void Widget::on_clipboard_button_clicked()
{
clip = QApplication::clipboard(); /*获取系统剪贴板*/
clip->setText(ui->textEdit->toPlainText()); /*设置系统剪贴板内容*/
}
| true |
03d5c43e19de6fe1ea1d6a8b6a0a277d615f3ece | C++ | avsobolev/prata_cpp_exercises | /chapter5/05_02.cpp | UTF-8 | 1,290 | 3.640625 | 4 | [] | no_license | /* 05_02.cpp
Занятия по книге Стивена Прата "Язык программирования С++" (2012, 6-е издание).
Упражнения по программированию. Глава 5, страница 255, упражнение 2
Перепишите код из листинга 5.4 с использованием объекта array вместо
встроенного массива и типа long double вместо long long. Найдите значение 100!
ЛИСТИНГ 5.4
#include <iostream>
const int ArSize =16; // пример внешнего объявления
int main()
{
long long factorials[ArSize];
factorials [1] = factorials[0] = 1LL;
for (int i = 2; i < ArSize; i + + )
factorials[i] = i * factorials[i-l];
for (i = 0; i < ArSize; i + + )
std::cout « i « " ! = " << factorials [i] « std::endl;
return 0;
}
*/
#include <iostream>
#include <array>
const int ArSize =101;
int main() {
std::array<long double, ArSize> factorials;
factorials[1] = factorials[0] = 1LL;
for (int i = 2; i < ArSize; i++)
factorials[i] = i * factorials[i-1];
std::cout << "100! = " << factorials [ArSize-1] << std::endl;
return 0;
} | true |
1fcb6c96a2b8bdff4e2d38129ef5058cbd87d9b0 | C++ | saksham-jain01/Data-Structures-and-Algorithms | /linked-lists/Node.h | UTF-8 | 159 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef NODE_H
#define NODE_H
template <typename T>
class Node{
public:
T data;
Node<T>*next;
Node(T d):data(d),next(NULL){}
};
#endif
| true |
55f7aeaf77d5df2ecbb98eff2bc307ed951c1d71 | C++ | qtux/ggj15 | /src/Menu.cpp | UTF-8 | 4,119 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2015-2017 Annemarie Mattmann, Johannes Mattmann,
* Matthias Gazzari, Moritz Hagemann, Sebastian Artz
*
* Licensed under the MIT license. See the LICENSE file for details.
*/
#include "Menu.hpp"
#include "Editor.hpp"
#include "Level.hpp"
#include "Credits.hpp"
#include <fstream>
#include <sstream>
Menu::Menu(Menu::Command initialCmd, unsigned int currentLevel):
Scene(gb::sceneSize),
cmdMap({{EDITOR, "Editor"}, {LEVEL, "Level"}, {EXIT, "Exit"}, {OPTIONS, "Options"}, {CREDITS, "Credits"}}),
_currentEntry(0),
_currentLevel(currentLevel),
_levelMap(TileMap(gb::tileSize, gb::gridSize, std::string(PATH) + "levels/level" + std::to_string(currentLevel)))
{
// read level number from file
std::ifstream indexFile("levels/index.txt");
if (indexFile.is_open())
{
unsigned int level;
while (indexFile >> level)
{
_levels.push_back(level);
}
}
std::sort(_levels.begin(), _levels.end());
std::unique(_levels.begin(), _levels.end());
// TODO use a set instead of a vector to keep track of all levels
// create entries
sf::Vector2f center(sceneSize / 2.0f);
float radius = sceneSize.x / 4.0f;
float angle = M_PI;
for (auto& kv: cmdMap)
{
_entries.push_back(Entry(kv.second, gb::ressourceManager.getFont(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf"), sf::Color(0xcc, 0x22, 0x22), 42, center, angle, radius, kv.first));
angle += 2.0f * M_PI / cmdMap.size();
}
// set first entry on top
for (auto i = 0; i < _entries.size(); ++i)
{
if (_entries[i].cmd == initialCmd)
{
break;
}
rotate(true);
}
overlay.setFillColor(sf::Color(0, 0, 0, 200));
_entries[LEVEL].appendText(" " + std::to_string(_currentLevel));
}
unsigned int Menu::nextPos(unsigned int pos, unsigned int size, bool clockWise)
{
auto forward = (pos < size - 1) ? pos + 1 : 0;
auto backward = (pos > 0) ? pos - 1 : size - 1;
return clockWise ? forward : backward;
}
void Menu::rotate(bool clockWise)
{
float angle = 2.0f * M_PI / (float) _entries.size();
angle *= clockWise ? -1.0f : 1.0f;
_currentEntry = nextPos(_currentEntry, _entries.size(), clockWise);
for (auto& entry: _entries)
{
entry.rotate(angle);
}
}
Scene* Menu::processEvent(sf::Event event, sf::RenderWindow& window)
{
// preprocessing key input (to enhance code readability)
sf::Keyboard::Key keyPressed = sf::Keyboard::Unknown;
if (event.type == sf::Event::KeyPressed)
{
keyPressed = event.key.code;
}
bool levelSelected = (_entries[_currentEntry].cmd == LEVEL);
switch(keyPressed)
{
case sf::Keyboard::Escape:
window.close();
break;
case sf::Keyboard::Right:
rotate(true);
break;
case sf::Keyboard::Left:
rotate(false);
break;
case sf::Keyboard::Up:
if (levelSelected)
{
_currentLevel = _levels[nextPos(_currentLevel, _levels.size(), true)];
_entries[LEVEL].appendText(" " + std::to_string(_currentLevel));
_levelMap = TileMap(gb::tileSize, gb::gridSize, std::string(PATH) + "levels/level" + std::to_string(_currentLevel));
}
break;
case sf::Keyboard::Down:
if (levelSelected)
{
_currentLevel = _levels[nextPos(_currentLevel, _levels.size(), false)];
_entries[LEVEL].appendText(" " + std::to_string(_currentLevel));
_levelMap = TileMap(gb::tileSize, gb::gridSize, std::string(PATH) + "levels/level" + std::to_string(_currentLevel));
}
break;
case sf::Keyboard::Return:
// load a scene dependend on the current command
switch(_entries[_currentEntry].cmd)
{
case EDITOR:
return new Editor();
case LEVEL:
return new Level(_currentLevel);
break;
case EXIT:
window.close();
break;
case OPTIONS:
/*TODO*/
break;
case CREDITS:
return new Credits();
break;
default:
break;
}
break;
default:
break;
}
return this;
}
Scene* Menu::update(sf::Time deltaT, sf::RenderWindow& window)
{
for (auto& entry: _entries)
{
entry.update(deltaT.asSeconds() * 10.0f);
}
return this;
}
void Menu::draw(sf::RenderTarget& target, bool focus)
{
_levelMap.draw(target);
for (auto& entry: _entries)
{
target.draw(entry.text);
}
if (!focus)
{
target.draw(overlay);
}
}
| true |
7f6530e382a18c58fcab651e2bb3b7da708f9abc | C++ | MiXo20/LearningPro | /Struct/fraction.cpp | UTF-8 | 5,595 | 3.390625 | 3 | [] | no_license | #include "fraction.h"
void Fraction::Display()
{
if(chasel==1)
cout <<chasel/NSD(chasel, denominator)<<' ';
else
cout << chasel/NSD(chasel, denominator)<<'/'<<denominator/NSD(chasel, denominator)<<' ';
}
int NSD(int ch, int den)
{
if(den==0)
return abs(ch);
else
return NSD(abs(den),abs(ch%den));
}
Fraction operator + (const Fraction &a,const Fraction &b)
{
Fraction c;
c.chasel=a.chasel*b.denominator+a.denominator*b.chasel;
c.denominator=a.denominator*b.denominator;
return c;
}
Fraction &Fraction::operator +=(const Fraction &b)
{
chasel=chasel*b.denominator+(denominator*b.chasel);
denominator=denominator*b.denominator;
return *this;
}
Fraction operator - (const Fraction &a,const Fraction &b)
{
Fraction c;
c.chasel=a.chasel*b.denominator-a.denominator*b.chasel;
if(c.chasel==0)
c.denominator=1;
else
c.denominator=a.denominator*b.denominator;
return c;
}
//Fraction operator - (const int a, const Fraction &b)
//{
// Fraction res;
// res.chasel=a*b.denominator-b.chasel;
// if (res.chasel==0)
// res.denominator=1;
// else
// res.denominator=b.denominator;
// return res;
//}
//Fraction operator - (const Fraction &b, const int a)
//{
// Fraction res;
// res.chasel=b.chasel-a*b.denominator;
// if (res.chasel==0)
// res.denominator=1;
// else
// res.denominator=b.denominator;
// return res;
//}
Fraction& Fraction::operator -=(const Fraction &b)
{
chasel=chasel*b.denominator-denominator*b.chasel;
if(chasel==0)
denominator=1;
else
denominator=denominator*b.denominator;
return *this;
}
Fraction operator * (const Fraction &a,const Fraction &b)
{
Fraction c;
c.chasel=a.chasel*b.chasel;
c.denominator=a.denominator*b.denominator;
return c;
}
Fraction& Fraction::operator *=(const Fraction &b)
{
chasel=chasel*b.chasel;
denominator=denominator*b.denominator;
return *this;
}
Fraction operator / (const Fraction &a, const Fraction &b)
{
Fraction c;
c.chasel=a.chasel*b.denominator;
c.denominator=a.denominator*b.chasel;
if(c.chasel<0&&c.denominator<0)
return c.Fabs();
else if(c.denominator<0&&c.chasel>0)
{
c.chasel=-c.chasel;
c.denominator=abs(c.denominator);
return c;
}
return c;
}
Fraction& Fraction::operator /= (const Fraction &b)
{
chasel=chasel*b.denominator;
denominator=denominator*b.chasel;
if(chasel<0&&denominator<0)
return *this=this->Fabs();
else
if(denominator<0&&chasel>0)
{
chasel=-chasel;
denominator=abs(denominator);
return *this;
}
return *this;
}
Fraction Fraction::operator - () const
{
Fraction b(*this);
b.chasel=-b.chasel;
return b;
}
Fraction Fraction::Fpow(const int n) const
{
Fraction res;
res.chasel=pow(chasel,n);
res.denominator=pow(denominator,n);
return res;
}
Fraction Fraction::Fabs() const
{
Fraction res;
res.chasel=abs(chasel);
res.denominator=abs(denominator);
return res;
}
bool Fraction::operator > (const Fraction &a) const
{
if(chasel*a.denominator>a.chasel*denominator)
return true;
return false;
}
bool Fraction::operator > (const int a) const
{
if(chasel>a*denominator)
return true;
return false;
}
bool operator > (const int a, const Fraction &b)
{
if(a*b.denominator>b.chasel)
return true;
return false;
}
bool Fraction::operator < (const Fraction &a) const
{
if(chasel*a.denominator<a.chasel*denominator)
return true;
return false;
}
bool Fraction::operator < (const int a) const
{
if(chasel<a*denominator)
return true;
return false;
}
bool operator < (const int a, const Fraction &b)
{
if(a*b.denominator<b.chasel)
return true;
return false;
}
bool Fraction::operator == (const Fraction &a) const
{
return chasel*a.denominator==a.chasel*denominator;
}
bool Fraction::operator == (const int a) const
{
return chasel==a*denominator;
}
bool operator == (const int a,const Fraction &b)
{
return a*b.denominator==b.chasel;
}
ostream& operator << (ostream &os, const Fraction &a)
{
if(a.chasel==0)
{
os <<a.chasel<<'/'<<1;
return os;
}
else
{
os << a.chasel/NSD(a.chasel, a.denominator)<<'/'<<a.denominator/NSD(a.chasel, a.denominator);
return os;
}
}
istream& operator >> (istream &is, Fraction &p)
{
for(;;)
{
if(is>>p.chasel)
{
if(is.peek()=='/')
{
is.ignore(1);
if(is>>p.denominator)
{
if(p.denominator<0)
{
p.chasel=-p.chasel;
p.denominator=-p.denominator;
}
return is;
}
else
{
is.clear();
is.ignore(500,'\n');
}
}
else
if(is.peek()=='\n')
{
p.denominator=1;
return is;
}
else
{
is.clear();
is.ignore(500,'\n');
}
}
else
{
is.clear();
is.ignore(500,'\n');
}
cout << "Bad input!!!\n";
}
}
| true |
c45727acf22185ff5d2b94b25b31b765b232b293 | C++ | Snow20132573/Compiler | /procedure/lexical_analysis/compile.cpp | GB18030 | 21,645 | 2.78125 | 3 | [] | no_license | #include<cstring>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
#include<iomanip>
#include<sstream>
using namespace std;
//ؼ
char* key[]= {"if","else","for","while","do","return","int","void","main","break","continue","cout","float"};
//ʶ
struct name
{
char ID[20];
} name[1000];
int namenum=0;//ʶ
//
char* operate[]= {"%","+","#","-","*","/",">","<","=","++","--",">=","<=","==","!=","&&","||"};
//ֽ
char* border[]= {",",";","{","}","(",")","[","]"};
//
struct num
{
int num1;
float num2;
bool x1;//trueʱnum1
bool x2;//trueʱnum2
} num[1000];
int numbernum=0;//
char* f1name="f1.txt";//Ԫ
char* f2name="f2.txt";//
char* f3name="f3.txt";//ʶ
FILE* f1,*f2,*f3;//ű
int x;//ȡַλ
int i,j,k,f=0,len;
char A[20];//ʱַ
string getsym="";//ʼʱûжǿմ
string Array[100000];
int length;//ij
int Len=0;//Arrayij
struct Siyuan
{
string op;
string w1;
string w2;
string step;
}Si[1000];
struct Goal
{
int step;
string G1;
string G2;
string G3;
}Goal[1000];
int Begin=1,END=2000,start=1;
void Read_file(char* s,string &getsym)
{
FILE *fp;
if((fp=fopen(s,"r"))!=NULL)
{
while(!feof(fp))//ȡgetsym
{
getsym+=fgetc(fp);
}
}
cout<<getsym<<endl;
fclose(fp);
}
void openfile()
{
f1=fopen(f1name,"a");
if(!f1)
{
f1=fopen(f1name,"w");
}
char* sm="1.ؼ2.ʶ3.4.5.";//Ԫͷ
fputs(sm,f1);//Ԫͷ
f2=fopen(f2name,"a");
if(!f2)
{
f2=fopen(f2name,"w");
}
f3=fopen(f3name,"a");
if(!f3)
{
f3=fopen(f1name,"w");
}
}
void closefile()
{
fclose(f1);
fclose(f2);
fclose(f3);
}
void delete_blank()//˵ոСTab
{
//cout<<x<<length<<endl;
while(x<length&&(getsym[x]==' '||getsym[x]==9||getsym[x]==10))
x++;
}
void character()//ǰĸ
{
k=0;//ʾʴij
f=0;
do
{
if(k<10)
A[k++]=getsym[x++];
}
while(x<length&&(getsym[x]>='a'&&getsym[x]<='z'||getsym[x]>='0'&&getsym[x]<='9'));
//strcpy(id,A);
for(j=0; j<13; j++)
{
//string str(key[j]);
if(strcmp(A,key[j])==0)
{
f=1;//ҵƥĹؼ
break;
}
}
//cout<<A<<endl;
if(f)//Aǹؼ,дԪ
{
fputs("\n",f1);
fputs(A,f1);
string a(A);
len=a.size();
int ll=15-len;
for(int t=0; t<ll; t++)
fputs(" ",f1);
fputs("1",f1);
}
else//ADZʶ
{
//***ʶдԪ***************************
fputs("\n",f1);
fputs(A,f1);
string a(A);
len=a.size();
int ll=15-len;
for(int t=0; t<ll; t++)
fputs(" ",f1);
fputs("2",f1);
//****״γֵıʶдʶ********************
int p=0;
for(int e=0; e<namenum; e++) //ұʶǷֹ
if(strcmp(name[e].ID,A)==0)
{
p=1;
break;
}
if(!p)
{
strcpy(name[namenum++].ID,A);
fputs("\n",f2);
fputs(A,f2);
}
}
}
void Number()//
{
int start=x,end;//¼ʴĿʼͽβ
float number=0,number1=0;//number1ʱС
do
{
number=10*number+getsym[x++]-'0';
}
while(x<length&&getsym[x]>='0'&&getsym[x]<='9');
if(getsym[x]=='.')//ʱΪ
{
x++;
do
{
number1=number1/10+getsym[x++]-'0';
}
while(x<length&&getsym[x]>='0'&&getsym[x]<='9');
number+=number1;
num[numbernum].num2=number;
num[numbernum++].x2=true;
//cout<<number<<endl;
}
else//ʱΪ
{
num[numbernum].num1=(int)number;
num[numbernum++].x1=true;
//cout<<number<<endl;
}
end=x;
memset(A,'\0',20*sizeof(char));
for(int y=start,k=0; y<end; y++,k++)
A[k]=getsym[y];
fputs("\n",f3);
fputs(A,f3);//д볣
//***дԪ
fputs("\n",f1);
fputs(A,f1);
string a(A);
len=a.size();
int ll=15-len;
for(int t=0; t<ll; t++)
fputs(" ",f1);
fputs("3",f1);
}
void Border()
{
//***ֽдԪ
fputs("\n",f1);
fputs(border[i],f1);
//strcpy(id,border[i]);
string a(border[i]);
len=a.size();
int ll=15-len;
for(int t=0; t<ll; t++)
fputs(" ",f1);
fputs("5",f1);
x++;
//cout<<border[i]<<endl;
}
//*****************************************************************
void Operate()
{
//***жϵǰDzŵ
//cout<<"**********************1\n";
memset(A,'\0',20*sizeof(char));
f=0;
for(i=9; i<17; i++)
{
//char* h;
A[0]=getsym[x];
if(x+1<length)
A[1]=getsym[x+1];
//cout<<A<<endl;
if(strcmp(A,operate[i])==0)
{
f=1;
break;
}
}
if(f)//***ǰһŵ
{
//***һŵдԪ
fputs("\n",f1);
fputs(operate[i],f1);
//strcpy(id,operate[i]);
string a(operate[i]);
len=a.size();
int ll=15-len;
for(int t=0; t<ll; t++)
fputs(" ",f1);
fputs("4",f1);
x+=2;
//cout<<operate[i]<<endl;
}
else//***ǰŵĹ涨֮ķ
{
f=0;
memset(A,'\0',20*sizeof(char));
A[0]=getsym[x];
for(i=0; i<9; i++)
{
if(strcmp(A,operate[i])==0)
{
f=1;
break;
}
}
//cout<<A<<endl;
if(f)//***ǰŵ
{
//***ŵдԪ
fputs("\n",f1);
fputs(operate[i],f1);
//strcpy(id,operate[i]);
string a(operate[i]);
len=a.size();
int ll=15-len;
for(int t=0; t<ll; t++)
fputs(" ",f1);
fputs("4",f1);
x++;
//cout<<operate[i]<<endl;
}
}
}
///***************************************************************
void getSym()
{
openfile();//ļ
for(x=0; x<=length-1;)
{
//cout<<getsym[82]<<endl;
f=0;//־ʼ
memset(A,'\0',20*sizeof(char));
delete_blank();
//*************жϵǰDzĸ
if(x<length&&getsym[x]>='a'&&getsym[x]<='z')
character();
else//ǰʴĸͷx>=length
{
if(x>=length)
break;
else if(getsym[x]>='0'&&getsym[x]<='9')//Ƿ09ͷ
Number();
else//ǰַǹؼ/ʶ/
{
//***жϵǰDzǷֽ*********
f=0;
memset(A,'\0',20*sizeof(char));
A[0]=getsym[x];
for(i=0; i<8; i++)
{
if(strcmp(A,border[i])==0)
{
f=1;
break;
}
}
if(f)//ǰǷֽ
{
Border();
if(x==length-1)
break;
}
else//ǰǷֽߴ
{
//cout<<"*********************1\n";
Operate();
//cout<<"*********************2\n";
}
}
}
}
closefile();
}
void Read_filef1(char* s)
{
FILE* fp;
int f;
char c;
string Prog="";
if((fp=fopen(s,"r"))!=NULL)
{
fseek(fp,38,0);//˿ʼı־
while(!feof(fp))//˿ոسÿʷ
{
c=fgetc(fp);
if(c!=' '&&c!='\n')
Prog+=c;
else
{
while(c==' '||c=='\n')
c=fgetc(fp);
Prog+='\0';
Array[Len++]=Prog;
Prog="";
Prog+=c;
}
}
Array[Len++]=Prog;
}
fclose(fp);
for(int j=0;j<Len;j++)
cout<<Array[j]<<endl;
}
char procede(char theta1,char theta2)//Ƚַȼ
{
int row,col;
char ch[10]="%=+-*/()#";
char R[9][10]={{">>>>>><>>"},{"</<<<<</>"},{"</>><<<>>"},{"</>><<<>>"},{">/>>>><>>"},{">/>>>><>>"},{"</<<<<<=/"},{">/>>>>/>>"},{"<<<<<<</="}};
for(int i=0;i<9;i++)
if(ch[i]==theta1)
{
row=i;
break;
}
for(int i=0;i<9;i++)
if(ch[i]==theta2)
{
col=i;
break;
}
if(row<9&&col<9)
return R[row][col];
else
return '/';
}
bool Is_ZM(char c)
{
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9'))
return true;
return false;
}
void CLEAR(stack<char> sta)
{
while(!sta.empty())
sta.pop();
}
void Num_Str(int x,string& mm)
{
int c=0;
char* sss;
while(1)
{
sss[c++]=(x%10)+'0';
x=x/10;
if(x==0)
break;
}
c--;
for(;c>=0;)
mm+=sss[c--];
//cout<<mm<<endl;
}
void Biaodashi(string infixexp)//ɱʽԪʽ
{
//infixexp=infixexp.substr(2);
infixexp+='#';
//cout<<infixexp<<endl;
stack<char> s;
stack<char> sp;
CLEAR(s);
CLEAR(sp);
char w,topelement;
int i=0,j=0,h=0;
s.push('#');
w=infixexp[i];
while(!s.empty())
{
//string y,y1,y2;
//cout<<"w = "<<w<<endl;
if(Is_ZM(w))
{
//cout<<"sp.top()="<<w<<endl;
sp.push(w);
i=i+2;
w=infixexp[i];
}
else
{
topelement=s.top();
switch(procede(topelement,w))
{
case '>':
{
string y="",y1="",y2="";
char c,c1,c2;
c=s.top();
y+=c;
s.pop();
//cout<<"****************8\n";
c1=sp.top();
y1+=c1;
sp.pop();
//cout<<"****************9\n";
c2=sp.top();
y2+=c2;
sp.pop();
//cout<<" y1.length ="<<y1.length()<<endl;
//cout<<"y1="<<y1<<" y2="<<y2<<endl;
Si[Begin].op=y;
Si[Begin].w1=y1;
if(c=='=')
{
Si[Begin].w2="-";
Si[Begin++].step=y2;
}
else
{
Si[Begin].w2=y2;
//Num_Str(Begin+1,u);
Si[Begin++].step='A'+h;
sp.push('A'+h);
h++;
}
break;
}
case '=':{
s.pop();
if(w!='#')
{
i=i+2;
w=infixexp[i];
}
break;
}
case '<':{//cout<<"****************3\n";
s.push(w);
i=i+2;
w=infixexp[i];
break;
}
case '/':cout<<"************4\n";
break;
default:cout<<"ʽǷ"<<endl;
}
}
}
//cout<<postfixexp<<endl;
}
void cout_Si(int i)
{
cout<<"("<<i<<")";
if(i>0&&i<=9)
cout<<" "<<setw(5);
else if(i>=10&&i<=99)
cout<<" "<<setw(4);
else
cout<<setw(3);
cout<<Si[i].op<<","<<Si[i].w1<<" ,"<<Si[i].w2<<" ,"<<Si[i].step<<endl;//жһΪʱ
}
void Manage_if(int L,int R,int M)//LΪʽߣRΪifĽMelseĽ
{
//cout<<"***************2\n";
Si[Begin].op=Array[L+2];
Si[Begin].w1=Array[L];
Si[Begin].w2=Array[L+4];
string yy="";
//cout<<Begin<<endl;
Num_Str(Begin+2,yy);
yy+='\0';
//cout<<yy<<endl;
Si[Begin].step=yy;
cout_Si(Begin++);
//cout<<"("<<Begin++<<")"<<setw(5)<<"( "<<Array[L+2]<<","<<Array[L]<<","<<Array[L+4]<<Begin+1<<")"<<endl;//жһΪʱ
Si[Begin].op="J--";
Si[Begin].w1="-";
Si[Begin].w2="-";
int m=Begin++;//¼ʽΪʱԪʽ
L=L+10;
while(L<R)//ΪʱĴ
{
string exp1="";
while(Array[L][0]!=';')
{
exp1+=Array[L];
L=L+2;
}
//cout<<exp1<<endl;
Biaodashi(exp1);
if(Array[L+2][0]=='}')
break;
else
L=L+2;
}
Si[Begin].op="J-";//ΪִҪȥ
Si[Begin].w1="-";
Si[Begin].w2="-";
int nn=Begin++;
yy="";
Num_Str(Begin,yy);
yy+='\0';
//cout<<"Begin ="<<Begin<<"yy ="<<yy<<endl;
Si[m].step=yy;//Ϊ洦֪ΪʱҪȥ
L=L+8;
while(Array[L][0]!='}')
{
string exp1="";
while(Array[L][0]!=';')
{
exp1+=Array[L];
L=L+2;
}
Biaodashi(exp1);
if(Array[L+2][0]=='}')
break;
else
L=L+2;
}
yy="";
Num_Str(Begin,yy);
yy+='\0';
//cout<<"Begin ="<<Begin<<yy<<endl;
Si[nn].step=yy;
for(int i=m;i<Begin;i++)
cout_Si(i);
}
void Manage_While(int l,int r)
{
int i=l+4;
int m=Begin;
Si[Begin].op=Array[i+2];
Si[Begin].w1=Array[i];
Si[Begin].w2=Array[i+4];
string mm="";
Num_Str(Begin+2,mm);
Si[Begin].step=mm;//whileΪʱ
cout_Si(Begin++);
Si[Begin].op="J--";//whileΪʱ
Si[Begin].w1="-";
Si[Begin].w2="-";
m=Begin++;
int L=i+10;
while(Array[L][0]!='}')
{
string exp1="";
while(Array[L][0]!=';')
{
exp1+=Array[L];
L=L+2;
}
Biaodashi(exp1);
if(Array[L+2][0]=='}')
break;
else
L=L+2;
}
mm="";
Num_Str(Begin,mm);
Si[m].step=mm;
for(i=m;i<Begin;i++)
cout_Si(i);
}
void Expression()
{
cout<<"Ԫʽ\n";
for(int i=10;i<Len;)
{
if(Array[i+1][0]=='1')//ʾǹؼ
{
//cout<<"***************3\n";
switch (Array[i][0])
{
//cout<<"***************2\n";
case 'i'://ʱΪint ,if
if(Array[i][1]=='n')
{
Si[Begin].op="int";
Si[Begin].w1="-";
Si[Begin].w2="-";
Si[Begin].step=Array[i+2];
//cout<<"("<<Begin++<<")"<<setw(5)<<"---,--,--,"<<Array[i+2]<<endl;//ĵһ
cout_Si(Begin++);
i=i+6;
while(Array[i][0]!=';')
{
if(Array[i][0]==',')
i=i+2;
Si[Begin].op="int";
Si[Begin].w1="-";
Si[Begin].w2="-";
Si[Begin].step=Array[i];
//cout<<"("<<Begin++<<")"<<setw(5)<<"---,--,--,"<<Array[i+2]<<endl;
cout_Si(Begin++);
i=i+2;
}
i=i+2;
}
else
{
int L=i+4,R,M,j;
for(j=i+6;Array[j][0]!='}';j++);
R=j-1;
for(j=j+6;Array[j][0]!='}';j++);
M=j-1;
Manage_if(L,R,M);//if
i=M+3;
}
break;
case 'w':
//cout<<"$$$$$$$$$$$$$$$$$$$$$$$$46\n";
int j,r;
for(j=i;Array[j][0]!='}';j++);
r=j-1;
//cout<<"$$$$$$$$$$$$$$$$$$$$$$1\n";
Manage_While(i,r);
//cout<<"$$$$$$$$$$$$$$$$$$$$$$2\n";
i=j+2;
break;
case 'r':
return ;
}
}
else if(Array[i+1][0]=='2')//ʶ
{
//cout<<"***************5";
string exp1="";
while(Array[i][0]!=';')
{
exp1+=Array[i];
i=i+2;
}
int x=Begin;
Biaodashi(exp1);
for(int i=x;i<Begin;i++)
cout_Si(i);
i=i+2;
//cout<<Array[i]<<endl;
}
//cout<<"!!!!!!!!!!!";
}
}
/********************************Ԫʽдļ***************/
void Write_tofile()
{
FILE * fp;
if((fp=fopen("Ԫʽ.txt","w"))==NULL)
{
cout<<"Failure to open Ԫʽ.txt\n";
exit(0);
}
fwrite(Si,sizeof(struct Siyuan),Begin-1,fp);
fclose(fp);
}
/********************************дļ***************/
void Write_file()
{
FILE * fp;
if((fp=fopen(".txt","w"))==NULL)
{
cout<<"Failure to open .txt\n";
exit(0);
}
fwrite(Goal,sizeof(struct Goal),Begin-1,fp);
fclose(fp);
}
/****************************Ŀ**********************/
void INITT(int x,string g1,string g2,string g3)
{
Goal[start].step=x;
Goal[start].G1=g1;
Goal[start].G2=g2;
Goal[start].G3=g3;
start++;
}
///*************************ַת*******************/
int StrtoNum(string ss)
{
int num;
stringstream s1(ss);
s1>>num;
return num;
}
/*************************תַ*******************/
string NumtoStr(int x)
{
stringstream ss;
ss<<x;
return ss.str();
}
void cout_G(int i)
{
cout<<Goal[i].step<<" : "<<Goal[i].G1<<" "<<Goal[i].G2<<" "<<Goal[i].G3<<endl;
}
void Goal_Prog()
{
cout<<":"<<endl;
for(int i=0;i<Begin;i++)
{
switch (Si[i].op[0])
{
case 'i':
INITT(END++,"DW",Si[i].step,"");
cout_G(start-1);
break;
case '=':
INITT(END++,"MOV",Si[i].step,Si[i].w1);
cout_G(start-1);
break;
case '+':
INITT(END++,"MOV","AX",Si[i].w2);
cout_G(start-1);
INITT(END++,"ADD","AX",Si[i].w1);
cout_G(start-1);
INITT(END++,"MOV",Si[i].step,"AX");
cout_G(start-1);
break;
case '-':
INITT(END++,"CMP",Si[i].w2,Si[i].w1);
cout_G(start-1);
END++;
INITT(END,"JNC","",NumtoStr(END+3));
cout_G(start-1);
INITT(END++,"SBB",Si[i].w2,Si[i].w1);
cout_G(start-1);
INITT(END++,"JMP","",NumtoStr(END+2));
cout_G(start-1);
INITT(END++,"SUB",Si[i].w2,Si[i].w1);
cout_G(start-1);
break;
case '*':
INITT(END++,"MOV","AX",Si[i].w2);
cout_G(start-1);
INITT(END++,"IMUL","",Si[i].w1);
cout_G(start-1);
INITT(END++,"MOV",Si[i].step,"AX");
cout_G(start-1);
case '/':
INITT(END++,"MOV","AX",Si[i].w2);
cout_G(start-1);
INITT(END++,"IDIV","",Si[i].w1);
cout_G(start-1);
INITT(END++,"MOV",Si[i].step,"AX");
cout_G(start-1);
break;
case '%':
INITT(END++,"MOV","AX",Si[i].w2);
cout_G(start-1);
INITT(END++,"IDIV","",Si[i].w1);
cout_G(start-1);
INITT(END++,"MOV",Si[i].step,"DX");
cout_G(start-1);
break;
case '>':
INITT(END++,"CMP",Si[i].w1,Si[i].w2);
cout_G(start-1);
break;
case 'J':
INITT(END++,"JC","",NumtoStr(END+StrtoNum(Si[i].step)-i));
cout_G(start-1);
break;
}
}
}
void function()
{
char* s="1.txt";
Read_file(s,getsym);//ȡ
length=getsym.size();
getSym();//
s="f1.txt";
Read_filef1(s);
Expression();
Write_tofile();
Goal_Prog();
Write_file();
//cout<<Begin<<endl;
//cout<<"$$$$$$$$$$$$$4\n";
}
int main()
{
function();
return 0;
}
| true |
939349ef6e67a05e7b11be8bc95342ee078eebd8 | C++ | xrj-sysu/hdu_submit | /hdu2473.cpp | UTF-8 | 1,394 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<set>
#include<cstdio>
using namespace std;
// 题目给的n的大小是骗人的
// the key is to open the b array. I have tried add a new value but failed.
int a[1000005];
int b[1000005];
void init(int n) {
for (int i = 0; i < n; ++i) {
a[i] = i;
b[i] = i;
}
}
int find(int x) {
if (x == a[x]) {
return x;
} else {
a[x] = find(a[x]);
return a[x];
}
}
void merge(int m, int n) {
int x = find(m);
int y = find(n);
if (x == y) {
return;
} else {
a[x] = y;
}
}
int main() {
int n, m, p, q, i, ans, temp;
char c;
int count = 0;
while (scanf("%d%d", &n, &m)) {
count++;
if (n == 0 && m == 0) {
break;
}
init(n);
ans = 0;
temp = n;
while (m--) {
getchar();
scanf("%c", &c);
if (c == 'M') {
scanf("%d%d", &p, &q);
merge(b[p], b[q]);
}
if (c == 'S') {
scanf("%d", &p);
b[p] = temp;
a[temp] = temp;
temp++;
}
}
set<int> myset;
for (i = 0; i < n; ++i) {
myset.insert(find(b[i]));
}
ans = myset.size();
printf("Case #%d: %d\n", count, ans);
}
return 0;
}
| true |
bc073ea5d6f68dad06ec5ada4e2999c7f1feeb50 | C++ | CreepyCreature/Simple3D | /simple3d/src/gfx/ShaderProgram.cpp | UTF-8 | 5,396 | 3.09375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "ShaderProgram.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
ShaderProgram::ShaderProgram()
{
program_ = glCreateProgram();
}
// When passing the Program by value it gets destroyed and deletes
// eveything from the actual Program. Check for this!
ShaderProgram::~ShaderProgram()
{
std::cout << "DESTROYING SHADER PROGRAM!" << std::endl;
glDeleteProgram(program_);
for (GLint i = 0; i < attached_shaders_.size(); ++i)
{
glDetachShader(program_, attached_shaders_.at(i));
glDeleteShader(attached_shaders_.at(i));
}
}
GLboolean ShaderProgram::LoadFromFile(const GLchar * filepath, ShaderStage stage)
{
std::string sh_source_str;
std::ifstream sh_file;
sh_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
sh_file.open(filepath);
std::stringstream sh_stream;
sh_stream << sh_file.rdbuf();
sh_file.close();
sh_source_str = sh_stream.str();
}
catch (std::ifstream::failure ex)
{
std::cout << "ShaderProgram: error reading file!" << std::endl;
}
return LoadShader(sh_source_str, stage);
}
GLboolean ShaderProgram::LoadShader(const std::string& sh_source_str, ShaderStage stage)
{
// Create an empty shader handle
GLuint shader = glCreateShader((GLuint)stage);
// Send the shader source code to GL
const GLchar* sh_source = sh_source_str.c_str();
glShaderSource(shader, 1, &sh_source, NULL);
// Compile the shader
glCompileShader(shader);
// Check if the shader compiled successfully
GLint compilation_ok = GL_FALSE;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compilation_ok);
if (compilation_ok == GL_FALSE)
{
// Get the length of the log string
GLint maxlen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxlen);
// Get the log string
std::vector<GLchar> infolog(maxlen);
glGetShaderInfoLog(shader, maxlen, &maxlen, &infolog[0]);
// Delete the shader
glDeleteShader(shader);
// Print something useful
std::cout << "ShaderProgram: error compiling shader";
switch (stage)
{
case ShaderProgram::ShaderStage::VERTEX_SHADER:
std::cout << " (VERTEX_SHADER): " << std::endl;
break;
case ShaderProgram::ShaderStage::GEOMETRY_SHADER:
std::cout << " (GEOMETRY_SHADER): " << std::endl;
break;
case ShaderProgram::ShaderStage::FRAGMENT_SHADER:
std::cout << " (FRAGMENT_SHADER): " << std::endl;
break;
case ShaderProgram::ShaderStage::COMPUTE_SHADER:
std::cout << " (COMPUTE_SHADER): " << std::endl;
break;
default:
std::cout << " (UNKNOWN): " << std::endl;
break;
}
std::cout << &infolog[0];
return GL_FALSE;
}
// If all is well attach the shader to the program
glAttachShader(program_, shader);
attached_shaders_.push_back(shader);
return GL_TRUE;
}
GLboolean ShaderProgram::Link()
{
// Check if any shaders are attached, if not, do nothing
if (attached_shaders_.empty())
{
return GL_FALSE;
}
// Link the program
glLinkProgram(program_);
// Check for errors
GLint link_ok = GL_FALSE;
glGetProgramiv(program_, GL_LINK_STATUS, &link_ok);
if (link_ok == GL_FALSE)
{
// Get the lenth of the info log
GLint maxlen = 0;
glGetProgramiv(program_, GL_INFO_LOG_LENGTH, &maxlen);
// Get the info log
std::vector<GLchar> infolog(maxlen);
glGetProgramInfoLog(program_, maxlen, &maxlen, &infolog[0]);
// Delete the program and any attached shaders
glDeleteProgram(program_);
for (GLint i = 0; i < attached_shaders_.size(); ++i)
{
glDeleteShader(attached_shaders_.at(i));
}
attached_shaders_.resize(0);
// Recreate the program
program_ = glCreateProgram();
// Print something useful
std::cout << "ShaderProgram: error linking the attached shaders:"
<< std::endl << &infolog[0];
return GL_FALSE;
}
// If all is ok then detach and delete the shaders
for (GLint i = 0; i < attached_shaders_.size(); ++i)
{
glDetachShader(program_, attached_shaders_.at(i));
glDeleteShader(attached_shaders_.at(i));
}
attached_shaders_.resize(0);
// Load some common uniform locations
model_uniform_ = GetModelUniformLocation() ;
view_uniform_ = GetViewUniformLocation() ;
projection_uniform_ = GetProjectionUniformLocation() ;
view_position_uniform_ = GetViewPositionUniformLocation() ;
return GL_TRUE;
}
GLvoid ShaderProgram::Bind() const
{
glUseProgram(program_);
}
GLvoid ShaderProgram::Unbind() const
{
glUseProgram(0);
}
GLuint ShaderProgram::ID() const
{
return program_;
}
GLuint ShaderProgram::ModelUniformLocation() const
{
return model_uniform_;
}
GLuint ShaderProgram::ViewUniformLocation() const
{
return view_uniform_;
}
GLuint ShaderProgram::ProjectionUniformLocation() const
{
return projection_uniform_;
}
GLuint ShaderProgram::ViewPositionUniformLocation() const
{
return view_position_uniform_;
}
GLuint ShaderProgram::GetModelUniformLocation()
{
return glGetUniformLocation(program_, "u_model");
}
GLuint ShaderProgram::GetViewUniformLocation()
{
return glGetUniformLocation(program_, "u_view");
}
GLuint ShaderProgram::GetProjectionUniformLocation()
{
return glGetUniformLocation(program_, "u_projection");
}
GLuint ShaderProgram::GetViewPositionUniformLocation()
{
return glGetUniformLocation(program_, "u_viewpos");
}
GLvoid ShaderProgram::SetUniform1i(const GLchar* uniform_name, GLint value)
{
Bind();
glUniform1i(
glGetUniformLocation(program_, uniform_name),
value
);
Unbind();
} | true |
9b9709f6442c4a99b5af1fd50eaa0bb6779d8ef3 | C++ | kimichang/Algorithm | /algorithm/leetcode/test.cpp | UTF-8 | 1,347 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <exception>
class father
{
public:
std::string name;
virtual std::string getName(){return this->name; };
father(std::string s = "father"){ name = s;};
};
class son : public father
{
std::string getName(){ return "son";};
};
class mother
{
};
struct s1
{
char *ptr,ch; //有指针变成4+4
union //后面跟了A定义了一个类型,不占内存,而后面不跟A,是声明了结构体的一个成员,占内存,
{
short a,b;
unsigned int c:2, d:1;
};
struct s1* next; //指针占4
};//这样是8+4=12个字节
struct t
{
uint8_t aa;
uint8_t ab;
uint16_t ac;
uint32_t ag;
char si[0];
};
int main()
{
std::cout << sizeof(s1) << std::endl;
std::cout << sizeof(t) << std::endl;
#ifdef __cplusplus
std::cout << "c++";
#else
std::cout << "C";
#endif
son* s = new son();
son& b = *s;
father* f = dynamic_cast<father*>(s);//new son();
std::cout << f->getName() << std::endl;
mother* m = dynamic_cast<mother*>(s);
try{
mother& mm = dynamic_cast<mother&>(b);
}catch(std::bad_cast& e)
{
std::cout << e.what() << std::endl;
}
const int aa = 0;
std::cout << aa << std::endl;
int ae = 5,ab = 7,c;
c = ae+++ab;
std::cout << c << std::endl;
}
| true |
bb1586328fa1e356b536e72b1feeb1ca472bab8e | C++ | ricpersi/ClickHouse | /dbms/src/Functions/FunctionsJSON.h | UTF-8 | 7,640 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <Functions/IFunction.h>
#include <Common/config.h>
#if USE_SIMDJSON
#include <Columns/ColumnConst.h>
#include <Columns/ColumnString.h>
#include <DataTypes/DataTypeFactory.h>
#include <Common/typeid_cast.h>
#include <ext/range.h>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wnewline-eof"
#endif
#include <simdjson/jsonparser.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int CANNOT_ALLOCATE_MEMORY;
extern const int ILLEGAL_COLUMN;
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
}
template <typename Impl, bool ExtraArg>
class FunctionJSONBase : public IFunction
{
private:
enum class Action
{
key = 1,
index = 2,
};
mutable std::vector<Action> actions;
mutable DataTypePtr virtual_type;
bool tryMove(ParsedJson::iterator & pjh, Action action, const Field & accessor)
{
switch (action)
{
case Action::key:
if (!pjh.is_object() || !pjh.move_to_key(accessor.get<String>().data()))
return false;
break;
case Action::index:
if (!pjh.is_object_or_array() || !pjh.down())
return false;
int steps = accessor.get<Int64>();
if (steps > 0)
steps -= 1;
else if (steps < 0)
{
steps += 1;
ParsedJson::iterator pjh1{pjh};
while (pjh1.next())
steps += 1;
}
else
return false;
for (const auto i : ext::range(0, steps))
{
(void)i;
if (!pjh.next())
return false;
}
break;
}
return true;
}
public:
static constexpr auto name = Impl::name;
static FunctionPtr create(const Context &) { return std::make_shared<FunctionJSONBase>(); }
String getName() const override { return Impl::name; }
bool isVariadic() const override { return true; }
size_t getNumberOfArguments() const override { return 0; }
bool useDefaultImplementationForConstants() const override { return true; }
DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
{
if constexpr (ExtraArg)
{
if (arguments.size() < 2)
throw Exception{"Function " + getName() + " requires at least two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH};
auto col_type_const = typeid_cast<const ColumnConst *>(arguments[1].column.get());
if (!col_type_const)
throw Exception{"Illegal non-const column " + arguments[1].column->getName() + " of argument of function " + getName(),
ErrorCodes::ILLEGAL_COLUMN};
virtual_type = DataTypeFactory::instance().get(col_type_const->getValue<String>());
}
else
{
if (arguments.size() < 1)
throw Exception{"Function " + getName() + " requires at least one arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH};
}
if (!isString(arguments[0].type))
throw Exception{"Illegal type " + arguments[0].type->getName() + " of argument of function " + getName(),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT};
actions.reserve(arguments.size() - 1 - ExtraArg);
for (const auto i : ext::range(1 + ExtraArg, arguments.size()))
{
if (isString(arguments[i].type))
actions.push_back(Action::key);
else if (isInteger(arguments[i].type))
actions.push_back(Action::index);
else
throw Exception{"Illegal type " + arguments[i].type->getName() + " of argument of function " + getName(),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT};
}
if constexpr (ExtraArg)
return Impl::getType(virtual_type);
else
return Impl::getType();
}
void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result_pos, size_t input_rows_count) override
{
MutableColumnPtr to{block.getByPosition(result_pos).type->createColumn()};
to->reserve(input_rows_count);
const ColumnPtr & arg_json = block.getByPosition(arguments[0]).column;
auto col_json_const = typeid_cast<const ColumnConst *>(arg_json.get());
auto col_json_string
= typeid_cast<const ColumnString *>(col_json_const ? col_json_const->getDataColumnPtr().get() : arg_json.get());
if (!col_json_string)
throw Exception{"Illegal column " + arg_json->getName() + " of argument of function " + getName(), ErrorCodes::ILLEGAL_COLUMN};
const ColumnString::Chars & chars = col_json_string->getChars();
const ColumnString::Offsets & offsets = col_json_string->getOffsets();
size_t max_size = 1;
for (const auto i : ext::range(0, input_rows_count))
if (max_size < offsets[i] - offsets[i - 1] - 1)
max_size = offsets[i] - offsets[i - 1] - 1;
ParsedJson pj;
if (!pj.allocateCapacity(max_size))
throw Exception{"Can not allocate memory for " + std::to_string(max_size) + " units when parsing JSON",
ErrorCodes::CANNOT_ALLOCATE_MEMORY};
for (const auto i : ext::range(0, input_rows_count))
{
bool ok = json_parse(&chars[offsets[i - 1]], offsets[i] - offsets[i - 1] - 1, pj) == 0;
ParsedJson::iterator pjh{pj};
for (const auto j : ext::range(0, actions.size()))
{
if (!ok)
break;
ok = tryMove(pjh, actions[j], (*block.getByPosition(arguments[j + 1 + ExtraArg]).column)[i]);
}
if (ok)
{
if constexpr (ExtraArg)
to->insert(Impl::getValue(pjh, virtual_type));
else
to->insert(Impl::getValue(pjh));
}
else
{
if constexpr (ExtraArg)
to->insert(Impl::getDefault(virtual_type));
else
to->insert(Impl::getDefault());
}
}
block.getByPosition(result_pos).column = std::move(to);
}
};
}
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
}
template <typename Impl>
class FunctionJSONDummy : public IFunction
{
public:
static constexpr auto name = Impl::name;
static FunctionPtr create(const Context &) { return std::make_shared<FunctionJSONDummy>(); }
String getName() const override { return Impl::name; }
bool isVariadic() const override { return true; }
size_t getNumberOfArguments() const override { return 0; }
DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName &) const override
{
throw Exception{"Function " + getName() + " is not supported without AVX2", ErrorCodes::NOT_IMPLEMENTED};
}
void executeImpl(Block &, const ColumnNumbers &, size_t, size_t) override
{
throw Exception{"Function " + getName() + " is not supported without AVX2", ErrorCodes::NOT_IMPLEMENTED};
}
};
}
| true |
3dfde306336130eb0282dd45a591e91024038001 | C++ | M4573R/UVa-Online-Judge-1 | /10394 - Twin Primes/10394 - Twin Primes.cpp | UTF-8 | 1,823 | 2.6875 | 3 | [] | no_license | //******************************************************************
// Coded by: Huynh Nhat Minh
// Problem Code: 10042 - Smith Numbers
// Verdict: Accepted
//******************************************************************
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <deque>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <cctype>
#define PI 3.1415926535897932384626433832795
#define read(x) scanf("%d",&x)
#define out(x) printf("%d\n",x)
#define DEBUG(x) cout << #x << " = " << x << endl
#define FOR(i,a,b) for(int i = a ; i <= b ; i++)
#define mp make_pair
#define ff first
#define ss second
#define pb push_back
#define maxN 20000000
#define INF 1000111222
#define int64 long long
using namespace std;
vector<int> primes;
bool check[maxN+5];
pair<int,int> ans[100005];
void sieve()
{
for(int i = 0 ; i <= maxN ; i++)
check[i] = true;
for(int64 i = 2 ; i <= maxN ; i++)
if(check[i])
{
primes.pb(i);
for(int64 j = i ; i*j <= maxN ; j++)
check[i*j] = false;
}
}
void pre_cal()
{
sieve();
int sz = primes.size();
int cnt = 1;
for(int i = 1 ; i < primes.size() && cnt < 100001 ; i++)
if(primes[i] - primes[i-1] == 2)
{
ans[cnt].ff = primes[i-1];
ans[cnt].ss = primes[i];
cnt++;
}
}
int main()
{
freopen("10394 - Twin Primes.INP","r",stdin);
freopen("10394 - Twin Primes.OUT","w",stdout);
pre_cal();
int n;
while(scanf(" %d ",&n) == 1)
{
printf("(%d, %d)\n",ans[n].ff,ans[n].ss);
}
return 0;
}
| true |
4a9b829f01a1db242d4aa3ebf7c558d649d5dd7a | C++ | ifknot/fbuf | /canvas_factory.h | UTF-8 | 11,742 | 2.859375 | 3 | [
"MIT"
] | permissive | #ifndef FBUF_CANVAS_FACTORY_H
#define FBUF_CANVAS_FACTORY_H
#if (defined (LINUX) || defined (__linux__))
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <string>
#include <sstream>
#include <stdexcept>
#include "dev/device.h"
namespace linux_util {
/**
* Raspberry Pi:
* HDMI map /dev/fb0 is double buffered
* SPI map /dev/fb1 and no double buffering due to hardware limitations
*/
enum screen_t {HDMI, SPI};
/**
* HDMI 24bit colour canvas - the factory creates a RAII double buffered memory mapping of the linux display screen buffer for simple graphics
* True colour 16,777,216 color variations
* @tparam HDMI
*/
template<screen_t HDMI>
class canvas_factory: public device {
const uint32_t DEFAULT_BPP = 32; //24bit colour + 8bit transparency - 16,777,216 colours
public:
/**
* 32-bits, 4 bytes per pixel
*/
using pixel_t = uint32_t;
/**
* Build a True Colour, double buffered, graphics canvas
* @param width desired width as pixels
* @param height desired height as pixels
* @param device_path defaults to "/dev/fb0"
*/
canvas_factory(size_t width, size_t height, const std::string device_path = "/dev/fb0"): device(device_path), width(width), height(height) {
initialize();
}
/**
* Safely RAII release memory resources
*/
virtual ~canvas_factory() {
deinitialize();
}
/**
* Set the active colour used by the graphics primitives
* @param r 8-bit red value
* @param g 8-bit green value
* @param b 8-bit blue value
* @param a 8-bit transparent value
*/
void rgb(pixel_t r, pixel_t g, pixel_t b, pixel_t a = 0xFF) {
colour = (r << vinfo.red.offset) | (g << vinfo.green.offset) | (b << vinfo.blue.offset) | (a << vinfo.transp.offset);
}
/**
* Clear the current active screen to black
* @note changes not visible until ```swap()```
*/
void clear() {
memset(screen1, 0u, screensize);
}
/**
* Draw a rectangular block of colour
* @note changes not visible until ```swap()```
* @param x
* @param y
* @param width
* @param height
*/
void fill(size_t x, size_t y, size_t width, size_t height) {
uint64_t c = colour;
c <<= vinfo.bits_per_pixel;
c |= colour;
size_t h{y + height};
size_t w{(x + width) >> 1}; // 2 x 32bit pixel_t per uint64_t
size_t linesize{finfo.line_length >> 3}; // 4 x 8bit bytes per pixel_t
size_t offset{y * linesize};
for(size_t i{y}; i < h; ++i) {
for (size_t j{(x >> 1)}; j < w; ++j) {
((uint64_t *) (screen1))[offset + j] = c;
}
offset += linesize;
}
}
/**
* Plot a single pixel current colour
* @note changes not visible until ```swap()```
* @param x
* @param y
*/
inline void pixel(uint x, uint y) {
((pixel_t *) (screen1))[(y * vinfo.xres) + x] = colour;
}
/**
* Fast horizontal line in current colour
* @note changes not visible until ```swap()```
* @param x
* @param y
* @param width
*/
void hline(size_t x, size_t y, size_t width) {
y *= vinfo.xres;
y += x;
for(size_t i{0}; i < width; ++i) {
((pixel_t *) (screen1))[y + i] = colour;
}
}
/**
* Fast vertical line in current colour
* @note changes not visible until ```swap()```
* @param x
* @param y
* @param height
*/
void vline(size_t x, size_t y, size_t height) {
y *= vinfo.xres;
y += x;
for(size_t i{0}; i < height; ++i) {
((pixel_t *) (screen1))[y] = colour;
y += vinfo.xres;
}
}
/**
* Draw a rectangle lines in current colour
* @note changes not visible until ```swap()```
* @param x
* @param y
* @param width
* @param height
*/
void rect(size_t x, size_t y, size_t width, size_t height) {
hline(x, y, width);
vline(x, y, height);
hline(x, y + height, width);
vline(x + width, y, height);
}
/**
* TODO Bresh. line algo
* @note changes not visible until ```swap()```
* @param x1
* @param y1
* @param x2
* @param y2
*/
void line(uint x1, uint y1, uint x2, uint y2) {
}
/**
* Swap the off-screen active working buffer into the visible inactive state
*/
void swap() {
vinfo.yoffset = (vinfo.yoffset == screen1_yoffset) ?screen2_yoffset :screen1_yoffset;
xioctl(FBIO_WAITFORVSYNC, 0);
xioctl(FBIOPAN_DISPLAY, &vinfo);
std::swap(screen1, screen2);
}
/**
* Get framebuffer variable screen info
* @note Omits obselete, timing & reserved info
* @return string - tabulated info
*/
std::string variable_info() {
xioctl(FBIOGET_VSCREENINFO, &vinfo); // acquire variable info
std::stringstream ss;
ss << "\nxres\t\t" << vinfo.xres // visible resolution
<< "\nyres\t\t" << vinfo.yres
<< "\nxres_virtual\t" << vinfo.xres_virtual // virtual resolution
<< "\nyres_virtual\t" << vinfo.yres_virtual
<< "\nxoffset\t\t" << vinfo.xoffset // offsets from virtual to visible resolution
<< "\nyoffset\t\t" << vinfo.yoffset
<< "\nbits_per_pixel\t" << vinfo.bits_per_pixel
<< "\nr shift\t\t" << vinfo.red.offset
<< "\ng shift\t\t" << vinfo.green.offset
<< "\nb shift\t\t" << vinfo.blue.offset
<< "\nt shift\t\t" << vinfo.transp.offset
<< "\ngrayscale\t" << vinfo.grayscale // 0 = color, 1 = grayscale, >1 = FOURCC
<< "\nnonstd\t\t" << vinfo.nonstd // != 0 non standard pixel format
<< "\nactivate\t" << vinfo.activate // e.g FB_ACTIVATE_NOW set values immediately (or vbl), FB_ACTIVATE_FORCE force apply even when no change
<< "\nheight\t\t" << vinfo.height << "mm" // height of picture in mm
<< "\nwidth\t\t" << vinfo.width << "mm\n"; // width of picture in mm
return ss.str();
}
/**
* Get framebuffer fixed screen info
* @return string - tabulated info
*/
std::string fixed_info() {
xioctl(FBIOGET_FSCREENINFO, &finfo);
std::stringstream ss;
ss << "\nid\t\t" << std::string(finfo.id); // identification string
ss << "\nmem start\t" << std::hex << finfo.smem_start // Start of frame buffer mem (physical address)
<< "\nmem length\t" << std::dec << finfo.smem_len << " bytes" // Length of frame buffer mem
<< "\ntype\t\t" << finfo.type
<< "\naux\t\t"<< finfo.type_aux // Interleave for interleaved Planes
<< "\nvisual\t\t"<< finfo.visual
<< "\nxpanstep\t"<< finfo.xpanstep // zero if no hardware panning
<< "\nypanstep\t"<< finfo.ypanstep // zero if no hardware panning
<< "\nywrapstep\t"<< finfo.ywrapstep // zero if no hardware ywrap
<< "\nline length\t"<< finfo.line_length // length of a line in bytes
<< "\nmap IO addr\t"<< std::hex << finfo.mmio_start // Start of Memory Mapped I/O (physical address)
<< "\nmap length\t"<< std::dec << finfo. mmio_len << " bytes" // Length of Memory Mapped I/O
<< "\naccel\t\t"<< finfo.accel // Indicate to driver which specific chip/card we have
<< "\ncapabilities\t"<< finfo.capabilities << "\n";
return ss.str();
}
private:
/**
* Change the screen resolution, bits per pixel, and set up 2 x virtual screens for the canvas
* @note canvas uses 2 new buffers and leaves the original screen buffer (screen0) unmolested
* @param width - visible screen dimensions
* @param height
*/
void initialize() override final {
xioctl(FBIOGET_VSCREENINFO, &vinfo); // acquire variable info
memcpy(&vinfo_old, &vinfo, sizeof(struct fb_var_screeninfo)); // copy current info for restore
vinfo.xres = width;
vinfo.yres = height;
screen1_yoffset = vinfo.yres;
screen2_yoffset = screen1_yoffset + vinfo.yres;
vinfo.xres_virtual = vinfo.xres;
vinfo.yres_virtual = vinfo.yres * 3; //make space for 2 virtual screens
vinfo.yoffset = screen2_yoffset; //so the first swap works correctly
vinfo.grayscale = 0; // ensure colour
vinfo.bits_per_pixel = DEFAULT_BPP;
vinfo.activate = FB_ACTIVATE_VBL;
xioctl(FBIOPUT_VSCREENINFO, &vinfo); // write new vinfo
xioctl(FBIOGET_VSCREENINFO, &vinfo); // re-acquire variable info
xioctl(FBIOGET_FSCREENINFO, &finfo); // acquire fixed info
screensize = vinfo.yres * finfo.line_length; // size of visible area
//memory map entire frame buffer of 3 x "screens"
screen0 = static_cast<uint8_t *>(mmap(0, finfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, device::fildes(), (off_t)0));
screen1 = screen0 + screensize; // offset each of the virtual screens
screen2 = screen1 + screensize;
}
/**
* Restore the original screen parameters from ```vinfo_old```
* @throws std::invalid_argument(strerror(errno))
*/
void deinitialize() override final {
xioctl(FBIOPUT_VSCREENINFO, &vinfo_old);
munmap(screen0, finfo.smem_len);
}
std::string device_path;
size_t width;
size_t height;
uint32_t screensize; //visible screen size bytes
//original screen & 2 virtual screen maps
uint8_t* screen0{0};
uint8_t* screen1{0};
uint8_t* screen2{0};
//offsets into the virtual screen memory maps
uint32_t screen1_yoffset;
uint32_t screen2_yoffset;
//colour used by graphic primitives
pixel_t colour;
/**
* Used to describe the features of a video card that are _user_ defined.
* With ```fb_var_screeninfo``` such as depth and the resolution can be defined.
*/
struct fb_var_screeninfo vinfo;
/**
* Original system vinfo for restore
*/
struct fb_var_screeninfo vinfo_old;
/**
* Defines the _fixed_ properties of a video card that are created when a mode is set.
* E.g. the start of the frame buffer memory - the address of the frame buffer memory cannot be changed or moved.
*/
struct fb_fix_screeninfo finfo;
};
}
#endif // __linux__
#endif //FBUF_CANVAS_FACTORY_H
| true |