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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dbcc333f5bd76ca9711efcf374054bb61e293f01 | C++ | hemang-h/C-Cpp-Programs | /src/Odd-even/code.cpp | UTF-8 | 280 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
int main()
{
int number = 0;
cout << "Enter integer number\n";
cin >> number;
if (number % 2 == 0) {
cout << "The value " << number << " is an even number.\n";
}
else {
cout << "The value " << number << " is an odd number.\n";
}
return 0;
}
| true |
057156818c3f153f2946967579d591711aa6aeca | C++ | thverney-dozo/Piscine-CPP | /C01/ex02/ZombieEvent.cpp | UTF-8 | 1,764 | 2.53125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ZombieEvent.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aeoithd <aeoithd@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/06 12:11:07 by aeoithd #+# #+# */
/* Updated: 2020/10/06 12:11:08 by aeoithd ### ########.fr */
/* */
/* ************************************************************************** */
#include "ZombieEvent.hpp"
#include "Zombie.hpp"
ZombieEvent::ZombieEvent(void) {};
ZombieEvent::~ZombieEvent(void) {};
void ZombieEvent::setZombieType(std::string _type)
{
this->_type = _type;
}
Zombie *ZombieEvent::newZombie(std::string _name)
{
return new Zombie(_name, this->_type);
}
void ZombieEvent::randomChump(void)
{
srand(time(0));
int i = rand();
std::string name;
if (i % 10 == 0)
name = "Rick the dead";
else if (i % 10 == 1)
name = "Unknown Zombie";
else if (i % 10 == 2)
name = "T-Bag";
else if (i % 10 == 3)
name = "Totorina";
else if (i % 10 == 4)
name = "Michael J";
else if (i % 10 == 5)
name = "Handsome Zombie";
else if (i % 10 == 6)
name = "Claris";
else if (i % 10 == 7)
name = "Nice Dude";
else if (i % 10 == 8)
name = "John Mc John";
else if (i % 10 == 9)
name = "Steve-Bie";
Zombie z = Zombie(name, this->_type);
} | true |
34739bb11c69ee11f3323fd1000eeb0ae957ddca | C++ | ctslater/mops_daymops | /include/lsst/mops/Track.h | UTF-8 | 5,861 | 2.515625 | 3 | [] | no_license | // -*- LSST-C++ -*-
/* jonathan myers
8/10/09
*/
#ifndef LSST_TRACK_H
#define LSST_TRACK_H
#include <set>
#include <vector>
#include <Eigen/Dense>
#include "gsl/gsl_cdf.h"
#include "MopsDetection.h"
#include "Tracklet.h"
namespace lsst { namespace mops {
/** \class Track Track.h "lsst/mops/Track.h"
\brief A linked set of detections which span multiple nights; possibly an asteroid
A track is really a set of *DETECTIONS*. We also allow the user to track the
*tracklets* which were used to build the track, but this is just for their
reference.
note that a track is this is not merely the union of the detections
associated with the tracklets associated with the; if the track contains two
tracklets which are in 'conflict' (contain multiple detections from the same
image time) then only one of the possible detections is chosen.
Note that detection are stored both as diaIds as well as indices into some
array of detections. The diaIds are written to file and used for provenance
as well as for computing whether two trackSets are equal or subsets of each
other; when running linkTracklets (or other algorithms) it is usually smart
to access the detections using indices into an array (as we can do this in
constant time, rather than a lookup which will take at least log time).
Use the utility function addDetection() and it will update both the
detectionIndices and detectionDiaIds appropriately.
It is up to the user to keep a Track's Detection Indices associated with the
same Detection vector throughout its lifetime; if you have two distinct
Detection vectors (currently this has no use case) and you create a track
using indices from one vector, then try to refer to the other vector using
indices from the same track you will get into trouble!
*/
class Track {
private:
void calculateBestFitRa(const std::vector<MopsDetection> &allDets,
const int forceOrder = -1,
std::ostream *outFile = NULL);
void calculateBestFitDec(const std::vector<MopsDetection> &allDets,
const int forceOrder = -1,
std::ostream *outFile = NULL);
public:
Track();
void addDetection(unsigned int detIndex, const std::vector<MopsDetection> & allDets);
/* Add a tracklet to the track; this will add the DETECTIONS of the tracklet
to the current track's detection set AND add the tracklet's given tracklet index
to componentTrackletIndices. Used in LinkTracklets to quickly add endpoint tracklets.
DO NOT BE MISLEAD: This is not the only way in which detection/tracklets
are added in linkTracklets. Support detections may be added without any
associated tracklets.
*/
void addTracklet(unsigned int trackletIndex,
const Tracklet &t,
const std::vector<MopsDetection> & allDets);
const std::set<unsigned int> getComponentDetectionIndices() const;
const std::set<unsigned int> getComponentDetectionDiaIds() const;
double getProbChisqRa() const { return probChisqRa; }
double getProbChisqDec() const { return probChisqDec; }
double getFitRange() const;
/* until this function is called, initial position, velocity and
acceleration for the track are NOT SET. the USER is responsible for
calling before using predictLocationAtTime() or getBestFitQuadratic().
*/
void calculateBestFitQuadratic(const std::vector<MopsDetection> &allDets,
const int forceOrder = -1,
std::ostream *outFile = NULL);
/* use best-fit quadratic to predict location at time mjd. will return WRONG VALUES
if calculateBestFitQuadratic has not been called.*/
void predictLocationAtTime(const double mjd, double &ra, double &dec) const;
/* use best-fit quadratic to predict location uncertainty at time mjd. will return WRONG VALUES
if calculateBestFitQuadratic has not been called.*/
void predictLocationUncertaintyAtTime(const double mjd, double &raUnc, double &decUnc, const bool calcRa=true, const bool calcDec=true) const;
/* you MUST call calculateBestFitQuadratic before calling this. */
void getBestFitQuadratic(double &epoch,
double &ra0, double &raV, double &raAcc,
double &dec0, double &decV, double &decAcc) const;
/*
the tracklets which were used to build this track, if any. Currently this
information is not used but could be useful for debugging or investigation.
*/
std::set<unsigned int> componentTrackletIndices;
Track & operator= (const Track &other);
bool operator==(const Track &other) const {
bool toRet = componentDetectionDiaIds == other.componentDetectionDiaIds;
return toRet ;
}
bool operator!=(const Track &other) const {
return ! (*this == other);
}
int getObjectId(const std::vector<MopsDetection> &allDets);
/* the results of this comparison are probably not meaningful to a human but
* this operator is needed for building container classes for this class */
bool operator<(const Track &other) const {
bool toRet = componentDetectionDiaIds < other.componentDetectionDiaIds;
return toRet;
}
private:
std::set<unsigned int> componentDetectionIndices;
std::set<unsigned int> componentDetectionDiaIds;
Eigen::VectorXd raFunc;
Eigen::VectorXd decFunc;
Eigen::MatrixXd raCov;
Eigen::MatrixXd decCov;
double chisqRa;
double chisqDec;
double probChisqRa;
double probChisqDec;
double epoch;
double meanTopoCorr;
};
}} // close lsst::mops namespace
#endif
| true |
a58fba693c5b3f214a856667534dccf7464382c6 | C++ | Hatcher/CSCI-6221 | /W4A1/src/W4A1.cpp | UTF-8 | 1,797 | 3.796875 | 4 | [] | no_license | //============================================================================
// Name : W4A1.cpp
// Author : Anderson Thomas
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <time.h>
using namespace std;
/*
* Write two functions in C++:
* 1) one that declares a large array on the stack
* 2) and one that creates the same large array from the heap.
*
* Call each of the functions a large number of times (> 100k times) and
* output the time required by each. Explain the results.
*/
/*
* In C++, when you use the new operator to allocate memory,
* this memory is allocated in the application’s heap segment.
*/
void heapArray(int inputArraySize){
int *arr = new int[inputArraySize];
delete [] arr;
}
void stackArray(int inputArraySize){
int arr [inputArraySize];
}
int main() {
int arraySize = 1000;
int totalCallsToMake = 100009;
double timeToMakeHeapArray = 0;
for(int i = 0; i < totalCallsToMake; i++){
clock_t begin = clock();
heapArray(arraySize);
clock_t end = clock();
timeToMakeHeapArray = timeToMakeHeapArray + double(end-begin)/CLOCKS_PER_SEC;
}
cout << "The time to make " << totalCallsToMake << " arrays, of size " << arraySize << ", on the heap was " << timeToMakeHeapArray << endl;
double timeToMakeStackArray = 0;
for(int i = 0; i < totalCallsToMake; i++){
clock_t begin = clock();
stackArray(arraySize);
clock_t end = clock();
timeToMakeStackArray = timeToMakeStackArray + double(end-begin)/CLOCKS_PER_SEC;
}
cout << "The time to make " << totalCallsToMake << " arrays, of size " << arraySize << ", on the stack was " << timeToMakeStackArray << endl;
return 0;
}
| true |
afc02bacfa2fe7292ec6150894f8e85b92dc3b6c | C++ | ShakedY/ex4 | /server/Server.cpp | UTF-8 | 6,305 | 2.828125 | 3 | [] | no_license | #include "Server.h"
#include <stdlib.h>
#define BUFFSIZE 1024
volatile int running_threads = 0;
Server::Server(int argc, char* argv[]) :
factory()
{
//Create Udp socket.Port will be in command line arguments.
socket = new Tcp(1, atoi(argv[1]));
socket->initialize();
StringInput input(argc, argv);
input.readMapInfo();
createMap(input);
mainLoop(input);
}
Server::~Server()
{
delete center;
delete map;
}
Cab* Server::createCab(StringInput::CabInfo cabsInfo)
{
//Create a cab with the CabFactory object.
return factory.generateCab(cabsInfo.id, cabsInfo.taxi_type, cabsInfo.color,
cabsInfo.manufacturer);
}
Trip* Server::createTrip(StringInput::TripInfo tripInfo)
{
//Create a new trip based on the TripInfo.
Point start(tripInfo.x_start, tripInfo.y_start), end(tripInfo.x_end,
tripInfo.y_end);
return new Trip(tripInfo.id, tripInfo.num_passengers, start, end,
tripInfo.tariff, tripInfo.time);
}
void Server::createMap(StringInput& info)
{
//Create a new map based on the info entered in StringInfo.
list<Point> obstacles = *(info.gridInfo.obstacles);
map = Map::getInstance(info.gridInfo.width, info.gridInfo.height,
*(info.gridInfo.obstacles));
}
void Server::mainLoop(StringInput& info)
{
//Create our TaxiCenter.
center = TaxiCenter::getInstance(map);
int answer, driver_id;
char garbage;
const Point* location;
Trip *tmp;
do
{
if (0 == scanf("%d", &answer))
{
// Discard everything up to and including the newline.
while ((garbage = getchar()) != EOF && garbage != '\n')
;
continue;
}
switch (answer)
{
case 1:
//Get number of drivers from the user.
getNumDrivers();
break;
case 2:
//Case 2,get Trip from the console and add it to the TaxiCenter.
info.getTripInfo();
tmp = createTrip(info.tripInfo);
center->addTrip(tmp);
break;
case 3:
//Case 3,get Cab from the console and add it to the TaxiCenter.
info.getCabInfo();
center->addCab(createCab(info.cabInfo));
break;
case 4:
//Case 4,get id of driver and print it's location.
scanf("%d", &driver_id);
location = center->getDriverLocation(driver_id);
if (location != NULL)
{
cout << *location << endl;
}
break;
case 9:
//Tell the TaxiCenter to move all the drivers by one step.
center->moveAllOneStep();
break;
default:
// no such option
break;
}
} while (answer != 7);
//Send shutdown to all the clients.
center->endWorking();
}
void Server::getNumDrivers()
{
int numDrivers;
pthread_t currentThread;
Param* currentStruct;
//Scan the number of drivers from the console.
scanf("%d", &numDrivers);
running_threads = numDrivers;
GlobalInfo* global = GlobalInfo::getInstance(numDrivers);
//Now we expect to get the drivers through the socket and send them cabs.
while (numDrivers-- != 0)
{
// Deserialize the data.
//Move accept of client to a thread so we will be able to get clients at once.
currentStruct = new Param;
currentStruct->serverSocket = socket;
//Set up the mutex lock.
pthread_mutex_init(&(currentStruct->locker), 0);
//Create thread for running the code blocking accept.
pthread_create(¤tThread, NULL, Server::manageClient,
currentStruct);
}
sleep(1);
//Wait for all the threads to accept all the clients.
while (running_threads > 0)
{
sleep(1);
}
center->attachCabsToDrivers();
}
void* Server::manageClient(void * params)
{
Param* parameters = (Param*) params;
Socket* mySocket = parameters->serverSocket;
pthread_mutex_t lock = parameters->locker;
Tcp* clientSocket;
Driver* drv;
TaxiCenter* myCenter = TaxiCenter::getInstance();
int size;
char buffer[BUFFSIZE];
RemoteDriver* currentDriver;
GlobalInfo* global = GlobalInfo::getInstance();
//Get descriptor of client.
clientSocket = ((Tcp*) mySocket)->acceptClient();
size = clientSocket->reciveData(buffer, BUFFSIZE);
drv = Server::deSerializeObj<Driver>(buffer, size);
//Create the new remote driver.
currentDriver = new RemoteDriver(drv, clientSocket);
//Remote driver saved all of the driver's data so delete the driver.
delete drv;
//Add the RemoteDriver to the TaxiCenter.
//We will lock before adding to prevent severe cases.
pthread_mutex_lock(&lock);
//Decrease the number of threads to know we got the client.
myCenter->addDriver(currentDriver);
running_threads--;
pthread_mutex_unlock(&lock);
//Now we will wait until there is a cab to send.
while (global->getIthCab(currentDriver->getId()) == NULL)
{
//Loop until there is a cab.
sleep(1);
}
//There is a cab we will aply it to the RemoteDriver.
currentDriver->setCab(global->getIthCab(currentDriver->getId()));
//Set the pointer in the GlobalInfo to be null to prevent bugs.
global->setIthCab(currentDriver->getId(), NULL);
//Now we will wait for the trip,because there could be a lot of trips for a driver
//we will store the loop that waits for a trip in a function.
//Destroy the mutex lock.
waitForTrip(currentDriver,lock);
pthread_mutex_destroy(&lock);
return NULL;
}
void Server::waitForTrip(Driver* driver,pthread_mutex_t lock)
{
GlobalInfo* global = GlobalInfo::getInstance();
Trip* myTrip;
while (!global->getIthTrip(driver->getId()))
{
//Sleep until there is a trip.
if (global->toExit())
{
return;
}
sleep(1);
}
myTrip = global->getIthTrip(driver->getId());
global->setIthTrip(driver->getId(), NULL);
driver->setTrip(myTrip);
//pthread_mutex_unlock(&lock);
Server::waitForTrip(driver,lock);
}
template<class T>
void Server::serializeObj(std::string* serial_str, T* obj)
{
//Serialize an object same as recitations examples.
boost::iostreams::back_insert_device<std::string> inserter(*serial_str);
boost::iostreams::stream<boost::iostreams::back_insert_device<std::string> > s(
inserter);
boost::archive::binary_oarchive oa(s);
oa << obj;
s.flush();
}
template<class T>
T* Server::deSerializeObj(const char* serial_str, int size)
{
//Deserialize an object same as recitations examples.
T* obj;
boost::iostreams::basic_array_source<char> device(serial_str, size);
boost::iostreams::stream<boost::iostreams::basic_array_source<char> > s(
device);
boost::archive::binary_iarchive ia(s);
ia >> obj;
return obj;
}
int main(int argc, char* argv[])
{
Server flow(argc, argv);
return 0;
}
| true |
7bd49c406ebdd0fe04ef46b52478367b1d905c0f | C++ | ClaraShar/csp | /小试牛刀/棋局评估.cpp | UTF-8 | 2,458 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int mp[4][4];//map为棋盘
bool row(int r,int tag){
return mp[r][0]==tag && mp[r][0]==mp[r][1] && mp[r][1]==mp[r][2]; //判断行是否三颗相连
}
bool col(int c,int tag){
return mp[0][c]==tag && mp[0][c]==mp[1][c] && mp[1][c]==mp[2][c]; //判断列是否三颗相连
}
int space(){
int res=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(!mp[i][j])
res++;
return res;
}
int win(int tag){//tag为当时下棋的人,判断当前局面胜负情况,看是否已经是赢的局面了
int wi=0,ans;
if(row(0,tag)||row(1,tag)||row(2,tag)) wi=1;
if(col(0,tag)||col(1,tag)||col(2,tag)) wi=1;
if(mp[0][0]==tag && mp[0][0]==mp[1][1] && mp[1][1]==mp[2][2])wi=1;//对角线
if(mp[0][2]==tag && mp[0][2]==mp[1][1] && mp[1][1]==mp[2][0])wi=1;
if(!wi)//wi标志是否是有人赢的局面
return 0;
ans=space()+1;
return (tag==1)?ans:-ans;//返回分数
}
int DFS(int peo){ //对抗搜索
if(!space())
return 0;//下满了,结束
int Max=-10,Min=10;//0-Alice-Max,1-Bob-Min
for(int i=0;i<3;i++)
{
for(int j=0,w;j<3;j++)
{
if(!mp[i][j])//如果当前格子为空
{
mp[i][j]=peo+1;//下棋的人,1为X,2为O
w=win(peo+1);//计算当前可以赢吗?
if(w)//如果可以赢
{
mp[i][j]=0;//回溯
return w>0?max(Max,w):min(Min,w);//看得分是正是负?
}
//如果当前还不能赢
if(!peo)
Max=max(Max,DFS(1));//Alice得分最大
else
Min=min(Min,DFS(0));//Bob得分最小
mp[i][j]=0;//回溯
}
}
}
return peo?Min:Max;//0-Alice-Max,1-Bob-Min
}
int main()
{
int T;
cin>>T;//注意可能是文件
while(T--){
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
cin>>mp[i][j];
int x=win(1),y=win(2);//判断是否已经有人赢了
if(x){cout<<x<<endl;continue;}
if(y){cout<<y<<endl;continue;}
cout<<DFS(0)<<endl; //不是的话,Alice先下(0表示Alice下,1表示Bob下)
}
return 0;
} | true |
ade744ce8a5fb646e19de6135c8d3c7000df81d4 | C++ | AleksanderKirintsev/study | /Olymp/HSE/2019/11/lvl1/A/simple.cpp | UTF-8 | 572 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
string a,b,c;
bool F(string v, string u) {
for(int i = 0; i <= int(u.size()) - int(v.size()); i++){
string x = u.substr(i,v.size());
if(v == x)
return 1;
}
return 0;
}
int main() {
cin >> a >> b >> c;
string ans;
for(int i = 0; i < a.size(); i++)
for(int j = i; j < a.size(); j++) {
string tmp = a.substr(i,j-i+1);
ans = (tmp.size() > ans.size() && F(tmp,b) && F(tmp,c) ? tmp : ans);
}
cout << ans;
return 0;
}
| true |
efe5cec6f206311623d23f444b42bfec540a5005 | C++ | aman1228/LeetCode | /Algorithms/longest-common-prefix.cpp | UTF-8 | 815 | 3.546875 | 4 | [] | no_license | 14. Longest Common Prefix
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
return f1(strs, 0, strs.size());
}
private:
string f1(vector<string>& strs, int begin, int end) {
if (begin == end) {
return "";
}
if (begin + 1 == end) {
return strs[begin];
}
int mid = begin + (end - begin) / 2;
string a = f1(strs, begin, mid), b = f1(strs, mid, end);
string result;
int sz = min(a.size(), b.size()), i = 0;
while (i < sz and a[i] == b[i]) {
result.push_back(a[i]);
++i;
}
return result;
}
}; | true |
7ae4697f86bcfa3cbb33267f28d61abcb6b2bfb1 | C++ | kesar/reward-contract | /reward/src/reward.cpp | UTF-8 | 1,703 | 2.6875 | 3 | [] | no_license | #include <reward/reward.hpp>
void reward::claim()
{
stats stat(_self, 0);
const auto& record = stat.get(0);
auto time = current_time_point().sec_since_epoch();
check(time > record.last_claimed + TIME_TO_CLAIM, "need more time to claim");
if (record.quantity.amount > 0) {
auto dev_amount = record.quantity * PERCENTAGE_DEV / 100;
action(permission_level{_self, "active"_n}, EOS_CONTRACT, "transfer"_n, make_tuple(_self, DEV_ACCOUNT, dev_amount, string("claim reward"))).send();
action(permission_level{_self, "active"_n}, EOS_CONTRACT, "transfer"_n, make_tuple(_self, COMPANY_ACCOUNT, (record.quantity - dev_amount), string("claim reward"))).send();
}
stat.modify(record, same_payer, [time](auto &a) {
a.last_claimed = time;
a.quantity = asset(0, EOS_SYMBOL);
});
}
// EOS
void reward::transfer(const name &from, const name &to, const asset &quantity, const string &memo)
{
require_auth(from);
if (from == _self) {
return;
}
check(EOS_CONTRACT == get_first_receiver(), "invalid contract");
check(to == _self, "contract is not involved in this transfer");
check(quantity.symbol.is_valid(), "invalid quantity");
check(quantity.amount > 0, "only positive quantity allowed");
check(quantity.symbol == EOS_SYMBOL, "only EOS tokens allowed");
stats stat(_self, 0);
auto record = stat.find(0);
if (record == stat.end()) {
stat.emplace(_self, [&](auto &a) {
a.last_claimed = 0;
a.quantity = quantity;
});
}
else {
stat.modify(record, same_payer, [quantity](auto &a) {
a.quantity += quantity;
});
}
}
| true |
93f2fde7b90f35d6020e58ebadc4f04e33d99777 | C++ | SyouheiKobayashi/Kobayashi_Shouhei_GAMEs | /吉田学園情報ビジネス専門学校@小林将兵/C言語/<2>2Dアクション/ソースコード/title.cpp | SHIFT_JIS | 6,490 | 2.53125 | 3 | [] | no_license | //=========================================================================
// ^Cgʂ̏ [title.cpp]
// Author:Kobayashi/
//=========================================================================
#include "main.h" //C
#include "title.h" //^Cg
#include "input.h" //͏
#include "fade.h" //tF[hʐւ
//=========================================================================
//}N
//=========================================================================
#define T_TYPE (2)//wi̖
#define Title_TEXTURENAME "DATA\\TEXTURE\\wiP_.jpg"//ǂݍރeNX`
#define Title_TEXTURENAME2 "DATA\\TEXTURE\\^Cg.png"//ǂݍރeNX`
#define Title_POS_X (0) //wi̍XW
#define Title_POS_Y (0) //wi̍YW
#define Title_WIDTH (SCREEN_WIDTH) //wi̕
#define Title_HEIGHT (SCREEN_HEIGHT) //wi̍
//=========================================================================
//O[o
//=========================================================================
LPDIRECT3DTEXTURE9 g_pTextureTitle[T_TYPE] = {}; //eNX`ւ̃|C^
LPDIRECT3DVERTEXBUFFER9 g_pVtxBuffTitle = NULL; //_obt@ւ̃|C^
int g_ScrollAnim;
//=========================================================================
//^Cg /
//=========================================================================
void InitTitle(void)
{
g_ScrollAnim = 0;
LPDIRECT3DDEVICE9 pDevice; //foCXւ̃|C^
pDevice = GetDevice(); //foCX̏
//eNX`̓ǂݍ
D3DXCreateTextureFromFile(pDevice, Title_TEXTURENAME, &g_pTextureTitle[0]);//wip
D3DXCreateTextureFromFile(pDevice, Title_TEXTURENAME2, &g_pTextureTitle[1]);//^Cg
//_obt@̐
pDevice->CreateVertexBuffer(sizeof(VERTEX_2D) * 4 * T_TYPE,
D3DUSAGE_WRITEONLY,
FVF_VERTEX_2D,
D3DPOOL_MANAGED,
&g_pVtxBuffTitle,
NULL);
VERTEX_2D*pVtx; //_ւ̃|C^
//_obt@bNA_f[^ւ̃|C^
g_pVtxBuffTitle->Lock(0, 0, (void**)&pVtx, 0);
for (int nCntT = 0; nCntT < T_TYPE; nCntT++)
{
//_W̐ݒ
pVtx[0].pos = D3DXVECTOR3(Title_POS_X, Title_POS_Y, 0.0f);
pVtx[1].pos = D3DXVECTOR3(Title_POS_X + Title_WIDTH, Title_POS_Y, 0.0f);
pVtx[2].pos = D3DXVECTOR3(Title_POS_X, Title_POS_Y + Title_HEIGHT, 0.0f);
pVtx[3].pos = D3DXVECTOR3(Title_POS_X + Title_WIDTH, Title_POS_Y + Title_HEIGHT, 0.0f);
//rhw̐ݒ
pVtx[0].rhw = 1.0f;
pVtx[1].rhw = 1.0f;
pVtx[2].rhw = 1.0f;
pVtx[3].rhw = 1.0f;
//_J[̐ݒ
pVtx[0].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[1].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[2].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[3].col = D3DCOLOR_RGBA(255, 255, 255, 255);
//eNX`W̐ݒ
pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f);
pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f);
//--------------------
//^Cg
//--------------------
//_W̐ݒ
pVtx[4].pos = D3DXVECTOR3(0, 0, 0.0f);
pVtx[5].pos = D3DXVECTOR3(Title_WIDTH, 0, 0.0f);
pVtx[6].pos = D3DXVECTOR3(0, Title_HEIGHT, 0.0f);
pVtx[7].pos = D3DXVECTOR3(Title_WIDTH, Title_HEIGHT, 0.0f);
//rhw̐ݒ
pVtx[4].rhw = 1.0f;
pVtx[5].rhw = 1.0f;
pVtx[6].rhw = 1.0f;
pVtx[7].rhw = 1.0f;
//_J[̐ݒ
pVtx[4].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[5].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[6].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[7].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[4].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[5].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[6].tex = D3DXVECTOR2(0.0f, 1.0f);
pVtx[7].tex = D3DXVECTOR2(1.0f, 1.0f);
}
//_obt@AbN
g_pVtxBuffTitle->Unlock();
}
//=========================================================================
//^Cg / I
//=========================================================================
void UninitTitle(void)
{
for (int nCnt = 0; nCnt < T_TYPE; nCnt++)
{
if (g_pTextureTitle[nCnt] != NULL)
{
g_pTextureTitle[nCnt]->Release();
g_pTextureTitle[nCnt] = NULL;
}
}
//_obt@̔j
if (g_pVtxBuffTitle != NULL)
{
g_pVtxBuffTitle->Release();
g_pVtxBuffTitle = NULL;
}
}
//=========================================================================
//^Cg / XV
//=========================================================================
void UpdateTitle(void)
{
g_ScrollAnim++;
VERTEX_2D*pVtx;//_ւ̃|C^
//_obt@bNA_f[^ւ̃|C^
g_pVtxBuffTitle->Lock(0, 0, (void**)&pVtx, 0);
pVtx[0].tex = D3DXVECTOR2(0.0f + (0.0005f * g_ScrollAnim), 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f + (0.0005f * g_ScrollAnim), 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f + (0.0005f * g_ScrollAnim), 1.0f);
pVtx[3].tex = D3DXVECTOR2(1.0f + (0.0005f * g_ScrollAnim), 1.0f);
if (pVtx[0].tex.x < 0.0f)
{
pVtx[0].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[3].tex = D3DXVECTOR2(0.0f, 0.0f);
}
if (pVtx[2].tex.x < 0.0f)
{
pVtx[2].tex = D3DXVECTOR2(1.0f, 1.0f);
pVtx[1].tex = D3DXVECTOR2(0.0f, 1.0f);
}
pVtx += 4;
//_obt@AbN
g_pVtxBuffTitle->Unlock();
FADE pFade;
pFade = GetFade();
if (pFade == FADE_NONE)
{
if (GetKeyboardTrigger(DIK_RETURN) == true)
{
//[h̐ݒ
SetFade(MODE_TUTORIAL);
}
}
}
//=========================================================================
//^Cg / `
//=========================================================================
void DrawTitle(void)
{
LPDIRECT3DDEVICE9 pDevice;
//foCX
pDevice = GetDevice();
//_obt@foCX̃f[^Xg[ɐݒ
pDevice->SetStreamSource(0, g_pVtxBuffTitle, 0, sizeof(VERTEX_2D));
//_tH[}bg̐ݒ
pDevice->SetFVF(FVF_VERTEX_2D);
for (int nCntBG = 0; nCntBG < T_TYPE; nCntBG++)
{
//eNX`̐ݒ
pDevice->SetTexture(0, g_pTextureTitle[nCntBG]);
//|S̕`
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, nCntBG*4, 2);
}
}
| true |
8b8c64ce0d712285bff6b08382b7c9614af0aa45 | C++ | tfwio/twix | /TimingInterval.h | UTF-8 | 1,230 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef __TIMING_INTERVAL__
#define __TIMING_INTERVAL__
class TimingInterval
{
public:
enum TIMINGPARAMS {
_tTempo,
_tIsRunning,
_tQuarters,
_tDivisions
};
// void Play(){} void Pause(){} void Stop(){} void Reset(){}
int GetQuarters() { return int(quar); }
int GetDivisions() { return int(divs); }
double GetTempo() { return Tempo; }
virtual void Set(TIMINGPARAMS paramid, double value)
{
switch (paramid)
{
case 0: Tempo = value; break;
case 1: IsRunning = bool(value); break;
case 2: quar = int8(value); Update(); break;
case 3: divs = int8(value); Update(); break;
case 4: segs = int8(value); Update(); break;
}
}
private:
void Update(){
calcDivs = (double(quar) / double(divs));
calcSegs = calcDivs * segs;
Frames = long(floor(calcSegs));
}
double Tempo, SampleRate;
bool IsRunning; // Play is pressed.
byte quar; // number of quarters per segment (numerator)
byte divs; // divide number of quarters by this
double calcDivs; // quar/div
byte segs; // Segment length; total number of `quars/divs` segments per interval
double calcSegs; // number of frames per segment; (QN / DIV) * Segments
long Frames;
};
#endif | true |
04b94087f18c1712296bdda7518e899a1aa05330 | C++ | chaojunhou/LeetCode | /Algorithm/CPP/missing_number.cpp | UTF-8 | 407 | 2.625 | 3 | [] | no_license | # include <stdio.h>
# include <iostream>
# include <vector>
# include <string>
# include <cctype>
# include <algorithm>
# include<time.h>
using namespace std;
class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum = 0;
int n = nums.size();
for(int i=0;i<n;++i)
{
sum += nums[i];
}
return n*(n+1)/2 - sum;
}
};
| true |
8c9f0bdb3febf96dd253ace09327f9467e0d547a | C++ | kalipav/3D_Viewer | /Field3D.h | UTF-8 | 1,815 | 2.953125 | 3 | [] | no_license | #ifndef _FIELD3D_H_
#define _FIELD3D_H_
#include "Point3D.h"
#include <vector>
// параметры метода Field3D::Kramer
struct Kramer_params
{
// спроецированные координаты (x, y, z)
double* proj_coords;
// координаты направляющего вектора (x, y, z)
const double* direction_vector;
// координаты точки (x, y, z), через которую прохидит прямая
const double* dot_coord;
// коэффициент а плоскости
const double a_coef_plane;
// коэффициент b плоскости
const double b_coef_plane;
// коэффициент c плоскости
const double c_coef_plane;
// коэффициент d плоскости
const double d_coef_plane;
};
class Field3D
{
private:
// вектор точек
std::vector <Point3D> m_points;
public:
// конструктор
Field3D();
// деструктор
~Field3D();
// добавить точку в поле
void Add_point(const double&, const double&, const double&);
// отобразить все точки поля c координатами
void Show_all_points() const;
// спроецировать все точки на плоскость
void Project_all_points(const double&, const double&);
// перевести все точки в 2-хмерное пространство
void Convert_2D(const double&, const double&);
// решение теоремы Крамера
bool Kramer(const Kramer_params&);
// установка смасштабированных координат
void Set_scale_coords_all(const double&, const double*);
// отрисовка
void Draw() const;
};
#endif // _FIELD3D_H_
| true |
98bc47429891f0f0db7db3a39755024c990ae780 | C++ | sweng2013team4/shredder | /ShredderSource/DiskManager/diskmanager.h | UTF-8 | 784 | 2.640625 | 3 | [] | no_license | #ifndef DISKMANAGER_H
#define DISKMANAGER_H
#include <string>
#include "disk_drive.h"
#define DISK_BUFFER 100
#define MAX_DRIVE_DEVICES 15
#define DRIVES_TMP_FILE "/tmp/hd.tmp"
#define GET_DRIVES_CMD "sudo Scripts/get_drives.sh " DRIVES_TMP_FILE
#define BOOT_TMP_FILE "/tmp/boot_dev.tmp"
#define GET_BOOT_CMD "sudo Scripts/get_boot_drive.sh " BOOT_TMP_FILE
#define NO_BOOT_DRIVE "NO_BOOT"
class DiskManager
{
public:
DiskManager();
void Refresh();
int DrivesCount;
int nBootDrive;
int nBootPart;
disk_drive GetDrive(int i) { return this->drives[i]; }
char* GetBootDrive();
char* GetBootPart();
private:
std::string GetBootDevice();
void SetBootByName(std::string strBootPart);
disk_drive drives[MAX_DRIVE_DEVICES];
};
#endif
| true |
d56450f6f4d46d5388594b5c439b032ec42d1e9b | C++ | aviana37/signal | /include/signal/emitter.hpp | UTF-8 | 1,819 | 3.046875 | 3 | [
"BSL-1.0"
] | permissive | #pragma once
#include "detail/control.hpp"
namespace signal
{
template <typename ... signals>
class emitter final : detail::not_copyable
{
private:
template <typename> friend class detail::control;
template <typename Signal> using instance_ptr = detail::make_emitter_instance_ptr<Signal>::type;
using instances = detail::transform<detail::mixin<signals ...>, detail::make_emitter_instance>;
instances m_instances;
template <typename Signal>
constexpr auto get_instance_ptr() {
return static_cast<instance_ptr<Signal>>(&m_instances);
}
public:
emitter() : m_instances{} {}
~emitter() = default;
template <typename Signal, typename R>
void connect(R& receiver) {
detail::control<Signal>::connect(
get_instance_ptr<Signal>(),
detail::control<Signal>::instance_access(receiver));
}
template <typename Signal, typename R>
void disconnect(R& receiver) {
detail::control<Signal>::disconnect(
get_instance_ptr<Signal>(),
detail::control<Signal>::instance_access(receiver));
}
template <typename Signal>
void disconnect() {
detail::control<Signal>::disconnect(get_instance_ptr<Signal>());
}
template <typename Signal>
void emit(typename Signal::traits::tuple_type&& signal_data) {
detail::control<Signal>::emit(get_instance_ptr<Signal>(), std::move(signal_data));
}
template <typename Signal, typename R>
bool is_connected(R& receiver) {
return get_instance_ptr<Signal>()->
is_connected(detail::control<Signal>::instance_access(receiver));
}
};
} | true |
c5d22d6da96b6afd236853f6037820e20867ee3f | C++ | 66112/memory_pool | /CentralCache.cpp | GB18030 | 2,829 | 2.765625 | 3 | [] | no_license | #include "CentralCache.h"
#include "PageCache.h"
CentralCache CentralCache::_inst; //һ¾̬Ա
//ĻȡһĶthreadcache
size_t CentralCache::FetchRangeObj(void*& start, void*& end, size_t num, size_t size)
{
//threadcache
//start = malloc(num*size);
//end = (char*)start + size*(num - 1);
//void* cur = start;
//while (cur < end){
// void* next = (char*)cur + size;
// NEXT_OBJ(cur) = next;
// cur = next;
//}
//NEXT_OBJ(end) = nullptr;
//return num;
size_t index = SizeClass::Index(size);
SpanList& spanlist = _spanList[index];
//ǰͰ RAII
std::unique_lock<std::mutex> lock(spanlist._mtx);
Span* span = GetOneSpan(&spanlist, size);
void* cur = span->_objlist;
void* prev = cur;
size_t fetchnum = 0;
while (cur && fetchnum < num){
prev = cur;
cur = NEXT_OBJ(cur);
++fetchnum;
}
start = span->_objlist;
end = prev;
NEXT_OBJ(end) = nullptr;
span->_objlist = cur;
span->_usecount += fetchnum;
return fetchnum;
}
//sizeΪҵÿĴС
Span* CentralCache::GetOneSpan(SpanList* spanlist, size_t size)
{
Span* span = spanlist->Begin();
while (span != spanlist->End()){
if (span->_objlist){
return span;
}
span = span->_next;
}
//pagecacheһʴСspan
size_t npage = SizeClass::NumMovePage(size);
Span* newspan = PageCache::GetInstance()->NewSpan(npage);
//_id_centralspan_map[newspan->_pageid] = newspan;
//spanڴиһsizeСĶ
char* start = (char*)(newspan->_pageid << PAGE_SHIFT);
char* end = start + (newspan->_npage << PAGE_SHIFT);
char* cur = start;
char* next = cur + size;
while (next < end){
NEXT_OBJ(cur) = next;
cur = next;
next = cur + size;
}
NEXT_OBJ((void*)cur) = nullptr;
newspan->_objlist = start;
newspan->_objsize = size;
newspan->_usecount = 0;
//µspanڶӦλ
spanlist->PushFront(newspan);
return newspan;
}
void CentralCache::ReleaseListToSpans(void* start, size_t size)
{
size_t index = SizeClass::Index(size);
SpanList& spanlist = _spanList[index];
std::unique_lock<std::mutex> lock(spanlist._mtx);
//ֹ쳣
//RAIIݶͷ
//ͬλõspanlistӰ
while (start){
Span* span = PageCache::GetInstance()->MapObjectToPageSpan(start); //
//һһͷ
void* next = NEXT_OBJ(start);
//ͷŶ
NEXT_OBJ(start) = span->_objlist;
span->_objlist = start;
//usecount == 0ʾspanгȥĶ
if (--span->_usecount == 0){
spanlist.Erase(span);
span->_objlist = nullptr;
span->_objsize = 0;
span->_prev = span->_next = nullptr;
PageCache::GetInstance()->ReleaseSpanToPageCache(span);
}
start = next;
}
}
| true |
77ed6ec7c2cdba084af4d69898051545e957f81e | C++ | eugendun/CAD-Practice | /Homogeneous Coordinates/Matrix4.cpp | MacCentralEurope | 4,430 | 3.0625 | 3 | [] | no_license | // ========================================================================= //
// Authors: Matthias Bein //
// mailto:matthias.bein@igd.fraunhofer.de //
// //
// GRIS - Graphisch Interaktive Systeme //
// Technische Universitt Darmstadt //
// Fraunhoferstrasse 5 //
// D-64283 Darmstadt, Germany //
// //
// Creation Date: 29.10.2013 //
// ========================================================================= //
#include "Matrix4.h"
#define _USE_MATH_DEFINES
#include <math.h>
Matrix4f::Matrix4f()
{
for(unsigned int row = 0; row < 4; ++row)
{
for(unsigned int column = 0; column < 4; ++column)
{
if(row == column)
values[row][column] = 1.0f;
else
values[row][column] = 0.0f;
}
}
}
Matrix4f::Matrix4f(float val)
{
for(unsigned int row = 0; row < 4; ++row)
{
for(unsigned int column = 0; column < 4; ++column)
{
values[row][column] = val;
}
}
}
Matrix4f Matrix4f::operator* (const Matrix4f& rightMatrix) const
{
// start with 0-matrix
Matrix4f result(0.0f);
for (int i = 0; i < 4; i++)
{
for (int k = 0; k < 4; k++)
{
for (int j = 0; j < 4; j++)
{
result.values[i][k] += values[i][j] * rightMatrix.values[j][k];
}
}
}
return result;
}
Vec4f Matrix4f::operator* (const Vec4f& vec) const
{
// start with 0-vector
Vec4f result;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i] += values[i][j] * vec[j];
}
}
return result;
}
std::ostream& operator<< (std::ostream& os, const Matrix4f& matrix)
{
os << matrix.values[0][0] << ", " << matrix.values[0][1] << ", " << matrix.values[0][2] << ", " << matrix.values[0][3] << std::endl
<< matrix.values[1][0] << ", " << matrix.values[1][1] << ", " << matrix.values[1][2] << ", " << matrix.values[1][3] << std::endl
<< matrix.values[2][0] << ", " << matrix.values[2][1] << ", " << matrix.values[2][2] << ", " << matrix.values[2][3] << std::endl
<< matrix.values[3][0] << ", " << matrix.values[3][1] << ", " << matrix.values[3][2] << ", " << matrix.values[3][3];
return os;
}
Matrix4f Matrix4f::translationMatrix(float tx, float ty, float tz)
{
// start with eye matrix
Matrix4f result;
// enter translation components in last column
result.values[0][3] = tx;
result.values[1][3] = ty;
result.values[2][3] = tz;
return result;
}
Matrix4f Matrix4f::rotateX(float angle)
{
float a = angle * M_PI / 180.0f;
Matrix4f result;
result.values[1][2] = cosf(a);
result.values[1][1] = -sinf(a);
result.values[2][1] = sinf(a);
result.values[2][2] = cosf(a);
return result;
}
Matrix4f Matrix4f::rotateY(float angle)
{
float a = angle * M_PI / 180.0f;
Matrix4f result;
result.values[0][0] = cosf(a);
result.values[2][0] = -sinf(a);
result.values[0][2] = sinf(a);
result.values[2][2] = cosf(a);
return result;
}
Matrix4f Matrix4f::rotateZ(float angle)
{
float a = angle * M_PI / 180.0f;
Matrix4f result;
result.values[0][0] = cosf(a);
result.values[1][0] = sinf(a);
result.values[0][1] = -sinf(a);
result.values[1][1] = cosf(a);
return result;
}
Matrix4f Matrix4f::rotate(const Quaternion& quaternion)
{
float a = quaternion.getAngle();
float x = quaternion.getAxis().x;
float y = quaternion.getAxis().y;
float z = quaternion.getAxis().z;
float cosa = cosf(a);
float sina = sinf(a);
Matrix4f result;
result.values[0][0] = x*x * (1 - cosa) + cosa; result.values[0][1] = x*y * (1 - cosa) - z*sina; result.values[0][2] = x*z * (1 - cosa) + y*sina;
result.values[1][0] = y*x * (1 - cosa) + z*sina; result.values[1][1] = y*y * (1 - cosa) + cosa; result.values[1][2] = y*z * (1 - cosa) - x*sina;
result.values[2][0] = z*x * (1 - cosa) - y*sina; result.values[2][1] = z*y * (1 - cosa) + x*sina; result.values[2][2] = z*z * (1 - cosa) + cosa;
return result;
}
Matrix4f Matrix4f::scale(float s)
{
return Matrix4f::scale(s, s, s);
}
Matrix4f Matrix4f::scale(float x, float y, float z)
{
Matrix4f result;
result.values[0][0] = x;
result.values[1][1] = y;
result.values[2][2] = z;
return result;
}
| true |
23a47705a2dce7cf7a2beb169190a0f39dd808a5 | C++ | shudashov/ArduSat-utils | /libraries/SamplingLib/IncSamplingMethod.h | UTF-8 | 2,850 | 2.890625 | 3 | [] | no_license | /*
********************************************************************
Copyright 2014, Jean-François Omhover (jf.omhover@gmail.com, twitter @jfomhover)
********************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
********************************************************************
Description : A sampling method that tries to fit the data serie with linear approximations
This linear approximation is sought starting from the beginning to the end,
and cutting where this approx doesn't meet the error criteria
(this method's complexity is O(n^2)... I guess)
Last Changed : Jan. 17, 2014
********************************************************************
*/
#ifndef _INCSAMPLINGMETHOD_H_
#define _INCSAMPLINGMETHOD_H_
#include <Arduino.h>
#include "SamplingMethod.h"
class IncSamplingMethod : public SamplingMethod {
public:
// the method called for actually compressing the data with error parameter epsilon
void sample(float epsilon) {
// initialization step
mask.keepNoValue(); // zeroes all flags
mask.keepValue(0, true); // keep first data point
int rankA = 0; // starts with first and last data points
int rankB = 1;
while((rankA < (proc->getLength()-1)) && (rankB < (proc->getLength()))) { // loops until we reach the end of the data array
float t_error = proc->computeMaxErrorByLinearApprox(rankA, rankB); // computes the approximation error between the two data points
if (t_error < epsilon) { // IF this approximation error is below epsilon
rankB++; // => progress in the ranks
} else { // ELSE : if approximation error is above epsilon
mask.keepValue(rankB-1, true); // keep the point just before
rankA = rankB-1; // start over from this point just before
rankB++; // no need to inspect rankA-rankB since there's no point between them, so skip to the next point
}
};
mask.keepValue(proc->getLength()-1, true); // keep last data point
};
};
#endif /* _INCSAMPLINGMETHOD_H_ */
| true |
fb59d1ee7cce8945e628b0ecfcd263339665acba | C++ | vxl/vxl | /contrib/gel/vsol/vsol_line_2d.cxx | UTF-8 | 11,701 | 2.515625 | 3 | [] | no_license | // This is gel/vsol/vsol_line_2d.cxx
#include <iostream>
#include <cmath>
#include "vsol_line_2d.h"
//:
// \file
#include <cassert>
#ifdef _MSC_VER
# include "vcl_msvc_warnings.h"
#endif
#include "vnl/vnl_math.h"
#include <vbl/io/vbl_io_smart_ptr.h>
#include <vsol/vsol_point_2d.h>
#include "vgl/vgl_homg_point_2d.h"
#include "vgl/vgl_vector_2d.h"
#include "vgl/vgl_homg_line_2d.h"
#include "vgl/vgl_line_segment_2d.h"
#include "vgl/vgl_point_2d.h"
//***************************************************************************
// Initialization
//***************************************************************************
//---------------------------------------------------------------------------
//: Default Constructor
//---------------------------------------------------------------------------
vsol_line_2d::vsol_line_2d()
: vsol_curve_2d(),
p0_(new vsol_point_2d),
p1_(new vsol_point_2d)
{
}
//---------------------------------------------------------------------------
//: Constructor from the direction and the middle point
//---------------------------------------------------------------------------
vsol_line_2d::vsol_line_2d(vgl_vector_2d<double> const& new_direction,
const vsol_point_2d_sptr &new_middle)
: vsol_curve_2d(),
p0_(new vsol_point_2d(*(new_middle->plus_vector(-(new_direction)/2)))),
p1_(new vsol_point_2d(*(new_middle->plus_vector((new_direction)/2))))
{
}
//---------------------------------------------------------------------------
//: Constructor from the direction and the middle point
//---------------------------------------------------------------------------
vsol_line_2d::vsol_line_2d(vgl_vector_2d<double> const& new_direction,
const vgl_point_2d<double> &new_middle)
: vsol_curve_2d(),
p0_(new vsol_point_2d(*(vsol_point_2d(new_middle).plus_vector(-(new_direction)/2)))),
p1_(new vsol_point_2d(*(vsol_point_2d(new_middle).plus_vector((new_direction)/2))))
{
}
//---------------------------------------------------------------------------
//: Constructor from two vgl_point_2d (end points)
//---------------------------------------------------------------------------
vsol_line_2d::vsol_line_2d(vgl_point_2d<double> const& p0,
vgl_point_2d<double> const& p1)
: vsol_curve_2d(),
p0_(new vsol_point_2d(p0)),
p1_(new vsol_point_2d(p1))
{
}
//---------------------------------------------------------------------------
//: Constructor
//---------------------------------------------------------------------------
vsol_line_2d::vsol_line_2d(vgl_line_segment_2d<double> const& l)
: vsol_curve_2d(),
p0_(new vsol_point_2d(l.point1())),
p1_(new vsol_point_2d(l.point2()))
{
}
//---------------------------------------------------------------------------
//: Clone `this': creation of a new object and initialization
// See Prototype pattern
//---------------------------------------------------------------------------
vsol_spatial_object_2d* vsol_line_2d::clone() const
{
return new vsol_line_2d(*this);
}
//***************************************************************************
// Access
//***************************************************************************
//---------------------------------------------------------------------------
//: Middle point of the straight line segment
//---------------------------------------------------------------------------
vsol_point_2d_sptr vsol_line_2d::middle() const
{
return p0_->middle(*p1_);
}
//---------------------------------------------------------------------------
//: direction of the straight line segment.
//---------------------------------------------------------------------------
vgl_vector_2d<double> vsol_line_2d::direction() const
{
return p0_->to_vector(*p1_);
}
//***************************************************************************
// Comparison
//***************************************************************************
//---------------------------------------------------------------------------
//: Has `this' the same points than `other' ?
//---------------------------------------------------------------------------
bool vsol_line_2d::operator==(vsol_line_2d const& other) const
{
if (this==&other)
return true;
return vsol_curve_2d::endpoints_equal(other);
}
//: spatial object equality
bool vsol_line_2d::operator==(vsol_spatial_object_2d const& obj) const
{
return
obj.cast_to_curve() && obj.cast_to_curve()->cast_to_line() &&
*this == *obj.cast_to_curve()->cast_to_line();
}
//***************************************************************************
// Status report
//***************************************************************************
//---------------------------------------------------------------------------
//: Compute the bounding box of `this'
//---------------------------------------------------------------------------
void vsol_line_2d::compute_bounding_box() const
{
set_bounding_box( p0_->x(), p0_->y());
add_to_bounding_box(p1_->x(), p1_->y());
}
//---------------------------------------------------------------------------
//: Return the length of `this'
//---------------------------------------------------------------------------
double vsol_line_2d::length() const
{
return p0_->distance(p1_);
}
//---------------------------------------------------------------------------
//: Return the tangent angle in degrees of `this'.
// By convention, the angle is in degrees and lies in the interval [0, 360].
//---------------------------------------------------------------------------
double vsol_line_2d::tangent_angle() const
{
static const double deg_per_rad = vnl_math::deg_per_rad;
double dy = p1_->y()-p0_->y();
double dx = p1_->x()-p0_->x();
double ang;
// do special cases separately, to avoid rounding errors:
if (dx == 0) ang = dy<0 ? 270.0 : 90.0; // vertical line
else if (dy == 0) ang = dx<0 ? 180.0 : 0.0; // horizontal line
else if (dy == dx) ang = dy<0 ? 225.0 : 45.0;
else if (dy+dx==0) ang = dy<0 ? 315.0 :135.0;
// the general case:
else ang = deg_per_rad * std::atan2(dy,dx);
if (ang<0) ang+= 360.0;
return ang;
}
//***************************************************************************
// Status setting
//***************************************************************************
//---------------------------------------------------------------------------
//: Set the first point of the straight line segment
//---------------------------------------------------------------------------
void vsol_line_2d::set_p0(vsol_point_2d_sptr const& new_p0)
{
p0_=new_p0;
}
//---------------------------------------------------------------------------
//: Set the last point of the straight line segment
//---------------------------------------------------------------------------
void vsol_line_2d::set_p1(vsol_point_2d_sptr const& new_p1)
{
p1_=new_p1;
}
//---------------------------------------------------------------------------
//: Set the length of `this'. Doesn't change middle point and orientation.
// If p0 and p1 are equal then the direction is set to (1,0)
// Require: new_length>=0
//---------------------------------------------------------------------------
void vsol_line_2d::set_length(const double new_length)
{
// require
assert(new_length>=0);
vsol_point_2d_sptr m=middle();
vgl_vector_2d<double> d =
(*p0_)==(*p1_) ? vgl_vector_2d<double>(1.0,0.0)
: normalized(direction());
d *= new_length;
p0_=new vsol_point_2d(*(m->plus_vector(-d/2)));
p1_=new vsol_point_2d(*(m->plus_vector(d/2)));
}
//***************************************************************************
// Basic operations
//***************************************************************************
//---------------------------------------------------------------------------
//: Is `p' in `this' ?
//---------------------------------------------------------------------------
bool vsol_line_2d::in(vsol_point_2d_sptr const& p) const
{
// `p' belongs to the straight line
bool result=(p0_->y()-p1_->y())*p->x()+(p1_->x()-p0_->x())*p->y()
+p0_->x()*p1_->y() -p0_->y()*p1_->x() ==0;
if (result) // `p' belongs to the segment
{
double dot_product=(p->x()-p0_->x())*(p1_->x()-p0_->x())
+(p->y()-p0_->y())*(p1_->y()-p0_->y());
result=(dot_product>=0)&&
(dot_product<(vnl_math::sqr(p1_->x()-p0_->x())
+vnl_math::sqr(p1_->y()-p0_->y())));
}
return result;
}
//---------------------------------------------------------------------------
//: Return the tangent to `this' at `p'. Has to be deleted manually
// Require: in(p)
//---------------------------------------------------------------------------
vgl_homg_line_2d<double> *
vsol_line_2d::tangent_at_point(vsol_point_2d_sptr const & p) const {
// require
assert(in(p));
return new vgl_homg_line_2d<double>(p0_->y()-p1_->y(),p1_->x()-p0_->x(),
p0_->x()*p1_->y()-p0_->y()*p1_->x());
}
//--------------------------------------------------------------------
//: compute an infinite homogeneous line corresponding to *this
//--------------------------------------------------------------------
vgl_homg_line_2d<double> vsol_line_2d::vgl_hline_2d() const
{
vgl_homg_point_2d<double> vp0(p0_->x(), p0_->y());
vgl_homg_point_2d<double> vp1(p1_->x(), p1_->y());
vgl_homg_line_2d<double> l(vp0, vp1);
return l;
}
//--------------------------------------------------------------------
//: compute a vgl line segment corresponding to *this
//--------------------------------------------------------------------
vgl_line_segment_2d<double> vsol_line_2d::vgl_seg_2d() const
{
vgl_homg_point_2d<double> vp0(p0_->x(), p0_->y());
vgl_homg_point_2d<double> vp1(p1_->x(), p1_->y());
vgl_line_segment_2d<double> l(vp0, vp1);
return l;
}
//----------------------------------------------------------------
// ================ Binary I/O Methods ========================
//----------------------------------------------------------------
//: Binary save self to stream.
void vsol_line_2d::b_write(vsl_b_ostream &os) const
{
vsl_b_write(os, version());
vsol_spatial_object_2d::b_write(os);
vsl_b_write(os, p0_);
vsl_b_write(os, p1_);
}
//: Binary load self from stream. (not typically used)
void vsol_line_2d::b_read(vsl_b_istream &is)
{
if (!is)
return;
short ver;
vsl_b_read(is, ver);
switch (ver)
{
case 1:
vsol_spatial_object_2d::b_read(is);
vsl_b_read(is, p0_);
vsl_b_read(is, p1_);
break;
default:
std::cerr << "vsol_line_2d: unknown I/O version " << ver << '\n';
}
}
//: Return IO version number;
short vsol_line_2d::version() const
{
return 1;
}
//: Print an ascii summary to the stream
void vsol_line_2d::print_summary(std::ostream &os) const
{
os << *this;
}
//: Binary save vsol_line_2d to stream.
void
vsl_b_write(vsl_b_ostream &os, const vsol_line_2d* p)
{
if (p==nullptr) {
vsl_b_write(os, false); // Indicate null pointer stored
}
else{
vsl_b_write(os,true); // Indicate non-null pointer stored
p->b_write(os);
}
}
//: Binary load vsol_line_2d from stream.
void
vsl_b_read(vsl_b_istream &is, vsol_line_2d* &p)
{
delete p;
bool not_null_ptr;
vsl_b_read(is, not_null_ptr);
if (not_null_ptr) {
p = new vsol_line_2d();
p->b_read(is);
}
else
p = nullptr;
}
void vsol_line_2d::describe(std::ostream &strm, int blanking) const
{
if (blanking < 0) blanking = 0; while (blanking--) strm << ' ';
strm << '[' << *(p0()) << ' ' << *(p1()) << ']' << std::endl;
}
| true |
ebd59f4f089978a620eea845777bcf5b5b3e6298 | C++ | yuishin-kikuchi/eckert | /src/calc/engine/OperatorsRandom.h | UTF-8 | 1,421 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef _OPERATORS_RANDOM_H_
#define _OPERATORS_RANDOM_H_
#include "GeneralOperator.h"
#include <random>
namespace engine {
class RandomOperator : public GeneralOperator {
protected:
static std::mt19937_64 mt;
public:
virtual bool operate(StackEngine &stackEngine) const = 0;
virtual std::size_t getRequiredCount() const {
return 0;
}
static void init() {
std::random_device rd;
mt.seed(rd());
}
static void seed(const uint64_t &val) {
mt.seed(val);
}
};
class RandomIntegerOperator : public RandomOperator {
public:
virtual bool operate(StackEngine &stackEngine) const {
auto &proc = getGeneralProcessor();
proc.resetFlags();
stackEngine.setCommandMessage("OP_RAND");
stackEngine.setErrorMessage("NO_ERROR");
auto &stack = stackEngine.refExStack();
uinteger_t temp = mt() >> 1;
stack.push(GEN_INTEGER((integer_t)temp));
return false;
}
};
class RandomFloatingOperator : public RandomOperator {
public:
virtual bool operate(StackEngine &stackEngine) const {
auto &proc = getGeneralProcessor();
proc.resetFlags();
stackEngine.setCommandMessage("OP_FRND");
stackEngine.setErrorMessage("NO_ERROR");
auto &stack = stackEngine.refExStack();
std::uniform_real_distribution<floating_t> distribution(0.0, 1.0);
stack.push(GEN_FLOATING(distribution(mt)));
return false;
}
};
} // namespace engine
#endif // ifndef _OPERATORS_RANDOM_H_
| true |
0ee780d599071c024bb486e3f5456b8ea62992f4 | C++ | kedixa/LeetCode | /C++/126.cpp | UTF-8 | 2,299 | 2.609375 | 3 | [] | no_license | class Solution {
using vs = vector<string>;
vector<vs> result;
vs tmp;
vector<vector<int>> next;
vector<string> vstr;
bool diff_by_one(const string &a, const string &b)
{
int s = 0;
for(int i = 0; s !=2 && i < a.length(); ++i)
s += (a[i]!=b[i]);
return s==1;
}
void dfs(int b, int e)
{
if(b==e)
{
result.push_back(tmp);
return;
}
for(int i = 0; i < next[b].size(); ++i)
{
auto &n = next[b][i];
tmp.push_back(vstr[n]);
dfs(n, e);
tmp.pop_back();
}
return;
}
public:
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
// 从endWord开始bfs出一棵树,再从beginWord开始dfs出所有结果即可
// 代码效率较低,有待提高
result.clear();
next.clear();
int b, e;
vstr.assign(wordList.begin(), wordList.end());
if(wordList.find(beginWord)!=wordList.end()) b = find(vstr.begin(), vstr.end(), beginWord) - vstr.begin();
else vstr.push_back(beginWord), b = vstr.size() - 1;
if(wordList.find(endWord)!=wordList.end()) e = find(vstr.begin(), vstr.end(), endWord) - vstr.begin();
else vstr.push_back(endWord), e = vstr.size() - 1;
// bfs from endWord to beginWord
vector<int> depth(vstr.size(), 99999999);
next.resize(vstr.size());
queue<int> que;
que.push(e);
depth[e]=0;
while(!que.empty() && depth[b]==99999999)
{
int sz = que.size();
while(sz--)
{
int p = que.front();
que.pop();
for(int i = 0; i < vstr.size(); ++i)
{
if(depth[i] > depth[p] && diff_by_one(vstr[i], vstr[p]))
{
next[i].push_back(p);
if(depth[i]==99999999) que.push(i);
depth[i] = depth[p]+1;
}
}
}
}
// dfs from beginWord to endWord
tmp.clear();
tmp.push_back(vstr[b]);
dfs(b, e);
return result;
}
};
| true |
dce564ab0871e606392432a4e1ed1fb7af381739 | C++ | Chenxiaojiang10/C | /no06-2.cpp | GB18030 | 916 | 3.546875 | 4 | [] | no_license | #include<iostream>
#include<string>
//ַתint
using namespace std;
class Solution {
public:
bool NotIsNumber(char s) {
if ((s > '0' && s < '9') || s == ' ' || s == '-' || s == '+') {
return false;
}
return true;
}
int StrToInt(string str) {
int flag = 1;//
int i = 0;
for (; i < (int)str.size(); i++) {
if (str[i] != ' ') {
break;
}
}
if (str[i] == '-') {
flag = -1;
}
string::reverse_iterator it = str.rbegin();
int m = 1;
int sum = 0;
//cout << *(str.end() - 1 )<< endl;
while (it != str.rend()) {
if (NotIsNumber(*it)) {
return 0;
}
if (*it == ' ' || *it == '-' || *it == '+') {
++it;
continue;
}
sum += ((int)*it - 48) * m;
m *= 10;
//cout << *it << endl;
++it;
}
return sum * flag;
}
};
int main() {
string str("-123");
Solution s;
cout << s.StrToInt(str) << endl;
return 0;
}
//1a33 | true |
67e3bb59036612ea9e34644cff26679b480ab422 | C++ | NimeshJohari02/DataStructures | /ARRAY(display).cpp | UTF-8 | 574 | 3.75 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct array
{
int *a;
int size;
int length;
};
void display(struct array arr)
{
cout<<"ELEMENTS ENTERED \n ";
for(int i=0;i<arr.length;i++)
cout<<arr.a[i]<<endl;
}
int main()
{
struct array a1;
cout<<"Enter the size of the array"<<endl;
cin>>a1.size;
a1.a=new int[a1.size];
a1.length=0;
int n;
cout<<"How many numbers you want to enter into the array"<<endl;
cin>>n;
cout<<"ELEMENTS \n ";
for(int i=0;i<n;i++)
{
cin>>a1.a[i];
a1.length=a1.length+1;
}
display(a1);
return 0;
}
| true |
ab6f52ce1d85df02015f2bc3c773bc5209586079 | C++ | kianoosh-j/HMAX | /SVN/Codes/Hmax/implementations/picture_handler.cpp | UTF-8 | 9,941 | 3.078125 | 3 | [] | no_license | #include "headers.h"
#include "picture_handler.h"
#define MAX_MATRIX_SIZE 1000 * 1000
#define CURRENT_HEIGHT 140
int max_pictures ( Picture result , Picture first , Picture second ){
if ( result.width != first.width || result.width != second.width && result.width < 0){
cerr<<"not equal width for max pictures\n";
return -1;
}
if ( result.height != first.height || result.height != second.height && result.height < 0){
cerr<<"not equal height for max pictures\n";
return -1;
}
for ( int i=0 ; i<result.height ; i++){
for ( int j=0 ; j<result.width ; j++){
result.matrix[i*result.width + j] = max ( first.matrix[i*result.width + j] , second.matrix[i*result.width + j] );
}
}
return 0;
}
void free_picture ( Picture &p){
free(p.matrix);
}
int divide_pictures ( Picture &dest , const Picture &division, const Picture &divisor){
if ( equal_size_pictures ( dest , division ) && equal_size_pictures ( dest , divisor ) ){
for ( int i=0 ; i<dest.height ; i++ ){
for ( int j=0 ; j<dest.width ; j++ ){
int index = i*dest.width + j;
if ( divisor.matrix[index] == 0 ){
cerr<<"error : divide_pictures : divide by zero at matrix["<<i<<"]["<<j<<"]\n";
return -1;
}
dest.matrix[index] = division.matrix[index] / divisor.matrix[index];
}
}
return 0;
}
else{
cerr<<"error : divide_pictures : size of pictures are not OK\n";
return -1;
}
}
int init_copy_picture ( Picture &dest , Picture &src ){
if ( src.width < 0 || src.height < 0 ){
cerr<<"error : init_copy_picture : width and height should be more than zero\n";
return -1;
}
dest.width = src.width;
dest.height = src.height;
dest.matrix = new float [dest.width * dest.height];
for ( int i=0 ; i<src.height ; i++ ){
for ( int j=0 ; j<src.width ; j++ ){
dest.matrix[i*src.width+j] = src.matrix[i*src.width+j];
}
}
return 0;
}
bool equal_size_pictures ( const Picture &p1 , const Picture &p2 ){
if ( !valid_picture ( p1 ) || !valid_picture ( p2 ) ){
return false;
}
if ( p1.width != p2.width || p1.height != p2.height ){
return false;
}
return true;
}
bool valid_picture ( const Picture & p ){
if ( p.width < 0 || p.height < 0 ){
cerr<<"error valid picture : width or height is less than zero\n";
return -1;
}
return true;
}
int init_picture ( Picture &p , int w , int h ){
if ( w < 0 || h < 0 ){
cerr<<"error : init_picture : w or h is not valid\n";
return -1;
}
p.width = w;
p.height = h;
if ( init_picture_matrix (p) ){
return 0;
}
return -1;
}
int init_picture ( Picture &p , int w , int h , int value){
if ( w < 0 || h < 0 ){
cerr<<"error : init_picture : w or h is not valid\n";
return -1;
}
p.width = w;
p.height = h;
if ( init_picture_matrix (p) ) {
for ( int i=0 ; i<h ; i++ ){
for ( int j=0 ; j<w ; j++ ){
p.matrix[i*w + j] = value;
}
}
return 0;
}
return -1;
}
void print_picture (Picture p){
cout<<"\n\n****************** printing picture \n\n";
cout<<"\t\tPicture size is : h = "<<p.height<<" and w = "<<p.width<<endl<<endl;
cout<<setprecision(4);
for(int i=0;i<p.height;i++){
for(int j=0;j<p.width;j++)
printf ( " %20.15lf" , p.matrix[i*p.width+j] );
cout<<endl;
}
}
bool init_picture_matrix ( Picture &p){
if ( p.width < 0 || p.height < 0 )
return false;
p.matrix = new float [ p.width * p.height ];
return true;
}
int abs_matrix ( float *dest , float *src , int size ){
if ( size < 0 )
return -1;
for ( int i=0 ; i<size ; i++ ){
dest[i] = src[i] > 0 ? src[i] : -src[i];
}
}
int inverse_picture ( Picture &pic ){
if ( !valid_picture ( pic ) ){
cerr<<"error : inverse_picture : picture is not valid\n";
return -1;
}
//cout<<"in inverse : before anythig\n\n";
//print_matrix ( pic.matrix , pic.width , pic.height );
for ( int i=0 ; i<(pic.height/2) ; i++ ){
for ( int j=0 ; j<pic.width ; j++ ){
int index1 = i*pic.width + j;
int index2 = pic.width * pic.height - index1 -1;
//cout<<"index1 = "<<index1<<" , index2 = "<<index2<<endl;
//cout<<"pic["<<index1<<"] = "<<pic.matrix[index1]<<" , pic["<<index2<<"] = "<<pic.matrix[index2]<<endl;
float temp = pic.matrix[index1];
pic.matrix[index1] = pic.matrix[index2];
pic.matrix[index2] = temp;
//cout<<"pic["<<index1<<"] = "<<pic.matrix[index1]<<" , pic["<<index2<<"] = "<<pic.matrix[index2]<<endl;
//cout<<"pic[1] = "<<pic.matrix[index1]<<" , pic[2] = "<<pic.matrix[index2]<<endl;
}
}
//cout<<"in inverse : middle of doing inverse\n\n";
//print_matrix ( pic.matrix , pic.width , pic.height );
if ( pic.height %2 != 0 ){
int i=pic.height/2;
for ( int j=0 ; j<pic.width/2 ; j++ ){
int index1 = i*pic.width + j;
int index2 = pic.width * pic.height - index1 -1;
// cout<<"index1 = "<<index1<<" , index2 = "<<index2<<endl;
// cout<<"pic["<<index1<<"] = "<<pic.matrix[index1]<<" , pic["<<index2<<"] = "<<pic.matrix[index2]<<endl;
float temp = pic.matrix[index1];
pic.matrix[index1] = pic.matrix[index2];
pic.matrix[index2] = temp;
// cout<<"pic["<<index1<<"] = "<<pic.matrix[index1]<<" , pic["<<index2<<"] = "<<pic.matrix[index2]<<endl;
//cout<<"pic[1] = "<<pic.matrix[index1]<<" , pic[2] = "<<pic.matrix[index2]<<endl;
}
}
//cout<<"in inverse : after doing inverse\n\n";
//print_matrix ( pic.matrix , pic.width , pic.height );
return 0;
}
void print_matrix ( float *a , int w , int h ){
for ( int i=0 ; i<h ; i++ ){
for ( int j=0 ; j<w ; j++ ){
printf ( " %8.4f" , a[i*w + j] );
}
printf ( "\n" );
}
}
void read_matrix ( float *a , int w , int h ){
for ( int i=0 ; i<h ; i++ ){
for ( int j=0 ; j<w ; j++ ){
cin>>a[i*w+j];
//cout<<a[i*w+j];
}
}
}
void free_list_list_pictures ( list<list<Picture> > &pictures ){
for ( list<list<Picture> >::iterator iter_lpicture=pictures.begin() ; iter_lpicture != pictures.end() ; iter_lpicture++ ){
free_list_pictures ( *iter_lpicture );
iter_lpicture->clear();
}
pictures.clear();
}
void free_list_pictures ( list<Picture> pictures ){
for ( list<Picture>::iterator iter_picture=pictures.begin() ; iter_picture != pictures.end() ; iter_picture++ ){
//cerr<<"before freeing picture\n";
free_picture ( *iter_picture );
//cerr<<"after freeing picture\n";
}
pictures.clear();
}
bool equal_list_pictures ( list<Picture> &pictures ){
if ( pictures.size() <= 0 ){
cerr<<"error : equal_list_pictures : list is empty\n";
return -1;
}
Picture pic_temp = *(pictures.begin());
for ( list<Picture>::iterator iter=pictures.begin() ; iter!=pictures.end() ; iter++){
if ( !equal_size_pictures ( *iter , pic_temp ) )
return false;
pic_temp = *iter;
}
return true;
}
int create_random_picture ( Picture &pic , int width , int height ){
if ( init_picture ( pic , width , height ) != 0 )
return -1;
for ( int i=0 ; i<height ;i++){
for ( int j=0 ; j<width ; j++ ){
int index = i*width + j;
pic.matrix[index] = (float)((rand()%999999)+1)/(float)(1000001);
if ( (rand()%10000) < 369 )
pic.matrix[index] = -pic.matrix[index];
}
}
}
int read_picture_from_file ( Picture &pic , string file_name ){
cout << "in read_picture_from_file " << endl;
fstream fin;
fin.open ( file_name.c_str() , ios::in );
if ( fin.fail() ){
cerr<<"read_picture_from_file : error while reading file "<<file_name<<endl;
return -1;
}
float temp_fl;
char temp_ch;
int height=0 , width=0;
int columns_counter, rows_counter;
rows_counter = CURRENT_HEIGHT;
float matrix_temp [ MAX_MATRIX_SIZE ];
int matrix_index = 0;
while ( fin >> matrix_temp[matrix_index++] ){
}
height = rows_counter;
fin.close();
Picture pic_temp;
pic_temp.width = matrix_index / rows_counter;
pic_temp.height = height;
pic_temp.matrix = &matrix_temp[0];
init_copy_picture ( pic , pic_temp );
return 0;
}
int read_patch_from_file ( Picture &pic , string file_name ){
cout << "in read_patch_from_file " << endl;
fstream fin;
fin.open ( file_name.c_str() , ios::in );
if ( fin.fail() ){
cerr<<"read_patch_from_file : error while reading file "<<file_name<<endl;
return -1;
}
cout << "opened successfully" << endl;
float temp_fl;
char temp_ch;
int height=0 , width=0;
int columns_counter, rows_counter;
rows_counter = CURRENT_HEIGHT;
float matrix_temp [ MAX_MATRIX_SIZE ];
int matrix_index = 0;
while ( fin >> matrix_temp[matrix_index++] ){
}
height = rows_counter;
fin.close();
Picture pic_temp;
pic_temp.width = sqrt(matrix_index);
pic_temp.height = sqrt(matrix_index);
pic_temp.matrix = &matrix_temp[0];
init_copy_picture ( pic , pic_temp );
return 0;
}
void print_list_list_picture ( const list<list<Picture> > &llpictures ){
for ( list<list<Picture> >::const_iterator iter = llpictures.begin() ; iter != llpictures.end() ; iter++ ){
print_list_picture ( *iter );
}
}
void print_list_picture ( const list<Picture> &lpictures ){
for ( list<Picture>::const_iterator iter = lpictures.begin() ; iter != lpictures.end() ; iter++ ){
print_picture ( *iter );
}
}
void show_image ( cv::Mat &img ){
string window_name = "image window";
namedWindow ( window_name.c_str() , CV_WINDOW_AUTOSIZE );
imshow ( window_name.c_str() , img );
waitKey ( 3000 );// wait for 3 seconds
}
void show_image_picture ( Picture &picture ){
Mat image = picture.convert_to_opencvMat();
show_image ( image );
}
void show_image ( string image_file_name ){
Mat image = imread ( image_file_name , CV_LOAD_IMAGE_COLOR );
show_image ( image );
}
| true |
21f9d941c6721aa6f4e26f12e2a72ac414bfc90c | C++ | Itachi546/Software-Renderer | /src/Core/MainWindow.cpp | UTF-8 | 5,451 | 2.9375 | 3 | [] | no_license | #include "MainWindow.h"
#include "InputManager.h"
#include <SDL2/SDL.h>
#include <cmath>
#include <climits>
#include "../Math/Math.h"
MainWindow::MainWindow(int width, int height, const char* title){
this->width = width;
this->height = height;
running = true;
SDL_Init(SDL_INIT_VIDEO);
//Enable default vertical sync
SDL_GL_SetSwapInterval(1);
SDL_CreateWindowAndRenderer(width, height, 0, &window, &renderer);
SDL_SetWindowTitle(window, title);
z_buffer = new float[width * height];
}
void MainWindow::destroy(){
delete []z_buffer;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void MainWindow::clear_depth(){
//@Note need to find efficient way to clear the depth buffer
for (unsigned int i= 0; i < width * height; i++) z_buffer[i] = FLT_MAX;
}
void MainWindow::clear(uint8_t r, uint8_t g, uint8_t b){
SDL_SetRenderDrawColor(renderer, r, g, b, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0 ,0, 0);
clear_depth();
}
void MainWindow::render(){
SDL_RenderPresent(renderer);
}
bool MainWindow::is_open(){
return running;
}
void MainWindow::set_title(const char* title){
SDL_SetWindowTitle(window, title);
}
void MainWindow::poll_events(){
SDL_Event event;
while(SDL_PollEvent(&event)){
switch(event.type){
case SDL_KEYDOWN:
{
InputManager::KeyDown(event.key.keysym.scancode);
}break;
case SDL_KEYUP:
{
InputManager::KeyUp(event.key.keysym.scancode);
}break;
case SDL_QUIT:
{
running = false;
}
}
}
}
void MainWindow::plot_pixel(int x, int y, vec3 color){
SDL_SetRenderDrawColor(renderer, int(color.x), int(color.y), int(color.z), 255);
SDL_RenderDrawPoint(renderer, x, y);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
}
void MainWindow::draw_line(vec2 v1, vec2 v2, vec3 color){
int dx = abs(v2.x - v1.x);
int dy = abs(v2.y - v1.y);
int x = v1.x;
int y = v1.y;
int dy2 = 2 * dy;
int dx2 = 2 * dx;
if(fabs(dx) > fabs(dy)){
int p0 = dy2 - dx;
dx = 1;
dy = 1;
if(v1.x > v2.x){
x = v2.x;
y = v2.y;
v2 = v1;
}
if(v2.y < y) dy = -1;
while(x <= v2.x){
plot_pixel(x, y, color);
x += dx;
if(p0 < 0) p0 += dy2;
else{
y += dy;
p0 += dy2 - dx2;
}
}
}else{
dx = 1;
dy = 1;
int p0 = dx2 - dy;
if(v1.y > v2.y){
x = v2.x;
y = v2.y;
v2 = v1;
}
if(v2.x < x) dx = -1;
while(y <= v2.y){
plot_pixel(x, y, color);
y += dy;
if(p0 < 0) p0 += dx2;
else{
x+=dx;
p0 += dx2 - dy2;
}
}
}
}
vec3 MainWindow::barycentric(const vec2& a, const vec2& b, const vec2&c, const vec2& p){
//Calculate the barycentric value from given vertices
/*
u = (Area of v1v2p)/(Area of triangle v0v1v2)
v = (Area of v2v0p)/(Area of triangle v0v1v2)
w = (Area of v0v1p)/(Area of triangle v0v1v2)
*/
float u, v, w;
vec2 v0 = b - a, v1 = c - a, v2 = p - a;
float den = v0.x * v1.y - v1.x * v0.y;
v = (v2.x * v1.y - v1.x * v2.y) / den;
w = (v0.x * v2.y - v2.x * v0.y) / den;
u = 1.0f - v - w;
return vec3(u, v, w);
}
void MainWindow::draw_triangle(vec2 v0, vec2 v1, vec2 v2){
int faceDir = vec2::cross(v0, v1) + vec2::cross(v1, v2) + vec2::cross(v2, v0);
if(faceDir > 0) return;
draw_line(v0, v1, vec3(255,255,255));
draw_line(v1, v2, vec3(255,255,255));
draw_line(v2, v0, vec3(255,255,255));
}
void MainWindow::draw_triangle(Vertex3d v0, Vertex3d v1, Vertex3d v2){
//Sulley's algorith to determine the front facing or back facing triangle
// faceDir < 0 then backfacing else front facing but opposite is working
int faceDir = vec2::cross(v0.position, v1.position) + vec2::cross(v1.position, v2.position) + vec2::cross(v2.position, v0.position);
if(faceDir > 0) return;
//Calculation of bounding box for given triangle
//@Note maybe need to change the implementation to raster faster
int minX = int(std::fmin(std::fmin(v0.position.x, v1.position.x), v2.position.x));
int maxX = int(std::fmax(std::fmax(v0.position.x, v1.position.x), v2.position.x));
int minY = int(std::fmin(std::fmin(v0.position.y, v1.position.y), v2.position.y));
int maxY = int(std::fmax(std::fmax(v0.position.y, v1.position.y), v2.position.y));
//Clipping the vertices against the screen
minX = int(std::max(minX, 0));
maxX = int(std::min(maxX, int(width-1)));
minY = int(std::max(minY, 0));
maxY = int(std::min(maxY, int(height-1)));
for(int i = minX; i <= maxX; ++i){
for(int j = minY; j <= maxY; ++j){
//for a point to be inside the triangle it's barycentric value must be all positive and sum must be equal to 1
vec3 barycentric_value = barycentric(v0.position, v1.position, v2.position, vec2(i, j));
//Check whether the pixel is inside or outside the triangle
if(barycentric_value.x < 0 || barycentric_value.y < 0 || barycentric_value.z < 0) continue;
//Garoud shading of color
vec3 color = v0.color * barycentric_value.x + v1.color * barycentric_value.y + v2.color * barycentric_value.z;
float zCoords = barycentric_value.x * v0.position.z + barycentric_value.y * v1.position.z + barycentric_value.z * v2.position.z;
if(z_buffer[i + j * width] >= zCoords){
z_buffer[i + j * width] = zCoords;
plot_pixel(i, j, color);
}
}
}
}
| true |
1b910c39f1d84518f7426c3b56205da43c324889 | C++ | stamborindegui/CS165new | /week03/myAssign03.cpp | UTF-8 | 6,036 | 3.328125 | 3 | [] | no_license | /***********************************************************************
* Program:
* Assignment 03, Digital Forensics with Corrupt Files.
* Brother Dudley, CS165
* Author:
* Sandro Tamborindegui
* Summary:
* This program will read all logs by prompt the user to enter the file
* location start and end date. After list all files accessed, and who was
* the user that access these files.
* This program will ignore any corrupted log, and will return all valid
* entries
*
* Estimated: 6.0 hrs
* Actual: 9.0 hrs
* Create the parseLine/File functions and incorporate all the
* suggestions from Assignment 2.
************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
/**********************************************************************
* Struct Access Record
***********************************************************************/
struct AccessRecord
{
std::string userName;
std::string fileName;
long timeStamp;
};
/**********************************************************************
*Struct Date Range
***********************************************************************/
struct DateRange
{
long startDate;
long endDate;
};
/**********************************************************************
* Prompt the user for the file location
***********************************************************************/
//from the forum discussion board example
void getPromptFilePath(char promptFilePath[])
{
if (promptFilePath == NULL) //check for invalid
{
std::cout << "Invalid access record file." ;
return;
}
}
std::string promptFilePath() //prompt for file path
{
std::string path;
std::cout << "Enter the access record file: ";
std::cin >> path;
return path;
}
/**********************************************************************
* Prompt the user for enter the start and end time
***********************************************************************/
DateRange promptTimes()
{
DateRange dr;
std::cout << "Enter the start time: ";
std::cin >> dr.startDate;
std::cout << "Enter the end time: ";
std::cin >> dr.endDate;
return dr;
}
/**********************************************************************
* Display the records that match the criteria
***********************************************************************/
void displayAccessRecords(const AccessRecord(&ar)[500])
{
const int LINE_LENGTH = 19;
std::cout << "The following records match your criteria:" << std::endl;
std::cout << std::endl;
std::cout << " Timestamp" << " " << " File";
std::cout << " " << " User" << std::endl;
std::cout << "--------------- ------------------- -------------------"
<< std::endl;
for (int i = 0; i < 500 ; i++)
{
if (ar[i].timeStamp > 0 && ar[i].fileName.size() > 0
&& ar[i].userName.size() > 0)
{
std::cout << " " << ar[i].timeStamp << " ";
for (int j = 0; j < (LINE_LENGTH - ar[i].fileName.size()); j++)
{
std::cout << " ";
}
std::cout << ar[i].fileName << " ";
for (int j = 0; j < (LINE_LENGTH - ar[i].userName.size()); j++)
{
std::cout << " ";
}
std::cout << ar[i].userName << std::endl;
}
}
std::cout << "End of records" << std::endl;
}
/**********************************************************************
* Accepts a line (a string) and populates a struct for the AccessRecord
***********************************************************************/
AccessRecord parseLine (std::string line) throw (std::string)
{
AccessRecord ar;
std::stringstream ss;
ss.str(line);
ss >> ar.fileName;
if (ss.fail())
throw std::string("no filename on line");
ss >> ar.userName;
if (ss.fail())
throw std::string("no username on line");
ss >> ar.timeStamp;
if (ss.fail())
throw std::string("Timestamp is invalid/not found");
if (ar.timeStamp < 1000000000)
throw std::string("Timestamp is not long enough");
if (ar.timeStamp > 10000000000)
throw std::string("Timestamp is too long");
return ar;
}
/**********************************************************************
* Parses the file one line at a time and check for errors
***********************************************************************/
void parseFile(std::string fileName, AccessRecord(&ar)[500])
{
std::ifstream inputFileStream;
inputFileStream.open(fileName.c_str());
std::string line;
int i = 0;
while (getline(inputFileStream, line))
{
try
{
ar[i] = parseLine(line);
i++;
}
//catch any errors, display the message
catch (std::string err)
{
std::cout << "Error parsing line: " << line << std::endl;
}
}
}
/**********************************************************************
* Main
* Will call all functions and display the results for the user
***********************************************************************/
int main()
{
AccessRecord allAccessRecords[500];
std::string filePath = promptFilePath();
parseFile(filePath, allAccessRecords);
std::cout << std::endl;
DateRange range = promptTimes();
std::cout << std::endl;
AccessRecord matchedRecords[500];
int count = 0;
for (int i = 0; i < 500; i++)
{
if (allAccessRecords[i].timeStamp >= range.startDate
&& allAccessRecords[i].timeStamp <= range.endDate)
{
matchedRecords[count] = allAccessRecords[i];
count++;
}
}
displayAccessRecords(matchedRecords);
return 0;
}
| true |
20442ac539e3a47f8703e4eba97d98b1fb10a34f | C++ | LazerTony20/RobusP17APP | /Tests bluetooth/src/main.cpp | UTF-8 | 2,039 | 2.765625 | 3 | [] | no_license | #include <Arduino.h>
/*
--------------------RÉFÉRENCES-----------------
https://www.arduino.cc/en/Tutorial/BuiltInExamples/MultiSerialMega
https://www.arduino.cc/en/Reference/StringLibrary
https://www.arduino.cc/reference/en/language/functions/communication/serial/readstring/
https://www.arduino.cc/reference/en/language/functions/communication/serial/read/
https://www.arduino.cc/reference/en/language/functions/communication/serial/
https://maker.pro/arduino/tutorial/bluetooth-basics-how-to-control-led-using-smartphone-arduino#:~:text=Arduino%20Pins%20%7C%20Bluetooth%20Pins&text=Connect%20an%20LED%20positive%20to,jumper%20wires%20and%20a%20connector.
http://www.dsdtech-global.com/2017/09/sh-m08.html
*/
String incomingByte = ""; // for incoming serial data
String outMessage = "";
int mode = 0; //0 for read-write and 1 for read only
void setup() {
// put your setup code here, to run once:
//Initialise le port de communication et attend pour l'ouvrir:
Serial.begin(9600);
Serial1.begin(9600);
//Ce delai permet de s'assurer que le moniteur serie (Serial monitor) soit disponible
delay(1500);
}
void loop() {
if(mode == 0){
if (Serial1.available() > 0) {
// read the incoming byte:
incomingByte = Serial1.readString();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte);
}
if (Serial.available() > 0) {
// read the incoming byte:
outMessage = Serial.readString();
// say what you got:
Serial.print(outMessage);
Serial1.print(outMessage);
}
}else if(mode == 1){
if (Serial1.available() > 0) {
// read the incoming byte:
incomingByte = Serial1.readString();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte);
}
}else{
Serial.println("How did you get here ?");
}
/*
// put your main code here, to run repeatedly:
Serial.println("Bonjour le monde!");
Serial1.println("Hello Bluetooth !");
delay(3000);
*/
} | true |
9171bb719c6d452c0b25d863d8144fd6a5981ede | C++ | shphrd/bitcoin-sv | /src/invalid_txn_sinks/file_sink.h | UTF-8 | 2,735 | 2.703125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | // Copyright (c) 2020 Bitcoin Association
// Distributed under the Open BSV software license, see the accompanying file LICENSE.
#pragma once
#include <map>
#include <mutex>
#include <string>
#include <boost/filesystem.hpp>
#include "invalid_txn_publisher.h"
#include "util.h"
namespace InvalidTxnPublisher
{
// Writes invalid transactions to disk. Each transaction to separate file (YYYY-MM-DD_HH-MM-SS_<transaction id>_<ord number>.json).
// Keeps track of the on the overall disk usage. If the transaction is found to be invalid more than once its hex is written only in the first file.
// When disk usage limit is reached, we can delete old or ignore new transactions, depending on the policy which can be set from outside.
class CInvalidTxnFileSink : public CInvalidTxnSink
{
bool isInitialized = false;
int64_t maximumDiskUsed = CInvalidTxnPublisher::DEFAULT_FILE_SINK_DISK_USAGE; // maximal cumulative size of the files written to the disk
boost::filesystem::path directory;
InvalidTxEvictionPolicy evictionPolicy;
std::mutex guard;
std::map<std::string, int64_t> files; // mapping filename to file size (taking advantage that std::map is sorted to evict first or last added file, depending on policy)
int64_t cumulativeFilesSize = 0; // current size of all files written to the disk
std::map<std::string, int> idCountMap; // how many times we have seen any transaction (key: hex of transaction id, value: how many times it is seen)
// Writes transaction to disk
void SaveTransaction(const InvalidTxnInfo& invalidTxnInfo, bool doWriteHex);
// Checks file name and extract relevant data
static bool ParseFilename(const std::string& fname, std::string& txid, int& ordNum1);
// Enumerates files on the disk to find cumulative files size and to count how many times each transaction is seen
void FillFilesState();
// Deletes a file and updates file relevant data
bool RemoveFile(const std::string fname, int64_t fsize);
// Deletes files, until cumulative files size drops below maximalSize
bool ShrinkToSize(int64_t maximalSize);
// Initialize state (executes lazy, right before first transaction is written)
void Initialize();
public:
CInvalidTxnFileSink(int64_t maxDiskUsed, InvalidTxEvictionPolicy policy)
: maximumDiskUsed(maxDiskUsed)
, directory(GetDataDir() / "invalidtxs")
, evictionPolicy(policy)
{
}
void Publish(const InvalidTxnInfo& invalidTxnInfo) override;
int64_t ClearStored() override;
};
} | true |
4d14028107c98d7993529051494eb08d368a53d2 | C++ | jai-singhal/dsa | /competitive/code_quest/collision.cpp | UTF-8 | 779 | 3.046875 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include <map>
#include <iterator>
using namespace std;
int main(){
int C, x, y, v, t, d;
cin >> C;
map<float, int> collisons;
for(int i = 1; i <= C; i++){
cin >> x >> y >> v;
d = sqrt(pow(x, 2) + pow(y, 2));
t = ceilf((d/v)*100)/100;
if(collisons.find(t) != collisons.end()){
collisons.at(t) += 1;
}
else
collisons.insert(pair<float, int>(t, 1));
}
int totalCollisions = 0;
map<float, int>::iterator itr;
for (itr = collisons.begin(); itr != collisons.end(); ++itr) {
totalCollisions += (itr->second)*(itr->second-1)/2;
}
cout << totalCollisions << endl;
return 0;
}
/*
5
5 12 1
16 63 5
-10 24 2
7 24 2
-24 7 2
*/
| true |
838a5d15cc5231e8f6192de5c1366abc53a3d47b | C++ | Ediolot/IA-Coche | /src/utility.cpp | UTF-8 | 1,183 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "../include/utility.hpp"
////////////////////////////////////////////////////////////////////////////////
void displayFPS(ALLEGRO_FONT *font)
{
static uint iteration = 0;
static double elapsed = 0;
static double old_time = 0;
static int fps = 0;
double new_time = al_get_time();
if (++iteration > 20)
{
fps = 20/elapsed;
iteration = 0;
elapsed = 0;
}
else
elapsed += (new_time - old_time);
std::string stringFPS("FPS: "+std::to_string(fps));
al_draw_text(font, BLACK, 10, 10,ALLEGRO_ALIGN_LEFT, stringFPS.c_str());
old_time = new_time;
}
////////////////////////////////////////////////////////////////////////////////
std::string versionToString()
{
uint32_t version_allg = al_get_allegro_version();
std::string version_string("");
int major = version_allg >> 24;
int minor = (version_allg >> 16) & 255;
version_string += NAME+" ";
version_string += std::to_string(VERSION_MAYOR)+"."+std::to_string(VERSION_MINOR)+" (" + STAGE + ") ";
version_string += "[Allegro "+std::to_string(major) + "." + std::to_string(minor) + "]";
return version_string;
}
| true |
c8523e8f50e1deee086a7458e6330cd8233a216e | C++ | Eigenbaukombinat/arduino-workshop | /Sketches/Ultraschall/Ultraschall.ino | UTF-8 | 1,311 | 2.859375 | 3 | [] | no_license | const int echoPin = 7; // Pin für das analoge Echo
const int trigPin = 8; // Pin für den digitalen Triggerimpuls
const int ledPin = 13; // LED
int target = 0; // minimale Zieldistanz
long duration; // Impulsdauer in µs
long mils;
int state = 0;
int cnt = 0;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
// Impuls aussenden
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// auf Impulsantwort warten -> Impulslänge in µs wird zurück gegeben
duration = pulseIn(echoPin, HIGH);
if (state == 0) {
state = 1;
target = duration - 200;
Serial.println("Target:");
Serial.println(target);
}
if (duration < target) {
cnt++;
if (state == 1) {
digitalWrite(ledPin, HIGH);
state = 2;
mils = millis();
Serial.println("Start");
delay(3000);
} else if (state == 2) {
digitalWrite(ledPin, LOW);
state = 1;
mils = millis() - mils;
Serial.println("Seconds:");
Serial.println(mils / 100);
delay(3000);
}
}
Serial.println(duration);
// 50 ms verzögern
delay(50);
}
| true |
d750ee4ef529115a3a58180d1b01f992cebaae0a | C++ | tommag/Farfadet_Arduino | /Farfadet.cpp | UTF-8 | 3,219 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <Farfadet.h>
void Farfadet::init(uint8_t txPin, int stepsPerTurn, int address)
{
init(txPin, stepsPerTurn, Serial1,address);
}
void Farfadet::init(uint8_t txPin, int stepsPerTurn, HardwareSerial& serial, int address)
{
tmc = Estee_TMC5130_UART_Transceiver(txPin, serial, address);
serial.begin(250000);
serial.setTimeout(5); // TMC5130 should answer back immediately when reading a register.
_stepsPerTurn = stepsPerTurn;
_spoolDiameter = 0;
tmc.begin(4, 4, Estee_TMC5130::NORMAL_MOTOR_DIRECTION);
setControlMode(ANGULAR_POSITION_MODE);
tmc.setMaxSpeed(200);
tmc.setRampSpeeds(0, 0.1, 100); //Start, stop, threshold speeds
tmc.setAccelerations(250, 350, 500, 700); //AMAX, DMAX, A1, D1
tmc.resetCommunication();
}
void Farfadet::setAddress(int address)
{
tmc.setSlaveAddress(address);
}
void Farfadet::stop()
{
tmc.stop();
}
void Farfadet::setControlMode(uint8_t mode)
{
if( mode != _controlMode )
{
_controlMode = mode;
if( _controlMode == SPEED_CONTROL_MODE )
{
tmc.setRampMode(Estee_TMC5130::VELOCITY_MODE);
}
else if( _controlMode == LINEAR_POSITION_MODE || _controlMode == ANGULAR_POSITION_MODE )
{
tmc.setRampMode(Estee_TMC5130::POSITIONING_MODE);
}
}
}
void Farfadet::setTargetPosition(float target)
{
if( _controlMode == LINEAR_POSITION_MODE )
{
float nbTurns = target/(M_PI*_spoolDiameter);
long targetSteps = nbTurns * _stepsPerTurn;
tmc.setTargetPosition(targetSteps);
}
else if( _controlMode == ANGULAR_POSITION_MODE )
{
long targetSteps = target*_stepsPerTurn/360.0;
tmc.setTargetPosition(targetSteps);
}
}
void Farfadet::setTargetSpeed(float speed)
{
float rps = speed/(M_PI*_spoolDiameter);
float rpm = rps*60;
setTargetSpeedRPM(rpm);
}
void Farfadet::setTargetSpeedRPM(float rpm)
{
tmc.setMaxSpeed(rpm*_stepsPerTurn/60.0);
}
float Farfadet::getCurrentPosition()
{
if( _controlMode == LINEAR_POSITION_MODE )
{
float nbTurns = tmc.getCurrentPosition()/_stepsPerTurn;
return nbTurns*M_PI*_spoolDiameter;
}
else if( _controlMode == ANGULAR_POSITION_MODE )
{
long currentAngle = tmc.getCurrentPosition()*360.0/_stepsPerTurn;
return currentAngle;
}
return 0;
}
float Farfadet::getCurrentSpeed()
{
float rps = getCurrentSpeedRPM()/60.0;
return rps*M_PI*_spoolDiameter;
}
float Farfadet::getCurrentSpeedRPM()
{
return tmc.getCurrentSpeed()*60.0/_stepsPerTurn;
}
void Farfadet::setAcceleration(float acceleration)
{
tmc.setAcceleration(acceleration);
}
void Farfadet::setAccelerationRamps(float maxAccel, float maxDecel, float startAccel, float finalDecel)
{
tmc.setAccelerations(maxAccel, maxDecel, startAccel, finalDecel);
}
void Farfadet::setSpoolDiameter(float diameter)
{
_spoolDiameter = diameter;
}
float Farfadet::getSpoolDiameter()
{
return _spoolDiameter;
}
void Farfadet::resetCommunication()
{
tmc.resetCommunication();
}
void Farfadet::activateBusOutput()
{
tmc.writeRegister(TMC5130_Reg::IO_INPUT_OUTPUT, 0); //set NAO low
}
Estee_TMC5130_UART::ReadStatus Farfadet::getReadStatus()
{
Estee_TMC5130_UART::ReadStatus readStatus;
tmc.readRegister(TMC5130_Reg::GCONF, &readStatus);
return readStatus;
}
| true |
e66fb3f9b52ebfeaaf86f3be18dee3c565f2d4e7 | C++ | rainscut/tyra | /src/engine/include/modules/camera_base.hpp | UTF-8 | 1,621 | 2.75 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
# ______ ____ ___
# | \/ ____| |___|
# | | | \ | |
#-----------------------------------------------------------------------
# Copyright 2020, tyra - https://github.com/h4570/tyra
# Licenced under Apache License 2.0
# Sandro Sobczyński <sandro.sobczynski@gmail.com>
*/
#ifndef _TYRA_CAMERA_BASE_
#define _TYRA_CAMERA_BASE_
#include "../models/math/plane.hpp"
#include "../models/math/matrix.hpp"
#include "../models/math/vector3.hpp"
#include "../models/screen_settings.hpp"
/** Class responsible for frustum culling */
class CameraBase
{
public:
CameraBase(ScreenSettings *t_screen, Vector3 *t_position);
virtual ~CameraBase(){};
/**
* Frustum planes.
* Set by lookAt() method.
*/
Plane planes[6];
/**
* View matrix
* Set by lookAt() method.
*/
Matrix view;
protected:
/** Pointer to screen settings */
ScreenSettings *screen;
/**
* Adaption of OpenGL lookAt camera.
* Calculates view matrix and update frustum planes
* Should be called every frame.
*/
void lookAt(Vector3 &t_target);
/**
* Do not call this method unless you know what you do.
* Called via lookAt().
* Calculate and update frustum planes.
* http://www.lighthouse3d.com/tutorials/view-frustum-culling/geometric-approach-extracting-the-planes/
*/
void updatePlanes(Vector3 t_target);
private:
Vector3 *p_position;
float farPlaneDist, nearPlaneDist, nearHeight, nearWidth, farHeight, farWidth;
Vector3 ftl, ftr, fbl, fbr, ntl, ntr, nbl, nbr;
Vector3 up; // always 0.0F, 1.0F, 0.0F
};
#endif
| true |
f03f99561ee73812fa6e03078b2a893c4b1e150c | C++ | gregueiras/proj_AEDA_2017 | /src/VehicleMenuView.cpp | UTF-8 | 1,187 | 2.515625 | 3 | [] | no_license | /*
* VehicleMenuView.cpp
*
* Created on: 28 Dec 2017
* Author: jotaa
*/
#include "VehicleMenuView.h"
VehicleMenuView::VehicleMenuView() {
this->u = new Utilities();
}
VehicleMenuView::~VehicleMenuView() {
// TODO Auto-generated destructor stub
}
void VehicleMenuView::printMessage(const string& message) {
cout << message << endl;
}
void VehicleMenuView::printVehicleMenu() {
printMessage(vehicleMenu);
}
void VehicleMenuView::printEnterOption() {
printMessage(enterOption);
}
void VehicleMenuView::printWrongOption() {
printMessage(wrongOption);
}
void VehicleMenuView::printEnd() {
printMessage(end);
}
void VehicleMenuView::printShutdown() {
printMessage(shutdown);
}
void VehicleMenuView::printInformation(const string info) {
printMessage(info);
}
void VehicleMenuView::printPlateNotFound() {
printMessage(plateNotFound);
}
void VehicleMenuView::printEnterPlate() {
printMessage(enterPlate);
}
void VehicleMenuView::printVehicleList() {
printMessage(vehicleList);
}
void VehicleMenuView::printVehicleNotAvailable() {
printMessage(vehicleNotAvailable);
}
void VehicleMenuView::printNoVehicleRegistered() {
printMessage(noVehicleRegistered);
}
| true |
1296a4786dbd0be77b6d6b4248b1d08ce17d217c | C++ | abbyssoul/libsolace | /src/path.cpp | UTF-8 | 8,967 | 2.640625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2016 Ivan Ryabov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*******************************************************************************
* libSolace
* @file path.cpp
*******************************************************************************/
#include "solace/path.hpp"
#include <algorithm> // std::min/std::max
using namespace Solace;
const StringView Path::Delimiter("/");
const StringView SelfRef(".");
const StringView ParentRef("..");
Path makeRoot() {
auto root = makePath(StringView{""});
return root.isOk()
? root.moveResult()
: Path{};
}
const Path Path::Root = makeRoot();
Result<Path, Error>
Solace::makePath(StringView str) {
auto maybeString = makeString(str);
if (!maybeString) {
return maybeString.moveError();
}
auto maybeArray = makeArrayOf<String>(maybeString.moveResult());
if (!maybeArray) {
return maybeArray.moveError();
}
return Ok(makePath(maybeArray.moveResult()));
}
Result<Path, Error>
Path::parse(StringView str, StringView delim) {
Optional<Error> maybeError{};
Vector<String> nonEmptyComponents;
str.split(delim, [&](StringView c, StringView::size_type i, StringView::size_type count) {
if (maybeError) return;
if (nonEmptyComponents.capacity() == 0 && count != 0) {
auto maybeComponents = makeVector<String>(count);
if (maybeComponents) {
nonEmptyComponents = maybeComponents.moveResult();
} else {
maybeError = maybeComponents.moveError();
}
}
if (i + 1 == count && c.empty()) {
return;
}
auto r = makeString(c);
if (r) {
nonEmptyComponents.emplace_back(r.moveResult());
} else {
maybeError = r.moveError();
}
});
if (maybeError) {
return maybeError.move();
}
if (nonEmptyComponents.empty()) {
nonEmptyComponents.emplace_back(String{});
}
return Ok(Path(nonEmptyComponents.toArray()));
}
Path::Iterator&
Path::Iterator::operator++ () {
_index += 1;
return *this;
}
StringView
Path::Iterator::operator-> () const {
return _path[_index].view();
}
String::size_type
Path::length(StringView delim) const noexcept {
auto const delimLen = delim.length();
auto const nbComponents = _components.size();
if (nbComponents == 0) {
return 0;
} else if (nbComponents == 1) {
const auto& one = _components[0];
return (one.empty())
? delimLen // Root - single empty item
: one.length();
}
String::size_type len = 0;
for (auto const& s : _components) { // Accomulate:
len += (delimLen + s.length());
}
return (len - delimLen);
}
int Path::compareTo(const Path& other) const {
const size_type minLen = std::min(getComponentsCount(), other.getComponentsCount());
// Find where this path diverges from other:
for (size_type i = 0; i < minLen; ++i) {
const auto& thisComponent = _components[i];
const auto& otherComponent = other._components[i];
auto const diff = thisComponent.compareTo(otherComponent);
if (diff != 0) {
return diff;
}
}
return static_cast<int>(getComponentsCount()) - static_cast<int>(other.getComponentsCount());
}
bool Path::startsWith(const Path& other) const {
if (empty())
return other.empty();
if (other.empty())
return empty();
if (other.length() > length())
return false;
auto const nbComponents = other.getComponentsCount();
for (size_type i = 0; i < nbComponents; ++i) {
const auto& otherComponent = other._components[i];
const auto& thisComponent = _components[i];
if (!thisComponent.equals(otherComponent)) {
return thisComponent.startsWith(otherComponent) && (i + 1 == nbComponents);
}
}
return true;
}
bool Path::endsWith(const Path& other) const {
if (empty()) {
return other.empty();
}
if (other.empty()) {
return empty();
}
if (other.length() > length()) {
return false;
}
auto const thisEnd = _components.size();
auto const nbComponents = other.getComponentsCount();
for (size_type i = 0; i < nbComponents; ++i) {
const auto& thisComponent = _components[thisEnd - 1 - i];
const auto& otherComponent = other._components[nbComponents - 1 - i];
if (!thisComponent.equals(otherComponent)) {
return thisComponent.endsWith(otherComponent) && (i + 1 == nbComponents);
}
}
return true;
}
bool Path::contains(const Path& path) const {
auto const nbOtherComponents = path.getComponentsCount();
auto const nbThisComponents = getComponentsCount();
if (nbOtherComponents > nbThisComponents) {
// Longer path can not be contained in this shorter one
return false;
}
for (size_type firstMatch = 0, nbComponents = nbThisComponents - nbOtherComponents + 1;
firstMatch < nbComponents;
++firstMatch) {
const auto& a = _components[firstMatch];
if (a.equals(path._components[0])) {
bool allMatched = true;
for (size_type i = 1; i < nbOtherComponents; ++i) {
const auto& b = _components[firstMatch + i];
if (!b.equals(path._components[i])) {
allMatched = false;
break;
}
}
if (allMatched)
return true;
}
}
return false;
}
bool
Path::isAbsolute() const noexcept {
return (!empty() && _components[0].empty());
}
bool
Path::isRelative() const noexcept {
return !isAbsolute();
}
Path
Path::normalize() const {
// FIXME(abbyssoul): Dynamic memory re-allocation!!!
auto maybeComponents = makeVector<String>(_components.size()); // Assumption: we don't make path any longer
if (!maybeComponents) {
return Path{}; // fixme, maybe return a view or an error
}
auto& components = maybeComponents.unwrap();
for (auto const& c : _components) {
if (c.equals(SelfRef)) { // Skip '.' entries
continue;
} else if (c.equals(ParentRef) && components.size() > 0) { // Skip '..' entries
components.pop_back();
} else {
auto r = makeString(c);
if (r) {
components.emplace_back(r.moveResult());
}
}
}
return Path{components.toArray()};
}
Path
Path::getParent() const {
auto const nbComponents = _components.size();
if (nbComponents < 2) {
auto maybeArray = makeArray<String>(_components); // Copy components vector
return maybeArray
? Path{maybeArray.moveResult()}
: Path{};
}
auto const nbBaseComponents = nbComponents - 1;
auto maybeBasePath = makeVector<String>(nbBaseComponents);
if (!maybeBasePath) {
return Path{};
}
auto& basePath = maybeBasePath.unwrap();
// TODO(abbyssoul): Should use array copy
for (size_type i = 0; i < nbBaseComponents; ++i) {
auto r = makeString(_components[i]);
if (r) {
basePath.emplace_back(r.moveResult());
}
}
return Path{basePath.toArray()};
}
StringView
Path::getBasename() const {
auto const nbComponents = _components.size();
return (nbComponents == 1 && _components[0].empty())
? Delimiter
: (nbComponents == 0
? String::Empty
: _components[nbComponents - 1]).view();
}
StringView Path::getComponent(size_type index) const {
return _components[index].view();
}
Path
Path::subpath(size_type from, size_type to) const noexcept {
auto const nbComponent = _components.size();
from = std::min(from, nbComponent);
to = std::max(from, std::min(to, nbComponent));
auto maybeComponenets = makeVector<String>(to - from);
auto& components = maybeComponenets.unwrap();
for (size_type i = from; i < to; ++i) {
auto r = makeString(_components[i]);
if (r) {
components.emplace_back(r.moveResult());
}
}
return {components.toArray()};
}
bool
Path::equals(Path const& rhv) const noexcept {
return (&rhv == this) || rhv._components == _components;
}
String
Path::toString(StringView delim) const {
if (isAbsolute() && _components.size() == 1) {
auto delimString = makeString(delim);
return (delimString)
? delimString.moveResult()
: String{};
}
auto maybePath = makeStringJoin(delim, _components.view());
return (maybePath)
? maybePath.moveResult()
: String{};
}
| true |
5be90d0309805bfae41509bd17d626ce98381fb8 | C++ | gypaos/Kinematics | /TNoyau.cxx | UTF-8 | 7,453 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <stdlib.h>
#include <cmath>
using namespace std;
#include "TNoyau.h"
#include "Constant.h"
ClassImp(TNoyau)
TNoyau::TNoyau()
: fNom("unknown"),
fMasse(0),
fCharge(0),
fExcesMasse(0),
fExcitationEnergy(0),
fDemiVie("unknown"),
fSpin(0),
fParite("unknown"),
fEnergy(0),
fMomentum(0),
fWaveVector(0),
fBeta(0),
fGamma(0),
fBrho(0),
fTimeOfFlight(0)
{
//----------- Constructeur par defaut ----------
// initialize chart
for (Int_t i = 0; i < 119; i++) {
for (Int_t j = 0; j < 294; j++) {
fChart[i][j] = 0;
}
}
// on ouvre le fichier de donnees
TString path = getenv("DATANUC");
TString fileName = path + "/Masses/nubtab03.asc";
ifstream fich;
fich.open(fileName);
if (!fich)
cout << "Probleme d'ouverture dans le fichier " << fileName << endl;
// on cherche la ligne correspondante dans le fichier de donnes
Char_t line[256];
TString s, s_masse, s_charge;
Int_t masse, charge;
while (!fich.eof()) {
fich.getline(line, sizeof(line));
s = line;
s_masse = s(0,3);
s_charge = s(4,4);
masse = atoi(s_masse.Data());
charge = floor(atoi(s_charge.Data())/10);
fChart[charge][masse] = 1;
}
}
TNoyau::TNoyau(Int_t Z, Int_t A)
{
//----------- Constructeur avec des entiers ------------
// (Z,A) charge et masse du noyau
// on ouvre le fichier de donnees
TString path = getenv("DATANUC");
TString fileName = path + "/Masses/nubtab03.asc";
ifstream fich;
fich.open(fileName);
if ( !fich )
cout << "Probleme d'ouverture dans le fichier " << fileName << endl;
// on cherche la ligne correspondante dans le fichier de donnes
Char_t line[256];
TString s, s_masse, s_charge;
Int_t masse, charge;
while ( !fich.eof() ) {
fich.getline(line, sizeof(line));
s = line;
s_masse = s(0,3);
s_charge = s(4,4);
masse = atoi( s_masse.Data() );
charge = atoi( s_charge.Data() );
if ( (masse == A && charge == Z*10) ) break;
}
// on extrait les proprietes du noyau
Extract(line);
}
TNoyau::TNoyau(const char* name)
{
//----------- Constructeur avec une chaine de caracteres ------------
// name = "18F", "4He" ...
// on ouvre le fichier de donnees
TString path = getenv("DATANUC");
TString fileName = path + "/Masses/nubtab03.asc";
ifstream fich;
fich.open(fileName);
if ( !fich )
cout << "Probleme d'ouverture dans le fichier " << fileName << endl;
// on cherche la ligne correspondante dans le fichier de donnes
Char_t line[256];
TString s, nom;
while ( !fich.eof() ) {
fich.getline(line, sizeof(line));
s = line;
nom = s(11,6);
nom = nom.Strip();
if (nom.Contains(name) && nom.Length() == strlen(name)) break;
}
// on extrait les proprietes du noyau
Extract(line);
}
TNoyau::~TNoyau()
{
//----------- Destructeur par defaut ------------
}
void TNoyau::Extract(char *line)
{
// Extract() permet d'extraire les parametres du noyau, une fois qu'il est
// trouve dans le fichier de donnees "nubtab97.asc"
// Extract() est utilise par le constructeur
TString s = (TString) line;
// on teste si le noyau existe
if ( s.IsNull() ) {
cout << "Attention, ce noyau n'existe pas" << endl;
fNom = "unknown";
fMasse = 0;
fCharge = 0;
fExcesMasse = 0;
fDemiVie = "unknown";
fSpin = 0;
fParite = "unknown";
}
else {
// on extrait le nom
fNom = s(11,6);
fNom = fNom.Strip();
// on extrait la masse et la charge
TString s_masse = s(0,3);
TString s_charge = s(4,4);
fMasse = atoi( s_masse.Data() );
fCharge = atoi( s_charge.Data() ); fCharge /= 10;
// on extrait l'exces de masse
TString s_exces = s(18,10);
fExcesMasse = atof( s_exces.Data() );
// on extrait la demi-vie
fDemiVie = s(60,11);
// on extrait le spin et la parite
TString jpi = s(79,13);
// parite
if ( jpi.Contains("+") ) fParite = "+";
if ( jpi.Contains("-") ) fParite = "-";
if ( !jpi.Contains("+") && !jpi.Contains("-") ) fParite = "?";
//spin
if ( jpi.Contains("0") ) fSpin = 0;
if ( jpi.Contains("1") ) fSpin = 1;
if ( jpi.Contains("2") ) fSpin = 2;
if ( jpi.Contains("3") ) fSpin = 3;
if ( jpi.Contains("4") ) fSpin = 4;
if ( jpi.Contains("5") ) fSpin = 5;
if ( jpi.Contains("6") ) fSpin = 6;
if ( jpi.Contains("7") ) fSpin = 7;
if ( jpi.Contains("8") ) fSpin = 8;
if ( jpi.Contains("9") ) fSpin = 9;
if ( jpi.Contains("10") ) fSpin = 10;
if ( jpi.Contains("1/2") ) fSpin = 0.5;
if ( jpi.Contains("3/2") ) fSpin = 1.5;
if ( jpi.Contains("5/2") ) fSpin = 2.5;
if ( jpi.Contains("7/2") ) fSpin = 3.5;
if ( jpi.Contains("9/2") ) fSpin = 4.5;
if ( jpi.Contains("11/2") ) fSpin = 5.5;
if ( jpi.Contains("13/2") ) fSpin = 6.5;
if ( jpi.Contains("15/2") ) fSpin = 7.5;
if ( jpi.Contains("17/2") ) fSpin = 8.5;
if ( jpi.Contains("19/2") ) fSpin = 9.5;
if ( jpi.Contains("21/2") ) fSpin = 10.5;
}
}
bool TNoyau::IsKnown(Int_t charge, Int_t mass) const
{
bool isKnown = false;
if (fChart[charge][mass] == 1) isKnown = true;
return isKnown;
}
Int_t TNoyau::FirstKnown(Int_t charge) const
{
Int_t mass = 0;
while (!IsKnown(charge, mass)) {
mass++;
}
return mass;
}
Int_t TNoyau::LastKnown(Int_t charge) const
{
Int_t mass = 277;
while (!IsKnown(charge, mass)) {
mass--;
}
return mass;
}
bool TNoyau::IsStable() const
{
bool isStable = false;
if (fDemiVie.Contains("stbl")) isStable = true;
return isStable;
}
Double_t TNoyau::Mass() const
{
// we assume ions to be fully stripped
return (fMasse + fExcesMasse / 1000 / uma - me*fCharge) * uma;
// we neglect electron binding energy
// return (fMasse + fExcesMasse / 1000 / uma) * uma;
}
void TNoyau::EnergyToBrho()
{
fBrho = sqrt(pow(fEnergy,2) + 2*fEnergy*Mass()) * 1e6 / C / fCharge;
}
void TNoyau::EnergyToMomentum()
{
fMomentum = sqrt(pow(fEnergy,2) + 2*fEnergy*Mass());
}
void TNoyau::MomentumToWaveVector()
{
fWaveVector = fMomentum / hbarc;
}
void TNoyau::BetaToGamma()
{
fGamma = 1 / sqrt(1 - pow(fBeta, 2));
}
void TNoyau::BrhoToEnergy()
{
Double_t P = fBrho / 1e6 * C * fCharge;
vector<Double_t> E = QuadraticSolver(1, 2*Mass(), -pow(P,2));
for (UInt_t i = 0; i < E.size(); i++) {
if (E.at(i) > 0) fEnergy = E.at(i);
}
}
vector<Double_t> TNoyau::QuadraticSolver(Double_t a, Double_t b, Double_t c) const
{
// Function to solve ax^2 + bx + c = 0
vector<Double_t> result;
Double_t delta = pow(b, 2) - 4*a*c;
if (delta > 0) {
result.push_back((-b - sqrt(delta)) / 2 / a);
result.push_back((-b + sqrt(delta)) / 2 / a);
}
return result;
}
void TNoyau::Print() const
{
//------------ Imprime a l'ecran les caracteristiques d'un noyau -------
cout << endl;
cout << fNom << " : " << "Z = " << fCharge << " A = " << fMasse << " Ex = " << fExcesMasse << " keV " << fParite << endl;
cout << " T1/2 = " << fDemiVie << endl;
}
| true |
cb837a00e3e68f3e69a4acc1f4dc69b11d65db6b | C++ | avida/sandbox | /cpp/compare.cpp | UTF-8 | 212 | 2.96875 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
int main()
{
const char* c_str = "Hello";
cout << "Hi" <<endl;
if ("Hello" == string(c_str))
cout << "MATCH!!\n";
return 0;
} | true |
6eee460a5c6553ed0028eb6a980a848131d6c3aa | C++ | whm200410/suace | /suace.h | UTF-8 | 414 | 2.625 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include <opencv2\opencv.hpp>
using namespace cv;
/*
@brief Enhance the contrast with SUACE;
@param src source image with the type CV_8UC1.
@param dst output image
@param distance the old reference contrast range to be enhanced. less value means more contrast.
@param sigma the sigma value of the Gaussina filter in SUACE
*/
void performSUACE(Mat & src, Mat & dst, int distance=20, double sigma=7);
| true |
c6897eb9263a1df73f68fece13031ee8300c6dfd | C++ | OC-MCS/drawing-01-DietrichWasHere | /Drawing/main.cpp | UTF-8 | 3,522 | 2.890625 | 3 | [] | no_license | //================================================
// Dietrich Versaw
// Drawing Program
// Due 3/25/19
//================================================
#include <iostream>
#include <fstream>
using namespace std;
#include <SFML\Graphics.hpp>
#include <cctype>
#include "SettingsMgr.h"
#include "ShapeMgr.h"
#include "SettingsUI.h"
#include "DrawingUI.h"
using namespace sf;
// Finish this code. Other than where it has comments telling you to
// add code, you shouldn't need to add any logic to main to satisfy
// the requirements of this programming assignment
// run the program
int main()
{
// declare size of window
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
RenderWindow window(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Drawing");
window.setFramerateLimit(60);
SettingsMgr settingsMgr(Color::Red, ShapeEnum::CIRCLE);
SettingsUI settingsUI(&settingsMgr);
ShapeMgr shapeMgr;
DrawingUI drawingUI(Vector2f(200, 0), Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT), 25);
fstream file; // file storage
// ********* Add code here to make the managers read from shapes file (if the file exists)
char loadFile; // char for user input to load file or start from scractch
cout << "Load file (Y / N)? Old will be overwritten regardless! ";
cin >> loadFile;
if (tolower(loadFile) == 'y')
{
// load file for reading
file.open("shapes.bin", ios::in | ios::out | ios::binary);
settingsMgr.loadFromFile(file);
shapeMgr.loadFile(file);
file.close();
settingsUI.loadPresets();
}
while (window.isOpen())
{
Event event; // to hold mouse actions for each frame
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
// overwrite the old file
// not entirely sure how it overwrites all the other shapes, but it does
// no remnants from previous file
// I guess bringing it in as read only erases the entirety of the file...?
// yes, I realise this assumptiveness is a poor attitude for programming
window.close();
file.open("shapes.bin", ios::out | ios::binary);
settingsMgr.saveToFile(file);
shapeMgr.saveFile(file);
file.close();
// write all data to shapes file
}
else if (event.type == Event::MouseButtonReleased)
{
// maybe they just clicked on one of the settings "buttons"
// check for this and handle it. Done!
Vector2f mousePos = window.mapPixelToCoords(Mouse::getPosition(window));
// get mouse location for, check for clicking of ui
settingsUI.handleMouseUp(mousePos);
}
else if (event.type == Event::MouseMoved && Mouse::isButtonPressed(Mouse::Button::Left))
{
Vector2f mousePos = window.mapPixelToCoords(Mouse::getPosition(window));
// check to see if mouse is in the drawing area, using the vector2f
if (drawingUI.isMouseInCanvas(mousePos))
{
// add a shape to the list based on current settings
shapeMgr.addShape(mousePos, settingsMgr.getCurShape(), settingsMgr.getCurColor());
}
}
}
// The remainder of the body of the loop draws one frame of the animation
window.clear();
// this should draw the left hand side of the window (all of the settings info)
settingsUI.draw(window);
// this should draw the rectangle that encloses the drawing area, then draw the
// shapes. This is passed the shapeMgr so that the drawingUI can get the shapes
// in order to draw them. This redraws *all* of the shapes every frame.
drawingUI.draw(window, &shapeMgr);
window.display();
} // end body of animation loop
return 0;
} | true |
b64678bc621d8411b1a5c3c17a75d5235aee8d3f | C++ | shenjunHZ/PabulumElement | /C_Interface/Common/Util/FileUtil.h | GB18030 | 1,114 | 2.765625 | 3 | [] | no_license | #ifndef __COMMON_FILEUTIL_H__
#define __COMMON_FILEUTIL_H__
#include "Common/CommonGlobal.h"
#include <vector>
#include <string>
namespace Common
{
// ȡļб
COMMON_EXPORT std::vector<std::string> GetFileList(const char* pDirName);
// ȡļб
COMMON_EXPORT std::vector<std::string> GetFileNameList(const char* pDirName);
// ļ
COMMON_EXPORT bool MakeDir(const char* pDirName);
// ļ ԭc
COMMON_EXPORT bool MakeDirEx(const char* pDirName);
// ɾļ
COMMON_EXPORT bool RemoveFile(const char* pFileName);
// windows ļЧԣЧַʹá_滻.
COMMON_EXPORT std::string GetValidFileName(const char* szFileName);
// жļǷ
COMMON_EXPORT bool FileExists(const char* pFilePath);
// ļ
COMMON_EXPORT bool RenameFile(const char* pOldFileName, const char* pNewFileName);
// ļ
COMMON_EXPORT bool CopyFileFunc(const char* pSrcFile, const char* pDstFile);
// ȡִг·
COMMON_EXPORT std::string GetCurDirPath();
}
#endif | true |
8afb49e60a95a03369f15a55fce98f3295e9da16 | C++ | pluruel/Algorithm-Study | /Backjoon/b_17822/main.cpp | UTF-8 | 2,593 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <queue>
#define INSIDE ty <= N && ty > 0
using namespace std;
int dy[4] = { 0, 1, 0, -1 };
int dx[4] = {1, 0, -1, 0};
int N, M, T;
int p[51][51];
bool search(int y, int x) {
int n = p[y][x];
if (!n) return false;
queue<pair<int, int> > q;
queue<pair<int, int> > q2;
q.push({y, x});
bool checked[51][51] = {0,};
while(q.size()) {
auto a = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int ty = a.first + dy[i], tx = (a.second + dx[i] + M) % M;
if((INSIDE) && !checked[ty][tx] && p[ty][tx] == n) {
q.push({ty,tx});
q2.push({ty, tx});
checked[ty][tx] = 1;
}
}
}
if(q2.size()) {
q2.push({y,x});
while(q2.size()) {
auto a = q2.front();
q2.pop();
p[a.first][a.second] = 0;
}
}else {
return false;
}
return true;
}
void turn(int x, int d, int k) {
if(d) k = -k;
k %= M;
k = (M + k)% M;
queue<int> q;
for (int pp = x; pp <= N; pp+= x) {
for (int i = 0; i < M + k; ++i) {
if(i < M) {
q.push(p[pp][i]);
}
if(i >= k) {
p[pp][i%M] = q.front();
q.pop();
}
}
}
int judge = 0;
for (int i = 1; i <= N; ++i) {
for (int j = 0; j < M; ++j) {
judge += search(i,j);
}
}
if(!judge){
int sum = 0, n = 0;;
for (int i = 1; i <= N; ++i) {
for (int j = 0; j < M; ++j) {
if(p[i][j]){
sum += p[i][j]; n++;
}
}
}
for (int i = 1; i <= N; ++i) {
for (int j = 0; j < M; ++j) {
if(p[i][j]) {
if(p[i][j] * n > sum)
p[i][j]--;
else if(p[i][j] * n < sum)
p[i][j]++;
}
}
}
}
return;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> N >> M >> T;
for (int i = 1; i <= N; ++i) {
for (int j = 0; j < M; ++j) {
cin >> p[i][j];
}
}
for (int i = 0; i< T; ++i) {
int x,d,k;
cin >> x >> d >> k;
turn(x,d,k);
}
int sum = 0;
for (int i = 1; i <= N; ++i) {
for (int j = 0; j < M; ++j) {
sum += p[i][j];
}
}
cout << sum << '\n';
return 0;
}
| true |
3a8e1aa9adad934a91ebdf2980fa9650c3fb2231 | C++ | SauliusE/thesisWork | /OpenDaVINCI-msv/apps/2015/driver/src/Driver.cpp | UTF-8 | 8,678 | 2.625 | 3 | [
"AFL-3.0"
] | permissive | /*
* Mini-Smart-Vehicles.
*
* This software is open source. Please see COPYING and AUTHORS for further information.
*/
#include <stdio.h>
#include <math.h>
#include "core/io/ContainerConference.h"
#include "core/data/Container.h"
#include "core/data/Constants.h"
#include "core/data/control/VehicleControl.h"
#include "core/data/environment/VehicleData.h"
// Data structures from msv-data library:
#include "SteeringData.h"
#include "SensorBoardData.h"
#include "UserButtonData.h"
#include "Driver.h"
int carstate = 3; // What the car is doing at the moment. 3 = parking
int interval = 0; // Used for timer to define how long time to do something
int parkingState = -1; // Used for different steps during parking
double speed = 0.0; // Speed of the car
double steering = 0.0; // Angle of the wheels
timeval timer; // General starttimer
timeval timer2; // General timer that gets current time
namespace msv {
using namespace std;
using namespace core::base;
using namespace core::data;
using namespace core::data::control;
using namespace core::data::environment;
Driver::Driver(const int32_t &argc, char **argv) :
ConferenceClientModule(argc, argv, "Driver") {
}
Driver::~Driver() {}
void Driver::setUp() {
// This method will be call automatically _before_ running body().
}
void Driver::tearDown() {
// This method will be call automatically _after_ return from body().
}
// This method will do the main data processing job.
ModuleState::MODULE_EXITCODE Driver::body() {
while (getModuleState() == ModuleState::RUNNING) {
// In the following, you find example for the various data sources that are available:
// 1. Get most recent vehicle data:
Container containerVehicleData = getKeyValueDataStore().get(Container::VEHICLEDATA);
VehicleData vd = containerVehicleData.getData<VehicleData> ();
cerr << "Most recent vehicle data: '" << vd.toString() << "'" << endl;
// 2. Get most recent sensor board data:
Container containerSensorBoardData = getKeyValueDataStore().get(Container::USER_DATA_0);
SensorBoardData sbd = containerSensorBoardData.getData<SensorBoardData> ();
cerr << "Most recent sensor board data: '" << sbd.toString() << "'" << endl;
// 3. Get most recent user button data:
Container containerUserButtonData = getKeyValueDataStore().get(Container::USER_BUTTON);
UserButtonData ubd = containerUserButtonData.getData<UserButtonData> ();
cerr << "Most recent user button data: '" << ubd.toString() << "'" << endl;
// 4. Get most recent steering data as fill from lanedetector for example:
Container containerSteeringData = getKeyValueDataStore().get(Container::USER_DATA_1);
SteeringData sd = containerSteeringData.getData<SteeringData> ();
cerr << "Most recent steering data: '" << sd.toString() << "'" << endl;
// Design your control algorithm here depending on the input data from above.
if (carstate == 3) {
cerr << "parkingState: '" << parkingState << "'" << endl;
speed = 1.0;
// Begin parking sequence once an object is detected
if (sbd.getDistance(2) > 0.0 && parkingState == -1) {
parkingState = 0;
}
// start the timer when an empty space is detected
if (sbd.getDistance(2) < 0.0 && parkingState == 0) {
parkingState = 1;
gettimeofday(&timer, 0);
}
// start timer2 when object is detected
if (sbd.getDistance(2) > 0.0 && parkingState == 1) {
parkingState = 2;
gettimeofday(&timer2, 0);
interval = 5500;
}
// checking if the space is large enough for parking
if (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000) * speed > interval && parkingState == 2) {
parkingState = 3;
interval = 12500;
gettimeofday(&timer, 0);
}
else if (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000) * speed <= interval && parkingState == 2) {
parkingState = 0;
}
// Turning right backwords to park
if (parkingState == 3) {
gettimeofday(&timer2, 0);
speed = -0.5;
steering = 25 * Constants::DEG2RAD;
if (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000) <= 900) {
speed = 1.0;
}
if (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000) <= 2000) {
steering = 0 * Constants::DEG2RAD;
}
if (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000) >= interval) {
interval = 12000 ;
gettimeofday(&timer, 0);
parkingState = 4;
}
cerr << "interval3: '" << (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000)) << "'" << endl;
}
// Straightening the car
if (parkingState == 4) {
gettimeofday(&timer2, 0);
speed = -0.5;
steering = -25 * Constants::DEG2RAD;
if (((timer2.tv_sec - timer.tv_sec) * 1000) + ((timer2.tv_usec - timer.tv_usec) / 1000) * speed >= interval || (sbd.getDistance(0) < 0.5 && sbd.getDistance(1) > 0.0) ) {
speed = 0.0;
parkingState = 5;
}
}
if (parkingState == 5) {
speed = 0.5;
steering = 25 * Constants::DEG2RAD;
if (abs(sbd.getDistance(0) - sbd.getDistance(1)) < 0.1) {
speed = 0.0;
parkingState = 6;
}
}
if (parkingState == 6) {
speed = -0.5;
steering = 0;
if (abs(sbd.getDistance(0)) < 1.0) {
speed = 0.0;
}
}
// Create vehicle control data.
VehicleControl vc;
// With setSpeed you can set a desired speed for the vehicle in the range of -2.0 (backwards) .. 0 (stop) .. +2.0 (forwards)
vc.setSpeed(speed);
// With setSteeringWheelAngle, you can steer in the range of -26 (left) .. 0 (straight) .. +25 (right)
// double desiredSteeringWheelAngle = 0; // 4 degree but SteeringWheelAngle expects the angle in radians!
vc.setSteeringWheelAngle(steering);
// You can also turn on or off various lights:
vc.setBrakeLights(false);
vc.setLeftFlashingLights(false);
vc.setRightFlashingLights(true);
// Create container for finally sending the data.
Container c(Container::VEHICLECONTROL, vc);
// Send container.
getConference().send(c);
}
}
return ModuleState::OKAY;
}
} // msv
| true |
cd0b829bea54179ac8d5602871a8cd646661db3a | C++ | hkduke/MIE-BPR-Tutorial3 | /Tutorial3-TimeSetup/Parser.cpp | UTF-8 | 689 | 3.078125 | 3 | [] | no_license | #include "stdafx.h"
#include "Parser.h"
char Parser::delimiter = '|';
Parser::Parser(){
}
Parser::~Parser(){
}
vector<string> Parser::split(const string &s, char delim) {
stringstream ss(s);
string item;
vector<string> tokens;
while (getline(ss, item, delim)) {
tokens.push_back(item);
}
return tokens;
}
void Parser::parseTime(string timeString, SYSTEMTIME* st) {
vector<string> att = Parser::split(timeString, Parser::delimiter);
string min = att[0];
string hour = att[1];
string day = att[2];
string month = att[3];
string year = att[4];
st->wMinute = stoi(min);
st->wHour = stoi(hour);
st->wDay = stoi(day);
st->wMonth = stoi(month);
st->wYear = stoi(year);
} | true |
4240cf2a30a1e00ee10abd5f0321205067d74d50 | C++ | HANXU2018/HBU2019programingtext | /2020程序设计天梯赛/未命名7.cpp | UTF-8 | 553 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<queue>
#include<vector>
using namespace std;
int main(){
int n;
cin>>n;
vector<int>num(n);
queue<int>ans;
for(int i=0;i<n;i++){
cin>>num[i];
}
int flag=0;
ans.push(0);
ans.push(n-1);
int count=n;
while(ans.size()!=0){
int a= ans.front();
ans.pop();
int b= ans.front();
ans.pop();
if(flag==1){
cout<<" ";
}
flag=1;
cout<<num[b];
count--;
if(count==0){
return 0;
}
if(a<b){
ans.push(a);
ans.push((a+b-1)/2);
ans.push((a+b-1)/2+1);
ans.push(b-1);
}
}
return 0;
}
| true |
1594e48a538e38494b46c1f2867579639e367166 | C++ | nassemz/4inRow | /Game Server/LoginThread.cpp | UTF-8 | 2,704 | 2.671875 | 3 | [] | no_license | ///////////////////////////////////////////////////
// LoginThread.cpp
// By: Nissim Zohar ID: 066412149
///////////////////////////////////////////////////
#include "LoginThread.h"
#include "../common/StreamSocket.h"
LoginThread::LoginThread(StreamSocket *socket,TableManager* manag): m_socket(socket), mannager(manag) ,m_finished(false) {}
int LoginThread::Process() {
Reply reply_answer;
int option;
bool flag=false;
Login l;
try {
char buf[256];
//option
//1) Registration
//2) Login
//3) Report
m_socket->recv(buf,sizeof(int));
option=StringToInt(buf);
// connect to data base server
StreamSocket socket;
socket.connect(mannager->GetDbIP(),mannager->GetDbPort());
flag=true;
switch (option)
{
case 1:
/////////////////////////////////////////////
//Registration
/////////////////////////////////////////////
Registration r;
m_socket->recv(buf,sizeof(Registration));
r = (struct Registration&) buf;
// talk with the server Registration
buf[0] = 0;
itoa(option,buf,10);
socket.send(buf,4);
socket.send( (char *)& r, sizeof(Registration));
socket.recv(buf,sizeof(Reply));
break;
case 2:
/////////////////////////////////////////////
//Login
/////////////////////////////////////////////
m_socket->recv(buf,sizeof(Login));
l = (struct Login&) buf;
// talk with the server Login
buf[0] = 0;
itoa(option,buf,10);
socket.send(buf,4);
socket.send( (char *)& l, sizeof(Login));
socket.recv(buf,sizeof(Reply));
break;
case 3:
/////////////////////////////////////////////
//Report
/////////////////////////////////////////////
m_socket->recv(buf,sizeof(Login));
l = (struct Login&) buf;
// talk with the server Login
buf[0] = 0;
itoa(option,buf,10);
socket.send(buf,4);
socket.send( (char *)& l, sizeof(Login));
socket.recv(buf,sizeof(Reply));
break;
default:
break;
}
//returnig to the client with the reply msg
reply_answer= (struct Reply&) buf;
m_socket->send( (char *)& reply_answer, sizeof(Reply));
//add the player to the mannager only if loged on as OK
if((option == 2) && (reply_answer.status == OK) && (reply_answer.stonoff == NO ))
{
Player* player_login = new Player(l.username,m_socket);
mannager->addPlayerToTable(player_login);
}
}
catch (Socket::SocketException e) {
std::cout << e.what() << std::endl;
try
{
if(flag==false)
{
reply_answer.status = FAIL;
m_socket->send( (char *)& reply_answer, sizeof(Reply));
}
}catch (Socket::SocketException e) {
}
}
// tell main this thread is finished
m_finished = true;
return 0;
}
LoginThread::~LoginThread() {
}
| true |
af219cf30733cca41b69b51f18780ee2531e6c20 | C++ | Deeds85/BeginningGameProgramming | /CreateSurface/CreateSurface/winmain.cpp | UTF-8 | 4,629 | 2.796875 | 3 | [] | no_license | #include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <time.h>
#include <iostream>
using namespace std;
//application title
const string APPTITLE = "Create Surface Program";
//macro to read the keyboard
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code)&0x8000)?1:0)
//screen resolution
#define SCREENW 1024
#define SCREENH 768
//Direct 3D objects
LPDIRECT3D9 d3d = NULL;
LPDIRECT3DDEVICE9 d3ddev = NULL;
LPDIRECT3DSURFACE9 backbuffer = NULL;
LPDIRECT3DSURFACE9 surface = NULL;
RECT rect;
bool gameover = false;
//Game Initialization Function
bool Game_Init(HWND hwnd)
{
//Initialize Direct3D
d3d = Direct3DCreate9(D3D_SDK_VERSION);
if (d3d == NULL)
{
MessageBox(hwnd, "Error Initializing Direct3D", "Error", MB_OK);
return false;
}
//set Direct3D presentation parameters
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferWidth = SCREENW;
d3dpp.BackBufferHeight = SCREENH;
d3dpp.hDeviceWindow = hwnd;
//create Direct3D device
d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);
if(!d3ddev)
{
MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK);
return false;
}
//set random number seed
srand(time(NULL));
//clear the backbuffer to black
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
//create surface
HRESULT result = d3ddev->CreateOffscreenPlainSurface(
SCREENW, //width of the surface
SCREENH, //height of the surface
D3DFMT_X8R8G8B8, //surface format
D3DPOOL_DEFAULT, //memory pool to use
&surface, //pointer to the surface
NULL); //reserved (always NULL)
if (!SUCCEEDED(result)) return false;
//load surface from file into newly created surface
result = D3DXLoadSurfaceFromFile(
surface, //destination surface
NULL, //destination palette
NULL, //destination rectangle
"legotron.bmp", //source filename
NULL, //source rectangle
D3DX_DEFAULT, //controls how image is filtered
0, //for transparency (0 for none)
NULL); //source image info (usually NULL)
//make sure the image was loaded okay
if(!SUCCEEDED(result)) return false;
//create pointer to the back buffer
d3ddev->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO, &backbuffer);
rect.left = 0;
rect.right = SCREENW / 2;
rect.top = 0;
rect.bottom = SCREENH / 2;
return true;
}
//Game update function
void Game_Run(HWND hwnd)
{
// make sure the Direct3D device is valid
if(!d3ddev) return;
//start rendering
if(d3ddev->BeginScene())
{
//draw surface to the backbuffer
d3ddev->StretchRect(surface, NULL , backbuffer, &rect, D3DTEXF_NONE);
//stop rendering
d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);
}
//check for escape key to exit program
if(KEY_DOWN(VK_ESCAPE))
PostMessage(hwnd, WM_DESTROY, 0, 0);
}
//Game shutdown function
void Game_End(HWND hwnd)
{
if(surface) surface->Release();
if(d3ddev) d3ddev->Release();
if(d3d) d3d->Release();
}
//Windows event callback function
LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
gameover = true;
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
//Windows entry point function
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
//create the window class structure
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = APPTITLE.c_str();
wc.hIconSm = NULL;
RegisterClassEx(&wc);
//create a new window
HWND window = CreateWindow(APPTITLE.c_str(), APPTITLE.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, SCREENW, SCREENH, NULL, NULL, hInstance, NULL);
//was there an error creating the window?
if(window == 0) return 0;
//display the window
ShowWindow(window, nCmdShow);
UpdateWindow(window);
//initialize the game
if(!Game_Init(window)) return 0;
//main message loop
MSG message;
while(!gameover)
{
if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
Game_Run(window);
}
return message.wParam;
} | true |
164bcac993a15122fb26cff021759a2163d0a905 | C++ | cs2103jan2015-w10-4c/main | /TaskHubTest/StorageControllerTest.cpp | UTF-8 | 1,078 | 2.625 | 3 | [] | no_license | //@author A0111322E
#include "stdafx.h"
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TaskHubTest{
TEST_CLASS(StorageControllerTest) {
public:
TEST_METHOD(TestSetFileName){
StorageController* test = new StorageController();
//test case 1
std::string fileName1("a.txt");
std::string expectedResult1("a.txt");
test->setFileName(fileName1);
std::string testResult1 = test->getFileName();
Assert::AreEqual(expectedResult1, testResult1);
//test case 2: empty string
std::string expectedResult2("");
test->setFileName("");
std::string testResult2 = test->getFileName();
Assert::AreEqual(expectedResult2, testResult2);
//test case 3: longer string with non numerical or alphabetical symbols
test->setFileName("adasfd.fdfdg\\dfggdfg");
std::string testResult3 = test->getFileName();
std::string expectedResult3("adasfd.fdfdg\\dfggdfg");
Assert::AreEqual(testResult3, expectedResult3);
Assert::AreNotEqual(testResult1, expectedResult3);
delete test;
}
};
} | true |
069057098206f4d72731046428d6dc7ac51cdfb4 | C++ | anirudhbatra/Hackerrank-files | /voters list.cpp | UTF-8 | 675 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
int n1,n2,n3;
cin >> n1 >> n2 >> n3;
int total = n1 + n2 + n3;
int a[total];
for (int i = 0;i < total;i++)
{
cin >> a[i];
}
sort(a,a+total);
int prev,cont = 1;
prev = a[0];
vector<int> voters;
for (int i = 1;i < total + 1;i++)
{
if (prev == a[i])
{
cont++;
}
else{
if (cont >= 2)
{
voters.push_back(prev);
}
prev = a[i];
cont = 1;
}
}
int x = voters.size();
cout << x << endl;
for (int c = 0;c < x;c++)
cout << voters[c] << endl;
return 0;
}
| true |
1b5bfc865890fb8919931c9747cfdcc9edd1af9c | C++ | uwuvalem/Roblox-Exploit | /ROBLOX hack creation/ROBLOX hack creation/LuaC/LuaC.cpp | UTF-8 | 3,689 | 2.875 | 3 | [
"MIT"
] | permissive | #include "LuaC.h"
enum LuaC_OPCODES
{
NOTHING,
OP_GETGLOBAL,
OP_GETFIELD,
OP_SETGLOBAL,
OP_SETFIELD,
OP_PCALL,
OP_CALL,
OP_PUSHNIL,
OP_PUSHSTRING,
OP_PUSHVALUE,
OP_PUSHNUMBER,
OP_PUSHBOOLEAN,
OP_SETTOP,
OP_POP,
OP_WAIT,
OP_EMPTYSTACK
};
LuaC_OPCODES returnop(string func)
{
if ("getglobal" == func) return OP_GETGLOBAL;
if ("getfield" == func) return OP_GETFIELD;
if ("setglobal" == func) return OP_SETGLOBAL;
if ("setfield" == func) return OP_SETFIELD;
if ("pcall" == func) return OP_PCALL;
if ("call" == func) return OP_CALL;
if ("pushnil" == func) return OP_PUSHNIL;
if ("pushstring" == func) return OP_PUSHSTRING;
if ("pushvalue" == func) return OP_PUSHVALUE;
if ("pushnumber" == func) return OP_PUSHNUMBER;
if ("pushboolean" == func) return OP_PUSHBOOLEAN;
if ("settop" == func) return OP_SETTOP;
if ("pop" == func) return OP_POP;
if ("wait" == func) return OP_WAIT;
if ("emptystack" == func) return OP_EMPTYSTACK;
return NOTHING;
}
BOOL LuaC::Execute(LPSTR script)
{
char* buffer, *buffer1, *next;
buffer = strtok_s(script, " ", &next);
if (strlen(buffer) == NULL)
return FALSE;
switch (returnop(script))
{
case OP_GETGLOBAL:
{
if (strlen(next) == NULL)
return FALSE;
rlua_getglobal(luaState, next);
}
break;
case OP_GETFIELD:
{
buffer = strtok_s(NULL, " ", &next);
if (strlen(buffer) == NULL
|| strlen(next) == NULL)
return FALSE;
rlua_getfield(luaState, stoi(buffer), next);
}
break;
case OP_SETGLOBAL:
{
if (strlen(next) == NULL)
return FALSE;
rlua_setglobal(luaState, next);
}
break;
case OP_SETFIELD:
{
buffer = strtok_s(NULL, " ", &next);
if (strlen(buffer) == NULL
|| strlen(next) == NULL)
return FALSE;
rlua_setfield(luaState, stoi(buffer), next);
}
break;
case OP_PCALL:
{
buffer = strtok_s(NULL, " ", &next);
if (strlen(buffer) == NULL
|| strlen(next) == NULL)
return FALSE;
buffer1 = strtok_s(NULL, " ", &next);
if (strlen(buffer) == NULL
|| strlen(next) == NULL)
return FALSE;
rlua_pcall(luaState, stoi(buffer), stoi(buffer1), stoi(next));
}
break;
case OP_CALL:
{
buffer = strtok_s(NULL, " ", &next);
if (strlen(buffer) == NULL
|| strlen(next) == NULL)
return FALSE;
rlua_call(luaState, stoi(buffer), stoi(next));
}
break;
case OP_PUSHNIL:
{
rlua_pushnil(luaState);
}
break;
case OP_PUSHSTRING:
{
if (strlen(next) == NULL)
return FALSE;
rlua_pushstring(luaState, next);
}
break;
case OP_PUSHVALUE:
{
if (strlen(next) == NULL)
return FALSE;
rlua_pushvalue(luaState, stoi(next));
}
break;
case OP_PUSHNUMBER:
{
if (strlen(next) == NULL)
return FALSE;
rlua_pushnumber(luaState, stod(next));
}
break;
case OP_PUSHBOOLEAN:
{
if (strlen(next) == NULL)
return FALSE;
rlua_pushboolean(luaState, stoi(next));
}
break;
case OP_SETTOP:
{
if (strlen(next) == NULL)
return FALSE;
rlua_settop(luaState, stoi(next));
}
break;
case OP_POP:
{
if (strlen(next) == NULL)
return FALSE;
rlua_pop(luaState, stoi(next));
}
break;
case OP_WAIT:
{
if (strlen(next) == NULL)
return FALSE;
Sleep(stoi(next) * 1000);
}
break;
case OP_EMPTYSTACK:
{
rlua_settop(luaState, 0);
}
break;
default:
break;
}
return TRUE;
}
void LuaC::Parse(LPSTR script)
{
char* buffer = NULL;
char* next = NULL;
buffer = strtok_s(script, "\r\n", &next);
while (buffer != NULL)
{
Execute(buffer);
buffer = strtok_s(NULL, "\r\n", &next);
}
}
| true |
09dae4166ef42d53cbbc56800676476765937738 | C++ | farmerboy95/CompetitiveProgramming | /XXOpenCup/XXOpenCup-GPNanjing2020-A.cpp | UTF-8 | 3,252 | 2.71875 | 3 | [] | no_license | /*
Author: Nguyen Tan Bao
Status: AC
Idea:
- First simplify: X = x_1^x_2...^x_N^x_1'^x_2'^...^x_N'
- Now all pairs (x_i, y_i) become (0, x_i^y_i)
- So after A's moves then you have some value of X. What does B do to minimize? B should
try to remove max bit of X if possible. What if B can do this with more than one number?
- We replace B's numbers with basis of B's numbers. So if most significant bits of B's
basis are b_1 > b_2 > ... > b_k then x will have none of these bits after the reduction.
- We then replace A's numbers with basis of A's numbers. We can't just find the max #
that A can make. For each number in A's basis, reduce by basis of B -> no number will
have any of the bits b_1,b_2,...,b_k
- So now, we're done because we can just find max XOR in modification of A's basis.
*/
#include <bits/stdc++.h>
#define FI first
#define SE second
#define EPS 1e-9
#define ALL(a) a.begin(),a.end()
#define SZ(a) int((a).size())
#define MS(s, n) memset(s, n, sizeof(s))
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
//__builtin_ffs(x) return 1 + index of least significant 1-bit of x
//__builtin_clz(x) return number of leading zeros of x
//__builtin_ctz(x) return number of trailing zeros of x
using namespace std;
using ll = long long;
using ld = double;
typedef pair<int, int> II;
typedef pair<II, int> III;
typedef complex<ld> cd;
typedef vector<cd> vcd;
const ll MODBASE = 1000000007LL;
const int MAXN = 20010;
const int MAXM = 1000;
const int MAXK = 16;
const int MAXQ = 200010;
int n, m;
ll x[MAXN], y[MAXN];
const int D = 60;
ll basis[D], basis2[D], basis3[D];
void insertVector(ll *basis, ll mask) {
FORE(i,D-1,0) {
if (!(mask & (1LL<<i))) continue;
if (!basis[i]) {
basis[i] = mask;
return;
}
mask ^= basis[i];
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
cin >> n >> m;
FOR(i,1,n+m) cin >> x[i] >> y[i];
MS(basis, 0);
MS(basis2, 0);
MS(basis3, 0);
ll origin = 0;
FOR(i,1,n+m) origin ^= x[i];
FOR(i,1,n) insertVector(basis, x[i] ^ y[i]);
FOR(i,n+1,n+m) insertVector(basis2, x[i] ^ y[i]);
// minimum number that you can create, the result will be larger or equal to this origin
FORE(i,D-1,0)
if (origin & (1LL << i))
if (basis2[i]) origin ^= basis2[i];
FORE(i,D-1,0)
if (basis[i]) {
ll x = basis[i];
// For each number in A's basis, reduce by basis of B -> no number will have any of the bits b_1,b_2,...,b_k
FORE(j,D-1,0)
if (x & (1LL << j))
if (basis2[j]) x ^= basis2[j];
insertVector(basis3, x);
}
// find max
FORE(i,D-1,0)
if (!(origin & (1LL << i)))
if (basis3[i]) origin ^= basis3[i];
cout << origin << "\n";
}
return 0;
} | true |
5c40968cb52e5a8a085449548b61569bbeb38b85 | C++ | basecq/opentesarenapp | /WinArena/ParseBSA.h | UTF-8 | 10,717 | 2.6875 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////////////////
//
// $Header: /WinArena/ParseBSA.h 10 12/31/06 10:51a Lee $
//
// File: ParseBSA.h
//
//
// Basic layout of Globals.BSA:
// * 16-bit word indicating total number of index entries at end of file
// * all data files packed one after another
// * array of index values
//
// To scan through Globals.BSA, first read the 16-bit from the start of the
// file. This indicates how many files are packed into Globals.BSA, which
// is used to scan backwards from the end of the file to locate the start
// of the index. Then scan through the index from first to last, adding up
// the size of each file (starting with an initial size of 2 bytes for the
// file/index count value).
//
// Arena.exe appears to first scan through its directory to see if a named
// file can be loaded from there. If not, it pulls the data from the BSA
// file. This allows the patches to replace a few of the INF files (which
// are also special, in that the INF files stored in Globals.BSA are encoded
// using a bit hashing technique, but the ones in the Arena directory are
// plain text).
//
// WARNING: The list of files locating the BSA index are *ALMOST* sorted,
// but not completely (e.g., EVLINTRO.XMI and EVLINTRO.XFM are reversed).
// Doing a binary look-up of a file works 99% of the time, but will sometimes
// fail. My guess is that the look-up code in Arena.exe scans through the
// index in order, adding up the size values to compute the file's offset
// within Globals.BSA so it doesn't need to cache the offsets. The code
// implemented here will cache those values, and does do binary look-up,
// but falls back to a linear search if it could not locate the file.
//
//
// All of the INF files use a bit-hashing technique to encode them into
// something unreadable (unless you like reading hex dumps and looking for
// repeating patterns -- thankfully the patched version of the game includes
// plain-text versions of some of the INF files that are almost identical to
// the ones stored in Globals.BSA, at least for the first several hundred
// bytes).
//
// To decode INF files, MakeInverseCodeTable() needs to be called once.
// Currently this is done from within BSALoadResources(), so it is already
// taken care of once Global.BSA is available for processing. This will
// build some look-up tables that are used to decode the hashed bits. Note
// that the INF files only contain 7-bit ASCII. There are no symbols above
// 127, and the fonts in the game only define values for symbols 32 - 127.
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#pragma pack(push, normalPacking)
#pragma pack(1)
//
// This is the format of the index entries that occur at the end of the
// Globals.BSA file.
//
struct BSAIndex_t
{
char Name[12]; // 8.3 formatted file name, without any '\0' terminator
WORD U1; // Unkown, possibly unused
WORD Size;
WORD U2; // Unkown, possibly unused
};
//
// This is the struct used to cache index info into the BSA file. An initial
// pass over the raw index is done to compute the offsets, and to fix up the
// file name so it's useable by string operations.
//
// ParseGlobalIndex() is responsible for doing all of this processing.
//
struct GlobalIndex_t
{
char Name[16]; // fixed version of file name with '\0', padded to DWORD alignment
DWORD Offset; // byte offset from start of BSA file
DWORD Size; // size of resource, in bytes
};
//
// This is the header that is found at the beginning of CFA files, which are
// used for creature animations. Refer to LoadCFA() for the specifics on how
// animations are stored, and the work required to decode them.
//
struct HeaderCFA_t
{
WORD WidthUncompressed; // actual width of the image
WORD Height;
WORD WidthCompressed; // bytes/line of bit-packed image
WORD u2;
WORD u3;
BYTE BitsPerPixel; // indicates how to demux the encoded pixels
BYTE FrameCount;
WORD HeaderSize; // this also includes the color LUT following the header
};
struct HeaderCIF_t
{
WORD u1;
WORD u2;
WORD Width;
WORD Height;
WORD Flags;
WORD RecordSize;
};
//
// DFA files are used to static animations, such as fire bits, bartenders,
// jugglers, and other decorative sprites. These are typically a static
// frame with a small block of animation.
//
struct HeaderDFA_t
{
WORD FrameCount;
WORD u2;
WORD u3;
WORD Width;
WORD Height;
WORD CompressedSize;
};
#define IMG_FLAG_PIXELCOUNT 0x0008 // indicates uncompressed size is stored at offset 0x0C
#define IMG_FLAG_PALETTE 0x0100 // indicates last 0x300 bytes contain a custom palette
#define IMG_FLAG_MYSTERY1 0x0004
#define IMG_FLAG_MYSTERY2 0x0800
// It's not clear what the two mystery flags indicate. They are usually
// present with compressed images, but not always. And are set for some
// of the non-compressed images. These may be hints for how to interpret
// the palette.
struct HeaderIMG_t
{
WORD OffsetX;
WORD OffsetY;
WORD Width;
WORD Height;
WORD Flags; // unknown, 0x8000 == compressed? or 0x00800 maybe?
WORD RecordSize; // size of record - 12 for most images, add 12 to get offset to palette for splash screens
WORD UncompressedSize; // size of image when uncompressed, only present if IMG_FLAG_PIXELCOUNT flag is set
};
//
// Header block found at the beginning of each sound file. These are Creative
// Voice files, but there does not appear to be any information about the
// audio formatting. All audio is 8-bit mono. I have no idea whether these
// are linear, A-law, or mu-law encoded. The format bits that look like they
// should indicate this are not set, so I assume they're linear. Mixing them
// by linear addition doesn't seem to change the value, so I assume linear,
// but I'm an expert on video, not audio.
//
struct HeaderVOC_t
{
char CreativeVoice[19];
BYTE MarkEOF;
WORD DataOffset;
WORD Version; // 0x010A
WORD TwosCompVersion; // 0x1129
};
//
// Fonts are stored in a packed bit format, one bit per pixel, with each line
// of a symbol packed into 8 or 16 bits, with an array of lines-per-symbol
// values stored at the beginning of the font file.
//
// Once a font is decoded, it is packed into an array of FontElement_t structs
// so they can be easily accessed to mask chars into place by rendering code.
//
struct FontElement_t
{
DWORD Width;
DWORD Height;
WORD Lines[16];
};
#pragma pack(pop, normalPacking)
extern char g_ArenaPath[]; // fill with Arena's path, ".\" or "C:\Arena\"
void MakeArenaDirectory(char name[]);
enum ArenaPalette_t
{
Palette_Default = 0,
Palette_CharSheet = 1,
Palette_Daytime = 2,
Palette_Dreary = 3,
Palette_ArraySize = 4
};
enum ArenaFont_t
{
Font_A, // height = 11
Font_B, // height = 6
Font_C, // height = 14
Font_D, // height = 7
Font_S, // height = 5
Font_4, // height = 7
Font_Arena, // height = 9 -- used for stat values in character sheet
Font_Char, // height = 8 -- used for stat field names in character sheet
Font_Teeny, // height = 8
Font_ArraySize
};
class ArenaLoader
{
private:
struct PrivateIndex_t
{
char Name[16];
DWORD Size;
DWORD Offset;
bool HasOverride;
};
PrivateIndex_t* m_pIndex;
DWORD m_Palette[Palette_ArraySize][256];
FontElement_t m_FontList[Font_ArraySize][96];
DWORD m_IndexCount;
GlobalIndex_t* m_pGlobalIndex;
DWORD m_GlobalDataSize;
BYTE* m_pGlobalData;
// A large scratch buffer is used to hold temporary data, usually while
// decompressing images.
//
BYTE* m_pScratch;
// For normal resource access, there will be a pointer directly into the
// data withing m_pGlobalData. However, some resources are located
// directly in the Arena directory. Those will be loaded into this
// buffer for processing.
//
BYTE* m_pFileScratch;
public:
ArenaLoader(void);
~ArenaLoader(void);
bool LoadResources(void);
void FreeResources(void);
void ParseIndex(BYTE *pData, GlobalIndex_t *pIndex, DWORD entryCount);
BYTE* LoadFile(char name[], DWORD &size, bool *pFromBSA = NULL);
DWORD LookUpResource(char name[]);
void LoadPalette(char filename[], DWORD palette[]);
DWORD* GetPaletteARGB(ArenaPalette_t select);
void GetPaletteARGB(ArenaPalette_t select, DWORD palette[]);
void GetPaletteBlueFirst(ArenaPalette_t select, BYTE palette[]);
void GetPaletteRedFirst(ArenaPalette_t select, BYTE palette[]);
void LoadFont(char filename[], DWORD fontHeight, FontElement_t symbols[]);
FontElement_t* GetFont(ArenaFont_t font);
void LoadLightMap(char name[], BYTE buffer[], bool dump = false);
BYTE* LoadData(char name[], DWORD &dataSize);
BYTE* LoadSound(char name[], DWORD &sampleCount, DWORD &sampleRate);
void DumpSounds(void);
void CheckCFA(DWORD id, DWORD &width, DWORD &height, DWORD &frameCount);
void LoadCFA(DWORD id, DWORD width, DWORD height, DWORD pitch, DWORD frameCount, BYTE *ppFrames[]);
void DumpCFA(void);
void CheckDFA(DWORD id, DWORD &width, DWORD &height, DWORD &frameCount);
void LoadDFA(DWORD id, DWORD width, DWORD height, DWORD pitch, DWORD frameNum, BYTE *pResult);
void DumpDFA(void);
void CheckCIF(char name[], DWORD frameNum, DWORD &width, DWORD &height, DWORD &offsetX, DWORD &offsetY);
void LoadCIF(char name[], DWORD width, DWORD height, DWORD frameNum, BYTE *pResult);
void DumpCIF(void);
void CheckIMG(char name[], DWORD &width, DWORD &height, DWORD &offsetX, DWORD &offsetY, bool &hasHeader);
DWORD* LoadIMG(char name[], DWORD width, DWORD height, DWORD pitch, bool hasHeader, BYTE *pResult);
void DumpIMG(char filename[]);
void DumpIMGRAW(char filename[], DWORD width, DWORD height, DWORD palette32[]);
void DumpIMGFAT(char filename[]);
void DumpImages(void);
void ScanIMGs(void);
void LoadWallTexture(DWORD index, BYTE *pPixels, DWORD offset);
void LoadWater(char name[], DWORD frameNum, BYTE *pPixels);
void MakeInverseCodeTable(void);
void DeobfuscateINF(BYTE text[], DWORD count);
void DumpBSAIndex(void);
void DumpInfo(void);
void DumpMap(char resname[], char prefix[]);
void DumpMaps(void);
void DumpWalls(void);
void ExtractFile(char filename[]);
void HexDump(char filename[], char path[] = "", bool rightToLeft = false);
};
extern ArenaLoader* g_pArenaLoader;
| true |
c1edef638197deb26f8a181da6947fb145706951 | C++ | lambertwang/tensor_stuff | /src/trainNode/train.cpp | UTF-8 | 1,685 | 2.921875 | 3 | [] | no_license | /**
* Train class
*/
#include "train.h"
#include "tensoralgebra.h"
Train::Train(const TensorNode *val, Tensor n_learning_rate) {
input.push_back(val);
graph = new GraphNode(val);
learning_rate = n_learning_rate;
}
Tensor Train::evaluate(Session *session) const {
Tensor result;
for (const TensorNode *n: input) {
result = session->getEval(n);
}
#ifdef DEBUG
std::cout << "DEBUG: Beginning Training Step" << std::endl;
#endif
// A map of node tags to edges on the graph. The value of an
// edge is the derivative of its parent with respect to itself.
// (*edgeMap)[a][b] = db/da
std::map<std::string, std::map<std::string, Tensor>> edgeMap;
graph->computeEdges(session, &edgeMap);
#ifdef DEBUG
std::cout << "DEBUG: Computed Edges" << std::endl;
#endif
// A map of nodes to their derivatives with respect to the root.
std::map<std::string, Tensor> derivatives;
graph->computeDerivatives(&edgeMap, &derivatives);
#ifdef DEBUG
std::cout << "DEBUG: Computed Derivatives" << std::endl;
#endif
// Adjust each variable in the session according to its derivative
std::map<std::string, Tensor> variable_store = session->getVarStore();
for (auto const& v: variable_store) {
// Tensor adj = derivatives[v.first] * (learning_rate * result);
Tensor adj = derivatives[v.first] * learning_rate;
#ifdef DEBUG
std::cout << "DEBUG: variable '" << v.first << " ' initial val " << v.second<< std::endl;
std::cout << "DEBUG: Adjusting variable '" << v.first << "' by " << adj << std::endl;
#endif
session->setVar(v.first, v.second - adj);
}
return result;
} | true |
1d4e77ad574488f091a850582e45a87549797529 | C++ | SUSREE64/Cplusplus | /strings.cpp | UTF-8 | 967 | 3.765625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
string name = "Sreenivasulu";
string slice;
cout << name << endl;
// string concatenation
cout << "Hi! " + name << endl;
cout << "Legth of string" << name.length() << endl;
//append
name.append(" Gentleman");
cout << name << endl;
// Length of the strig another way.
cout << "String size() : " << name.size() << endl;
cout << "First letter of the string : " << name.front() << endl;
cout << "last letter of the string : " << name.back() << endl;
// Slicing, with substring
slice = name.substr(3, 5);
cout << "Sliced content of the string :" << slice << endl;
// indexing
cout << "The letter at index 2 is : " << name.at(2) << endl;
cout << "The letter at index 2 is : " << name[2] << endl;
// Replace
string str1 = "Hello World";
string str2 = "My";
str1.replace(5, 2, str2);
cout << str1 << endl;
return 0;
}
| true |
8e5b2c64eade45af6d893fae566d8d84a8da45cd | C++ | kelasterbuka/CPP_Lanjut_OOP | /19 - Friend Class/src/Main.cpp | UTF-8 | 1,618 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
// belajar tentang friend class
// akses friend class hanya satu arah, tidak berlaku sebaliknya
// friend class akan memberikan akses dari class yang mendeklarasikan friend
class PersegiPanjang;
class Persegi{
// memberikan akses seluruh atribut dan method kepada class PersegiPanjang
friend class PersegiPanjang;
private:
double sisi;
public:
Persegi(double sisi){
this->sisi = sisi;
}
double luas(){
return this->sisi*this->sisi;
}
bool isLebihPanjang(const PersegiPanjang &obj){
bool isTrue = this->sisi > obj.panjang;
return isTrue;
}
};
class PersegiPanjang{
friend class Persegi;
private:
double panjang;
double lebar;
public:
PersegiPanjang(double panjang, double lebar){
this->panjang = panjang;
this->lebar = lebar;
}
double luas(){
return this->panjang*this->lebar;
}
bool isLebihPanjang(const Persegi &obj){
bool isTrue = this->panjang > obj.sisi;
return isTrue;
}
};
int main(int argc, char const *argv[]){
// kita buat objectnya
Persegi persegi = Persegi(5);
PersegiPanjang kotak = PersegiPanjang(5,10);
cout << "Luas persegi = " << persegi.luas() << endl;
cout << "Luas kotak = " << kotak.luas() << endl;
bool logika = kotak.isLebihPanjang(persegi);
cout << "apakah kotak lebih panjang dari persegi = " << logika << endl;
return 0;
}
| true |
c55c4b22d59555732fe4121ffe30262f7f6d5c7c | C++ | thanhnhani654/Megaman--X3 | /Megaman/Component/MoveComponent.h | UTF-8 | 2,204 | 2.53125 | 3 | [] | no_license | #pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include <math.h>
#include <iostream>
class MoveComponent
{
private:
D3DXVECTOR2* position;
D3DXVECTOR2 prevPosition;
D3DXVECTOR2* velocity;
D3DXVECTOR2 acceleration;
float speed;
bool bGravity; //Bằng true cho Player. Tất cả mấy cái còn lại không cần
float gravity; //Khi bGravity bằng true thì acceleration.y = gravity
float limitedSpeed; //Nên là số nguyên
float jumpPower;
bool bOnAcceleration;
bool bDashing;
public:
#pragma region GetSet
D3DXVECTOR2 GetPosition()
{
return *position;
}
D3DXVECTOR2 GetVelocity()
{
return *velocity;
}
D3DXVECTOR2 GetAcceleration()
{
return acceleration;
}
void SetAcceleration(D3DXVECTOR2 acc)
{
acceleration = acc;
}
void SetAcceleration(float x, float y)
{
acceleration.x = x;
acceleration.y = y;
}
void SetVelocity(D3DXVECTOR2 vec)
{
acceleration = vec;
}
void SetVelocity(float x, float y)
{
velocity->x = x;
velocity->y = y;
}
float GetSpeed()
{
return speed;
}
void SetSpeed(float spd)
{
speed = spd;
}
void EnableGravity()
{
bGravity = true;
}
void DisableGravity()
{
bGravity = false;
}
float GetGravity()
{
return gravity;
}
void SetGravity(float gra)
{
gravity = gra;
}
float GetLimitedSpeed()
{
return limitedSpeed;
}
void SetLimitedSpeed(float limit)
{
limitedSpeed = limit;
}
float GetJumpPower()
{
return jumpPower;
}
void SetJumpPower(float jp)
{
jumpPower = jp;
}
void OnAcceleration()
{
bOnAcceleration = true;
}
#pragma endregion
void Initialize(D3DXVECTOR2 *position, D3DXVECTOR2 *velocity);
void MoveUp(); //Chỉ dùng khi bGravity False
void MoveDown(); //Chỉ dùng khi bGravity False
void Jump(); //Chỉ dùng khi bGravity True
void Dash(int);
void OnDashing();
void OffDashing();
void MoveLeft();
void MoveRight();
void IdleX();
void IdleY();
void TinhVanTocDuaTrenPhuongTrinhTheoThoiGian(float ptx, float pty); //Điều kiện sử dụng là bGravity = false và không sử dụng bất kỳ hàm nào khác
void UpdateMovement(float deltatime);
void BugCatcher(D3DXVECTOR2 position);
}; | true |
5b687b610f1f4c088ea0c12522138347c100e366 | C++ | gnunesmoura/simulador2 | /include/init/instance/edge.hpp | UTF-8 | 521 | 2.578125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include <valarray>
#include <utility>
#define pera getchar()
#define eae std::cout << "Filha da puta\n"
namespace sim {
class Node;
typedef struct edge {
constexpr edge (double t_value, Node& t_node) :
first(t_value), second(t_node) {};
double first;
Node& second;
double dist (const Node& arg0) const;
constexpr bool operator< (const edge& b) const { return first < b.first; }
}edge;
using edges = std::vector<edge>;
} //namespace | true |
c746607c58ad602d5ed176f933ce210168fb6f85 | C++ | API-Beast/libColorProcess | /Colors/GenericColor.h | UTF-8 | 1,620 | 3.0625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "ColorSpaces.h"
#include "Colors.h"
class GenericColor
{
protected:
union
{
LinearRGB linRgb;
sRGB sRgb;
sRGB_uint8 sRgbu8;
HSV Hsv;
LinearHSV linHsv;
HCY hcy;
Vec3f genericVec3f;
Vec3u8 genericVec3u8;
};
ColorSpace color_space = ColorSpace::LinearRGB;
public:
constexpr GenericColor():linRgb(1.0, 1.0, 1.0), color_space(ColorSpace::LinearRGB){};
constexpr GenericColor(LinearRGB rgb):linRgb(rgb), color_space(ColorSpace::LinearRGB){};
constexpr GenericColor(sRGB rgb):sRgb(rgb), color_space(ColorSpace::sRGB){};
constexpr GenericColor(sRGB_uint8 rgb):sRgbu8(rgb), color_space(ColorSpace::sRGB_uint8){};
constexpr GenericColor(HSV hsv):Hsv(hsv), color_space(ColorSpace::HSV){};
constexpr GenericColor(LinearHSV hsv):linHsv(hsv), color_space(ColorSpace::LinearHSV){};
constexpr GenericColor(HCY hcy):hcy(hcy), color_space(ColorSpace::HCY){};
GenericColor(Vec3f generic, ColorSpace p_space);
ColorSpace get_color_space();
void convert_to(ColorSpace space);
Vec3f get_vector();
template<typename T>
operator T();
};
template<typename T>
GenericColor::operator T()
{
switch(color_space)
{
case ColorSpace::LinearRGB:
return colorspace_cast<T>(linRgb);
case ColorSpace::sRGB:
return colorspace_cast<T>(sRgb);
case ColorSpace::sRGB_uint8:
return colorspace_cast<T>(sRgbu8);
case ColorSpace::HSV:
return colorspace_cast<T>(Hsv);
case ColorSpace::LinearHSV:
return colorspace_cast<T>(linHsv);
case ColorSpace::HCY:
return colorspace_cast<T>(hcy);
}
return T(-1, -1, -1);
}; | true |
96f224f9d49edac96f142ca3beacc346174121af | C++ | IlyaNikiforov/Home_Works | /semester_1/home_work_2/task_5/Задача №5.cpp | WINDOWS-1251 | 1,237 | 3.4375 | 3 | [] | no_license | // 5.cpp : Defines the entry point for the console application.
//
#include "iostream"
#include "time.h"
#include "stdlib.h"
using namespace std;
int max(int a[], int i, int j)
{
if (a[i] >= a[j])
return i;
else
return j;
}
void swap(int &a, int &b)
{
int p = 0;
p = a;
a = b;
b = p;
}
void heaping(int a[], int begin, int end)
{
int p = 0;
if (2 * begin + 2 <= end)
p = max(a, 2 * begin + 1, 2 * begin + 2);
else
p = 2 * begin + 1;
while ((a[begin] < a[p]) && (begin * 2 + 1 <= end))
{
swap(a[begin], a[p]);
begin = p;
if (2 * begin + 2 <= end)
p = max(a, 2 * begin + 1, 2 * begin + 2);
else if (2 * begin + 1 <= end)
p = 2 * begin + 1;
}
}
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heaping(a, i, n - 1);
for (int i = n - 1; i >= 1; i--)
{
swap(a[0], a[i]);
heaping(a, 0, i - 1);
}
}
int main()
{
cout << "HeapSort" << endl;
srand(time(NULL));
cout << "Enter n:" << endl;
int n = 0;
cin >> n;
int *a = new int [n];
for (int i = 0; i < n; i++)
{
a[i] = rand() % 100;
cout << a[i] << " ";
}
cout << endl;
heapSort(a, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cin >> n;
delete[] a;
return 0;
}
| true |
ed2e289f6cbca94b7b31941b2b61afbc39a8cc2d | C++ | danchris1029/CodingPractice | /C++/simplify-path.cpp | UTF-8 | 1,992 | 3.46875 | 3 | [] | no_license | //Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
class Solution {
public:
string simplifyPath(string path) {
string res = "",
dir = "";
int dot = 0;
vector<string> directs;
for(int i = 0; i < path.length(); i++){
// slash clears current directory or periods
if(path[i] == '/'){
if(dot && dir.length()){
string dots = "";
for(int i = 0; i < dot; i++)
dots += ".";
dir += dots;
}
else if(dot == 2 && directs.size() > 0)
directs.pop_back();
else if(dot == 3)
directs.push_back("...");
if(dir.length())
directs.push_back(dir);
dot = 0;
dir = "";
continue;
}
else if(path[i] == '.')
dot++;
else{
// watch out for hidden periods behind directory name
if(dot){
string dots = "";
for(int i = 0; i < dot; i++)
dots += ".";
dir = dots;
dot = 0;
}
dir += path[i];
}
}
// last check after loop
if(dot == 2 && directs.size())
directs.pop_back();
if(dot == 3)
directs.push_back("...");
if(dir.length())
directs.push_back(dir);
// make final string
if(directs.size()){
for(auto dir:directs){
res += "/";
res += dir;
}
}
else
res = "/";
return res;
}
};
| true |
2bbfb658e3468498a5d2b83fd9ae69592d361ffa | C++ | xairry/PAT-Basic | /1021/S1021_0.cpp | UTF-8 | 534 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int count_char_in_string(string, char);
int main() {
string number;
cin>>number;
for (int i=0; i<10; i++) {
int n;
n = count_char_in_string(number, to_string(i)[0]);
if (n > 0) {
cout<<i<<":"<<n<<endl;
}
}
return 0;
}
int count_char_in_string(string s, char c) {
int s_length = s.length();
int c_n=0;
for (int i=0; i<s_length; i++) {
if (s[i] == c)
c_n++;
}
return c_n;
}
| true |
a76f86b28107c51661ae996fc33423787ff7ce2e | C++ | Coletinn/dados-projeto2-calculadoraRPN | /projeto2-dados/main.cpp | ISO-8859-1 | 1,354 | 3.265625 | 3 | [] | no_license | /*
Gustavo Coleto de Freitas 32076541
Joo Vitor Teles Centrone 32033125
*/
#include <iostream>
#include <sstream>
#include "DynamicStack.h"
#include <clocale>
using namespace std;
float Math(const std::string& input, DynamicStack& stack);
int main()
{
setlocale(LC_ALL, "portuguese");
DynamicStack stack = Create();
while (true)
{
std::cout << "> ";
float res = 0;
std::string input;
std::getline(std::cin, input);
if (input == "0")
{
std::cout << "Fim.";
break;
}
std::istringstream iss(input); // Passa o input para um istringstream.
std::string str;
std::cout << str;
while (iss >> str)
{
try
{
float value = std::stof(str);
Push(stack, value);
}
catch (std::invalid_argument e)
{
res = Math(str, stack);
}
}
if (res != NULL)
{
std::cout << res << "\n\n";
}
else
{
std::cout << "\nErro na expresso.\n\n";
}
}
}
float Math(const std::string& input, DynamicStack& stack)
{
float v2 = Top(stack);
v2 = Pop(stack);
float v1 = Top(stack);
v1 = Pop(stack);
float result = 0;
if (input == "-")
{
result = v1 - v2;
Push(stack, result);
}
else if (input == "+")
{
result = v1 + v2;
Push(stack, result);
}
else if (input == "*")
{
result = v1 * v2;
Push(stack, result);
}
else if (input == "/")
{
result = v1 / v2;
Push(stack, result);
}
return result;
}
| true |
ac6f4992a7b92e1cc8d252835179e30ca7e85527 | C++ | DPCEKY/myleet | /843.cpp | UTF-8 | 801 | 3.59375 | 4 | [] | no_license | /**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* class Master {
* public:
* int guess(string word);
* };
*/
class Solution {
public:
void findSecretWord(vector<string>& wordlist, Master& master) {
vector<string> mywords = wordlist;
for(int i = 0; i < 10; i++) {
string word = mywords[0];
int num = master.guess(word);
if(num == 6)
return;
vector<string> next_round;
for(auto& myword : mywords) {
if(num == diff(myword, word)) {
next_round.push_back(myword);
}
}
mywords.swap(next_round);
}
}
int diff(string a, string b) {
int res = 0;
for(int i = 0; i < 6; i++) {
res += a[i] == b[i];
}
return res;
}
};
| true |
8fe59a3f275acfed48202984f4421ef7410cd1df | C++ | serialization/test.cpp | /test/age/AgeContainsTest.cpp | UTF-8 | 4,380 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by Sarah Stieß on 28.05.19.
//
#include "../../lib/ogss.common.cpp/ogss/internal/AbstractPool.h"
#include "../../src/age/File.h"
#include "../../src/empty/File.h"
#include "../common/utils.h"
#include <gtest/gtest.h>
using ::age::api::File;
TEST(AgePoolAddTest, ContainsNull) {
try {
auto sg = common::tempFile<File>();
ASSERT_FALSE(sg->contains(nullptr));
} catch (ogss::Exception &e) {
GTEST_FAIL() << "unexpected failure: " << e.what();
} catch (std::exception &e) {
GTEST_FAIL() << "std::exception: " << e.what();
} catch (...) {
GTEST_FAIL() << "unexpected exception";
}
}
TEST(AgePoolAddTest, ContainsNew) {
try {
auto sg = common::tempFile<File>();
auto age = sg->Age->make();
ASSERT_TRUE(sg->contains(age));
} catch (ogss::Exception &e) {
GTEST_FAIL() << "unexpected failure: " << e.what();
} catch (std::exception &e) {
GTEST_FAIL() << "std::exception: " << e.what();
} catch (...) {
GTEST_FAIL() << "unexpected exception";
}
}
TEST(AgePoolAddTest, ContainsKnown) {
try {
auto sg = common::tempFile<File>();
sg->Age->build()->age(0)->make();
sg->Age->build()->age(1)->make();
sg->close();
auto sg1 = std::unique_ptr<File>(File::open(sg->currentPath()));
auto it = sg1->Age->allObjects();
// just ensuring that we'll enter the loop.
ASSERT_TRUE(it->hasNext());
while (it->hasNext()) {
auto x = it->next();
ASSERT_TRUE(sg1->contains(x));
ASSERT_FALSE(sg->contains(x));
}
} catch (ogss::Exception &e) {
GTEST_FAIL() << "unexpected failure: " << e.what();
} catch (std::exception &e) {
GTEST_FAIL() << "std::exception: " << e.what();
} catch (...) {
GTEST_FAIL() << "unexpected exception";
}
}
TEST(AgePoolAddTest, ContainsUnknown) {
try {
auto sg = common::tempFile<File>();
sg->Age->build()->age(0)->make();
sg->Age->build()->age(1)->make();
sg->close();
auto sg1 = std::unique_ptr<::empty::api::File>(
::empty::api::File::open(sg->currentPath()));
// age type is the only type. empty has no types of its own.
ASSERT_EQ(1, sg1->size());
for (auto t = sg1->begin(); t < sg1->end(); t++) {
ASSERT_EQ(2, (*t)->size());
auto it = (*t)->allObjects();
// just ensuring that we'll enter the loop.
ASSERT_TRUE(it->hasNext());
while (it->hasNext()) {
auto x = it->next();
ASSERT_TRUE(sg1->contains(x));
ASSERT_FALSE(sg->contains(x));
}
}
} catch (ogss::Exception &e) {
GTEST_FAIL() << "unexpected failure: " << e.what();
} catch (std::exception &e) {
GTEST_FAIL() << "std::exception: " << e.what();
} catch (...) {
GTEST_FAIL() << "unexpected exception";
}
}
TEST(AgePoolAddTest, ContainsForeign) {
try {
auto sg = common::tempFile<File>();
sg->Age->build()->age(0)->make();
sg->Age->build()->age(1)->make();
sg->close();
ASSERT_EQ(2, sg->Age->size());
auto sg1 = common::tempFile<File>();
ASSERT_EQ(0, sg1->Age->size());
auto it = sg->Age->allObjects();
// just ensuring that we'll enter the loop.
ASSERT_TRUE(it->hasNext());
while (it->hasNext()) {
auto x = it->next();
ASSERT_FALSE(sg1->contains(x));
}
} catch (ogss::Exception &e) {
GTEST_FAIL() << "unexpected failure: " << e.what();
} catch (std::exception &e) {
GTEST_FAIL() << "std::exception: " << e.what();
} catch (...) {
GTEST_FAIL() << "unexpected exception";
}
}
TEST(AgePoolAddTest, ContainsDeleted) {
try {
auto sg = common::tempFile<File>();
auto age = sg->Age->build()->age(0)->make();
sg->free(age);
ASSERT_FALSE(sg->contains(age));
sg->flush();
ASSERT_FALSE(sg->contains(age));
} catch (ogss::Exception &e) {
GTEST_FAIL() << "unexpected failure: " << e.what();
} catch (std::exception &e) {
GTEST_FAIL() << "std::exception: " << e.what();
} catch (...) {
GTEST_FAIL() << "unexpected exception";
}
} | true |
6ffd64667f75dc08542f4448f529e2cf1b990b5d | C++ | markhuberty/fung_disambiguator | /include/newcluster.h | UTF-8 | 4,853 | 2.6875 | 3 | [] | no_license |
#ifndef PATENT_NEWCLUSTER_H
#define PATENT_NEWCLUSTER_H
#include "engine.h"
#include "clusterhead.h"
/**
* Cluster objects are the molecules of disambiguation,
* while Record objects are atoms of disambiguation.
* Each cluster contains a cluster_head, a list of members, and some other
* information. The aim of disambiguation is reorganize clusters
* so that some can probably compound to bigger ones. Disambiguation
* starts from smallest clusters that contain only one record, and
* ends with clusters that contain some amount of records.
*/
class Cluster {
private:
static const unsigned int invalid_year = 0;
//ClusterHead m_info: cluster head of the cluster,
//including the delegate and the cohesion of the cluster.
ClusterHead m_info;
//RecordPList m_fellows: the list of members of the cluster.
RecordPList m_fellows;
//bool m_mergeable: a boolean, indicating "*this" cluster
//has been merged into others or not.
bool m_mergeable;
//bool m_usable: a boolean preventing misuse earlier than
//fully prepared.
bool m_usable;
//static const cRatios * pratio: a pointer that points to a
//cRatio object which contains a map of similarity profile to ratio
static const cRatios * pratio;
/**
* static const map<const Record *, RecordPList, cSort_by_attrib> * reference_pointer:
* a pointer that points to a patent tree, which can be obtained in
* a cBlocking_Operation_By_Coauthor object.
*/
static const PatentTree * reference_pointer;
//Cluster & operator = ( const Cluster &): forbid the assignment operation.
Cluster & operator = ( const Cluster &);
//void find_representative(): to sets a component of cluster
//head to be the record whose columns appear most frequently
//among the all the members.
void find_representative();
unsigned int first_patent_year;
unsigned int last_patent_year;
set < const cLatitude * > locs;
void update_locations();
void update_year_range();
unsigned int patents_gap( const Cluster & rhs) const;
bool is_valid_year() const;
public:
// Cluster(const ClusterHead & info, const RecordPList & fellows): constructor
Cluster(const ClusterHead & info, const RecordPList & fellows);
// ~Cluster() : destructor
~Cluster();
// Cluster ( const Cluster & rhs ): copy constructor
Cluster ( const Cluster & rhs );
/**
* void merge( Cluster & mergee, const ClusterHead & info):
* merge the "mergee" cluster into "*this", and set
* the cluster head of the new cluster to be info.
*/
void merge( Cluster & mergee, const ClusterHead & info);
/**
* ClusterHead disambiguate(const Cluster & rhs, const double prior,
* const double mutual_threshold) const:
* disambiguate "*this" cluster with rhs cluster,
* with the prior and mutual_threshold information.
* Returns a ClusterHead to tell whether the two clusters should
* be merged or not, and if yes, the cohesion of the new one.
*/
ClusterHead disambiguate(const Cluster & rhs, const double prior,
const double mutual_threshold) const;
//static void set_ratiomap_pointer( const cRatios & r):
//set the ratio map pointer to a good one.
static void set_ratiomap_pointer( const cRatios & r) {pratio = &r;}
//const RecordPList & get_fellows() const:
//get the members (actually it is reference to const) of the cluster.
const RecordPList & get_fellows() const {
return m_fellows;
}
//const ClusterHead & get_cluster_head () const:
//get the cluster head (const reference) of the cluster.
const ClusterHead & get_cluster_head () const {return m_info;};
//void insert_elem( const Record *): insert a new member into
//the member list. This could potentially change the cluster head.
void insert_elem(const Record *);
//void self_repair(): call this if insertion of elements is done manually,
//usually for a batch of record objects (not recommended).
void self_repair();
//static void set_reference_patent_tree_pointer(
//const map < const Record *, RecordPList, cSort_by_attrib > & reference_patent_tree):
//set the patent tree pointer.
static void set_reference_patent_tree_pointer(
const PatentTree & reference_patent_tree) {
reference_pointer = & reference_patent_tree;
}
/**
* void change_mid_name(): to change pointers to abbreviated middle
* names to full middle names. This step is controversial, as it
* actually changed the raw data. Or more correctly, it changed
* the pointers of the raw data.
*/
void change_mid_name();
void add_uid2uinv(Uid2UinvTree & uid2uinv) const;
};
/**
* cException_Empty_Cluster: an exception that may be used.
*/
class cException_Empty_Cluster : public cAbstract_Exception {
public:
cException_Empty_Cluster(const char * errmsg): cAbstract_Exception(errmsg) {};
};
#endif /* PATENT_NEWCLUSTER_H */
| true |
682018b75a09329206fee80985c9345c3cbe8007 | C++ | Niyijie/Chinese-Chess | /Classes/ChessClass.h | UTF-8 | 3,499 | 2.5625 | 3 | [] | no_license | #ifndef ChessClass_h
#define ChessClass_h
#include "cocos2d.h"
USING_NS_CC;
#define RED 1
#define BLACK -1
#define BKING -2
#define BROOK -3
#define BKNIGNT -4
#define BCANNON -5
#define BMANDARIN -6
#define BELEPHANT -7
#define BPAWN -8
#define RKING 2
#define RROOK 3
#define RKNIGNT 4
#define RCANNON 5
#define RMANDARIN 6
#define RELEPHANT 7
#define RPAWN 8
class chess
{
public:
chess()
{
for(int i=0;i<=9;i++)
for(int j=0;j<=10;j++)
ChessBoardFlag[i][j] = 0;
checkFlag = false;
chessID = 0;
}
virtual void moveTrack(Scene *scene,int mode)
{
CCLOG("chess moving...");
}
int ChessBoardFlag[9][10];
bool checkFlag; //是否将军的标志
int chessID;
int color;
int cx;
int cy;
};
class king:public chess
{
public:
king(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RKING;
color = RED;
}
else if(ID<0)
{
chessID = BKING;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
class rook:public chess
{
public:
rook(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RROOK;
color = RED;
}
else if(ID<0)
{
chessID = BROOK;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
class knight:public chess
{
public:
knight(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RKNIGNT;
color = RED;
}
else if(ID<0)
{
chessID = BKNIGNT;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
class Cannon:public chess
{
public:
Cannon(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RCANNON;
color = RED;
}
else if(ID<0)
{
chessID = BCANNON;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
class Mandarin:public chess
{
public:
Mandarin(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RMANDARIN;
color = RED;
}
else if(ID<0)
{
chessID = BMANDARIN;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
class Elephant:public chess
{
public:
Elephant(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RELEPHANT;
color = RED;
}
else if(ID<0)
{
chessID = BELEPHANT;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
class Pawn:public chess
{
public:
Pawn(int ID,int xx,int yy)
{
checkFlag = false;
cx = xx;
cy = yy;
if(ID > 0)
{
chessID = RPAWN;
color = RED;
}
else if(ID<0)
{
chessID = BPAWN;
color = BLACK;
}
}
void moveTrack(Scene *scene,int mode);
};
#endif
| true |
71dca8156c3ae1e1d37cf3906dba8dc6bb142d91 | C++ | GarrettXUPT/C-_updata | /p5_20200505/源.cpp | GB18030 | 4,321 | 3.828125 | 4 | [] | no_license | #include<iostream>
using namespace std;
/*
һع÷
ںУβںòĻԲβֻ֣ͣ(ԭ)Ҳ
ͷŵ֮ǰǰ÷
C++11ú÷ͣںͺУдڲб֮
auto func(int a, int b) ->void auto־Ϊ÷ֵͣǴ->֮ʼ
ǰinlineͨͱ
úԴСǵкƵ
1.inlineӰڱinlineֺдϵͳԽøúĵö滻Ϊ壬
int func(){
return 1;
}
int abc = func(5) εʱϵͳͻ᳢ʹint abc = 1 ԭ
2.inlineֻǿ߶ԱĽ飬ԳȥҲԲȥȡںϹܣͬıͬ
3.Ķͷļ(.hļ)ʹ.cppͿֱӽincludeԱ
ҵԴ룬滻ڵ
ȱ㣺
ŵ㣺
滻ɹԺСѹջСռõڴ棬ߴЧ
ȱ㣺
ɴ
飺
ĺ御Сֹ
ע⣺
֮Чϴinline뾡Сѭ֧ݹ鲻Ҫinline
пΪЩ룬ܾΪ
constexprԿһָΪϸ
#defineչҲinline
Ӻ÷ܽ
1ΪvoidʾκͣǿԵһʱvoidʹΪһvoidֵ
ķֵ
2ָͷ
3һãúֻûʵֲ
4ֻܶһΣԴļУ
5ΪβΣԼӵĸıֵ൱Cָ룬ҴЧʽϸ
6֧
ġconst char*,char const*, char* constߵ
const char* ָָݲɱ䣬˼Dzָͨ
char const* ܵȼ
char* const ڶʱʼʾpһָһͲָָָɱ
const char* const p = str; pָָҲɸı
int i = 100;
const int& a = i; aݲ
5βдconst
ںıβεֵôҪβбconst ֵֹ
ʵͿԸ
*/
/*
÷
*/
auto func(int a, int b) ->void {
cout << "÷ֵ" << endl;
}
/*
ͨ
*/
void test01() {
cout << "Ǹͨ" << endl;
}
/*
*/
inline void test02() {
cout << "һ" << endl;
}
/*
Ӻ÷
*/
void funca() {
}
void funcb() {
return funca();
}
/*
ִԱͨDZ
еطеãֵʱĵַ
ڸõַڴдֵ
*/
int* funcc() {
int value1 = 9;
return &value1;
}
/*
ڸõַڴдֵҲ
ڵʱýӣʹӾû
*/
int& funcd() {
int value1 = 9;
return value1;
}
int main() {
/*
ú÷ֵͺ
*/
int a = 1, b = 2;
func(a, b);
system("pause");
return 0;
} | true |
9a46fa058f8f6301e7800342f6c6c1554b5d1113 | C++ | voivoid/ComObjectSample | /ComObject/arithmetics_factory.cpp | UTF-8 | 1,614 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "arithmetics_factory.h"
#include "arithmetics_impl.h"
#include <memory>
namespace
{
std::atomic_size_t g_instances = 0;
std::atomic_size_t g_locks = 0;
}
CoArithmeticsFactory::CoArithmeticsFactory() : m_references( 0 )
{
++g_instances;
}
CoArithmeticsFactory::~CoArithmeticsFactory()
{
--g_instances;
}
STDMETHODIMP CoArithmeticsFactory::QueryInterface( REFIID iface_id, void ** iface_ptr )
{
assert( iface_ptr );
*iface_ptr = nullptr;
if ( iface_id == IID_IUnknown )
{
*iface_ptr = static_cast<IUnknown*>( this );
}
else if ( iface_id == IID_IClassFactory )
{
*iface_ptr = static_cast<IClassFactory*>( this );
}
if (*iface_ptr)
{
AddRef();
}
return *iface_ptr ? S_OK : E_NOINTERFACE;
}
STDMETHODIMP_( ULONG ) CoArithmeticsFactory::AddRef()
{
return ++m_references;
}
STDMETHODIMP_( ULONG ) CoArithmeticsFactory::Release()
{
auto updated_refs = --m_references;
if ( updated_refs == 0 )
{
delete this;
}
return updated_refs;
}
STDMETHODIMP CoArithmeticsFactory::CreateInstance( IUnknown* outer_ptr, REFIID iface_id, void** iface_ptr )
{
if ( outer_ptr )
{
return CLASS_E_NOAGGREGATION;
}
auto arithmetics_ptr = std::make_unique<CoArithmetics>();
const HRESULT res = arithmetics_ptr->QueryInterface( iface_id, iface_ptr );
if ( SUCCEEDED( res ) )
{
arithmetics_ptr.release();
}
return res;
}
STDMETHODIMP CoArithmeticsFactory::LockServer( BOOL lock )
{
lock ? ++g_locks : --g_locks;
return S_OK;
}
size_t CoArithmeticsFactory::GetInstancesNum()
{
return g_instances + g_locks;
}
| true |
8cae40166f632c29864bd6874107d4e055548258 | C++ | jmcarter17/Primes | /tests/testListPrimesUpToANumber.cpp | UTF-8 | 1,190 | 3.1875 | 3 | [] | no_license | #include <CppUTest/TestHarness.h>
#include <list>
#include "PrimeLister.h"
TEST_GROUP(PrimeLister){
PrimeLister pl;
std::list<int> listOfPrimes;
void setup(){
listOfPrimes.clear();
}
void checkListOfPrimesUpTo(int number, std::list<int> list){
pl.sieve(number);
listOfPrimes = pl.getList();
CHECK_EQUAL(list.size(), listOfPrimes.size());
auto j = listOfPrimes.begin();
for (auto i = list.begin(); i != list.end(); ++i) {
CHECK_EQUAL(*i, *j);
++j;
}
}
};
TEST(PrimeLister, List_Of_Primes){
checkListOfPrimesUpTo(1,{});
checkListOfPrimesUpTo(0, {});
checkListOfPrimesUpTo(-1, {});
checkListOfPrimesUpTo(2,{2});
checkListOfPrimesUpTo(3, {2,3});
checkListOfPrimesUpTo(10, {2,3,5,7});
}
TEST(PrimeLister, Sum_Of_Primes){
pl.sieve(10);
CHECK_EQUAL(17, pl.sum());
pl.sieve(100);
CHECK_EQUAL(1060, pl.sum());
pl.sieve(1000);
CHECK_EQUAL(76127, pl.sum());
pl.sieve(10000);
CHECK_EQUAL(5736396, pl.sum());
pl.sieve(100000);
CHECK_EQUAL(454396537, pl.sum());
// pl.sieve(2000000);
// CHECK_EQUAL(142913828922, pl.sum());
} | true |
5cf24323ea1b51c1323e7639767a85c4d482ba36 | C++ | lgarczyn/Abstract-VM | /src/Operands/Operand.hpp | UTF-8 | 3,060 | 2.90625 | 3 | [] | no_license | #pragma once
#include "Exceptions/VMException.hpp"
#include "IOperand.hpp"
#include "Libs/SafeInt.hpp"
#include <string>
typedef SafeInt<int8_t> safe_int8;
typedef SafeInt<int16_t> safe_int16;
typedef SafeInt<int32_t> safe_int32;
// Implements all operations on the logical level
class AOperand : public virtual IOperand
{
public:
// Utility
int getMaxPrecision( IOperand const& rhs ) const;
// Operations
IOperand const* operator+( IOperand const& rhs ) const;
IOperand const* operator-( IOperand const& rhs ) const;
IOperand const* operator*( IOperand const& rhs ) const;
IOperand const* operator/( IOperand const& rhs ) const;
IOperand const* operator%( IOperand const& rhs ) const;
bool operator==( IOperand const& rhs ) const;
bool operator!=( IOperand const& rhs ) const;
// Cast to any of the underlying types
virtual safe_int8 asI8() const = 0;
virtual safe_int16 asI16() const = 0;
virtual safe_int32 asI32() const = 0;
virtual float asF32() const = 0;
virtual double asF64() const = 0;
virtual double asF80() const = 0;
virtual bool isZero() const = 0;
};
// The type specific implementation of IOperand
// Handles type directly
template <typename T> class Operand : public AOperand
{
private:
static const eOperandType type;
T _value;
std::string _representation;
public:
// Coplien's form basic definitions
Operand( T value );
Operand()
: Operand( 0 )
{
}
Operand( const Operand& cpy ) = default;
Operand& operator=( const Operand& rhs ) = default;
~Operand() = default;
// Various utility functions
const IOperand* clone() const { return new Operand( *this ); }
int getPrecision( void ) const { return static_cast<int>( type ); }
eOperandType getType( void ) const { return type; }
const std::string& getTypeName( void ) const { return IOperand::operands[ type ].name; }
bool isZero( void ) const { return _value == 0; }
bool operator!=( IOperand const& rhs ) const { return !( *this == rhs ); }
std::string const& toString( void ) const { return this->_representation; }
char toChar( void ) const
{
if ( type == TypeI8 )
return _value;
throw ForbiddenPrintException( this->getTypeName() );
}
private:
// Casting functions
safe_int8 asI8() const { return static_cast<safe_int8>( this->_value ); }
safe_int16 asI16() const { return static_cast<safe_int16>( this->_value ); }
safe_int32 asI32() const { return static_cast<safe_int32>( this->_value ); }
float asF32() const { return static_cast<float>( this->_value ); }
double asF64() const { return static_cast<double>( this->_value ); }
double asF80() const { return static_cast<long double>( this->_value ); }
static std::string toRepresentation( T i );
};
template<> Operand<safe_int8>::Operand( safe_int8 value );
template<> Operand<safe_int16>::Operand( safe_int16 value );
template<> Operand<safe_int32>::Operand( safe_int32 value );
template<> Operand<float>::Operand( float value );
template<> Operand<double>::Operand( double value );
template<> Operand<long double>::Operand( long double value );
| true |
24e993f57d6a584132f54c16bf25b8f564d24e76 | C++ | colinrlly/Automatic_Plant_Watering_Machine | /first_water_machine/first_water_machine.ino | UTF-8 | 806 | 3.359375 | 3 | [] | no_license | int motorPin = A0; // pin that turns on the motor
int watertime = 90; // how long to water in seconds
int waittime = 4320; // how long to wait between watering, in minutes
void setup() {
pinMode(motorPin, OUTPUT); // set A0 to an output so we can use it to turn on the transistor
pinMode(LED_BUILTIN, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
}
void loop() {
digitalWrite(motorPin, HIGH); // turn on the motor
digitalWrite(LED_BUILTIN, HIGH); // turn on the LED
delay(90000); // multiply by 1000 to translate seconds to milliseconds
digitalWrite(motorPin, LOW); // turn off the motor
digitalWrite(LED_BUILTIN, LOW); // turn off the LED
delay(waittime*60000); // multiply by 60000 to translate minutes to milliseconds
}
| true |
8034f46b694384dc25f7c7ac35e65b8469ea37ba | C++ | hyoilll/hong_cplusplus | /chapter2-3/main.cpp | UHC | 771 | 3.59375 | 4 | [] | no_license | /*
ʺ c++ 11 <cstdint>
ּ ϰ ֱ ü ٸ ִ.
ȮǼ ذϱ Ȱ ϴ ' ʺ '
*/
#include <iostream>
int main()
{
using namespace std;
std::int16_t i(5); //16bit Ҵϰڴ. = short
std::int8_t myint = 65; //8bit ҴѴ. = char
cout << myint << endl; //A
cout << sizeof(i) << endl; //2bytes
cout << sizeof(myint) << endl; //1bytes
std::int_fast8_t fi(5); //int 8bit ߿ Ÿ Ҵ
std::int_least64_t fl(5); // 64bit Ҵ
cout << sizeof(fi) << endl; //1bytes
cout << sizeof(fl) << endl; //8bytes
return 0;
} | true |
bf6654b1ca91fe245dbbf52a20d89d07509d1cb5 | C++ | jasonfan1997/convexoptimization | /project (1)/DENSE_DATA_READ.h | UTF-8 | 1,317 | 2.890625 | 3 | [] | no_license | #ifndef DENSE_DATA_READ_H
#define DENSE_DATA_READ_H
#include <fstream>
#include <cstring>
#include <string>
#include <cstdlib>
#include<vector>
#include <stdlib.h>
#include "Matrix.h"
using namespace std;
void DataGen(int m, int n, string &pathname)
{
Matrix A(m,n);
Matrix b(m,1);
for(int i = 0; i < m; i++)
{
b.data[i][0]= rand()%10;
for(int j = 0; j < n; j++)
{
A.data[i][j]=rand()%10/10.0;
}
}
string m_s = to_string(m);
string n_s = to_string(n);
pathname = m_s + "_" + n_s +".txt";
ofstream fout;
fout.open(pathname.c_str());
for(int i = 0; i < m ; i++)
{
fout << b.data[i][0] << " ";
for(int j = 0; j < n; j++)
fout << A.data[i][j] << " ";
fout << "\n";
}
fout.close();
}
void DataRead(int m, int n,string pathname, Matrix &b, Matrix &M)
{
ifstream fin;
fin.open(pathname.c_str());
M.row= m;
M.column= n;
b.row= m;
b.column= 1;
if (fin.is_open())
{
string line;
int i = 0;
int j= 0;
while(getline(fin,line)){
char *str = (char*)line.data();
char *seg;
j= 0;
seg= strtok(str, " ");
b.data[i][0]= atof(seg);
seg= strtok(NULL, " ");
while( seg != NULL)
{
M.data[i][j]= atof(seg);
j= j+1;
seg= strtok(NULL, " ");
}
i= i+ 1;
}
}
}
#endif
| true |
6e8752434dfd8d63a352a1524dd4f0ec95ed9608 | C++ | PatiVioleta/Graph-Data-Structure-And-Algorithms | /Graph Data Structure And Algorithms/Huffman/main.cpp | UTF-8 | 3,055 | 2.6875 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
ifstream f("in");
ofstream g("out");
char s[100],copie[100];
int k,nrCaractere;
struct NOD{
char ch='*';
int st=-1;
int dr=-1;
int fr=0;}nod[100];
struct compara{ bool operator()(NOD x, NOD y) {return x.fr > y.fr;}};
priority_queue<NOD, vector<NOD>, compara> Q;
void noduriInitiale(int &k)
{
f.getline(s,100); ///s sirul de caractere
k=0; ///nr de noduri din graf
strcpy(copie,s);
for(int i=0;i<strlen(s);i++)
{
char curent=s[i];
int aparitii=0;
for(int j=0;j<strlen(s);j++)
if(s[j]==curent)
{
aparitii++;
strcpy(s+j,s+j+1);
j--;
}
nod[k].ch=curent;
nod[k].fr=aparitii;
Q.push(nod[k]);
k++;
i--;
}
}
void afisareNoduri()
{
for(int i=0;i<k;i++)
cout<<"nodul cu cifra "<<nod[i].ch<<" aparitii: "<<nod[i].fr<<" st: "<<nod[i].st<<" dr: "<<nod[i].dr<<endl;
}
void afisareNod(NOD i)
{
cout<<"continut "<<i.ch<<" fr: "<<i.fr<<" st: "<<i.st<<" dr: "<<i.dr<<endl;
}
void afisareCoada()
{
while(!Q.empty()) {
cout << Q.top().ch << " "<<Q.top().fr<<endl;
Q.pop();
}
}
int cautaNod(NOD x)
{
for(int i=0;i<k;i++)
if(nod[i].ch==x.ch && nod[i].dr==x.dr && nod[i].st==x.st && nod[i].fr==x.fr)
return i;
}
void huffman(int &k)
{
k--;
for(int i=1;i<nrCaractere;i++)
{
k++;
NOD x,y;
x=Q.top();
Q.pop();
y=Q.top();
Q.pop();
nod[k].st=cautaNod(x);
nod[k].dr=cautaNod(y);
nod[k].fr=x.fr+y.fr;
Q.push(nod[k]);
}
}
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout<<arr[i];
cout<<endl;
}
void printCodes(int root, int arr[], int top)
{
if (nod[root].st!=-1)
{
arr[top] = 0;
printCodes(nod[root].st, arr, top + 1);
}
if (nod[root].dr!=-1)
{
arr[top] = 1;
printCodes(nod[root].dr, arr, top + 1);
}
if (nod[root].dr==-1 && nod[root].st==-1)
{
cout<<"root "<<root<<" car "<<nod[root].ch<<": ";
printArr(arr, top);
char cod[100];
strcpy(cod,"");
for(int j=0;j<top;j++)
{
if(arr[j]==1)
strcat (cod,"1");
else
strcat(cod,"0");
}
char* p;
char aux[100];
p=strchr(copie, nod[root].ch);
while (p)
{
strcpy (aux, cod); //aux e codul
strcat (aux, p+1);
strcpy(p, aux);
p=strchr(p+strlen(cod), nod[root].ch);
}
//cout<<copie<<endl;
}
}
int main()
{
noduriInitiale(k);
//afisareNoduri();
//afisareCoada();
nrCaractere=k;
huffman(k);
cout<<endl;
k++;
//afisareNoduri();
int arr[100];
printCodes(10,arr,0);
cout<<endl<<copie<<endl;
g<<copie;
return 0;
}
| true |
2457bce72934c9a2a423e7f060f110683d6178ab | C++ | eknaepen/NP | /Candy-Crush-NP/candy_field.h | UTF-8 | 434 | 2.65625 | 3 | [] | no_license | #ifndef CANDY_FIELD_H
#define CANDY_FIELD_H
#include "random_candy.h"
#include "field.h"
class Candy_Field : public Field
{
public:
Candy_Field() : rand(new Random_candy){} // get a new random_candy
virtual ~Candy_Field(){delete rand;}
unsigned char setsign(){ // asign the sign to fill grid
sign=rand->color;
return sign;
}
private:
const Random_candy * rand;
};
#endif // CANDY_FIELD_H
| true |
81bcbbcee5e3b38d9c4db29fb06d8122da4b2463 | C++ | eli-schwartz/sysdig | /userspace/libsinsp/async_container.h | UTF-8 | 2,964 | 2.671875 | 3 | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
Copyright (C) 2019 Draios Inc dba Sysdig.
This file is part of sysdig.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "async_key_value_source.h"
#include "container_info.h"
#include "container.h"
namespace sysdig {
/**
* \brief Base class for async container metadata sources
* @tparam key_type lookup key (container id plus optionally other data)
*
* The result type is hardcoded as sinsp_container_info.
*/
template<typename key_type>
class async_container_source : public async_key_value_source<key_type, sinsp_container_info>
{
public:
using async_key_value_source<key_type, sinsp_container_info>::async_key_value_source;
/**
* \brief Start async lookup of container metadata
* @param key the container lookup key
* @param manager the instance of sinsp_container_manager to store
* the metadata found
*/
void lookup_container(const key_type& key, sinsp_container_manager *manager);
/**
* \brief Wait for all pending lookups to complete
*/
virtual void quiesce() {
this->stop();
}
};
template<typename key_type>
void async_container_source<key_type>::lookup_container(const key_type& key, sinsp_container_manager *manager)
{
auto cb = [manager](const key_type& key, const sinsp_container_info &res)
{
g_logger.format(sinsp_logger::SEV_DEBUG,
"async_container_source (%s): Source callback result successful=%s",
static_cast<const std::string&>(key).c_str(),
(res.m_status == sinsp_container_lookup_state::SUCCESSFUL ? "true" : "false"));
// store the container metadata in container_manager regardless of the result
// this ensures that we don't get stuck with incomplete containers
// when all async lookups fail
//
// the manager will ignore any lookup results reported after the first
// successful one and return false
//
// if we did use the metadata and the lookup succeeded,
// generate a container event for libsinsp consumers
if(manager->update_container(res) && res.m_status == sinsp_container_lookup_state::SUCCESSFUL)
{
manager->notify_new_container(res);
}
};
sinsp_container_info result;
if (this->lookup(key, result, cb))
{
// if a previous lookup call already found the metadata, process it now
cb(key, result);
// This should *never* happen, as ttl is 0 (never wait)
g_logger.format(sinsp_logger::SEV_ERROR,
"async_container_source (%s): Unexpected immediate return from lookup()",
static_cast<const std::string&>(key).c_str());
}
}
}
| true |
0be5557edc73760e506585d04768c2303e09d88b | C++ | kaikai4n/leetcode_practice | /problems/200-300/207/2021_04_17.cpp | UTF-8 | 1,697 | 3.03125 | 3 | [] | no_license | /*
* https://leetcode.com/problems/course-schedule/
* DFS Search: time: O(V + E), space: O(V + E)
* Runtime: 24 ms, faster than 43.26% of C++ online submissions
* Memory Usage: 17.4 MB, less than 7.52% of C++ online submissions
*/
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
for (auto pre: prerequisites) {
graph[pre[0]].push_back(pre[1]);
}
vector<bool> checkBefore(numCourses, false);
for (int startNode = 0; startNode < numCourses; startNode ++) {
if (checkBefore[startNode])
continue;
vector<bool> traveled(numCourses, false);
vector<int> traveledNodes;
stack<pair<int, bool>> s;
s.push({startNode, false});
while (!s.empty()) {
auto topNode = s.top();
int node = topNode.first, isEnd = topNode.second;
s.pop();
if (isEnd) {
traveled[node] = false;
continue;
}
s.push({node, true});
traveled[node] = true;
traveledNodes.push_back(node);
for (int neighbor: graph[node]) {
if (checkBefore[neighbor])
continue;
else if (traveled[neighbor])
return false;
else
s.push({neighbor, false});
}
}
for (int node: traveledNodes)
checkBefore[node] = true;
}
return true;
}
};
| true |
46d11c4f4703b705da27330b098c68d60042d4ac | C++ | moves-rwth/carl-storm | /src/carl/core/DivisionResult.h | UTF-8 | 371 | 3.125 | 3 | [
"MIT"
] | permissive | /**
* @file DivisionResult.h
* @author Sebastian Junges
*
*/
#pragma once
namespace carl
{
/**
* A strongly typed pair encoding the result of a division,
* being a quotient and a remainder.
*/
template<typename Type>
struct DivisionResult
{
public:
DivisionResult(const Type& q, const Type& r) :
quotient(q), remainder(r)
{}
Type quotient;
Type remainder;
};
} | true |
8533151ac05eb4021a8fe44797e4c8f92d0b5b2e | C++ | devaar100/SudokuSolver | /sudoku_solver.cpp | UTF-8 | 1,441 | 2.75 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int sudoku[9][9];
int grids[9];
int rows[9];
int cols[9];
bool done=false;
int MAX=(1<<11)-1;
void print(){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++)
cout<<sudoku[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
void solve(int i,int j){
if(i==8&&j==9){
print();
done=true;
return;
}
if(j==9){
solve(i+1,0);
return;
}
if(sudoku[i][j]!=0){
solve(i,j+1);
return;
}
int g=((i/3)*3)+(j/3);
int pos = (~grids[g])&(~cols[j])&(~rows[i]);
for(int p=1;p<=9&&!done;p++){
if(pos&(1<<p)){
//cout<<i<<" "<<j<<" "<<p<<endl;
sudoku[i][j]=p;
grids[g]|=(1<<p);
rows[i]|=(1<<p);
cols[j]|=(1<<p);
//print();
solve(i,j+1);
sudoku[i][j]=0;
//cout<<(MAX-(1<<p))<<endl;
grids[g]&=(MAX-(1<<p));
rows[i]&=(MAX-(1<<p));
cols[j]&=(MAX-(1<<p));
}
}
}
int main() {
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
cin>>sudoku[i][j];
int g=((i/3)*3)+(j/3);
grids[g]|=(1<<sudoku[i][j]);
rows[i]|=(1<<sudoku[i][j]);
cols[j]|=(1<<sudoku[i][j]);
}
solve(0,0);
return 0;
}
| true |
8f1eaffae57bf7eee20278f6672a364643c2fe3d | C++ | ProshantaDebnath/CP-chapter | /C++/Basic/Array/4.Program to search for an element in an array using linear search.cpp | UTF-8 | 587 | 3.9375 | 4 | [] | no_license |
#include<iostream>
using namespace std;
int linearsearch(int arr[], int x,int n){
int i;
for(i = 0; i < n; i++)
if(arr[i]== x)
return i;
return -1;
}
int main(){
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(int);
int x;
cout << "Enter the element want to search : " ;
cin >> x;
int result = linearsearch(arr, x, n);
(result == -1)
? cout << "Element does not exists."
: cout << "Search item present at index :" << result;
return 0;
}
//The time complexity of the above algorithm is O(n).
| true |
5c3644f02c21ae4c563a76f51c2d0308129bd7f5 | C++ | ideahitme/contest | /hackerearth/thoughworks/points/code.cpp | UTF-8 | 1,408 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
ll sum_in_range(int l, int r, vector<ll> &prefix){
if (l == 0) return prefix[r];
else return prefix[r] - prefix[l-1];
}
bool is_prime(int n){
if (n == 2) return true;
bool is = true;
int s = floor(sqrt(n)) + 1;
for(int j = 2; j <= s; j++){
if (n % j == 0) {
is = false;
break;
}
}
return is;
}
int main(int argc, char const *argv[])
{
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++) cin >> a[i];
vector<ll> prefix(n);
ll so_far = 0;
for(int i = 0; i < n; i++){
so_far += a[i];
prefix[i] = so_far;
}
vector<int> primes;
for(int i = 2; i < 5101; i++){
if (is_prime(i)) primes.push_back(i);
}
// for(int i = 0; i < primes.size(); i++){
// cout << primes[i] << endl;
// }
vector<ll> dp(n);
for(int i = 0; i < n; i++){
if (i == 0) dp[i] = 0;
else if (i == 1) dp[i] = a[0] + a[1];
else {
ll _max = dp[i-1];
int cur = 0;
while(primes[cur] <= i + 1){
ll to_compare;
if (primes[cur] == i + 1){
ll cand = prefix[i];
if (cand > _max) _max = cand;
} else {
ll addon = ( i >= primes[cur] + 1 ) ? dp[i-primes[cur]-1] : 0;
ll cand = sum_in_range(i-primes[cur]+1,i,prefix) + addon;
if (cand > _max) _max = cand;
}
cur++;
}
dp[i] = _max;
}
}
cout << dp[n-1] << endl;
/* code */
return 0;
}
| true |
adbfb07bde1d0bd2e9e9c715ab9149b7a65da104 | C++ | CarlRaymond/TCS3200 | /colorsample/hsv.cpp | UTF-8 | 1,036 | 3.15625 | 3 | [] | no_license | #include "hsv.h";
#include "math.h";
HSV::HSV(int h, unsigned int s, unsigned int v) {
this->h = h;
this->s = s;
this->v = v;
}
HSV::HSV() : HSV(0, 0, 0) {
}
void HSV::fromScaledRGB(unsigned int scale, unsigned int r, unsigned int g, unsigned int b, HSV &out) {
// scale is the maximum range of r, g, b.
// Find min and max of r,g,b
unsigned int min = r;
unsigned int max = r;
if (g > max) { max = g; }
if (g < min) { min = g; }
if (b > max) { max = b; }
if (b < min) { min = b; }
unsigned int delta = max - min;
int h = 0;
int s = 0;
int v = 0;
v = (250L * max) / scale ;
if (max == 0) {
s = 0;
h = -1;
}
else {
s = (250L * delta) / max;
if (r == max) {
// Yellow to magenta. H = -60 to 60
h = 60 * (g - b) / delta;
}
else if (g == max) {
// Cyan to yellow. H = 60 to 180
h = 120 + (60 * (b - r) / delta);
}
else {
// Magenta to cyan. H = 180 to 300
h = 240 + (60 * (r - g) / delta);
}
if (h < 0) {
h += 360;
}
}
out.h = h;
out.s = s;
out.v = v;
return;
} | true |
089b37fefac1ceee934c73e75e9d987d78ea22cd | C++ | zeikar/Break-Bricks-3D | /BreakBricks3D/BreakBricks3D/GameLevelManager.cpp | UHC | 1,405 | 2.953125 | 3 | [] | no_license | #include "GameLevelManager.h"
#include "GameObjectManager.h"
void GameLevelManager::init()
{
ifstream levelDataFile("Data\\level.txt");
if (!levelDataFile)
{
cout << "Cannot read level.dat File!!" << endl;
return;
}
// ʱȭ
levelDataFile >> totalLevel >> mapHeight >> mapWidth;
for (int i = 0; i < totalLevel; i++)
{
stringstream input;
for (int i = 0; i < mapHeight; i++)
{
string temp;
getline(levelDataFile, temp);
// ׳
if (temp.empty())
{
i--;
continue;
}
input << temp;
}
blockInfo.push_back(input.str());
}
}
bool GameLevelManager::initNewLevel(bool firstLevel)
{
if (firstLevel)
{
currentLevel = 0;
}
if (currentLevel >= totalLevel)
{
return false;
}
GameObjectManager::getInstance().initPlayer();
GameObjectManager::getInstance().initBall();
initBlocks();
++currentLevel;
return true;
}
void GameLevelManager::initBlocks()
{
for (int i = 0; i < mapHeight; i++)
{
for (int j = 0; j < mapWidth; j++)
{
char blockType = blockInfo[currentLevel][i * mapWidth + j];
int matType, hp;
if (blockType == '0')
{
continue;
}
if (blockType >= '1' && blockType <= '3')
{
matType = blockType - '0' + 2;
hp = blockType - '0';
}
else
{
matType = 1;
hp = -1;
}
GameObjectManager::getInstance().addBlock(j, mapHeight - i, matType, hp);
}
}
}
| true |
7428acd500a2621c235250ee935c833946bb35da | C++ | benedicka/Competitive-Programming | /UVA/11057/12642592_AC_900ms_0kB.cpp | UTF-8 | 701 | 2.953125 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int n,price[10000],m,ans1,ans2,min;
while (scanf("%d",&n)!=EOF)
{
for (int i=0;i<n;i++)
{
scanf("%d",&price[i]);
}
scanf("%d",&m);
for (int i=0;i<n;i++)
{
for (int j=i+1;j<n;j++)
{
if (price[i]>price[j])
{
int swap;
swap=price[i];
price[i]=price[j];
price[j]=swap;
}
}
}
min = m;
for (int i=0;i<n-1;i++)
{
for (int j=i+1;j<n;j++)
{
if (price[i]+price[j]==m && price[j]-price[i]<min)
{
ans1=price[i];
ans2=price[j];
min=price[j]-price[i];
if (min==0) break;
}
}
}
printf("Peter should buy books whose prices are %d and %d.\n\n",ans1,ans2);
}
return 0;
} | true |
a6659c50049f0d01bc5065b6fcc46f605fdf37a9 | C++ | staryzhu/myTest | /testmmv.cpp | UTF-8 | 547 | 2.78125 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char str[15] = "abcdefghi";
char *dest = &(str[3]);
char *p = (char *)malloc(sizeof(char) * 1024);
memcpy(p, str, 10);
printf("p addr : %x\n", p);
p = (char *)realloc(p, sizeof(char) *2048);
printf("p raddr: %x\n", p);
printf("src : %s\n", str);
//memmove(dest, str, 12);
memcpy(dest, str, 12);
memcpy(dest, str, 12);
printf("out: %s\n", str);
printf("p val : %s \n", p);
char *q = p + 3;
memcpy(q, p, 20);
printf("p val : %s \n", p);
free(p);
return 0;
}
| true |
02647030d0d34cec7f2ce2fc1c7178238ff249a5 | C++ | NazmulHayat/Competitive-Programming | /CodeForces And Random Practice Problems/matchingbrackets.cpp | UTF-8 | 861 | 2.796875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;\
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
char f1 = '(';
char f2 = ')';
char s1 = '[';
char s2 = ']';
char t1 = '{';
char t2 = '}';
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0, cnt5 = 0, cnt6 = 0;
string s;
cin>>s;
for(int i = 0 ; i < s.length() ; i++)
{
if(s[i] == f1)
cnt1++;
else if(s[i] == f2)
cnt2++;
else if(s[i] == s1)
cnt3++;
else if(s[i] == s2)
cnt4++;
else if(s[i] == t1)
cnt5++;
else if(s[i] == t2)
cnt6++;
}
cout<<cnt1<<endl<<cnt2<<endl<<cnt3<<endl<<cnt4<<endl<<cnt5<<endl<<cnt6<<endl;
if(cnt1 == cnt2 && cnt3 == cnt4 && cnt5 == cnt6)
printf("Yes\n");
else
printf("No\n");
}
| true |
a4abd20d6f9926077865bac93c997f2eb33b81b2 | C++ | ShadmanShihab/UVA-Solutions | /uva 10127 Ones(bigmod) .cpp | UTF-8 | 633 | 3.015625 | 3 | [] | no_license | ///uva 10127 Ones(bigmod)
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll BigMod(ll n, ll p, ll m)
{
if(p==0)
return 1;
if(p % 2 == 0)
{
ll ret = BigMod(n, p/2, m);
return ((ret%m) * (ret%m)) %m;
}
else
return ((n%m) * (BigMod(n, p-1, m) %m))%m;
}
int main()
{
ll ones;
ll m;
int c;
while(scanf("%lld",&m)==1)
{
c = 1;
ones = 1;
while(ones % m!=0)
{
ones = (ones*10) + 1;
c++;
ones = BigMod(ones,1,m);
}
printf("%d\n",c);
}
return 0;
}
| true |
8bd4825ae7401092c44ff1cf48e13ad5d973a046 | C++ | networkit/networkit | /networkit/cpp/components/RandomSpanningForest.cpp | UTF-8 | 1,403 | 2.65625 | 3 | [
"MIT"
] | permissive | /*
* RandomSpanningForest.cpp
*
* Created on: 06.09.2015
* Author: Henning
*/
#include <unordered_set>
#include <networkit/components/ConnectedComponents.hpp>
#include <networkit/components/RandomSpanningForest.hpp>
#include <networkit/graph/GraphTools.hpp>
namespace NetworKit {
RandomSpanningForest::RandomSpanningForest(const Graph &G) : SpanningForest(G) {}
void RandomSpanningForest::run() {
// handle disconnected graphs:
// determine connected components first
// then start random walk in each component!
ConnectedComponents cc(*G);
cc.run();
const auto comps = cc.getComponents();
forest = GraphTools::copyNodes(*G);
for (const auto &comp : comps) {
std::unordered_set<node> visited;
// find and process random root
index rand = Aux::Random::integer(comp.size() - 1);
node curr = comp[rand];
visited.insert(curr);
// random walk starting from root
while (visited.size() < comp.size()) {
// get random neighbor
node neigh = GraphTools::randomNeighbor(*G, curr);
// if not seen before, insert tree edge
if (visited.count(neigh) == 0) {
forest.addEdge(curr, neigh);
visited.insert(neigh);
}
// move to neighbor
curr = neigh;
}
}
}
} /* namespace NetworKit */
| true |
c7df2cd02d3d91cde62e36753ee96c129d9603f7 | C++ | Xylot/Labs | /Lab 8/Data Files/sample_binary1_soln.cpp | UTF-8 | 4,401 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
/* this program reads a sequence of 8 binary bytes of data into an int array
and prints them out. The data is output in both decimal and hex.
It then rewinds the file to the beginning, and reads the same binary data
into a char array and prints them out, first in decimal and then in hex.
Note that PCs are big-endian, whereas Macs are little-endian. Therefore
there are two versions of the program (controlled by #ifdef's). The first is for
Macs, the second is for PCs. The only difference is that the PC version swaps the
bytes around after reading, so it can give the same results as the Mac does.
Note 2: It only opens the data file once. Then after reading the 24 bytes, using
ifstream.seekg(0) to rewind to the beginning of the file.
Note 3: the read function expects the address of a char array. Therefore,
to use it to read integer data, we have to cast the address of the int array so
it looks like the address of a char array. For this, we use reinterpret_cast<char *>
*/
using namespace std;
#ifndef WIN32 // Mac version first:
int main( )
{
char buf[8]={0};
int ibuf[2]={0};
// Open file for reading in binary mode
ifstream ifs("sample_binary1.dat", ios::binary);
if (!ifs) {cerr << "error opening file"<<endl; return 1;}
// read the file into an int array and output as ints and then in hex
ifs.read(reinterpret_cast<char *>(ibuf), 2*sizeof(int));
cout << "int:"<<endl;
for (int i=0;i<2;i++)
cout << dec << setw(10)<< ibuf[i]<<" ";
cout << endl;
// cout <<setfill('0');
for (int i=0;i<6;i++)
cout << "0x"<<hex << setw(8)<< ibuf[i]<<" ";
// cout << setfill(' ');
cout << endl << endl;
// now read the file into a char array
ifs.seekg(0); // rewind the file first.
ifs.read(buf, 8*sizeof(char));
cout << "char: "<<endl;
// output the 8 chars.
for (int i=0;i<8;i++)
cout << " "<<buf[i]<<" ";
cout << endl;
// output the integer version of each char
for (int i=0;i<8;i++)
cout << setw(4)<<static_cast<int>(buf[i])<<" ";
cout << endl;
// and now output it in hexadecimal
for (int i=0;i<8;i++)
cout << "0x"<<hex << setw(2)<<static_cast<int>(buf[i])<<" ";
cout << endl << endl;
return 0;
}
#else //............................PC version, which does byte swapping after reading the ints.
void swap(char &a, char &b); // swaps 2 chars
void reverse(short &sval); // reverse the bytes of a short
void reverse(int &ival); // int
int main( )
{
int ibuf[2]={0};
char buf[8]={0};
// Open file for reading in binary mode
ifstream ifs("sample_binary1.dat", ios::binary);
if (!ifs) {cerr << "error opening file"<<endl; return 1;}
// read the file into an int array and output as ints and then in hex
ifs.read(reinterpret_cast<char *>(ibuf), 2*sizeof(int));
reverse(ibuf[0]);
reverse(ibuf[1]);
cout << "int:"<<endl;
for (int i=0;i<2;i++)
cout << dec << setw(10)<< ibuf[i]<<" ";
cout << endl;
for (int i=0;i<2;i++)
cout << "0x"<<hex << setw(8)<< ibuf[i]<<" ";
cout << endl << endl;
// now read the file into a char array
ifs.seekg(0); // rewind the file first.
ifs.read(buf, 8*sizeof(char));
cout << "char: "<<endl;
// output the 8 chars.
for (int i=0;i<8;i++)
cout << " "<<buf[i]<<" ";
cout << endl;
// output the integer version of each char
for (int i=0;i<8;i++)
cout << dec << setw(4)<<static_cast<int>(buf[i])<<" ";
cout << endl;
// and now output it in hexadecimal
for (int i=0;i<8;i++)
cout << "0x"<<hex << setw(2)<<static_cast<int>(buf[i])<<" ";
cout << endl << endl;
system("pause");
return 0;
}
void swap(char &a, char &b)
{char t = a; a = b; b = t;}
void reverse(short &sval)
{
char *p = reinterpret_cast<char *>(&sval);
swap(p[0],p[1]);
}
void reverse(int &ival)
{
char *p = reinterpret_cast<char *>(&ival);
swap(p[0],p[3]);
swap(p[1],p[2]);
}
#endif
| true |
67180052c21010d8f63adf8246a378baf5bc3e8e | C++ | Rhysoshea/Algos | /Data_Structures/week6_binary_search_trees/my_is_bst_hard.cpp | UTF-8 | 3,885 | 3.046875 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/resource.h>
#endif
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using namespace std;
struct Node {
long long int key;
long long int left;
long long int right;
Node() : key(0), left(-1), right(-1) {}
Node(long long int key_, long long int left_, long long int right_) : key(key_), left(left_), right(right_) {}
};
struct Position {
Position (long long int value, int flag) :
value(value),
flag(flag)
{}
// flag to show that that left !< key or right !>= key
// 0 if ok, 1 if problem
long long int value;
int flag;
};
long long int inOrderTraversal(const vector<Node>& tree, int i, bool& stop, queue<Position>& order) {
long long int left;
long long int right = tree[i].key;
if (tree[i].left == -1 && tree[i].right == -1) {
// cout << tree[i].key << "\n";
order.push(Position(tree[i].key, 0));
return tree[i].key;
}
if (tree[i].left != -1) {
left = inOrderTraversal(tree, tree[i].left, stop, order);
// cout << "left: " << left << " key: " << tree[i].key << "\n";
// if (left > tree[i].key) {
// stop = true;
// }
}
// cout << "left: " << left << " right: " << right << "\n";
// cout << "key: " << tree[i].key << "\n";
if (left < tree[i].key && tree[tree[i].right].key >= tree[i].key && tree[i].right != -1 && tree[i].left != -1) {
order.push(Position(tree[i].key, 0));
} else if (left < tree[i].key && tree[i].right == -1 && tree[i].left != -1) {
order.push(Position(tree[i].key, 0));
} else if (tree[tree[i].right].key >= tree[i].key && tree[i].right != -1 && tree[i].left == -1) {
order.push(Position(tree[i].key, 0));
} else {
order.push(Position(tree[i].key, 1));
}
// cout << tree[i].key << "\n";
if (tree[i].right != -1) {
right = inOrderTraversal(tree, tree[i].right, stop, order);
// cout << "key: " << tree[i].key << " right: " << right << "\n";
// if (tree[i].key > right) {
// stop = true;
// }
}
if (tree[i].right == -1) {
return tree[i].key;
}
return right;
}
bool IsBinarySearchTree(const vector<Node>& tree) {
// Implement correct algorithm here
queue<Position> order;
if (tree.size() < 2){
return true;
}
bool stop = false;
inOrderTraversal(tree, 0, stop, order);
// cout << "queue:\n";
Position last = order.front();
order.pop();
while (!order.empty()) {
Position current = order.front();
// cout << "last: " << last.value << " " << last.flag << " current: " << current.value << " " << current.flag << "\n";
if (last.value > current.value) {
return false;
}
if (current.flag == 1){
return false;
}
last = current;
order.pop();
}
return true;
}
int main() {
int nodes;
cin >> nodes;
vector<Node> tree;
for (int i = 0; i < nodes; ++i) {
long long int key, left, right;
cin >> key >> left >> right;
tree.push_back(Node(key, left, right));
}
if (IsBinarySearchTree(tree)) {
cout << "CORRECT" << endl;
} else {
cout << "INCORRECT" << endl;
}
return 0;
}
// int main (int argc, char **argv)
// {
// #if defined(__unix__) || defined(__APPLE__)
// // Allow larger stack space
// const rlim_t kStackSize = 1024 * 1024 * 1024; // min stack size = 16 MB
// struct rlimit rl;
// int result;
//
// result = getrlimit(RLIMIT_STACK, &rl);
// if (result == 0)
// {
// if (rl.rlim_cur < kStackSize)
// {
// rl.rlim_cur = kStackSize;
// result = setrlimit(RLIMIT_STACK, &rl);
// if (result != 0)
// {
// std::cerr << "setrlimit returned result = " << result << std::endl;
// }
// }
// }
//
// #endif
// return main_test_solution();
// }
| true |
751de7f223370fb93d7c9fe6ae16953269539b1a | C++ | huynguyen1212/bttin | /bttin/9.lagestsmallern.cpp | UTF-8 | 656 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main (){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
if(s.size()==1){
cout<<"-1";
}
else{
int n=s.size();
int i=n-2;
while(i>=0 && s[i]<s[i+1]) i--;
if(i==-1){
cout<<"-1";
}
else{
int k=n-1;
while(s[k]>s[i]){
k--;
}
if(i==0 && s[k]=='0'){
cout<<"-1";
}
else{
swap(s[k],s[i]);
int x=n-1,y=i+1;
while(x>y){
swap(s[x],s[y]);
x--;
y++;
}
for(int i=0;i<n;i++){
cout<<s[i];
}
}
}
}
cout<<endl;
}
return 0;
}
//Code by Ninh Ngoc
| true |
b5e2f00115c66c26480e0ec6d18b180d0f0aa87e | C++ | kkangzzoo/GoF | /Adapter/src/ObjectAdapter.cpp | UTF-8 | 1,463 | 3.28125 | 3 | [] | no_license | /*
* ObjectAdapter.cpp
*
* Created on: 2018. 1. 2.
* Author: daum
* Description: Object Adapter 패턴에 의한 TextShape 클래스의 구현 및 활용 예
* nonAdapter) 객체의 자료형이 다름. -> 객체의 자료형 통일 -> Shape클래스의 자료형으로 통일
* TextShape와 같은 이름으로 Shape클래스의 하위 클래스로 정의 -> Shape 클래스와 동일한 인터페이스를 갖음.
*
* >> Object Adapter 이용
* 내부에서 TextView 클래스 호출. > pText_
*
*/
#include <iostream>
using namespace std;
class Rectangle{
public:
Rectangle(int x1, int y1, int x2, int y2){
x1_=x1; y1_=y1; x2_=x2; y2_=y2;
}
void Draw(){}
private:
int x1_, y1_, x2_, y2_;
};
class TextView{
public:
Rectangle GetExtent(){
return Rectangle(x1_, y1_, x1_+width_,y1_+height_);
}
private:
int x1_,y1_;
int width_, height_;
};
class Shape{
public:
virtual Rectangle BoundingBox()=0;
};
class LineShape:public Shape{
public:
Rectangle BoundingBox(){
return Rectangle(x1_,y1_,x2_,y2_);
}
private:
int x1_, y1_, x2_, y2_;
};
class TextShape:public Shape{
public:
TextShape(){
pText_=new TextView;
}
Rectangle BoundingBox(){
return pText_->GetExtent();
}
private:
TextView *pText_;
};
void DisplayBoundingBox(Shape *pSelectedShape){
(pSelectedShape->BoundingBox()).Draw();
}
int main(){
TextShape text;
DisplayBoundingBox(&text);
}
| true |
be44badbdfdbbb3f137fb42a808026186e22ed60 | C++ | carmaselli/Server_Client_simulator | /Client/Client.cpp | UTF-8 | 3,097 | 2.703125 | 3 | [] | no_license | #include "Client.h"
using namespace std;
Client::Client()
{
IO_handler = new boost::asio::io_service();
socket_forClient = new boost::asio::ip::tcp::socket(*IO_handler);
client_resolver = new boost::asio::ip::tcp::resolver(*IO_handler);
error_.type = N_ERROR;
file = fopen("webService.txt", "wb");
if (file == NULL)
{
error_.type = FILE_ERROR;
error_.errStr = string("Error opening the file");
}
}
void Client::startConnection(const char * host)
{
endpoint = client_resolver->resolve(boost::asio::ip::tcp::resolver::query(host, HELLO_PORT_STR));
boost::system::error_code error;
boost::asio::connect(*socket_forClient, endpoint, error);
if (error)
{
error_.type = CONNECTION_ERROR;
error_.errStr = string("Error while trying to listen to ") + HELLO_PORT_STR + " Port " + error.message();
/*cout << "Error connecting to " << host << " Error Message: " << error.message() << endl;
if (error.value() == boost::asio::error::connection_refused)
cout << "Host " << host << " is not listening on the other side" << endl;*/
}
socket_forClient->non_blocking(true);
}
void Client::generateStringToSend(parseString route)
{
messageToServer = "GET " + route.pathRoute + " HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
}
void Client::sendMessage(void)
{
if (error_.type == N_ERROR)
{
size_t len;
boost::system::error_code error;
do
{
len = socket_forClient->write_some(boost::asio::buffer(messageToServer.c_str(), messageToServer.length()), error);
} while ((error.value() == WSAEWOULDBLOCK));
if (error)
{
//std::cout << "Error while trying to send message from client " << error.message() << std::endl;
error_.type = CONNECTION_ERROR;
error_.errStr = string("Error while trying to send massage. ") + error.message();
}
}
}
void Client::receiveMessage()
{
if (error_.type == N_ERROR)
{
char buf[512];
boost::system::error_code error;
size_t len = 0;
cout << "Receiving Message" << std::endl;
boost::timer::cpu_timer t;
t.start();
boost::timer::cpu_times pastTime = t.elapsed();
double elapsedSeconds = 0.0;
do
{
len = socket_forClient->read_some(boost::asio::buffer(buf), error);
boost::timer::cpu_times currentTime = t.elapsed();
if ((currentTime.wall - pastTime.wall) > 1e9)
{
elapsedSeconds += (currentTime.wall - pastTime.wall) / 1e9;
pastTime = currentTime;
cout << "Pasaron " << (int)floor(elapsedSeconds) << " segundos." << endl;
}
if (!error)
{
messageFromServer += buf;
}
} while (error.value() == WSAEWOULDBLOCK);
if (!error)
{
messageFromServer[len] = '\0';
fputs(messageFromServer.c_str(), file);
printf("%s", messageFromServer.c_str());
error_.errStr = string("Succes reading from server");
fflush(file);
}
else
{
error_.type = CONNECTION_ERROR;
error_.errStr = string("Error while trying to recive message. ") + error.message();
}
}
}
error_t Client::getError()
{
return error_;
}
Client::~Client()
{
fclose(file);
socket_forClient->close();
delete client_resolver;
delete socket_forClient;
delete IO_handler;
}
| true |
e09c89cd408b6f742fa1cd26fb2226d1962edec5 | C++ | tskirilowa/Project | /Store/Product.h | UTF-8 | 1,358 | 3.109375 | 3 | [] | no_license | #pragma once
# include<iostream>
#include"Warehouse.h"
#include"Date.h"
class Product
{
private:
char name[32];
Date expiryDate;
Date dateAraival;
char manufacturer[32];
double unit;
int quantity;
Warehouse location;
char comment[264];
void copy(const Product& other);
public:
Product();
Product(const Product& other);
Product& operator=(const Product& other);
Product(const char* newName, Date newExpiryDate, Date newDateAraival, const char* newManufacturer,double newUnit,int newQuantity, Warehouse newLocation, const char* newComment);
void setName(const char* newName);
const char* getName()const;
void setExpiryDate(int newDay, int newMonth,int newYear);
Date getExpiryDate()const;
void setDateAraival(int newDay,int newMonth, int newYear);
Date getDateArival()const;
void setManufacturer(const char* newManufacturer);
const char* getManufacturer()const;
void setUnit(double newUnit);
double getUnit()const;
void setQuantity(int newQuantity);
int getQuantity()const;
void setLocation(const Warehouse&);
const Warehouse& location()const;
void setComment(const char* newComment);
const char* getComment()const;
friend std::ostream& operator<<(std::ostream& out, const Product& other);
friend std::istream& operator>>(std::istream& in, Product& other);
};
| true |
170133276e4723d8811cb41fea1deb23821aa4f5 | C++ | gro-mit/LeetCode | /537 Complex Number Multiplication.cpp | UTF-8 | 592 | 2.921875 | 3 | [] | no_license | class Solution {
public:
vector<int>toInt(string a){
int plus=int(a.find('+',1));
int r=atoi(a.substr(0,plus).c_str());
int v=atoi(a.substr(plus+1,a.length()-plus-2).c_str());
return vector<int>({r,v});
}
string complexNumberMultiply(string a, string b) {
if(a==""||b=="")return "0";
vector<int> first=toInt(a),second=toInt(b),res(2);
res[0]=first[0]*second[0]-first[1]*second[1];
res[1]=first[0]*second[1]+first[1]*second[0];
string s=to_string(res[0])+"+"+to_string(res[1])+"i";
return s;
}
};
| true |
d9bacb2f7195d9311ab1f354dc3d0c226e740b7d | C++ | Enigma228322/NeuralNetwork | /NeuralNet1/Layer.h | UTF-8 | 1,174 | 3.671875 | 4 | [] | no_license | #pragma once
#include <vector>
struct Layer
{
Layer() {}
Layer(int size_)
{
size = size_;
}
Layer(int size_,const std::vector <double> &values_)
{
size = size_;
values = values_;
}
void operator=(const Layer &other)
{
size = other.size;
values.resize(size);
for (int i = 0; i < size; i++)
{
values[i] = other.values[i];
}
}
Layer operator-(const Layer &other)
{
std::vector <double> v(size);
for (int i = 0; i < size; i++)
{
v[i] = values[i] - other.values[i];
}
return Layer(size, v);
}
Layer operator-(double other)
{
std::vector <double> v(size);
for (int i = 0; i < size; i++)
{
v[i] = values[i] - other;
}
return Layer(size, v);
}
double operator*(const Layer &other)
{
double sum = 0;
for (int i = 0; i < size; i++)
{
sum += values[i] * other.values[i];
}
return sum;
}
Layer operator*(double val)
{
std::vector <double> v(size);
for (int i = 0; i < size; i++)
{
v[i] = values[i] * val;
}
return Layer(size, v);
}
double Sum()
{
double sum = 0;
for (int i = 0; i < size; i++)
{
sum += values[i];
}
return sum;
}
std::vector <double> values;
int size;
}; | true |
ac49c6945e8a65b6485dc57968542c4196fd28f8 | C++ | Lutila243/C- | /programs/exam 2/exam2-16.cpp | UTF-8 | 742 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include<cmath>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
int num=0;
float gal;
float lit;
lit= 3.785;
cout<<"\nEnter the gallon(s)? to convert to liter ";
cin>>gal;
cout<<fixed<<showpoint<<setprecision(3)<<endl;
cout<<"\tnum"<< setw(16)<<"\tGallon"<<setw(25)<<"\tLiter"<<endl;
while(gal<=20){
cout<<fixed<<showpoint<<setprecision(3)<<endl;
cout<<"\t" << num<<setw(25)<<gal<<setw(27)<<lit<<endl;
gal = lit;
num++;
continue;
}
system("pause");
return 0;
}
| true |
875ee931d177fb2616a90f710f89d5764c1ad501 | C++ | fireairforce/CPPalgorithm | /pat/1076.cpp | UTF-8 | 838 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+7;
struct code
{
string a;
string b;
string c;
string d;
}q[maxn];
int main()
{
int n,emm2[maxn]={0},zoom=0;
map<char,int>emm1;
emm1['A']=1;
emm1['B']=2;
emm1['C']=3;
emm1['D']=4;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
cin>>q[i].a>>q[i].b>>q[i].c>>q[i].d;
if(q[i].a[2]=='T')
{
emm2[zoom++]=emm1[q[i].a[0]];
}
else if(q[i].b[2]=='T')
{
emm2[zoom++]=emm1[q[i].b[0]];
}
else if(q[i].c[2]=='T')
{
emm2[zoom++]=emm1[q[i].c[0]];
}
else if(q[i].d[2]=='T')
{
emm2[zoom++]=emm1[q[i].d[0]];
}
}
for(int i=0;i<zoom;i++)
{
printf("%d",emm2[i]);
}
printf("\n");
return 0;
}
| true |
728a943ecefc247b8c88ba2773d45fe369147a35 | C++ | jazzy28/DSA-using-CPP | /introduction/14-if-else-if.cpp | UTF-8 | 644 | 4.15625 | 4 | [] | no_license | #include <iostream>
using namespace std;
// ! operator: negates the condition
int main()
{
bool isFemale = false;//stores a true or a false value
bool isTall = false;
if(isFemale) // is its true, then inner code will be executed
{
cout << "You are a tall female" << endl;
}
else if (isFemale && !isTall)
{
cout << "You are a short female" << endl;
}
else if (!isFemale && isTall)
{
cout << "Your are tall but not female" << endl;
}
else //responding to a situation which says false
{
cout << "You are not a female" << endl;
}
return 0;
}
| true |
6ce41801366d32fb51d8d3eb8a786f2c6dc47fc9 | C++ | LXMKevince/LXMKevince.github.io | /Arduino/libraries/Ciao/examples/CiaoBluemixMQTT/CiaoBluemixMQTT.ino | UTF-8 | 1,351 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
Arduino Ciao example
This sketch uses Ciao mqtt connector. Sketch sends via MQTT brightness and temperature information that will be shown graphically in the blueMix IBM system.
Upload your sketch an than connect to the webpage:
https://quickstart.internetofthings.ibmcloud.com/#/device/BlueMixTest902345/sensor/
NOTE: be sure to activate and configure mqtt connector on Linino OS.
http://labs.arduino.org/Ciao
created September 2015
by andrea[at]arduino[dot]org
*/
#include <Ciao.h>
int ctrl=0;
void setup()
{
Ciao.begin(); //Start the serial connection with the computer
//to view the result open the serial monitor
pinMode(9,OUTPUT);
}
void loop() // run over and over again
{
//getting the voltage reading from the temperature sensor
int readingTemp = analogRead(A0);
// converting readingTemp to voltage
float voltage = readingTemp * 4.56;
voltage /= 1024;
// now print out the temperature
float temperatureC = (voltage - 0.5) * 100 ;
int readingLum = analogRead(A2);
analogWrite(9,map(readingLum,0,1023,0,255));
if (ctrl>=10){
Ciao.write("mqtt","iot-2/evt/status/fmt/json","{\"d\": {\"temperature\":"+String(temperatureC)+",\"luminosity\":"+String(readingLum)+"}}");
ctrl=0;
}
ctrl++;
delay(100);
} | true |
a54001c0f5e6e8b0f3164cc43eb292fd418166cb | C++ | MarkOates/ncurses-art | /src/Quiz.cpp | UTF-8 | 708 | 3.046875 | 3 | [] | no_license |
#include <Quiz.hpp>
#include <random>
#include <random>
#include <algorithm>
Quiz::Quiz(std::vector<Question> questions)
: questions(questions)
{
}
Quiz::~Quiz()
{
}
void Quiz::set_questions(std::vector<Question> questions)
{
this->questions = questions;
}
std::vector<Question> Quiz::get_questions()
{
return questions;
}
void Quiz::append_questions(std::vector<Question> new_questions)
{
questions.insert( questions.end(), new_questions.begin(), new_questions.end() ); return;
}
void Quiz::shuffle_questions()
{
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(questions.begin(), questions.end(), g);
std::shuffle(questions.begin(), questions.end(), g);
}
| true |