text
stringlengths
8
6.88M
#include <iostream> using namespace std; int h = 0, w = 0; char canvas[51][51] = { 0 }; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; void dfs(int x, int y) { canvas[x][y] = 'B'; for (int i = 0; i < 4; i++) { if (x + dx[i] >= 0 && x + dx[i] < h && y + dy[i] >= 0 && y + dy[i] < w && canvas[x + dx[i]][y + dy[i]] == '#') { dfs(x + dx[i], y + dy[i]); } } } bool checkAroundTarget(int x, int y) { int flag = false; for (int i = 0; i < 4; i++) { if (canvas[x + dx[i]][y + dy[i]] == '#') { flag = true; break; } } return flag; } int main() { bool ans = true; cin >> h >> w; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { cin >> canvas[i][j]; } } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (canvas[i][j] == '#') { if (!checkAroundTarget(i, j)) { ans = false; break; } dfs(i, j); } } if (!ans) break; } cout << (ans ? "Yes" : "No") << endl; return 0; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int lengthOfLastWord(string s) { //基本思想:字符串从右往左遍历,去掉末尾空格,再计数出现空格前的非空格字符个数,就是最后一个单词长度 int res = 0, i = s.length() - 1; while (i >= 0 && s[i] == ' ') i--; while (i >= 0 && s[i--] != ' ') res++; return res; } }; int main() { Solution solute; string s = " hello world "; cout << solute.lengthOfLastWord(s) << endl; return 0; }
#ifndef GESTIONNAIREPLATEFORME_H #define GESTIONNAIREPLATEFORME_H #include "utilisateur.h" /** @brief La classe GestionnairePlateforme, hérite de @ref Utilisateur. ** ** Elle contient un constructeur, le nom, le prenom et les points de collecte aux quels il est abonné . ** ** @version 1 ** ** @author P. Marty, M. Labalette, A. Larcher **/ class GestionnairePlateforme : public Utilisateur { public: /// @brief Le constructeur par défaut attribue les valeurs passée en paramètre. /// /// Constructeur de la classe GestionnairePlateforme /// /// @param n nom de l'utilisateur /// @param pren prenom de l'utilisateur /// @param pc Points de collectes aux quels l'utilisateur est abonné GestionnairePlateforme(std::string n, std::string pren, std::vector<PointDeCollecte> pc, Application app); /// @brief procedure qui permet la création d'un point de controle selon le message envoyer /// /// @param m Message : message transmit /// @param accept bool : "feu vert" void repondreMessage(Message m, bool accept); /// @brief fonction qui regarde si c'est un utilisateur /// /// @return true si c'est un utilisateur false sinon bool estUtilisateur() { return false; }; /// @brief fonction qui regarde si c'est un GestionnairePlateforme /// /// @return true si c'est un GestionnairePlateforme false sinon bool estGestionnairePlateforme() { return true; }; ~GestionnairePlateforme(); }; #endif // GESTIONNAIREPLATEFORME_H
/* * node_car_detect.cpp * * This is the node to extract car states. * * Author: yubocheng@live.cn * * Copyright (c) 2019 Jimu * All rights reserved. * */ #include "node_car_detect.h" int main(int argc, char **argv) { ros::init(argc, argv, "car_extractor_node", ros::init_options::NoRosout); CarExtractorNode carExtractorNode; if (!carExtractorNode.Init()) return -1; while (ros::ok()) { ros::spinOnce(); } return 0; }
#include "CCGreePlatform.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxGreeRequestDialog.h" using namespace cocos2d; NS_CC_GREE_EXT_BEGIN CCGreeRequestDialog::CCGreeRequestDialog(void* obj){ mRequestDialog = obj; } CCGreeRequestDialog* CCGreeRequestDialog::create(){ jobject obj = createRequestDialogJni(); CCGreeRequestDialog* dialog = NULL; if(obj != NULL){ dialog = new CCGreeRequestDialog((void*)obj); dialog->autorelease(); dialog->retain(); } return dialog; } void CCGreeRequestDialog::setParams(CCDictionary *params){ if(params != NULL && mRequestDialog != NULL){ setRequestDialogParamsJni((jobject)mRequestDialog, params); } } void CCGreeRequestDialog::show(){ if(mRequestDialog != NULL){ setRequestDialogHandlerJni((jobject)mRequestDialog, (void*)this); showRequestDialogJni((jobject)mRequestDialog); } } void CCGreeRequestDialog::handleDialogOpened(){ CCGreeRequestDialogDelegate *delegate = CCGreePlatform::getRequestDialogDelegate(); if(delegate != NULL){ delegate->requestDialogOpened(this); } } void CCGreeRequestDialog::handleDialogCompleted(int count, const char** users){ CCGreeRequestDialogDelegate *delegate = CCGreePlatform::getRequestDialogDelegate(); if(delegate != NULL){ CCArray *userStringArray = new CCArray(); if(users != NULL){ for(int i = 0; i < count; i++){ CCString *str = new CCString(users[i]); str->autorelease(); userStringArray->addObject(str); } } delegate->requestDialogCompleted(this, userStringArray); delegate->requestDialogClosed(this); } } void CCGreeRequestDialog::handleDialogClosed(){ CCGreeRequestDialogDelegate *delegate = CCGreePlatform::getRequestDialogDelegate(); if(delegate != NULL){ delegate->requestDialogClosed(this); } } NS_CC_GREE_EXT_END
#pragma once #include <ResourcesManager.h> #include <OGLML/Shader.h> #include <string> namespace breakout { class ShadersManager : public ResourcesManager<oglml::Shader> { public: static ShadersManager& Get(); protected: virtual bool getFromFile(const std::string& path, oglml::Shader& resource) override; private: ShadersManager(); ~ShadersManager(); ShadersManager(ShadersManager&) = delete; ShadersManager(ShadersManager&&) = delete; void operator=(ShadersManager&) = delete; void operator=(ShadersManager&&) = delete; }; }
//include definition file #include "dataReader.h" #include <iostream> #include <fstream> #include <string.h> #include <math.h> #include <algorithm> using namespace std; using namespace cv; /******************************************************************* * Destructor ********************************************************************/ dataReader::~dataReader() { //clear data CLayer.clear(); for (int i=0; i < (int) data.size(); i++ ) delete data[i]; data.clear(); } /******************************************************************* * Loads a csv file of input data ********************************************************************/ bool dataReader::loadDataFile4Train( const char* filename, int nI, int nT ,float tratio, float gratio, bool method) { //clear any previous data for (int i=0; i < (int) data.size(); i++ ) delete data[i]; data.clear(); tSet.clear(); //set number of inputs and outputs nInputs = nI; nTargets = nT; //open file for reading fstream inputFile; inputFile.open(filename, ios::in); if ( inputFile.is_open() ) { string line = ""; //read data while ( !inputFile.eof() ) { // get num of line getline(inputFile, line); //process line if (line.length() > 2 ) processLine(line); } //print success cout << "Input File: " << filename << "\nRead Complete: " << data.size() << " Patterns Loaded" << endl; if (method == NML){ //normalize data double *buf[(int)nInputs]; vector <double> minVal, maxVal; ofstream maxmin("log/maxmin.csv"); for(int i=0; i < nInputs; i++) { buf[i] = new( double[(int)data.size()] ); double min=100000, max = 0; for(int j=0; j < (int)data.size(); j++) { double temp = (double)data[j]->pattern[i]; if (temp > max) max = temp; else if (temp < min) min = temp; buf[i][j] = temp; } minVal.push_back(min); maxVal.push_back(max); maxmin << min << "," << max << endl; } maxmin.close(); for(int ii=0; ii < nInputs; ii++) { for(int jj=0; jj < data.size(); jj++) { double diff = maxVal[ii]-minVal[ii]; if (diff==0) data[jj]->pattern[ii]=1.0; else data[jj]->pattern[ii]=(double)((buf[ii][jj]-minVal[ii])/diff); // normalization to 0~1 } }; } else{ //standardize data double* avg = new double[nInputs]; double* std = new double[nInputs]; for(int i=0; i < nInputs; i++) { Mat buf = Mat::zeros(1,(int)data.size(),CV_64FC1); for(int j=0; j < (int)data.size(); j++) buf.ATD(0,j) = data[j]->pattern[i]; Scalar mean, stddev; meanStdDev(buf,mean,stddev); avg[i]=mean[0]; std[i]=stddev[0]; } for(int ii=0; ii < nInputs; ii++) { for(int jj=0; jj < data.size(); jj++) { if (std[ii]!=0) data[jj]->pattern[ii]=(double)((data[jj]->pattern[ii]-avg[ii])/std[ii]); else data[jj]->pattern[ii]=(double)0.0f; } } delete[] avg; delete[] std; } //shuffle data random_shuffle(data.begin(), data.end()); //split data set trainingDataEndIndex = (int) ( tratio * data.size() ); int gSize = (int) ( ceil(gratio * data.size()) ); int vSize = (int) ( data.size() - trainingDataEndIndex - gSize ); //generalization set for ( int i = trainingDataEndIndex; i < trainingDataEndIndex + gSize; i++ ) tSet.generalizationSet.push_back( data[i] ); //validation set for ( int i = trainingDataEndIndex + gSize; i < (int) data.size(); i++ ) tSet.validationSet.push_back( data[i] ); //close file inputFile.close(); return true; } else { cout << "Error Opening Input File: " << filename << endl; return false; } } bool dataReader::loadImageFile4Train( const char* filename, int nI, int nT ,float tratio, float gratio, bool GAP) { //clear any previous data for (int i=0; i < (int) data.size(); i++ ) delete data[i]; data.clear(); tSet.clear(); //set number of inputs and outputs sImage = nI; nTargets = nT; //open file for reading fstream inputFile; inputFile.open(filename, ios::in); if ( inputFile.is_open() ) { string line = ""; //read data while ( !inputFile.eof() ) { // get num of line getline(inputFile, line); //process line if (line.length() > 2 ) processLine4Image(line); } //print success cout << "Input File: " << filename << "\nRead Complete: " << data.size() << " Patterns Loaded" << endl; // normalize and convolve data for(int jj=0; jj < data.size(); jj++) data[jj]-> pattern = ConvNPooling(data[jj]->pattern,sImage,GAP); //shuffle data random_shuffle(data.begin(), data.end()); //split data set trainingDataEndIndex = (int) ( tratio * data.size() ); int gSize = (int) ( ceil(gratio * data.size()) ); int vSize = (int) ( data.size() - trainingDataEndIndex - gSize ); //generalization set for ( int i = trainingDataEndIndex; i < trainingDataEndIndex + gSize; i++ ) tSet.generalizationSet.push_back( data[i] ); //validation set for ( int i = trainingDataEndIndex + gSize; i < (int) data.size(); i++ ) tSet.validationSet.push_back( data[i] ); //close file inputFile.close(); return true; } else { cout << "Error Opening Input File: " << filename << endl; return false; } } void dataReader::loadImage4Test(const Mat frame,int sI, int nT, bool GAP) { //clear any previous data for (int i=0; i < (int) data.size(); i++ ) delete data[i]; data.clear(); tSet.clear(); sImage = sI; nTargets = nT; processMat(frame,GAP); //validation set trainingDataEndIndex = (int)0; for ( int i = 0; i < (int) data.size(); i++ ) tSet.validationSet.push_back( data[i] ); } bool dataReader::maxmin( const char* filename) { //open file for maxmin value fstream maxminFile; maxminFile.open(filename, ios::in); if ( maxminFile.is_open() ) { string line2 = ""; cout << "ManMin Reference File Loaded" << endl; //read data while ( !maxminFile.eof() ) { // get num of line getline(maxminFile, line2); if (line2.length() > 2 ) processLine4maxmin(line2); //ref[i]->p_min } //close file maxminFile.close(); return true; } else { cout << "Error Opening MaxMin File " << endl; return false; } } /******************************************************************* * Processes a single line from the data file ********************************************************************/ void dataReader::processMat( const Mat frame, bool GAP ) { //create new pattern and target double* pattern = new double[sImage]; double* target = new double[nTargets]; frame.convertTo(frame, CV_64FC1, 1.0/255, 0); pattern = ConvNPooling(frame,GAP); for (int i=0; i<nTargets; i++) if ( i < sImage ) target[i] = 0; //add to records data.push_back( new dataEntry( pattern, target ) ); } void dataReader::processLine( string &line ) { //create new pattern and target double* pattern = new double[nInputs]; double* target = new double[nTargets]; //store inputs char* cstr = new char[line.size()+1]; char* t; strcpy(cstr, line.c_str()); //tokenise int i = 0; t=strtok (cstr,","); while ( t!=NULL && i < (nInputs + nTargets) ) { if ( i < nInputs ) pattern[i] = atof(t); else target[i - nInputs] = atof(t); //move token onwards t = strtok(NULL,","); i++; } //add to records data.push_back( new dataEntry( pattern, target ) ); } void dataReader::processLine4Image( string &line ) { //create new pattern and target double* pattern = new double[sImage]; double* target = new double[nTargets]; //store inputs char* cstr = new char[line.size()+1]; char* t; strcpy(cstr, line.c_str()); //tokenise int i = 0; t=strtok (cstr,","); while ( t!=NULL && i < (sImage + nTargets) ) { if ( i < sImage ) pattern[i] = atof(t); else target[i - sImage] = atof(t); //move token onwards t = strtok(NULL,","); i++; } //add to records data.push_back( new dataEntry( pattern, target ) ); } void dataReader::processLine4maxmin( string &line2 ) { //create new pattern and target double p_max = 0; double p_min = 0; //store inputs char* cstr = new char[line2.size()+1]; char* t; strcpy(cstr, line2.c_str()); //tokenise int i = 0; t=strtok (cstr,","); while ( t!=NULL && i < 2 ) { if ( i < 1 ) p_min = atof(t); else p_max = atof(t); //move token onwards t = strtok(NULL,","); i++; } //add to records ref.push_back( new reference( p_max, p_min ) ); } /******************************************************************* * Selects the data set creation approach ********************************************************************/ void dataReader::setCreationApproach( int approach, double param1, double param2 ) { //static if ( approach == STATIC ) { creationApproach = STATIC; //only 1 data set numTrainingSets = 1; } //growing else if ( approach == GROWING ) { if ( param1 <= 100.0 && param1 > 0) { creationApproach = GROWING; //step size growingStepSize = param1 / 100; growingLastDataIndex = 0; //number of sets numTrainingSets = (int) ceil( 1 / growingStepSize ); } } //windowing else if ( approach == WINDOWING ) { //if initial size smaller than total entries and step size smaller than set size if ( param1 < data.size() && param2 <= param1) { creationApproach = WINDOWING; //params windowingSetSize = (int) param1; windowingStepSize = (int) param2; windowingStartIndex = 0; //number of sets numTrainingSets = (int) ceil( (double) ( trainingDataEndIndex - windowingSetSize ) / windowingStepSize ) + 1; } } } /******************************************************************* * Returns number of data sets created by creation approach ********************************************************************/ int dataReader::getNumTrainingSets() { return numTrainingSets; } /******************************************************************* * Get data set created by creation approach ********************************************************************/ trainingDataSet* dataReader::getTrainingDataSet() { switch ( creationApproach ) { case STATIC : createStaticDataSet(); break; case GROWING : createGrowingDataSet(); break; case WINDOWING : createWindowingDataSet(); break; } return &tSet; } /******************************************************************* * Get all data entries loaded ********************************************************************/ vector<dataEntry*>& dataReader::getAllDataEntries() { return data; } /******************************************************************* * Create a static data set (all the entries) ********************************************************************/ void dataReader::createStaticDataSet() { //training set for ( int i = 0; i < trainingDataEndIndex; i++ ) tSet.trainingSet.push_back( data[i] ); } /******************************************************************* * Create a growing data set (contains only a percentage of entries * and slowly grows till it contains all entries) ********************************************************************/ void dataReader::createGrowingDataSet() { //increase data set by step percentage growingLastDataIndex += (int) ceil( growingStepSize * trainingDataEndIndex ); if ( growingLastDataIndex > (int) trainingDataEndIndex ) growingLastDataIndex = trainingDataEndIndex; //clear sets tSet.trainingSet.clear(); //training set for ( int i = 0; i < growingLastDataIndex; i++ ) tSet.trainingSet.push_back( data[i] ); } /******************************************************************* * Create a windowed data set ( creates a window over a part of the data * set and moves it along until it reaches the end of the date set ) ********************************************************************/ void dataReader::createWindowingDataSet() { //create end point int endIndex = windowingStartIndex + windowingSetSize; if ( endIndex > trainingDataEndIndex ) endIndex = trainingDataEndIndex; //clear sets tSet.trainingSet.clear(); //training set for ( int i = windowingStartIndex; i < endIndex; i++ ) tSet.trainingSet.push_back( data[i] ); //increase start index windowingStartIndex += windowingStepSize; } /////////////////////////////////////////////////////////////////////////////// Mat dataReader::Pooling(const Mat &M, int pVert, int pHori, int poolingMethod){ if(pVert == 1 && pHori == 1){ Mat res; M.copyTo(res); return res; } int remX = M.cols % pHori; int remY = M.rows % pVert; Mat newM; if(remX == 0 && remY == 0) M.copyTo(newM); else{ Rect roi = Rect(remX / 2, remY / 2, M.cols - remX, M.rows - remY); M(roi).copyTo(newM); } Mat res = Mat::zeros(newM.rows / pVert, newM.cols / pHori, CV_64FC1); for(int i=0; i<res.rows; i++){ for(int j=0; j<res.cols; j++){ Mat temp; Rect roi = Rect(j * pHori, i * pVert, pHori, pVert); newM(roi).copyTo(temp); double val = 0.0; // for Max Pooling if(POOL_MAX == poolingMethod){ double minVal = 0.0; double maxVal = 0.0; Point minLoc; Point maxLoc; minMaxLoc( temp, &minVal, &maxVal, &minLoc, &maxLoc ); val = maxVal; }elif(POOL_MEAN == poolingMethod){ // Mean Pooling val = sum(temp)[0] / (pVert * pHori); }elif(POOL_STOCHASTIC == poolingMethod){ // Stochastic Pooling double sumval = sum(temp)[0]; Mat prob = temp.mul(Reciprocal(sumval)); val = sum(prob.mul(temp))[0]; prob.release(); } res.ATD(i, j) = val; temp.release(); } } newM.release(); return res; } double* dataReader::ConvNPooling(double *pattern, int sImage, bool GAP) { int rows = (int)sqrt(sImage); Mat img(rows,rows,CV_64FC1); for(int j = 0; j < rows; j++) for(int i = 0; i < rows; i++) img.ATD(j, i) = (double)pattern[j*rows+i]; Mat kk = Mat::ones(6, 6, CV_8UC1); erode(img, img, kk); normalize(img,img, 0,255,NORM_MINMAX, CV_8UC1); img.convertTo(img, CV_64FC1, 1.0/255, 0); vector<vector<Mat>> conv(CLayer.size()+1); int count=1; for (int i = 0; i < CLayer.size()+1; i++) { conv[i].reserve(count); count = count * CLayer[i].Kernels.size(); } conv[0].push_back(img); for(int l=0; l<CLayer.size(); l++){ // Convolution and Pooling computation for(int n = 0; n < conv[l].size(); n++) { for(int k = 0; k < CLayer[l].Kernels.size(); k++) { Mat temp = rot90(CLayer[l].Kernels[k], 2); Mat tmpconv = convCalc(conv[l][n], temp, CONV_SAME); tmpconv = nonLinearity(tmpconv, CLayer[l].non_linear); tmpconv = Pooling(tmpconv, CLayer[l].pdim, CLayer[l].pdim, CLayer[l].pmethod); conv[l+1].push_back(tmpconv); // conv[l+1].size() == Kernelset.size() temp.release(); tmpconv.release(); } } if(CLayer[l].LRN==true) for(int k = 0; k < conv[l].size(); k++) normalize(conv[l][k],conv[l][k], 0,1,NORM_MINMAX, CV_64FC1); } int nPixel = conv[CLayer.size()][0].cols*conv[CLayer.size()][0].rows; double* conv_pattern = new( double[conv[CLayer.size()].size()*nPixel] ); if (GAP==true) { conv_pattern = (new(double[conv[CLayer.size()].size()])); for(int k = 0; k < conv[CLayer.size()].size(); k++) { Scalar meanVal = mean(conv[CLayer.size()][k]); double matMean = (double)meanVal.val[0]; conv_pattern[k] = matMean; } } else { conv_pattern = (new(double[conv[CLayer.size()].size()*nPixel])); for(int k = 0; k < conv[CLayer.size()].size(); k++) for(int j = 0; j < (int)sqrt(nPixel); j++) for(int i = 0; i < (int)sqrt(nPixel); i++) conv_pattern[k*nPixel+j*conv[CLayer.size()][k].rows+i] = conv[CLayer.size()][k].ATD(j,i); } for(int k = 0; k < conv.size(); k++) conv[k].clear(); conv.clear(); return conv_pattern; } double* dataReader::ConvNPooling(Mat pattern, bool GAP) { // Normalization pattern.convertTo(pattern, CV_64FC1, 1.0/255, 0); vector<vector<Mat>> conv(CLayer.size()+1); int count=1; for (int i = 0; i < CLayer.size()+1; i++) { conv[i].reserve(count); count = count * CLayer[i].Kernels.size(); } conv[0].push_back(pattern); for(int l=0; l<CLayer.size(); l++){ // Convolution and Pooling computation for(int n = 0; n < conv[l].size(); n++) { for(int k = 0; k < CLayer[l].Kernels.size(); k++) { Mat temp = rot90(CLayer[l].Kernels[k], 2); Mat tmpconv = convCalc(conv[l][n], temp, CONV_SAME); tmpconv = nonLinearity(tmpconv,CLayer[l].non_linear); tmpconv = Pooling(tmpconv, CLayer[l].pdim, CLayer[l].pdim, CLayer[l].pmethod); conv[l+1].push_back(tmpconv); // conv[l+1].size() == Kernelset.size() temp.release(); tmpconv.release(); } } } int nPixel = conv[CLayer.size()][0].cols*conv[CLayer.size()][0].rows; double* conv_pattern = new( double[conv[CLayer.size()].size()*nPixel] ); if (GAP==true) { conv_pattern = (new(double[conv[CLayer.size()].size()])); for(int k = 0; k < conv[CLayer.size()].size(); k++) { Scalar meanVal = mean(conv[CLayer.size()][k]); double matMean = (double)meanVal.val[0]; conv_pattern[k] = matMean; } } else { conv_pattern = (new(double[conv[CLayer.size()].size()*nPixel])); for(int k = 0; k < conv[CLayer.size()].size(); k++) for(int j = 0; j < (int)sqrt(nPixel); j++) for(int i = 0; i < (int)sqrt(nPixel); i++) conv_pattern[k*nPixel+j*conv[CLayer.size()][k].rows+i] = conv[CLayer.size()][k].ATD(j,i); } for(int k = 0; k < conv.size(); k++) conv[k].clear(); conv.clear(); return conv_pattern; } bool dataReader::loadKernels(const char* filename, vector<ConvLayer> CL) { CLayer.reserve(CL.size()); CLayer = CL; //open file for reading fstream inputFile; inputFile.open(filename, ios::in); if ( inputFile.is_open() ) { vector<double> weights; string line = ""; //read data while ( !inputFile.eof() ) { getline(inputFile, line); //process line if (line.length() > 2 ) { //store inputs char* cstr = new char[line.size()+1]; char* t; strcpy(cstr, line.c_str()); //tokenise int i = 0; t=strtok (cstr,","); while ( t!=NULL ) { weights.push_back( atof(t) ); //move token onwards t = strtok(NULL,","); i++; } //free memory delete[] cstr; } } //check if sufficient weights were loaded int num_weight = 0; for(int i=0; i<CLayer.size(); i++) num_weight = num_weight + (int)(CLayer[i].sKernel * CLayer[i].sKernel * CLayer[i].nKernel); if ( weights.size() != num_weight ) { cout << endl << "Error - Incorrect number of weights in input file: " << filename << endl; cout << "System requires " << num_weight << " and " << weights.size() << " put in " << endl; //close file inputFile.close(); return false; } else { //set weights int pos = 0; for(int l=0; l<CLayer.size(); l++){ for ( int k=0; k < CLayer[l].nKernel; k++ ) { Mat buf(CLayer[l].sKernel,CLayer[l].sKernel,CV_64FC1); for ( int j=0; j < CLayer[l].sKernel; j++ ) { for ( int i=0; i < CLayer[l].sKernel; i++ ) { buf.ATD(j,i) = weights[pos]; pos++; } } CLayer[l].Kernels.push_back(buf); buf.release(); } } //print success cout << endl << "Convolution Kernels loaded successfully from '" << filename << "'" << endl; //close file inputFile.close(); return true; } } else { cout << endl << "Error - Kernel input file '" << filename << "' could not be opened: " << endl; return false; } }
/*Дано два натуральних числа, знайти середнє геометричне */ #include <iostream> #include <cmath> using namespace std; int main() { cout << "Your number\n"; int a,b; cin >> a >> b ; cout << pow((a*b),0.5) << endl; return 0; }
// // Created by 송지원 on 2020-03-08. // #include <iostream> #define ABS(X) ((X)<0? (X)*(-1) : (X)) using namespace std; int num_list[101]; int prime_lists[101][1001]; int avg[1001]; int pow(int a, int b) { int ret = 1; for (int i=0; i<b; i++) { ret *= a; } return ret; } int get_diff(int num) { int diff = 0; int temp; for (int i=0; i<num; i++) { for (int j=0; j<1001; j++) { temp = avg[j] - prime_lists[i][j]; diff += ABS(temp); } } return diff; } int get_GCD(){ int ret = 1; for (int i=0; i<1001; i++) { if (avg[i] > 0) { ret *= pow(i, avg[i]); } } return ret; } void make_avg_prime(int num) { int total; for (int i=0; i<1001; i++) { total = 0; for (int j=0; j<101; j++) { total += prime_lists[j][i]; } total /= num; avg[i] = total; } } void check_prime(int index, int num) { int prime = 2; while (num/prime >= 1 /*&& prime*prime <= num*/) { if (num%prime == 0) { prime_lists[index][prime]++; num /= prime; } else { prime++; } } } void check_prime2(int index, int num) { for (int i=2; i*i <= num; i++) { while (num%i == 0) { prime_lists[index][i]++; num /= i; } } if (num > 1) { prime_lists[index][num]++; } } int main() { int N; scanf("%d", &N); for (int i=0; i<N; i++) { scanf("%d", &num_list[i]); check_prime2(i, num_list[i]); } // for (int i=0; i<N; i++) { // for (int j=0; j<1000; j++) { // printf("%d", prime_lists[i][j]); // } // printf("\n"); // } // printf("\n"); make_avg_prime(N); // for (int i=0; i<1000; i++) { // printf("%d", avg[i]); // } printf("%d %d\n", get_GCD(), get_diff(N)/2); return 0; }
#include <iostream> #include <vector> #include <algorithm> int main(int argc,char *argv[]) { int n; std::cin >> n; std::vector<int> v(n); for(int i = 0;i < n;i++) std::cin >> v[i]; std::sort(v.begin(),v.end(),std::greater<int>()); int ans = 0; for(int i = 0;i < n;i++) if(i%2) ans -= v[i]; else ans += v[i]; std::cout << ans << std::endl; return 0; }
#include "Health.h" using namespace uth; using namespace pmath; Health::Health() : Component("defaultHealth") , m_Health(0, 100, 100) { } Health::Health(float min, float max) : Component("Health") , m_Health(min, max, max) { } void Health::Init() { } void Health::Draw(uth::RenderTarget& target) { } void Health::Update(float delta) { }
#include "_pch.h" #include "CtrlActBrowser.h" using namespace wh; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- CtrlActBrowser::CtrlActBrowser( const std::shared_ptr<ViewActBrowser>& view , const std::shared_ptr<ModelActBrowserWindow>& model) :CtrlWindowBase(view, model) { namespace ph = std::placeholders; if (!view) return; connModel_BeforeRefresh = mModel->sigBeforeRefresh .connect(std::bind(&T_View::SetBeforeRefresh, mView.get(), ph::_1)); connModel_AfterRefresh = mModel->sigAfterRefresh .connect(std::bind(&T_View::SetAfterRefresh, mView.get(), ph::_1)); connModel_GetSelect = mModel->sigGetSelection .connect(std::bind(&T_View::GetSelection, mView.get(), ph::_1)); connViewCmd_Activate = mView->sigActivate .connect(std::bind(&CtrlActBrowser::Activate, this)); }; //--------------------------------------------------------------------------- void CtrlActBrowser::Activate() { mModel->DoActivate(); }
// Created on: 2016-06-23 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepMesh_ModelHealer_HeaderFile #define _BRepMesh_ModelHealer_HeaderFile #include <IMeshTools_ModelAlgo.hxx> #include <IMeshTools_Parameters.hxx> #include <IMeshData_Model.hxx> #include <TopoDS_Vertex.hxx> //! Class implements functionality of model healer tool. //! Iterates over model's faces and checks consistency of their wires, //! i.e.whether wires are closed and do not contain self - intersections. //! In case if wire contains disconnected parts, ends of adjacent edges //! forming the gaps are connected in parametric space forcibly. The notion //! of this operation is to create correct discrete model defined relatively //! parametric space of target face taking into account connectivity and //! tolerances of 3D space only. This means that there are no specific //! computations are made for the sake of determination of U and V tolerance. //! Registers intersections on edges forming the face's shape and tries to //! amplify discrete representation by decreasing of deflection for the target edge. //! Checks can be performed in parallel mode. class BRepMesh_ModelHealer : public IMeshTools_ModelAlgo { public: //! Constructor. Standard_EXPORT BRepMesh_ModelHealer(); //! Destructor. Standard_EXPORT virtual ~BRepMesh_ModelHealer(); //! Functor API to discretize the given edge. void operator() (const Standard_Integer theEdgeIndex) const { process(theEdgeIndex); } //! Functor API to discretize the given edge. void operator() (const IMeshData::IFaceHandle& theDFace) const { process(theDFace); } DEFINE_STANDARD_RTTIEXT(BRepMesh_ModelHealer, IMeshTools_ModelAlgo) protected: //! Performs processing of edges of the given model. Standard_EXPORT virtual Standard_Boolean performInternal ( const Handle(IMeshData_Model)& theModel, const IMeshTools_Parameters& theParameters, const Message_ProgressRange& theRange) Standard_OVERRIDE; private: //! Checks existing discretization of the face and updates data model. void process(const Standard_Integer theFaceIndex) const { const IMeshData::IFaceHandle& aDFace = myModel->GetFace(theFaceIndex); process(aDFace); } //! Checks existing discretization of the face and updates data model. void process(const IMeshData::IFaceHandle& theDFace) const; //! Amplifies discretization of edges in case if self-intersection problem has been found. void amplifyEdges(); //! Returns common vertex of two edges or null ptr in case if there is no such vertex. TopoDS_Vertex getCommonVertex( const IMeshData::IEdgeHandle& theEdge1, const IMeshData::IEdgeHandle& theEdge2) const; //! Connects pcurves of previous and current edge on the specified face //! according to topological connectivity. Uses next edge in order to //! identify closest point in case of single vertex shared between both //! ends of edge (degenerative edge) Standard_Boolean connectClosestPoints( const IMeshData::IPCurveHandle& thePrevDEdge, const IMeshData::IPCurveHandle& theCurrDEdge, const IMeshData::IPCurveHandle& theNextDEdge) const; //! Chooses the most closest point to reference one from the given pair. //! Returns square distance between reference point and closest one as //! well as pointer to closest point. Standard_Real closestPoint( gp_Pnt2d& theRefPnt, gp_Pnt2d& theFristPnt, gp_Pnt2d& theSecondPnt, gp_Pnt2d*& theClosestPnt) const { // Find the most closest end-points. const Standard_Real aSqDist1 = theRefPnt.SquareDistance(theFristPnt); const Standard_Real aSqDist2 = theRefPnt.SquareDistance(theSecondPnt); if (aSqDist1 < aSqDist2) { theClosestPnt = &theFristPnt; return aSqDist1; } theClosestPnt = &theSecondPnt; return aSqDist2; } //! Chooses the most closest points among the given to reference one from the given pair. //! Returns square distance between reference point and closest one as //! well as pointer to closest point. Standard_Real closestPoints( gp_Pnt2d& theFirstPnt1, gp_Pnt2d& theSecondPnt1, gp_Pnt2d& theFirstPnt2, gp_Pnt2d& theSecondPnt2, gp_Pnt2d*& theClosestPnt1, gp_Pnt2d*& theClosestPnt2) const { gp_Pnt2d *aCurrPrevUV1 = NULL, *aCurrPrevUV2 = NULL; const Standard_Real aSqDist1 = closestPoint(theFirstPnt1, theFirstPnt2, theSecondPnt2, aCurrPrevUV1); const Standard_Real aSqDist2 = closestPoint(theSecondPnt1, theFirstPnt2, theSecondPnt2, aCurrPrevUV2); if (aSqDist1 - aSqDist2 < gp::Resolution()) { theClosestPnt1 = &theFirstPnt1; theClosestPnt2 = aCurrPrevUV1; return aSqDist1; } theClosestPnt1 = &theSecondPnt1; theClosestPnt2 = aCurrPrevUV2; return aSqDist2; } //! Adjusts the given pair of points supposed to be the same. //! In addition, adjusts another end-point of an edge in order //! to perform correct matching in case of gap. void adjustSamePoints( gp_Pnt2d*& theMajorSamePnt1, gp_Pnt2d*& theMinorSamePnt1, gp_Pnt2d*& theMajorSamePnt2, gp_Pnt2d*& theMinorSamePnt2, gp_Pnt2d& theMajorFirstPnt, gp_Pnt2d& theMajorLastPnt, gp_Pnt2d& theMinorFirstPnt, gp_Pnt2d& theMinorLastPnt) const { if (theMajorSamePnt2 == theMajorSamePnt1) { theMajorSamePnt2 = (theMajorSamePnt2 == &theMajorFirstPnt) ? &theMajorLastPnt : &theMajorFirstPnt; closestPoint(*theMajorSamePnt2, theMinorFirstPnt, theMinorLastPnt, theMinorSamePnt2); } *theMajorSamePnt1 = *theMinorSamePnt1; *theMajorSamePnt2 = *theMinorSamePnt2; } //! Connects ends of pcurves of face's wires according to topological coherency. void fixFaceBoundaries(const IMeshData::IFaceHandle& theDFace) const; //! Returns True if check can be done in parallel. Standard_Boolean isParallel() const { return (myParameters.InParallel && myModel->FacesNb() > 1); } //! Collects unique edges to be updated from face map. Clears data stored in face map. Standard_Boolean popEdgesToUpdate(IMeshData::MapOfIEdgePtr& theEdgesToUpdate); private: Handle(IMeshData_Model) myModel; IMeshTools_Parameters myParameters; Handle(IMeshData::DMapOfIFacePtrsMapOfIEdgePtrs) myFaceIntersectingEdges; }; #endif
#include "DoubleEdit.h" // RsaToolbox #include "General.h" using namespace RsaToolbox; // Qt #include <QDebug> #include <QKeyEvent> #include <QRegExp> #include <QRegExpValidator> #include <QScopedPointer> DoubleEdit::DoubleEdit(QWidget *parent) : QLineEdit(parent), _parameterName("Value"), _decimalPlaces(3), _displayWithSiPrefix(true), _useMKeyAsMilli(false), _unitAbbr("U"), _value(DBL_NAN), _isMinimum(false), _isMaximum(false), _minimumValue(DBL_NEG_INF), _maximumValue(DBL_INF) { _setValidator(); connect(this, SIGNAL(returnPressed()), this, SLOT(handleReturnPressed())); } DoubleEdit::~DoubleEdit() { } // Public: void DoubleEdit::setParameterName(const QString &name) { _parameterName = name; } void DoubleEdit::setDecimalPlaces(int places) { _decimalPlaces = places; processText(); } void DoubleEdit::setUnits(Units units) { setUnitAbbrev(toString(units)); } void DoubleEdit::setUnitAbbrev(const QString &abbreviation) { _unitAbbr = abbreviation; updateText(); } void DoubleEdit::interpretMKeyAsMilli(bool isMilli) { _useMKeyAsMilli = isMilli; } void DoubleEdit::disableSiPrefixes(bool disable) { _displayWithSiPrefix = !disable; updateText(); } double DoubleEdit::value() const { return _value; } void DoubleEdit::clearMinimum() { _isMinimum = false; _minimumValue = DBL_NEG_INF; } void DoubleEdit::clearMaximum() { _isMaximum = false; _maximumValue = DBL_INF; } void DoubleEdit::setMinimum(double value) { clearAcceptedValues(); _isMinimum = true; _minimumValue = value; // Check for validity if (!text().isEmpty()) setValue(_value); } void DoubleEdit::setMinimum(double value, SiPrefix prefix) { setMinimum(value * toDouble(prefix)); } void DoubleEdit::setMaximum(double value) { clearAcceptedValues(); _isMaximum = true; _maximumValue = value; // Check for validity if (!text().isEmpty()) setValue(_value); } void DoubleEdit::setMaximum(double value, SiPrefix prefix) { setMaximum(value * toDouble(prefix)); } void DoubleEdit::clearAcceptedValues() { _acceptedValues.clear(); } void DoubleEdit::setAcceptedValues(const QRowVector &frequencies_Hz) { clearMinimum(); clearMaximum(); _acceptedValues = frequencies_Hz; for (int i = 0; i < _acceptedValues.size(); i++) { if (_acceptedValues[i] < 0) _acceptedValues.removeAt(i); } if (!text().isEmpty()) setValue(_value); } void DoubleEdit::clearLimits() { clearMinimum(); clearMaximum(); clearAcceptedValues(); } // Slots: void DoubleEdit::setValue(double value) { if (_isMinimum && value < _minimumValue) value = _minimumValue; if (_isMaximum && value > _maximumValue) value = _maximumValue; if (isAcceptedValues()) value = findClosest(value, _acceptedValues); if (value == _value) { updateText(); return; } _value = value; updateText(); emit valueChanged(_value); } void DoubleEdit::setValue(double value, SiPrefix prefix) { const double _value = value * toDouble(prefix); setValue(_value); } void DoubleEdit::setText(const QString &text) { QLineEdit::setText(text); processText(); } // Protected void DoubleEdit::keyPressEvent(QKeyEvent *event) { Qt::Key key = Qt::Key(event->key()); if (key != Qt::Key_T && key != Qt::Key_G && key != Qt::Key_M && key != Qt::Key_K && key != Qt::Key_U && key != Qt::Key_N && key != Qt::Key_P && key != Qt::Key_F) { QLineEdit::keyPressEvent(event); return; } event->accept(); SiPrefix prefix; switch (key) { case Qt::Key_T: prefix = SiPrefix::Tera; break; case Qt::Key_G: prefix = SiPrefix::Giga; break; case Qt::Key_M: if (_useMKeyAsMilli) { prefix = SiPrefix::Milli; } else { prefix = SiPrefix::Mega; } break; case Qt::Key_K: prefix = SiPrefix::Kilo; break; case Qt::Key_U: prefix = SiPrefix::Micro; break; case Qt::Key_N: prefix = SiPrefix::Nano; break; case Qt::Key_P: prefix = SiPrefix::Pico; break; case Qt::Key_F: prefix = SiPrefix::Femto; break; default: prefix = SiPrefix::None; break; } QString text = this->text(); text = chopNonDigits(text); _value = text.toDouble() * toDouble(prefix); updateText(); processText(); selectAll(); } void DoubleEdit::focusInEvent(QFocusEvent *event) { selectAll(); QLineEdit::focusInEvent(event); } void DoubleEdit::focusOutEvent(QFocusEvent *event) { processText(); QLineEdit::focusOutEvent(event); } // Private slots void DoubleEdit::handleReturnPressed() { processText(); selectAll(); } // Private void DoubleEdit::_setValidator() { QString regexStr; // No prefix if (_displayWithSiPrefix) { regexStr = "-?(([0-9]+\\.?[0-9]*)|(\\.0*[1-9]+0*))(\\s*%1)?"; } else { // Prefix regexStr = "-?(([0-9]+\\.?[0-9]*)|(\\.0*[1-9]+0*))(\\s*[TGMKmupf]?%1)?"; } regexStr = regexStr.arg(_unitAbbr); QRegExp regex(regexStr, Qt::CaseInsensitive); QScopedPointer<QRegExpValidator> validator(new QRegExpValidator(regex, this)); setValidator(validator.take()); } bool DoubleEdit::isNaN() const { return _value != _value; } bool DoubleEdit::containsF(const QString &text) { return text.contains("F", Qt::CaseInsensitive); } bool DoubleEdit::containsP(const QString &text) { return text.contains("P", Qt::CaseInsensitive); } bool DoubleEdit::containsN(const QString &text) { return text.contains("N", Qt::CaseInsensitive); } bool DoubleEdit::containsU(const QString &text) { return text.contains("U", Qt::CaseInsensitive); } bool DoubleEdit::containsT(const QString &text) { return text.contains("T", Qt::CaseInsensitive); } bool DoubleEdit::containsG(const QString &text) { return text.contains("G", Qt::CaseInsensitive); } bool DoubleEdit::containsM(const QString &text) { // ...milli? return text.contains("M", Qt::CaseInsensitive); } bool DoubleEdit::containsK(const QString &text) { return text.contains("K", Qt::CaseInsensitive); } QString DoubleEdit::chopNonDigits(QString text) { int last = text.size() - 1; while (!text.isEmpty() && !text[last].isDigit()) { text.chop(1); last = text.size() - 1; } return text; } void DoubleEdit::updateText() { if (isNaN()) { this->clear(); return; } updateText(_value); } void DoubleEdit::updateText(const double &value) { QString text; if (_displayWithSiPrefix) { text = formatValue(value, _decimalPlaces, _unitAbbr); } else { text = "%1 %2"; text = text.arg(formatDouble(value, _decimalPlaces)); text = text.arg(_unitAbbr); text = text.trimmed(); } bool isBlocked = blockSignals(true); QLineEdit::setText(text); blockSignals(isBlocked); } void DoubleEdit::processText() { QString text = this->text(); if (text.isEmpty()) { return; } if (text.endsWith(_unitAbbr, Qt::CaseInsensitive)) { text.chop(_unitAbbr.size()); } SiPrefix prefix = SiPrefix::None; if (containsT(text)) { prefix = SiPrefix::Tera; } else if (containsG(text)) { prefix = SiPrefix::Giga; } else if (containsM(text)) { if (text.endsWith("m")) { prefix = SiPrefix::Milli; } else { prefix = SiPrefix::Mega; } } else if (containsK(text)) { prefix = SiPrefix::Kilo; } else if (containsU(text)) { prefix = SiPrefix::Micro; } else if (containsN(text)) { prefix = SiPrefix::Nano; } else if (containsP(text)) { prefix = SiPrefix::Pico; } else if (containsF(text)) { prefix = SiPrefix::Femto; } // Apply prefix text = chopNonDigits(text); double value = text.toDouble() * toDouble(prefix); // Round to acceptable value if (_isMinimum && value < _minimumValue) { QString name = _parameterName; if (name.isEmpty()) name = "Value"; QString msg = "*%1 must be at least %2"; msg = msg.arg(name); msg = msg.arg(formatValue(_minimumValue, 3, Units::Hertz)); emit outOfRange(msg); value = _minimumValue; } else if (_isMaximum && value > _maximumValue) { QString name = _parameterName; if (name.isEmpty()) name = "Value"; QString msg = "*%1 must be at most %2"; msg = msg.arg(name); msg = msg.arg(formatValue(_maximumValue, 3, Units::Hertz)); emit outOfRange(msg); value = _maximumValue; } else if (isAcceptedValues() && !_acceptedValues.contains(value)) { double newValue = findClosest(value, _acceptedValues); if (newValue != value) { QString msg = "*%1 Rounded to closest value: %2"; msg = msg.arg(formatValue(value, 3, Units::Hertz)); msg = msg.arg(formatValue(newValue, 3, Units::Hertz)); emit outOfRange(msg); value = newValue; } } // If value is unchanged, clean up // display and return if (value == _value) { updateText(); return; } // Change value _value = value; updateText(); emit valueChanged(_value); emit valueEdited(_value); } bool DoubleEdit::isAcceptedValues() const { return !_acceptedValues.isEmpty(); }
#include "EvaluationMapForm.h" #include "ui_ScaleForm.h" #include "Entities/EvaluationMap/EvaluationMap.h" #include "Entities/Range/Appraised/AppraisedRange.h" #include "Entities/Scale/Scale.h" #include "Forms/AddAppraisedRangeForm/AddAppraisedRangeForm.h" typedef AddAppraisedRangeForm AddForm; EvaluationMapForm::EvaluationMapForm(Scale *scale, QWidget *parent) : QWidget(parent), m_scale(scale), m_evaluationMap(scale->getEvaluationMap()), ui(new Ui::ScaleForm) { ui->setupUi(this); connect(ui->deleteBtn, &QPushButton::clicked, this, &EvaluationMapForm::onDeleteBtnClicked); configureTable(); configureAddForm(); update(); } EvaluationMapForm::~EvaluationMapForm() { delete ui; } void EvaluationMapForm::configureTable() { ui->key->setColumnCount(COLUMNS_AMOUNT); QStringList labels; labels << "Баллы" << "Результат" << ""; ui->key->setHorizontalHeaderLabels(labels); connect(ui->key, &QTableWidget::cellDoubleClicked, this, &EvaluationMapForm::onRangeDoubleClicked); connect(ui->key, &QTableWidget::cellClicked, [&](int i, int j) { if(j == DELETE_BTN) deleteRangeAt(i); }); } void EvaluationMapForm::configureAddForm() { m_addForm = new AddForm(this); connect(m_addForm, &AddForm::editingFinished, this, &EvaluationMapForm::addAppraisedRange); ui->addFormLayout->addWidget(m_addForm); } void EvaluationMapForm::update() { ui->key->clearContents(); ui->key->setRowCount(0); ui->scaleName->setText(m_scale->getName()); for(uint i = 0; i < m_evaluationMap->size(); ++i) { addAppraisedRangeOnForm(m_evaluationMap->at(i)); } } void EvaluationMapForm::onDeleteBtnClicked() { emit scaleDeleted(m_scale->getName()); deleteLater(); } void EvaluationMapForm::deleteRangeAt(const uint index) { ui->key->removeRow(index); m_evaluationMap->removeAt(index); } void EvaluationMapForm::onRangeDoubleClicked(int row) { m_addForm->setAppraisedRange(m_evaluationMap->at(row)); deleteRangeAt(row); } void EvaluationMapForm::addAppraisedRange(const AppraisedRange &appraisedRange) { m_scale->getEvaluationMap()->addAppraisedRange(appraisedRange); addAppraisedRangeOnForm(appraisedRange); } void EvaluationMapForm::addAppraisedRangeOnForm(const AppraisedRange &appraisedRange) { uint insertRow = ui->key->rowCount(); ui->key->setRowCount(insertRow + 1); ui->key->setItem(insertRow, RANGE, makeRange(appraisedRange.getRange())); ui->key->setItem(insertRow, RESULT, new QTableWidgetItem(appraisedRange.getResult())); ui->key->setItem(insertRow, DELETE_BTN, new QTableWidgetItem("Удалить")); ui->key->resizeColumnsToContents(); } QTableWidgetItem *EvaluationMapForm::makeRange(const Range &range) const { QString result = QString::number(range.first); if(range.first != range.second) { result.append(" - " + QString::number(range.second)); } return new QTableWidgetItem(result); }
#include <iostream> #include <sstream> #include <omp.h> #include <vector> #include <chrono> #include <atomic> #ifdef _WIN32 // Windows #define cpuid(info, x) __cpuidex(info, x, 0) #else // GCC Intrinsics #include <cpuid.h> void cpuid(int info[4], int InfoType){ __cpuid_count(InfoType, 0, info[0], info[1], info[2], info[3]); } #endif // Misc. bool HW_MMX; bool HW_x64; bool HW_ABM; // Advanced Bit Manipulation bool HW_RDRAND; bool HW_BMI1; bool HW_BMI2; bool HW_ADX; bool HW_PREFETCHWT1; // SIMD: 128-bit bool HW_SSE; bool HW_SSE2; bool HW_SSE3; bool HW_SSSE3; bool HW_SSE41; bool HW_SSE42; bool HW_SSE4a; bool HW_AES; bool HW_SHA; // SIMD: 256-bit bool HW_AVX; bool HW_XOP; bool HW_FMA3; bool HW_FMA4; bool HW_AVX2; // SIMD: 512-bit bool HW_AVX512F; // AVX512 Foundation bool HW_AVX512CD; // AVX512 Conflict Detection bool HW_AVX512PF; // AVX512 Prefetch bool HW_AVX512ER; // AVX512 Exponential + Reciprocal bool HW_AVX512VL; // AVX512 Vector Length Extensions bool HW_AVX512BW; // AVX512 Byte + Word bool HW_AVX512DQ; // AVX512 Doubleword + Quadword bool HW_AVX512IFMA; // AVX512 Integer 52-bit Fused Multiply-Add bool HW_AVX512VBMI; // AVX512 Vector Byte Manipulation Instructions void detect() { int info[4]; cpuid(info, 0); int nIds = info[0]; cpuid(info, 0x80000000); unsigned nExIds = info[0]; // Detect Features if (nIds >= 0x00000001){ cpuid(info,0x00000001); HW_MMX = (info[3] & ((int)1 << 23)) != 0; HW_SSE = (info[3] & ((int)1 << 25)) != 0; HW_SSE2 = (info[3] & ((int)1 << 26)) != 0; HW_SSE3 = (info[2] & ((int)1 << 0)) != 0; HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0; HW_SSE41 = (info[2] & ((int)1 << 19)) != 0; HW_SSE42 = (info[2] & ((int)1 << 20)) != 0; HW_AES = (info[2] & ((int)1 << 25)) != 0; HW_AVX = (info[2] & ((int)1 << 28)) != 0; HW_FMA3 = (info[2] & ((int)1 << 12)) != 0; HW_RDRAND = (info[2] & ((int)1 << 30)) != 0; } if (nIds >= 0x00000007){ cpuid(info,0x00000007); HW_AVX2 = (info[1] & ((int)1 << 5)) != 0; HW_BMI1 = (info[1] & ((int)1 << 3)) != 0; HW_BMI2 = (info[1] & ((int)1 << 8)) != 0; HW_ADX = (info[1] & ((int)1 << 19)) != 0; HW_SHA = (info[1] & ((int)1 << 29)) != 0; HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0; HW_AVX512F = (info[1] & ((int)1 << 16)) != 0; HW_AVX512CD = (info[1] & ((int)1 << 28)) != 0; HW_AVX512PF = (info[1] & ((int)1 << 26)) != 0; HW_AVX512ER = (info[1] & ((int)1 << 27)) != 0; HW_AVX512VL = (info[1] & ((int)1 << 31)) != 0; HW_AVX512BW = (info[1] & ((int)1 << 30)) != 0; HW_AVX512DQ = (info[1] & ((int)1 << 17)) != 0; HW_AVX512IFMA = (info[1] & ((int)1 << 21)) != 0; HW_AVX512VBMI = (info[2] & ((int)1 << 1)) != 0; } if (nExIds >= 0x80000001){ cpuid(info,0x80000001); HW_x64 = (info[3] & ((int)1 << 29)) != 0; HW_ABM = (info[2] & ((int)1 << 5)) != 0; HW_SSE4a = (info[2] & ((int)1 << 6)) != 0; HW_FMA4 = (info[2] & ((int)1 << 16)) != 0; HW_XOP = (info[2] & ((int)1 << 11)) != 0; } } template <typename Clock = std::chrono::high_resolution_clock> class stopwatch { typename Clock::time_point start_point; public: stopwatch() { std::atomic_thread_fence(std::memory_order_relaxed); start_point = Clock::now(); std::atomic_thread_fence(std::memory_order_relaxed); } template <typename Rep = typename Clock::duration::rep, typename Units = typename Clock::duration> Rep elapsed() const { std::atomic_thread_fence(std::memory_order_relaxed); std::chrono::duration<Rep, Units> duration = Clock::now() - start_point; std::atomic_thread_fence(std::memory_order_relaxed); return duration.count(); } }; #include <immintrin.h> __attribute__ ((__target__ ("avx2"))) std::ostream& operator << (std::ostream& out, __m256i& r) { out << "[" << _mm256_extract_epi32(r, 0) << " " << _mm256_extract_epi32(r, 1) << " " << _mm256_extract_epi32(r, 2) << " " << _mm256_extract_epi32(r, 3) << " " << _mm256_extract_epi32(r, 4) << " " << _mm256_extract_epi32(r, 5) << " " << _mm256_extract_epi32(r, 6) << " " << _mm256_extract_epi32(r, 7) << "]"; return out; } //https://db.in.tum.de/~finis/x86-intrin-cheatsheet-v2.1.pdf const long long loopsize = 1000000000; __attribute__ ((__target__ ("avx2"))) uint32_t avx2_sum32(const std::vector<uint32_t>& v) { auto loops = v.size() / 8; auto steps = v.size() % 8; // std::cout << loops << "," << steps << std::endl; uint32_t buffer[sizeof(__m256i)/sizeof(uint32_t)] = {0}; __m256i accum = _mm256_load_si256((const __m256i*)&buffer); const __m256i* data = (const __m256i*)v.data(); while(loops > 0) { auto current = _mm256_load_si256(data); //std::cout << accum << "+" << current << std::endl; accum = _mm256_add_epi32(accum, current); //std::cout << accum << std::endl; --loops; ++data; } _mm256_store_si256((__m256i *)buffer, accum); auto total = buffer[0]+buffer[1]+buffer[2]+buffer[3]+buffer[4]+buffer[5]+buffer[6]+buffer[7]; auto start = (v.size() / 8) * 8; for(int i = start;i < v.size(); ++i) total += v[i]; return total; } __attribute__ ((__target__ ("avx512f"))) uint32_t avx512f_sum32(const std::vector<uint32_t>& v) { auto size = v.size(); __m512i accum_simd = _mm512_setzero_epi32(); for(long long i = 0;i < size; i+=16) { auto current = _mm512_load_si512((const __m256i*)&v[i]); accum_simd = _mm512_add_epi32(accum_simd, current); } return _mm512_reduce_add_epi32(accum_simd); } template <typename TR, typename T1> using FUNCR = TR (*) (const T1& v); FUNCR<uint32_t,std::vector<uint32_t>> sum32; int main(int argc, char** argv) { detect(); if(HW_AVX512F) sum32 = &avx512f_sum32; else if(HW_AVX2) sum32 = &avx2_sum32; std::cout << "HW_MMX: " << HW_MMX << std::endl; std::cout << "HW_x64: " << HW_x64 << std::endl; std::cout << "HW_ABM: " << HW_ABM << std::endl; std::cout << "HW_RDRAND: " << HW_RDRAND << std::endl; std::cout << "HW_BMI1: " << HW_BMI1 << std::endl; std::cout << "HW_BMI2: " << HW_BMI2 << std::endl; std::cout << "HW_ADX: " << HW_ADX << std::endl; std::cout << "HW_PREFETCHWT1: " << HW_PREFETCHWT1 << std::endl; std::cout << "HW_SSE: " << HW_SSE << std::endl; std::cout << "HW_SSE2: " << HW_SSE2 << std::endl; std::cout << "HW_SSE3: " << HW_SSE3 << std::endl; std::cout << "HW_SSSE3: " << HW_SSSE3 << std::endl; std::cout << "HW_SSE41: " << HW_SSE41 << std::endl; std::cout << "HW_SSE42: " << HW_SSE42 << std::endl; std::cout << "HW_SSE4a: " << HW_SSE4a << std::endl; std::cout << "HW_AES: " << HW_AES << std::endl; std::cout << "HW_SHA: " << HW_SHA << std::endl; std::cout << "HW_AVX: " << HW_AVX << std::endl; std::cout << "HW_XOP: " << HW_XOP << std::endl; std::cout << "HW_FMA3: " << HW_FMA3 << std::endl; std::cout << "HW_FMA4: " << HW_FMA4 << std::endl; std::cout << "HW_AVX2: " << HW_AVX2 << std::endl; std::cout << "HW_AVX512F: " << HW_AVX512F << std::endl; std::cout << "HW_AVX512CD: " << HW_AVX512CD << std::endl; std::cout << "HW_AVX512PF: " << HW_AVX512PF << std::endl; std::cout << "HW_AVX512ER: " << HW_AVX512ER << std::endl; std::cout << "HW_AVX512VL: " << HW_AVX512VL << std::endl; std::cout << "HW_AVX512BW: " << HW_AVX512BW << std::endl; std::cout << "HW_AVX512DQ: " << HW_AVX512DQ << std::endl; std::cout << "HW_AVX512IFMA: " << HW_AVX512IFMA << std::endl; std::cout << "HW_AVX512VBMI: " << HW_AVX512VBMI << std::endl; std::stringstream ss; ss << argv[1]; int value; ss >> value; int numThreads = 1; if(argc > 2) { ss << argv[2]; ss >> numThreads; omp_set_num_threads(numThreads); } std::vector<uint32_t> v; do { std::string line; std::cout << "> "; std::getline (std::cin, line); std::stringstream parser; parser << line; std::string cmd; parser >> cmd; if(cmd == "array") { size_t size; parser >> size; // std::cout << ":" << cmd << " " << size << std::endl; v = std::vector<uint32_t>(size, 1); } { auto timer = stopwatch<>{}; std::cout << "..." << std::endl; auto total = sum32(v); std::cout << total << std::endl; std::cout << numThreads << " thread(s), elapsed: " << timer.elapsed<double, std::chrono::seconds::period>() << std::endl; } }while(true); }
#include "stdafx.h" #include "animation.h" #include "sprite.h" #include "level_sprite.h" #include "sprite_property.h" #include "rom_file.h" Animation::Animation() { SetRect(&base_, 0, 0, 0, 0); frame_index_ = 0; frame_count_ = 0; counter_ = 0; flip_horz_ = false; flip_vert_ = false; } Animation::~Animation() { } bool Animation::Draw(BitmapSurface& surface, int to_x, int to_y, int from_x, int from_y) { if (frame_index_ >= frames_.size()) { return false; } Frame& frame = frames_[frame_index_]; if (flip_vert_ || flip_horz_) { frame.sprite->DrawFlipped(surface, to_x, to_y, from_x, from_y, flip_horz_, flip_vert_ ); } else { frame.sprite->Draw(surface, to_x, to_y, from_x, from_y ); } return true; } bool Animation::DrawDC(HDC hdc, int to_x, int to_y, int from_x, int from_y) { Ref<SpriteResource> sprite = GetCurrentSprite(); if (!sprite) { return false; } sprite->DrawDC(hdc, to_x, to_y, from_x, from_y ); return true; } bool Animation::DrawSelection(BitmapSurface& surface, int x, int y) { Ref<SpriteResource> sprite = GetCurrentSprite(); if (!sprite) { return false; } RECT zone = base_; OffsetRect(&zone, x, y); surface.DrawSelection(zone, RGB(0, 0, 0), RGB(255, 255, 255), false ); return true; } void Animation::SetFrame(UINT nFrame) { if (frames_.size() == 0) { return ; } counter_ = nFrame % frames_.size(); } bool Animation::NextFrame() { if (frame_index_ >= frames_.size()) { return false; } Frame& frame = frames_[frame_index_]; counter_++; if (counter_ >= frame.duration) { IncreaseFrame(); return true; } return false; } bool Animation::Load(Buffer& src_buf, SpritePool& sprites, UINT anim_id, UINT pal_id) { CartFile::Scope scope(src_buf); frames_.clear(); frame_count_ = 0; anim_id_ = anim_id; if (!src_buf.FollowPtr2(0x390000, anim_id * 4)) { return false; } BYTE frame_duration; if (!src_buf.ReadByte(frame_duration)) { return false; } SetRect(&base_, 256, 256, -256, -256); while (frame_duration != 0x80) { UINT sprite_id = 0x00000000; if (!src_buf.Read(&sprite_id, 2)) { return false; } if (frame_duration > 0x80) { if (frame_duration == 0x8f) { src_buf.Skip(2); return true; } else if (frame_duration == 0x81) { //cart.Skip(2); } else if (frame_duration == 0x83) { //cart.Skip(2); } else if (frame_duration == 0x84) { //cart.Skip(2); } else if (frame_duration == 0x82) { //cart.Skip(2); } else { } } else { Frame frame; frame.duration = frame_duration; frame.sprite = sprites.New(MAKELONG(sprite_id, pal_id)); if (!frame.sprite) { return false; } const RECT& sprite_rect = frame.sprite->GetRect(); frame_count_ += frame.duration; if (base_.left > sprite_rect.left) { base_.left = sprite_rect.left; } if (base_.top > sprite_rect.top) { base_.top = sprite_rect.top; } if (base_.bottom < sprite_rect.bottom) { base_.bottom = sprite_rect.bottom; } if (base_.right < sprite_rect.right) { base_.right = sprite_rect.right; } frames_.push_back(frame); } if (!src_buf.ReadByte(frame_duration)) { return false; } } return true; } bool Animation::LoadStatic(Buffer& src_buf, SpritePool& sprites, UINT sprite_id, UINT pal_id) { frames_.clear(); Frame frame; frame.duration = 0; frame.sprite = sprites.New(MAKELONG(sprite_id, pal_id)); if (!frame.sprite) { return false; } frames_.push_back(frame); base_ = frame.sprite->GetRect(); return true; } bool Animation::LoadFromProperty(Buffer& src_buf, SpritePool& sprites, SpriteProperty& prop) { SpriteGraphicDef gfx; if (prop.GetGraphics(src_buf, gfx)) { flip_horz_ = gfx.flip_horz; flip_vert_ = gfx.flip_vert; if (gfx.anim_id) { if (!Load(src_buf, sprites, gfx.anim_id, gfx.palette_id)) { return false; } return true; } else if (gfx.sprite_id) { if (!LoadStatic(src_buf, sprites, gfx.sprite_id, gfx.palette_id)) { return false; } return true; } } return false; } bool Animation::IntersectBox(RECT& box) { Ref<SpriteResource> sprite = GetCurrentSprite(); if (!sprite) { return false; } RECT dstRect; return IntersectRect(&dstRect, &base_, &box) != FALSE; } bool Animation::IntersectPoint(POINT& pt) { return base_.left <= pt.x && base_.right >= pt.x && base_.top <= pt.y && base_.bottom >= pt.y; } const RECT& Animation::GetBoundingBox() const { return base_; } Ref<SpriteResource> Animation::GetCurrentSprite() { Frame& frame = GetCurrentFrame(); if (!frame.sprite) { return Ref<SpriteResource>(); } return frame.sprite; } void Animation::UpdateFrameCount() { frame_count_ = 0; std::vector<Frame>::iterator i; for (i = frames_.begin(); i != frames_.end(); ++i) { frame_count_ += i->duration; } } void Animation::IncreaseFrame() { frame_index_++; counter_ = 0; if (frame_index_ >= frames_.size()) { frame_index_ = 0; } } Animation::Frame& Animation::GetCurrentFrame() { if (frame_index_ >= frames_.size()) { return Frame(); } return frames_[frame_index_]; } AnimationPool::AnimationPool(CartFile& cart, SpritePool& sprites) : cart_(cart), sprites_(sprites) { } bool AnimationPool::OnResourceAlloc(DWORD id, AnimationRef* resource) { return resource->Load(cart_, sprites_, LOWORD(id), HIWORD(id)); }
#include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0) #define rep1(i, n) for(int i=0;i<(int)n;i++) #define rep2(i, a, b) for(int i=(int)a;i<(int)b;i++) #define st first #define nd second #define pb push_back #define pf push_front #define p_b pop_back #define p_f pop_front #define mp make_pair #define MAX 100010 #define oo INT_MAX using namespace std; //tipagem de pares typedef pair<int, int> ii; typedef pair<char, char> cc; typedef pair<int, char> ic; typedef pair<char, int> ci; //tipagem de vetores typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef vector<pair<int, int>> vii; typedef vector<bool> vb; //tipagem de outras estruturas typedef queue<int> qi; typedef deque<int> dqi; //tipagem de tipos primitivos typedef long long int ll; typedef unsigned long long int ull; typedef struct pl{ int p; vi r; }pl; bool compare(const pl& a, const pl& b){ return a.r.size() > b.r.size(); } int main() { fastio; // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int n, m; while(cin >> n >> m && (n || m)){ map<int, vi> x; rep1(i, n){ rep1(j, m){ int num; cin >> num; if(x.find(num) == x.end()){ x.insert({num, {j+1}}); }else{ x[num].pb(j+1); } } } pl rank[x.size()]; int i = 0; for(map<int, vi>::iterator it = x.begin();it!=x.end();it++){ rank[i].p = it->first; rep1(j, it->second.size()){ rank[i].r.pb(it->nd[j]); } i++; } rep1(i, x.size()){ sort(rank[i].r.begin(), rank[i].r.end()); } sort(rank, rank + x.size(), compare); vector<int> ans; rep1(i, x.size()){ if(rank[i].r.size() == rank[1].r.size()){ ans.pb(rank[i].p); } } sort(ans.begin(), ans.end()); rep1(i, ans.size()){ cout << ans[i] << ' '; } cout << endl; } return 0; }
#include "CCheckUserName.h" #include "json/json.h" #include "Logger.h" #include "threadres.h" #include "Helper.h" int CCheckUserName::do_request(const Json::Value& root, char *client_ip, HttpResult& out) { //Json::Value ret; std::string username = Helper::filterInput(root["param"]["username"].asString()); if (username.empty() || isMobile(username) || !isUserName(username)) { out["result"] = -1; out["msg"] = "用户名格式错误"; //out = write.write(ret); return status_ok; } if (hasUsername(username)) { out["result"] = -2; out["msg"] = "用户名已存在"; //out = write.write(ret); return status_ok; } out["result"] = 1; out["msg"] = "用户名正确"; //out = write.write(ret); return status_ok; } bool CCheckUserName::hasUsername(std::string &username) { MySqlDBAccess* pDBUcenter = ThreadResource::getInstance().getDBConnMgr()->DBSlave(); if (NULL == pDBUcenter) return false; std::string strSql = StrFormatA("SELECT count(username) FROM ucenter.uc_register_username WHERE username='%s' LIMIT 1",username.c_str()); MySqlResultSet *pResult = pDBUcenter->Query( strSql.c_str() ); if ( pResult == NULL ) return false; int count = 0; if (pResult->hasNext()) count = pResult->getIntValue(0); delete pResult; return count > 0 ? true : false; }
// // Created by 邦邦 on 2022/4/22. // #ifndef BB_LOG_H #define BB_LOG_H #include <string> #include <mutex> #include <exception> #include "Time.h" namespace bb { //__FILE__,__LINE__,__func__ class Log{ const char *log_path_ = "./bb.log"; //日志保存位置 std::string msg_arr_; //消息内容 Log()=default; ~Log(); public: static Log &obj(); public: //一般信息 void info(std::string msg); void info(std::string msg,const std::string &file_path); void info(std::string msg,const std::string &file_path,const int &line); //警告信息 void warn(std::string msg); void warn(std::string msg,const std::string &file_path); void warn(std::string msg,const std::string &file_path,const int &line); //错误信息 void error(std::string msg); void error(std::string msg,const std::string &file_path); void error(std::string msg,const std::string &file_path,const int &line); }; } #endif //BB_LOG_H
#include<cstdio> #include<iostream> #include<string> #include<cstring> using namespace std; int N,L; int train[55]; int cas=0; int sw(){ for(int i=0;i<L;i++) for(int j=0;j<L-i-1;j++){ if(train[j]>train[j+1]){ int t; t=train[j]; train[j]=train[j+1]; train[j+1]=t; cas++; } } } int main(){ scanf("%d",&N); while(N--){ scanf("%d",&L); memset(train,0,sizeof(train)); for(int i=0;i<L;i++){ scanf("%d",&train[i]); } sw(); printf("Optimal train swapping takes %d swaps.\n",cas); cas=0; } return 0; }
#include "Transform.h" glm::vec3 transform(glm::mat4 m, glm::vec3 r); Transform::Transform(const glm::vec3& pos, const glm::quat& rot, const glm::vec3& scale) : m_pos(pos), m_rot(rot), m_scale(scale), m_parent(nullptr) { // Transform Constructor utilizing Quaternion Rotation } bool Transform::hasChanged() const { if (m_parent && m_parent->hasChanged()) return true; if (m_pos != m_old_pos || m_rot != m_old_rot || m_scale != m_old_scale) return true; return false; } void Transform::update() { if (hasChanged()) { m_old_pos = m_pos; m_old_rot = m_rot; m_old_scale = m_scale; if (m_parent) m_parentMatrix = m_parent->getWorldMatrix(); } } glm::mat4 Transform::getWorldMatrix() const { glm::mat4 posMatrix = translate(m_pos); glm::mat4 scaleMatrix = scale(m_scale); glm::mat4 rotMatrix = glm::mat4_cast(glm::normalize(m_rot)); return m_parentMatrix * posMatrix * rotMatrix * scaleMatrix; } glm::vec3 Transform::getTransformedPos() { return transform(m_parentMatrix, m_pos); } glm::quat Transform::getTransformedRot() { glm::quat parentRot = glm::quat(0, 0, 0, 1); if (m_parent != nullptr) parentRot = m_parent->getTransformedRot(); return parentRot * getRot(); } glm::quat Transform::mul(glm::quat q, glm::vec3 v) { float w = -q.x * v.x - q.y * v.y - q.z * v.z; float x = q.w * v.x + q.y * v.z - q.z * v.y; float y = q.w * v.y + q.z * v.x - q.x * v.z; float z = q.w * v.z + q.x * v.y - q.y * v.x; return glm::quat(w, x, y, x); } glm::mat4 Transform::translate(const glm::vec3& v) const { glm::mat4 m; for (unsigned int i = 0; i < 4; i++) for (unsigned int j = 0; j < 4; j++) if (i == 3 && j != 3) m[i][j] = v[j]; return m; } glm::mat4 Transform::scale(const glm::vec3& v) const { glm::mat4 m; for (unsigned int i = 0; i < 3; i++) for (unsigned int j = 0; j < 3; j++) if (i == j && i != 3) m[i][j] = v[i]; return m; } void Transform::rotate(const glm::vec3& axis, float angle) { rotate(glm::angleAxis(angle, axis)); } void Transform::rotate(glm::quat rotation) { m_rot = glm::normalize(rotation * m_rot); } glm::vec3 Transform::rotate(glm::vec3 axis, glm::quat rotation) { glm::quat _q = glm::conjugate(rotation); glm::quat w = rotation * glm::quat(0, axis) * _q; return glm::normalize(glm::vec3(w[0], w[1], w[2])); } glm::vec3& Transform::getPos() { return m_pos; } glm::quat & Transform::getRot() { return m_rot; } glm::vec3 & Transform::getScale() { return m_scale; } Transform* Transform::getParent() { return m_parent; } void Transform::setPos(const glm::vec3 & pos) { m_pos = pos; } void Transform::setRot(const glm::quat & rot) { m_rot = rot; } void Transform::setScale(const glm::vec3 & scale) { m_scale = scale; } void Transform::setParent(Transform* parent) { m_parent = parent; } glm::vec3 Transform::getForward() { return rotate(glm::vec3(0, 0, 1), m_rot); } glm::vec3 Transform::getBackward() { return rotate(glm::vec3(0, 0, -1), m_rot); } glm::vec3 Transform::getUp() { return rotate(glm::vec3(0, 1, 0), m_rot); } glm::vec3 Transform::getDown() { return rotate(glm::vec3(0, -1, 0), m_rot); } glm::vec3 Transform::getRight() { return rotate(glm::vec3(-1, 0, 0), m_rot); } glm::vec3 Transform::getLeft() { return rotate(glm::vec3(1, 0, 0), m_rot); } // HELPER FUNCTIONS // --------------------------------------------------------------------------------------------- glm::vec3 transform(glm::mat4 m, glm::vec3 r) { return glm::vec3( m[0][0] * r.x + m[0][1] * r.y + m[0][2] * r.z + m[0][3], m[1][0] * r.x + m[1][1] * r.y + m[1][2] * r.z + m[1][3], m[2][0] * r.x + m[2][1] * r.y + m[2][2] * r.z + m[2][3] ); }
#include "opennwa/NwaFwd.hpp" #include <wali/util/DisjointSets.hpp> namespace opennwa { namespace construct { /** * * @brief constructs the NWA which is the result of applying the quotient operation on the given NWA * * @param - out: the quotient NWA of the given NWA * @param - nwa: the NWA on which to apply quotient operation * @param - partition: the disjoint set which specifies the equivalence relation on the NWA * */ extern void quotient( Nwa & out, Nwa const & nwa, wali::util::DisjointSets<State> partition ); /** * * @brief constructs the NWA which is the result of applying the quotient operation on the given NWA * * @param - nwa: the NWA on which to apply quotient operation * @param - partition: the disjoint set which specifies the equivalence relation on the NWA * @return - the quotient NWA of the given NWA * */ extern NwaRefPtr quotient( Nwa const & nwa, wali::util::DisjointSets<State> partition ); } } // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End:
/* @author: AkshitAggarwal @date: 08/03/2019 */ #include<iostream> using namespace std; void pattern_1(int n) { cout<<"#Pattern01\n"; for(int i = 0; i < n; i++) { for(int j = 0; j <= i; j++) cout<<j+1<<" "; cout<<'\n'; } cout<<"==============================\n"; } void pattern_2(int n) { cout<<"#Pattern02\n"; int k = 0; for(int i = 0; i < n; i++) { for( int j = 0; j <= i; j++) cout<<++k<<" "; cout<<'\n'; } cout<<"==============================\n"; } void pattern_3(int n) { cout<<"#Pattern03\n"; for(int i = 0; i < n; i++) { for(int j = 0; j <= i; j++) cout<<j+1<<" "; cout<<'\n'; } for(int i = n - 1; i > 0; i--) //Lower Half { for(int j = 0; j < i; j++) cout<<j+1<<" "; cout<<'\n'; } cout<<"==============================\n"; } void pattern_4(int n) { cout<<"#Pattern04\n"; for(int i = 0; i < n; i++) { int k = i; for(int j = i; j < n-1; j++) //Spaces on the left cout<<" "; for(int j = 0; j <= i; j++) //Left side pattern, central numbers included cout<<++k<<' '; int l = k; for(int j = 0; j < i; j++) //Right side pattern cout<<--l<<' '; for(int j = i; j < n-1; j++) //Spaces on the right cout<<" "; cout<<'\n'; } cout<<"==============================\n"; } void pattern_5(int n) { cout<<"#Pattern05\n"; for(int i = n, k = 0; i > 0; i--, k++) { for(int j = 0; j < k; j++) cout<<" "; for(int j = i; j > 0; j--) cout<<"* "; for(int j = i - 1; j > 0; j--) cout<<"* "; cout<<'\n'; } cout<<"==============================\n"; } /* * * * * * * * * * * * * * */ void pattern_6(int n) { cout<<"#Pattern06\n"; for(int i = 0; i < n; i++) { int k = i; for(int j = i; j < n - 1; j++) cout<<" "; for(int j = 0; j <= i; j++) { cout<<"* "; k++; } for(int j = 0; j < i; j++) cout<<"* "; cout<<'\n'; } //Lower Half of the pattern. for(int i = n, k = 0; i > 0; i--, k++) { for(int j = 0; j < k + 1; j++) cout<<" "; for(int j = i; j > 1; j--) cout<<"* "; for(int j = i - 1; j > 1; j--) cout<<"* "; cout<<'\n'; } cout<<"==============================\n"; } /* * * * * * * * * * * * * * * * * * * * * * * * * */ void pattern_7(int n) { cout<<"#Pattern07\n"; for(int i = 0; i < n; i++) { for(int j = n; j > i; j--) cout<<"* "; for(int j = 0; j < i; j++) cout<<" "; for(int j = n; j > i; j--) cout<<"* "; cout<<'\n'; } for(int i = 0; i < n; i++) //Lower Half of the pattern. { for(int j = 0; j <= i; j++) cout<<"* "; for(int j = n; j > i + 1; j--) cout<<" "; for(int j = 0; j <= i; j++) cout<<"* "; cout<<'\n'; } cout<<"==============================\n"; } void pattern_8(int n) { cout<<"#Pattern08\n"; for(int i = 0; i < n; i++) { for(int j = 0; j <= i; j++) cout<<"* "; for(int j = n; j > i + 1; j--) cout<<" "; for(int j = 0; j <= i; j++) cout<<"* "; cout<<'\n'; } for(int i = 0; i < n; i++) { for(int j = n; j > i; j--) cout<<"* "; for(int j = 0; j < i; j++) cout<<" "; for(int j = n; j > i; j--) cout<<"* "; cout<<'\n'; } cout<<"==============================\n"; } int main() { int input = 0; cin>>input; cout<<"==============================\n"; pattern_1(input); pattern_2(input); pattern_3(input); pattern_4(input); pattern_5(input); pattern_6(input); pattern_7(input); pattern_8(input); return 0; }
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> #define INT_MAX 0x7fffffff #define INT_MIN 0x80000000 using namespace std; int numTrees(int n){ vector<int> index(n+1,0); index[0]=1; index[1]=1; for(int i=2;i<=n;i++){ for(int j=0;j<i;j++){ index[i] += index[j] * index[i-j-1]; } } return index[n]; } int main(){ int i; cin >> i; cout << numTrees(i) <<endl; }
#pragma once #include <Arduino.h> #include "fastIO.h" class FastButton { private: FastIO io; int buttonState = LOW; int currentRead = -1; //uninitialized unsigned long lastChangeTime = 0; unsigned long debounceDelay; bool justFell = false; bool justRose = false; public: FastButton(); virtual ~FastButton(); void begin(uint8_t pin, bool pullup = true, unsigned long debounceDelay = 50); /** * updates the button (call every loop) * @return the button changed state */ bool update(); /** * @return the button's current stable state (HIGH|LOW) */ uint8_t state(); /** * @return true if the button just rose (stabely) */ bool rose(); /** * @return true if the button just fell (stabely) */ bool fell(); /** * @return true if the button just toggled (stabely) */ bool toggled(); };
// // Created by Cristian Marastoni on 23/04/15. // #include "SocketImpl.h"
#include "pch.h" #include "RepeatUntilFail.h" namespace Hourglass { IBehavior::Result RepeatUntilFail::Run( Entity* entity ) { Result result = GetChild()->Run( entity ); if (result == kFAILURE) { return kSUCCESS; } else if (result == kSUCCESS) { GetChild()->Reset(); } return kRUNNING; } IBehavior* RepeatUntilFail::MakeCopy() const { RepeatUntilFail* copy = (RepeatUntilFail *)IBehavior::Create( SID( RepeatUntilFail ) ); copy->SetBehavior( GetChild()->MakeCopy() ); return copy; } }
#include <iostream> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "OokDecoder.h" #include "NewKakuDecoder.h" NewKakuDecoder::NewKakuDecoder () { decoderName = "NEWKAKU"; } NewKakuDecoder::NewKakuDecoder (OokDecoder *pdecoder) { decoderName = "NEWKAKU"; copyDecoder(pdecoder); } NewKakuDecoder::~NewKakuDecoder () {} int NewKakuDecoder::decode (uint32_t width) { // Start bit ... if (state == UNKNOWN && (180 <= width && width < 450)) { state = START_BIT; } else if (state == START_BIT && (2250 <= width)) { state = OK; // } else if ((state != UNKNOWN) && (( 100 <= width && width < 450) || (950 <= width && width < 1250))) { } else if ((state != UNKNOWN) && (( 100 <= width && width < 450) || (950 <= width && width < 1300))) { byte w = width >= 700; switch (state) { case UNKNOWN: case OK: if (w == 0) state = T0; else return -1; break; case T0: state = T1; break; case T1: state = T2; break; case T2: if (w) gotBit(0); else gotBit(1); break; } if (total_bits>=32) return 1; } else return -1; return 0; } static char *commandOrders[] = {"OFF", "ON", "", "ALLOFF", "ALLON"}; char *NewKakuDecoder::display () { reverseBits(); unsigned long bitstream = (((((data[0] << 8) + data[1]) << 8) + data[2]) << 8) + data[3]; int command = (bitstream >> 4) & 0x03; if (command > 1) command ++; if (total_bits > 32) { // DIM -> 2 octets de plus byte dim = (data[4] << 8) + data[5]; sprintf(pbuffer,"20;%02X;NewKaku;ID=%08lx;SWITCH=%x;CMD=SET_LEVEL=%d;\n",0,((bitstream) >> 6),((bitstream)&0x0f)+1,dim); } else { sprintf(pbuffer,"20;%02X;NewKaku;ID=%08lx;SWITCH=%x;CMD=%s;\n",0,((bitstream) >> 6),((bitstream)&0x0f)+1,commandOrders[command]); } return pbuffer; } #define NewKAKU_1T 250 // us #define NewKAKU_2T 290 #define NewKAKU_mT 650/RAWSIGNAL_SAMPLE_RATE // us, approx. in between 1T and 4T #define NewKAKU_4T NewKAKU_1T*5 // 1250 us #define NewKAKU_8T NewKAKU_1T*10 // 2500 us, Tijd van de space na de startbit int NewKakuDecoder::TX (char *InputBuffer_Serial, struct RawSignalStruct *pRawSignal) { int success=false; //10;NewKaku;123456;3;ON; // ON, OFF, ALLON, ALLOFF, ALL 99, 99 //10;NewKaku;0cac142;2;ON; //10;NewKaku;050515;f;OFF; //10;NewKaku;2100fed;1;ON; //10;NewKaku;000001;10;ON; //10;NewKaku;306070b;f;ON; //10;NewKaku;306070b;10;ON; //01234567890123456789012 if (strncasecmp(InputBuffer_Serial+3,"NEWKAKU;",8) == 0) { byte x=18; // pointer to the switch number if (InputBuffer_Serial[17] != ';') { if (InputBuffer_Serial[18] != ';') { return false; } else { x=19; } } unsigned long bitstream=0L; unsigned long tempaddress=0L; byte cmd=0; byte c=0; byte Address=0; // Address 1..16 // ----- InputBuffer_Serial[ 9]=0x30; // Get NEWKAKU/AC main address part from hexadecimal value InputBuffer_Serial[10]=0x78; InputBuffer_Serial[x-1]=0x00; tempaddress=strtoul(InputBuffer_Serial+9,NULL,0); // ----- //while((c=InputBuffer_Serial[x++])!=';'){ // Address: 1 to 16 // if(c>='0' && c<='9'){Address=Address*10;Address=Address+c-'0';} //} InputBuffer_Serial[x-2]=0x30; // Get unit number from hexadecimal value InputBuffer_Serial[x-1]=0x78; // x points to the first character of the unit number if (InputBuffer_Serial[x+1] == ';') { InputBuffer_Serial[x+1]=0x00; cmd=2; } else { if (InputBuffer_Serial[x+2] == ';') { InputBuffer_Serial[x+2]=0x00; cmd=3; } else { return false; } } Address=strtoul(InputBuffer_Serial+(x-2),NULL,0); // NewKAKU unit number if (Address > 16) return false; // invalid address Address--; // 1 to 16 -> 0 to 15 (transmitted value is 1 less than shown values) x=x+cmd; // point to on/off/dim command part // ----- tempaddress=(tempaddress <<6) + Address; // Complete transmitted address // ----- cmd=str2cmd(InputBuffer_Serial+x); // Get ON/OFF etc. command if (cmd == false) { // Not a valid command received? ON/OFF/ALLON/ALLOFF cmd=strtoul(InputBuffer_Serial+x,NULL,0); // get DIM value } // --------------- NEWKAKU SEND ------------ //unsigned long bitstream=0L; byte i=1; x=0; // aantal posities voor pulsen/spaces in RawSignal // bouw het KAKU adres op. Er zijn twee mogelijkheden: Een adres door de gebruiker opgegeven binnen het bereik van 0..255 of een lange hex-waarde //if (tempaddress<=255) // bitstream=1|(tempaddress<<6); // Door gebruiker gekozen adres uit de Nodo_code toevoegen aan adres deel van de KAKU code. //else bitstream=tempaddress & 0xFFFFFFCF; // adres geheel over nemen behalve de twee bits 5 en 6 die het schakel commando bevatten. if (cmd == VALUE_ON || cmd == VALUE_OFF) { bitstream|=(cmd == VALUE_ON)<<4; // bit-5 is het on/off commando in KAKU signaal x=130; // verzend startbit + 32-bits = 130 } else x=146; // verzend startbit + 32-bits = 130 + 4dimbits = 146 // bitstream bevat nu de KAKU-bits die verzonden moeten worden. // for(i=3;i<=x;i++) { // pRawSignal->Pulses[i]=NewKAKU_1T; // De meeste tijden in signaal zijn T. Vul alle pulstijden met deze waarde. Later worden de 4T waarden op hun plek gezet // } i=1; pRawSignal->Pulses[i++]=NewKAKU_1T; // Start bit 250 + 2600 s. pRawSignal->Pulses[i++]=NewKAKU_8T; byte y=31; // bit uit de bitstream while(i<x) { if ((bitstream>>(y--))&1) { // un bit a 1 c'est 250 + 1250 + 250 + 290 pRawSignal->Pulses[i++]=NewKAKU_1T; pRawSignal->Pulses[i++]=NewKAKU_4T; pRawSignal->Pulses[i++]=NewKAKU_1T; pRawSignal->Pulses[i++]=NewKAKU_2T; } else { // Un bit a 0 c'est 250 + 290 + 250 + 1250 pRawSignal->Pulses[i++]=NewKAKU_1T; pRawSignal->Pulses[i++]=NewKAKU_2T; pRawSignal->Pulses[i++]=NewKAKU_1T; pRawSignal->Pulses[i++]=NewKAKU_4T; } // if ((bitstream>>(y--))&1) // pRawSignal->Pulses[i+1]=NewKAKU_4T; // Bit=1; // T,4T,T,T // else // pRawSignal->Pulses[i+3]=NewKAKU_4T; // Bit=0; // T,T,T,4T // if (x==146) { // als het een dim opdracht betreft // if (i==111) // Plaats van de Commando-bit uit KAKU // pRawSignal->Pulses[i+3]=NewKAKU_1T; // moet een T,T,T,T zijn bij een dim commando. // if (i==127) { // als alle pulsen van de 32-bits weggeschreven zijn // bitstream=(unsigned long)cmd; // nog vier extra dim-bits om te verzenden. // y=3; // } // } // i+=4; } // On remet un pulse bit derrière ... car ça enchaine par un 250 + "silence ..." (fait par delay pour nous) pRawSignal->Pulses[i++]=NewKAKU_1T; pRawSignal->Number=i; //pRawSignal->Number=i-1; // aantal bits*2 die zich in het opgebouwde RawSignal bevinden success=true; } pRawSignal->Repeats = 5; // Leave default 3 value ? pRawSignal->Delay = 9900L; // Leave default 900 value ? // -------------------------------------- return success; }
#pragma once #include "FahrAusnahme.h" class Streckenende : public FahrAusnahme { public: Streckenende(Fahrzeug *pCar, Weg *pWay); ~Streckenende(void){}; virtual void vBearbeiten(); };
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Reactive.JavaScript/1.3.1/ThreadWorker.ScriptClass.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Reactive{struct ThreadWorker;}}} namespace g{namespace Fuse{namespace Reactive{struct ThreadWorker__ReadonlyPropertyClosure;}}} namespace g{namespace Fuse{namespace Scripting{struct Function;}}} namespace g{namespace Fuse{namespace Scripting{struct ScriptReadonlyProperty;}}} namespace g{ namespace Fuse{ namespace Reactive{ // private sealed class ThreadWorker.ReadonlyPropertyClosure :96 // { uType* ThreadWorker__ReadonlyPropertyClosure_typeof(); void ThreadWorker__ReadonlyPropertyClosure__ctor__fn(ThreadWorker__ReadonlyPropertyClosure* __this, ::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptReadonlyProperty* constant, ::g::Fuse::Reactive::ThreadWorker* worker); void ThreadWorker__ReadonlyPropertyClosure__New1_fn(::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptReadonlyProperty* constant, ::g::Fuse::Reactive::ThreadWorker* worker, ThreadWorker__ReadonlyPropertyClosure** __retval); struct ThreadWorker__ReadonlyPropertyClosure : uObject { void ctor_(::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptReadonlyProperty* constant, ::g::Fuse::Reactive::ThreadWorker* worker); static ThreadWorker__ReadonlyPropertyClosure* New1(::g::Fuse::Scripting::Function* cl, ::g::Fuse::Scripting::ScriptReadonlyProperty* constant, ::g::Fuse::Reactive::ThreadWorker* worker); }; // } }}} // ::g::Fuse::Reactive
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::inserirNaTabela(Aluno fulano, int linha) { ui->tbl_dados->setItem(linha,0,new QTableWidgetItem(fulano.getNome())); ui->tbl_dados->setItem(linha,1,new QTableWidgetItem(fulano.getMatricula())); ui->tbl_dados->setItem(linha,2,new QTableWidgetItem(calculoVeterano(fulano.veterano()))); ui->tbl_dados->setItem(linha,3,new QTableWidgetItem(calculoCurso(fulano.getCurso()))); } QString MainWindow::calculoVeterano(bool a) { QString resultado; if(a==false){ resultado="Não"; } else{ resultado="Sim"; } return resultado; } QString MainWindow::calculoCurso(int b) { QString resultado; if(b==1){resultado="Engenharia Elétrica";} else if(b==2){resultado="Administrção";} else if(b==3){resultado="Computação";} else if(b==4){resultado="Automação Industrial";} else if(b==5){resultado="Contabilidade";} else if(b==6){resultado="Design de Interiores";} else if(b==7){resultado="Engenharia Civil";} else if(b==8){resultado="Telecomunicações";} else if(b==9){resultado="Geoprocessamento";} else if(b==10){resultado="Engenharia Química";} return resultado; } void MainWindow::calcularQuantidade(Aluno b) { if(b.getCurso()==1){EE++;} else if(b.getCurso()==2){Admin++;} else if(b.getCurso()==3){Comput++;} else if(b.getCurso()==4){AI++;} else if(b.getCurso()==5){Cont++;} else if(b.getCurso()==6){DI++;} else if(b.getCurso()==7){EC++;} else if(b.getCurso()==8){Tele++;} else if(b.getCurso()==9){Geo++;} else if(b.getCurso()==10){EQ++;} } void MainWindow::mostrarQuantidade() { ui->lne_EngenhariaEletrica->setText(QString::number(EE)); ui->lne_Administracao->setText(QString::number(Admin)); ui->lne_Computacao->setText(QString::number(Comput)); ui->lne_AutomacaoIndustrial->setText(QString::number(AI)); ui->lne_Contabilidade->setText(QString::number(Cont)); ui->lne_DesignDeInteriores->setText(QString::number(DI)); ui->lne_EngenhariaCivil->setText(QString::number(EC)); ui->lne_Telecomunicacoes->setText(QString::number(Tele)); ui->lne_Geoprocessamento->setText(QString::number(Geo)); ui->lne_EngenhariaQuimica->setText(QString::number(EQ)); } void MainWindow::on_btn_inserir_clicked() { if(ui->lne_nome->text().size() != 0 && ui->lne_matricula->text().size() == 9){ Aluno fulano; fulano.setNome(ui->lne_nome->text()); fulano.setMatricula(ui->lne_matricula->text()); fulano.setCurso(); QString temporario=fulano.getMatricula(); if(fulano.getCurso()>0 && fulano.getCurso()<11 && temporario[4]>'0' && temporario[4]<'3'){ ui->lne_nome->clear(); ui->lne_matricula->clear(); bool temp=true; for(int i=0;i<Matriculados.size();i++){ if(Matriculados[i].getNome()==fulano.getNome() or Matriculados[i].getMatricula()==fulano.getMatricula()){ inserirNaTabela(fulano,i); temp=false; calcularQuantidade(fulano); if(Matriculados[i].getCurso()==1){EE--;} else if(Matriculados[i].getCurso()==2){Admin--;} else if(Matriculados[i].getCurso()==3){Comput--;} else if(Matriculados[i].getCurso()==4){AI--;} else if(Matriculados[i].getCurso()==5){Cont--;} else if(Matriculados[i].getCurso()==6){DI--;} else if(Matriculados[i].getCurso()==7){EC--;} else if(Matriculados[i].getCurso()==8){Tele--;} else if(Matriculados[i].getCurso()==9){Geo--;} else if(Matriculados[i].getCurso()==10){EQ--;} Matriculados.replace(i,fulano); } } if(temp==true){ int row = ui->tbl_dados->rowCount(); ui->tbl_dados->insertRow(row); inserirNaTabela(fulano, row); Matriculados.inserirAluno(fulano); calcularQuantidade(fulano); } mostrarQuantidade(); } else{QMessageBox::warning(this,"Erro","Matrícula inválida");} } } void MainWindow::on_btn_OrdenarNome_clicked() { ui->tbl_dados->clearContents(); Matriculados.ordenarPorNome(); for(int i = 0; i<Matriculados.size(); i++){ inserirNaTabela(Matriculados[i], i); } } void MainWindow::on_btn_OrdenarMatricula_clicked() { ui->tbl_dados->clearContents(); Matriculados.ordenarPorMatricula(); for(int i = 0; i<Matriculados.size(); i++){ inserirNaTabela(Matriculados[i], i); } } void MainWindow::on_btn_OrdenarCurso_clicked() { ui->tbl_dados->clearContents(); Matriculados.ordenarPorCurso(); for(int i = 0; i<Matriculados.size(); i++){ inserirNaTabela(Matriculados[i], i); } } void MainWindow::on_actionSalvar_triggered() { QString nome_arquivo = QFileDialog::getSaveFileName(this,"Salvar arquivo","","(*.txt)"); QFile arquivo(nome_arquivo); arquivo.open(QIODevice::WriteOnly); QTextStream saida(&arquivo); for(int i=0;i<Matriculados.size();i++){ saida<<Matriculados[i].getNome()<<" , "<<Matriculados[i].getMatricula()<<" , "<<calculoCurso(Matriculados[i].getCurso())<<endl; } arquivo.close(); } void MainWindow::on_actionCarregar_triggered() { ui->tbl_dados->clearContents(); Matriculados.clear(); QString nome_arquivo = QFileDialog::getOpenFileName(this,"Carregar arquivo","","(*.txt)"); QFile arquivo(nome_arquivo); arquivo.open(QIODevice::ReadOnly); QTextStream entrada(&arquivo); QString linha; while(!entrada.atEnd()){ linha=entrada.readLine(); QStringList dados=linha.split(" , "); Aluno a; a.setNome(dados[0]); a.setMatricula(dados[1]); a.setCurso(); Matriculados.inserirAluno(a); } for(int i=0;i<Matriculados.size();i++){ if(i >= ui->tbl_dados->rowCount()){ ui->tbl_dados->insertRow(i); } inserirNaTabela(Matriculados[i],i); calcularQuantidade(Matriculados[i]); } mostrarQuantidade(); arquivo.close(); }
class cxp_weapon_shop { idd = 38400; movingEnable = 0; enableSimulation = 1; class controlsBackground { class RscTitleBackground: cxp_RscText { colorBackground[] = {"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])", "(profilenamespace getvariable ['GUI_BCG_RGB_A',0.7])"}; idc = -1; x = 0.1; y = 0.2; w = 0.32; h = (1 / 25); }; class MainBackground: cxp_RscText { colorBackground[] = {0,0,0,0.7}; idc = -1; x = 0.1; y = 0.2 + (11 / 250); w = 0.32; h = 0.6 - (22 / 250); }; class Title: cxp_RscTitle { colorBackground[] = {0,0,0,0}; idc = 38401; text = ""; x = 0.1; y = 0.2; w = 0.32; h = (1 / 25); }; class itemInfo: cxp_RscStructuredText { idc = 38404; text = ""; sizeEx = 0.035; x = 0.11; y = 0.68; w = 0.2; h = 0.2; }; class FilterList: cxp_RscCombo { idc = 38402; onLBSelChanged = "_this call cxp_fnc_weaponShopFilter"; x = 0.11; y = 0.64; w = 0.3; h = 0.035; }; }; class controls { class itemList: cxp_RscListBox { idc = 38403; onLBSelChanged = "_this call cxp_fnc_weaponShopSelection"; sizeEx = 0.035; x = 0.11; y = 0.25; w = 0.3; h = 0.38; }; class ButtonBuyWithGang: cxp_RscButtonMenu { idc = 384115; text = "$STR_ATM_BuyWithGangButton"; onButtonClick = "if(playerSide isEqualTo civilian) then { [true] spawn cxp_fnc_weaponShopBuySell; true } else { hint ""Apenas rebeldes podem usar esta acao !""};"; x = 0.1 - (6.25 / 40) - (1 / 250 / (safezoneW / safezoneH)); y = 0.8 - (1 / 25); w = (6.25 / 40); h = (1 / 25); }; class ButtonBuySell: cxp_RscButtonMenu { idc = 38405; text = "$STR_Global_Buy"; onButtonClick = "[false] spawn cxp_fnc_weaponShopBuySell; true"; x = 0.1; y = 0.8 - (1 / 25); w = (6.25 / 40); h = (1 / 25); }; class ButtonClose: cxp_RscButtonMenu { idc = -1; text = "$STR_Global_Close"; onButtonClick = "closeDialog 0;"; x = 0.1 + (6.25 / 40) + (1 / 250 / (safezoneW / safezoneH)); y = 0.8 - (1 / 25); w = (6.25 / 40); h = (1 / 25); }; class ButtonMags: cxp_RscButtonMenu { idc = 38406; text = "$STR_Global_Mags"; onButtonClick = "_this call cxp_fnc_weaponShopMags; _this call cxp_fnc_weaponShopFilter"; x = 0.1; y = 0.8 + (1 / 250 / (safezoneW / safezoneH)); w = (6.25 / 40); h = (1 / 25); }; class ButtonAccs: cxp_RscButtonMenu { idc = 38407; text = "$STR_Global_Accs"; onButtonClick = "_this call cxp_fnc_weaponShopAccs; _this call cxp_fnc_weaponShopFilter"; x = 0.1 + (6.25 / 40) + (1 / 250 / (safezoneW / safezoneH)); y = 0.8 + (1 / 250 / (safezoneW / safezoneH)); w = (6.25 / 40); h = (1 / 25); }; }; };
#pragma once #include "ISpatial.h" namespace Hourglass { template<typename T, Aabb(*FB)(const T*), bool(*FR)(const T*, const Ray&, float*, Vector3*, uint16_t)> class QuadtreeNode { public: QuadtreeNode(const Vector2& center, float size, int depth = 0) { for (int i = 0; i < 4; i++) children[i] = nullptr; this->size = size; this->center = center; this->depth = depth; nodeBound.pMin.x = center.x - size * 0.5f; nodeBound.pMin.z = center.y - size * 0.5f; nodeBound.pMax.x = center.x + size * 0.5f; nodeBound.pMax.z = center.y + size * 0.5f; } ~QuadtreeNode() { for (int i = 0; i < 4; i++) { if (children[i]) delete children[i]; } } bool Insert(T* obj, const Aabb& aabb, int max_depth) { if (!Contains2D(nodeBound, aabb)) return false; // Extent aabb in y direction if (nodeBound.pMin.y > aabb.pMin.y) nodeBound.pMin.y = aabb.pMin.y; if (nodeBound.pMax.y < aabb.pMax.y) nodeBound.pMax.y = aabb.pMax.y; if (depth < max_depth) { // Try inserting into child nodes if (aabb.pMax.x <= center.x && aabb.pMax.z <= center.y) { if (!children[0]) children[0] = new QuadtreeNode((center + Vector2(nodeBound.pMin.x, nodeBound.pMin.z)) * 0.5f, size * 0.5f, depth + 1); children[0]->Insert(obj, aabb, max_depth); return true; } else if (aabb.pMax.x <= center.x && aabb.pMin.z >= center.y) { if (!children[1]) children[1] = new QuadtreeNode((center + Vector2(nodeBound.pMin.x, nodeBound.pMax.z)) * 0.5f, size * 0.5f, depth + 1); children[1]->Insert(obj, aabb, max_depth); return true; } else if (aabb.pMin.x >= center.x && aabb.pMin.z >= center.y) { if (!children[2]) children[2] = new QuadtreeNode((center + Vector2(nodeBound.pMax.x, nodeBound.pMax.z)) * 0.5f, size * 0.5f, depth + 1); children[2]->Insert(obj, aabb, max_depth); return true; } else if (aabb.pMin.x >= center.x && aabb.pMax.z <= center.y) { if (!children[3]) children[3] = new QuadtreeNode((center + Vector2(nodeBound.pMax.x, nodeBound.pMin.z)) * 0.5f, size * 0.5f, depth + 1); children[3]->Insert(obj, aabb, max_depth); return true; } } objects.push_back(obj); return true; } bool RayCast(Ray& ray, T** outObj, float *t, Vector3* outNormal, uint16_t collisionGroupMasks) { if (!ray.Intersects(nodeBound) && !nodeBound.Contains(ray.Origin)) return false; //DebugRenderer::DrawAabb(nodeBound, Color(0, 1, 0)); bool result = false; // Test ray with objects in current node for (uint32_t i = 0; i < objects.size(); i++) { if (FR(objects[i], ray, t, outNormal, collisionGroupMasks)) { ray.Distance = *t; result = true; *outObj = objects[i]; } } // Test ray with objects in child nodes for (int i = 0; i < 4; i++) { if (children[i]) result |= children[i]->RayCast(ray, outObj, t, outNormal, collisionGroupMasks); } return result; } void DebugDrawNode() { DebugRenderer::DrawAabb(nodeBound); for (int i = 0; i < 4; i++) { if (children[i]) children[i]->DebugDrawNode(); } } void DebugPrint(int depth = 0) { for (int i = 0; i < objects.size(); i++) { for (int j = 0; j < depth; j++) { OutputDebugStringA(" "); } OutputDebugStringA(objects[i]->GetEntity()->GetName().c_str()); OutputDebugStringA("\n"); } for (int i = 0; i < 4; i++) { if (children[i]) { for (int j = 0; j < depth; j++) { OutputDebugStringA(" "); } char buf[1024]; sprintf_s(buf, "Child %d (depth: %d)\n", i, depth + 1); OutputDebugStringA(buf); children[i]->DebugPrint(depth + 1); } } } QuadtreeNode* children[4]; Aabb nodeBound; float size; Vector2 center; // XZ center of bound std::vector<T*> objects; int depth; private: // Return if a contains b in xz direction static bool Contains2D(const Aabb& a, const Aabb& b) { if (b.pMin.x < a.pMin.x || b.pMax.x > a.pMax.x) return false; if (b.pMin.z < a.pMin.z || b.pMax.z > a.pMax.z) return false; return true; } }; template<typename T, Aabb(*FB)(const T*), bool(*FR)(const T*, const Ray&, float*, Vector3*, uint16_t)> class Quadtree : public ISpatial { public: Quadtree(int max_depth = 4) : m_Root(nullptr), m_MaxDepth(max_depth) { } ~Quadtree() { delete m_Root; } void Init(const std::vector<T*>& objs) { Aabb treeBound; for (uint32_t i = 0; i < objs.size(); i++) { treeBound.Expand(FB(objs[i])); } Vector3 center = treeBound.GetCenter(); float size_x = treeBound.pMax.x - treeBound.pMin.x; float size_z = treeBound.pMax.z - treeBound.pMin.z; float size = max(size_x, size_z) + 10.0f; assert(m_Root == nullptr); m_Root = new QuadtreeNode<T, FB, FR>(Vector2(center.x, center.z), size); //m_Root = new QuadtreeNode<T, FB, FR>(Vector2(0, 0), 200); for (uint32_t i = 0; i < objs.size(); i++) { m_Root->Insert(objs[i], FB(objs[i]), m_MaxDepth); } } void DebugRender() { m_Root->DebugDrawNode(); } bool RayCast(const Ray& ray, T** outObj, float *t = nullptr, Vector3* outNormal = nullptr, uint16_t collisionGroupMasks = COLLISION_GROUP_ALL) { Ray testRay = ray; return m_Root->RayCast(testRay, outObj, t, outNormal, collisionGroupMasks); } void DebugPrint() { OutputDebugStringA("*** Begin Print Quadtree ***\n"); m_Root->DebugPrint(); OutputDebugStringA("*** End Print Quadtree ***\n"); } private: QuadtreeNode<T, FB, FR>* m_Root; int m_MaxDepth; }; }
// Created on: 1993-01-11 // Created by: CKY / Contract Toubro-Larsen ( TCD ) // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESGraph_TextDisplayTemplate_HeaderFile #define _IGESGraph_TextDisplayTemplate_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <gp_XYZ.hxx> #include <IGESData_IGESEntity.hxx> class IGESGraph_TextFontDef; class gp_Pnt; class IGESGraph_TextDisplayTemplate; DEFINE_STANDARD_HANDLE(IGESGraph_TextDisplayTemplate, IGESData_IGESEntity) //! defines IGES TextDisplayTemplate Entity, //! Type <312>, form <0, 1> in package IGESGraph //! //! Used to set parameters for display of information //! which has been logically included in another entity //! as a parameter value class IGESGraph_TextDisplayTemplate : public IGESData_IGESEntity { public: Standard_EXPORT IGESGraph_TextDisplayTemplate(); //! This method is used to set the fields of the class //! TextDisplayTemplate //! - aWidth : Character box width //! - aHeight : Character box height //! - afontCode : Font code //! - aFontEntity : Text Font Definition Entity //! - aSlantAngle : Slant angle //! - aRotationAngle : Rotation angle //! - aMirrorFlag : Mirror Flag //! - aRotationFlag : Rotate internal text flag //! - aCorner : Lower left corner coordinates(Form No. 0), //! Increments from coordinates (Form No. 1) Standard_EXPORT void Init (const Standard_Real aWidth, const Standard_Real aHeight, const Standard_Integer aFontCode, const Handle(IGESGraph_TextFontDef)& aFontEntity, const Standard_Real aSlantAngle, const Standard_Real aRotationAngle, const Standard_Integer aMirrorFlag, const Standard_Integer aRotationFlag, const gp_XYZ& aCorner); //! Sets <me> to be Incremental (Form 1) if <mode> is True, //! or Basolute (Form 0) else Standard_EXPORT void SetIncremental (const Standard_Boolean mode); //! returns True if entity is Incremental (Form 1). //! False if entity is Absolute (Form 0). Standard_EXPORT Standard_Boolean IsIncremental() const; //! returns Character Box Width. Standard_EXPORT Standard_Real BoxWidth() const; //! returns Character Box Height. Standard_EXPORT Standard_Real BoxHeight() const; //! returns False if theFontEntity is Null, True otherwise. Standard_EXPORT Standard_Boolean IsFontEntity() const; //! returns the font code. Standard_EXPORT Standard_Integer FontCode() const; //! returns Text Font Definition Entity used to define the font. Standard_EXPORT Handle(IGESGraph_TextFontDef) FontEntity() const; //! returns slant angle of character in radians. Standard_EXPORT Standard_Real SlantAngle() const; //! returns Rotation angle of text block in radians. Standard_EXPORT Standard_Real RotationAngle() const; //! returns Mirror flag //! Mirror flag : 0 = no mirroring. //! 1 = mirror axis perpendicular to text base line. //! 2 = mirror axis is text base line. Standard_EXPORT Standard_Integer MirrorFlag() const; //! returns Rotate internal text flag. //! Rotate internal text flag : 0 = text horizontal. //! 1 = text vertical. Standard_EXPORT Standard_Integer RotateFlag() const; //! If IsIncremental() returns False, //! gets coordinates of lower left corner //! of first character box. //! If IsIncremental() returns True, //! gets increments from X, Y, Z coordinates //! found in parent entity. Standard_EXPORT gp_Pnt StartingCorner() const; //! If IsIncremental() returns False, //! gets coordinates of lower left corner //! of first character box. //! If IsIncremental() returns True, //! gets increments from X, Y, Z coordinates //! found in parent entity. Standard_EXPORT gp_Pnt TransformedStartingCorner() const; DEFINE_STANDARD_RTTIEXT(IGESGraph_TextDisplayTemplate,IGESData_IGESEntity) protected: private: Standard_Real theBoxWidth; Standard_Real theBoxHeight; Standard_Integer theFontCode; Handle(IGESGraph_TextFontDef) theFontEntity; Standard_Real theSlantAngle; Standard_Real theRotationAngle; Standard_Integer theMirrorFlag; Standard_Integer theRotateFlag; gp_XYZ theCorner; }; #endif // _IGESGraph_TextDisplayTemplate_HeaderFile
#ifndef _ChangeCardResultProc_H_ #define _ChangeCardResultProc_H_ #include "BaseProcess.h" class ChangeCardResultProc :public BaseProcess { public: ChangeCardResultProc(); virtual ~ChangeCardResultProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); private: }; #endif
// Created on: 1994-03-21 // Created by: Bruno DUMORTIER // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomAPI_PointsToBSpline_HeaderFile #define _GeomAPI_PointsToBSpline_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColgp_Array1OfPnt.hxx> #include <Standard_Integer.hxx> #include <GeomAbs_Shape.hxx> #include <Approx_ParametrizationType.hxx> #include <TColStd_Array1OfReal.hxx> class Geom_BSplineCurve; //! This class is used to approximate a BsplineCurve //! passing through an array of points, with a given Continuity. //! Describes functions for building a 3D BSpline //! curve which approximates a set of points. //! A PointsToBSpline object provides a framework for: //! - defining the data of the BSpline curve to be built, //! - implementing the approximation algorithm, and consulting the results. class GeomAPI_PointsToBSpline { public: DEFINE_STANDARD_ALLOC //! Constructs an empty approximation algorithm. //! Use an Init function to define and build the BSpline curve. Standard_EXPORT GeomAPI_PointsToBSpline(); //! Approximate a BSpline Curve passing through an //! array of Point. The resulting BSpline will have //! the following properties: //! 1- his degree will be in the range [Degmin,Degmax] //! 2- his continuity will be at least <Continuity> //! 3- the distance from the point <Points> to the //! BSpline will be lower to Tol3D Standard_EXPORT GeomAPI_PointsToBSpline(const TColgp_Array1OfPnt& Points, const Standard_Integer DegMin = 3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point. The resulting BSpline will have //! the following properties: //! 1- his degree will be in the range [Degmin,Degmax] //! 2- his continuity will be at least <Continuity> //! 3- the distance from the point <Points> to the //! BSpline will be lower to Tol3D Standard_EXPORT GeomAPI_PointsToBSpline(const TColgp_Array1OfPnt& Points, const Approx_ParametrizationType ParType, const Standard_Integer DegMin = 3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point, which parameters are given by the //! array <Parameters>. //! The resulting BSpline will have the following //! properties: //! 1- his degree will be in the range [Degmin,Degmax] //! 2- his continuity will be at least <Continuity> //! 3- the distance from the point <Points> to the //! BSpline will be lower to Tol3D Standard_EXPORT GeomAPI_PointsToBSpline(const TColgp_Array1OfPnt& Points, const TColStd_Array1OfReal& Parameters, const Standard_Integer DegMin = 3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point using variational smoothing algorithm, //! which tries to minimize additional criterium: //! Weight1*CurveLength + Weight2*Curvature + Weight3*Torsion Standard_EXPORT GeomAPI_PointsToBSpline(const TColgp_Array1OfPnt& Points, const Standard_Real Weight1, const Standard_Real Weight2, const Standard_Real Weight3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point. The resulting BSpline will have //! the following properties: //! 1- his degree will be in the range [Degmin,Degmax] //! 2- his continuity will be at least <Continuity> //! 3- the distance from the point <Points> to the //! BSpline will be lower to Tol3D Standard_EXPORT void Init (const TColgp_Array1OfPnt& Points, const Standard_Integer DegMin = 3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point. The resulting BSpline will have //! the following properties: //! 1- his degree will be in the range [Degmin,Degmax] //! 2- his continuity will be at least <Continuity> //! 3- the distance from the point <Points> to the //! BSpline will be lower to Tol3D Standard_EXPORT void Init (const TColgp_Array1OfPnt& Points, const Approx_ParametrizationType ParType, const Standard_Integer DegMin = 3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point, which parameters are given by the //! array <Parameters>. //! The resulting BSpline will have the following //! properties: //! 1- his degree will be in the range [Degmin,Degmax] //! 2- his continuity will be at least <Continuity> //! 3- the distance from the point <Points> to the //! BSpline will be lower to Tol3D Standard_EXPORT void Init (const TColgp_Array1OfPnt& Points, const TColStd_Array1OfReal& Parameters, const Standard_Integer DegMin = 3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Approximate a BSpline Curve passing through an //! array of Point using variational smoothing algorithm, //! which tries to minimize additional criterium: //! Weight1*CurveLength + Weight2*Curvature + Weight3*Torsion Standard_EXPORT void Init (const TColgp_Array1OfPnt& Points, const Standard_Real Weight1, const Standard_Real Weight2, const Standard_Real Weight3, const Standard_Integer DegMax = 8, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Real Tol3D = 1.0e-3); //! Returns the computed BSpline curve. //! Raises StdFail_NotDone if the curve is not built. Standard_EXPORT const Handle(Geom_BSplineCurve)& Curve() const; Standard_EXPORT operator Handle(Geom_BSplineCurve)() const; Standard_EXPORT Standard_Boolean IsDone() const; protected: private: Standard_Boolean myIsDone; Handle(Geom_BSplineCurve) myCurve; }; #endif // _GeomAPI_PointsToBSpline_HeaderFile
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ /* * Copyright (C) Opera Software ASA 1995-2011 */ #ifndef ES_CLONE_OBJECT_H #define ES_CLONE_OBJECT_H #include "modules/ecmascript/structured/es_clone.h" #include "modules/util/OpHashTable.h" #include "modules/util/adt/opvector.h" class ES_CloneToObject : public ES_CloneBackend { public: ES_CloneToObject(ES_Runtime *runtime, ES_Context *context); virtual ~ES_CloneToObject(); virtual void PushNullL(); virtual void PushUndefinedL(); virtual void PushBooleanL(BOOL value); virtual void PushNumberL(double value); virtual void PushStringL(const uni_char *value, unsigned length); virtual void PushStringL(unsigned index); virtual void PushObjectL(unsigned index); virtual void StartObjectL(); virtual void StartObjectBooleanL(); virtual void StartObjectNumberL(); virtual void StartObjectStringL(); virtual void StartObjectArrayL(); virtual void StartObjectRegExpL(); virtual void StartObjectDateL(); virtual void StartObjectArrayBufferL(const unsigned char *value, unsigned length); virtual void StartObjectTypedArrayL(unsigned kind, unsigned offset, unsigned size); virtual void AddPropertyL(int attributes); virtual BOOL HostObjectL(EcmaScript_Object *source_object); #ifdef ES_PERSISTENT_SUPPORT virtual BOOL HostObjectL(ES_PersistentItem *source_item); #endif // ES_PERSISTENT_SUPPORT ES_Value_Internal &GetResult() { OP_ASSERT(stack_used == 1); return stack[0]; } OP_STATUS AddTransferObject(ES_Object *object); private: ES_Runtime *runtime; ES_Context *context; ES_Global_Object *global; OpVector<ES_Object> objects; void AddObjectL(ES_Object *object); BOOL HostObjectL(EcmaScript_Object *source_object, ES_PersistentItem *source_item); OpVector<JString> strings; ES_Value_Internal *stack; unsigned stack_used, stack_size; void GrowStackL(); }; class ES_CloneFromObject : public ES_CloneFrontend { public: ES_CloneFromObject(ES_Runtime *runtime, ES_Context *context, const ES_Value_Internal &value, ES_Runtime::CloneStatus &status, BOOL uncloned_to_null); virtual ~ES_CloneFromObject(); virtual void CloneL(ES_CloneBackend *target); OP_STATUS AddTransferObject(ES_Object *object); private: ES_Runtime *runtime; ES_Context *context; ES_Value_Internal value; ES_Runtime::CloneStatus &status; BOOL uncloned_to_null; ES_CloneBackend *target; OpPointerHashTable<ES_Object, int> objects; unsigned objects_count; ES_Identifier_List *strings; void OutputValueL(const ES_Value_Internal &value); void OutputStringL(JString *string); void OutputObjectL(ES_Object *object); void OutputPropertiesL(ES_Object *object); void FailL(ES_Runtime::CloneStatus::FaultReason reason, ES_Object *object); }; #endif // ES_CLONE_OBJECT_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #ifdef DATASTREAM_SEQUENCE_ENABLED #include "modules/datastream/fl_lib.h" void DataStream_BaseRecord::IndexRecordsL() { ResetRead(); payload_records_index.Clear(); while(MoreData()) { DataStream_BaseRecord *next_record = (DataStream_BaseRecord *) GetNextRecordL(); if(next_record == NULL || !next_record->Finished()) { // OOM safe: next_record is owned by this object, and is only released when it is finished break; } next_record->Into(&payload_records_index); } } DataStream_BaseRecord *DataStream_BaseRecord::GetIndexedRecord(uint32 _tag) { DataStream_BaseRecord *current_record; current_record = (DataStream_BaseRecord *) payload_records_index.First(); while(current_record && current_record->GetTag() != _tag) current_record = (DataStream_BaseRecord *) current_record->Suc(); return current_record; } DataStream_BaseRecord *DataStream_BaseRecord::GetIndexedRecord(DataStream_BaseRecord *p_rec, uint32 _tag) { DataStream_BaseRecord *current_record; current_record = (DataStream_BaseRecord *) payload_records_index.First(); while(current_record && current_record != p_rec) current_record = (DataStream_BaseRecord *) current_record->Suc(); if(current_record) current_record = (DataStream_BaseRecord *) current_record->Suc(); while(current_record && current_record->GetTag() != _tag) current_record = (DataStream_BaseRecord *) current_record->Suc(); return current_record; } OP_STATUS DataStream_BaseRecord::ReadRecordFromIndexedRecordL(DataStream *target, uint32 tag, BOOL content_only) { if(target == NULL) DS_LEAVE(OpRecStatus::ERR_NULL_POINTER); DataStream_BaseRecord *rec1 = GetIndexedRecord(tag); if(rec1 == NULL) return OpRecStatus::RECORD_NOT_FOUND; if(content_only) { target->AddContentL(rec1); return OpRecStatus::FINISHED; } return target->ReadRecordFromStreamL(rec1); } DataStream_BaseRecord::DataStream_BaseRecord() : read_tag_field(FALSE),read_length_field(FALSE), default_tag(4), default_length(4), payload_source(NULL), tag(&default_tag), length(&default_length) { default_tag.SetItemID(DataStream_BaseRecord::RECORD_TAG); default_length.SetItemID(DataStream_BaseRecord::RECORD_LENGTH); tag.Into(this); length.Into(this); } const DataRecord_Spec *DataStream_BaseRecord::GetRecordSpec() { return &spec; } #ifdef DATASTREAM_USE_SWAP_TAG_LEN_FUNC void DataStream_BaseRecord::SwapTagAndLength() { OP_ASSERT(tag.InList()); OP_ASSERT(length.InList()); if(tag.Suc() == &length) { length.Out(); length.Precede(&tag); } else if(tag.Pred() == &length) { length.Out(); length.Follow(&tag); } else { DataStream *len_suc = length.Suc(); length.Out(); length.Follow(&tag); tag.Out(); if(len_suc) tag.Precede(len_suc); else tag.Into(this); } } #endif #ifdef DATASTREAM_USE_ADV_TAG_LEN_FUNC void DataStream_BaseRecord::RegisterTag(DataStream_UIntBase *app_tag) { if(app_tag) app_tag->SetItemID(DataStream_BaseRecord::RECORD_TAG); tag.SetReference(app_tag ? app_tag : &default_tag); } void DataStream_BaseRecord::RegisterLength(DataStream_UIntBase *app_length) { if(app_length) app_length->SetItemID(DataStream_BaseRecord::RECORD_LENGTH); length.SetReference(app_length ? app_length : &default_length); } #endif // DATASTREAM_USE_ADV_TAG_LEN_FUNC void DataStream_BaseRecord::SetRecordSpec(const DataRecord_Spec &new_spec) { spec = new_spec; default_tag.SetSize(spec.idtag_len); default_tag.SetBigEndian(spec.tag_big_endian); default_tag.SetMSBDetection(spec.tag_MSB_detection); default_length.SetSize(spec.length_len); default_length.SetBigEndian(spec.length_big_endian); tag.SetEnableRecord(spec.enable_tag); length.SetEnableRecord(spec.enable_length); } /* DataStream *DataStream_BaseRecord::CreateRecordL() { return NULL; } */ void DataStream_BaseRecord::PerformActionL(DataStream::DatastreamAction action, uint32 arg1, uint32 arg2) { switch(action) { case DataStream::KSetTag: tag->SetValue(arg1); break; case DataStream::KWriteAction: case DataStream::KReadAction: { uint32 step = arg1; int record_item_id = (int) arg2; if(record_item_id == DataStream_SequenceBase::STRUCTURE_START) { const DataRecord_Spec *spec = GetRecordSpec(); tag.SetEnableRecord(TRUE); //tag.SetItemID(DataStream_BaseRecord::RECORD_TAG); length.SetEnableRecord(TRUE); //length.SetItemID(DataStream_BaseRecord::RECORD_LENGTH); if(action == DataStream::KReadAction) { read_tag_field = FALSE; read_length_field= FALSE; } else // if(action == DataStream::KWriteAction) { length->SetValue(CalculatePayloadLength()); DS_DEBUG_Start(); #ifdef _DATASTREAM_DEBUG_ if(tag.GetEnabledRecord()) DS_Debug_Printf2("Initiating write record Tag %d (%x)\n", tag->GetValue(), tag->GetValue()); if(length.GetEnabledRecord()) DS_Debug_Printf2("Initiating write record Length %d (%x)\n", length->GetValue(), length->GetValue()); #endif } if(spec) { tag.SetEnableRecord(spec->enable_tag); if(spec->enable_tag) { default_tag.SetSize(spec->idtag_len); default_tag.SetBigEndian(spec->tag_big_endian); default_tag.SetMSBDetection(spec->tag_MSB_detection); } length.SetEnableRecord(spec->enable_length); if(spec->enable_length) { default_length.SetSize(spec->length_len); default_length.SetBigEndian(spec->length_big_endian); } if(action == DataStream::KReadAction) { read_tag_field = !spec->enable_tag; read_length_field= !spec->enable_length; } else if(spec->tag_MSB_detection && (tag->GetValue() & MSB_VALUE) != 0) { length.SetEnableRecord(FALSE); } } } DataStream_SequenceBase::PerformActionL(action, step, record_item_id); switch(record_item_id) { case DataStream_SequenceBase::STRUCTURE_START: if(action == DataStream::KWriteAction) { length->SetValue(CalculatePayloadLength()); DS_DEBUG_Start(); #ifdef _DATASTREAM_DEBUG_ if(tag.GetEnabledRecord()) DS_Debug_Printf2("Initiating write record Tag %d (%x)\n", tag->GetValue(), tag->GetValue()); if(length.GetEnabledRecord()) DS_Debug_Printf2("Initiating write record Length %d (%x)\n", length->GetValue(), length->GetValue()); #endif } break; case DataStream_BaseRecord::RECORD_TAG: if(action == DataStream::KReadAction && tag.GetEnabledRecord()) { DS_DEBUG_Start(); DS_Debug_Printf2("Read Tag %d (%x)\n", tag->GetValue(), tag->GetValue()); read_tag_field = TRUE; if(spec.tag_MSB_detection && (tag->GetValue() & MSB_VALUE) != 0) { length.SetEnableRecord(FALSE); read_length_field = TRUE; payload_source.SetReadLength(0); } } break; case DataStream_BaseRecord::RECORD_LENGTH: if(action == DataStream::KReadAction && length.GetEnabledRecord()) { DS_DEBUG_Start(); DS_Debug_Printf2("Read Length %d (%x)\n", length->GetValue(), length->GetValue()); read_length_field = TRUE; payload_source.SetReadLength(length->GetValue()); } break; } } return; } DataStream_SequenceBase::PerformActionL(action, arg1, arg2); } void DataStream_BaseRecord::SetTag(uint32 tag_number) { tag->SetValue(tag_number); } DataStream *DataStream_BaseRecord::GetInputSource(DataStream *src) { if(read_length_field) { payload_source.SetStreamSource(DataStream_SequenceBase::GetInputSource(src), FALSE); return &payload_source; } return DataStream_SequenceBase::GetInputSource(src); } uint32 DataStream_BaseRecord::CalculatePayloadLength() { uint32 len = 0; OP_ASSERT(length.InList()); DataStream *item = length.Suc(); while(item) { if(item->GetEnabledRecord()) len += item->CalculateLength(); item = item->Suc(); } return len; } uint32 DataStream_BaseRecord::GetAttribute(DataStream::DatastreamUIntAttribute attr) { if(attr == DataStream::KFinished) return (DataStream_SequenceBase::GetAttribute(attr) && !payload_source.GetAttribute(DataStream::KMoreData)); return DataStream_SequenceBase::GetAttribute(attr); } #if defined _SSL_SUPPORT_ OP_STATUS DataStream_BaseRecord::PerformStreamActionL(DataStream::DatastreamStreamAction action, DataStream *src_target) { switch(action) { case DataStream::KReadRecordHeader: { DataStream *item = GetLastHeaderElement(); return (item ? ReadRecordSequenceFromStreamL(src_target, item) : OpRecStatus::FINISHED); } case DataStream::KWriteRecordHeader: case DataStream::KWriteRecordPayload: { DataStream *last_item = GetLastHeaderElement(); DataStream *first_item = NULL; if(action == DataStream::KWriteRecordPayload) { first_item = last_item; last_item = NULL; } if(action == DataStream::KWriteRecordPayload || last_item) // header write only of there is a header => Last_item != NULL, always write for payload WriteRecordSequenceL(src_target, TRUE, first_item, last_item); return OpRecStatus::FINISHED; } } return DataStream_SequenceBase::PerformStreamActionL(action, src_target); } #endif DataStream *DataStream_BaseRecord::GetLastHeaderElement() { DataStream *item = (tag.InList() ? &tag : NULL); if(!item || (length.InList() && !length.Precedes(item))) item = (length.InList() ? &length : NULL); return item; } #endif
#include "llvm/Pass.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/IR/BasicBlock.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/IR/IRBuilder.h" #include <map> #include <iterator> #include <numeric> using namespace llvm; std::string fname_count = "_Z10count_instPci"; std::string fname_printInfo = "_Z10print_infov"; namespace { struct DynamicInstructionsCount : public ModulePass { static char ID; DynamicInstructionsCount() : ModulePass(ID) {} virtual bool runOnModule(Module &M) { // to remove printf calls //std::vector<Instruction*> to_remove; // Function inst_count // Function type std::vector<Type*> fargs_count; fargs_count.push_back(Type::getInt8PtrTy(M.getContext())); fargs_count.push_back(IntegerType::get(M.getContext(),32)); FunctionType *ftype_count = FunctionType::get(Type::getVoidTy(M.getContext()), fargs_count, false); // Create function Function *func_count = (Function*)M.getOrInsertFunction(fname_count, ftype_count); // Function printInfo // Function type FunctionType *ftype_printInfo = FunctionType::get(Type::getVoidTy(M.getContext()), false); // Create function Function *func_printInfo = (Function*)M.getOrInsertFunction(fname_printInfo, ftype_printInfo); for (auto& F : M) { for (auto& B : F) { for (auto& I : B) { // Get required info std::string inst_name = I.getOpcodeName(); int inst_code = I.getOpcode(); if (inst_name == "phi") continue; // Create builder auto* inst = &I; IRBuilder<> builder(inst); // Arguments for the function std::vector<Value*> fparams_count; Value *inst_name_ptr = builder.CreateGlobalStringPtr(inst_name.c_str()); Value *inst_code_ptr = builder.getInt32(inst_code); fparams_count.push_back(inst_name_ptr); fparams_count.push_back(inst_code_ptr); // Create func. call builder.CreateCall(func_count, fparams_count); if (I.getParent()->getParent()->getName() == "main" && inst_name == "ret") { IRBuilder<> builder(inst); builder.CreateCall(func_printInfo); } } } } return true; } }; } char DynamicInstructionsCount::ID = 0; static RegisterPass<DynamicInstructionsCount> X("dcount", "Dynamic Instructions Count Pass", false, false); static void registerDynamicInstructionsCount(const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(new DynamicInstructionsCount()); } static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible, registerDynamicInstructionsCount);
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef SEARCHMAIL_H #define SEARCHMAIL_H #include "adjunct/quick_toolkit/widgets/Dialog.h" class MailDesktopWindow; /*********************************************************************************** ** ** SearchMailDialog ** ***********************************************************************************/ class SearchMailDialog : public Dialog { public: virtual ~SearchMailDialog(); void Init(MailDesktopWindow* parent_window, int index_id, int search_index_id = 0); Type GetType() {return DIALOG_TYPE_SEARCH_MAIL;} const char* GetWindowName() {return "Search Mail Dialog";} const char* GetHelpAnchor() {return "mail.html#search";} virtual void OnInit(); virtual UINT32 OnOk(); virtual void OnCancel(); virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse); private: MailDesktopWindow* m_parent_window; int m_index_id; int m_search_index_id; }; #endif //SEARCHMAIL_H
#include<iostream> using namespace std; #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef char TElemType ; typedef struct BiTNode { TElemType data; struct BiTNode *lchild,*rchild; } BiTNode,*BiTree; typedef BiTree SElemType ; typedef struct { SElemType *base; SElemType *top; int stacksize; } SqStack; int InitStack(SqStack &S) { try { S.base=new SElemType[STACK_INIT_SIZE]; S.top=S.base; S.stacksize=STACK_INIT_SIZE; return OK; } catch ( const bad_alloc& e ) { exit(OVERFLOW); } } int GetTop(SqStack S,SElemType &e) { if(S.top==S.base)return ERROR; e=*(S.top-1); return OK; } int Push(SqStack &S,SElemType e) { if(S.top-S.base>=S.stacksize) { } *S.top++=e; return OK; } int Pop(SqStack &S,SElemType &e) { if(S.top==S.base)return ERROR; e = *--S.top; return OK; } int StackEmpty(SqStack S) { return S.top==S.base; } int CreateBiTree(BiTree &T) { TElemType ch; cin.get(ch); if(ch==' ') T = NULL; else { try { T=new BiTNode; T->data=ch; cout<<"running.."<<endl; CreateBiTree(T->lchild); CreateBiTree(T->rchild); return OK; } catch ( const bad_alloc& e ) { exit(OVERFLOW); } } } int PreOrderTraverse(BiTree T) { if(T) { cout<<T->data<<" "; PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); } } int InOrderTraverse(BiTree T) { if(T) { InOrderTraverse(T->lchild); cout<<T->data<<" "; InOrderTraverse(T->rchild); } } int PostOrderTraverse(BiTree T) { if(T) { PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild); cout<<T->data<<" "; } } void Inder(BiTree T) { SqStack S; InitStack(S); while(T!=NULL||!StackEmpty(S)) { if(T) { Push(S,T); T=T->lchild; } else { if(!StackEmpty(S)) { Pop(S,T); cout<<T->data<<" "; T=T->rchild; } } } } void Postder(BiTree T) { SqStack S; InitStack(S); while(T!=NULL||!StackEmpty(S)) { if(T) { Push(S,T); T=T->lchild; } else { if(!StackEmpty(S)) { Pop(S,T); cout<<T->data<<" "; T=T->rchild; } } } } void Preder(BiTree T) {//xianxu SqStack S; InitStack(S); while(T!=NULL||!StackEmpty(S)) { if(T) { Push(S,T); cout<<T->data<<" "; T=T->lchild; } else { if(!StackEmpty(S)) { Pop(S,T); T=T->rchild; } } } } int main() { BiTree T; CreateBiTree(T); PreOrderTraverse(T); cout<<endl; cout<<"pre:"<<endl; Preder(T); cout<<endl; InOrderTraverse(T); cout<<endl; cout<<"zh:"<<endl; Inder(T); cout<<endl; PostOrderTraverse(T); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #ifndef SSLSNLIST_H #define SSLSNLIST_H #ifdef _NATIVE_SSL_SUPPORT_ class SSL_ServerName_List : public SSL_Error_Status { public: class SNList_string : public OpAutoVector<OpString8> { public: OP_STATUS AddString(const char *str, int len); }; SNList_string DNSNames; SSL_varvector16_list IPadr_List; OpAutoVector<OpString8> CommonNames; OpString8 Namelist; OpString Matched_name; public: SSL_ServerName_List(); void Reset(); BOOL MatchName(ServerName *servername); BOOL MatchNameRegexp(ServerName *servername, OpStringC8 *name, BOOL reg_exp); private: void InternalInit(); }; #endif // _NATIVE_SSL_SUPPORT_ #endif /* SSLSNLIST_H */
// Copyright (c) 2020 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Aspect_XRGenericAction_HeaderFile #define _Aspect_XRGenericAction_HeaderFile //! Generic XR action. enum Aspect_XRGenericAction { Aspect_XRGenericAction_IsHeadsetOn, //!< headset is on/off head Aspect_XRGenericAction_InputAppMenu, //!< application menu button pressed/released Aspect_XRGenericAction_InputSysMenu, //!< system menu button pressed/released Aspect_XRGenericAction_InputTriggerPull, //!< trigger squeezing [0..1], 1 to click Aspect_XRGenericAction_InputTriggerClick, //!< trigger clicked/released Aspect_XRGenericAction_InputGripClick, //!< grip state on/off Aspect_XRGenericAction_InputTrackPadPosition, //!< trackpad 2D position [-1,+1] with X and Y axes Aspect_XRGenericAction_InputTrackPadTouch, //!< trackpad touched/untouched Aspect_XRGenericAction_InputTrackPadClick, //!< trackpad clicked/released Aspect_XRGenericAction_InputThumbstickPosition, //!< thumbstick 2D position [-1,+1] with X and Y axes Aspect_XRGenericAction_InputThumbstickTouch, //!< thumbstick touched/untouched Aspect_XRGenericAction_InputThumbstickClick, //!< thumbstick clicked/released Aspect_XRGenericAction_InputPoseBase, //!< base position of hand Aspect_XRGenericAction_InputPoseFront, //!< front position of hand Aspect_XRGenericAction_InputPoseHandGrip, //!< position of main handgrip Aspect_XRGenericAction_InputPoseFingerTip, //!< position of main fingertip Aspect_XRGenericAction_OutputHaptic //!< haptic output (vibration) }; enum { Aspect_XRGenericAction_NB = Aspect_XRGenericAction_OutputHaptic + 1 }; #endif // _Aspect_XRGenericAction_HeaderFile
#pragma once #using <mscorlib.dll> #include "llvm/IR/Module.h" #include "Metadata.h" #include "Value.h" namespace LLVM { ref class LLVMContext; ref class GlobalValue; ref class StructType; ref class FunctionType; ref class AttributeSet; ref class Constant; ref class Function; ref class GlobalVariable; ref class Type; ref class GlobalAlias; ref class NamedMDNode; ref class Value; ref class MDNode; ref class GVMaterializer; ref class ValueSymbolTable; ref class raw_ostream; ref class AssemblyAnnotationWriter; public ref class Module { public: enum class Endianness { AnyEndianness, LittleEndian, BigEndian }; enum class PointerSize { AnyPointerSize, Pointer32, Pointer64 }; enum class ModFlagBehavior { Error = 1, Warning = 2, Require = 3, Override = 4, Append = 5, AppendUnique = 6 }; value class ModuleFlagEntry { public: ModFlagBehavior ^Behavior; MDString ^Key; Value ^Val; ModuleFlagEntry(ModFlagBehavior B, MDString ^K, Value ^V) : Behavior(B) , Key(K) , Val(V) { } internal: ModuleFlagEntry(llvm::Module::ModuleFlagEntry *base) : Behavior(safe_cast<ModFlagBehavior>(base->Behavior)) , Key(MDString::_wrap(base->Key)) , Val(Value::_wrap(base->Val)) { } }; private: bool constructed; static llvm::Module *_construct(System::String ^ModuleID, LLVMContext ^C); internal: llvm::Module *base; protected: Module(llvm::Module *base); internal: static inline Module ^_wrap(llvm::Module *base); public: !Module(); virtual ~Module(); // typedef iplist<GlobalVariable> GlobalListType; // typedef iplist<Function> FunctionListType; // typedef iplist<GlobalAlias> AliasListType; // typedef ilist<NamedMDNode> NamedMDListType; // typedef GlobalListType::iterator global_iterator; // typedef GlobalListType::const_iterator const_global_iterator; // typedef FunctionListType::iterator iterator; // typedef FunctionListType::const_iterator const_iterator; // typedef AliasListType::iterator alias_iterator; // typedef AliasListType::const_iterator const_alias_iterator; // typedef NamedMDListType::iterator named_metadata_iterator; // typedef NamedMDListType::const_iterator const_named_metadata_iterator; Module(System::String ^ModuleID, LLVMContext ^C); // const std::string &getModuleIdentifier(); // const std::string &getDataLayout(); // const std::string &getTargetTriple(); Module::Endianness getEndianness(); Module::PointerSize getPointerSize(); LLVMContext ^getContext(); // const std::string &getModuleInlineAsm(); void setModuleIdentifier(System::String ^ID); void setDataLayout(System::String ^DL); void setTargetTriple(System::String ^T); void setModuleInlineAsm(System::String ^Asm); void appendModuleInlineAsm(System::String ^Asm); GlobalValue ^getNamedValue(System::String ^Name); unsigned getMDKindID(System::String ^Name); array<System::String ^> ^getMDKindNamesArray(); // typedef DenseMap<StructType *, unsigned, DenseMapInfo<StructType *> >; // NumeredTypesMapTy; StructType ^getTypeByName(System::String ^Name); Constant ^getOrInsertFunction(System::String ^Name, FunctionType ^T, AttributeSet ^AttributeList); Constant ^getOrInsertFunction(System::String ^Name, FunctionType ^T); // Constant *getOrInsertFunction(StringRef Name, AttributeSet AttributeList, Type *RetTy, ...) END_WITH_NULL; // Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...); // END_WITH_NULL; Constant ^getOrInsertTargetIntrinsic(System::String ^Name, FunctionType ^Ty, AttributeSet ^AttributeList); Function ^getFunction(System::String ^Name); GlobalVariable ^getGlobalVariable(System::String ^Name); GlobalVariable ^getGlobalVariable(System::String ^Name, bool AllowInternal); GlobalVariable ^getNamedGlobal(System::String ^Name); Constant ^getOrInsertGlobal(System::String ^Name, Type ^Ty); GlobalAlias ^getNamedAlias(System::String ^Name); NamedMDNode ^getNamedMetadata(System::String ^Name); NamedMDNode ^getOrInsertNamedMetadata(System::String ^Name); void eraseNamedMetadata(NamedMDNode ^NMD); array<Module::ModuleFlagEntry ^> ^getModuleFlagsMetadataArray(); NamedMDNode ^getModuleFlagsMetadata(); NamedMDNode ^getOrInsertModuleFlagsMetadata(); void addModuleFlag(ModFlagBehavior Behavior, System::String ^Key, Value ^Val); void addModuleFlag(ModFlagBehavior Behavior, System::String ^Key, uint32_t Val); void addModuleFlag(MDNode ^Node); void setMaterializer(GVMaterializer ^GVM); GVMaterializer ^getMaterializer(); bool isMaterializable(GlobalValue ^GV); bool isDematerializable(GlobalValue ^GV); bool Materialize(GlobalValue ^GV); void Dematerialize(GlobalValue ^GV); bool MaterializeAll(); bool MaterializeAllPermanently(); // const GlobalListType &getGlobalList(); System::Collections::Generic::List<GlobalVariable ^> ^getGlobalList(); // static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable *); // const FunctionListType &getFunctionList(); System::Collections::Generic::List<Function ^> ^getFunctionList(); // static iplist<Function> Module::*getSublistAccess(Function *); // const AliasListType &getAliasList(); System::Collections::Generic::List<GlobalAlias ^> ^getAliasList(); // static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias *); // const NamedMDListType &getNamedMDList(); System::Collections::Generic::List<NamedMDNode ^> ^getNamedMDList(); // static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode *); // const ValueSymbolTable &getValueSymbolTable(); ValueSymbolTable ^getValueSymbolTable(); // global_iterator global_begin(); // const_global_iterator global_begin(); // global_iterator global_end(); // const_global_iterator global_end(); bool global_empty(); // iterator begin(); // const_iterator begin(); // iterator end(); // const_iterator end(); size_t size(); bool empty(); // alias_iterator alias_begin(); // const_alias_iterator alias_begin(); // alias_iterator alias_end(); // const_alias_iterator alias_end(); size_t alias_size(); bool alias_empty(); // named_metadata_iterator named_metadata_begin(); // const_named_metadata_iterator named_metadata_begin(); // named_metadata_iterator named_metadata_end(); // const_named_metadata_iterator named_metadata_end(); size_t named_metadata_size(); bool named_metadata_empty(); void print(raw_ostream ^OS, AssemblyAnnotationWriter ^AAW); void dump(); void dropAllReferences(); }; }
#include <iostream> #include <limits.h> #include <fstream> #include <cstdlib> using namespace std; // class for BST node class Node { public: Node *left, *right; int val; public: // constructor Node(int val) { this->val = val; left = right = NULL; } }; // class for BST class BST { public: Node *root; int number_of_rotations_during_insertion; int number_of_rotations_during_deletion; int number_of_comparisons_during_insertion; int number_of_comparisons_during_deletion; void copyConstructorHelper(const Node *node); void deleteLeaf(Node *node, Node *par); void deleteNodeWithOneChild(Node *node, Node *par); void deleteNodeWithTwoChildren(Node *node, Node *par); int kthElementHelper(Node *node, int k); long int BST_Average_Height_Of_Nodes_Helper(Node *node, long int &total_height, double &number_of_nodes); int BST_Height_Helper(Node *node); public: BST(); BST(BST &bst); void insert(int x); bool search(int x); void deleteKey(int x); Node *successor(Node *node); Node *predecessor(Node *node); void printTree(); void printTreeHelper(const Node *node, ofstream &fout); void split(int k); int BST_Height(); double BST_Average_Height_Of_Nodes(); int get_number_of_rotations_during_insertion(); int get_number_of_rotations_during_deletion(); int get_number_of_comparisons_during_insertion(); int get_number_of_comparisons_during_deletion(); }; // default constructor BST::BST() { number_of_comparisons_during_deletion = 0; number_of_comparisons_during_insertion = 0; number_of_rotations_during_deletion = 0; number_of_rotations_during_insertion = 0; root = NULL; } // copy constructor BST::BST(BST &bst) { number_of_comparisons_during_deletion = 0; number_of_comparisons_during_insertion = 0; number_of_rotations_during_deletion = 0; number_of_rotations_during_insertion = 0; // Node *node = bst->root; if (bst.root) copyConstructorHelper(bst.root); } void BST::copyConstructorHelper(const Node *node) { if (!node) return; insert(node->val); copyConstructorHelper(node->left); copyConstructorHelper(node->right); } // insert function void BST::insert(int x) { Node *cur = root; Node *par = NULL; // find position where element is to be inserted while (cur) { number_of_comparisons_during_insertion++; if (x == cur->val) return; par = cur; if (x < cur->val) { cur = cur->left; } else { cur = cur->right; } } Node *node = new Node(x); if (!par) // insert as root { root = node; } else if (x < par->val) // insert as left child { par->left = node; } else // insert as right child { par->right = node; } } // search element in bst bool BST::search(int x) { Node *cur = root; while (cur) { // return if found if (x == cur->val) return true; else if (x < cur->val) { // go to left child cur = cur->left; } else { // go to right child cur = cur->right; } } // not found return false; } // deletekey function void BST::deleteKey(int x) { Node *cur = root, *par = NULL; // find the element to be deleted while (cur) { number_of_comparisons_during_deletion++; if (x == cur->val) { break; } par = cur; if (x < cur->val) { cur = cur->left; } else { cur = cur->right; } } if (!cur) return; // Check if the node to be // deleted has atmost one child. if (cur->left == NULL || cur->right == NULL) { // newcur will replace // the node to be deleted. Node *newcur; // if the left child does not exist. if (cur->left == NULL) newcur = cur->right; else newcur = cur->left; // check if the node to // be deleted is the root. if (par == NULL) { root = NULL; delete (newcur); } // check if the node to be deleted // is par's left or right child // and then replace this with newcur if (cur == par->left) par->left = newcur; else par->right = newcur; // free memory of the // node to be deleted. delete (cur); } // node to be deleted has // two children. else { Node *p = NULL; Node *temp; // Compute the inorder successor temp = cur->right; while (temp->left != NULL) { p = temp; temp = temp->left; } // check if the parent of the inorder // successor is the cur or not(i.e. cur= // the node which has the same data as // the given data by the user to be // deleted). if it isn't, then make the // the left child of its parent equal to // the inorder successor'd right child. if (p != NULL) p->left = temp->right; // if the inorder successor was the // cur (i.e. cur = the node which has the // same data as the given data by the // user to be deleted), then make the // right child of the node to be // deleted equal to the right child of // the inorder successor. else cur->right = temp->right; cur->val = temp->val; delete (temp); } } // void BST::deleteLeaf(Node *node, Node *par) // { // // If Node to be deleted is root // if (!par) // root = NULL; // // If Node to be deleted is left // // of its parent // else if (node == par->left) // { // par->left = NULL; // } // else // { // par->right = NULL; // } // // Free memory // delete (node); // } // void BST::deleteNodeWithTwoChildren(Node *node, Node *par) // { // // Find inorder successor and its parent. // Node *parsucc = node; // Node *succ = node->right; // // Find leftmost child of successor // while (succ->left != NULL) // { // parsucc = succ; // succ = succ->left; // } // node->val = succ->val; // if (!succ->left && !succ->right) // deleteLeaf(succ, parsucc); // else // deleteNodeWithOneChild(succ, parsucc); // } // void BST::deleteNodeWithOneChild(Node *node, Node *par) // { // Node *child; // // Initialize child Node to be deleted has // // left child. // if (node->left) // child = node->left; // // Node to be deleted has right child. // else // child = node->right; // // Node to be deleted is root Node. // if (par == NULL) // root = child; // // Node is left child of its parent. // else if (node == par->left) // par->left = child; // else // par->right = child; // // Find successor and predecessor // Node *s = successor(node); // Node *p = predecessor(node); // // If node has left subtree. // if (node->left) // p->right = s; // // If node has right subtree. // else // { // if (node->right) // s->left = p; // } // // free memory // delete (node); // } // find successor of a node // Node *BST::successor(Node *node) // { // Node *cur = node; // // if right child does not exist // // return successor stored as right child // if (cur->rthread) // return cur->right; // // go to right child if exists // cur = cur->right; // if (!cur) // return cur; // // go to left most element // while (cur->left) // cur = cur->left; // return cur; // } // Node *BST::predecessor(Node *node) // { // // if left child does not exist // // return successor stored as left child // Node *cur = node; // if (cur->lthread) // return cur->left; // // go to left child if exists // cur = cur->left; // if (!cur) // return cur; // // go to right most element // while (!cur->rthread && cur->right) // cur = cur->right; // return cur; // } //======================================================================================================================== int BST::BST_Height() { return BST_Height_Helper(root); } //======================================================================================================================== int BST::BST_Height_Helper(Node *node) { if (!node) return 0; int lh = BST_Height_Helper(node->left); int rh = BST_Height_Helper(node->right); return 1 + max(lh, rh); } //======================================================================================================================== double BST::BST_Average_Height_Of_Nodes() { long int h = 0; int c = 1; double number_of_nodes = 0; BST_Average_Height_Of_Nodes_Helper(root, h, number_of_nodes); return h / number_of_nodes; } //======================================================================================================================== long int BST::BST_Average_Height_Of_Nodes_Helper(Node *node, long int &total_height, double &number_of_nodes) { if (!node) return 0; ++number_of_nodes; long int lh = BST_Average_Height_Of_Nodes_Helper(node->left, total_height, number_of_nodes); long int rh = BST_Average_Height_Of_Nodes_Helper(node->right, total_height, number_of_nodes); int h = max(lh, rh) + 1; total_height += h; return h; } //======================================================================================================================== int BST::get_number_of_rotations_during_insertion() { return number_of_rotations_during_insertion; } int BST::get_number_of_rotations_during_deletion() { return number_of_rotations_during_deletion; } int BST::get_number_of_comparisons_during_insertion() { return number_of_comparisons_during_insertion; } int BST::get_number_of_comparisons_during_deletion() { return number_of_comparisons_during_deletion; }
// SimpleGraphic Engine // (c) David Gowor, 2014 // // System OpenGL Header // // ======= // Classes // ======= // OpenGL settings structure struct sys_glSet_s { int bColor; // Color bits int bDepth; // Depth bits int bStencil; // Stencil bits bool vsync; // Enable vsync? }; // ========== // Interfaces // ========== // System OpenGL class sys_IOpenGL { public: static sys_IOpenGL* GetHandle(class sys_IMain* sysHnd); static void FreeHandle(sys_IOpenGL* hnd); virtual bool Init(sys_glSet_s* set) = 0; // Initialise virtual bool Shutdown() = 0; // Shutdown virtual void Swap() = 0; // Swap buffers virtual void* GetProc(char* name) = 0; // Get extension function address virtual bool CaptureSecondary() = 0; // Capture secondary context virtual bool ReleaseSecondary() = 0; // Release secondary content };
#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "visual_perception_msgs/PersonFollowedData.h" #include "std_msgs/Int32.h" #include "std_msgs/Float32.h" #include "std_msgs/String.h" #include "sensor_msgs/CameraInfo.h" #include <bica/Component.h> #include <cmath> #include <string> const float Pi = 3.1416; class pdAlgorithm: public bica::Component { private: ros::NodeHandle n_; ros::Subscriber sub_, info_sub_; ros::Publisher speed_pub_, talk_publisher_; std_msgs::String data_; int width; float minDist, maxDist, Kp, Kd, prevErrorLinear, prevErrorAngular, maxV, maxW, prevV; public: pdAlgorithm() { sub_ = n_.subscribe("/person_followed_data", 1, &pdAlgorithm::cb, this); info_sub_ = n_.subscribe("/camera/rgb/camera_info", 1, &pdAlgorithm::cb_info, this); speed_pub_ = n_.advertise<geometry_msgs::Twist>("/mobile_base/commands/velocity", 1); talk_publisher_ = n_.advertise<std_msgs::String>("/talk", 1); width = 0; minDist = 800.0; maxDist = 1000.0; maxV = 0.5; Kp = 0.2; Kd = 0.8; prevV = 0; maxW = Pi / 2; prevErrorLinear = 0; prevErrorAngular = 0; } float linear(float d) { //Calculo la salida del control proporcional if(d > maxDist){ std_msgs::String s; //s.data = "Come closer, please"; //talk_publisher_.publish(s); d = maxDist; } float currentErrorLinear = (d - minDist) / (maxDist - minDist); //error entre 0 y 1 float output = currentErrorLinear * Kp + (currentErrorLinear - prevErrorLinear) * Kd; prevErrorLinear = currentErrorLinear; float v = output * maxV; if(abs(v - prevV) >= maxV / 8.0){ v = v / 8.0; } if(v < 0.0){ v = prevV; } prevV = v; return v; } float angular(int p) { //calculo el error entre 0 y 1 float currentErrorAngular = ((float)(width / 2) - (float)p) / (float)(width / 2); float output = currentErrorAngular * Kp + (currentErrorAngular - prevErrorAngular) * Kd; return output * maxW; prevErrorAngular = currentErrorAngular; } void cb(const visual_perception_msgs::PersonFollowedData::ConstPtr& msg) { if(isActive()){ if(width != 0){ float dist = msg->dist; int centralPixel = msg->centralPixel; float v = pdAlgorithm::linear(dist); float w = pdAlgorithm::angular(centralPixel); geometry_msgs::Twist vel; vel.linear.x = v; vel.angular.z = w; speed_pub_.publish(vel); } } } void cb_info(const sensor_msgs::CameraInfo::ConstPtr& msg) { width = msg->width; info_sub_.shutdown(); } }; int main(int argc, char **argv) { ros::init(argc, argv, "PD_Algorithm"); pdAlgorithm pd; ros::spin(); }
// Created on: 1992-10-14 // Created by: Christophe MARION // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRBRep_TheIntersectorOfTheIntConicCurveOfCInter_HeaderFile #define _HLRBRep_TheIntersectorOfTheIntConicCurveOfCInter_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <IntRes2d_Intersection.hxx> #include <Standard_Integer.hxx> #include <TColStd_Array1OfReal.hxx> class Standard_ConstructionError; class IntCurve_IConicTool; class HLRBRep_CurveTool; class HLRBRep_TheProjPCurOfCInter; class HLRBRep_MyImpParToolOfTheIntersectorOfTheIntConicCurveOfCInter; class IntRes2d_Domain; class gp_Pnt2d; class HLRBRep_TheIntersectorOfTheIntConicCurveOfCInter : public IntRes2d_Intersection { public: DEFINE_STANDARD_ALLOC //! Empty constructor. Standard_EXPORT HLRBRep_TheIntersectorOfTheIntConicCurveOfCInter(); //! Intersection between an implicit curve and //! a parametrised curve. //! The exception ConstructionError is raised if the domain //! of the parametrised curve does not verify HasFirstPoint //! and HasLastPoint return True. Standard_EXPORT HLRBRep_TheIntersectorOfTheIntConicCurveOfCInter(const IntCurve_IConicTool& ITool, const IntRes2d_Domain& Dom1, const Standard_Address& PCurve, const IntRes2d_Domain& Dom2, const Standard_Real TolConf, const Standard_Real Tol); //! Intersection between an implicit curve and //! a parametrised curve. //! The exception ConstructionError is raised if the domain //! of the parametrised curve does not verify HasFirstPoint //! and HasLastPoint return True. Standard_EXPORT void Perform (const IntCurve_IConicTool& ITool, const IntRes2d_Domain& Dom1, const Standard_Address& PCurve, const IntRes2d_Domain& Dom2, const Standard_Real TolConf, const Standard_Real Tol); Standard_EXPORT Standard_Real FindU (const Standard_Real parameter, gp_Pnt2d& point, const Standard_Address& TheParCurev, const IntCurve_IConicTool& TheImpTool) const; Standard_EXPORT Standard_Real FindV (const Standard_Real parameter, gp_Pnt2d& point, const IntCurve_IConicTool& TheImpTool, const Standard_Address& ParCurve, const IntRes2d_Domain& TheParCurveDomain, const Standard_Real V0, const Standard_Real V1, const Standard_Real Tolerance) const; Standard_EXPORT void And_Domaine_Objet1_Intersections (const IntCurve_IConicTool& TheImpTool, const Standard_Address& TheParCurve, const IntRes2d_Domain& TheImpCurveDomain, const IntRes2d_Domain& TheParCurveDomain, Standard_Integer& NbResultats, TColStd_Array1OfReal& Inter2_And_Domain2, TColStd_Array1OfReal& Inter1, TColStd_Array1OfReal& Resultat1, TColStd_Array1OfReal& Resultat2, const Standard_Real EpsNul) const; protected: private: }; #endif // _HLRBRep_TheIntersectorOfTheIntConicCurveOfCInter_HeaderFile
#include <stdio.h> #define MAXN 10 typedef float ElementType; ElementType Average( ElementType S[], int N ); int main () { ElementType S[MAXN]; int N, i; scanf("%d", &N); for ( i=0; i<N; i++ ) scanf("%f", &S[i]); printf("%.2f\n", Average(S, N)); return 0; } ElementType Average( ElementType S[], int N ){ float total; for(int i = 0; i < N; i++){ total += S[i]; } return total/N; }
//File name: point.cpp #include"point.h" using namespace std; Point::Point() : mX(0), mY(0) //Initializers can only be used with constructors. { } // end point default constructor Point::Point(int inX, int inY) : mX(inX), mY(inY) { } //end point void Point::setX(int inX) { mX = inX; } //end setX void Point::setY(int inY) { mY = inY; } //end setY int Point::getX() const { return mX; } // end getX int Point::getY() const { return mY; } //end getY double Point::distance(const Point& p2) { return sqrt(pow((p2.mY - mY), 2) + pow((p2.mX - mX), 2)); } //end distance void Point::display() { cout << "(" << getX() << ',' << getY() << ')'; } //end display bool Point::operator==(const Point& p2) const { return ((mX == p2.mX) && (mY == p2.mY)); } // end operator==
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int n, pr[111], IT, was[111]; vector<int> g[111]; LD ans = 0, t, disA[111], disB[111], d[111][111]; struct { LD x, y; } a[111], b[111]; bool kuhn(int x) { if(was[x] == IT) return false; was[x] = IT; for (int i = 0; i < g[x].size(); ++i) if (pr[g[x][i]] == -1 || kuhn(pr[g[x][i]])) { pr[g[x][i]] = x; return true; } return false; } bool Can(LD c) { for (int i = 0; i < n; ++i) { g[i].clear(); for (int j = 0; j < n; ++j) { if (c >= d[i][j] * 2 + disA[i] + disB[j]) { g[i].push_back(j); } } } memset(pr, -1, sizeof(pr)); for (int i = 0; i < n; ++i) { ++IT; if (!kuhn(i)) return false; } return true; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); cin >> n >> t; for (int i = 0; i < n; ++i) cin >> a[i].x >> a[i].y; for (int i = 0; i < n; ++i) cin >> b[i].x >> b[i].y; for (int i = 0; i < n; ++i) { disA[i] = min(min(a[i].x, a[i].y), min(1 - a[i].x, 1 - a[i].y)); disB[i] = min(min(b[i].x, b[i].y), min(1 - b[i].x, 1 - b[i].y)); for (int j = 0; j < n; ++j) { d[i][j] = sqrtl(sqr(a[i].x - b[j].x) + sqr(a[i].y - b[j].y)); } } LD left = 0; LD right = 100; while ((right - left) > 1e-4) { LD c = (left + right) / 2; if (Can(c)) right = c;else left = c; } cout.precision(12); cout <<fixed; cout << (right + left) / (2 * t) << endl; return 0; }
#pragma once #include "Item.h" /* SeedPack represents a pack of seeds the player can plant when interacting with a 'NoInteractable' map tile */ class SeedPack : public Item { public: SeedPack() : Item(ItemType::seedPack) {} };
#if !defined (NULL) #define NULL 0 #endif #if !defined (RADIXSORT_H) #define RADIXSORT_H #include "CSC2110/CD.h" using CSC2110::CD; #include "CSC2110/QueueLinked.h" using CSC2110::QueueLinked; #include "CSC2110/text.h" using CSC2110::String; #include "CSC2110/Valtostr.h" //my own class using CSC2110::Valtostr; template < class T > class RadixSort { private: /* Pre : Current character cannot be greater than the total amount of characters Post: Sorts the bin recursivly */ static void binSort(QueueLinked<T>* bin, int curr_char, int num_chars, char (*getRadixChar) (T* item, int index)); static int asc_index(char rad); /* Pre : Num items are greater than 0, num_chars greater than 0 Post: sorts the items */ static void radixSortAsc(T** sort, int n, int num_chars, char (*getRadixChar) (T* item, int index)); //algorithm 1 /* Pre : Num items are greater than 0, num chars greater than 0 Post: Sorts the items with bins */ static void radixSortDesc(T** sort, int n, int num_chars, char (*getRadixChar) (T* item, int index)); //algorithm 2 public: /* Pre : N/A Post: returns a sorted array */ static T** radixSort(T** sort, int num_to_sort, int num_chars, bool asc, char (*getRadixChar) (T* item, int index)); /* Pre : N/A Post: Returns the index of the bin the character and/or item should be placed */ static int calc_bin_index(char rad); //used for convenience }; template < class T > T** RadixSort<T>::radixSort(T** unsorted, int num_to_sort, int num_chars, bool asc, char (*getRadixChar) (T* item, int index)) { T** radix_sorted_array = new T*[num_to_sort]; //create a new array for items //puts items in new array int x = 0; while(x < num_to_sort) { radix_sorted_array[x] = unsorted[x]; x++; } //execute the specified sorting function if(!asc) radixSortDesc(radix_sorted_array, num_to_sort, num_chars, getRadixChar); else radixSortAsc(radix_sorted_array, num_to_sort, num_chars, getRadixChar); return radix_sorted_array; } template < class T > void RadixSort<T>::radixSortAsc(T** sort, int n, int num_chars, char (*getRadixChar) (T* st, int index)) { //if(num_chars < 0 || n < 0 || sort == NULL) return; QueueLinked<T>* bin_sort_bin = new QueueLinked<T>(); //creates a queue for binsort //enqueues all the items in array int x = 0; while(x < n) { bin_sort_bin->enqueue(sort[x]); x++; } binSort(bin_sort_bin, 1, num_chars, getRadixChar); //calls binsort to deal with first character first //puts sorted items back into the array x = 0; while(x < n) { sort[x] = bin_sort_bin->dequeue(); x++; } delete bin_sort_bin; } template < class T > void RadixSort<T>::binSort(QueueLinked<T>* bin, int curr_char, int num_chars, char (*getRadixChar) (T* st, int index)) { //check to see if parameters are vaid if(num_chars < curr_char) return; int q_num = 37; QueueLinked<T>** _bin = new QueueLinked<T>*[q_num]; //creates 37 bins of queues //put queues in all 37 bins int x = 0; while(x < 37) { _bin[x] = new QueueLinked<T>(); x++; } //get items from bin and put them in 37 bins while(!bin->isEmpty()) { T* item = bin->dequeue(); _bin[asc_index((*getRadixChar)(item, curr_char))]->enqueue(item); } //checks all bins x = 0; while(x < q_num) { //check for more that one item in bin if(_bin[x]->size() > 1) binSort(_bin[x], curr_char + 1, num_chars, getRadixChar); //recursivly call binsort while(!_bin[x]->isEmpty()) { bin->enqueue(_bin[x]->dequeue()); } delete _bin[x]; //delete each bin x++; } delete[] _bin; } template < class T > void RadixSort<T>::radixSortDesc(T** sort, int n, int num_chars, char (*getRadixChar) (T* st, int index)) { if(num_chars < 0 || n < 0 || sort == NULL) return; int q_num = 37; //covers letters and digits int counter = 0; QueueLinked<T>** _bin = new QueueLinked<T>*[37]; //must instantiate each of the queues int x = 0; while(x < 37) { _bin[x] = new QueueLinked<T>(); x++; } //go through max number of characters x = num_chars; while(x > 0) //number of times to bin stuff { //put each word in bin int y = 0; while(y < n) { _bin[asc_index((*getRadixChar)(sort[y],x))]->enqueue(sort[y]); y++; } int a = 0; //used for index of the array of items int z = 36; //take items out of each bin while(z >= 0) { //empty each queue while(!_bin[z]->isEmpty()) { sort[a] = _bin[z]->dequeue(); a++; } z--; } x--; } //delete the bins x = 0; while (x < 37) { delete _bin[x]; x++; } delete[] _bin; } template < class T > int RadixSort<T>::asc_index(char rad) { if(rad >= 48 && rad <= 57) return (rad - 47); else if(rad >= 65 && rad <= 90) return (rad - 54); else if(rad >= 97 && rad <= 122) return (rad - 86); else return 0; } #endif
#pragma once #include "MainPage.g.h" namespace ClientUI { public ref class MainPage sealed { public: MainPage(); private: void SourceCodeGetAPIButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); void ShowMessageBox(const Platform::String^ message); }; }
struct Trie{ int trie[MAX][26]; bool finish[MAX]; int nxt = 1, len = 0; void add(string &s){ int node = 0; for(auto c: s){ if(trie[node][c-'a'] == 0){ node = trie[node][c-'a'] = nxt; nxt++; }else node = trie[node][c-'a']; } if(!finish[node]){ finish[node] = true; len++; } } bool find(string &s, bool remove){ int idx = 0; for(auto c: s) if(trie[idx][c-'a'] == 0) return false; else idx = trie[idx][c-'a']; if(remove and finish[idx]){ finish[idx]=false; len--; } return finish[idx]; } bool find(string &s){ return find(s, 0); } void del(string &s){ find(s, 1); } };
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2019 Howard Chu <https://github.com/hyc> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/net/stratum/Url.h" #include <cassert> #include <cstring> #include <cstdlib> #include <cstdio> #ifdef _MSC_VER # define strncasecmp _strnicmp #endif namespace xmrig { static const char kStratumTcp[] = "stratum+tcp://"; static const char kStratumSsl[] = "stratum+ssl://"; static const char kSOCKS5[] = "socks5://"; #ifdef XMRIG_FEATURE_HTTP static const char kDaemonHttp[] = "daemon+http://"; static const char kDaemonHttps[] = "daemon+https://"; #endif } xmrig::Url::Url(const char *url) { parse(url); } xmrig::Url::Url(const char *host, uint16_t port, bool tls, Scheme scheme) : m_tls(tls), m_scheme(scheme), m_host(host), m_port(port) { const size_t size = m_host.size() + 8; assert(size > 8); char *url = new char[size](); snprintf(url, size - 1, "%s:%d", m_host.data(), m_port); m_url = url; } bool xmrig::Url::isEqual(const Url &other) const { return (m_tls == other.m_tls && m_scheme == other.m_scheme && m_host == other.m_host && m_url == other.m_url && m_port == other.m_port); } bool xmrig::Url::parse(const char *url) { if (url == nullptr) { return false; } const char *p = strstr(url, "://"); const char *base = url; if (p) { if (strncasecmp(url, kStratumTcp, sizeof(kStratumTcp) - 1) == 0) { m_scheme = STRATUM; m_tls = false; } else if (strncasecmp(url, kStratumSsl, sizeof(kStratumSsl) - 1) == 0) { m_scheme = STRATUM; m_tls = true; } else if (strncasecmp(url, kSOCKS5, sizeof(kSOCKS5) - 1) == 0) { m_scheme = SOCKS5; m_tls = false; } # ifdef XMRIG_FEATURE_HTTP else if (strncasecmp(url, kDaemonHttps, sizeof(kDaemonHttps) - 1) == 0) { m_scheme = DAEMON; m_tls = true; } else if (strncasecmp(url, kDaemonHttp, sizeof(kDaemonHttp) - 1) == 0) { m_scheme = DAEMON; m_tls = false; } # endif else { return false; } base = p + 3; } if (!strlen(base) || *base == '/') { return false; } m_url = url; if (base[0] == '[') { return parseIPv6(base); } const char *port = strchr(base, ':'); if (!port) { m_host = base; return true; } const auto size = static_cast<size_t>(port++ - base + 1); char *host = new char[size](); memcpy(host, base, size - 1); m_host = host; m_port = static_cast<uint16_t>(strtol(port, nullptr, 10)); return true; } bool xmrig::Url::parseIPv6(const char *addr) { const char *end = strchr(addr, ']'); if (!end) { return false; } const char *port = strchr(end, ':'); if (!port) { return false; } const auto size = static_cast<size_t>(end - addr); char *host = new char[size](); memcpy(host, addr + 1, size - 1); m_host = host; m_port = static_cast<uint16_t>(strtol(port + 1, nullptr, 10)); return true; }
#include<iostream> #include<iomanip> using namespace std; int main() { int n,m,k; int value[100],ans; char ch[100]; string in; cin>>n; while(n--) { int no[100]={}; cin>>k; for(int i=0;i<k;i++) {cin>>ch[i]>>value[i]; } cin>>m; cin.ignore(); for(int i=0;i<m;i++) { in.clear(); getline(cin,in); for(int j=0;j<in.length();j++) { for(int l=0;l<k;l++) { if(in.at(j)==ch[l]) no[l]++; } } } ans=0; for(int i=0;i<k;i++) { ans+=(value[i])*(no[i]); } printf("%d.%02d$\n", ans/100, ans%100); } return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 5e5 + 100; int f[maxn][2],s[maxn]; int main() { int n,k,ans = -101; scanf("%d",&n); memset(f,-INF,sizeof(f)); memset(s,-INF,sizeof(s)); f[0][0] = 0; for (int i = 1;i <= n; i++) { scanf("%d",&k); f[i][0] = max(f[i-1][0],0) + k; if (i > 2) { s[i-2] = max(s[i-3],f[i-2][0]); f[i][1] = max(f[i-1][1],s[i-2]) + k; ans = max(ans,f[i][1]); } } //for (int i = 1;i <= n; i++) // printf("%d %d %d\n",f[i][0], f[i][1],s[i]); printf("%d\n",ans); return 0; }
// SPDX-FileCopyrightText: 2021 Samuel Cabrero <samuel@orica.es> // // SPDX-License-Identifier: MIT #ifndef __STATE_UNARMORING_H__ #define __STATE_UNARMORING_H__ #include "state.h" class TUnarmoring : public TState { public: TUnarmoring(); virtual const char *name() const; virtual void enter(); virtual void loop(); virtual void exit(); private: bool timedout(); unsigned long m_timestamp; }; #endif /* __STATE_UNARMORING_H__ */
// Copyright (c) 2016 Mozart Alexander Louis. All rights reserved. #include "fmod_engine.hxx" AudioUtils* AudioUtils::m_instance_ = nullptr; inline void check_result(const FMOD_RESULT result) { CCASSERT(result == FMOD_OK, "FMOD Asset Failed..."); } AudioUtils::AudioUtils() : audio_enabled_(true), low_level_system_(nullptr), fmod_system_(nullptr) {} AudioUtils::~AudioUtils() { check_result(low_level_system_->release()); check_result(fmod_system_->release()); delete m_instance_; } AudioUtils* AudioUtils::getInstance() { if (!m_instance_) { m_instance_ = new (nothrow) AudioUtils(); m_instance_->initAudioEngine(); } return m_instance_; } void AudioUtils::preloadAudio(const string& path) { if (audio_instance_map_iter_ == audio_instance_map_.end()) { const auto& instance = getEvent(path.c_str(), true); audio_instance_map_.insert(audio_instance_map_iter_, make_pair(path.c_str(), instance)); } } void AudioUtils::playAudio(const char* name, bool persist) { if (audio_enabled_) { findAudioInstance(name); if (audio_instance_map_iter_ == audio_instance_map_.end()) { // Create a new audio instance and insert it into our audio instance map. const auto& instance = getEvent(name); check_result(instance->start()); // Store the created instance in the audio map if persistence is needed // if not, fire and forget. if (persist) audio_instance_map_.insert(audio_instance_map_iter_, make_pair(name, instance)); else check_result(instance->release()); } else { if (getCurrentlyPlaying() != audio_instance_map_iter_->first) check_result(audio_instance_map_iter_->second->start()); } } } void AudioUtils::playAudioWithParam(const char* name, const char* param, const float value, const bool persist) { if (audio_enabled_) { FMOD::Studio::ParameterInstance* paramInst; findAudioInstance(name); if (audio_instance_map_iter_ == audio_instance_map_.end()) { const auto& instance = getEvent(name); check_result(instance->getParameter(param, &paramInst)); check_result(paramInst->setValue(value)); check_result(instance->start()); // Store the created instance in the audio map if persistence is needed // if not, fire and forget. if (persist) audio_instance_map_.insert(audio_instance_map_iter_, make_pair(name, instance)); else check_result(instance->release()); } else { check_result(audio_instance_map_iter_->second->getParameter(param, &paramInst)); check_result(paramInst->setValue(value)); } } } string AudioUtils::getCurrentlyPlaying() { for (const auto& itr : audio_instance_map_) { FMOD_STUDIO_PLAYBACK_STATE state; check_result(itr.second->getPlaybackState(&state)); if (state == FMOD_STUDIO_PLAYBACK_PLAYING) return itr.first; } return ""; } void AudioUtils::pauseAudio(const char* name) { findAudioInstance(name); if (audio_instance_map_iter_ != audio_instance_map_.end()) check_result(audio_instance_map_iter_->second->setPaused(true)); } void AudioUtils::resumeAudio(const char* name) { if (audio_enabled_) { findAudioInstance(name); if (audio_instance_map_iter_ != audio_instance_map_.end()) check_result(audio_instance_map_iter_->second->setPaused(false)); } } void AudioUtils::stopAudio(const char* name, bool release) { findAudioInstance(name); if (audio_instance_map_iter_ != audio_instance_map_.end()) { check_result(audio_instance_map_iter_->second->stop(FMOD_STUDIO_STOP_ALLOWFADEOUT)); if (release) { CCLOG("Releasing Audio"); FMOD::Studio::EventDescription* desc; check_result(audio_instance_map_iter_->second->getDescription(&desc)); check_result(audio_instance_map_iter_->second->release()); audio_instance_map_.erase(audio_instance_map_iter_); } } } void AudioUtils::setAudioParam(const char* name, const char* param, float value) { findAudioInstance(name); if (audio_instance_map_iter_ != audio_instance_map_.end()) { FMOD::Studio::ParameterInstance* paramInst; check_result(audio_instance_map_iter_->second->getParameter(param, &paramInst)); check_result(paramInst->setValue(value)); } } void AudioUtils::stopAll(bool release) { for (const auto& pair : audio_instance_map_) { check_result(pair.second->stop(FMOD_STUDIO_STOP_ALLOWFADEOUT)); if (release) { CCLOG("Releasing Audio"); FMOD::Studio::EventDescription* desc; check_result(pair.second->getDescription(&desc)); check_result(pair.second->release()); } } if (release) audio_instance_map_.clear(); } void AudioUtils::pauseMixer() const { check_result(low_level_system_->mixerSuspend()); } void AudioUtils::resumeMixer() const { check_result(low_level_system_->mixerResume()); } void AudioUtils::setEnabled(bool enable) { audio_enabled_ = enable; } bool AudioUtils::getEnabled() const { return audio_enabled_; } void AudioUtils::update() const { check_result(fmod_system_->update()); } void AudioUtils::findAudioInstance(string name) { audio_instance_map_iter_ = find_if(audio_instance_map_.begin(), audio_instance_map_.end(), [name](pair<string, FMOD::Studio::EventInstance*> audio_id) { return audio_id.first == name; }); } void AudioUtils::initAudioEngine() { check_result(FMOD::Studio::System::create(&fmod_system_)); check_result(fmod_system_->getLowLevelSystem(&low_level_system_)); check_result(low_level_system_->setDSPBufferSize(1024, 4)); check_result(fmod_system_->initialize(32, FMOD_STUDIO_INIT_NORMAL, FMOD_INIT_NORMAL, nullptr)); FMOD::Studio::Bank* masterBank; check_result(fmod_system_->loadBankFile(MASTER_FILE.c_str(), FMOD_STUDIO_LOAD_BANK_NORMAL, &masterBank)); FMOD::Studio::Bank* stringsBank; check_result( fmod_system_->loadBankFile(MASTER_STRINGS_FILE.c_str(), FMOD_STUDIO_LOAD_BANK_NORMAL, &stringsBank)); } FMOD::Studio::EventInstance* AudioUtils::getEvent(const char* event_path, bool preload) const { FMOD::Studio::EventDescription* desc; check_result(fmod_system_->getEvent(event_path, &desc)); if (preload) desc->loadSampleData(); FMOD::Studio::EventInstance* inst = nullptr; check_result(desc->createInstance(&inst)); return inst; }
#pragma once #include <mutex> struct AVPacket; struct AVFormatContext; struct AVDictionary; struct AVCodecParameters; class XDemux { public: XDemux(); virtual ~XDemux(); public: //初始化部分参数 virtual bool Init(); //打开媒体文件,或者流媒体文件 virtual bool Open(const char* url); //关闭媒体文件 virtual void Close(); //清空当前参数 virtual void Clear(); //定位到视频中的某一个时间点 virtual bool Seek(double pos); //获取视频返回的参数 返回的空间需要清理 virtual AVCodecParameters* CopyVParam(); virtual AVCodecParameters* CopyAParam(); //判断是否是音频 virtual bool IsAudio(AVPacket* pkt); //读取视频包Pkt virtual AVPacket* ReadVideoPkt(); //读取所有数据包 virtual AVPacket* Read(); int GetWidth() { return m_nWidth; } int Getheight() { return m_nHeight; } int GetSampleRate() { return m_nSampleRate; } int GetChannels() { return m_nChannels; } int GetTotalMs() { return m_totalMs; } private: AVFormatContext *pCtx = NULL; AVDictionary *opt = NULL; //当前视频的总时长 int m_totalMs; //视频流ID int videoStreamId; //视频帧的宽高,作为渲染窗口使用 int m_nWidth; int m_nHeight; //音频流ID int audioStreamId; //采样率和通道数 int m_nSampleRate; int m_nChannels; };
// Created on: 2002-12-12 // Created by: data exchange team // Copyright (c) 2002-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepElement_SurfaceSection_HeaderFile #define _StepElement_SurfaceSection_HeaderFile #include <Standard.hxx> #include <StepElement_MeasureOrUnspecifiedValue.hxx> #include <Standard_Transient.hxx> class StepElement_SurfaceSection; DEFINE_STANDARD_HANDLE(StepElement_SurfaceSection, Standard_Transient) //! Representation of STEP entity SurfaceSection class StepElement_SurfaceSection : public Standard_Transient { public: //! Empty constructor Standard_EXPORT StepElement_SurfaceSection(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const StepElement_MeasureOrUnspecifiedValue& aOffset, const StepElement_MeasureOrUnspecifiedValue& aNonStructuralMass, const StepElement_MeasureOrUnspecifiedValue& aNonStructuralMassOffset); //! Returns field Offset Standard_EXPORT StepElement_MeasureOrUnspecifiedValue Offset() const; //! Set field Offset Standard_EXPORT void SetOffset (const StepElement_MeasureOrUnspecifiedValue& Offset); //! Returns field NonStructuralMass Standard_EXPORT StepElement_MeasureOrUnspecifiedValue NonStructuralMass() const; //! Set field NonStructuralMass Standard_EXPORT void SetNonStructuralMass (const StepElement_MeasureOrUnspecifiedValue& NonStructuralMass); //! Returns field NonStructuralMassOffset Standard_EXPORT StepElement_MeasureOrUnspecifiedValue NonStructuralMassOffset() const; //! Set field NonStructuralMassOffset Standard_EXPORT void SetNonStructuralMassOffset (const StepElement_MeasureOrUnspecifiedValue& NonStructuralMassOffset); DEFINE_STANDARD_RTTIEXT(StepElement_SurfaceSection,Standard_Transient) protected: private: StepElement_MeasureOrUnspecifiedValue theOffset; StepElement_MeasureOrUnspecifiedValue theNonStructuralMass; StepElement_MeasureOrUnspecifiedValue theNonStructuralMassOffset; }; #endif // _StepElement_SurfaceSection_HeaderFile
// BullCowGame.cpp : This file contains the 'main' function. Program execution begins and ends there. // /* This is the console executable that makes use of the BullCow class This acts as the view in the MVC pattern and is responsible for all user int32eraction. For game logic see the FBullCowGame class. */ #include "pch.h" #include <iostream> #include <string> #include "FBullCowGame.h" using FText = std::string; using int32 = int; void PrintIntro(); void PlayGame(); FText GetValidGuess(); bool AskToPlayAgain(); int32 GetHiddenWordLength(); EGuessStatus CheckGuessValidity(); void PrintGameSummary(); FBullCowGame BCGame; // instantiate a new game // the entry point32 for our application int main() { bool bPlayAgain = false; do { PrintIntro(); PlayGame(); bPlayAgain = AskToPlayAgain(); } while (bPlayAgain); return 0; // exit the application } void PrintIntro() { // prints intro of the game std::cout << "Welcome to Bulls and Cows, a fun word game"; std::cout << std::endl; std::cout << " } { _____ " << std::endl; std::cout << " (o o) (o o) " << std::endl; std::cout << R"( /------\ / \ /-------\ )" << std::endl; std::cout << R"( / | BULL |0 0| COW | \)" << std::endl; std::cout << " * |-,--- | |-----| " << std::endl; std::cout << " ^ ^ ^ ^ " << std::endl; std::cout << "Can you guess the " << BCGame.GetHiddenWordLength() << " letter isogram I'm thinking of?\n"; // return; } void PlayGame() { BCGame.Reset(); int32 MaxTries = BCGame.GetMaxTries(); std::cout << "Your maximum number of tries is: " << MaxTries << std::endl; // loop for number of turns asking for guesses while (!BCGame.IsGameWon() && BCGame.GetCurrentTry() <= MaxTries){ FText Guess = GetValidGuess(); // Submit valid guess to the game FBullCowCount BullCowCount = BCGame.SubmitValidGuess(Guess); std::cout << "Bulls = " << BullCowCount.Bulls << std::endl; std::cout << "Cows = " << BullCowCount.Cows << std::endl; } // summarize game PrintGameSummary(); // return; } // loop continually until the user gives a valid guess FText GetValidGuess() { FText Guess; EGuessStatus Status = EGuessStatus::Invalid_Status; do { // get a guess from the player int32 CurrentTry = BCGame.GetCurrentTry(); std::cout << "Current Try: " << CurrentTry << " of " << BCGame.GetMaxTries(); std::cout << ". Enter your guess: " << std::endl; // std::cout << "Enter your guess: "; getline(std::cin, Guess); // check status and give feedback Status = BCGame.CheckGuessValidity(Guess); switch (Status) { case EGuessStatus::Not_Isogram: std::cout << "Please enter a word without repeating letters!\n\n"; break; case EGuessStatus::Not_Lowercase: std::cout << "Please enter a word in lowercase.\n\n"; break; case EGuessStatus::Wrong_Length: std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n\n"; break; default: break; } } while (Status != EGuessStatus::OK); // keep looping until we get no errors return Guess; } bool AskToPlayAgain() { std::cout << "Do you want to play again with the same word? (y/n)"; FText Response; getline(std::cin, Response); if (tolower(Response[0]) == 'y') { // return tolower(Response[0]) == 'y'; return true; } else { return false; } } void PrintGameSummary() { if(BCGame.IsGameWon()){ std::cout << "Congrats. You won!\n"; }else{ std::cout << "Better luck next time!\n"; } }
// Copyright (c) 2021 ETH Zurich // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/assert.hpp> #include <pika/concepts/concepts.hpp> #include <pika/errors/try_catch_exception_ptr.hpp> #include <pika/execution/algorithms/detail/partial_algorithm.hpp> #include <pika/execution_base/operation_state.hpp> #include <pika/execution_base/receiver.hpp> #include <pika/execution_base/sender.hpp> #include <pika/functional/tag_invoke.hpp> #include <pika/futures/detail/future_data.hpp> #include <pika/futures/future.hpp> #include <pika/futures/traits/acquire_shared_state.hpp> #include <exception> #include <type_traits> #include <utility> namespace pika::keep_future_detail { template <typename Receiver, typename Future> struct operation_state { PIKA_NO_UNIQUE_ADDRESS std::decay_t<Receiver> receiver; std::decay_t<Future> future; friend void tag_invoke(pika::execution::experimental::start_t, operation_state& os) noexcept { pika::detail::try_catch_exception_ptr( [&]() { auto state = pika::traits::detail::get_shared_state(os.future); if (!state) { PIKA_THROW_EXCEPTION(pika::error::no_state, "operation_state::start", "the future has no valid shared state"); } // The operation state has to be kept alive until set_value // is called, which means that we don't need to move // receiver and future into the on_completed callback. state->set_on_completed([&os]() mutable { pika::execution::experimental::set_value( PIKA_MOVE(os.receiver), PIKA_MOVE(os.future)); }); }, [&](std::exception_ptr ep) { pika::execution::experimental::set_error(PIKA_MOVE(os.receiver), PIKA_MOVE(ep)); }); } }; template <typename Future> struct keep_future_sender_base { using is_sender = void; std::decay_t<Future> future; template <template <typename...> class Tuple, template <typename...> class Variant> using value_types = Variant<Tuple<std::decay_t<Future>>>; template <template <typename...> class Variant> using error_types = Variant<std::exception_ptr>; static constexpr bool sends_done = false; using completion_signatures = pika::execution::experimental::completion_signatures< pika::execution::experimental::set_value_t(std::decay_t<Future>), pika::execution::experimental::set_error_t(std::exception_ptr)>; }; template <typename Future> struct keep_future_sender; template <typename T> struct keep_future_sender<pika::future<T>> : public keep_future_sender_base<pika::future<T>> { using future_type = pika::future<T>; using base_type = keep_future_sender_base<pika::future<T>>; using base_type::future; template <typename Future, typename = std::enable_if_t<!std::is_same<std::decay_t<Future>, keep_future_sender>::value>> explicit keep_future_sender(Future&& future) : base_type{PIKA_FORWARD(Future, future)} { } keep_future_sender(keep_future_sender&&) = default; keep_future_sender& operator=(keep_future_sender&&) = default; keep_future_sender(keep_future_sender const&) = delete; keep_future_sender& operator=(keep_future_sender const&) = delete; template <typename Receiver> friend operation_state<Receiver, future_type> tag_invoke( pika::execution::experimental::connect_t, keep_future_sender&& s, Receiver&& receiver) { return {PIKA_FORWARD(Receiver, receiver), PIKA_MOVE(s.future)}; } template <typename Receiver> friend operation_state<Receiver, future_type> tag_invoke(pika::execution::experimental::connect_t, keep_future_sender const&, Receiver&&) { static_assert(sizeof(Receiver) == 0, "Are you missing a std::move? The keep_future sender of a future is not copyable " "(because future is not copyable) and thus not l-value connectable. Make sure you " "are passing an r-value reference of the sender."); } }; template <typename T> struct keep_future_sender<pika::shared_future<T>> : keep_future_sender_base<pika::shared_future<T>> { using future_type = pika::shared_future<T>; using base_type = keep_future_sender_base<pika::shared_future<T>>; using base_type::future; template <typename Future, typename = std::enable_if_t<!std::is_same<std::decay_t<Future>, keep_future_sender>::value>> explicit keep_future_sender(Future&& future) : base_type{PIKA_FORWARD(Future, future)} { } keep_future_sender(keep_future_sender&&) = default; keep_future_sender& operator=(keep_future_sender&&) = default; keep_future_sender(keep_future_sender const&) = default; keep_future_sender& operator=(keep_future_sender const&) = default; template <typename Receiver> friend operation_state<Receiver, future_type> tag_invoke( pika::execution::experimental::connect_t, keep_future_sender&& s, Receiver&& receiver) { return {PIKA_FORWARD(Receiver, receiver), PIKA_MOVE(s.future)}; } template <typename Receiver> friend operation_state<Receiver, future_type> tag_invoke(pika::execution::experimental::connect_t, keep_future_sender const& s, Receiver&& receiver) { return {PIKA_FORWARD(Receiver, receiver), s.future}; } }; } // namespace pika::keep_future_detail namespace pika::execution::experimental { inline constexpr struct keep_future_t final { // clang-format off template <typename Future, PIKA_CONCEPT_REQUIRES_( pika::traits::is_future_v<std::decay_t<Future>> )> // clang-format on constexpr PIKA_FORCEINLINE auto operator()(Future&& future) const { return keep_future_detail::keep_future_sender<std::decay_t<Future>>( PIKA_FORWARD(Future, future)); } constexpr PIKA_FORCEINLINE auto operator()() const { return detail::partial_algorithm<keep_future_t>{}; } } keep_future{}; } // namespace pika::execution::experimental
// // newSet.cpp // Homework 1 // // Created by Hender Lin on 4/12/21. // #include <iostream> #include <string> #include "newSet.h" using namespace std; Set::Set(int max) { if (max < 0) { exit(1); } m_length = 0; m_max = max; m_set = new ItemType[max]; } Set::Set(const Set &other) { m_length = other.m_length; m_max = other.m_max; m_set = new ItemType[m_length]; for (int i = 0; i < m_length; i++) { m_set[i] = other.m_set[i]; } } Set &Set::operator=(const Set &other) { if (&other == this) { return *this; } delete [] m_set; m_length = other.m_length; m_max = other.m_max; m_set = new ItemType[m_length]; for (int i = 0; i < m_length; i++) { m_set[i] = other.m_set[i]; } return *this; } Set::~Set() { delete [] m_set; } bool Set::empty() const { if (m_length == 0) { return true; } return false; } int Set::size() const { return m_length; } bool Set::insert(const ItemType& value) { if (m_length >= m_max) { return false; } if (m_length == 0) { m_set[0] = value; m_length++; return true; } if (contains(value)) { return false; } for (int i = 0; i < m_length; i++) { if (m_set[i] > value) { for (int j = m_length; j > i; j--) { m_set[j] = m_set[j - 1]; } m_set[i] = value; m_length++; return true; } } m_set[m_length] = value; m_length++; return true; } bool Set::erase(const ItemType& value) { for (int i = 0; i < m_length; i++) { if (m_set[i] == value) { for (int j = i; j < m_length - 1; j++) { m_set[j] = m_set[j + 1]; } m_length--; return true; } } return false; } bool Set::contains(const ItemType& value) const { for (int i = 0; i < m_length; i++) { if (m_set[i] == value) { return true; } } return false; } bool Set::get(int i, ItemType& value) const { if (i < 0 || i >= m_length) { return false; } value = m_set[m_length-1-i]; return true; } void Set::swap(Set& other) { std::swap(this->m_length, other.m_length); std::swap(this->m_max, other.m_max); std::swap(this->m_set, other.m_set); }
/* 1220.cc */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; #define M 5 #define N 20 class A{ public: A(){ cout<<"class A created."<<endl; } ~A(){ cout<<"class A deleted."<<endl; } }; class B: public A{ public: B(){ cout<<"class B created."<<endl; } ~B(){ cout<<"class B deleted."<<endl; } }; class C: public B{ public: C(){ cout<<"class C created."<<endl; } ~C(){ cout<<"class C deleted."<<endl; } }; void prim(int m, int n){ if(m >= n){ while(m%n) n++; m /= n; prim(m, n); cout<<n<<endl; } } //string array int func(char(* ss)[N], int *n){ int i, k = 0, len = N; for(i=0; i<M; i++){ len = strlen(ss[i]); if(len < *n){ *n = len; k = i; } } return k; } void GetMemory(char* p){ p = (char*)malloc(100); } int main(int argc, char **argv){ /* B *b = new B(); C *c = new C(); A *pab = dynamic_cast<B*>(b); A *pac = dynamic_cast<C*>(c); B *pbc = dynamic_cast<C*>(c); //B *pb = dynamic_cast<A*>(a);// downward cast failed delete(b); delete(c); */ /* char a; // 1byte int b; //2byte int pm = 12456; int pn = 24; float c; //4byte double d; //8byte printf("sizeof(char)=%d\n", sizeof(a)); printf("sizeof(int)=%d\n", sizeof(b)); printf("sizeof(float)=%d\n", sizeof(c)); printf("sizeof(double)=%d\n", sizeof(d)); prim(pm, pn); char ss[M][N] = {"shanghai", "guangzhou", "beijing", "tianjing", "chongqing"}; int n, k, i; printf("\nThe originalb string are: \n"); for(i=0; i<M; i++) puts(ss[i]); //print to the screen k = func(ss, &n); printf("\nThe length of shortest string is: %d\n", n); printf("\nThe shortes string is : %s\n", ss[k]); */ /* char ccString1[] = "Is Page Fault??"; char ccString2[] = "No Page Fault??"; strcpy(ccString1, "No"); //"No\0Page Fault??" if(strcmp(ccString1, ccString2)==0) //returns when strcmp counter '\0' cout<<ccString2<<endl; else cout<<ccString1<<endl; */ /* char *str = NULL; GetMemory(str); str = (char*)malloc(100); strcpy(str, "Thunder"); strcat(str+2, "Downloader"); //append string to source string printf(str); */ FILE *fp; //define a file pointer int i, a[6]={1,2,3,4,5,6}, k; fp = fopen("data.dat", "w+b"); //open a rw file in binary for(i=0; i<6; i++){ //overwrite fseek(fp, 0L, 0); //point to begining of the file fwrite(&a[5-i], sizeof(int), 1, fp); //write data array into file reversely } rewind(fp); //point to head of the file fread(&k, sizeof(int), 1, fp); //read an int data into k fclose(fp); printf("%d\n", k); return 0; }
// Example 6.6 : Time and date // Created by Oleksiy Grechnyev 2017 #include <iostream> #include <thread> #include <ratio> #include <chrono> #include <ctime> #include <iomanip> using namespace std; using namespace std::chrono; // Some method we are going to time int fun(int n){ int result = 0; for (int i = 0; i<1000*1000; ++i) result = (result + i*(i+1)*(i+2))%12345; return result; } //============================== int main(){ { cout << "\nRatio: :\n\n"; using R1 = ratio<1, 1000>; cout << "1/1000 = " << R1::num << "/" << R1::den << endl; using R2 = ratio<25, 15>; cout << "25/15 = " << R2::num << "/" << R2::den << endl; using R3 = ratio<100, -10>; cout << "100/-10 = " << R3::num << "/" << R3::den << endl; // Pre-defined ratios cout << "atto = " << atto::num << "/" << atto::den << endl; cout << "nano = " << nano::num << "/" << nano::den << endl; cout << "milli = " << milli::num << "/" << milli::den << endl; cout << "giga = " << giga::num << "/" << giga::den << endl; cout << "exa = " << exa::num << "/" << exa::den << endl; // Arithmetics using R5 = ratio_add<ratio<1, 2>, ratio<1, 3>>; cout << "1/2 + 1/3 = " << R5::num << "/" << R5::den << endl; using R6 = ratio_multiply<ratio<1, 2>, ratio<1, 3>>; cout << "1/2 * 1/3 = " << R6::num << "/" << R6::den << endl; // Comparison. Static field value gives true or false. cout << boolalpha << "1/2 > 1/3 = " << ratio_greater<ratio<1, 2>, ratio<1, 3>>::value << endl; } { cout << "\nduration, duration_cast :\n\n"; // Define own duration types using DMinutes = duration<double, ratio<60>>; using DSeconds = duration<double>; using DDays = duration<double, ratio<60*60*24>>; // 60*60*24/1 using DHours = duration<double, ratio<60*60>>; // 60*60/1 // Examples from cppreference.com constexpr auto year = 31556952ll; // seconds in average Gregorian year using Shakes = duration<int, ratio<1, 100000000>>; using Jiffies = duration<int, centi>; using Microfortnights = duration<float, ratio<14*24*60*60, 1000000>>; using Nanocenturies = duration<float, ratio<100*year, 1000000000>>; // Variables seconds s148(148); //148 int seconds minutes m1(1); //1 int minute DSeconds ds1_3(1.3); //1.3 double seconds auto dur1 = minutes(1) + seconds(3) - milliseconds(247); // Time literals, use operator""h etc. using namespace std::chrono_literals; auto dur2 = 1h + 10min + 42s; auto dur3 = 1s + 234ms + 567us + 890ns; // count(), duration_cast // Implicit cast cout.precision(9); cout << "148 seconds = " << DMinutes(s148).count() << " DMinutes" << endl; // Here we need duration_cast beacuse of loss of accuracy cout << "148 seconds = " << duration_cast<minutes>(s148).count() << " minutes" << endl; cout << "1.3 seconds = " << duration_cast<milliseconds>(ds1_3).count() << " milliseconds" << endl; cout << "dur1 = " << milliseconds(dur1).count() << " milliseconds" << endl; cout << "dur2 = " << seconds(dur2).count() << " seconds" << endl; cout << "dur3 = " << DSeconds(dur3).count() << " DSeconds" << endl; } { cout << "\nclocks, timing execution :\n\n"; // How do we time execution? Ge the first time_point auto t1 = high_resolution_clock::now(); int result = fun(17); auto t2 = high_resolution_clock::now(); // time_point 2 cout << "fun(17) = " << result << endl; nanoseconds dNS = duration_cast<nanoseconds>(t2-t1); using DSeconds = duration<double>; DSeconds dS = duration_cast<DSeconds >(t2-t1); cout << "Timing(nanoseconds) : " << dNS.count() << endl; cout << "Timing(seconds) : " << dS.count() << endl; // Sleep for a while cout << "Going to sleep ..." << endl; this_thread::sleep_for(milliseconds(1260)); cout << "Waking up ..." << endl; } { cout << "\nC time, printing time :\n\n"; // time_t is the integer type for time in seconds since epoch (1970) // C time, returns time_t time_t t1 = time(nullptr); cout << "t1 = " << t1 << endl; // The same type time_t can be obtained from a C++ time_point system_clock::time_point tP2 = system_clock::now(); // auto is usually used, of course time_t t2 = system_clock::to_time_t(tP2); // Convert to time_t cout << "t2 = " << t2 << endl; cout << "Different ways to print time_t: t1 = " << endl; // Preferred c++ way cout << "put_time(localtime()) : " << put_time(localtime(&t1), "%c %Z") << endl; cout << "put_time(gmtime()) : " << put_time(gmtime(&t1), "%c %Z") << endl; // Old C ways cout << "asctime(localtime()) : " << asctime(localtime(&t1)); // No endl, as asctime gives \n cout << "ctime : " << ctime(&t1); // Short for asctime(localtime(&t1)) cout << "asctime(gmtime()) : " << asctime(gmtime(&t1)); cout << "\n\n"; // tm calendar structure tm tM1 = *localtime(&t1); // Copy from static buffer to tM1 cout << "put_time(&tM1) = " << put_time(&tM1, "%c %Z") << endl; cout << "tM1.tm_year = " << tM1.tm_year << endl; cout << "tM1.tm_mon = " << tM1.tm_mon << endl; cout << "tM1.tm_mday = " << tM1.tm_mday << endl; cout << "tM1.tm_hour = " << tM1.tm_hour << endl; cout << "tM1.tm_min = " << tM1.tm_min << endl; cout << "tM1.tm_sec = " << tM1.tm_sec << endl; cout << "tM1.tm_wday = " << tM1.tm_wday << endl; cout << "tM1.tm_yday = " << tM1.tm_yday << endl; cout << "tM1.tm_isdst = " << tM1.tm_isdst << endl; // C clock(), time since the program started, usually in milliseconds clock_t c = clock(); double cD = 1.0*c/CLOCKS_PER_SEC; cout << "\nThe program ran for " << cD << " seconds" << endl; } return 0; }
#include "stdafx.h" #include "Deque.cpp" class Simple2TieredVector : public ArrayDataStructure { private: int32_t n = 0; int32_t m = 0; // Number of children protected: vector<Deque> children; void init(int32_t size) { this->m = size; this->children = vector<Deque>(m); } void increaseCapacity() { int32_t oldM = m; m *= 2; vector<Deque> newChildren(m); for (int32_t i = 0; i < oldM; i++) { newChildren[i] = children[i]; newChildren[i].increaseCapacity(); } for (int32_t i = oldM; i < m; i++) { newChildren[i] = Deque(m); } children = newChildren; // Move everything to the lower 1/4 of the current TV int32_t nextDequeWithElems = 1; int32_t moved = 0; int32_t limit = n - children[0].size(); for (int32_t i = 0; moved < limit; i++) { while (!children[i].isFull()) { children[i].insertLast(children[nextDequeWithElems].removeFirst()); moved++; if (moved >= limit) { break; } while (children[nextDequeWithElems].isEmpty()) { nextDequeWithElems = (nextDequeWithElems + 1); } } } } void decreaseCapacity() { vector<Deque> newA(m / 2); for (int32_t i = 0; i < m / 2; i++) { newA[i] = Deque(m / 2); } for (int32_t i = 0; i < m / 4; i++) { newA[i] = children[i / 2].lowerHalf(); i++; newA[i] = children[i / 2].upperHalf(); } children = newA; m /= 2; } public: Simple2TieredVector(int32_t size) { init(size); for (int32_t i = 0; i < size; i++) { children[i] = Deque(size); } } Simple2TieredVector(void) { init(DEFAULT_SIZE); } ~Simple2TieredVector(void) { children.clear(); vector<Deque>().swap(children); } uint32_t size() { return n; } int32_t getElemAt(int32_t r) { int32_t i = r / m; return children[i].getElemAt(r - i*m); } void setElemAt(int32_t r, int32_t e) { int32_t i = r / m; return children[i].setElemAt(r - i*m, e); } void insertElemAt(int32_t r, int32_t e) { if (isFull()) { increaseCapacity(); } int32_t i = r / m; if (children[i].isFull()) { int32_t back = n / m; if (children[back].isFull()) { back++; } for (int32_t j = back; j > i; j--) { children[j].insertFirst(children[j - 1].removeLast()); } } children[i].insertElemAt(r - i*m, e); n++; } void insertLast(int32_t e) { if (isFull()) { increaseCapacity(); } int32_t i = n / m; if (children[i].isFull()) i++; children[i].insertLast(e); n++; } int32_t removeElemAt(int32_t r) { if (n < m * m / 8) { decreaseCapacity(); } int32_t i = r / m; int32_t e = children[i].removeElemAt(r - i*m); for (int32_t j = i; j < (n - 1) / m; j++) { children[j].insertLast(children[j + 1].removeFirst()); } n--; return e; } int32_t removeLast() { if (n < m * m / 8) { decreaseCapacity(); } int32_t i = (n - 1) / m; int32_t e = children[i].removeElemAt(n - 1 - i*m); n--; return e; } bool isFull() { return children[m - 1].isFull(); } string toStringSimple() { string s = ""; if (m > 0) { s += children[0].toStringSimple(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toStringSimple(); } return s; } string toStringPretty() { string s = "{ "; if (m > 0) { s += children[0].toStringPretty(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toStringPretty(); } return s += " }"; } string toString() { string s = "{ "; if (m > 0) { s += children[0].toString(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toString(); } return s += " }"; } }; class BitTrickSimple2TieredVector : public ArrayDataStructure { private: int32_t n = 0; int32_t m = 0; protected: vector<BitTrickDeque> children; int8_t shift; void increaseCapacity() { int32_t oldM = m; m = m << 1; vector<BitTrickDeque> newSubvectors(m); for (int32_t i = 0; i < oldM; i++) { newSubvectors[i] = children[i]; newSubvectors[i].increaseCapacity(); } for (int32_t i = oldM; i < m; i++) { newSubvectors[i] = BitTrickDeque(m); } children = newSubvectors; // Move everything to the lower 1/4 of the current TV int32_t nextDequeWithElems = 1; int32_t moved = 0; int32_t limit = n - children[0].size(); for (int32_t i = 0; moved < limit; i++) { while (!children[i].isFull()) { children[i].insertLast(children[nextDequeWithElems].removeFirst()); moved++; if (moved >= limit) { break; } while (children[nextDequeWithElems].isEmpty()) { nextDequeWithElems = (nextDequeWithElems + 1); } } } shift++; } void decreaseCapacity() { m = m >> 1; vector<BitTrickDeque> newSubvectors(m); for (int32_t i = 0; i < m; i++) { newSubvectors[i] = BitTrickDeque(m); } for (int32_t i = 0; i < m >> 1; i++) { newSubvectors[i] = children[i >> 1].lowerHalf(); i++; newSubvectors[i] = children[i >> 1].upperHalf(); } children = newSubvectors; shift--; } public: BitTrickSimple2TieredVector() { this->m = DEFAULT_SIZE; this->shift = (int32_t)log2(DEFAULT_SIZE); this->children = vector<BitTrickDeque>(DEFAULT_SIZE); } ~BitTrickSimple2TieredVector(void) { children.clear(); vector<BitTrickDeque>().swap(children); } uint32_t size() { return n; } int32_t getElemAt(int32_t r) { int32_t i = r >> shift; return children[i].getElemAt(r - (i << shift)); } void setElemAt(int32_t r, int32_t e) { int32_t i = r >> shift; return children[i].setElemAt(r - (i << shift), e); } void insertElemAt(int32_t r, int32_t e) { if (isFull()) { increaseCapacity(); } int32_t i = r >> shift; if (children[i].isFull()) { int32_t back = n >> shift; if (children[back].isFull()) { back++; } for (int32_t j = back; j > i; j--) { children[j].insertFirst(children[j - 1].removeLast()); } } children[i].insertElemAt(r - (i << shift), e); n++; } void insertLast(int32_t e) { if (isFull()) { increaseCapacity(); } int32_t i = n >> shift; if (children[i].isFull()) i++; children[i].insertLast(e); n++; } int32_t removeElemAt(int32_t r) { if (n < (m << shift) >> 3) { // Divide by 8 decreaseCapacity(); } int32_t i = r >> shift; int32_t e = children[i].removeElemAt(r - (i << shift)); for (int32_t j = i; j < (n - 1) >> shift; j++) { children[j].insertLast(children[j + 1].removeFirst()); } n--; return e; } int32_t removeLast() { if (n < m << shift >> 3) { // Divide by 8 decreaseCapacity(); } int32_t i = (n - 1) >> shift; int32_t e = children[i].removeElemAt(n - 1 - (i << shift)); n--; return e; } bool isFull() { return children[m - 1].isFull(); } string toStringSimple() { string s = ""; if (m > 0) { s += children[0].toStringSimple(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toStringSimple(); } return s; } string toStringPretty() { string s = "{ "; if (m > 0) { s += children[0].toStringPretty(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toStringPretty(); } return s += " }"; } string toString() { string s = "{ "; if (m > 0) { s += children[0].toString(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toString(); } return s += " }"; } }; class Deque2TieredVector : public ArrayDataStructure { private: int32_t n = 0; int32_t h = 0; int32_t m = 0; // Number of children vector<Deque> children; int32_t child(int32_t r) { return (h + r) % m; } void incH(int8_t inc) { h = (h + inc + m) % m; } void init(int32_t size) { this->m = size; this->children = vector<Deque>(size); } void increaseCapacity() { vector<Deque> newA(m * 2); for (int32_t i = 0; i < m * 2; i++) { newA[i] = Deque(m * 2); } // Move everything to the lower 1/4 of this tiered vector int32_t idx = 0; for (int32_t i = 0; i < m; i++) { while (!newA[i].isFull() && idx < n) { newA[i].insertLast(getElemAt(idx)); idx++; } } children = newA; m *= 2; h = 0; } void decreaseCapacity() { vector<Deque> newA(m / 2); for (int32_t i = 0; i < m / 2; i++) { newA[i] = Deque(m / 2); } int32_t to = 0; for (int32_t i = 0; i < n; i++) { newA[to].insertElemAt(i % (m / 2), getElemAt(i)); if (newA[to].isFull()) to++; } children = newA; m /= 2; h = 0; } bool lastFull() { int32_t i = (h - 1 + m) % m; return children[i].size() == m; } bool firstFull() { return children[h].size() == m; } bool tooFull() { return children[h].size() > 0 && children[(h - 1 + m) % m].size() > 0; } bool tooEmpty() { return n < m * m / 8; } public: Deque2TieredVector() { init(DEFAULT_SIZE); } Deque2TieredVector(int32_t size) { init(size); } ~Deque2TieredVector(void) { children.clear(); vector<Deque>().swap(children); } uint32_t size() { return n; } int32_t getElemAt(int32_t r) { int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) % m; return children[child(i)].getElemAt(newR); } void setElemAt(int32_t r, int32_t e) { int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) % m; return children[child(i)].setElemAt(newR, e); } void insertElemAt(int32_t r, int32_t e) { if (r == n) { return insertLast(e); } else if (r == 0) { return insertFirst(e); } bool insertFront = r < n - r; if (tooFull() && ((insertFront && firstFull()) || (!insertFront && lastFull()))) { increaseCapacity(); } int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) % m; if (insertFront) { if (children[h].isFull()) { incH(-1); i++; } if (i > 0) { newR--; if (newR < 0) { i--; newR = i == 0 ? children[h].size() : m - 1; } } for (int32_t j = 0; j < i; j++) { children[child(j)].insertLast(children[child(j + 1)].removeFirst()); } } else { int32_t back = (int32_t)ceil((double)(n - n0) / m); if (children[child(back)].isFull()) { back++; } for (int32_t j = back; j > i; j--) { children[child(j)].insertFirst(children[child(j - 1)].removeLast()); } } children[child(i)].insertElemAt(newR, e); n++; } void insertFirst(int32_t e) { if (tooFull() && firstFull()) { increaseCapacity(); } if (children[h].isFull()) incH(-1); children[h].insertFirst(e); n++; } void insertLast(int32_t e) { if (tooFull() && lastFull()) { increaseCapacity(); } int32_t i = n / m; if (children[child(i)].isFull()) i++; children[child(i)].insertLast(e); n++; } int32_t removeElemAt(int32_t r) { if (tooEmpty()) { decreaseCapacity(); } int32_t e; bool removeFront = r < n - r; int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) % m; if (removeFront) { e = children[child(i)].removeElemAt(newR); for (int32_t j = i; j > 0; j--) { children[child(j)].insertFirst(children[child(j - 1)].removeLast()); } if (children[h].isEmpty()) { incH(1); } } else { e = children[child(i)].removeElemAt(newR); int32_t back = (int32_t)ceil((double)(n - n0) / m); if (children[child(back)].isEmpty()) { back--; } for (int32_t j = i; j < back; j++) { children[child(j)].insertLast(children[child(j + 1)].removeFirst()); } } n--; return e; } int32_t removeFirst() { return removeElemAt(0); } int32_t removeLast() { return removeElemAt(n); } bool isFull() { return n == m * m; } bool isEmpty() { return n == 0; } string toStringPretty() { string s = "{ "; if (m > 0) { s += children[h].toStringPretty(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[child(i)].toStringPretty(); } return s += " }"; } string toString() { string s = "{ "; if (m > 0) { s += children[0].toString(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toString(); } return s += " }"; } }; // TODO class BitTrickDeque2TieredVector : public ArrayDataStructure { private: int32_t n = 0; int32_t h = 0; int32_t m = 0; // Number of children int8_t shift; vector<BitTrickDeque> children; int32_t child(int32_t r) { return (h + r) & (m - 1); } void incH(int8_t inc) { h = (h + inc + m) & (m - 1); } void increaseCapacity() { int32_t newM = m << 1; vector<BitTrickDeque> newA(newM); for (int32_t i = 0; i < newM; i++) { newA[i] = BitTrickDeque(newM); } // Move everything to the lower 1/4 of this tiered vector int32_t idx = 0; for (int32_t i = 0; i < m; i++) { while (!newA[i].isFull() && idx < n) { newA[i].insertLast(getElemAt(idx)); idx++; } } children = newA; m = newM; shift++; h = 0; } void decreaseCapacity() { int32_t newM = m >> 1; vector<BitTrickDeque> newA(newM); for (int32_t i = 0; i < newM; i++) { newA[i] = BitTrickDeque(newM); } int32_t to = 0; for (int32_t i = 0; i < n; i++) { newA[to].insertElemAt(i & (newM - 1), getElemAt(i)); if (newA[to].isFull()) to++; } children = newA; m = newM; shift--; h = 0; } bool lastFull() { int32_t i = (h - 1 + m) & (m - 1); return children[i].size() == m; } bool firstFull() { return children[h].size() == m; } bool tooFull() { return children[h].size() > 0 && children[(h - 1 + m) & (m - 1)].size() > 0; } bool tooEmpty() { return n < m << shift >> 3; } public: BitTrickDeque2TieredVector() { this->m = DEFAULT_SIZE; this->children = vector<BitTrickDeque>(DEFAULT_SIZE); this->shift = (int32_t)log2(DEFAULT_SIZE); } ~BitTrickDeque2TieredVector(void) { children.clear(); vector<BitTrickDeque>().swap(children); } uint32_t size() { return n; } int32_t getElemAt(int32_t r) { int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) & (m - 1); return children[child(i)].getElemAt(newR); } void setElemAt(int32_t r, int32_t e) { int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) & (m - 1); return children[child(i)].setElemAt(newR, e); } void insertElemAt(int32_t r, int32_t e) { if (r == n) { return insertLast(e); } else if (r == 0) { return insertFirst(e); } bool insertFront = r < n - r; if (tooFull() && ((insertFront && firstFull()) || (!insertFront && lastFull()))) { increaseCapacity(); } int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) & (m - 1); if (insertFront) { if (children[h].isFull()) { incH(-1); i++; } if (i > 0) { newR--; if (newR < 0) { i--; newR = i == 0 ? children[h].size() : m - 1; } } for (int32_t j = 0; j < i; j++) { children[child(j)].insertLast(children[child(j + 1)].removeFirst()); } } else { int32_t back = (int32_t)ceil((double)(n - n0) / m); if (children[child(back)].isFull()) { back++; } for (int32_t j = back; j > i; j--) { children[child(j)].insertFirst(children[child(j - 1)].removeLast()); } } children[child(i)].insertElemAt(newR, e); n++; } void insertFirst(int32_t e) { if (tooFull() && firstFull()) { increaseCapacity(); } if (children[h].isFull()) incH(-1); children[h].insertFirst(e); n++; } void insertLast(int32_t e) { if (tooFull() && lastFull()) { increaseCapacity(); } int32_t i = n >> shift; if (children[child(i)].isFull()) i++; children[child(i)].insertLast(e); n++; } int32_t removeElemAt(int32_t r) { if (tooEmpty()) { decreaseCapacity(); } int32_t e; bool removeFront = r < n - r; int32_t n0 = children[h].size(); int32_t i = (int32_t)ceil((double)(r + 1 - n0) / m); int32_t newR = i == 0 ? r : (r - n0) & (m - 1); if (removeFront) { e = children[child(i)].removeElemAt(newR); for (int32_t j = i; j > 0; j--) { children[child(j)].insertFirst(children[child(j - 1)].removeLast()); } if (children[h].isEmpty()) { incH(1); } } else { e = children[child(i)].removeElemAt(newR); int32_t back = (int32_t)ceil((double)(n - n0) / m); if (children[child(back)].isEmpty()) { back--; } for (int32_t j = i; j < back; j++) { children[child(j)].insertLast(children[child(j + 1)].removeFirst()); } } n--; return e; } int32_t removeFirst() { return removeElemAt(0); } int32_t removeLast() { return removeElemAt(n); } bool isFull() { return n == m << shift; } bool isEmpty() { return n == 0; } string toStringPretty() { string s = "{ "; if (m > 0) { s += children[h].toStringPretty(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[child(i)].toStringPretty(); } return s += " }"; } string toString() { string s = "{ "; if (m > 0) { s += children[0].toString(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toString(); } return s += " }"; } }; class DeamortisedBitTrickSimple2TieredVector : public ArrayDataStructure { private: int32_t n = 0; int32_t m = 0; int32_t n_double = 0; int32_t missing_double = 0; protected: vector<BitTrickDeque> children; vector<BitTrickDeque> children_double; int8_t shift; void increaseCapacity() { int32_t oldM = m; m = m << 1; children.swap(children_double); n_double = 0; missing_double = 0; shift++; } void decreaseCapacity() { throw exception("Not implemented"); //int32_t oldM = m; //m = m >> 1; //moreChildren.clear(); //moreChildren = vector<BitTrickDeque>(oldM); //for (int32_t i = 0; i < oldM; i++) { // moreChildren[i] = BitTrickDeque(oldM); //} //shift--; } void insertElemAtMore(int32_t r, int32_t e) { int8_t moreShift = shift + 1; int32_t i = r >> moreShift; if (children_double.size() > m << 1) { children_double.erase(children_double.end()); } if (missing_double < m << 1) { if (children_double.size() > missing_double) children_double[missing_double++] = BitTrickDeque(m << 1); else children_double.insert(children_double.begin() + missing_double++, BitTrickDeque(m << 1)); } if (children_double[i].isFull()) { int32_t back = n_double >> moreShift; if (children_double[back].isFull()) { back++; } for (int32_t j = back; j > i; j--) { children_double[j].insertFirst(children_double[j - 1].removeLast()); } } children_double[i].insertElemAt(r - (i << moreShift), e); n_double++; } void insertMoreLast(int32_t e) { insertElemAtMore(n_double, e); } public: DeamortisedBitTrickSimple2TieredVector() { this->m = DEFAULT_SIZE; this->shift = (int32_t)log2(DEFAULT_SIZE); this->children = vector<BitTrickDeque>(DEFAULT_SIZE); this->children_double = vector<BitTrickDeque>(DEFAULT_SIZE << 1); for (int32_t i = 0; i < m << 1; i++) { children_double[i] = BitTrickDeque(m << 1); } } ~DeamortisedBitTrickSimple2TieredVector(void) { children.clear(); vector<BitTrickDeque>().swap(children); children_double.clear(); vector<BitTrickDeque>().swap(children_double); } uint32_t size() { return n; } int32_t getElemAt(int32_t r) { int32_t i = r >> shift; return children[i].getElemAt(r - (i << shift)); } void setElemAt(int32_t r, int32_t e) { throw exception("Not implemented"); int32_t i = r >> shift; children[i].setElemAt(r - (i << shift), e); } void insertElemAt(int32_t r, int32_t e) { if (isFull()) { increaseCapacity(); } int32_t i = r >> shift; if (children[i].isFull()) { int32_t back = n >> shift; if (children[back].isFull()) { back++; } for (int32_t j = back; j > i; j--) { children[j].insertFirst(children[j - 1].removeLast()); } } children[i].insertElemAt(r - (i << shift), e); n++; if (r < n_double) { insertElemAtMore(r, e); } if (n_double < n) { insertMoreLast(getElemAt(n_double)); } if (n_double < n) { insertMoreLast(getElemAt(n_double)); } } void insertLast(int32_t e) { if (isFull()) { increaseCapacity(); } int32_t i = n >> shift; if (children[i].isFull()) i++; children[i].insertLast(e); n++; } int32_t removeElemAt(int32_t r) { throw exception("Not implemented"); if (n < (m << shift) >> 3) { // Divide by 8 decreaseCapacity(); } int32_t i = r >> shift; int32_t e = children[i].removeElemAt(r - (i << shift)); for (int32_t j = i; j < (n - 1) >> shift; j++) { children[j].insertLast(children[j + 1].removeFirst()); } n--; if (n_double > r) { removeElemAtMore(r); } return e; } int32_t removeLast() { if (n < m << shift >> 3) { // Divide by 8 decreaseCapacity(); } int32_t i = (n - 1) >> shift; int32_t e = children[i].removeElemAt(n - 1 - (i << shift)); n--; if (n_double > n) { removeElemAtMore(n_double); } return e; } void removeElemAtMore(int32_t r) { int8_t moreShift = shift + 1; int32_t i = r >> moreShift; int32_t e = children_double[i].removeElemAt(r - (i << moreShift)); for (int32_t j = i; j < (n_double - 1) >> moreShift; j++) { children_double[j].insertLast(children_double[j + 1].removeFirst()); } n_double--; } bool isFull() { return children[m - 1].isFull(); } string toStringSimple() { string s = ""; if (m > 0) { s += children[0].toStringSimple(); } for (int32_t i = 1; i < m; i++) { s += ", " + children[i].toStringSimple(); } return s; } string toStringPretty() { string s = "{ "; if (m > 0) { s += children[0].toStringPretty(); } for (int32_t i = 1; i < children.size(); i++) { s += ", " + children[i].toStringPretty(); } s += " }"; s += "\n{ "; if (m > 0) { s += children_double[0].toStringPretty(); } for (int32_t i = 1; i < children_double.size(); i++) { s += ", " + children_double[i].toStringPretty(); } return s += " }"; } string toString() { string s = "{ "; if (m > 0) { s += children[0].toString(); } for (int32_t i = 1; i < children.size(); i++) { s += ", " + children[i].toString(); } return s += " }"; } };
/* Castle of Despair SDH 1/21/03 */ #include "stdafx.h" #include "windows.h" #include <cstdlib> #include <conio.h> #include <iostream> #include <string> #include <time.h> #include <vector> using namespace std; int random(int max) { return rand() % max; } void randomize(void) { srand (time(NULL)); } struct MatrixType { MatrixType(); char Space[8][8]; }; MatrixType::MatrixType() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Space[i][j] = '.'; } } } typedef vector<MatrixType> FloorType; struct StatsType { string Race; string Gender; int Attack; int Defense; int Health; int Magic; int Dex; int Gold; int Immobilize; bool Blind; bool Book; bool Runestaff; string WeaponName; int WeaponAttack; string ArmorName; int ArmorDefense; bool Dead; }; struct PosType { int t; int x; int y; int z; }; struct TreasureType { bool BlueFlame; bool RubyRed; bool GreenGem; bool OminousGlobe; bool OpalEye; bool NornStone; bool Palantir; bool PalePearl; bool Silmaril; }; struct MonsterType { string Name; int Health; int Attack; int Defense; int Dex; int Magic; int Bribe; int Immobilize; bool Dead; }; void Intro() { cout << "*******************************************************************************" << endl; cout << " Castle of Despair " << endl; cout << "*******************************************************************************" << endl; cout << endl; cout << endl; cout << " A long time ago, a wizard by the name of Barbarus built a" << endl; cout << " castle in the land of N'ruk. He ruled the surrounding area" << endl; cout << " with an iron fist his entire life. Soon the castle only" << endl; cout << " became known as the Castle of Despair. When he died, he" << endl; cout << " left his castle full of treasure and demons." << endl; cout << endl; cout << " The castle still stands a century later. Now you are one" << endl; cout << " of the brave explorers who venture into the castle in" << endl; cout << " search of the greatest treasure Barbarus was said to have" << endl; cout << " left: the Ominous Globe. So far, many have entered the" << endl; cout << " castle, but none have returned..." << endl; cout << endl; cout << endl; } void GetStartStats(StatsType &Stats, char &Race, char &Gender) { cout << "All right, bold one." << endl; cout << endl; while (true) { cout << "Which race are you (Elf, Dwarf, Man, Hobbit)? "; cin >> Race; if ( (Race == 'E' || Race == 'e') || (Race == 'D' || Race == 'd') || (Race == 'M' || Race == 'm') || (Race == 'H' || Race == 'h') ) { break; } cout << "Ha!" << endl; } if (Race == 'E' || Race == 'e') { Stats.Race = "Elf"; } if (Race == 'D' || Race == 'd') { Stats.Race = "Dwarf"; } if (Race == 'M' || Race == 'm') { Stats.Race = "Man"; } if (Race == 'H' || Race == 'h') { Stats.Race = "Hobbit"; } cout << endl; while (true) { cout << "What gender are you? "; cin >> Gender; if ( (Gender == 'M' || Gender == 'm') || (Gender == 'F' || Gender == 'f') ) { break; } cout << "I don\'t believe you!" << endl; } if (Gender == 'M' || Gender == 'm') { Stats.Gender = "male"; } if (Gender == 'F' || Gender == 'f') { Stats.Gender = "female"; } cout << endl; if (Race == 'E' || Race == 'e') { Stats.Attack = 8; Stats.Defense = 8; Stats.Magic = 10; Stats.Dex = 14; } if (Race == 'D' || Race == 'd') { Stats.Attack = 16; Stats.Defense = 10; Stats.Magic = 6; Stats.Dex = 8; } if (Race == 'M' || Race == 'm') { Stats.Attack = 10; Stats.Defense = 10; Stats.Magic = 10; Stats.Dex = 10; } if (Race == 'H' || Race == 'h') { Stats.Attack = 8; Stats.Defense = 9; Stats.Magic = 10; Stats.Dex = 13; } Stats.Health = 20; } void StartEquip(StatsType &Stats) { char Choice; while (true) { cout << "You have " << Stats.Gold << " gold and " << Stats.WeaponName << "." << endl; cout << "<25> Dagger <10> Knife <0> Nothing" << endl; cout << "What do you want? "; cin >> Choice; if ( (Choice == 'D' || Choice == 'd') || (Choice == 'K' || Choice == 'k') || (Choice == 'N' || Choice == 'n') ) { break; } cout << "I don\'t see that one!" << endl; } cout << endl; if (Choice == 'D' || Choice == 'd') { Stats.WeaponName = "a Dagger"; Stats.WeaponAttack = 10; Stats.Attack += Stats.WeaponAttack; Stats.Gold -= 25; } if (Choice == 'K' || Choice == 'k') { Stats.WeaponName = "a Knife"; Stats.WeaponAttack = 5; Stats.Attack += Stats.WeaponAttack; Stats.Gold -= 10; } if (Choice == 'N' || Choice == 'n') { Stats.WeaponName = "no weapon"; Stats.WeaponAttack = 0; Stats.Attack += Stats.WeaponAttack; } while (true) { cout << "You have " << Stats.Gold << " gold and " << Stats.ArmorName << "." << endl; cout << "<25> Plate <10> Cloth <0> Nothing" << endl; cout << "What do you want? "; cin >> Choice; if ( (Choice == 'P' || Choice == 'p') || (Choice == 'C' || Choice == 'c') || (Choice == 'N' || Choice == 'n') ) { break; } cout << "Where\'s that choice?" << endl; } cout << endl; if (Choice == 'P' || Choice == 'p') { Stats.ArmorName = "Plate armor"; Stats.ArmorDefense = 10; Stats.Defense += Stats.ArmorDefense; Stats.Gold -= 25; } if (Choice == 'C' || Choice == 'c') { Stats.ArmorName = "Cloth armor"; Stats.ArmorDefense = 5; Stats.Defense += Stats.ArmorDefense; Stats.Gold -= 10; } if (Choice == 'N' || Choice == 'n') { Stats.ArmorName = "no armor"; Stats.ArmorDefense = 0; Stats.Defense += Stats.ArmorDefense; } } void StockCastle(FloorType &Floor) { const int MaxFloorNum = 7; int FloorNum; Floor[0].Space[0][0] = 'E'; for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Monsters = (random(3) + 9); while (Monsters > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'M'; Monsters--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Warps = (random(3) + 2); while (Warps > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'W'; Warps--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Pools = (random(3) + 2); while (Pools > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'P'; Pools--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Chests = (random(3) + 6); while (Chests > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'C'; Chests--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Books = (random(3) + 6); while (Books > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'B'; Books--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Orbs = (random(3) + 2); while (Orbs > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'O'; Orbs--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Sinkholes = (random(3) + 4); while (Sinkholes > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'S'; Sinkholes--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Gold = (random(3) + 4); while (Gold > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'G'; Gold--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int Vendor = (random(2) + 1); while (Vendor > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'V'; Vendor--; } } } for (FloorNum = 0; FloorNum <= MaxFloorNum; FloorNum++) { int UStairs = (random(2) + 1); if (FloorNum == 7) { UStairs = 1; } while (UStairs > 0) { int RandNum1 = random(8); int RandNum2 = random(8); if (Floor[FloorNum].Space[RandNum1][RandNum2] == '.') { Floor[FloorNum].Space[RandNum1][RandNum2] = 'U'; UStairs--; if (FloorNum < MaxFloorNum) { Floor[FloorNum + 1].Space[RandNum1][RandNum2] = 'D'; } } } } } void DispFloor(const FloorType Floor, PosType Position) { const int FloorNum = Position.z; for (int Row = 0; Row <= 7; Row++) { for (int Col = 0; Col <=7; Col++) { if (Position.x == Row && Position.y == Col) { cout << "<" << Floor [FloorNum].Space[Row][Col]; cout << "> "; } else { cout << " " << Floor[FloorNum].Space[Row][Col]; cout << " "; } } cout << endl << endl; } cout << "You are at (" << Position.x << "," << Position.y << ")"; cout << ", Floor " << Position.z << endl; } void DispStats(StatsType Stats, TreasureType Treasures) { cout << "You are a " << Stats.Gender << " "<< Stats.Race; cout << " with:" << endl; const int NumWidth = 2; const int ColWidth = 16; cout.setf(ios::left); cout.width(NumWidth); cout << Stats.Health << " "; cout.width(ColWidth); cout << "Health"; cout.width(NumWidth); cout << Stats.Gold << " "; cout.width(ColWidth); cout << "Gold"; cout << endl; cout.width(NumWidth); cout << Stats.Attack << " "; cout.width(ColWidth); cout << "Attack"; cout.width(NumWidth); cout << Stats.Defense << " "; cout.width(ColWidth); cout << "Defense"; cout << endl; cout.width(NumWidth); cout << Stats.Dex << " "; cout.width(ColWidth); cout << "Dexterity"; cout.width(NumWidth); cout << Stats.Magic << " "; cout.width(ColWidth); cout << "Magic"; cout << endl; cout.width(NumWidth); cout << "" << " "; cout.width(ColWidth); cout << Stats.WeaponName; cout.width(NumWidth); cout << "" << " "; cout.width(ColWidth); cout << Stats.ArmorName; cout << endl; if (Treasures.BlueFlame == true) { cout << " The Blue Flame "; } if (Treasures.GreenGem == true) { cout << " The Green Gem "; } if (Treasures.NornStone == true) { cout << " The Norn Stone "; } if (Treasures.OpalEye == true) { cout << " The Opal Eye"; } cout << endl; if (Treasures.Palantir == true) { cout << " The Palantir "; } if (Treasures.PalePearl == true) { cout << " The Pale Pearl "; } if (Treasures.RubyRed == true) { cout << " The Ruby Red "; } if (Treasures.Silmaril == true) { cout << " The Silmaril "; } cout << endl; } char GetCommand(StatsType Stats) { char Command; do { cout << "What do you want to do? "; cin >> Command; if ( (Command != 'H' && Command != 'h') && (Command != 'N' && Command != 'n') && (Command != 'S' && Command != 's') && (Command != 'E' && Command != 'e') && (Command != 'W' && Command != 'w') && (Command != 'D' && Command != 'd') && (Command != 'U' && Command != 'u') && (Command != 'R' && Command != 'r') && (Command != 'O' && Command != 'o') && (Command != 'G' && Command != 'g') && (Command != 'T' && Command != 't') && (Command != 'Q' && Command != 'q') ) { cout << "Silly " << Stats.Race; cout << ", that\'s not a command!" << endl; } } while ( (Command != 'H' && Command != 'h') && (Command != 'N' && Command != 'n') && (Command != 'S' && Command != 's') && (Command != 'E' && Command != 'e') && (Command != 'W' && Command != 'w') && (Command != 'D' && Command != 'd') && (Command != 'U' && Command != 'u') && (Command != 'R' && Command != 'r') && (Command != 'O' && Command != 'o') && (Command != 'G' && Command != 'g') && (Command != 'T' && Command != 't') && (Command != 'Q' && Command != 'q') ); return Command; } void InsertBreak() { cout << "Press any key to continue" << endl; getch(); cout << endl; } void Help() { cout << "The following commands are available:" << endl; cout << endl; cout << "H/elp N/orth S/outh E/ast W/est" << endl; cout << "D/own U/p O/pen G/aze T/eleport" << endl; cout << "DR/ink Q/uit" << endl; cout << endl; cout << "The contents of rooms are:" << endl; cout << endl; cout << ". = Empty Room B = Book C = Chest" << endl; cout << "D = Stairs Down E = Entrance G = Gold" << endl; cout << "M = Monster O = Crystal Orb P = Magic Pool" << endl; cout << "S = Sinkhole T = Treasure U = Stairs Up" << endl; cout << "V = Vendor W = Warp" << endl; cout << endl; cout << "The benefits of having treasures:" << endl; cout << endl; cout << "Ruby Red - Fire Spell Pale Pearl - Web Spell" << endl; cout << "Green Gem - Lightning Spell Opal Eye - Cures Blindness" << endl; cout << "Blue Flame - Dissolves Book Norn Stone - Critical Attacks" << endl; cout << "Palantir - Death Spell Silmaril - Heal Spell" << endl; cout << endl; cout << endl; cout << endl; InsertBreak(); } void North(PosType &Position) { if (Position.x > 0) { Position.x -= 1; } else if (Position.x == 0) { Position.x = 7; } } void South(PosType &Position) { if (Position.x < 7) { Position.x += 1; } else if (Position.x == 7) { Position.x = 0; } } void East(PosType &Position) { if (Position.y < 7) { Position.y += 1; } else if (Position.y == 7) { Position.y = 0; } } void West(PosType &Position) { if (Position.y > 0) { Position.y -= 1; } else if (Position.y == 0) { Position.y = 7; } } void OpenChest(StatsType &Stats, PosType &Position, FloorType &Floor) { cout << endl; if (Floor[Position.z].Space[Position.x][Position.y] == 'C') { int RandNum = random(100) + 1; if (RandNum <= 20) { cout << "Toxic gas fills the air - you stagger to the closest exit!" << endl; int PosX = Position.x; int PosY = Position.y; int PosZ = Position.z; int RandDir = random(4); if (RandDir == 0) { North(Position); } if (RandDir == 1) { South(Position); } if (RandDir == 2) { East(Position); } if (RandDir == 3) { West(Position); } Floor[PosZ].Space[PosX][PosY] = '.'; } if (RandNum > 20 && RandNum <= 40) { cout << "KABOOM!!! The chest explodes!" << endl; Stats.Health -= 2; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 40 && RandNum <= 50) { cout << "There is nothing in this chest except cobwebs." << endl; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 50 && RandNum <= 65) { int Weight = random(3); int GoldAmount; if (Weight == 0 || Weight == 1) { GoldAmount = random(500) + 1; } if (Weight == 2) { GoldAmount = random(500) + 501; } Stats.Gold += GoldAmount; cout << "You get " << GoldAmount << " gold from the chest." << endl; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 65 && RandNum <= 75) { cout << "You found a Health Potion - you feel a little healthier." << endl; Stats.Health += 5; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 75 && RandNum <= 85) { cout << "You found a Magic Potion - you can feel your fingers tingle." << endl; Stats.Magic += 5; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 85 && RandNum <= 95) { cout << "You found a Dexterity Potion - your feet feel lighter already." << endl; Stats.Dex += 5; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 95) { cout << "FLASH!!! There is a sudden white light, causing you to go blind." << endl; Stats.Blind = true; Floor[Position.z].Space[Position.x][Position.y] = '.'; } } cout << endl; InsertBreak(); } void OpenBook(StatsType &Stats, PosType &Position, FloorType &Floor) { cout << endl; if (Floor[Position.z].Space[Position.x][Position.y] == 'B') { int RandNum = random(100) + 1; if (RandNum <= 20) { cout << "It\'s just a blank copy." << endl; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 20 && RandNum <= 35) { cout << "It\'s a spellbook - you gain ancient magic from it." << endl; Stats.Magic += 5; Floor[Position.z].Space[Position.x][Position.y] = '.';; } if (RandNum > 35 && RandNum <= 50) { cout << "It turns out to be a manual on how to sharpen your weapons." << endl; Stats.Attack += 5; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 50 && RandNum <= 65) { cout << "The book is an armor-hardening guide." << endl; Stats.Defense += 5; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 65 && RandNum <= 85) { cout << "Poetry of a modern kind can be found in this book of ancient bind." << endl; Floor[Position.z].Space[Position.x][Position.y] = '.'; } if (RandNum > 85) { cout << "The book sticks to your hands! Now you are unable to draw your weapon!" << endl; Stats.Book = true; Floor[Position.z].Space[Position.x][Position.y] = '.'; } } cout << endl; InsertBreak(); } void Gaze(FloorType Floor, StatsType &Stats) { int RandNum = random(100) + 1; cout << endl; if (RandNum <= 25) { int RandX = random(8); int RandY = random(8); int RandZ = random(8); char SpaceChar = Floor[RandZ].Space[RandX][RandY]; cout << "You will fine "; switch (SpaceChar) { case '.': cout << "an empty room "; break; case 'E': cout << "the entrance "; break; case 'M': cout << "a monster "; break; case 'W': cout << "a warp "; break; case 'P': cout << "a magical pool "; break; case 'C': cout << "a chest "; break; case 'B': cout << "a book "; break; case 'O': cout << "a crystal orb "; break; case 'S': cout << "a sinkhole "; break; case 'G': cout << "some gold "; break; case 'V': cout << "a vendor "; break; case 'U': cout << "stairs leading up "; break; case 'D': cout << "stairs leading down "; break; } cout << "at (" << RandX << "," << RandY << ") Floor " << RandZ << endl; } if (RandNum > 25 && RandNum <=45) { cout << "You see yourself in a bloody heap!" << endl; Stats.Health -= 2; } if (RandNum > 45 && RandNum <= 70) { cout << "You see a"; int RandMonster = random(13); switch (RandMonster) { case 0: cout << "n ogre "; break; case 1: cout << " wolf "; break; case 2: cout << " kobold "; break; case 3: cout << " dragon "; break; case 4: cout << " gargoyle "; break; case 5: cout << " goblin "; break; case 6: cout << " vendor "; break; case 7: cout << " lion "; break; case 8: cout << " troll "; break; case 9: cout << " bear "; break; case 10: cout << " minotaur "; break; case 11: cout << " chimera "; break; case 12: cout << " balrog "; break; } cout << "looking back at you." << endl; } if (RandNum > 70) { cout << "You see yourself drinking from a pool and becoming a"; int RandMonster = random(13); switch (RandMonster) { case 0: cout << "n ogre "; break; case 1: cout << " wolf "; break; case 2: cout << " kobold "; break; case 3: cout << " dragon "; break; case 4: cout << " gargoyle "; break; case 5: cout << " goblin "; break; case 6: cout << " vendor "; break; case 7: cout << " lion "; break; case 8: cout << " troll "; break; case 9: cout << " bear "; break; case 10: cout << " minotaur "; break; case 11: cout << " chimera "; break; case 12: cout << " balrog "; break; } cout << "." << endl; } cout << endl; InsertBreak(); } void Teleport(PosType &Position, StatsType Stats) { cout << endl; int XCoor, YCoor, ZCoor; bool Break; do { cout << "Enter the X-coordinate: "; cin >> XCoor; cout << "Enter the Y-coordinate: "; cin >> YCoor; cout << "Enter the Z-coordinate: "; cin >> ZCoor; if ( (XCoor < 0 || XCoor > 7) || (YCoor < 0 || YCoor > 7) || (ZCoor < 0 || ZCoor > 7) ) { cout << "Try entering a number between 0 and 7, stupid " << Stats.Race << "." << endl; Break = false; } else { Break = true; } } while (Break == false); Position.x = XCoor; Position.y = YCoor; Position.z = ZCoor; } void Drink(StatsType &Stats) { int RandNum = random(100) + 1; cout << endl; cout << "You drink from the pool and "; if (RandNum <= 10) { cout << "you changed into a "; if (Stats.Gender == "male") { Stats.Gender = "female"; } else { Stats.Gender = "male"; } cout << Stats.Gender << "!" << endl; } if (RandNum > 10 && RandNum <= 20) { cout << "you changed into a "; int RandRace = random(3); if (Stats.Race == "Elf") { if (RandRace == 0) { Stats.Race = "Dwarf"; } if (RandRace == 1) { Stats.Race = "Man"; } if (RandRace == 2) { Stats.Race = "Hobbit"; } } if (Stats.Race == "Dwarf") { if (RandRace == 0) { Stats.Race = "Elf"; } if (RandRace == 1) { Stats.Race = "Man"; } if (RandRace == 2) { Stats.Race = "Hobbit"; } } if (Stats.Race == "Man") { if (RandRace == 0) { Stats.Race = "Elf"; } if (RandRace == 1) { Stats.Race = "Dwarf"; } if (RandRace == 2) { Stats.Race = "Hobbit"; } } if (Stats.Race == "Hobbit") { if (RandRace == 0) { Stats.Race = "Elf"; } if (RandRace == 1) { Stats.Race = "Dwarf"; } if (RandRace == 2) { Stats.Race = "Man"; } } cout << Stats.Race << "!" << endl; } if (RandNum > 20 && RandNum <= 50) { int RandPM = random(2); if (RandPM == 0) { Stats.Dex += 2; cout << "feel nimbler!" << endl; } if (RandPM == 1) { Stats.Dex -= 2; cout << "feel slower!" << endl; } } if (RandNum > 50 && RandNum <= 80) { int RandPM = random(2); if (RandPM == 0) { Stats.Magic += 2; cout << "feel magical!" << endl; } if (RandPM == 1) { Stats.Magic -= 2; cout << "feel less magical!" << endl; } } if (RandNum > 80) { cout << "feel refreshed!" << endl; } cout << endl; InsertBreak(); } void Died(StatsType Stats, PosType Position, TreasureType Treasure) { cout << "You died due to lack of health!" << endl; cout << "When you died you had: " << endl; if (Treasure.RubyRed == true) { cout << " Ruby Red" << endl; } if (Treasure.GreenGem == true) { cout << " Green Gem" << endl; } if (Treasure.BlueFlame == true) { cout << " Blue Flame" << endl; } if (Treasure.Palantir == true) { cout << " Palantir" << endl; } if (Treasure.PalePearl == true) { cout << " Pale Pearl" << endl; } if (Treasure.OpalEye == true) { cout << " Opal Eye" << endl; } if (Treasure.NornStone == true) { cout << " Norn Stone" << endl; } if (Treasure.Silmaril == true) { cout << " Silmaril" << endl; } cout << Stats.ArmorName << endl; cout << Stats.WeaponName << endl; } bool QuitGame(StatsType Stats) { char Quit; cout << endl; cout << "Do you really want to quit (Y/N)? "; cin >> Quit; cout << endl; if (Quit == 'Y' || Quit == 'y') { cout << "Maybe the dumb " << Stats.Race << " is not so dumb after all!" << endl; cout << endl; InsertBreak(); return(true); } else { cout << "Then don\'t say you do!" << endl; cout << endl; InsertBreak(); return(false); } } void PickMonster(MonsterType &Monster) { int RandNum = random(13); switch (RandNum) { case 0: { Monster.Name = "ogre"; Monster.Health = 28; Monster.Attack = 20; Monster.Defense = 14; Monster.Dex = 10; Monster.Magic = 0; Monster.Bribe = 200; break; } case 1: { Monster.Name = "wolf"; Monster.Health = 24; Monster.Attack = 18; Monster.Defense = 16; Monster.Dex = 20; Monster.Magic = 0; Monster.Bribe = 0; break; } case 2: { Monster.Name = "kobold"; Monster.Health = 22; Monster.Attack = 17; Monster.Defense = 16; Monster.Dex = 16; Monster.Magic = 16; Monster.Bribe = 100; break; } case 3: { Monster.Name = "dragon"; Monster.Health = 30; Monster.Attack = 30; Monster.Defense = 30; Monster.Dex = 12; Monster.Magic = 25; Monster.Bribe = 300; break; } case 4: { Monster.Name = "gargoyle"; Monster.Health = 25; Monster.Attack = 15; Monster.Defense = 26; Monster.Dex = 10; Monster.Magic = 20; Monster.Bribe = 200; break; } case 5: { Monster.Name = "goblin"; Monster.Health = 20; Monster.Attack = 18; Monster.Defense = 16; Monster.Dex = 16; Monster.Magic = 14; Monster.Bribe = 300; break; } case 6: { Monster.Name = "vendor"; Monster.Health = 25; Monster.Attack = 20; Monster.Defense = 20; Monster.Dex = 20; Monster.Magic = 20; Monster.Bribe = 0; break; } case 7: { Monster.Name = "lion"; Monster.Health = 24; Monster.Attack = 20; Monster.Defense = 14; Monster.Dex = 18; Monster.Magic = 0; Monster.Bribe = 0; break; } case 8: { Monster.Name = "troll"; Monster.Health = 30; Monster.Attack = 25; Monster.Defense = 20; Monster.Dex = 12; Monster.Magic = 10; Monster.Bribe = 0; break; } case 9: { Monster.Name = "bear"; Monster.Health = 25; Monster.Attack = 20; Monster.Defense = 12; Monster.Dex = 12; Monster.Magic = 0; Monster.Bribe = 0; break; } case 10: { Monster.Name = "minotaur"; Monster.Health = 30; Monster.Attack = 22; Monster.Defense = 20; Monster.Dex = 10; Monster.Magic = 0; Monster.Bribe = 0; break; } case 11: { Monster.Name = "chimera"; Monster.Health = 20; Monster.Attack = 18; Monster.Defense = 18; Monster.Dex = 16; Monster.Magic = 20; Monster.Bribe = 250; break; } case 12: { Monster.Name = "balrog"; Monster.Health = 30; Monster.Attack = 26; Monster.Defense = 20; Monster.Dex = 16; Monster.Magic = 25; Monster.Bribe = 300; break; } } } void PlayerMove(StatsType &Stats, PosType &Position, TreasureType &Treasure, MonsterType &Monster, bool &BattleContinue) { cout << "You can:" << endl; cout << " Attack" << endl; cout << " Retreat" << endl; if (Monster.Bribe > 0) { cout << " Bribe" << endl; } if ( (Stats.Magic >= 2) && (Treasure.RubyRed == true) ) { cout << " Cast a Spell" << endl; } cout << endl; char Command; do { cout << "What do you want to do? "; cin >> Command; if ( (Command != 'A') && (Command != 'a') && (Command != 'R') && (Command != 'r') && (Command != 'B') && (Command != 'b') && (Command != 'S') && (Command != 's') ) { cout << "You can\'t do that!" << endl; } } while ( (Command != 'A') && (Command != 'a') && (Command != 'R') && (Command != 'r') && (Command != 'B') && (Command != 'b') && (Command != 'S') && (Command != 's') ); if (Command == 'A' || Command == 'a') { int Damage = Stats.Attack - (Monster.Defense * 0.5); if (Damage < 1) { Damage = 1; } int HitProb = random(21) + 1; if (HitProb >= Monster.Dex) { cout << "You attacked the monster and did " << Damage << " damage." << endl; Monster.Health -= Damage; } else { cout << "You swung at the " << Monster.Name << " but missed." << endl; } } if (Command == 'R' || Command == 'r') { int EscapeProb = Monster.Dex; int Escape = random(100) + 1; if (Escape >= EscapeProb) { cout << "The " << Monster.Name << " blocked your escape!" << endl; } else { BattleContinue = false; char RunDir; do { cout << "Which way do you want to run? "; cin >> RunDir; if ( (RunDir != 'N' && RunDir != 'n') && (RunDir != 'S' && RunDir != 's') && (RunDir != 'E' && RunDir != 'e') && (RunDir != 'W' && RunDir != 'w') ) { cout << "Enter a real direction!" << endl; } } while ( (RunDir != 'N' && RunDir != 'n') && (RunDir != 'S' && RunDir != 's') && (RunDir != 'E' && RunDir != 'e') && (RunDir != 'W' && RunDir != 'w') ); cout << "You ran from battle!" << endl; } } if ( (Command == 'B' || Command == 'b') && (Monster.Bribe == 0) ) { cout << endl; cout << "You can\'t bribe this monster!" << endl; cout << endl; } if ( (Command == 'B' || Command == 'b') && (Monster.Bribe > 0) ) { char GiveBribe; cout << endl; cout << "The monster demands " << Monster.Bribe; cout << " gold pieces." << endl; cout << "Give it to him? "; cin >> GiveBribe; if (GiveBribe == 'Y' || GiveBribe == 'y') { if (Stats.Gold < Monster.Bribe) { cout << "You don\'t have that much money!" << endl; cout << "The monster is enraged that you can\'t give it the money!" << endl; } else { cout << "You wisely gave the " << Monster.Name << " the money and it became docile." << endl; Stats.Gold -= Monster.Bribe; BattleContinue = false; } } else { cout << "The monster is enraged that you would not give it the money!" << endl; } } if (Command == 'S' || Command == 's') { cout << "You can use the following spells:" << endl; if (Treasure.RubyRed == true) { cout << " Fireball" << endl; } if (Treasure.GreenGem == true) { cout << " Thunderbolt" << endl; } if ( (Stats.Magic >= 3) && (Treasure.PalePearl == true) ) { cout << " Web" << endl; } if ( (Stats.Magic >= 5) && (Treasure.Silmaril== true) ) { cout << " Heal" << endl; } if ( (Stats.Magic >= 8) && (Treasure.Palantir == true) ) { cout << " Deathspell" << endl; } char Spell; do { cout << "Which spell do you want to use? "; cin >> Spell; if ( (Spell != 'F' && Spell != 'f') && (Spell != 'T' && Spell != 't') && (Spell != 'W' && Spell != 'w') && (Spell != 'H' && Spell != 'h') && (Spell != 'D' && Spell != 'D') ) { cout << "You don\'t have that spell!" << endl; } } while ( (Spell != 'F' && Spell != 'f') && (Spell != 'T' && Spell != 't') && (Spell != 'W' && Spell != 'w') && (Spell != 'H' && Spell != 'h') && (Spell != 'D' && Spell != 'D') ); int SpellDamage = 0; bool SpellUsed = false; if ( (Spell == 'F' || Spell == 'f') && (Stats.Magic >= 2) ) { cout << "You sent a fireball from heaven onto the "; cout << Monster.Name << "!" << endl; SpellDamage = 10; cout << "You caused " << SpellDamage << " damage!" << endl; Stats.Magic -= 2; SpellUsed = true; } if ( (Spell == 'T' || Spell == 't') && (Stats.Magic >= 2) ) { cout << "You called down lightning from the sky"; int HitProb = random(10); if (HitProb == 1) { cout << ", but it missed!" << endl; SpellDamage = 0; } else { cout << " and electrified the " << Monster.Name << "!" << endl; SpellDamage = random(3) + 10; cout << "You caused " << SpellDamage << " damage!" << endl; } Stats.Magic -= 2; SpellUsed = true; } if ( (Spell == 'W' || Spell == 'w') && (Stats.Magic >= 3) ) { cout << "You shot out a web and immobilized the " << Monster.Name << "!" << endl; Monster.Immobilize = 3; Stats.Magic -= 3; SpellUsed = true; } if ( (Spell == 'H' || Spell == 'h') && (Stats.Magic >= 5) ) { cout << "You cast the Heal spell on yourself "; int HealAmount = random(3) + 4; cout << "and gained " << HealAmount << " health!" << endl; Stats.Health += HealAmount; Stats.Magic -= 5; SpellUsed = true; } if ( (Spell == 'D' || Spell == 'd') && (Stats.Magic >= 8) ) { cout << "You cast the Death spell on the " << Monster.Name; cout << " and it dropped dead at your feet!" << endl; Monster.Dead = true; Stats.Magic -= 8; SpellUsed = true; } if (SpellUsed == false) { cout << "You don\'t have enough magic!" << endl; PlayerMove(Stats, Position, Treasure, Monster, BattleContinue); } Monster.Health -= SpellDamage; } } void MonsterMove(StatsType &Stats, MonsterType &Monster) { bool GotMove = false; do { int SpellDamage = 0; int RandNum = random(100) + 1; if (RandNum <= 45) { int Damage = Monster.Attack - (Stats.Defense * 0.5); if (Damage < 1) { Damage = 1; } int HitProb = random(21) + 1; if (HitProb >= Stats.Dex) { cout << "The monster attacked you and did " << Damage << " damage!" << endl; Stats.Health -= Damage; } else { cout << "The " << Monster.Name << " swung at you, but it missed!" << endl; } GotMove = true; } if ( (RandNum > 45 && RandNum <= 65) && (Monster.Magic >= 2) ) { cout << "The " << Monster.Name << " called fire from heaven onto you!" << endl; SpellDamage = 10; cout << "It caused you " << SpellDamage << " damage!" << endl; Monster.Magic -= 2; GotMove = true; } if ( (RandNum > 65 && RandNum <= 85) && (Monster.Magic >= 2) ) { cout << "The " << Monster.Name << " called down lightning from the sky"; int HitProb = random(10); if (HitProb == 1) { cout << ", but it missed!" << endl; SpellDamage = 0; } else { cout << "!" << endl; SpellDamage = random(3) + 10; cout << "It caused " << SpellDamage << " damage!" << endl; } Monster.Magic -= 2; GotMove = true; } if ( (RandNum > 85 && RandNum <= 90) && (Monster.Magic >= 3) ) { cout << "The " << Monster.Name << " shot out a web and immobilized you!" << endl; Stats.Immobilize = 3; Monster.Magic -= 3; GotMove = true; } if ( (RandNum > 90 && RandNum <= 100) && (Monster.Magic >= 5) ) { cout << "The monster cast the Heal spell on itself "; int HealAmount = random(3) + 4; cout << "and gained " << HealAmount << " health!" << endl; Monster.Health += HealAmount; Monster.Magic -= 5; GotMove = true; } Stats.Health -= SpellDamage; } while (GotMove == false); } void Battle(StatsType &Stats, PosType &Position, TreasureType Treasure) { cout << endl; MonsterType Monster; PickMonster(Monster); bool BattleContinue = true; do { cout << endl; DispStats(Stats, Treasure); cout << "You are facing a " << Monster.Name << "!" << endl; if (Stats.Immobilize > 0) { cout << "You still can\'t move!" << endl; Stats.Immobilize--; } else { cout << endl; PlayerMove(Stats, Position, Treasure, Monster, BattleContinue); } if (Monster.Health <= 0) { Monster.Dead = true; BattleContinue = false; } if (BattleContinue == true) { if (Monster.Immobilize > 0) { cout << "The " << Monster.Name << " still can\'t move!" << endl; } else { MonsterMove(Stats, Monster); } } if (Stats.Health <= 0) { Stats.Dead = true; BattleContinue = false; } } while (BattleContinue == true); if (Monster.Dead == true) { cout << "You defeated the " << Monster.Name << "!" << endl; InsertBreak(); } if (Stats.Dead == true) { cout << "The " << Monster.Name << " has defeated you!" << endl; InsertBreak(); } } int _tmain(int argc, _TCHAR* argv[]) { randomize(); Intro(); StatsType Stats; char Race, Gender; GetStartStats(Stats, Race, Gender); Stats.WeaponName = "no weapon"; Stats.ArmorName = "no armor"; Stats.Gold = 50; StartEquip(Stats); PosType Position; Position.x = 0; Position.y = 0; Position.z = 0; FloorType Floor(8); StockCastle(Floor); // Display all floors /*for (int Counter = 0; Counter <= 7; Counter++) { for (int Counter1 = 0; Counter1 <= 7; Counter1++) { for (int Counter2 = 0; Counter2 <= 7; Counter2++) { cout << Floor[Counter].Space[Counter1][Counter2] << " "; } cout << endl; } cout << endl << endl; }*/ bool End = false; bool Quit; TreasureType Treasure; Treasure.BlueFlame = false; Treasure.GreenGem = false; Treasure.NornStone = false; Treasure.OminousGlobe = false; Treasure.OpalEye = false; Treasure.Palantir = false; Treasure.PalePearl = false; Treasure.RubyRed = false; Treasure.Silmaril = false; do { DispStats(Stats, Treasure); DispFloor(Floor, Position); char Command = GetCommand(Stats); if (Command == 'H' || Command == 'h') { Help(); } if (Command == 'N' || Command == 'n') { North(Position); } if (Command == 'S' || Command == 's') { South(Position); } if (Command == 'E' || Command == 'e') { East(Position); } if (Command == 'W' || Command == 'w') { West(Position); } if (Command == 'D' || Command == 'd') { if (Floor[Position.z].Space[Position.x][Position.y] == 'D') { Position.z--; } else { cout << endl; cout << "There are no stairs leading down from here!" << endl; cout << endl; InsertBreak(); } } if (Command == 'U' || Command == 'u') { if (Floor[Position.z].Space[Position.x][Position.y] == 'U') { Position.z++; } else { cout << endl; cout << "There\'s no way up!" << endl; cout << endl; InsertBreak(); } } if (Command == 'O' || Command == 'o') { char SpaceChar = Floor[Position.z].Space[Position.x][Position.y]; if (SpaceChar == 'C') { OpenChest(Stats, Position, Floor); } else if (SpaceChar == 'B') { OpenBook(Stats, Position, Floor); } else { cout << endl; cout << "There is nothing to open!" << endl; cout << endl; InsertBreak(); } } if (Command == 'G' || Command == 'g') { if (Floor[Position.z].Space[Position.x][Position.y] == 'O') { Gaze(Floor, Stats); } } if (Command == 'T' || Command == 't') { if (Stats.Runestaff == true) { Teleport(Position, Stats); } else { cout << endl; cout << "You can\t teleport without the Runestaff!" << endl; cout << endl; InsertBreak(); } } if (Command == 'R' || Command == 'r') { if (Floor[Position.z].Space[Position.x][Position.y] == 'P') { Drink(Stats); } } if (Command == 'Q' || Command == 'q') { Quit = QuitGame(Stats); if (Quit == true) { End = true; } } if (Floor[Position.z].Space[Position.x][Position.y] == 'M') { Battle(Stats, Position, Treasure); } if (Stats.Dead == true) { Died(Stats, Position, Treasure); InsertBreak(); End = true; } } while (End == false); return 0; }
#pragma once #include <set> #include <memory> #include <iosfwd> #include <boost/range/iterator_range.hpp> #include <bullet/btBulletDynamicsCommon.h> #include <bullet/BulletCollision/btBulletCollisionCommon.h> namespace physics { class body { public: /*! represents body shape To create box shape, type \code shape_type box = make_unique<btBoxShape>(btVector3{50, 50, 50}); \endcode */ using shape_type = std::unique_ptr<btCollisionShape>; body(shape_type && shape, btTransform && T, btScalar mass = 0); btVector3 const & position() const; // native geters btRigidBody & rigid_body() {return _body;} template <typename T> bool is_same(T * p) const {return (void *)p == &_body;} private: shape_type _shape; btDefaultMotionState _motion; btRigidBody _body; }; struct collision_listener { virtual void on_collision(btCollisionObject * a, btCollisionObject * b) {} virtual void on_separation(btCollisionObject * a, btCollisionObject * b) {} }; class world { public: using collision_range = boost::iterator_range<btCollisionObject * const *>; world(); void add_body(body * b); void remove_body(body * b); void simulate(btScalar time_step, int sub_steps = 10); collision_range collision_objects(); void subscribe_collisions(collision_listener * l); void unsubscribe_collisions(collision_listener * l); btDiscreteDynamicsWorld & native() {return _world;} private: using collision_pairs = std::set<std::pair<btCollisionObject const *, btCollisionObject const *>>; void handle_collisions(); void collision_event(btCollisionObject * a, btCollisionObject * b); void separation_event(btCollisionObject * a, btCollisionObject * b); btDefaultCollisionConfiguration _config; btCollisionDispatcher _dispatcher; btDbvtBroadphase _pair_cache; btSequentialImpulseConstraintSolver _solver; btDiscreteDynamicsWorld _world; collision_pairs _last_collisions; std::vector<collision_listener *> _collision_listeners; }; // helpers btTransform translate(btVector3 const & v); } // physics // STL support std::ostream & operator<<(std::ostream & o, btVector3 const & v);
#include "Renderer.hpp" #include "lodepng.h" #include <string> #include <iostream> using namespace std; namespace mobo { GLfloat vtxData[] = { -1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 }; GLint vtxDataSize = 12; GLfloat clrData[] = { 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0 }; GLint clrDataSize = 12; GLfloat uvData[] = { 0.0, 1.0, 1.0, 1.0, 0.5, 0.0 }; GLint uvDataSize = 6; const string vtxShaderSource( R"( #version 330 core layout(location = 0) in vec4 iVtxPos; layout(location = 1) in vec4 iVtxClr; layout(location = 2) in vec2 iVtxUV; out vec4 fVtxClr; out vec2 fVtxUV; void main() { gl_Position = iVtxPos; fVtxClr = iVtxClr; fVtxUV = iVtxUV; } )"); const string frgShaderSource( R"( #version 330 core uniform sampler2D tex; in vec4 fVtxClr; in vec2 fVtxUV; out vec4 oColor; void main() { oColor = texture(tex, fVtxUV); } )"); void Renderer::init() { glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_ALPHA_TEST); glDepthFunc(GL_LESS); glClearColor(0.0, 0.0, 0.0, 1.0); glClearDepth(1.0f); auto vtxShader = glCreateShader(GL_VERTEX_SHADER); auto frgShader = glCreateShader(GL_FRAGMENT_SHADER); const GLchar* vtxSrcPtr = vtxShaderSource.c_str(); const GLchar* frgSrcPtr = frgShaderSource.c_str(); GLint vtxSrcSize = vtxShaderSource.size(), frgSrcSize = frgShaderSource.size(); glShaderSource(vtxShader, 1, &vtxSrcPtr, &vtxSrcSize); glCompileShader(vtxShader); GLint compileStatus; glGetShaderiv(vtxShader, GL_COMPILE_STATUS, &compileStatus); if(compileStatus != GL_TRUE) { cerr << "Failed to compile vertex shader" << endl; } glShaderSource(frgShader, 1, &frgSrcPtr, &frgSrcSize); glCompileShader(frgShader); glGetShaderiv(frgShader, GL_COMPILE_STATUS, &compileStatus); if(compileStatus != GL_TRUE) { cerr << "Failed to compile fragment shader" << endl; } prog = glCreateProgram(); glAttachShader(prog, vtxShader); glAttachShader(prog, frgShader); glLinkProgram(prog); GLint linkStatus; glGetProgramiv(prog, GL_LINK_STATUS, &linkStatus); if(linkStatus != GL_TRUE) { cerr << "Failed to link program" << endl; } glDeleteShader(frgShader); glDeleteShader(vtxShader); glUseProgram(prog); glGenBuffers(3, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, vtxDataSize * sizeof(GLfloat), vtxData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, clrDataSize * sizeof(GLfloat), clrData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); glBufferData(GL_ARRAY_BUFFER, uvDataSize * sizeof(GLfloat), uvData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); string imageFilename("BearInRed.png"); unsigned imgWidth, imgHeight; vector<unsigned char> buffer; lodepng::load_file(buffer, imageFilename.c_str()); lodepng::State state; vector<unsigned char> imageBytes; lodepng::decode(imageBytes, imgWidth, imgHeight, state, buffer); glGenTextures(1, &tex); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex); // glTexStorage2D(GL_TEXTURE_2D, 0, GL_RGBA8, imgWidth, imgHeight); // NOT Available until OpenGL V4.2 // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, imgWidth, imgHeight, GL_RGBA, GL_UNSIGNED_BYTE, (void*) &(imageBytes[0])); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imgWidth, imgHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (void*) &(imageBytes[0])); glGenSamplers(1, &samp); glSamplerParameteri(samp, GL_TEXTURE_WRAP_S, GL_REPEAT); glSamplerParameteri(samp, GL_TEXTURE_WRAP_T, GL_REPEAT); glSamplerParameteri(samp, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glSamplerParameteri(samp, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glSamplerParameterf(samp, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0f); /* auto info = state.info_png; auto color = info.color; cout << "Image width: " << imgWidth << endl; cout << "Image height: " << imgHeight << endl; cout << "Bit depth: " << color.bitdepth << endl; cout << "Bits per pixel: " << lodepng_get_bpp(&color) << endl; cout << "Channels per pixel: " << lodepng_get_channels(&color) << endl; cout << "Can have alpha: " << lodepng_can_have_alpha(&color) << endl; */ glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, 0); } Renderer::~Renderer() { if(prog) glDeleteProgram(prog); } void Renderer::didReshape(int w, int h) { glViewport(0, 0, w, h); } void Renderer::render() { glUseProgram(prog); GLint texLoc = glGetUniformLocation(prog, "tex"); glUniform1i(texLoc, 0); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex); glBindSampler(0, samp); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 3); glBindSampler(0, 0); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glFinish(); glutSwapBuffers(); } float Renderer::calculateFrameRate() { auto newTime = steady_clock::now(); if(timestamp != time_point<steady_clock>(seconds(0))) { duration<float, micro> period(newTime - timestamp); float newFPS = seconds(1) / period; fpsAVG.push_back(newFPS); fpsWMA = fpsAVG.wma(); if(emaWindow == 0) { fpsEMA = newFPS; } else { float k = 2.0f / (emaWindow + 1.0f); fpsEMA = newFPS * k + fpsEMA * (1.0 - k); } if(emaWindow < 15) emaWindow++; } else { fpsWMA = 0.0; fpsEMA = 0.0; } timestamp = newTime; return fpsEMA; } }
#include<iostream> #include<cstdio> #include<malloc.h> using namespace std; struct Road{ int from; int to; }; int k=0; int main(){ int quicksort(Road *data,int low,int high); int find_the_height(int spot,int m,Road*road); //输入 int n,m; fscanf(stdin,"%d %d",&n,&m); Road*road=(Road*)malloc(1000100*sizeof(Road)); for(int i=0;i<m;i++){ fscanf(stdin,"%d %d",&(road[i].from),&(road[i].to)); } //找出所有没有被指向的点,也就是可以作为起点的点 int *find_origin=(int*)malloc(100100*sizeof(int)); for(int i=0;i<100100;i++){ find_origin[i]=0; } for(int i=0;i<m;i++){ int temporary=road[i].to; find_origin[temporary]=temporary; } int *origin=(int *)malloc(100100*sizeof(int)); int origin_number;//起点的个数(不含0) for(int i=1,j=0;i<=n;i++){ if(0==find_origin[i]){ origin[j++]=i; origin_number=j; } } //给路排序 quicksort(road,0,m-1); //行动 int number=0; for(int i=0;i<origin_number;i++){//一次循环,一个起点,一条路线 int temporary=find_the_height(origin[i],m,road); if(temporary>number){ number=temporary; } } //输出 fprintf(stdout,"%d",number); return 0; } int find_the_height(int spot,int m,Road*road){ int binary_search(Road *data,int low,int high, int be_searched); int length=0; int sign=9; int result=binary_search(road,0,m-1,spot); for(int i=result;i<m;i++){ if(spot==road[i].from){ int temporary=find_the_height(road[i].to,m,road); if(temporary>length){ length=temporary; } sign=10; }else{ break; } } if(9==sign){ return 1; } if(10==sign){ return length+1; } } //二分查找 int binary_search(Road *data,int low,int high ,int be_searched){ for(;low<=high;){ int middle=(low+high)>>1; if(be_searched<data[middle].from){ high=middle-1; } else if(be_searched>data[middle].from){ low=middle+1; } else{ for(;be_searched==data[middle].from;middle=middle-1); middle=middle+1; return middle; } } return 10000010; } //快速排序 int quicksort(Road *data,int low,int high){ int partition(Road *data,int low,int high); if ((high-low)<1){ return 0; } int middle=partition(data,low,high-1); quicksort(data,low,middle); quicksort(data,middle+1,high); return 0; } int partition(Road *data,int low,int high){ int backup_low=low; int backup_high=high; Road middle_data=data[low]; for(;low<high;){ for(;low<high;){ if(data[high].from>middle_data.from){ high=high-1; }else{ data[low]=data[high]; low=low+1; break; } } for(;low<high;){ if(data[low].from<middle_data.from){ low=low+1; }else{ data[high]=data[low]; high=high-1; break; } } } int middle=low; data[low]=middle_data; low=backup_low; high=backup_high; return middle; }
#include "akasztofa.h" #include <string> #include <gtest/gtest.h> TEST(AkasztofaTest, getHatra_feladvanyHossz) { std::string feladvany = "abcde"; Akasztofa a(feladvany); EXPECT_EQ(feladvany.length(), a.getHatra()) << "A feladvany hosszanak kell lennie az alapertelmezett " << "maximalis probalkozasi szamnak.\n"; } TEST(AkasztofaTest, getHatra_adottHossz) { int hossz = 10; Akasztofa a("abcde", hossz); EXPECT_EQ(hossz, a.getHatra()) << "A feladvany hosszanak " << hossz << "-nak kell lennie.\n"; } TEST(AkasztofaTest, tipp_felfedes) { Akasztofa a("aaa bb c"); EXPECT_EQ(6, a.tipp('x')) << "Hibas tippre a rejtett betuk szama nem csokkenhet.\n"; EXPECT_EQ(3, a.tipp('a')) << "Minden 'a' betut fel kellene ismernie.\n"; EXPECT_EQ(1, a.tipp('b')) << "Minden 'b' betut fel kellene ismernie.\n"; EXPECT_EQ(0, a.tipp('c')) << "Minden karakternek felfedettnek kellene lennie.\n"; } TEST(AkasztofaTest, tipp_kivetel) { Akasztofa a("a", 1); EXPECT_NO_THROW(a.tipp('a')) << "Egyet kellene tudni tippelni.\n"; EXPECT_THROW(a.tipp('b'), const char*) << "Nem lenne szabad ujabbat tippelni.\n"; } TEST(AkasztofaTest, kiiras) { Akasztofa a("aaa bb c"); testing::internal::CaptureStdout(); std::cout << a << std::endl; a.tipp('c'); std::cout << a << std::endl; a.tipp('b'); std::cout << a << std::endl; a.tipp('a'); std::cout << a << std::endl; std::string kimenet = testing::internal::GetCapturedStdout(); EXPECT_EQ("*** ** *\n*** ** c\n*** bb c\naaa bb c\n", kimenet); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "stdafx.h" #include "utils.h" #include <malloc.h> /** double the size of an array with error checking @param array pointer to an array whose size is to be doubled @param n number of elements allocated for \a array @param size size in bytes of elements in \a array @return returns the new number of elements allocated for \a array */ int array_double(void** array, int n, int size) { void* tmp; tmp = realloc(*array, 2 * n * size); if (!tmp) { fprintf(stderr, "Warning: unable to allocate memory in array_double()," " %s line %d \n", __FILE__, __LINE__); if (*array) { free(*array); } *array = NULL; return 0; } *array = tmp; return n * 2; }
#include <iostream> #include <vector> #include <Poco/Environment.h> #include <Poco/Exception.h> #include <Poco/Logger.h> #include <Poco/StringTokenizer.h> #include <Poco/Version.h> #include <Poco/Util/OptionSet.h> #include <Poco/Util/OptionCallback.h> #include <Poco/Util/HelpFormatter.h> #include "di/DependencyInjector.h" #include "di/DIApplicationConfigurationLoader.h" #include "di/DIDaemon.h" #include "loop/StoppableLoop.h" #include "util/AutoConfigurationExplorer.h" #include "util/Loggable.h" #include "util/PosixSignal.h" using namespace std; using namespace Poco; using namespace Poco::Util; using namespace BeeeOn; DIDaemon::DIDaemon(const About &about): m_about(about) { setUnixOptions(isUnix()); m_helpOption.shortName("h"); m_helpOption.fullName("help"); m_helpOption.required(false); m_helpOption.repeatable(false); m_helpOption.noArgument(); m_helpOption.callback(OptionCallback<DIDaemon>( this, &DIDaemon::handleHelp)); m_versionOption.shortName("V"); m_versionOption.fullName("version"); m_versionOption.required(false); m_versionOption.repeatable(false); m_versionOption.noArgument(); m_versionOption.callback(OptionCallback<DIDaemon>( this, &DIDaemon::handleVersion)); m_debugStartupOption.fullName("debug-startup"); m_debugStartupOption.required(false); m_debugStartupOption.repeatable(false); m_debugStartupOption.noArgument(); m_debugStartupOption.callback(OptionCallback<DIDaemon>( this, &DIDaemon::handleDebugStartup)); m_defineOption.shortName("D"); m_defineOption.fullName("define"); m_defineOption.required(false); m_defineOption.repeatable(true); m_defineOption.argument("<key>=<value>", true); m_defineOption.callback(OptionCallback<DIDaemon>( this, &DIDaemon::handleDefine)); m_configOption.shortName("c"); m_configOption.fullName("config"); m_configOption.required(false); m_configOption.repeatable(false); m_configOption.argument("<file>", true); m_configOption.callback(OptionCallback<DIDaemon>( this, &DIDaemon::handleConfig)); m_notifyStartedOption.shortName("N"); m_notifyStartedOption.fullName("notify-started"); m_notifyStartedOption.required(false); m_notifyStartedOption.repeatable(false); m_notifyStartedOption.argument("<PID>", true); m_notifyStartedOption.binding( "di.daemon.notify.started", &config()); m_noEarlyOption.shortName("E"); m_noEarlyOption.fullName("no-early"); m_noEarlyOption.required(false); m_noEarlyOption.repeatable(false); m_noEarlyOption.noArgument(); m_noEarlyOption.callback(OptionCallback<DIDaemon>( this, &DIDaemon::handleNoEarly)); } DIDaemon::~DIDaemon() { } /** * Handle all possible uncought throws and print them to stderr as * the last emergency action. */ int DIDaemon::up(int argc, char **argv, const About &about) { try { poco_throw_on_signal; DIDaemon daemon(about); return daemon.run(argc, argv); } catch (const Exception &e) { cerr << e.displayText() << endl; } catch (const exception &e) { cerr << e.what() << endl; } catch (const char *s) { cerr << s << endl; } catch (...) { cerr << "unknown failure" << endl; } return EXIT_SOFTWARE; } void DIDaemon::initialize(Application &self) { AutoConfigurationExplorer configExplorer(config()); DIApplicationConfigurationLoader configLoader(*this); configExplorer.explore(configLoader); Application::initialize(self); } int DIDaemon::main(const std::vector<std::string> &) { if (helpRequested()) { printHelp(); return EXIT_OK; } if (versionRequested()) { printVersion(); return EXIT_OK; } ErrorHandler::set(&m_errorHandler); logStartup(); testPocoCompatibility(); if (logger().debug()) { list<string> names; DIWrapperFactory::listFactories(names); for (const auto &name : names) { logger().debug("registered class " + name, __FILE__, __LINE__); } } logger().debug("creating runner " + runnerName(), __FILE__, __LINE__); try { startRunner(runnerName()); return EXIT_OK; } catch (const Exception &e) { logger().critical(e.displayText(), __FILE__, __LINE__); } catch (const exception &e) { logger().critical(e.what(), __FILE__, __LINE__); } catch (const char *s) { logger().critical(s, __FILE__, __LINE__); } catch (...) { logger().critical("unknown failure", __FILE__, __LINE__); } return EXIT_SOFTWARE; } void DIDaemon::startRunner(const string &name) { DependencyInjector di( config().createView("factory"), libraryPaths(), noEarlyRequested()); StoppableLoop::Ptr runner = di.create<StoppableLoop>(name); logger().notice("starting runner " + name, __FILE__, __LINE__); runner->start(); try { notifyStarted(); waitForTerminationRequest(); runner->stop(); } catch (...) { runner->stop(); throw; } } void DIDaemon::defineOptions(OptionSet &options) { options.addOption(m_helpOption); options.addOption(m_versionOption); options.addOption(m_debugStartupOption); options.addOption(m_defineOption); options.addOption(m_configOption); options.addOption(m_notifyStartedOption); options.addOption(m_noEarlyOption); } void DIDaemon::handleHelp(const string &, const string &) { stopOptionsProcessing(); m_helpRequested = true; } void DIDaemon::printHelp() const { HelpFormatter formatter(options()); formatter.setCommand(config().getString("application.baseName")); formatter.setUnixStyle(isUnix()); formatter.setWidth(80); formatter.setUsage("[-h] ..."); if (!m_about.description.empty()) formatter.setHeader(m_about.description); formatter.format(cout); } void DIDaemon::handleVersion(const string &, const string &) { stopOptionsProcessing(); m_versionRequested = true; } void DIDaemon::printVersion() const { cout << version() << endl; } void DIDaemon::handleDebugStartup(const string &, const string &) { Loggable::configureSimple(Logger::root(), "debug"); } void DIDaemon::handleDefine(const string &, const string &value) { size_t off = value.find("="); if (off == string::npos) { logger().debug("overriding " + value + " as empty", __FILE__, __LINE__); config().setString(value, ""); } else { const string key = value.substr(0, off); const string val = value.substr(off + 1); logger().debug("overriding " + key + " = " + val, __FILE__, __LINE__); config().setString(key, val); } } void DIDaemon::handleConfig(const string &, const string &value) { logger().debug("loading configuration: " + value, __FILE__, __LINE__); loadConfiguration(value); Path configDir(value); if (configDir.isAbsolute()) config().setString("application.configDir", configDir.parent().toString()); else config().setString("application.configDir", configDir.absolute().parent().toString()); } void DIDaemon::handleNoEarly(const string &, const string &) { logger().debug("early instances would not be created", __FILE__, __LINE__); m_noEarlyRequested = true; } bool DIDaemon::isUnix() const { #if defined(__linux__) || defined(__unix__) || defined(_POSIX_VERSION) || defined(__APPLE__) return true; #else return false; #endif } bool DIDaemon::helpRequested() const { return m_helpRequested; } bool DIDaemon::versionRequested() const { return m_versionRequested; } bool DIDaemon::noEarlyRequested() const { return m_noEarlyRequested; } vector<string> DIDaemon::libraryPaths() { StringTokenizer paths( config().getString("application.di.ldpath", ""), ":;", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); return {paths.begin(), paths.end()}; } string DIDaemon::runnerName() { return config().getString("application.di.runner", "main"); } string DIDaemon::version() const { if (m_about.version.empty()) return "unknown"; return m_about.version; } static string pocoVersion(unsigned long version = 0) { version = version == 0? Environment::libraryVersion() : version; unsigned int major = (version >> 24) & 0xff; unsigned int minor = (version >> 16) & 0xff; unsigned int alpha = (version >> 8) & 0xff; unsigned int beta = (version >> 0) & 0xff; return to_string(major) + "." + to_string(minor) + "." + to_string(alpha) + "-" + to_string(beta); } void DIDaemon::testPocoCompatibility() const { bool upgrade = false; if (Environment::libraryVersion() > POCO_VERSION) { logger().warning( "runtime Poco library is newer then built-in headers", __FILE__, __LINE__); } if (Environment::libraryVersion() < m_about.requirePocoVersion) { throw IllegalStateException("too old Poco library, required at least " + pocoVersion(m_about.requirePocoVersion)); } if (POCO_VERSION < m_about.recommendPocoVersion) { logger().warning( "Poco library headers are older then recommended", __FILE__, __LINE__); upgrade = true; } if (Environment::libraryVersion() < m_about.recommendPocoVersion) { logger().warning( "runtime Poco library is older then recommended", __FILE__, __LINE__); upgrade = true; } if (upgrade) { logger().warning("recommended to upgrade Poco library to version " + pocoVersion(m_about.recommendPocoVersion) + " or newer", __FILE__, __LINE__); } } void DIDaemon::logStartup() const { logger().notice("version " + version(), __FILE__, __LINE__); logger().notice("Poco library " + pocoVersion() + " (headers " + pocoVersion(POCO_VERSION) + ")", __FILE__, __LINE__); logger().notice("OS " + Environment::osDisplayName() + " (" + Environment::osName() + " " + Environment::osVersion() + ")", __FILE__, __LINE__); logger().notice("Machine " + Environment::osArchitecture() + " (cores: " + to_string(Environment::processorCount()) + ")", __FILE__, __LINE__); logger().debug("Node " + Environment::nodeName() + " (" + Environment::nodeId() + ")", __FILE__, __LINE__); } void DIDaemon::notifyStarted() const { int pid = config().getInt("di.daemon.notify.started", -1); if (pid < 0) return; try { PosixSignal::send(pid, "SIGTERM"); logger().debug("started, notify process " + to_string(pid), __FILE__, __LINE__); } catch (const Exception &e) { logger().log(e, __FILE__, __LINE__); } } DIDaemon::UnhandledErrorHandler::~UnhandledErrorHandler() { } void DIDaemon::UnhandledErrorHandler::exception(const Exception &e) { logger().log(e, __FILE__, __LINE__); logger().critical(e.displayText(), __FILE__, __LINE__); } void DIDaemon::UnhandledErrorHandler::exception(const std::exception &e) { logger().critical(e.what(), __FILE__, __LINE__); } void DIDaemon::UnhandledErrorHandler::exception() { logger().critical("unhandled unknown error", __FILE__, __LINE__); }
#include "proto\Request.pb.h" #include "proto\RequestOrdersStatus.pb.h" #include "proto\SignalOrdersStatus.pb.h" #include "proto\Signal.pb.h" #include "proto\SignalMT4Trade.pb.h" #include "proto\RequestExecution.pb.h" #include "SignalModule.h" #include "ZeroMqDealer.h" #include <iostream> #include <thread> class SignalModule_pimpl { /// Public methods public: /// Initialize connection settings void Init(std::string host, std::string port, std::string serverName) { this->serverName = serverName; this->host = host; this->port = port; } /// Start signal module void Start() { try { if (isStarted) Stop(); dealer.Connect(host, port, serverName); dealer.Subscribe(std::function<void(std::string)>(std::bind(&SignalModule_pimpl::HandleMessage, this, std::placeholders::_1))); isStarted = true; poller = std::thread(std::bind(&SignalModule_pimpl::PollerThread, this)); //heartbeatThread = std::thread(std::bind(&SignalModule_pimpl::HeartbeatThread, this)); } catch (std::exception &ex) { std::cout << "Error: " << ex.what(); } } /// Stop signal module void Stop() { try { if (isStarted) { isStarted = false; dealer.Close(); poller.join(); } //heartbeatThread.join(); } catch (std::exception &ex) { std::cout << "Error: " << ex.what(); } } /// Handle raw message void HandleMessage(std::string mess) { ProtoTypes::Request request; if(!request.ParseFromString(mess)) { std::cout << "Error deserialize messages" << std::endl; } switch(request.requesttype()) { case ProtoTypes::RequestType::OrderStatusRequestType: { ProtoTypes::OrdersStatusRequest statusRequest; if(!statusRequest.ParseFromString(request.content())) { std::cout << "Error deserialize OrdersStatusRequest" << std::endl; } HandleOrderStatusRequest(statusRequest); break; } case ProtoTypes::RequestType::ExecutionRequestType: { ProtoTypes::ExecutionSignal executionSignal; if(!executionSignal.ParseFromString(request.content())) { std::cout << "Error deserialize ExecutionRequest" << std::endl; } ExecutionSignal signal = ProtoToExecutionSignal(executionSignal); HandleExecutionRequest(signal); break; } // Handling other messages put here default: break; } } ///Subscribe on Order status request void SubscribeOnOrderStatusRequest(std::function<void(std::vector<int>&)> func) { statusRequestHandler = func; } ///Subscribe on Order status request void SubscribeOnExecuteSignal(std::function<void(ExecutionSignal)> func) { executionSignalHandler = func; } /// Send orders status response void SendOrdersStatusResponse(OrdersStatusResponse& response) { ProtoTypes::OrdersStatusResponse proto = OrdersStatusResponseToProto(response); auto content = proto.SerializeAsString(); SendSignal(ProtoTypes::SignalOrdersStatus, content); } /// Send trade signal void SendTradeSignal(MT4TradeSignal &tradeSignal) { ProtoTypes::MT4TradeSignal proto = MT4TradeSignalToProto(tradeSignal); auto content = proto.SerializeAsString(); SendSignal(ProtoTypes::TradeSignal, content); } ///Private methods private: ProtoTypes::MT4TradeSignal MT4TradeSignalToProto(MT4TradeSignal &tradeSignal) { ProtoTypes::MT4TradeSignal proto; proto.set_side(tradeSignal.Side == TradeSide::Buy ? ProtoTypes::TradeSide::Buy : ProtoTypes::TradeSide::Sell); proto.set_actiontype(tradeSignal.ActionType == ActionType::Open ? ProtoTypes::ActionType::Open : ProtoTypes::ActionType::Close); proto.set_datetime(tradeSignal.DateTime); proto.set_equity(tradeSignal.Equity); proto.set_balance(tradeSignal.Balance); proto.set_volume(tradeSignal.Volume); proto.set_symbol(tradeSignal.Symbol); if(tradeSignal.StopLoss != 0.0) proto.set_stoploss(tradeSignal.StopLoss); if(tradeSignal.TakeProfit != 0.0) proto.set_takeprofit(tradeSignal.TakeProfit); proto.set_login(tradeSignal.Login); proto.set_server(tradeSignal.Server); proto.set_orderid(tradeSignal.OrderID); proto.set_comment(tradeSignal.Comment); proto.set_profit(tradeSignal.Profit); proto.set_providercommission(tradeSignal.ProviderCommission); std::cout << "MT4TradeSignalToProto commission " << tradeSignal.ProviderCommission << std::endl; return proto; } ProtoTypes::OrdersStatusResponse OrdersStatusResponseToProto(OrdersStatusResponse& response) { ProtoTypes::OrdersStatusResponse proto; for(int i = 0, n = response.OrdersStatus.size(); i < n; ++i) { auto ordersStatus = proto.add_ordersstatus(); ordersStatus->set_login(response.OrdersStatus[i].Login); int size = response.OrdersStatus[i].Status.size(); for (int j = 0; j < size; j++) { auto orderStatus = ordersStatus->add_orderstatus(); orderStatus->set_orderid(response.OrdersStatus[i].Status[j].OrderID); orderStatus->set_side(response.OrdersStatus[i].Status[j].Side == TradeSide::Buy ? ProtoTypes::TradeSide::Buy : ProtoTypes::TradeSide::Sell); orderStatus->set_datetime(response.OrdersStatus[i].Status[j].DateTime); orderStatus->set_volume(response.OrdersStatus[i].Status[j].Volume); orderStatus->set_symbol(response.OrdersStatus[i].Status[j].Symbol); orderStatus->set_comment(response.OrdersStatus[i].Status[j].Comment); if(response.OrdersStatus[i].Status[j].StopLoss != 0.0) orderStatus->set_stoploss(response.OrdersStatus[i].Status[j].StopLoss); if(response.OrdersStatus[i].Status[j].TakeProfit != 0.0) orderStatus->set_takeprofit(response.OrdersStatus[i].Status[j].TakeProfit); } } for (int i = 0, n = response.OrdersStatus.size(); i < n; ++i) { int size = response.OrdersStatus[i].Status.size(); } return proto; } ExecutionSignal ProtoToExecutionSignal(ProtoTypes::ExecutionSignal signal) { ExecutionSignal executionSignal; executionSignal.comment = signal.comment(); for(int i = 0, n = signal.orders_size(); i < n; ++i) { ExecutionOrder order; order.Login = signal.orders(i).login(); order.ActionType = signal.orders(i).actiontype() == ProtoTypes::ActionType::Open ? ActionType::Open : ActionType::Close; order.TradeSide = signal.orders(i).side() == ProtoTypes::TradeSide::Buy ? TradeSide::Buy : TradeSide::Sell; order.Symbol = signal.orders(i).symbol(); order.Volume = signal.orders(i).volume(); order.Commission = signal.orders(i).commission(); if(signal.orders(i).has_orderid()) { order.OrderID = signal.orders(i).orderid(); } executionSignal.Orders.push_back(order); } return executionSignal; } void PollerThread() { dealer.Poll(); } void HeartbeatThread() { std::cout << "HeartbeatThread started" << std::endl; std::string mess("connect"); while (isStarted) { SendSignal(ProtoTypes::SignalType::ConnectSignal, mess); Sleep(100); } std::cout << "HeartbeatThread finished" << std::endl; } void SendSignal(ProtoTypes::SignalType signalType, std::string &content) { ProtoTypes::Signal signal; signal.set_type(signalType); signal.set_source(serverName); signal.set_content(content); auto mess = signal.SerializeAsString(); Send(mess); } void HandleOrderStatusRequest(ProtoTypes::OrdersStatusRequest request) { std::vector<int> logins; for(int i = 0, n = request.logins_size(); i < n; ++i) { int login = request.logins(i); logins.push_back(login); } if(statusRequestHandler) statusRequestHandler(logins); } void HandleExecutionRequest(ExecutionSignal executionSignal) { if(executionSignalHandler) executionSignalHandler(executionSignal); } void Send(std::string& mess) { dealer.Send(mess); } /// Private fields private: std::function<void(std::vector<int>&)> statusRequestHandler; std::function<void(ExecutionSignal)> executionSignalHandler; std::string serverName; std::string host; std::string port; ZeroMqDealer dealer; std::thread poller; std::thread heartbeatThread; bool isStarted = false; }; SignalModule::SignalModule() : pimpl(new SignalModule_pimpl()) {} /// Initialize connection settings void SignalModule::Init(std::string host, std::string port, std::string serverName) { pimpl->Init(host, port, serverName); } /// Start signal module void SignalModule::Start() { pimpl->Start(); } void SignalModule::Stop() { pimpl->Stop(); } /// Handle raw message void SignalModule::HandleMessage(std::string mess) { pimpl->HandleMessage(mess); } /// Subscribe on Order status request void SignalModule::SubscribeOnOrderStatusRequest(std::function<void(std::vector<int>&)> func) { pimpl->SubscribeOnOrderStatusRequest(func); } /// Subscribe on Order status request void SignalModule::SubscribeOnExecuteSignal(std::function<void(ExecutionSignal)> func) { pimpl->SubscribeOnExecuteSignal(func); } /// Send orders status response void SignalModule::SendOrdersStatusResponse(OrdersStatusResponse& response) { pimpl->SendOrdersStatusResponse(response); } /// Send trade signal void SignalModule::SendTradeSignal(MT4TradeSignal &tradeSignal) { pimpl->SendTradeSignal(tradeSignal); }
/* * In a more traditional environments, one would split into .H and .CPP files. However in Arduino, the ".ino" file * comes with certain built-in includes (such as "Arduino.h" and more) which are not automatically added to other CPP * files. So, to make things more seamless, I will be putting implementation directly into the header files, which may * look unnatural to C++ purists */ #pragma once #define TDM_SERVOS_PER_LEG 3 #define TDM_LEGS_PER_ROBOT 6 namespace tdm { /* * Describes a Leg of 3 servos */ class Leg : public ServoGroup { private: Leg(uint8_t ch1, uint8_t ch2, uint8_t ch3) : ServoGroup(TDM_SERVOS_PER_LEG, ch1, ch2, ch3) { }; public: Leg(char legName) { switch (legName) { case 'A': addChannel(31); addChannel(30); addChannel(29); break; case 'B': addChannel(27); addChannel(26); addChannel(25); break; case 'C': addChannel(23); addChannel(22); addChannel(21); break; case 'D': addChannel(13); addChannel(14); addChannel(15); break; case 'E': addChannel(9); addChannel(10); addChannel(11); break; case 'F': addChannel(5); addChannel(6); addChannel(7); break; } } }; // class Leg /* * A class for controling multiple legs. Example: (3,'A','B','C') describes a group * of 3 legs: 'A', 'B' and 'C" */ class LegGroup { private: Vector<Leg*> _items; public: LegGroup(int numargs, ...) { va_list args; va_start(args, numargs); for(int i=0; i<numargs; i++) { /* * read as int and cast to char to get around compiler bugs */ char legName = va_arg(args, int); _items.push_back(new Leg(legName)); } va_end(args); } /* * get leg at index */ Leg* getLegAtIndex(int index) { return _items[index]; } /* * set angles */ void setAngles(int degrees[][TDM_SERVOS_PER_LEG]){ for(int i=0; i < size(); i++) { _items[i]->setAngles(degrees[i]); } } /* * turn off all legs */ void turnOffAllLegs(void) { for(int i=0; i < size(); i++) { _items[i]->turnOffAllServos(); } } /* * turn off all servos at certain index. For example "turnOffAtIndex(0)" turns off * all 0-index servos in the group */ void turnOffAtIndex(int index) { for(int i=0; i < size(); i++) { _items[i]->turnOffAtIndex(index); } } /* * get the group size */ int size() { return _items.size(); } }; //class LegGroup }; //namespace
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string> > ans; if (n == 1) { vector<string> vec; vec.push_back("Q"); ans.push_back(vec); return ans; } else if (n >= 2 && n <= 3) { return ans; } vector<vector<bool> > board(n, vector<bool>(n, 0)); backtrack(0, n, board, ans); return ans; } bool isSafe(int row, int col, int n, vector<vector<bool> > &board) { for (int i=0; i<col; i++) { if (board[row][i]) { return 0; } } for (int i=row, j=col; i>=0 && j>=0; i--, j--) { if (board[i][j]) { return 0; } } for (int i=row, j=col; i<n && j>=0; i++, j--) { if (board[i][j]) { return 0; } } return 1; } void backtrack(int col, int n, vector<vector<bool> > &board, vector<vector<string> > &ans) { if (col == n) { addBoardConfig(n, board, ans); return; } for (int i=0; i<n; i++) { if (isSafe(i, col, n, board)) { board[i][col] = 1; backtrack(col + 1, n, board, ans); board[i][col] = 0; } } } void addBoardConfig(int n, vector<vector<bool> > &board, vector<vector<string> > &ans) { vector<string> vec; for (int i=0; i<n; i++) { string s = ""; for (int j=0; j<n; j++) { if (board[i][j]) { s += "Q"; } else { s += "."; } } vec.push_back(s); } ans.push_back(vec); } };
#include "server.h" Server::Server() { } Server::Server(unsigned short int port) { this->isMessage = false; this->port = port; this->listeningSocketDescriptor = -1; this->maxSocketDescriptor = 0; FD_ZERO(&(this->socketsDescriptors)); } bool Server::createListeningSocket() { if((this->listeningSocketDescriptor = socket(AF_INET, SOCK_STREAM, 0)) == -1) return false; FD_SET(this->listeningSocketDescriptor, &(this->socketsDescriptors)); this->maxSocketDescriptor = this->listeningSocketDescriptor; return true; } bool Server::bindListeningSocketToPort() { this->serverAddress.sin_family = AF_INET; this->serverAddress.sin_port = htons(this->port); this->serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); memset(&(this->serverAddress.sin_zero), '\0', 8); if(bind(this->listeningSocketDescriptor, (struct sockaddr *) &(this->serverAddress), sizeof(struct sockaddr)) == -1) { char yes = '1'; if(setsockopt(this->listeningSocketDescriptor, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) return false; return true; } return true; } bool Server::startListening() { if(listen(this->listeningSocketDescriptor, 10) == -1) return false; return true; } int Server::acceptPendingConnection() { int newUserDescriptor, addressLength; addressLength = sizeof(struct sockaddr_in); if((newUserDescriptor = accept(this->listeningSocketDescriptor, (struct sockaddr *) &(this->newClientAddress), &addressLength)) == -1) return -1; return newUserDescriptor; } void Server::closeListeningSocket() { closesocket(this->listeningSocketDescriptor); } void Server::closeSocket(int descriptor) { closesocket(descriptor); } int Server::getListeningSocketDescriptor() { return this->listeningSocketDescriptor; } fd_set Server::getSocketsDescriptors() { return this->socketsDescriptors; } int Server::getMaxSocketDescriptor() { return this->maxSocketDescriptor; } void Server::addSocketDescriptor(int newSocketDescriptor) { FD_SET(newSocketDescriptor, &(this->socketsDescriptors)); if(newSocketDescriptor > this->maxSocketDescriptor) this->maxSocketDescriptor = newSocketDescriptor; } void Server::deleteSocketDescriptor(int uselessSocketsDescriptor) { FD_CLR(uselessSocketsDescriptor, &(this->socketsDescriptors)); if(this->socketsDescriptors.fd_count > 0) { this->maxSocketDescriptor = this->socketsDescriptors.fd_array[0]; for(int i = 1; i < this->socketsDescriptors.fd_count; i++) if((int) this->socketsDescriptors.fd_array[i] > this->maxSocketDescriptor) this->maxSocketDescriptor = (int) this->socketsDescriptors.fd_array[i]; } else this->maxSocketDescriptor = 0; } int Server::isSocketSet(int socketDescriptor, fd_set *socketsDescriptors) { return FD_ISSET(socketDescriptor, socketsDescriptors); } void Server::checkReadableSockets(fd_set *socektsDescriptors) { select(this->maxSocketDescriptor, socektsDescriptors, NULL, NULL, NULL); } int Server::readMessage(int descriptor) { if(!this->isMessage) this->tmpBuffer.clear(); this->isMessage = true; char buffer[256] = {0}; int numberOfBytes; numberOfBytes = recv(descriptor, buffer, sizeof(buffer), 0); this->tmpBuffer.append(buffer); if(this->tmpBuffer.endsWith("\r\n")) this->isMessage = false; return numberOfBytes; } void Server::sendMessage(QString message, int descriptor) { send(descriptor, message.toLocal8Bit().data(), message.length(), 0); } QString Server::getMessage() { return this->tmpBuffer; } bool Server::getIsMessage() { return this->isMessage; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/container/F14Map.h> #include <glog/logging.h> #include <set> #include <quic/codec/Types.h> namespace quic { constexpr uint8_t kDefaultPriorityLevels = kDefaultMaxPriority + 1; constexpr uint8_t kDefaultPriorityLevelsSize = 2 * kDefaultPriorityLevels; using OrderId = uint64_t; struct OrderedStream { StreamId streamId; OrderId orderId; OrderedStream(StreamId s, OrderId o) : streamId(s), orderId(o) {} }; struct ordered_stream_cmp { bool operator()(OrderedStream lhs, OrderedStream rhs) const { return (lhs.orderId == rhs.orderId) ? lhs.streamId < rhs.streamId : lhs.orderId < rhs.orderId; } }; using OrderedStreamSet = std::set<OrderedStream, ordered_stream_cmp>; /** * Priority is expressed as a level [0,7] and an incremental flag. */ struct Priority { uint8_t level : 3; bool incremental : 1; OrderId orderId : 58; Priority(uint8_t l, bool i, OrderId o = 0) : level(l), incremental(i), orderId(o) {} bool operator==(Priority other) const noexcept { return level == other.level && incremental == other.incremental && orderId == other.orderId; } }; extern const Priority kDefaultPriority; /** * Priority queue for Quic streams. It represents each level/incremental bucket * as an entry in a vector. Each entry holds a set of streams (sorted by * stream ID, ascending). There is also a map of all streams currently in the * queue, mapping from ID -> bucket index. The interface is almost identical * to std::set (insert, erase, count, clear), except that insert takes an * optional priority parameter. */ struct PriorityQueue { struct Level { class Iterator { protected: const Level& level; public: explicit Iterator(const Level& inLevel, uint64_t maxNexts) : level(inLevel), maxNextsPerStream(maxNexts), nextStreamIt(level.streams.end()) {} virtual ~Iterator() = default; virtual void begin() const = 0; virtual bool end() const = 0; virtual StreamId current() const { return nextStreamIt->streamId; } virtual void next(bool force = false) = 0; virtual void override(OrderedStreamSet::const_iterator it) { nextStreamIt = it; } mutable uint64_t nextsSoFar{0}; uint64_t maxNextsPerStream{1}; mutable OrderedStreamSet::const_iterator nextStreamIt; }; class IncrementalIterator : public Iterator { private: mutable OrderedStreamSet::const_iterator startStreamIt; public: explicit IncrementalIterator(const Level& inLevel, uint64_t maxNexts) : Iterator(inLevel, maxNexts), startStreamIt(level.streams.end()) {} void begin() const override { if (nextStreamIt == level.streams.end()) { nextStreamIt = level.streams.begin(); } startStreamIt = nextStreamIt; } bool end() const override { return nextStreamIt == startStreamIt; } // force will ignore the max nexts and always moves to the next stream. void next(bool force) override { CHECK(!level.empty()); if (!force && ++nextsSoFar < maxNextsPerStream) { return; } nextStreamIt++; if (nextStreamIt == level.streams.end()) { nextStreamIt = level.streams.begin(); } nextsSoFar = 0; } }; class SequentialIterator : public Iterator { public: explicit SequentialIterator(const Level& inLevel, uint64_t maxNexts) : Iterator(inLevel, maxNexts) {} void begin() const override { nextStreamIt = level.streams.begin(); } bool end() const override { return nextStreamIt == level.streams.end(); } void next(bool) override { CHECK(!level.empty()); nextStreamIt++; } }; OrderedStreamSet streams; bool incremental{false}; std::unique_ptr<Iterator> iterator; FOLLY_NODISCARD bool empty() const { return streams.empty(); } FOLLY_NODISCARD OrderedStream getOrderedStream(StreamId id) const { auto it = streamToOrderId.find(id); if (it == streamToOrderId.end()) { return OrderedStream(id, 0); } return OrderedStream(id, it->second); } bool insert(StreamId streamId, OrderId orderId) { if (orderId > 0) { streamToOrderId[streamId] = orderId; } return streams.insert(OrderedStream(streamId, orderId)).second; } OrderedStreamSet::const_iterator erase( OrderedStreamSet::const_iterator it) { streamToOrderId.erase(it->streamId); return streams.erase(it); } private: folly::F14FastMap<StreamId, OrderId> streamToOrderId; }; std::vector<Level> levels; using LevelItr = decltype(levels)::const_iterator; // This controls how many times next() needs to be called before moving // onto the next stream. uint64_t maxNextsPerStream{1}; void setMaxNextsPerStream(uint64_t maxNexts) { maxNextsPerStream = maxNexts; for (auto& l : levels) { l.iterator->maxNextsPerStream = maxNexts; } } PriorityQueue() : levels(kDefaultPriorityLevelsSize) { for (size_t index = 0; index < levels.size(); index++) { if (index % 2 == 1) { levels[index].incremental = true; levels[index].iterator = std::make_unique<Level::IncrementalIterator>( levels[index], maxNextsPerStream); } else { levels[index].iterator = std::make_unique<Level::SequentialIterator>( levels[index], maxNextsPerStream); } } } static uint8_t priority2index(Priority pri) { uint8_t index = pri.level * 2 + uint8_t(pri.incremental); DCHECK_LT(index, kDefaultPriorityLevelsSize) << "Logic error: level=" << pri.level << " incremental=" << pri.incremental; return index; } /** * Update stream priority if the stream already exist in the PriorityQueue * * This is a no-op if the stream doesn't exist, or its priority is the same as * the input. */ void updateIfExist(StreamId id, Priority priority) { auto iter = writableStreamsToLevel_.find(id); if (iter != writableStreamsToLevel_.end()) { updateExistingStreamPriority(iter, priority); } } void insertOrUpdate(StreamId id, Priority pri) { auto it = writableStreamsToLevel_.find(id); auto index = priority2index(pri); if (it != writableStreamsToLevel_.end()) { updateExistingStreamPriority(it, pri); } else { writableStreamsToLevel_.emplace(id, index); auto res = levels[index].insert(id, pri.orderId); DCHECK(res) << "PriorityQueue inconsistent: stream=" << id << " already at level=" << index; } } void erase(StreamId id) { auto it = writableStreamsToLevel_.find(id); if (it != writableStreamsToLevel_.end()) { eraseFromLevel(it->second, it->first); writableStreamsToLevel_.erase(it); } } // Only used for testing void clear() { writableStreamsToLevel_.clear(); for (auto& level : levels) { level.streams.clear(); level.iterator->nextStreamIt = level.streams.end(); } } FOLLY_NODISCARD size_t count(StreamId id) const { return writableStreamsToLevel_.count(id); } FOLLY_NODISCARD bool empty() const { return writableStreamsToLevel_.empty(); } // Testing helper to override scheduling state void setNextScheduledStream(StreamId id) { auto it = writableStreamsToLevel_.find(id); CHECK(it != writableStreamsToLevel_.end()); auto& level = levels[it->second]; const auto& stream = level.getOrderedStream(id); auto streamIt = level.streams.find(stream); CHECK(streamIt != level.streams.end()); level.iterator->override(streamIt); } // Only used for testing void prepareIterator(Priority pri) { auto& level = levels[priority2index(pri)]; level.iterator->begin(); } // Only used for testing FOLLY_NODISCARD StreamId getNextScheduledStream(Priority pri) const { auto& level = levels[priority2index(pri)]; if (!level.incremental || level.iterator->nextStreamIt == level.streams.end()) { CHECK(!level.streams.empty()); return level.streams.begin()->streamId; } return level.iterator->nextStreamIt->streamId; } FOLLY_NODISCARD StreamId getNextScheduledStream() const { const auto& levelIter = std::find_if(levels.cbegin(), levels.cend(), [&](const auto& level) { return !level.empty(); }); // The expectation is that calling this function on an empty queue is // a bug. CHECK(levelIter != levels.cend()); levelIter->iterator->begin(); return levelIter->iterator->current(); } private: folly::F14FastMap<StreamId, uint8_t> writableStreamsToLevel_; using WSIterator = decltype(writableStreamsToLevel_)::iterator; void eraseFromLevel(uint8_t levelIndex, StreamId id) { auto& level = levels[levelIndex]; const auto& stream = level.getOrderedStream(id); auto streamIt = level.streams.find(stream); if (streamIt == level.streams.end()) { LOG(DFATAL) << "Stream=" << levelIndex << " not found in PriorityQueue level=" << id; return; } if (streamIt == level.iterator->nextStreamIt) { level.iterator->nextStreamIt = level.streams.erase(streamIt); level.iterator->nextsSoFar = 0; } else { level.streams.erase(streamIt); } } void updateExistingStreamPriority(WSIterator it, Priority pri) { CHECK(it != writableStreamsToLevel_.end()); auto index = priority2index(pri); if (it->second == index) { // same priority, doesn't need changing return; } VLOG(4) << "Updating priority of stream=" << it->first << " from " << it->second << " to " << index; eraseFromLevel(it->second, it->first); it->second = index; auto res = levels[index].insert(it->first, pri.orderId); DCHECK(res) << "PriorityQueue inconsistent: stream=" << it->first << " already at level=" << index; } }; } // namespace quic
class CZ_750_S1_ACR; class CZ750_DZ: CZ_750_S1_ACR { displayName = $STR_DZ_WPN_CZ750_NAME; descriptionShort = $STR_DZ_WPN_CZ750_DESC; magazines[] = {"10Rnd_762x51_CZ750"}; };
#include "mailRefList.h" #include <fstream> #include <string> #include <iomanip> using namespace std; void initialize(tMailRefList &refList) { refList.counter = 0; } void load(tMailRefList &refList, ifstream &file) { file >> refList.counter; for (int i = 0; i < refList.counter; i++) { file >> refList.references[i].id; file >> refList.references[i].read; } } void save(const tMailRefList &refList, ofstream &file) { file << refList.counter << endl; for (int i = 0; i < refList.counter; i++) { file << refList.references[i].id << setw(8) << right << noboolalpha << refList.references[i].read << endl; } } bool insertRef(tMailRefList &refList, tMailRef ref) { bool inserted; if (refList.counter < Max_Ref) //If there is enough space in the list { refList.references[refList.counter] = ref; refList.counter++; inserted = true; } else inserted = false; return inserted; } bool deleteRef(tMailRefList &refList, string id) { bool deleted = false; int pos; pos = find(refList, id); if (pos != -1) //If found, delete it and move all references one position to the left. { refList.references[pos].id = ""; refList.references[pos].read = false; for (int i = pos; i < refList.counter - 1; i++) { refList.references[i] = refList.references[i + 1]; } refList.counter--; deleted = true; } return deleted; } bool readMail(tMailRefList &refList, string id) { bool read = false; int pos; pos = find(refList, id); if (pos != -1) //If the mail has been found { refList.references[pos].read = true; //Mark reference as read read = true; } return read; } int find(const tMailRefList &refList, string id) { int pos = 0; bool found = false; while ((pos < refList.counter) && !found) // While not at the end and not found { if (refList.references[pos].id == id) found = true; else pos++; } if (!found) pos = -1; return pos; } // Main program to test MailListRef module //int main() { // tMailRef mailref; // tMailRefList mailbox; // ifstream inFile; // ofstream outFile; // int pos; // // initialize(mailbox); // inFile.open("mailbox.txt"); // if (inFile.is_open()) // { // load(mailbox, inFile); // inFile.close(); // pos = find(mailbox, "javi@fdimail.com_1426614381"); // if (pos == -1) // { // cout << "Mail with id javi@fdimail.com_1426614381 NOT found!" << endl; // } // else // { // cout << "Mail with id javi@fdimail.com_1426614381 found in position " << pos << endl; // } // deleteRef(mailbox, "javi@fdimail.com_1426614381"); // pos = find(mailbox, "javi@fdimail.com_1426614381"); // if (pos == -1) // { // cout << "Mail with id javi@fdimail.com_1426614381 NOT found!" << endl; // } // else // { // cout << "Mail with id javi@fdimail.com_1426614381 found in position " << pos << endl; // } // readMail(mailbox, "luis@fdimail.com_1426607318"); // mailref.id = "javi@fdimail.com_1426614381"; // mailref.read = false; // insertRef(mailbox, mailref); // outFile.open("mailbox.txt"); // save(mailbox, outFile); // outFile.close(); // } // else // { // cout << "File not found!" << endl; // } // // system("pause"); // return 0; //}
/* * @lc app=leetcode.cn id=355 lang=cpp * * [355] 设计推特 */ // @lc code=start #include<iostream> #include<vector> #include<set> #include<algorithm> #include<queue> #include<map> using namespace std; class Twitter { static int timestamp; struct Tweet{ int id; int time; Tweet *next; Tweet(int id, int time){ this->id = id; this->time = time; this->next = NULL; } }; struct User{ int id; set<int> followed; Tweet* head; User(int userId) { this->id = userId; this->head = NULL; follow(id); } void follow(int userId){ followed.insert(userId); } void unfollow(int userId){ if(userId!=this->id){ followed.erase(userId); } } void post(int tweetId){ Tweet* twt = new Tweet(tweetId, timestamp); timestamp++; twt->next = head; head = twt; } }; map<int, User> userMap; public: /** Initialize your data structure here. */ Twitter() { } /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { if(userMap.find(userId)==userMap.end()) { userMap[userId] = User(userId); } User &u = userMap[userId]; u.post(tweetId); } static bool cmp(Tweet* a, Tweet* b){ return b->time > a->time; } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ vector<int> getNewsFeed(int userId) { vector<int> res; if(userMap.find(userId)==userMap.end())return res; set<int> users = userMap[userId].followed; priority_queue<Tweet*,vector<Tweet*>, cmp() > pq; for(auto it=users.begin();it!=users.end();it++){ Tweet* twt = userMap[*it].head; if(twt==NULL)continue; pq.push(twt); } while (!pq.empty()) { if(res.size()==10)break; Tweet *twt = pq.top(); pq.pop(); res.push_back(twt->id); if(twt->next!=NULL) { pq.push(twt->next); } } return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { if(userMap.find(followerId)==userMap.end()){ userMap[followerId] = User(followerId); } if(userMap.find(followeeId) == userMap.end()){ userMap[followeeId] = User(followeeId); } User &u = userMap[followerId]; u.follow(followeeId); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { if(userMap.find(followerId)==userMap.end()){ User &flwer = userMap[followerId]; flwer.unfollow(followeeId); } } }; /** * Your Twitter object will be instantiated and called as such: * Twitter* obj = new Twitter(); * obj->postTweet(userId,tweetId); * vector<int> param_2 = obj->getNewsFeed(userId); * obj->follow(followerId,followeeId); * obj->unfollow(followerId,followeeId); */ // @lc code=end
/*** File system class. ***/ /** Version 2 + modifications for functional model. **/ #include "r2/src/common.hh" using namespace r2; /** Included files. **/ #include "filesystem.hpp" #include "RPCServer.hpp" extern RPCServer *server; bool Dotx = true; uint64_t TxLocalBegin() { if (!Dotx) return 0; return server->getTxManagerInstance()->TxLocalBegin(); } void TxWriteData(uint64_t TxID, uint64_t address, uint64_t size) { if (!Dotx) return; server->getTxManagerInstance()->TxWriteData(TxID, address, size); } uint64_t getTxWriteDataAddress(uint64_t TxID) { if (!Dotx) return 0; return server->getTxManagerInstance()->getTxWriteDataAddress(TxID); } void TxLocalCommit(uint64_t TxID, bool action) { if (!Dotx) return; server->getTxManagerInstance()->TxLocalCommit(TxID, action); } uint64_t TxDistributedBegin() { if (!Dotx) return 0; return server->getTxManagerInstance()->TxDistributedBegin(); } void TxDistributedPrepare(uint64_t TxID, bool action) { if (!Dotx) return; server->getTxManagerInstance()->TxDistributedPrepare(TxID, action); } void TxDistributedCommit(uint64_t TxID, bool action) { if (!Dotx) return; server->getTxManagerInstance()->TxDistributedCommit(TxID, action); } void FileSystem::updateRemoteMeta(uint16_t parentNodeID, DirectoryMeta *meta, uint64_t parentMetaAddress, uint64_t parentHashAddress) { Debug::debugTitle("updateRemoteMeta"); /* Prepare imm data. */ uint32_t imm, temp; /* | 12b | 20b | +-------+------------+ | 0XFFF | HashAdress | +-------+------------+ */ temp = 0XFFF; imm = (temp << 20); imm += (uint32_t)parentHashAddress; /* Remote write with imm. */ uint64_t SendBuffer; server->getMemoryManagerInstance()->getServerSendAddress(parentNodeID, &SendBuffer); uint64_t RemoteBuffer = parentMetaAddress; Debug::debugItem("imm = %x, SendBuffer = %lx, RemoteBuffer = %lx", imm, SendBuffer, RemoteBuffer); if (parentNodeID == server->getRdmaSocketInstance()->getNodeID()) { memcpy((void *)(RemoteBuffer + server->getMemoryManagerInstance()->getDmfsBaseAddress()), (void *)meta, sizeof(DirectoryMeta)); //unlockWriteHashItem(0, parentNodeID, parentHashAddress); return; } uint64_t size = sizeof(DirectoryMeta) - sizeof(DirectoryMetaTuple) * (MAX_DIRECTORY_COUNT - meta->count); memcpy((void *)SendBuffer, (void *)meta, size); server->getRdmaSocketInstance()->RdmaWrite(parentNodeID, SendBuffer, RemoteBuffer, size, -1, 1); server->getRdmaSocketInstance()->RdmaRead(parentNodeID, SendBuffer, RemoteBuffer, size, 1); /* Data will be written to the remote address, and lock will be released with the assist of imm data. */ /* WRITE READ will be send after that, flushing remote data. */ } void RdmaCall(uint16_t NodeID, char *bufferSend, uint64_t lengthSend, char *bufferReceive, uint64_t lengthReceive) { server->getRPCClientInstance()->RdmaCall(NodeID, bufferSend, lengthSend, bufferReceive, lengthReceive); } /** Implemented functions. **/ /* Check if node hash is local. @param hashNode Given node hash. @return If given node hash points to local node return true, otherwise return false. */ bool FileSystem::checkLocal(NodeHash hashNode) { if (hashNode == hashLocalNode) { return true; /* Succeed. Local node. */ } else { return false; /* Succeed. Remote node. */ } } /* Get parent directory. Examples: "/parent/file" -> "/parent" return true "/file" -> "/" return true "/" -> return false @param path Path. @param parent Buffer to hold parent path. @return If succeed return true, otherwise return false. */ bool FileSystem::getParentDirectory(const char *path, char *parent) { /* Assume path is valid. */ if ((path == NULL) || (parent == NULL)) { /* Actually there is no need to check. */ return false; } else { strcpy(parent, path); /* Copy path to parent buffer. Though it is better to use strncpy later but current method is simpler. */ uint64_t lengthPath = strlen(path); /* FIXME: Might cause memory leak. */ if ((lengthPath == 1) && (path[0] == '/')) { /* Actually there is no need to check '/' if path is assumed valid. */ return false; /* Fail due to root directory has no parent. */ } else { bool resultCut = false; for (int i = lengthPath - 1; i >= 0; i--) { /* Limit in range of signed integer. */ if (path[i] == '/') { parent[i] = '\0'; /* Cut string. */ resultCut = true; break; } } if (resultCut == false) { return false; /* There is no '/' in string. It is an extra check. */ } else { if (parent[0] == '\0') { /* If format is '/path' which contains only one '/' then parent is '/'. */ parent[0] = '/'; parent[1] = '\0'; return true; /* Succeed. Parent is root directory. */ } else { return true; /* Succeed. */ } } } } } /* Get file name from path. Examples: '/parent/file' -> 'file' return true '/file' -> 'file' return true '/' -> return false @param path Path. @param name Buffer to hold file name. @return If succeed return true, otherwise return false. */ bool FileSystem::getNameFromPath(const char *path, char *name) { /* Assume path is valid. */ if ((path == NULL) || (name == NULL)) { /* Actually there is no need to check. */ return false; } else { uint64_t lengthPath = strlen(path); /* FIXME: Might cause memory leak. */ if ((lengthPath == 1) && (path[0] == '/')) { /* Actually there is no need to check '/' if path is assumed valid. */ return false; /* Fail due to root directory has no parent. */ } else { bool resultCut = false; int i; for (i = lengthPath - 1; i >= 0; i--) { /* Limit in range of signed integer. */ if (path[i] == '/') { resultCut = true; break; } } if (resultCut == false) { return false; /* There is no '/' in string. It is an extra check. */ } else { strcpy(name, &path[i + 1]); /* Copy name to name buffer. path[i] == '/'. Though it is better to use strncpy later but current method is simpler. */ return true; } } } } /* Lock hash item for write. */ uint64_t FileSystem::lockWriteHashItem(NodeHash hashNode, AddressHash hashAddress) { //NodeHash hashNode = storage->getNodeHash(hashUnique); /* Get node hash. */ //AddressHash hashAddress = hashUnique->value[0] & 0x00000000000FFFFF; /* Get address hash. */ uint64_t *value = (uint64_t *)(this->addressHashTable + hashAddress * sizeof(HashItem)); Debug::debugItem("value before write lock: %lx", *value); uint64_t ret = lock->WriteLock((uint16_t)(hashNode), (uint64_t)(sizeof(HashItem) * hashAddress)); Debug::debugItem("value after write lock, address: %lx, key: %lx", value, ret); return ret; } /* Unlock hash item. */ void FileSystem::unlockWriteHashItem(uint64_t key, NodeHash hashNode, AddressHash hashAddress) { uint64_t *value = (uint64_t *)(this->addressHashTable + hashAddress * sizeof(HashItem)); Debug::debugItem("value before write unlock: %lx", *value); lock->WriteUnlock(key, (uint16_t)(hashNode), (uint64_t)(sizeof(HashItem) * hashAddress)); Debug::debugItem("value after write unlock: %lx address = %lx", value, *value); } /* Lock hash item for read. */ uint64_t FileSystem::lockReadHashItem(NodeHash hashNode, AddressHash hashAddress) { uint64_t *value = (uint64_t *)(this->addressHashTable + hashAddress * sizeof(HashItem)); Debug::debugItem("value before read lock: %lx", *value); uint64_t ret = lock->ReadLock((uint16_t)(hashNode), (uint64_t)(sizeof(HashItem) * hashAddress)); Debug::debugItem("value after read lock, address: %lx, key: %lx", *value, ret); return ret; } /* Unlock hash item. */ void FileSystem::unlockReadHashItem(uint64_t key, NodeHash hashNode, AddressHash hashAddress) { uint64_t *value = (uint64_t *)(this->addressHashTable + hashAddress * sizeof(HashItem)); Debug::debugItem("value before read unlock: %lx", *value); lock->ReadUnlock(key, (uint16_t)(hashNode), (uint64_t)(sizeof(HashItem) * hashAddress)); Debug::debugItem("value after read unlock: %lx", *value); } /* Send message. */ bool FileSystem::sendMessage(NodeHash hashNode, void *bufferSend, uint64_t lengthSend, void *bufferReceive, uint64_t lengthReceive) { return true;//return _cmd.sendMessage((uint16_t)hashNode, (char *)bufferSend, lengthSend, (char *)bufferReceive, lengthReceive); /* Actual send message. */ } /* Parse message. */ void FileSystem::parseMessage(char *bufferRequest, char *bufferResponse) { /* No check on parameters. */ GeneralSendBuffer *bufferGeneralSend = (GeneralSendBuffer *)bufferRequest; /* Send and request. */ GeneralReceiveBuffer *bufferGeneralReceive = (GeneralReceiveBuffer *)bufferResponse; /* Receive and response. */ bufferGeneralReceive->message = MESSAGE_RESPONSE; /* Fill response message. */ switch(bufferGeneralSend->message) { case MESSAGE_ADDMETATODIRECTORY: { AddMetaToDirectorySendBuffer *bufferSend = (AddMetaToDirectorySendBuffer *)bufferGeneralSend; UpdataDirectoryMetaReceiveBuffer *bufferReceive = (UpdataDirectoryMetaReceiveBuffer *)bufferResponse; bufferReceive->result = addMetaToDirectory( bufferSend->path, bufferSend->name, bufferSend->isDirectory, &(bufferReceive->TxID), &(bufferReceive->srcBuffer), &(bufferReceive->desBuffer), &(bufferReceive->size), &(bufferReceive->key), &(bufferReceive->offset)); break; } case MESSAGE_REMOVEMETAFROMDIRECTORY: { RemoveMetaFromDirectorySendBuffer *bufferSend = (RemoveMetaFromDirectorySendBuffer *)bufferGeneralSend; UpdataDirectoryMetaReceiveBuffer *bufferReceive = (UpdataDirectoryMetaReceiveBuffer *)bufferResponse; bufferGeneralReceive->result = removeMetaFromDirectory( bufferSend->path, bufferSend->name, &(bufferReceive->TxID), &(bufferReceive->srcBuffer), &(bufferReceive->desBuffer), &(bufferReceive->size), &(bufferReceive->key), &(bufferReceive->offset)); break; } case MESSAGE_DOCOMMIT: { DoRemoteCommitSendBuffer *bufferSend = (DoRemoteCommitSendBuffer *)bufferGeneralSend; bufferGeneralReceive->result = updateDirectoryMeta( bufferSend->path, bufferSend->TxID, bufferSend->srcBuffer, bufferSend->desBuffer, bufferSend->size, bufferSend->key, bufferSend->offset); break; } case MESSAGE_MKNOD: { bufferGeneralReceive->result = mknod(bufferGeneralSend->path); break; } case MESSAGE_GETATTR: { GetAttributeReceiveBuffer *bufferReceive = (GetAttributeReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = getattr(bufferGeneralSend->path, &(bufferReceive->attribute)); break; } case MESSAGE_ACCESS: { bufferGeneralReceive->result = access(bufferGeneralSend->path); break; } case MESSAGE_MKDIR: { bufferGeneralReceive->result = mkdir(bufferGeneralSend->path); break; } case MESSAGE_READDIR: { ReadDirectoryReceiveBuffer *bufferReceive = (ReadDirectoryReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = readdir(bufferGeneralSend->path, &(bufferReceive->list)); break; } case MESSAGE_READDIRECTORYMETA: { ReadDirectoryMetaReceiveBuffer *bufferReceive = (ReadDirectoryMetaReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = readDirectoryMeta(bufferGeneralSend->path, &(bufferReceive->meta), &(bufferReceive->hashAddress), &(bufferReceive->metaAddress), &(bufferReceive->parentNodeID)); break; } case MESSAGE_EXTENTREAD: { ExtentReadSendBuffer *bufferSend = (ExtentReadSendBuffer *)bufferGeneralSend; ExtentReadReceiveBuffer *bufferReceive = (ExtentReadReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = extentRead(bufferSend->path, bufferSend->size, bufferSend->offset, &(bufferReceive->fpi), &(bufferReceive->offset), &(bufferReceive->key)); unlockReadHashItem(bufferReceive->key, (NodeHash)bufferSend->sourceNodeID, (AddressHash)(bufferReceive->offset)); break; } case MESSAGE_EXTENTWRITE: { ExtentWriteSendBuffer *bufferSend = (ExtentWriteSendBuffer *)bufferGeneralSend; ExtentWriteReceiveBuffer *bufferReceive = (ExtentWriteReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = extentWrite(bufferSend->path, bufferSend->size, bufferSend->offset, &(bufferReceive->fpi), &(bufferReceive->offset), &(bufferReceive->key)); unlockWriteHashItem(bufferReceive->key, (NodeHash)bufferSend->sourceNodeID, (AddressHash)(bufferReceive->offset)); break; } case MESSAGE_UPDATEMETA: { // UpdateMetaSendBuffer *bufferSend = // (UpdateMetaSendBuffer *)bufferGeneralSend; // bufferGeneralReceive->result = updateMeta(bufferSend->path, // &(bufferSend->metaFile), bufferSend->key); break; } case MESSAGE_EXTENTREADEND: { // ExtentReadEndSendBuffer *bufferSend = // (ExtentReadEndSendBuffer *)bufferGeneralSend; // bufferGeneralReceive->result = extentReadEnd(bufferSend->key, bufferSend->path); break; } case MESSAGE_TRUNCATE: { TruncateSendBuffer *bufferSend = (TruncateSendBuffer *)bufferGeneralSend; bufferGeneralReceive->result = truncate(bufferSend->path, bufferSend->size); break; } case MESSAGE_RMDIR: { bufferGeneralReceive->result = rmdir(bufferGeneralSend->path); break; } case MESSAGE_REMOVE: { GetAttributeReceiveBuffer *bufferReceive = (GetAttributeReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = remove(bufferGeneralSend->path, &(bufferReceive->attribute)); break; } case MESSAGE_FREEBLOCK: { BlockFreeSendBuffer *bufferSend = (BlockFreeSendBuffer *)bufferGeneralSend; bufferGeneralReceive->result = blockFree(bufferSend->startBlock, bufferSend->countBlock); break; } case MESSAGE_MKNODWITHMETA: { MakeNodeWithMetaSendBuffer *bufferSend = (MakeNodeWithMetaSendBuffer *)bufferGeneralSend; bufferGeneralReceive->result = mknodWithMeta(bufferSend->path, &(bufferSend->metaFile)); break; } case MESSAGE_RENAME: { RenameSendBuffer *bufferSend = (RenameSendBuffer *)bufferGeneralSend; bufferGeneralReceive->result = rename(bufferSend->pathOld, bufferSend->pathNew); break; } case MESSAGE_RAWWRITE: { ExtentWriteSendBuffer *bufferSend = (ExtentWriteSendBuffer *)bufferGeneralSend; ExtentWriteReceiveBuffer *bufferReceive = (ExtentWriteReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = extentWrite(bufferSend->path, bufferSend->size, bufferSend->offset, &(bufferReceive->fpi), &(bufferReceive->offset), &(bufferReceive->key)); unlockWriteHashItem(bufferReceive->key, (NodeHash)bufferSend->sourceNodeID, (AddressHash)(bufferReceive->offset)); break; } case MESSAGE_RAWREAD: { ExtentReadSendBuffer *bufferSend = (ExtentReadSendBuffer *)bufferGeneralSend; ExtentReadReceiveBuffer *bufferReceive = (ExtentReadReceiveBuffer *)bufferGeneralReceive; bufferReceive->result = extentRead(bufferSend->path, bufferSend->size, bufferSend->offset, &(bufferReceive->fpi), &(bufferReceive->offset), &(bufferReceive->key)); unlockReadHashItem(bufferReceive->key, (NodeHash)bufferSend->sourceNodeID, (AddressHash)(bufferReceive->offset)); break; } default: break; } } /* Internal add meta to directory function. Might cause overhead. No check on parameters for internal function. @param path Path of directory. @param name Name of meta. @param isDirectory Judge if it is directory. @return If succeed return true, otherwise return false. */ bool FileSystem::addMetaToDirectory(const char *path, const char *name, bool isDirectory, uint64_t *TxID, uint64_t *srcBuffer, uint64_t *desBuffer, uint64_t *size, uint64_t *key, uint64_t *offset) { Debug::debugTitle("FileSystem::addMetaToDirectory"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ uint64_t LocalTxID; if (checkLocal(hashNode) == true) { /* If local node. */ // return true; bool result; *key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ *offset = (uint64_t)hashAddress; Debug::debugItem("key = %lx, offset = %lx", *key, *offset); { Debug::debugItem("Stage 2. Check directory."); uint64_t indexDirectoryMeta; /* Meta index of directory. */ bool isDirectoryTemporary; /* Different from parameter isDirectory. */ if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectoryTemporary) == false) { /* If directory does not exist. */ result = false; /* Fail due to directory path does not exist. In future detail error information should be returned and independent access() and create() functions should be offered. */ } else { if (isDirectoryTemporary == false) { /* If not a directory. */ result = false; /* Fail due to path is not directory. */ } else { DirectoryMeta metaDirectory; if (storage->tableDirectoryMeta->get(indexDirectoryMeta, &metaDirectory) == false) { /* Get directory meta. */ result = false; /* Fail due to get directory meta error. */ } else { LocalTxID = TxLocalBegin(); metaDirectory.count++; /* Add count of names under directory. */ //printf("metaDirectory.count: %d, name len: %d\n", metaDirectory.count, (int)strlen(name)); strcpy(metaDirectory.tuple[metaDirectory.count - 1].names, name); /* Add name. */ metaDirectory.tuple[metaDirectory.count - 1].isDirectories = isDirectory; /* Add directory state. */ /* Write to log first. */ TxWriteData(LocalTxID, (uint64_t)&metaDirectory, (uint64_t)sizeof(DirectoryMeta)); *srcBuffer = getTxWriteDataAddress(LocalTxID); *size = (uint64_t)sizeof(DirectoryMeta); // printf("%s ", path); *TxID = LocalTxID; if (storage->tableDirectoryMeta->put(indexDirectoryMeta, &metaDirectory, desBuffer) == false) { /* Update directory meta. */ result = false; /* Fail due to put directory meta error. */ } else { // printf("addmeta, desBuffer = %lx, srcBuffer = %lx, size = %d\n", *desBuffer, *srcBuffer, *size); result = true; /* Succeed. */ } } } } } if (result == false) { TxLocalCommit(LocalTxID, false); } else { TxLocalCommit(LocalTxID, true); } // unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ AddMetaToDirectorySendBuffer bufferAddMetaToDirectorySend; /* Send buffer. */ bufferAddMetaToDirectorySend.message = MESSAGE_ADDMETATODIRECTORY; /* Assign message type. */ strcpy(bufferAddMetaToDirectorySend.path, path); /* Assign path. */ strcpy(bufferAddMetaToDirectorySend.name, name); /* Assign name. */ bufferAddMetaToDirectorySend.isDirectory = isDirectory; UpdataDirectoryMetaReceiveBuffer bufferGeneralReceive; RdmaCall((uint16_t)hashNode, (char *)&bufferAddMetaToDirectorySend, (uint64_t)sizeof(AddMetaToDirectorySendBuffer), (char *)&bufferGeneralReceive, (uint64_t)sizeof(UpdataDirectoryMetaReceiveBuffer)); *srcBuffer = bufferGeneralReceive.srcBuffer; *desBuffer = bufferGeneralReceive.desBuffer; *TxID = bufferGeneralReceive.TxID; *size = bufferGeneralReceive.size; *key = bufferGeneralReceive.key; *offset = bufferGeneralReceive.offset; return bufferGeneralReceive.result; } } /* Internal remove meta from directory function. Might cause overhead. No check on parameters for internal function. @param path Path of directory. @param name Name of meta. @param isDirectory Judge if it is directory. @return If succeed return true, otherwise return false. */ bool FileSystem::removeMetaFromDirectory(const char *path, const char *name, uint64_t *TxID, uint64_t *srcBuffer, uint64_t *desBuffer, uint64_t *size, uint64_t *key, uint64_t *offset) { Debug::debugTitle("FileSystem::removeMetaFromDirectory"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ uint64_t LocalTxID; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; *key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ *offset = (uint64_t)hashAddress; { Debug::debugItem("Stage 2. Check directory."); uint64_t indexDirectoryMeta; /* Meta index of directory. */ bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectory) == false) { /* If directory does not exist. */ Debug::notifyError("Directory does not exist."); result = false; /* Fail due to directory path does not exist. In future detail error information should be returned and independent access() and create() functions should be offered. */ } else { if (isDirectory == false) { /* If not a directory. */ result = false; /* Fail due to path is not directory. */ } else { DirectoryMeta metaDirectory; if (storage->tableDirectoryMeta->get(indexDirectoryMeta, &metaDirectory) == false) { /* Get directory meta. */ Debug::notifyError("Get directory meta failed."); result = false; /* Fail due to get directory meta error. */ } else { LocalTxID = TxLocalBegin(); DirectoryMeta metaModifiedDirectory; /* Buffer to save modified directory. */ bool found = false; uint64_t indexModifiedNames = 0; for (uint64_t i = 0; i < metaDirectory.count; i++) { if (strcmp(metaDirectory.tuple[i].names, name) == 0) { /* If found selected name. */ found = true; /* Mark and continue. */ } else { strcpy(metaModifiedDirectory.tuple[indexModifiedNames].names, metaDirectory.tuple[i].names); /* Copy original name to modified meta. */ metaModifiedDirectory.tuple[indexModifiedNames].isDirectories = metaDirectory.tuple[i].isDirectories; /* Add directory state. */ indexModifiedNames++; } } metaModifiedDirectory.count = indexModifiedNames; /* No need to +1. Current point to index after last one. Can be adapted to multiple removes. However it should not occur. */ if (found == false) { Debug::notifyError("Fail due to no selected name."); TxLocalCommit(LocalTxID, false); result = false; /* Fail due to no selected name. */ } else { /* Write to log first. */ TxWriteData(LocalTxID, (uint64_t)&metaModifiedDirectory, (uint64_t)sizeof(DirectoryMeta)); *srcBuffer = getTxWriteDataAddress(LocalTxID); *size = (uint64_t)sizeof(DirectoryMeta); *TxID = LocalTxID; if (storage->tableDirectoryMeta->put(indexDirectoryMeta, &metaModifiedDirectory, desBuffer) == false) { /* Update directory meta. */ result = false; /* Fail due to put directory meta error. */ } else { Debug::debugItem("Item. "); result = true; /* Succeed. */ } } } } } } if (result == false) { TxLocalCommit(LocalTxID, false); } else { TxLocalCommit(LocalTxID, true); } //unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ RemoveMetaFromDirectorySendBuffer bufferRemoveMetaFromDirectorySend; /* Send buffer. */ bufferRemoveMetaFromDirectorySend.message = MESSAGE_REMOVEMETAFROMDIRECTORY; /* Assign message type. */ strcpy(bufferRemoveMetaFromDirectorySend.path, path); /* Assign path. */ strcpy(bufferRemoveMetaFromDirectorySend.name, name); /* Assign name. */ UpdataDirectoryMetaReceiveBuffer bufferGeneralReceive; /* Receive buffer. */ RdmaCall((uint16_t)hashNode, (char *)&bufferRemoveMetaFromDirectorySend, (uint64_t)sizeof(RemoveMetaFromDirectorySendBuffer), (char *)&bufferGeneralReceive, (uint64_t)sizeof(UpdataDirectoryMetaReceiveBuffer)); *srcBuffer = bufferGeneralReceive.srcBuffer; *desBuffer = bufferGeneralReceive.desBuffer; *TxID = bufferGeneralReceive.TxID; *size = bufferGeneralReceive.size; *key = bufferGeneralReceive.key; *offset = bufferGeneralReceive.offset; return bufferGeneralReceive.result; } } bool FileSystem::updateDirectoryMeta(const char *path, uint64_t TxID, uint64_t srcBuffer, uint64_t desBuffer, uint64_t size, uint64_t key, uint64_t offset) { Debug::debugTitle("FileSystem::updateDirectoryMeta"); if (path == NULL) { return false; /* Fail due to null path. */ } else { Debug::debugItem("path = %s, TxID = %d, srcBuffer = %lx, desBuffer = %lx, size = %ld", path, TxID, srcBuffer, desBuffer, size); UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ // AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { Debug::debugItem("Stage 2. Check Local."); bool result = true; // uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ uint64_t indexDirectoryMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectory) == false) { /* If path exists. */ Debug::notifyError("The path does not exists."); result = false; /* Fail due to existence of path. */ } else { result = true; // printf("%s ", path); Debug::debugItem("update, desbuf = %lx, srcbuf = %lx, size = %d",desBuffer, srcBuffer, size); memcpy((void *)desBuffer, (void *)srcBuffer, size); Debug::debugItem("copied"); } Debug::debugItem("key = %lx, offset = %lx", key, offset); unlockWriteHashItem(key, hashNode, (AddressHash)offset); /* Unlock hash item. */ TxLocalCommit(TxID, true); if (result == false) { Debug::notifyError("DOCOMMIT With Error."); } return result; } else { DoRemoteCommitSendBuffer bufferSend; strcpy(bufferSend.path, path); bufferSend.message = MESSAGE_DOCOMMIT; bufferSend.TxID = TxID; bufferSend.srcBuffer = srcBuffer; bufferSend.desBuffer = desBuffer; bufferSend.size = size; bufferSend.key = key; bufferSend.offset = offset; GeneralReceiveBuffer bufferReceive; RdmaCall((uint16_t)hashNode, (char *)&bufferSend, (uint64_t)sizeof(DoRemoteCommitSendBuffer), (char *)&bufferReceive, (uint64_t)sizeof(GeneralReceiveBuffer)); if (bufferReceive.result == false) { Debug::notifyError("Remote Call on DOCOMMIT With Error."); } return bufferReceive.result; } } } /* Make node (file) with file meta. @param path Path of file. @param metaFile File meta. @return If succeed return true, otherwise return false. */ bool FileSystem::mknodWithMeta(const char *path, FileMeta *metaFile) { Debug::debugTitle("FileSystem::mknodWithMeta"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if ((path == NULL) || (metaFile == NULL)) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ Debug::debugItem("Stage 2. Check parent."); bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == true) { /* If path exists. */ result = false; /* Fail due to existence of path. */ } else { Debug::debugItem("Stage 3. Create file meta from old."); uint64_t indexFileMeta; metaFile->timeLastModified = time(NULL); /* Set last modified time. */ if (storage->tableFileMeta->create(&indexFileMeta, metaFile) == false) { result = false; /* Fail due to create error. */ } else { if (storage->hashtable->put(&hashUnique, indexFileMeta, false) == false) { /* false for file. */ result = false; /* Fail due to hash table put. No roll back. */ } else { result = true; } } } } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Make node. That is to create an empty file. @param path Path of file. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::mknod(const char *path) { #ifdef TRANSACTION_2PC assert(false); return mknod2pc(path); #endif #ifdef TRANSACTION_CD return mknodcd(path); #endif } bool FileSystem::mknodcd(const char *path) { Debug::debugTitle("FileSystem::mknod"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ // uint64_t DistributedTxID; uint64_t LocalTxID; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { // DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); Debug::debugItem("Stage 2. Update parent directory metadata."); char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); DirectoryMeta parentMeta; uint64_t parentHashAddress, parentMetaAddress; uint16_t parentNodeID; getParentDirectory(path, parent); getNameFromPath(path, name); if (readDirectoryMeta(parent, &parentMeta, &parentHashAddress, &parentMetaAddress, &parentNodeID) == false) { Debug::notifyError("readDirectoryMeta failed."); // TxDistributedPrepare(DistributedTxID, false); result = false; } else { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == true) { /* If path exists. */ Debug::notifyError("addMetaToDirectory failed."); // TxDistributedPrepare(DistributedTxID, false); result = false; /* Fail due to existence of path. */ } else { /* Update directory meta first. */ parentMeta.count++; /* Add count of names under directory. */ strcpy(parentMeta.tuple[parentMeta.count - 1].names, name); /* Add name. */ parentMeta.tuple[parentMeta.count - 1].isDirectories = isDirectory; /* Add directory state. */ Debug::debugItem("Stage 3. Create file meta."); uint64_t indexFileMeta; FileMeta metaFile; metaFile.timeLastModified = time(NULL); /* Set last modified time. */ metaFile.count = 0; /* Initialize count of extents as 0. */ metaFile.size = 0; //metaFile.size = 1024 * 1024 * 12; /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)&parentMeta, (uint64_t)sizeof(DirectoryMeta)); /* Receive remote prepare with (OK) */ // TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ updateRemoteMeta(parentNodeID, &parentMeta, parentMetaAddress, parentHashAddress); /* Only allocate momery, write to log first. */ if (storage->tableFileMeta->create(&indexFileMeta, &metaFile) == false) { result = false; /* Fail due to create error. */ } else { if (storage->hashtable->put(&hashUnique, indexFileMeta, false) == false) { /* false for file. */ result = false; /* Fail due to hash table put. No roll back. */ } else { result = true; } } } } free(parent); free(name); } if (result == false) { TxLocalCommit(LocalTxID, false); // TxDistributedCommit(DistributedTxID, false); } else { TxLocalCommit(LocalTxID, true); // TxDistributedCommit(DistributedTxID, true); } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } bool FileSystem::mknod2pc(const char *path) { Debug::debugTitle("FileSystem::mknod"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ uint64_t DistributedTxID; uint64_t LocalTxID; uint64_t RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); Debug::debugItem("Stage 2. Update parent directory metadata."); char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); getParentDirectory(path, parent); getNameFromPath(path, name); if (addMetaToDirectory(parent, name, false, &RemoteTxID, &srcBuffer, &desBuffer, &size, &remotekey, &offset) == false) { Debug::notifyError("addMetaToDirectory failed."); TxDistributedPrepare(DistributedTxID, false); result = false; } else { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == true) { /* If path exists. */ Debug::notifyError("addMetaToDirectory failed."); TxDistributedPrepare(DistributedTxID, false); result = false; /* Fail due to existence of path. */ } else { Debug::debugItem("Stage 3. Create file meta."); uint64_t indexFileMeta; FileMeta metaFile; metaFile.timeLastModified = time(NULL); /* Set last modified time. */ metaFile.count = 0; /* Initialize count of extents as 0. */ metaFile.size = 0; /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)&metaFile, (uint64_t)sizeof(FileMeta)); /* Receive remote prepare with (OK) */ TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ Debug::debugItem("mknod, key = %lx, offset = %lx", remotekey, offset); updateDirectoryMeta(parent, RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset); /* Only allocate momery, write to log first. */ if (storage->tableFileMeta->create(&indexFileMeta, &metaFile) == false) { result = false; /* Fail due to create error. */ } else { if (storage->hashtable->put(&hashUnique, indexFileMeta, false) == false) { /* false for file. */ result = false; /* Fail due to hash table put. No roll back. */ } else { result = true; } } } } free(parent); free(name); } if (result == false) { TxLocalCommit(LocalTxID, false); TxDistributedCommit(DistributedTxID, false); } else { TxLocalCommit(LocalTxID, true); TxDistributedCommit(DistributedTxID, true); } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Get attributes. @param path Path of file or folder. @param attribute Attribute buffer of file to get. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::getattr(const char *path, FileMeta *attribute) { Debug::debugTitle("FileSystem::getattr"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if ((path == NULL) || (attribute == NULL)) /* Judge if path and attribute buffer are valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ // return true; bool result; uint64_t key = lockReadHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexMeta; bool isDirectory; Debug::debugItem("Stage 1.1."); if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == false) { /* If path does not exist. */ Debug::debugItem("Stage 1.2."); result = false; /* Fail due to path does not exist. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == false) { /* If file meta. */ if (storage->tableFileMeta->get(indexMeta, attribute) == false) { result = false; /* Fail due to get file meta error. */ } else { Debug::debugItem("FileSystem::getattr, meta.size = %d", attribute->size); result = true; /* Succeed. */ } } else { attribute->count = MAX_FILE_EXTENT_COUNT; /* Inter meaning, representing directoiries */ result = true; } } } unlockReadHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Access. That is to judge the existence of file or folder. @param path Path of file or folder. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::access(const char *path) { Debug::debugTitle("FileSystem::access"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) /* Judge if path is valid. */ return false; /* Null path error. */ else { Debug::debugItem("Stage 2. Check access."); UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ Debug::debugItem("Stage 3."); if (checkLocal(hashNode) == true) { /* If local node. */ bool result; Debug::debugItem("Stage 4."); uint64_t key = lockReadHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to path does not exist. */ } else { result = true; /* Succeed. Do not need to check parent. */ } } unlockReadHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Make directory. @param path Path of folder. @return If operation succeeds then return true, otherwise return false. */ // bool FileSystem::mkdir(const char *path) // { // Debug::debugTitle("FileSystem::mkdir"); // Debug::debugItem("Stage 1. Entry point. Path: %s.", path); // char *parent = (char *)malloc(strlen(path) + 1); // getParentDirectory(path, parent); // nrfsfileattr attribute; // Debug::debugItem("Stage 2. Check parent."); // getattr(parent, &attribute); // char *name = (char *)malloc(strlen(path) + 1); /* Allocate buffer of parent path. Omit failure. */ // getNameFromPath(path, name); // Debug::debugItem("Stage 3. Add name."); // addMetaToDirectory(parent, name, true); // free(parent); // free(name); // return true; // } bool FileSystem::mkdir(const char *path) { #ifdef TRANSACTION_2PC return mkdir2pc(path); #endif #ifdef TRANSACTION_CD return mkdircd(path); #endif } // XD: the mkdir execution path bool FileSystem::mkdircd(const char *path) { //LOG(4) << "in mkdir cd"; Debug::debugTitle("FileSystem::mkdir"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { ASSERT(false); return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ // uint64_t DistributedTxID; uint64_t LocalTxID; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { // DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); Debug::debugItem("Stage 2. Check parent."); char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); DirectoryMeta parentMeta; uint64_t parentHashAddress, parentMetaAddress; uint16_t parentNodeID; getParentDirectory(path, parent); getNameFromPath(path, name); if (readDirectoryMeta(parent, &parentMeta, &parentHashAddress, &parentMetaAddress, &parentNodeID) == false) { // TxDistributedPrepare(DistributedTxID, false); result = false; } else { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == true) { /* If path exists. */ // TxDistributedPrepare(DistributedTxID, false); result = false; /* Fail due to existence of path. */ } else { /* Update directory meta first. */ parentMeta.count++; /* Add count of names under directory. */ strcpy(parentMeta.tuple[parentMeta.count - 1].names, name); /* Add name. */ parentMeta.tuple[parentMeta.count - 1].isDirectories = true; /* Add directory state. */ Debug::debugItem("Stage 3. Write directory meta."); uint64_t indexDirectoryMeta; DirectoryMeta metaDirectory; metaDirectory.count = 0; /* Initialize count of names as 0. */ /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)&parentMeta, (uint64_t)sizeof(DirectoryMeta)); /* Receive remote prepare with (OK) */ // TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ updateRemoteMeta(parentNodeID, &parentMeta, parentMetaAddress, parentHashAddress); if (storage->tableDirectoryMeta->create(&indexDirectoryMeta, &metaDirectory) == false) { result = false; /* Fail due to create error. */ } else { Debug::debugItem("indexDirectoryMeta = %d", indexDirectoryMeta); if (storage->hashtable->put(&hashUnique, indexDirectoryMeta, true) == false) { /* true for directory. */ result = false; /* Fail due to hash table put. No roll back. */ } else { result = true; } } } } free(parent); free(name); } if (result == false) { TxLocalCommit(LocalTxID, false); // TxDistributedCommit(DistributedTxID, false); } else { TxLocalCommit(LocalTxID, true); // TxDistributedCommit(DistributedTxID, true); } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } bool FileSystem::mkdir2pc(const char *path) { Debug::debugTitle("FileSystem::mkdir"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ uint64_t DistributedTxID; uint64_t LocalTxID; uint64_t RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); Debug::debugItem("Stage 2. Check parent."); char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); getParentDirectory(path, parent); getNameFromPath(path, name); if (addMetaToDirectory(parent, name, true, &RemoteTxID, &srcBuffer, &desBuffer, &size, &remotekey, &offset) == false) { TxDistributedPrepare(DistributedTxID, false); result = false; } else { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == true) { /* If path exists. */ TxDistributedPrepare(DistributedTxID, false); result = false; /* Fail due to existence of path. */ } else { Debug::debugItem("Stage 3. Write directory meta."); uint64_t indexDirectoryMeta; DirectoryMeta metaDirectory; metaDirectory.count = 0; /* Initialize count of names as 0. */ /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)&metaDirectory, (uint64_t)sizeof(DirectoryMeta)); /* Receive remote prepare with (OK) */ TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ Debug::debugItem("mknod, key = %lx, offset = %lx", remotekey, offset); updateDirectoryMeta(parent, RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset); if (storage->tableDirectoryMeta->create(&indexDirectoryMeta, &metaDirectory) == false) { result = false; /* Fail due to create error. */ } else { Debug::debugItem("indexDirectoryMeta = %d", indexDirectoryMeta); if (storage->hashtable->put(&hashUnique, indexDirectoryMeta, true) == false) { /* true for directory. */ result = false; /* Fail due to hash table put. No roll back. */ } else { result = true; } } } } free(parent); free(name); } if (result == false) { TxLocalCommit(LocalTxID, false); TxDistributedCommit(DistributedTxID, false); } else { TxLocalCommit(LocalTxID, true); TxDistributedCommit(DistributedTxID, true); } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Read filenames in directory. @param path Path of folder. @param list List buffer of names in directory. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::readdir(const char *path, nrfsfilelist *list) { Debug::debugTitle("FileSystem::readdir"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if ((path == NULL) || (list == NULL)) /* Judge if path and list buffer are valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockReadHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexDirectoryMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to path does not exist. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == false) { /* If file meta. */ result = false; /* Fail due to not directory. */ } else { DirectoryMeta metaDirectory; /* Copy operation of meta might cause overhead. */ if (storage->tableDirectoryMeta->get(indexDirectoryMeta, &metaDirectory) == false) { result = false; /* Fail due to get directory meta error. */ } else { list->count = metaDirectory.count; /* Assign count of names in directory. */ for (uint64_t i = 0; i < metaDirectory.count; i++) { strcpy(list->tuple[i].names, metaDirectory.tuple[i].names); if (metaDirectory.tuple[i].isDirectories == true) { list->tuple[i].isDirectories = true; /* Mode 1 for directory. */ } else { list->tuple[i].isDirectories = false; /* Mode 0 for file. */ } } result = true; /* Succeed. */ } } } } unlockReadHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Read filenames in directory. @param path Path of folder. @param list List buffer of names in directory. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::recursivereaddir(const char *path, int depth) { if (path == NULL) /* Judge if path and list buffer are valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ bool result; { uint64_t indexDirectoryMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to path does not exist. */ } else { if (isDirectory == false) { /* If file meta. */ result = false; /* Fail due to not directory. */ } else { DirectoryMeta metaDirectory; /* Copy operation of meta might cause overhead. */ if (storage->tableDirectoryMeta->get(indexDirectoryMeta, &metaDirectory) == false) { result = false; /* Fail due to get directory meta error. */ } else { for (uint64_t i = 0; i < metaDirectory.count; i++) { for (int nn = 0; nn < depth; nn++) printf("\t"); if (metaDirectory.tuple[i].isDirectories == true) { printf("%d DIR %s\n", (int)i, metaDirectory.tuple[i].names); char *childPath = (char *)malloc(sizeof(char) * (strlen(path) + strlen(metaDirectory.tuple[i].names) + 2)); strcpy(childPath, path); if (strcmp(childPath, "/") != 0) strcat(childPath, "/"); strcat(childPath, metaDirectory.tuple[i].names); recursivereaddir(childPath, depth + 1); free(childPath); } else { printf("%d FILE %s\n", (int)i, metaDirectory.tuple[i].names); } } result = true; /* Succeed. */ } } } } return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Read directory meta. @param path Path of folder. @param meta directory meta pointer. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::readDirectoryMeta(const char *path, DirectoryMeta *meta, uint64_t *hashAddress, uint64_t *metaAddress, uint16_t *parentNodeID) { Debug::debugTitle("FileSystem::readDirectoryMeta"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) /* Judge if path and list buffer are valid. */ return false; /* Null parameter error. */ else { bool result; UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ *hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ *parentNodeID = (uint16_t)hashNode; if (checkLocal(hashNode) == true) { /* If local node. */ uint64_t key = lockReadHashItem(hashNode, *hashAddress); /* Lock hash item. */ { uint64_t indexDirectoryMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectory) == false) { /* If path does not exist. */ Debug::notifyError("path does not exist"); result = false; /* Fail due to path does not exist. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == false) { /* If file meta. */ Debug::notifyError("Not a directory"); result = false; /* Fail due to not directory. */ } else { if (storage->tableDirectoryMeta->get(indexDirectoryMeta, meta, metaAddress) == false) { Debug::notifyError("Fail due to get directory meta error."); result = false; /* Fail due to get directory meta error. */ } else { Debug::debugItem("metaAddress = %lx, getDmfsBaseAddress = %lx", *metaAddress, server->getMemoryManagerInstance()->getDmfsBaseAddress()); *metaAddress = *metaAddress - server->getMemoryManagerInstance()->getDmfsBaseAddress(); result = true; /* Succeed. */ } } } } unlockReadHashItem(key, hashNode, *hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ GeneralSendBuffer bufferSend; bufferSend.message = MESSAGE_READDIRECTORYMETA; strcpy(bufferSend.path, path); ReadDirectoryMetaReceiveBuffer bufferReceive; RdmaCall((uint16_t)hashNode, (char *)&bufferSend, (uint64_t)sizeof(GeneralSendBuffer), (char *)&bufferReceive, (uint64_t)sizeof(ReadDirectoryMetaReceiveBuffer)); if (bufferReceive.result == false) { Debug::notifyError("Remote Call readDirectoryMeta failed"); result = false; } else { memcpy((void *)meta, (void *)&(bufferReceive.meta), sizeof(DirectoryMeta)); *hashAddress = bufferReceive.hashAddress; *metaAddress = bufferReceive.metaAddress; *parentNodeID = bufferReceive.parentNodeID; return bufferReceive.result; } return false; } } } /*There are 2 schemas of blocks. * * Schema 1, only one block: ("[" means start byte and "]" means end byte.) * * Bound of Block + start_block = end_block * Index | * -------------------+----------------------------------------+-------------------- * | | * Previous Blocks | Start Block (End Block) | Following Blocks * | | * -------------------+-------[-----------------------]--------+-------------------- * | | * Relative Address + offset + offset + size - 1 * in File \ / * ------- size ------- * * Schema 2, several blocks: * * Bound of Block + start_block + end_block * Index | | * -------------------+---------------+-------------------------------------+-------------+-------------------- * | | Middle Blocks | | * Previous Blocks | Start Block +-----+-----+---------+-----+---------+ End Block | Following Blocks * | | 0 | 1 | ... | i | ... | | * -------------------+----[----------[-----+-----+---------[-----+---------+---------]---+-------------------- * | | | | * start_block * BLOCK_SIZE + + (start_block + 1) + (start_block + 1 + i) + start_block * BLOCK_SIZE * + offset % BLOCK_SIZE \ * BLOCK_SIZE * BLOCK_SIZE / + offset % BLOCK_SIZE + size - 1 * ------------------------ size -------------------------- * * +----------------------------------------------------------+ * | | * | Buffer | * | | * [----------[-----+-----+---------[-----+---------[---------] * | | | | ... | | ... | | * + 0 | + + | + | + size - 1 * | | | * | | + BLOCK_SIZE - offset % BLOCK_SIZE + (end_block - start_block - 1) * BLOCK_SIZE * | | * | + BLOCK_SIZE - offset % BLOCK_SIZE + i * BLOCK_SIZE * | * + BLOCK_SIZE - offset % BLOCK_SIZE * * start_block = offset / BLOCK_SIZE * end_block = (offset + size - 1) / BLOCK_SIZE */ /* Fill file position information for read and write. No check on parameters. @param size Size to operate. @param offset Offset to operate. @param fpi File position information. @param metaFile File meta. */ /* FIXME: review logic here. */ void FileSystem::fillFilePositionInformation(uint64_t size, uint64_t offset, file_pos_info *fpi, FileMeta *metaFile) { Debug::debugItem("Stage 8."); uint64_t offsetStart, offsetEnd; offsetStart = offset; /* Relative offset of start byte to operate in file. */ offsetEnd = size + offset - 1; /* Relative offset of end byte to operate in file. */ uint64_t boundStartExtent, boundEndExtent, /* Bound of start extent and end extent. */ offsetInStartExtent, offsetInEndExtent, /* Offset of start byte in start extent and end byte in end extent. */ sizeInStartExtent, sizeInEndExtent; /* Size to operate in start extent and end extent. */ uint64_t offsetStartOfCurrentExtent = 0; /* Relative offset of start byte in current extent. */ Debug::debugItem("Stage 9."); for (uint64_t i = 0; i < metaFile->count; i++) { if ((offsetStartOfCurrentExtent + metaFile->tuple[i].countExtentBlock * BLOCK_SIZE - 1) >= offsetStart) { /* A -1 is needed to locate offset of end byte in current extent. */ boundStartExtent = i; /* Assign bound of extent containing start byte. */ offsetInStartExtent = offsetStart - offsetStartOfCurrentExtent; /* Assign relative offset of start byte in start extent. */ sizeInStartExtent = metaFile->tuple[i].countExtentBlock * BLOCK_SIZE - offsetInStartExtent; /* Assign size to opreate in start extent. */ break; } offsetStartOfCurrentExtent += metaFile->tuple[i].countExtentBlock * BLOCK_SIZE; /* Add count of blocks in current extent. */ } offsetStartOfCurrentExtent = 0; /* Relative offset of end byte in current extent. */ Debug::debugItem("Stage 10. metaFile->count = %lu", metaFile->count); for (uint64_t i = 0; i < metaFile->count; i++) { if ((offsetStartOfCurrentExtent + metaFile->tuple[i].countExtentBlock * BLOCK_SIZE - 1) >= offsetEnd) { /* A -1 is needed to locate offset of end byte in current extent. */ boundEndExtent = i; /* Assign bound of extent containing end byte. */ offsetInEndExtent = offsetEnd - offsetStartOfCurrentExtent; /* Assign relative offset of end byte in end extent. */ sizeInEndExtent = offsetInEndExtent + 1; /* Assign size to opreate in end extent. */ break; } offsetStartOfCurrentExtent += metaFile->tuple[i].countExtentBlock * BLOCK_SIZE; /* Add count of blocks in current extent. */ } Debug::debugItem("Stage 11. boundStartExtent = %lu, boundEndExtent = %lu", boundStartExtent, boundEndExtent); if (boundStartExtent == boundEndExtent) { /* If in one extent. */ fpi->len = 1; /* Assign length. */ fpi->tuple[0].node_id = metaFile->tuple[boundStartExtent].hashNode; /* Assign node ID. */ fpi->tuple[0].offset = metaFile->tuple[boundStartExtent].indexExtentStartBlock * BLOCK_SIZE + offsetInStartExtent; /* Assign offset. */ fpi->tuple[0].size = size; } else { /* Multiple extents. */ Debug::debugItem("Stage 12."); fpi->len = boundEndExtent - boundStartExtent + 1; /* Assign length. */ fpi->tuple[0].node_id = metaFile->tuple[boundStartExtent].hashNode; /* Assign node ID of start extent. */ fpi->tuple[0].offset = metaFile->tuple[boundStartExtent].indexExtentStartBlock * BLOCK_SIZE + offsetInStartExtent; /* Assign offset. */ fpi->tuple[0].size = sizeInStartExtent; /* Assign size. */ for (int i = 1; i <= ((int)(fpi->len) - 2); i++) { /* Start from second extent to one before last extent. */ fpi->tuple[i].node_id = metaFile->tuple[boundStartExtent + i].hashNode; /* Assign node ID of start extent. */ fpi->tuple[i].offset = metaFile->tuple[boundStartExtent + i].indexExtentStartBlock * BLOCK_SIZE; /* Assign offset. */ fpi->tuple[i].size = metaFile->tuple[boundStartExtent + i].countExtentBlock * BLOCK_SIZE; /* Assign size. */ } fpi->tuple[fpi->len - 1].node_id= metaFile->tuple[boundEndExtent].hashNode; /* Assign node ID of start extent. */ fpi->tuple[fpi->len - 1].offset = 0; /* Assign offset. */ fpi->tuple[fpi->len - 1].size = sizeInEndExtent; /* Assign size. */ Debug::debugItem("Stage 13."); } } /* Read extent. That is to parse the part to read in file position information. @param path Path of file. @param size Size of data to read. @param offset Offset of data to read. @param fpi File position information buffer. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::extentRead(const char *path, uint64_t size, uint64_t offset, file_pos_info *fpi, uint64_t *key_offset, uint64_t *key) { //printf("fs-read, path: %s, size: %lx, offset: %lx\n", path, size, offset); Debug::debugTitle("FileSystem::read"); Debug::debugCur("read, size = %x, offset = %x", size, offset); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if ((path == NULL) || (fpi == NULL) || (size == 0) || (key == NULL)) /* Judge if path and file position information buffer are valid or size to read is valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ bool result; *key = lockReadHashItem(hashNode, hashAddress); /* Lock hash item. */ *key_offset = hashAddress; //printf("read lock succeed\n"); { uint64_t indexFileMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexFileMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to path does not exist. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == true) { /* If directory meta. */ Debug::notifyError("Directory meta."); result = false; /* Fail due to not file. */ } else { FileMeta metaFile; Debug::debugItem("Stage 3. Get Filemeta index."); if (storage->tableFileMeta->get(indexFileMeta, &metaFile) == false) { Debug::notifyError("Fail due to get file meta error."); result = false; /* Fail due to get file meta error. */ } else { Debug::debugItem("Stage 3-1. meta.size = %d, size = %d, offset = %d", metaFile.size, size, offset); if (offset + 1 > metaFile.size) { /* Judge if offset and size are valid. */ fpi->len = 0; return true; } else if((metaFile.size - offset) < size) { size = metaFile.size - offset; } fillFilePositionInformation(size, offset, fpi, &metaFile); /* Fill file position information. */ result = true; /* Succeed. */ } } } } /* Do not unlock here. */ // unlockReadHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Read extent end. Only unlock path due to lock in extentRead. @param Key key obtained from read lock. @param path Path of file or folder.*/ bool FileSystem::extentReadEnd(uint64_t key, char* path) { Debug::debugTitle("FileSystem::extentReadEnd"); if (path == NULL) /* Judge if path and file meta buffer are valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ /* Do not lock. It has been locked in extentRead. */ // uint64_t key = lockHashItem(path); /* Lock hash item. */ uint64_t indexFileMeta; bool isDirectory; storage->hashtable->get(&hashUnique, &indexFileMeta, &isDirectory); if(isDirectory) Debug::notifyError("Directory is read."); unlockReadHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return true; /* Return. */ } else { /* If remote node. */ return false; } } } /* Write extent. That is to parse the part to write in file position information. Attention: do not unlock here. Unlock is implemented in updateMeta. @param path Path of file. @param size Size of data to write. @param offset Offset of data to write. @param fpi File position information. @param metaFile File meta buffer. @param key Key buffer to unlock. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::extentWrite(const char *path, uint64_t size, uint64_t offset, file_pos_info *fpi, uint64_t *key_offset, uint64_t *key) /* Write. */ { Debug::debugTitle("FileSystem::write"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); Debug::debugItem("write, size = %x, offset = %x", size, offset); if ((path == NULL) || (fpi == NULL) || (key == NULL)) /* Judge if path, file position information buffer and key buffer are valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ bool result; *key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ *key_offset = hashAddress; { uint64_t indexFileMeta; bool isDirectory; FileMeta *metaFile = (FileMeta *)malloc(sizeof(FileMeta)); if (storage->hashtable->get(&hashUnique, &indexFileMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to path does not exist. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == true) { /* If directory meta. */ result = false; /* Fail due to not file. */ } else { if (storage->tableFileMeta->get(indexFileMeta, metaFile) == false) { result = false; /* Fail due to get file meta error. */ } else { if (((0xFFFFFFFFFFFFFFFF - offset) < size) || (size == 0)) { result = false; /* Fail due to offset + size will cause overflow or size is zero. */ } else { Debug::debugItem("Stage 3."); if ((metaFile->size == 0) || ((offset + size - 1) / BLOCK_SIZE > (metaFile->size - 1) / BLOCK_SIZE)) { /* Judge if new blocks need to be created. */ uint64_t countExtraBlock; /* Count of extra blocks. At least 1. */ int64_t boundCurrentExtraExtent; /* Bound of current extra extent. */ /* Consider 0 size file. */ Debug::debugItem("Stage 4. metaFile->size = %lu", metaFile->size); if (metaFile->size == 0) { boundCurrentExtraExtent = -1; /* Bound current extra extent start from 0. */ countExtraBlock = (offset + size - 1) / BLOCK_SIZE + 1; Debug::debugItem("Stage 4-1, countExtraBlock = %d, BLOCK_SIZE = %d", countExtraBlock, BLOCK_SIZE); } else { boundCurrentExtraExtent = (int64_t)metaFile->count - 1; /* Bound current extra extent start from metaFile->count. */ countExtraBlock = (offset + size - 1) / BLOCK_SIZE - (metaFile->size - 1) / BLOCK_SIZE; } uint64_t indexCurrentExtraBlock; /* Index of current extra block. */ uint64_t indexLastCreatedBlock; Debug::debugItem("Stage 5."); bool resultFor = true; for (uint64_t i = 0; i < countExtraBlock; i++) { /* No check on count of extra blocks. */ Debug::debugItem("for loop, i = %d", i); if (storage->tableBlock->create(&indexCurrentExtraBlock) == false) { resultFor = false; /* Fail due to no enough space. Might cause inconsistency. */ break; } else { /* So we need to modify the allocation way in table class. */ indexLastCreatedBlock = -1; if(boundCurrentExtraExtent >= 0) { indexLastCreatedBlock = metaFile->tuple[boundCurrentExtraExtent].indexExtentStartBlock + metaFile->tuple[boundCurrentExtraExtent].countExtentBlock; } Debug::debugItem("%d, %d, %d", boundCurrentExtraExtent, indexLastCreatedBlock, indexCurrentExtraBlock); if(boundCurrentExtraExtent >= 0 && (indexCurrentExtraBlock == indexLastCreatedBlock)) { metaFile->tuple[boundCurrentExtraExtent].countExtentBlock++; /* Increment of count of blocks in current extent. */ } else if (boundCurrentExtraExtent == -1 || indexCurrentExtraBlock != indexLastCreatedBlock) { /* Separate block index generates a new extent. */ boundCurrentExtraExtent++; metaFile->tuple[boundCurrentExtraExtent].hashNode = hashLocalNode; /* Assign local node hash. */ metaFile->tuple[boundCurrentExtraExtent].indexExtentStartBlock = indexCurrentExtraBlock; /* Assign start block in extent. */ metaFile->tuple[boundCurrentExtraExtent].countExtentBlock = 1; /* Assign count of block in extent. */ metaFile->count++; /* Update count of extents. */ } else{ /* Continuous blocks in one extent. */ resultFor = false; break; } } } if(resultFor == false) result = false; else { metaFile->size = offset + size; Debug::debugItem("meta.size: %lx", metaFile->size); fillFilePositionInformation(size, offset, fpi, metaFile); /* Fill file position information. */ result = true; } } else { metaFile->size = (offset + size) > metaFile->size ? (offset + size) : metaFile->size; /* Update size of file in meta. */ fillFilePositionInformation(size, offset, fpi, metaFile); /* Fill file position information. */ /*printf("(int)(fpi->len) = %d, (int)(fpi->offset[0]) = %d, (int)(fpi->size[0]) = %d\n", (int)(fpi->len), (int)(fpi->offset[0]), (int)(fpi->size[0]));*/ result = true; /* Succeed. */ } } } } } if(result) { metaFile->timeLastModified = time(NULL); storage->tableFileMeta->put(indexFileMeta, metaFile); } for(int i = 0; i < (int)metaFile->count; i++) Debug::debugCur("at %ld, start: %lx, len: %lx", i, metaFile->tuple[i].indexExtentStartBlock, metaFile->tuple[i].countExtentBlock); for(unsigned int i = 0; i < fpi->len; i++) Debug::debugCur("fpi, at %d, offset: %lx, size: %lx", i, fpi->tuple[i].offset, fpi->tuple[i].size); Debug::debugItem("Stage 8. meta.size = %d", metaFile->size); free(metaFile); } /* Do not unlock hash item here. */ // unlockHashItem(key, hashNode, hashAddress); /* Unlock hash item. Temporarily put it here. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } } return false; } /* Update meta. Only unlock path due to lock in extentWrite. @param path Path of file or folder. @param metaFile File meta to update. @oaram key Key to unlock. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::updateMeta(const char *path, FileMeta *metaFile, uint64_t key) { Debug::debugTitle("FileSystem::updateMeta"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if ((path == NULL) || (metaFile == NULL)) /* Judge if path and file meta buffer are valid. */ return false; /* Null parameter error. */ else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ bool result; /* Do not lock. It has been locked in extentWrite. */ // uint64_t key = lockHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexFileMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexFileMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to path does not exist. */ } else { Debug::debugItem("Stage 2. Put meta."); if (isDirectory == true) { /* If directory meta. */ result = false; } else { metaFile->timeLastModified = time(NULL); /* Set last modified time. */ if (storage->tableFileMeta->put(indexFileMeta, metaFile) == false) { result = false; /* Fail due to put file meta error. */ } else { Debug::debugItem("stage 3. Update Meta Succeed."); result = true; /* Succeed. */ } } } } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Truncate file. Currently only support shrink file but cannot enlarge. @param path Path of file. @param size Size of file. @return If operation succeeds then return 0, otherwise return negative value. */ bool FileSystem::truncate(const char *path, uint64_t size) /* Truncate size of file to 0. */ { Debug::debugTitle("FileSystem::truncate"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexFileMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexFileMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to existence of path. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == true) { /* If directory meta. */ result = false; } else { FileMeta metaFile; if (storage->tableFileMeta->get(indexFileMeta, &metaFile) == false) { result = false; /* Fail due to get file meta error. */ } else { if (size >= metaFile.size) { /* So metaFile.size won't be 0. At least one block. */ result = false; /* Fail due to no bytes need to removed. */ } else { uint64_t countTotalBlockTillLastExtentEnd = 0; /* Count of total blocks till end of last extent. */ uint64_t countNewTotalBlock; /* Count of total blocks in new file. */ if (size == 0) { countNewTotalBlock = 0; /* For 0 size file. */ } else { countNewTotalBlock = (size - 1) / BLOCK_SIZE + 1; /* For normal file. */ } Debug::debugItem("Stage 3. Remove blocks."); /* Current assume all blocks in local node. */ bool found = false; uint64_t i; for (i = 0; i < metaFile.count; i++) { if ((countTotalBlockTillLastExtentEnd + metaFile.tuple[i].countExtentBlock >= countNewTotalBlock)) { found = true; break; } countTotalBlockTillLastExtentEnd += metaFile.tuple[i].countExtentBlock; } if (found == false) { result = false; /* Fail due to count of current total blocks is less than truncated version. Actually it cannot be reached. */ } else { uint64_t resultFor = true; // for (uint64_t j = (countNewTotalBlock - countTotalBlockTillLastExtentEnd - 1 + 1); /* Bound of first block to truncate. A -1 is to convert count to bound. A +1 is to move bound of last kept block to bound of first to truncate. */ // j < metaFile.countExtentBlock[i]; j++) { /* i is current extent. */ // if (storage->tableBlock->remove(metaFile.indexExtentStartBlock[i] + j) == false) { // resultFor = false; // break; // } // } for (int j = metaFile.tuple[i].countExtentBlock - 1; j >= (int)(countNewTotalBlock - countTotalBlockTillLastExtentEnd - 1 + 1); j--) { /* i is current extent. */ /* Bound of first block to truncate. A -1 is to convert count to bound. A +1 is to move bound of last kept block to bound of first to truncate. */ if (storage->tableBlock->remove(metaFile.tuple[i].indexExtentStartBlock + j) == false) { resultFor = false; break; } } if (resultFor == false) { result = false; } else { resultFor = true; // for (uint64_t j = i + 1; j < metaFile.count; j++) { /* Remove rest extents. */ // for (uint64_t k = 0; k < metaFile.countExtentBlock[j]; k++) { // if (storage->tableBlock->remove(metaFile.indexExtentStartBlock[j] + k) == false) { // resultFor = false; // break; // } // } // } for (uint64_t j = i + 1; j < metaFile.count; j++) { /* Remove rest extents. */ for (int k = metaFile.tuple[j].countExtentBlock - 1; k >= 0; k--) { if (storage->tableBlock->remove(metaFile.tuple[j].indexExtentStartBlock + k) == false) { resultFor = false; break; } } } if (resultFor == false) { result = false; /* Fail due to block remove error. */ } else { metaFile.size = size; /* Size is the acutal size. */ metaFile.count = i + 1; /* i is the last extent containing last block. */ if (storage->tableFileMeta->put(indexFileMeta, &metaFile) == false) { /* Update meta. */ result = false; /* Fail due to update file meta error. */ } else { result = true; /* Succeed. */ } } } } } } } } } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Remove directory (Unused). @param path Path of directory. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::rmdir(const char *path) { Debug::debugTitle("FileSystem::rmdir"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ uint64_t RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexDirectoryMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexDirectoryMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to existence of path. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == false) { /* If not directory meta. */ result = false; } else { Debug::debugItem("Stage 3. Remove meta from directory."); char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); getNameFromPath(path, name); getParentDirectory(path, parent); if (removeMetaFromDirectory(parent, name, &RemoteTxID, &srcBuffer, &desBuffer, &size, &remotekey, &offset) == false) { result = false; } else { DirectoryMeta metaDirectory; if (storage->tableDirectoryMeta->get(indexDirectoryMeta, &metaDirectory) == false) { result = false; /* Fail due to get file meta error. */ } else { if (metaDirectory.count != 0) { /* Directory is not empty. */ result = false; /* Fail due to directory is not empty. */ } else { Debug::debugItem("Stage 3. Remove directory meta."); if (storage->tableDirectoryMeta->remove(indexDirectoryMeta) == false) { result = false; /* Fail due to remove error. */ } else { if (storage->hashtable->del(&hashUnique) == false) { result = false; /* Fail due to hash table del. No roll back. */ } else { result = true; } } } } } free(parent); free(name); } } } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return true; } } } /* Remove file or empty directory. @param path Path of file or directory. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::remove(const char *path, FileMeta *metaFile) { #ifdef TRANSACTION_2PC return remove2pc(path, metaFile); #endif #ifdef TRANSACTION_CD return removecd(path, metaFile); #endif } bool FileSystem::removecd(const char *path, FileMeta *metaFile) { Debug::debugTitle("FileSystem::remove"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ // uint64_t DistributedTxID; uint64_t LocalTxID = 0; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to existence of path. */ } else { char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); DirectoryMeta parentMeta; uint64_t parentHashAddress, parentMetaAddress; uint16_t parentNodeID; getParentDirectory(path, parent); getNameFromPath(path, name); Debug::debugItem("Stage 2. Get meta."); if(isDirectory) { DirectoryMeta metaDirectory; if (storage->tableDirectoryMeta->get(indexMeta, &metaDirectory) == false) { result = false; /* Fail due to get file meta error. */ } else { metaFile->count = MAX_FILE_EXTENT_COUNT; if (metaDirectory.count != 0) { /* Directory is not empty. */ result = false; /* Fail due to directory is not empty. */ } else { // DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); if (readDirectoryMeta(parent, &parentMeta, &parentHashAddress, &parentMetaAddress, &parentNodeID) == false) { Debug::notifyError("Remove Meta From Directory failed."); // TxDistributedPrepare(DistributedTxID, false); result = false; } else { /* Remove meta from directory */ DirectoryMeta metaModifiedDirectory; /* Buffer to save modified directory. */ uint64_t indexModifiedNames = 0; for (uint64_t i = 0; i < parentMeta.count; i++) { if (strcmp(parentMeta.tuple[i].names, name) == 0) { /* If found selected name. */ } else { strcpy(metaModifiedDirectory.tuple[indexModifiedNames].names, parentMeta.tuple[i].names); /* Copy original name to modified meta. */ metaModifiedDirectory.tuple[indexModifiedNames].isDirectories = parentMeta.tuple[i].isDirectories; /* Add directory state. */ indexModifiedNames++; } } metaModifiedDirectory.count = indexModifiedNames; /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)&parentMeta, (uint64_t)sizeof(DirectoryMeta)); /* Receive remote prepare with (OK) */ // TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ updateRemoteMeta(parentNodeID, &metaModifiedDirectory, parentMetaAddress, parentHashAddress); /* Only allocate momery, write to log first. */ Debug::debugItem("Stage 3. Remove directory meta."); if (storage->tableDirectoryMeta->remove(indexMeta) == false) { result = false; /* Fail due to remove error. */ } else { if (storage->hashtable->del(&hashUnique) == false) { result = false; /* Fail due to hash table del. No roll back. */ } else { result = true; } } } } } } else { if (storage->tableFileMeta->get(indexMeta, metaFile) == false) { result = false; /* Fail due to get file meta error. */ } else { // DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); if (readDirectoryMeta(parent, &parentMeta, &parentHashAddress, &parentMetaAddress, &parentNodeID) == false) { Debug::notifyError("Remove Meta From Directory failed."); // TxDistributedPrepare(DistributedTxID, false); result = false; } else { /* Remove meta from directory */ DirectoryMeta metaModifiedDirectory; /* Buffer to save modified directory. */ uint64_t indexModifiedNames = 0; for (uint64_t i = 0; i < parentMeta.count; i++) { if (strcmp(parentMeta.tuple[i].names, name) == 0) { /* If found selected name. */ } else { strcpy(metaModifiedDirectory.tuple[indexModifiedNames].names, parentMeta.tuple[i].names); /* Copy original name to modified meta. */ metaModifiedDirectory.tuple[indexModifiedNames].isDirectories = parentMeta.tuple[i].isDirectories; /* Add directory state. */ indexModifiedNames++; } } metaModifiedDirectory.count = indexModifiedNames; /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)&parentMeta, (uint64_t)sizeof(DirectoryMeta)); /* Receive remote prepare with (OK) */ // TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ updateRemoteMeta(parentNodeID, &metaModifiedDirectory, parentMetaAddress, parentHashAddress); /* Only allocate momery, write to log first. */ bool resultFor = true; Debug::debugItem("Stage 3. Remove blocks."); for (uint64_t i = 0; (i < metaFile->count) && (metaFile->tuple[i].hashNode == hashNode); i++) { for (int j = (int)(metaFile->tuple[i].countExtentBlock) - 1; j >= 0; j--) { if (storage->tableBlock->remove(metaFile->tuple[i].indexExtentStartBlock + j) == false) { ; } } } if (resultFor == false) { result = false; /* Fail due to block remove error. */ } else { Debug::debugItem("Stage 4. Remove file meta."); if (storage->tableFileMeta->remove(indexMeta) == false) { result = false; /* Fail due to remove error. */ } else { if (storage->hashtable->del(&hashUnique) == false) { result = false; /* Fail due to hash table del. No roll back. */ } else { result = true; } } } } } } free(parent); free(name); } } if (result == false) { TxLocalCommit(LocalTxID, false); // TxDistributedCommit(DistributedTxID, false); } else { TxLocalCommit(LocalTxID, true); // TxDistributedCommit(DistributedTxID, true); } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } bool FileSystem::remove2pc(const char *path, FileMeta *metaFile) { Debug::debugTitle("FileSystem::remove"); Debug::debugItem("Stage 1. Entry point. Path: %s.", path); if (path == NULL) { return false; /* Fail due to null path. */ } else { UniqueHash hashUnique; HashTable::getUniqueHash(path, strlen(path), &hashUnique); /* Get unique hash. */ NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash by unique hash. */ AddressHash hashAddress = HashTable::getAddressHash(&hashUnique); /* Get address hash by unique hash. */ uint64_t DistributedTxID; uint64_t LocalTxID; uint64_t RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset; if (checkLocal(hashNode) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNode, hashAddress); /* Lock hash item. */ { uint64_t indexMeta; bool isDirectory; if (storage->hashtable->get(&hashUnique, &indexMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to existence of path. */ } else { char *parent = (char *)malloc(strlen(path) + 1); char *name = (char *)malloc(strlen(path) + 1); getParentDirectory(path, parent); getNameFromPath(path, name); Debug::debugItem("Stage 2. Get meta."); if(isDirectory) { DirectoryMeta metaDirectory; if (storage->tableDirectoryMeta->get(indexMeta, &metaDirectory) == false) { result = false; /* Fail due to get file meta error. */ } else { metaFile->count = MAX_FILE_EXTENT_COUNT; if (metaDirectory.count != 0) { /* Directory is not empty. */ result = false; /* Fail due to directory is not empty. */ } else { DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); if (removeMetaFromDirectory(parent, name, &RemoteTxID, &srcBuffer, &desBuffer, &size, &remotekey, &offset) == false) { Debug::notifyError("Remove Meta From Directory failed."); TxDistributedPrepare(DistributedTxID, false); result = false; } else { char *logData = (char *)malloc(strlen(path) + 4); sprintf(logData, "del %s", path); /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)logData, (uint64_t)strlen(logData)); free(logData); /* Receive remote prepare with (OK) */ TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ updateDirectoryMeta(parent, RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset); /* Only allocate momery, write to log first. */ Debug::debugItem("Stage 3. Remove directory meta."); if (storage->tableDirectoryMeta->remove(indexMeta) == false) { result = false; /* Fail due to remove error. */ } else { if (storage->hashtable->del(&hashUnique) == false) { result = false; /* Fail due to hash table del. No roll back. */ } else { result = true; } } } } } } else { if (storage->tableFileMeta->get(indexMeta, metaFile) == false) { result = false; /* Fail due to get file meta error. */ } else { DistributedTxID = TxDistributedBegin(); LocalTxID = TxLocalBegin(); if (removeMetaFromDirectory(parent, name, &RemoteTxID, &srcBuffer, &desBuffer, &size, &remotekey, &offset) == false) { Debug::notifyError("Remove Meta From Directory failed."); TxDistributedPrepare(DistributedTxID, false); result = false; } else { char *logData = (char *)malloc(strlen(path) + 4); sprintf(logData, "del %s", path); /* Apply updated data to local log. */ TxWriteData(LocalTxID, (uint64_t)logData, (uint64_t)strlen(logData)); free(logData); /* Receive remote prepare with (OK) */ TxDistributedPrepare(DistributedTxID, true); /* Start phase 2, commit it. */ updateDirectoryMeta(parent, RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset); /* Only allocate momery, write to log first. */ bool resultFor = true; Debug::debugItem("Stage 3. Remove blocks."); for (uint64_t i = 0; (i < metaFile->count) && (metaFile->tuple[i].hashNode == hashNode); i++) { for (int j = (int)(metaFile->tuple[i].countExtentBlock) - 1; j >= 0; j--) { if (storage->tableBlock->remove(metaFile->tuple[i].indexExtentStartBlock + j) == false) { ; } } } if (resultFor == false) { result = false; /* Fail due to block remove error. */ } else { Debug::debugItem("Stage 4. Remove file meta."); if (storage->tableFileMeta->remove(indexMeta) == false) { result = false; /* Fail due to remove error. */ } else { if (storage->hashtable->del(&hashUnique) == false) { result = false; /* Fail due to hash table del. No roll back. */ } else { result = true; } } } } } } free(parent); free(name); } } if (result == false) { TxLocalCommit(LocalTxID, false); TxDistributedCommit(DistributedTxID, false); } else { TxLocalCommit(LocalTxID, true); TxDistributedCommit(DistributedTxID, true); } unlockWriteHashItem(key, hashNode, hashAddress); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } bool FileSystem::blockFree(uint64_t startBlock, uint64_t countBlock) { Debug::debugTitle("FileSystem::blockFree"); Debug::debugItem("Stage 1. startBlock = %d, countBlock = %d", startBlock, countBlock); bool result; for (int j = (int)countBlock - 1; j >= 0; j--) { if (storage->tableBlock->remove(startBlock + j) == false) { result = false; /* Fail due to block remove error. */ break; } } return result; } /* Rename file. @param pathOld Old path. @param pathNew New path. @return If operation succeeds then return true, otherwise return false. */ bool FileSystem::rename(const char *pathOld, const char *pathNew) { Debug::debugTitle("FileSystem::rename"); Debug::debugItem("Stage 1. Entry point. Path: %s.", pathNew); if ((pathOld == NULL) || (pathNew == NULL)) { return false; /* Fail due to null path. */ } else { UniqueHash hashUniqueOld; HashTable::getUniqueHash(pathOld, strlen(pathOld), &hashUniqueOld); /* Get unique hash. */ NodeHash hashNodeOld = storage->getNodeHash(&hashUniqueOld); /* Get node hash by unique hash. */ AddressHash hashAddressOld = HashTable::getAddressHash(&hashUniqueOld); /* Get address hash by unique hash. */ uint64_t RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset; // UniqueHash hashUniqueNew; // HashTable::getUniqueHash(pathNew, strlen(pathNew), &hashUniqueNew); /* Get unique hash. */ // NodeHash hashNodeNew = storage->getNodeHash(&hashUniqueNew); /* Get node hash by unique hash. */ // AddressHash hashAddressNew = HashTable::getAddressHash(&hashUniqueNew); /* Get address hash by unique hash. */ if (checkLocal(hashNodeOld) == true) { /* If local node. */ bool result; uint64_t key = lockWriteHashItem(hashNodeOld, hashAddressOld); /* Lock hash item. */ { uint64_t indexFileMeta; bool isDirectory; if (storage->hashtable->get(&hashUniqueOld, &indexFileMeta, &isDirectory) == false) { /* If path does not exist. */ result = false; /* Fail due to existence of path. */ } else { Debug::debugItem("Stage 2. Get meta."); if (isDirectory == true) { /* If directory meta. */ result = false; /* Fail due to directory rename is not supported. */ } else { char *parent = (char *)malloc(strlen(pathOld) + 1); char *name = (char *)malloc(strlen(pathOld) + 1); getParentDirectory(pathOld, parent); getNameFromPath(pathOld, name); if (removeMetaFromDirectory(parent, name, &RemoteTxID, &srcBuffer, &desBuffer, &size, &remotekey, &offset) == false) { result = false; } else { FileMeta metaFile; if (storage->tableFileMeta->get(indexFileMeta, &metaFile) == false) { result = false; /* Fail due to get file meta error. */ } else{ updateDirectoryMeta(parent, RemoteTxID, srcBuffer, desBuffer, size, remotekey, offset); Debug::debugItem("Stage 4. Remove file meta."); if (storage->tableFileMeta->remove(indexFileMeta) == false) { result = false; /* Fail due to remove error. */ } else { if (storage->hashtable->del(&hashUniqueOld) == false) { result = false; /* Fail due to hash table del. No roll back. */ } else { result = true; } } } } free(parent); free(name); } } } unlockWriteHashItem(key, hashNodeOld, hashAddressOld); /* Unlock hash item. */ Debug::debugItem("Stage end."); return result; /* Return specific result. */ } else { /* If remote node. */ return false; } } } /* Initialize root directory. @param LocalNode Local Node ID. */ void FileSystem::rootInitialize(NodeHash LocalNode) { this->hashLocalNode = LocalNode; /* Assign local node hash. */ /* Add root directory. */ UniqueHash hashUnique; HashTable::getUniqueHash("/", strlen("/"), &hashUnique); NodeHash hashNode = storage->getNodeHash(&hashUnique); /* Get node hash. */ Debug::debugItem("root node: %d", (int)hashNode); if (hashNode == this->hashLocalNode) { /* Root directory is here. */ Debug::notifyInfo("Initialize root directory."); DirectoryMeta metaDirectory; metaDirectory.count = 0; /* Initialize count of files in root directory is 0. */ uint64_t indexDirectoryMeta; if (storage->tableDirectoryMeta->create(&indexDirectoryMeta, &metaDirectory) == false) { fprintf(stderr, "FileSystem::FileSystem: create directory meta error.\n"); exit(EXIT_FAILURE); /* Exit due to parameter error. */ } else { if (storage->hashtable->put("/", indexDirectoryMeta, true) == false) { /* true for directory. */ fprintf(stderr, "FileSystem::FileSystem: hashtable put error.\n"); exit(EXIT_FAILURE); /* Exit due to parameter error. */ } else { ; } } } } /* Constructor of file system. @param buffer Buffer of memory. @param countFile Max count of file. @param countDirectory Max count of directory. @param countBlock Max count of blocks. @param countNode Max count of nodes. @param hashLocalNode Local node hash. From 1 to countNode. */ FileSystem::FileSystem(char *buffer, char *bufferBlock, uint64_t countFile, uint64_t countDirectory, uint64_t countBlock, uint64_t countNode, NodeHash hashLocalNode) { if ((buffer == NULL) || (bufferBlock == NULL) || (countFile == 0) || (countDirectory == 0) || (countBlock == 0) || (countNode == 0) || (hashLocalNode < 1) || (hashLocalNode > countNode)) { fprintf(stderr, "FileSystem::FileSystem: parameter error.\n"); exit(EXIT_FAILURE); /* Exit due to parameter error. */ } else { this->addressHashTable = (uint64_t)buffer; storage = new Storage(buffer, bufferBlock, countFile, countDirectory, countBlock, countNode); /* Initialize storage instance. */ lock = new LockService((uint64_t)buffer); } } /* Destructor of file system. */ FileSystem::~FileSystem() { delete storage; /* Release storage instance. */ }
#include <stdio.h> #include <stdlib.h> #include <stdio.h> #include "_syslog.h" // #include <basetsd.h> #include <ctype.h> #include <string> #include <libxml/tree.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #if defined(LIBXML_XPATH_ENABLED) && defined(LIBXML_SAX1_ENABLED) && defined(LIBXML_OUTPUT_ENABLED) #else #error "XPath support not compiled in libxml" #endif #include "phrasea_clock_t.h" #include "dom.h" #include "connbas_dbox.h" #include "sbas.h" #include "indexer.h" extern char arg_forcedefault; // prototypes local fcts void evt_start(CDOMDocument *xmlparser, const char *name, const char *path, const char *upath); void evt_end(CDOMDocument *xmlparser); void evt_keyword(CDOMDocument *xmlparser, const char *lowKeyword, unsigned int lowKeywordLen, unsigned int pos, unsigned int len, unsigned int index, const char *lng, unsigned int lngLen); // prototypes external fcts extern CSyslog zSyslog; // , LOG_PID, LOG_DAEMON); extern const char *arg_clng; void loadThesaurus(CIndexer *indexer); // ---------------------------------------------- // the parser has seen an opening tag // path : xpath as "/record/description/MotCle" // upath : xpath as "/RECORD[0]/DESCRIPTION[0]/MOTCLE[4]" // ---------------------------------------------- void evt_start(CDOMDocument *xmlparser, const char *name, const char *path, const char *upath) { // get data passed to this callback CIndexer *indexer = (CIndexer *)(xmlparser->userData); // search/create the upath into the xpaths list CXPath *xp; for(xp=indexer->tXPaths; xp; xp=xp->next) { if(strcmp((char*)(xp->upath), (char *)upath) == 0) break; } if(!xp) { if( (xp = new CXPath(upath, strlen((char *)upath))) ) { xp->next = indexer->tXPaths; indexer->tXPaths = xp; } } indexer->current_xpath = xp; // search the field into the structure indexer->xmlparser->parseText = false; indexer->xmlparser->getContent = false; indexer->xmlparser->onEnd = NULL; for(int i=0; i<indexer->nStructFields; i++) { if(strcmp(path, indexer->tStructField[i].fullpath)==0) { // the field is known in the structure // so we tell it to the current node of the parser indexer->xmlparser->currentNode->field = indexer->tStructField + i; if(xp) xp->field = indexer->tStructField + i; indexer->xmlparser->parseText = true; if(indexer->tStructField[i].tXPathCtxThesaurus || indexer->tStructField[i].type != CStructField::TYPE_NONE) { // the current field has at least one xpathcontext to a branch of the thesaurus, or a type // ... so we need the content of the field // ... so we tell the parser to get the content indexer->xmlparser->getContent = true; // ... and we ask a callback a the end of the tag indexer->xmlparser->onEnd = evt_end; } break; } } } bool is_integer(char *s) { while(*s && *s>='0' && *s<='9') s++; return(*s == '\0'); } bool is_multidigits(char *s) { while(*s && ((*s>='0' && *s<='9') || *s=='_' || isspace(*s))) s++; return(*s == '\0'); } bool is_delimdate(char *s) { char buff[90]; int l; int date[6]; if( (l = strlen(s)) > 89 ) l = 89; memcpy(buff, s, l+1); buff[l+1] = '\0'; while(l >= 0) { if(buff[l]<'0' || buff[l]>'9') buff[l] = ' '; l--; } l = sscanf(buff, "%d %d %d %d %d %d", &date[0], &date[1], &date[2], &date[3], &date[4], &date[5]); return(l==3 || l==6); } void evt_end(CDOMDocument *xmlparser) { // get data passed to this callback CIndexer *indexer = (CIndexer *)(xmlparser->userData); CDOMElement *currentNode = indexer->xmlparser->currentNode; CStructField *currentField = currentNode->field; currentNode->addValueC('\0', currentNode->lastFlags, CFLAG_NORMALCHAR); currentNode->addValueLC('\0', currentNode->lastFlags, CFLAG_NORMALCHAR); char *valueLCND = currentNode->valueLCND; char *valueLC = currentNode->valueLC; char *value = currentNode->value; if(valueLC[0] == '\0') return; // champ vide char strbuff[1000]; std::string cstr; if(currentField && currentField->type != CStructField::TYPE_NONE) { snprintf(strbuff, 1000, "field <%s> start=%d, end=%d\nvalue=%s\nvalueLC=%s\nvalueLCND=%s\n", currentField->name, currentNode->index_start, currentNode->index_end, value, valueLC, valueLCND ); cstr += strbuff; // the current field has a type CProp *prop = NULL; char buff[90]; double fv; // float value int lv; // int value int l; int date[6]; switch(currentField->type) { case CStructField::TYPE_FLOAT: fv = atof((char *)valueLC); l = sprintf(buff, "%f", fv); if(l>0 && buff[l-1]=='.') buff[--l] = '\0'; prop = new CProp(buff); snprintf(strbuff, 1000, "got prop '%s' of type=TYPE_FLOAT (%d) \n", buff, currentField->type); cstr += strbuff; break; case CStructField::TYPE_INT: lv = atol((char *)valueLC); l = sprintf(buff, "%d", lv); prop = new CProp(buff); snprintf(strbuff, 1000, "got prop '%s' of type=TYPE_INT (%d) \n", buff, currentField->type); cstr += strbuff; break; case CStructField::TYPE_DATE: if( (l = strlen((char *)valueLC)) > 89 ) l = 89; memcpy(buff, valueLC, l+1); buff[l+1] = '\0'; while(l >= 0) { if(buff[l]<'0' || buff[l]>'9') buff[l] = ' '; l--; } l = sscanf(buff, "%d %d %d %d %d %d", &date[0], &date[1], &date[2], &date[3], &date[4], &date[5]); if(l == EOF) { for(l=0; l<6; l++) date[l] = 0; } else { while(l < 6) date[l++] = 0; if(date[0] < 0) date[0] = 0; else if(date[0]<20) date[0] += 2000; else if(date[0] < 100) date[0] += 1900; else if(date[0] >9999) date[0] = 9999; for(l=1; l<6; l++) { if(date[l] < 0) date[l] = 0; else if(date[l] > 99) date[l] = 99; } } sprintf(buff, "%04d%02d%02d%02d%02d%02d", date[0], date[1], date[2], date[3], date[4], date[5] ); snprintf(strbuff, 1000, "got prop '%s' of type=TYPE_DATE (%d) \n", buff, currentField->type); cstr += strbuff; prop = new CProp(buff); break; case CStructField::TYPE_TEXT: snprintf(strbuff, 1000, "got prop '%s' of type=TYPE_TEXT (%d) \n", valueLC, currentField->type); cstr += strbuff; prop = new CProp(valueLC); break; } if( prop ) { prop->type = currentField->type; prop->record_id = indexer->current_rid; // prop->pxpath = indexer->current_xpath; prop->pfield = indexer->current_xpath->field; prop->business = currentField->business; prop->next = indexer->firstProp; indexer->firstProp = prop; currentField->found = true; } } if(currentField && currentField->nXPathCtxThesaurus > 0) { // there's a least one tbranch, we search in the thesaurus // search the value in the thesaurus if(valueLCND && currentNode->index_end >= currentNode->index_start) { char *w = NULL; char *k = NULL; int lw=0, lk=0; register int i; // delete quotes (simples and doubles) of the lowvalue for(i=0; i <= currentNode->valueLCND_length; i++) { if(currentNode->valueLCND[i] == '\'' || currentNode->valueLCND[i] == '"') currentNode->valueLCND[i] = ' '; } if(currentNode->t0 >= 0 && (lw=(currentNode->t1-currentNode->t0+1)) > 0) { w = currentNode->valueLCND + currentNode->t0; currentNode->valueLCND[currentNode->t1+1] = '\0'; } if(currentNode->k0 >= 0 && (lk=(currentNode->k1-currentNode->k0+1)) > 0) { k = currentNode->valueLCND + currentNode->k0; currentNode->valueLCND[currentNode->k1+1] = '\0'; } // on cherche dans le thesaurus snprintf(strbuff, 1000, " searching in %d thesaurus branches w='%s' ; k='%s' :\n", currentField->nNodesThesaurus , w?w:(char *)"NULL", k?k:(char *)"NULL"); cstr += strbuff; int nfound = 0; for(i=0; i < currentField->nNodesThesaurus; i++) { CtidSet tids; tids.find(currentField->tNodesThesaurus[i], w, k); CTHit *thit; for(int j=0; j < tids.idNr; j++) { if(tids.idTab[j] && (thit = new CTHit(tids.idTab[j])) ) { snprintf(strbuff, 1000, " -> found id='%s'\n", tids.idTab[j]); cstr += strbuff; thit->record_id = indexer->current_rid; thit->pxpath = indexer->current_xpath; if(indexer->firstTHit) thit->next = indexer->firstTHit; indexer->firstTHit = thit; thit->hitstart = currentNode->index_start; thit->hitlen = currentNode->index_end - currentNode->index_start + 1; thit->business = currentField->business; } } nfound += tids.idNr; } // if we don't want candidates, return if(!currentField->candidatesDates && !currentField->candidatesIntegers && !currentField->candidatesStrings && !currentField->candidatesFirstDigit && !currentField->candidatesMultiDigits) return; if(nfound == 0) { // not found in the thesaurus, search in the cterms snprintf(strbuff, 1000, " searching in the cterms branch :\n"); cstr += strbuff; CtidSet tids; tids.find(currentField->xmlNodeCterms, w, k); for(int j=0; j < tids.idNr; j++) { CTHit *thit; if(tids.idTab[j] && (thit = new CTHit(tids.idTab[j])) ) { snprintf(strbuff, 1000, " -> found id='%s'\n", tids.idTab[j]); cstr += strbuff; thit->record_id = indexer->current_rid; thit->pxpath = indexer->current_xpath; if(indexer->firstTHit) thit->next = indexer->firstTHit; indexer->firstTHit = thit; thit->hitstart = currentNode->index_start; thit->hitlen = currentNode->index_end - currentNode->index_start + 1; thit->business = currentField->business; } } nfound += tids.idNr; } if(nfound == 0 && indexer->xmlNodePtr_deleted) { // not found in thesaurus neither in cterms : search in deleted (if the 'deleted' branch exists) snprintf(strbuff, 1000, " searching in the deleted branch :\n"); cstr += strbuff; CtidSet tids; tids.find(indexer->xmlNodePtr_deleted, w, k); for(int j=0; j < tids.idNr; j++) { CTHit *thit; if(tids.idTab[j] && (thit = new CTHit(tids.idTab[j])) ) { snprintf(strbuff, 1000, " -> found id='%s'\n", tids.idTab[j]); cstr += strbuff; thit->record_id = indexer->current_rid; thit->pxpath = indexer->current_xpath; if(indexer->firstTHit) thit->next = indexer->firstTHit; indexer->firstTHit = thit; thit->hitstart = currentNode->index_start; thit->hitlen = currentNode->index_end - currentNode->index_start + 1; thit->business = currentField->business; } } nfound += tids.idNr; } if(nfound == 0) { // not found in thesaurus neither in cterms neither in deleted : create in cterms // check if this term can be candidate bool canBeCandidate = false; if(is_delimdate(valueLCND)) { if(currentField->candidatesDates) canBeCandidate = true; } else if(is_multidigits(valueLCND)) { if(currentField->candidatesMultiDigits) canBeCandidate = true; } else if(is_integer(valueLCND)) { if(currentField->candidatesIntegers) canBeCandidate = true; } else if(*valueLCND>='0' && *valueLCND<='9') { if(currentField->candidatesFirstDigit) canBeCandidate = true; } else { if(currentField->candidatesStrings) canBeCandidate = true; } if(!canBeCandidate) return; xmlNodePtr cbranch = currentField->xmlNodeCterms; // get the nextid xmlChar *id=NULL, *nextid=NULL; if( (id = xmlGetProp(cbranch, (const xmlChar *)"id")) && (nextid = xmlGetProp(cbranch, (const xmlChar *)"nextid")) ) { char *buff; int l_id = strlen((const char *)id); int l_nextid = strlen((const char *)nextid); if( (buff = (char *)_MALLOC_WHY(l_id + 1 + l_nextid + 2 + 1, "main.cpp:evt_end:buff")) ) { xmlNodePtr te, sy; if((te = xmlNewChild(cbranch, NULL, (const xmlChar*)"te", NULL)) != NULL) { if((sy = xmlNewChild(te, NULL, (const xmlChar*)"sy", NULL)) != NULL) { memcpy(buff, id, l_id); buff[l_id] = '.'; memcpy(buff+l_id+1, nextid, l_nextid + 1); // prop 'id' of new 'te' xmlSetProp(te, (const xmlChar*)"id", (const xmlChar *)buff); // prop 'nextid' of new te xmlSetProp(te, (const xmlChar*)"nextid", (const xmlChar *)"1"); // prop 'id' of new 'sy' memcpy(buff+l_id+1+l_nextid, ".0", 3); xmlSetProp(sy, (const xmlChar*)"id", (const xmlChar *)buff); // add the thit to the record if(CTHit *thit = new CTHit(buff) ) { thit->record_id = indexer->current_rid; thit->pxpath = indexer->current_xpath; if(indexer->firstTHit) thit->next = indexer->firstTHit; indexer->firstTHit = thit; thit->hitstart = currentNode->index_start; thit->hitlen = currentNode->index_end - currentNode->index_start + 1; thit->business = currentField->business; } // prop 'lng' of the new 'sy' xmlSetProp(sy, (const xmlChar*)"lng", (const xmlChar *)arg_clng); // prop 'v' of the new 'sy' xmlSetProp(sy, (const xmlChar*)"v", (const xmlChar *)value); if(currentNode->t0 >= 0) { // prop 'w' of the new 'sy' xmlSetProp(sy, (const xmlChar*)"w", (const xmlChar *)valueLCND + currentNode->t0); } if(currentNode->k0 >= 0) { // prop 'k' of the new 'sy' xmlSetProp(sy, (const xmlChar*)"k", (const xmlChar *)valueLCND + currentNode->k0); } // prop 'nextid' du nvo 'sy' xmlSetProp(sy, (const xmlChar*)"nextid", (const xmlChar *)"0"); // increase nextid char ibuff[34]; sprintf(ibuff, "%d", atoi((const char *)nextid) + 1); xmlSetProp(cbranch, (const xmlChar*)"nextid", (const xmlChar *)ibuff ); } } _FREE(buff); indexer->ctermsChanged = true; // saveCterms(indexer); } } if(nextid) xmlFree(nextid); if(id) xmlFree(id); } } else { // printf("no-value !!\n"); } } // printf("evt_end(end)\n"); zSyslog._log(CSyslog::LOGL_PARSE, CSyslog::LOGC_INDEXING, (TCHAR *)(cstr.c_str()) ); } // ---------------------------------------------- // the parser met a keyword // ---------------------------------------------- void evt_keyword(CDOMDocument *xmlparser, const char *lowKeyword, unsigned int lowKeywordLen, unsigned int pos, unsigned int len, unsigned int index, const char *lng, unsigned int lngLen) { CIndexer *indexer = (CIndexer *)(xmlparser->userData); CStructField *currentField = indexer->xmlparser->currentNode->field; if(!currentField || currentField->index==false) return; unsigned int record_id = indexer->current_rid; // on finit notre keyword par '\0' char buff[256]; if(lowKeywordLen > 255) lowKeywordLen = 255; memcpy(buff, lowKeyword, lowKeywordLen); buff[lowKeywordLen] = '\0'; unsigned int hash = hashKword(lowKeyword, lowKeywordLen); // on le cherche dans le tableau de kword CKword *k; for(k=indexer->tKeywords[hash]; k; k=k->next) { if(strcmp((char *)(k->kword), buff) == 0 && strcmp(k->lng, lng) == 0) break; } if(!k) { if(debug_flag & DEBUG_PARSE) { char buff[100]; int l = lowKeywordLen; if(l>99) l=99; memcpy(buff, lowKeyword, l); buff[l] = '\0'; zSyslog._log(CSyslog::LOGL_PARSE, CSyslog::LOGC_INDEXING, "%s(%d) unknown kword('%s') for lng='%s'\n", __FILE__, __LINE__, buff, lng); } // new keyword if( (k = new CKword(lowKeyword, lowKeywordLen, lng, lngLen)) != NULL) { k->next = indexer->tKeywords[hash]; indexer->tKeywords[hash] = k; indexer->nNewKeywords++; } } if(k) { CHit *h; if( (h = new CHit(record_id, pos, len, index, currentField->business)) != NULL) { h->pxpath = indexer->current_xpath; h->next = k->firsthit; k->firsthit = h; } } } // ------------------------------------------------------------------------ // callback called by scanRecords, for each record // ------------------------------------------------------------------------ void callbackRecord(CConnbas_dbox *connbas, unsigned int record_id, char *xml, unsigned long len) { extern int arg_flush; CIndexer *indexer = (CIndexer *)(connbas->userData); zSyslog._log(CSyslog::LOGL_RECORD, CSyslog::LOGC_INDEXING, "#%ld : Indexing recordid=%d", connbas->sbas_id, record_id); // create a xml parser if( (indexer->xmlparser = new CDOMDocument()) ) { // we reload the thesaurus loadThesaurus(indexer); // let's flag the record as 'indexing' (status bit 2 to '0') // indexer->connbas->updateRecord_lock(record_id); if( CRecord *record = new CRecord ) { record->id = record_id; record->next = indexer->tRecord; indexer->tRecord = record; } // tell the indexer who to call when it parses a word in the xml indexer->xmlparser->userData = (void *)indexer; indexer->xmlparser->onKeyword = evt_keyword; indexer->xmlparser->onStart = evt_start; indexer->xmlparser->onEnd = NULL; // it's the opening tag who decides if a close callback is needed (if field with type or thesaurus) indexer->current_rid = record_id; // mark each field as not found before indexing for(int i=0; i<indexer->nStructFields; i++) indexer->tStructField[i].found = false; // load and parse in one shot indexer->xmlparser->loadXML(xml, len); // fix unfound fields with a default value if(arg_forcedefault == 'A' || arg_forcedefault == 'Z') { for(int i=0; i<indexer->nStructFields; i++) { if(!indexer->tStructField[i].found && indexer->tStructField[i].type != CStructField::TYPE_NONE) { CProp *prop; switch(indexer->tStructField[i].type) { case CStructField::TYPE_DATE: prop = new CProp(arg_forcedefault=='A' ? "00000000000000" : "99999999999999"); break; case CStructField::TYPE_FLOAT: prop = new CProp(arg_forcedefault=='A' ? "0" : "99999999999999"); break; case CStructField::TYPE_INT: prop = new CProp(arg_forcedefault=='A' ? "0" : "99999999999999"); break; case CStructField::TYPE_TEXT: prop = new CProp(arg_forcedefault=='A' ? "" : "ZZZZZZZZZZZZZZ"); break; } if( prop ) { prop->type = indexer->tStructField[i].type; prop->record_id = indexer->current_rid; // prop->pxpath = NULL; prop->pfield = indexer->tStructField + i; prop->business = indexer->tStructField[i].business; prop->next = indexer->firstProp; indexer->firstProp = prop; } } } } indexer->nrecsInBuff++; if(indexer->nrecsInBuff >= arg_flush) // flush infos every n records { indexer->flush(); indexer->nrecsInBuff = 0; } // destroy the parser delete indexer->xmlparser; // flag the record as 'indexed' (status bit 2 to '1') // indexer->connbas->updateRecord_unlock(record_id); // not now ! flush will do the job } }
#include <cppunit/extensions/HelperMacros.h> #include <Poco/Exception.h> #include "cppunit/BetterAssert.h" #include "model/RefreshTime.h" using namespace std; using namespace Poco; namespace BeeeOn { class RefreshTimeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RefreshTimeTest); CPPUNIT_TEST(testNone); CPPUNIT_TEST(testDisabled); CPPUNIT_TEST(testFromSeconds); CPPUNIT_TEST(testFromMinutes); CPPUNIT_TEST(testParse); CPPUNIT_TEST(testToString); CPPUNIT_TEST(testCompare); CPPUNIT_TEST_SUITE_END(); public: void testNone(); void testDisabled(); void testFromSeconds(); void testFromMinutes(); void testParse(); void testToString(); void testCompare(); }; CPPUNIT_TEST_SUITE_REGISTRATION(RefreshTimeTest); void RefreshTimeTest::testNone() { CPPUNIT_ASSERT(RefreshTime::NONE.isNone()); CPPUNIT_ASSERT(!RefreshTime::NONE.isDisabled()); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::NONE); CPPUNIT_ASSERT_EQUAL(-1, RefreshTime::NONE.seconds()); } void RefreshTimeTest::testDisabled() { CPPUNIT_ASSERT(RefreshTime::DISABLED.isDisabled()); CPPUNIT_ASSERT(!RefreshTime::DISABLED.isNone()); CPPUNIT_ASSERT_EQUAL(RefreshTime::DISABLED, RefreshTime::DISABLED); CPPUNIT_ASSERT_EQUAL(0, RefreshTime::DISABLED.seconds()); } void RefreshTimeTest::testFromSeconds() { CPPUNIT_ASSERT_EQUAL(RefreshTime::DISABLED, RefreshTime::fromSeconds(0)); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::fromSeconds(-1)); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::fromSeconds(-454123)); CPPUNIT_ASSERT_EQUAL( -1, RefreshTime::fromSeconds(-1).seconds()); CPPUNIT_ASSERT_EQUAL( -1, RefreshTime::fromSeconds(-90732).seconds()); CPPUNIT_ASSERT_EQUAL( 0, RefreshTime::fromSeconds(0).seconds()); CPPUNIT_ASSERT_EQUAL( 1, RefreshTime::fromSeconds(1).seconds()); CPPUNIT_ASSERT_EQUAL( 5, RefreshTime::fromSeconds(5).seconds()); CPPUNIT_ASSERT_EQUAL( 10, RefreshTime::fromSeconds(10).seconds()); CPPUNIT_ASSERT_EQUAL( 15, RefreshTime::fromSeconds(15).seconds()); CPPUNIT_ASSERT_EQUAL( 60, RefreshTime::fromSeconds(60).seconds()); CPPUNIT_ASSERT_EQUAL(1000, RefreshTime::fromSeconds(1000).seconds()); } void RefreshTimeTest::testFromMinutes() { CPPUNIT_ASSERT_EQUAL(RefreshTime::DISABLED, RefreshTime::fromMinutes(0)); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::fromMinutes(-1)); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::fromMinutes(-454123)); CPPUNIT_ASSERT_EQUAL( -1, RefreshTime::fromMinutes(-1).seconds()); CPPUNIT_ASSERT_EQUAL( -1, RefreshTime::fromMinutes(-90732).seconds()); CPPUNIT_ASSERT_EQUAL( 0, RefreshTime::fromMinutes(0).seconds()); CPPUNIT_ASSERT_EQUAL( 60, RefreshTime::fromMinutes(1).seconds()); CPPUNIT_ASSERT_EQUAL( 300, RefreshTime::fromMinutes(5).seconds()); CPPUNIT_ASSERT_EQUAL( 600, RefreshTime::fromMinutes(10).seconds()); CPPUNIT_ASSERT_EQUAL( 900, RefreshTime::fromMinutes(15).seconds()); CPPUNIT_ASSERT_EQUAL(3600, RefreshTime::fromMinutes(60).seconds()); } void RefreshTimeTest::testParse() { CPPUNIT_ASSERT_EQUAL(RefreshTime::DISABLED, RefreshTime::parse("disabled")); CPPUNIT_ASSERT_EQUAL(RefreshTime::DISABLED, RefreshTime::parse("0")); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::parse("none")); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::parse("-1")); CPPUNIT_ASSERT_EQUAL(RefreshTime::NONE, RefreshTime::parse("-10123")); CPPUNIT_ASSERT_EQUAL( -1, RefreshTime::parse("-1").seconds()); CPPUNIT_ASSERT_EQUAL( -1, RefreshTime::parse("-39863").seconds()); CPPUNIT_ASSERT_EQUAL( 0, RefreshTime::parse("0").seconds()); CPPUNIT_ASSERT_EQUAL( 1, RefreshTime::parse("1").seconds()); CPPUNIT_ASSERT_EQUAL( 5, RefreshTime::parse("5").seconds()); CPPUNIT_ASSERT_EQUAL(1000, RefreshTime::parse("1000").seconds()); } void RefreshTimeTest::testToString() { CPPUNIT_ASSERT_EQUAL("none", RefreshTime::NONE.toString()); CPPUNIT_ASSERT_EQUAL("disabled", RefreshTime::DISABLED.toString()); CPPUNIT_ASSERT_EQUAL("none", RefreshTime::fromSeconds(-1).toString()); CPPUNIT_ASSERT_EQUAL("disabled", RefreshTime::fromSeconds(0).toString()); CPPUNIT_ASSERT_EQUAL("1", RefreshTime::fromSeconds(1).toString()); CPPUNIT_ASSERT_EQUAL("156", RefreshTime::fromSeconds(156).toString()); CPPUNIT_ASSERT_EQUAL("18098", RefreshTime::fromSeconds(18098).toString()); } void RefreshTimeTest::testCompare() { CPPUNIT_ASSERT(RefreshTime::NONE <= RefreshTime::NONE); CPPUNIT_ASSERT(RefreshTime::NONE >= RefreshTime::NONE); CPPUNIT_ASSERT(RefreshTime::DISABLED <= RefreshTime::DISABLED); CPPUNIT_ASSERT(RefreshTime::DISABLED >= RefreshTime::DISABLED); CPPUNIT_ASSERT(RefreshTime::fromSeconds(10) <= RefreshTime::fromSeconds(10)); CPPUNIT_ASSERT(RefreshTime::fromSeconds(10) >= RefreshTime::fromSeconds(10)); CPPUNIT_ASSERT(RefreshTime::NONE < RefreshTime::DISABLED); CPPUNIT_ASSERT(RefreshTime::NONE <= RefreshTime::DISABLED); CPPUNIT_ASSERT(RefreshTime::DISABLED > RefreshTime::NONE); CPPUNIT_ASSERT(RefreshTime::DISABLED >= RefreshTime::NONE); CPPUNIT_ASSERT(RefreshTime::NONE < RefreshTime::fromSeconds(1)); CPPUNIT_ASSERT(RefreshTime::NONE <= RefreshTime::fromSeconds(1)); CPPUNIT_ASSERT(RefreshTime::fromSeconds(1) > RefreshTime::NONE); CPPUNIT_ASSERT(RefreshTime::fromSeconds(1) >= RefreshTime::NONE); CPPUNIT_ASSERT(RefreshTime::DISABLED < RefreshTime::fromSeconds(1)); CPPUNIT_ASSERT(RefreshTime::DISABLED <= RefreshTime::fromSeconds(1)); CPPUNIT_ASSERT(RefreshTime::fromSeconds(1) > RefreshTime::DISABLED); CPPUNIT_ASSERT(RefreshTime::fromSeconds(1) >= RefreshTime::DISABLED); CPPUNIT_ASSERT(RefreshTime::fromSeconds(1) < RefreshTime::fromSeconds(10)); CPPUNIT_ASSERT(RefreshTime::fromSeconds(1) <= RefreshTime::fromSeconds(10)); CPPUNIT_ASSERT(RefreshTime::fromSeconds(10) > RefreshTime::fromSeconds(1)); CPPUNIT_ASSERT(RefreshTime::fromSeconds(10) >= RefreshTime::fromSeconds(1)); } }
#include "stdafx.h" #include "AbsShaderCreator.h" void AbsShaderCreator::SetNext(shared_ptr<AbsShaderCreator> next) { NextShader = next; } HRESULT AbsShaderCreator::CreateShader(ComPtr<ID3D11Device> d3dDevice, string type, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage) { if (ShaderType != type) { return ToNext(d3dDevice, type, pShaderBytecode, BytecodeLength, pClassLinkage); } IsCreated = true; return Handle(d3dDevice, pShaderBytecode, BytecodeLength, pClassLinkage); } void AbsShaderCreator::SetPiplineShader(ComPtr<ID3D11DeviceContext> d3dContext, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) { Handle(d3dContext, IsCreated ? Shader.Get() : nullptr, ppClassInstances, NumClassInstances); ToNext(d3dContext, ppClassInstances, NumClassInstances); } HRESULT AbsShaderCreator::ToNext(ComPtr<ID3D11Device> d3dDevice, string type, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage) { if (NextShader.get()) { return NextShader->CreateShader(d3dDevice, type, pShaderBytecode, BytecodeLength, pClassLinkage); } return E_INVALIDARG; } void AbsShaderCreator::ToNext(ComPtr<ID3D11DeviceContext> d3dContext, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) { if (NextShader.get()) { NextShader->SetPiplineShader(d3dContext, ppClassInstances, NumClassInstances); } }
#include <bits/stdc++.h> using namespace std; #define ll long long int int status[3700005]; vector<int>prms; int main() { ll n,i,si,j; si=int(sqrt((double)n+1)); for(i=2; i<=3600000; i++) { if(status[i]==0) { prms.push_back(i); for(j=i; j<=3600000; j+=i) { status[j]++; } } } //for(int i=1;i<=30;i++) // cout<<status[i]<<endl; while(cin>>n) { ll nc = n; int prmfact = 0; int fpf = 1; int cnt = 0; for(int i=0; i<prms.size(); i++) { while(n%prms[i]==0) { prmfact++; n/=prms[i]; if(cnt<2) { cnt++; fpf *= prms[i]; } } } if(n!=1) prmfact++; if(nc==1) { printf("1\n0\n"); } else if(prmfact==1) { printf("1\n0\n"); } else if(prmfact==2) { printf("2\n"); } else { printf("1\n%d\n",fpf); } } return 0; }
#include <mesh.h> #include <vector> #include <algorithm> Mesh::Mesh() {} Mesh::Mesh(Vertex* vertices, unsigned int numVertices) { m_drawcount = numVertices; glGenVertexArrays(1, &m_vertexArrayObject); glBindVertexArray(m_vertexArrayObject); std::vector<glm::vec3> positions; std::vector<glm::vec2> texCoords; std::vector<glm::vec3> normals; std::vector<unsigned int> index; for (unsigned int i = 0; i < m_drawcount; i++) { positions.push_back(vertices[i].GetPos()); texCoords.push_back(vertices[i].GetTexCoord()); normals.push_back(glm::vec3(0,0,0)); } glm::vec3 v1 = positions[1] - positions[0]; glm::vec3 v2 = positions[2] - positions[0]; glm::vec3 norm1 = glm::normalize(glm::cross(v1,v2)); glm::vec3 v3 = positions[0] - positions[1]; glm::vec3 v4 = positions[3] - positions[1]; glm::vec3 norm2 = glm::normalize(glm::cross(v3,v4)); glm::vec3 v5 = positions[0] - positions[2]; glm::vec3 v6 = positions[3] - positions[2]; glm::vec3 norm3 = glm::normalize(glm::cross(v5,v6)); glm::vec3 v7 = positions[2] - positions[3]; glm::vec3 v8 = positions[1] - positions[3]; glm::vec3 norm4 = glm::normalize(glm::cross(v7, v8)); normals[0] += norm1; normals[1] += norm2; normals[2] += norm3; normals[3] += norm4; for(unsigned int i = 0; i < positions.size(); i++) normals[i] = glm::normalize(normals[i]); positions.reserve(numVertices); texCoords.reserve(numVertices); normals.reserve(numVertices); glGenBuffers(NUM_BUFFERS, &m_vertexArrayBuffers[0]); // set GL buffers for vertex positions. glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[POSITION_VB]); glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(vertices[0]), &vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(POSITION_VB); glVertexAttribPointer(POSITION_VB, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), 0); // set GL buffers for texture coordinates. glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[TEXCOORD_VB]); glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(texCoords[0]), &texCoords[0], GL_STATIC_DRAW); glEnableVertexAttribArray(TEXCOORD_VB); glVertexAttribPointer(TEXCOORD_VB, 2, GL_FLOAT, GL_FALSE, 0, 0); // set Gl buffers for vertex normals glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[NORMALS_VB]); glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(normals[0]), &normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(NORMALS_VB); glVertexAttribPointer(NORMALS_VB, 3, GL_FLOAT, GL_FALSE, 0, 0); } Mesh::~Mesh() { glDeleteVertexArrays(1, &m_vertexArrayObject); } void Mesh::Draw() { glBindVertexArray(m_vertexArrayObject); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); }
/* -*-C++-*- */ /* * Copyright 2016 EU Project ASAP 619706. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This code is based on code from Pheonix++, license below applies. */ /* Copyright (c) 2007-2011, Stanford University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Stanford University nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <vector> #include <algorithm> #include <iostream> #include <memory> #ifdef P2_UNORDERED_MAP #include "p2_unordered_map.h" #endif // P2_UNORDERED_MAP #if SEQUENTIAL && PMC #include <likwid.h> #endif #if !SEQUENTIAL #include <cilk/cilk.h> #include <cilk/reducer.h> #include <cilk/reducer_opadd.h> // #include "cilkpub/sort.h" #else #define cilk_sync #define cilk_spawn #define cilk_for for #endif #if TRACING #include "tracing/events.h" #include "tracing/events.cc" #define TRACE(e) event_tracer::get().record( event_tracer::e, 0, 0 ) #else #define TRACE(e) do { } while( 0 ) #endif #include "stddefines.h" #include <tuple> #include <map> #include <set> #include <fstream> #include <math.h> #include <sys/types.h> #include <dirent.h> #include <errno.h> // kmeans merged header section start #include <stdlib.h> #include <cilk/cilk_api.h> #include <cerrno> #include <cmath> #include <limits> #include <cassert> #define DEF_NUM_POINTS 100000 #define DEF_NUM_MEANS 100 #define DEF_DIM 3 #define DEF_GRID_SIZE 1000 #define DEF_NUM_THREADS 8 #define REAL_IS_INT 0 typedef float real; int num_points; // number of vectors int num_dimensions; // Dimension of each vector int num_clusters; // number of clusters // bool force_dense; // force a (slower) dense calculation bool kmeans_workflow = false; bool tfidf_unit = true; int max_iters; // maximum number of iterations real * min_val; // min value of each dimension of vector space real * max_val; // max value of each dimension of vector space const char * fname= NULL; // input file #define CROAK(x) croak(x,__FILE__,__LINE__) // kmeans merged header sections end // a passage from the text. The input data to the Map-Reduce struct wc_string { char* data; uint64_t len; }; // a single null-terminated word struct wc_word { char* data; wc_word(char * d = 0) : data( d ) { } // necessary functions to use this as a key bool operator<(wc_word const& other) const { return strcmp(data, other.data) < 0; } bool operator==(wc_word const& other) const { return strcmp(data, other.data) == 0; } }; // a hash for the word struct wc_word_hash { // FNV-1a hash for 64 bits size_t operator()(wc_word const& key) const { char* h = key.data; uint64_t v = 14695981039346656037ULL; while (*h != 0) v = (v ^ (size_t)(*(h++))) * 1099511628211ULL; return v; } }; struct wc_word_pred { bool operator() ( const wc_word & a, const wc_word & b ) const { return !strcmp( a.data, b.data ); } }; struct wc_sort_pred_by_first { bool operator() ( const std::pair<wc_word, size_t> & a, const std::pair<wc_word, size_t> & b ) const { return a.first < b.first; } }; struct wc_sort_pred { bool operator() ( const std::pair<wc_word, size_t> & a, const std::pair<wc_word, size_t> & b ) const { return a.second > b.second || (a.second == b.second && strcmp( a.first.data, b.first.data ) > 0); } }; struct wc_merge_pred { bool operator() ( const std::pair<wc_word, size_t> & a, const std::pair<wc_word, size_t> & b ) const { return strcmp( a.first.data, b.first.data ) < 0; } }; // Use inheritance for convenience, should use encapsulation. static size_t nfiles = 0; class fileVector : public std::vector<size_t> { public: fileVector() : std::vector<size_t>( nfiles, 0 ) { } }; #ifdef P2_UNORDERED_MAP typedef std::p2_unordered_map<wc_word, size_t, wc_word_hash, wc_word_pred> wc_unordered_map; #elif defined(STD_UNORDERED_MAP) #include <unordered_map> typedef std::unordered_map<wc_word, fileVector, wc_word_hash, wc_word_pred> wc_unordered_map; #elif defined(PHOENIX_MAP) #include "container.h" typedef hash_table<wc_word, fileVector, wc_word_hash> wc_unordered_map; #else #include "container.h" typedef hash_table_stored_hash<wc_word, fileVector, wc_word_hash> wc_unordered_map; #endif // P2_UNORDERED_MAP #if !SEQUENTIAL void merge_two_dicts( wc_unordered_map & m1, wc_unordered_map & m2 ) { for( auto I=m2.cbegin(), E=m2.cend(); I != E; ++I ) { std::vector<size_t> & counts1 = m1[I->first]; const std::vector<size_t> & counts2 = I->second; // Vectorized size_t * v1 = &counts1.front(); const size_t * v2 = &counts2.front(); v1[0:nfiles] += v2[0:nfiles]; } m2.clear(); } class dictionary_reducer { struct Monoid : cilk::monoid_base<wc_unordered_map> { static void reduce( wc_unordered_map * left, wc_unordered_map * right ) { TRACE( e_sreduce ); merge_two_dicts( *left, *right ); TRACE( e_ereduce ); } static void identity( wc_unordered_map * p ) { // Initialize to useful default size depending on chunk size new (p) wc_unordered_map( 1<<16); } }; private: cilk::reducer<Monoid> imp_; public: dictionary_reducer() : imp_() { } void swap( wc_unordered_map & c ) { imp_.view().swap( c ); } fileVector & operator []( wc_word idx ) { return imp_.view()[idx]; } size_t empty() const { return imp_.view().size() == 0; } size_t size() const { return imp_.view().size(); } typename wc_unordered_map::iterator begin() { return imp_.view().begin(); } // typename wc_unordered_map::const_iterator cbegin() { return imp_.view().cbegin(); } typename wc_unordered_map::iterator end() { return imp_.view().end(); } // typename wc_unordered_map::const_iterator cend() { return imp_.view().cend(); } #if defined(STD_UNORDERED_MAP) wc_unordered_map::hasher hash_function() { return imp_.view().hash_function(); } #endif }; #else typedef wc_unordered_map dictionary_reducer; #endif // kmeans merged declarations sections end inline void __attribute__((noreturn)) croak( const char * msg, const char * srcfile, unsigned lineno ) { const char * es = strerror( errno ); std::cerr << srcfile << ':' << lineno << ": " << msg << ": " << es << std::endl; exit( 1 ); } struct point; struct sparse_point { int * c; real * v; int nonzeros; int cluster; sparse_point() { c = NULL; v = NULL; nonzeros = 0; cluster = -1; } sparse_point(int *c, real* d, int nz, int cluster) : c(c), v(v), nonzeros(nz), cluster(cluster) { } sparse_point(const point&pt); bool normalize() { if( cluster == 0 ) { std::cerr << "empty cluster...\n"; return true; } else { #if VECTORIZED v[0:nonzeros] /= (real)cluster; #else for(int i = 0; i < nonzeros; ++i) v[i] /= (real)cluster; #endif return false; } } void clear() { #if VECTORIZED c[0:nonzeros] = (int)0; v[0:nonzeros] = (real)0; #else for(int i = 0; i < nonzeros; ++i) { c[i] = (int)0; v[i] = (real)0; } #endif } real sq_dist(point const& p) const; bool equal(point const& p) const; void dump() const { for(int j = 0; j < nonzeros; j++) { #if REAL_IS_INT printf("%d: %5ld ", (int)c[j], (long)v[j]); #else printf("%d: %6.4f ", (int)c[j], (double)v[j]); #endif } printf("\n"); } }; struct point { real * d; int cluster; point() { d = NULL; cluster = -1; } point(real* d, int cluster) { this->d = d; this->cluster = cluster; } bool normalize() { if( cluster == 0 ) { std::cerr << "empty cluster...\n"; return true; } else { #if VECTORIZED d[0:num_dimensions] /= (real)cluster; #else for(int i = 0; i < num_dimensions; ++i) d[i] /= (real)cluster; #endif return false; } } void clear() { #if VECTORIZED d[0:num_dimensions] = (real)0; #else for(int i = 0; i < num_dimensions; ++i) d[i] = (real)0; #endif } #if VECTORIZED static unsigned real esqd( real a, real b ) { real diff = a - b; need to adjust ... return diff * diff; } real sq_dist(point const& p) const { return __sec_reduce_add( esqd( d[0:num_dimensions], p.d[0:num_dimensions] ) ); } #else real sq_dist(point const& p) const { real sum = 0; for (int i = 0; i < num_dimensions; i++) { real diff = d[i] - p.d[i]; // if( diff < (real)0 ) // diff = -diff; // diff = (diff - min_val[i]) / (max_val[i] - min_val[i] + 1); sum += diff * diff; } return sum; } #endif void dump() const { for(int j = 0; j < num_dimensions; j++) { #if REAL_IS_INT printf("%5ld ", (long)d[j]); #else printf("%6.4f ", (double)d[j]); #endif } printf("\n"); } // For reduction of centre computations const point & operator += ( const point & pt ) { #if VECTORIZED d[0:num_dimensions] += pt.d[0:num_dimensions]; #else for(int j = 0; j < num_dimensions; j++) d[j] += pt.d[j]; #endif cluster += pt.cluster; return *this; } const point & operator += ( const sparse_point & pt ) { // #if VECTORIZED // d[0:num_dimensions] += pt.d[0:num_dimensions]; // #else for(int j = 0; j < pt.nonzeros; j++) d[pt.c[j]] += pt.v[j]; // #endif cluster += pt.cluster; return *this; } }; typedef struct point Point; sparse_point::sparse_point(const point&pt) { nonzeros=0; for( int i=0; i < num_dimensions; ++i ) if( pt.d[i] != (real)0 ) ++nonzeros; c = new int[nonzeros]; v = new real[nonzeros]; int k=0; for( int i=0; i < num_dimensions; ++i ) if( pt.d[i] != (real)0 ) { c[k] = i; v[k] = pt.d[i]; ++k; } assert( k == nonzeros ); } real sparse_point::sq_dist(point const& p) const { real sum = 0; for (int i = 0; i < nonzeros; i++) { real diff = v[i] - p.d[c[i]]; sum += diff * diff; } return sum; } bool sparse_point::equal(point const& p) const { int k=0; for( int i=0; i < nonzeros; ++i ) { while( k < c[i] ) { if( p.d[k++] != (real)0 ) return false; } if( p.d[k++] != v[i] ) return false; } while( k < num_dimensions ) { if( p.d[k++] != (real)0 ) return false; } return true; } class Centres { Point * centres; real * data; public: Centres() { // Allocate backing store and initalize to zero data = new real[num_clusters * num_dimensions](); centres = new Point[num_clusters]; for( int c=0; c < num_clusters; ++c ) { centres[c] = Point( &data[c*num_dimensions], 0 ); centres[c].cluster = 0; } } ~Centres() { delete[] centres; delete[] data; } void clear() { for( int c=0; c < num_clusters; ++c ) { centres[c].clear(); centres[c].cluster = 0; } } void add_point( Point * pt ) { int c = pt->cluster; for( int i=0; i < num_dimensions; ++i ) centres[c].d[i] += pt->d[i]; centres[c].cluster++; } void add_point( sparse_point * pt ) { int c = pt->cluster; for( int i=0; i < pt->nonzeros; ++i ) centres[c].d[pt->c[i]] += pt->v[i]; centres[c].cluster++; } void normalize( int c ) { centres[c].normalize(); } bool normalize() { bool modified = false; cilk_for( int c=0; c < num_clusters; ++c ) modified |= centres[c].normalize(); return modified; } void select( const point * pts ) { for( int c=0; c < num_clusters; ) { int pi = rand() % num_points; // Check if we already have this point (may have duplicates) bool incl = false; for( int k=0; k < c; ++k ) { if( memcmp( centres[k].d, pts[pi].d, sizeof(real) * num_dimensions ) ) { incl = true; break; } } if( !incl ) { for( int i=0; i < num_dimensions; ++i ) centres[c].d[i] = pts[pi].d[i]; ++c; } } } void select( const sparse_point * pts ) { for( int c=0; c < num_clusters; ) { int pi = rand() % num_points; // Check if we already have this point (may have duplicates) bool incl = false; for( int k=0; k < c; ++k ) { if( pts[pi].equal( centres[k] ) ) { incl = true; break; } } if( !incl ) { centres[c].clear(); for( int i=0; i < pts[pi].nonzeros; ++i ) centres[c].d[pts[pi].c[i]] = pts[pi].v[i]; ++c; } } } const Point & operator[] ( int c ) const { return centres[c]; } void reduce( Centres * cc ) { for( int c=0; c < num_clusters; ++c ) centres[c] += cc->centres[c]; } void swap( Centres & c ) { std::swap( data, c.data ); std::swap( centres, c.centres ); } }; #if !SEQUENTIAL class centres_reducer { struct Monoid : cilk::monoid_base<Centres> { static void reduce( Centres * left, Centres * right ) { #if TRACING event_tracer::get().record( event_tracer::e_sreduce, 0, 0 ); #endif left->reduce( right ); #if TRACING event_tracer::get().record( event_tracer::e_ereduce, 0, 0 ); #endif } }; private: cilk::reducer<Monoid> imp_; public: centres_reducer() : imp_() { } const Point & operator[] ( int c ) const { return imp_.view()[c]; } void swap( Centres & c ) { imp_.view().swap( c ); } void add_point( Point * pt ) { imp_.view().add_point( pt ); } void add_point( sparse_point * pt ) { imp_.view().add_point( pt ); } }; #else typedef Centres centres_reducer; #endif // kmeans merged declarations sections end void wc( char * data, uint64_t data_size, uint64_t chunk_size, dictionary_reducer & dict, unsigned int file) { uint64_t splitter_pos = 0; while( 1 ) { TRACE( e_ssplit ); /* End of data reached, return FALSE. */ if ((uint64_t)splitter_pos >= data_size) { TRACE( e_esplit ); break; } /* Determine the nominal end point. */ uint64_t end = std::min(splitter_pos + chunk_size, data_size); /* Move end point to next word break */ while(end < data_size && data[end] != ' ' && data[end] != '\t' && data[end] != '\r' && data[end] != '\n') end++; if( end < data_size ) data[end] = '\0'; /* Set the start of the next data. */ wc_string s; s.data = data + splitter_pos; s.len = end - splitter_pos; splitter_pos = end; TRACE( e_esplit ); /* Continue with map since the s data is valid. */ cilk_spawn [&] (wc_string s) { TRACE( e_smap ); // TODO: is it better for locatiy to move toupper() into the inner loop? for (uint64_t i = 0; i < s.len; i++) s.data[i] = toupper(s.data[i]); uint64_t i = 0; uint64_t start; wc_word word = { s.data+start }; while(i < s.len) { while(i < s.len && (s.data[i] < 'A' || s.data[i] > 'Z')) i++; start = i; /* and can we also vectorize toupper? while( i < s.len ) { s.data[i] = toupper(s.data[i]); if(((s.data[i] >= 'A' && s.data[i] <= 'Z') || s.data[i] == '\'')) i++; else break; } */ // while(i < s.len && ((s.data[i] >= 'A' && s.data[i] <= 'Z') || s.data[i] == '\'')) while(i < s.len && ((s.data[i] >= 'A' && s.data[i] <= 'Z') )) i++; if(i > start) { s.data[i] = 0; word = { s.data+start }; dict[word][file]++; } } TRACE( e_emap ); }( s ); } cilk_sync; TRACE( e_synced ); // std::cout << "final hash table size=" << final_dict.bucket_count() << std::endl; } #define NO_MMAP // vim: ts=8 sw=4 sts=4 smarttab smartindent using namespace std; int getdir (std::string dir, std::vector<std::string> &files) { DIR *dp; struct dirent *dirp; if((dp = opendir(dir.c_str())) == NULL) { std::cerr << "Error(" << errno << ") opening " << dir << std::endl; return errno; } while ((dirp = readdir(dp)) != NULL) { std::string relFilePath=dir + "/" + dirp->d_name; struct stat buf; if( lstat(relFilePath.c_str(), &buf) < 0 ) { std::cerr << "Error(" << errno << ") lstat " << relFilePath << std::endl; return errno; } if (S_ISREG(buf.st_mode)) files.push_back(relFilePath); } closedir(dp); return 0; } #include <unordered_map> size_t is_nonzero( size_t s ) { return s != 0; } // kmeans merged reading sections start template<typename DSPoint> int kmeans_cluster(Centres & centres, DSPoint * points) { int modified = 0; centres_reducer new_centres; #if GRANULARITY int nmap = std::min(num_points, 16) * 16; int g = std::max(1, (int)((double)(num_points+nmap-1) / nmap)); #pragma cilk grainsize = g cilk_for(int i = 0; i < num_points; i++) { #else cilk_for(int i = 0; i < num_points; i++) { #endif #if TRACING event_tracer::get().record( event_tracer::e_smap, 0, 0 ); #endif //assign points to cluster real smallest_distance = std::numeric_limits<real>::max(); int new_cluster_id = -1; for(int j = 0; j < num_clusters; j++) { //assign point to cluster with smallest total squared difference (for all d dimensions) real total_distance = points[i].sq_dist(centres[j]); if(total_distance < smallest_distance) { smallest_distance = total_distance; new_cluster_id = j; } } //if new cluster then update modified flag if(new_cluster_id != points[i].cluster) { // benign race; works well. Alternative: reduction(|: modified) modified = 1; points[i].cluster = new_cluster_id; } new_centres.add_point( &points[i] ); #if TRACING event_tracer::get().record( event_tracer::e_emap, 0, 0 ); #endif } #if TRACING event_tracer::get().record( event_tracer::e_synced, 0, 0 ); #endif /* cilk_for(int i = 0; i < num_clusters; i++) { if( new_centres[i].cluster == 0 ) { cilk_for(int j = 0; j < num_dimensions; j++) { new_centres[i].d[j] = centres[i].d[j]; } } } */ // for(int i = 0; i < num_clusters; i++) { // std::cout << "in cluster " << i << " " << new_centres[i].cluster << " points\n"; // } new_centres.swap( centres ); centres.normalize(); return modified; } void parse_args(int argc, char **argv) { int c; extern char *optarg; // num_points = DEF_NUM_POINTS; num_clusters = DEF_NUM_MEANS; max_iters = 0; // num_dimensions = DEF_DIM; // grid_size = DEF_GRID_SIZE; while ((c = getopt(argc, argv, "c:i:m:d:")) != EOF) { switch (c) { // case 'd': // num_dimensions = atoi(optarg); // break; // case 'd': // force_dense = true; // break; case 'd': fname = optarg; break; case 'm': max_iters = atoi(optarg); break; case 'c': num_clusters = atoi(optarg); break; case 'k': kmeans_workflow = true; break; case 'u': tfidf_unit = true; break; // case 'p': // num_points = atoi(optarg); // break; // case 's': // grid_size = atoi(optarg); // break; case '?': printf("Usage: %s -d <vector dimension> -c <num clusters> -p <num points> -s <max value> -t <number of threads>\n", argv[0]); exit(1); } } // Make sure a filename is specified if( !fname ) { printf("USAGE: %s -d <directory name> [-c]\n", argv[0]); exit(1); } if( num_clusters <= 0 ) CROAK( "Number of clusters must be larger than 0." ); if( !fname ) CROAK( "Input file must be supplied." ); std::cerr << "Number of clusters = " << num_clusters << '\n'; std::cerr << "Input file = " << fname << '\n'; } struct arff_file { std::vector<const char *> idx; std::vector<Point> points; char * fdata; char * relation; real * minval, * maxval; bool sparse_data; public: arff_file() : sparse_data(false) { } }; #if 0 TODELETE khere void read_sparse_file( const char * fname ) { struct stat finfo; int fd; if( (fd = open( fname, O_RDONLY )) < 0 ) CROAK( fname ); if( fstat( fd, &finfo ) < 0 ) CROAK( "fstat" ); uint64_t r = 0; fdata = new char[finfo.st_size+1]; while( r < (uint64_t)finfo.st_size ) r += pread( fd, fdata + r, finfo.st_size, r ); fdata[finfo.st_size] = '\0'; close( fd ); // Now parse the data char * p = fdata, * q; #define ADVANCE(pp) do { if( *(pp) == '\0' ) goto END_OF_FILE; ++pp; } while( 0 ) do { while( *p != '@' ) ADVANCE( p ); ADVANCE( p ); if( !strncasecmp( p, "relation ", 9 ) ) { p += 9; while( *p == ' ' ) ADVANCE( p ); relation = p; if( *p == '\'' ) { // scan until closing quote ADVANCE( p ); while( *p != '\'' ) ADVANCE( p ); ADVANCE( p ); ADVANCE( p ); *(p-1) = '\0'; } else { // scan until space while( !isspace( *p ) ) ADVANCE( p ); ADVANCE( p ); *(p-1) = '\0'; } } else if( !strncasecmp( p, "attribute ", 10 ) ) { p += 10; // Isolate token while( isspace( *p ) ) ADVANCE( p ); q = p; while( !isspace( *p ) ) ADVANCE( p ); ADVANCE( p ); *(p-1) = '\0'; // Isolate type while( isspace( *p ) ) ADVANCE( p ); char * t = p; while( !isspace( *p ) ) ADVANCE( p ); ADVANCE( p ); *(p-1) = '\0'; if( strcmp( t, "numeric" ) ) { std::cerr << "Warning: treating non-numeric attribute '" << q << "' of type '" << t << "' as numeric\n"; } idx.push_back( q ); } else if( !strncasecmp( p, "data", 4 ) ) { // From now on everything is data int ndim = idx.size(); p += 4; do { while( isspace(*p) ) ADVANCE( p ); bool is_sparse = *p == '{'; if( is_sparse ) { ADVANCE( p ); sparse_data = true; } real * coord = new real[ndim](); // zero init unsigned long nexti = 0; do { while( isspace( *p ) ) ADVANCE( p ); if( is_sparse ) { unsigned long i = strtoul( p, &p, 10 ); while( isspace( *p ) ) ADVANCE( p ); if( *p == '?' ) CROAK( "missing data not supported" ); real v = 0; #if REAL_IS_INT v = strtoul( p, &p, 10 ); #else v = strtod( p, &p ); #endif coord[i] = v; } else { while( isspace( *p ) ) ADVANCE( p ); if( *p == '?' ) CROAK( "missing data not supported" ); real v = 0; #if REAL_IS_INT v = strtoul( p, &p, 10 ); #else v = strtod( p, &p ); #endif coord[nexti++] = v; } while( isspace( *p ) && *p != '\n' ) ADVANCE( p ); if( *p == ',' ) ADVANCE( p ); } while( *p != '}' && *p != '\n' ); do { ADVANCE( p ); } while( isspace( *p ) ); points.push_back( point( coord, -1 ) ); } while( *p != '\0' ); } } while( 1 ); ENDOF TODELETE khere #endif // kmeans merged reading sections end int main(int argc, char *argv[]) { struct timespec begin, end, all_begin; std::vector<std::string> files; dictionary_reducer dict; get_time (begin); all_begin = begin; #if TRACING event_tracer::init(); #endif bool checkResults=false; int c; //read args parse_args(argc,argv); /* todelete khere while ( (c = getopt (argc, argv, "cd:")) != -1 ) switch (c) { case 'c': checkResults = 1; break; case 'd': fname = optarg; break; case '?': if (optopt == 'd') fprintf (stderr, "Option -%c requires a directory argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } // Make sure a filename is specified if( !fname ) { printf("USAGE: %s -d <directory name> [-c]\n", argv[0]); exit(1); } */ getdir(fname,files); nfiles = files.size(); char * fdata[files.size()]; struct stat finfo[files.size()]; int fd[files.size()]; get_time (end); #ifdef TIMING print_time("initialize", begin, end); #endif cilk_for (unsigned int i = 0;i < files.size();i++) { struct timespec beginI, endI, beginWC, endWC; get_time(beginI); // dict.setReserve(files.size()); // Read in the file fd[i] = open(files[i].c_str(), O_RDONLY); // Get the file info (for file length) fstat(fd[i], &finfo[i]); #ifndef NO_MMAP #ifdef MMAP_POPULATE // Memory map the file fdata[i] = (char*)mmap(0, finfo[i].st_size + 1, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd[i], 0); #else // Memory map the file fdata[i] = (char*)mmap(0, finfo[i].st_size + 1, PROT_READ, MAP_PRIVATE, fd[i], 0); #endif #else uint64_t r = 0; fdata[i] = (char *)malloc (finfo[i].st_size); while(r < (uint64_t)finfo[i].st_size) r += pread (fd[i], fdata[i] + r, finfo[i].st_size, r); #endif get_time (endI); #ifdef TIMING print_time("thread file-read", beginI, endI); #endif #ifndef NO_MMAP #ifdef MMAP_POPULATE #else #endif #else close(fd[i]); #endif get_time (beginWC); wc(fdata[i], finfo[i].st_size, 1024*1024, dict, i); get_time (endWC); #ifdef TIMING print_time("thread WC ", beginWC, endWC); #endif TRACE( e_smerge ); } arff_file arff_data; arff_data.relation = "tfidf"; // File initialisation string strFilename(fname); string arffTextFilename(strFilename + ".arff"); ofstream resFileTextArff; resFileTextArff.open(arffTextFilename, ios::out | ios::trunc ); get_time (begin); #define SS(str) (str), (sizeof((str))-1)/sizeof((str)[0]) #define XS(str) (str).c_str(), (str).size() #define ST(i) ((const char *)&(i)), sizeof((i)) // Char initialisations char nline='\n'; char space=' '; char tab='\t'; char comma=','; char colon=':'; char lbrace='{'; char rbrace='}'; char what; // // print out arff text format // string loopStart = "@attribute "; string typeStr = "numeric"; string dataStr = "@data"; string headerTextArff("@relation tfidf"); string classTextArff("@attribute @@class@@ {text}"); resFileTextArff << headerTextArff << "\n" << classTextArff << "\n";; resFileTextArff.flush(); long i=1; /* #ifdef STD_UNORDERED_MAP wc_unordered_map::hasher fn = dict.hash_function(); #endif */ for( auto I=dict.begin(), E=dict.end(); I != E; ++I ) { resFileTextArff << "\t"; const string & str = I->first.data; /* #ifndef STD_UNORDERED_MAP uint64_t id = I.getIndex(); #else uint64_t id = fn(I->first); #endif */ resFileTextArff << loopStart << str << " " << typeStr << "\n"; arff_data.idx.push_back(str.c_str()); // idMap[id]=i; i++; } resFileTextArff << "\n\n" << dataStr << "\n\n"; resFileTextArff.flush(); // // print the data // // in-memory workflow setup int ndim = dict.size(); real * coord = new real[ndim](); // zero init for (unsigned int i = 0;i < files.size();i++) { string & keyStr = files[i]; if( dict.empty() ) continue; resFileTextArff << "\t{"; // iterate over each word to collect total counts of each word in all files (reducedCount) // OR the number of files that contain the work (existsInFilesCount) long id=1; for( auto I=dict.begin(), E=dict.end(); I != E; ++I, ++id ) { size_t tf = I->second[i]; if (!tf) continue; // todo: workout how the best way to calculate and store each // word total once for all files #if 0 cilk::reducer< cilk::op_add<size_t> > existsInFilesCount(0); cilk_for (int j = 0; j < I->second.size(); ++j) { // *reducedCount += I->second[j]; // Use this if we want to count every occurence if (I->second[j] > 0) *existsInFilesCount += 1; } size_t fcount = existsInFilesCount.get_value(); #else const size_t * v = &I->second.front(); size_t len = I->second.size(); size_t fcount = __sec_reduce_add( is_nonzero(v[0:len]) ); #endif // Calculate tfidf --- Alternative versions of tfidf: // double tfidf = tf * log10(((double) files.size() + 1.0) / ((double) sumOccurencesOfWord + 1.0)); // double tfidf = tf * log10(((double) files.size() + 1.0) / ((double) numOfOtherDocsWithWord + 2.0)); // double tfidf = tf * log10(((double) files.size() + 1.0) / ((double) reducedCount.get_value() + 1.0)); // Sparks version; double tfidf = (double) tf * log10(((double) files.size() + 1.0) / ((double) fcount + 1.0)); /* #ifndef STD_UNORDERED_MAP uint64_t id = I.getIndex(); #else uint64_t id = fn(I->first); #endif */ coord[id] = tfidf; // Note: // If Weka etc doesn't care if there is an extra unnecessary comma at end // of a each record then we'd rather avoid the branch test here, so leave comma in resFileTextArff << id << ' ' << tfidf << ','; } resFileTextArff << "}\n"; } resFileTextArff.close(); if (kmeans_workflow) { arff_data.minval = new real[ndim]; arff_data.maxval = new real[ndim]; for( int i=0; i < ndim; ++i ) { arff_data.minval[i] = std::numeric_limits<real>::max(); arff_data.maxval[i] = std::numeric_limits<real>::min(); } cilk_for( int i=0; i < ndim; ++i ) { for( int j=0; j < arff_data.points.size(); ++j ) { real v = arff_data.points[j].d[i]; if( arff_data.minval[i] > v ) arff_data.minval[i] = v; if( arff_data.maxval[i] < v ) arff_data.maxval[i] = v; } for( int j=0; j < arff_data.points.size(); ++j ) { arff_data.points[j].d[i] = (arff_data.points[j].d[i] - arff_data.minval[i]) / (arff_data.maxval[i] - arff_data.minval[i]+1); } } // // From kmeans main, the rest of kmeans computation and output num_dimensions = arff_data.idx.size(); num_points = arff_data.points.size(); min_val = arff_data.minval; max_val = arff_data.maxval; // allocate memory // get points point * points = &arff_data.points[0]; // get means Centres centres; for( int i=0; i < num_points; ++i ) { points[i].cluster = rand() % num_clusters; centres.add_point( &points[i] ); } centres.normalize(); // for(int i = 0; i < num_clusters; i++) { // std::cout << "in cluster " << i << " " << centres[i].cluster << " points\n"; // } get_time (end); print_time("initialize", begin, end); printf("KMeans: Calling MapReduce Scheduler\n"); // keep re-clustering until means stabilise (no points are reassigned // to different clusters) #if SEQUENTIAL && PMC LIKWID_MARKER_START("mapreduce"); #endif // SEQUENTIAL && PMC get_time (begin); int niter = 1; if( arff_data.sparse_data /* && !force_dense */ ) { // First build sparse representation std::vector<sparse_point> spoints; spoints.reserve( num_points ); for( int i=0; i < num_points; ++i ) spoints.push_back( sparse_point( points[i] ) ); while(kmeans_cluster(centres, &spoints[0])) { if( ++niter >= max_iters && max_iters > 0 ) break; } for( int i=0; i < num_points; ++i ) { delete[] spoints[i].c; delete[] spoints[i].v; } } else { while(kmeans_cluster(centres, points)) { if( ++niter >= max_iters && max_iters > 0 ) break; } } get_time (end); #if SEQUENTIAL && PMC LIKWID_MARKER_STOP("mapreduce"); #endif // SEQUENTIAL && PMC print_time("library", begin, end); get_time (begin); //print means printf("KMeans: MapReduce Completed\n"); fprintf( stdout, "iterations: %d\n", niter ); real sse = 0; for( int i=0; i < num_points; ++i ) { sse += centres[points[i].cluster].sq_dist( points[i] ); } fprintf( stdout, "within cluster sum of squared errors: %11.4lf\n", sse ); fprintf( stdout, "%37s\n", "Cluster#" ); fprintf( stdout, "%-16s", "Attribute" ); fprintf( stdout, "%10s", "Full Data" ); for( int i=0; i < num_clusters; ++i ) fprintf( stdout, "%11d", i ); fprintf( stdout, "\n" ); char buf[32]; sprintf( buf, "(%d)", num_points ); fprintf( stdout, "%26s", buf ); for( int i=0; i < num_clusters; ++i ) { sprintf( buf, "(%d)", centres[i].cluster ); fprintf( stdout, "%11s", buf ); } fprintf( stdout, "\n" ); fprintf( stdout, "================" ); fprintf( stdout, "==========" ); for( int i=0; i < num_clusters; ++i ) fprintf( stdout, "===========" ); fprintf( stdout, "\n" ); for( int i=0; i < num_dimensions; ++i ) { fprintf( stdout, "%-16s", arff_data.idx[i] ); real s = 0; for( int j=0; j < num_points; ++j ) s += points[j].d[i]; s /= (real)num_points; s = min_val[i] + s * (max_val[i] - min_val[i] + 1); fprintf( stdout, "%10.4lf", s ); for( int k=0; k < num_clusters; ++k ) { real s = 0; for( int j=0; j < num_points; ++j ) if( points[j].cluster == k ) s += points[j].d[i]; s /= (real)centres[k].cluster; s = min_val[i] + s * (max_val[i] - min_val[i] + 1); fprintf( stdout, "%11.4lf", s ); } fprintf( stdout, "\n" ); } //free memory // delete[] points; -- done in arff_file // oops, not freeing points[i].d } get_time (end); #ifdef TIMING print_time("output", begin, end); print_time("complete time", all_begin, end); #endif get_time (end); #ifdef TIMING // print_time("finalize", begin, end); #endif #if TRACING event_tracer::destroy(); #endif for(int i = 0; i < files.size() ; ++i) { #ifndef NO_MMAP munmap(fdata[i], finfo[i].st_size + 1); #else free (fdata[i]); #endif } return 0; } // kmeans merged main sections start /* khere todelete int main(int argc, char **argv) { struct timespec begin, end; struct timespec veryStart, veryEnd; srand( time(NULL) ); get_time( begin ); get_time( veryStart ); //read args parse_args(argc,argv); std::cerr << "Available threads: " << __cilkrts_get_nworkers() << "\n"; #if SEQUENTIAL && PMC LIKWID_MARKER_INIT; #endif // SEQUENTIAL && PMC #if TRACING event_tracer::init(); #endif arff_file arff_data; arff_data.read_sparse_file( infile ); num_dimensions = arff_data.idx.size(); num_points = arff_data.points.size(); min_val = arff_data.minval; max_val = arff_data.maxval; // allocate memory // get points point * points = &arff_data.points[0]; // get means Centres centres; for( int i=0; i < num_points; ++i ) { points[i].cluster = rand() % num_clusters; centres.add_point( &points[i] ); } centres.normalize(); // for(int i = 0; i < num_clusters; i++) { // std::cout << "in cluster " << i << " " << centres[i].cluster << " points\n"; // } get_time (end); print_time("initialize", begin, end); printf("KMeans: Calling MapReduce Scheduler\n"); // keep re-clustering until means stabilise (no points are reassigned // to different clusters) #if SEQUENTIAL && PMC LIKWID_MARKER_START("mapreduce"); #endif // SEQUENTIAL && PMC get_time (begin); int niter = 1; if( arff_data.sparse_data && !force_dense ) { // First build sparse representation std::vector<sparse_point> spoints; spoints.reserve( num_points ); for( int i=0; i < num_points; ++i ) spoints.push_back( sparse_point( points[i] ) ); while(kmeans_cluster(centres, &spoints[0])) { if( ++niter >= max_iters && max_iters > 0 ) break; } for( int i=0; i < num_points; ++i ) { delete[] spoints[i].c; delete[] spoints[i].v; } } else { while(kmeans_cluster(centres, points)) { if( ++niter >= max_iters && max_iters > 0 ) break; } } get_time (end); #if SEQUENTIAL && PMC LIKWID_MARKER_STOP("mapreduce"); #endif // SEQUENTIAL && PMC print_time("library", begin, end); get_time (begin); //print means printf("KMeans: MapReduce Completed\n"); #if 0 printf("\n\nFinal means:\n"); for(int i = 0; i < num_clusters; i++) centres[i].dump(); #endif fprintf( stdout, "iterations: %d\n", niter ); real sse = 0; for( int i=0; i < num_points; ++i ) { sse += centres[points[i].cluster].sq_dist( points[i] ); } fprintf( stdout, "within cluster sum of squared errors: %11.4lf\n", sse ); fprintf( stdout, "%37s\n", "Cluster#" ); fprintf( stdout, "%-16s", "Attribute" ); fprintf( stdout, "%10s", "Full Data" ); for( int i=0; i < num_clusters; ++i ) fprintf( stdout, "%11d", i ); fprintf( stdout, "\n" ); char buf[32]; sprintf( buf, "(%d)", num_points ); fprintf( stdout, "%26s", buf ); for( int i=0; i < num_clusters; ++i ) { sprintf( buf, "(%d)", centres[i].cluster ); fprintf( stdout, "%11s", buf ); } fprintf( stdout, "\n" ); fprintf( stdout, "================" ); fprintf( stdout, "==========" ); for( int i=0; i < num_clusters; ++i ) fprintf( stdout, "===========" ); fprintf( stdout, "\n" ); for( int i=0; i < num_dimensions; ++i ) { fprintf( stdout, "%-16s", arff_data.idx[i] ); #if REAL_IS_INT #error not yet implemented #else real s = 0; for( int j=0; j < num_points; ++j ) s += points[j].d[i]; s /= (real)num_points; s = min_val[i] + s * (max_val[i] - min_val[i] + 1); fprintf( stdout, "%10.4lf", s ); #endif for( int k=0; k < num_clusters; ++k ) { #if REAL_IS_INT #error not yet implemented #else real s = 0; for( int j=0; j < num_points; ++j ) if( points[j].cluster == k ) s += points[j].d[i]; s /= (real)centres[k].cluster; s = min_val[i] + s * (max_val[i] - min_val[i] + 1); fprintf( stdout, "%11.4lf", s ); #endif } fprintf( stdout, "\n" ); } //free memory // delete[] points; -- done in arff_file // oops, not freeing points[i].d get_time (end); print_time("finalize", begin, end); print_time("complete time", veryStart, end); #if TRACING event_tracer::destroy(); #endif #if SEQUENTIAL && PMC LIKWID_MARKER_CLOSE; #endif // SEQUENTIAL && PMC return 0; } // kmeans merged main sections end // */ // Unused function, code for future reference void recordOfCodeForALLOutputFormats() { // // This func is Non-compilable, for future record for cleaner output formats code // #if 0 string strFilename(fname); string txtFilename(strFilename + ".txt"); string binFilename(strFilename + ".bin"); string arffTextFilename(strFilename + ".arff"); string arffBinFilename(strFilename + ".arff.bin"); ofstream resFile (txtFilename, ios::out | ios::trunc | ios::binary); ofstream resFileArff ( arffBinFilename, ios::out | ios::trunc | ios::binary); auto name_max = pathconf(fname, _PC_NAME_MAX); ofstream resFileTextArff; resFileTextArff.open(arffTextFilename, ios::out | ios::trunc ); get_time (begin); string headerText("Document Vectors (sequencefile @ hdfs):"); string headerTextArff("@relation tfidf"); string classText("Key class: class org.apache.hadoop.io.Text Value Class: class org.apache.mahout.math.VectorWritable"); string classTextArff("@attribute @@class@@ {text}"); #define SS(str) (str), (sizeof((str))-1)/sizeof((str)[0]) #define XS(str) (str).c_str(), (str).size() #define ST(i) ((const char *)&(i)), sizeof((i)) char nline='\n'; char space=' '; char tab='\t'; char comma=','; char colon=':'; char lbrace='{'; char rbrace='}'; char what; // print arff string loopStart = "@attribute "; string typeStr = "numeric"; string dataStr = "@data"; resFileArff.write (headerTextArff.c_str(), headerTextArff.size()); resFileArff.write ((char *)&nline,1); resFileArff.write ((char *)&tab,1); resFileArff.write (classTextArff.c_str(), classTextArff.size()); resFileArff.write ((char *)&nline,1); resFileTextArff << headerTextArff << "\n" << classTextArff << "\n";; resFileTextArff.flush(); // uint64_t indices[dict.size()]; unordered_map<uint64_t, uint64_t> idMap; // hash_table<uint64_t, uint64_t, wc_word_hash> idMap; int i=1; for( auto I=dict.begin(), E=dict.end(); I != E; ++I ) { resFileArff.write((char *)&tab, 1); resFileTextArff << "\t"; uint64_t id = I.getIndex(); string str = I->first.data; resFileArff.write((char *) loopStart.c_str(), loopStart.size()); resFileArff.write((char *) str.c_str(), str.size()); resFileArff.write((char *) &space, sizeof(char)); resFileArff.write((char *) typeStr.c_str(), typeStr.size()); resFileArff.write((char *) &nline, sizeof(char)); resFileTextArff << loopStart << str << " " << typeStr << "\n"; idMap[id]=i; i++; // cout << "\t" << loopStart << id << "\n"; } resFileArff.write((char *) &nline, sizeof(char)); resFileArff.write((char *) &nline, sizeof(char)); resFileArff.write((char *) dataStr.c_str(), dataStr.size()); resFileArff.write((char *) &nline, sizeof(char)); resFileArff.write((char *) &nline, sizeof(char)); resFileTextArff << "\n\n" << dataStr << "\n\n"; // printing mahoot Dictionary cout << headerText << nline; cout << "\t" << classText << nline; // printing mahoot Dictionary resFile.write (headerText.c_str(), headerText.size()); resFile.write ((char *)&nline,1); resFile.write ((char *)&tab,1); resFile.write (classText.c_str(), classText.size()); resFile.write ((char *)&nline,1); for( auto I=dict.begin(), E=dict.end(); I != E; ++I ) { uint64_t id = I.getIndex(); const string & str = I->first.data; resFile.write( SS( "\tKey: " ) ) .write( XS( str ) ) .write( SS( " Value: " ) ) .write( ST( id ) ) .write( SS( "\n" ) ); } // printing mahoot output header resFile.write (headerText.c_str(), headerText.size()); resFile.write((char *) &nline, sizeof(char)); resFile.write ((char *)&tab,1); resFile.write (classText.c_str(), classText.size()); resFile.write((char *) &nline, sizeof(char)); // cout << headerText << nline << "\t" << classText << nline; resFileTextArff.flush(); for (unsigned int i = 0;i < files.size();i++) { // printing mahoot loop start text including filename twice ! string & keyStr = files[i]; if( dict.empty() ) { // string loopStart = "Key: " + keyStr + ": " + "Value: " // + keyStr + ":"; // resFile.write ((char *)&tab, 1); // resFile.write (loopStart.c_str(), loopStart.size()); // resFile.write ((char *)&rbrace, 1); // resFile.write ((char *)&nline, 1); resFile.write( SS( "\tKey: " ) ) .write( XS( keyStr ) ) .write( SS( ": Value: " ) ) .write( XS( keyStr ) ) .write( SS( ":{}\n" ) ); continue; } resFile.write( SS( "\tKey: " ) ) .write( XS( keyStr ) ) .write( SS( ": Value: " ) ) .write( XS( keyStr ) ) .write( SS( ":{" ) ); resFileTextArff << "\t{"; // iterate over each word to collect total counts of each word in all files (reducedCount) // OR the number of files that contain the work (existsInFilesCount) for( auto I=dict.begin(), E=dict.end(); I != E; ) { size_t tf = I->second[i]; if (!tf) { ++I; continue; } // todo: workout how the best way to calculate and store each // word total once for all files #if 0 cilk::reducer< cilk::op_add<size_t> > existsInFilesCount(0); cilk_for (int j = 0; j < I->second.size(); ++j) { // *reducedCount += I->second[j]; // Use this if we want to count every occurence if (I->second[j] > 0) *existsInFilesCount += 1; } size_t fcount = existsInFilesCount.get_value(); #else const size_t * v = &I->second.front(); size_t len = I->second.size(); size_t fcount = __sec_reduce_add( is_nonzero(v[0:len]) ); #endif // Calculate tfidf --- Alternative versions of tfidf: // double tfidf = tf * log10(((double) files.size() + 1.0) / ((double) sumOccurencesOfWord + 1.0)); // double tfidf = tf * log10(((double) files.size() + 1.0) / ((double) numOfOtherDocsWithWord + 2.0)); // double tfidf = tf * log10(((double) files.size() + 1.0) / ((double) reducedCount.get_value() + 1.0)); // Sparks version; double tfidf = (double) tf * log10(((double) files.size() + 1.0) / ((double) fcount + 1.0)); uint64_t id = I.getIndex(); resFile.write( ST(id) ) .write( SS(":") ) .write( ST( tfidf ) ); resFileTextArff << idMap[id] << space << tfidf; // if( I != E ) resFile.write ((char *) &comma, sizeof(char)); resFileArff.write ((char *) &comma, sizeof(char)); ++I; // Note: // If Weka etc doesn't care if there is an extra unnecessary comma at end // of a each record then we'd rather avoid the branch test here, so leave it in cout << ","; resFileArff.write ((char *) &comma, sizeof(char)); resFileTextArff << comma; } // cout << "\n"; // What is this? Reverse one character? // In order to avoid this, need to count number of words in each // file during wc(). Not sure if that pays off... long pos = resFile.tellp(); resFile.seekp (pos-1); resFile.write ((char *)&rbrace, 1); resFile.write ((char *)&nline, 1); pos = resFileArff.tellp(); resFileArff.seekp (pos-1); resFileArff.write( SS( "}\n" ) ); resFile.write( SS( "}\n" ) ); resFileTextArff << "}\n"; cout << "}\n"; } resFileArff.close(); resFileTextArff.close(); resFile.close(); get_time (end); #ifdef TIMING print_time("output", begin, end); print_time("all", all_begin, end); #endif // Check on binary file: // -c at the command line with try to read results back in from binary file and display // but note there will be odd chars before unsigned int64's as we do simple read of unsigned // int 64 for 'id' Examining the binary file itself shows the binary file has the correct values for 'id' if (checkResults) { char colon, comma, cbrace, nline, tab; uint64_t id; double tfidf; char checkHeaderText[headerText.size()]; char checkClassText[classText.size()]; ifstream inResFile; inResFile.open("testRes.txt", ios::binary); std::cerr << "\nREADING IN --------------------------------" << "\n" ; // reading mahoot Dictionary inResFile.read( (char*)&checkHeaderText, headerText.size()); inResFile.read( (char*)&nline, sizeof(char)); inResFile.read( (char*)&tab, 1); inResFile.read( (char*)&checkClassText, classText.size()); inResFile.read( (char*)&nline, sizeof(char)); // checkClassText[classText.size()+1]=0; std::cerr << checkHeaderText << nline << tab << checkClassText << nline; for( auto I=dict.begin(), E=dict.end(); I != E; ++I ) { inResFile.read( (char*)&tab, 1); string str = I->first.data; string iterStartCheck = "Key: " + str + " Value: "; char preText[iterStartCheck.size() +1 ]; inResFile.read((char *)&preText, iterStartCheck.size()); inResFile.read( (char*)&id, sizeof(uint64_t)); inResFile.read( (char*)&nline, sizeof(char)); std::cerr << tab << preText << id << nline; // std::cerr << tab << preText << id; } // reading mahoot TFIDF mappings per word per file inResFile.read( (char*)checkHeaderText, headerText.size()); inResFile.read( (char*)&nline, sizeof(char)); inResFile.read( (char*)&tab, 1); inResFile.read( (char*)checkClassText, classText.size()); inResFile.read( (char*)&nline, sizeof(char)); std::cerr << checkHeaderText << nline << tab << checkClassText << nline; // read for each files for (unsigned int i = 0;i < files.size();i++) { string & keyStr = files[i]; string loopStart = "Key: " + keyStr + ": " + "Value: " + keyStr + ":" + "{"; char preText[loopStart.size() +1]; inResFile.read( (char*)&tab, 1); inResFile.read( (char*)&preText, loopStart.size()); std::cerr << tab << preText; // iterate over each word to collect total counts of each word in all files for( auto I=dict.begin(), E=dict.end(); I != E; ++I ) { size_t tf = I->second[i]; if (!tf) continue; inResFile.read( (char*)&id, sizeof(uint64_t)); inResFile.read( (char*)&colon, sizeof(char)); inResFile.read( (char*)&tfidf, sizeof(double)); inResFile.read( (char*)&comma, sizeof(char)); std::cerr << id << colon << tfidf << comma ; } // inResFile.read((char*)&cbrace, 1); // comma will contain cbrace after last iteration cbrace=comma; inResFile.read((char*)&nline, 1); std::cerr << nline; } } #endif }
/* 在字符原数组上进行操作。计算出有多少个空格和新字符串的长度。使用two pointers的方法,从后向前复制,遇到空格则替换为"%20"。 当两个pointer相遇时所有空格已经替换完。 */ class Solution { public: void replaceSpace(char *str,int length) { int originalLength = 0; // exclude '\0' int numOfBlank = 0; int i = 0; while(str[i] != '\0'){ originalLength++; if(str[i] == ' ') numOfBlank++; i++; } int newLength = originalLength + 2*numOfBlank; int q = newLength, p = originalLength; // start from '\0' while(p < q){ if(str[p] != ' '){ str[q--] = str[p--]; }else{ str[q--] = '0'; str[q--] = '2'; str[q--] = '%'; p--; } } } };
// Created on: 2016-04-13 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-2016 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BVH_QuickSorter_Header #define _BVH_QuickSorter_Header #include <BVH_Sorter.hxx> //! Performs centroid-based sorting of abstract set along //! the given axis (X - 0, Y - 1, Z - 2) using quick sort. template<class T, int N> class BVH_QuickSorter : public BVH_Sorter<T, N> { public: //! Creates new BVH quick sorter for the given axis. BVH_QuickSorter (const Standard_Integer theAxis = 0) : myAxis (theAxis) { } //! Sorts the set. virtual void Perform (BVH_Set<T, N>* theSet) Standard_OVERRIDE { Perform (theSet, 0, theSet->Size() - 1); } //! Sorts the given (inclusive) range in the set. virtual void Perform (BVH_Set<T, N>* theSet, const Standard_Integer theStart, const Standard_Integer theFinal) Standard_OVERRIDE { Standard_Integer aLft = theStart; Standard_Integer aRgh = theFinal; T aPivot = theSet->Center ((aRgh + aLft) / 2, myAxis); while (aLft < aRgh) { while (theSet->Center (aLft, myAxis) < aPivot && aLft < theFinal) { ++aLft; } while (theSet->Center (aRgh, myAxis) > aPivot && aRgh > theStart) { --aRgh; } if (aLft <= aRgh) { if (aLft != aRgh) { theSet->Swap (aLft, aRgh); } ++aLft; --aRgh; } } if (aRgh > theStart) { Perform (theSet, theStart, aRgh); } if (aLft < theFinal) { Perform (theSet, aLft, theFinal); } } protected: //! Axis used to arrange the primitives (X - 0, Y - 1, Z - 2). Standard_Integer myAxis; }; #endif // _BVH_QuickSorter_Header
#include "mainwindow.h" #include <QApplication> #include <QMessageBox> #include <iostream> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; // QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); // db.setDatabaseName("test"); // db.open(); // if(db.open()) // { w.setWindowTitle("可视化航班查询系统"); w.show(); // } // else // { // QMessageBox::warning(NULL,"error","数据库连接失败"); // return 0; // } return a.exec(); }
#include<bits/stdc++.h> using namespace std; class Node{ public: int key; Node* left; Node* right; int height; int findHeight(Node* n){ if(n==NULL){ return 0; } return n->height; } Node* newNode(int key){ Node* n = new Node(); n->key = key; n->left = NULL; n->right = NULL; n->height = 1; return n; } Node* rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; x->right=y; y->left=T2; y->height = max(findHeight(y->left),findHeight(y->right))+1; x->height = max(findHeight(x->left),findHeight(x->right))+1; return x; } Node* leftRotate(Node *x){ Node *y = x->right; Node*T2 = y->left; y->left = x; x->right = T2; x->height = max(findHeight(x->left),findHeight(x->right))+1; y->height = max(findHeight(y->left),findHeight(y->right))+1; return y; } int getBalance(Node *N){ if(N==NULL){ return 0; } return findHeight(N->left)-findHeight(N->right); } Node* insert(Node* root, int key){ if(root==NULL){ return(newNode(key)); } if(key<root->key){ root->left = insert(root->left,key); } else if(key>root->key){ root->right = insert(root->right,key); } else{ return root; } root->height = 1 + max(findHeight(root->left),findHeight(root->right)); int balance = getBalance(root); if(balance>1&&key<root->left->key){ return rightRotate(root); } if(balance<-1&&key>root->right->key){ return leftRotate(root); } if(balance>1&&key>root->left->key){ root->left = leftRotate(root->left); return rightRotate(root); } if(balance<-1&&key<root->right->key){ root->right = rightRotate(root->right); return leftRotate(root); } return root; } void preOrder(Node *root){ if(root){ cout<<"k: "<<root->key<<"h: "<<root->height; preOrder(root->left); preOrder(root->right); } } }; int main(){ Node n; Node *root = NULL; root = n.insert(root,10); root = n.insert(root,20); root = n.insert(root,30); root = n.insert(root, 40); root = n.insert(root, 50); root = n.insert(root, 25); n.preOrder(root); return 0; }
#include "../include/Player.h" #include "../include/WindowInfo.h" #include "../include/Camera.h" #include "../include/Bullet.h" #include "../include/TextureManager.h" #include "../include/BulletManager.h" #include "../include/AudioManager.h" #include "../include/Global.h" #include <cmath> namespace gnGame { // プレイヤーの重力や速さなどのパラメータ namespace PlayerParameters { // プレイヤーにかかる重力 constexpr float Gravity = 0.980f; // 最大の重力 constexpr float MaxGravity = Gravity * 10.0f; // プレイヤーが進む速さ //constexpr float Speed = 5.0f; // プレイヤーのジャンプ力 constexpr float JumpPower = -7.0f; }; // プレイヤーが移動するときに入力される値 namespace PlayerInput { static float xspeedtime = 0; float getinertia() { if (Input::getKey(Key::LEFT)) { xspeedtime = max(xspeedtime - 0.2f, -1.0f); } else if (Input::getKey(Key::RIGHT)) { xspeedtime = min(xspeedtime + 0.2f, 1.0f); } else { xspeedtime *= 0.9f; } return xspeedtime; } } namespace { // プレイヤーの最大のパラメータ // 体力、弾の数、攻撃力、守備力、スピード static const ActorParameter MaxParameter{ 30.0f, 20.0f, 2.0f, 3.0f, 5.0f }; } // ---------- プレイヤークラス ---------- Player::Player() : Actor() , map() , collider() , playerState(PlayerState::Wait) , playerBody(MaxParameter) , moveTime() , jumpTime() , isJump(false) , isGround(false) , isFall(false) , jumpInput(false) , isMove(true) , waitImage(2, 1, 3.0f) , walkImage(10, 1, 24.0f) { walkImage.setTexture(TextureManager::getTexture("Main_Walk")); waitImage.setTexture(TextureManager::getTexture("Main_Wait")); // 自身のオブジェクトの名前を決める this->name = "Player"; // jumpTimeの加算時間を0.16にしたいのでscaleを10倍にする jumpTime.setTimeScale(10.0f); } void Player::onStart() { this->setActive(true); // プレイヤーのパラメータをセット(リセット)する playerBody.setParamater(MaxParameter); velocity = Vector2::Zero; bounds.minPos.setPos(0, 0); bounds.maxPos.setPos(32, 32); bounds.size.setPos(bounds.maxPos - bounds.minPos); bounds.center.setPos(bounds.size.half()); } void Player::onUpdate() { if (!this->isActive) { return; } if (this->fallScreen(map->getMapSize().y)) { death(); } movePlayer(); jumpPlayer(); shotPlayer(); playerBody.onUpdate(); if (!isMove) { moveTime.update(); if (moveTime.isTimeUp(0.25)) { isMove = true; moveTime.reset(); } } { float healMp = playerBody.getParameter().mp + Time::deltaTime(); healMp = clamp(healMp, 0.0f, MaxParameter.mp); playerBody.setMP(healMp); } // ----- 座標更新 ----- if(isMove) this->transform.pos = intersectTileMap(); // 座標を更新 // 画面外にプレイヤーが出ないようにする this->transform.pos = vecClamp( this->transform.pos, { Camera::minScreenPos().x + 16.0f, Camera::minScreenPos().y + 16.0f }, { Camera::maxScreenPos().x - 16.0f, 10000.0f } ); Camera::setTarget(this->transform.pos); // プレイヤーを追跡するようにカメラに座標を渡す auto screen = Camera::toScreenPos(this->transform.pos); // 座標をスクリーン座標へと変換 // ----- コライダー更新 ----- collider.update(screen, 32.0f, 32.0f); // ----- 描画 ----- const float scaleXY = 32.0f / 24.0f; isFlip = velocity.x < 0.0f; if (std::abs(velocity.x) <= 0.005f) { velocity.x = 0.0f; waitImage.draw(screen, { scaleXY, scaleXY }, transform.angle, true, isFlip); } else { walkImage.draw(screen, { scaleXY, scaleXY }, transform.angle, true, isFlip); } // ----- デバッグ ----- debug(); } void Player::setMap(Map* _map) { map = _map; } Vector2 Player::intersectTileMap() { auto nextPos = this->transform.pos + velocity; // 判定を行う座標を決める float offX{ bounds.center.x / 4.0f - 1.0f }; float offY{ bounds.center.y / 4.0f - 1.0f }; // 上下判定用に判定ボックス更新 bounds.minPos.setPos(this->transform.pos.x - bounds.center.x, nextPos.y - bounds.center.y); bounds.maxPos.setPos(this->transform.pos.x + bounds.center.x, nextPos.y + bounds.center.y); // -- 下 -- intersectPoint.bottom[0] = Vector2{ bounds.minPos.x + offX, bounds.maxPos.y + 1.0f }; intersectPoint.bottom[1] = Vector2{ bounds.maxPos.x - offX, bounds.maxPos.y + 1.0f }; // -- 上 -- intersectPoint.top[0] = Vector2{ bounds.minPos.x + offX, bounds.minPos.y }; intersectPoint.top[1] = Vector2{ bounds.maxPos.x - offX, bounds.minPos.y }; nextPos = verticalIntersect(nextPos); // 左右判定用に判定ボックス更新 bounds.minPos.setPos(nextPos.x - bounds.center.x, this->transform.pos.y - bounds.center.y); bounds.maxPos.setPos(nextPos.x + bounds.center.x, this->transform.pos.y + bounds.center.y); // -- 右 -- intersectPoint.right[0] = Vector2{ bounds.maxPos.x , bounds.minPos.y + offY }; intersectPoint.right[1] = Vector2{ bounds.maxPos.x , bounds.maxPos.y - offY }; // -- 左 -- intersectPoint.left[0] = Vector2{ bounds.minPos.x - 1.0f, bounds.minPos.y + offY }; intersectPoint.left[1] = Vector2{ bounds.minPos.x - 1.0f, bounds.maxPos.y - offY }; nextPos = holizontalIntersect(nextPos); return nextPos; } Vector2 Player::verticalIntersect(const Vector2& _nextPos) { auto nextPos = _nextPos; // -- 上との当たり判定 -- for (int i{ 0 }; i < IntersectPoint::Size; ++i) { auto mapID = map->getTile((int)intersectPoint.top[i].x / 32, (int)intersectPoint.top[i].y / 32); if (mapID == MapTile::BLOCK) { auto hitPos = ((int)intersectPoint.top[i].y / MapInfo::MapSize + 1) * (float)MapInfo::MapSize; if (intersectPoint.top[i].y <= hitPos) { nextPos.y = nextPos.y + fabsf(intersectPoint.top[i].y - hitPos); break; } } } // -- 下との当たり判定 -- for (int i{ 0 }; i < IntersectPoint::Size; ++i) { auto mapID = map->getTile((int)intersectPoint.bottom[i].x / 32, (int)intersectPoint.bottom[i].y / 32); if (mapID == MapTile::BLOCK) { auto hitPos = (int)(intersectPoint.bottom[i].y / MapInfo::MapSize) * (float)MapInfo::MapSize; if (intersectPoint.bottom[i].y >= hitPos) { nextPos.y = nextPos.y - fabsf(intersectPoint.bottom[i].y - hitPos) + 1.0f; // 地面についているとき isGround = true; break; } } else if(mapID == MapTile::OBJECT){ auto sub = this->transform.pos.y - nextPos.y; if (sub <= 0) { auto hitPos = (int)(intersectPoint.bottom[i].y / MapInfo::MapSize) * (float)MapInfo::MapSize; if (intersectPoint.bottom[i].y >= hitPos) { nextPos.y = nextPos.y - fabsf(intersectPoint.bottom[i].y - hitPos) + 1.0f; // 地面についているとき isGround = true; break; } } } else { // 下にマップチップがないとき isGround = false; } } return nextPos; } Vector2 Player::holizontalIntersect(const Vector2& _nextPos) { auto nextPos = _nextPos; // -- 右との当たり判定 -- for (int i{ 0 }; i < IntersectPoint::Size; ++i) { auto mapID = map->getTile((int)intersectPoint.right[i].x / 32, (int)intersectPoint.right[i].y / 32); if (mapID == MapTile::BLOCK) { float hitPos = (int)(intersectPoint.right[i].x / MapInfo::MapSize) * (float)MapInfo::MapSize; if (intersectPoint.right[i].x >= hitPos) { nextPos.x = nextPos.x - fabsf(intersectPoint.right[i].x - hitPos); break; } } } // -- 左との当たり判定 -- for (int i{ 0 }; i < IntersectPoint::Size; ++i) { auto mapID = map->getTile((int)intersectPoint.left[i].x / 32, (int)intersectPoint.left[i].y / 32); if (mapID == MapTile::BLOCK) { float hitPos = ((int)intersectPoint.left[i].x / MapInfo::MapSize + 1) * (float)MapInfo::MapSize; if (intersectPoint.left[i].x <= hitPos) { nextPos.x = nextPos.x + fabsf(intersectPoint.left[i].x - hitPos) - 1.0f; break; } } } return nextPos; } void Player::resetPosition(const Vector2& _pos) { this->setActive(true); this->transform.setPos(_pos); } BoxCollider& Player::getCollider() { return collider; } PlayerBody& Player::getPlayerBody() { return playerBody; } void Player::death() { isActive = false; } void Player::respawn(const Vector2& _pos) { // velocityを0にする this->velocity = Vector2::Zero; PlayerInput::xspeedtime = 0.0f; isGround = true; // パラメータをもとに戻す playerBody.setParamater(MaxParameter); this->transform.setPos(_pos); Camera::setTarget(this->transform.pos); isActive = true; } void Player::reset() { velocity = Vector2::Zero; isMove = true; } void Player::setIsMove(bool _isMove) { isMove = _isMove; } void Player::movePlayer() { // ----- 移動 ----- velocity.x = PlayerInput::getinertia() * playerBody.getParameter().speed; } void Player::jumpPlayer() { // ----- ジャンプ ----- jumpInput = Input::getKeyDown(Key::Z); // ジャンプキーが押された時 if (jumpInput) { // 地面に足がついているとき if (isGround) { AudioManager::getIns()->setPosition("SE_jump", 0); AudioManager::getIns()->play("SE_jump"); isGround = false; isJump = true; isFall = true; jumpTime.reset(); } } // 空中にいるとき if (isJump) { // 1.0秒を超えたらjumpフラグをfalseにする if(jumpTime.isTimeUp(1.0f)){ jumpTime.setTime(1.0f); isJump = false; jumpInput = false; } jumpTime.update(); velocity.y = PlayerParameters::JumpPower * jumpTime.getFrameTime(); } else { isFall = true; velocity.y += PlayerParameters::Gravity; velocity.y = min(velocity.y, PlayerParameters::MaxGravity); } // 地面に足がついているとき、地面にめり込まないようにする if (isGround) { isFall = false; velocity.y = 0.0f; } } void Player::shotPlayer() { if (Input::getKeyDown(Key::X)) { if (playerBody.getParameter().mp < 2) { return; } AudioManager::getIns()->setPosition("SE_shot", 0); AudioManager::getIns()->play("SE_shot"); float vx = (velocity.x >= 0) ? 10.0f : -10.0f; BulletPtr bulletPtr(new Bullet(this->transform.pos, Vector2{ vx, 0.0f }, BulletType::Player)); bulletPtr->onStart(); bulletPtr->setAttack(playerBody.getParameter().attack); BulletManager::getIns()->addBullet(bulletPtr); playerBody.subMp(2.0f); } } void Player::debug() { #if _DEBUG static Font font{ 24, "MS 明朝" }; font.drawText(0, 60, Color::Black, "Position = %s", this->transform.pos.toString().c_str()); font.drawText(0, 80, Color::Black, "Velocity = %s", velocity.toString().c_str()); //Debug::drawFormatText(0, 80, Color::Black, "isGround = %d", isGround); //Debug::drawFormatText(0, 100, Color::Black, "isJump = %d", isJump); //Debug::drawFormatText(0, 120, Color::Black, "isFall = %d", isFall); #endif // _DEBUG } }
/** \file Renderer.cpp * \author Eduardo Pinho ( enet4mikeenet AT gmail.com ) * \date 2013 */ #include "Renderer.h" #include <string.h> #ifdef Derplotter_DEBUG #include <stdio.h> static void DEBUG(const char* s) { printf("RENDERER: %s\n", s); fflush(stdout);} #else static void DEBUG(const char* s){} #endif using namespace derplot; using namespace op; using namespace math; Renderer::Renderer() : ok(false) {} Renderer::Renderer(int width, int height, void* extern_buffer) : buffer(width, height, extern_buffer) , program(buffer) , ok(true) , thread(run, this) {} Renderer::~Renderer() {} bool Renderer::operator!(void) const { return !buffer || !ok; } int Renderer::bufferCopy(void* dest) const { if (!(*this) || dest == nullptr) return 0; memcpy(dest, this->buffer.data(), buffer.getWidth()*buffer.getHeight()*sizeof(unsigned int)); return 1; } Renderer& Renderer::operator>>(op::RendererOperation* op) { if (!(*this)) return *this; std::unique_lock<std::mutex> q_lock(this->q_mutex); this->q.emplace(op); this->q_hasOp.notify_all(); q_lock.unlock(); return *this; } void Renderer::flush(void) { if (!(*this)) return; std::unique_lock<std::mutex> q_lock(this->q_mutex); if (!q.empty()) q_empty.wait(q_lock); } void Renderer::terminate(void) { if (!(*this)) return; *this >> new Terminate; thread.join(); } void Renderer::clear(void) { *this >> new Clear(); } void Renderer::drawRawPoint(std::pair<int,int> p) { *this >> new RawPoint(p, 0); } void Renderer::drawRawBigPoint(std::pair<int,int> p) { *this >> new RawPoint(p, 1); } void Renderer::drawRawLine(std::pair<int,int> point1, std::pair<int,int> point2) { *this >> new RawLine(point1, point2); } void Renderer::drawPoint(const Vector4f& p) { *this >> new Point(p, 0); } void Renderer::drawBigPoint(const Vector4f& p) { *this >> new Point(p, 1); } void Renderer::drawLine(const math::Vector4f& point1, const math::Vector4f& point2) { *this >> new Line(point1, point2); } void Renderer::orthoProjection(float left, float right, float bottom, float top, float near, float far) { *this >> new Ortho(left, right, top, bottom, near, far); } void Renderer::perspectiveProjection(float fovy, float near, float far, float aspect_ratio) { *this >> new Perspective(fovy, near, far, aspect_ratio); } void Renderer::setProjectionMatrix(const math::Mat4x4f& mat) { *this >> new MatrixSet(mat, 1); } void Renderer::setModelViewMatrix(const math::Mat4x4f& mat) { *this >> new MatrixSet(mat, 0); } void Renderer::translate(const math::Vector4f& v, int matrix) { *this >> new MatrixTranslate(v, matrix); } void Renderer::rotateX(float x_angle, int matrix) { *this >> new MatrixRotate(x_angle, 0, matrix); } void Renderer::rotateY(float y_angle, int matrix) { *this >> new MatrixRotate(y_angle, 1, matrix); } void Renderer::rotateZ(float z_angle, int matrix) { *this >> new MatrixRotate(z_angle, 2, matrix); } void Renderer::scale(const math::Vector4f& v, int matrix) { *this >> new MatrixScale(v, matrix); } void Renderer::front_color(unsigned int color) { *this >> new FrontColor(color); } void Renderer::clear_color(unsigned int color) { *this >> new ClearColor(color); } void Renderer::setViewPort(const math::Region2i& viewport) { *this >> new ViewPort(viewport); } void Renderer::run(Renderer* renderer) { DEBUG("I live!"); bool running = true; RendererOperation* op = nullptr; do { std::unique_lock<std::mutex> q_lock(renderer->q_mutex); // wait for operation if (renderer->q.empty()) { DEBUG("Waiting for operation..."); renderer->q_hasOp.wait(q_lock); DEBUG("Woken up by \"hasOp\"\n"); } // retrieve operation from operation queue op = (RendererOperation*) renderer->q.front().release(); renderer->q.pop(); q_lock.unlock(); if (op == nullptr) continue; DEBUG("Executing..."); int r = op->onDispatch(renderer->program); // dispatch operation DEBUG("Done Executing."); delete op; if (r == -1) // termination code { DEBUG("Terminating..."); q_lock.lock(); while (!renderer->q.empty()) renderer->q.pop(); // clear queue running = false; renderer->ok = false; q_lock.unlock(); } q_lock.lock(); if (renderer->q.empty()) { DEBUG("Operation queue is empty. Signalling now."); renderer->q_empty.notify_all(); } q_lock.unlock(); } while(running); DEBUG("Reached end of thread function."); }
/* * Copyright (c) 2016-2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_COMPARATORS_PROJECTION_COMPARE_H_ #define CPPSORT_COMPARATORS_PROJECTION_COMPARE_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <tuple> #include <utility> #include <cpp-sort/utility/as_function.h> #include <cpp-sort/utility/branchless_traits.h> #include "../detail/type_traits.h" namespace cppsort { template<typename Compare, typename Projection> class projection_compare { private: using compare_t = detail::remove_cvref_t< decltype(utility::as_function(std::declval<Compare>())) >; using projection_t = detail::remove_cvref_t< decltype(utility::as_function(std::declval<Projection>())) >; std::tuple<compare_t, projection_t> data; public: projection_compare(Compare compare, Projection projection): data(utility::as_function(compare), utility::as_function(projection)) {} template<typename T, typename U> constexpr auto operator()(T&& lhs, U&& rhs) noexcept(noexcept(std::get<0>(data)(std::get<1>(data)(std::forward<T>(lhs)), std::get<1>(data)(std::forward<U>(rhs))))) -> decltype(std::get<0>(data)(std::get<1>(data)(std::forward<T>(lhs)), std::get<1>(data)(std::forward<U>(rhs)))) { return std::get<0>(data)(std::get<1>(data)(std::forward<T>(lhs)), std::get<1>(data)(std::forward<U>(rhs))); } template<typename T, typename U> constexpr auto operator()(T&& lhs, U&& rhs) const noexcept(noexcept(std::get<0>(data)(std::get<1>(data)(std::forward<T>(lhs)), std::get<1>(data)(std::forward<U>(rhs))))) -> decltype(std::get<0>(data)(std::get<1>(data)(std::forward<T>(lhs)), std::get<1>(data)(std::forward<U>(rhs)))) { return std::get<0>(data)(std::get<1>(data)(std::forward<T>(lhs)), std::get<1>(data)(std::forward<U>(rhs))); } using is_transparent = void; }; template<typename Compare, typename Projection> auto make_projection_compare(Compare compare, Projection projection) -> projection_compare<Compare, Projection> { return { std::move(compare), std::move(projection) }; } namespace utility { template<typename Compare, typename Projection, typename T> struct is_probably_branchless_comparison<projection_compare<Compare, Projection>, T>: cppsort::detail::conjunction< is_probably_branchless_projection<Projection, T>, is_probably_branchless_comparison< Compare, cppsort::detail::invoke_result_t<Projection, T> > > {}; } } #endif // CPPSORT_COMPARATORS_PROJECTION_COMPARE_H_
// Created on: 1992-10-29 // Created by: Gilles DEBARBOUILLE // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Units_Unit_HeaderFile #define _Units_Unit_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TColStd_HSequenceOfHAsciiString.hxx> #include <Standard_Transient.hxx> #include <TCollection_AsciiString.hxx> #include <Standard_Integer.hxx> class TCollection_HAsciiString; class Units_Quantity; class Units_Token; class Units_Unit; DEFINE_STANDARD_HANDLE(Units_Unit, Standard_Transient) //! This class defines an elementary word contained in //! a physical quantity. class Units_Unit : public Standard_Transient { public: //! Creates and returns a unit. <aname> is the name of //! the unit, <asymbol> is the usual abbreviation of the //! unit, and <avalue> is the value in relation to the //! International System of Units. Standard_EXPORT Units_Unit(const Standard_CString aname, const Standard_CString asymbol, const Standard_Real avalue, const Handle(Units_Quantity)& aquantity); //! Creates and returns a unit. <aname> is the name of //! the unit, <asymbol> is the usual abbreviation of the //! unit. Standard_EXPORT Units_Unit(const Standard_CString aname, const Standard_CString asymbol); //! Creates and returns a unit. <aname> is the name of //! the unit. Standard_EXPORT Units_Unit(const Standard_CString aname); //! Returns the name of the unit <thename> TCollection_AsciiString Name() const; //! Adds a new symbol <asymbol> attached to <me>. Standard_EXPORT void Symbol (const Standard_CString asymbol); //! Returns the value in relation with the International //! System of Units. Standard_Real Value() const; //! Returns <thequantity> contained in <me>. Handle(Units_Quantity) Quantity() const; //! Returns the sequence of symbols <thesymbolssequence> Handle(TColStd_HSequenceOfHAsciiString) SymbolsSequence() const; //! Sets the value <avalue> to <me>. void Value (const Standard_Real avalue); //! Sets the physical Quantity <aquantity> to <me>. void Quantity (const Handle(Units_Quantity)& aquantity); //! Starting with <me>, returns a new Token object. Standard_EXPORT virtual Handle(Units_Token) Token() const; //! Compares all the symbols linked within <me> with the //! name of <atoken>, and returns True if there is one //! symbol equal to the name, False otherwise. Standard_EXPORT Standard_Boolean IsEqual (const Standard_CString astring) const; //! Useful for debugging Standard_EXPORT virtual void Dump (const Standard_Integer ashift, const Standard_Integer alevel) const; DEFINE_STANDARD_RTTIEXT(Units_Unit,Standard_Transient) protected: Handle(TColStd_HSequenceOfHAsciiString) thesymbolssequence; Standard_Real thevalue; private: Handle(TCollection_HAsciiString) thename; Handle(Units_Quantity) thequantity; }; #include <Units_Unit.lxx> #endif // _Units_Unit_HeaderFile
// // EPITECH PROJECT, 2019 // kevin // File description: // cpp // #include "saveData.hpp" Save::Save() { initLoadable(); } Save::~Save(){} void Save::printName() { for (auto i = _name.rbegin(); i != _name.rend(); ++i) std::cout << *i << std::endl; } bool Save::loadData(std::string player_name) { if (_loaded == false && player_name.compare("Enter Name")) { for (int i = 0; i != _name.size(); ++i) { if (!_name.at(i).compare(player_name)) { std::cout << "player exist" << std::endl; _loaded == true; return true; } } } else { std::cout << "No match for this user" << std::endl; return false; } } void Save::initLoadable() { DIR *dir = opendir(".data"); int i = 0; if (dir == NULL) { std::cerr << "Error: Can't find loadable data" << std::endl; exit(84); } struct dirent *enter; while((enter = readdir(dir)) != NULL) { std::string str(".data/"); str.append(enter->d_name); if (!str.compare(".data/.") || !str.compare(".data/..")) continue; std::string str2(enter->d_name); _name.push_back(str2); _loadablePath.push_back(str); } closedir(dir); _loaded = false; }