blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
70e1514603660fb16fba214e0d0f4918ac1b486e | C++ | nolan-downey/SchoolCodingWork | /fundcomp/lab3/polar.cpp | UTF-8 | 1,640 | 4.03125 | 4 | [] | no_license | //Nolan Downey
//Function to produce radius and angle to a given point, along with which quadrant the given point is located
#include<iostream>
#include<cmath>
using namespace std;
double get_radius(double,double);
double get_angle(double, double);
void quadrant_info(double, double);
int main() //main function
{
double x, y;
cout << "Please enter the x-coordinate: ";
cin >> x;
cout << "Please enter the y-coordinate: ";
cin >> y;
cout << "The radius to the given point is " << get_radius(x,y) << endl;
cout << "The angle to the given point is " << get_angle(x,y) << endl;
quadrant_info(x,y);
return 0;
}
double get_radius(double x, double y) //function defined to find length of radius
{
double radius;
radius = sqrt(x*x+y*y);
return radius;
}
double get_angle(double x, double y) //function defined to find angle to the given point
{
double angle;
angle = atan2(x,y);
angle = angle*180/M_PI;
if (angle<0)
angle = angle+360;
return angle;
}
void quadrant_info(double x,double y) //function to tell user which quadrant the given point is located
{
if ((x==0) and (y!=0))
cout << "The point is on the y-axis." << endl;
else if ((y==0) and (x!=0))
cout << "The point is on the x-axis." << endl;
else if ((x==0) and (y==0))
cout << "The point is on the origin." << endl;
else if ((x>0) and (y>0))
cout << "The specified point is in quadrant I." << endl;
else if ((x<0) and (y>0))
cout << "The specified point is in quadrant II." << endl;
else if ((x<0)and (y<0))
cout << "The specified point is in quadrant III." << endl;
else
cout << "The specified point is in quadrant IV." << endl;
}
| true |
a8bc5d42671b015475fef65fa861a30d1b5f1243 | C++ | konflicts/Sandbox | /C++/MultiArrays/MultiArrays/main.cpp | UTF-8 | 2,270 | 3.015625 | 3 | [] | no_license | //
// main.cpp
// MultiArrays
//
// Created by Pedro Pena on 5/1/14.
// Copyright (c) 2014 Pedo Peña. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
const int vendor = 5;
const int month = 6;
int sales [vendor] [month]= { {750,800,850,540,320,900},
{800,720,650,980,825,925},
{500,600,700,800,900,990},
{340,420,1000,280,995,998},
{600,700,500,400,300,800}
};
string monthName[6] = {"April","May","June","July","August","September"};
int SalesTotal;
int VendorSalesTotal[vendor] = {0}; // va a retener las ventas para los 6 meses por vendedor
int GlobalTotal = 0,
maxSalesVendor = 0,
maxSalesMonth = 0,
maxSales = 0;
string mes;
cout<<"Numero "<<"Abril "<<"Mayo "<<"Junio "<<"Julio "<<"Agosto "<<"septiembre"<<"total "<<endl;
for(int row = 0; row < vendor; row++)
{
cout<< "vendor" << row + 1 << " ";
SalesTotal = 0;
for(int col = 0; col < month; col++)
{
cout << sales[row][col] <<" ";
if(sales[row][col] > maxSales)
{
maxSales = sales[row][col];
maxSalesVendor = row;
maxSalesMonth = col;
}
SalesTotal = SalesTotal + sales[row][col];
GlobalTotal = GlobalTotal + SalesTotal;
}
VendorSalesTotal[row] = SalesTotal;
cout<< VendorSalesTotal[row] <<endl;
}
cout<<"El total de ventas global fue: "<< GlobalTotal <<endl;
cout << "The maximum sale is : " << maxSales << " in " << monthName[maxSalesMonth] << " by Vendor" << maxSalesVendor + 1 << endl;
}
| true |
b4d6d4508ccf67f117af7b5823ee70a0824bf770 | C++ | A284Philipi/1541_Construindo-Casas_Cpp | /main.cpp | UTF-8 | 772 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
long long int comprimento_casa, altura_casa, porcentagem_contrucao, lado_lote, cont, area_casa, area_lote;
while (true){
cin >> comprimento_casa;
if (comprimento_casa == 0){
break;
}
cin >> altura_casa;
area_casa = altura_casa * comprimento_casa;
cin >> porcentagem_contrucao;
area_lote = (area_casa * 100) / porcentagem_contrucao;
cont = 0;
lado_lote = 0;
while (cont < area_lote){
lado_lote++;
cont = lado_lote * lado_lote;
}
if (cont != area_lote){
lado_lote--;
}
cout << lado_lote <<endl;
}
}
| true |
5e5898060c5536473f6455e89306706064cc0f4f | C++ | rosynirvana/ZeroJudge | /a263.cpp | UTF-8 | 1,170 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <ios>
#include <cstdlib>
inline bool isLeapYear(int);
inline int daysPassed(int, int ,int);
int month[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int main()
{
std::ios_base::sync_with_stdio(false);
int y1, m1, d1;
while(std::cin >> y1 >> m1 >> d1){
int y2, m2, d2;
std::cin >> y2 >> m2 >> d2;
int sum = 0;
if(y1 < y2){
for(int y=y1; y<y2; ++y){
sum += (isLeapYear(y) ? 366 : 365);
}
sum += (daysPassed(y2, m2, d2) - daysPassed(y1, m1, d1));
}
else if(y1 > y2){
for(int y=y2; y<y1; ++y){
sum += (isLeapYear(y) ? 366 : 365);
}
sum += (daysPassed(y1, m1, d1) - daysPassed(y2, m2, d2));
}
else{
//std::cout << daysPassed(y1, m1, d1) << "\n";
//std::cout << daysPassed(y2, m2, d2) << "\n";
sum = abs(daysPassed(y1, m1, d1) - daysPassed(y2, m2, d2));
}
std::cout << sum << "\n";
}
}
bool isLeapYear(int year)
{
if(year % 400 == 0)
return true;
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
int daysPassed(int y, int m, int d)
{
int days = 0;
for(int i=0; i<m-1; ++i)
days += month[i];
if(isLeapYear(y) && m >= 3)
days += 1;
return days+d;
} | true |
4e35a8b0b115e98322246f81cfe1df69cbb86c6d | C++ | strisunshine/RemoteCodeManagement | /Message/Message.cpp | UTF-8 | 8,684 | 2.640625 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////////
// Message.cpp - Support message construction and configuration //
// ver 1.0 //
// //
// Application: CSE687 2015 Project 3 - Message Passing //
// Platform: Win7, Visual Studio 2013 //
// Author: Wenting Wang, wwang34@syr.edu //
/////////////////////////////////////////////////////////////////////
#include "Message.h"
// constructor
Message::Message(){
commandNumberMap.insert({ "FILE_UPLOAD", 1 });
commandNumberMap.insert({ "FILE_UPLOAD_REPLY", 2 });
commandNumberMap.insert({ "FILE_SEARCH", 3 });
commandNumberMap.insert({ "FILE_SEARCH_REPLY", 4 });
commandNumberMap.insert({ "FILE_DOWNLOAD", 5 });
commandNumberMap.insert({ "FILE_DOWNLOAD_REPLY", 6 });
commandNumberMap.insert({ "TEXT_SEARCH", 7 });
commandNumberMap.insert({ "TEXT_SEARCH_REPLY", 8 });
commandNumberMap.insert({ "QUIT", 9 });
commandNumberMap.insert({ "QUIT_REPLY", 10 });
}
// get the command-number map
std::map<std::string, int> Message::getCommandNumberMap(){
return commandNumberMap;
};
// set the command
bool Message::setCommand(const std::string& command){
command_ = command;
return true;
};
// get the command
std::string Message::getCommand(){
return command_;
};
//set the body
bool Message::setBody(const std::string& body){
body_ = body;
return true;
};
// get the body
std::string Message::getBody(){
return body_;
};
// get the name of the file to be uploaded
std::string Message::getFiletoUpload(){
return filename_;
};
// set the name of the file to be uploaded
bool Message::setFiletoUpload(const std::string& filename){
filename_ = filename;
return true;
};
// get the block length when send the file block by block
size_t Message::getFileUploadBlockLength(){
return fileUploadBlockLen_;
};
// build a message for file upload used by the client
void Message::configureFileUploadMsg(const std::string& filename, const std::string& srcAddress, const std::string& dstAddress, const std::string& path, const std::string& mode, size_t contentLen){
clear();
command_ = "FILE_UPLOAD";
filename_ = filename;
fileUploadBlockLen_ = contentLen;
clientSenttime = std::chrono::high_resolution_clock::now();
attribs_.insert({ "path", path });
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "mode", mode });
}
// build a message for file search used by client
void Message::configureFileSearchMsg(const std::string& srcAddress, const std::string& dstAddress, const std::string& asxml, const std::string& patterns, const std::string& serverrelativepath, const std::string& mode){
clear();
command_ = "FILE_SEARCH";
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "asxml", asxml});
attribs_.insert({ "patterns", patterns });
attribs_.insert({ "serverrelativepath", serverrelativepath });
attribs_.insert({ "mode", mode });
}
// build a message for text search used by client
void Message::configureTextSearchMsg(const std::string& srcAddress, const std::string& dstAddress, const std::string& asxml, const std::string& patterns, const std::string& searchtext, const std::string& threads, const std::string& mode){
clear();
command_ = "TEXT_SEARCH";
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "asxml", asxml });
attribs_.insert({ "patterns", patterns });
attribs_.insert({ "searchtext", searchtext });
attribs_.insert({ "threads", threads });
attribs_.insert({ "mode", mode });
}
// build a message for file download used by the client
void Message::configureFileDownloadMsg(const std::string& filename, const std::string& srcAddress, const std::string& dstAddress, std::string& serverrelativepath, const std::string& mode, size_t contentLen){
clear();
command_ = "FILE_DOWNLOAD";
filename_ = filename;
fileUploadBlockLen_ = contentLen;
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "path", serverrelativepath });
attribs_.insert({ "mode", mode });
}
// build a message for quitting used by the client
void Message::configureQuitMsg(const std::string srcAddress, const std::string dstAddress){
clear();
command_ = "QUIT";
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
}
// recover a message received for file upload reply used by the client
void Message::configureFileUploadReply(const std::string& filename, const std::string& srcAddress, const std::string& dstAddress, const std::string& servernumber, std::string path, const std::string& result, const std::string& mode){
clear();
setFiletoUpload(filename);
setCommand("FILE_UPLOAD_REPLY");
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "mode", mode });
attribs_.insert({ "result", result });
attribs_.insert({ "servernumber", servernumber });
attribs_.insert({ "path", path});
};
// recover a message received for file search reply used by the client
void Message::configureFileSearchReply(const std::string& srcAddress, const std::string& dstAddress, const std::string& asxml, const std::string& servernumber, const std::string& numberoffiles, const std::string& numberofdirectories, const std::string& serverrelativepath, const std::string& patterns, const std::string& body, const std::string& mode){
clear();
setCommand("FILE_SEARCH_REPLY");
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "asxml", asxml });
attribs_.insert({ "mode", mode });
attribs_.insert({ "numberoffiles", numberoffiles });
attribs_.insert({ "numberofdirectories", numberofdirectories });
attribs_.insert({ "servernumber", servernumber });
attribs_.insert({ "serverrelativepath", serverrelativepath });
attribs_.insert({ "patterns", patterns });
setBody(body);
};
// recover a message received for text search reply used by the client
void Message::configureTextSearchReply(const std::string& srcAddress, const std::string& dstAddress, const std::string& asxml, const std::string& servernumber, const std::string& numberoffiles, const std::string& patterns, const std::string& searchtext, const std::string& body, const std::string& mode){
clear();
setCommand("TEXT_SEARCH_REPLY");
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "asxml", asxml });
attribs_.insert({ "mode", mode });
attribs_.insert({ "numberoffiles", numberoffiles });
attribs_.insert({ "servernumber", servernumber });
attribs_.insert({ "searchtext", searchtext });
attribs_.insert({ "patterns", patterns });
setBody(body);
};
// build a message for file download reply used by the server
void Message::configureFileDownloadReply(const std::string& filename, const std::string& srcAddress, const std::string& dstAddress, const std::string& servernumber, std::string& serverrelativepath, std::string& localpath, const std::string& mode, size_t contentLen){
clear();
setFiletoUpload(filename);
setCommand("FILE_DOWNLOAD_REPLY");
fileUploadBlockLen_ = contentLen;
attribs_.insert({ "srcAddress", srcAddress });
attribs_.insert({ "dstAddress", dstAddress });
attribs_.insert({ "mode", mode });
attribs_.insert({ "servernumber", servernumber });
attribs_.insert({ "serverrelativepath", serverrelativepath });
attribs_.insert({ "localpath", localpath });
};
// get the block length when send the file block by block
void Message::setFileUploadBlockLength(size_t contentLen){
fileUploadBlockLen_ = contentLen;
}
// add attribute to the message
bool Message::addAttrib(const std::string& name, const std::string& value){
std::pair<std::string, std::string> attrib = { name, value };
attribs_.insert(attrib);
return true;
};
// get all the attributes of the message
std::map<std::string, std::string> Message::getAttributes(){
return attribs_;
};
// clear the files of the message that have been set previously
void Message::clear(){
command_ = "";
filename_ = "";
fileUploadBlockLen_ = 0;
attribs_.clear();
};
#ifdef TEST_MESSAGE
int main()
{
Message ms;
ms.configureFileUploadMsg("SameFile.txt", "::1@9080", "::1@8090");
ms.configureQuitMsg("::1@9080", "::1@8090");
ms.configureFileUploadReply("SameFile.txt", "::1@9080", "::1@8090", "1", "../Server", "success");
return 0;
}
#endif | true |
3fced59174541f383aa12852df9e52354ee57872 | C++ | icrelae/cpp_primer | /6-function/6.12-parameter_passing.cpp | UTF-8 | 281 | 3.078125 | 3 | [] | no_license | /* 2016.10.05 12:46
* P_190
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void Swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
int main(int argc, char **argv)
{
int a = 10, b = 80;
Swap(a, b);
cout << a << ' ' << b;
return 0;
}
| true |
948cfea0a9f0bce4470b066d66b67099c86ec518 | C++ | lizzyly7/SmartDraw | /aBaseTool/src/utility/Ini.cpp | UTF-8 | 3,758 | 2.515625 | 3 | [] | no_license | #include <assert.h>
#include <utility\ini.h>
#include <fstream>
#include <windows.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
// parameter :
// description :
// remarks :
// returns :
CIni::CIni()
{
m_szFilePath[0] = '\0';
}
// parameter :
// description :
// remarks :
// returns :
CIni::~CIni()
{
for(list<SECTION*>::iterator itr=m_lstSection.begin();itr != m_lstSection.end();){
delete ((*itr)->plst);
m_lstSection.erase(itr++);
}
}
// parameter :
// description :
// remarks :
// returns :
bool CIni::Read(const char* pszFilePath){
assert(pszFilePath && "pszFilePath is NULL");
bool bRet=false;
if(pszFilePath){
static char szLine[1024]={0,};
ifstream file(pszFilePath);
while(file.good()){
memset(szLine,'\0',1024);
file.getline(szLine,1024);
ParseLine(szLine);
}
file.close();
}
return bRet;
}
// parameter :
// description :
// remarks :
// returns :
void CIni::ParseLine(const char* pszLine){
assert(pszLine && "pszLine is NULL");
if(pszLine){
static char szSection[MAX_KEY_LEN]={0,};
CIni::KEY_VALUE varKeyValue;
char szKey[MAX_KEY_LEN]={0,},szValue[MAX_VAL_LEN]={0,};
// SECTION.
if(('[' == pszLine[0]) && (']' == pszLine[strlen(pszLine) - 1])){
memset(szSection,'\0',MAX_KEY_LEN);
strncpy(szSection,pszLine + 1,MAX_KEY_LEN);
szSection[MAX_KEY_LEN - 1] = '\0';
int nLen=strlen(szSection);
if(']' == szSection[nLen - 1]){
szSection[nLen - 1] = '\0';
nLen--;
}
for(int i = 0;i < nLen;i++) szSection[i] = toupper(szSection[i]);
}else if(strchr(pszLine,'=')){
for(int i=0;pszLine[i] && ('=' != pszLine[i]);i++) varKeyValue.szKey[i] = pszLine[i];
varKeyValue.szKey[i] = '\0';
strncpy(varKeyValue.szValue,pszLine + i + 1,MAX_VAL_LEN);
varKeyValue.szValue[MAX_VAL_LEN - 1] = '\0';
int nLen=strlen(varKeyValue.szKey);
for(i = 0;i < nLen;i++) varKeyValue.szKey[i] = toupper(varKeyValue.szKey[i]);
nLen=strlen(varKeyValue.szValue);
for(i = 0;i < nLen;i++) varKeyValue.szValue[i] = toupper(varKeyValue.szValue[i]);
bool bFind=false;
for(list<CIni::SECTION*>::iterator itr=m_lstSection.begin();itr != m_lstSection.end();++itr){
if(0 == strcmp((*itr)->szSection,szSection)){
if((*itr)->plst) (*itr)->plst->push_back(varKeyValue);
bFind = true;
break;
}
}
if(!bFind){
SECTION* pSection=(CIni::SECTION*)calloc(sizeof(CIni::SECTION),1);
if(pSection){
strcpy(pSection->szSection,szSection);
pSection->plst = new list<CIni::KEY_VALUE>;
pSection->plst->push_back(varKeyValue);
m_lstSection.push_back(pSection);
}
}
}
}
}
// parameter :
// description :
// remarks :
// returns :
char* CIni::Value(const char* pszSection,const char* pszKey){
assert(pszSection && "pszSection is NULL");
assert(pszKey && "pszKey is NULL");
if(pszSection && pszKey){
char szSection[MAX_KEY_LEN]={0,},szKey[MAX_KEY_LEN]={0,};
strncpy(szSection,pszSection,MAX_KEY_LEN);
szSection[MAX_KEY_LEN - 1] = '\0';
int nLen=strlen(szSection);
for(int i = 0;i < nLen;i++) szSection[i] = toupper(szSection[i]);
strncpy(szKey,pszKey,MAX_KEY_LEN);
szKey[MAX_KEY_LEN - 1] = '\0';
nLen=strlen(szKey);
for(i = 0;i < nLen;i++) szKey[i] = toupper(szKey[i]);
for(list<CIni::SECTION*>::iterator itr=m_lstSection.begin();itr != m_lstSection.end();++itr){
if(0 == strcmp((*itr)->szSection,szSection)){
for(list<CIni::KEY_VALUE>::iterator itrKeyValue=(*itr)->plst->begin();itrKeyValue != (*itr)->plst->end();++itrKeyValue){
if(0 == strcmp(szKey,itrKeyValue->szKey)) return itrKeyValue->szValue;
}
}
}
}
return NULL;
}
| true |
1db28d7771223249d247c6b093195fc9c34077b7 | C++ | ExcaliburEX/My-oj | /蓝桥_芯片测试_3.25.cpp | GB18030 | 659 | 3.046875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
int count1[25];
int arr[25][25];
int main()
{
int n, i, j;
cin >> n;
for (i = 0; i<n; i++)
{
for (j = 0; j<n; j++)
{
cin >> arr[i][j];
}
}
for (j = 0; j<n; j++)
{
for (i = 0; i<n; i++)
{
if (j != i && arr[i][j] == 1) //ΪλͳÿоƬоƬԼ
{
count1[j]++;
}
}
}
for (j = 0; j<n; j++)
{
if (count1[j] >= n / 2) //жΪõĴһߵһΪоƬΪоƬ
{
cout << j + 1<<" ";
}
}
cout << endl;
return 0;
} | true |
fe8e00f542f29a6bd5e6f88544d2785231b17286 | C++ | jediserg/ws-server | /tests/fake_ws_server_impl.cpp | UTF-8 | 1,165 | 2.53125 | 3 | [] | no_license | //
// Created by serg on 7/6/16.
//
#include "fake_ws_server_impl.h"
FakeWsServerImpl::FakeWsServerImpl() {
}
void FakeWsServerImpl::_close(Connection c) {
auto info = _map.find(c);
if(info == _map.end())
return;
info->second = {.is_oppened = true, .in_msg_cnt = 0, .out_msg_cnt = 0};
_onClose(c);
}
void FakeWsServerImpl::_send(Connection c, std::string data) {
auto info = _map.find(c);
if(info == _map.end())
return;
info->second.out_msg_cnt++;
info->second.last_out = data;
}
FakeWsServerImpl::ConnectionMap &FakeWsServerImpl::getConnsctions() {
return _map;
}
FakeWsServerImpl::Connection FakeWsServerImpl::newConnection() {
static int last_id = 1;
Connection con = std::make_shared<int>(last_id++);
ConnectionInfo info {.is_oppened = true, .in_msg_cnt = 0, .out_msg_cnt = 0};
_map[con] = info;
_onOpen(con);
return con;
}
void FakeWsServerImpl::recvMessage(Connection c, std::string msg) {
auto info = _map.find(c);
if(info == _map.end())
return;
info->second.last_in = msg;
info->second.in_msg_cnt++;
_onMessage(c, msg);
}
| true |
0938545493ab7d4da66fbf62cd40ddf07c7c1ba4 | C++ | sameerkhan97/data-structure-sheet | /searching sorting/ProductArrayPuzzle.cpp | UTF-8 | 1,064 | 3.765625 | 4 | [] | no_license | /*Given an array A[] of size N, construct a Product Array P (of same size N) such that P[i]
is equal to the product of all the elements of A except A[i].
Example 1:
Input: N = 5 A[] = {10, 3, 5, 6, 2}
Output: 180 600 360 300 900
Explanation:
For i=0, P[i] = 3*5*6*2 = 180.
For i=1, P[i] = 10*5*6*2 = 600.
For i=2, P[i] = 10*3*6*2 = 360.
For i=3, P[i] = 10*3*5*2 = 300.
For i=4, P[i] = 10*3*5*6 = 900.
Example 2:
Input: N = 2 A[] = {12,0}
Output: 0 12 */
vector<long long int> productExceptSelf(vector<long long int>& nums, int n) {
vector<long long int> vec(n,1ll);
long long int temp=1ll;
// In this loop temp will store the product of values on the left side of nums[i]
for(int i=0;i<n;i++)
{
vec[i]*=temp;
temp*=nums[i];
}
// In this loop temp will store the product of values on the right side of nums[i]
temp=1ll;
for(int i=n-1;i>=0;i--)
{
vec[i]*=temp;
temp*=nums[i];
}
return vec;
}
| true |
e30a56b42a9ee24c29e82333fb791545d48287c6 | C++ | WilliamMajor/CmpE142-Assignment3 | /src/Swap.h | UTF-8 | 344 | 2.5625 | 3 | [] | no_license | #ifndef SWAP_H
#define SWAP_H
#include <iostream>
using namespace std;
class Swap
{
public:
Swap();
~Swap();
string getPID() const;
string getVM() const;
void setPID(string argPID);
void setVM(string argVM);
private:
string PID;
string VM;
};
#endif | true |
64648b0c33b6d21468dd59bdc44ac67cc49a3b38 | C++ | duffwang/hash-table-simple | /hashtable.cpp | UTF-8 | 2,212 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
class Node {
public:
string key, value;
Node* next;
Node(string a, string b) {
key = a;
value = b;
next = NULL;
}
};
class LinkedList {
public:
Node* start;
int insertData(string key, string value){
Node* node_last = start;
Node* node_temp = start;
while (node_temp != NULL && node_temp->key != key) {
node_last = node_temp;
node_temp = node_temp->next;
}
node_last->next = new Node(key, value);
if (node_temp != NULL) {
node_last->next->next = node_temp->next;
delete node_temp;
}
return(1);
}
void dump() {
Node* current = start;
while (current->next != NULL) {
current = current->next;
cout << "\nCurrent key " << current->key << " with value " << current->value << "\n";
}
}
string getData(string keyToGet) {
Node* current = start;
while (current->next != NULL) {
current = current->next;
if (current->key == keyToGet) {
return(current->value);
}
}
return("Could not find");
}
LinkedList() {
start = new Node("head", "");
}
};
class Hashtable {
public:
LinkedList* table;
int hash_size;
int hash(string key) {
int hash_value = 0;
for (int i = 0; i < key.length(); i++)
hash_value += key[i];
return hash_value % hash_size;
}
int insertData(string key, string value) {
int hash_value = hash(key);
table[hash_value].insertData(key, value);
return 1;
}
string getData(string key) {
int hash_value = hash(key);
return(table[hash_value].getData(key));
}
void dump(string key) {
int hash_value = hash(key);
table[hash_value].dump();
}
Hashtable(int size) {
table = new LinkedList[size];
hash_size = size;
}
~Hashtable() {
delete [] table;
}
};
int main() {
Hashtable test(3);
test.insertData("testdfsersdf", "womp");
test.insertData("dffd", "tim");
test.insertData("dff", "PLO");
test.insertData("testdfsdfsersdf", "123");
test.insertData("fsda", "321");
test.insertData("testdfsersdf", "3233");
test.insertData("wer", "1");
test.insertData("tre", "2");
test.insertData("dff", "PLO2");
test.dump("testdfsersdf");
cout << "\n\n\n\n" << test.getData("dff");
return 0;
}
| true |
d2d6982c137835cf14eb3f95e6eb75c1340b4b46 | C++ | gcc-o-o/cpp_code | /content_1/text/textin4.cpp | UTF-8 | 243 | 3.625 | 4 | [] | no_license | //textin4.cpp read char with cin.get()
#include<iostream>
int main(void)
{
using namespace std;
char ch;
int count=0;
while((ch=cin.get())!=EOF)
{
cout.put(ch);
count++;
}
cout<<endl<<count<<" characters read"<<endl;
return 0;
} | true |
82b1f5dce1431e252b9ba5faf66838c016081d25 | C++ | Joklost/sims | /include/sims/link.h | UTF-8 | 890 | 2.796875 | 3 | [
"MIT"
] | permissive | #ifndef MANETSIMS_LINK_H
#define MANETSIMS_LINK_H
#include <utility>
#include <ostream>
#include <functional>
#include "node.h"
namespace sims {
class Link {
public:
Link() = default;
Link(unsigned long long id, sims::Node &node1, sims::Node &node2);
const ::std::pair<sims::Node, sims::Node> &get_nodes() const;
double get_distance() const;
unsigned long long get_id() const;
bool operator==(const Link &rhs) const;
bool operator!=(const Link &rhs) const;
bool operator<(const Link &rhs) const;
bool operator>(const Link &rhs) const;
bool operator<=(const Link &rhs) const;
bool operator>=(const Link &rhs) const;
double distance{};
private:
unsigned long long id{};
::std::pair<sims::Node, sims::Node> nodes;
};
}
#endif /* MANETSIMS_LINK_H */
| true |
df3a2cd485d0a26ccd14e908eb386f158bdac6af | C++ | Sylwestrone/Game-engine | /ComponentMovement.h | UTF-8 | 1,218 | 2.875 | 3 | [] | no_license | #ifndef MOVEMENT_COMPONENT_H
#define MOVEMENT_COMPONENT_H
#include <vector>
#include <list>
#include "Component.h"
#include "Map.h"
class ComponentMovement : public Component
{
public:
ComponentMovement(Map& gameMap);
ComponentMovement* clone() const override;
const std::vector<int>& getPath() const;
void acceptMessage(MessageType messageType);
void setDestinationTile(int tileIndex);
virtual void update(GameEntity& gameEntity);
private:
class PathStep
{
public:
int tileIndex;
unsigned int pathScoreG;
unsigned int pathScoreH;
PathStep* parent;
PathStep(int tileIndex, unsigned int pathScoreG, unsigned int pathScoreH, PathStep* parent = nullptr) : tileIndex(tileIndex), pathScoreG(pathScoreG), pathScoreH(pathScoreH), parent(parent) {}
unsigned int getScoreF() { return pathScoreG + pathScoreH;}
};
int destinationTile;
Map& gameMap;
bool isPathCalculated = false;
float movementSpeed;
std::vector<int> path;
bool messageSent = false;
void findNewPath(GameEntity& gameEntity);
unsigned int getHeuristicDistance(int startTileIndex, int endTileIndex);
};
#endif // MOVEMENT_COMPONENT_H
| true |
273a29b9e811a5b35a00b41388357d9ed9392e17 | C++ | TimberToss/tp-lab-7 | /src/LivingObject.cpp | UTF-8 | 2,398 | 3.296875 | 3 | [] | no_license | #include "LivingObject.h"
#include "Ocean.h"
#include "Cell.h"
LivingObject::LivingObject(int x, int y, Ocean* ocean) : Object(x, y, ocean) {}
LivingObject::LivingObject(Coordinates coordinates, Ocean* ocean) : Object(coordinates, ocean) {}
void LivingObject::move(int x, int y) {
ocean->getCell(&location)->setObject(nullptr);
location = { x,y };
ocean->getCell(x,y)->setObject(this);
}
void LivingObject::motion() {
int where = rand() % 4;
Cell* cellTo;
switch (where) {
case UP:
cellTo = ocean->getCell(location.x, location.y - 1);
if (cellTo != nullptr && checkCell(cellTo)) {
move(location.x, location.y - 1);
}
break;
case RIGHT:
cellTo = ocean->getCell(location.x + 1, location.y);
if (cellTo != nullptr && checkCell(cellTo)) {
move(location.x + 1, location.y);
}
break;
case DOWN:
cellTo = ocean->getCell(location.x, location.y + 1);
if (cellTo != nullptr && checkCell(cellTo)) {
move(location.x, location.y + 1);
}
break;
case LEFT:
cellTo = ocean->getCell(location.x - 1, location.y);
if (cellTo != nullptr && checkCell(cellTo)) {
move(location.x - 1, location.y);
}
break;
}
}
void LivingObject::die() {
ocean->deleteObject(this);
ocean->getCell(&location)->setObject(nullptr);
delete this;
}
void LivingObject::birth() {
ocean->addObject(this);
ocean->getCell(&location)->setObject(this);
}
std::vector<Cell*> LivingObject::getNeighbouredCells() {
std::vector<Cell*> neighbours;
for (int i = -1, j = -1; i < 2; i++) {
Cell* cellTo = ocean->getCell(location.x + i, location.y + j);
if (cellTo) {
neighbours.push_back(cellTo);
}
}
for (int i = -1, j = 1; i < 2; i++) {
Cell* cellTo = ocean->getCell(location.x + i, location.y + j);
if (cellTo) {
neighbours.push_back(cellTo);
}
}
Cell* cellTo = ocean->getCell(location.x - 1, location.y);
if (cellTo) {
neighbours.push_back(cellTo);
}
cellTo = ocean->getCell(location.x + 1, location.y);
if (cellTo) {
neighbours.push_back(cellTo);
}
return neighbours;
} | true |
07bedff0ccc66593c8bfa64d10c0d784f0b71ccb | C++ | danymtz/C-Course-for-begginers | /01.- Preliminares.cpp | ISO-8859-1 | 2,749 | 3.09375 | 3 | [] | no_license | /*Estructura general de un programa econmico en C.
main()
{
//Sentencia 1;
//Sentencia 2;
//Sentencia n;
}
////////////////////////////////////////////////////////////////////////////////
Estructura de control condicional if, else if, else en C
if (condicin)
{
Sentencia 1;
Sentencia 2;
Sentencia n;
}
else if (condicin)
{
Sentencia 1;
Sentencia 2;
Sentencia n;
}
else
{
Sentencia 1;
Sentencia 2;
Sentencia n;
}
"if" compara valores para aprobarlos como verdadero o falso
y decidir si ejecutar el segmento que incluye
"else if" es un segmento alternativo que tambin incluye condicn en caso de
de que "if" haya resultado falso. Se pueden usar tantos "else if" como el usuario desee
"else" es un segmento alternativo que NO lleva condicin, y este puede
incluirse o no.
NOTA: Si if, else if else slo incluyen una sentencia(lnea) en su segmento,
se puede omitir el uso de llaves "{ }"
Ejm:
if (condicin)
Sentencia 1;
else if (condicin)
Sentencia 1;
else
Sentencia 1;
/////////////////////////////////////////////////////////////////////////////////////////
Estructura de control condicional multiple en C
switch-case
switch(valor)
{
case 1:
Sentencia 1;
Sentencia 2;
Sentencia n;
break;
case 2:
Sentencia 1;
Sentencia 2;
Sentencia n;
break;
case 3:
Sentencia 1;
Sentencia 2;
Sentencia n;
break;
case n:
Sentencia 1;
Sentencia 2;
Sentencia n;
break;
default:
Sentencia por defecto;
}
"switch" analiza y compara un valor para ejecutar sentencias
"case" permite enumerar las posibilidades de ejecutar un segmento de cdigo
desde la lnea en que ste se encuentra
"break" termina las sentencias y sale de la estructura de control para seguir ejecutando
cdigo que est fuera de esta
"default" contiene las sentencias que siempre se ejecutaran simpre QUE NO se ejecute ningn "case"
//////////////////////////////////////////////////////////////////////////////////////////////////////
CICLOS O BUCLES
/*
Estructura de control precondicional
for (inicializacin; condicin; iteracin)
{
Sentencias...
}
*/
/*
Estructura de control precondicional controlada por eventos
while (condicin)
{
Sentencias...
Iteracin
}
*/
/*
Estructura de control post-condicional controlada por eventos
do
{
Sentencias...
Iteracin...
}while(Condicin);
*/
/*
Anidamiento
ifs aninados
*/
| true |
3c41f457a58158979ae3114ed473ade3170788e6 | C++ | kahyunKo/C-plus-plus_class | /ch03/default.cpp | UHC | 433 | 3.6875 | 4 | [] | no_license | // p140
#include <iostream>
using namespace std;
void display(char c = '*', int n = 10) {
for (int i = 0; i < n; i++) {
cout << c;
}
cout << endl;
}
int main() {
cout << "ƹ μ ʴ : \n";
display();
cout << "\nù ° μ Ǵ : \n";
display('#');
cout << "\n μ Ǵ : \n";
display('#', 5);
return 0;
} | true |
685dbae86cde7d49f77cf78315aeff4fcc943054 | C++ | linmx0130/OJCode | /RQNOJ/40/main.cpp | UTF-8 | 493 | 2.6875 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
string h[10000];
int t,mm;
int main(){
h[1]="http://www.acm.org/";
t=1;
mm=1;
string s;
while (cin >>s){
if (s=="VISIT"){
cin>>s;
cout << s <<endl;
h[++t]=s;
mm=t;
continue;
}
if (s=="BACK"){
if (t==1) cout <<"Ignored\n";
else cout << h[--t] <<endl;
continue;
}
if (s=="FORWARD"){
if (t==mm) cout <<"Ignored\n";
else cout <<h[++t] <<endl;
continue;
}
if (s=="QUIT") return 0;
}
}
| true |
ca36cb7725762de0df64463a76d457c78efe6850 | C++ | huimingli/leetcodedailyworks | /LeetcodeProject/isHappy.h | UTF-8 | 386 | 2.6875 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include<unordered_set>
#include<queue>
using namespace std;
bool isHappy(int n) {
string num = to_string(n);
int sum = 0;
for (char a : num) {
sum += pow((a - '0'), 2);
}
if (sum<6 && sum != 1) {
return false;
}
if (sum == 1) return true;
return isHappy(sum);
} | true |
d5a7b595b8721aa42981b375e176cd69bd4f76ab | C++ | tisma/ctorious | /runner_agent.cpp | UTF-8 | 1,104 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | #include <atomic>
#include <chrono>
#include <thread>
#include <utility>
#include <fmt/printf.h>
#include <gsl/gsl_assert>
template <typename Agent> concept IsAgent = requires(Agent agent) {
{agent.doWork()};
};
template <typename Agent> requires IsAgent<Agent> class Runner {
public:
Runner(Agent &&agent) : m_agent(std::forward<Agent>(agent)) {}
constexpr void start() {
m_running = true;
m_thread = std::thread([&]() { run(); });
}
constexpr void run() {
while (m_running) {
m_agent.doWork();
}
}
constexpr void stop() {
m_running = false;
m_thread.join();
}
~Runner() { Expects(m_running == false); }
private:
Agent m_agent;
std::thread m_thread;
std::atomic<bool> m_running{false};
};
template <typename Agent> Runner(Agent &&)->Runner<Agent>;
class HelloWorldAgent {
public:
void doWork() noexcept { fmt::print("Hello, {}!\n", "Nanosecond"); }
};
int main() {
using namespace std::chrono_literals;
auto runner = Runner{HelloWorldAgent{}};
runner.start();
std::this_thread::sleep_for(2s);
runner.stop();
return 0;
}
| true |
c9533817b63cd97f03c23e313bcca9365be0cca3 | C++ | swzhangmit/Coding-Practice | /Codeforces/1055/d/d.cc | UTF-8 | 2,931 | 2.875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
void computeLPSArray(string pat, int M, int* lps);
int KMPSearch(string pat, string txt)
{
int M = pat.length();
int N = txt.length();
int lps[M];
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
int j = 0; // index for pat[]
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
return i - j;
j = lps[j - 1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return -1;
}
void computeLPSArray(string pat, int M, int* lps)
{
int len = 0;
lps[0] = 0; // lps[0] is always 0
int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else {
if (len != 0) {
len = lps[len - 1];
}
else {
lps[i] = 0;
i++;
}
}
}
}
int main() {
int n;
cin >> n;
vector<string> w1;
vector<string> w2;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
w1.push_back(s);
}
for (int i = 0; i < n; i++) {
string s;
cin >> s;
w2.push_back(s);
}
vector<string> diffs1;
vector<string> diffs2;
vector<int> startindices;
vector<int> endindices;
string find = " ";
string replace = " ";
for (int i = 0; i < n; i++) {
if (w1[i] == w2[i]) {
//sames.push_back(w1[i]);
} else {
diffs1.push_back(w1[i]);
diffs2.push_back(w2[i]);
int startix = -1;
int endix = -1;
for (int j = 0; j < w1[i].length(); j++) {
if (w1[i][j] != w2[i][j]) {
startix = j;
startindices.push_back(startix);
break;
}
}
for (int j = w1[i].length() - 1; j >= 0; j--) {
if (w1[i][j] != w2[i][j]) {
endix = j + 1;
endindices.push_back(endix);
break;
}
}
string start = w1[i].substr(startix, endix - startix);
string end = w2[i].substr(startix, endix - startix);
if (find == " ") {
find = start;
replace = end;
} else if (find != start || replace != end) {
cout << "NO" << endl;
return 0;
}
}
}
for (int i = 0; i < startindices.size(); i++) {
for (int j = startindices[i]; j < ?; j++) {
//finish later
}
}
for (int i = 0; i < w1.size(); i++) {
int search = KMPSearch(find, w1[i]);
if (search != -1 && w2[i].substr(search, find.length()) != replace) {
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
cout << find << endl << replace << endl;
return 0;
}
| true |
3b4e780f295651f3a1e6386ce4d9327dbfacd44d | C++ | igorbrasileiro/competitive | /aa-intermediary/19.1/list4/c.cpp | UTF-8 | 2,629 | 3.15625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
// Multiples of 3
struct node {
int lazy;
vector<int> mult; // alterar pra vector
};
void print_arr(vector<node> &sgtree) {
for (int i = 0; i < sgtree.size(); i++) {
cout << '[';
for(auto &c: sgtree[i].mult) {
cout << c << ',';
}
cout << "] ";
}
cout << endl;
}
void func(vector<int> &mults, vector<int> &a, vector<int> &b) {
mults[0] = a[0] + b[0];
mults[1] = a[1] + b[1];
mults[2] = a[2] + b[2];
}
void shiftRight(vector<int> &mults) {
int aux = mults[2];
mults[2] = mults[1];
mults[1] = mults[0];
mults[0] = aux;
}
void propagate(vector<node> &sgtree, int id, int L, int R) {
if (L != R) {
sgtree[2 * id].lazy += sgtree[id].lazy;
sgtree[2 * id + 1].lazy += sgtree[id].lazy;
}
for (int i = 0; i < sgtree[id].lazy % 3; i++) {
shiftRight(sgtree[id].mult);
}
sgtree[id].lazy = 0;
}
void build(vector<node> &sgtree, int id, int L, int R) {
if (L == R) {
sgtree[id].lazy = 0;
sgtree[id].mult = {1, 0, 0};
} else {
int mid = (L + R) / 2;
build(sgtree, 2 * id, L, mid);
build(sgtree, 2 * id + 1, mid + 1, R);
sgtree[id].lazy = 0;
sgtree[id].mult = {0,0,0};
func(sgtree[id].mult, sgtree[2 * id].mult, sgtree[2 * id + 1].mult);
}
}
int query(vector<node> &sgtree, int id, int L, int R, int X, int Y) {
if (X <= L and R <= Y) {
propagate(sgtree, id, L, R);
return sgtree[id].mult[0];
} else if (X > R || Y < L) {
// should have a propagete here, but without get accepted
return 0;
} else {
propagate(sgtree, id, L, R);
int m = (L + R) / 2;
return query(sgtree, 2 * id, L, m, X, Y) + query(sgtree, 2 * id + 1, m + 1, R, X, Y);
}
}
void update(vector<node> &sgtree, int id, int L, int R, int X, int Y) {
if (X <= L and R <= Y) {
sgtree[id].lazy += 1;
propagate(sgtree, id, L, R);
} else if (X > R || Y < L) {
propagate(sgtree, id, L, R);
return;
} else {
propagate(sgtree, id, L, R);
int m = (L + R) / 2;
update(sgtree, 2 * id, L, m, X, Y);
update(sgtree, 2 * id + 1, m + 1, R, X, Y);
func(sgtree[id].mult, sgtree[2 * id].mult, sgtree[2 * id + 1].mult);
}
}
int main() {
int N, Q, OP, A, B;
scanf("%d%d", &N, &Q);
vector<node> sgtree(N * 4);
build(sgtree, 1, 1, N);
// print_arr(sgtree);
for (int i = 0; i < Q; i++) {
scanf("%d%d%d", &OP, &A, &B);
if (OP == 1) {
printf("%d\n", query(sgtree, 1, 1, N, A + 1, B + 1));
} else {
update(sgtree, 1, 1, N, A + 1, B + 1);
// printf("%d %d\n", A + 1, B + 1);
// print_arr(sgtree);
}
}
return 0;
} | true |
971053d1df09fbe02ae05445ca0fa76708b28ccc | C++ | ThaliaVillalobos/fileIO_B | /Villalobos_IOB.cpp | UTF-8 | 2,217 | 3.328125 | 3 | [] | no_license | //Name:Thalia Villalobos
//22 Oct 2015
//Write a program that will utilize a text input file (scores.txt) and compute the listed specifications. The text input file "scores.txt" is provided. Write a program to compute numeric grades for a course. The course records are a file that will serve as the input file. The input file format is specified "scores.txt".
#include<iostream> //cin, cout
#include<fstream> //fin, fout
#include<string> //string
#include<cstdlib> //exit()
#include<iomanip> //(ios::fixed)
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
char file_name [12];
double max= 0;
string firstName, lastName, highestFirstName, hightestLastName;
double s1,s2,s3,s4,s5,s6, average, userAverage;
cout << "Enter file_name:" << endl;
cin >> file_name;
//Open files
fin.open(file_name);
fout.open("results.txt");
//Check if there is an error when both file fail to open
if (fin.fail())
{
cout << "Error opening input file" << endl;
exit(1);
}
if (fout.fail())
{
cout << "Error opening input file" << endl;
exit(1);
}
//Loop
while(fin >> firstName >> lastName >> s1 >> s2 >> s3 >> s4 >> s5 >> s6)
{
fout.setf(ios::fixed);
fout.setf(ios::showpoint);
fout.precision(1);
fout.setf(ios::left);
average = (s1+s2+s3+s4+s5) / 5;
if (average >= max)
{
highestFirstName = firstName;
hightestLastName = lastName;
max = average;
}
else
{
max = max;
}
//Output to results.txt
fout << setw(12) << firstName << setw(12) << lastName << setw(6)
<< s1 << setw(6) << s2 << setw(6) << s3 << setw(6)
<< s4 << setw(6) << s5;
fout.precision(2);
fout << setw(8) << average << setw(8) <<endl;
} //endl of loop
fout << "\nHighest score: " << setw(8) << highestFirstName << setw(10)
<< hightestLastName << endl;
fin.close();
fout.close();
return 0;
}
| true |
5fac3de27fd3d6ac8406aea1cab4e11f2dde80cf | C++ | ibMH/multi_robot_system | /formation/include/formation/formation_publisher.h | UTF-8 | 2,497 | 2.8125 | 3 | [] | no_license | #pragma once
#include<ros/ros.h>
#include<formation/formation.h>
class FormationPublisher{
public:
/**
* @brief Construct a new Formation Publisher object
*
*/
FormationPublisher();
/**
* @brief Construct a new Formation Publisher object for a given formation
*
* @param formation pointer to the formation wich data should be published
*/
FormationPublisher(Formation* formation);
void publishPoses();
/**
* @brief Publishs the laser scan data of the hole formation
*
*/
void publishLaserScans();
/**
* @brief Publishs the clustered laser scan data of the hole formation
*
*/
void publishClusteredLaserScans();
/**
* @brief Publishs the Poses wich are predicted by the laser scanner data
*
*/
void publishScanPoses();
/**
* @brief Publishs the Laser scanner data of the formation
*
*/
void publishSeperatedLaserScans();
/**
* @brief Publishs the clustered Laser scanner data of the formation
*
*/
void publishSeperatedClusterScans();
/**
* @brief Publish the Poses wich are determined from the lasser scanner data within the formation
*
*/
void publishSeperatedScannedPoses();
/**
* @brief Publishs all the formation data
*
*/
void publish();
private:
std::shared_ptr<Formation> formation_; //< Pointer to the formation wich data should be published
ros::NodeHandle nh_; //< Nodehandle for clearing namespaces of the published topics
ros::Publisher scan_pub_; //< Publihser for the hole formation scanner data
ros::Publisher cluster_scan_pub_; //<Publisher for the hole clustered scan data
std::map<std::string,ros::Publisher> pose_pub_list_;
std::map<std::string,ros::Publisher> scan_pub_list_; //< List of publishers for publishing each robots laser scanner data
std::map<std::string,ros::Publisher> cluster_scan_pub_list_; //< List of publisher for publishing each robots clustered laser scanner data
bool publish_pose_;
bool publish_scans_;
bool publish_scans_clustered_;
bool publish_seperated_;
bool publish_combined_;
};
| true |
dd094bc80809d5e8a42a8c85c1f2426ee2d98738 | C++ | Nazrath10R/RUHI-MSA | /Archive/old_scripts/main_pedro_saved.cpp | UTF-8 | 94,458 | 3.25 | 3 | [] | no_license |
// main.cpp
// ptm
//
// Created by Nazrath Nawaz on 28/08/2019.
// Developed by Pedro Cardoso on 09/06/2020.
// Copyright © 2019 Nazrath Nawaz. All rights reserved.
//
//uiuiuiu
#include <iostream>
#include <fstream>
#include <vector>
#include "string"
#include <limits>
#include <algorithm>
#include <math.h>
#include <chrono>
#include <tuple>
#include <sstream>
#include <cstdlib>
//=======================================================================================================//
using namespace std;
// function to extract line of file based on position specified
void GotoLine(fstream& file, unsigned int num) {
file.seekg(ios::beg);
for (int i = 0; i < num - 1; ++i) {
file.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
//fuction that finds all elements of a list that are within a certain range
vector<int> binarySearch( float masses[], const int &array_Size, const float &mass_shift_lower, const float &mass_shift_upper) {
size_t first = 0; //first array element
size_t last = array_Size - 1; //last array element
size_t middle {}; //mid point of search
vector<int> position {}; //position of search value
bool found = false; //flag
while ((first<=last) && (found==false)) {
middle = (first + last) / 2; //this finds the mid point
if ((roundf(masses[middle]*10000)/10000 <= mass_shift_upper) &&
(roundf(masses[middle]*10000)/10000 >= mass_shift_lower)) {
position.push_back(middle); //we might have more than one match! need to change code for that
int set_middle = middle; // to use on the way down the array
middle = middle + 1; //moving up the array
while (roundf(masses[middle]*10000)/10000 <= mass_shift_upper) {
position.push_back(middle);
middle++;
}
set_middle = set_middle - 1; //moving down the array
while (roundf(masses[set_middle]*10000)/10000 >= mass_shift_lower) {
position.push_back(set_middle);
set_middle--;
}
found = true;
}
else if (masses[middle] > mass_shift_upper) { // if it's in the lower half
last = middle - 1;
}
else {
first = middle + 1; //if it's in the upper half
}
}
return position;
}
//using Binary Search principle to obtain specific value
int binarySearchSmallerElement_decreasing(float masses[], const float &mass_shift, const int &size_of_array){
int l = 0;
int r = size_of_array -1;
int resultantIndex = size_of_array;
while(l<=r) {
int mid = l + (r-l) / 2;
if(masses[mid] >= mass_shift){
l = mid +1;
}
else{
r = mid -1;
resultantIndex = mid;
}
}
if (resultantIndex == size_of_array)
return (resultantIndex -1);
else
return (resultantIndex);
}
//using Binary Search principle to obtain specific value
int SpecificBinarySearch( float masses[], const int &array_Size, const float &number) {
size_t first = 0; //first array element
size_t last = array_Size - 1; //last array element
size_t middle {}; //mid point of search
while (first<=last) {
middle = (first + last) / 2; //this finds the mid point
if ((roundf(masses[middle]*10000)/10000 == number)) {
return middle;
}
else if ((roundf(masses[middle]*10000)/10000 > number)) { // if it's in the lower half
last = middle - 1;
}
else {
first = middle + 1; //if it's in the upper half
}
}
return -1; //not found
}
//using Binary Search principle to obtain fisrt value of the list that is bigger than a specific value (mass_shift)
int binarySearchLargerElement( float masses[], const float &mass_shift, const int &size_of_array) {
int l = 0;
int r = size_of_array -1;
int resultantIndex = size_of_array;
while(l<=r) {
int mid = l + (r-l) / 2;
if(masses[mid] <= mass_shift){
l = mid +1;
}
else{
r = mid -1;
resultantIndex = mid;
}
}
if (resultantIndex == size_of_array)
return (resultantIndex -1);
else
return (resultantIndex);
}
std::tuple<vector<int>*, vector<int>*, int*> finding1PTM ( float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
vector<int> highest_prob_pos_1 {PTM_list-1};
//Storing all possible PTMs on position_combination1
vector<int> position_combination1 = binarySearch(masses, PTM_list, mass_shift_lower, mass_shift_upper); //all PTMs that are withing our tolerance
int pos_length = position_combination1.size();
if (pos_length > 1) //checking which of the PTMs is more probable and storing
for ( size_t i {0}; i < pos_length; i++) { //
//cout << position_combination1[i] << " is the position! The number is " << masses[position_combination1[i]]
//cout << " that is bigger than " << mass_shift_lower << " and lower than " << mass_shift_upper << endl;
if (prob[position_combination1[i]] >= prob[highest_prob_pos_1[0]])
highest_prob_pos_1[0] = position_combination1[i];
}
else if (pos_length ==1) {
highest_prob_pos_1[0] = position_combination1[0];
}
else {
//cout << "\n" << "The mass shift can not be explained by 1 PTM " << endl;
}
return {&highest_prob_pos_1, &position_combination1, &pos_length};
}
std::tuple<vector<int>, vector<int>, int> findingCombinationOf2PTM ( float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
vector<int> position_combination2 {}; // here is were we store all matched positions
int list_end = PTM_list-1;
vector<int> highest_prob_pos_2 {list_end, list_end};
int combination_2 = 0;
if (mass_shift_upper > 0) {
float maximum = mass_shift_upper + abs(masses[0]); //find the maximum mass shift that we need to look.
int limit {};
limit = binarySearchLargerElement(masses, maximum, PTM_list); //find position of first larger number of the maximum
float minimum = mass_shift_upper/2;
int minimum_limit {};
minimum_limit = binarySearchLargerElement( masses, minimum, PTM_list) - 1;
//cout << minimum << " " << minimum_limit << " " << masses[minimum_limit] << endl;
for (int j = 0; j < limit; j++) {
int k = minimum_limit;
while (masses[j] + masses[k] <= mass_shift_upper) {
float sum = roundf((masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if (masses[j] + masses[k] == 0) {
k++;
continue;//does break statement make sense here?? think not because we can have more matches
}
else {
position_combination2.push_back(j);
position_combination2.push_back(k);
// cout << masses[j] << " " << masses[k] << "\n";
if (prob[j] + prob[k] >= prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) {
highest_prob_pos_2[0] = j; highest_prob_pos_2[1] = k;
//cout << " \n" << highest_prob_pos_2[0] << " and " << highest_prob_pos_2[1] << endl;
}
combination_2++;
}
}
if (k==j)
k = j + 1; // dont repeat combinations
else
k++;
}
}
}
else {
int maximum = abs(masses[0]);//the maximum mass shift is the absolute value of the first value
int limit {};
limit = binarySearchLargerElement(masses, maximum, PTM_list); //find position of first larger number of the maximum
float minimum {0}; // because adding two positive number will never be a negative number
int minimum_limit {};
minimum_limit = binarySearchLargerElement( masses, minimum, PTM_list); // no need of -1 becasue here we are looking for the first postivie number. mass_shift will not be 0.
//cout << minimum << " " << minimum_limit << " " << masses[minimum_limit] << endl;
//hcek this values above...
for (int j = 0; j < limit; j++) {
int k = minimum_limit;
while (masses[j] + masses[k] <= mass_shift_upper) {
float sum = roundf((masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if (masses[j] + masses[k] == 0) {
k++;
continue; //does break statement make sense here?? think not because we can have more matches
}
else {
position_combination2.push_back(j); // can use insert below to keep the most probable in 0 and 1;
position_combination2.push_back(k);
// cout << masses[j] << " " << masses[k] << "\n";
if (prob[j] + prob[k] >= prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) {
highest_prob_pos_2[0] = j; highest_prob_pos_2[1] = k;
//cout << " \n" << highest_prob_pos_2[0] << " and " << highest_prob_pos_2[1] << endl;
}
combination_2++;
}
}
if (k==j)
k = j+ 1;
else
k++;
}
}
}
return {highest_prob_pos_2, position_combination2, combination_2};
}
std::tuple<vector<int>*, int*> findingCombinationOf3PTM ( float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
int list_end {PTM_list-1};
vector<int> highest_prob_pos_3 {list_end, list_end, list_end};
int combination_3 = 0;
float maximum = mass_shift_upper + (abs(masses[0])*2);//the maximum mass shift we need to check in the first loop
int limit {};
if (maximum < masses[list_end])
limit = binarySearchLargerElement(masses, maximum, PTM_list);
else
limit = list_end;
// increasing loop
if (mass_shift_upper < 160) {
for (int i = 0; i < limit; i++) {
float maximum_1 = -(masses[i]) + abs(masses[0]) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = i; j < limit_1; j++) {
float minimum_1 {};
minimum_1 = -(masses[i]) - (masses[j]) + mass_shift_lower;
int minimum_limit_1 = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
int k {};
if (minimum_limit_1 < j)
k = j;
else
k = minimum_limit_1;
while (masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum = roundf((masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
if ((prob[i] + prob[j] + prob[k]) >= (prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]])) {
highest_prob_pos_3[0] = i; highest_prob_pos_3[1] = j; highest_prob_pos_3[2] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_3++;
}
if (k==j)
k = j + 1;
k++;
}
}
}
} else {
// decreasing loop
for (int i = limit; i >= 0; i--) {
float maximum_1 = -(masses[i]) + abs(masses[0]) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = limit_1; j >= i; j--) {
float minimum_1 {};
minimum_1 = -(masses[i]) - (masses[j]) + mass_shift_lower;
int minimum_limit_1 = binarySearchLargerElement (masses, minimum_1, PTM_list); //not -1 because in this case we are decreasing in the loop
int k = minimum_limit_1;
while (masses[i] + masses[j] + masses[k] >= mass_shift_lower && k >= 0) {
float sum = roundf((masses[i] + masses[j] + masses[k])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k--;
continue;
}
if (prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]] ) {
highest_prob_pos_3[0] = i; highest_prob_pos_3[1] = j; highest_prob_pos_3[2] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_3++;
}
if (k==j)
k = j - 1;
else
k--;
}
}
}
}
return {&highest_prob_pos_3, &combination_3};
}
std::tuple<vector<int>,vector<int>, int, vector<int>, int> findingCombinationOf2and3PTM ( float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
vector<int> position_combination2 {}; // here is were we store all matched positions
int list_end = PTM_list-1;
vector<int> highest_prob_pos_2 {list_end, list_end};
int combination_2 = 0;
vector<int> highest_prob_pos_3 {list_end, list_end, list_end};
int combination_3 = 0;
float list_top_value = masses[list_end]; //maximum value of the list
float list_lowest_value = masses[0]; //lowest value of the list
float dif_upper_lower = mass_shift_upper - mass_shift_lower;
float maximum = mass_shift_upper + (abs(list_lowest_value)*2);//the maximum mass shift we need to check in the first loop
int limit {};
if (maximum < list_top_value)
limit = binarySearchLargerElement(masses, maximum, PTM_list);
else
limit = list_end;
// increasing loop
if (mass_shift_upper < 160) {
for (int i = 0; i < limit; i++) {
float maximum_1 = -(masses[i]) - (list_lowest_value) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
int j {i};
float maximum_lowest = -(masses[i]) - (list_top_value) + mass_shift_upper;
if (maximum_1 < list_lowest_value || maximum_lowest > list_top_value)
break;
// else
// j = binarySearchLargerElement( masses, maximum_lowest, PTM_list);
// if (j<i)
// j=i;
while (masses[i] + masses[j] <= mass_shift_upper && j < limit_1) {
float sum = roundf((masses[i] + masses[j])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if (masses[i] + masses[j] == 0) {
j++;
continue;//does break statement make sense here?? think not because we can have more matches
}
else {
//position_combination2.push_back(i);
//position_combination2.push_back(j);
// cout << masses[j] << " " << masses[k] << "\n";
if (prob[i] + prob[j] >= prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) {
highest_prob_pos_2[0] = i; highest_prob_pos_2[1] = j;
//cout << masses[i] << " " << masses[j] << "\n";
}
combination_2++;
}
}
float minimum_1 {};
minimum_1 = -(masses[i]) - (masses[j]) + mass_shift_lower;
float minimum_1_highest = minimum_1 + dif_upper_lower;
int k{};
if (minimum_1_highest < list_lowest_value && minimum_1 > list_top_value) {
j++; continue; }
else
k = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
if (k<j)
k = j;
while (masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum = roundf((masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
if ((prob[i] + prob[j] + prob[k]) >= (prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]])) {
highest_prob_pos_3[0] = i; highest_prob_pos_3[1] = j; highest_prob_pos_3[2] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_3++;
}
k++;
}
j++;
}
}
} else {
// decreasing loop
for (int i = limit; i >= 0; i--) {
float maximum_1 = -(masses[i]) - (list_lowest_value) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
int j {};
float maximum_lowest = -(masses[i]) - (list_top_value) + mass_shift_upper;
if (maximum_1 < list_lowest_value || maximum_lowest > list_top_value) {
i--; continue; }
else
j = limit_1;
if (j > i)
j = i;
while (masses[i] + masses[j] >= mass_shift_lower && j >= 0) {
float sum = roundf((masses[i] + masses[j])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if (masses[i] + masses[j] == 0) {
j--;
continue; //does break statement make sense here?? think not because we can have more matches
}
else {
//position_combination2.push_back(i); // can use insert below to keep the most probable in 0 and 1;
//position_combination2.push_back(j);
//cout << masses[j] << " " << masses[k] << "\n";
if (prob[i] + prob[j] >= prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) {
highest_prob_pos_2[0] = i; highest_prob_pos_2[1] = j;
//cout << masses[i] << " " << masses[j] << "\n";
}
combination_2++;
}
}
float maximum_2 = -(masses[i]) - (masses[j]) + mass_shift_upper;
// int limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
int k {};
float maximum2_lowest = -(masses[i]) - (list_top_value) + mass_shift_upper;
if (maximum_2 < list_lowest_value || maximum2_lowest > list_top_value) {
j--; continue; }
else
k = limit_1;
if (k > j)
k = j;
while (masses[i] + masses[j] + masses[k] >= mass_shift_lower && k >= 0) {
float sum = roundf((masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k--;
continue;
}
if (prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]] ) {
highest_prob_pos_3[0] = i; highest_prob_pos_3[1] = j; highest_prob_pos_3[2] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_3++;
}
if (k>j)
k = j;
else
k--;
}
if (j>i)
j = i;
else
j--;
}
}
}
return {highest_prob_pos_2, position_combination2, combination_2, highest_prob_pos_3, combination_3};
}
std::tuple<vector<int>, int> findingCombinationOf4NaturalPTM (float nat_prob [], float nat_masses [],float prob [], const int &nat_prob_length, const float &mass_shift_lower, const float &mass_shift_upper, float &sum_of_probs_4) {
int nat_end = nat_prob_length -1;
// zero prob event
vector<int> highest_prob_pos_4 = {nat_end, nat_end, nat_end, nat_end};
int combination_4 = 0;
if (sum_of_probs_4 < (4*nat_prob[0])) { //check if is possible to obtain a better score
for (int x = 0; x < nat_prob_length; x++) {
float maximum_prob = -(nat_prob[x]) - (nat_prob[x]*2) + sum_of_probs_4;
int limit_prob {};
if (maximum_prob > nat_prob[x])
break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
else if ( maximum_prob < 0)
limit_prob = nat_prob_length; // if is
else {
limit_prob = binarySearchSmallerElement_decreasing (nat_prob, maximum_prob, nat_end);
}
for (int i = x; i < limit_prob; i++) {
float maximum_1 = -(nat_prob[x]) - (nat_prob[i]) - (nat_prob[i]) + sum_of_probs_4;
int limit1_prob {};
if (maximum_1 > nat_prob[i])
break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
else if ( maximum_1 < 0)
limit1_prob = nat_prob_length;
else {
limit1_prob = binarySearchSmallerElement_decreasing (nat_prob, maximum_1, nat_end);
}
for (int j = i; j < limit1_prob; j++) {
float maximum_2 = -(nat_prob[x]) - (nat_prob[i]) - (nat_prob[j]) + sum_of_probs_4;
int k {j};
int limit2 {};
if (maximum_2 > nat_prob[j])
break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
else if ( maximum_2 < 0)
limit2 = nat_prob_length;
else {
limit2 = binarySearchSmallerElement_decreasing (nat_prob, maximum_2, nat_end);
}
while (nat_prob[x] + nat_prob[i] + nat_prob[j] + nat_prob[k] > sum_of_probs_4 && k < limit2) {
float sum = roundf((nat_masses[x] + nat_masses[i] + nat_masses[j] + nat_masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((nat_masses[x] + nat_masses[i] == 0) || (nat_masses[x] + nat_masses[j] == 0) || (nat_masses[x] + nat_masses[k] == 0) ||
(nat_masses[i] + nat_masses[j] == 0) || (nat_masses[i] + nat_masses[k] == 0) || (nat_masses[j] + nat_masses[k] == 0)) {
k++;
continue;
}
float prob_sum = nat_prob[x] + nat_prob[i] + nat_prob[j] + nat_prob[k];
if (prob_sum >= nat_prob[highest_prob_pos_4[0]] + nat_prob[highest_prob_pos_4[1]] + nat_prob[highest_prob_pos_4[2]] + nat_prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = x; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
//cout << x << " " << i << " " << j << " " << k << endl;
}
combination_4++;
}
k++;
}
}
}
}
}
return {highest_prob_pos_4, combination_4};
}
std::tuple<vector<int>, int> findingCombinationOf4PTM ( float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
// cout << "4 PTMs...";
int list_end = PTM_list -1;
vector<int> highest_prob_pos_4 = {list_end, list_end, list_end, list_end};
int combination_4 = 0;
float maximum = mass_shift_upper + (abs(masses[0])*3);//the maximum mass shift we need to check in the first loop
int limit {};
if (maximum < masses[list_end])
limit = binarySearchLargerElement(masses, maximum, PTM_list);
else
limit = list_end;
// increasing loop
if (mass_shift_upper < 160) {
for (int y = 0; y < limit; y++) {
float maximum_2 = -(masses[y]) + (abs(masses[0])*2) + mass_shift_upper;
int limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
for (int i = y; i < limit_2; i++) {
float maximum_1 = -(masses[y]) -(masses[i]) + abs(masses[0]) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = i; j < limit_1; j++) {
float minimum_1 {};
minimum_1 = -(masses[y]) -(masses[i]) - (masses[j]) + mass_shift_lower;
int minimum_limit_1 = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
int k {};
if (minimum_limit_1 < j)
k = j;
else
k = minimum_limit_1;
while (masses[y] + masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_4++;
}
k++;
}
}
}
}
} else {
// decreasing loop
for (int y = limit; y >= 0; y--) {
float maximum_2 = -(masses[y]) + (abs(masses[0])*3) + mass_shift_upper;
int limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
for (int i = limit_2; i >= y; i--) {
float maximum_1 = -(masses[y]) -(masses[i]) + (abs(masses[0])*2) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = limit_1; j >= i; j--) {
float minimum_1 {};
minimum_1 = -(masses[y]) -(masses[i]) - (masses[j]) + abs(masses[0]) + mass_shift_upper;
int minimum_limit_1 = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
int k {};
if (minimum_limit_1 > j)
k = j;
else
k = minimum_limit_1;
while (masses[y] + masses[i] + masses[j] + masses[k] >= mass_shift_lower && k >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
}
combination_4++;
}
k--;
}
}
}
}
}
return {highest_prob_pos_4, combination_4};
}
std::tuple<vector<int>, int, vector<int>, int> findingCombinationOf4and5PTM_A (float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
int list_end = PTM_list -1;
vector<int> highest_prob_pos_4 {list_end, list_end, list_end, list_end};
int combination_4 = 0;
vector<int> highest_prob_pos_5 {list_end, list_end, list_end, list_end, list_end};
int combination_5 = 0;
float maximum = mass_shift_upper + (abs(masses[0])*3);//the maximum mass shift we need to check in the first loop
int limit {};
if (maximum < masses[list_end])
limit = binarySearchLargerElement(masses, maximum, PTM_list);
else
limit = list_end;
// increasing loop
if (mass_shift_upper < 160) {
for (int y = 0; y <= limit; y++) {
float maximum_2 = -(masses[y]) + (abs(masses[0])*2) + mass_shift_upper;
int limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
for (int i = y; i <= limit_2; i++) {
float maximum_1 = -(masses[y]) -(masses[i]) + (abs(masses[0])) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = i; j <= limit_1; j++) {
float minimum_1 {};
minimum_1 = -(masses[y]) -(masses[i]) - (masses[j]) + mass_shift_upper;
int minimum_limit_1 = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
int k {};
if (minimum_limit_1 < j)
k = j;
else
k = minimum_limit_1;
while (masses[y] + masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_4++;
}
float minimum_2 {};
minimum_2 = -(masses[y]) -(masses[i]) - (masses[j]) - (masses[k]) + mass_shift_upper;
int minimum_limit_2 = binarySearchLargerElement (masses, minimum_2, PTM_list) -1;
int x {};
if (minimum_limit_2 < k)
x = k;
else
x = minimum_limit_2;
while (masses[y] + masses[i] + masses[j] + masses[k] + masses[x] >= mass_shift_lower && k < PTM_list) {
float sum1 = roundf((masses[y] + masses[i] + masses[j] + masses[k] + masses[x])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum1 <= mass_shift_upper) && (sum1 >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0) ||
(masses[x] + masses[y] == 0) || (masses[x] + masses[i] == 0) || (masses[x] + masses[j] == 0) ||
(masses[x] + masses[k] == 0)) {
x++;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] + prob[x] >= prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] + prob[highest_prob_pos_5[4]]) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = i; highest_prob_pos_5[2] = j; highest_prob_pos_5[3] = k; highest_prob_pos_5[4] = x;
}
combination_5++;
}
x++;
}
k++;
}
}
}
}
} else {
// decreasing loop
for (int y = limit; y >= 0; y--) {
float maximum_2 = -(masses[y]) + (abs(masses[0])*2) + mass_shift_upper;
int limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
for (int i = limit_2; i >= y; i--) {
float maximum_1 = -(masses[y]) -(masses[i]) + abs(masses[0]) + mass_shift_upper;
int limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = limit_1; j >= i; j--) {
float minimum_1 {};
minimum_1 = -(masses[y]) -(masses[i]) - (masses[j]) + mass_shift_lower;
int minimum_limit_1 = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
int k {};
if (minimum_limit_1 > j)
k = j;
else
k = minimum_limit_1;
while (masses[y] + masses[i] + masses[j] + masses[k] >= mass_shift_lower && k >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
break;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
}
combination_4++;
}
float minimum_2 {};
minimum_2 = -(masses[y]) -(masses[i]) - (masses[j]) + abs(masses[k]) + mass_shift_upper;
int minimum_limit_2 = binarySearchLargerElement (masses, minimum_2, PTM_list) -1;
int x {};
if (minimum_limit_2 > k)
x = k;
else
x = minimum_limit_2;
while (masses[y] + masses[i] + masses[j] + masses[k] + masses[x] >= mass_shift_lower && k >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k] + masses[x])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0) ||
(masses[x] + masses[y] == 0) || (masses[x] + masses[i] == 0) || (masses[x] + masses[j] == 0) ||
(masses[x] + masses[k] == 0)) {
x++;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] + prob[x] >= prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] + prob[highest_prob_pos_5[4]]) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = i; highest_prob_pos_5[2] = j; highest_prob_pos_5[3] = k; highest_prob_pos_5[4] = x;
}
combination_5++;
}
x--;
}
k--;
}
}
}
}
}
return {highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5};
}
std::tuple<vector<int>, int, vector<int>, int, float> findingCombinationOf4and5NaturalPTM (float nat_prob [], float nat_masses [],float prob [], const int &nat_prob_length, const float &mass_shift_lower, const float &mass_shift_upper,
float &sum_of_probs_4, float &prob_average_1, float &prob_average_2, float &prob_average_3, float &prob_average_4, float &prob_vector_max_1) {
int nat_end = nat_prob_length-1;
// zero prob event
vector<int> highest_prob_pos_4 = {nat_end, nat_end, nat_end, nat_end};
vector<int> highest_prob_pos_5 = {nat_end, nat_end, nat_end, nat_end, nat_end};
int combination_4 = 0;
int combination_5 = 0;
float sum_of_probs_5 = prob_vector_max_1 * 5;
//if (sum_of_probs_4 < (4*nat_prob[0]) || sum_of_probs_5 < (5*nat_prob[0]))
for (int y = 0; y < nat_prob_length; y++) {
// float maximum_prob_5 = -(nat_prob[y]) - (nat_prob[y]*3) + sum_of_probs_5;
// int limit_prob_5 = {};
// if (maximum_prob_5 > nat_prob[y])
// break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
// else if ( maximum_prob_5 < 0)
// limit_prob_5 = nat_prob_length; // if is
// else {
// limit_prob_5 = binarySearchSmallerElement_decreasing (nat_prob, maximum_prob_5, nat_end);
// }
for (int x = y; x < nat_prob_length; x++) {
// float maximum_prob = -(nat_prob[y]) -(nat_prob[x]) - (nat_prob[x]*2) + sum_of_probs_4;
// int limit_prob {};
// if (maximum_prob > nat_prob[x])
// break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
// else if ( maximum_prob < 0)
// limit_prob = nat_prob_length; // if is
// else {
// limit_prob = binarySearchSmallerElement_decreasing (nat_prob, maximum_prob, nat_end);
// }
for (int i = x; i < nat_prob_length; i++) {
// float maximum_1 = -(nat_prob[y]) -(nat_prob[x]) - (nat_prob[i]*2) + sum_of_probs_4;
// int limit1_prob {};
// if (maximum_1 > nat_prob[i])
// break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
// else if ( maximum_1 < 0)
// limit1_prob = nat_prob_length;
// else {
// limit1_prob = binarySearchSmallerElement_decreasing (nat_prob, maximum_1, nat_end);
// }
int j {i};
while (nat_prob[y] + nat_prob[x] + nat_prob[i] + nat_prob[j] > sum_of_probs_4 && j < nat_prob_length) {
float sum = roundf((nat_masses[x] + nat_masses[i] + nat_masses[j] + nat_masses[y])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((nat_masses[x] + nat_masses[i] == 0) || (nat_masses[x] + nat_masses[j] == 0) || (nat_masses[x] + nat_masses[y] == 0) ||
(nat_masses[i] + nat_masses[j] == 0) || (nat_masses[i] + nat_masses[y] == 0) || (nat_masses[j] + nat_masses[y] == 0)) {
j++;
continue;
}
float prob_sum = nat_prob[x] + nat_prob[i] + nat_prob[j] + nat_prob[y];
if (prob_sum >= nat_prob[highest_prob_pos_4[0]] + nat_prob[highest_prob_pos_4[1]] + nat_prob[highest_prob_pos_4[2]] + nat_prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = x; highest_prob_pos_4[2] = i; highest_prob_pos_4[3] = j;
//cout << y << " " << x << " " << i << " " << j << endl;
prob_average_4 = (nat_prob[highest_prob_pos_4[0]] + nat_prob[highest_prob_pos_4[1]] + nat_prob[highest_prob_pos_4[2]] + nat_prob[highest_prob_pos_4[3]]) / 4;
vector<float> prob_vector_2 = {prob_average_1, prob_average_2, prob_average_3, prob_average_4};
float prob_vector_max_2 = *max_element(prob_vector_2.begin(), prob_vector_2.end());
sum_of_probs_5 = prob_vector_max_2*5;
}
combination_4++;
}
//float maximum_2 = -(nat_prob[y]) -(nat_prob[x]) - (nat_prob[i]) - (nat_prob[j]) + sum_of_probs_5;
int k {j};
//int limit2 {};
// if (maximum_2 > nat_prob[j]) {
// break; // if maximum is more than nat_prob[0] then it means that sum_of_probs will never be reached
// }
// else if ( maximum_2 < 0)
// limit2 = nat_prob_length;
// else {
// limit2 = binarySearchSmallerElement_decreasing (nat_prob, maximum_2, nat_end);
// }
while (nat_prob[y] + nat_prob[x] + nat_prob[i] + nat_prob[j] + nat_prob[k] > sum_of_probs_5 && k < nat_prob_length) {
float sum1 = roundf((nat_masses[y] + nat_masses[x] + nat_masses[i] + nat_masses[j] + nat_masses[k])*10000)/10000;
if ((sum1 <= mass_shift_upper) && (sum1 >= mass_shift_lower)) {
// masses that cancel each other
if ((nat_masses[x] + nat_masses[i]) == 0 || (nat_masses[x] + nat_masses[j] == 0) || (nat_masses[x] + nat_masses[y] == 0) ||
(nat_masses[i] + nat_masses[j] == 0) || (nat_masses[i] + nat_masses[y] == 0) || (nat_masses[j] + nat_masses[y] == 0) ||
(nat_masses[x] + nat_masses[k] == 0) || (nat_masses[y] + nat_masses[k] == 0) || (nat_masses[i] + nat_masses[k] == 0) ||
(nat_masses[j] + nat_masses[k] == 0)) { k++; continue; }
float prob_sum1 = nat_prob[y] + nat_prob[x] + nat_prob[i] + nat_prob[j] + nat_prob[k];
if (prob_sum1 >=(nat_prob[highest_prob_pos_5[0]] + nat_prob[highest_prob_pos_5[1]] + nat_prob[highest_prob_pos_5[2]] + nat_prob[highest_prob_pos_5[3]] + nat_prob[highest_prob_pos_5[4]])) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = x; highest_prob_pos_5[2] = i; highest_prob_pos_5[3] = j; highest_prob_pos_5[4] = k;
//cout << y << " " << x << " " << i << " " << j << " " << k << endl;
}
combination_5++;
}
k++;
}
j++;
}
}
}
}
return {highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5, prob_average_4};
}
std::tuple<vector<int>, int, vector<int>, int> findingCombinationOf4and5PTM_Best (float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
int list_end = PTM_list -1;
vector<int> highest_prob_pos_4 {list_end, list_end, list_end, list_end};
int combination_4 = 0;
vector<int> highest_prob_pos_5 {list_end, list_end, list_end, list_end, list_end};
int combination_5 = 0;
float list_top_value = masses[list_end]; //maximum value of the list
float list_lowest_value = masses[0]; //lowest value of the list
float dif_upper_lower = mass_shift_upper - mass_shift_lower;
float maximum = mass_shift_upper + (abs(list_lowest_value)*3);//the maximum mass shift we need to check in the first loop
int limit {};
if (maximum < list_top_value)
limit = binarySearchLargerElement(masses, maximum, PTM_list);
else
limit = list_end;
// increasing loop
if (mass_shift_upper < 160) {
for (int y = 0; y <= limit; y++) {
float maximum_2 = -(masses[y]) + (abs(list_lowest_value)*2) + mass_shift_lower;
int limit_2 {};
int maximum_2_highest = maximum_2 + dif_upper_lower;
if (maximum_2 > list_top_value || maximum_2_highest < list_lowest_value)
break; //if its bigger then there is now way to achieve the mass_shift wanted. if the
else
limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
for (int i = y; i <= limit_2; i++) {
float maximum_1 = -(masses[y]) -(masses[i]) + (abs(list_lowest_value)) + mass_shift_lower;
int limit_1 {};
int maximum_1_high = maximum_1 + dif_upper_lower;
if (maximum_1 > list_top_value || maximum_1_high < list_lowest_value)
break;
else
limit_1 = binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = i; j <= limit_1; j++) {
float minimum_1 {};
minimum_1 = -(masses[y]) -(masses[i]) - (masses[j]) + mass_shift_lower;
int minimum_1_highest = minimum_1 + dif_upper_lower;
int k {};
if (minimum_1 > list_top_value || minimum_1_highest < list_lowest_value)
break;
else
k = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
while (masses[y] + masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_4++;
}
float minimum_2 {};
minimum_2 = -(masses[y]) -(masses[i]) - (masses[j]) - (masses[k]) + mass_shift_lower;
int minimum_2_highest = minimum_2 + dif_upper_lower;
int x {};
if (minimum_2_highest > list_top_value || minimum_2 < list_lowest_value)
break;
else
x = binarySearchLargerElement (masses, minimum_2, PTM_list) -1;
while (masses[y] + masses[i] + masses[j] + masses[k] + masses[x] <= mass_shift_upper && k < PTM_list) {
float sum1 = roundf((masses[y] + masses[i] + masses[j] + masses[k] + masses[x])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum1 <= mass_shift_upper) && (sum1 >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0) ||
(masses[x] + masses[y] == 0) || (masses[x] + masses[i] == 0) || (masses[x] + masses[j] == 0) ||
(masses[x] + masses[k] == 0)) {
x++;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] + prob[x] >= prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] + prob[highest_prob_pos_5[4]]) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = i; highest_prob_pos_5[2] = j; highest_prob_pos_5[3] = k; highest_prob_pos_5[4] = x;
}
combination_5++;
}
if (x <= k)
x = k + 1;
else
x++;
}
if ( k <= j)
k = j + 1;
else
k++;
}
}
}
}
} else {
// decreasing loop
for (int y = limit; y >= 0; y--) {
float maximum_2 = -(masses[y]) + (abs(list_lowest_value)*2) + mass_shift_upper;
int limit_2 {};
int maximum_2_lower = maximum_2 - dif_upper_lower;
if (maximum_2_lower > list_top_value || maximum_2 < list_lowest_value)
break;
else
limit_2 = binarySearchLargerElement( masses, maximum_2, PTM_list);
for (int i = limit_2; i >= y; i--) {
float maximum_1 = -(masses[y]) -(masses[i]) + abs(list_lowest_value) + mass_shift_upper;
int maximum_1_lowest = maximum_1 - dif_upper_lower;
int limit_1 {};
if (maximum_1_lowest > list_top_value || maximum_1 < list_lowest_value)
break;
else
limit_1= binarySearchLargerElement( masses, maximum_1, PTM_list);
for (int j = limit_1; j >= i; j--) {
float minimum_1 {};
minimum_1 = -(masses[y]) -(masses[i]) - (masses[j]) + mass_shift_upper;
int minimum_1_lowest = minimum_1 - dif_upper_lower;
int k {};
if (minimum_1_lowest > list_top_value || minimum_1 < list_lowest_value)
break;
else
k = binarySearchLargerElement (masses, minimum_1, PTM_list) -1;
while (masses[y] + masses[i] + masses[j] + masses[k] >= mass_shift_lower && y >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
y--;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
}
combination_4++;
}
float minimum_2 {};
minimum_2 = -(masses[y]) -(masses[i]) - (masses[j]) - (masses[k]) + mass_shift_upper;
int minimum_2_lowest = minimum_2 - dif_upper_lower;
int x {};
if (minimum_2_lowest > list_top_value || minimum_2 < list_lowest_value)
break;
else
x = binarySearchLargerElement (masses, minimum_2, PTM_list) -1;
while (masses[y] + masses[i] + masses[j] + masses[k] + masses[x] >= mass_shift_lower && x >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k] + masses[x])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0) ||
(masses[x] + masses[y] == 0) || (masses[x] + masses[i] == 0) || (masses[x] + masses[j] == 0) ||
(masses[x] + masses[k] == 0)) {
x--;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] + prob[x] >= prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] + prob[highest_prob_pos_5[4]]) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = i; highest_prob_pos_5[2] = j; highest_prob_pos_5[3] = k; highest_prob_pos_5[4] = x;
}
combination_5++;
}
if (x==k)
x = k - 1;
else
x--;
}
if (k ==j)
k = j -1;
else
k--;
}
}
}
}
}
return {highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5};
}
std::tuple<vector<int>, int, vector<int>, int, vector<int>, int, vector<int>, int> findingCombinationOf2_3_4_5_PTM ( float masses [],float prob [], const int &PTM_list, const float &mass_shift_lower, const float &mass_shift_upper) {
vector<int> position_combination2 {}; // here is were we store all matched positions
int list_end = PTM_list-1;
vector<int> highest_prob_pos_2 {list_end, list_end};
int combination_2 = 0;
vector<int> highest_prob_pos_3 {list_end, list_end, list_end};
int combination_3 = 0;
vector<int> highest_prob_pos_4 {list_end, list_end,list_end, list_end,list_end};
int combination_4 = 0;
vector<int> highest_prob_pos_5 {list_end, list_end, list_end, list_end, list_end};
int combination_5 = 0;
float list_top_value = masses[list_end]; //maximum value of the list
float list_lowest_value = masses[0]; //lowest value of the list
float maximum = mass_shift_upper + (abs(list_lowest_value));//the maximum mass shift we need to check in the first loop
int limit {};
if (maximum < list_top_value)
limit = binarySearchLargerElement(masses, maximum, PTM_list);
else
limit = list_end;
// increasing loop
if (mass_shift_upper < 160) {
for (int i = 0; i < limit; i++) {
int j {i};
while (masses[i] + masses[j] <= mass_shift_upper && j < PTM_list) {
float sum = roundf((masses[i] + masses[j])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
//cout << masses[i] << " " << masses[j] << "\n";
// masses that cancel each other
if (masses[i] + masses[j] == 0) {
j++;
continue;//does break statement make sense here?? think not because we can have more matches
}
else {
//position_combination2.push_back(i);
//position_combination2.push_back(j);
// cout << masses[j] << " " << masses[k] << "\n";
if (prob[i] + prob[j] >= prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) {
highest_prob_pos_2[0] = i; highest_prob_pos_2[1] = j;
//cout << masses[i] << " " << masses[j] << "\n";
}
combination_2++;
}
}
int k {j};
while (masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum1 = roundf((masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum1 <= mass_shift_upper) && (sum1 >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k++;
continue;
}
if ((prob[i] + prob[j] + prob[k]) >= (prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]])) {
highest_prob_pos_3[0] = i; highest_prob_pos_3[1] = j; highest_prob_pos_3[2] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_3++;
}
int y {k};
while (masses[y] + masses[i] + masses[j] + masses[k] <= mass_shift_upper && k < PTM_list) {
float sum2 = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum2 <= mass_shift_upper) && (sum2 >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
y++;
continue;
}
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << " "<< masses[y] << "\n";
}
combination_4++;
}
int x {y};
while (masses[y] + masses[i] + masses[j] + masses[k] + masses[x] <= mass_shift_upper && k < PTM_list) {
float sum3 = roundf((masses[y] + masses[i] + masses[j] + masses[k] + masses[x])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum3 <= mass_shift_upper) && (sum3 >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0) ||
(masses[x] + masses[y] == 0) || (masses[x] + masses[i] == 0) || (masses[x] + masses[j] == 0) ||
(masses[x] + masses[k] == 0)) {
x++;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] + prob[x] >= prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] + prob[highest_prob_pos_5[4]]) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = i; highest_prob_pos_5[2] = j; highest_prob_pos_5[3] = k; highest_prob_pos_5[4] = x;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << " "<< masses[y] << " " << masses[x] << "\n";
}
combination_5++;
}
x++;
}
y++;
}
k++;
}
j++;
}
}
} else {
// decreasing loop
for (int i = limit; i >= 0; i--) {
int j {i};
while (masses[i] + masses[j] >= mass_shift_lower && j >= 0) {
float sum = roundf((masses[i] + masses[j])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if (masses[i] + masses[j] == 0) {
j++;
continue; //does break statement make sense here?? think not because we can have more matches
}
else {
//position_combination2.push_back(i); // can use insert below to keep the most probable in 0 and 1;
//position_combination2.push_back(j);
//cout << masses[j] << " " << masses[k] << "\n";
if (prob[i] + prob[j] >= prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) {
highest_prob_pos_2[0] = i; highest_prob_pos_2[1] = j;
//cout << masses[i] << " " << masses[j] << "\n";
}
combination_2++;
}
}
int k {j};
while (masses[i] + masses[j] + masses[k] >= mass_shift_lower && k >= 0) {
float sum = roundf((masses[i] + masses[j] + masses[k])*10000)/10000;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
k--;
continue;
}
if (prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]] ) {
highest_prob_pos_3[0] = i; highest_prob_pos_3[1] = j; highest_prob_pos_3[2] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
}
combination_3++;
}
int y {k};
while (masses[y] + masses[i] + masses[j] + masses[k] >= mass_shift_lower && y >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0)) {
y--;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] >= prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) {
highest_prob_pos_4[0] = y; highest_prob_pos_4[1] = i; highest_prob_pos_4[2] = j; highest_prob_pos_4[3] = k;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << " "<< masses[y] << " " << "\n";
}
combination_4++;
}
int x {y};
// float minimum_3 {};
// minimum_3 = -(masses[y]) -(masses[i]) - (masses[j]) - (masses[k]) + mass_shift_upper;
// float minimum_3_highest = minimum_3 + dif_upper_lower;
// if (minimum_3_highest < list_lowest_value || minimum_3 > list_top_value)
// break;
// else
// x = binarySearchLargerElement (masses, minimum_3_highest, PTM_list);
while (masses[y] + masses[i] + masses[j] + masses[k] + masses[x] >= mass_shift_lower && x >= 0) {
float sum = roundf((masses[y] + masses[i] + masses[j] + masses[k] + masses[x])*10000)/10000;
// cout << k << "\n";
// cout << sum << endl;
if ((sum <= mass_shift_upper) && (sum >= mass_shift_lower)) {
// masses that cancel each other
if ((masses[y] + masses[i] == 0) || (masses[y] + masses[j] == 0) || (masses[y] + masses[k] == 0) ||
(masses[i] + masses[j] == 0) || (masses[i] + masses[k] == 0) || (masses[j] + masses[k] == 0) ||
(masses[x] + masses[y] == 0) || (masses[x] + masses[i] == 0) || (masses[x] + masses[j] == 0) ||
(masses[x] + masses[k] == 0)) {
x--;
continue;
}
// cout << masses[i] << " " << masses[j] << " " << masses[k] << "\n";
if (prob[y] + prob[i] + prob[j] + prob[k] + prob[x] >= prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] + prob[highest_prob_pos_5[4]]) {
highest_prob_pos_5[0] = y; highest_prob_pos_5[1] = i; highest_prob_pos_5[2] = j; highest_prob_pos_5[3] = k; highest_prob_pos_5[4] = x;
//cout << masses[i] << " " << masses[j] << " " << masses[k] << " "<< masses[y] << " " << masses[x] << "\n";
}
combination_5++;
}
x--;
}
y--;
}
k--;
}
j--;
}
}
}
//cout << "---------------------------------------------------------------------------------------------------------------------------------";
return {highest_prob_pos_2, combination_2, highest_prob_pos_3, combination_3, highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5};
}
float* openFile(string path, int length) {
ifstream inputFile;
inputFile.open(path);
float *array = new float[length];
// put into function
// if file is not found
if (!inputFile) {
cout << "no file" << "\n" << "double check: " << path << "\n";
exit(-1);
}
// masses array
int count = 0;
while (!inputFile.eof()) {
inputFile >> array[count];
count++;
// cout << masses[count-1]<<endl;
}
return array;
}
//=======================================================================================================//
int main(int argc, char** argv) {
/* Main arguments:
* first = sample name
* second = tolerance
*/
auto start = chrono::steady_clock::now();
string sample = "JOHNPP_l1";
string dir_path = "/Users/pedrocardoso/Documents/RUHI-MSA/";
string input_path = dir_path + "input/" + sample + ".txt";
//-------------------------------- Read Input files ------------------------------------------//
/* this is probably not needed since we are reading the file now with a while loop
// number of lines in input file
//
int lines;
string s;
ifstream inputFile;
inputFile.open(input_path);
if (!inputFile) {
cout << "no file" << "\n" << "double check in: " << input_path << "\n";
exit(-1);
}
while (!inputFile.eof()) {
getline(inputFile, s);
lines++;
}
// cout << "No of Peptides: " << lines << "\n";
*/
//--------------------------------//
//================================| Input |================================//
//// PTM masses and probabilities
// mass shift array
const int PTM_list = 1498; //1497 PTMs
// list_end is -1 because on an array with 10 element position 9 is the last element!!!!
const int list_end = PTM_list; //last element to create null prob for no matches
const int nat_list = 90; //89 natural PTMs
const int nat_end = nat_list;
//// UniMod masses and probabilities
// mass shift array // PTMs array
float* masses = openFile(dir_path + "libs/new_masses.txt", PTM_list);
// Probabilities array
float* prob = openFile(dir_path + "libs/new_prob.txt", (PTM_list+1));
// null probability for no matches (last new vector position)
prob[list_end] = 0;
//// Natural frequency masses and probabilities
// Nat probabilities array
float* nat_prob = openFile(dir_path + "libs/new_nat_prob.txt", (nat_list+1));
nat_prob[nat_end] = 0;
// Nat masses array
float* nat_masses = openFile(dir_path + "libs/new_nat_masses.txt", nat_list);
// Nat names array
string nat_names[nat_list];
ifstream fakeNames;
fakeNames.open(dir_path + "libs/new_nat_names.txt");
int names_count = 0;
while (!fakeNames.eof()) {
fakeNames >> nat_names[names_count];
names_count++;
}
// sizes
int nat_prob_length = nat_list;
//-------------------------------------------------------//
//-----------OUTPUT file--------------------------------//
string output_file_path = dir_path + "results/" + sample + "_output.txt";
ofstream output_file;
output_file.open(output_file_path, ios::out);
output_file << "Peptide" << "\t" << "Mass_shift" << "\t" << "Peptide Mass" << "\t" << "Mass of PTMs" << "\t" << "Score" << "\t" << "PTM 1" << "\t"<< "PTM 2" << "\t"<< "PTM 3" << "\t"<< "PTM4" << "\t" << "PTM5";
output_file.close();
//================================| Peptide - Mass Shift |================================//
//reading Peptide data: sequence, Mass_shift and peptide Mass
ifstream inputPeptideData;
inputPeptideData.open(input_path);
string peptide;
float mass_shift;
float peptide_mass;
if (!inputPeptideData) { //testing if the file is being open correctly
throw std::runtime_error("Error opening file");
}
else
while (!inputPeptideData.eof()) {
//================================//
inputPeptideData >> peptide >> mass_shift >> peptide_mass;
//outfile << peptide << " " << mass_shift << " " << peptide_mass << endl;
// auto end1 = chrono::steady_clock::now();
// mass error
// float peptide_mass = 1000;
float tolerance = 10; // this has been defined on the .main arguments
float mass_error = peptide_mass * tolerance / 1000000;
//cout << mass_error << endl;
float mass_shift_upper = mass_shift + mass_error;
float mass_shift_lower = mass_shift - mass_error;
//cout << mass_shift_lower << "-" << mass_shift_upper << endl;
mass_shift_upper = roundf(mass_shift_upper*10000)/10000; //check if this works without rounding. If we round we are losing precision
mass_shift_lower = roundf(mass_shift_lower*10000)/10000;
//cout << mass_shift_lower << "-" << mass_shift_upper << endl;
//================================//
//string output_file_path = dir_path + "results/" + sample + "/" + peptide + "_output.txt";
// int break_scenario=0;
//----------------------------------//
// string peptide = "VSAMEDEMNEMK";
// float mass_shift = -0.0011;
//----------------------------------//
// counters
// int count;
int combination = 0;
int more_than_3 = 0;
//=======================================================================================================//
// start timer
//auto start = chrono::steady_clock::now();
// null vector of probability positions to populate
vector<int> highest_prob_pos (5,list_end);
// vector<int> *highest_prob_pos_1 = new vector<int>();
// number of loops to attempt counter
int number_of_possible_ptms = 1;
//cout << "Searching combinations of:" << "\n";
//--------------------------------------------------------------------------------------------------//
//––––––––––––––––––––––––––//
//––––––––| 1 PTM |–––––––––//
//––––––––––––––––––––––––––//
//Search PTMs matching mass shift range
auto [highest_prob_pos_1_ptr, position_combination1_ptr, pos_length] = finding1PTM(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
int combination_1 = *pos_length;
float prob_average_1 = 0.0;
// storing highest probability and index of matched PTM
if (combination_1 > 0) {
prob_average_1 = prob[(*highest_prob_pos_1_ptr).at(0)];
//cout << "\n" << "The mass shift can be explained by 1 PTM - ";
//cout << "with score: " << prob_average_1 << "\n";
highest_prob_pos[0] = (*highest_prob_pos_1_ptr).at(0);
combination = combination_1;
more_than_3 = 1;
} else { number_of_possible_ptms++; }
//--------------------------------------------------------------------------------------------------//
//auto end2 = chrono::steady_clock::now();
//––––––––––––––––––––––––––//
//––––––––| 2 PTMs |––––––––//
//––––––––––––––––––––––––––//
// Search combination of 2 and 3 PTMs that match mass shift
auto [highest_prob_pos_2, position_combination2, combination_2, highest_prob_pos_3, combination_3] = findingCombinationOf2and3PTM(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
//auto [highest_prob_pos_2, combination_2, highest_prob_pos_3, combination_3, highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5] = findingCombinationOf2_3_4_5_PTM(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
// Search combination of 2 PTMs that match mass shift
//auto [highest_prob_pos_2, position_combination2, combination_2] = findingCombinationOf2PTM(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
float prob_average_2 = 0.0;
// storing highest probability matches and its index
if (combination_2 > 0) {
prob_average_2 = (prob[highest_prob_pos_2[0]] + prob[highest_prob_pos_2[1]]) / 2;
//cout << "\n" << "The mass shift can be explained by 2 PTMs - ";
//cout << "with score: " << prob_average_2 << "\n";
if (prob_average_2 > prob_average_1) {
//cout << "2 PTMs have a higher weighting" << "\n";
highest_prob_pos[0] = highest_prob_pos_2[0]; highest_prob_pos[1] = highest_prob_pos_2[1];
combination = combination_2;
more_than_3 = 2;
}
} else { number_of_possible_ptms++; }
//--------------------------------------------------------------------------------------------------//
//––––––––––––––––––––––––––//
//––––––––| 3 PTMs |––––––––//
//––––––––––––––––––––––––––//
// Search combination of 3 PTMs that match mass shift
//auto [highest_prob_pos_3_ptr, combination_3_ptr] =findingCombinationOf3PTM ( masses ,prob , PTM_list, mass_shift_lower, mass_shift_upper);
float prob_average_3 = 0.0;
// storing highest probability matches and its index
if (combination_3 > 0) {
prob_average_3 = (prob[highest_prob_pos_3[0]] + prob[highest_prob_pos_3[1]] + prob[highest_prob_pos_3[2]]) / 3;
//cout << "\n" << "The mass shift can be explained by 3 PTMs - ";
//cout << "with score: " << prob_average_3 << "\n";
if ( prob_average_3 > prob_average_1 && prob_average_3 > prob_average_2 ) {
//cout << "3 PTMs have a higher weighting" << "\n";
highest_prob_pos[0] = highest_prob_pos_3[0]; highest_prob_pos[1] = highest_prob_pos_3[1]; highest_prob_pos[2] = highest_prob_pos_3[2];
combination = combination_3;
more_than_3 = 3;
}
} else { number_of_possible_ptms++; }
//--------------------------------------------------------------------------------------------------//
// highest values of all probabilities till 3
vector<float> prob_vector_1 = {prob_average_1, prob_average_2, prob_average_3};
float prob_vector_max_1 = *max_element(prob_vector_1.begin(), prob_vector_1.end());
// auto end3 = chrono::steady_clock::now();
//--------------------------------------------------------------------------------------------------//
//––––––––––––––––––––––––––//
//––––––––| 4 PTMs |––––––––//
//––––––––––––––––––––––––––//
// Search for combination of 4 natural PTMs that have an higher probability
//float sum_of_probs_4 = prob_vector_max_1 * 4; // prob max is an average so we need to find the actual value of the probs before
//auto [highest_prob_pos_4, combination_4] = findingCombinationOf4NaturalPTM ( nat_prob, nat_masses, prob, nat_prob_length, mass_shift_lower, mass_shift_upper, sum_of_probs_4);
//--------------------------------------------------------------------------------------------------//
// float prob_average_4 = 0.0;
// storing highest probability matches and its index
// if (combination_4 > 0) {
//
// prob_average_4 = ((nat_prob[highest_prob_pos_4[0]] + nat_prob[highest_prob_pos_4[1]] + nat_prob[highest_prob_pos_4[2]] + nat_prob[highest_prob_pos_4[3]]) / 4);
// cout << "\n" << "The mass shift can be explained by 4 PTMs - ";
// cout << "with score: " << prob_average_4 << "\n";
//
// if ( prob_average_4 > prob_average_3 && prob_average_4 > prob_average_2 && prob_average_4 > prob_average_1) {
// cout << " >>> 4 PTMs have a higher weighting <<< " << "\n" << "\n"; // this will always happen because we are only checking the combinations with higher prob than the rest
// highest_prob_pos[0] = highest_prob_pos_4[0]; highest_prob_pos[1] = highest_prob_pos_4[1];
// highest_prob_pos[2] = highest_prob_pos_4[2]; highest_prob_pos[3] = highest_prob_pos_4[3];
// combination = combination_4;
// more_than_3 = 4;
// }
//
// } else { number_of_possible_ptms++; }
//
//
// highest values of all probabilities
//vector<float> prob_vector_2 = {prob_average_1, prob_average_2, prob_average_3, prob_average_4};
//float prob_vector_max_2 = *max_element(prob_vector_2.begin(), prob_vector_2.end());
//--------------------------------------------------------------------------------------------------//
//––––––––––––––––––––––––––//
//––––––––| 4 and/or 5 NAtural PTMs |––––––––//
//––––––––––––––––––––––––––//
float sum_of_probs_4 = prob_vector_max_1 * 4; // prob max is an average so we need to find "raw" probablility.
float prob_average_4 = 0.0;
// Search for combination of 4 and/or 5 natural PTMs that have higher probability
auto [highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5, new_prob_average_4] = findingCombinationOf4and5NaturalPTM (nat_prob,nat_masses,prob, nat_prob_length, mass_shift_lower, mass_shift_upper, sum_of_probs_4, prob_average_1, prob_average_2, prob_average_3, prob_average_4, prob_vector_max_1);
prob_average_4 = new_prob_average_4;
//---------------------------------------------------------------------------------------------------------//
// storing highest probability matches and its index for combination of 4
if (combination_4 > 0) {
//prob_average_4 has been calculated during findingCombinationOf4and5NaturalPTM function.
//prob_average_4 = (nat_prob[highest_prob_pos_4[0]] + nat_prob[highest_prob_pos_4[1]] + nat_prob[highest_prob_pos_4[2]] + nat_prob[highest_prob_pos_4[3]]) / 4;
//cout << "\n" << "The mass shift can be explained by 4 PTMs - ";
//cout << "with score: " << prob_average_4 << "\n";
if ( prob_average_4 > prob_average_3 && prob_average_4 > prob_average_2 && prob_average_4 > prob_average_1) {
//cout << " >>> 4 PTMs have a higher weighting <<< " << "\n" << "\n"; // this will always happen because we are only checking the combinations with higher prob than the rest
highest_prob_pos[0] = highest_prob_pos_4[0]; highest_prob_pos[1] = highest_prob_pos_4[1];
highest_prob_pos[2] = highest_prob_pos_4[2]; highest_prob_pos[3] = highest_prob_pos_4[3];
combination = combination_4;
more_than_3 = 4;
}
} else { number_of_possible_ptms++; }
//--------------------------------------------------------------------------------------------------//
float prob_average_5 = 0.0;
// storing highest probability matches and its index for combination of 5
if (combination_5 > 0) {
prob_average_5 = (nat_prob[highest_prob_pos_5[0]] + nat_prob[highest_prob_pos_5[1]] + nat_prob[highest_prob_pos_5[2]] + nat_prob[highest_prob_pos_5[3]] + nat_prob[highest_prob_pos_5[4]]) / 5;
//cout << "\n" << "The mass shift can be explained by 5 PTMs - ";
//cout << "with score: " << prob_average_5 << "\n";
if (prob_average_5 > prob_average_4 && prob_average_5 > prob_average_3 && prob_average_5 > prob_average_2 && prob_average_5 > prob_average_1) {
//cout << " >>> 5 PTMs have a higher weighting <<< " << "\n" << "\n";
highest_prob_pos[0] = highest_prob_pos_5[0]; highest_prob_pos[1] = highest_prob_pos_5[1];
highest_prob_pos[2] = highest_prob_pos_5[2]; highest_prob_pos[3] = highest_prob_pos_5[3]; highest_prob_pos[4] = highest_prob_pos_5[4];
combination = combination_5;
more_than_3 = 5;
}
} else { number_of_possible_ptms++; }
//auto end4 = chrono::steady_clock::now();
//------------------------------------------------------------------------------//
//––––––––––––––––––––––––––//
//––––––| 4 PTMs alt |––––––//
//––––––––––––––––––––––––––//
if (combination == 0 && number_of_possible_ptms == 6) {
// cout << "4 PTMs (Alternative)...";
//
//auto [highest_prob_pos_4, combination_4] = findingCombinationOf4PTM_inprogress(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
//auto [highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5] = findingCombinationOf4and5PTM(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
auto [highest_prob_pos_4, combination_4, highest_prob_pos_5, combination_5] = findingCombinationOf4and5PTM_Best(masses, prob, PTM_list, mass_shift_lower, mass_shift_upper);
number_of_possible_ptms = 4;
// cout << "4 PTMs...";
float prob_average_4 = 0.0;
if (combination_4 > 0) {
prob_average_4 = (prob[highest_prob_pos_4[0]] + prob[highest_prob_pos_4[1]] + prob[highest_prob_pos_4[2]] + prob[highest_prob_pos_4[3]]) / 4;
//cout << "\n" << "The mass shift can be explained by 4 PTMs - ";
//cout << "with score: " << prob_average_4 << "\n";
if ( prob_average_4 > prob_average_3 && prob_average_4 > prob_average_2 && prob_average_4 > prob_average_1) {
//cout << " >>> 4 PTMs have a higher weighting <<< " << "\n" << "\n";
highest_prob_pos[0] = highest_prob_pos_4[0]; highest_prob_pos[1] = highest_prob_pos_4[1];
highest_prob_pos[2] = highest_prob_pos_4[2]; highest_prob_pos[3] = highest_prob_pos_4[3];
combination = combination_4;
more_than_3 = 6;
}
// break;
} else {
number_of_possible_ptms = 6;
}
float prob_average_5 = 0.0;
if (combination_5 > 0) {
prob_average_5 = (prob[highest_prob_pos_5[0]] + prob[highest_prob_pos_5[1]] + prob[highest_prob_pos_5[2]] + prob[highest_prob_pos_5[3]] +prob[highest_prob_pos_5[4]]) / 5;
//cout << "\n" << "The mass shift can be explained by 4 PTMs - ";
//cout << "with score: " << prob_average_4 << "\n";
if ( prob_average_5 > prob_average_4 && prob_average_5 > prob_average_3 && prob_average_5 > prob_average_2 && prob_average_5 > prob_average_1) {
//cout << " >>> 4 PTMs have a higher weighting <<< " << "\n" << "\n";
highest_prob_pos[0] = highest_prob_pos_5[0]; highest_prob_pos[1] = highest_prob_pos_5[1];
highest_prob_pos[2] = highest_prob_pos_5[2]; highest_prob_pos[3] = highest_prob_pos_5[3]; highest_prob_pos[4] = highest_prob_pos_5[4];
combination = combination_5;
more_than_3 = 6;
}
// break;
} else {
number_of_possible_ptms = 6;
}
}
// auto end5 = chrono::steady_clock::now();
//=======================================================================================================//
// No results
if (combination == 0 && number_of_possible_ptms == 6) {
cout << "\n" << "The mass shift of " << peptide << " can NOT be explained till 5 PTMs" << "\n" << "\n";
//ofstream output_file;
output_file.open(output_file_path, ios::out | ios::app);
output_file << peptide << "\t" << mass_shift << "\t" << peptide_mass << "NA" << "NA" << "NA" << "NA" << "NA" << "\n";
output_file.close();
//// skip to next peptide
continue;
}
//=======================================================================================================//
//================================| Output |================================//
// timers
// auto end = chrono::steady_clock::now();
// auto diff = end - start;
// string elapsed_time;
//
// if (chrono::duration <double, milli> (diff).count() < 1) {
// elapsed_time = to_string(chrono::duration <double, milli> (diff).count()) + " ms";
// } else {
// elapsed_time = to_string(chrono::duration <double, milli> (diff).count() / 1000) + " s";
// }
//// print output combination stats
// cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << "\n\n";
// cout << "peptide: " << peptide << "\n\n";
// cout << "PTM list: " << length << "; number of PTMs: " << number_of_possible_ptms << "\n";
// cout << "mass shift: " << mass_shift << " ± " << mass_error << "; combinations: " << combination << "\n" << "\n";
// cout << "=======================================================================" << "\n" << "\n";
// cout << prob_average_3 << " " <<prob_average_4 << "\n";
vector<string> out_PTM_name;
float sum_of_masses {}; // mass of all PTMS
float prob_PTMs {}; // score of PTMs
//// 1-3 PTMs
if (more_than_3 <= 3) {
//// print PTM names from file
fstream inputPTMnames;
inputPTMnames.open(dir_path + "new_names.txt");
//string sline;
for (int i = 0; i < 4; i++) {
if (highest_prob_pos[i] != list_end) {
GotoLine(inputPTMnames, 1 + highest_prob_pos[i]);
string line;
inputPTMnames >> line;
//cout << line << "\t";
out_PTM_name.push_back(line);
sum_of_masses += masses[highest_prob_pos[i]];
prob_PTMs += prob[highest_prob_pos[i]];
}
}
//cout << "\n\nmass shift sum: ";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// cout << masses[highest_prob_pos[i]] << "\t";
// }
// print positions
// cout << "\n\npositions: ";
//
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// cout << 1 + highest_prob_pos[i] << " ";
// }
// }
//// 4-5 PTMs
} else if (more_than_3 <= 5) {
fstream Natural_PTM_Names;
Natural_PTM_Names.open(dir_path + "new_nat_names.txt");
//cout << "\nPTM combination: ";
for (int i = 0; i <= 4; i++) {
if (highest_prob_pos[i] != list_end) {
GotoLine(Natural_PTM_Names, 1 + highest_prob_pos[i]);
string line;
Natural_PTM_Names >> line;
//cout << line << "\t";
out_PTM_name.push_back(line);
sum_of_masses += nat_masses[highest_prob_pos[i]];
prob_PTMs += nat_prob[highest_prob_pos[i]];
}
}
// cout << "\n\nmass shift sum: ";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// cout << nat_masses[highest_prob_pos[i]] << "\t";
// }
// }
// cout << "\npositions: ";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// cout << 1 + highest_prob_pos[i] << " ";
// }
// }
} else if (more_than_3 == 6) {
//// print PTM names from file
fstream inputPTMnames;
inputPTMnames.open(dir_path + "new_names.txt");
//string sline;
for (int i = 0; i <= 4; i++) {
if (highest_prob_pos[i] != list_end) {
GotoLine(inputPTMnames, 1 + highest_prob_pos[i]);
string line;
inputPTMnames >> line;
//cout << line << "\t";
out_PTM_name.push_back(line);
sum_of_masses += masses[highest_prob_pos[i]];
prob_PTMs += prob[highest_prob_pos[i]];
}
}
// cout << "\n\nmass shift sum: ";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// cout << masses[highest_prob_pos[i]] << "\t";
// }
// }
//
//
// // print positions
// cout << "\n\npositions: ";
//
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// cout << 1 + highest_prob_pos[i] << " ";
// }
// }
}
// print run-time
//cout << "\n\n" << "execution time = " << elapsed_time << "\n\n";
//cout << "=======================================================================" << "\n";
//cout << prob_average_1 << " " << prob_average_2 << " " << prob_average_3 << " " << prob_average_4 << " " << prob_average_5 << "\n";
//--------------------------------------------------------------------------------------------------/
//================================| Write Output |================================//
//// write output into file
//ofstream output_file;
output_file.open(output_file_path, ios::out | ios::app); //ios::app to open file in append mode
//output_file << "Peptide" << "\t" << "Mass_shift" << "\t" << "field" << "\t"; //DONE at the beginning
// for (int i = 1; i < out_PTM_name.size(); i++) {
// output_file << "PTM " << i << "\t";
// }
//"Peptide" << "\t" << "Mass_shift" << "\t" << "Peptide Mass" << "\t" << "Mass of PTMs" << "\t" << "Score" << "\t" << "PTM 1" << "PTM 2" etc...;
output_file << "\n" << peptide << "\t" << mass_shift << "\t" << peptide_mass << "\t" << sum_of_masses << "\t" << prob_PTMs << "\t";
for (int i = 0; i < out_PTM_name.size(); i++) {
output_file << out_PTM_name[i] << "\t";
}
//output_file << "\n";
output_file.close();
// for (int i = 0; i < out_name.size(); i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << masses[highest_prob_pos[i]] << "\t";
// }
// }
//
// output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < out_name.size(); i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << prob[highest_prob_pos[i]] << "\t";
// }
// }
// output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < out_name.size(); i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << 1 + highest_prob_pos[i] << "\t";
// }
// }
//// 4-5 PTMs
// else if (more_than_3 <= 5) {
//
// if (more_than_3 == 4) {
// output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t" << "1" << "\t" << "2" << "\t" << "3" << "\t" << "4" << "\t";
// } else if (more_than_3 == 5) { output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t" << "1" << "\t" << "2" << "\t" << "3" << "\t" << "4" << "\t" << "5" << "\t"; }
//
//
// output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << nat_names[highest_prob_pos[i]] << "\t";
// }
// }
//
// output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << nat_masses[highest_prob_pos[i]] << "\t";
// }
// }
//
// output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << nat_prob[highest_prob_pos[i]] << "\t";
// }
// }
//
// output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i <= 4; i++) {
// if (highest_prob_pos[i] != list_end) {
// output_file << 1 + highest_prob_pos[i] << "\t";
// }
// }
// }
//cout << "\n\n";
//--------------------------------------------------------------------------------------------------/
//================================| Alt Output |================================//
//// write alternative outputs into files
// string alt_output_file_path = dir_path + "results/" + sample + "/" + peptide + "_alternative.txt";
//
// ofstream alt_output_file;
// alt_output_file.open(alt_output_file_path, ios::out | ios::app);
//
//
//
//
// if (combination_1 > 0 && prob_average_1 > 0) {
//
// alt_output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t";
//
// for (int i = 1; i < 1; i++) {
// alt_output_file << i << "\t";
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
// for (int i = 0; i < 1; i++) {
//// alt_output_file << names[highest_prob_pos_1[i]] << "\t";
// alt_output_file << "\t";
// }
//
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i < 1; i++) {
// if (highest_prob_pos_1[i] != list_end) {
// alt_output_file << masses[highest_prob_pos_1[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < 1; i++) {
// if (highest_prob_pos_1[i] != list_end) {
// alt_output_file << prob[highest_prob_pos_1[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < 1; i++) {
// if (highest_prob_pos_1[i] != list_end) {
// alt_output_file << 1 + highest_prob_pos_1[i] << "\t";
// }
// }
//
//
// } else if (combination_2 > 0 && prob_average_2 > 0) {
//
// alt_output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t";
//
// for (int i = 1; i < 2; i++) {
// alt_output_file << i << "\t";
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
// for (int i = 0; i < 2; i++) {
//// alt_output_file << names[highest_prob_pos_1[i]] << "\t";
// alt_output_file << "\t";
// }
//
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i < 2; i++) {
// if (highest_prob_pos_2[i] != list_end) {
// alt_output_file << masses[highest_prob_pos_2[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < 2; i++) {
// if (highest_prob_pos_2[i] != list_end) {
// alt_output_file << prob[highest_prob_pos_2[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < 2; i++) {
// if (highest_prob_pos_2[i] != list_end) {
// alt_output_file << 1 + highest_prob_pos_2[i] << "\t";
// }
// }
//
// } else if (combination_3 > 0 && prob_average_3 > 0) {
//
// alt_output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t";
//
// for (int i = 1; i < 3; i++) {
// alt_output_file << i << "\t";
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
// for (int i = 0; i < 3; i++) {
// // alt_output_file << names[highest_prob_pos_1[i]] << "\t";
// alt_output_file << "\t";
// }
//
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i < 3; i++) {
// if (highest_prob_pos_3[i] != list_end) {
// alt_output_file << masses[highest_prob_pos_3[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < 3; i++) {
// if (highest_prob_pos_3[i] != list_end) {
// alt_output_file << prob[highest_prob_pos_3[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < 3; i++) {
// if (highest_prob_pos_3[i] != list_end) {
// alt_output_file << 1 + highest_prob_pos_3[i] << "\t";
// }
// }
// }
//
// else if ( more_than_3 == 6 && combination_4 > 0 && prob_average_4 > 0) {
//
// alt_output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t";
//
// for (int i = 1; i < 4; i++) {
// alt_output_file << i << "\t";
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
// for (int i = 0; i < 4; i++) {
// // alt_output_file << names[highest_prob_pos_1[i]] << "\t";
// alt_output_file << "\t";
// }
//
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << masses[highest_prob_pos_4[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << prob[highest_prob_pos_4[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << 1 + highest_prob_pos_4[i] << "\t";
// }
// }
// }
//
//
//
//
//
// if (more_than_3 == 4 && combination_4 > 0) {
// alt_output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t" << "1" << "\t" << "2" << "\t" << "3" << "\t" << "4" << "\t";
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << nat_names[highest_prob_pos_4[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << nat_masses[highest_prob_pos_4[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << nat_prob[highest_prob_pos_4[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < 4; i++) {
// if (highest_prob_pos_4[i] != list_end) {
// alt_output_file << 1 + highest_prob_pos_4[i] << "\t";
// }
// }
//
// } else if (more_than_3 == 5 && combination_5 > 0) {
// alt_output_file << "peptide" << "\t" << "mass_shift" << "\t" << "field" << "\t" << "1" << "\t" << "2" << "\t" << "3" << "\t" << "4" << "\t" << "5" << "\t";
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "name" << "\t";
//
// for (int i = 0; i < 5; i++) {
// if (highest_prob_pos_5[i] != list_end) {
// alt_output_file << nat_names[highest_prob_pos_5[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "mass" << "\t";
// for (int i = 0; i < 5; i++) {
// if (highest_prob_pos_5[i] != list_end) {
// alt_output_file << nat_masses[highest_prob_pos_5[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "score" << "\t";
// for (int i = 0; i < 5; i++) {
// if (highest_prob_pos_5[i] != list_end) {
// alt_output_file << nat_prob[highest_prob_pos_5[i]] << "\t";
// }
// }
//
// alt_output_file << "\n" << peptide << "\t" << mass_shift << "\t" << "position" << "\t";
// for (int i = 0; i < 5; i++) {
// if (highest_prob_pos_5[i] != list_end) {
// alt_output_file << 1 + highest_prob_pos_5[i] << "\t";
// }
// }
// }
//
//
// alt_output_file << "\n";
// alt_output_file.close();
}
delete [] masses; delete[] prob; delete [] nat_masses; delete [] nat_prob; //deleting array created using memory allocation
auto end = chrono::steady_clock::now();
auto diff = end - start;
string elapsed_time;
if (chrono::duration <double, milli> (diff).count() < 1) {
elapsed_time = to_string(chrono::duration <double, milli> (diff).count()) + " ms";
} else {
elapsed_time = to_string(chrono::duration <double, milli> (diff).count() / 1000) + " s";
}
output_file.open(output_file_path, ios::out | ios::app);
output_file << "\n" << "Elapsed time is : " << elapsed_time << "\n";
output_file.close();
return 0;
}
//a->push_back(3);
//cout << "here " << a->at(0);
| true |
a860ce3f993ae5928cc31aaa3fe6b10682537a09 | C++ | Anton94/itc | /tests/condition_variable_tests.cpp | UTF-8 | 1,131 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "condition_variable_tests.h"
#include "utils.hpp"
#include <itc/condition_variable.hpp>
#include <itc/thread.h>
#include <chrono>
namespace cv_tests
{
using namespace std::chrono_literals;
void run_tests(int iterations)
{
auto th1 = itc::make_thread();
auto th2 = itc::make_thread();
for(int i = 0; i < iterations; ++i)
{
// for the purpose of testing we will make it as shared_ptr
auto cv = std::make_shared<itc::condition_variable>();
itc::invoke(th1.get_id(), [cv, i]() {
std::mutex m;
std::unique_lock<std::mutex> lock(m);
auto res = cv->wait_for(lock, 50ms);
if(res == std::cv_status::no_timeout)
{
sout() << "th1 cv notified " << i;
}
else
{
sout() << "th1 cv timed out " << i;
}
});
itc::invoke(th2.get_id(), [cv, i]() {
std::mutex m;
std::unique_lock<std::mutex> lock(m);
auto res = cv->wait_for(lock, 100ms);
if(res == std::cv_status::no_timeout)
{
sout() << "th2 cv notified " << i;
}
else
{
sout() << "th2 cv timed out " << i;
}
});
std::this_thread::sleep_for(60ms);
cv->notify_all();
}
}
} // namespace cv_tests
| true |
af5246fe1c376d464b6e9bfc441d5282caec92dc | C++ | KimDoKy/Cpp-ex-200 | /part3.중급/076.cpp | UTF-8 | 593 | 3.6875 | 4 | [] | no_license | // Call by Address 이해하기
// 주소를 명시적으로 전달받아 4바이트가 할당
#include <iostream>
using namespace std;
void Func1(bool *is_on)
{
cout << "Call by address: " << sizeof(is_on) << endl;
}
void Func2(bool &is_on)
{
cout << "Call by reference: " << sizeof(is_on) << endl;
}
int main()
{
bool is_tmp = true;
// 함수가 포인터를 인자로 받기 때문에 호출도 주소를 명시해야 함
Func1(&is_tmp);
// 함수가 주소를 인자로 받는데, 호출은 값을 그대로 넘겨야 함
Func2(is_tmp);
return 0;
}
| true |
15889cd29432a078476b2f83b4b2d3a0c431d0a9 | C++ | Kanu-Priya-Sehrawat/InterviewPrep | /Maximum of all subarrays of size k.cpp | UTF-8 | 899 | 3.25 | 3 | [] | no_license | //Function to find maximum of each subarray of size k.
vector <int> max_of_subarrays(int *arr, int n, int k)
{
// your code here
vector<int> ans;
int i, j;
i = j = 0;
list<int> l;
while(j < n){
// Calculation
// All the smaller element in the list ...... pop krne h
while(l.size()>0 && l.back()<arr[j])
l.pop_back();
// aur phir push kr dena h
l.push_back(arr[j]);
if(j-i+1 < k){
j++;
}
else if(j-i+1 == k){
// ans from calculation
ans.push_back(l.front());
// slide the window
if(arr[i] == l.front())
l.pop_front();
i++;
j++;
}
}
return ans;
}
| true |
3b6c96df3f1126e860de0217bba73eb9f061509a | C++ | ryuxsherlockdeveloper/LPU-Workshop | /Day 1/recursion_2nd.cpp | UTF-8 | 2,341 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <climits>
#include <algorithm>
#include <cmath>
#include <bitset>
#include <cstdio>
#include <cstring>
#include <stack>
#include <iomanip>
#include <set>
#include <map>
using namespace std;
string removeDuplicates(string str) {
if (str.length() == 0) {
return str;
}
char ch = str[0];
string ros = str.substr(1);
string recursionResult = removeDuplicates(ros);
if (recursionResult[0] == ch) {
return recursionResult;
} else {
return ch + recursionResult;
}
}
string addStarBetweenDuplicates(string str) {
if (str.length() == 0) return str;
char ch = str[0];
string ros = str.substr(1);
string recursionResult = addStarBetweenDuplicates(ros);
if (recursionResult[0] == ch) {
// return ch + string("*") + recursionResult;
recursionResult = '*' + recursionResult;
return ch + recursionResult;
} else {
return ch + recursionResult;
}
}
string moveXToEnd(string str) {
if (str.length() == 0) return str;
char ch = str[0];
string ros = str.substr(1);
string recursionResult = moveXToEnd(ros);
if (ch == 'x') {
return recursionResult + ch;
} else {
return ch + recursionResult;
}
}
string replacePi(string str) {
if (str.length() == 0) return str;
char ch = str[0];
string ros = str.substr(1);
string recursionResult = replacePi(ros);
if (ch == 'p' and recursionResult[0] == 'i') {
return "3.14" + recursionResult.substr(1);
} else {
return ch + recursionResult;
}
}
void printSubsequence(string str, string ans) {
if (str.length() == 0) {
cout << "" << endl;
// cout << ans << endl;
return;
}
char ch = str[0];
string ros = str.substr(1);
printSubsequence(ros, ans + ch);
printSubsequence(ros, ans);
}
void printPermutations(string str, string ans) {
if (str.length() == 0) {
cout << ans << endl;
return;
}
for (int i = 0; i < str.length(); i++) {
char ch = str[i];
string ros = str.substr(0, i) + str.substr(i + 1);
printPermutations(ros, ans + ch);
}
}
int main() {
// cout << removeDuplicates("abbccdggf") << endl;
// cout << addStarBetweenDuplicates("hhelloo") << endl;
// cout << moveXToEnd("xabcxxyx") << endl;
// cout << replacePi("xxpiipixxppix") << endl;
// printSubsequence("abc", "");
// printPermutations("abc", "");
return 0;
} | true |
e28c9d29a4c981f3623fc696050dc7dc3cba2d25 | C++ | gezi322/WindowsPrinterDriver | /UI/Pdk/PdkApp.h | UTF-8 | 5,306 | 2.53125 | 3 | [] | no_license | #ifndef PDKAPP_H_ // (make sure this is only included once)
#define PDKAPP_H_
#ifndef __cplusplus
#error PdkApp.h included in a non-C++ source file!
#endif
// --------------------------------------------------------------------
// INCLUDES
// --------------------------------------------------------------------
#include "PdkBase.h"
// --------------------------------------------------------------------
// #DEFINES, TYPEDEF'S, and TEMPLATES
// --------------------------------------------------------------------
// --------------------------------------------------------------------
// EXPORTED CLASSES
// --------------------------------------------------------------------
// ....................................................................
// CLASS NAME: PdkApp
//
// REPONSIBILITIES:
//
// NOTES:
// ....................................................................
class CPdkApp : public CPdkBase
{
public:
// ## Constructors / Destructor
CPdkApp (); // class constructor
~CPdkApp (); // class destructor
// ## Public Members
// ....................................................................
// METHOD NAME: InitApp
// DESCRIPTION:
// Initializes the application/DLL by setting the app/dll instance
// handle and names. This method will also open the supplied
// resource DLL by trying the array of directories until the
// first successful load has been accomplished. m_hInstRes and
// m_hInst will both be initialized to hInst. If a separate
// DLL is required for resources, use OpenResourceDLL() below.
//
// szResourceDLLPath should contain the full path to the resource
// DLL and m_hInstRes will be set to the return value of the
// LoadLibrary call. If szResourceDLLPath is empty length or NULL,
// the current value of m_hInst will be used for m_hInstRes.
//
// The resource DLL will not actually be loaded upon this call.
// Instead, it will be loaded the first time it is needed when
// accessed through GetResourceInst()
//
// After this call, m_hInst, m_szResourceDLLPath, m_szModName, and
// m_szAppName are initialized. m_hInstRes is not initialized.
//
// RETURN VALUE:
// Returns 0 (ERROR_SUCCESS) on success
// ....................................................................
int InitApp(HINSTANCE hInst, const TCHAR *szModName,
const TCHAR *szAppName, const TCHAR *szResourceDLLPath);
// ....................................................................
// METHOD NAME: GetInst
// DESCRIPTION:
// Returns the instance handle of this application or DLL.
//
// RETURN VALUE:
// ....................................................................
HINSTANCE GetInst() const;
#ifndef KERNEL_MODE
// ....................................................................
// METHOD NAME: GetResourceInst
// DESCRIPTION:
// Returns the instance handle of this applications resource DLL.
// If m_hInstRes has not yet been set, then it will attempt to
// execute LoadLibrary to load the DLL using the m_szResourceDLLPath
// member. If m_szResourceDLLPath is not set, it will return
// m_hInst.
//
// If will return NULL if the LoadLibrary call failed.
//
// RETURN VALUE:
// ....................................................................
#ifndef WIN_95
HINSTANCE GetResourceInst() const;
#else
HINSTANCE GetResourceInst();
#endif
// ....................................................................
// METHOD NAME: GetVerString
// DESCRIPTION:
// Returns version information in string format for each of the
// fields supplied. Any of the supplied strings may be NULL if
// this info is not required. Any strings that are non-NULL must
// have character lengths of at least maxStrLen.
//
// The first language available in the version resource is used to
// supply this information.
//
// RETURN VALUE:
// The encapsulated devmode or NULL on error
// ....................................................................
bool
GetVerString(unsigned int maxStrLen, TCHAR *szComments,
TCHAR *szCompanyName, TCHAR *szFileDescription,
TCHAR *szFileVersion, TCHAR *szLegalCopyright,
TCHAR *szProductName, TCHAR *szProductVersion);
#endif // !KERNEL_MODE
// Name of this module - usually the DLL name
TCHAR m_szModName[MAX_PATH];
// Name of this application, usually used for debugging
TCHAR m_szAppName[MAX_PATH];
private:
// ## Instance Variables
// Handle to the default resources of the application / DLL
#ifndef WIN_95
mutable
#endif
HINSTANCE m_hInstRes;
// Handle to the current instance of this application. If this is a
// DLL, then it is the HINSTANCE of the DLL.
HINSTANCE m_hInst;
// The full path to the resource DLL. If this is the empty string,
// then m_hInst will be used as the instance handle to the resources.
TCHAR m_szResourceDLLPath[MAX_PATH];
};
// This must be implemented once per DLL, so the PDK can
// get the actual driver object.
CPdkApp* GetPdkAppObj();
#endif // PDKAPP_H_
| true |
a5cedf37d66e51ad13f97c79e98b9c29202e0c1c | C++ | tallavi11/csci13600-labs | /lab_01/smaller3.cpp | UTF-8 | 773 | 3.46875 | 3 | [] | no_license | /*
Author: Tal Lavi
Course: CSCI-133
Instructor: Mike Zamansky
Assignment: Lab1B
Write a program smaller3.cpp that asks the user to input three integer numbers and prints out the smaller of the three.
*/
#include <iostream>
using namespace std;
int main() {
int x = 0;
int y = 0;
int z = 0;
cout << "Enter the first number: ";
cin >> x;
cout << "Enter the second number: ";
cin >> y;
cout << "Enter the third number: ";
cin >> z;
cout << "\n";
if (x < y){
if(x < z){
cout << "The smaller of the three is " << x << endl;
} else {
cout << "The smaller of the three is " << z << endl;
}
} else if(z < y){
cout << "The smaller of the three is " << z << endl;
} else {
cout << "The smaller of the three is " << y << endl;
}
return 0;}
| true |
22fd106197f77a62b564027635894a3ce8dec810 | C++ | siolag161/thread_pool | /thread_pool.hpp | UTF-8 | 1,158 | 2.953125 | 3 | [] | no_license |
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
typedef std::function<void()> Task;
class ThreadWorker;
class ThreadPool {
public:
ThreadPool(unsigned max_workers=5, unsigned max_tasks = 20);
virtual ~ThreadPool();
template<class F, class... Args>
bool enqueue(F&& f, Args&&... args) {
if (tasks.size() >= max_tasks) return false;
auto task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
{
std::unique_lock<std::mutex> lock(q_mutex);
tasks.push(task);
}
has_task_q.notify_one();
return true;
};
void shutdown();
friend class ThreadWorker;
private:
std::vector<std::shared_ptr<ThreadWorker>> workers;
std::queue<Task> tasks;
unsigned max_workers;
unsigned max_tasks;
std::mutex q_mutex;
std::condition_variable has_task_q;
bool stop;
bool done;
};
class ThreadWorker {
public:
ThreadWorker(ThreadPool& pool);
virtual ~ThreadWorker() {}
void join();
private:
void run();
private:
ThreadPool& pool;
std::thread thread;
};
| true |
a674e0d45064ff5ea5c1c2acd4b58c7b0fe42922 | C++ | SoC-OpenGL/soc-assignment-1-nnicobar | /Q1/MyShape.cpp | UTF-8 | 8,356 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include<math.h>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// Window dimensions
const GLuint WIDTH = 700, HEIGHT = 700;
// Shaders
const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";
const GLchar* fragmentShader1Source = "#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
const GLchar* fragmentShader2Source = "#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = vec4(0.4f, 0.5f, 0.6f, 1.0f );\n"
"}\n\0";
// The MAIN function, from here we start the application and run the game loop
int main()
{
// Init GLFW
glfwInit( );
// Set all the required options for GLFW
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow *window = glfwCreateWindow( WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr );
int screenWidth, screenHeight;
glfwGetFramebufferSize( window, &screenWidth, &screenHeight );
if ( nullptr == window )
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate( );
return EXIT_FAILURE;
}
glfwMakeContextCurrent( window );
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if ( GLEW_OK != glewInit( ) )
{
std::cout << "Failed to initialize GLEW" << std::endl;
return EXIT_FAILURE;
}
// Define the viewport dimensions
glViewport( 0, 0, screenWidth, screenHeight );
// Build and compile our shader programs
// Vertex shader
GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );
glShaderSource( vertexShader, 1, &vertexShaderSource, NULL );
glCompileShader( vertexShader );
// Check for compile time errors
GLint success;
GLchar infoLog[512];
glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &success );
if ( !success )
{
glGetShaderInfoLog( vertexShader, 512, NULL, infoLog );
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment shader Disc
GLuint fragmentShaderDisc = glCreateShader( GL_FRAGMENT_SHADER );
glShaderSource( fragmentShaderDisc, 1, &fragmentShader1Source, NULL );
glCompileShader( fragmentShaderDisc );
// Check for compile time errors
glGetShaderiv( fragmentShaderDisc, GL_COMPILE_STATUS, &success );
if ( !success )
{
glGetShaderInfoLog( fragmentShaderDisc, 512, NULL, infoLog );
std::cout << "ERROR::SHADER::FRAGMENT1::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment shader BG
GLuint fragmentShaderBG = glCreateShader( GL_FRAGMENT_SHADER );
glShaderSource( fragmentShaderBG, 1, &fragmentShader2Source, NULL );
glCompileShader( fragmentShaderBG );
// Check for compile time errors
glGetShaderiv( fragmentShaderBG, GL_COMPILE_STATUS, &success );
if ( !success )
{
glGetShaderInfoLog( fragmentShaderBG, 512, NULL, infoLog );
std::cout << "ERROR::SHADER::FRAGMENT2::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Link shader Disc
GLuint shaderProgramDisc = glCreateProgram( );
glAttachShader( shaderProgramDisc, vertexShader );
glAttachShader( shaderProgramDisc, fragmentShaderDisc );
glLinkProgram( shaderProgramDisc );
// Check for linking errors
glGetProgramiv( shaderProgramDisc, GL_LINK_STATUS, &success );
if ( !success )
{
glGetProgramInfoLog( shaderProgramDisc, 512, NULL, infoLog );
std::cout << "ERROR::SHADERDISC::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(fragmentShaderDisc);
// Link shader BG
GLuint shaderProgramBG = glCreateProgram( );
glAttachShader( shaderProgramBG, vertexShader );
glAttachShader( shaderProgramBG, fragmentShaderBG );
glLinkProgram( shaderProgramBG );
// Check for linking errors
glGetProgramiv( shaderProgramBG, GL_LINK_STATUS, &success );
if ( !success )
{
glGetProgramInfoLog( shaderProgramBG, 512, NULL, infoLog );
std::cout << "ERROR::SHADERBG::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader( vertexShader );
glDeleteShader( fragmentShaderBG );
// Set up vertex data (and buffer(s)) and attribute pointers
//VERTEX DATA FOR OUTER DISC
GLfloat vertices[1089], theta, radius = 0.5f;
vertices[0] = 0.0f;
vertices[1] = 0.0f;
vertices[2] = 0.0f;
for(int i = 3; i<1089; i+=3)
{
GLfloat theta = (((i/3)-1)*3.14)/180;
vertices[i] = radius* cos(theta);
vertices[i+1] = radius* sin(theta);
vertices[i+2] = 0.0f;
}
//VERTEX DATA FOR INNER DISC
GLfloat invertices[1089], inradius = 0.4f;
invertices[0] = 0.0f;
invertices[1] = 0.0f;
invertices[2] = 0.0f;
for(int i = 3; i<1089; i+=3)
{
theta = (((i/3)-1)*3.14)/180;
invertices[i] = inradius* cos(theta);
invertices[i+1] = inradius* sin(theta);
invertices[i+2] = 0.0f;
}
//INDICES
GLuint indices[363];
for(int i = 0 ; i<=362; i++)
{
indices[i] = i;
}
//DECLARING ARRAYS
GLuint VBO[2], VAO[2], EBO[2];
//FOR OUTER DISC
glGenVertexArrays( 1, &VAO[0]);
glGenBuffers( 1, &VBO[0]);
glGenBuffers(1, &EBO[0]);
glBindVertexArray( VAO[0] );
glBindBuffer( GL_ARRAY_BUFFER, VBO[0] );
glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW );
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer( 0, 3, GL_FLOAT , GL_FALSE, 3 * sizeof( GLfloat ), ( GLvoid * ) 0 );
glEnableVertexAttribArray( 0 );
glBindVertexArray( 0 );
//FOR INNER DISC
glGenVertexArrays( 1, &VAO[1]);
glGenBuffers( 1, &VBO[1]);
glGenBuffers(1, &EBO[1]);
glBindVertexArray( VAO[1] );
glBindBuffer( GL_ARRAY_BUFFER, VBO[1] );
glBufferData( GL_ARRAY_BUFFER, sizeof( invertices ), invertices, GL_STATIC_DRAW );
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer( 0, 3, GL_FLOAT , GL_FALSE, 3 * sizeof( GLfloat ), ( GLvoid * ) 0 );
glEnableVertexAttribArray( 0 );
glBindVertexArray( 0 );
// Game loop
while ( !glfwWindowShouldClose( window ) )
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents( );
// Render
// Clear the colorbuffer
glClearColor( 0.4f, 0.5f, 0.6f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT );
// Draw our outer disc
glUseProgram( shaderProgramDisc );
glBindVertexArray( VAO[0] );
glDrawElements(GL_TRIANGLE_FAN, 1080, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
//Draw our inner disc
glUseProgram(shaderProgramBG);
glBindVertexArray( VAO[1] );
glDrawElements(GL_TRIANGLE_FAN, 1080, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// Swap the screen buffers
glfwSwapBuffers( window );
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays( 1, &VAO[0] );
glDeleteVertexArrays( 1, &VAO[1] );
glDeleteBuffers( 1, &VBO[0] );
glDeleteBuffers( 1, &VBO[1] );
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate( );
return EXIT_SUCCESS;
}
| true |
0317c10165b375474c504a56cb565677b384b39e | C++ | wesmail/hydra | /old_hydra/hydra/branches/v3_04stable/base/geantutil/hgeantshower.h | UTF-8 | 1,653 | 2.5625 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////
// HGeantShower
//
// GEANT SHOWER event data
//
// last modified on 29/1/99 by R.Holzmann (GSI)
///////////////////////////////////////////////////////////////////////////
#ifndef HGEANTSHOWER_H
#define HGEANTSHOWER_H
#include "hlocateddataobject.h"
class HGeantShower : public HLocatedDataObject
{
private:
Int_t trackNumber; // GEANT track number
Float_t eHit; // energy deposited (in MeV)
Float_t xHit; // x of hit (in cm)
Float_t yHit; // y of hit (in cm)
Float_t thetaHit; // angle of incidence (0-180 deg)
Float_t phiHit; // azimuthal angle (0-360 deg)
Float_t betaHit; // beta particle (momentum/energy)
Char_t sector; // sector number (0-5)
Char_t module; // module number (0-2)
public:
HGeantShower(void);
HGeantShower(HGeantShower &aShower);
~HGeantShower(void);
inline void setTrack(Int_t aTrack) {trackNumber = aTrack;}
void setHit(Float_t ae, Float_t ax, Float_t ay, Float_t abeta);
void setIncidence(Float_t ath, Float_t aph);
void setAddress (Char_t s, Char_t m);
inline Int_t getTrack(void) {return trackNumber;}
void getHit(Float_t &ae, Float_t &ax, Float_t &ay, Float_t &abeta);
void getIncidence(Float_t &ath, Float_t &aph);
inline Char_t getSector(void) {return sector;}
inline Char_t getModule(void) {return module;}
inline Int_t getNLocationIndex(void) {return 2;}
inline Int_t getLocationIndex(Int_t i);
ClassDef(HGeantShower,1) // Geant SHOWER event data class
};
#endif /*! HGEANTSHOWER_H */
| true |
0de0f0cddd59aade660a2e6de95d47383eb84a9e | C++ | wushangzhen/LeetCode-Practice | /137-clone-graph/8-20-2018-bfs.cc | UTF-8 | 1,392 | 3.1875 | 3 | [] | no_license | /**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/*
* @param node: A undirected graph node
* @return: A undirected graph node
*/
UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) {
// write your code here
if (!node) {
return NULL;
}
UndirectedGraphNode* p1 = node;
UndirectedGraphNode* p2 = new UndirectedGraphNode(node->label);
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map; // for used node
queue<UndirectedGraphNode*> que;
que.push(p1);
map[node] = p2;
while (!que.empty()) {
p1 = que.front();
p2 = map[p1];
que.pop();
for (int i = 0; i < p1->neighbors.size(); i++) {
UndirectedGraphNode *nb = p1->neighbors[i];
if (map.count(nb)) {
p2->neighbors.push_back(map[nb]);
} else {
UndirectedGraphNode *temp = new UndirectedGraphNode(nb->label);
p2->neighbors.push_back(temp);
map[nb] = temp;
que.push(nb);
}
}
}
return map[node];
}
};
| true |
2ac3fd63d49b78cdd4ea02837fa76355371e8226 | C++ | zpiao1/CPP-Primer | /Exercise 13.22.cpp | UTF-8 | 474 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class HasPtr {
public:
HasPtr(const std::string &s = std::string()):
ps(new std::string(s)), i(0) {}
HasPtr(const HasPtr &hp):
ps(new std::string(*(hp.ps))), i(hp.i) {}
HasPtr &operator=(const HasPtr &hp) {
std::string *temp = new std::string(*hp.ps);
delete ps;
ps = temp;
i = hp.i;
return *this;
}
private:
std::string *ps;
int i;
}; | true |
3bf53615dd5a56e0a6b165ed0ce10c8b64daa217 | C++ | baturevychvitalii/game_book | /src/game_book/items/food.h | UTF-8 | 599 | 2.953125 | 3 | [] | no_license | #ifndef __GAMEBOOK_ITEMS_FOOD__
#define __GAMEBOOK_ITEMS_FOOD__
#include "../item.h"
/**
is supposed to heal the creature, on which is being used
*/
class Food : public Item
{
int heal_value;
size_t Use(size_t charges = 1, Creature *potential_opponent = nullptr) override;
public:
/**
constructs item from xml tag
*/
Food(
IChangeable * parent,
size_t width,
short y,
short x,
short active_color,
short inactive_color,
const xml::Tag & t
);
/**
serializes food's properties to xml tag
*/
xml::Tag Serialize() const override;
};
#endif
| true |
97581c36de91c45c622187d0f6192937248c770f | C++ | nik464/Coding-Ninjas-DSA-CPP | /Tree/StructurallyIdentical.cpp | UTF-8 | 530 | 3.46875 | 3 | [] | no_license |
bool areIdentical(TreeNode<int> *root1, TreeNode<int> * root2) {
if((root1==nullptr && root2 !=nullptr) || (root1 !=nullptr && root2==nullptr) )
{
return false;
}
if(root1->data != root2->data)
{
return false;
}
if(root1->children.size()!=root2->children.size())
{
return false;
}
for(int i=0;i<root1->children.size();i++)
{
if(!areIdentical(root1->children[i],root2->children[i]))
{
return false;
}
}
return true;
}
| true |
d87575a97f23fa9acac5fb700d676f4385bf0bcc | C++ | aseem01/Competitive_Programming | /codeforce/Codeforce_Rating_Round/round_413/B. T-shirt buying.cpp | UTF-8 | 4,464 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define uniq(x) x.erase(unique(x.begin(),x.end()), x.end()) //Unique value find from vector
#define upper(arr,n,fixed) upper_bound(arr,arr+n,fixed)-arr //Upper value search;
#define lower(arr,n,fixed) upper_bound(arr,arr+n,fixed)-arr //Lower value search;
#define max3(a,b,c) max(max(a,b),c)//maximum value find three value;
#define min3(a,b,c) min(min(a,b),c)//minimum value find three value;
#define rep(i,intial,n) for(int i=intial; i<(n) ; i++)
#define REP(i,intial,n) for(int i=intial; i<=(n) ; i++)
#define PI acos(-1.0)//PI Calculation
#define LL long long
#define MP make_pair
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define MX 1000005
#define MOD 1000000007
template<typename T> T POW(T b,T p) //Pow calculation
{
T r=1;
while(p)
{
if(p&1)r=(r*b);
b=(b*b);
p>>=1;
}
return r;
}
LL big_mod(LL n, LL p)
{
if(p==0) return 1;
if(!(p&1))
{
LL r = big_mod(n,p/2) % MOD;
return ( (r%MOD) * (r%MOD) ) % MOD;
}
else return ( ( n%MOD) * (big_mod(n,p-1) %MOD)) % MOD;
}
long long gcd(long long a, long long b)
{
while (b != 0)
{
long long t = a % b;
a = b;
b = t;
}
return a;
}
//||--------------------------->||Main_Code_Start_From_Here||<---------------------------------||
int n,p[200010],f[200010],b[200010],query,value,fc,bc,check,flag,visit[200010];
bool cmp(pair<int,int>a,pair<int,int>b)
{
return a.first>b.first;
}
int main()
{
//freopen("a.in", "r", stdin);
//freopen("a.out", "w", stdout);
vector<pair<int,int> >v1,v2,v3;
while(cin>>n)
{
memset(visit,0,sizeof(visit));
v1.clear();
v2.clear();
v3.clear();
rep(i,0,n) cin>>p[i];
rep(i,0,n)
{
cin>>fc;
if(fc==1) v1.push_back(make_pair(p[i],i));
else if(fc==2) v2.push_back(make_pair(p[i],i));
else v3.push_back(make_pair(p[i],i));
}
rep(i,0,n)
{
cin>>bc;
if(bc==1) v1.push_back(make_pair(p[i],i));
else if(bc==2) v2.push_back(make_pair(p[i],i));
else v3.push_back(make_pair(p[i],i));
}
sort(v1.begin(),v1.end(),cmp);
sort(v2.begin(),v2.end(),cmp);
sort(v3.begin(),v3.end(),cmp);
/*cout<<"v1 sorting "<<endl;
rep(i,0,v1.size()) cout<<v1[i].first<<" "<<v1[i].second<<endl;
cout<<"v2 sorting"<<endl;
rep(i,0,v2.size()) cout<<v2[i].first<<" "<<v2[i].second<<endl;
cout<<"v3 sorting"<<endl;
rep(i,0,v3.size()) cout<<v3[i].first<<" "<<v3[i].second<<endl;*/
cin>>query;
rep(i,0,query)
{
cin>>value;
if(value==1)
{
flag=0;
for(int j=v1.size()-1;j>=0;j--)
{
check=v1[j].second;
if(visit[check]==0)
{
cout<<v1[j].first<<endl;
v1.pop_back();
visit[check]=1;
flag=1;
break;
}
else v1.pop_back();
}
if(!flag) cout<<"-1"<<endl;
}
if(value==2)
{
flag=0;
for(int j=v2.size()-1;j>=0;j--)
{
check=v2[j].second;
if(visit[check]==0)
{
cout<<v2[j].first<<endl;
visit[check]=1;
v2.pop_back();
flag=1;
break;
}
else v2.pop_back();
}
if(!flag) cout<<"-1"<<endl;
}
if(value==3)
{
flag=0;
for(int j=v3.size()-1;j>=0;j--)
{
check=v3[j].second;
if(visit[check]==0)
{
cout<<v3[j].first<<endl;
visit[check]=1;
v3.pop_back();
flag=1;
break;
}
else v3.pop_back();
}
if(!flag) cout<<"-1"<<endl;
}
}
}
}
| true |
ed2983c0abdbb7f1ddca1d8ad9d3ac185c22d958 | C++ | adamjer/Virtual-World | /SowThistle.cpp | UTF-8 | 2,126 | 2.703125 | 3 | [] | no_license | #include "SowThistle.h"
namespace organisms
{
SowThistle::SowThistle(worlds::VirtualWorld* world, SDL_Point& location)
{
this->initiative = 0;
this->strength = 0;
this->location = location;
this->world = world;
this->name = "SowThistle";
this->isAfterAction = false;
this->texture.loadFromFile(this->world->getRenderer(), "data/Images/SowThistle.png");
}
SowThistle::SowThistle(SowThistle& a)
{
this->initiative = a.initiative;
this->strength = a.strength;
this->location = a.location;
this->world = a.world;
this->name = a.name;
this->isAfterAction = a.isAfterAction;
this->texture.loadFromFile(this->world->getRenderer(), "data/Images/SowThistle.png");
}
SowThistle::~SowThistle()
{
}
void SowThistle::action()
{
if (!this->isAfterAction)
{
for (int k = 0; k < 3; k++)
{
std::vector<SDL_Point> availableSquares;
int place;
this->addAllSquares(availableSquares);
int seeding = rand() % 100;
if (seeding < SEEDING_PROBABILITY)
{
std::vector<SDL_Point> freeSquares;
for (int i = 0; i < (int)availableSquares.size(); i++)
{
bool isFree = true;
for (int j = 0; j < (int)this->world->getAllOrganisms().size(); j++)
{
if (availableSquares[i].x == this->world->getAllOrganisms()[j]->getLocation().x &&
availableSquares[i].y == this->world->getAllOrganisms()[j]->getLocation().y)
{
isFree = false;
break;
}
}
if (isFree)
freeSquares.push_back(availableSquares[i]);
}
if ((int)freeSquares.size() > 0)
{
place = rand() % (int)freeSquares.size();
this->world->getAllOrganisms().push_back(new SowThistle(this->world, freeSquares[place]));
this->world->getAllOrganisms()[this->world->getAllOrganisms().size() - 1]->setAfterAction();
this->isAfterAction = false;
this->collision();
this->world->draw();
SDL_Delay(PLANT_SPEED);
}
}
}
}
}
void SowThistle::collision()
{
Plant::collision();
}
}
| true |
12036dc7d7b45d383a7c5604f7db106ae7183366 | C++ | Oktianto123/T-8 | /8-4-19.cpp | UTF-8 | 872 | 3.203125 | 3 | [] | no_license | #include <iostream>
using namespace std;
double input (string ohyeah){
double total;
cout<<"Input Nilai "<<ohyeah<<" : ";cin>>total;
return total;}
void grade (double total){
if(total>80)
{cout<<total<<endl;cout<<"A"<<endl;}
else if(total>60)
{cout<<total<<endl;cout<<"B"<<endl;}
else if(total>40)
{cout<<total<<endl;cout<<"C"<<endl;}
else if(total>20)
{cout<<total<<endl;cout<<"D"<<endl;}
else
{cout<<total<<endl;cout<<"E"<<endl;}}
struct yo{
float u,ua,tu,ab;}y;
main()
{double uts,uas,tugas,absen;
double total;
uts=input ("UTS");
uas=input ("UAS");
tugas=input ("TUGAS");
absen=input ("ABSEN");
y.u=20*uts/100;
y.ua=30*uas/100;
y.tu=35*tugas/100;
y.ab=15*absen/100;
total=y.u+y.ua+y.tu+y.ab;
cout<<y.u<<endl;
cout<<y.ua<<endl;
cout<<y.tu<<endl;
cout<<y.ab<<endl;
grade(total);
}
| true |
526bbb84bb7a294a5dcd812674e14825043739e3 | C++ | StevenD33/Plante_Connecte | /Capteurs/capteurs.ino | UTF-8 | 1,181 | 2.53125 | 3 | [] | no_license | #include "SparkFunBME280.h"
// La librairie accepte I2C ou SPI, on inclue donc les deux
#include "Wire.h"
#include "SPI.h"
#include <math.h>
// const int sensor=A0;
BME280 capteur;
void setup() {
Serial.begin(9600);
while (!Serial) {
// Attente de l'ouverture du port série pour Arduino MKR WiFi 1010
}
//configuration du capteur
capteur.settings.commInterface = I2C_MODE;
capteur.settings.I2CAddress = 0x76;
capteur.settings.runMode = 3;
capteur.settings.tStandby = 4;
capteur.settings.filter = 0;
capteur.settings.tempOverSample = 1 ;
capteur.settings.pressOverSample = 1;
capteur.settings.humidOverSample = 1;
delay(10); // attente de la mise en route du capteur. 10 ms
// chargement de la configuration du capteur
capteur.begin();
}
void loop() {
// int sensorValue=analogRead(sensor);
Serial.print(capteur.readTempC(), 2);
Serial.print(" ");
Serial.print(capteur.readFloatPressure() / 100.0F, 2);
Serial.print(" ");
Serial.print(capteur.readFloatHumidity(), 2);
// Serial.print(" ");
// Serial.println(sensorValue);
Serial.print("return");
delay(1000);
}
| true |
e6afb0a22b5446c0cc6374b3ef8d7cb9d8c2ff31 | C++ | DaniBarac/Connect-four | /AI.cpp | UTF-8 | 2,411 | 3 | 3 | [] | no_license | #include "Board.h"
#include "AI.h"
//#include "hash_map.h"
#include <unordered_map>
#include <iostream>
using namespace ai;
int min(int a, int b) {
return a < b ? a : b;
}
int max(int a, int b) {
return a > b ? a : b;
}
// Player 1 minimizes, player 2 maximizes
int minimax(Board board, std::unordered_map<Board, int, BoardHasher>& seen_boards, int depth, int alpha = -1000000, int beta = 1000000) {
if (board.isGameOver())
return -((float)board.turn - 1.5f) * 100000000;
else if (board.isFull())
return 0;
else if (depth == 0)
return 0;
if (board.turn == 1)
{
int bestVal = 1000000;
Board daughter;
for (int i = 0; i < 8; i++) {
if (!board.isFullCol(i)) {
daughter = board;
daughter.make_move(i);
int val;
auto it = seen_boards.find(daughter);
if (it != seen_boards.end())
{
val = it->second;
}
else
{
val = minimax(daughter, seen_boards, depth - 1, alpha, beta);
seen_boards.insert({ daughter, val });
}
bestVal = min(bestVal, val);
beta = min(bestVal, beta);
if (beta <= alpha)
break;
}
}
return bestVal;
}
else
{
int bestVal = -1000000;
Board daughter;
for (int i = 0; i < 8; i++) {
if (!board.isFullCol(i)) {
daughter = board;
daughter.make_move(i);
int val;
auto it = seen_boards.find(daughter);
if (it == seen_boards.end()) {
val = minimax(daughter, seen_boards, depth - 1, alpha, beta);
seen_boards.insert({ daughter, val });
}
else
{
val = it->second;
}
bestVal = max(bestVal, val);
alpha = max(bestVal, alpha);
if (beta <= alpha)
break;
}
}
return bestVal;
}
}
int ai::findBestMove(Board board, int depth) {
int bestVal = -((float)board.turn - 1.5f) * 1000000;
int bestMove = 0;
Board daughter;
std::unordered_map<Board, int, BoardHasher> seen_boards;
std::cout << std::endl << "Progress: " << '\r';
for (int i = 0; i < 8; i++) {
if (!board.isFullCol(i)) {
daughter = board;
daughter.make_move(i);
int val = minimax(daughter, seen_boards, depth);
std::cout << "Progress: ";
for (int j = 0; j <= i; j++)
std::cout << '\u2580';
std::cout << '\r';
if (board.turn == 1)
{
if (val <= bestVal)
{
bestVal = val;
bestMove = i;
}
}
else
{
if (val >= bestVal)
{
bestVal = val;
bestMove = i;
}
}
}
}
return bestMove;
}
| true |
16905dc772f6149c13f5dc07db2a3e03c1199340 | C++ | pkunjam/Data-Structures-and-Algorithms | /Sorting/Three way partitioning.cpp | UTF-8 | 2,108 | 3.390625 | 3 | [
"MIT"
] | permissive | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector<int> threeWayPartition(vector<int> A,
int lowVal, int highVal);
int main() {
int t;
cin>>t;
while(t--)
{
int N;
cin>>N;
vector<int> A(N);
int hash[1000001];
memset(hash,0,sizeof hash);
for(int i=0;i<N;i++){
cin>>A[i];
hash[A[i]]++;
}
int n,m;
cin>>n>>m;
// vector to store the answer
// to verify the correct output
vector<int> B(A.size());
for(int i=0;i<A.size();i++)
{
B[i]=A[i];
}
int k1=0,k2=0,k3=0;
int kk1=0;int kk2=0;int kk3=0;
for(int i=0;i<B.size();i++)
{
if(B[i]>m)
{
k3++;
}
else if(B[i]<=m and B[i]>=n)
{
k2++;
}
else if(B[i]<m)
k1++;
}
vector<int> Res = threeWayPartition(A,
n,m);
for(int i=0;i<k1;i++)
{
if(Res[i]<m)
kk1++;
}
for(int i=k1;i<k1+k2;i++)
{
if(Res[i]<=m and Res[i]>=n)
kk2++;
}
for(int i=k1+k2;i<k1+k2+k3;i++)
{
if(Res[i]>m)
kk3++;
}
bool ok = 0;
if(k1==kk1 and k2 ==kk2 and k3 == kk3)
ok = 1;
for(int i=0;i<Res.size();i++)
hash[Res[i]]--;
for(int i=0;i<Res.size();i++)
if(hash[Res[i]]!=0)
ok=0;
if(ok)
cout<<1<<endl;
else
cout<<0<<endl;
}
return 0;
}// } Driver Code Ends
/*The function should return the modified array
as specified in the problem statement */
vector<int> threeWayPartition(vector<int> A, int a, int b)
{
int l=0, h=A.size()-1, mid=0;
while(mid<=h)
{
if(A[mid]<a)
{
swap(A[mid],A[l]);
l++;
mid++;
}
else if(A[mid]>b)
{
swap(A[mid],A[h]);
h--;
}
else
{
mid++;
}
}
return A;
}
| true |
8c6cf4b82e21317df376157a3b6f4d1c54071a58 | C++ | dalalsunil1986/OnlineJudge-Solution | /UVa Online Judge/uva 10226.cpp | UTF-8 | 619 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<map>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
int tc;
//string s;
cin>>tc;
getchar();
getchar();
while(tc--)
{
map<string,int>dict;
string s;
int total = 0;
while(getline(cin,s))
{
if(s.compare("")==0)
break;
dict[s]++;
total++;
}
for(auto i:dict)
{
cout<<i.first<<" "<<fixed<<setprecision(4)<<((i.second)*100.00)/total<<endl;
}
if(tc)
puts("");
}
return 0;
}
| true |
9f51f742dd86b4c78676d92162f92eedce2ec31f | C++ | cwlseu/Algorithm | /cpp/AcceleratCPP/Chapter4/CStackWithMin.cpp | UTF-8 | 2,637 | 3.96875 | 4 | [] | no_license | /**
* 讨论:如果思路正确,编写上述代码不是一件很难的事情。但如果能注意一些细节无疑能在面试中加分。
比如我在上面的代码中做了如下的工作:
· 用模板类实现。如果别人的元素类型只是int类型,模板将能给面试官带来好印象;
· 两个版本的top函数。在很多类中,都需要提供const和非const版本的成员访问函数;
· min函数中assert。把代码写的尽量安全是每个软件公司对程序员的要求;
· 添加一些注释。注释既能提高代码的可读性,又能增加代码量,何乐而不为?
总之,在面试时如果时间允许,尽量把代码写的漂亮一些。说不定代码中的几个小亮点
就能让自己轻松拿到心仪的Offer。
*/
#include <deque>
#include <assert.h>
#include <iostream>
using namespace std;
template <typename T> class CStackWithMin
{
public:
CStackWithMin(void) {}
virtual ~CStackWithMin(void) {}
T& top(void);
const T& top(void) const;
void push(const T& value);
void pop(void);
const T& min(void) const;
private:
deque<T> m_data; // the elements of stack
deque<size_t> m_minIndex; // the indices of minimum elements
};
// get the last element of mutable stack
template <typename T> T& CStackWithMin<T>::top()
{
return m_data.back();
}
// get the last element of non-mutable stack
template <typename T> const T& CStackWithMin<T>::top() const
{
return m_data.back();
}
// insert an elment at the end of stack
template <typename T> void CStackWithMin<T>::push(const T& value)
{
// append the data into the end of m_data
m_data.push_back(value);
// set the index of minimum elment in m_data at the end of m_minIndex
if(m_minIndex.size() == 0)
m_minIndex.push_back(0);
else
{
if(value < m_data[m_minIndex.back()])
m_minIndex.push_back(m_data.size() - 1);
else
m_minIndex.push_back(m_minIndex.back());
}
}
// erease the element at the end of stack
template <typename T> void CStackWithMin<T>::pop()
{
// pop m_data
m_data.pop_back();
// pop m_minIndex
m_minIndex.pop_back();
}
// get the minimum element of stack
template <typename T> const T& CStackWithMin<T>::min() const
{
assert(m_data.size() > 0);
assert(m_minIndex.size() > 0);
return m_data[m_minIndex.back()];
}
int main()
{
CStackWithMin<int>*s=new CStackWithMin<int>();
s->push(12);
s->push(13);
s->push(23);
std::cout<<s->min()<<std::endl;
return 1;
}
| true |
aec518427be7acad4c994f1099af0c5a84bceda1 | C++ | shahed-shd/Online-Judge-Solutions | /UVa-Online-Judge/121 - Pipe Fitters.cpp | UTF-8 | 541 | 3.171875 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const double K = 2/sqrt(3.0);
int calc_skew(double a, double b)
{
int col = int(b);
int row = 1 + K*(a-1);
return row * col - ((b - int(b) < 0.5)? row/2 : 0);
}
int main()
{
double a, b;
while(scanf("%lf %lf", &a, &b) != EOF) {
int grid = int(a) * int(b);
int skew = max(calc_skew(a, b), calc_skew(b, a));
if(grid >= skew) printf("%d grid\n", grid);
else printf("%d skew\n", skew);
}
return 0;
}
| true |
dc4b5335c2a8e5be2f5b7acfb30c286b418158fb | C++ | zehuichen123/DataStructure_homework | /homework9.cpp | UTF-8 | 5,670 | 4.09375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Node{
public:
Node():left(NULL),right(NULL){} //初始化让左右两个节点为NULL
~Node(){}
Node* left; //指向左子节点
Node* right; //指向右子节点
int value; //保存该节点的值
};
class bTree{ //抽象整个二叉排序树
public:
bTree(){}
~bTree(){}
void Create(); //构建二叉排序树
Node* getHead(){return Head;} //获得二叉排序树的头节点
void setHead(Node* node){Head=node;} //设置二叉排序树的头节点
void Insert(int number); //向树中插入新的元素
bool Find(int number); //在二叉排序树中寻找是否有number元素
void MidTraverse(Node* ptr); //中序遍历二叉排序树
void Display(); //打印二叉排序树
private:
Node* Head; //保存二叉排序树的头节点
};
void bTree::Create() {
int num=1;
cout<<"Please input key to create Bsort_Tree:"<<endl;
do{
cin>>num;
if(num==0){ //遇到输入为0停止输入
break;
}
else{
Insert(num); //将读入的数插入树中
}
}while(1);
Display(); //打印二叉排序树
}
void bTree::Display() {
cout<<"Bsort_Tree is: "<<endl;
auto head=getHead();
MidTraverse(head); //调用中序遍历打印二叉排序树
cout<<endl;
}
void bTree::MidTraverse(Node *ptr) {
if(ptr){
MidTraverse(ptr->left);
cout<<ptr->value<<"->";
MidTraverse(ptr->right);
}
}
void bTree::Insert(int number){
auto node=new Node;
node->value=number;
auto ptr=getHead();
if(ptr){ //如果二叉排序树当前不为空则向下查找可插入的位置
while(1){
if(number<ptr->value){ //如果插入的数比当前节点小就进入左子树
if(ptr->left){
ptr=ptr->left;
}
else{ //如果没有左子树就直接插入其左子树位置
ptr->left=node;
break;
}
}
else if(number>ptr->value){ //如果插入的数比当前节点大就进入右子树
if(ptr->right){
ptr=ptr->right;
}
else{ //如果没有右子树就直接插入其右子树位置
ptr->right=node;
break;
}
}
else{ //如果插入的数已经存在树中则返回
cout<<"The input key<"<<number<<"> is have in!"<<endl;
return;
}
}
}
else{
setHead(node);
}
}
bool bTree::Find(int number){
auto ptr=getHead();
while(ptr){ //寻找到ptr为NULL时返回未找到false
if(ptr->value>number){
ptr=ptr->left;
}
else if(ptr->value<number){
ptr=ptr->right;
}
else{
return true; //找到则直接返回true
}
}
return false;
}
class System{ //将整个程序操作抽象为系统
public:
System();
~System(){}
void Create(); //构建二叉排序树
void Insert(); //插入操作
void Find(); //查找操作
bTree bSortTree; //声明二叉排序树结构
};
System::System() {
cout<<"** 二叉排序树 **"<<endl;
cout<<"=================================================="<<endl;
cout<<"** 1.---建立二叉排序树 **"<<endl;
cout<<"** 2.---插入元素 **"<<endl;
cout<<"** 3.---查询元素 **"<<endl;
cout<<"** 4.---退出程序 **"<<endl;
cout<<"=================================================="<<endl;
}
void System::Create() {
bSortTree.Create();
}
void System::Insert() {
int number;
cout<<"Please input key which inserted: ";
cin>>number;
bSortTree.Insert(number);
bSortTree.Display();
}
void System::Find() {
int number;
cout<<"Please input key which searched: ";
cin>>number;
if(bSortTree.Find(number)){
cout<<"search success!"<<endl;
}
else{
cout<<number<<" not existed!"<<endl;
}
}
int main(void){
System myTree;
int operand;
while(1){
cout<<"Please select: ";
cin>>operand;
switch(operand){
case 1:{
myTree.Create();
break;
}
case 2:{
myTree.Insert();
break;
}
case 3:{
myTree.Find();
break;
}
case 4:{
cout<<"press any key to continue"<<endl;
getchar();
getchar();
return 0;
}
default:{
cout<<"it seems your operand is not between 1-4"
"Please reinput your operand"<<endl;
}
}
}
} | true |
a2abb508892da4206745351d3beffa01c43626de | C++ | AbelDeLuna/CSUSM | /CS311/HW7Part2/llist.h | UTF-8 | 2,100 | 4 | 4 | [] | no_license | #ifndef LLIST_H
#define LLIST_H
#include <vector>
typedef char el_t;
using namespace std;
// The single Linked List class
// Data members are marked "protected" instead of "private" for use in later classes.
class llist
{
protected:
// The basic building block of a Linked list is a node.
// A node has some piece of data, and a pointer to the next node in the list.
// The pointer may point to NULL if this node is the last in the list.
struct Node
{
el_t Elem;
Node *Next;
};
int count; // The counter variable is not used to determine emptiness
// But rather to help when looping around the list.
Node *front; // front is a pointer to a Node which is at the "front" of the list.
Node *rear; // front is a pointer to a Node which is at the "rear" of the list.
// a helper function used by addRear or addFront to reduce code duplication.
void createFirst(el_t NewNum); // 'protected' because it is somewhat dangerous.
public:
// Public constructor/destructor.
llist(); // Does not create any nodes, but init's front/rear to NULL
~llist(); // Iteratively calls deleteFront() until the list is empty.
// These empty classes are used for Exception handling.
class Underflow {}; // the list is being accessed but is empty
class OutOfRange {}; // the list is being accessed but the index provided is too low/high.
// Member functions //
// Useful helper functions for a linked list
bool isEmpty() const; // Just checks to see if the list is empty or not
void displayAll(); // Displays [ empty ] or list contents in brackets
// Adds an element to the front or back of a list, creating nodes.
void addRear(el_t NewNum);
void addFront(el_t NewNum);
// Removes the element (and deletes the node) from the list front or back.
// (returns it in pass-by-reference.)
void deleteRear(el_t& OldNum);
void deleteFront(el_t& OldNum);
// Adds/removes the element at a specified 1-based index and re-links the list.
void addBeforeIth(int I, el_t OldNum);
void deleteIth(int I, el_t& OldNum);
};
#endif // LLIST_H
| true |
574427ae1a8b0db9feae87ae8e8634aacf113f7e | C++ | 1432junaid/quarentine | /online-classes/virtual_demo.cpp | UTF-8 | 532 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class base{
public:
virtual void printer(){ //printer1
cout<<"Printer of base "<<endl;
}
void display(){
cout<<"Display of base"<<endl;
}
};
class derived:public base{
public:
void printer(){
cout<<"Printer of derived "<<endl;
}
virtual void display(){ //we can not do this static void (both)
cout<<"display of derived"<<endl;
}
};
int main(){
// derived* d = new base(); //error
base* d = new derived(); //experiment
d->printer();
d->display();
return 0;
}
| true |
39e4e185b3b7e89d7a101bf291e7ee4c9a6ef73d | C++ | liruqi/topcoder | /POJ/2559/12349638_AC_141MS_1860K.cc | UTF-8 | 1,226 | 2.65625 | 3 | [] | no_license | //Problem: 2559 User: himdd
//Memory: 1344K Time: 141MS
//Language: C++ Result: Accepted
//Source Code
#include<iostream>
#include<stdio.h>
using namespace std;
const int A=100005;
struct{
long long h;
int id;
}st[A];
long long h[A];
int main()
{
//freopen("1.txt","r",stdin);
int n;
while(scanf("%d",&n),n)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&h[i]);
}
h[n+1]=0;
long long ans=0,tmp;
int top=1;
st[top].h=h[1];
st[top].id=1;
for(int i=2;i<=n+1;i++)
{
if(st[top].h>h[i])
{
while(top!=0&&st[top].h>h[i])
{
tmp=st[top].h*(i-1-st[top].id+1);
//st[top].id~i-1的h都是大于等于st[top].h
//栈顶元素是序列的最小元素
if(ans<tmp)
{
ans=tmp;
}
top--;
}
top++;
st[top].h=h[i];
//注意这里st[top].id还是原来的id,因为st[top].id~i-1的h都是>h[i]
//下一次以h[i]为高计算时,st[top].id~i-1也是要加上的。
}
else//满足栈单调不减入栈
{
top++;
st[top].h=h[i];
st[top].id=i;//注意这里的下标还是本来的i
}
}
printf("%lld\n",ans);
}
} | true |
5b7cf3dc780fc6581a0cfabe6e864529a948e942 | C++ | programowanie-obiektowe-cpp-classes/kolokwium-1a-paulass97 | /include/zad3.hpp | UTF-8 | 448 | 2.59375 | 3 | [] | no_license | #include "zad1.hpp"
#include <cstdint>
#include <functional>
• przyjmuje jako drugi argument stałą referencję do obiektu typu, którym jest sparametryzowany (obiekt ten reprezentuje sos)
• zwraca obiekt typu std::size_t, będący wynikiem wywołania metody polej drugiego argumentu na pierwszym argumencie (załóż, że typ będący parametrem szablonu posiada taką metodę)
template <typename T>
void polejSosem(Tagliatelleconst T&){} | true |
882145fa3379be2e7a1c9725af5d64c49c0b55e2 | C++ | iujaypuppy/LeetCode | /zyy/462.cpp | UTF-8 | 322 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
int mid(nums[nums.size() / 2]);
int moves(0);
for (vector<int>::iterator i(nums.begin()); i != nums.end(); i++) {
moves += abs(*i - mid);
}
return moves;
}
};
| true |
d4be922a2b2e9ca7aa6994b7e51c2ff7e7f1ca7e | C++ | rid-32/avr-timer1 | /lib/Led/Led.cpp | UTF-8 | 280 | 2.8125 | 3 | [] | no_license | #include "Led.hpp"
using namespace led;
Led::Led(volatile uint8_t *port, uint8_t pin) {
this->port = port;
this->pin = pin;
/* set DDRx register */
*(port - 1) |= 1 << pin;
/* set PORTx register */
*port &= ~(1 << pin);
}
void Led::toggle() { *port ^= 1 << pin; }
| true |
dd0dbec511cd8f08a6993a69dccee87dd4302afe | C++ | ghali/gcb | /GLOW/07/04-float-to-binary/04-float-to-binary.cpp | UTF-8 | 1,935 | 3.03125 | 3 | [] | no_license | /* The following code example is described in the book "Introduction
* to Geometric Computing" by Sherif Ghali, Springer-Verlag, 2008.
*
* Copyright (C) 2008 Sherif Ghali. This code may be freely copied,
* modified, or republished electronically or in print provided that
* this copyright notice appears in all copies. This software is
* provided "as is" without express or implied warranty; not even for
* merchantability or fitness for a particular purpose.
*/
#include <iostream>
using namespace std;
void binary_print(int n, char c)
{
cout << ((c & 0x80) ? 1 : 0);
if(n>=2) cout << " ";
cout << ((c & 0x40) ? 1 : 0)
<< ((c & 0x20) ? 1 : 0)
<< ((c & 0x10) ? 1 : 0)
<< ((c & 0x08) ? 1 : 0)
<< ((c & 0x04) ? 1 : 0)
<< ((c & 0x02) ? 1 : 0)
<< ((c & 0x01) ? 1 : 0);
}
void print(float x)
{
char *ix = reinterpret_cast<char*>(&x);
int n = 4;
while(n--)
binary_print(n, ix[n]);
cout << endl;
}
int main()
{
float x;
x = 4.0f ; print(x);
x = 2.0f ; print(x);
x = 1.0f ; print(x);
x = 0.5f ; print(x);
x = 0.25f; print(x);
cout << endl;
x = - 0.25f; print(x);
x = - 0.5f ; print(x);
x = - 1.0f ; print(x);
x = - 2.0f ; print(x);
x = - 4.0f ; print(x);
cout << endl;
x = 1.0625000f; print(x); // 1 + 1/16 (0.0625000)
x = 1.0312500f; print(x); // 1 + 1/32 (0.0312500)
x = 1.0156250f; print(x); // 1 + 1/64 (0.0156250)
x = 1.0078125f; print(x); // 1 + 1/128 (0.0078125)
x = 1.00000047683715820312f; print(x); // 1 + 1/2^21 (0.00000047683715820312)
x = 1.00000023841857910156f; print(x); // 1 + 1/2^22 (0.00000023841857910156)
x = 1.00000011920928955078f; print(x); // 1 + 1/2^23 (0.00000011920928955078)
x = 1.00000005960464477539f; print(x); // 1 + 1/2^24 (0.00000005960464477539)
}
| true |
770d73cef50717da05ea11d8fe0dc2b5e3409751 | C++ | rakhils/SpecialTopic | /Engine/Code/Engine/Time/Clock.hpp | UTF-8 | 1,445 | 2.671875 | 3 | [] | no_license | #pragma once
#include <stdint.h>
#include <vector>
#include <vcruntime_string.h>
#include "Engine/Core/Time.hpp"
/*\class : Clock
* \group : <GroupName>
* \brief :
* \TODO: :
* \note :
* \author : Rakhil Soman
* \version: 1.0
* \date : 3/6/2018 4:15:45 PM
* \contact: srsrakhil@gmail.com
*/
struct TimeUnit
{
uint64_t m_hpc;
double m_hpcSeconds;
double m_seconds;
uint64_t m_milliSeconds;
TimeUnit()
{
memset(this,0,sizeof(TimeUnit)); // setting to 0
}
void TimeReset()
{
memset(this,0,sizeof(TimeUnit));
}
};
class Clock
{
public:
//Member_Variables
uint64_t m_startHPC;
uint64_t m_lastFrameHPC;
uint64_t m_frameCount;
double m_timeScale = 1;
bool m_paused;
TimeUnit frame;
TimeUnit total;
Clock *m_parent = nullptr;
std::vector<Clock*> m_children;
//Static_Member_Variables
static Clock *g_theMasterClock;
//Methods
Clock( Clock *parent = nullptr );
~Clock();
void ResetClock();
void BeginFrame();
void AddChild(Clock *child);
void StepClock(uint64_t hpc);
void SetPausedState(bool paused);
void SetScale(float scale);
void ClockSystemStartUp();
double GetMasterDeltaTime();
//Static_Methods
static Clock* GetMasterClock() { return g_theMasterClock; }
protected:
//Member_Variables
//Static_Member_Variables
//Methods
//Static_Methods
private:
//Member_Variables
//Static_Member_Variables
//Methods
//Static_Methods
};
| true |
59bd3e11822480079439645c1f219f01c3a8b709 | C++ | quadhier/KidFTP | /ftpsession.h | UTF-8 | 371 | 2.546875 | 3 | [] | no_license | #ifndef FTPSESSION_H
#define FTPSESSION_H
#include "ftpuser.h"
#include <string>
class FTPSession
{
public:
FTPSession() { }
FTPSession(const FTPUser *user, std::string cwd, int cmd_sock, int data_sock) : user(user), cwd(cwd), cmd_sock(cmd_sock), data_sock(data_sock) { };
const FTPUser *user;
std::string cwd;
int cmd_sock;
int data_sock;
private:
};
#endif
| true |
237ebb6839013a93275dfe008946b33d847a555d | C++ | sgc109/acm-icpc-teamnote | /tree/lowest-common-ancestor.cpp | UTF-8 | 1,509 | 3.25 | 3 | [] | no_license | /*
주의 사항
1. 노드 번호는 0번 부터 시작
*/
class LCA {
vector <vector<int>> G, par;
vector<int> dep;
int root, size, depLog;
public:
LCA(int size, int root) {
this->root = root;
this->size = size;
depLog = 1;
int sz = 1;
while (sz < size - 1) depLog++, sz *= 2;
par = vector < vector < int > > (size, vector<int>(depLog + 1, -1));
G = vector < vector < int > > (size);
dep = vector<int>(size, 0);
}
void buildLCA() {
dfs(root, -1);
}
void addEdge(int from, int to) {
G[from].push_back(to);
G[to].push_back(from);
}
void dfs(int cur, int dad) {
for (int i = 1; (1 << i) <= dep[cur]; i++) par[cur][i] = par[par[cur][i - 1]][i - 1];
for (int next : G[cur]) {
if (next == dad) continue;
par[next][0] = cur;
dep[next] = dep[cur] + 1;
dfs(next, cur);
}
}
int getLCA(int a, int b) {
if (dep[a] < dep[b]) swap(a, b);
for (int i = 0; dep[a] != dep[b]; i++) {
int diff = dep[a] - dep[b];
if (diff & (1 << i)) a = par[a][i];
}
for (int i = depLog; i >= 0; i--) {
if (par[a][i] == -1) continue;
if (par[a][i] != par[b][i]) a = par[a][i], b = par[b][i];
}
if (a == b) return a;
return par[a][0];
}
};
| true |
7e45cd1bb16a1bbe6cd9b7ed6cde2d8c54410a5a | C++ | polBachelin/BomberVerse | /src/gameEngine/objects/Moveable.cpp | UTF-8 | 1,939 | 2.875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2021
** Indie_Studio
** File description:
** Moveable
*/
#include "Moveable.hpp"
using namespace gameEngine::objects;
Moveable::Moveable(const std::string &id) : AGameObject(id)
{
}
Moveable::~Moveable()
{}
Vector3T<float> Moveable::getSpeed() const noexcept
{
return _speed;
}
void Moveable::setSpeed(const Vector3T<float> &speed) noexcept
{
_speed = speed;
}
void Moveable::move(const std::size_t &tick) noexcept
{
gameEngine::systems::Move::move(_transform, _speed, tick);
}
void Moveable::moveDirection(std::size_t tick,
const gameEngine::systems::Move::direction_e direction)
{
float velocity = 0;
if (direction == gameEngine::systems::Move::UP || direction == gameEngine::systems::Move::DOWN)
velocity = _speed._z;
else if (direction == gameEngine::systems::Move::RIGHT || direction == gameEngine::systems::Move::LEFT)
velocity = _speed._x;
else
velocity = _speed._y;
try
{
gameEngine::systems::Move::moveDirection(_transform, velocity, tick, direction);
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
}
void Moveable::moveRight(std::size_t tick) noexcept
{
gameEngine::systems::Move::moveRight(_transform, _speed._x, tick);
}
void Moveable::moveLeft(std::size_t tick) noexcept
{
gameEngine::systems::Move::moveLeft(_transform, _speed._x, tick);
}
void Moveable::moveForward(std::size_t tick) noexcept
{
gameEngine::systems::Move::moveForward(_transform, _speed._y, tick);
}
void Moveable::moveBackward(std::size_t tick) noexcept
{
gameEngine::systems::Move::moveBackward(_transform, _speed._y, tick);
}
void Moveable::moveUp(std::size_t tick) noexcept
{
gameEngine::systems::Move::moveUp(_transform, _speed._z, tick);
}
void Moveable::moveDown(std::size_t tick) noexcept
{
gameEngine::systems::Move::moveDown(_transform, _speed._z, tick);
}
| true |
d020f881f7129d965c2af225913910084d6ec251 | C++ | SanyaAttri/LeetCode | /01283. Find the Smallest Divisor Given a Threshold.cpp | UTF-8 | 2,018 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <numeric>
using namespace std;
/**
*
*
1283. Find the Smallest Divisor Given a Threshold
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division.
Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
**/
// 59 / 59 test cases passed.
// Status: Accepted
// Runtime: 44 ms
// Memory Usage: 11.5 MB
class Solution {
public:
bool valid(int val, vector<int>& nums, int threshold){
int ret = 0;
for(int num : nums){
ret = ret + (num + val - 1) / val;
}
return ret <= threshold;
}
int smallestDivisor(vector<int>& nums, int threshold) {
int left = 1;
int right = 1e6;
int mid;
while(left < right){
mid = left + (right - left) / 2;
if(valid(mid, nums, threshold)){
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
int main(){
Solution solve;
vector<int> nums = {19};
cout<<solve.smallestDivisor(nums, 5)<<endl;
} | true |
8bbce2be389bd0f6bfa54b5b161d95ce9747fbdf | C++ | Tasselmi/algorithms_in_cpp | /chapter09/ArrayQueue.h | UTF-8 | 2,737 | 3.59375 | 4 | [] | no_license | //
// Created by Tasselmi liang on 2020/6/24.
//
#ifndef ALGORITHMS_IN_CPP_ARRAYQUEUE_H
#define ALGORITHMS_IN_CPP_ARRAYQUEUE_H
#include <sstream>
#include "../exception/myExceptions.h"
#include "Queue.h"
using namespace std;
template<typename T>
class ArrayQueue : public Queue<T>
{
private:
int theFront;
int theBack;
int arrayLength;
T *queue;
public:
ArrayQueue(int initialCapacity = 10);
~ArrayQueue();
bool empty() const override;
int size() const override;
T &front() override;
T &back() override;
void pop() override;
void push(const T &theElement) override;
};
template<typename T>
ArrayQueue<T>::ArrayQueue(int initialCapacity) {
if (initialCapacity < 1) {
ostringstream s;
s << "initial capacity = " << initialCapacity << " must be > 0 ";
throw IllegalParameterValue(s.str());
}
arrayLength = initialCapacity;
queue = new T[arrayLength]; //new是在堆上分配内存,一定要手动释放
theFront = 0;
theBack = 0;
}
template<typename T>
ArrayQueue<T>::~ArrayQueue() {
delete [] queue;
}
template<typename T>
bool ArrayQueue<T>::empty() const {
return theFront == theBack;
}
template<typename T>
int ArrayQueue<T>::size() const {
return (theBack - theFront + arrayLength) % arrayLength;
}
template<typename T>
T &ArrayQueue<T>::front() {
if (theFront == theBack)
throw QueueEmpty();
return queue[(theFront + 1) % arrayLength];
}
template<typename T>
T &ArrayQueue<T>::back() {
if (theFront == theBack)
throw QueueEmpty();
return queue[theBack];
}
template<typename T>
void ArrayQueue<T>::pop() {
if (theFront == theBack)
throw QueueEmpty();
//theFront本身是一个空占位,因此移动到下一位即可
//首个数据项实际存储的就是在下一位,因此直接把移动后的位置上的数据进行析构
theFront = (theFront + 1) % arrayLength;
queue[theFront].~T();
}
template<typename T>
void ArrayQueue<T>::push(const T &theElement) {
if ((theBack + 1) % arrayLength == theFront) {
T* newQueue = new T[arrayLength * 2];
int start = (theFront + 1) % arrayLength;
if (start < 2) {
copy(queue + start, queue + start + arrayLength - 1, newQueue);
} else {
copy(queue + start, queue + arrayLength, newQueue);
copy(queue, queue + theBack + 1, newQueue + arrayLength - start);
}
theFront = arrayLength * 2 - 1;
theBack = arrayLength - 2;
arrayLength *= 2;
delete [] queue;
queue = newQueue;
}
theBack = (theBack + 1) % arrayLength;
queue[theBack] = theElement;
}
#endif //ALGORITHMS_IN_CPP_ARRAYQUEUE_H
| true |
296cb65a28d076c8ec5766ffaa9b419adc79f3ae | C++ | raulsg3/TrueInferno | /galeon/Src/Graphics/Scene.h | UTF-8 | 7,997 | 3.015625 | 3 | [] | no_license | //---------------------------------------------------------------------------
// Scene.h
//---------------------------------------------------------------------------
/**
@file Scene.h
Contiene la declaraci�n de la clase contenedora de los elementos
de una escena.
@see Graphics::CScene
@author David Llansó
@date Julio, 2010
*/
#ifndef __Graphics_Scene_H
#define __Graphics_Scene_H
#include <string>
#include <list>
namespace Ogre
{
class Vector3;
class Root;
class Viewport;
class SceneManager;
class StaticGeometry;
class Light;
class BillboardSet;
}
namespace Graphics
{
class CServer;
class CCamera;
class CEntity;
class CStaticEntity;
}
namespace Graphics
{
/**
Clase que controla todos los elementos de una escena. Puede ser de
un estado como el men� o un nivel del juego. Su equivalente en la
l�gica del juego en el caso de ser un nivel ser�a el mapa. la escena
es un contenedor de todas las entidades gr�ficas que pueden ser
reenderizadas por un viewport asociado a esa escena. Se asume que una
escena solo va a ser reenderizada desde un punto de vista por lo que
por defecto se crea una �nica c�mara y cuando se activa la escena se
crea un �nico viewport mostrado en la totalidad de la ventana de
reenderizado. En funci�n del tipo de juego puede quererse hacer m�s de
un reenderizado de la misma escena a la vez y mostrarlo en diferentes
viewports en la ventana. Por ejemplo en un juego de coches para mostrar
la imagen de los retrovisores del coche.
<p>
Tr�s crear la escena se deben a�adir las diferentes entidades y
entidades est�ticas. Al a�adir las entidades a la escena se fuerza su
carga. Las entidades est�ticas se almacenan en una estructura. Una vez
a�adidas todas las entidades se debe crear la geometr�a est�tica ya
que hasta que no se invoque a buildStaticGeometry() las entidades no
pasar�n a formar parte de la geometr�a est�tica. Al activar la escena
se fuerza la creaci�n de la geometr�a est�tica si no se hab�a creado.
<p>
@remarks Una vez activada la escena las modificaciones realizadas en
los valores de las entidades est�ticas no tendr�n efecto.
<p>
@remarks Solo el servidor gr�fico (Graphics::CServer) puede crear o
liberar escenas.
@ingroup graphicsGroup
@author David Llansó
@date Julio, 2010
*/
class CScene
{
public:
/**
Devuelve la c�mara de la escena.
@return Puntero a la c�mara de la escena.
*/
CCamera *getCamera() {return _camera;}
/**
Devuelve el nombre de la escena.
@return Nombre de la escena.
*/
const std::string& getName() {return _name;}
/**
A�ade una entidad gr�fica a la escena.
<p>
@remarks La escena NO se hace responsable de destruir la
entidad.
@param entity Entidad gr�fica que se quiere a�adir a la escena.
@return Cierto si la entidad se a�adi� y carg� correctamente.
*/
bool addEntity(CEntity* entity);
/**
A�ade una entidad gr�fica est�tica a la escena. No sirve
addEntity porque estas entidades deben ser almacenadas en otra
lista para cuando se cree la geometr�a est�tica de la escena poder
recuperarlas y cargarlas.
<p>
@remarks La escena NO se hace responsable de destruir la
entidad.
@param entity Entidad gr�fica que se quiere a�adir a la escena.
@return Cierto si la entidad se a�adi� y carg� correctamente.
*/
bool addStaticEntity(CStaticEntity* entity);
/**
Elimina una entidad gr�fica de la escena.
<p>
@remarks Este m�todo NO destrulle la entidad, �sta solo deja de
ser parte de la escena.
@param entity Entidad gr�fica que se quiere eliminar de la escena.
*/
void removeEntity(CEntity* entity);
/**
Elimina una entidad gr�fica est�tica de la escena.
<p>
@remarks Este m�todo NO destrulle la entidad, �sta solo deja de
ser parte de la escena.
@param entity Entidad gr�fica est�tica que se quiere eliminar de
la escena.
*/
void removeStaticEntity(CStaticEntity* entity);
/**
Crear billboards.
*/
Ogre::BillboardSet* createBillboardSet(CEntity* entity, const std::string& name, const Ogre::Vector3& position) const;
Ogre::BillboardSet* createBillboardSet(CEntity* entity, const std::string& name) const;
/**
Activar y desactivar la luz focal para edificios.
*/
void turnOnBuildingLight(Ogre::Vector3 buildingPosition);
void turnOffBuildingLight();
protected:
/**
Clase amiga. Solo el servidor gr�fico puede crear o liberar escenas,
activarlas o desactivarlas y actualizar su estado.
*/
friend class CServer;
/**
Constructor de la clase.
*/
CScene(const std::string& name);
/**
Destructor de la aplicaci�n.
*/
virtual ~CScene();
/**
Despierta la escena y crea un viewport que ocupa toda la
pantalla.
*/
void activate();
/**
Duerme la escena y destruye su viewport para que no se siga
reenderizando.
*/
void deactivate();
/**
Actualiza el estado de la escena cada ciclo. Llama a su vez a
todas las entidades.
@param secs N�mero de segundos transcurridos desde la �ltima
llamada.
*/
void tick(float secs);
/**
A�ade las entidades est�ticas a la geometr�a est�tica del nivel
y la construlle. Si la geometr�a est�tica ya ha sido construida
no se vuelve a construir.
<p>
@remarks Una vez construida la geometr�a est�tica no se pueden
modificar los valores de las entidades est�ticas.
*/
void buildStaticGeometry();
/**
Clase amiga. Solo las entidades y la c�mara pueden acceder al
gestor de la escena de Ogre.
*/
friend class CEntity;
friend class CCamera;
/**
Devuelve el gestor de la escena de Ogre
@return Puntero al gestor de la escena de Ogre.
*/
Ogre::SceneManager *getSceneMgr() { return _sceneMgr; }
/**
Clase amiga. Solo las entidades pueden acceder al gestor de la
escena de Ogre.
*/
friend class CStaticEntity;
/**
Devuelve la geometr�a est�tica de la escena de Ogre
@return Puntero a la geometr�a est�tica de la escena de Ogre.
*/
Ogre::StaticGeometry *getStaticGeometry() {return _staticGeometry;}
/**
Nombre de la escena.
*/
std::string _name;
/**
Punto de entrada al sistema Ogre.
*/
Ogre::Root *_root;
/**
Marco en la ventana de reenderizado donde se pinta lo captado por
una c�mara. Solo puede haber una c�mara asociada a un viewport,
sin embargo una ventana de reenderizado puede tener diferentes
viewports al mismo tiempo.
*/
Ogre::Viewport *_viewport;
/**
Controla todos los elementos Ogre de una escena. Su equivalente
en la l�gica del juego ser�a el mapa o nivel.
*/
Ogre::SceneManager *_sceneMgr;
/**
Luz direccional que se crea por defecto en la escena. Gr�ficamente
mejora la escena bastante respecto a tener solo luz ambiente ya que
se ven mejor los vol�menes de las entidades.
*/
Ogre::Light *_directionalLight;
/**
Luz focal que apunta desde la cámara al cursor.
*/
Ogre::Light *_spotlightLight;
/**
Luz focal que ilumina un edificio concreto durante el tutorial.
*/
Ogre::Light *_buildingHighlight;
float _spotlightAcumTime;
float _spotlightThresholdTime;
/**
Camara desde la que se ver� la escena. Puede haber c�maras m�s
sofisticadas y m�s tipos de c�maras desde el punto de vista l�gico,
ellas se encargar�n de mover esta instancia.
*/
CCamera *_camera;
/**
Tipos para la lista de entidades.
*/
typedef std::list<CStaticEntity*> TStaticEntityList;
/**
Tipos para la lista de entidades.
*/
typedef std::list<CEntity*> TEntityList;
/**
Lista de entidades est�ticas.
*/
TStaticEntityList _staticEntities;
/**
Lista de entidades din�micas.
*/
TEntityList _dynamicEntities;
/**
Geometr�a est�tica de la escena.
*/
Ogre::StaticGeometry *_staticGeometry;
}; // class CScene
} // namespace Graphics
#endif // __Graphics_Scene_H
| true |
618e0638645b743db095e2a69530669ac0084b0d | C++ | rscalt/SUSU_CPP_LAB | /labs_C1_S1/listings/control/practice/T10-0.cpp | UTF-8 | 14,639 | 3.046875 | 3 | [] | no_license | /* Валяльная фабрика производит валенки.
Данные об объемах сбыта продукции и о ценах продаж за прошлый год помесячно
хранятся в файле в виде таблицы.
При подведении итогов года необходимо выяснить динамику сбыта, то есть найти и упорядочить по убыванию информацию о прибылях, приносимых производством.
Использовать функцию для вычисления ежемесячной прибыли.
Для сортировки матрицы по столбцу «прибыль» использовать функцию сортировки матрицы методом пузырька. */
#include <fstream> //class ifstream
#include <iostream>
#include <iomanip>
#include <string> //class string
#include <sstream> //class stringstream
using namespace std;
const int total_lines = 12; //всего строк //месяцы
string month_enum[total_lines] = //месяцы
{
"Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"};
const int total_columns = 5; //столбцы
const int column_id = 1; //номер колонки: id строки *БД*
const int column_month = 2; //номер колонки: месяц
const int column_sales_volume = 3; //номер колонки: объем продаж, пар
const int column_price = 4; //номер колонки: цена продажи пары
const int column_costs = 5; //номер колонки: стоимость производства пары
int array_length = total_lines * total_columns; //всего элементов в csv-массиве
const int profit_array_columns = 2; //колонок в матрице прибылей по месяцам
const int profit_column_id = 1; //номер колонки: "id"
const int profit_column_profit = 2; //номер колонки: "прибыль"
//====================================================================================
void cout_matrix(string csv_array_as_matrix[total_lines][total_columns],
bool append_profit_column = false,
long profit_array[][profit_array_columns] = NULL,
int total_lines = total_lines, int total_columns = total_columns);
void cout_array(string *csv_array_as_line, int array_length = array_length);
void cout_profit(long profit_array[total_lines][profit_array_columns]);
long calc_profit(int &month_sales, int &month_price, int &month_costs);
void bubble_sort_desc(long profit_array[total_lines][profit_array_columns]);
void bubble_sort_desc(string array[total_lines][total_columns], int selected_column);
void swap_line(long *arr_1, long *arr_2, int total_columns);
void swap_line(string *arr_1, string *arr_2, int total_columns);
void swap_content_between_lines(long array[][profit_array_columns], int first_line_index, int second_line_index, int column_number);
void swap_content_between_lines(string array[total_lines][total_columns], int first_line_index, int second_line_index, int column_number);
void swap_values(long &a, long &b);
//====================================================================================
//getline(файл) -> getline(строка файла) -> ячейка таблицы
int main()
{
//файловый обменник сайта не принимает csv-файлы,
//но в дальнейшем на этот файл мы будем ссылаться как на csv
string filename = "db_sales_2020.doc"; //имя файла
ifstream data; //поток данных из файла
data.open(filename, ios::out); //файл только для чтения
string line; //строка таблицы
string csv_array_as_line[12 * 5]; // линейный массив
string csv_array_as_matrix[12][5]; // матричный массив = [строка][id, имя месяца, продажи, цена, себестоимость]
int read_cell_count = 0; //число считанных ячеек ~ позиция считывалеля
// data >> line при каждой итерации; getline(data, line) = 0 при EOF
while (getline(data, line))
{
stringstream line_stream(line); //строка в виде потока
string cell; //ячейка
while (getline(line_stream, cell, ';')) //строка в виде потока (до разделителя ';') >> ячейка
{
read_cell_count++; //для отладки
csv_array_as_line[read_cell_count - 1] = cell; //линейный csv-массив
}
}
//из линейного массива заполняем матричный
for (int line_index = 0; line_index < total_lines; line_index++)
for (int column_index = 0; column_index < total_columns; column_index++)
csv_array_as_matrix[line_index][column_index] = csv_array_as_line[line_index * total_columns + column_index];
//вывод линейного csv-массива //для отладки
//cout_array(csv_array_as_line);
cout_matrix(csv_array_as_matrix);
//заполняем матрицу прибылей
long profit_array[total_lines][profit_array_columns] = {}; // ...[2] : id, profit
for (int line_index = 0; line_index < total_lines; line_index++)
{
//присваиваем значения
string month_sales_str = csv_array_as_matrix[line_index][column_sales_volume - 1];
string month_price_str = csv_array_as_matrix[line_index][column_price - 1];
string month_costs_str = csv_array_as_matrix[line_index][column_costs - 1];
string id_str = csv_array_as_matrix[line_index][column_id - 1];
//для преобразования
int month_sales = 0;
int month_price = 0;
int month_costs = 0;
int id = 0;
//строку как поток символов передаем в int
stringstream(month_sales_str) >> month_sales;
stringstream(month_price_str) >> month_price;
stringstream(month_costs_str) >> month_costs;
stringstream(id_str) >> id;
long profit = calc_profit(month_sales, month_price, month_costs); //функция расчета приыбли
profit_array[line_index][profit_column_id - 1] = id; //через id удобнее, если строки не упорядочены
profit_array[line_index][profit_column_profit - 1] = profit;
}
cout << "\n\n";
//вывод матрицы месячной прибыли
cout_profit(profit_array);
//сортировка двумерного массива методом пузырька (по убыванию)
bubble_sort_desc(profit_array);
cout << "\n\n";
//результат сортировки
cout_profit(profit_array);
cout << "\n\n";
//матрица со столбцом прибылей
cout_matrix(csv_array_as_matrix, true, profit_array);
cout << "\n\n";
//отсортируем по объему продаж..
bubble_sort_desc(csv_array_as_matrix, 3);
cout << "\n\n";
//... и снова дополним столбцом прибылей
cout_matrix(csv_array_as_matrix, true, profit_array);
}
//вывод csv-матрицы
//для дополнения вывода столбцом прибылей: bool append_profit_column (default: false)
void cout_matrix(string csv_array_as_matrix[total_lines][total_columns],
bool append_profit_column, long profit_array[][profit_array_columns],
int total_lines, int total_columns)
{
for (int line_index = 0; line_index < total_lines; line_index++)
{
cout << "\n";
for (int column_index = 0; column_index < total_columns; column_index++)
{
cout << csv_array_as_matrix[line_index][column_index] << "\t";
if (append_profit_column == true && column_index == total_columns - 1) //если требуется отобразить прибыль и мы в последней колонке csv:
{
//конвертер string -> int
string str_csv_id = csv_array_as_matrix[line_index][column_id - 1]; //значение csv-id
int int_csv_id; //значение csv-id
stringstream(str_csv_id) >> int_csv_id;
//по сконвертированному значению можно найти соответствующее значение прибыли
for (int i = 0; i < total_lines; i++)
if ( int_csv_id == profit_array[i][profit_column_id - 1] ) //для т екущего csv-id ищем соответствующее по значение прибыли через profit_id
cout << profit_array[i][profit_column_profit - 1];
}
}
}
}
//вывод матрицы прибылей (перегрузка)
void cout_matrix(long profit_array[total_lines][profit_array_columns])
{
for (int line_index = 0; line_index < total_lines; line_index++)
{
cout << "\n";
for (int column_index = 0; column_index < profit_array_columns; column_index++)
cout << profit_array[line_index][column_index] << "\t";
}
}
//вывод линейного csv-массива
void cout_array(string *csv_array_as_line, int array_length)
{
for (int i = 0; i < array_length; i++)
cout << i << ": " << csv_array_as_line[i] << endl;
}
//вывод матрицы помесячной прибыли (месяц, прибыль)
void cout_profit(long profit_array[total_lines][profit_array_columns])
{
for (int line_index = 0; line_index < total_lines; line_index++)
{
int id;
string month;
long profit;
id = profit_array[line_index][profit_column_id - 1];
month = month_enum[id - 1];
profit = profit_array[line_index][profit_column_profit - 1];
cout << "id: "
<< setw(3) << id << ": "
<< "\t";
cout << month << "\t";
cout << setw(8) << profit << endl;
}
}
//расчет прибыли
long calc_profit(int &month_sales, int &month_price, int &month_costs)
{
long month_profit = 0;
month_profit = month_sales * (month_price - month_costs);
return month_profit;
}
//сортировка пузырьком (по убыванию) //для прибылей
void bubble_sort_desc(long profit_array[total_lines][profit_array_columns])
{
for (int i = 0; i < total_lines - 1; i++) //максимальное смещение: на один индекс
for (int j = 0; j < total_lines - 1; j++) //в худшем случае таких смещений нужно по общему числу элементов
{
for (int line_index = 0; line_index < total_lines; line_index++)
if (profit_array[line_index + 1][profit_column_profit - 1] > profit_array[line_index][profit_column_profit - 1])
swap_line(profit_array[line_index], profit_array[line_index + 1], profit_array_columns);
}
}
//сортировка пузырьком (по убыванию) //для заданного номера (по счету) столбца csv-таблицы
void bubble_sort_desc(string array[total_lines][total_columns], int selected_column)
{
for (int i = 0; i < total_lines - 1; i++) //максимальное смещение: на один индекс
for (int j = 0; j < total_lines - 1; j++) //в худшем случае таких смещений нужно по общему числу элементов
{
for (int line_index = 0; line_index < total_lines; line_index++)
if (array[line_index + 1][selected_column - 1] > array[line_index][selected_column - 1])
swap_line(array[line_index], array[line_index + 1], total_columns);
}
}
//переставляет значения a и b
void swap_values(long &a, long &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
//переставляет значения одной колонки (по номеру колонки) между двумя указанными строками (по индексам строк) //перегрузка для long-массивов
void swap_content_between_lines(long array[][profit_array_columns], int first_line_index, int second_line_index, int column_number)
{
int buffer_array_length;
buffer_array_length = 1;
long int *buffer_array_ptr = new long[buffer_array_length]();
buffer_array_ptr[0] = array[first_line_index][column_number - 1];
array[first_line_index][column_number - 1] = array[second_line_index][column_number - 1];
array[second_line_index][column_number - 1] = buffer_array_ptr[0];
//delete buffer_array_ptr;
}
//переставляет значения колонки (по номеру колонки) между указанными строками (по индексам строк) //перегрузка для string-массивов
void swap_content_between_lines(string array[total_lines][total_columns], int first_line_index, int second_line_index, int column_number)
{
int buffer_array_length;
buffer_array_length = 1;
string *buffer_array_ptr = new string[buffer_array_length]();
buffer_array_ptr[0] = array[first_line_index][column_number - 1];
array[first_line_index][column_number - 1] = array[second_line_index][column_number - 1];
array[second_line_index][column_number - 1] = buffer_array_ptr[0];
//delete buffer_array_ptr;
}
//переставляет местами две строки (все элементы двух строк) long 2D-массива:
//при обращении к 2D-массиву как к одномерному получаем указатель...
void swap_line(long *arr_1, long *arr_2, int total_columns)
{
for (long i = 0; i < total_columns; i++)
{
long tmp = arr_1[i];
arr_1[i] = arr_2[i]; //...каждый элемент строки меняем на соответствующий элемент другой строки
arr_2[i] = tmp;
}
}
//перегрузка для string
void swap_line(string *arr_1, string *arr_2, int total_columns)
{
for (long i = 0; i < total_columns; i++)
{
string tmp = arr_1[i];
arr_1[i] = arr_2[i]; //...каждый элемент строки меняем на соответствующий элемент другой строки
arr_2[i] = tmp;
}
} | true |
ec8b49399b446c6728185084a724a996e43d7e7a | C++ | Ta-ma/TP3---C | /Ejercicio 5/cliente.cpp | UTF-8 | 4,335 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string>
#include <signal.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
#define TAM 4096
/*
Nombre del archivo: cliente.cpp
Trabajo Práctico 3 - Ejercicio 5
Grupo: 12
Gómez Markowicz, Federico - 38858109
Kuczerawy, Damián - 37807869
Mediotte, Facundo - 39436162
Siculin, Luciano - 39213320
Tamashiro, Santiago - 39749147
*/
char* memoriaLeer();
void memoriaEscribir(char* mensaje);
char opcion;
int sockfd;
void terminar (int signum) {
cout << endl << "cerrando..." << endl;
// envio s al servidor para que se de cuenta que se desconectó el cliente
opcion = 's';
write(sockfd,&opcion,sizeof(opcion));
exit(0);
}
void limpiar_stdin(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
int main(int argc, char *argv[])
{
if (argc == 2) {
string param(argv[1]);
if (param == "-help" || param == "-h" || param == "-?") {
cout << "./cliente ip" << endl;
cout << "Donde:" << endl;
cout << "ip: Dirección de IP a donde se conectará el cliente." << endl;
cout << "El cliente puede enviar una frase para encriptar/desencriptar."
<< " y el servidor realizará la acción deseada." << endl;
return 0;
}
} else {
cerr << "Error en los parámetros enviados, utilice -help." << endl;
return -1;
}
signal(SIGINT, terminar);
signal(SIGTERM, terminar);
char* respuesta;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("Error: No se pudo crear el socket.");
return 1;
}
char recvBuff[1024];
memset(recvBuff, '0',sizeof(recvBuff));
struct sockaddr_in serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
inet_pton(AF_INET, argv[1], &serv_addr.sin_addr); // Error si IP mal escrita
if ( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Error: No se pudo conectar.\n");
return 1;
}
char mensaje[250];
int bytesRecibidos = 0;
// creo el semáforo y lo inicializo en 1
// si ya fue creado (por otro cliente) entonces referencia al mismo semáforo y no lo pisa.
sem_t *semaforo = sem_open("semaforo", O_CREAT, S_IRUSR | S_IWUSR, 1);
while(1) {
do {
puts("Desea encriptar, desencriptar o salir? (e/d/s)");
scanf("%c",&opcion);
limpiar_stdin();
} while(opcion != 'e' && opcion != 'd' && opcion != 's');
if (opcion == 'e') printf("Escriba mensaje a encriptar: \n");
else if (opcion == 'd') printf("Escriba mensaje a desencriptar: \n");
else {
write(sockfd,&opcion,sizeof(opcion));
return 0;
}
scanf("%s",mensaje);
sem_wait(semaforo);
limpiar_stdin();
write(sockfd,&opcion,sizeof(opcion));
memoriaEscribir(mensaje);
read(sockfd,&opcion,sizeof(opcion));
respuesta=memoriaLeer();
sem_post(semaforo);
if(opcion == 'e') printf("El mensaje encriptado es: %s\n",respuesta);
else printf("El mensaje desencriptado es: %s\n",respuesta);
}
return 0;
}
char* memoriaLeer(){
int pid,memoriaID;
char *punteroAMemoriaCompartida = NULL;
memoriaID = shmget(1315511,TAM,0660|IPC_CREAT);
punteroAMemoriaCompartida = (char*)shmat(memoriaID,NULL,0); //Asociacion
shmdt(&punteroAMemoriaCompartida); //Desasociacion
if(shmctl(memoriaID,IPC_RMID,NULL)==-1){
fprintf(stderr,"Error al liberar la memoria");
}
return punteroAMemoriaCompartida;
}
void memoriaEscribir(char *mensaje){
int pid,memoriaID;
char *punteroAMemoriaCompartida = NULL;
if((memoriaID = shmget(1315511,TAM,0660|IPC_CREAT))==-1) { //El primer valor es un identificador unico, puede dar problemas
fprintf(stderr,"Error al reservar la memoria");
} //Creo la memoria compartida
punteroAMemoriaCompartida = (char*)shmat(memoriaID,(void *)0,0); //Asociacion
strcpy(punteroAMemoriaCompartida,mensaje);
}
| true |
72ceb559a319f1fb4534c773846fae2a99949b13 | C++ | artHub-j/JUTGE | /X59210/solution.cpp | UTF-8 | 552 | 2.828125 | 3 | [] | no_license | #include "llista.hpp"
#include <iostream>
using namespace std;
Llista::Llista(const vector<int> &v) : _long(v.size())
// Pre: True
// Post: El p.i. conté els elements de v amb el mateix ordre.
{
_prim = new node;
_prim->info = 0;
_prim->seg = NULL;
if (not v.empty())
{
node *pant = _prim;
for (int i = 0; i < v.size(); i++)
{
node *p = new node;
p->info = v[i];
p->seg = NULL;
pant->seg = p;
pant = p;
p = p->seg;
}
}
} | true |
8f6aa023c8f3eeb574b33edc0cb954d4e74a458d | C++ | wzj1988tv/code-imitator | /data/dataset_2017/dataset_2017_8_formatted_macrosremoved/zhiheng3/5304486_5697460110360576_zhiheng3.cpp | UTF-8 | 2,146 | 2.5625 | 3 | [] | no_license | #include <cstring>
#include <iostream>
using namespace std;
int R[50];
int Q[50][50];
int n;
int d[201][201];
int match[201];
bool visited[201];
bool matching(int k) {
for (int i = 0; i < n; ++i) {
if (d[k][i] && !visited[i]) {
visited[i] = true;
if (match[i] == -1 || matching(match[i])) {
match[i] = k;
return true;
}
}
}
return false;
}
void findInterval(int i, int j, int &a, int &b) {
int need = R[i];
int ingre = Q[i][j];
a = int(ingre / (need * 1.1));
while (a * need * 1.1 < ingre) {
++a;
}
b = int(ingre / (need * 0.9));
while (b * need * 0.9 > ingre) {
--b;
}
// cout << need << ' ' << ingre << ' ' << a << ' ' << b << endl;
}
bool judge(int A, int B) {
int a0, b0, a1, b1;
findInterval(0, A, a0, b0);
findInterval(1, B, a1, b1);
if (a0 > b0 || a1 > b1) {
return false;
}
if (a0 > a1 && a0 > b1) {
return false;
}
if (a1 > a0 && a1 > b0) {
return false;
}
return true;
}
int main() {
int T;
cin >> T;
for (int c = 1; c <= T; ++c) {
memset(d, 0, sizeof(d));
memset(match, -1, sizeof(match));
int N, P;
cin >> N >> P;
for (int i = 0; i < N; ++i) {
cin >> R[i];
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < P; ++j) {
cin >> Q[i][j];
}
}
if (N == 1) {
int result = 0;
for (int i = 0; i < P; ++i) {
int a, b;
findInterval(0, i, a, b);
if (a <= b) {
++result;
}
}
cout << "Case #" << c << ": " << result << endl;
continue;
}
for (int i = 0; i < P; ++i) {
for (int j = 0; j < P; ++j) {
if (judge(i, j)) {
d[i][j] = 1;
}
}
} /*
for (int i = 0; i < P; ++i) {
for (int j = 0; j < P; ++j) {
cout << d[i][j];
}
cout << endl;
}*/
int result = 0;
n = N;
for (int i = 0; i < N; ++i) {
memset(visited, false, sizeof(visited));
if (matching(i)) {
++result;
}
}
cout << "Case #" << c << ": " << result << endl;
}
return 0;
}
| true |
171528a30c79393969613b76ffd710c59f7b1260 | C++ | Zoruk/labos-asd2 | /Labo 5/Code/ASD2_Labo5/wrongword.h | UTF-8 | 675 | 2.828125 | 3 | [] | no_license | #ifndef WRONGWORD_H
#define WRONGWORD_H
#include <string>
#include <array>
#include <list>
#include <iostream>
#include "worddictionary.h"
class WrongWord
{
friend std::ostream& operator<<(std::ostream& out, const WrongWord& wrongWord);
public:
typedef std::array<std::list<std::string>, 4> Possibilities;
enum class CorrectionType {
LETTER_REMOVED,
LETTER_ADDED,
LETTER_CHANGED,
LETTER_SWAPED
};
private:
std::string word;
Possibilities posibilites;
public:
WrongWord(std::string word, const WordDictionary& dico);
const Possibilities& getPosibilites() { return posibilites; }
};
#endif // WRONGWORD_H
| true |
133de7e18e7e605f0ab85670e0d8b86841f0b55c | C++ | BiomedNMR/aura | /include/boost/aura/backend/cuda/call.hpp | UTF-8 | 1,096 | 2.5625 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef AURA_BACKEND_CUDA_CALL_HPP
#define AURA_BACKEND_CUDA_CALL_HPP
#include <stdio.h>
/// check if a call returned error and throw exception if it did
#define AURA_CUDA_SAFE_CALL(call) { \
CUresult err = call; \
if (err != CUDA_SUCCESS) { \
printf("CUDA error %d at %s:%d\n", err, __FILE__, __LINE__ ); \
const char* errstr; \
cuGetErrorName(err, &errstr); \
printf("Description: %s\n", errstr); \
} \
} \
/**/
/// check if a call returned error and throw exception if it did
#define AURA_CUFFT_SAFE_CALL(call) { \
cufftResult err = call; \
if (err != CUFFT_SUCCESS) { \
std::ostringstream os; \
os << "CUFFT error " << err << " file " << \
__FILE__ << " line " << __LINE__; \
throw os.str(); \
} \
} \
/**/
/// check for error and throw exception if true
#define AURA_CUDA_CHECK_ERROR(err) { \
if (err != CUDA_SUCCESS) { \
printf("CUDA error %d at %s:%d\n", err, __FILE__, __LINE__ ); \
const char* errstr; \
cuGetErrorName(err, &errstr); \
printf("Description: %s\n", errstr); \
} \
} \
/**/
#endif // AURA_BACKEND_CUDA_CALL_HPP
| true |
e17fee4c81f67a70cd4d7d0344f6af29cff94ee9 | C++ | kolibreath/HomeWorks | /CppClass/C++进阶二/CRect.cpp | UTF-8 | 747 | 3.125 | 3 | [] | no_license | #include "CRect.h"
Rect::Rect() {}
Rect::Rect(string stype) {
this->type = stype;
}
void Rect::setRect()
{
setGraph();
cout<<"please input the width"<<endl;
int w;
cin >> w;;
width = w;
cout << "please input the height" << endl;
int h;
cin >> h;
height = h;
}
void Rect::show()
{
cout << "the type of the graph is " << type << endl;
cout << "the linewidth is" << linewidth << endl;
cout << "the color of the graph is " << color << endl;
cout << "the position is (" << pos.x << "," << pos.y << ")" << endl;
cout << "the width of the graph" << width << endl;
cout << "the height of the graph" << height << endl;
}
int Rect::getHeight() {return height;}
int Rect::getWidth() {return width;}
| true |
fe9a36c814c780170bfe32dafd39c05ffc73ba34 | C++ | CloudNartiveProjects/SEAL | /native/src/seal/randomgen.h | UTF-8 | 21,208 | 2.890625 | 3 | [
"MIT",
"CC0-1.0"
] | permissive | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include "seal/dynarray.h"
#include "seal/memorymanager.h"
#include "seal/version.h"
#include "seal/util/common.h"
#include "seal/util/defines.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
namespace seal
{
inline constexpr std::size_t prng_seed_uint64_count = 8;
inline constexpr std::size_t prng_seed_byte_count = prng_seed_uint64_count * util::bytes_per_uint64;
using prng_seed_type = std::array<std::uint64_t, prng_seed_uint64_count>;
/**
A type indicating a specific pseud-random number generator.
*/
enum class prng_type : std::uint8_t
{
unknown = 0,
blake2xb = 1,
shake256 = 2
};
/**
Returns a random 64-bit integer.
*/
SEAL_NODISCARD std::uint64_t random_uint64();
class UniformRandomGenerator;
class UniformRandomGeneratorInfo
{
friend class UniformRandomGenerator;
public:
/**
Creates a new UniformRandomGeneratorInfo.
*/
UniformRandomGeneratorInfo() = default;
/**
Creates a new UniformRandomGeneratorInfo.
@param[in] type The PRNG type
@param[in] seed The PRNG seed
*/
UniformRandomGeneratorInfo(prng_type type, prng_seed_type seed) : type_(type), seed_(std::move(seed))
{}
/**
Creates a new UniformRandomGeneratorInfo by copying a given one.
@param[in] copy The UniformRandomGeneratorInfo to copy from
*/
UniformRandomGeneratorInfo(const UniformRandomGeneratorInfo ©) = default;
/**
Copies a given UniformRandomGeneratorInfo to the current one.
@param[in] assign The UniformRandomGeneratorInfo to copy from
*/
UniformRandomGeneratorInfo &operator=(const UniformRandomGeneratorInfo &assign) = default;
/**
Compares two UniformRandomGeneratorInfo instances.
@param[in] compare The UniformRandomGeneratorInfo to compare against
*/
SEAL_NODISCARD inline bool operator==(const UniformRandomGeneratorInfo &compare) const noexcept
{
return (seed_ == compare.seed_) && (type_ == compare.type_);
}
/**
Compares two UniformRandomGeneratorInfo instances.
@param[in] compare The UniformRandomGeneratorInfo to compare against
*/
SEAL_NODISCARD inline bool operator!=(const UniformRandomGeneratorInfo &compare) const noexcept
{
return !operator==(compare);
}
/**
Clears all data in the UniformRandomGeneratorInfo.
*/
void clear() noexcept
{
type_ = prng_type::unknown;
util::seal_memzero(seed_.data(), prng_seed_byte_count);
}
/**
Destroys the UniformRandomGeneratorInfo.
*/
~UniformRandomGeneratorInfo()
{
clear();
}
/**
Creates a new UniformRandomGenerator object of type indicated by the PRNG
type and seeded with the current seed. If the current PRNG type is not
an official Microsoft SEAL PRNG type, the return value is nullptr.
*/
std::shared_ptr<UniformRandomGenerator> make_prng() const;
/**
Returns whether this object holds a valid PRNG type.
*/
SEAL_NODISCARD inline bool has_valid_prng_type() const noexcept
{
switch (type_)
{
case prng_type::blake2xb:
/* fall through */
case prng_type::shake256:
/* fall through */
case prng_type::unknown:
return true;
}
return false;
}
/**
Returns the PRNG type.
*/
SEAL_NODISCARD inline prng_type type() const noexcept
{
return type_;
}
/**
Returns a reference to the PRNG type.
*/
SEAL_NODISCARD inline prng_type &type() noexcept
{
return type_;
}
/**
Returns a reference to the PRNG seed.
*/
SEAL_NODISCARD inline const prng_seed_type &seed() const noexcept
{
return seed_;
}
/**
Returns a reference to the PRNG seed.
*/
SEAL_NODISCARD inline prng_seed_type &seed() noexcept
{
return seed_;
}
/**
Returns an upper bound on the size of the UniformRandomGeneratorInfo, as
if it was written to an output stream.
@param[in] compr_mode The compression mode
@throws std::invalid_argument if the compression mode is not supported
@throws std::logic_error if the size does not fit in the return type
*/
SEAL_NODISCARD static inline std::streamoff SaveSize(
compr_mode_type compr_mode = Serialization::compr_mode_default)
{
std::size_t members_size =
Serialization::ComprSizeEstimate(sizeof(prng_type) + prng_seed_byte_count, compr_mode);
return static_cast<std::streamoff>(sizeof(Serialization::SEALHeader) + members_size);
}
/**
Returns an upper bound on the size of the UniformRandomGeneratorInfo, as
if it was written to an output stream.
@param[in] compr_mode The compression mode
@throws std::invalid_argument if the compression mode is not supported
@throws std::logic_error if the size does not fit in the return type
*/
SEAL_NODISCARD inline std::streamoff save_size(
compr_mode_type compr_mode = Serialization::compr_mode_default) const
{
return UniformRandomGeneratorInfo::SaveSize(compr_mode);
}
/**
Saves the UniformRandomGeneratorInfo to an output stream. The output is
in binary format and is not human-readable. The output stream must have
the "binary" flag set.
@param[out] stream The stream to save the UniformRandomGeneratorInfo to
@param[in] compr_mode The desired compression mode
@throws std::invalid_argument if the compression mode is not supported
@throws std::logic_error if the data to be saved is invalid, or if
compression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff save(
std::ostream &stream, compr_mode_type compr_mode = Serialization::compr_mode_default) const
{
using namespace std::placeholders;
return Serialization::Save(
std::bind(&UniformRandomGeneratorInfo::save_members, this, _1), save_size(compr_mode_type::none),
stream, compr_mode);
}
/**
Loads a UniformRandomGeneratorInfo from an input stream overwriting the
current UniformRandomGeneratorInfo.
@param[in] stream The stream to load the UniformRandomGeneratorInfo from
@throws std::logic_error if the data cannot be loaded by this version of
Microsoft SEAL, if the loaded data is invalid, or if decompression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff load(std::istream &stream)
{
using namespace std::placeholders;
UniformRandomGeneratorInfo new_info;
auto in_size =
Serialization::Load(std::bind(&UniformRandomGeneratorInfo::load_members, &new_info, _1, _2), stream);
std::swap(*this, new_info);
return in_size;
}
/**
Saves the UniformRandomGeneratorInfo to a given memory location. The output
is in binary format and is not human-readable.
@param[out] out The memory location to write the UniformRandomGeneratorInfo to
@param[in] size The number of bytes available in the given memory location
@param[in] compr_mode The desired compression mode
@throws std::invalid_argument if out is null or if size is too small to
contain a SEALHeader, or if the compression mode is not supported
@throws std::logic_error if the data to be saved is invalid, or if
compression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff save(
seal_byte *out, std::size_t size, compr_mode_type compr_mode = Serialization::compr_mode_default) const
{
using namespace std::placeholders;
return Serialization::Save(
std::bind(&UniformRandomGeneratorInfo::save_members, this, _1), save_size(compr_mode_type::none), out,
size, compr_mode);
}
/**
Loads a UniformRandomGeneratorInfo from a given memory location overwriting
the current UniformRandomGeneratorInfo.
@param[in] in The memory location to load the UniformRandomGeneratorInfo from
@param[in] size The number of bytes available in the given memory location
@throws std::invalid_argument if in is null or if size is too small to
contain a SEALHeader
@throws std::logic_error if the data cannot be loaded by this version of
Microsoft SEAL, if the loaded data is invalid, or if decompression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff load(const seal_byte *in, std::size_t size)
{
using namespace std::placeholders;
UniformRandomGeneratorInfo new_info;
auto in_size =
Serialization::Load(std::bind(&UniformRandomGeneratorInfo::load_members, &new_info, _1, _2), in, size);
std::swap(*this, new_info);
return in_size;
}
public:
void save_members(std::ostream &stream) const;
void load_members(std::istream &stream, SEALVersion version);
prng_type type_ = prng_type::unknown;
prng_seed_type seed_ = {};
};
/**
Provides the base class for a seeded uniform random number generator. Instances
of this class are meant to be created by an instance of the factory class
UniformRandomGeneratorFactory. This class is meant for users to sub-class to
implement their own random number generators.
*/
class UniformRandomGenerator
{
public:
/**
Creates a new UniformRandomGenerator instance initialized with the given seed.
@param[in] seed The seed for the random number generator
*/
UniformRandomGenerator(prng_seed_type seed)
: seed_([&seed]() {
// Create a new seed allocation
DynArray<std::uint64_t> new_seed(
seed.size(), MemoryManager::GetPool(mm_prof_opt::mm_force_new, true));
// Assign the given seed and return
std::copy(seed.cbegin(), seed.cend(), new_seed.begin());
return new_seed;
}()),
buffer_(buffer_size_, MemoryManager::GetPool(mm_prof_opt::mm_force_new, true)),
buffer_begin_(buffer_.begin()), buffer_end_(buffer_.end()), buffer_head_(buffer_.end())
{}
SEAL_NODISCARD inline prng_seed_type seed() const noexcept
{
prng_seed_type ret;
std::copy(seed_.cbegin(), seed_.cend(), ret.begin());
return ret;
}
/**
Fills a given buffer with a given number of bytes of randomness.
*/
void generate(std::size_t byte_count, seal_byte *destination);
/**
Generates a new unsigned 32-bit random number.
*/
SEAL_NODISCARD inline std::uint32_t generate()
{
std::uint32_t result;
generate(sizeof(result), reinterpret_cast<seal_byte *>(&result));
return result;
}
/**
Discards the contents of the current randomness buffer and refills it
with fresh randomness.
*/
inline void refresh()
{
std::lock_guard<std::mutex> lock(mutex_);
refill_buffer();
buffer_head_ = buffer_begin_;
}
/**
Returns a UniformRandomGeneratorInfo object representing this PRNG.
*/
SEAL_NODISCARD inline UniformRandomGeneratorInfo info() const noexcept
{
UniformRandomGeneratorInfo result;
std::copy_n(seed_.cbegin(), prng_seed_uint64_count, result.seed_.begin());
result.type_ = type();
return result;
}
/**
Destroys the random number generator.
*/
virtual ~UniformRandomGenerator() = default;
protected:
SEAL_NODISCARD virtual prng_type type() const noexcept = 0;
virtual void refill_buffer() = 0;
const DynArray<std::uint64_t> seed_;
const std::size_t buffer_size_ = 4096;
private:
DynArray<seal_byte> buffer_;
std::mutex mutex_;
protected:
seal_byte *const buffer_begin_;
seal_byte *const buffer_end_;
seal_byte *buffer_head_;
};
/**
Provides the base class for a factory instance that creates instances of
UniformRandomGenerator. This class is meant for users to sub-class to implement
their own random number generators.
*/
class UniformRandomGeneratorFactory
{
public:
/**
Creates a new UniformRandomGeneratorFactory. The seed will be sampled
randomly for each UniformRandomGenerator instance created by the factory
instance, which is desirable in most normal use-cases.
*/
UniformRandomGeneratorFactory() : use_random_seed_(true)
{}
/**
Creates a new UniformRandomGeneratorFactory and sets the default seed to
the given value. For debugging purposes it may sometimes be convenient to
have the same randomness be used deterministically and repeatedly. Such
randomness sampling is naturally insecure and must be strictly restricted
to debugging situations. Thus, most users should never have a reason to
use this constructor.
@param[in] default_seed The default value for a seed to be used by all
created instances of UniformRandomGenerator
*/
UniformRandomGeneratorFactory(prng_seed_type default_seed)
: default_seed_(default_seed), use_random_seed_(false)
{}
/**
Creates a new uniform random number generator.
*/
SEAL_NODISCARD auto create() -> std::shared_ptr<UniformRandomGenerator>
{
return use_random_seed_
? create_impl({ random_uint64(), random_uint64(), random_uint64(), random_uint64(),
random_uint64(), random_uint64(), random_uint64(), random_uint64() })
: create_impl(default_seed_);
}
/**
Creates a new uniform random number generator seeded with the given seed,
overriding the default seed for this factory instance.
@param[in] seed The seed to be used for the created random number generator
*/
SEAL_NODISCARD auto create(prng_seed_type seed) -> std::shared_ptr<UniformRandomGenerator>
{
return create_impl(seed);
}
/**
Destroys the random number generator factory.
*/
virtual ~UniformRandomGeneratorFactory() = default;
/**
Returns the default random number generator factory. This instance should
not be destroyed.
*/
static auto DefaultFactory() -> std::shared_ptr<UniformRandomGeneratorFactory>;
/**
Returns whether the random number generator factory creates random number
generators seeded with a random seed, or if a default seed is used.
*/
SEAL_NODISCARD inline bool use_random_seed() noexcept
{
return use_random_seed_;
}
/**
Returns the default seed used to seed every random number generator created
by this random number generator factory. If use_random_seed() is false, then
the returned seed has no meaning.
*/
SEAL_NODISCARD inline prng_seed_type default_seed() noexcept
{
return default_seed_;
}
protected:
SEAL_NODISCARD virtual auto create_impl(prng_seed_type seed) -> std::shared_ptr<UniformRandomGenerator> = 0;
private:
prng_seed_type default_seed_ = {};
bool use_random_seed_ = false;
};
/**
Provides an implementation of UniformRandomGenerator for using Blake2xb for
generating randomness with given 128-bit seed.
*/
class Blake2xbPRNG : public UniformRandomGenerator
{
public:
/**
Creates a new Blake2xbPRNG instance initialized with the given seed.
@param[in] seed The seed for the random number generator
*/
Blake2xbPRNG(prng_seed_type seed) : UniformRandomGenerator(seed)
{}
/**
Destroys the random number generator.
*/
~Blake2xbPRNG() = default;
protected:
SEAL_NODISCARD prng_type type() const noexcept override
{
return prng_type::blake2xb;
}
void refill_buffer() override;
private:
std::uint64_t counter_ = 0;
};
class Blake2xbPRNGFactory : public UniformRandomGeneratorFactory
{
public:
/**
Creates a new Blake2xbPRNGFactory. The seed will be sampled randomly
for each Blake2xbPRNG instance created by the factory instance, which is
desirable in most normal use-cases.
*/
Blake2xbPRNGFactory() : UniformRandomGeneratorFactory()
{}
/**
Creates a new Blake2xbPRNGFactory and sets the default seed to the given
value. For debugging purposes it may sometimes be convenient to have the
same randomness be used deterministically and repeatedly. Such randomness
sampling is naturally insecure and must be strictly restricted to debugging
situations. Thus, most users should never use this constructor.
@param[in] default_seed The default value for a seed to be used by all
created instances of Blake2xbPRNG
*/
Blake2xbPRNGFactory(prng_seed_type default_seed) : UniformRandomGeneratorFactory(default_seed)
{}
/**
Destroys the random number generator factory.
*/
~Blake2xbPRNGFactory() = default;
protected:
SEAL_NODISCARD auto create_impl(prng_seed_type seed) -> std::shared_ptr<UniformRandomGenerator> override
{
return std::make_shared<Blake2xbPRNG>(seed);
}
private:
};
/**
Provides an implementation of UniformRandomGenerator for using SHAKE-256 for
generating randomness with given 128-bit seed.
*/
class Shake256PRNG : public UniformRandomGenerator
{
public:
/**
Creates a new Shake256PRNG instance initialized with the given seed.
@param[in] seed The seed for the random number generator
*/
Shake256PRNG(prng_seed_type seed) : UniformRandomGenerator(seed)
{}
/**
Destroys the random number generator.
*/
~Shake256PRNG() = default;
protected:
SEAL_NODISCARD prng_type type() const noexcept override
{
return prng_type::shake256;
}
void refill_buffer() override;
private:
std::uint64_t counter_ = 0;
};
class Shake256PRNGFactory : public UniformRandomGeneratorFactory
{
public:
/**
Creates a new Shake256PRNGFactory. The seed will be sampled randomly for
each Shake256PRNG instance created by the factory instance, which is
desirable in most normal use-cases.
*/
Shake256PRNGFactory() : UniformRandomGeneratorFactory()
{}
/**
Creates a new Shake256PRNGFactory and sets the default seed to the given
value. For debugging purposes it may sometimes be convenient to have the
same randomness be used deterministically and repeatedly. Such randomness
sampling is naturally insecure and must be strictly restricted to debugging
situations. Thus, most users should never use this constructor.
@param[in] default_seed The default value for a seed to be used by all
created instances of Shake256PRNG
*/
Shake256PRNGFactory(prng_seed_type default_seed) : UniformRandomGeneratorFactory(default_seed)
{}
/**
Destroys the random number generator factory.
*/
~Shake256PRNGFactory() = default;
protected:
SEAL_NODISCARD auto create_impl(prng_seed_type seed) -> std::shared_ptr<UniformRandomGenerator> override
{
return std::make_shared<Shake256PRNG>(seed);
}
private:
};
} // namespace seal
| true |
3c4106df1dc4a3e2e3d0f6f8fb8e9ff58a340171 | C++ | bbkgl/bbkgl | /src/net/EventLoopThreadPool.cpp | UTF-8 | 1,168 | 2.984375 | 3 | [
"MIT"
] | permissive | //
// Created by bbkgl on 19-4-3.
//
#include "EventLoopThreadPool.h"
#include "EventLoop.h"
#include "EventLoopThread.h"
EventLoopThreadPool::EventLoopThreadPool(EventLoop *loop) :
base_loop_(loop),
started_(false),
num_threads_(0),
next_(0)
{}
EventLoopThreadPool::~EventLoopThreadPool()
{
// 这里不需要删除base_loop_,是栈上的变量
}
void EventLoopThreadPool::Start()
{
assert(!started_);
base_loop_->AssertInLoopThread();
// 标记线程池开始运行
started_ = true;
// 产生固定数目的已经占用线程的EventLoop对象
for (int i = 0; i < num_threads_; i++)
{
EventLoopThread *t = new EventLoopThread;
threads_.push_back(t);
loops_.push_back(t->StartLoop());
}
}
EventLoop* EventLoopThreadPool::GetNextLoop()
{
base_loop_->AssertInLoopThread();
EventLoop *loop = base_loop_;
// Round-robin调度算法
// 轮询每个EventLoop,然后返回去处理连接
if (!loops_.empty())
{
loop = loops_[next_];
++next_;
if (static_cast<size_t>(next_) >= loops_.size())
next_ = 0;
}
return loop;
} | true |
6841c6912421a94575e7fa1e96d24889e78d71d2 | C++ | grzesiakm/OOP1 | /Bubble/Calc_error.h | UTF-8 | 1,286 | 3.078125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include <string>
#include <exception>
//static int value of levels
int LicznikPoziomow::lvl = 0;
//this class shows the number of line and file name where the error occured, as well as reason to throw exception
class Calc_error : public std::runtime_error {
public:
Calc_error(std::runtime_error *eo, std::string str, std::string f_name, int line_n)
: std::runtime_error(str + ", [plik = " + f_name + ", linia = " + std::to_string(line_n) + "]"), next(eo) {}
~Calc_error() = default;
//method to handle all of the exceptions
static void handler() {
try {
throw;
} catch(std::runtime_error* e) {
std::cout<<" Zlapano wyjatek:"<<std::endl;
while(e) {
std::cout<<" -- z powodu: "<< e->what() <<std::endl;
auto ex = dynamic_cast<Calc_error*>(e);
if(!ex) {
delete e;
e = nullptr;
}
else {
e = ex->next;
delete ex;
}
}
}
}
friend class LicznikPoziomow;
protected:
//pointer to the next error
std::runtime_error *next;
};
| true |
9320c85c948500b6a11508355414d60ee72383e8 | C++ | qualab/dot | /include/dot/box.h | UTF-8 | 12,983 | 3.234375 | 3 | [
"MIT"
] | permissive | // dot::box<slim> contains value of slim type
// which size allows ot store it in-place (by value)
// this is suitable for simple values and small structures
// data class box<slim>::cat is simply contain its value
#pragma once
#include <dot/object.h>
#include <utility>
#include <new>
namespace dot
{
// base class for any other box
class DOT_PUBLIC box_based : public object
{
public:
box_based();
template <class slim>
explicit box_based(slim&& value);
DOT_HIERARCHIC(object);
class cat_based;
};
// box contains slim cat which is liquid enough
// to be suitable for internal object's buffer
template <class slim>
class box : public box_based
{
public:
box(const object& another);
template <class... arguments>
explicit box(arguments... args);
const slim& look() const noexcept;
slim& touch() noexcept;
template <class other> bool operator == (const box<other>& another) const;
template <class other> bool operator != (const box<other>& another) const;
template <class other> bool operator <= (const box<other>& another) const;
template <class other> bool operator >= (const box<other>& another) const;
template <class other> bool operator < (const box<other>& another) const;
template <class other> bool operator > (const box<other>& another) const;
template <class other> bool operator == (const other& another) const;
template <class other> bool operator != (const other& another) const;
template <class other> bool operator <= (const other& another) const;
template <class other> bool operator >= (const other& another) const;
template <class other> bool operator < (const other& another) const;
template <class other> bool operator > (const other& another) const;
DOT_HIERARCHIC(box_based);
class cat;
private:
cat* my_cat;
};
template <typename left, typename right> bool operator == (const left& x, const box<right>& y);
template <typename left, typename right> bool operator != (const left& x, const box<right>& y);
template <typename left, typename right> bool operator <= (const left& x, const box<right>& y);
template <typename left, typename right> bool operator >= (const left& x, const box<right>& y);
template <typename left, typename right> bool operator < (const left& x, const box<right>& y);
template <typename left, typename right> bool operator > (const left& x, const box<right>& y);
// base class for any cat in the box
class DOT_PUBLIC box_based::cat_based : public object::data
{
public:
DOT_HIERARCHIC(object::data);
};
// data contains value in-placed as a field
template <class slim>
class box<slim>::cat : public box_based::cat_based
{
public:
cat(const cat& another);
template <class... arguments>
cat(arguments... args);
const slim& look() const noexcept;
slim& touch() noexcept;
DOT_HIERARCHIC(box_based::cat_based);
protected:
virtual object::data* copy_to(void* buffer) const noexcept override;
virtual object::data* move_to(void* buffer) noexcept override;
virtual void write(std::ostream& stream) const override;
virtual void read(std::istream& stream) override;
virtual bool equals(const object::data& another) const noexcept override;
virtual bool less(const object::data& another) const noexcept override;
private:
slim my_value;
};
// -- implementation of the box methods --
template <class slim>
box_based::box_based(slim&& value)
: base(std::forward<slim>(value))
{
}
template <class slim>
box<slim>::box(const object& another)
: my_cat(initialize<box<slim>::cat>(
another.data_as<box<slim>::cat>()))
{
}
template <class slim>
template <class... arguments>
box<slim>::box(arguments... args)
: my_cat(initialize<cat>(std::forward<arguments>(args)...))
{
}
template <class slim>
const slim& box<slim>::look() const noexcept
{
return my_cat->look();
}
template <class slim>
slim& box<slim>::touch() noexcept
{
return my_cat->touch();
}
template <class slim>
template <class other>
bool box<slim>::operator == (const box<other>& another) const
{
if constexpr (are_comparable<slim, other>)
{
return look() == another.look();
}
else
{
return my_cat->equals(another.get_data());
}
}
template <class slim>
template <class other>
bool box<slim>::operator != (const box<other>& another) const
{
return !(*this == another);
}
template <class slim>
template <class other>
bool box<slim>::operator <= (const box<other>& another) const
{
return !(another < *this);
}
template <class slim>
template <class other>
bool box<slim>::operator >= (const box<other>& another) const
{
return !(*this < another);
}
template <class slim>
template <class other>
bool box<slim>::operator < (const box<other>& another) const
{
if constexpr (are_orderable<slim, other>)
{
return look() < another.look();
}
else
{
return my_cat->less(another.get_data());
}
}
template <class slim>
template <class other>
bool box<slim>::operator > (const box<other>& another) const
{
return another < *this;
}
template <class slim>
template <class other>
bool box<slim>::operator == (const other& another) const
{
if constexpr (are_comparable<slim, other>)
{
return look() == another;
}
else if constexpr (std::is_base_of_v<object, other>)
{
return base::operator == (another);
}
else
{
static_assert(false, "Unable to compare box_based with non comparable type.");
}
}
template <class slim>
template <class other>
bool box<slim>::operator != (const other& another) const
{
return !(*this == another);
}
template <class slim>
template <class other>
bool box<slim>::operator <= (const other& another) const
{
return !(*this > another);
}
template <class slim>
template <class other>
bool box<slim>::operator >= (const other& another) const
{
return !(*this < another);
}
template <class slim>
template <class other>
bool box<slim>::operator < (const other& another) const
{
if (are_orderable<slim, other>)
{
return look() < another;
}
else if constexpr (std::is_base_of_v<object, other>)
{
return base::operator < (another);
}
else
{
static_assert(false, "Unable to order box_based with non orderable type.");
}
}
template <class slim>
template <class other>
bool box<slim>::operator > (const other& another) const
{
if (are_orderable<other, slim>)
{
return another < look();
}
else if constexpr (std::is_base_of_v<object, other>)
{
return base::operator > (another);
}
else
{
static_assert(false, "Unable to order box_based with non orderable type.");
}
}
template <typename left, typename right>
bool operator == (const left& x, const box<right>& y)
{
return y == x;
}
template <typename left, typename right>
bool operator != (const left& x, const box<right>& y)
{
return y != x;
}
template <typename left, typename right>
bool operator <= (const left& x, const box<right>& y)
{
return y >= x;
}
template <typename left, typename right>
bool operator >= (const left& x, const box<right>& y)
{
return y <= x;
}
template <typename left, typename right>
bool operator < (const left& x, const box<right>& y)
{
return y > x;
}
template <typename left, typename right>
bool operator > (const left& x, const box<right>& y)
{
return y < x;
}
// -- implementation of the cat in the box methods --
template <class slim>
box<slim>::cat::cat(const cat& another)
: my_value(another.my_value)
{
}
template <class slim>
template <class... arguments>
box<slim>::cat::cat(arguments... args)
: my_value(std::forward<arguments>(args)...)
{
}
template <class slim>
const slim& box<slim>::cat::look() const noexcept
{
return my_value;
}
template <class slim>
slim& box<slim>::cat::touch() noexcept
{
return my_value;
}
template <class slim>
object::data* box<slim>::cat::copy_to(void* buffer) const noexcept
{
return new(buffer) cat(*this);
}
template <class slim>
object::data* box<slim>::cat::move_to(void* buffer) noexcept
{
return new(buffer) cat(std::move(*this));
}
template <class slim>
void box<slim>::cat::write(std::ostream& stream) const
{
if constexpr (is_writable<slim>)
{
stream << look();
}
else
{
base::write(stream);
}
}
template <class slim>
void box<slim>::cat::read(std::istream& stream)
{
if constexpr (is_readable<slim>)
{
stream >> touch();
}
else
{
base::read(stream);
}
}
template <class slim>
bool box<slim>::cat::equals(const object::data& another) const noexcept
{
if constexpr (is_comparable<slim>)
{
if (another.is<cat>())
return look() == another.as<cat>().look();
else
return base::equals(another);
}
else
{
return base::equals(another);
}
}
template <class slim>
bool box<slim>::cat::less(const object::data& another) const noexcept
{
if constexpr (is_orderable<slim>)
{
if (another.is<cat>())
return look() < another.as<cat>().look();
else
return base::equals(another);
}
else
{
return base::equals(another);
}
}
// -- definition of the identifiers for the boxes of native types --
template<> DOT_PUBLIC const class_id& box<long long>::id() noexcept;
template<> DOT_PUBLIC const class_id& box<long >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<int >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<short >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<char >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned long long>::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned long >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned int >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned short >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned char >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<double>::id() noexcept;
template<> DOT_PUBLIC const class_id& box<float >::id() noexcept;
template<> DOT_PUBLIC const class_id& box<bool>::id() noexcept;
template<> DOT_PUBLIC const class_id& box<char>::id() noexcept;
// -- definition of the identifiers for the cats in the box of native types --
template<> DOT_PUBLIC const class_id& box<long long>::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<long >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<int >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<short >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<char >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned long long>::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned long >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned int >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned short >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<unsigned char >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<double>::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<float >::cat::id() noexcept;
template<> DOT_PUBLIC const class_id& box<bool>::cat::id() noexcept;
}
// Здесь должен быть Unicode
| true |
31338b1a7ed98729f4dbbd31adc3adc56d1a0f62 | C++ | mambolevis/tcpppl | /test/adl.cpp | UTF-8 | 2,019 | 2.953125 | 3 | [
"MIT"
] | permissive | // Created by Samvel Khalatyan on Jan 29, 2014
// Copyright (c) 2014 Samvel Khalatyan. All rights reserved
//
// Use of this source code is governed by a license that can be found in
// the LICENSE file.
#include <iostream>
using namespace std;
namespace base
{
struct Struct {};
void a(const Struct &)
{
cout << "base::a(base::Struct)" << endl;
}
void b(const Struct &b)
{
cout << "base::b(base::Struct)" << endl;
a(b);
}
struct Base
{
virtual void a(const Struct &)
{
cout << "base::Base::a(base::Struct)" << endl;
}
};
}
namespace child
{
struct Struct {};
struct CStruct: public base::Struct {};
void a(const base::Struct &)
{
cout << "child::a(base::Struct)" << endl;
}
void a(const child::Struct &)
{
cout << "child::a(child::Struct)" << endl;
}
void a(const child::CStruct &)
{
cout << "child::a(child::CStruct)" << endl;
}
struct Child: public base::Base
{
virtual void a(const base::Struct &)
{
cout << "child::Child[Base]::a(base::Struct)" << endl;
}
virtual void a(const Struct &)
{
cout << "child::Child[Base]::a(child::Struct)" << endl;
}
virtual void b(const Struct &s)
{
cout << "child::Child[Base]::b(child::Struct)" << endl;
a(s);
}
};
}
int main(int, char *[])
{
a(base::Struct{});
cout << "--" << endl;
b(base::Struct{});
cout << "--" << endl;
a(child::Struct{});
cout << "--" << endl;
a(child::CStruct{});
cout << "--" << endl;
a(static_cast<const base::Struct &>(child::CStruct{}));
cout << "--" << endl;
base::Base{}.a(base::Struct{});
cout << "--" << endl;
child::Child{}.a(base::Struct{});
cout << "--" << endl;
static_cast<base::Base>(child::Child{}).a(base::Struct{});
cout << "--" << endl;
child::Child{}.a(child::Struct{});
}
| true |
77c06e6bd9e500bee18516e027802a9e4886b967 | C++ | rjindel/OnlineServices | /OnlineService/Utils.h | UTF-8 | 666 | 2.9375 | 3 | [] | no_license | //-------------------------------------------------------------------------
//
// File: Utils.h
//
// helper functions
//
//--------------------------------------------------------------------------
#pragma once
#include "stdafx.h"
namespace Utils
{
//Convert a single ascii character to a 4 bit hex value
//If the character is outside outside the range [0-9a-fA-F] throw
char CharToHex(char character);
//Convert a null terminated string to a byte array
void StringToHex(const char* str, BYTE* hex);
//Clear the console screen
//Lines number of lines to clear. default clears the whole screen
void ClearScreen(HANDLE consoleHandle, uint32_t lines = 0);
} | true |
c127fcf9d2b62d5043bdad98c6492cb9a8628733 | C++ | mhorowitzgelb/TinyRendererWindowsApp | /TinyRendererWindowsApp/gaurad_shader.h | UTF-8 | 755 | 2.515625 | 3 | [] | no_license | #pragma once
#include "SimpleGraphics.h"
#include "model.h"
/*
namespace simple_graphics {
class GauraudShader :
public IShader
{
public:
GauraudShader() = delete;
~GauraudShader() = default;
explicit GauraudShader(Model* model, TGAImage* texture, const Vec3f& light_direction) :
model_(model), texture_(texture), light_direction_(light_direction) {}
// Inherited via IShader
virtual Vec3f vertex(int iface, int nthvert) override;
virtual bool fragment(Vec3f bar, SimpleColor& color) override;
protected :
Model* model_;
TGAImage* texture_;
Vec3f light_direction_;
Vec3f varying_intensity_;
Vec3f varying_texture_[2];
};
}*/
| true |
182c31cb4ab16e2f63d254943ecf0909ff305c6b | C++ | ivokaragyozov/Programming-Contests | /CodeForces/Round#253_DIV2/a.cpp | UTF-8 | 422 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define endl '\n'
using namespace std;
bool used_letters[26];
int size_s, ans;
string s;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
getline(cin, s);
size_s = s.size();
for(int i = 0; i < size_s; i++)
{
if(s[i] >= 'a' && s[i] <= 'z')
{
if(!used_letters[s[i] - 'a'])
{
used_letters[s[i] - 'a'] = true;
ans++;
}
}
}
cout<<ans<<endl;
return 0;
}
| true |
c4630cd658732da62c75d274bca917a8bdc537a3 | C++ | ericgu/ESP8266Animation | /SingleColor.h | UTF-8 | 902 | 2.90625 | 3 | [] | no_license | class SingleColor: public Animation
{
private:
Adafruit_NeoPixel* _pStrip;
Mapper* _pMapper;
Pixel _pixel;
Chunk* _pChunk;
RGBColor _color;
public:
SingleColor(Adafruit_NeoPixel* pStrip, RGBColor color)
{
_pStrip = pStrip;
_color = color;
_pMapper = new Mapper(_pStrip);
_pChunk = new Chunk(1);
_pixel = Pixel(color);
_pChunk->setPixel(0, _pixel);
}
~SingleColor()
{
delete _pChunk;
delete _pMapper;
}
void dimToPercentage(int percentage)
{
int red = (_color.red * percentage) / 100;
int green = (_color.green * percentage) / 100;
int blue = (_color.blue * percentage) / 100;
_pixel.animateToNewColor(RGBColor(red, green, blue), 255);
}
virtual void update()
{
_pixel.update();
_pMapper->renderAndShow(_pChunk);
}
};
| true |
7aaf38cec30ab11428f7df9289a37daf15c09b6a | C++ | 18600130137/leetcode | /LeetCodeCPP/264. Ugly Number II/main.cpp | UTF-8 | 864 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | //
// main.cpp
// 264. Ugly Number II
//
// Created by admin on 2019/7/2.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> helper{1};
int i2=0,i3=0,i5=0;
for(int i=1;i<n;i++){
int next=min(min(helper[i2]*2,helper[i3]*3),helper[i5]*5);
helper.push_back(next);
if (next == helper[i2] * 2)
++i2;
if (next == helper[i3] * 3)
++i3;
if (next == helper[i5] * 5)
++i5;
}
return helper[n-1];
}
};
int main(int argc, const char * argv[]) {
Solution so=Solution();
int ret=so.nthUglyNumber(10);
cout<<"The ret is:"<<ret<<endl;
return 0;
}
| true |
3b8f5834cb9a65efd9d7bb489071de241e57f6e7 | C++ | natemc/qiss | /src/key.cpp | UTF-8 | 1,426 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <key.h>
#include <exception.h>
#include <limits>
#include <numeric>
#include <ukv.h>
namespace {
template <class X> using OT = ObjectTraits<X>;
template <class X> L<X> iota(index_t n) {
L<X> r(n);
std::iota(r.begin(), r.end(), X(0));
return r;
}
}
L<J> Til::operator()(index_t n) const { return iota<J>(n); }
L<J> Til::operator()(O x) const {
#define ATOM(X) case -OT<X>::typei(): return (*this)(X::rep(x.atom<X>()))
switch (int(x.type())) {
ATOM(B); ATOM(I); ATOM(J); ATOM(X);
default:
if (x.is_list()) return (*this)(x.get()->n);
throw Exception("nyi: til");
}
#define ATOM(X) case -OT<X>::typei(): return (*this)(X::rep(x.atom<X>()))
}
L<I> TilI::operator()(index_t n) const {
if (std::numeric_limits<I::rep>::max() < n) throw Exception("length (tili)");
return iota<I>(n);
}
L<I> TilI::operator()(O x) const {
#define ATOM(X) case -OT<X>::typei(): return (*this)(X::rep(x.atom<X>()))
switch (int(x.type())) {
ATOM(B); ATOM(I); ATOM(J); ATOM(X);
default:
if (x.is_list()) return (*this)(x.get()->n);
throw Exception("nyi: tili");
}
#undef ATOM
}
O key(O x) {
if (x.is_atom()) return til(std::move(x));
if (x.is_dict()) return UKV(std::move(x)).key();
// if (x.is_list()) return til(UL(std::move(x)).size());
if (x.is_list()) return til(x.get()->n);
throw Exception("nyi: key");
}
| true |
4a07a1d77b55a634947f633164b0591a44d2f750 | C++ | Kewenjing1020/C-Primer | /chap3/chap3.cpp | UTF-8 | 2,536 | 3.390625 | 3 | [] | no_license | //writen by Ke Wenjing,19/11/2015
//C++ Primer, chap3
//including using, string, vector, iterator, bitset
#include <iostream>
#include <string>
#include <vector>
#include <bitset>
using std::bitset;
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main(){
// string s1;
// string s2;
// cin>>s1>>s2;
// cout<<s1<<endl;
// cout<<s2<<endl;
// return 0;
// string word;
// while(cin>>word)
// cout<<word;
// return 0;
//getline
// string line;
// while(getline(cin,line))
// cout<<line<<endl;
// return 0;
// string st;
// string word;
// while(cin>>word)
// st = st + word;
// cout<<st;
// cout << "the size of \'" <<st<<"\' is"<< st.size()<<endl;
// return 0;
//attention! string::size_type
//Full replication
// string str("some string");
// for(string::size_type ix=0;ix !=str.size();++ix)
// // cout<< str[ix]<<endl;
// str[ix]='*';
//int a=2,b=3;
// string::size_type a=2,b=3;
// str[a*b]=a;
// cout<<str<<endl;
// return 0;
//calculate number of punct
//ispunct
// string s("Hello World!!!");
// string::size_type cnt=0;
// for(string::size_type index =0;index<= s.size();++index){
// if(ispunct(s[index]))
// cnt++;
// }
// cout<<cnt<<endl;
// //tolower
// for(string::size_type index =0;index<= s.size();++index)
// {
// s[index]=tolower(s[index]);
// }
// cout <<s<<endl;
// return 0;
//vector
// vector<string> v(10,"hello");
// string a=v[2];
// cout <<a <<endl;
// return 0;
//add element
// string word;
// std::vector<string> text;
// while(cin>>word)
// text.push_back(word);
// vector<int> ivec;
// for(vector<int>::size_type ix=0;ix!=10;++ix)
// {
// ivec.push_back(ix);
// cout<<ivec[ix]<<endl;
// }
// for(vector<int>::iterator iter = ivec.begin();iter!=ivec.end();++iter)
// {
// cout<<*iter;
// *iter = 0;
// cout<<*iter <<endl;
// }
// return 0;
// for(vector<int>::const_iterator iter = ivec.begin();iter!=ivec.end();++iter)
// {
// cout<<*iter;
// }
// return 0;
//bitset, right to left
bitset<16> bitvet1 (0xffff);
bitset<32> bitvet2 (0xffff);
bitset<128> bitvet3 (0xffff);
cout << bitvet1<<endl;
cout << bitvet2<<endl;
cout << bitvet3<<endl;
string strval("1100");
bitset<32> bitvec4(strval);
cout<<bitvec4<<endl;
string str("1111111011101000000011");
bitset<32> bitvec5(str,5,4);
bitset<32> bitvec6(str,str.size()-4);
cout<<bitvec5<<endl;
cout<<bitvec6<<endl;
return 0;
}
| true |
7a1e8695c507312ec70a497f32549e65c29a5ace | C++ | grayengineering425/HomeAiAutomation | /VideoStream/VideoStream/Camera.cpp | UTF-8 | 1,868 | 2.703125 | 3 | [] | no_license | #include "Camera.h"
#include "Frame.h"
#include <filesystem>
ICamera::ICamera () = default;
ICamera::~ICamera() = default;
bool ICamera::isActive() const { return active; }
//-------------------------------------------------------------//
Camera::Camera(int cameraIndex, std::string name)
: ICamera ()
, windowName(name)
, cap (0)
{
dWidth = cap.get(cv::CAP_PROP_FRAME_WIDTH );
dHeight = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
cv::namedWindow(windowName);
}
Camera::~Camera() = default;
void Camera::startCamera()
{
active = true;
while (active)
{
cv::Mat frame;
if (!cap.read(frame))
{
std::cout << "Camera disconnected!\n";
continue;
}
{
std::lock_guard<std::mutex> guard(mutex);
if (eventNewFrame) eventNewFrame(std::make_shared<Frame>(frame));
}
}
}
void Camera::stopCamera()
{
active = false;
}
//---------------------------------------------------------------------------------------------
CameraSimulator::CameraSimulator()
: ICamera ()
, directoryPath (L"C:/users/graye/Pictures/jre")
, currentIndex (0)
{
loadFrames();
}
CameraSimulator::~CameraSimulator() = default;
void CameraSimulator::startCamera()
{
active = true;
if (frames.empty()) return;
while (active)
{
auto frame = frames[currentIndex++];
if (currentIndex >= frames.size()) currentIndex = 0;
if (eventNewFrame) eventNewFrame(frame);
std::this_thread::sleep_for(std::chrono::milliseconds(60));
}
}
void CameraSimulator::stopCamera()
{
active = false;
}
void CameraSimulator::loadFrames()
{
std::experimental::filesystem::directory_iterator it(directoryPath);
for (const auto& dir : it)
{
if (std::experimental::filesystem::exists(dir))
{
std::experimental::filesystem::path p(dir);
auto loadedImage = cv::imread(p.string());
frames.emplace_back(std::make_shared<Frame>(loadedImage));
}
}
}
| true |
43b952d5b9a982261e5f01ba8383a8b956d8ab6f | C++ | LuHeFr/cpp-course | /05_rational/rational.cpp | UTF-8 | 133 | 3.171875 | 3 | [] | no_license | unsigned int gcd(unsigned int x, unsigned int y) {
while (y != 0) {
auto tmp = y;
y = x % y;
x = tmp;
}
return x;
} | true |
519cc4b5418e49a52921543bb38b8e9b5ebcf73b | C++ | snow-cube/Luogu_OJ_code | /P1423.cpp | UTF-8 | 278 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
double goal, length = 2, step_len = 2;
int steps = 1;
cin >> goal;
while (length < goal) {
step_len *= 0.98;
length += step_len;
steps++;
}
cout << steps;
return 0;
} | true |
964377260a04b79e21b439bdf26e657cfa2acb1e | C++ | bit-zll/cpp | /20200731/test.cpp | GB18030 | 3,342 | 3.46875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include "Student.h"
#include <iostream>
#include <string.h>
using namespace std;
//class A1
//{
//public:
// void f1(){}
//private:
// int _a;
// char _b;
//};
//class A2
//{
//public:
// void f2(){}
//};
//class A3
//{};
//struct A
//{
// int a;
// char b;
// double c;
// char d;
//};
//int main()
//{
// cout << sizeof(A1) << endl;
// cout << sizeof(A2) << endl;
// cout << sizeof(A3) << endl;
//
// A3 a1, a2, a3;
// cout << &a1 << " " << &a2 << " " << &a3 << endl;
//
// cout << offsetof(A, b) << endl;
// cout << offsetof(A, c) << endl;
// return 0;
//}
// ע⣺C++У۾IJһ----ڴ͵͵
// ÿ"Ա"һĬϵIJòʱʱָ̿øóԱĶòΪthisָ
// ע⣺صthisָDZڱڼԶϵ,ûҪӣҲҪ
//class Student
//{
//public:
// void SetStudentInfo(/*Student const this*/char name[], char gender[], int age);
// //{
// // //this=nullptr; thisָָ
// // strcpy(this->_name, name);
// // strcpy(this->_gender, gender);
// // this->_age = age;
// //}
// //void PrintStudentInfo(/*Student const this*/)
// //{
// // cout << this->_name << "-" << this->_gender << "-" << this->age << endl;
// //}
//public:
// char _name[20];
// char _gender[3];
// int _age;
//};
//int main()
//{
// Student s1, s2, s3;
//
// // thisָûаڶУӰĴСDZԱӵһֲָͬ
// cout << sizeof(s1) << endl;
//
// //thisָĴݷʽ
// // 1. òбݵ
// // 2. һòͨecxĴݵ
// // ע⣺һ³ԱDZthis_callԼΣthis_callԼεijԱ
// // thisָͨecxĴ, _cdeclԼεijԱthisͨѹջķʽ
// return 0;
//}
// CУǴôдôԴκ--㿴ľDZִе
//#include <stdio.h>
//#include <string.h>
//typedef struct Student
//{
// char name[20];
// char gender[3];
// int age;
//}Student;
//
//void SetStudentInfo(Student* this, char name[], char gender[], int age)
//{
// strcpy(this->name, name);
// strcpy(this->gender, gender);
// this->age = age;
//}
//void PrintStudentInfo(Student* this)
//{
// printf("%s %s %d", this->name, this->gender, this->age);
//}
//int main()
//{
// Student s1, s2, s3;
// SetStudentInfo(&s1, "ܴ","", 5);
// SetStudentInfo(&s2, "ܶ","ĸ", 4);
// SetStudentInfo(&s3, "ǿ", "", 28);
//
// PrintStudentInfo(&s1);
// PrintStudentInfo(&s2);
// PrintStudentInfo(&s3);
// return 0;
//}
void Student::SetStudentInfo(char name[], char gender[], int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
void Student::PrintStudentInfo()
{
cout << _name << "-" << _gender << "-" << _age << endl;
}
int main()
{
Student s1, s2;
s1.SetStudentInfo("Ű", "", 25);
s2.SetStudentInfo("", "Ů", 24);
s1.PrintStudentInfo();
s2.PrintStudentInfo();
return 0;
} | true |
84a5fa380147224637425dd051458f6bd3c52295 | C++ | ddarkclay/programming-cookbook | /C++ Programs/Class/18_areaofcircle.cpp | UTF-8 | 519 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
class aoc
{
private:
int r;
float pi,area;
public:
void check()
{
pi=3.14;
cout<<"Enter the radius of a circle : ";
cin>>r;
area=r*r*pi;
cout<<"\n\nThe Area of the circle is = "<<area;
}
};
int main()
{
aoc a1;
a1.check();
getch();
return 0;
}
| true |
410d3ffb1c147b2cb541ccc346d5ec0dfdf26f27 | C++ | TzeHimSung/AcmDailyTraining | /Leetcode/1248.cpp | UTF-8 | 360 | 2.734375 | 3 | [] | no_license | class Solution {
public:
int numberOfSubarrays(vector<int> &nums, int k) {
vector<int> cnt(nums.size() + 1, 0);
int currSum = 0, ans = 0;
cnt[0] = 1;
for (auto x : nums) {
currSum += x & 1;
cnt[currSum]++;
if (currSum >= k) ans += cnt[currSum - k];
}
return ans;
}
};
| true |
607b13547a01d88aca56040a3a94b160c7795237 | C++ | monsty/licenserecognizer | /Server/myclient.cpp | UTF-8 | 2,880 | 2.59375 | 3 | [] | no_license | #include "myclient.h"
MyClient::MyClient(QObject *parent) :
QObject(parent)
{
QThreadPool::globalInstance()->setMaxThreadCount(5);
isLoggedIn = false;
}
void MyClient::SetSocket(int Descriptor)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
socket->setSocketDescriptor(Descriptor);
qDebug() << "client connected";
}
void MyClient::connected()
{
}
void MyClient::disconnected()
{
qDebug() << "client disconnected";
}
void MyClient::readyRead()
{
QByteArray Datas = socket->readAll();
QList<QByteArray> DatasList = Datas.split('\n');
qDebug() << "received:" << Datas;
if (DatasList[0][0] == '1')
{
qDebug() << " Launch login task ";
QByteArray LoginPass = Datas.mid(1);
QList<QByteArray> res = LoginPass.split('\n');
qDebug() << " Login: " << res[0];
qDebug() << " Pass: " << res[1];
LoginTask *logintask = new LoginTask(res[0], res[1]);
logintask->setAutoDelete(true);
connect(logintask, SIGNAL(Result(int)), this, SLOT(TaskResult(int)), Qt::QueuedConnection);
QThreadPool::globalInstance()->start(logintask);
}
else if (DatasList[0][0] == '2')
{
qDebug() << " Launch getPic task ";
QByteArray newRec;
int size = DatasList[1].toInt();
int received = Datas.length();
while(received < size)
{
newRec = socket->readAll();
socket->waitForReadyRead(300);
received += newRec.length();
Datas += newRec;
}
Datas.remove(0, 2 + DatasList[1].length() + 1);
QString tmp_path(QDir::currentPath());
tmp_path.append(QDir::separator()).append("temp_file.jpg");
QFile file(QDir::toNativeSeparators(tmp_path));
file.open(QIODevice::WriteOnly);
file.write(Datas);
file.close();
GetPicTask *pictask = new GetPicTask(tmp_path);
pictask->setAutoDelete(true);
connect(pictask, SIGNAL(Result(QString)), this, SLOT(TaskResult(QString)), Qt::QueuedConnection);
QThreadPool::globalInstance()->start(pictask);
qDebug() << "Trying to save" << QDir::toNativeSeparators(tmp_path);
qDebug() << "File size expected" << size;
qDebug() << "File size received " << Datas.length();
}
else
{
qDebug() << " Launch other task ";
}
}
void MyClient::TaskResult(int Number)
{
QByteArray Buffer;
Buffer.append(QString::number(Number));
if (Number == 1)
isLoggedIn = true;
socket->write(Buffer);
}
void MyClient::TaskResult(QString Plate)
{
QByteArray Buffer;
Buffer.append(Plate);
socket->write(Buffer);
}
| true |
8d89e93f290528c2a1d59d2d24eb6f3b50c9d431 | C++ | khlebous/milling-machine-5C | /Engine/src/Graphics/Buffers/VertexBuffer.h | UTF-8 | 2,202 | 2.671875 | 3 | [] | no_license | #pragma once
#include "pch.h"
namespace fe
{
class VertexBuffer
{
private:
Microsoft::WRL::ComPtr<ID3D11Buffer> buffer;
UINT stride;
UINT vertexCount = 0;
public:
VertexBuffer() {}
ID3D11Buffer* Get()const
{
return buffer.Get();
}
ID3D11Buffer* const* GetAddressOf()const
{
return buffer.GetAddressOf();
}
UINT VertexCount() const
{
return this->vertexCount;
}
const UINT Stride() const
{
return this->stride;
}
const UINT* StridePtr() const
{
return &this->stride;
}
HRESULT Initialize(ID3D11Device* _device, void* _data, UINT _stride, UINT _vertexCount)
{
if (buffer.Get() != nullptr)
buffer.Reset();
this->stride = _stride;
this->vertexCount = _vertexCount;
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = stride * _vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData;
ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
vertexBufferData.pSysMem = _data;
HRESULT hr = _device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, this->buffer.GetAddressOf());
return hr;
}
HRESULT InitializeInstanced(ID3D11Device* _device, void* _data, UINT _stride, UINT _vertexCount)
{
if (buffer.Get() != nullptr)
buffer.Reset();
this->stride = _stride;
this->vertexCount = _vertexCount;
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = stride * _vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData;
ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
vertexBufferData.pSysMem = _data;
HRESULT hr = _device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, this->buffer.GetAddressOf());
return hr;
}
};
}
| true |
aee3de71a738fd1965e6fdbffa1c85e727016dce | C++ | gzhang8/klg2oni | /src/Utils/Resolution_depre.h | UTF-8 | 1,684 | 2.515625 | 3 | [] | no_license | /*
* This file is part of ElasticFusion.
*
* Copyright (C) 2015 Imperial College London
*
* The use of the code within this file and all code within files that
* make up the software that is ElasticFusion is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.imperial.ac.uk/dyson-robotics-lab/downloads/elastic-fusion/elastic-fusion-license/>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email researchcontracts.engineering@imperial.ac.uk.
*
*/
#ifndef RESOLUTION_H_
#define RESOLUTION_H_
#include <cassert>
class Resolution
{
public:
static const Resolution & getInstance(int width = 0,int height = 0);
const int & width() const
{
return imgWidth;
}
const int & height() const
{
return imgHeight;
}
const int & cols() const
{
return imgWidth;
}
const int & rows() const
{
return imgHeight;
}
const int & numPixels() const
{
return imgNumPixels;
}
private:
Resolution(int width, int height)
: imgWidth(width),
imgHeight(height),
imgNumPixels(width * height)
{
assert(width > 0 && height > 0 && "You haven't initialised the Resolution class!");
}
const int imgWidth;
const int imgHeight;
const int imgNumPixels;
};
#endif /* RESOLUTION_H_ */
| true |
602c7a911a4bcd26139b4148ec7b2b97a2b0da0e | C++ | jackiechen0708/Algorithm | /sort/MergeSort.cpp | UTF-8 | 845 | 3.265625 | 3 | [] | no_license | //
// Created by JackieChen on 16/10/13.
//
#include "MergeSort.h"
#include <iostream>
void MergeSort::merge(int *a, int p, int q, int r) {
int left[q-p+1+1];
int right[r-q+1];
//Copy Thus O(n)
for(int i=0;i<q-p+1;i++){
left[i]=a[p+i];
}
for(int i=0;i<r-q;i++){
right[i]=a[q+1+i];
}
left[q-p+1]=INT32_MAX;//Act as guard to minimize edge judgement
right[r-q]=INT32_MAX;
int ptr_l=0,ptr_r=0;
for(int i=0;i<r-p+1;i++){
if(left[ptr_l]<=right[ptr_r]){ //use <= but not < to make this sorting algorithm stable
a[p+i]=left[ptr_l++];
} else{
a[p+i]=right[ptr_r++];
}
}
}
void MergeSort::sort(int *a,int p,int r) {
if(p<r){
int mid=p/2+r/2;
sort(a,p,mid);
sort(a,mid+1,r);
merge(a,p,mid,r);
}
}
| true |
9e1466eebbcd292563bf8bc3354871fc817e3b83 | C++ | artash/sandbox | /algo/quick_sort.cpp | UTF-8 | 1,770 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cassert>
template<typename T>
void printArray(const std::vector<T>& vec)
{
std::copy(vec.begin(), vec.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
template<typename T>
void swap(T& a, T& b)
{
T t = a;
a = b;
b = t;
}
template<typename T>
typename std::vector<T>::iterator partition(std::vector<T>& vec, typename std::vector<T>::iterator from, typename std::vector<T>::iterator to)
{
assert(distance(from, to) > 1);
T& pivot = *from;
typename std::vector<T>::iterator it1, it2;
it1 = it2 = from + 1;
for(; it1 != to; ++it1)
{
if (*it1 < pivot)
{
swap(*it1, *it2);
++it2;
}
}
--it2;
swap(pivot, *it2);
return it2;
}
template<typename T>
void quickSort(std::vector<T>& vec, typename std::vector<T>::iterator from, typename std::vector<T>::iterator to)
{
//printArray(vec);
//std::cout << "from=" << *from << " to-1=" << *(to-1) << std::endl;
//std::cout << "the distance is " << std::distance(from, to) << std::endl << std::endl;
if(std::distance(from, to) > 1)
{
typename std::vector<T>::iterator it = partition(vec, from, to);
quickSort(vec, from, it);
quickSort(vec, it + 1, to);
}
// if the distance is 1 there's nothing to do, it's a 0 or 1 element array which is already sorted
}
template<typename T>
void quickSort(std::vector<T>& vec)
{
quickSort(vec, vec.begin(), vec.end());
}
int main()
{
int unsorted[] = {15, 47, 478, 21, 78, 33, 6, 239, 0, 4, 2, 8, 33, 8, 45, 2, 1, 7, 9 };
std::vector<int> uv(unsorted, unsorted + sizeof(unsorted) / sizeof(int));
printArray(uv);
quickSort(uv);
// std::cout << *partition(uv, uv.begin(), uv.end()) << std::endl;
printArray(uv);
return 0;
}
| true |
3e82d81ea54830cc460a673f1a3ea955dbd71a32 | C++ | JaiAravindh-git/HactoberFest21 | /LeetCode Problems/C++/Minimum Absolute Difference in BST.cpp | UTF-8 | 447 | 3.0625 | 3 | [
"Unlicense"
] | permissive | class Solution {
public:
void inorder(TreeNode* root,vector<int> &v)
{
if(root==NULL)
return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
int getMinimumDifference(TreeNode* root) {
vector<int> v;
inorder(root,v);
int mini=INT_MAX;
for(int i=1;i<v.size();i++)
mini=min(mini,abs(v[i]-v[i-1]));
return mini;
}
};
| true |
8ce19352ea77f7055bfe25856e468b5583ee16a9 | C++ | nnghsa/Reactor | /ThreadPoll.h | UTF-8 | 1,313 | 2.65625 | 3 | [] | no_license | #pragma once
#include"EventHandler.h"
#include<pthread.h>
#include<functional>
#include<memory>
#include<vector>
const int THREADPOOL_INVALID = -1;
const int THREADPOOL_LOCK_FAILURE = -2;
const int THREADPOOL_QUEUE_FULL = -3;
const int THREADPOOL_SHUTDOWN = -4;
const int THREADPOOL_THREAD_FAILURE = -5;
const int THREADPOOL_GRACEFUL = 1;
const int MAX_THREADS = 1024;
const int MAX_QUEUE = 65535;
typedef enum
{
immediate_shutdown = 1,
graceful_shtudown = 2
}ShutDownOption;
struct ThreadPoolTask
{
std::function<void(std::shared_ptr<void>)>func;
std::shared_ptr<void>args;
};
class ThreadPool
{
private:
static pthread_mutex_t _lock;
static pthread_cond_t _notify;
static std::vector<pthread_t> _threads;
static std::vector<ThreadPoolTask>_queue;
static int _thread_count;
static int _queue_size;
static int _head;
static int _tail;
static int _count;
static int _shutdown;
static int _started;
public:
static int threadpool_create(int thread_count, int queue_size);
static int threadpool_free();
static int threadpool_add(std::shared_ptr<void>args, std::function<void(std::shared_ptr<void>)>fun);
static int threadpool_destroy(ShutDownOption shut_option = graceful_shtudown);
static void* threadpool_thread(void* args);
}; | true |
39b4c34c8b5af7238767f1f91852e3587ad0944d | C++ | jxie418/leetcodecpp | /palindromenumber.cpp | UTF-8 | 417 | 3.546875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Solution {
public:
bool isPalindrom(int x) {
if (x < 0)
return false;
int k = x;
int v = 0;
while(k > 0) {
v = v * 10 + k % 10;
k /=10;
}
return x == v;
}
};
int main() {
Solution s;
cout << s.isPalindrom(121)<<endl;
cout << s.isPalindrom(123)<<endl;
cout << "Done"<<endl;
return 0;
}
| true |
a184d5060b21b1bb6918669d0b1a0970f227a3f7 | C++ | mstmkn67/pem | /src/Frame.h | UTF-8 | 408 | 2.609375 | 3 | [] | no_license | #ifndef _FRAME_H_
#define _FRAME_H_
#include "Vector3d.h"
#include <cmath>
using namespace std;
class Frame{
public:
Frame();
Frame(const Vector3d& u1,const Vector3d& u2);
virtual ~Frame();
//
virtual void update();
virtual Vector3d operator()(int i)const;
Vector3d u1,u2,u3;
protected:
virtual void correct1();
virtual void correct2();
private:
};
#endif // _FRAME_H_
| true |
cc56bee824cc69a6ea72786bec27d0b006536d49 | C++ | tobyrobb/Xbee-Parachute | /ParachuteRX.ino | UTF-8 | 2,191 | 2.8125 | 3 | [] | no_license | // T robb
// for the arduino nano
#include <Servo.h>
#define servoPin 9
#define speakerPin 4
#define ledHeartbeatPin 5
#define ledActivationPin 6
#define buttonPin 7
Servo myservo; // create servo object to control a servo
int openPos = 0; // variable to store the servo position
int closePos = 180; // variable to store the servo position
String commandString = ""; //somewhere to put the command received
// these are the valid command strings we should recieve
String OPEN = "open";
String HEARTBEAT = "+";
void setup() {
Serial.begin(4800);
//Setup the pins
pinMode(servoPin, OUTPUT);
pinMode(speakerPin, OUTPUT);
myservo.attach(servoPin); // attaches the servo on pin 9 to the servo object
myservo.write(closePos); // tell servo to go to position in variable 'pos'
//Lets beep on successful BOOT
tone(speakerPin, 500);
delay(1000);
noTone(speakerPin);
//all done
Serial.println("Parachute release receiver - April 2016");
Serial.println("");
Serial.println(" Setup Complete");
}
void loop() {
//send a heartbeat
delay(10);
Serial.println(HEARTBEAT); //send heartbeat
//Serial.println("Heartbeat sent");
//Serial.print("Waiting for the OPEN command...Last message received was: ");
//Serial.println(commandString);
checkSerial();
delay(300);
}
void checkSerial(void){
String content = "";
char character;
while(Serial.available()) {
character = Serial.read();
content.concat(character);
if (content != "") {
//begin your command choices here
commandString = content; //copy the serial string into serialString
if (commandString == OPEN)
{
myservo.write(openPos); // tell servo to go to position in variable 'pos'
Serial.println("Opening Servo");
tone(speakerPin, 1500, 1000);
commandString == "";
delay(500);
}
if (commandString == HEARTBEAT)
{
//Serial.println("Connected");
tone(speakerPin, 50);
analogWrite(ledHeartbeatPin, 255);
commandString = "";
delay(100);
}
}
}
}
| true |
73a2c04f5eba2f3b6801adfa888ff9f93149c8fa | C++ | laughtrey/cis202 | /Midterm/addresslisting.h | UTF-8 | 388 | 2.703125 | 3 | [] | no_license | #ifndef ADDRESSLISTING_H
#define ADDRESSLISTING_H
#include <iostream>
#include <string>
class AddressListing {
private:
std::string m_name, m_address;
public:
AddressListing(const std::string& name, const std::string& address);
void set_name(const std::string& name);
void set_address(const std::string& address);
std::string get_name() const;
std::string get_address() const;
};
#endif
| true |
cff9e6c30da66e0ac8450ff712bebd74c21fa6a3 | C++ | marehr/cpp_template_external_linkage_test | /my_class.hpp | UTF-8 | 271 | 3.140625 | 3 | [] | no_license |
template <typename value_t>
class my_class
{
public:
my_class(value_t value) : _value{value}
{};
value_t value()
{
return _value;
}
private:
value_t _value;
};
extern template class my_class<char>;
extern template class my_class<int>;
| true |