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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
38bbdce5525d41db1619f671ac083e6b4f4157ed | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/libs/filesystem/example/mbcopy.cpp | UTF-8 | 2,661 | 2.828125 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | // Boost.Filesystem mbcopy.cpp ---------------------------------------------//
// Copyright Beman Dawes 2005
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Copy the files in a directory, using mbpath to represent the new file names
// See http://../doc/path.htm#mbpath for more information
// See deprecated_test for tests of deprecated features
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem/config.hpp>
#ifdef BOOST_FILESYSTEM_NARROW_ONLY
#error This compiler or standard library does not support wide-character strings or paths
#endif
#include "mbpath.hpp"
#include <iostream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include "../src/utf8_codecvt_facet.hpp"
namespace fs = boost::filesystem;
namespace {
// we can't use boost::filesystem::copy_file() because the argument types
// differ, so provide a not-very-smart replacement.
void copy_file(const fs::wpath& from, const user::mbpath& to)
{
fs::ifstream from_file(from, std::ios_base::in | std::ios_base::binary);
if (!from_file)
{
std::cout << "input open failed\n";
return;
}
fs::ofstream to_file(to, std::ios_base::out | std::ios_base::binary);
if (!to_file)
{
std::cout << "output open failed\n";
return;
}
char c;
while (from_file.get(c))
{
to_file.put(c);
if (to_file.fail())
{
std::cout << "write error\n";
return;
}
}
if (!from_file.eof())
{
std::cout << "read error\n";
}
}
} // namespace
int main(int argc, char* argv[])
{
if (argc != 2)
{
std::cout << "Copy files in the current directory to a target directory\n"
<< "Usage: mbcopy <target-dir>\n";
return 1;
}
// For encoding, use Boost UTF-8 codecvt
std::locale global_loc = std::locale();
std::locale loc(global_loc, new fs::detail::utf8_codecvt_facet);
user::mbpath_traits::imbue(loc);
std::string target_string(argv[1]);
user::mbpath target_dir(user::mbpath_traits::to_internal(target_string));
if (!fs::is_directory(target_dir))
{
std::cout << "Error: " << argv[1] << " is not a directory\n";
return 1;
}
for (fs::wdirectory_iterator it(L".");
it != fs::wdirectory_iterator(); ++it)
{
if (fs::is_regular_file(it->status()))
{
copy_file(*it, target_dir / it->path().filename());
}
}
return 0;
}
| true |
1ea966e6508ff76be9d8c2b544b6c52ea53dee56 | C++ | penny12/my_hobby | /programming/c++/c++08/testFile1.cpp | UTF-8 | 486 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
fstream file;
// file.open("test.txt", ios::out);
// file << "aasdf" << endl;
// file.close();
file.open("test.txt", ios::in | ios::out);
string str;
// getline(file, str);
// cout << str << endl;
// file << "assdaads" << endl;
getline(file, str);
cout << str << endl;
file << "as" << endl;
file.close();
int p = 0123;
cout << p << endl;
}
| true |
8ec45acfd3831a7b3c55a83e9986d51c352d2ebc | C++ | Miao4382/Starting-Out-with-Cplusplus | /Chapter 2/Programming Challenges/13.cpp | UTF-8 | 316 | 3.5 | 4 | [] | no_license | // Programming Challenges 13: Circuit Board Price
#include <iostream>
using namespace std;
int main()
{
double cost = 14.95, profit_rate = 0.35, profit, sale_price;
profit = cost*profit_rate;
sale_price = cost + profit;
cout << "The retail price for the circuit board is: " << sale_price << endl;
return 0;
} | true |
3f820ad4ce2d5ea6568e1a00912b1f1cb1b65393 | C++ | AndreDF98/16-Jogos-em-cpp | /16Jogos/CarRacing.h | UTF-8 | 660 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Game.h"
class CarRacing : public Game
{
public:
void init() override;
void handleEvents() override;
void update() override;
void render() override;
void clean() override;
virtual bool running()
{
return isRunning;
}
static SDL_Renderer* renderer;
static SDL_Event event;
private:
bool isRunning;
bool isPaused;
SDL_Window* window;
Mix_Music* music;
Texture* car;
Texture* background;
float x = 300, y = 300;
float speed = 0, angle = 0;
float maxSpeed = 12.0f;
float acc = 0.2f;
float dec = 0.3f;
float turnSpeed = 0.08f;
int offsetX = 0, offsetY = 0;
bool Up = 0, Right = 0, Down = 0, Left = 0;
}; | true |
e6c8b07d0d7f731947462a219beca90e589f3333 | C++ | CaiCui/C-language-probloem | /hdu1720.cpp | UTF-8 | 341 | 2.59375 | 3 | [] | no_license | //hdu1720
//%X大写16进制输出 %x小写16进制输出 %p读入16进制数 %p还用于打印指针地址
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
int main()
{
int a,b;
while(scanf("%p%p",&a,&b)!=EOF)//scanf("%x%x",&a,&b)==2
{
printf("%d\n",a+b);
}
return 0;
}
| true |
62bb1403bcd5fb8458185fcbc65cd114fcf561a9 | C++ | LukacsBotond/sincronize-clocks | /src/common/EnValues.cpp | UTF-8 | 3,924 | 3.015625 | 3 | [] | no_license | #include "EnValues.h"
#include <iostream>
#include <algorithm>
using namespace std;
string EnValues::getString(string value){
string ret1=IntToString(value.size()+1)+'s';
return ret1+value;
}
string EnValues::getString(int value){
string ret2 = to_string(value);
string ret1=IntToString(ret2.size()+1)+'i';
return ret1+ret2;
}
string EnValues::IntToString(int value)
{
string ret="";
unsigned char ures;
for (int i = 0; i <= 1; i++)
{
ures = value % 256;
value /= 256;
ret+=ures;
}
reverse(ret.begin(),ret.end());
return ret;
}
/*
string MyInt::getString(any value){
int ertek = any_cast<int>(value);
string ret2= to_string(ertek);
string ret1=IntToString(ret2.size()+1)+'i';
return ret1+ret2;
}
string MyFloat::getString(any value){
float ertek = any_cast<float>(value);
string ret2= to_string(ertek);
string ret1=IntToString(ret2.size()+1)+'f';
return ret1+ret2;
}
string MyDouble::getString(any value){
double ertek = any_cast<double>(value);
string ret2= to_string(ertek);
string ret1=IntToString(ret2.size()+1)+'d';
return ret1+ret2;
}
string MyChar::getString(any value){
char ertek = any_cast<char>(value);
string ret1=IntToString(2)+'c'+ertek;
return ret1;
}
string MyString::getString(any value){
string ret2 = any_cast<const char*>(value);
string ret1=IntToString(ret2.size()+1)+'s';
return ret1+ret2;
}
string MyBool::getString(any value){
bool ertek = any_cast<bool>(value);
string ret2= to_string(ertek);
string ret1=IntToString(ret2.size()+1)+'b';
return ret1+ret2;
}
string MyIntP::getString(any value){
MyIntpS ertek = any_cast<MyIntpS>(value);
string ret2 = "I";//tipus
ret2 += IntToString(ertek.size);//hany elem van osszesen
for(int i=0;i<ertek.size;i++){
string tmp = to_string(ertek.ertek[i]);
ret2+=(IntToString(tmp.size()) + tmp);
}
string ret1 = IntToString(ret2.size());
return ret1+ret2;
}
string MyFloatP::getString(any value){
MyFloatpS ertek = any_cast<MyFloatpS>(value);
string ret2 = "F";//tipus
ret2 += IntToString(ertek.size);//hany elem van osszesen
for(int i=0;i<ertek.size;i++){
string tmp = to_string(ertek.ertek[i]);
ret2+=(IntToString(tmp.size()) + tmp);
}
string ret1 = IntToString(ret2.size());
return ret1+ret2;
}
string MyDoubleP::getString(any value){
MyDoublepS ertek = any_cast<MyDoublepS>(value);
string ret2 = "D";//tipus
ret2 += IntToString(ertek.size);//hany elem van osszesen
for(int i=0;i<ertek.size;i++){
string tmp = to_string(ertek.ertek[i]);
ret2+=(IntToString(tmp.size()) + tmp);
}
string ret1 = IntToString(ret2.size());
return ret1+ret2;
}
string MyCharP::getString(any value){
MyCharpS ertek = any_cast<MyCharpS>(value);
string ret2 = "C";//tipus
ret2 += IntToString(ertek.size);//hany elem van osszesen
for(int i=0;i<ertek.size;i++){
char tmp = ertek.ertek[i];
ret2+=(IntToString(1) + tmp);
}
string ret1 = IntToString(ret2.size());
return ret1+ret2;
}
string MyStringP::getString(any value){
MyStringpS ertek = any_cast<MyStringpS>(value);
string ret2 = "S";//tipus
ret2 += IntToString(ertek.size);//hany elem van osszesen
for(int i=0;i<ertek.size;i++){
string tmp = ertek.ertek[i];
ret2+=(IntToString(tmp.size()) + tmp);
}
string ret1 = IntToString(ret2.size());
return ret1+ret2;
}
string MyBoolP::getString(any value){
MyBoolpS ertek = any_cast<MyBoolpS>(value);
string ret2 = "I";//tipus
ret2 += IntToString(ertek.size);//hany elem van osszesen
for(int i=0;i<ertek.size;i++){
string tmp = to_string(ertek.ertek[i]);
ret2+=(IntToString(tmp.size()) + tmp);
}
string ret1 = IntToString(ret2.size());
return ret1+ret2;
}
*/
| true |
a3989686b5c2f742504a94569add6517b84b374a | C++ | krstoilo/SoftUni-Fundamentals | /CPP-Fundamentals/Associative-containers/largest3.cpp | UTF-8 | 613 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string inputLine;
getline(cin, inputLine);
set<double> setOfNum;
double num;
istringstream ssLine(inputLine);
while (ssLine >> num) {
setOfNum.insert(num);
}
if (setOfNum.size() < 3) {
for (auto n:setOfNum){
cout << n << " ";
}
}
else {
int count = 3;
while (count > 0) {
for (auto m : setOfNum) {
cout << m << " ";
}
count--;
}
}
return 0;
}
| true |
73cac4d497c1185750427e7284407d0de5b39ad3 | C++ | Eduardopinatec/EstructuraDeDatosTec | /ExamenParcial2/AlgoritmosDeBusqueda.cpp | UTF-8 | 1,203 | 3.484375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int busquedaSecuencial(int *a, int buscado, int size){
for(int i=0; i<size; i++){
if(a[i]==buscado){
return i;
}
}
return -1;
}
int busquedaOrdenada1(int *a, int buscado, int size){
if (buscado>a[size-1]){
return -1;
}
for(int i=0; i<size; i++){
if(a[i]>buscado){
return -1;
}
if(a[i]==buscado){
return i;
}
}
return -1;
}
int busquedaAux(int *a, int inicio, int fin, int buscado){
for(int i=inicio; i<=fin; i++){
if(a[i]==buscado){
return i;
}
}
return -1;
}
int busquedaOrdenada2(int *a, int size, int buscado, int paso){
int i=0;
for(i=0; i<size; i+=paso){
int finBloque=i+paso-1;
if(size-1<finBloque){
finBloque=size-1;
}
if(a[finBloque]>=buscado){
return busquedaAux(a, i, finBloque,buscado);
}
}
return -1;
}
int busquedaBinaria(int *a, int inicio, int fin, int buscado){
if(fin<inicio){
return -1;
}
int medio=(fin+inicio)/2;
if(buscado==a[medio]){
return medio;
}else if(buscado<a[medio]){
return busquedaBinaria(a, inicio, medio-1, buscado);
}else{
return busquedaBinaria(a, medio+1, fin, buscado);
}
} | true |
a9d9e8a208d0cd25083a6fecc0b6761231d531b3 | C++ | Anguei/OI-Codes | /LuoguCodes/CF47A.cpp | UTF-8 | 249 | 3.15625 | 3 | [
"MIT"
] | permissive | //【CF47A】Triangular numbers - 洛谷 - Wa
#include <iostream>
int main() {
int n;
std::cin >> n;
for (int i = 1; i <= n; ++i)
if (i * i + i == 2 * n) {
std::cout << "YES" << std::endl;
return 0;
}
std::cout << "NO" << std::endl;
} | true |
0ceceae48dfbe43084e5d52137d29c2274401a73 | C++ | NickinAction/Durak | /toast.cpp | UTF-8 | 1,335 | 2.578125 | 3 | [] | no_license | #include "toast.h"
#include <ctime>
#include <cstdlib>
#include <vector>
#include <QMessageBox>
#include <QLabel>
#include <QDebug>
#include <QString>
#include <QShortcut>
#include <QThread>
#include <thread>
#include <QKeySequence>
#include <QToolTip>
#include <unistd.h>
#include <stdio.h>
#include <QHBoxLayout>
Toast::Toast(QWidget *parent, QString init_message, int init_duration, int x, int y, int width, int height) : QWidget(parent)
{
message = new QLabel();
message->setText(init_message);
duration = init_duration;
message->setWordWrap(true);
message->setTextFormat(Qt::TextFormat(Qt::RichText));
message->setStyleSheet("QLabel { background-color : white ; color: green ; font : 16pt; border : 2px solid green; }");
message->setAlignment(Qt::AlignCenter);
this->setGeometry(x, y, width, height);
QHBoxLayout* layout = new QHBoxLayout();
layout->addWidget(message);
this->setLayout(layout);
this->setWindowFlags(Qt::FramelessWindowHint);
toastThread = new ToastThread(duration);
connect(this->toastThread, SIGNAL(finished()), this, SLOT(closeAll()));
toastThread->start();
}
void Toast::closeAll() {
toastThread->terminate();
this->close();
}
ToastThread::ToastThread(int sec)
{
seconds = sec;
}
void ToastThread::run() {
this->sleep(seconds);
}
| true |
ed0b4825f83777a292abd489fb5cef8f9b3212e8 | C++ | CIA66/Competitive-Programming | /UVA/534/19984300_AC_560ms_0kB.cpp | UTF-8 | 1,654 | 2.96875 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#define MAXN 100000
int Parent[MAXN + 10];
void makeSet(int n){
for(int i=0; i<=n; i++){
Parent[i] = i;
}
}
int findParent(int x){
if(Parent[x] == x) return x;
return Parent[x] = findParent(Parent[x]);
}
void merge(int a, int b){
Parent[findParent(a)] = findParent(b);
}
int isSameSet(int a, int b){
return findParent(a) == findParent(b);
}
struct edge{
int a, b;
double cost;
};
struct edge arr[100000];
struct Batu{
int x, y;
}batu[1006];
int main(){
int N = 0;
int tc = 1;
while(1){
scanf("%d", &N);
if(N == 0) break;
makeSet(N);
int x = 0, y = 0;
for(int a=0; a<N; a++){
scanf("%d %d", &x, &y);
batu[a].x = x;
batu[a].y = y;
}
int idx = 0;
for(int i=0; i<N; i++){
for(int k=i+1; k<N; k++){
arr[idx].a = i;
arr[idx].b = k;
double tempCost = sqrt( pow((double)batu[k].x - (double)batu[i].x, 2) + pow((double)batu[k].y - (double)batu[i].y, 2) );
arr[idx].cost = tempCost;
idx++;
}
}
for(int i=idx-1; i>0; i--){
for(int k=0; k<i; k++){
if(arr[k].cost > arr[k+1].cost){
struct edge temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
// for(int i=0; i<idx; i++){
// printf(" >. %d - %d : %lf\n", arr[i].a, arr[i].b, arr[i].cost);
// }
printf("Scenario #%d\n", tc++);
for(int i=0; i<idx; i++){
if(isSameSet(arr[i].a, arr[i].b)){
continue;
}
merge(arr[i].a, arr[i].b);
if(isSameSet(0, 1)){
printf("Frog Distance = %.3lf\n", arr[i].cost);
break;
}
// printf(" Edge MST : %d %d --> %.3lf\n", arr[i].a, arr[i].b, arr[i].cost);
}
puts("");
}
return 0;
} | true |
7539b81d2c68569138716ce20c4b6afdc1d593b1 | C++ | shenhuashan/ImuDAQ-ImuDataProcesser | /ImuDataProcesser_ChangeSeries/imudata.cpp | UTF-8 | 6,919 | 2.734375 | 3 | [] | no_license | #include "imudata.h"
ImuData::ImuData()
{
}
bool ImuData::AppendTimeVector(int time){
this->time.push_back(time);
return true;
}
bool ImuData::AppendLegSignal(LegType legtype,LegPositionType legpositiontype,SignalType signaltype,double signal)
{
switch (legtype) {
case RT:
switch(legpositiontype){
case Foot:
switch (signaltype) {
case AccX:
this->signal.RightLegSignal.FootSignal.AccX.push_back(signal);
break;
case AccY:
this->signal.RightLegSignal.FootSignal.AccY.push_back(signal);
break;
case AccZ:
this->signal.RightLegSignal.FootSignal.AccZ.push_back(signal);
break;
case CoursRate:
this->signal.RightLegSignal.FootSignal.CourseRate.push_back(signal);
break;
case Roll:
this->signal.RightLegSignal.FootSignal.Roll.push_back(signal);
break;
case Pitch:
this->signal.RightLegSignal.FootSignal.Pitch.push_back(signal);
break;
}
break;
case Thigh:
switch (signaltype) {
case AccX:
this->signal.RightLegSignal.ThighSignal.AccX.push_back(signal);
break;
case AccY:
this->signal.RightLegSignal.ThighSignal.AccY.push_back(signal);
break;
case AccZ:
this->signal.RightLegSignal.ThighSignal.AccZ.push_back(signal);
break;
case CoursRate:
this->signal.RightLegSignal.ThighSignal.CourseRate.push_back(signal);
break;
case Roll:
this->signal.RightLegSignal.ThighSignal.Roll.push_back(signal);
break;
case Pitch:
this->signal.RightLegSignal.ThighSignal.Pitch.push_back(signal);
break;
}
break;
}
break;
case LT:
switch(legpositiontype){
case Foot:
switch (signaltype) {
case AccX:
this->signal.LeftLegSignal.FootSignal.AccX.push_back(signal);
break;
case AccY:
this->signal.LeftLegSignal.FootSignal.AccY.push_back(signal);
break;
case AccZ:
this->signal.LeftLegSignal.FootSignal.AccZ.push_back(signal);
break;
case CoursRate:
this->signal.LeftLegSignal.FootSignal.CourseRate.push_back(signal);
break;
case Roll:
this->signal.LeftLegSignal.FootSignal.Roll.push_back(signal);
break;
case Pitch:
this->signal.LeftLegSignal.FootSignal.Pitch.push_back(signal);
break;
}
break;
case Thigh:
switch (signaltype) {
case AccX:
this->signal.LeftLegSignal.ThighSignal.AccX.push_back(signal);
break;
case AccY:
this->signal.LeftLegSignal.ThighSignal.AccY.push_back(signal);
break;
case AccZ:
this->signal.LeftLegSignal.ThighSignal.AccZ.push_back(signal);
break;
case CoursRate:
this->signal.LeftLegSignal.ThighSignal.CourseRate.push_back(signal);
break;
case Roll:
this->signal.LeftLegSignal.ThighSignal.Roll.push_back(signal);
break;
case Pitch:
this->signal.LeftLegSignal.ThighSignal.Pitch.push_back(signal);
break;
}
break;
}
break;
}
return true;
}
bool ImuData::AppendMarkerVector(int marknum)
{
this->marker.push_back(marknum);
return true;
}
TimeVector ImuData::GetTimeVector()
{
return this->time;
}
LegSignal ImuData::GetLegSignal()
{
return this->signal;
}
MarkerVector ImuData::GetMarkerVector()
{
return this->marker;
}
bool ImuData::ImuDataShower()
{
unsigned int length = time.size();
for(unsigned int i=0;i<length;i++)
{
std::cout<<" Time : "<<time[i]<<std::endl;
std::cout<<" Right"<<"Foot AccX : "<<signal.RightLegSignal.FootSignal.AccX[i]<<std::endl;
std::cout<<" Right"<<"Foot AccY : "<<signal.RightLegSignal.FootSignal.AccY[i]<<std::endl;
std::cout<<" Right"<<"Foot AccZ : "<<signal.RightLegSignal.FootSignal.AccZ[i]<<std::endl;
std::cout<<" Right"<<"Foot CourseRate : "<<signal.RightLegSignal.FootSignal.CourseRate[i]<<std::endl;
std::cout<<" Right"<<"Foot Roll : "<<signal.RightLegSignal.FootSignal.Roll[i]<<std::endl;
std::cout<<" Right"<<"Foot Pitch : "<<signal.RightLegSignal.FootSignal.Pitch[i]<<std::endl;
std::cout<<" Right"<<"Thigh AccX : "<<signal.RightLegSignal.ThighSignal.AccX[i]<<std::endl;
std::cout<<" Right"<<"Thigh AccY : "<<signal.RightLegSignal.ThighSignal.AccY[i]<<std::endl;
std::cout<<" Right"<<"Thigh AccZ : "<<signal.RightLegSignal.ThighSignal.AccZ[i]<<std::endl;
std::cout<<" Right"<<"Thigh CourseRate : "<<signal.RightLegSignal.ThighSignal.CourseRate[i]<<std::endl;
std::cout<<" Right"<<"Thigh Roll : "<<signal.RightLegSignal.ThighSignal.Roll[i]<<std::endl;
std::cout<<" Right"<<"Thigh Pitch : "<<signal.RightLegSignal.ThighSignal.Pitch[i]<<std::endl;
std::cout<<" Left"<<"Foot AccX : "<<signal.LeftLegSignal.FootSignal.AccX[i]<<std::endl;
std::cout<<" Left"<<"Foot AccY : "<<signal.LeftLegSignal.FootSignal.AccY[i]<<std::endl;
std::cout<<" Left"<<"Foot AccZ : "<<signal.LeftLegSignal.FootSignal.AccZ[i]<<std::endl;
std::cout<<" Left"<<"Foot CourseRate : "<<signal.LeftLegSignal.FootSignal.CourseRate[i]<<std::endl;
std::cout<<" Left"<<"Foot Roll : "<<signal.LeftLegSignal.FootSignal.Roll[i]<<std::endl;
std::cout<<" Left"<<"Foot Pitch : "<<signal.LeftLegSignal.FootSignal.Pitch[i]<<std::endl;
std::cout<<" Left"<<"Thigh AccX : "<<signal.LeftLegSignal.ThighSignal.AccX[i]<<std::endl;
std::cout<<" Left"<<"Thigh AccY : "<<signal.LeftLegSignal.ThighSignal.AccY[i]<<std::endl;
std::cout<<" Left"<<"Thigh AccZ : "<<signal.LeftLegSignal.ThighSignal.AccZ[i]<<std::endl;
std::cout<<" Left"<<"Thigh CourseRate : "<<signal.LeftLegSignal.ThighSignal.CourseRate[i]<<std::endl;
std::cout<<" Left"<<"Thigh Roll : "<<signal.LeftLegSignal.ThighSignal.Roll[i]<<std::endl;
std::cout<<" Left"<<"Thigh Pitch : "<<signal.LeftLegSignal.ThighSignal.Pitch[i]<<std::endl;
std::cout<<" Marker : "<<marker[i]<<std::endl;
}
return true;
}
| true |
df58a8a1799caf40c5b4ebb8cad275c17a930a84 | C++ | switchpiggy/Competitive_Programming | /CodeForces/1200 - 1400/dualPalindromes.cpp | UTF-8 | 940 | 2.875 | 3 | [] | no_license | /*
ID: alanxia1
PROG: dualpal
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
inline char to_char(int c){
if(c >= 10)
return c - 10 + 'A';
return c + '0';
}
string tobase(int num, int base){
string ret;
int div = base;
while(div < num)
div *= base;
for(div /= base;;){
ret += to_char(num / div);
// get remainder
num = num % div;
// next
if(div < 2) break;
div /= base;
}
return ret;
}
string reverse_str(string str){
reverse(str.begin(), str.end());
return str;
}
int main() {
ofstream fout ("dualpal.out");
ifstream fin ("dualpal.in");
int N, S;
fin >> N >> S;
while(N){
if(++S > 100000)
break;
int num = 0;
for(int j = 2; j <= 10; ++j){
// fail: I put S * S instead of S
string check = tobase(S, j);
if(check == reverse_str(check) && ++num >= 2){
--N;
fout << S << endl;
break;
}
}
}
return 0;
} | true |
2c2acf2c01123bbc709b15c98cbe7296d96006bf | C++ | akash-mankar/RayTracer | /ray/src/KDTreeNode.h | UTF-8 | 906 | 2.609375 | 3 | [] | no_license | #ifndef _KDTREE_NODE_H_
#define _KDTREE_NODE_H_
#include "vecmath/vec.h"
#include "scene/scene.h"
#include "scene/ray.h"
#include "scene/bbox.h"
#include <vector>
#include <iostream>
using namespace std;
class KDTreeNode {
public:
bool isLeaf();
vector <Geometry*> getChildren();
void setMyself(BoundingBox* myself) {
this->myself = myself;
}
const BoundingBox* getMyself() {
return myself;
}
// bool intersects(const Vec3d& point) const {
// return myself->intersects(point);
// }
bool intersect(const ray& r, double& tMin, double& tMax) const {
return myself->intersect(r,tMin,tMax);
}
const BoundingBox* myself;
private:
vector <Geometry*> children;
vector <BoundingBox*> boxes;
};
class KDTree {
public:
KDTreeNode* getRoot();
void setScene(Scene* scene);
private:
vector <Geometry*> totalObjects;
Scene* scene;
};
#endif
| true |
93909b8930d19e9696bd87df4a5040afa506971a | C++ | b-chae/AlgorithmStudy | /baekjoon/DP/2624.cpp | UTF-8 | 620 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int A[100][2];
long long D[100][10001];
int main()
{
int T, N;
cin >> T >> N;
for(int i=0;i<N;i++){
cin >> A[i][0] >> A[i][1];
}
for(int k=0; k<=A[0][1]; k++){
if(A[0][0]*k > T) break;
D[0][A[0][0]*k] = 1;
}
for(int i=1;i<N;i++){
for(long long j=0;j<=T;j++){
if(D[i-1][j] == 0) continue;
for(int k=0; k<=A[i][1]; k++){
if(j+A[i][0]*k > T) break;
D[i][j+A[i][0]*k] += D[i-1][j];
}
}
}
cout << D[N-1][T] << "\n";
return 0;
}
| true |
ddaefc32ce2b3ef5461fd3e206bb1865cc4fa833 | C++ | xantnef/gochan | /gochanQ.h | UTF-8 | 2,521 | 3.171875 | 3 | [] | no_license | #include <queue>
#include <condition_variable>
#include <mutex>
////////////////////////////////////////////////////////////////////////////////////////////////////
template <class T>
class gochanQ : public gochan<T> {
std::queue<T> elems;
std::queue<std::condition_variable*> writers;
std::queue<std::condition_variable*> readers;
std::mutex _mtx;
std::unique_lock<std::mutex> lk;
void wait_in_queue(std::queue<std::condition_variable*>&);
void wake_queue(std::queue<std::condition_variable*>&);
public:
gochanQ(unsigned size) : gochan<T>(size), lk(_mtx, std::defer_lock) {}
~gochanQ();
void send(const T& elem);
T recv(void);
void close(void);
};
template <class T>
gochanQ<T>::~gochanQ(void)
{
if (!this->closed)
close();
}
template <class T>
void gochanQ<T>::wait_in_queue(std::queue<std::condition_variable*>& q)
{
std::condition_variable cond;
q.push(&cond);
cond.wait(lk);
}
template <class T>
void gochanQ<T>::wake_queue(std::queue<std::condition_variable*>& q)
{
q.front()->notify_one();
q.pop();
}
template <class T>
void gochanQ<T>::send(const T& elem)
{
lk.lock();
if (this->closed)
throw std::logic_error("send on closed channel");
elems.push(elem);
if (!readers.empty())
wake_queue(readers);
if (!writers.empty() || elems.size() > this->size)
wait_in_queue(writers);
if (this->closed)
throw std::logic_error("send on closed channel");
lk.unlock();
}
template <class T>
T gochanQ<T>::recv(void)
{
lk.lock();
if (!readers.empty() || (elems.empty() && !this->closed))
wait_in_queue(readers);
if (elems.empty()) {
if (this->closed) {
T elem;
lk.unlock();
return elem;
}
throw std::logic_error("unexpected empty channel");
}
T elem = elems.front();
elems.pop();
if (!writers.empty())
wake_queue(writers);
lk.unlock();
return elem;
}
template <class T>
void gochanQ<T>::close(void)
{
lk.lock();
if (this->closed)
throw std::logic_error("close on closed channel");
// Do we have to wait for readers/writers woken for execution?
while (!elems.empty() && !readers.empty()) {
// just have to yield
lk.unlock();
lk.lock();
}
this->closed = true;
while (!readers.empty())
wake_queue(readers);
while (!writers.empty())
wake_queue(writers);
lk.unlock();
}
| true |
4b7704d7f60eb158500d97eb27f0563e27cefc92 | C++ | reantoansorih/tugas2metnum | /Untitled2.cpp | UTF-8 | 2,179 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <conio.h>
#include <math.h>
#define nMax 100
int main(){
//kamus
int x[nMax+1];
int y[nMax+1];
int x2[nMax+1];
int y2[nMax+1];
int xy[nMax+1];
int n,i,elemen;
int sigma_x=0,sigma_y=0,sigma_x2=0,sigma_y2=0,sigma_xy=0;
float selisih[nMax+1];
float m=0,c=0,error,sigma_prediksi=0,sigma_selisih=0;
float prediksi[nMax+1];
//algoritma
Home:
printf("Perhitungan perkiraan lama waktu \n\n");
printf("Masukan jumlah n : ");scanf("%d", &n);
//n kurang dari 2
if(n<2){
printf("eror");
getch();
goto Home;
//jika lebih dari 100
}else if (n>100){
printf("Teralu banyak");
getch();
goto Home;
}
else{
for(i=1;i<=n;i++){
printf("Jarak ke tempat pelanggan ke-%d = ",i);scanf("%d", &elemen);
x[i]=elemen;
sigma_x=sigma_x+x[i];
}
for(i=1;i<=n;i++){
x2[i]=x[i]*x[i];
sigma_x2=sigma_x2+x2[i];
}
printf("\n");
for(i=1;i<=n;i++){
printf("Perkiraan waktu yang ditempuh ke-%d = ",i);scanf("%d", &elemen);
y[i]=elemen;
sigma_y=sigma_y+y[i];
}
for(i=1;i<=n;i++){
y2[i]=y[i]*y[i];
sigma_y2=sigma_y2+y2[i];
xy[i]=x[i]*y[i];
sigma_xy=sigma_xy+xy[i];
}
m = ((n*sigma_xy)-(sigma_x*sigma_y))/((n*sigma_x2)-pow(sigma_x,2));
c = ((sigma_y*sigma_x2)-(sigma_x*sigma_xy))/((n*sigma_x2)-pow(sigma_x,2));
for(i=1;i<=n;i++){
prediksi[i]=(m*x[i])+c;
}
printf("\nJarak ke tempat pelanggan \n");
for(i=1;i<=n;i++){
printf("|%dKM| ",x[i]);
}
printf("\n\nPerkiraan waktu yang ditempuh\n");
for(i=1;i<=n;i++){
printf("|%djam| ",y[i]);
}
printf("\n\nPrediksi Waktu\n");
for(i=1;i<=n;i++){
printf("|%.2f|",prediksi[i]);
}
printf("\n\nSelisih waktu perkiraan prediksi\n");
for(i=1;i<=n;i++){
selisih[i]=y[i]-prediksi[i];
if(selisih[i]<0){
selisih[i]=prediksi[i]-y[i];
}
printf("|%.2f|",selisih[i]);
sigma_selisih=sigma_selisih+selisih[i];
}
printf("\n\nError\n");
printf("|%.2f|",sigma_selisih/n);
}
getch();
return 0;
}
| true |
fc9838bac87a1601fa1db0136c3756253c462ff0 | C++ | FANGYuan827/Leetcode | /leetcode/demo11_maximum-subarray.cpp | UTF-8 | 1,196 | 3.671875 | 4 | [] | no_license | /*
2018年4月24日20:19:44
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array[−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray[4,−1,2,1]has the largest sum =6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
*/
#include "iostream"
using namespace std;
/*
解题思路:
直接从头开始累加并统计此时是否为最大值
累加直到和为负,舍弃前面这段(因为所加和不能为后面的累加值带来正的影响) sum清零 继续累加
*/
class Solution_demo11 {
public:
int maxSubArray(int A[], int n) {
if(n==0)
return 0;
int max = A[0],sum = 0;
for(int i=0;i<n;++i)
{
sum+=A[i];
if(max<sum)
max = sum;
if(sum<0)
sum = 0;
}
return max;
}
};
void main_demo11()
{
Solution_demo11 s1;
int input[9] = {-2,-1,-3,-4,-1,-2,-1,-5,-4};
int maxSubArray = 0;
maxSubArray = s1.maxSubArray(input,9);
cout<<"最大连续子数组的和为:"<<maxSubArray<<endl;
system("pause");
} | true |
671408ccf142d6850538214b5ef6ffaff5d9ec59 | C++ | AntonFender/repo | /Scrypts/DAVNEYShIE_SKRIPTY/Vnedrennye/easyegais2/Iskhodnik Eshchenko/src/extractrests.cpp | UTF-8 | 2,528 | 2.5625 | 3 | [] | no_license | #include <string>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
struct rest
{
string quantity;
string informbregid;
string alccode;
string productvcode;
};
vector<string> lines;
vector<rest> rests;
vector<string> beercodes;
bool isBeer(string _code)
{
for (int i = 0; i < beercodes.size(); ++i)
{
if (beercodes[i] == _code)
return(true);
}
return(false);
}
int main(int argc, char* argv[])
{
if (argc == 1) return(0);
for (int i = 1; i < argc; ++i)
{
beercodes.push_back(argv[i]);
}
string filename = "./cache/ReplyRests.xml";
ifstream _in;
_in.open(filename);
if (!_in.is_open())
{
return(0);
}
string text = "";
while (!_in.eof())
{
string buf = "";
_in >> buf;
text += buf;
}
bool in_tag = false;
string buf = "";
for (int i = 0; i < text.length(); ++i)
{
if ((text[i] == '<') && !in_tag)
{
if (!buf.empty())
{
lines.push_back(buf);
buf.clear();
}
in_tag = true;
buf += text[i];
continue;
}
if ((text[i] == '>') && in_tag)
{
in_tag = false;
buf += text[i];
lines.push_back(buf);
buf.clear();
continue;
}
buf += text[i];
}
/*ofstream _out;
_out.open("11111.xml");
for (int i = 0; i < lines.size(); ++i)
{
_out << lines[i] << endl;
}*/
for (int i = 0; i < lines.size(); ++i)
{
if (lines[i].find("<rst:StockPosition") != string::npos)
{
rest REST;
REST.quantity = lines[i + 2];
REST.informbregid = lines[i + 8];
REST.alccode = lines[i + 15];
REST.productvcode = lines[i + 24];
if (REST.productvcode.find("ClientRegId") != string::npos) REST.productvcode = lines[i + 21];
rests.push_back(REST);
}
}
vector<rest> rests_unmarked;
for (int i = 0; i < rests.size(); ++i)
{
//if ((rests[i].productvcode == "500")||(rests[i].productvcode == "520")||(rests[i].productvcode == "261")||(rests[i].productvcode == "262"))
if (isBeer(rests[i].productvcode))
{
rests_unmarked.push_back(rests[i]);
}
}
ofstream _out;
_out.open("./cache/rests.list");
for (int i = 0; i < rests_unmarked.size(); ++i)
{
_out << rests_unmarked[i].quantity << "\t" << rests_unmarked[i].alccode << "\t" << rests_unmarked[i].informbregid << endl;
}
_out.flush();
_out.close();
cout << rests_unmarked.size();
//cout << text;
//char ch;
//cin >> ch;
_in.close();
return(0);
} | true |
e0616b289a7cf1bfca14285376a792fc9a050a3f | C++ | mikekenndy/ESE_224 | /Project/game_board.cpp | UTF-8 | 2,080 | 3.6875 | 4 | [] | no_license | // Mike Kennedy
// ESE 224 - Hangman project
// Game Board: Class responsible for providing user with game interface
#include "game_board.h"
#include "basicFunctions.h"
using namespace std;
// Default constructor
game_board::game_board()
{
this->phrase = "";
}
game_board::game_board(string phrase)
{
this->phrase = phrase;
}
string game_board::hangedMan(string guesses)
{
// Empty board looks as follows:
/* ___ */
/* | | */
/* | */
/* | */
/* | */
/* | */
/* ___ */
string display = " ___ \n";
display += " | |\n";
// First wrong guess
if (numWrong > 0)
display += " | O\n";
else
display += " | \n";
// Second, third and fourth wrong guess
if (numWrong > 3)
display += " | /|\\\n";
else if (numWrong > 2)
display += " | /| \n";
else if (numWrong > 1)
display += " | |\n";
else
display += " |\n";
// Fourth and fifth wrong guesses
if (numWrong > 5)
display += " | / \\\n";
else if (numWrong > 4)
display += " | /\n";
else
display += " |\n";
display += " | \n";
display += "___\n";
return display;
}
string game_board::formattedPhrase(string guesses)
{
string ret = "";
for (int i = 0; i < phrase.length(); i++)
{
// Add spaces if required
if (phrase[i] == '\r' || phrase[i] == ' ')
ret += " ";
// Correct guesses are displayed
else if (guesses.find(phrase[i]) != string::npos)
ret += phrase[i];
// All other characters are displayed as '_'
else
ret += "_";
}
return ret;
}
string game_board::wrongGuesses(string guesses)
{
string wrong = "";
for (int i = 0; i < guesses.length(); i++)
if (phrase.find(guesses[i]) == string::npos)
wrong += guesses[i];
// Set value for number of incorrect guesses
numWrong = wrong.length();
return wrong;
}
void game_board::setPhrase(string phrase)
{
this->phrase = phrase;
}
void game_board::displayBoard(string guesses)
{
string wrong = wrongGuesses(guesses);
cout << hangedMan(guesses) << endl;
cout << formattedPhrase(guesses) << endl;
printMessage("Past guesses: " + wrong, true, true);
cout << endl;
} | true |
d8c70f9e074e013a4b1a7ced2a4b515cb018ca37 | C++ | jjchromik/hilti-104-total | /hilti/variable.h | UTF-8 | 2,822 | 2.84375 | 3 | [
"BSD-2-Clause"
] | permissive |
#ifndef HILTI_VARIABLE_H
#define HILTI_VARIABLE_H
#include <ast/variable.h>
#include "common.h"
namespace hilti {
/// Base class for AST variable nodes.
class Variable : public ast::Variable<AstInfo>, public NodeWithAttributes {
AST_RTTI
public:
/// Constructor.
///
/// id: The name of the variable. Must be non-scoped.
///
/// type: The type of the variable.
///
/// Expression: An optional initialization expression, or null if none.
///
/// l: Associated location.
Variable(shared_ptr<ID> id, shared_ptr<Type> type, shared_ptr<Expression> init = nullptr,
const Location& l = Location::None)
: ast::Variable<AstInfo>(id, type, init, l), NodeWithAttributes(this)
{
}
ACCEPT_VISITOR_ROOT();
};
namespace variable {
/// AST node representing a global variable.
class Global : public hilti::Variable, public ast::variable::mixin::Global<AstInfo> {
AST_RTTI
public:
/// Constructor.
///
/// id: The name of the variable. Must be non-scoped.
///
/// type: The type of the variable.
///
/// Expression: An optional initialization expression, or null if none.
///
/// l: Associated location.
Global(shared_ptr<ID> id, shared_ptr<Type> type, shared_ptr<Expression> init = nullptr,
const Location& l = Location::None)
: hilti::Variable(id, type, init, l), ast::variable::mixin::Global<AstInfo>(this)
{
}
ACCEPT_VISITOR(hilti::Variable);
};
/// AST node representing a local variable.
class Local : public hilti::Variable, public ast::variable::mixin::Local<AstInfo> {
AST_RTTI
public:
/// Constructor.
///
/// id: The name of the variable. Must be non-scoped.
///
/// type: The type of the variable.
///
/// Expression: An optional initialization expression, or null if none.
///
/// l: Associated location.
Local(shared_ptr<ID> id, shared_ptr<Type> type, shared_ptr<Expression> init = nullptr,
const Location& l = Location::None)
: hilti::Variable(id, type, init, l), ast::variable::mixin::Local<AstInfo>(this)
{
}
/// Returns an internal name set by the ID resolver. This name will be
/// unique across the function the local is defined in (even if there are
/// other locals of the same name in other blocks.) Returns the ID itself
/// as long as nobody has set anything.
string internalName()
{
return _internal_name.size() ? _internal_name : id()->name();
}
/// Sets the internal name returned by internalName. This should be called
/// only by the ID resolver.
void setInternalName(const string& name)
{
_internal_name = name;
}
ACCEPT_VISITOR(hilti::Variable);
private:
string _internal_name = "";
};
}
}
#endif
| true |
c8be7cab4314e01146a7d53096746986b14df2cb | C++ | zrax/string_theory | /include/st_utf_conv_priv.h | UTF-8 | 23,756 | 2.578125 | 3 | [
"MIT"
] | permissive | /* Copyright (c) 2019 Michael Hansen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#ifndef _ST_UTF_CONV_PRIV_H
#define _ST_UTF_CONV_PRIV_H
namespace _ST_PRIVATE
{
constexpr unsigned int badchar_substitute = 0xFFFDu;
constexpr const char badchar_substitute_utf8[] = "\xEF\xBF\xBD";
constexpr size_t badchar_substitute_utf8_len = sizeof(badchar_substitute_utf8) - 1;
enum class conversion_error_t
{
success,
incomplete_utf8_seq,
incomplete_surrogate_pair,
invalid_utf8_seq,
out_of_range,
latin1_out_of_range,
};
inline void raise_conversion_error(conversion_error_t err)
{
switch (err) {
case conversion_error_t::success:
return;
case conversion_error_t::incomplete_utf8_seq:
throw ST::unicode_error("Incomplete UTF-8 sequence");
case conversion_error_t::incomplete_surrogate_pair:
throw ST::unicode_error("Incomplete surrogate pair");
case conversion_error_t::invalid_utf8_seq:
throw ST::unicode_error("Invalid UTF-8 sequence byte");
case conversion_error_t::out_of_range:
throw ST::unicode_error("Unicode character out of range");
case conversion_error_t::latin1_out_of_range:
throw ST::unicode_error("Latin-1 character out of range");
default:
ST_ASSERT(false, "Invalid conversion_error_t value");
}
}
# define _ST_CHECK_NEXT_SEQ_BYTE() \
do { \
++cp; \
if ((*cp & 0xC0) != 0x80) \
return conversion_error_t::invalid_utf8_seq; \
} while (false)
ST_NODISCARD
inline conversion_error_t validate_utf8(const char *buffer, size_t size)
{
const unsigned char *cp = reinterpret_cast<const unsigned char *>(buffer);
const unsigned char *ep = cp + size;
for (; cp < ep; ++cp) {
if (*cp < 0x80)
continue;
if ((*cp & 0xE0) == 0xC0) {
// Two bytes
if (cp + 2 > ep)
return conversion_error_t::incomplete_utf8_seq;
_ST_CHECK_NEXT_SEQ_BYTE();
} else if ((*cp & 0xF0) == 0xE0) {
// Three bytes
if (cp + 3 > ep)
return conversion_error_t::incomplete_utf8_seq;
_ST_CHECK_NEXT_SEQ_BYTE();
_ST_CHECK_NEXT_SEQ_BYTE();
} else if ((*cp & 0xF8) == 0xF0) {
// Four bytes
if (cp + 4 > ep)
return conversion_error_t::incomplete_utf8_seq;
_ST_CHECK_NEXT_SEQ_BYTE();
_ST_CHECK_NEXT_SEQ_BYTE();
_ST_CHECK_NEXT_SEQ_BYTE();
} else {
// Invalid sequence byte
return conversion_error_t::invalid_utf8_seq;
}
}
return conversion_error_t::success;
}
#undef _ST_CHECK_NEXT_SEQ_BYTE
inline size_t append_chars(char *&output, const char *src, size_t count)
{
if (output) {
std::char_traits<char>::copy(output, src, count);
output += count;
}
return count;
}
inline size_t cleanup_utf8(char *output, const char *buffer, size_t size)
{
size_t output_size = 0;
const unsigned char *sp = reinterpret_cast<const unsigned char *>(buffer);
const unsigned char *ep = sp + size;
while (sp < ep) {
if (*sp < 0x80) {
++output_size;
if (output)
*output++ = static_cast<char>(*sp);
sp += 1;
} else if ((*sp & 0xE0) == 0xC0) {
// Two bytes
if (sp + 2 > ep || (sp[1] & 0xC0) != 0x80) {
output_size += append_chars(output, badchar_substitute_utf8,
badchar_substitute_utf8_len);
sp += 1;
} else {
output_size += append_chars(output, reinterpret_cast<const char *>(sp), 2);
sp += 2;
}
} else if ((*sp & 0xF0) == 0xE0) {
// Three bytes
if (sp + 3 > ep || (sp[1] & 0xC0) != 0x80 || (sp[2] & 0xC0) != 0x80) {
output_size += append_chars(output, badchar_substitute_utf8,
badchar_substitute_utf8_len);
sp += 1;
} else {
output_size += append_chars(output, reinterpret_cast<const char *>(sp), 3);
sp += 3;
}
} else if ((*sp & 0xF8) == 0xF0) {
// Four bytes
if (sp + 4 > ep || (sp[1] & 0xC0) != 0x80 || (sp[2] & 0xC0) != 0x80
|| (sp[3] & 0xC0) != 0x80) {
output_size += append_chars(output, badchar_substitute_utf8,
badchar_substitute_utf8_len);
sp += 1;
} else {
output_size += append_chars(output, reinterpret_cast<const char *>(sp), 4);
sp += 4;
}
} else {
// Invalid sequence byte
output_size += append_chars(output, badchar_substitute_utf8,
badchar_substitute_utf8_len);
sp += 1;
}
}
return output_size;
}
ST_NODISCARD
inline ST::char_buffer cleanup_utf8_buffer(const ST::char_buffer &buffer)
{
size_t clean_size = cleanup_utf8(nullptr, buffer.data(), buffer.size());
ST::char_buffer cb_clean;
cb_clean.allocate(clean_size);
cleanup_utf8(cb_clean.data(), buffer.data(), buffer.size());
return cb_clean;
}
ST_NODISCARD
inline char32_t error_char(conversion_error_t value)
{
return static_cast<char32_t>(value) | 0x400000u;
}
ST_NODISCARD
inline conversion_error_t char_error(char32_t ch)
{
return (ch & 0x400000u) != 0
? static_cast<conversion_error_t>(ch & ~0x400000u)
: conversion_error_t::success;
}
ST_NODISCARD
inline char32_t extract_utf8(const unsigned char *&utf8, const unsigned char *end)
{
char32_t bigch;
if (*utf8 < 0x80) {
return *utf8++;
} else if ((*utf8 & 0xE0) == 0xC0) {
if (utf8 + 2 > end || (utf8[1] & 0xC0) != 0x80) {
utf8 += 1;
return error_char(conversion_error_t::incomplete_utf8_seq);
}
bigch = (*utf8++ & 0x1F) << 6;
bigch |= (*utf8++ & 0x3F);
return bigch;
} else if ((*utf8 & 0xF0) == 0xE0) {
if (utf8 + 3 > end || (utf8[1] & 0xC0) != 0x80 || (utf8[2] & 0xC0) != 0x80) {
utf8 += 1;
return error_char(conversion_error_t::incomplete_utf8_seq);
}
bigch = (*utf8++ & 0x0F) << 12;
bigch |= (*utf8++ & 0x3F) << 6;
bigch |= (*utf8++ & 0x3F);
return bigch;
} else if ((*utf8 & 0xF8) == 0xF0) {
if (utf8 + 4 > end || (utf8[1] & 0xC0) != 0x80 || (utf8[2] & 0xC0) != 0x80
|| (utf8[3] & 0xC0) != 0x80) {
utf8 += 1;
return error_char(conversion_error_t::incomplete_utf8_seq);
}
bigch = (*utf8++ & 0x07) << 18;
bigch |= (*utf8++ & 0x3F) << 12;
bigch |= (*utf8++ & 0x3F) << 6;
bigch |= (*utf8++ & 0x3F);
return bigch;
}
utf8 += 1;
return error_char(conversion_error_t::invalid_utf8_seq);
}
ST_NODISCARD
inline size_t utf8_measure(char32_t ch)
{
if (ch < 0x80) {
return 1;
} else if (ch < 0x800) {
return 2;
} else if (ch < 0x10000) {
return 3;
} else if (ch <= 0x10FFFF) {
return 4;
} else {
// Out-of-range code point always gets replaced
return badchar_substitute_utf8_len;
}
}
ST_NODISCARD
inline conversion_error_t write_utf8(char *&dest, char32_t ch)
{
if (ch < 0x80) {
*dest++ = static_cast<char>(ch);
} else if (ch < 0x800) {
*dest++ = 0xC0 | ((ch >> 6) & 0x1F);
*dest++ = 0x80 | ((ch ) & 0x3F);
} else if (ch < 0x10000) {
*dest++ = 0xE0 | ((ch >> 12) & 0x0F);
*dest++ = 0x80 | ((ch >> 6) & 0x3F);
*dest++ = 0x80 | ((ch ) & 0x3F);
} else if (ch <= 0x10FFFF) {
*dest++ = 0xF0 | ((ch >> 18) & 0x07);
*dest++ = 0x80 | ((ch >> 12) & 0x3F);
*dest++ = 0x80 | ((ch >> 6) & 0x3F);
*dest++ = 0x80 | ((ch ) & 0x3F);
} else {
return conversion_error_t::out_of_range;
}
return conversion_error_t::success;
}
ST_NODISCARD
inline char32_t extract_utf16(const char16_t *&utf16, const char16_t *end)
{
char32_t bigch;
if (*utf16 >= 0xD800 && *utf16 <= 0xDFFF) {
// Surrogate pair
if (utf16 + 1 >= end) {
utf16 += 1;
return error_char(conversion_error_t::incomplete_surrogate_pair);
} else if (*utf16 < 0xDC00) {
if (utf16[1] >= 0xDC00 && utf16[1] <= 0xDFFF) {
bigch = 0x10000 + ((utf16[0] & 0x3FF) << 10) + (utf16[1] & 0x3FF);
utf16 += 2;
return bigch;
}
utf16 += 1;
return error_char(conversion_error_t::incomplete_surrogate_pair);
} else {
if (utf16[1] >= 0xD800 && utf16[1] <= 0xDBFF) {
bigch = 0x10000 + (utf16[0] & 0x3FF) + ((utf16[1] & 0x3FF) << 10);
utf16 += 2;
return bigch;
}
utf16 += 1;
return error_char(conversion_error_t::incomplete_surrogate_pair);
}
}
return static_cast<char32_t>(*utf16++);
}
ST_NODISCARD
inline size_t utf16_measure(char32_t ch)
{
// Out-of-range code point always gets replaced
if (ch < 0x10000 || ch > 0x10FFFF)
return 1;
// Surrogate pair
return 2;
}
ST_NODISCARD
inline conversion_error_t write_utf16(char16_t *&dest, char32_t ch)
{
if (ch < 0x10000) {
*dest++ = static_cast<char16_t>(ch);
} else if (ch <= 0x10FFFF) {
ch -= 0x10000;
*dest++ = 0xD800 | ((ch >> 10) & 0x3FF);
*dest++ = 0xDC00 | ((ch ) & 0x3FF);
} else {
return conversion_error_t::out_of_range;
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t utf8_measure_from_utf16(const char16_t *utf16, size_t size)
{
if (!utf16)
return 0;
size_t u8len = 0;
const char16_t *sp = utf16;
const char16_t *ep = sp + size;
while (sp < ep)
u8len += utf8_measure(extract_utf16(sp, ep));
return u8len;
}
ST_NODISCARD
inline conversion_error_t utf8_convert_from_utf16(char *dest,
const char16_t *utf16, size_t size,
ST::utf_validation_t validation)
{
const char16_t *sp = utf16;
const char16_t *ep = sp + size;
while (sp < ep) {
char32_t bigch = extract_utf16(sp, ep);
conversion_error_t error = char_error(bigch);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
std::char_traits<char>::copy(dest, badchar_substitute_utf8,
badchar_substitute_utf8_len);
dest += badchar_substitute_utf8_len;
} else {
error = write_utf8(dest, bigch);
ST_ASSERT(error == conversion_error_t::success, "Input character out of range");
}
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t utf8_measure_from_utf32(const char32_t *utf32, size_t size)
{
if (!utf32)
return 0;
size_t u8len = 0;
const char32_t *sp = utf32;
const char32_t *ep = sp + size;
while (sp < ep)
u8len += utf8_measure(*sp++);
return u8len;
}
ST_NODISCARD
inline conversion_error_t utf8_convert_from_utf32(char *dest,
const char32_t *utf32, size_t size,
ST::utf_validation_t validation)
{
const char32_t *sp = utf32;
const char32_t *ep = sp + size;
while (sp < ep) {
const conversion_error_t error = write_utf8(dest, *sp++);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
std::char_traits<char>::copy(dest, badchar_substitute_utf8,
badchar_substitute_utf8_len);
dest += badchar_substitute_utf8_len;
}
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t utf8_measure_from_latin_1(const char *astr, size_t size)
{
if (!astr)
return 0;
size_t u8len = 0;
const char *sp = astr;
const char *ep = sp + size;
for (; sp < ep; ++sp) {
if (*sp & 0x80)
u8len += 2;
else
u8len += 1;
}
return u8len;
}
inline void utf8_convert_from_latin_1(char *dest, const char *astr, size_t size)
{
const char *sp = astr;
const char *ep = sp + size;
for (; sp < ep; ++sp) {
if (*sp & 0x80) {
*dest++ = 0xC0 | ((static_cast<unsigned char>(*sp) >> 6) & 0x1F);
*dest++ = 0x80 | ((static_cast<unsigned char>(*sp) ) & 0x3F);
} else {
*dest++ = *sp;
}
}
}
ST_NODISCARD
inline size_t utf16_measure_from_utf8(const char *utf8, size_t size)
{
if (!utf8)
return 0;
size_t u16len = 0;
const unsigned char *sp = reinterpret_cast<const unsigned char *>(utf8);
const unsigned char *ep = sp + size;
while (sp < ep)
u16len += utf16_measure(extract_utf8(sp, ep));
return u16len;
}
ST_NODISCARD
inline conversion_error_t utf16_convert_from_utf8(char16_t *dest,
const char *utf8, size_t size,
ST::utf_validation_t validation)
{
const unsigned char *sp = reinterpret_cast<const unsigned char *>(utf8);
const unsigned char *ep = sp + size;
while (sp < ep) {
char32_t bigch = extract_utf8(sp, ep);
conversion_error_t error = char_error(bigch);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
*dest++ = badchar_substitute;
} else {
error = write_utf16(dest, bigch);
ST_ASSERT(error == conversion_error_t::success, "Input character out of range");
}
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t utf16_measure_from_utf32(const char32_t *utf32, size_t size)
{
if (!utf32)
return 0;
size_t u16len = 0;
const char32_t *sp = utf32;
const char32_t *ep = sp + size;
while (sp < ep)
u16len += utf16_measure(*sp++);
return u16len;
}
ST_NODISCARD
inline conversion_error_t utf16_convert_from_utf32(char16_t *dest,
const char32_t *utf32, size_t size,
ST::utf_validation_t validation)
{
const char32_t *sp = utf32;
const char32_t *ep = sp + size;
while (sp < ep) {
const conversion_error_t error = write_utf16(dest, *sp++);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
*dest++ = badchar_substitute;
}
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t utf32_measure_from_utf8(const char *utf8, size_t size)
{
if (!utf8)
return 0;
size_t u32len = 0;
const unsigned char *sp = reinterpret_cast<const unsigned char *>(utf8);
const unsigned char *ep = sp + size;
while (sp < ep) {
(void)extract_utf8(sp, ep);
++u32len;
}
return u32len;
}
ST_NODISCARD
inline conversion_error_t utf32_convert_from_utf8(char32_t *dest,
const char *utf8, size_t size,
ST::utf_validation_t validation)
{
const unsigned char *sp = reinterpret_cast<const unsigned char *>(utf8);
const unsigned char *ep = sp + size;
while (sp < ep) {
char32_t bigch = extract_utf8(sp, ep);
const conversion_error_t error = char_error(bigch);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
bigch = badchar_substitute;
}
*dest++ = bigch;
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t utf32_measure_from_utf16(const char16_t *utf16, size_t size)
{
if (!utf16)
return 0;
size_t u32len = 0;
const char16_t *sp = utf16;
const char16_t *ep = sp + size;
while (sp < ep) {
(void)extract_utf16(sp, ep);
++u32len;
}
return u32len;
}
ST_NODISCARD
inline conversion_error_t utf32_convert_from_utf16(char32_t *dest,
const char16_t *utf16, size_t size,
ST::utf_validation_t validation)
{
const char16_t *sp = utf16;
const char16_t *ep = sp + size;
while (sp < ep) {
char32_t bigch = extract_utf16(sp, ep);
const conversion_error_t error = char_error(bigch);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
bigch = badchar_substitute;
}
*dest++ = bigch;
}
return conversion_error_t::success;
}
inline void utf16_convert_from_latin_1(char16_t *dest, const char *astr, size_t size)
{
const char *sp = astr;
const char *ep = sp + size;
while (sp < ep)
*dest++ = static_cast<unsigned char>(*sp++);
}
inline void utf32_convert_from_latin_1(char32_t *dest, const char *astr, size_t size)
{
const char *sp = astr;
const char *ep = sp + size;
while (sp < ep)
*dest++ = static_cast<unsigned char>(*sp++);
}
ST_NODISCARD
inline size_t latin_1_measure_from_utf8(const char *utf8, size_t size)
{
// This always returns the same answer as UTF-32
return utf32_measure_from_utf8(utf8, size);
}
ST_NODISCARD
inline conversion_error_t latin_1_convert_from_utf8(char *dest,
const char *utf8, size_t size,
ST::utf_validation_t validation,
bool substitute_out_of_range)
{
const unsigned char *sp = reinterpret_cast<const unsigned char *>(utf8);
const unsigned char *ep = sp + size;
while (sp < ep) {
char32_t bigch = extract_utf8(sp, ep);
const conversion_error_t error = char_error(bigch);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
bigch = '?';
}
if (bigch >= 0x100) {
if (substitute_out_of_range)
bigch = '?';
else
return conversion_error_t::latin1_out_of_range;
}
*dest++ = static_cast<char>(bigch);
}
return conversion_error_t::success;
}
ST_NODISCARD
inline size_t latin_1_measure_from_utf16(const char16_t *utf16, size_t size)
{
// This always returns the same answer as UTF-32
return utf32_measure_from_utf16(utf16, size);
}
ST_NODISCARD
inline conversion_error_t latin_1_convert_from_utf16(char *dest,
const char16_t *utf16, size_t size,
ST::utf_validation_t validation,
bool substitute_out_of_range)
{
const char16_t *sp = utf16;
const char16_t *ep = sp + size;
while (sp < ep) {
char32_t bigch = extract_utf16(sp, ep);
const conversion_error_t error = char_error(bigch);
if (error != conversion_error_t::success) {
if (validation == ST::check_validity)
return error;
bigch = '?';
}
if (bigch >= 0x100) {
if (substitute_out_of_range)
bigch = '?';
else
return conversion_error_t::latin1_out_of_range;
}
*dest++ = static_cast<char>(bigch);
}
return conversion_error_t::success;
}
ST_NODISCARD
inline conversion_error_t latin_1_convert_from_utf32(char *dest,
const char32_t *utf32, size_t size,
ST::utf_validation_t validation,
bool substitute_out_of_range)
{
const char32_t *sp = utf32;
const char32_t *ep = sp + size;
while (sp < ep) {
char32_t bigch = *sp++;
if (bigch > 0x10FFFF && validation == ST::check_validity)
return conversion_error_t::out_of_range;
if (bigch >= 0x100) {
if (substitute_out_of_range)
bigch = '?';
else
return conversion_error_t::latin1_out_of_range;
}
*dest++ = static_cast<char>(bigch);
}
return conversion_error_t::success;
}
}
#endif // _ST_UTF_CONV_PRIV_H
| true |
82752ccb07d7209bbc1d3ba9fcfd14eb4b1848e6 | C++ | ETalienwx/ETGitHub | /SmartPtr/SmartPtr.cpp | GB18030 | 8,696 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <thread>
#include <mutex>
using namespace std;
////ָԭ
//template<class T>
//class SmartPtr
//{
//public:
// SmartPtr(T* ptr)
// :_ptr(ptr)
// {}
// ~SmartPtr()
// {
// cout <<"delete:"<< _ptr << endl;
// delete _ptr;
// }
//private:
// T* _ptr;
//};
//
////void Func()
////{
//// int* p = new int;
//// vector<int> v;
//// v.at(0) = 10;//쳣
//// delete p;//pûͷ
////}
//
//void Func()
//{
// int* p = new int;
// SmartPtr<int> sp(p);
// vector<int> v;
// v.at(0) = 10;//쳣
//}
//int main()
//{
// try
// {
// Func();
// }
// catch (exception& e)
// {
// cout << e.what() << endl;
// }
// system("pause");
// return 0;
//}
//ָ-->
//template<class T>//ģ͵ҲSmartLock
//class SmartLock
//{
//public:
// SmartLock(T& lock)
// :_lock(lock)
// {
// _lock.lock();
// }
// ~SmartLock()
// {
// _lock.unlock();
// }
//private:
// T& _lock;
//};
//
//mutex mtx;
//
//void add(int n, int *value)
//{
// SmartLock<mutex> smtlock(mtx);//smtlockmtxԶ
// for (int i = 0; i < n; i++)
// {
// ++(*value);
// }
//}
//
//int main()
//{
// int x = 0;
// thread t1(add, 10000, &x);
// thread t2(add, 10000, &x);
//
// t1.join();
// t2.join();
//
// cout << x << endl;
// system("pause");
// return 0;
//}
//ָһΪ
//template<class T>
//class SmartPtr
//{
//public:
// SmartPtr(T* ptr)
// :_ptr(ptr)
// {}
// ~SmartPtr()
// {
// delete _ptr;
// }
// T& operator*()//ڣԷ
// {
// return *_ptr;//
// }
// T* operator->()
// {
// return _ptr;//ԭָ
// }
//private:
// T* _ptr;
//};
//
//struct A
//{
// int _a1;
// int _a2;
//};
//
//int main()
//{
// SmartPtr<int> p1(new int);
// *p1 = 10;
// cout << *p1 << endl;
//
// SmartPtr<A> p2(new A);
// (*p2)._a1 = 10;
// cout << p2->_a1 << endl;
// p2->_a2 = 100;
// cout << p2->_a2 << endl;
//
// system("pause");
// return 0;
//}
//auto_ptrC++98,Ȩתƣȱݵƣ˾Ͻʹ
//unique_ptrC++11,ֱЧʸߣܲȫʹ
//shared_ptrȫֿ֧üƸӣѭ
namespace PTR
{
template <class T>
class auto_ptr
{
public:
auto_ptr(T* ptr)//
:_ptr(ptr)
{}
~auto_ptr()//
{
cout << "delete:" << _ptr << endl;
delete _ptr;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
//
//p1(p2)--->p2p1ʱp2ÿգȨp1
auto_ptr(auto_ptr<T>& ptr)//thisָp1ptrp2
:_ptr(ptr._ptr)
{
ptr._ptr = nullptr;
}
//ֵ
//p1=p2
//this=ptr--->ptrthisٰptrÿ
auto_ptr& operator=(auto_ptr<T>& ptr)
{
if (this != &ptr)//ԼԼֵ
{
//p1ΪվͰp1Դͷ
if (_ptr)
{
delete _ptr;
}
//ٽȨת
_ptr = ptr._ptr;
ptr._ptr = nullptr;
}
return *this;
}
private:
T* _ptr;
};
template<class T>
class unique_ptr
{
public:
unique_ptr(T* ptr)
:_ptr(ptr)
{}
~unique_ptr()
{
cout << "delete:" << _ptr << endl;
delete _ptr;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
//
//
unique_ptr(unique_ptr<T>& ptr) = delete;
//ֵ
unique_ptr<T>& operator=(unique_ptr<T>& ptr) = delete;
private:
T* _ptr;
};
template<class T>
class shared_ptr
{
public:
shared_ptr(T* ptr)
:_ptr(ptr)
, _pcount(new int(1))
{}
~shared_ptr()
{
if (--(*_pcount) == 0)
{
cout << "delete:" << _ptr << endl;
delete _ptr;
delete _pcount;
}
}
T& operator*()//*ǵĿ
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
//p2(p1)
//
shared_ptr(const shared_ptr<T>& ptr)
:_ptr(ptr._ptr)
, _pcount(ptr._pcount)
{
++(*_pcount);
}
//p1=p2
//ֵ
shared_ptr<T>& operator=(shared_ptr<T>& ptr)
{
//if (this != &ptr)ǿŻ
//ptrͬͲȥˣ--++ù
//ҪͬĶptrͬͲ
//ҪDzͬĶָͬһռ䣬ptrͬҲ
if (_ptr != ptr._ptr)
{
if (--(*_pcount) == 0)//ҪֵĶüΪ1ſԽͷ
{
delete _ptr;
delete _pcount;
}
_ptr = ptr._ptr;
_pcount = ptr._pcount;
++(*_pcount);
}
return *this;
}
//鿴ü
int use_count()
{
return *_pcount;
}
private:
T* _ptr;
int* _pcount;//ü
};
}
//void test_auto_ptr()
//{
// PTR::auto_ptr<int> p1(new int);
// PTR::auto_ptr<int> p2(p1);//p1ÿ
// //*p1 = 10;//p1
// *p2 = 20;
//
// PTR::auto_ptr<int> p3(new int);
// p3 = p2;//︳ֵp2ÿ
// //*p2 = 30;//
// *p3 = 40;
//}
//void test_unique_ptr()
//{
// PTR::unique_ptr<int> p1(new int);
// //PTR::unique_ptr<int> p2(p1);//ʾʹɾĺ
//}
//void test_shared_ptr()
//{
// PTR::shared_ptr<int> p1(new int);//p1üΪ1
// PTR::shared_ptr<int> p2(p1);//p1p2ָͬһռ䣬ռüΪ2
// *p1 = 10;
// *p2 = 20;
// p1 = p2;
//
// PTR::shared_ptr<int> p3(new int(30));//p3üΪ1
// p1 = p3;//p3p1ָͬһռ䣬üΪ2p2üΪ1
//}
//void copy_ptr(PTR::shared_ptr<int>& ptr, int n)
//{
// //nptr
// for (int i = 0; i < n; i++)
// {
// PTR::shared_ptr<int> copy(ptr);
// }
//}
//void test_shared_ptr_safe()
//{
// PTR::shared_ptr<int> p(new int);
// thread t1(copy_ptr, p, 1000);
// thread t2(copy_ptr, p, 1000);
//
// cout << p.use_count() << endl;
// t1.join();
// t2.join();
//}
//int main()
//{
// //test_auto_ptr();
// //test_unique_ptr();
// //test_shared_ptr();
// test_shared_ptr_safe();//ü⣬˵߳²ȫ
// system("pause");
// return 0;
//}
//shared_ptrȫİ汾
namespace safe
{
template<class T>
class shared_ptr
{
public:
shared_ptr(T* ptr)
:_ptr(ptr)
, _pcount(new int(1))
, _pmtx(new mutex)
{}
~shared_ptr()
{
Release();
}
T& operator*(){return *_ptr;}
T* operator->(){return _ptr;}
void Addref()
{
_pmtx->lock();
++(*_pcount);
_pmtx->unlock();
}
void Release()
{
_pmtx->lock();
int flag = 0;
if (--(*_pcount) == 0)
{
cout << "delete:" << _ptr << endl;
delete _ptr;
delete _pcount;
flag = 1;
}
_pmtx->unlock();
if (flag == 1){ delete _pmtx; }
}
//
shared_ptr(const shared_ptr<T>& ptr)
:_ptr(ptr._ptr)
, _pcount(ptr._pcount)
, _pmtx(ptr._pmtx)
{
//++(*_pcount);
Addref();
}
//ֵ
shared_ptr<T>& operator=(const shared_ptr<T>& ptr)
{
if (_ptr != ptr._ptr)
{
Release();
_ptr = ptr._ptr;
_pcount = ptr._pcount;
_pmtx = ptr._pmtx;
Addref();
}
return *this;
}
//鿴ü
int use_count(){return *_pcount;}
private:
T* _ptr;
int* _pcount;//ü
mutex* _pmtx;
};
}
void copy_ptr(safe::shared_ptr<int>& ptr, int n)
{
//nptr
for (int i = 0; i < n; i++)
{
safe::shared_ptr<int> copy(ptr);//̰߳ȫ
++(*copy);//̰߳ȫ
}
}
void test_shared_ptr_safe()
{
safe::shared_ptr<int> p(new int(0));
thread t1(copy_ptr, p, 1000);
thread t2(copy_ptr, p, 1000);
t1.join();
t2.join();
cout << p.use_count() << endl;
cout << *p << endl;
}
//int main()
//{
// test_shared_ptr_safe();
// system("pause");
// return 0;
//}
#include <memory>//shared_ptrͷļ
//shared_ptrѭ
struct ListNode
{
std::weak_ptr<ListNode> _prev;
std::weak_ptr<ListNode> _next;
~ListNode()
{
cout << "~ListNode()" << endl;
}
};
void test_shared_ptr_cycle_ref()
{
std::shared_ptr<ListNode> node1(new ListNode);
std::shared_ptr<ListNode> node2(new ListNode);
node1->_next = node2;
node2->_prev = node1;
}
//int main()
//{
// test_shared_ptr_cycle_ref();
// system("pause");
// return 0;
//}
//ɾ
template<class T>
struct DeleteArray
{
void operator()(T* ptr)
{
delete[] ptr;
}
};
struct test
{
~test()
{
cout << "~test()" << endl;
}
};
void test_shared_ptr_delete()
{
DeleteArray<test> del;
std::shared_ptr<test> ptr(new test[10], del);
}
int main()
{
test_shared_ptr_delete();
system("pause");
return 0;
} | true |
4b79b23f75bdebe74361094776789ab26902fa89 | C++ | moevm/oop | /7383/Vlasov_Roman/lab1/array.h | UTF-8 | 1,759 | 3.796875 | 4 | [] | no_license | #include <assert.h>
#include <iostream>
#include <algorithm> // std::copy
#include <cstddef> // size_t
template<typename T>
class Array
{
public:
// (default) constructor
Array(const size_t size = 0)
: m_size(size)
, m_array(m_size ? new T[m_size]() : nullptr)
{
}
Array(const Array &a) //copy constructor
{
size_t tmps = a.m_size;
T* tmpa = tmps ? new T[tmps]() : nullptr;
try {
for (size_t i = 0; i < tmps; i++)
tmpa[i] = a.m_array[i];
} catch (...) {
delete[] tmpa;
throw;
}
this->m_size = tmps;
this->m_array = tmpa;
}
Array(Array &&a) //move constructor
{
this->m_size = a.m_size;
this->m_array = a.m_array;
a.m_array = nullptr;
}
Array & operator=(const Array &a) //copy assignment operator
{
if(&a == this)
return *this;
size_t tmps = a.m_size;
T* tmpa = tmps ? new T[tmps]() : nullptr;;
try {
for (size_t i = 0; i < tmps; i++)
tmpa[i] = a.m_array[i];
} catch (...) {
delete[] tmpa;
throw;
}
delete this->m_array;
this->m_size = tmps;
this->m_array = tmpa;
return *this;
}
Array & operator=(Array &&a) //move assignment operator
{
if (&a == this)
return *this;
delete this->m_array;
this->m_size = a.m_size;
this->m_array = a.m_array;
a.m_array = nullptr;
return *this;
}
~Array()
{
delete[] this->m_array;
}
const size_t size() const
{
return m_size;
}
T& operator [](const size_t index)
{
assert(index < m_size);
return m_array[index];
}
private:
size_t m_size;
T* m_array;
};
| true |
a725bd1deba76314a2b5754c19b45e618e328e84 | C++ | MicrosoftDocs/visualstudio-docs | /docs/snippets/cpp/VS_Snippets_Winforms/InstanceDescriptorSample/CPP/instancedescriptor.cpp | UTF-8 | 4,115 | 3.28125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive |
//<snippet1>
#using <system.dll>
#using <system.drawing.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design::Serialization;
using namespace System::Drawing;
using namespace System::Globalization;
using namespace System::Collections;
using namespace System::Reflection;
/* This sample shows how to support code generation for a custom type of object
using a type converter and InstanceDescriptor objects.
To use this code, copy it to a file and add the file to a project. Then add
a component to the project and declare a Triangle field and a public property
with accessors for the Triangle field on the component.
The Triangle property will be persisted using code generation.
*/
ref class TriangleConverter;
[TypeConverter(TriangleConverter::typeid)]
public ref class Triangle
{
private:
// Triangle members
Point P1;
Point P2;
Point P3;
public:
property Point Point1
{
Point get()
{
return P1;
}
void set( Point value )
{
P1 = value;
}
}
property Point Point2
{
Point get()
{
return P2;
}
void set( Point value )
{
P2 = value;
}
}
property Point Point3
{
Point get()
{
return P3;
}
void set( Point value )
{
P3 = value;
}
}
Triangle( Point point1, Point point2, Point point3 )
{
P1 = point1;
P2 = point2;
P3 = point3;
}
/* A TypeConverter for the Triangle object. Note that you can make it internal,
private, or any scope you want and the designers will still be able to use
it through the TypeDescriptor object. This type converter provides the
capability to convert to an InstanceDescriptor. This object can be used by
the .NET Framework to generate source code that creates an instance of a
Triangle object. */
[System::Security::Permissions::PermissionSet(System::Security::
Permissions::SecurityAction::Demand, Name = "FullTrust")]
ref class TriangleConverter: public TypeConverter
{
public:
/* This method overrides CanConvertTo from TypeConverter. This is called when someone
wants to convert an instance of Triangle to another type. Here,
only conversion to an InstanceDescriptor is supported. */
virtual bool CanConvertTo( ITypeDescriptorContext^ context, Type^ destinationType ) override
{
if ( destinationType == InstanceDescriptor::typeid )
{
return true;
}
// Always call the base to see if it can perform the conversion.
return TypeConverter::CanConvertTo( context, destinationType );
}
/* This code performs the actual conversion from a Triangle to an InstanceDescriptor. */
virtual Object^ ConvertTo( ITypeDescriptorContext^ context, CultureInfo^ culture, Object^ value, Type^ destinationType ) override
{
if ( destinationType == InstanceDescriptor::typeid )
{
array<Type^>^type1 = {Point::typeid,Point::typeid,Point::typeid};
ConstructorInfo^ ci = Triangle::typeid->GetConstructor( type1 );
Triangle^ t = safe_cast<Triangle^>(value);
array<Object^>^obj1 = {t->Point1,t->Point2,t->Point3};
return gcnew InstanceDescriptor( ci,safe_cast<ICollection^>(obj1) );
}
// Always call base, even if you can't convert.
return TypeConverter::ConvertTo( context, culture, value, destinationType );
}
};
};
public ref class TestComponent: public System::ComponentModel::Component
{
private:
Triangle^ myTriangle;
public:
TestComponent()
{
myTriangle = gcnew Triangle( Point(5,5),Point(10,10),Point(1,8) );
}
property Triangle^ MyTriangle
{
Triangle^ get()
{
return myTriangle;
}
void set( Triangle^ value )
{
myTriangle = value;
}
}
};
//</snippet1>
| true |
cf5e6eb7578147ad1acfe775acbc8f5565851b3b | C++ | ishine/docker-volume | /light-nn/src/operators/conv2d.cc | GB18030 | 12,790 | 2.90625 | 3 | [] | no_license | //ͷļ
#include "operators/conv2d.h"
#include "utils/math-functions.h"
namespace lnn {
//float * convert_x(const float *A, float *A_convert, const int outM, const int in_channels, int Map, int Kernel)
//{//ת ݲkernel_sizeСת
// //屻
// const int convAw = Kernel * Kernel * in_channels;
// const int convAh = outM * outM;
// //float A_convert[convh*convAw] = { 0 };
// for (int i = 0; i < outM; i++)
// {
// for (int j = 0; j < outM; j++)
// {
// int wh = i * outM * convAw + j * convAw;
// for (size_t k = 0; k < in_channels; k++)
// {
// //int wh = k * outM * outM *convAw+ i * outM * convAw + j * convAw;
// int col1 = k * Map * Map + i * Map + j; //һkmap*mapԪأάɶάһά
// for (size_t m = 0; m < Kernel; m++)
// {
// A_convert[wh+m] = A[col1+m];
// }
// int col2 = k * Map * Map + (i + 1) * Map + j;
// A_convert[wh + 3] = A[col2];
// A_convert[wh + 4] = A[col2 + 1];
// A_convert[wh + 5] = A[col2 + 2];
// int col3 = k * Map * Map + (i + 2) * Map + j;
// A_convert[wh + 6] = A[col3];
// A_convert[wh + 7] = A[col3 + 1];
// A_convert[wh + 8] = A[col3 + 2];
// wh += Kernel * Kernel;
// }
// }
// }
// return A_convert;
//}
float * convert_x(const float *A, float *A_convert, const int outM, const int in_channels, const int Map, const int Kernel, const int stride)
{//ת ݲkernel_sizeСת
//屻
const int convAw = Kernel * Kernel * in_channels;
const int convAh = outM * outM;
//float A_convert[convh*convAw] = { 0 };
for (int i = 0; i < outM; i++)
{
for (int j = 0; j < outM; j++)
{
int wh = i * outM * convAw + j * convAw;
//kchannelsƶiƶjƶ
//strideȡֵù,ȡֵʼ
int col = (i*stride*Map + j * stride);
//ԭͼһά뵽άתͼ
for (size_t k = 0; k < in_channels; k++)
{
col += (k * Map*Map);
//ӦͬСkernel_size
int id = 0;
for (size_t m = 0; m < Kernel; m++)
{
col += (m*Map);
//col += Map;
for (size_t n = 0; n < Kernel; n++)
{
A_convert[wh + id] = A[col + n];
/*cout << "" << i << "";
cout << "" << j << "";
cout << "ʼ±" << col;
cout << ""<<(k+1)*(id+1)<<"Ԫ"<<A[col + n] << endl;*/
id++;
}
//λ
col -= (m*Map);
}
//λ
col -= (k * Map*Map);
wh += Kernel * Kernel;
}
}
}
return A_convert;
}
void padding_x(const float *A, float *new_A, const int padding, const int height, const int width, const int in_channels)
{
const int new_width = width + padding * 2;
const int new_height = height + padding * 2;
for (size_t c = 0; c < in_channels; c++)
{
size_t start = c * new_width*new_height;
//ԭеԪӵ
for (size_t i = 0; i < height; i++)
{
start += (i + padding) * new_width + padding;//ÿһͨͼʼ
for (size_t j = 0; j < width; j++)
{
new_A[start + j] = A[c*height*width + i*width + j];
}
//λ
start -= (i + padding) * new_width + padding;
}
}
}
Conv2D::Conv2D(const Json::Value &config) : Operator(config) {
m_name = config["name"].asString();
m_input_size = config["param"]["input_size"].asInt();
m_output_size = config["param"]["output_size"].asInt();
m_kernel_size = config["param"]["kernel_size"].asInt();
if (config["param"].isMember("stride")) {
m_stride = config["param"]["stride"].asInt();
}
else {
m_stride = 1;
}
if (config["param"].isMember("padding")) {
m_padding = config["param"]["padding"].asInt();
}
else {
m_padding = 0;
}
if (config["param"].isMember("dilation")) {
m_dilation = config["param"]["dilation"].asInt();
}
else {
m_dilation = 1;
}
if (config["param"].isMember("bias")) {
b_bias = config["param"]["bias"].asBool();
}
else {
b_bias = true;
}
}
Conv2D::~Conv2D() {
}
bool Conv2D::set_weight(const std::vector<Tensor> &weights,
const std::map<std::string, size_t> &weights_name2id) {
std::vector<std::string> tensor_name;
std::vector<size_t> tensor_size, shape;
std::vector<std::vector<size_t> > tensor_shape;
m_weights.resize(1);
tensor_name.push_back(m_name + ".weight");
tensor_size.push_back(m_output_size * m_kernel_size *m_kernel_size* m_input_size);
shape.push_back(m_output_size);
shape.push_back(m_input_size);
shape.push_back(m_kernel_size);
shape.push_back(m_kernel_size);
tensor_shape.push_back(shape);
if (b_bias) {
m_weights.resize(2);
tensor_name.push_back(m_name + ".bias");
tensor_size.push_back(m_output_size);
shape.resize(1);
tensor_shape.push_back(shape);
}
// get tensors needed by current operator
std::map<std::string, size_t>::const_iterator it;
for (size_t i = 0; i < tensor_name.size(); ++i) {
get_tensor(tensor_name[i], m_name, "Conv2D", m_weights[i]);
}
// check consistency of weight tensor's size
for (size_t i = 0; i < tensor_name.size(); ++i) {
if (m_weights[i]->size() != tensor_size[i]) {
LOG(ERROR) << "Size mismatch of tensor [" << m_weights[i]->name()
<< "] between weight file and model file (" << m_weights[i]->size()
<< ", " << tensor_size[i] << ")!" << std::endl;
return false;
}
}
// set weight tensor's shape
for (size_t i = 0; i < tensor_name.size(); ++i) {
std::cout << "ǰtensor name:" << tensor_name[i] << std::endl;
for (size_t j = 0; j < tensor_shape[i].size(); j++)
{
std::cout << tensor_shape[i][j] << std::endl;
}
m_weights[i]->set_shape(tensor_shape[i]);
}
return true;
}
bool Conv2D::reshape(const std::vector<Tensor *> &input,
std::vector<Tensor *> &output) {
if (0 != input[0]->size() % m_input_size) {
LOG(ERROR) << "Input size [" << input[0]->size() << "] should be divided by ["
<< m_input_size << "]!" << std::endl;
return false;
}
std::cout << input[0]->num_axes() ;
std::cout << "\n";
if (3 != input[0]->num_axes()) {
LOG(ERROR) << "Only support 2d input of shape C*W*H!" << std::endl;
return false;
}
std::vector<size_t> shape; //channel_first
//ͼ
const int out_w = (input[0]->shape(1) + 2 * m_padding - m_dilation * (m_kernel_size - 1) - 1) / m_stride + 1;
const int out_h = (input[0]->shape(2) + 2 * m_padding - m_dilation * (m_kernel_size - 1) - 1) / m_stride + 1;
shape.push_back(m_output_size);
shape.push_back(out_w);
shape.push_back(out_h);
output[0]->realloc(shape);
if (m_padding > 0) {
shape = input[0]->shape();
const size_t new_w = input[0]->shape(1) + m_padding * 2;
const size_t new_h = input[0]->shape(2) + m_padding * 2;
shape[1] += 2 * m_padding;
shape[2] += 2 * m_padding;
m_buf.realloc(shape);
lnn_set(shape[1] * shape[2] * m_input_size, 0., m_buf.data()); //m_bufʼΪ0
//float *new_A = new float[m_input_size*new_h*new_h]();
padding_x(input[0]->data(), m_buf.data(), m_padding, input[0]->shape(1), input[0]->shape(2), m_input_size);
//֤padding
/*for (size_t i = 0; i < m_input_size; i++)
{
for (size_t j = 0; j < new_w; j++)
{
for (size_t k = 0; k < new_h; k++)
{
std::cout << m_buf.data()[i*new_w*new_h + j * new_h + k] << ",";
}
std::cout << std::endl;
}
std::cout << std::endl;
}*/
}
if (b_bias) {
std::vector<size_t> t_shape;
t_shape.push_back(out_w);
t_shape.push_back(out_h);
m_bias_multiplier.realloc(t_shape);
lnn_set(t_shape[0]* t_shape[1], 1., m_bias_multiplier.data());
}
if (m_dilation > 1) {
shape.resize(1);
shape[0] = m_kernel_size * m_input_size;
m_buf_2.realloc(shape);
}
return true;
}
void Conv2D::forward_impl(const std::vector<Tensor *> &input,
std::vector<Tensor *> &output) {
size_t Map = input[0]->shape(1);
//
size_t outM = (Map + 2 * m_padding - m_dilation * (m_kernel_size - 1) - 1) / m_stride + 1;
if (b_bias) {
lnn_gemm(CblasNoTrans, CblasNoTrans, m_output_size,outM*outM, 1,
1., m_weights[1]->data(), m_bias_multiplier.data(), 0., output[0]->data());
}
else {
lnn_set(output[0]->size(), 0., output[0]->data());
}
/* std::cout << "bias ijȣ" << output[0]->size() << "\t";
for (size_t i = 0; i < output[0]->size(); i++)
{
std::cout << output[0]->data()[i] << " ";
}*/
std::cout << std::endl;
const float* data = input[0]->data();
//1.inputpadding
if (m_padding > 0)
{
data = m_buf.data();
Map = m_buf.shape(1);
}
//2.inputconvert(strideתɶӦľ)
//֤padding
LOG(INFO) << "conv2d padding" << std::endl;
//for (size_t i = 0; i < m_input_size; i++)
//{
// for (size_t j = 0; j < Map; j++)
// {
// for (size_t k = 0; k < Map; k++)
// {
// std::cout << data[i*Map*Map + j * Map + k] << ",";
// }
// std::cout << std::endl;
// }
// //break;
// std::cout << std::endl;
//}
//屻
const int convAw = m_kernel_size * m_kernel_size * m_input_size;
const int convAh = outM * outM;
float * a_convert = new float[convAh*convAw];
float *A_convert = convert_x(data, a_convert, outM, m_input_size, Map, m_kernel_size, m_stride);
//3.cblas_gemmо
LOG(INFO) << "conv2d convert matrix" << std::endl;
//for (size_t i = 0; i < convAh*convAw / m_input_size; i++)
//{
// for (size_t j = 0; j < m_input_size; j++)
// {
// int k = i * m_input_size + j;
// std::cout << A_convert[k];
// }
// /*if (i > m_kernel_size*m_kernel_size*m_input_size)
// {
// break;
// }*/
// std::cout << std::endl;
//}
//cblasʼֵ
//const int M = m_output_size;//AC
float* a = m_weights[0]->data();
float* b = A_convert;
//
//float C[M*N];
//cblas M=36 N=1 k=9A_convert = [36,9]=36*9,B=[9,1]=9*1 C= [M,N]=M*N
/*(const CBLAS_TRANSPOSE transa, const CBLAS_TRANSPOSE transb,
const int m, const int n, const int k, const float alpha,
const float* a, const float* b, const float beta, float* c*/
//cblas_sgemm(Order, TransA, TransB, m_output_size, N, K, alpha, m_weights[0]->data(), lda, A_convert, ldb, beta, output[0]->data(), ldc);
lnn_gemm(CblasNoTrans, CblasTrans,m_output_size, convAh, convAw,1.0,a,b ,1.0, output[0]->data());
delete[] a_convert;
std::cout << sizeof(output[0]->data()) / sizeof(output[0]->data()[0]) << std::endl;
//֤
/*std::cout << "A is:" << std::endl;
for (size_t k = 0; k < m_input_size; k++)
{
for (int i = 0; i < Map; i++)
{
for (int j = 0; j < Map; j++)
{
std::cout << data[k*Map*Map + i * Map + j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "B is:" << std::endl;
for (size_t k = 0; k < m_input_size; k++)
{
for (size_t m = 0; m < m_output_size; m++)
{
for (int i = 0; i < m_kernel_size; i++)
{
for (int j = 0; j < m_kernel_size; j++)
{
std::cout << m_weights[0]->data()[k*m_output_size*m_kernel_size*m_kernel_size + m * m_kernel_size*m_kernel_size + i * m_kernel_size + j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "C is:" << std::endl;
for (size_t k = 0; k < m_output_size; k++)
{
for (int i = 0; i < outM; i++)
{
for (int j = 0; j < outM; j++)
{
std::cout << output[0]->data()[k*outM*outM + i * outM + j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << std::endl;*/
}
/*if (m_dilation == 1) {
for (size_t i = 0; i < O; ++i) {
lnn_gemv(CblasNoTrans, m_output_size, m_kernel_size*m_input_size, 1.,
m_weights[0]->data(), data + i * m_stride*m_input_size, 1.,
output[0]->data() + i * m_output_size);
}
}
else {
for (size_t i = 0; i < O; ++i) {
const float* cur = data + i * m_stride*m_input_size;
for (size_t j = 0; j < m_kernel_size; ++j) {
lnn_copy(m_input_size, cur + j * m_dilation*m_input_size, m_buf_2.data() + j * m_input_size);
}
lnn_gemv(CblasNoTrans, m_output_size, m_kernel_size*m_input_size, 1.,
m_weights[0]->data(), m_buf_2.data(), 1.,
output[0]->data() + i * m_output_size);
}
}*/
#ifdef DEBUG
dump(output, std::cout);
#endif // DEBUG
}
// namespace lnn
| true |
65d4ccc9fd14bbf792e19dc6947da3f1ad98b201 | C++ | jollywing/dungeon-generator | /mapstyle.cpp | UTF-8 | 3,980 | 2.765625 | 3 | [] | no_license | #include <stdlib.h>
#include "graphic.h"
static MapStyle map_styles[MAP_STYLE_COUNT];
void InitMapStyles() {
// 武当山
map_styles[0].width = 60;
map_styles[0].height = 45;
map_styles[0].blank_tile1 = 20;
map_styles[0].blank_tile1_dark = 21;
map_styles[0].blank_tile2 = 0;
map_styles[0].blank_tile2_dark = 1;
map_styles[0].floor_tile1 = 2;
map_styles[0].floor_tile1_dark = 4;
map_styles[0].floor_tile2 = 3;
map_styles[0].floor_tile2_dark = 4;
map_styles[0].wall_tile1 = 8;
map_styles[0].wall_tile1_dark = 9;
map_styles[0].wall_tile2 = 7;
map_styles[0].wall_tile2_dark = 9;
// 青城山
map_styles[1].width = 48;
map_styles[1].height = 42;
map_styles[1].blank_tile1 = 5;
map_styles[1].blank_tile1_dark = 6;
map_styles[1].blank_tile2 = 0;
map_styles[1].blank_tile2_dark = 1;
map_styles[1].floor_tile1 = 25;
map_styles[1].floor_tile1_dark = 27;
map_styles[1].floor_tile2 = 26;
map_styles[1].floor_tile2_dark = 27;
map_styles[1].wall_tile1 = 22;
map_styles[1].wall_tile1_dark = 24;
map_styles[1].wall_tile2 = 23;
map_styles[1].wall_tile2_dark = 24;
// 大沙漠
map_styles[2].width = 72;
map_styles[2].height = 42;
map_styles[2].blank_tile1 = 28;
map_styles[2].blank_tile1_dark = 30;
map_styles[2].blank_tile2 = 12;
map_styles[2].blank_tile2_dark = 13;
map_styles[2].floor_tile1 = 28;
map_styles[2].floor_tile1_dark = 30;
map_styles[2].floor_tile2 = 29;
map_styles[2].floor_tile2_dark = 30;
map_styles[2].wall_tile1 = 12;
map_styles[2].wall_tile1_dark = 13;
map_styles[2].wall_tile2 = 10;
map_styles[2].wall_tile2_dark = 11;
// 雪山
map_styles[3].width = 60;
map_styles[3].height = 45;
map_styles[3].blank_tile1 = 14;
map_styles[3].blank_tile1_dark = 15;
map_styles[3].blank_tile2 = 16;
map_styles[3].blank_tile2_dark = 17;
map_styles[3].floor_tile1 = 33;
map_styles[3].floor_tile1_dark = 35;
map_styles[3].floor_tile2 = 34;
map_styles[3].floor_tile2_dark = 35;
map_styles[3].wall_tile1 = 31;
map_styles[3].wall_tile1_dark = 36;
map_styles[3].wall_tile2 = 32;
map_styles[3].wall_tile2_dark = 36;
// 海岛
map_styles[4].width = 60;
map_styles[4].height = 45;
map_styles[4].blank_tile1 = 18;
map_styles[4].blank_tile1_dark = 19;
map_styles[4].blank_tile2 = 18;
map_styles[4].blank_tile2_dark = 19;
map_styles[4].floor_tile1 = 40;
map_styles[4].floor_tile1_dark = 42;
map_styles[4].floor_tile2 = 41;
map_styles[4].floor_tile2_dark = 42;
map_styles[4].wall_tile1 = 37;
map_styles[4].wall_tile1_dark = 39;
map_styles[4].wall_tile2 = 38;
map_styles[4].wall_tile2_dark = 39;
// 草原
map_styles[5].width = 60;
map_styles[5].height = 45;
map_styles[5].blank_tile1 = 43;
map_styles[5].blank_tile1_dark = 44;
map_styles[5].blank_tile2 = 47;
map_styles[5].blank_tile2_dark = 46;
map_styles[5].floor_tile1 = 43;
map_styles[5].floor_tile1_dark = 44;
map_styles[5].floor_tile2 = 43;
map_styles[5].floor_tile2_dark = 44;
map_styles[5].wall_tile1 = 45;
map_styles[5].wall_tile1_dark = 46;
map_styles[5].wall_tile2 = 48;
map_styles[5].wall_tile2_dark = 49;
// 森林
map_styles[6].width = 60;
map_styles[6].height = 45;
map_styles[6].blank_tile1 = 45;
map_styles[6].blank_tile1_dark = 46;
map_styles[6].blank_tile2 = 43;
map_styles[6].blank_tile2_dark = 44;
map_styles[6].floor_tile1 = 43;
map_styles[6].floor_tile1_dark = 44;
map_styles[6].floor_tile2 = 43;
map_styles[6].floor_tile2_dark = 44;
map_styles[6].wall_tile1 = 47;
map_styles[6].wall_tile1_dark = 46;
map_styles[6].wall_tile2 = 48;
map_styles[6].wall_tile2_dark = 49;
}
MapStyle * GetMapStyle(unsigned short i)
{
if(i < 0 || i >= MAP_STYLE_COUNT)
return NULL;
return &(map_styles[i]);
}
| true |
656b343ffefc5e716a3a36eeb8a09517abf17386 | C++ | KenSporger/Digital-Image-Processing-Course | /Image-processing-algorithm/Image Extracting/connectedAreaMarkDFS.cpp | UTF-8 | 2,341 | 2.921875 | 3 | [] | no_license | #include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
void seedFilling(Mat &src)
{
// 标签容器,初始化为标记0
vector<vector<int>> labels(src.rows, vector<int>(src.cols, 0));
// 当前的种子标签
int curLabel = 1;
// 四连通位置偏移
pair<int, int> offset[4] = {make_pair(0, 1), make_pair(1, 0), make_pair(-1, 0), make_pair(0, -1)};
// 当前连通域中的单位域队列
vector<pair<int, int>> tempList;
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
// 当前单位域已被标记或者属于背景区域, 则跳过
if (labels[i][j] != 0 || src.at<uchar>(i, j) == 0)
{
continue;
}
// 当前单位域未标记并且属于前景区域, 用种子为其标记
labels[i][j] = curLabel;
// 加入单位域队列
tempList.push_back(make_pair(i, j));
// 遍历单位域队列
for (int k = 0; k < tempList.size(); k++)
{
// 四连通范围内检查未标记的前景单位域
for (int m = 0; m < 4; m++)
{
int row = offset[m].first + tempList[k].first;
int col = offset[m].second + tempList[k].second;
// 防止坐标溢出图像边界
row = (row < 0) ? 0: ((row >= src.rows) ? (src.rows - 1): row);
col = (col < 0) ? 0: ((col >= src.cols) ? (src.cols - 1): col);
// 邻近单位域未标记并且属于前景区域, 标记并加入队列
if (labels[row][col] == 0 && src.at<uchar>(row, col) == 255)
{
labels[row][col] = curLabel;
tempList.push_back(make_pair(row, col));
}
}
}
// 一个完整连通域查找完毕,标签更新
curLabel++;
// 清空队列
tempList.clear();
}
}
return;
}
int main()
{
Mat img = imread("img/qrcode2.jpg", IMREAD_GRAYSCALE);
threshold(img, img, 0, 255, THRESH_OTSU);
// 4.5s for 1000 times
seedFilling(img);
} | true |
75de5478b6d82d6d40a40f38dc32f044060dab4c | C++ | jenenena/DataStructures | /DataStructures/Controller/FileController.cpp | UTF-8 | 9,157 | 2.765625 | 3 | [] | no_license | //
// FileController.cpp
// DataStructures
//
// Created by Mills, Jenna on 2/5/19.
// Copyright © 2019 CTEC. All rights reserved.
//
#include "FileController.hpp"
//CRIME DATA ---------------------------------------------
//CRIME DATA VECTOR
vector<CrimeData> FileController :: readCrimeDataToVector(string filename)
{
std :: vector<CrimeData> crimeVector;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//if the file exists at that path
if (dataFile.is_open())
{
//keep reading until you reach the end of the line
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0)
{
//Create a CrimeData instance from the line. exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
CrimeData row(currentCSVLine);
crimeVector.push_back(row);
}
}
}
}
return crimeVector;
}
//CRIME DATA LINKED LIST
LinkedList<CrimeData> FileController :: readDataToList(string filename)
{
LinkedList<CrimeData> crimes;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//If the file exists at that path
if (dataFile.is_open())
{
//Keep reading until at the end of the file
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0)
{
//Create a CrimeData instance from the line. Exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
CrimeData row(currentCSVLine);
crimes.add(row);
}
}
rowCount++;
}
dataFile.close();
}
else
{
cerr << "NO FILE" << endl;
}
return crimes;
}
//CRIME DATA STACK
Stack<CrimeData> FileController :: readCrimeDataToStack(string filename)
{
Stack<CrimeData> crimes;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//If the file exists at that path
if (dataFile.is_open())
{
//Keep reading until at the end of the file
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0)
{
//Create a CrimeData instance from the line. Exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
CrimeData row(currentCSVLine);
crimes.push(row);
}
}
rowCount++;
}
dataFile.close();
}
else
{
cerr << "NO FILE" << endl;
}
return crimes;
}
//CRIME DATA QUEUE
Queue<CrimeData> FileController :: readCrimeDataToQueue(string filename)
{
Queue<CrimeData> crimes;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//If the file exists at that path
if (dataFile.is_open())
{
//Keep reading until at the end of the file
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0)
{
//Create a CrimeData instance from the line. Exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
CrimeData row(currentCSVLine);
crimes.enqueue(row);
}
}
rowCount++;
}
dataFile.close();
}
else
{
cerr << "NO FILE" << endl;
}
return crimes;
}
//MUSIC DATA ---------------------------------------------
//MUSIC VECTOR
vector<Music> FileController :: musicDataToVector(string filename)
{
std :: vector<Music> musicVector;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//if the file exists at that path
if (dataFile.is_open())
{
//keep reading until you reach the end of the line
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0)
{
//Create a CrimeData instance from the line. exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
Music row(currentCSVLine);
musicVector.push_back(row);
}
}
}
}
return musicVector;
}
//MUSIC LINKED LIST
LinkedList<Music> FileController :: musicDataToList(string filename)
{
LinkedList<Music> musicList;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//If the file exists at that path
if (dataFile.is_open())
{
//Keep reading until at the end of the file
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0)
{
//Create a CrimeData instance from the line. Exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
Music row(currentCSVLine);
musicList.add(row);
}
}
rowCount++;
}
dataFile.close();
}
else
{
cerr << "NO FILE" << endl;
}
return musicList;
}
//MUSIC STACK
Stack<Music> FileController :: musicDataToStack(string filename)
{
Stack<Music> musicList;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//If the file exists at that path
if (dataFile.is_open())
{
//Keep reading until at the end of the file
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0 && rowCount <= 10)
{
//Create a CrimeData instance from the line. Exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
Music row(currentCSVLine);
musicList.push(row);
}
}
rowCount++;
}
dataFile.close();
}
else
{
cerr << "NO FILE" << endl;
}
return musicList;
}
//MUSIC QUEUE
Queue<Music> FileController :: musicDataToQueue(string filename)
{
Queue<Music> musicList;
string currentCSVLine;
int rowCount = 0;
ifstream dataFile(filename);
//If the file exists at that path
if (dataFile.is_open())
{
//Keep reading until at the end of the file
while (!dataFile.eof())
{
//Grab each line from the CSV separated by the carriage return character
getline(dataFile, currentCSVLine, '\r');
//Exclude header row
if (rowCount != 0 && rowCount <= 10)
{
//Create a CrimeData instance from the line. Exclude a blank line (usually if opened separately)
if(currentCSVLine.length() != 0)
{
Music row(currentCSVLine);
musicList.enqueue(row);
}
}
rowCount++;
}
dataFile.close();
}
else
{
cerr << "NO FILE" << endl;
}
return musicList;
}
| true |
178d76b90acd8d61cb297b71bfb68a2100a20403 | C++ | CyberROFL/YandexSort | /YandexSort/src/main.cpp | UTF-8 | 1,356 | 3.265625 | 3 | [] | no_license | /*
@author Ilnaz Nizametdinov (c)
@project YandexSort
@description
Application entry point.
*/
#include <pch.h>
#include <algo/generator.hpp>
#include <algo/sorter.hpp>
int main(int argc, char* argv[])
{
typedef int value_type;
// Restrictions
const size_t file_size = 1 << 30; // 1G
const size_t mem_limit = 100 * (1 << 20); // 100M
assert (0 != file_size);
assert (0 != mem_limit);
assert (0 == (file_size % sizeof(value_type)));
assert (0 == (mem_limit % sizeof(value_type)));
// chunk size cannot be zero
assert (0 != ((mem_limit / sizeof(value_type)) / ((file_size / mem_limit) + 1)));
try
{
if (3 != argc)
{
std::cout << "Usage: YandexSort <gen-file> <sorted-file>\n";
std::cout << "Example:\n";
std::cout << " YandexSort gen sorted\n";
return 1;
}
std::cout << "Generating " << file_size << " byte(s) of data...\n";
generator<value_type> gen(file_size, mem_limit);
gen.generate(argv[1]);
std::cout << "Sorting...\n";
sorter<value_type> srt(mem_limit);
srt.sort(argv[1], argv[2]);
std::cout << "Done!\n";
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
| true |
7be2906f02d89a6e873fcc631a3ca88424cd1866 | C++ | shlomilougassi/car | /main.cpp | UTF-8 | 5,941 | 2.828125 | 3 | [] | no_license | //shlomi lougassi 300620077
//tal kot 305468050
#include <iostream>
#include "car.h"
#include "customer.h"
#include "fileparser.h"
#include "garage.h"
#define amount_of_clients_from_file 4
using namespace std;
void matching_cars_to_customers(customer* ptr_customer[], car* ptr_car[], int which_car)
{
for (int i = 0; i < amount_of_clients_from_file; i++)
{
if (ptr_customer[i]->getid() == ptr_car[which_car]->getcarid())
{
ptr_customer[i]->assigncar(ptr_car[which_car]);
ptr_car[which_car]->setowner_full_name(ptr_customer[i]->getfullname());
}
}
}
void main(int argc, char* argv[])
{
int whichaction = 0, choose_customer = 0, do_you_want_to_fix = 0, which_car_is_mine = 0, which_car_to_fix = 0, i = 0;
fileParser* filep = new fileParser();
customer* ptr_customer[amount_of_clients_from_file] = { NULL };
car* ptr_car[amount_of_clients_from_file] = { NULL };
for ( i = 0; i < amount_of_clients_from_file; i++)
{
ptr_customer[i] = filep->parsecustomerfile(argv[1]);
ptr_car[i] = filep->parsecarfile(argv[2]);
}
for (i = 0; i < amount_of_clients_from_file; i++) matching_cars_to_customers(ptr_customer, ptr_car, i);
garage* ptr_garage = new garage();
for (i = 0; i < amount_of_clients_from_file; i++)ptr_garage->set_create_full_customers_list(ptr_customer[i]);
cout << "Hello user,";
do
{
cout <<endl<< "Please choose your wanted action from the list below - " << endl << "(1)\t To print full customers list" << endl << "(2)\t To print all registered cars in the garage" << endl << "(3)\t To print all the registered customers in the garage" << endl << "(4)\t To exit the program" << endl;
cout << "Please choose your action - ";
cin >> whichaction;
while ((whichaction != 1) && (whichaction != 2) && (whichaction != 3) && (whichaction != 4))
{
cout << "Please use valid input" << endl;
cin >> whichaction;
}
if (whichaction == 1)
{
cout << "Please choose customer from the list:" << endl;
for (int temp = 0; temp < amount_of_clients_from_file; temp++) cout <<"(" << temp + 1 <<")\t" << ptr_customer[temp]->getfullname() << endl ;
cout << "The customer you want to check his car is - ";
cin >> choose_customer;
--choose_customer;
while (choose_customer>amount_of_clients_from_file-1 || choose_customer < 0)
{
cout << "Please use valid input" << endl;
cin >> choose_customer;
--choose_customer;
}
if (!ptr_customer[choose_customer]->getcar())
{
cout << "ERROR - The car is already in the garage - you can't sent it twice" << endl;
}
else
{
if (ptr_garage->calculateprice(ptr_customer[choose_customer]->getcar()) == 0)
{
cout << "There are no malfuncations in this client's car" << endl;
}
else
{
if (ptr_garage->calculateprice(ptr_customer[choose_customer]->getcar()) > 0)
{
cout << endl << "this client's car needs to be fix." << endl << "in order for us to fix all the malfuncations, it will cost the client - " << ptr_garage->calculateprice(ptr_customer[choose_customer]->getcar()) << "$" << endl;
if (ptr_customer[choose_customer]->getfunds() < ptr_garage->calculateprice(ptr_customer[choose_customer]->getcar()))
{
cout << "you don't have enough money to fix your car - try to get a better job :)" << endl;
}
else
{
cout << "do you want to check your car in to the garage?" << endl;
cout << "1. Yes " << endl << "2. No " << endl << "Please choose your action - ";
cin >> do_you_want_to_fix;
while ((do_you_want_to_fix != 1) && (do_you_want_to_fix != 2))
{
cout << "plaese use valid input" << endl;
cin >> do_you_want_to_fix;
}
if (do_you_want_to_fix == 2)
{
cout << "You chose not to fix the client's car" << endl;
}
else
{
ptr_garage->addcustomer(*ptr_customer[choose_customer]);
cout << "The client's car sent to the garage" << endl;
}
}
}
}
}
}
else if (whichaction == 2)
{
cout << "You choose to print the cars that are currnet location is the garage:" << endl;
if (ptr_garage->print_cars_in_garage())
{
cout << endl << "choose the car that you want to fix: " << endl;
cin >> which_car_to_fix;
--which_car_to_fix;
while ((which_car_to_fix>=ptr_garage->gethow_many_in_garage()) || (which_car_to_fix<0))
{
cout << "plaese use valid input" << endl;
cin >> which_car_to_fix;
--which_car_to_fix;
}
ptr_garage->checkoutcar(*ptr_garage->getcars_in_garage(which_car_to_fix));
}
}
else if (whichaction == 3)
{
cout<< "You choose to print the customers that are currnet location is the garage:" << endl;
if (ptr_garage->print_customers_in_garage())
{
cout << endl << "choose the customer that you want to fix: " << endl;
int which_customer_to_fix = 0;
cin >> which_customer_to_fix;
--which_customer_to_fix;
while ((which_customer_to_fix>=ptr_garage->gethow_many_in_garage()) || (which_customer_to_fix<0))
{
cout << "plaese use valid input" << endl;
cin >> which_customer_to_fix;
--which_customer_to_fix;
}
which_car_is_mine = ptr_garage->which_car_is_mine(*ptr_garage->getcustomers_in_garage(which_customer_to_fix));
if (which_car_is_mine == -1)
{
cout << "The client doesn't have a car in the garage" << endl;
}
else ptr_garage->checkoutcar(*ptr_garage->getcars_in_garage(which_car_is_mine));
}
}
else if (whichaction == 4)
{
cout << "You choose to exit the program, thank you for using.." << endl;
break;
}
} while ((whichaction == 1) || (whichaction == 2) || (whichaction == 3));
if (ptr_garage != NULL)delete ptr_garage;
if (filep != NULL)delete filep;
for (int i = 0; i < amount_of_clients_from_file; i++)
{
if (ptr_customer[i] != NULL) delete ptr_customer[i];
if (ptr_car[i] != NULL)delete ptr_car[i];
}
system("PAUSE");
}
| true |
fa354abe2566097c453d60263c4206999df1a62c | C++ | aarya-bhatia/maze-generator | /src/generator/DisjSet.hpp | UTF-8 | 715 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
#include "K.hpp"
#ifndef DISJ_SET_HPP
#define DISJ_SET_HPP
class DisjSet
{
public:
explicit DisjSet(int n);
~DisjSet()
{
if (K::DEBUG)
{
std::cout << __FILE__ << " destructor" << std::endl;
}
}
int find(int x);
void make_union(int x, int y);
friend std::ostream &operator<<(std::ostream &out, const DisjSet &s)
{
for (int i = 0; i < s.size(); i++)
{
out << s[i] << " ";
}
return out;
}
int operator[](int i) const { return set[i]; }
int size() const { return _size; }
private:
int _size;
std::vector<int> set;
};
#endif | true |
c237484c412cef55ee27dc6b753f2d2959905b42 | C++ | mhfu0/DIP2016FALL | /dip_hw4/main.cpp | UTF-8 | 5,944 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdio>
#include <cassert>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat doDFT(Mat img);
Mat doIDFT(Mat imgComplex);
Mat makeSpecImg(Mat imgComplex);
void shift(Mat &specImg);
void createGHPF(Mat &mask, float d0);
void createGLPF(Mat &mask, float d0);
string type2str(int type);
int main(int argc, char ** argv)
{
const char* filename = argc >=2 ? argv[1] : "selfie.jpg";
Mat img = imread(filename, 0);
if(img.empty())
return -1;
int opt;
printf("Choose options from below:\n [0] GHPF\n [1] GLPF\n");
scanf("%d", &opt);
switch(opt) {
case 0:
{
Mat imgComplex = doDFT(img);
Mat specImg = makeSpecImg(imgComplex);
// create Gaussian highpass filter
int d0;
printf("GHPF: D0 = ");
scanf("%d", &d0);
Mat GHPF = Mat::zeros(img.size(), CV_32F);
createGHPF(GHPF, d0);
shift(GHPF);
// multiply with Gaussian filter in freq. domain
Mat planes[] = {Mat::zeros(GHPF.size(), CV_32F), Mat::zeros(GHPF.size(), CV_32F)};
Mat kernel_spec;
planes[0] = GHPF; // real
planes[1] = GHPF; // imaginary
merge(planes, 2, kernel_spec);
mulSpectrums(imgComplex, kernel_spec, imgComplex, DFT_ROWS); // only DFT_ROWS accepted
specImg = makeSpecImg(GHPF);
imwrite("filter.jpg", specImg);
specImg = makeSpecImg(imgComplex);
imwrite("spectrum.jpg", specImg);
// perform inverse fourier transform
Mat dstImg = doIDFT(imgComplex);
imwrite("output.jpg", dstImg);
break;
}
case 1:
{
Mat imgComplex = doDFT(img);
Mat specImg = makeSpecImg(imgComplex);
// create Gaussian highpass filter
int d0;
printf("GLPF: D0 = ");
scanf("%d", &d0);
Mat GLPF = Mat::zeros(img.size(), CV_32F);
createGLPF(GLPF, d0);
shift(GLPF);
// multiply with Gaussian filter in freq. domain
Mat planes[] = {Mat::zeros(GLPF.size(), CV_32F), Mat::zeros(GLPF.size(), CV_32F)};
Mat kernel_spec;
planes[0] = GLPF; // real
planes[1] = GLPF; // imaginary
merge(planes, 2, kernel_spec);
mulSpectrums(imgComplex, kernel_spec, imgComplex, DFT_ROWS); // only DFT_ROWS accepted
specImg = makeSpecImg(GLPF);
imwrite("filter.jpg", specImg);
specImg = makeSpecImg(imgComplex);
imwrite("spectrum.jpg", specImg);
// perform inverse fourier transform
Mat dstImg = doIDFT(imgComplex);
imwrite("output.jpg", dstImg);
break;
}
default:
{
fprintf(stderr, "bad parameter\n");
return -1;
}
}
return 0;
}
Mat doDFT(Mat img) {
// expand input image to optimal size
Mat padded;
int m = getOptimalDFTSize(img.rows);
int n = getOptimalDFTSize(img.cols);
// expand border with zeros
copyMakeBorder(img, padded, 0, m-img.rows, 0, n-img.cols, BORDER_CONSTANT, Scalar::all(0));
Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
Mat complex;
merge(planes, 2, complex);
dft(complex, complex);
return complex;
}
Mat doIDFT(Mat imgComplex) {
Mat dstImg;
idft(imgComplex, dstImg, DFT_REAL_OUTPUT);
normalize(dstImg, dstImg, 0, 1, CV_MINMAX);
dstImg.convertTo(dstImg, CV_8U, 255.0);
return dstImg;
}
Mat makeSpecImg(Mat imgComplex) {
// compute the magnitude in logarithmic scale
Mat planes[] = {Mat::zeros(imgComplex.size(), CV_32F), Mat::zeros(imgComplex.size(), CV_32F)};
split(imgComplex, planes); // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
magnitude(planes[0], planes[1], planes[0]);
Mat specImg = planes[0];
specImg += Scalar::all(1); // avoid log(0)
log(specImg, specImg);
shift(specImg); // shift to center
normalize(specImg, specImg, 0, 1, CV_MINMAX);
specImg.convertTo(specImg, CV_8U, 255.0);
return specImg;
}
void shift(Mat &specImg) {
// crop when odd number of rows or columns
specImg = specImg(Rect(0, 0, specImg.cols & -2, specImg.rows & -2));
int cx = specImg.cols/2;
int cy = specImg.rows/2;
Mat q0(specImg, Rect(0, 0, cx, cy));
Mat q1(specImg, Rect(cx, 0, cx, cy));
Mat q2(specImg, Rect(0, cy, cx, cy));
Mat q3(specImg, Rect(cx, cy, cx, cy));
Mat tmp;
// swap quadrants (Top-Left with Bottom-Right)
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);
// swap quadrant (Top-Right with Bottom-Left)
q1.copyTo(tmp);
q2.copyTo(q1);
tmp.copyTo(q2);
}
void createGHPF(Mat &mask, float d0) {
// center position
int cx = mask.cols/2;
int cy = mask.rows/2;
for(int i=0; i<mask.cols; i++)
for(int j=0; j<mask.rows; j++) {
float px = i-cx+1;
float py = j-cy+1;
float d = sqrt(px*px+py*py);
float fxy0 = exp(-pow(d,2)/(2*pow(d0,2)));
float fxy = 1-fxy0;
mask.at<float>(Point(i,j)) = fxy;
}
}
void createGLPF(Mat &mask, float d0) {
// center position
int cx = mask.cols/2;
int cy = mask.rows/2;
for(int i=0; i<mask.cols; i++)
for(int j=0; j<mask.rows; j++) {
float px = i-cx+1;
float py = j-cy+1;
float d = sqrt(px*px+py*py);
float fxy = exp(-pow(d,2)/(2*pow(d0,2)));
mask.at<float>(Point(i,j)) = fxy;
}
}
string type2str(int type) {
// check the type of Mat
string r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;
}
| true |
5d4b6cbbedda87977b6440ca5d950d9652f593d0 | C++ | 719400737/LeetCode | /35.cpp | UTF-8 | 629 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
int m=0;
while (l<r)
{
m=(l+r)/2;
if(nums[m]==target)
return m;
else if(nums[m]<target)
l=m+1;
else
r=m-1;
}
m=(l+r)/2;
if(nums[m]<target)
return m+1;
else
return m;
}
};
int main(){
vector<int> vec={1,3,5,6};
int a=0;
Solution s;
s.searchInsert(vec,a);
return 0;
} | true |
2917ec573840ffae034939caaa1fbeabe08589c1 | C++ | tronicslab/ks0108pi | /Ks0108pi.cpp | UTF-8 | 11,213 | 2.765625 | 3 | [] | no_license | /*
Raspberry pi KS0108 LCD interface
Author: Christian Isenberg
With help from the following amazing libraries :D :
- Universal KS0108 driver library by Rados³aw Kwiecieñ, radek@dxp.pl
- BCM 2835 library by Mike McCauley
*/
#include "Ks0108pi.h"
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
Ks0108pi::Ks0108pi(void)
{
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
int Ks0108pi::init(void)
{
if (!bcm2835_init()){
printf("Failed to load bcm2835...\n");
return 1;
}
// pins
Ks0108pi::PIN_RS = 7;
Ks0108pi::PIN_EN = 11;
Ks0108pi::PIN_CS1 = 25;
Ks0108pi::PIN_CS2 = 8;
Ks0108pi::PIN_D0 = 2;
Ks0108pi::PIN_D1 = 3;
Ks0108pi::PIN_D2 = 4;
Ks0108pi::PIN_D3 = 17;
Ks0108pi::PIN_D4 = 27;
Ks0108pi::PIN_D5 = 22;
Ks0108pi::PIN_D6 = 10;
Ks0108pi::PIN_D7 = 9;
// other
Ks0108pi::screen_x=0;
Ks0108pi::screen_y=0;
Ks0108pi::SCREEN_WIDTH = 128;
Ks0108pi::SCREEN_HEIGHT = 64;
//sets all pins as output
bcm2835_gpio_fsel(PIN_EN, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_RS, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_CS1, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_CS2, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D0, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D1, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D2, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D3, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D4, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D5, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D6, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(PIN_D7, BCM2835_GPIO_FSEL_OUTP);
// initialize controllers
for(int i = 0; i < 2; i++)
writeCommand((DISPLAY_ON_CMD | ON), i);
// initialize frame buffer and clearout with 0's
framebuffer_size = (SCREEN_WIDTH * SCREEN_HEIGHT)/8;
framebuffer = new uint8_t[framebuffer_size];
std::fill_n(framebuffer,framebuffer_size, 0);
printf("Started bcm2835...\n");
return 0;
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::goTo(uint8_t x, uint8_t y)
{
uint8_t i;
screen_x = x;
screen_y = y;
for(i = 0; i < SCREEN_WIDTH/64; i++)
{
writeCommand(DISPLAY_SET_Y | 0,i);
writeCommand(DISPLAY_SET_X | y,i);
writeCommand(DISPLAY_START_LINE | 0,i);
}
writeCommand(DISPLAY_SET_Y | (x % 64), (x / 64));
writeCommand(DISPLAY_SET_X | y, (x / 64));
}
void Ks0108pi::putData(uint8_t data)
{
bcm2835_gpio_write(PIN_D0, (data >> 0) & 1 ) ;
bcm2835_gpio_write(PIN_D1, (data >> 1) & 1 ) ;
bcm2835_gpio_write(PIN_D2, (data >> 2) & 1 ) ;
bcm2835_gpio_write(PIN_D3, (data >> 3) & 1 ) ;
bcm2835_gpio_write(PIN_D4, (data >> 4) & 1 ) ;
bcm2835_gpio_write(PIN_D5, (data >> 5) & 1 ) ;
bcm2835_gpio_write(PIN_D6, (data >> 6) & 1 ) ;
bcm2835_gpio_write(PIN_D7, (data >> 7) & 1 ) ;
}
//-------------------------------------------------------------------------------------------------
// Write data to current position. Low level write to single pixel
//-------------------------------------------------------------------------------------------------
void Ks0108pi::writeData(uint8_t dataToWrite)
{
lcdDelay();
bcm2835_gpio_write(PIN_RS, HIGH);
putData(dataToWrite);
enableController(screen_x / 64);
bcm2835_gpio_write(PIN_EN, HIGH);
lcdDelay();
bcm2835_gpio_write(PIN_EN, LOW);
disableController(screen_x / 64);
screen_x++;
}
//-------------------------------------------------------------------------------------------------
// Write command to specified controller
//-------------------------------------------------------------------------------------------------
void Ks0108pi::writeCommand(uint8_t commandToWrite, uint8_t controller)
{
lcdDelay();
bcm2835_gpio_write(PIN_RS, LOW);
enableController(controller);
putData(commandToWrite);
bcm2835_gpio_write(PIN_EN, HIGH);
lcdDelay();
bcm2835_gpio_write(PIN_EN, LOW);
disableController(controller);
}
//-------------------------------------------------------------------------------------------------
// lcdDelay function
//-------------------------------------------------------------------------------------------------
void Ks0108pi::lcdDelay(void)
{
bcm2835_delayMicroseconds(3);
}
//-------------------------------------------------------------------------------------------------
// Enable/Disable Controller (0-1) - screen controlled by 2 64x64 pixel drivers
//-------------------------------------------------------------------------------------------------
void Ks0108pi::enableController(uint8_t controller)
{
switch(controller){
case 0 : bcm2835_gpio_write(PIN_CS1, HIGH); break;
case 1 : bcm2835_gpio_write(PIN_CS2, HIGH); break;
default: break;
}
}
void Ks0108pi::disableController(uint8_t controller)
{
switch(controller){
case 0 : bcm2835_gpio_write(PIN_CS1, LOW); break;
case 1 : bcm2835_gpio_write(PIN_CS2, LOW); break;
default: break;
}
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::clearScreen()
{
clearBuffer();
syncBuffer();
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::clearBuffer()
{
std::fill_n(framebuffer,framebuffer_size, 0);
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::syncBuffer()
{
uint8_t i, j;
int counter = 0;
for(j = 0; j < 8; j++)
{
goTo(0,j);
for(i = 0; i < SCREEN_WIDTH; i++)
writeData((uint8_t)framebuffer[counter++]);
}
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::wait(unsigned int millis)
{
bcm2835_delay(millis);
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::setPixel(uint8_t x, uint8_t y)
{
int idx = (SCREEN_WIDTH * (y/8)) + x;
framebuffer[idx] |= 1 << y%8;
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::clearPixel(uint8_t x, uint8_t y)
{
int idx = (SCREEN_WIDTH * (y/8)) + x;
framebuffer[idx] &= ~(1 << y%8);
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::setPixels(uint8_t x, uint8_t y, uint8_t byte)
{
int idx = (SCREEN_WIDTH * (y/8)) + x;
int idx2 = (SCREEN_WIDTH * ( (y/8)+1) ) + x;
uint8_t rest = y%8;
framebuffer[idx] |= ( byte << y%8 );
if(rest)
framebuffer[idx2] |= byte >> (8-y%8);
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, uint8_t style){
for(int nx=x; nx < (x+w) ; nx++){
for(int ny=y; ny < (y+h) ; ny++){
if(style & STYLE_BLACK_BG) setPixel(nx,ny);
else if(style & STYLE_WHITE_BG) clearPixel(nx,ny);
else if(style & STYLE_GRAY_BG){
if((nx+ny)%2==0)
clearPixel(nx,ny);
else
setPixel(nx,ny);
}
}
}
if( (style & STYLE_BLACK_BORDER) || (style & STYLE_WHITE_BORDER)) {
drawLine(x,y,(x+w)-1,y);
drawLine(x,(y+h)-1,(x+w)-1,(y+h)-1);
drawLine(x,y,x,(y+h)-1);
drawLine((x+w)-1,y,(x+w)-1,(y+h)-1);
}
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::drawLine(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1){
int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
int err = (dx>dy ? dx : -dy)/2, e2;
for(;;){
setPixel(x0,y0);
if (x0==x1 && y0==y1) break;
e2 = err;
if (e2 >-dx) { err -= dy; x0 += sx; }
if (e2 < dy) { err += dx; y0 += sy; }
}
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::writeChar(uint8_t x, uint8_t y, char charToWrite, uint8_t* font)
{
int firstChar = font[4];
int charCount = font[5];
int charHeight = font[3];
int charWidth = font[2];
int sum= 6;
int fixed_width = 1;
if( (font[0] + font [1]) != 0x00){
fixed_width = 0;
}
if( !fixed_width ){
charWidth = font[6+(charToWrite-firstChar)];
sum += charCount;
}
//jumps to the char data position on the array.
for(int i=firstChar; i<charToWrite; i++){
if( !fixed_width )
sum += font[6+i-firstChar] * ceil(charHeight/8.0);
else
sum += charWidth * ceil(charHeight/8.0);
}
for(int line=0; line < charHeight; line+=8){
for(int col=0; col<charWidth; col++){
setPixels(x+col, ceil(y+line),
font[sum + col + (int)ceil(charWidth*line/8.0)]
);
}
}
}
//-------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------
void Ks0108pi::writeString(uint8_t x, uint8_t y, char * stringToWrite, uint8_t* font)
{
while(*stringToWrite){
writeChar(x,y,*stringToWrite++, font);
x+=font[2]+1;
}
}
void Ks0108pi::shiftBufferHorizontal(int x)
{
uint8_t *originalfb = new uint8_t[framebuffer_size];
//backup of current framebuffer
std::copy(framebuffer, framebuffer+framebuffer_size, originalfb);
this->clearBuffer();
int x_original;
int x_new;
// line scan
for(int y=0; y<SCREEN_HEIGHT/8; y++)
{
//x scan
x_original = x < 0 ? x*-1 : 0;
x_new = x < 0 ? 0 : x ;
while(x_original < SCREEN_WIDTH && x_new < SCREEN_WIDTH)
{
this->setPixels(x_new, y*8, originalfb[ (y*SCREEN_WIDTH) + x_original ] );
x_original ++;
x_new ++;
}
}
}
| true |
55b4dd26d91316f0531c41c51a80ce8f5d6f3933 | C++ | boryssmejda/SPOJ | /NotSoFastMultiplication/include/BigMultiplication.hpp | UTF-8 | 1,360 | 3.4375 | 3 | [] | no_license | #include <chrono>
#include <iostream>
#include <string>
#include <vector>
class BigMultiplier {
protected:
std::string m_number;
static std::string multiplyBySingleDigit(const std::string& number,const char multiplyBy);
static void shiftLeftBy(std::string& number ,int shiftBy);
static std::string add(const std::string& a, const std::string& b);
public:
explicit BigMultiplier(const std::string& t_givenNumber): m_number{t_givenNumber}{}
explicit BigMultiplier(const char* t_givenNumber) : m_number{ t_givenNumber } {}
friend const BigMultiplier operator * (const BigMultiplier& t_numA, const BigMultiplier& t_numB);
friend bool operator == (const BigMultiplier& t_numA, const BigMultiplier& t_numB);
friend std::ostream& operator<<(std::ostream& os, const BigMultiplier& dt);
};
class Timer {
using Clock = std::chrono::high_resolution_clock;
public:
Timer()
{
m_startTimePoint = Clock::now();
}
~Timer()
{
stop();
}
private:
std::chrono::time_point<Clock> m_startTimePoint;
void stop()
{
auto endPoint = Clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(m_startTimePoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endPoint).time_since_epoch().count();
auto duration = end - start;
std::cout << duration << "us" << "\n";
}
}; | true |
c394a9746089b3480617fdfc40db2a4bab404d96 | C++ | tylerreisinger/vulkan_wrapper | /src/Extensions.h | UTF-8 | 2,291 | 3.015625 | 3 | [] | no_license | #ifndef EXTENSIONS_H_
#define EXTENSIONS_H_
#include <cstring>
#include <iosfwd>
#include <vector>
#include <vulkan/vulkan.h>
class Extension {
public:
Extension(VkExtensionProperties properties);
Extension(const char* name);
~Extension() = default;
bool operator ==(const Extension& extension) const { return std::strcmp(m_name, extension.m_name) == 0; }
bool operator !=(const Extension& extension) const { return !(*this == extension); }
Extension(const Extension& other) = default;
Extension(Extension&& other) noexcept = default;
Extension& operator =(const Extension& other) = default;
Extension& operator =(Extension&& other) noexcept = default;
const char* extension_name() const { return m_name; }
private:
const char* m_name;
};
class Extensions {
public:
using const_iterator = std::vector<Extension>::const_iterator;
Extensions() = default;
Extensions(std::vector<Extension> extensions);
~Extensions() = default;
Extensions(const Extensions& other) = delete;
Extensions(Extensions&& other) noexcept = default;
Extensions& operator =(const Extensions& other) = delete;
Extensions& operator =(Extensions&& other) noexcept = default;
bool operator ==(const Extensions& rhs) const;
bool operator !=(const Extensions& rhs) const { return !(*this == rhs); }
std::size_t size() const { return m_extensions.size(); }
bool empty() const { return m_extensions.empty(); }
void push(const char* name);
void push_all(const std::vector<const char*>& names);
const_iterator begin() const { return m_extensions.cbegin(); }
const_iterator end() const { return m_extensions.cend(); }
const_iterator cbegin() const { return m_extensions.cbegin(); }
const_iterator cend() const { return m_extensions.cend(); }
bool contains(const Extension& ex) const;
Extensions intersection(const Extensions& rhs) const;
Extensions difference(const Extensions& rhs) const;
const std::vector<Extension>& as_vector() const { return m_extensions; }
private:
std::vector<Extension> m_extensions;
};
std::ostream& operator <<(std::ostream& stream, const Extension& extension);
std::ostream& operator <<(std::ostream& stream, const Extensions& extensions);
#endif
| true |
4c09402a8f84371f41bdb101a4c8600db37efff0 | C++ | AdrienFM/Projet_-cole | /fonction_Tableau.cpp | MacCentralEurope | 3,077 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
#include <vector>
void outputArray(int tableau[], int tailleTableau)
{
for (int i = 0; i < tailleTableau; i++)
std::cout << tableau[i] << std::endl;
}
void fillArrayWithRandom(int tableau[], int tailleTableau, int minTableau, int maxTableau)
{
srand(time(0));
for (int i = 0; i < tailleTableau; i++)
{
tableau[i] = rand() % 5000 + 1;
}
}
void fillArrayWithRandom(std::vector<int>&tableau, int tailleTableau, int minTableau, int maxTableau)
{
int temp = 0;
for (int i =0; i < tailleTableau; i++)
{
temp = rand() % 5000 + 1;
tableau.push_back(temp);
}
}
bool searchArrayForNumber(int tableau[],int taille, int number)
{
for(int i = 0; i < taille; i++)
{
if (tableau[i] == number)
{
return true;
}
}
return false;
}
void sortArray( int tab[], int tab_size, bool croissant)
{
int i=0;
int tmp=0;
int j=0;
for(i = 0; i < tab_size; i++)
{
for(j = i+1; j < tab_size; j++)
{ if (croissant)
{
if(tab[j] < tab[i])
{
tmp = tab[i];
tab[i] = tab[j];
tab[j] = tmp;
}
}
else
{
if(tab[j] > tab[i])
{
tmp = tab[i];
tab[i] = tab[j];
tab[j] = tmp;
}
}
}
}
}
void sortArray(std::vector <int> &tableau, int tableau_size)
{
int i=0;
int tmp=0;
int j=0;
for(i = 0; i < tableau_size; i++)
{
for(j = i+1; j < tableau_size; j++)
{
if(tableau[j] < tableau[i])
{
tmp = tableau[i];
tableau[i] = tableau[j];
tableau[j] = tmp;
}
}
}
}
void fusionArray (std::vector<int> tableau1, std::vector<int> tableau2,std::vector<int>tableauFusion, bool fusion_choix)
{
unsigned int tailleFusion =0;
bool pasTrie =false;
tailleFusion = tableau1.size() + tableau2.size();
for (int i = 1; i < tableau1.size();i++)
{
if (tableau1[0]>tableau1[i])
{
pasTrie=true; // true pas tri
}
}
for (int i = 1; i < tableau2.size();i++)
{
if (tableau2[0]>tableau2[i])
{
pasTrie=true;
}
}
for (unsigned int i =0; i != tailleFusion; i++)
{
if(i<tableau1.size())
tableauFusion.push_back(tableau1[i]);
else
tableauFusion.push_back(tableau2[i-tableau1.size()]);
}
if(!pasTrie)
sortArray(tableauFusion,tableauFusion.size());
for (int i =0;i < tableauFusion.size();i++)
{
std :: cout << i+1 << ") " << tableauFusion[i] << std::endl;
}
}
| true |
03d1061da24ef50e197e64b72fddb1a5464739cc | C++ | zhouliyfly/LeetCode | /23/23.h | GB18030 | 1,949 | 3.078125 | 3 | [] | no_license | #ifndef _23_H_
#define _23_H_
#include "../general.h"
#include <vector>
#include <algorithm>
#include <queue>
#include <functional>
_LEETCODE23_BEGIN
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution { //320ms
public:
ListNode* mergeKLists(std::vector<ListNode*>& lists) {
// LeetCodeвᴫnullptrvector
auto iter = std::remove(lists.begin(), lists.end(), nullptr);
lists.erase(iter, lists.end());
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
while (!lists.empty()) {
std::vector<int> tmp;
for (int i = 0; i < lists.size(); ++i) {
tmp.push_back(lists[i]->val);
}
if (tmp.empty())
break;
auto pos = std::min_element(tmp.begin(), tmp.end());
int j = pos - tmp.begin();
cur->next = lists[j];
cur = cur->next;
if (lists[j]->next == nullptr)
lists.erase(lists.begin() + j);
else
{
lists[j] = lists[j]->next;
}
}
return dummy->next;
}
};
class Solution2 { //24ms
public:
ListNode* mergeKLists(std::vector<ListNode*>& lists) {
ListNode* head = new ListNode(0);
std::priority_queue<int> pq;
if (lists.empty())
return nullptr;
for (int i = 0; i < lists.size(); i++) {
ListNode* tmp = lists[i];
while (tmp) {
pq.push(tmp->val);
tmp = tmp->next;
}
}
while (!pq.empty()) {
ListNode* tmp = new ListNode(pq.top());
tmp->next = head->next;
head->next = tmp;
pq.pop();
}
return head->next;
}
};
_LEETCODE23_END
#endif // !_23_H_
| true |
8dbcbe7be44ff06fc69214ff7ef1700ea1e48ac7 | C++ | utkarsh914/LeetCode | /Arrays and hashing/795. Number of Subarrays with Bounded Maximum.cpp | UTF-8 | 2,476 | 3.703125 | 4 | [] | no_license | // https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/
/*
We are given an array nums of positive integers,
and two positive integers left and right (left <= right).
Return the number of (contiguous, non-empty) subarrays
such that the value of the maximum array element in that subarray
is at least left and at most right.
Example:
Input:
nums = [2, 1, 4, 3]
left = 2
right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Note:
left, right, and nums[i] will be an integer in the range [0, 109].
The length of nums will be in the range of [1, 50000].
*/
/*
my idea is that, any A[i] > Right splits the array in parts
which are valid.
so, just sum the number of possible subarrays of each part
now these valid parts also contain ele < Left.
all subarrays having all (ele < Left) will have to be discarded from every part,
as their max will not be in range [L, R]
so, keep counting the streak of smaller ele.
when that streak ends, subtract the # of total subarrays possible from that streak
and reset the streak to zero
*/
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int left, int right) {
long smaller = 0, count = 0;
for (int i = 0, prevInd = 0; i < A.size(); i++) {
if (A[i] < left) {
smaller++;
} else {
count -= (smaller * (smaller+1)) / 2;
smaller = 0;
}
if (A[i] > right) {
long n = i - prevInd;
count += (n * (n+1)) / 2L;
prevInd = i+1;
}
if (i == A.size()-1) {
long n = A.size() - prevInd;
count += (n * (n+1)) / 2L;
count -= (smaller * (smaller+1)) / 2;
smaller = 0;
}
}
return count;
}
};
/*
[16,69,88,85,79,87,37,33,39,34]
55
57
*/
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int left, int right) {
long smaller = 0, count = 0;
for (int i = 0, prevInd = 0; i < A.size(); i++) {
if (A[i] < left) {
smaller++;
}
else if (A[i] > right) {
long n = i - prevInd;
count += (n * (n+1)) / 2L;
prevInd = i+1;
count -= (smaller * (smaller+1)) / 2;
smaller = 0;
}
else {
count -= (smaller * (smaller+1)) / 2;
smaller = 0;
}
if (i == A.size()-1) {
long n = A.size() - prevInd;
count += (n * (n+1)) / 2L;
count -= (smaller * (smaller+1)) / 2;
}
}
return count;
}
};
| true |
26dc3aa501817e1144c0ac4b85d7059fc7f54a62 | C++ | Donione/Hedgehog | /Hedgehog/Include/Animation/Segment.h | UTF-8 | 1,543 | 2.71875 | 3 | [] | no_license | #pragma once
#include <Component/Transform.h>
#include <string>
#include <vector>
#include <glm/gtc/quaternion.hpp>
namespace Hedge
{
struct KeyPosition
{
float timeStamp;
glm::vec3 position;
};
struct KeyRotation
{
float timeStamp;
glm::quat rotation;
};
struct KeyScale
{
float timeStamp;
glm::vec3 scale;
};
struct KeyTransform
{
float timeStamp;
glm::mat4 transform;
};
class Segment
{
public:
Segment(const std::string& name, int ID) : name(name), ID(ID) {}
int GetID() const { return ID; }
const std::string& GetName() const { return name; }
const Transform GetTransform(float timeStamp) const;
const glm::mat4 GetTransformMatrix(float timeStamp) const;
private:
const glm::vec3 GetTranslation(float timeStamp) const;
const glm::quat GetRotation(float timeStamp) const;
const glm::vec3 GetScale(float timeStamp) const;
template <typename T>
int GetIndex(float timeStamp, const std::vector<T>& elements) const
{
for (auto it = elements.begin(); it != elements.end(); ++it)
{
if (timeStamp < it->timeStamp)
{
return (int)std::distance(elements.begin(), it) - 1;
}
}
return -1;
}
float GetInterpolant(float start, float end, float now) const;
public:
glm::mat4 offset{1.0f};
std::vector<KeyPosition> keyPositions;
std::vector<KeyRotation> keyRotations;
std::vector<KeyScale> keyScales;
std::vector<KeyTransform> keyTransforms;
private:
std::string name;
int ID;
};
} // namespace Hedge
| true |
1af8362eec1c1cfba1ba33aab377d427b26415b5 | C++ | antaljanosbenjamin/ch24-huncup | /solutions/sms/main.cpp | UTF-8 | 4,096 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
//properly calcute for any input, but print out the possible output only for one button
using namespace std;
int MODULO = 1000007;
// modify this array to watch the output with one button, eg. for 7:
char chars[] = {'p', 'q', 'r', 's', 'p', 'q', 'r', 's', 'p', 'q', 'r', 's'};
// eg. for 2:
//char chars[] = {'a','b','c','a','b','c','a','b','c','a','b','c'};
int repeats[] = {-1, 1, 3, 3, 3, 3, 3, 4, 3, 4};
vector<vector<string>> possibilities;
vector<vector<int>> possibleCount;
void initPossibleCount() {
vector<int> zero;
vector<int> one;
for (int i = 0; i <= 50; i++)
one.push_back(1);
vector<int> two;
possibleCount.push_back(zero);
possibleCount.push_back(one);
possibleCount.push_back(two);
for (int repeat = 3; repeat <= 4; repeat++) {
int length = 50;
vector<int> actualCount;
actualCount.push_back(1);
for (int i = 1; i <= length; i++) {
int count = 0;
for (int j = 0; (j < repeat) && (i - j > 0); j++) {
count += actualCount[i - j - 1];
count %= MODULO;
}
if (i > repeat)
count++;
actualCount.push_back(count % MODULO);
//cout << i << ".:" << count << endl;
}
possibleCount.push_back(actualCount);
}
}
int main(int argc, char *args) {
initPossibleCount();
string input = "./";
string output = "./M";
input += "10.in";
output += "10.out";
/*for (int i = 1; i <= 4; i++){
cout << i << ". : ";
for(int j = 0; j < possibleCount[i].size();j++){
cout << possibleCount[i][j] << " ";
}
cout << endl;
}*/
string sms;
std::ifstream f(input);
f >> sms;
char last = sms[0];
char length = 1;
vector<int> possibleSequence;
for (int i = 1; i < sms.size(); i++) {
char actual = sms[i];
if (actual == last) {
length++;
} else {
int button = last - '0';
int possibleCounttt = possibleCount[repeats[button]][length];
//cout << possibleCounttt;
possibleSequence.push_back(possibleCounttt);
length = 1;
last = actual;
}
}
int button = last - '0';
int possibleCounttt = possibleCount[repeats[button]][length];
//cout << possibleCounttt << " ";
possibleSequence.push_back(possibleCounttt);
unsigned long long int product = possibleSequence[0];
for (int i = 1; i < possibleSequence.size(); i++) {
product = (product * possibleSequence[i]) % MODULO;
}
std::ofstream o(output, std::ios::out);
cout << product;
o << product;
o.close();
return 0;
}
int main2() {
int repeat = 4;
int length = 10;
vector<string> zero;
zero.push_back("");
possibilities.push_back(zero);
for (int i = 1; i <= length; i++) {
vector<string> actual;
for (int j = 0; j < repeat && i - j > 0; j++) {
for (int k = 0; k < possibilities[i - j - 1].size(); k++) {
if (possibilities[i - j - 1][k][0] != '-')
actual.push_back(possibilities[i - j - 1][k] + chars[j]);
}
}
for (int j = repeat; j < i - 1; j++) {
for (int k = 0; k < possibilities[i - j - 1].size(); k++) {
if (possibilities[i - j - 1][k][0] != '-') {
string newString = possibilities[i - j - 1][k] + chars[j];
if (std::count(actual.begin(), actual.end(), newString) != 1) {
cout << endl << "HIBA" << endl;
}
}
}
}
if (i > repeat)
actual.push_back(string("") + chars[(i - 1) % repeat]);
cout << endl << i << ".: ";
for (int j = 0; j < actual.size(); j++)
cout << actual[j] << ", ";
cout << "size: " << actual.size() << endl;
possibilities.push_back(actual);
}
return 0;
} | true |
cb812eda13265977723e7776ab0e60c9f6b1a07e | C++ | kyelin/ClanLib | /Sources/API/Scene3D/ModelData/model_data_animation_timeline.h | UTF-8 | 2,794 | 2.59375 | 3 | [
"Zlib"
] | permissive | /*
** ClanLib SDK
** Copyright (c) 1997-2013 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#pragma once
#include "../../Core/Math/cl_math.h"
namespace clan
{
/// \brief A list of time stamps and the values to be used for each.
template<typename Type>
class ModelDataAnimationTimeline
{
public:
std::vector<float> timestamps;
std::vector<Type> values;
Type get_value(float timestamp) const
{
size_t index, index2;
float t = find_animation_indices(timestamp, index, index2);
return mix(values[index], values[index2], t);
}
float find_animation_indices(float timestamp, size_t &index, size_t &index2) const
{
if (timestamps.empty())
{
index = 0;
index2 = 0;
return 0.0f;
}
index = binary_search(timestamp);
index2 = min(index + 1, timestamps.size() - 1);
float start = timestamps[index];
float end = timestamps[index2];
if (start != end)
return clamp((timestamp - start) / (end - start), 0.0f, 1.0f);
else
return 0.0f;
}
private:
size_t binary_search(float timestamp) const
{
size_t imin = 0;
size_t imax = timestamps.size() - 1;
while (imin < imax)
{
size_t imid = imin + (imax - imin) / 2;
if (timestamps[imid] > timestamp)
imax = imid;
else
imin = imid + 1;
}
if (imin < timestamps.size() - 1)
return imin - 1;
else
return imin;
}
};
template<>
inline Quaternionf ModelDataAnimationTimeline<Quaternionf>::get_value(float timestamp) const
{
size_t index, index2;
float t = find_animation_indices(timestamp, index, index2);
return Quaternionf::lerp(values[index], values[index2], t);
}
template<>
inline Mat4f ModelDataAnimationTimeline<Mat4f>::get_value(float timestamp) const
{
size_t index, index2;
float t = find_animation_indices(timestamp, index, index2);
return values[index];
}
}
| true |
68cf60aaa01b761e2261413e6a06a63befd66036 | C++ | AlvaroVargasM/Scrabble | /Server/Logic/Node.h | UTF-8 | 492 | 2.859375 | 3 | [] | no_license | #ifndef QUEUE_USING_OOP_NODE_H
#define QUEUE_USING_OOP_NODE_H
/**+
* Node class for beaing used in the link list, it stores data similar to a Tile.
*/
class Node {
private:
char l;
Node *next;
int pts;
int i;
int j;
public:
Node(char letter,int row,int columns,int points);
char getL() const;
Node *getNext() const;
void setNext(Node *next);
int getPts() const;
int getI() const;
int getJ() const;
};
#endif //QUEUE_USING_OOP_NODE_H
| true |
5565d630bed12c18ac6d0edacbe1f9d6583fedbd | C++ | Ing-Josef-Klotzner/python | /_bob_and_the_minimum_string.cpp | UTF-8 | 862 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <stack>
#include <vector>
using namespace std;
int main () {
ios_base :: sync_with_stdio (false);
cin.tie (NULL); cout.tie (NULL);
int t, i, it;
cin >> t;
while (t--){
int n;
string s, re;
cin >> n >> s;
vector <int> mp (123, 0);
for (i = 0; i < n; ++i) mp [s [i]]++;
it = 97;
stack <char> st;
i = 0;
while (i < n){
mp [s [i]]--;
st.push (s [i]);
while (it < 123 and mp [it] <= 0) it++;
while (st.size () and it >= st.top ())
re += string (1, st.top ()), st.pop ();
i++;
}
while (st.size ()){
re += string (1, st.top ());
st.pop ();
}
cout << re << endl;
}
return 0;
} | true |
0fce2aa17112e28a6cc10590a55d53cf6652b730 | C++ | isaponsoft/libamtrs | /include/amtrs/chrono/.inc-chrono/chrono-functions.hpp | UTF-8 | 2,007 | 2.609375 | 3 | [
"BSD-2-Clause"
] | permissive | /* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *
* Use of this source code is governed by a BSD-style license that *
* can be found in the LICENSE file. */
#ifndef __libamtrs__functions__hpp
#define __libamtrs__functions__hpp
AMTRS_CHRONO_NAMESPACE_BEGIN
using time_t = std::time_t; // 64bit以上の time_tを使用する。
inline struct tm gmtime(time_t _t)
{
return *std::gmtime(&_t);
}
inline struct tm localtime(time_t _t)
{
static thread_local struct tm r;
static thread_local time_t t = 0;
if (t != _t)
{
t = _t;
r = *std::localtime(&t);
}
return r;
}
// ============================================================================
//! 閏年かどうか調べる。
// ----------------------------------------------------------------------------
constexpr bool isleap(int _year) noexcept
{
return (((_year % 400) == 0) || (((_year % 4) == 0) && ((_year % 100) != 0)))
? true
: false;
}
// ============================================================================
//! 各月のmdayを返す
// ----------------------------------------------------------------------------
constexpr int last_mday(int _year, int _mon) noexcept
{
constexpr int mday[2][12] =
{
{31,29,31,30,31,30,31,31,30,31,30,31}, // leap
{31,28,31,30,31,30,31,31,30,31,30,31} // no leap
};
return mday[isleap(_year) ? 0 : 1][_mon];
}
// ============================================================================
//! 時間を文字列に変換する。
// ----------------------------------------------------------------------------
//! format: http://en.cppreference.com/w/cpp/io/manip/put_time
// ----------------------------------------------------------------------------
template<class Clock, class Duration>
inline std::string format(const char* _format, std::chrono::time_point<Clock, Duration> _time)
{
return format(_format, std::chrono::system_clock::to_time_t(_time));
}
AMTRS_CHRONO_NAMESPACE_END
#endif
| true |
64acd696651f8a58a686c32e99e403c50efc5b58 | C++ | cbrghostrider/Hacking | /leetcode/_001216_validPalindromIII_TopDown_DP_TLE.cpp | UTF-8 | 2,118 | 3.109375 | 3 | [
"MIT"
] | permissive | class Solution {
// memoization cache
unordered_map<string, bool> cache;
// creates a memoization key for the subproblem
string signature(const unordered_set<int>& removed, int next, int k) {
string ret;
ret += "K:" + to_string(k) + ":";
ret += "N:" + to_string(next) + ":";
for (int r : removed) {
ret += to_string(r) + ":";
}
return ret;
}
// Is string s, with positions "removed" removed, a palindrome?
bool isPalin(const string& s, const unordered_set<int>& removed) {
int left=0, right=s.size()-1;
auto forwardLeft = [&left, &s, &removed]() {
while (left < s.size() && removed.find(left) != removed.end()) {left++;}
};
auto reverseRight = [&right, &s, &removed]() {
while (right >= 0 && removed.find(right) != removed.end()) {right--;}
};
forwardLeft();
reverseRight();
while (left < right) {
if (s[left] != s[right]) return false;
left++; forwardLeft();
right--; reverseRight();
}
return true;
}
// Is s, with "removed" positions removed, a k palindrome
bool isValid(const string& s, unordered_set<int> removed, int next, int k) {
string sig = signature(removed, next, k);
if (cache.find(sig) != cache.end()) {return cache[sig];}
if (next == s.size() || k == 0) {
cache[sig] = isPalin(s, removed);
return cache[sig];
}
// keep next
bool choice1 = isValid(s, removed, next+1, k);
// drop next
removed.insert(next);
bool choice2 = isValid(s, removed, next+1, k-1);
cache[sig] = choice1 || choice2;
return cache[sig];
}
public:
//
// Solution is functionally correct, but runs into TLE for bigger inputs.
//
bool isValidPalindrome(string s, int k) {
bool ans = isValid(s, {}, 0, k);
return ans;
}
};
| true |
f9a00765d3aaaaaa43a7a4679b3bd2c9e45c63bd | C++ | MatthewDaws/CPP_Learning | /prime_sieve/sieve.tpp | UTF-8 | 11,730 | 3.703125 | 4 | [] | no_license | /** @file: sieve.tpp
* @author: Matthew Daws
*
* Some Prime Sieve (aka Sieve of Eratosthenes) code.
* Lots of templates (quite plausible to use 64-bit integers; but this is a waste
* of memory if `unsigned int` is enough for you).
*/
#ifndef __SIEVE_TPP
#define __SIEVE_TPP
#include <vector>
#include <cmath>
#include <iostream>
using std::cout;
using std::endl;
// --------------------------------------------------------------------------
// class sieve<T> code
// --------------------------------------------------------------------------
/** Prime Sieve
* We use a std::vector<bool> and skip evens, so the mapping is
* 0->3, 1->5, 2->7, n->3+n+n
*
* type T just needs to be large enough to express the maximum prime; so int is
* probably fine.
*/
template <typename T>
class sieve {
public:
sieve(const T len);
bool is_prime(const T p)const;
std::vector<bool>& get_sieve() { return psieve; }
private:
std::vector<bool> psieve;
T length;
};
/** Lookup in the sieve to test if prime */
template <typename T>
bool sieve<T>::is_prime(const T p)const
{
if ( p <= 1 or (p%2) == 0 or p > length ) { return false; }
return psieve[ (p-3)/2 ];
}
/** Constructor which also makes the sieve */
template <typename T>
sieve<T>::sieve(const T len)
: length{len}
{
psieve.resize((length-3)/2+1,true);
T limit = sqrt(length);
T prime = 3;
while ( prime <= limit ) {
//for (T x = prime*prime; x<=length; x+=prime+prime) {
// psieve[(x-3)/2] = false;
//}
// This is equivalent, but some assembler staring suggests gets optimised
// better by the compiler.
for (T x = (prime*prime-3)/2; x<=(length-3)/2; x+=prime) {
psieve[x] = false;
}
prime += 2;
while ( prime<limit and psieve[(prime-3)/2]==false ) { prime+=2; }
}
}
// --------------------------------------------------------------------------
/** Returns a list of primes up to and including `len`
* Uses class sieve internally.
*/
template <typename T>
std::vector<T> prime_list(const T len)
{
sieve<T> s(len);
std::vector<T> primes;
primes.push_back(2);
for (T p=3; p<=len; p+=2) {
if ( s.is_prime(p) ) { primes.push_back(p); }
}
return primes;
}
// --------------------------------------------------------------------------
/** Returns a list of primes up to and including `len`
* Variant of above: constructs a small list of primes and then builds the rest of
* the sieve using this.
* Little more than a proof of concept, as the next class does the same but with much
* more control.
*/
template <typename T>
std::vector<T> prime_list1(const T len)
{
if ( len < 10 ) { return prime_list(len); }
// Get a list of primes of size sqrt(len)
T sqrt_len = sqrt(len);
if ( sqrt_len * sqrt_len < len ) { ++sqrt_len; }
auto primes = prime_list(sqrt_len);
// Now re-create the rest of the sieve
std::vector<bool> sieve(len/2,true);
T start = sqrt_len + 1 - (sqrt_len%2); // If even add one
// Mapping is start->0, start+2->1, start+4->2 etc.
for (auto it = primes.begin() + 1; it != primes.end(); ++it) {
auto p = *it;
T ps = start + p - 1;
ps = ps - (ps % p); // Now ps is the smallest multiple of p which is >= start
if ( (ps%2)==0 ) { ps+=p; } // Ensure ps not even
/*for (T pp = ps; pp <= len; pp += p + p) {
sieve[ (pp-start)/2 ] = false;
}*/
for (T pp = (ps-start)/2; pp <= (len-start)/2; pp += p) {
sieve[ pp ] = false;
}
}
// Add to list
/*for (T p=start; p<=len; p+=2) {
if ( sieve[ (p-start)/2 ] ) { primes.push_back(p); }
}*/
for (T p=0; p<=(len-start)/2; ++p) {
if ( sieve[ p ] ) { primes.push_back(start + p + p); }
}
return primes;
}
// --------------------------------------------------------------------------
/** Same as previous version, but now we've split the sieve creation into a separate routine,
* which can be called on an arbitrary range.
* The constructor parameter `len` is now the maximum initial prime to find; so the
* sieve can ultimately be constructed up to size `len*len`.
*/
template <typename T>
class prime_sieve_list {
public:
prime_sieve_list(const T len);
std::vector<T> primes;
std::vector<bool> partial_sieve(T start, T end)const;
std::vector<bool> partial_sieve(T start, T end, T stripe_size)const;
std::vector<T> sieve_to_list(T start, std::vector<bool> sieve)const;
void sieve_to_list_pushback(T start, std::vector<bool> sieve, std::vector<T> &l)const;
inline std::vector<T> primes_range(T start, T end)const
{ return sieve_to_list(start, partial_sieve(start,end)); }
void primes_range_pushback(T start, T end, T stripe_size, std::vector<T> &vec)const;
};
/** Constructor: make and store a small list of primes. */
template <typename T>
prime_sieve_list<T>::prime_sieve_list(const T len)
{
primes = prime_list(len);
}
/** Constructs a partial sieve. Assumes start > len
* If start is even it's increased, and then index 0 of the returned vector corresponds to
* start, index 1 to start+2, and so forth
*/
template <typename T>
std::vector<bool> prime_sieve_list<T>::partial_sieve(T start, T end)const
{
start += 1 - (start%2); // Increase, if necessary, to make odd
if ( start > end ) { return std::vector<bool>(0); }
std::vector<bool> sieve((end-start)/2+1,true);
for (auto it = primes.begin()+1; it != primes.end(); ++it) {
auto p = *it;
T ps = start + p - 1;
ps = ps - (ps % p);
if ( (ps%2)==0 ) { ps += p; } // ps smallest odd multiple of p greater than or equal to start
/*for (T pp=ps; pp<=end; pp+=p+p) {
sieve[ (pp-start)/2 ] = false;
}*/
for (T pp=(ps-start)/2; pp<=(end-start)/2; pp+=p) {
sieve[ pp ] = false;
}
}
return sieve;
}
/** As above, but does in chunks of stripe_size.
*/
template <typename T>
std::vector<bool> prime_sieve_list<T>::partial_sieve(T start, T end, T stripe_size)const
{
start += 1 - (start%2); // Increase, if necessary, to make odd
if ( start > end ) { return std::vector<bool>(0); }
std::vector<bool> sieve((end-start)/2+1,true);
for (T stripe_start = start; stripe_start <= end; stripe_start += stripe_size) {
T stripe_end = stripe_start + stripe_size - 1;
if ( stripe_end > end ) { stripe_end = end; }
for (auto it = primes.begin()+1; it != primes.end(); ++it) {
auto p = *it;
T ps = stripe_start + p - 1;
ps = ps - (ps % p);
if ( (ps%2)==0 ) { ps += p; } // ps smallest odd multiple of p greater than or equal to stripe_start
for (T pp = (ps-start)/2; pp <= (stripe_end-start)/2; pp += p) {
sieve[pp] = false;
}
}
}
return sieve;
}
/** Use a sieve to make a list of primes. If start is even it's increased to make it odd.
*/
template <typename T>
std::vector<T> prime_sieve_list<T>::sieve_to_list(T start, std::vector<bool> sieve)const
{
std::vector<T> prange;
sieve_to_list_pushback(start, sieve, prange);
return prange;
}
/** Same as sieve_to_list but uses passed vector.
*/
template <typename T>
void prime_sieve_list<T>::sieve_to_list_pushback(T start, std::vector<bool> sieve, std::vector<T> &vec)const
{
start += 1 - (start%2); // Increase, if necessary, to make odd
T p = start;
for (auto it = sieve.begin(); it != sieve.end(); ++it, p+=2) {
if ( *it ) { vec.push_back(p); }
}
}
/** Split the task into blocks of size stripe_size; hope to get a better play with cache.
*/
template <typename T>
void prime_sieve_list<T>::primes_range_pushback(T start, T end, T stripe_size, std::vector<T> &vec)const
{
for (T s = start; s <= end; s += stripe_size) {
T e = s + stripe_size - 1;
if ( e > end ) { e = end; }
sieve_to_list_pushback(s, partial_sieve(s,e), vec);
}
}
// --------------------------------------------------------------------------
/** This class prioritises finding the sieve, and allows the computation of arbitrary
* subsections, with a view to multi-threading
*/
template <typename T>
class sieve_stripe {
public:
sieve_stripe(const T len);
bool is_prime(const T p)const;
void compute_section(T start, T end);
std::vector<T> prime_list()const;
std::vector<bool> sieve;
private:
T length;
std::vector<T> smallprimes;
};
template <typename T>
sieve_stripe<T>::sieve_stripe(const T len)
: length{len}, sieve((len-1)/2, true)
{
// Find small primes
T sqrt_len = sqrt(len);
if ( sqrt_len * sqrt_len < len ) { ++sqrt_len; }
prime_sieve_list<T> pl(sqrt_len);
smallprimes = std::move(pl.primes);
}
template <typename T>
bool sieve_stripe<T>::is_prime(const T p)const
{
if ( p==2 ) { return true; }
if ( p<=1 or (p%2)==0 or p>length ) { return false; }
return sieve[ (p-3)/2 ];
}
template <typename T>
void sieve_stripe<T>::compute_section(T start, T end)
{
if ( start < 3 ) { start = 3; }
start += 1 - (start%2); // Ensure odd
if ( end > length ) { end = length; }
if ( start > end ) { return; }
T endcache = (end-3)/2;
if ( start < smallprimes.back()*smallprimes.back() ) {
for (auto it = smallprimes.begin()+1; it != smallprimes.end(); ++it) {
auto p = *it;
T ps = start + p - 1;
ps = ps - (ps % p);
if ( (ps%2)==0 ) { ps += p; } // ps smallest odd multiple of p greater than or equal to start
if ( ps < p*p ) { ps = p*p; }
for (T pp = (ps-3)/2; pp <= endcache; pp += p) {
sieve[pp] = false;
}
}
return;
}
for (auto it = smallprimes.begin()+1; it != smallprimes.end(); ++it) {
auto p = *it;
T ps = start + p - 1;
ps = ps - (ps % p);
if ( (ps%2)==0 ) { ps += p; } // ps smallest odd multiple of p greater than or equal to start
for (T pp = (ps-3)/2; pp <= endcache; pp += p) {
sieve[pp] = false;
}
}
}
template <typename T>
std::vector<T> sieve_stripe<T>::prime_list()const
{
std::vector<T> primes;
primes.push_back(2);
T p = 3;
for (auto it = sieve.begin(); it != sieve.end(); ++it, p+=2) {
if ( *it ) { primes.push_back(p); }
}
return primes;
}
// --------------------------------------------------------------------------
/** Actually find a full list using prime_sieve_list.
*/
template <typename T>
std::vector<T> prime_list2(const T len)
{
if ( len<10 ) { return prime_list(len); }
T sqrt_len = sqrt(len);
if ( sqrt_len * sqrt_len < len ) { ++sqrt_len; }
prime_sieve_list<T> pl(sqrt_len);
std::vector<T> primes = pl.primes;
pl.sieve_to_list_pushback(sqrt_len+1, pl.partial_sieve(sqrt_len+1,len), primes);
return primes;
}
/** Actually find a full list using prime_sieve_list.
* This version allows control of the stripe size: this is the size of the vector<bool>
*/
template <typename T>
std::vector<T> prime_list2(const T len, const T size)
{
if ( len<10 ) { return prime_list(len); }
T sqrt_len = sqrt(len);
if ( sqrt_len * sqrt_len < len ) { ++sqrt_len; }
prime_sieve_list<T> pl(sqrt_len);
std::vector<T> primes = pl.primes;
pl.primes_range_pushback(sqrt_len+1, len, size, primes);
return primes;
}
/** Version which computes the whole sieve at once, using a stripe size.
*/
template <typename T>
std::vector<T> prime_list3(const T len, const T size)
{
if ( len<10 ) { return prime_list(len); }
T sqrt_len = sqrt(len);
if ( sqrt_len * sqrt_len < len ) { ++sqrt_len; }
prime_sieve_list<T> pl(sqrt_len);
std::vector<T> primes = pl.primes;
pl.sieve_to_list_pushback(sqrt_len+1, pl.partial_sieve(sqrt_len+1, len, size), primes);
return primes;
}
/** Various testing routines */
/** Tests that prime_list returns correctly */
bool test1();
/** Tests that prime_list and prime_list1 return the same lists */
bool test2();
/** Tests that prime_list and prime_list2 return the same lists */
bool test3();
/** Tests that prime_list and prime_list2(...,stripe_size) return the same lists */
bool test4();
/** Tests that prime_list and prime_list3 return the same lists */
bool test5();
/** Tests that prime_list and class sieve_stripe return the same lists */
bool test6();
#endif // __SIEVE_TPP
| true |
acf218801359a7f1941b7aa08d18eecd32487ca5 | C++ | SadMathLovergo/LeetCodeSolution | /274hIndex/274hIndex.cpp | GB18030 | 840 | 3.390625 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
bool myLess(int m, int n) {
return m > n;
}
//274⣺Hָ
//˼·鰴Уҵcitations[num]ʹõi < numʱcitations[i] >= numi > = numʱcitations[i] < numnumΪHָ
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end(), myLess);
int i = 0;
while (i < citations.size() && citations[i] >= i + 1)
i++;
return i;
}
};
int main() {
vector<int> citations{ 230,217,203,120,50,177,118,236,209,98,156,15,126,4,15,113,49,173,25,88,115,73,46,152,64,47,160,111,194,119,234,72,79,89,37,14,31,15,21,77,246,192,230,53,14,200,190,40,74,227 };
cout << Solution().hIndex(citations) << endl;
system("pause");
return 0;
} | true |
bbdff7bfa6e27b0cc1bbed6704e643503f69dce7 | C++ | PhilipNelson5/AdventOfCode | /2018/1/1/main.cpp | UTF-8 | 294 | 2.890625 | 3 | [] | no_license | #include <fstream>
#include <iostream>
int main()
{
int frequ = 0;
int input;
std::ifstream fin("input.txt");
if (!fin)
{
std::cout << "bad file" << std::endl;
exit(EXIT_FAILURE);
}
while (fin >> input)
{
frequ += input;
}
std::cout << frequ << std::endl;
}
| true |
38232b833f56be70f1d6dc32a26c3ae57071ade1 | C++ | alchemz/CPlusPlusTraining | /review/copyConstuctor.cpp | UTF-8 | 552 | 4.09375 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Animal {
private:
string name;
public:
Animal() { cout << "1 Animal created" << endl; };
Animal(const Animal& other) :name(other.name) { cout << "2 Animal created by copy" << endl; };
void setName(string name) { this->name = name; };
void speak() const {
cout << "My name is " << name << endl;
}
};
int main() {
Animal animal1;
animal1.setName("Freddy");
Animal animal2;
animal2.setName("Bob");
animal1.speak();
animal2.speak();
Animal animal3(animal1);
return 0;
}
| true |
a6f195ed713b036d42cad2cffc036e818142d959 | C++ | Mohit21/Questions | /AmazonRohitSubarraySUm.cpp | UTF-8 | 889 | 2.703125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int lSum(int A[],int N,int sum){
int tSum=0,maxlen=0;
for(int i=0;i<N;i++){
tSum+=A[i];
}
if(sum==tSum){
maxlen=N;
return maxlen;
}
else{
tSum=0;
for(int i=0;i<N;i++){
tSum=A[i];
for(int j=i+1;j<N;j++){
if(tSum==sum){
if((maxlen)<(j-i)){
maxlen=(j-i);
}
}
tSum+=A[j];
}
}
if(maxlen==0){
return -1;
}
else{
return (maxlen);
}
}
}
int main(){
/*int A[]={7,3,4,1,10};
int N=sizeof(A)/sizeof(A[0]);
int sum=2;
*/
int N,sum;
cin>>N;
int A[N];
for(int i=0;i<N;i++){
cin>>A[i];
}
cin>>sum;
cout<<lSum(A,N,sum)<<endl;
return 0;
}
| true |
090f56608215db8de945eae7d86c1e39b0715933 | C++ | Dipet/dldt | /inference-engine/tests/unit/engines/vpu/containers_tests.cpp | UTF-8 | 6,492 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | // Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <algorithm>
#include <chrono>
#include <iostream>
#include <unordered_map>
#include <memory>
#include <gtest/gtest.h>
#include <vpu/utils/containers.hpp>
#include <vpu/utils/range.hpp>
#include <vpu/utils/handle.hpp>
using namespace testing;
TEST(VPU_SmallVectorTests, SimpleUsage) {
std::vector<int> vec1;
vpu::SmallVector<int, 5> vec2;
for (size_t i = 0; i < 5; ++i) {
vec1.push_back(i);
vec2.push_back(i);
}
for (size_t i = 0; i < vec1.size(); ++i) {
ASSERT_EQ(vec1.at(i), vec2.at(i));
}
vec1.clear();
vec2.clear();
for (size_t i = 0; i < 5; ++i) {
vec1.push_back(i);
}
vec2.insert(vec2.end(), vec1.begin(), vec1.end());
auto it1 = std::find(vec1.begin(), vec1.end(), 2);
auto it2 = std::find(vec2.begin(), vec2.end(), 2);
ASSERT_NE(it1, vec1.end());
ASSERT_NE(it2, vec2.end());
vec1.erase(it1);
vec2.erase(it2);
for (size_t i = 0; i < vec1.size(); ++i) {
ASSERT_EQ(vec1.at(i), vec2.at(i));
}
vec1.push_back(15);
vec1.push_back(16);
vec2.push_back(15);
vec2.push_back(16);
for (size_t i = 0; i < vec1.size(); ++i) {
ASSERT_EQ(vec1.at(i), vec2.at(i));
}
}
TEST(VPU_SmallVectorTests, Equal) {
vpu::SmallVector<int, 5> vec1;
vpu::SmallVector<int, 5> vec2;
vpu::SmallVector<int, 5> vec3;
for (size_t i = 0; i < 5; ++i) {
vec1.push_back(i);
vec2.push_back(i);
vec3.push_back(i + 1);
}
ASSERT_EQ(vec1, vec2);
ASSERT_NE(vec1, vec3);
}
TEST(VPU_SmallVectorTests, Swap) {
vpu::SmallVector<int, 5> vec1;
vpu::SmallVector<int, 5> vec2;
for (size_t i = 0; i < 5; ++i) {
vec1.push_back(i);
vec2.push_back(5 - i);
}
vec1.swap(vec2);
for (size_t i = 0; i < 5; ++i) {
ASSERT_EQ(vec1[i], 5 - i);
ASSERT_EQ(vec2[i], i);
}
}
namespace {
struct TestStruct final : public vpu::EnableHandle {
int val = 0;
vpu::IntrusiveHandleListNode<TestStruct> node1;
vpu::IntrusiveHandleListNode<TestStruct> node2;
explicit TestStruct(int val) : val(val), node1(this), node2(this) {}
};
}
TEST(VPU_IntrusiveHandleListTest, SimpleUsage) {
const int count = 5;
int gold = 0;
std::vector<std::shared_ptr<TestStruct>> base;
for (int i = 0; i < count; ++i) {
base.push_back(std::make_shared<TestStruct>(i));
}
vpu::IntrusiveHandleList<TestStruct> list1(&TestStruct::node1);
vpu::IntrusiveHandleList<TestStruct> list2(&TestStruct::node2);
for (int i = 0; i < count; ++i) {
list1.push_back(base[i]);
}
ASSERT_FALSE(list1.empty());
ASSERT_TRUE(list2.empty());
gold = 0;
for (const auto& ptr1 : list1) {
ASSERT_NE(ptr1, nullptr);
ASSERT_EQ(ptr1->val, gold);
ASSERT_EQ(ptr1.get(), base[ptr1->val].get());
++gold;
}
ASSERT_EQ(gold, count);
for (int i = 0; i < count / 2; ++i) {
list2.push_back(base[i]);
}
ASSERT_FALSE(list2.empty());
gold = 0;
for (const auto& ptr2 : list2) {
ASSERT_NE(ptr2, nullptr);
ASSERT_EQ(ptr2->val, gold);
ASSERT_EQ(ptr2.get(), base[ptr2->val].get());
list1.erase(ptr2);
++gold;
}
ASSERT_EQ(gold, count / 2);
gold = count / 2;
for (const auto& ptr1 : list1) {
ASSERT_NE(ptr1, nullptr);
ASSERT_EQ(ptr1->val, gold);
ASSERT_EQ(ptr1.get(), base[ptr1->val].get());
++gold;
}
ASSERT_EQ(gold, count);
}
TEST(VPU_IntrusiveHandleListTest, MoveFromOneListToAnother) {
const int count = 5;
std::list<std::shared_ptr<TestStruct>> base;
vpu::IntrusiveHandleList<TestStruct> list1(&TestStruct::node1);
vpu::IntrusiveHandleList<TestStruct> list2(&TestStruct::node1);
for (int i = 0; i < count; ++i) {
auto ptr = std::make_shared<TestStruct>(i);
base.push_back(ptr);
list1.push_back(ptr);
}
ASSERT_EQ(list1.size(), base.size());
ASSERT_TRUE(list2.empty());
for (const auto& item : list1) {
list1.erase(item);
list2.push_back(item);
}
ASSERT_TRUE(list1.empty());
ASSERT_EQ(list2.size(), base.size());
}
TEST(VPU_IntrusiveHandleListTest, ReleaseOrigObject) {
const int count = 5;
int gold = 0;
std::list<std::shared_ptr<TestStruct>> base;
vpu::IntrusiveHandleList<TestStruct> list(&TestStruct::node1);
for (int i = 0; i < count; ++i) {
auto ptr = std::make_shared<TestStruct>(i);
base.push_back(ptr);
list.push_back(ptr);
}
ASSERT_EQ(list.size(), base.size());
base.pop_front();
ASSERT_EQ(list.size(), base.size());
base.pop_back();
ASSERT_EQ(list.size(), base.size());
list.clear();
ASSERT_TRUE(list.empty());
gold = 0;
for (const auto& item : base) {
ASSERT_EQ(item->val, gold + 1);
++gold;
}
ASSERT_EQ(gold, count - 2);
}
TEST(VPU_IntrusiveHandleListTest, ReverseIter) {
const int count = 5;
int gold = 0;
std::vector<std::shared_ptr<TestStruct>> base;
for (int i = 0; i < count; ++i) {
base.push_back(std::make_shared<TestStruct>(i));
}
vpu::IntrusiveHandleList<TestStruct> list(&TestStruct::node1);
for (int i = 0; i < count; ++i) {
list.push_back(base[i]);
}
gold = count - 1;
for (auto it = list.rbegin(); it != list.rend(); ++it) {
auto ptr = *it;
ASSERT_NE(ptr, nullptr);
ASSERT_EQ(ptr->val, gold);
ASSERT_EQ(ptr.get(), base[ptr->val].get());
--gold;
}
ASSERT_EQ(gold, -1);
}
TEST(VPU_IntrusivePtrListTest, IteratorCopyAndMove) {
const int count = 5;
int gold = 0;
std::vector<std::shared_ptr<TestStruct>> base;
for (int i = 0; i < count; ++i) {
base.push_back(std::make_shared<TestStruct>(i));
}
vpu::IntrusiveHandleList<TestStruct> list(&TestStruct::node1);
for (int i = 0; i < count; ++i) {
list.push_back(base[i]);
}
ASSERT_FALSE(list.empty());
gold = 0;
for (auto it1 = list.begin(); it1 != list.end(); ++it1) {
ASSERT_EQ((*it1)->val, gold);
auto it2 = it1; // Copy
ASSERT_EQ((*it2)->val, gold);
auto it3 = std::move(it2);
ASSERT_EQ((*it3)->val, gold);
ASSERT_EQ(it2, list.end());
++gold;
}
ASSERT_EQ(gold, count);
}
| true |
383259c290afc995bd89ba0b62e7774e2ec5be83 | C++ | jamesnguyen30/uh-cosc | /os/assignment2/server.cpp | UTF-8 | 6,592 | 3 | 3 | [] | no_license | #include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sstream>
#define NUM_OCTETS 4
#define NUM_ADDRESS 6
using namespace std;
void error(string msg){
perror(msg.c_str());
exit(0);
}
struct request_package{
uint8_t ip[NUM_OCTETS];
uint8_t subnet[NUM_OCTETS];
};
struct response_package{
uint8_t ip[NUM_OCTETS];
uint8_t subnet[NUM_OCTETS];
uint8_t network[NUM_OCTETS];
uint8_t broadcast[NUM_OCTETS];
uint8_t hostmin[NUM_OCTETS];
uint8_t hostmax[NUM_OCTETS];
int num_host;
};
struct message{
int option;
int account;
double amount;
};
struct message2{
int value;
char buffer[256];
};
void convert_to_int_array(const std::string& str, uint8_t * container, char delim = '.')
{
std::stringstream ss(str);
std::string token;
int index = 0;
while (std::getline(ss, token, delim)) {
int number = stoi(token);
container[index++]= (uint8_t)number ;
}
}
int8_t get_min_host(uint8_t network, uint8_t & min_host){
// Returns a carry if there is
if(network == 255){
min_host=0;
return 1;
} else {
min_host =network + 1;
return 0;
}
}
int8_t get_max_host(uint8_t broadcast, uint8_t & max_host){
// Returns a carry if there is
if(broadcast == 0){
max_host=255;
return -1;
} else {
max_host = broadcast - 1;
return 0;
}
}
int count_zero_bits(const uint8_t n){
uint8_t count_1 = 0;
uint8_t temp = n;
while(temp){
count_1 += temp & 1;
temp >>= 1;
}
int count_0 = 8 - count_1;
return count_0;
}
int calculate_number_of_hosts(const uint8_t num_of_zeros){
int number_of_hosts = pow(2, num_of_zeros) - 2;
return number_of_hosts;
}
void get_network_octet(uint8_t ip, uint8_t subnet, uint8_t &network){
network = ip & subnet;
}
void get_broadcast_octet(uint8_t network, uint8_t subnet, uint8_t &broadcast ){
broadcast = network | ~subnet;
}
void calcualte_network_thread(uint8_t * ip,uint8_t * subnet, uint8_t * network){
//thread threads[NUM_OCTETS];
for(int i = 0; i< NUM_OCTETS;i++){
get_network_octet(ip[i], subnet[i], network[i]);
}
}
void calcualte_broadcast_thread(uint8_t * network,uint8_t * subnet, uint8_t * broadcast){
for(int i = 0; i< NUM_OCTETS;i++){
get_broadcast_octet(network[i], subnet[i], broadcast[i]);
}
}
void calculate_min_host(uint8_t * network, uint8_t * min_host){
uint8_t carry = 1;
for(int i = NUM_OCTETS - 1; i>=0;i--){
if(carry==1){
carry = get_min_host(network[i], min_host[i]);
} else {
min_host[i] = network[i];
}
}
}
void calculate_max_host(uint8_t * broadcast, uint8_t * max_host){
int8_t carry = -1;
for(int i = NUM_OCTETS - 1; i>=0;i--){
if(carry==-1){
carry = get_max_host(broadcast[i], max_host[i]);
} else {
max_host[i] = broadcast[i];
}
}
}
response_package start_process(uint8_t ip[NUM_OCTETS], uint8_t subnet[NUM_OCTETS]){
/*
* This function takes a raw string and calculate
* @param
* uint8_t ip
* uint8_t subnet
* @return
* response_package: calculated addresses
* */
response_package responsePackage;
uint8_t network_container[NUM_OCTETS];
uint8_t broadcast_container[NUM_OCTETS];
uint8_t min_host_container[NUM_OCTETS];
uint8_t max_host_container[NUM_OCTETS];
calcualte_network_thread(ip, subnet, network_container);
calcualte_broadcast_thread(network_container, subnet, broadcast_container);
calculate_min_host(network_container, min_host_container);
calculate_max_host(broadcast_container, max_host_container);
for(int i = 0;i<NUM_OCTETS;i++){
responsePackage.ip[i] = ip[i];
responsePackage.subnet[i] = subnet[i];
responsePackage.network[i] = network_container[i];
responsePackage.broadcast[i] = broadcast_container[i];
responsePackage.hostmin[i] = min_host_container[i];
responsePackage.hostmax[i] = max_host_container[i];
}
int total_zeros = 0;
for(int i = 0;i<NUM_OCTETS;i++){
total_zeros += count_zero_bits(responsePackage.subnet[i]);
}
int num_host = calculate_number_of_hosts(total_zeros);
responsePackage.num_host = num_host;
return responsePackage;
}
int main(int argc, char* argv[]){
int socketfd, new_socketfd;
int portno;
int client_addr_len;
struct message msg1;
struct request_package requestPackage;
//Stores a number of characters read or written
int n;
char buffer[256];
struct sockaddr_in server_addr, client_addr;
if (argc < 2){
cout<<"Error! No port provided"<<endl;
exit(1);
}
socketfd = socket(AF_INET, SOCK_STREAM, 0);
if(socketfd < 0){
error("Error opening socket");
}
//Clear out the server_addr block
bzero((char*) &server_addr, sizeof(server_addr));
portno = atoi(argv[1]);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(portno);
//cout<<"SERVER STARTING ... "<<endl;
//cout<<"SERVER NAME "<< portno <<endl;
//cout<<"PORT NUMBER "<< portno <<endl;
//Bind the socket to address
if(::bind(socketfd, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0){
error("ERROR on binding");
}
//cout<<"STARTED LISTENING FROM CLIENT ... "<<endl;
listen(socketfd, 5);
client_addr_len = sizeof(client_addr);
//cout<<"CALLING ACCEPT ... "<<endl;
//Waiting for connection from client, the process is on hold
while(1){
new_socketfd = accept(socketfd, (struct sockaddr*) &client_addr, (socklen_t *) &client_addr_len);
if(new_socketfd < 0){
error("Error on accept()");
}
pid_t pid = fork();
if(pid == 0){
close(socketfd);
//cout<<"READING CLIENT WITH CHILD PROCESS ... "<<endl;
n = read(new_socketfd, &requestPackage, sizeof(struct request_package));
if(n<0){
cout<<"Error receiving message"<<endl;
}
//} else {
//
// //debug
// for(int i = 0;i<NUM_OCTETS;i++){
// cout<<(int)requestPackage.ip[i]<<".";
// }
//cout<<"READ SUCCESS"<<endl;
response_package responsePackage;
//responsePackage.network[0] = requestPackage.ip[0] - 100;
//responsePackage.network[1] = requestPackage.ip[1] - 100;
//responsePackage.network[2] = requestPackage.ip[2] - 100;
//responsePackage.network[3] = requestPackage.ip[3] - 100;
responsePackage = start_process(requestPackage.ip, requestPackage.subnet);
n = write(new_socketfd, &responsePackage, sizeof(struct response_package));
if(n<0){
cout<<"Error writing message"<<endl;
}
//cout<<"WRITE SUCCESS, CLOSING SOCKET AND EXIT CHILD"<<endl;
exit(0);
} else {
//cout<<"EXIT PARENT"<<endl;
close(new_socketfd);
}
}
return 0;
}
| true |
e05e2dffaa32f1ec3577498e2227a08dcc11d6ab | C++ | yyong119/ACM-OnlineJudge | /leetcode/134.cpp | UTF-8 | 863 | 2.65625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int *diff = new int[n];
int sum = 0;
for (int i = 0; i < n; ++i) {
diff[i] = gas[i] - cost[i];
sum += diff[i];
}
if (sum < 0) return -1; //insufficient gas
int start = 0, visited = 1;
while (diff[start] < 0) ++start;
int cur = start, rest = diff[start];
while (visited < n) {
if (++cur == n) cur = 0;
rest += diff[cur];
if (rest >= 0) ++visited; //sufficient gas
else { //insufficient gas
while (diff[cur] < 0) ++cur; // start from new place
start = cur; visited = 1;
rest = diff[start];
}
}
return start;
}
}; | true |
fa35bcb8cbe7d59a0d79c142b3180f8eb7c67743 | C++ | lonercoder101/code_template | /array_suffix.cpp | UTF-8 | 783 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using ll=long long int;
int main () {
ll N, M;
// N for no. of elements, M for queries
scanf ("%lld %lld", &N, &M);
std::vector <ll> arr (N, 0);
for (ll i=0; i<M; i++) {
ll a, b;
scanf ("%lld %lld", &a, &b);
a--;
b--;
arr[a] += 1;
arr[b+1] -= 1;
}
std::vector <ll> original;
ll sum = 0;
for (ll i=0; i<N; i++) {
sum += arr[i];
original.push_back (sum);
}
ll count = 0;
for (ll i=0; i<N; i++) {
//printf ("%lld ", original[i]);
if (original[i] == M) {
//printf ("%lld ", original[i]);
count ++;
}
}
printf ("%lld\n", count);
}
| true |
e3f0b2d35979f019955af8ec773d7a40497c48cf | C++ | yaoelvon/Cpp_learn | /9/practice_9_18.cc | UTF-8 | 368 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <deque> //双向队列的头文件
using namespace std;
int main(int argc, const char *argv[])
{
string str_nb;
deque<string> destr;
while(cin >> str_nb)
{
destr.push_back(str_nb);
}
auto beg = destr.cbegin();
auto end = destr.cend();
while(beg != end)
{
cout << *beg << endl;
beg++;
}
return 0;
}
| true |
c9f5d273bcdbf86ed8dfbf4005c95536e7f7900b | C++ | ZhaoBeiChen/Home-Work | /Maze/Maze/maze.cpp | GB18030 | 3,891 | 3.046875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int maze[1000][1000];
int row;
int col;
int sum=0;
struct Coordinate //
{
int x;
int y;
};
class Block //ͨש
{
int ord;
Coordinate seat;
int direction;
public:
Block()
{
direction = 1;
}
void IN(int step, Coordinate site, int Dire)
{
ord = step;
seat = site;
direction = Dire;
}
void changeDir()
{
direction++;
}
int Out_ord()
{
return ord;
}
Coordinate Out_seat()
{
return seat;
}
int Out_Dire()
{
return direction;
}
};
Block nulldata;
class StackNode //ջ
{
Block a;
public:
StackNode(Block e)
{
a = e;
next = NULL;
}
Block Out_data()
{
return a;
}
StackNode *next;
};
class setStack //ջ
{
StackNode *top;
public:
setStack()
{
top = new StackNode(nulldata);
top->next = NULL;
}
bool IsEmpty()
{
if (top->next == NULL)
return true;
else return false;
}
void push(Block e)
{
StackNode *p;
p = new StackNode(e);
p->next = top->next;
top->next = p;
}
Block pop()
{
if (top->next != NULL)
{
StackNode *p;
Block e;
p = top->next;
e = p->Out_data();
top->next = p->next;
delete p;
return e;
}
else
{
cout << "the stack is Empty" << endl;
return nulldata;
}
}
Block GetTop()
{
if (top->next != NULL)
return top->next->Out_data();
else
{
cout << "the stack is Empty" << endl;
return nulldata;
}
}
};
class Maze //Թ
{
Block e;
Coordinate curpos;
int curstep;
public:
bool Pass(Coordinate curpos)
{
if (maze[curpos.x][curpos.y] == 1)
return true;
else return false;
}
void Footprint(Coordinate curpos)
{
maze[curpos.x][curpos.y]=0;
return;
}
void MakeStop(Coordinate curpos)
{
maze[curpos.x][curpos.y] = 0;
return;
}
Coordinate NextPos(Coordinate nowPos, int Dire)
{
if (Dire == 1 && nowPos.y<col)
{
nowPos.y++;
}
else if (Dire == 2&&nowPos.x<row)
{
nowPos.x++;
}
else if (Dire == 3 && nowPos.y>1 )
{
nowPos.y--;
}
else if (Dire == 4 && nowPos.x>1 )
{
nowPos.x--;
}
return nowPos;
}
void MazePath(Coordinate start,Coordinate end)
{
setStack s;
curpos = start;
curstep = 1;
do
{
if (Pass(curpos))
{
Footprint(curpos);
e.IN(curstep,curpos,1);
s.push(e);
if (curpos.x == end.x && curpos.y == end.y)
{
sum++;
e = s.pop();
maze[curpos.x][curpos.y] = 1;
e = s.pop();
while (e.Out_Dire() == 4 && !s.IsEmpty())
{
maze[e.Out_seat().x][e.Out_seat().y] = 1;
e = s.pop();
}
if (s.IsEmpty())
{
cout << sum << endl;
return;
}
e.changeDir();
s.push(e);
curpos.x = e.Out_seat().x;
curpos.y = e.Out_seat().y;
curpos = NextPos(curpos,e.Out_Dire());
}
else curpos = NextPos(curpos,1);
curstep++;
}
else
{
if (!s.IsEmpty())
{
e = s.pop();
while (e.Out_Dire() == 4 && !s.IsEmpty())
{
maze[e.Out_seat().x][e.Out_seat().y] = 1;
e = s.pop();
}
if (e.Out_Dire() < 4)
{
e.changeDir();
s.push(e);
curpos = NextPos(e.Out_seat(),e.Out_Dire());
}
}
}
} while (!s.IsEmpty());
if (sum != 0)
cout << sum << endl;
else cout << "ûͨ·" << endl;
}
};
int main()
{
while (1)
{
sum = 0;
cin >> row;
cin >> col;
if (row == 0 && col == 0)
break;
int i;
int j;
for (i = 1; i <= row; i++)
{
for (j = 1; j <= col; j++)
{
cin >> maze[i][j];
}
}
Coordinate start;
Coordinate end;
start.x = 1;
start.y = 1;
end.x = row;
end.y = col;
Maze s;
s.MazePath(start, end);
}
} | true |
f26b044ebadde3d775866b56f7ce0012fc3846e1 | C++ | robertcal/cpp_competitive_programming | /AtCoder/ABC/083/A.cpp | UTF-8 | 318 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define INF 1e9
using namespace std;
using ll = long long;
int main() {
int a, b, c, d; cin >> a >> b >> c >> d;
int l = a + b;
int r = c + d;
if (l > r) {
puts("Left");
} else if (l == r) {
puts("Balanced");
} else {
puts("Right");
}
} | true |
0491bc60c528d992ab64fe9afaf905b8a869a32b | C++ | afcarl/dqn_caffe | /src/ReplayMemory.cpp | UTF-8 | 1,151 | 2.578125 | 3 | [] | no_license | //
// Created by dc on 6/17/15.
//
#include "ReplayMemory.h"
#include <caffe/util/math_functions.hpp>
#include <algorithm>
void ReplayMemory::Add (CPState s0, int action, float reward, CPState s1, bool terminated)
{
buffer[bufferSize % bufferCapacity] = RMNode{s0, s1, action, reward, terminated};
vis[bufferSize % bufferCapacity] = 0;
++bufferSize;
}
void ReplayMemory::Sample (int cnt, std::vector<RMNode> &res)
{
assert(bufferSize >= (size_t)cnt);
static int timeStamp = 0;
++timeStamp;
res.resize((size_t)cnt);
for (int i = 0; i < cnt; ++i)
{
int id;
do
{
id = rand() % min(bufferSize, bufferCapacity);
if ((id < bufferSize && id + 4 >= bufferSize) ||
(id > bufferSize && (id + 4) % bufferCapacity >= bufferSize))
{
continue;
}
if (vis[id] && vis[id] + 4 >= timeStamp)
{
continue;
}
} while (false);
vis[id] = timeStamp;
res[i] = buffer[id];
}
}
void ReplayMemory::Init (int bufferSize)
{
buffer.clear();
vis.clear();
buffer.resize((size_t)bufferSize + 1);
vis.resize((size_t)bufferSize + 1);
fill(vis.begin(), vis.end(), 0);
bufferCapacity = bufferSize;
this->bufferSize = 0;
}
| true |
3e47a1658c00a6e5ae28f6f48d82eed53305bced | C++ | jkl09/intev | /quiz/map_pair.cpp | UTF-8 | 738 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <vector>
#include <set>
using namespace std;
int main(int argc, char const *argv[])
{
string word;
map<string, int> word_count;
word_count["james"] = 10;
while(cin >> word)
{
++word_count[word];
}
map<string,int>::iterator iter = word_count.begin();
while(word_count.end() != iter)
{
cout<< iter->first<<" " ;
cout<< iter->second;
iter++;
cout <<endl;
}
cout<<word_count.erase("james");
cout<<"-------"<<endl;
std::vector<int> ivec;
for (vector<int>::size_type i = 0; i < 10; ++i)
{
ivec.push_back(i);
ivec.push_back(i);
}
set<int> iset(ivec.begin(),ivec.end());
cout<< ivec.size() <<" "<< iset.size()<<endl;
return 0;
} | true |
bb349d77589fdc2541f1ad71ec904e0e5bb569a3 | C++ | asicoderOfficial/Interviews | /theory/searching/binary_search_array.cpp | UTF-8 | 1,796 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int iteration = 1;
//Recursive approach.
bool binarysearch_rec(vector<int> v, int left, int right, int num) {
cout << "Iteration number " << iteration << "\nLeft = " << left << "\nRight = " << right << endl;
if(v.empty() || v[0] > num || v[v.size()-1] < num)
return false;
else {
if(right >= left) {
int middle = (left + right) / 2;
cout << "Middle = " << middle << endl << endl;
if(v[middle] == num)
return true;
else if(v[middle] > num)
return binarysearch_rec(v, left, middle - 1, num);
return binarysearch_rec(v, middle + 1, right, num);
}
}
return false;
}
//Iterative approach.
bool binarysearch_it(vector<int> v, int left, int right, int num) {
cout << "Iteration number " << iteration << "\nLeft = " << left << "\nRight = " << right << endl;
if(v.empty() || v[0] > num || v[v.size()-1] < num)
return false;
else {
while(right >= left) {
int middle = (right + left) / 2;
cout << "Middle = " << middle << endl << endl;
if(v[middle] == num)
return true;
else if(v[middle] > num)
right = middle - 1;
else
left = middle + 1;
}
}
return false;
}
int main() {
cout << "Introduce length and array of ints" << endl;
int n, a, num;
cin >> n;
vector<int> v;
while(n--) {
cin >> a;
v.push_back(a);
}
sort(v.begin(), v.end());
cout << "Introduce number to search for" << endl;
cin >> num;
cout << (bool)binarysearch_rec(v, 0, v.size()-1, num) << endl;
return 0;
} | true |
82c245291bd5b8089890767f41ae9af67115744e | C++ | gwkdgwkd/leetcode | /c_c++/sort/merge/4.寻找两个正序数组的中位数.cpp | UTF-8 | 4,869 | 3.75 | 4 | [] | no_license | /*
给定两个大小分别为m和n的正序(从小到大)数组nums1和nums2。
请找出并返回这两个正序数组的中位数,算法的时间复杂度应该为O(log(m+n))。
示例1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3],中位数2
示例2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组= [1,2,3,4],中位数(2 + 3) / 2 = 2.5
提示:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-10^6 <= nums1[i], nums2[i] <= 10^6
*/
// 归并
// 时间复杂度是:O(m+n)
// 空间复杂度是:O(m+n)
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2,
int nums2Size) {
int len = nums1Size + nums2Size;
int arr[len];
int index = 0;
int i = 0;
int j = 0;
while (i < nums1Size && j < nums2Size) {
if (nums1[i] < nums2[j]) {
arr[index++] = nums1[i++];
} else {
arr[index++] = nums2[j++];
}
}
if (i == nums1Size) {
while (j < nums2Size) {
arr[index++] = nums2[j++];
}
}
if (j == nums2Size) {
while (i < nums1Size) {
arr[index++] = nums1[i++];
}
}
if (len % 2) {
return arr[len / 2];
} else {
return ((double)(arr[len / 2] + arr[len / 2 - 1])) / 2;
}
}
// 归并,只遍历,没有真正归并
// 时间复杂度是:O(m+n)
// 空间复杂度是:O(1)
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2,
int nums2Size) {
int i = 0;
int j = 0;
int middleValue1 = 0;
int middleValue2 = 0;
int middleIndex = 0;
int index = 0;
double middleValue;
middleIndex = (nums1Size + nums2Size) / 2;
while (index <= middleIndex) {
if ((i != nums1Size) && (j != nums2Size)) {
if (nums1[i] <= nums2[j]) {
middleValue1 = middleValue2;
middleValue2 = nums1[i++];
} else {
middleValue1 = middleValue2;
middleValue2 = nums2[j++];
}
} else if (i != nums1Size) {
middleValue1 = middleValue2;
middleValue2 = nums1[i++];
} else {
middleValue1 = middleValue2;
middleValue2 = nums2[j++];
}
index++;
}
if ((nums1Size + nums2Size) % 2 == 1) {
middleValue = (double)middleValue2;
} else {
middleValue = ((double)middleValue1 + (double)middleValue2) / 2;
}
return middleValue;
}
// 二分查找
// 时间复杂度:O(logmin(m,n)))
// 空间复杂度:O(1)
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2,
int nums2Size) {
if (nums1Size > nums2Size) { // 保证nums1比nums2短
return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size);
}
int m = nums1Size;
int n = nums2Size;
int left = 0, right = m;
int median1 = 0; // median1:前一部分的最大值
int median2 = 0; // median2:后一部分的最小值
while (left <= right) {
// 前一部分包含nums1[0 .. i-1]和nums2[0 .. j-1]
// 后一部分包含nums1[i .. m-1]和nums2[j .. n-1]
int i = (left + right) / 2;
int j = (m + n + 1) / 2 - i;
// nums_im1,nums_i,nums_jm1,nums_j分别表示nums1[i-1],nums1[i],nums2[j-1],nums2[j]
int nums_im1 = (i == 0 ? INT_MIN : nums1[i - 1]);
int nums_i = (i == m ? INT_MAX : nums1[i]);
int nums_jm1 = (j == 0 ? INT_MIN : nums2[j - 1]);
int nums_j = (j == n ? INT_MAX : nums2[j]);
if (nums_im1 <= nums_j) {
median1 = fmax(nums_im1, nums_jm1);
median2 = fmin(nums_i, nums_j);
left = i + 1;
} else {
right = i - 1;
}
}
return (m + n) % 2 == 0 ? (median1 + median2) / 2.0 : median1;
}
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) {
return findMedianSortedArrays(nums2, nums1);
}
int m = nums1.size();
int n = nums2.size();
int left = 0, right = m;
// median1:前一部分的最大值
// median2:后一部分的最小值
int median1 = 0, median2 = 0;
while (left <= right) {
// 前一部分包含nums1[0..i-1]和nums2[0..j-1]
// 后一部分包含nums1[i..m-1]和nums2[j..n-1]
int i = (left + right) / 2;
int j = (m + n + 1) / 2 - i;
// nums_im1,nums_i,nums_jm1,nums_j分别表示:
// nums1[i-1],nums1[i],nums2[j-1],nums2[j]
int nums_im1 = (i == 0 ? INT_MIN : nums1[i - 1]);
int nums_i = (i == m ? INT_MAX : nums1[i]);
int nums_jm1 = (j == 0 ? INT_MIN : nums2[j - 1]);
int nums_j = (j == n ? INT_MAX : nums2[j]);
if (nums_im1 <= nums_j) {
median1 = max(nums_im1, nums_jm1);
median2 = min(nums_i, nums_j);
left = i + 1;
} else {
right = i - 1;
}
}
return (m + n) % 2 == 0 ? (median1 + median2) / 2.0 : median1;
}
}; | true |
9aec443a03e2c1cf9425af6e67e0dbd2407919a5 | C++ | spersinger/fchacks-safety-sleeve | /source/visualizer.cpp | UTF-8 | 2,376 | 3.265625 | 3 | [
"MIT"
] | permissive | /*
* Visualizer Program. (This would run on a separate personal device as an application)
* This contains the analyzing of the data from the garment and the displaying of said data.
* This all simulates what would happen in the application on a separate device.
*/
#include <iostream>
#include "lib/termColor.hpp"
int main(int argc, char *argv[]) {
int sizeX, sizeY;
int threshCounterC = 0, threshCounterT = 0;
//Reads sizeX and sizeY from main program
std::cin >> sizeX;
std::cin >> sizeY;
//Default values for the compression and tension thresholds
double cThreshold = 0.6, tThreshold = 0.4;
//User input for both compression and tension threshold
if (argc > 1) {
double cThreshold = strtod(argv[1],NULL), tThreshold = strtod(argv[2],NULL);
}
for (int x = 0; x < sizeX; x++) {
for (int y = 0; y < sizeY; y++) {
//Reads node measurements from main program
double tenIn, comIn;
std::cin >> tenIn;
std::cin >> comIn;
//Determines if nodes are above safety limit and then outputs the result of the analysis
if (tenIn >= tThreshold)
if (comIn >= cThreshold) {
//BOTH ABOVE LIMIT - RED
std::cout << termcolor::red << "[#]" << termcolor::reset;
threshCounterC++;
threshCounterT++;
}
else {
//TENSION ABOVE LIMIT - CYAN
std::cout << termcolor::cyan << "[-]" << termcolor::reset;
threshCounterT++;
}
else if (comIn >= cThreshold) {
//COMPRESSION ABOVE LIMIT - MAGENTA
std::cout << termcolor::magenta << "[-]" << termcolor::reset;
threshCounterC++;
}
else {
//NONE ABOVE LIMIT - GREEN
std::cout << termcolor::green << "[ ]" << termcolor::reset;
}
}
std::cout << std::endl;
}
//Alerts user if 15 or more nodes are above the safety limit
if (threshCounterC >= 15 || threshCounterT >= 15) {
std::cout << "There is too much pressure on your wound, seek your doctors attention as soon as possible..." << std::endl;
return 0;
}
std::cout << std::endl;
return 0;
} | true |
17c333c4d4c62b57e0068a6b231cb6c094b8502c | C++ | pakpak123/BasisArduino | /Last_Project_ITC.ino | UTF-8 | 1,789 | 2.734375 | 3 | [] | no_license |
const int pingPin = 7; //trig
int inPin = 8;
int BUTTON = 2;
int Press = 0;
#include <Servo.h>
#include <Wire.h>
const int LCD_COLS = 16;
const int LCD_ROWS = 2;
Servo myservo; //ประกาศตัวแปรแทน Servo
void switch1()
{
if (digitalRead(BUTTON) == LOW)
{
Press++;
if (Press > 1)
{
Press = 0;
}
Serial.println(Press);
}
delay(200);
}
void setup() {
int status;
Serial.begin(9600);
myservo.attach(9);
attachInterrupt(digitalPinToInterrupt(BUTTON) , switch1, CHANGE);
pinMode(BUTTON, INPUT_PULLUP);
}
void loop()
{
if (Press == 1)
{
long duration, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
if (cm < 12)
{
myservo.write(90); // สั่งให้ Servo หมุนไปองศาที่ 180
delay(500); // หน่วงเวลา 1000ms
}
else
{
myservo.write(180); // สั่งให้ Servo หมุนไปองศาที่ 0
delay(500); // หน่วงเวลา 1000ms
}
}
else if (Press == 0)
{
}
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
| true |
4d4530e755e0e3e81cd132f920218ff7f98f5b16 | C++ | 1BM18CS147/ADS | /Program6/BTreeInsertion.cpp | UTF-8 | 2,688 | 3.46875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class BTreeN
{
int *values;
int t;
BTreeN **C;
int n;
bool leaf;
public:
BTreeN(int _t, bool _leaf);
void insertNonFull(int k);
void splitChild(int i, BTreeN *y);
void traverse();
BTreeN *search(int k);
friend class BTree;
};
class BTree
{
BTreeN *root;
int t;
public:
BTree(int _t)
{ root = NULL; t = _t; }
void traverse()
{ if (root != NULL) root->traverse(); }
BTreeN* search(int k)
{ return (root == NULL)? NULL : root->search(k); }
void insert(int k);
};
BTreeN::BTreeN(int t1, bool leaf1)
{
t = t1;
leaf = leaf1;
n = 0;
values = new int[2*t-1];
C = new BTreeN *[2*t];
}
void BTreeN::traverse()
{
int i;
for (i = 0; i < n; i++)
{
if (leaf == false)
C[i]->traverse();
cout << " " << values[i];
}
if (leaf == false)
C[i]->traverse();
}
BTreeN *BTreeN::search(int k)
{
int i = 0;
while (i < n && k > values[i]) i++;
if (values[i] == k)
return this;
if (leaf == true)
return NULL;
return C[i]->search(k);
}
void BTree::insert(int k)
{
if (root == NULL)
{
root = new BTreeN(t, true);
root->values[0] = k;
root->n = 1;
}
else
{
if (root->n == 2*t-1)
{
BTreeN *s = new BTreeN(t, false);
s->C[0] = root;
s->splitChild(0, root);
int i = 0;
if (s->values[0] < k)
i++;
s->C[i]->insertNonFull(k);
root = s;
}
else
root->insertNonFull(k);
}
}
void BTreeN::insertNonFull(int k)
{
int i = n-1;
if (leaf == true)
{
while (i >= 0 && values[i] > k)
{
values[i+1] = values[i];
i--;
}
values[i+1] = k;
n = n+1;
}
else
{
while (i >= 0 && values[i] > k) i--;
if (C[i+1]->n == 2*t-1)
{
splitChild(i+1, C[i+1]);
if (values[i+1] < k)
i++;
}
C[i+1]->insertNonFull(k);
}
}
void BTreeN::splitChild(int i, BTreeN *y)
{
BTreeN *z = new BTreeN(y->t, y->leaf);
z->n = t - 1;
for (int j = 0; j < t-1; j++)
z->values[j] = y->values[j+t];
if (y->leaf == false)
{
for (int j = 0; j < t; j++)
z->C[j] = y->C[j+t];
}
y->n = t - 1;
for (int j = n; j >= i+1; j--)
C[j+1] = C[j];
C[i+1] = z;
for (int j = n-1; j >= i; j--)
values[j+1] = values[j];
values[i] = y->values[t-1];
n = n + 1;
}
int main()
{
int n,k,num;
cout<<"Enter degree of tree\n";
cin>>num;
BTree t(num);
cout<<"Enter the no. of values"<<endl;
cin>>n;
cout<<"Enter the values"<<endl;
for(int i=0; i<n; i++)
{
cin>>k;
t.insert(k);
}
cout << "BTree after insertion is\n";
t.traverse();
cout<<"\n";
return 0;
}
| true |
819699faaf531d0969be6bd89dcf65f88003a5c8 | C++ | venkateshkulkarni345/venk_test1 | /11_MacroInlineNewDeleteMalloc.cpp | UTF-8 | 1,331 | 3.703125 | 4 | [] | no_license | #include<iostream>
using namespace std;
#define MULERROR(X) ( X * 10)
#define MULCORRECT(X) ( (X) * 10)
//1. Use of inline function : repetative use of the small block of code can be consider as an Inline function
//2. Will increase the performance(runs faster but utilizes the memory for placing the code for every call at the compilation):
// no need of stack call for the function declared as inline
inline double add(double x, double y)
{
return (x + y);
}
int main()
{
// 2+(5*10) = 52 -->wrong
cout << MULERROR(2 + 5) << endl;
// (2+5)10 = 70 --> correct
cout << MULCORRECT(2 + 5) << endl;
//inline call
cout << add(10, 10) << endl;
/*Memory creation and deletion using new and delete*/
/******************************************************************/
int *ptr = NULL;
ptr = new int[10];
if (ptr == NULL)
cout << "Bad dynamic mem allocation" << endl;
delete[] ptr;
/******************************************************************/
/*Memory creation and deletion using malloc and free*/
/******************************************************************/
int *ptr1 = NULL;
ptr1 = (int *)malloc( sizeof(int)*10);
if (ptr1 == NULL)
cout << "Bad dynamic mem allocation" << endl;
free(ptr1);
/******************************************************************/
return 0;
}
| true |
33258c3efc573d562cfe61917e3c7c4cfed790dd | C++ | Max-Sir/Password_Generator | /MyForm.cpp | UTF-8 | 2,211 | 2.703125 | 3 | [] | no_license | #include "MyForm.h"
#include<cmath>
#include<string>
#include<ctime>
#include<cstdlib>
#include <iostream>
using std::string;
using std::endl;
using std::cout;
using std::cin;
//using namespace std;
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
string abc()
{
string c = "";
for (int i = 32; i != 127; i++)
c += (char)i;
return c;
}
string Gen_Password(string a = abc(), int size = 16) {
//srand(time(NULL));
string password;
for (int i = 0; i < size; i++)
password += a[0 + rand() % (a.length() - 1)];
cout << password << endl;
return password;
}
string letters_uppercase()
{
string x = "";
for (int i = 65; i <= 90; i++)
x += (char)i;
return x;
}
string letters_lowercase()
{
string x = "";
for (int i = 97; i <= 122; i++)
x += (char)i;
return x;
}
string letters()
{
return letters_uppercase() + letters_lowercase();
}
string digits()
{
string x;
for (int i = 0; i < 10; i++)
x += i;
return x;
}
string PinCode(string s = digits(), int size = 4)
{
string x = "";
for (int i = 0; i < size; i++)
x += s[0 + rand() % (s.length() - 1)];
return x;
}
string Caesar_cipher(string s = "Hello World!", int shift = 1)
{
for (int i = 0; i < s.length(); i++)
if ((int)s[i] <= 90 && (int)s[i] >= 65)
{
s[i] = (char)((int)(s[i] + shift));
if ((int)s[i] > 90)
s[i] = (char)(((int)s[i]) % 90 + 65);
else
continue;
}
else if ((int)s[i] <= 122 && (int)s[i] >= 97)
{
s[i] = (char)((int)(s[i] + shift));
if ((int)s[i] > 122)
s[i] = (char)(((int)s[i]) % 122 + 97);
else
continue;
}
else
s[i] = s[i];
return s;
}
//int gcd(int a, int b) {
// return !b ? a : gcd(b, a % b);
//}
//template<class T, class U>
//T power(T a, U b) {
// if (a == 0 && b == 0) return 1;
// else if (a == 0)return 0;
// else
// for (int i = 0; i != b; i++) a *= a;
// return a;
//}
//template<class T>
//T absolute(T a) {
// if (a < 0) return -a;
// else return a;
//}
int factorial(int a)
{
return (a == 1 || a == 0) ? 1 : factorial(a - 1) * a;
}
void main(array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
PasswordGenerator::MyForm form;
Application::Run(% form);
} | true |
d41490cae410eac2d336a970f78997151c3a74a1 | C++ | jaranvil/Data-Structures | /Linked Lists/Project5/Project5/LinkedList.h | UTF-8 | 336 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include "Node.h"
using namespace std;
class LinkedList
{
public:
Node *first;
LinkedList() : first(NULL) {}
virtual ~LinkedList();
void addValue(int, string);
int getNodeNum(int nodenum);
void changeNode(int nodenum, int num);
};
ostream& operator<<(ostream& output, LinkedList& list);
| true |
ffbaabc6bab0b0434ea17bc7311de902080762a9 | C++ | hangkuyr/RPGgame | /tests/enemies/testpumpkin.cpp | UTF-8 | 1,092 | 2.90625 | 3 | [] | no_license | #include "doctest.h"
#include "enemy.hpp"
#include "pumpkin.hpp"
#include "dice.hpp"
Enemy* RPP = new Pumpkin(2);
TEST_CASE("Teste Enemy Damage - 1"){
CHECK(RPP->e_damage() >= 1);
}
TEST_CASE("Teste Enemy Damage - 2"){
CHECK(RPP->e_damage() <= 8);
}
TEST_CASE("Teste Enemy Damage - 3"){
RPP->set_hp(9);
CHECK(RPP->e_damage() >= 1);
}
TEST_CASE("Teste Enemy Damage - 4"){
CHECK(RPP->e_damage() <= 10);
}
TEST_CASE("Teste Enemy Damage - 5"){
RPP->set_hp(5);
CHECK(RPP->e_damage() >= 1);
}
TEST_CASE("Teste Enemy Damage - 6"){
CHECK(RPP->e_damage() <= 12);
}
TEST_CASE("Teste Enemy Damage - 7"){
RPP = new Pumpkin(5, 750);
CHECK(RPP->e_damage() >= 1);
}
TEST_CASE("Teste Enemy Damage - 8"){
CHECK(RPP->e_damage() <= 6);
}
TEST_CASE("Teste Enemy Damage (Efeito da Função) - 9"){
CHECK(RPP->get_hp() == 35);
}
TEST_CASE("Teste Enemy Damage - 10"){
RPP->set_hp(5);
CHECK(RPP->e_damage() >= 1);
}
TEST_CASE("Teste Enemy Damage - 11"){
CHECK(RPP->e_damage() <= 20);
}
TEST_CASE("Teste Enemy Damage (Efeito da Função) - 12"){
CHECK(RPP->get_hp() == 0);
delete(RPP);
} | true |
205919c7342a42d75e3e75c4bee6f9ebe4d7b8e6 | C++ | LeDDGroup/chopter | /src/control/Event.cpp | UTF-8 | 738 | 2.90625 | 3 | [] | no_license | #include <SDL2/SDL_events.h>
#include <SDL2/SDL_timer.h>
#include "Event.hpp"
Event::Event() {
quit = false;
timeout = 1000/30;
resetTime();
}
bool Event::waitForStepTime() {
while(checkEvents()) {
if (isTime()) {
resetTime();
break;
}
}
return !quit;
}
bool Event::checkEvents() {
SDL_Event event;
while (!quit && SDL_PollEvent(&event) != 0) {
if (!processEvent(event)) {
break;
}
}
return !quit;
}
bool Event::processEvent(const SDL_Event & event) {
switch (event.type) {
case SDL_QUIT:
quit = true;
return false;
}
return true;
}
bool Event::isTime() {
return prevTime + timeout <= SDL_GetTicks();
}
void Event::resetTime() {
prevTime = SDL_GetTicks();
}
| true |
158da3a530834dac3d91f12cb9258de7c1dfc249 | C++ | aaa055/GreenhouseProject | /Main/LogModule.h | UTF-8 | 2,172 | 2.6875 | 3 | [] | no_license | #ifndef _LOG_MODULE_H
#define _LOG_MODULE_H
#include "AbstractModule.h"
#include "Globals.h"
#include "DS3231Support.h"
#include <SD.h>
typedef struct
{
AbstractModule* RaisedModule; // модуль, который инициировал событие
String Message; // действие, которое было произведено
} LogAction; // структура с описанием действий, которые произошли
class LogModule : public AbstractModule // модуль логгирования данных с датчиков
{
private:
static String _COMMA;
static String _NEWLINE;
unsigned long lastUpdateCall;
#ifdef USE_DS3231_REALTIME_CLOCK
DS3231Clock rtc;
#endif
int8_t lastDOW;
bool hasSD;
File logFile; // текущий файл для логгирования
File actionFile; // файл с записями о произошедших действиях
String currentLogFileName; // текущее имя файла, с которым мы работаем сейчас
unsigned long loggingInterval; // интервал между логгированиями
#ifdef LOG_ACTIONS_ENABLED
int8_t lastActionsDOW;
void EnsureActionsFileCreated(); // убеждаемся, что файл с записями текущих действий создан
void CreateActionsFile(const DS3231Time& tm); // создаёт новый файл лога с записью действий
#endif
void CreateNewLogFile(const DS3231Time& tm);
void GatherLogInfo(const DS3231Time& tm);
#ifdef ADD_LOG_HEADER
void TryAddFileHeader();
#endif
String csv(const String& input);
// HH:MM,MODULE_NAME,SENSOR_TYPE,SENSOR_IDX,SENSOR_DATA\r\n
void WriteLogLine(const String& hhmm, const String& moduleName, const String& sensorType, const String& sensorIdx, const String& sensorData);
public:
LogModule() : AbstractModule("LOG") {}
bool ExecCommand(const Command& command, bool wantAnswer);
void Setup();
void Update(uint16_t dt);
void WriteAction(const LogAction& action); // записывает действие в файл событий
};
#endif
| true |
fcf96e550ca135b050e3d906499108c335ccd14f | C++ | goutomroy/uva.onlinejudge | /solved/The snail(573).cpp | UTF-8 | 499 | 2.5625 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
#include<math.h>
#define ERR 1e-10
void main( )
{
float feet,wall,one,fatig,night,per;
int day;
while(scanf("%f%f%f%f",&wall,&one,&night,&fatig)==4 )
{
if(fabs(wall - 0.00000) <ERR)
break;
day=1;feet=0;
per=(fatig*one)/100;
while(1)
{
if(one>=0)
feet=feet+one;
if(feet>wall)
{
printf("success on day %d\n",day);
break;
}
feet=feet-night;
if(feet<0)
{
printf("failure on day %d\n",day);
break;
}
one=one-per;
day++;
}
}
}
| true |
84999413828609604fe31ae6d10b0fcf4c0067e9 | C++ | muaddib1971/pucpp | /tutorials/groupb/week1/extern.cpp | UTF-8 | 272 | 2.703125 | 3 | [] | no_license | #include <cstdlib>
#include "extern1.h"
#include "extern2.h"
struct foo;
void doit(foo* f);
int i;
int main() {
i = 5;
/* incomplete type */
foo* f;
return EXIT_SUCCESS;
}
struct foo {
int a, b;
};
void func(foo* f) {
f->a = 5;
f->b = 42;
}
| true |
367e59db874a8d9b18b1425ca195419677ffc099 | C++ | DhikaAufa/P4-Dhika-Aufa-Hardinata | /Jobsheet 1 C.cpp | UTF-8 | 530 | 2.671875 | 3 | [] | no_license | #include<stdio.h>
main(){
int myarray[10] = {1,3,5,7,9,2,4,6,8,};
printf("\nNAMA : Dhika Aufa Hardinata");
printf("\nNIM : F1B019039");
printf("\nKELOMPOK : 8");
printf("\ndata ke-1 = %d" ,myarray[0]);
printf("\ndata ke-2 = %d" ,myarray[1]);
printf("\ndata ke-3 = %d" ,myarray[2]);
printf("\ndata ke-4 = %d" ,myarray[3]);
printf("\ndata ke-5 = %d" ,myarray[4]);
printf("\ndata ke-6 = %d" ,myarray[5]);
printf("\ndata ke-7 = %d" ,myarray[6]);
printf("\ndata ke-8 = %d" ,myarray[7]);
printf("\ndata ke-9 = %d" ,myarray[8]);
}
| true |
71c452a5088a82352adc2ed36d89e28e5d4e40bd | C++ | ji12345ba/CS225-UIUC | /lab_dict/cartalk_puzzle.cpp | UTF-8 | 1,354 | 3.328125 | 3 | [] | no_license | /**
* @file cartalk_puzzle.cpp
* Holds the function which solves a CarTalk puzzler.
*
* @author Matt Joras
* @date Winter 2013
*/
#include <fstream>
#include "cartalk_puzzle.h"
using namespace std;
/**
* Solves the CarTalk puzzler described here:
* http://www.cartalk.com/content/wordplay-anyone.
* @return A vector of (string, string, string) tuples
* Returns an empty vector if no solutions are found.
* @param d The PronounceDict to be used to solve the puzzle.
* @param word_list_fname The filename of the word list to be used.
*/
vector<std::tuple<std::string, std::string, std::string>> cartalk_puzzle(PronounceDict d,
const string& word_list_fname)
{
vector<std::tuple<std::string, std::string, std::string>> ret;
/* Your code goes here! */
ifstream wordsFile(word_list_fname);
string word;
if (wordsFile.is_open()) {
while (getline(wordsFile, word)) {
string subword1 = word.substr(1);
string subword2;
if(word.length() > 2){
subword2 = word.front() + word.substr(2);
}
else{
subword2 = word.substr(0, 1);
}
if(d.homophones(word, subword1) && d.homophones(word, subword2)){
ret.push_back({word, subword1, subword2});
}
}
}
return ret;
}
| true |
0194374ddd30e328056605d7a1c67448309e7188 | C++ | H-Shen/Collection_of_my_coding_practice | /Leetcode/1381/1381.cpp | UTF-8 | 790 | 3.609375 | 4 | [] | no_license | class CustomStack {
private:
vector<int> vec;
size_t maxSize;
public:
CustomStack(int maxSize) : maxSize(maxSize) {
}
void push(int x) {
if (vec.size() < maxSize) {
vec.emplace_back(x);
}
}
int pop() {
if (vec.empty()) {
return -1;
}
int result = vec.back();
vec.pop_back();
return result;
}
void increment(int k, int val) {
int n = (int)vec.size();
for (int i = 0; i < n && i < k; ++i) {
vec.at(i) += val;
}
}
};
/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*/ | true |
0b6f3a3479e4e25dffc25d41ed66b9bfd72c6c81 | C++ | Abdelrahman009/Algorithms | /Collection/StronglyConnectedComponents/StronglyConnectedComponentsFinder.cpp | UTF-8 | 1,612 | 3.15625 | 3 | [] | no_license |
#include "StronglyConnectedComponentsFinder.h"
#include "../DFS/DFSOperator.h"
void DFS(DirectedGraph &graph,vector<Vertex> &component,Vertex &v){
v.color = 1;
component.push_back(v);
for (int i = 0; i < v.edges.size(); ++i) {
for(Edge e : v.edges){
if(graph.vertices[e.destination].color == 0 ){
graph.vertices[e.destination].parent = v.index;
DFS(graph,component,graph.vertices[e.destination]);
}
}
}
}
vector<vector<Vertex>> StronglyConnectedComponentsFinder::findSCC(DirectedGraph graph){
DirectedGraph reverseGraph;
for (int i = 0; i < graph.vertices.size(); ++i) {
Vertex v;
v.name = graph.vertices[i].name;
v.value = graph.vertices[i].value;
v.index = graph.vertices[i].index;
reverseGraph.vertices.push_back(v);
}
for (int j = 0; j < graph.edges.size(); ++j) {
reverseGraph.addEdge(graph.edges[j].destination,graph.edges[j].source,graph.edges[j].weight);
}
DFSOperator dfsOperator;
vector<Vertex> vertices = dfsOperator.operateDFS(reverseGraph);
for (int i = 0; i < graph.vertices.size(); ++i) {
graph.vertices[i].color = 0;
graph.vertices[i].parent = -1;
}
vector<vector<Vertex>> components;
for (int k = vertices.size() - 1; k >= 0 ; --k) {
if(graph.vertices[vertices[k].index].color == 0) {
vector<Vertex> component;
DFS(graph, component, graph.vertices[vertices[k].index]);
components.push_back(component);
}
}
return components;
}
| true |
fef009e3982290f5a984ddbba7bc51d164ca27de | C++ | JayeRen/profile | /580-3DGraphicsAndRendering/JIAYI_REN_HW3/HW3/rend.cpp | UTF-8 | 23,041 | 2.9375 | 3 | [] | no_license | /* CS580 Homework 3 */
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "Gz.h"
#include "rend.h"
#include <vector>
using std::vector;
#define MAXINTENSITY 4095
#define PI (float) 3.14159265358979323846
//extra func
void Matrix_d4(GzMatrix x, GzMatrix y, GzMatrix z) {
float temp;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
temp = 0.0;
for (int k = 0; k < 4; k++) {
temp = temp+x[i][k] * y[k][j];
}
z[i][j] = temp;
}
}
}
//trans v to model-v
Vertex trs_v(Vertex v, GzMatrix ximg, Vertex v_m) {
//trans v to matrix 4*1;
float temp_v[4], temp_vm[4] = { 0.0,0.0,.0,.0 };
temp_v[0] = v.x;
temp_v[1] = v.y;
temp_v[2] = v.z;
temp_v[3] = 1;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
temp_vm[i] += ximg[i][j] * temp_v[j];
}
}
v_m.x = temp_vm[0] / temp_vm[3];
v_m.y = temp_vm[1] / temp_vm[3];
v_m.z = temp_vm[2] / temp_vm[3];
return v_m;
}
//check triangle
int cut_tri(vector<Vertex> v, int xres, int yres) {
int temp=0,count=0;
for(int i=0;i<3;i++){
if (v[i].z< 0) {
temp = 1;
break;
}
else if (v[i].x<0 || v[i].x>xres ||
v[i].y<0 || v[i].y>yres) {
count++;
}
}
if (count == 3) {
temp = 1;
}
return temp;
}
int GzRender::GzRotXMat(float degree, GzMatrix mat)
{
/* HW 3.1
// Create rotate matrix : rotate along x axis
// Pass back the matrix using mat value
*/
float deg = (degree / 180)*PI;
mat[0][0] =1 ;
mat[0][1] = 0;
mat[0][2] = 0;
mat[0][3] = 0;
mat[1][0] = 0;
mat[1][1] = cos(deg);
mat[1][2] = -sin(deg);
mat[1][3] = 0;
mat[2][0] = 0;
mat[2][1] = sin(deg);
mat[2][2] = cos(deg);
mat[2][3] =0 ;
mat[3][0] = 0;
mat[3][1] = 0;
mat[3][2] = 0;
mat[3][3] = 1;
return GZ_SUCCESS;
}
int GzRender::GzRotYMat(float degree, GzMatrix mat)
{
/* HW 3.2
// Create rotate matrix : rotate along y axis
// Pass back the matrix using mat value
*/
float deg = (degree / 180)*PI;
mat[0][0] = cos(deg);
mat[0][1] = 0;
mat[0][2] = sin(deg);
mat[0][3] =0 ;
mat[1][0] = 0;
mat[1][1] = 1;
mat[1][2] = 0;
mat[1][3] = 0;
mat[2][0] = -sin(deg);
mat[2][1] = 0;
mat[2][2] = cos(deg);
mat[2][3] =0 ;
mat[3][0] = 0;
mat[3][1] = 0;
mat[3][2] = 0;
mat[3][3] = 1;
return GZ_SUCCESS;
}
int GzRender::GzRotZMat(float degree, GzMatrix mat)
{
/* HW 3.3
// Create rotate matrix : rotate along z axis
// Pass back the matrix using mat value
*/
float deg = (degree / 180)*PI;
mat[0][0] = cos(deg);
mat[0][1] = -sin(deg);
mat[0][2] = 0;
mat[0][3] = 0;
mat[1][0] = sin(deg);
mat[1][1] = cos(deg);
mat[1][2] =0 ;
mat[1][3] = 0;
mat[2][0] = 0;
mat[2][1] = 0;
mat[2][2] = 1;
mat[2][3] = 0;
mat[3][0] =0 ;
mat[3][1] =0 ;
mat[3][2] = 0;
mat[3][3] = 1;
return GZ_SUCCESS;
}
int GzRender::GzTrxMat(GzCoord translate, GzMatrix mat)
{
/* HW 3.4
// Create translation matrix
// Pass back the matrix using mat value
*/
mat[0][0] = 1;
mat[0][1] = 0;
mat[0][2] = 0;
mat[0][3] = translate[0];
mat[1][0] = 0;
mat[1][1] = 1;
mat[1][2] = 0;
mat[1][3] = translate[1];
mat[2][0] = 0;
mat[2][1] = 0;
mat[2][2] = 1;
mat[2][3] = translate[2];
mat[3][0] = 0;
mat[3][1] = 0;
mat[3][2] = 0;
mat[3][3] = 1;
return GZ_SUCCESS;
}
int GzRender::GzScaleMat(GzCoord scale, GzMatrix mat)
{
/* HW 3.5
// Create scaling matrix
// Pass back the matrix using mat value
*/
mat[0][0] = scale[0];
mat[0][1] = 0;
mat[0][2] = 0;
mat[0][3] = 0;
mat[1][0] = 0;
mat[1][1] = scale[1];
mat[1][2] = 0;
mat[1][3] = 0;
mat[2][0] = 0;
mat[2][1] = 0;
mat[2][2] = scale[2];
mat[2][3] = 0;
mat[3][0] = 0;
mat[3][1] = 0;
mat[3][2] = 0;
mat[3][3] = 1;
return GZ_SUCCESS;
}
GzRender::GzRender(int xRes, int yRes)
{
/* HW1.1 create a framebuffer for MS Windows display:
-- set display resolution
-- allocate memory for framebuffer : 3 bytes(b, g, r) x width x height
-- allocate memory for pixel buffer
*/
if (xRes > MAXXRES) {
xres = MAXXRES;
}
else if (xRes < 0) {
xres = 0;
}
else {
xres = xRes;
}
if (yRes > MAXYRES) {
yres = MAXYRES;
}
else if (yRes < 0) {
yres = 0;
}
else {
yres = yRes;
}
int resolution = xres*yres;
framebuffer = new char[sizeof(char) * 3 * xres*yres];
pixelbuffer = new GzPixel[resolution];
/* HW 3.6
- setup Xsp and anything only done once
- init default camera
*/
matlevel = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
Xsp[i][j] = 0;
m_camera.Xpi[i][j] = 0;
m_camera.Xiw[i][j] = 0;
}
}
m_camera.FOV = DEFAULT_FOV;
m_camera.lookat[0] = 0.0;
m_camera.lookat[1] = 0.0;
m_camera.lookat[2] = 0.0;
m_camera.position[0] = DEFAULT_IM_X;
m_camera.position[1] = DEFAULT_IM_Y;
m_camera.position[2] = DEFAULT_IM_Z;
m_camera.worldup[0] = 0.0;
m_camera.worldup[1] = 1.0;
m_camera.worldup[2] = 0.0;
}
GzRender::~GzRender()
{
/* HW1.2 clean up, free buffer memory */
delete pixelbuffer;
delete framebuffer;
}
int GzRender::GzDefault()
{
/* HW1.3 set pixel buffer to some default values - start a new frame */
if (framebuffer == NULL) {
return GZ_FAILURE;
}
for (int i = 0; i < xres; i++) {
for (int j = 0; j < yres; j++) {
pixelbuffer[ARRAY(i, j)].alpha = 1;
pixelbuffer[ARRAY(i, j)].blue = 2550;
pixelbuffer[ARRAY(i, j)].green = 2550;
pixelbuffer[ARRAY(i, j)].red = 2550;
pixelbuffer[ARRAY(i, j)].z = INT32_MAX;
}
}
return GZ_SUCCESS;
}
int GzRender::GzBeginRender()
{
/* HW 3.7
- setup for start of each frame - init frame buffer color,alpha,z
- compute Xiw and projection xform Xpi from camera definition
- init Ximage - put Xsp at base of stack, push on Xpi and Xiw
- now stack contains Xsw and app can push model Xforms when needed
*/
//GzDefault();
float degree = (m_camera.FOV / 180) * PI;
float d = 1 / tan(degree / 2);
Xsp[0][0] = Xsp[0][3] = xres / 2;
Xsp[1][1] = -yres / 2;
Xsp[1][3] = yres / 2;
Xsp[2][2] = MAXINT;
Xsp[3][3] = 1;
Xsp[0][1] = Xsp[0][2] =
Xsp[1][0] = Xsp[1][2] =
Xsp[2][0] = Xsp[2][1] = Xsp[2][3] =
Xsp[3][0] = Xsp[3][1] = Xsp[3][2] = 0;
m_camera.Xpi[0][0] = 1.0;
m_camera.Xpi[1][1] = 1.0;
m_camera.Xpi[2][2] = 1 / d;
m_camera.Xpi[3][2] = 1 / d;
m_camera.Xpi[3][3] = 1.0;
m_camera.Xpi[0][1] = m_camera.Xpi[0][2] = m_camera.Xpi[0][3] =
m_camera.Xpi[1][0] = m_camera.Xpi[1][2] = m_camera.Xpi[1][3] =
m_camera.Xpi[2][0] = m_camera.Xpi[2][1] = m_camera.Xpi[2][3] =
m_camera.Xpi[3][0] = m_camera.Xpi[3][1] = 0;
//setup Z axis,include z-origin and z-unit
Axis_iw set_Z;
set_Z.vector_iw(m_camera.position, m_camera.lookat);
float mod_Z = set_Z.iw_m;
//setup Up vector and mod
Axis_iw set_up;
GzCoord temp_set = { 0,0,0 };
set_up.vector_iw(temp_set, m_camera.worldup);
float mod_Up = set_up.iw_m;
float cos_uz = (set_Z.x*set_up.x +
set_Z.y*set_up.y +
set_Z.z*set_up.z) / (mod_Z*mod_Up);
GzCoord up_p;
//get up prime
//up_p[0] = set_up.x*(1 - cos_uz);
//up_p[1] = set_up.y*(1 - cos_uz);
//up_p[2] = set_up.z*(1 - cos_uz);
up_p[0] = set_up.x - set_Z.unit_x*cos_uz;
up_p[1] = set_up.y - set_Z.unit_y*cos_uz;
up_p[2] = set_up.z - set_Z.unit_z*cos_uz;
//set up Y axis
Axis_iw set_Y;
set_Y.vector_iw(temp_set, up_p);
float mod_Y = set_up.iw_m;
//set up X axis
//X = (Y x Z)
GzCoord axix_X;
axix_X[0] = set_Y.unit_y*set_Z.unit_z -
set_Y.unit_z*set_Z.unit_y;
axix_X[1] = set_Y.unit_z*set_Z.unit_x -
set_Y.unit_x*set_Z.unit_z;
axix_X[2] = set_Y.unit_x*set_Z.unit_y -
set_Y.unit_y*set_Z.unit_x;
Axis_iw set_X;
set_X.vector_iw(temp_set, axix_X);
float mod_X = set_X.iw_m;
float XC, YC, ZC;
XC = set_X.unit_x *m_camera.position[0] +
set_X.unit_y*m_camera.position[1] +
set_X.unit_z*m_camera.position[2];
YC = set_Y.unit_x*m_camera.position[0] +
set_Y.unit_y*m_camera.position[1] +
set_Y.unit_z*m_camera.position[2];
ZC = set_Z.unit_x*m_camera.position[0] +
set_Z.unit_y*m_camera.position[1] +
set_Z.unit_z*m_camera.position[2];
m_camera.Xiw[0][0] = set_X.unit_x;
m_camera.Xiw[0][1] = set_X.unit_y;
m_camera.Xiw[0][2] = set_X.unit_z;
m_camera.Xiw[0][3] = -XC;
m_camera.Xiw[1][0] = set_Y.unit_x;
m_camera.Xiw[1][1] = set_Y.unit_y;
m_camera.Xiw[1][2] = set_Y.unit_z;
m_camera.Xiw[1][3] = -YC;
m_camera.Xiw[2][0] = set_Z.unit_x;
m_camera.Xiw[2][1] = set_Z.unit_y;
m_camera.Xiw[2][2] = set_Z.unit_z;
m_camera.Xiw[2][3] = -ZC;
m_camera.Xiw[3][0] = 0.0;
m_camera.Xiw[3][1] = 0.0;
m_camera.Xiw[3][2] = 0.0;
m_camera.Xiw[3][3] = 1.0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
Ximage[matlevel][i][j] = Xsp[i][j];
}
}
//Matrix_d4( default_ximg , Xsp, Ximage[matlevel]);
Matrix_d4(Ximage[matlevel], m_camera.Xpi, Ximage[matlevel+1]);
Matrix_d4(Ximage[matlevel+1], m_camera.Xiw, Ximage[matlevel+2]);
matlevel = matlevel + 3;
return GZ_SUCCESS;
}
int GzRender::GzPutCamera(GzCamera camera)
{
/* HW 3.8
/*- overwrite renderer camera structure with new camera definition
*/
m_camera.FOV = camera.FOV;
m_camera.lookat[0] = camera.lookat[0];
m_camera.lookat[1] = camera.lookat[1];
m_camera.lookat[2] = camera.lookat[2];
m_camera.position[0] = camera.position[0];
m_camera.position[1] = camera.position[1];
m_camera.position[2] = camera.position[2];
m_camera.worldup[0] = camera.worldup[0];
m_camera.worldup[1] = camera.worldup[1];
m_camera.worldup[2] = camera.worldup[2];
return GZ_SUCCESS;
}
int GzRender::GzPushMatrix(GzMatrix matrix)
{
/* HW 3.9
- push a matrix onto the Ximage stack
- check for stack overflow
*/
if (matlevel < MATLEVELS) {
Matrix_d4(Ximage[matlevel-1], matrix, Ximage[matlevel]);
matlevel = matlevel + 1;
}
else {
return GZ_FAILURE;
}
return GZ_SUCCESS;
}
int GzRender::GzPopMatrix()
{
/* HW 3.10
- pop a matrix off the Ximage stack
- check for stack underflow
*/
if (matlevel > 0) {
matlevel = matlevel - 1;
}
else {
return GZ_FAILURE;
}
return GZ_SUCCESS;
}
int GzRender::GzPut(int i, int j, GzIntensity r, GzIntensity g, GzIntensity b, GzIntensity a, GzDepth z)
{
/* HW1.4 write pixel values into the buffer */
if (framebuffer == NULL) {
return GZ_FAILURE;
}
if (i >= 0 && j >= 0 && i < xres && j < yres) {
//blue
if (b > MAXINTENSITY) {
(pixelbuffer[ARRAY(i, j)]).blue = MAXINTENSITY;
}
else if (b < 0) {
(pixelbuffer[ARRAY(i, j)]).blue = 0;
}
else {
(pixelbuffer[ARRAY(i, j)]).blue = b;
}
//green
if (g > MAXINTENSITY) {
(pixelbuffer[ARRAY(i, j)]).green = MAXINTENSITY;
}
else if (g < 0) {
(pixelbuffer[ARRAY(i, j)]).green = 0;
}
else {
(pixelbuffer[ARRAY(i, j)]).green = g;
}
//red
if (r > MAXINTENSITY) {
(pixelbuffer[ARRAY(i, j)]).red = MAXINTENSITY;
}
else if (r < 0) {
(pixelbuffer[ARRAY(i, j)]).red = 0;
}
else {
(pixelbuffer[ARRAY(i, j)]).red = r;
}
(pixelbuffer[ARRAY(i, j)]).alpha = a;
(pixelbuffer[ARRAY(i, j)]).z = z;
return GZ_SUCCESS;
}
else {
return GZ_FAILURE;
}
}
int GzRender::GzGet(int i, int j, GzIntensity *r, GzIntensity *g, GzIntensity *b, GzIntensity *a, GzDepth *z)
{
/* HW1.5 retrieve a pixel information from the pixel buffer */
if (i >= 0 && j >= 0 && i < xres && j < yres) {
*a = pixelbuffer[ARRAY(i, j)].alpha;
*r = pixelbuffer[ARRAY(i, j)].red;
*g = pixelbuffer[ARRAY(i, j)].green;
*b = pixelbuffer[ARRAY(i, j)].blue;
*z = pixelbuffer[ARRAY(i, j)].z;
return GZ_SUCCESS;
}
else {
return GZ_FAILURE;
}
}
int GzRender::GzFlushDisplay2File(FILE* outfile)
{
/* HW1.6 write image to ppm file -- "P6 %d %d 255\r" */
if (outfile == NULL) {
printf("File error!\n");
}
fprintf(outfile, "P6 %d %d 255\r", xres, yres);
int i, j;
for (i = 0; i < yres; i++) {
for (j = 0; j < xres; j++) {
char pb = pixelbuffer[ARRAY(j, i)].blue >> 4;
char pg = pixelbuffer[ARRAY(j, i)].green >> 4;
char pr = pixelbuffer[ARRAY(j, i)].red >> 4;
fprintf(outfile, "%c%c%c", pr, pg, pb);
}
}
return GZ_SUCCESS;
}
int GzRender::GzFlushDisplay2FrameBuffer()
{
/* HW1.7 write pixels to framebuffer:
- put the pixels into the frame buffer
- CAUTION: when storing the pixels into the frame buffer, the order is blue, green, and red
- NOT red, green, and blue !!!
*/
int i, j;
for (i = 0; i < yres; i++) {
for (j = 0; j < xres; j++) {
char pbb = pixelbuffer[ARRAY(j, i)].blue >> 4;
char pbg = pixelbuffer[ARRAY(j, i)].green >> 4;
char pbr = pixelbuffer[ARRAY(j, i)].red >> 4;
framebuffer[3 * ARRAY(j, i)] = pbb;
framebuffer[3 * ARRAY(j, i) + 1] = pbg;
framebuffer[3 * ARRAY(j, i) + 2] = pbr;
}
}
return GZ_SUCCESS;
}
/***********************************************/
/* HW2 methods: implement from here */
int GzRender::GzPutAttribute(int numAttributes, GzToken *nameList, GzPointer *valueList)
{
/* HW 2.1
-- Set renderer attribute states (e.g.: GZ_RGB_COLOR default color)
-- In later homeworks set shaders, interpolaters, texture maps, and lights
*/
for (int i = 0; i < numAttributes; i++) {
//gzrgbcolor
if (nameList[i] == GZ_RGB_COLOR) {
GzColor *tempcolor = (GzColor*)valueList[i];
flatcolor[0] = (*tempcolor)[0];
flatcolor[1] = (*tempcolor)[1];
flatcolor[2] = (*tempcolor)[2];
}
}
return GZ_SUCCESS;
}
void sortVertY(vector<Vertex> vertex, vector<Vertex> temp) {
int max = 0, min = 0, mid = 0;
for (int i = 0; i < 3; i++) {
if (vertex[i].y > vertex[max].y) {
max = i;
}
else if (vertex[i].y < vertex[min].y) {
min = i;
}
}
for (int m = 0; m < 3; m++) {
if (m != min && m != max) {
mid = m;
}
}
temp.push_back(vertex[max]);
temp.push_back(vertex[mid]);
temp.push_back(vertex[min]);
}
inline int CCDirection(vector<Vertex> vertex) {
float d, z, x2;
if (vertex.empty()) {
return GZ_FAILURE;
}
else {
d = (vertex[0].y - vertex[2].y) / (vertex[0].x - vertex[2].x);
z = vertex[0].y - d * vertex[0].x;
x2 = (vertex[1].y - z) / d;
//bottom hori
if ((float)(vertex[2].y - vertex[1].y) == 0) {
return 1;//bottom
}//top hori
else if ((float)(vertex[1].y - vertex[0].y) == 0) {
return 2;//top
}
else if (x2 > vertex[1].x) {
return 3;//left
}
else if (x2 < vertex[1].x) {
return 4;//right
}
else {
return GZ_FAILURE;
}
}
}
//set triangle
//top 1 0 | 1 0 bottom 0 | 0 left 0 |right 0
// 2 | 2 1 2 | 1 2 1 | 1
// 2 | 2
//edge e[0] 0-1 e[1] 1-2 e[2] 0-2
int setTri(int orient, vector<Edge>& edge, vector<Vertex>& v) {
if (v.empty() || edge.empty()) {
return GZ_FAILURE;
}
else {
edge[0].setEdge(v[0], v[1]);
edge[1].setEdge(v[1], v[2]);
edge[2].setEdge(v[0], v[2]);
}
return GZ_SUCCESS;
}
int GzRender::GzPutTriangle(int numParts, GzToken *nameList, GzPointer *valueList)
/* numParts - how many names and values */
{
/* HW 2.2
-- Pass in a triangle description with tokens and values corresponding to
GZ_NULL_TOKEN: do nothing - no values
GZ_POSITION: 3 vert positions in model space
-- Invoke the rastrizer/scanline framework
-- Return error code
*/
for (int count = 0; count < numParts; count++) {
//gzposition
vector<Vertex> v(3);
vector<Edge> e(3);
if (nameList[count] == GZ_POSITION) {
//setup triangle
GzCoord *CoTemp = (GzCoord*)valueList[count];
Vertex t_v, t_vm;
t_vm.x = 0;
t_vm.y = 0;
t_vm.z = 0;
v.clear();
//e.clear();
for (int k = 0; k < 3; k++) {
t_v.x = (*(CoTemp + k))[X];
t_v.y = (*(CoTemp + k))[Y];
t_v.z = (*(CoTemp + k))[Z];
//trs_V to model
t_vm = trs_v(t_v, Ximage[matlevel - 1], t_vm);
v.push_back(t_vm);
}
//cut triangle out of screen;
if (cut_tri(v, xres, yres) == 1){
continue;
}
//sort
vector<Vertex> v_sort;
//0-1-2 from top to bottom
int max = 0, min = 0, mid = 0;
for (int i = 0; i < 3; i++) {
if (v[i].y >= v[max].y) {
if (v[i].y > v[max].y || (v[i].y == v[max].y && v[i].x >= v[max].x)) {
max = i;
}
}
if (v[i].y <= v[min].y) {
if (v[i].y < v[min].y || (v[i].y == v[min].y && v[i].x >= v[min].x)) {
min = i;
}
}
}
for (int m = 0; m < 3; m++) {
if (m != min && m != max) {
mid = m;
}
}
v_sort.push_back(v[min]);
v_sort.push_back(v[mid]);
v_sort.push_back(v[max]);
int orient = CCDirection(v_sort);
setTri(orient, e, v_sort);
//scan
//default value
Span span;
float deltaY0, deltaY1;
float deltaX;
float deltaZ0, deltaZ1, deltaZ2;
float slopeX0, slopeX1, slopeX2;
float slopeZ0, slopeZ1, slopeZ2, slopeZ3;//Z3 for span
int i = 0;
int j = 0;
GzIntensity red;
GzIntensity green;
GzIntensity blue;
GzIntensity alpha;
GzDepth depthZ;
deltaX = 0;
deltaY0 = ceil(v_sort[0].y) - v_sort[0].y;
deltaY1 = ceil(v_sort[1].y) - v_sort[1].y;
if (e.empty()) { return GZ_FAILURE; }
else {
//edge 0:
slopeX0 = e[0].slopeX();
slopeZ0 = e[0].slopeZ();
e[0].current.x = e[0].start.x + slopeX0*deltaY0;
e[0].current.y = e[0].start.y + deltaY0;
e[0].current.z = e[0].start.z + slopeZ0*deltaY0;
//edge 2:
slopeX2 = e[2].slopeX();
slopeZ2 = e[2].slopeZ();
e[2].current.x = e[2].start.x + slopeX2*deltaY0;
e[2].current.y = e[2].start.y + deltaY0;
e[2].current.z = e[2].start.z + slopeZ2*deltaY0;
//top half side : v[1]:mid point 1 3+4
while (e[0].current.y < e[0].end.y) {
if (orient == 1 || orient == 3) { //bottom and left l:E0 r:E2
//x-line
span.setEdge(e[0].current, e[2].current);
deltaX = ceil(e[0].current.x) - e[0].current.x;
slopeZ3 = (e[2].current.z - e[0].current.z) / (e[2].current.x - e[0].current.x);
span.current.x = e[0].current.x + deltaX;
span.current.y = e[0].current.y;
span.current.z = e[0].current.z + deltaX*slopeZ3;
while (span.current.x < e[2].current.x) {
if (span.current.z < 0) {
continue;
}
//render
i = (int)span.current.x;
j = (int)span.current.y;
GzGet(i, j, &red, &green, &blue, &alpha, &depthZ);
if (depthZ == 0 || span.current.z < depthZ) {
GzPut(i, j, ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 0, (GzDepth)span.current.z);
}
span.current.x = span.current.x + 1;
span.current.z = span.current.z + slopeZ3;
}
}
else if (orient == 4) {//right l:E2 r:E0
//x-line
span.setEdge(e[2].current, e[0].current);
deltaX = ceil(e[2].current.x) - e[2].current.x;
slopeZ3 = (e[0].current.z - e[2].current.z) / (e[0].current.x - e[2].current.x);
span.current.x = e[2].current.x + deltaX;
span.current.y = e[2].current.y;
span.current.z = e[2].current.z + deltaX*slopeZ3;
while (span.current.x < e[0].current.x) {
if (span.current.z < 0) {
continue;
}
//render
i = (int)span.current.x;
j = (int)span.current.y;
GzGet(i, j, &red, &green, &blue, &alpha, &depthZ);
if (depthZ == 0 || span.current.z < depthZ) {
GzPut(i, j, ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 0, (GzDepth)span.current.z);
}
span.current.x = span.current.x + 1;
span.current.z = span.current.z + slopeZ3;
}
}
else if (orient == 2) {
break;
}
else {
return GZ_FAILURE;
}
e[0].current.x = e[0].current.x + slopeX0;
e[0].current.y = e[0].current.y + 1;
e[0].current.z = e[0].current.z + slopeZ0;
e[2].current.x = e[2].current.x + slopeX2;
e[2].current.y = e[2].current.y + 1;
e[2].current.z = e[2].current.z + slopeZ2;
}
//edge 1:
slopeX1 = e[1].slopeX();
slopeZ1 = e[1].slopeZ();
e[1].current.x = e[1].start.x + slopeX1*deltaY1;
e[1].current.y = e[1].start.y + deltaY1;
e[1].current.z = e[1].start.z + slopeZ1*deltaY1;
//low half side:v[1]:mid point 2 3 +4
while (e[1].current.y < e[1].end.y) {
if (orient == 2 || orient == 3) { //bottom and left l:E1 r:E2
//x-line
span.setEdge(e[1].current, e[2].current);
deltaX = ceil(e[1].current.x) - e[1].current.x;
slopeZ3 = (e[2].current.z - e[1].current.z) / (e[2].current.x - e[1].current.x);
span.current.x = e[1].current.x + deltaX;
span.current.y = e[1].current.y;
span.current.z = e[1].current.z + deltaX*slopeZ3;
while (span.current.x < e[2].current.x) {
if (span.current.z < 0) {
continue;
}
//render
i = (int)span.current.x;
j = (int)span.current.y; //choose curve
GzGet(i, j, &red, &green, &blue, &alpha, &depthZ);
if (depthZ == 0 || span.current.z < depthZ) {
GzPut(i, j, ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 0, (GzDepth)span.current.z);
}
span.current.x = span.current.x + 1;
span.current.z = span.current.z + slopeZ3;
}
}
else if (orient == 4) {//right l:E2 r:E1
//x-line
span.setEdge(e[2].current, e[1].current);
deltaX = ceil(e[2].current.x) - e[2].current.x;
slopeZ3 = (e[1].current.z - e[2].current.z) / (e[1].current.x - e[2].current.x);
span.current.x = e[2].current.x + deltaX;
span.current.y = e[2].current.y;
span.current.z = e[2].current.z + deltaX*slopeZ3;
while (span.current.x < e[1].current.x) {
if (span.current.z < 0) {
continue;
}
//render
i = (int)span.current.x;
j = (int)span.current.y;
GzGet(i, j, &red, &green, &blue, &alpha, &depthZ);
if (depthZ == 0 || span.current.z < depthZ) {
GzPut(i, j, ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 0, (GzDepth)span.current.z);
}
span.current.x = span.current.x + 1;
span.current.z = span.current.z + slopeZ3;
}
}
else if (orient == 1) {
break;
}
else {
return GZ_FAILURE;
}
e[1].current.x = e[1].current.x + slopeX1;
e[1].current.y = e[1].current.y + 1;
e[1].current.z = e[1].current.z + slopeZ1;
e[2].current.x = e[2].current.x + slopeX2;
e[2].current.y = e[2].current.y + 1;
e[2].current.z = e[2].current.z + slopeZ2;
}
}
}//gznulltoken
else if (nameList[count] == GZ_NULL_TOKEN) {
//do nothing
}
}
return GZ_SUCCESS;
}
| true |
0b4bc5bbb5359b4d8d786077e1c128e1edd19cba | C++ | danieljluna/Project-Perfect-Citizen | /Project-Perfect-Citizen/Code/Game/PipelineJobsAndIncomes.h | UTF-8 | 5,643 | 2.765625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <map>
namespace ppc {
//IF ADDING A JOB IT MUST BE PRESENT IN ALL LISTS OR THERE WILL BE
//PROBLEMS
const std::vector<std::string> JOBS_ALL = {
"Retail Sales Associate",
"Retail General Manager",
"Office Clerk",
"Chef",
"Line Cook",
"Nurse",
"Waitstaff",
"Customer Service",
"Janitor",
"Teacher",
"Manual Laborer",
"Secretary",
"Truck Driver",
"Sales",
"Mechanic",
"Administrative Assistant",
"Security Guard",
/*"Factory Worker",
"Housekeeping",
"Food Preparation",
"Landscaping",
"Construction",
"Doctor",
"Lawyer",
"Student",
"Police Officer",
"Firefighter",
"Software Engineer",
"Computer Engineer",
"System Administrator",
"Bartender",
"Child Care",
"Bank Teller",
"Accountant",
"Electrician",
"Dishwasher",
"Bus Driver",
"Plumber",
"Taxi Driver",
"Cosmetologist"*/
};
const std::map<std::string, int> STARTING_INCOME_MAP = {
{"Retail Sales Associate", 16 },
{"Retail General Manager", 29 },
{"Office Clerk", 20 },
{"Chef", 40 },
{"Line Cook", 18 },
{"Nurse", 39},
{"Waitstaff", 12 },
{"Customer Service", 25},
{"Janitor", 14 },
{"Teacher", 32 },
{"Manual Laborer", 19 },
{"Secretary", 19 },
{"Truck Driver", 30 },
{"Sales", 23 },
{"Mechanic", 24 },
{"Administrative Assistant", 26 },
{"Security Guard", 20 },
/* {"Factory Worker", },
{"Housekeeping", },
{"Food Preparation", },
{"Landscaping", },
{"Construction", },
{"Doctor", },
{"Lawyer", },
{"Student", },
{"Police Officer", },
{"Firefighter", },
{"Software Engineer", },
{"Computer Engineer", },
{"System Administrator", },
{"Bartender", },
{"Child Care", },
{"Bank Teller", },
{"Accountant", },
{"Electrician", },
{"Dishwasher", },
{"Bus Driver", },
{"Plumber", },
{"Taxi Driver", },
{"Cosmetologist", } */
};
const std::map<std::string, int> MEDIAN_INCOME_MAP = {
{ "Retail Sales Associate", 35 },
{ "Retail General Manager", 45 },
{ "Office Clerk", 29 },
{ "Chef", 56 },
{ "Line Cook", 27 },
{ "Nurse", 58 },
{ "Waitstaff", 25 },
{ "Customer Service", 32 },
{ "Janitor", 23 },
{ "Teacher", 46 },
{ "Manual Laborer", 34 },
{ "Secretary", 30 },
{ "Truck Driver", 49 },
{ "Sales", 40 },
{ "Mechanic", 42 },
{ "Administrative Assistant", 37 },
{ "Security Guard", 29 },
/* { "Factory Worker", },
{ "Housekeeping", },
{ "Food Preparation", },
{ "Landscaping", },
{ "Construction", },
{ "Doctor", },
{ "Lawyer", },
{ "Student", },
{ "Police Officer", },
{ "Firefighter", },
{ "Software Engineer", },
{ "Computer Engineer", },
{ "System Administrator", },
{ "Bartender", },
{ "Child Care", },
{ "Bank Teller", },
{ "Accountant", },
{ "Electrician", },
{ "Dishwasher", },
{ "Bus Driver", },
{ "Plumber", },
{ "Taxi Driver", },
{ "Cosmetologist", } */
};
const std::map<std::string, bool> INCOME_CAP = {
{ "Retail Sales Associate", true },
{ "Retail General Manager", true },
{ "Office Clerk", true },
{ "Chef", false },
{ "Line Cook", true },
{ "Nurse", false },
{ "Waitstaff", true },
{ "Customer Service", true },
{ "Janitor", true },
{ "Teacher", false },
{ "Manual Laborer", false },
{ "Secretary", false },
{ "Truck Driver", false },
{ "Sales", false },
{ "Mechanic", true },
{ "Administrative Assistant", true },
{ "Security Guard", true },
/*{ "Factory Worker", },
{ "Housekeeping", },
{ "Food Preparation", },
{ "Landscaping", },
{ "Construction", },
{ "Doctor", },
{ "Lawyer", },
{ "Student", },
{ "Police Officer", },
{ "Firefighter", },
{ "Software Engineer", },
{ "Computer Engineer", },
{ "System Administrator", },
{ "Bartender", },
{ "Child Care", },
{ "Bank Teller", },
{ "Accountant", },
{ "Electrician", },
{ "Dishwasher", },
{ "Bus Driver", },
{ "Plumber", },
{ "Taxi Driver", },
{ "Cosmetologist", }*/
};
/*
whoops probably unnecessary
const std::vector<std::string> JOBS_0 = {
"Retail Sales Associate",
"Retail General Manager",
"Chef",
"Line Cook",
"Waitstaff",
"Customer Service",
"Janitor",
"Manual Laborer",
"Security Guard",
"Truck Driver" ,
};
const std::vector<std::string> JOBS_1 = {
"Office Clerk",
"Secretary",
"Sales",
"Mechanic",
"Administrative Assistant",
};
const std::vector<std::string> JOBS_2 = {
};
const std::vector<std::string> JOBS_3 = {
"Teacher"
};
const std::vector<std::string> JOBS_4 = {
}
*/
// 0 - DID NOT GRADUATE HIGH SCHOOL, 1 - HIGH SCHOOL GRADUATE
// 2 - ASSOCIATE DEGREE, 3 - BACHELORS DEGREE,
// 4 - MASTERS DEGREE, 5 - DOCTORATE
const std::map<std::string, int> MIN_EDUCATION = {
{ "Retail Sales Associate", 0 },
{ "Retail General Manager", 0 },
{ "Office Clerk", 1 },
{ "Chef", 0 },
{ "Line Cook", 0 },
{ "Nurse", 4 },
{ "Waitstaff", 0 },
{ "Customer Service", 0 },
{ "Janitor", 0 },
{ "Teacher", 3 },
{ "Manual Laborer", 0 },
{ "Secretary", 1 },
{ "Truck Driver", 0 },
{ "Sales", 1 },
{ "Mechanic", 1 },
{ "Administrative Assistant", 1 },
{ "Security Guard", 0 },
/* {"Factory Worker", },
{"Housekeeping", },
{"Food Preparation", },
{"Landscaping", },
{"Construction", },
{"Doctor", },
{"Lawyer", },
{"Student", },
{"Police Officer", },
{"Firefighter", },
{"Software Engineer", },
{"Computer Engineer", },
{"System Administrator", },
{"Bartender", },
{"Child Care", },
{"Bank Teller", },
{"Accountant", },
{"Electrician", },
{"Dishwasher", },
{"Bus Driver", },
{"Plumber", },
{"Taxi Driver", },
{"Cosmetologist", } */
};
}; | true |
84163d44dc6e23ab1202496b2f7413d181b0ac8b | C++ | limbo018/Limbo | /limbo/thirdparty/dlx/test/nqueens/NQueens_test.cpp | UTF-8 | 1,047 | 2.796875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #include "../../example/nqueens/NQueens.hpp"
#include <gtest/gtest.h>
#include <algorithm>
namespace {
TEST(NQueens_test, zero) {
EXPECT_DEATH(NQueens(0), "Assertion");
}
TEST(NQueens_test, count_solutions) {
EXPECT_EQ(1, NQueens(1).count_solutions());
EXPECT_EQ(0, NQueens(2).count_solutions());
EXPECT_EQ(0, NQueens(3).count_solutions());
EXPECT_EQ(2, NQueens(4).count_solutions());
EXPECT_EQ(10, NQueens(5).count_solutions());
EXPECT_EQ(4, NQueens(6).count_solutions());
EXPECT_EQ(40, NQueens(7).count_solutions());
EXPECT_EQ(92, NQueens(8).count_solutions());
EXPECT_EQ(352, NQueens(9).count_solutions());
EXPECT_EQ(724, NQueens(10).count_solutions());
}
TEST(NQueens_test, find_solutions) {
EXPECT_TRUE(NQueens(2).find_solutions().empty());
EXPECT_EQ(std::vector<std::vector<unsigned>>{{0}}, NQueens(1).find_solutions());
auto n4 = NQueens(4).find_solutions();
std::sort(n4.begin(), n4.end());
EXPECT_EQ(
(std::vector<std::vector<unsigned>>{
{1,3,0,2},
{2,0,3,1}
}),
n4
);
}
}
| true |
b6efd787f8fd49af81f2174a41ec59d8faea978c | C++ | himani-singh-8899/Data_Structures_algorithms | /Stack/delete_middle.cpp | UTF-8 | 1,403 | 3.921875 | 4 | [] | no_license | /*
Input:
Stack = {1, 2, 3, 4, 5}
Output:
ModifiedStack = {1, 2, 4, 5}
Explanation:
As the number of elements is 5 ,
hence the middle element will be the 3rd
element which is deleted
*/
//Initial template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution
{
public:
//Function to delete middle element of a stack.
void deleteMid(stack<int>&s, int sizeOfStack)
{
stack <int> t;
int mid=sizeOfStack/2;
int count=0;
while(s.empty()==false && count<mid)
{
t.push(s.top());
s.pop();
count++;
}
s.pop();
while(t.empty()==false)
{
s.push(t.top());
t.pop();
}
}
};
// { Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--)
{
int sizeOfStack;
cin>>sizeOfStack;
stack<int> myStack;
for(int i=0;i<sizeOfStack;i++)
{
int x;
cin>>x;
myStack.push(x);
}
Solution ob;
ob.deleteMid(myStack,myStack.size());
while(!myStack.empty())
{
cout<<myStack.top()<<" ";
myStack.pop();
}
cout<<endl;
}
return 0;
}
// } Driver Code Ends
| true |
28872d1b237ac100d1b24849fa27e7a4dd2f69f5 | C++ | wjzhou/cuda-raytrace | /cuda_render/util/random/cudarandom.cpp | UTF-8 | 987 | 2.59375 | 3 | [] | no_license |
#include <stdio.h>
#include "cudarandom.h"
#include <curand.h>
#include "../cuda/helper_cuda.h"
class CudaRandom::impl
{
private:
impl(impl const &);
impl & operator=(impl const &);
curandGenerator_t prngGPU;
// private data
public:
impl(unsigned int seed)
{
checkCudaErrors(curandCreateGenerator(&prngGPU, CURAND_RNG_PSEUDO_MTGP32));
checkCudaErrors(curandSetPseudoRandomGeneratorSeed(prngGPU, seed));
}
~impl()
{
checkCudaErrors(curandDestroyGenerator(prngGPU));
}
void generate(float* d_Rand, unsigned int rand_n)
{
checkCudaErrors(curandGenerateUniform(prngGPU, d_Rand, rand_n));
}
};
CudaRandom::CudaRandom(unsigned int seed)
:pimpl_(new impl(seed))
{
}
//The unique_ptr need complete class definition for dtor. Thus, this method
//must been defined here
CudaRandom::~CudaRandom()
{
}
void CudaRandom::generate(float* d_Rand, unsigned int rand_n)
{
pimpl_->generate(d_Rand, rand_n);
}
| true |
5b4e349fff5ad68d0e475d14266a9313f127347d | C++ | lamer0k/RtosWrapper | /Application/ledsdriver.hpp | UTF-8 | 2,056 | 3 | 3 | [
"MIT"
] | permissive | /*******************************************************************************
* FILENAME: LedDriver.h
*
* DESCRIPTION:
*
* Copyright (c) 2018 by South Ural State Universaty
******************************************************************************/
#ifndef LEDDRIVER_H
#define LEDDRIVER_H
#include "leds.hpp" // For Led
#include "singleton.hpp" // for Singleton
#include <array> // for std::array
#include "gpioaregisters.hpp" // for GPIOA
#include "gpiocregisters.hpp" // for GPIOC
constexpr std::size_t ledsCount = 4U;
constexpr std::uint32_t led1Pin = 5U;
constexpr std::uint32_t led2Pin = 9U;
constexpr std::uint32_t led3Pin = 8U;
constexpr std::uint32_t led4Pin = 5U;
enum class LedNum
{
led1 = 0,
led2 = 1,
led3 = 2,
led4 = 3,
ledMax = ledsCount - 1
};
class LedsDriver : public Singleton<LedsDriver>
{
public:
inline void SwitchOnAll()
{
for(auto it: leds)
{
it.get().SwitchOn();
}
};
inline void SwitchOffAll()
{
for(auto it: leds)
{
it.get().SwitchOff();
}
};
inline void ToggleAll()
{
for(auto it: leds)
{
it.get().Toggle();
}
};
std::size_t GetLedsCount()
{
return leds.size();
};
inline ILed& GetLed(LedNum num)
{
return leds[static_cast<std::size_t>(num)];
}
friend class Singleton<LedsDriver>;
private:
LedsDriver() = default;
std::array<std::reference_wrapper<ILed>, ledsCount> leds {
Led<
Pin<Port<GPIOA>,
led1Pin,
PinWriteable>
>::GetInstance(),
Led<
Pin<Port<GPIOC>,
led2Pin,
PinWriteable>
>::GetInstance(),
Led<
Pin<Port<GPIOC>,
led3Pin,
PinWriteable>
>::GetInstance(),
Led<
Pin<Port<GPIOC>,
led4Pin,
PinWriteable>
>::GetInstance()
};
};
#endif | true |
51c73c543d42320f5a48ec8d7e72ba72d7a1fc1c | C++ | KOMMYHAP/education | /pattern_examples/proxy/shared_pointer/shared_pointer.h | UTF-8 | 5,990 | 3.71875 | 4 | [] | no_license | // interface for shared, unique, weak, etc pointers.
template <class T>
class pointer_base
{
public:
typedef T data_t;
private:
data_t *_data_ptr;
protected:
/** @param pointer: pointer on existing data
@brief: copy pointer
*/
pointer_base(data_t *pointer) noexcept
: _data_ptr(pointer) {}
// default c-tor initializes pointer with nullptr:
pointer_base() : _data_ptr(nullptr) {} noexcept
// copy c-tor copies other's pointer
pointer_base(pointer_base const &other) noexcept
: _data_ptr(other._data_ptr) {}
// move c-tor moves other's pointer
pointer_base(pointer_base &&other) noexcept
: _data_ptr(other._data_ptr)
{
other._data_ptr = nullptr;
}
// copy c-tor simply copies other's pointer but
// not removes old data
virtual
pointer_base& operator=(pointer_base const &other) noexcept
{
if (this == &other) return *this;
_data_ptr = other._data_ptr;
return *this;
}
// move c-tor simply moves other's pointer but
// not removes old data
virtual
pointer_base& operator=(pointer_base &&other) noexcept
{
if (this == &other) return *this;
_data_ptr = other._data_ptr;
other._data_ptr = nullptr;
return *this;
}
// however, pure d-tor need empty definition
virtual ~pointer_base() noexcept = 0;
virtual data_t* operator->() const noexcept
{
return data_ptr;
}
virtual data_t& operator*() const noexcept
{
return *data_ptr;
}
public:
inline
bool is_null() const noexcept
{
return _data_ptr == nullptr;
}
inline
bool operator!() const noexcept
{
return is_null();
}
inline
operator bool() const noexcept
{
return !is_null();
}
};
// empty definition for pure d-tor:
pointer_base::~pointer_base() {}
/**
@brief:
Every instance created increases counter
and every instance destructed decrease counter;
*/
template <class T>
class counter
{
public:
typedef T size_t;
private:
size_t *_counter_ptr {nullptr};
public:
counter() noexcept
: _counter_ptr(new size_t(1)) {}
counter(counter const &other) noexcept
: _counter_ptr(other._counter_ptr)
{
++(*_counter_ptr);
}
counter(counter &&other) noexcept
: _counter_ptr(other._counter_ptr)
{
other._counter_ptr = nullptr;
}
counter& operator=(counter const &other) noexcept
{
if (this == &other) return *this;
// decreases old counter:
--(*_counter_ptr);
// changes own counter on others counter:
_counter_ptr = other._counter_ptr;
// increases new counter:
++(*_counter_ptr);
return *this;
}
counter& operator=(counter &&other) noexcept
{
if (this == &other) return *this;
// decreases old counter:
--(*_counter_ptr);
// changes own counter on others counter:
_counter_ptr = other._counter_ptr;
// remove others counter:
other._counter_ptr = nullptr;
return *this;
}
~counter()
{
if (*_counter_ptr == 0) {
delete _counter_ptr;
}
}
inline
size_t use_count() const noexcept
{
return *_counter_ptr;
}
};
template <class T>
class shared_pointer
: public pointer_base<T>
{
public:
typedef unsigned int size_t;
private:
counter<size_t> _counter;
public:
typedef T data_t;
shared_pointer()
: pointer_base()
, counter() {}
shared_pointer(data_t *pointer)
: pointer_base(pointer)
, counter() {}
shared_pointer(shared_pointer const &other)
: pointer_base(static_cast<const &pointer_base>(&other))
,
};
/*
class shared_counter
{
public:
using size_t = unsigned int;
private:
size_t _counter {0};
public:
shared_counter() noexcept
: _counter(1) {}
shared_counter(shared_counter const &) = delete;
shared_counter& operator=(shared_counter const &) = delete;
shared_counter(shared_counter &&other) noexcept
: _counter(other._counter)
{
other._counter = 0;
}
shared_counter& operator=(shared_counter &&other) noexcept
{
if (this == &other) return *this;
_counter = other._counter;
other._counter = 0;
return *this;
}
~shared_counter() = default;
inline
size_t count() const noexcept
{
return _counter;
}
inline
bool is_zero() const noexcept
{
return _counter == 0;
}
inline
void inc() noexcept
{
++_counter;
}
inline
void dec() noexcept
{
--_counter;
}
};
template <class T>
class shared_pointer
{
public:
using data_t = T;
private:
data_t *_data_ptr {nullptr};
mutable shared_counter *_counter_ptr {nullptr};
//TODO: need read about "State" pattern...
void safe_remove() noexcept
{
// decrease counter:
if (!_counter_ptr->is_empty()) {
_counter_ptr->dec();
}
// if counter equals zero, than delete data;
if (_counter_ptr->is_empty()) {
delete _data_ptr;
_data_ptr = nullptr;
}
}
void remove_old_and_copy_new(shared_pointer const &other) noexcept
{
safe_remove();
if (!other._counter_ptr->is_empty()) {
// coping data pointer:
_data_ptr = other._data_ptr;
// changing counters:
_counter_ptr = other._counter_ptr;
}
}
void reset() noexcept
{
_data_ptr = nullptr;
_counter_ptr = nullptr;
}
public:
shared_pointer()
: _data_ptr(nullptr)
, _counter_ptr(new shared_counter) {}
explicit
shared_pointer(data_t *data_ptr)
: _data_ptr(data_ptr)
, _counter_ptr(new shared_counter) {}
shared_pointer(shared_pointer const &other)
: _data_ptr(other._data_ptr)
, _counter_ptr(other._counter_ptr)
{
if (_data_ptr != nullptr) {
_counter_ptr->inc();
}
}
shared_pointer(shared_pointer &&other)
: _data_ptr(other._data_ptr)
, _counter(other._counter)
{
other.reset();
}
shared_pointer<T>& operator=(shared_pointer const &other)
{
if (this == &other) return *this;
remove_old_and_copy_new(other);
return *this;
}
shared_pointer<T>& operator=(shared_pointer &&other)
{
if (this == &other) return *this;
remove_old_and_copy_new(other);
other.reset();
return *this;
}
~shared_pointer()
{
safe_remove();
}
T* operator->() const noexcept
{
return _data_ptr;
}
T& operator*() const noexcept
{
return *_data_ptr;
}
size_t use_count() const noexcept
{
return _counter;
}
};
*/ | true |
de54def23f517c2d2831a3bcce9e1e536c9f352c | C++ | zhqiu/My-OJ-Programs | /hw5/A.cpp | UTF-8 | 2,474 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <assert.h>
#include <queue>
#include <string.h>
#define N 10000
using namespace std;
struct node{
int id;
struct node* next;
};
struct vertex{
int id;
int color;
int part;
struct node* next;
};
void dfs(struct vertex* point, int start, int part){
point[start].part = part;
point[start].color = 1;
int nextpart;
if (part == 1) nextpart = 0;
else nextpart = 1;
struct node* p = point[start].next;
while (p != NULL)
{
if (point[p->id].color == 0)
{
dfs(point, p->id, nextpart);
}
p = p->next;
}
point[start].color = 2;
}
void bfs(struct vertex* point, int start, int max)
{
queue<int> q;
q.push(start);
int part=0;
int i=0;
while(i<=max){
int proc;
int size=q.size();
while(size>0){
proc=q.front();
q.pop();
point[proc].color=2;
point[proc].part=part;
i++;
node* p =point[proc].next;
while(p!=NULL){
if (point[p->id].color==0)
q.push(p->id);
p=p->next;
}
size--;
}
if(part==1) part=0;
else part=1;
}
}
int str2int(char* p){
char* s = p;
int res = 0;
while (*s<'0' || *s>'9')
s++;
while ((*s <= '9') && (*s >= '0')){
res = res * 10 + (*s - '0');
s++;
}
return res;
}
int main()
{
cout << "wo yi yue du guan yu chao xi de shuo ming" << endl;
vertex Point[N];
for (int i = 0; i<N; i++){
Point[i].id = i;
Point[i].color = 0;
Point[i].part = -1;
Point[i].next = NULL;
}
int max = -1;
int v_now = -1;
char* temp = new char[1000];
char* delim=" ";
while (cin.getline(temp, 1000))
{
v_now++;
char* p = strtok(temp, delim);
int order = 1;
int proc = -1;
while (p != NULL)
{
if (order == 1)
{
int number = str2int(p);
proc = number;
if (max<number) max = number;
}
else
{
struct node* newNode = new node;
int number = str2int(p);
if (max<number) max = number;
newNode->id = number;
newNode->next = Point[proc].next;
Point[proc].next = newNode;
}
p=strtok(NULL, delim);
}
if (v_now == max)
{
dfs(Point, 0, 0);
// bfs(Point, 0, max);
for (int i = 0; i<=max; i++)
if (Point[i].part == 0)
cout << i << endl;
for (int i = 0; i <N; i++)
{
Point[i].id = i;
Point[i].color = 0;
Point[i].part = -1;
struct node* d = Point[i].next;
while (d != NULL){
Point[i].next = d->next;
delete d;
d = Point[i].next;
}
Point[i].next=NULL;
}
max = -1;
v_now = -1;
}
}
return 0;
}
| true |
7a937171f6286d1bd439f8d79f3be1df555fdbc1 | C++ | akash-mankar/Coding | /Palindrome.cpp | UTF-8 | 855 | 2.953125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char* str = argv[1];
int len = strlen(str), N = 2*len+1;
char* hashStr = new char[N];
int* hashInt = new int[N];
bool hash = true;
int i = 0, index = 0;
while (i <= len)
{
hashInt[index] = 0;
if (hash)
{
hash = false;
hashStr[index++] = '#';
}
else
{
hashStr[index++] = str[i];
hash = true;
if (i == len)
{
hashStr[index] = 0;
break;
}
i++;
}
}
for (i = 1; i < N/2; i++)
{
for (int j = 0; j < N; j++)
{
if ((j - i >= 0) && (j + i < N) && (hashInt[j] == (i - 1)))
{
if (hashStr[j-i] == hashStr[j+i])
hashInt[j]++;
}
}
}
cout << hashStr << endl;
for (i = 0; i < N; i++)
{
cout << hashInt[i];
}
cout << endl;
return 0;
}
| true |
e9c0b34a7170c34a654e11cb69af64f03c936347 | C++ | vincentlie06/RPSains13-2020 | /C++/HamPath+Animasi.cpp | UTF-8 | 4,239 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <SFML/Graphics.hpp>
#include <math.h>
#include <vector>
using namespace std;
bool in(vector<int> vec, int args){
for(int x: vec){
if (args==x) return true;
}
return false;
}
void print_ham(vector<int> vec){
int s=vec.size();
cout<<vec[0];
for(int x=1; x<s; x++){
cout<<" -> "<<vec[x];
}
cout<<endl;
}
vector<vector<int>> find_connection(int node,int connection_count, vector<vector<int>> connections){
vector<vector<int>> arr;
for(int x=0; x<connection_count; x+=1){
if (connections[x][0]==node){
arr.push_back(connections[x]);
}
else if(connections[x][1]==node){
arr.push_back({node,connections[x][0]});
}
}
return arr;
}
void dfs(int node,vector<vector<vector<int>>> updated_con,vector<int>& storage,int node_count,vector<vector<int>>& ham_paths){
int updated_con_size=(updated_con[node]).size();
for(int a=0; a<updated_con_size;a+=1){
int current_node=updated_con[node][a][1];
if(!in(storage,current_node)){
storage.push_back(current_node);
dfs(current_node,updated_con,storage,node_count,ham_paths);
storage.pop_back();
}
}
if((storage.size())==node_count){
ham_paths.push_back(storage);
}
}
void find_ham(int node,vector<vector<vector<int>>> updated_con,int node_count,vector<vector<int>>& ham_paths){
vector<int> storage;
storage.push_back(node);
dfs(node,updated_con,storage,node_count,ham_paths);
}
float getDist(vector<float>x, vector<float> y){
float xDist=x[1]-y[1], yDist=x[0]-y[0];
float Dist=sqrt(xDist*xDist+yDist*yDist);
return Dist;
}
float getAngle(vector<float> p1, vector<float> p2){
float a=p2[1]-p1[1], b=p2[0]-p1[0];
float c=atan2(a,b);
float pi=2*acos(0.0);
return 360-(c*180/pi);
}
float zoom(vector<vector<float>> nodes){
vector<float> x=nodes[0], y=nodes[1];
return (250/getDist(x,y));
}
int main(){
vector<vector<float>> nodes={{0,0},{2,2},{2,0},{1,2}};
vector<vector<int>> connections={{0,1},{1,2},{1,3},{2,3}};
vector<vector<int>> ham_paths;
int node_count=nodes.size();
int connection_count=connections.size();
vector<vector<vector<int>>> updated_con;
for(int a=0; a<node_count; a+=1){
updated_con.push_back(find_connection(a,connection_count,connections));
}
for(int x=0; x<node_count; x+=1){
find_ham(x,updated_con,node_count,ham_paths);
}
cout<<"List of Hamiltonian Paths: "<<endl;
for(vector<int> ham_path: ham_paths){
print_ham(ham_path);
}
vector<vector<float>> zoomed_nodes;
float magnitude = zoom(nodes);
int WHeight=1000, WWidth=1000;
for (vector<float> x: nodes){
zoomed_nodes.push_back({x[0]*magnitude,x[1]*magnitude});
}
sf::RenderWindow window(sf::VideoMode(WHeight,WWidth), "Animation");
while (window.isOpen()){
sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
float Hcentre=WHeight/2, Wcentre=WWidth/2;
for (vector<int> x : connections){
sf::Vertex line[] =
{
sf::Vertex(sf::Vector2f(Hcentre+zoomed_nodes[x[0]][0], Wcentre-zoomed_nodes[x[0]][1])),
sf::Vertex(sf::Vector2f(Hcentre+zoomed_nodes[x[1]][0], Wcentre-zoomed_nodes[x[1]][1]))
};
window.draw(line, 2, sf::Lines);
}
for (vector<float> node : zoomed_nodes){
sf::CircleShape circle(10.f);
circle.setPosition(Hcentre+node[0]-10,Wcentre-node[1]-10);
window.draw(circle);
}
vector<int> path=ham_paths[0];
for (int i=0; i<node_count-1; i++){
vector<float> a=zoomed_nodes[path[i]], b=zoomed_nodes[path[i+1]];
float dist=getDist(a,b), angle=getAngle(a,b);
sf::RectangleShape line(sf::Vector2f(dist, 5.f));
line.rotate(angle);
line.setPosition(Hcentre+zoomed_nodes[i][0],Wcentre-zoomed_nodes[i][1]);
window.draw(line);
}
window.display();
}
}
| true |
ad0008cf3e4901da4f153886bd1d3f92b4c7e7dd | C++ | d-eremina/assembly | /microproject02/readers-writers.cpp | UTF-8 | 8,323 | 3.015625 | 3 | [] | no_license | /**
* Еремина Дарья Валерьевна
* Микропроект №2
* Вариант 8
*
* Задача о читателях и писателях-2 («грязное чтение»).
*
* Базу данных разделяют два типа потоков – читатели и писатели.
* Читатели выполняют транзакции, которые просматривают записи базы данных,
* транзакции писателей и просматривают и изменяют записи.
* Предполагается, что в начале БД находится в непротиворечивом состоянии
* (т.е. отношения между данными имеют смысл).
* Транзакции выполняются в режиме «грязного чтения»,
* то есть процесс-писатель не может получить доступ к БД только в том случае,
* если ее занял другой процесс-писатель, а процессы-читатели ему не мешают.
* Создать многопоточное приложение с потоками-писателями и потоками-читателями.
* Реализовать решение, используя семафоры, и не используя блокировки чтения-записи.
*/
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <random>
#include <csignal>
#include <string>
#include <ctime>
// Размер "базы данных"
const int dataSize = 3;
// Общий массив данных (база данных), к которому обращаются читатели/писатели
int data[dataSize];
// Двоичные семафоры
sem_t mutex = 1;
sem_t writing = 1;
sem_t reading = 1;
// Количество блоков итераций программы
unsigned int iter;
clock_t start;
// Глобальные переменне, отвечающие за число активных писателей/читателей
// и аналогично ожидающих писателей/читателей
int active_readers = 0;
int active_writers = 0;
int waiting_readers = 0;
int waiting_writers = 0;
// Генератор случайных чисел для изменений и получения значений из "базы данных"
std::mt19937 gen(6274674);
std::uniform_int_distribution<int> distIndex(0, dataSize - 1);
std::uniform_int_distribution<int> distValue(1, 100);
// Метод для чтения данных из базы
void *readData(void *param) {
int num = *((int *) param);
for (int i = 0; i < iter; ++i) {
// Начало критической секции
sem_wait(&mutex);
// Если существуют какие-либо писатели (активные или ожидающие),
// то данный читатель должен подождать окончания их работы,
// поэтому увеличиваем соответствующий счетчик
if (active_writers + waiting_writers > 0) {
++waiting_readers;
} else { // Иначе читатель может начать чтение
sem_post(&reading);
// Отражаем это также в соответствующем счетчике
++active_readers;
}
// Конец критической секции
sem_post(&mutex);
sem_wait(&reading);
// Имитация процесса чтения - получение случайного значения из массива
int index = distIndex(gen);
printf("%f: Reader №%d gets value %d from data[%d]\n", (float) (clock() - start) / CLOCKS_PER_SEC, num,
data[index], index);
// Начало критической секции
sem_wait(&mutex);
// В данный момент читатель окончил чтение, отражаем это в счетчике
--active_readers;
// Тогда если все активные читатели отработали,
// запускаем поток записи, если сейчас есть существующие писатели
if (active_readers == 0 && waiting_writers > 0) {
sem_post(&writing);
++active_writers;
--waiting_writers;
}
// Конец критической секции
sem_post(&mutex);
}
return nullptr;
}
// Метод для записи данных в базу
void *writeData(void *param) {
int num = *((int *) param);
for (int i = 0; i < iter; ++i) {
// Начало критической секции
sem_wait(&mutex);
// Если в данный момент происходит чтение/запись,
// то нужно подождать, чтобы начать записывать
if (active_writers + active_readers > 0) {
++waiting_writers;
} else { // Иначе можно просто начать запись
sem_post(&writing);
++active_writers;
}
// Конец критической секции
sem_post(&mutex);
sem_wait(&writing);
// Имитация процесса записи
int index = distIndex(gen);
int value = distValue(gen);
data[index] = value;
printf("%f: Writer №%d writes value %d to data[%d]\n", (float) (clock() - start) / CLOCKS_PER_SEC, num, value,
index);
fflush(stdout);
// Начало критической секции
sem_wait(&mutex);
// Писатель закончил запись
--active_writers;
// Если существуют ожидающие писатели,
// нужно начать запись
// (писатели в приоритете, так как наличие читателей не влияет на их доступ к базе)
if (waiting_writers > 0) {
sem_post(&writing);
++active_writers;
--waiting_writers;
} else if (waiting_readers > 0) { // Иначе если очереди ожидает читатель, дать ему получить данныые
sem_post(&reading);
++active_readers;
--waiting_readers;
}
// Конец критической секции
sem_post(&mutex);
}
return nullptr;
}
int main() {
int n_read;
int n_write;
std::cout << "Введите количество писателей: " << std::endl;
std::cin >> n_write;
while (n_write < 1 || n_write > 10) {
std::cout << "Количество должно быть в диапазоне [1; 10]: " << std::endl;
std::cin >> n_write;
}
std::cout << "Введите количество читателей: " << std::endl;
std::cin >> n_read;
while (n_read < 1 || n_read > 100) {
std::cout << "Количество должно быть в диапазоне [1; 100]: " << std::endl;
std::cin >> n_read;
}
std::cout << "Введите количество производимых итераций: " << std::endl;
std::cin >> iter;
while (iter < 1 || iter > 100) {
std::cout << "Количество должно быть в диапазоне [1; 100]: " << std::endl;
std::cin >> iter;
}
// Соответствующие потоки
pthread_t threadRE[n_read];
pthread_t threadWR[n_write];
// Создание потоков
for (int i = 0; i < n_write; i++) {
pthread_create(&(threadWR[i]), nullptr, writeData, (void *) &i);
}
for (int i = 0; i < n_read; i++) {
pthread_create(&(threadRE[i]), nullptr, readData, (void *) &i);
}
start = clock();
for (auto &i : threadRE) {
pthread_join(i, nullptr);
}
for (auto &i : threadWR) {
pthread_join(i, nullptr);
}
return 0;
} | true |
75861e3df3ecad0811682b2d6599490d3998e5a1 | C++ | MikhailGoriachev/C-C | /16. 09.02.2021 - Указатели. Двумерные динамические массивы. Файлы заголовков/1. Class work/1. Teacher/CPP_Pointers/CPP_Pointers/main.cpp | UTF-8 | 5,491 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include "myio.h"
using namespace std;
// принимает массив и символ, подсчитывает, сколько раз символ встечается в массиве
size_t check2DCharArray(char a[3][4], char ch)
{
int n = 0;
for (size_t i = 0; i < 3; i++)
{
for (size_t k = 0; k < 4; k++)
{
if (a[i][k] == ch)
n++;
if (n > 1)
return 2;
}
}
return n;
}
// печать одномерного массива
void printArray(char a[], size_t size)
{
for (size_t i = 0; i < size; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
// Функция принимает число и возвращает "перевёрнутое" число: 123 = > 321
unsigned int numberReverse(unsigned int num)
{
unsigned int result = 0;
while (num > 0)
{
int delta = num % 10;
num = num / 10;
result = result*10 + delta;
}
return result;
}
void main()
{
/*
int a;
a = 3;
// вывести адрес переменной a
cout << &a << endl;
// создать указатель и поместить в него адрес переменной a
int* p = &a;
// вывести адрес, который хранится в указателе p
cout << p << endl;
// вывести значение, на которое указывает указатель
cout << *p << endl;
// объявить массив (константный указатель на 0 ячейку массива)
int b[5] = { 1, 2, 3, 4, 5 };
cout << b[0] << endl;
// вывод адреса массива
cout << b << endl;
// объявить указатель p2 и поместить в него адрес массива b
int* p2 = b;
// изменение массива b через указатель p2
p2[0] = 12;
for (size_t i = 0; i < 5; i++)
{
cout << b[i] << " ";
}
cout << endl;
// помещение в указатель p2 адреса, взятого из указателя p
p2 = p;
// работа с динамическим массивом
cout << "Enter size of array: ";
int arrSize;
cin >> arrSize;
float* arr = new float[arrSize];
for (size_t i = 0; i < arrSize; i++)
{
arr[i] = i + 1;
cout << arr[i] << " ";
}
cout << endl;
delete[] arr;*/
// 2. Функция принимает 2D-массив символов 3x4 и копирует в динамический одномерный массив
// все символы без повторений
/*char letters[3][4];
// ввод двумерного массива
enter2DCharArray(letters);
// подсчёт количества неповторяющихся элементов
size_t counter = 0;
for (size_t i = 0; i < 3; i++)
{
for (size_t k = 0; k < 4; k++)
{
if (check2DCharArray(letters, letters[i][k]) == 1)
counter++;
}
}
// печать двумерного массива
print2DCharArray(letters);
char* letters2 = new char[counter];
// копирование неповторяющихся элементов в одномерный массив
size_t n = 0;
for (size_t i = 0; i < 3; i++)
{
for (size_t k = 0; k < 4; k++)
{
if (check2DCharArray(letters, letters[i][k]) < 2)
letters2[n++] = letters[i][k];
}
}
// печать результата
printArray(letters2, counter);
delete[] letters2;*/
// 3. Функция принимает 2 строки и добавляет 2 строку в конец первой в перевёрнутом виде и помещает это всё в третью
// динамическую строку
/*char s[40], s2[40];
cout << "Enter first string: ";
cin >> s;
cout << "Enter second string: ";
cin >> s2;
// длина первой строки
size_t length = strlen(s);
// длина второй строки
size_t length2 = strlen(s2);
// выделение памяти по результат
char* s3 = new char[length + length2 + 1];
// копирование первой строки
strcpy(s3, s);
// копирование перевёрнутой второй строки
int k = length;
for (int i = length2-1; i>=0; i--)
{
s3[k++] = s2[i];
}
s3[length + length2] = 0;
cout << "Result: " << s3 << endl;
// освобождение памяти
delete[] s3;*/
// Функция принимает число и возвращает "перевёрнутое" число: 123 => 321
/*int num;
cin >> num;
cout << numberReverse(num) << endl;*/
// ДВУМЕРНЫЕ ДИНАМИЧЕСКИЕ МАССИВЫ
/*size_t rows = 3;
size_t cols = 4;
cout << "Enter rows number: ";
cin >> rows;
cout << "Enter cols number: ";
cin >> cols;
int** a = new int* [rows];
for (size_t i = 0; i < rows; i++)
{
a[i] = new int[cols];
}
enter2DArray(a, cols, rows);
print2DArray(a, cols, rows);
for (size_t i = 0; i < rows; i++)
{
delete[] a[i];
}
delete[] a;*/
// двумерный динамический массив с различной длиной строк
size_t rows = 3;
cout << "Enter rows number: ";
cin >> rows;
int** a = new int* [rows];
for (size_t i = 0; i < rows; i++)
{
a[i] = new int[i+1];
for (size_t k = 0; k < i+1; k++)
{
a[i][k] = i + k + 1;
}
}
for (size_t i = 0; i < rows; i++)
{
for (size_t k = 0; k < i + 1; k++)
{
cout << a[i][k] << " ";
}
cout << endl;
}
for (size_t i = 0; i < rows; i++)
{
delete[] a[i];
}
delete[] a;
} | true |
dd1752718e1a7d33004e9b8d4c494edc878d6106 | C++ | Igor-amateur/mvp-for-license-service-project | /Linux_C++_server/src/file_parser.cpp | UTF-8 | 4,626 | 2.84375 | 3 | [] | no_license | #include"file_parser.h"
#include<fstream>
#include<sstream>
#include<map>
#include<vector>
#include<exception>
#include<memory>
#include <cstdlib>
#include<string.h>
using namespace std;
TargetPoint::TargetPoint(int port, string ip_addres, double time_dur)
{
port_ = port;
ip_addres_ = ip_addres;
time_dur_ = time_dur;
}
void TargetPoint::SetPort(int port)
{
port_ = port;
}
void TargetPoint::SetIPaddres(string ip_addres)
{
ip_addres_ = ip_addres;
}
void TargetPoint::SetTimeDuration(double time_dur)
{
time_dur_ = time_dur;
}
std::ostream& operator << (std::ostream &out, const TargetPoint &targetPoint)
{
// Поскольку operator<< является другом класса Point, то мы имеем прямой доступ к членам Point
out << "PORT_FLAG" << std::endl;
out << targetPoint.port_ << std::endl;
out << "IP_ADDRESS_FLAG" << std::endl;
out << targetPoint.ip_addres_ << std::endl;
out << "TIME_DUR_FLAG" << std::endl;
out << targetPoint.time_dur_ << std::endl;
return out;
}
std::wostream& operator << (std::wostream &out, const TargetPoint &targetPoint)
{
// Поскольку operator<< является другом класса Point, то мы имеем прямой доступ к членам Point
out << L"PORT_FLAG" << std::endl;
out << targetPoint.port_ << std::endl;
std::mbstate_t state = std::mbstate_t();
char *str_surs(new char[targetPoint.ip_addres_.size() + 1]);
strcpy(str_surs, targetPoint.ip_addres_.c_str());
std::size_t len = 1 + std::mbsrtowcs(NULL , (const char**)&str_surs, 0 , &state);
std::wstring wstr;
wstr.resize(len,'\0');
std::mbsrtowcs(&wstr[0], (const char**)&str_surs, wstr.size(), &state);
out << L"IP_ADDRESS_FLAG" << std::endl;
out << wstr << std::endl;
out << L"TIME_DUR_FLAG" << std::endl;
out << targetPoint.time_dur_ << std::endl;
return out;
}
// std::wifstream
std::wistream& operator >> (std::wistream &winput, TargetPoint &targetPoint)
{
// Поскольку operator<< является другом класса Point, то мы имеем прямой доступ к членам Point
wstring wline;
while(getline(winput, wline))
{
if(L"PORT_FLAG" == wline)
{
getline(winput, wline);
wstringstream ss(wline);
targetPoint.is_parsed_ = true;
int port(0);
if(ss >> port)
targetPoint.SetPort(port);
}
else if(L"TIME_DUR_FLAG" == wline)
{
getline(winput, wline);
wstringstream wss(wline);
targetPoint.is_parsed_ = true;
double time_dur(0.0);
if(wss >> time_dur)
targetPoint.SetTimeDuration(time_dur);
}
else if(L"IP_ADDRESS_FLAG" == wline)
{
targetPoint.is_parsed_ = true;
if(getline(winput, wline))
targetPoint.SetIPaddres(string(wline.begin(), wline.end()));
}
}
return winput;
}
std::istream& operator >> (std::istream &input, TargetPoint &targetPoint)
{
// Поскольку operator<< является другом класса Point, то мы имеем прямой доступ к членам Point
string line;
while(getline(input, line))
{
if("PORT_FLAG" == line)
{
getline(input, line);
stringstream ss(line);
targetPoint.is_parsed_ = true;
int port(0);
if(ss >> port)
targetPoint.SetPort(port);
}
else if("TIME_DUR_FLAG" == line)
{
getline(input, line);
stringstream ss(line);
double time_dur(0.0);
targetPoint.is_parsed_ = true;
if(ss >> time_dur)
targetPoint.SetTimeDuration(time_dur);
}
else if("IP_ADDRESS_FLAG" == line)
{
targetPoint.is_parsed_ = true;
if(getline(input, line))
targetPoint.SetIPaddres(line);
}
}
return input;
}
bool fileExist(const string& fileName)
{
ifstream file(fileName);
auto result(file.is_open());
file.close();
return result;
}
const TargetPoint& fileSaver(const TargetPoint& targetPoint, const string& fileName)
{
ofstream file(fileName, ios_base::out | ios_base::trunc);
file << targetPoint;
file.close();
return targetPoint;
}
TargetPoint& fileParser(TargetPoint& targetPoint, const string& fileName)
{
std::ifstream input(fileName);
input >> targetPoint;
input.close();
if(targetPoint.is_parsed_)
return targetPoint;
std::wifstream winput(fileName);
winput >> targetPoint;
winput.close();
return targetPoint;
}
| true |
ba7b9eb0b995c03dde2e7490ab0decd6a3640f47 | C++ | OleksandrVoronin/UbisoftNext2021 | /GameTest/Gameplay/WaveChoreographer.h | UTF-8 | 1,955 | 2.859375 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <stdlib.h>
#include "EnemySpawner.h"
#include "TowerDefenseArena.h"
#include "Enemies/EnemyBoss.h"
#include "Enemies/EnemyCorner.h"
#include "Enemies/EnemyHeavy.h"
#include "Enemies/EnemyScout.h"
#include "Enemies/EnemySoldier.h"
class TowerDefenseArena;
class WaveChoreographer
{
public:
WaveChoreographer(TowerDefenseArena* arena);
void Update();
boolean GetIsWaveInProgress() const
{
return isWaveInProgress;
}
float GetTimeUntilNextWave() const
{
return lastWaveFinishTimestamp + waveDelay - arena->GetTimeElapsed();
}
int GetWaveNumber() const
{
return wave;
}
private:
int wave = 0;
TowerDefenseArena* arena;
std::vector<IEnemySpawner*> enemySpawners;
const int BOSS_SPAWNER_ID = 0;
const int waveDelay = 20;
boolean isWaveInProgress = false;
int enemiesLeftThisBurst = 0;
float burstFinishTimestamp = std::numeric_limits<float>::lowest();
float lastSpawnTimestamp = std::numeric_limits<float>::lowest();
float lastWaveFinishTimestamp = std::numeric_limits<float>::lowest();
// Total counts of enemies allocated for this wave
int totalEnemies = 0;
int spawnedEnemies = 0;
// Total strength of this level
int GetWaveStrength() const
{
return 20 * wave;
}
// Delay between bursts (multiple spawns within a short timeframe).
float GetBurstDelay() const
{
return max(0.5f, 3 - (wave * 0.1f));
}
// Enemies to spawn within this burst.
int GetEnemiesCountThisBurst() const
{
return 5 * wave;
}
// Delay between spawns within a burst.
float GetBurstSpawnDelay() const
{
return max(0.1f, 1 - (wave * 0.05f));
}
// Stat multiplier applied to all new enemies.
float GetStrengthMultiplier() const
{
return 1 + 0.2f * wave;
}
void GenerateNextWave();
};
| true |
9e2064e549140c68ea5d5c0042710533cd1490c6 | C++ | oyiadin/Schoolworks | /Data Structure (2018-2019)/Homework - Month1/P17.2.11.cpp | UTF-8 | 1,350 | 3.71875 | 4 | [] | no_license | template <typename T>
int binary_search(const T &elem, const T *va, int length);
template <typename T>
void insert_into_nonstrictly_increasing_ordered_list(const T &elem, T *va, int &length) {
int pos = binary_search(elem, va, length);
for (int i = length; i > pos; --i)
// move move move!
va[i] = va[i-1];
va[pos] = elem;
++length;
}
template <typename T>
int binary_search(const T &elem, const T *va, const int length) {
// @return:
// the appropriate position to put the element in
// IMPORTANT:
// this function ISN'T meant to find EXACTLY where `elem` is
// exit the recursions when R == L+1 (that is, M == L)
// special case: the array is empty
if (length == 0)
return 0;
int L = 0, R = length - 1, M = (L+R)/2;
// special case: out of the range of `va`
// can also deal with the case that (length == 1)
if (elem < va[L])
return L;
else if (elem > va[R])
return R+1;
if (va[M] > elem) {
if (M == L)
return -1;
else
return L+binary_search(elem, va+L, M-L+1); // [L, M]
} else if (va[M] < elem) {
if (M == L)
return M+1;
else
return M+binary_search(elem, va+M, R-M+1); // [M, R]
} else { // va[M] == elem
return M;
}
}
| true |
72bde314c36b1b29411be7f7cf795c82b3670765 | C++ | letusget/Cplusplus_work | /无用:随机读写文件程序/随机读写文件程序/源.cpp | GB18030 | 7,738 | 3.171875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<fstream>
#include<cstring>
#include<cstdlib>
#include<cctype>
using namespace std;
const int header_size = 256;
const char Taken = 'T';
const char Free = 'F';
const char Deleted = 'D';
class frandom :public fstream {
public:
frandom();
frandom(const char*);//ʼopen exsiting file
frandom(const char*, int, int, int);//ʼopen new file
~frandom();//رļ
void open(const char*, int, int, int);//open new file
void open(const char*);//open exsting file
void close();//ļر
long get_slots()const { return slots; }//ļɵļ¼
long get_key_size()const { return key_size; }//ؼֵij
long get_total_bytes()const { return total_bytes; }//ǰļֽ
long get_no_records()const { return no_records; }//Ѵ洢ļ¼
bool add_record(char*);//ӹؼ
bool find_record(char*);//ҹؼ
bool remove_record(char*);//ɾؼ
private:
//ļͷϢ
long slots;//ļɵļ¼
long record_size;//ʵʵļ¼Сʶ
long key_size;//ؼֵij
long total_bytes;//ļֽ
long no_records;//Ѵ洢ļ¼
long loc_address; //¼ɴ洢λ
char* buffer;//洢һ¼
char* stored_key; //洢ؼ֣null)
long get_address(const char*)const;
bool locate(char*);
};
//ļǷ,
frandom::~frandom() {
if (is_open())//fstreamڿ⺯
{
//ɾ̬Ĵ洢
delete[] stored_key;
delete[] buffer;
char buff[header_size];
for (int i = 0; i < header_size; i++)
buff[i] = ' ';
//д¹ļͷ
sprintf(buff, "%ld %ld %ld %ld", slots, record_size, key_size, no_records);
seekp(0, ios_base::beg);
write(buff, header_size);
}
}
//ʼԱ
frandom::frandom() :fstream() {
buffer = stored_key = 0;
slots = record_size = key_size = 0;
total_bytes = no_records = 0;
}
//ĬϹ캯
frandom::frandom(const char* filename) : fstream() {
buffer = stored_key = 0;
open(filename);
}
//ļļ
frandom::frandom(const char* filename, int s1, int actual_record_size, int ks) :fstream() {
buffer = stored_key = 0;
open(filename, s1, actual_record_size, ks);
}
//Ѵڵļ
void frandom::open(const char* filename)
{
fstream::open(filename, ios::in | ios::out | ios::binary);
if (is_open())
{
//ļͷ
char buff[header_size];
read(buff, header_size);
//sscanfӹ̶жȡݶ
sscanf(buff, "%ld %ld %ld %ld", &slots, &record_size, &key_size, &no_records);
total_bytes = slots * record_size + header_size;//ֽ
stored_key = new char[key_size + 1];//ÿһɴ洢ļ¼С
buffer = new char[record_size];
}
}
//ļ
void frandom::open(const char* filename, int s1, int actual_record_size, int ks)
{
fstream::open(filename, ios::in | ios::out | ios::binary);
//ļ
if (is_open()) {
setstate(ios::failbit);
fstream::close();
return;
}
//ʧʱµļ
fstream::open(filename, ios::out | ios::binary);
if (is_open())
fstream::close();
fstream::open(filename, ios::in | ios::out | ios::binary);
if (is_open()) {
//ʼ
clear();
char buff[header_size];
slots = s1;
record_size = actual_record_size + 1;
key_size = ks;
total_bytes = slots * record_size + header_size;
no_records = 0;
//Ϊؼַռ
stored_key = new char[key_size + 1];
for (int i = 0; i < header_size; i++)
buff[i] = ' ';
//дļͷϢ
sprintf(buff, "%ld %ld %ld %ld", slots, record_size, key_size, no_records);
write(buff, header_size);
//Ϊ¼洢
buffer = new char[record_size];
for (int i = 1; i < record_size; i++)
buffer[i] = ' ';
buffer[0] = Free;//ʼ
for (int i = 0; i < slots; i++)//ע˴д涨СַӰbitͳ
write(buffer, record_size);
}
}
long frandom::get_address(const char* key)const {
memcpy(stored_key, key, key_size);//ؼstored_key <- key
stored_key[key_size] = '\0';
return (atol(stored_key) % slots) * record_size + header_size;//ϣʼַ
}
//Ѱ¼
bool frandom::locate(char* key) {
long address, start_address, unocc_address;
int delete_flag = false;
address = get_address(key);//ȡǰĹϣַ
unocc_address = start_address = address;
do {
seekg(address, ios::beg);//λǰĵַ
switch (get()) {//ȡļеǰλõַɾ
case Deleted:
if (!delete_flag) {
unocc_address = address;
delete_flag = true;
}
break;
case Free:
loc_address = delete_flag ? unocc_address : address;
return false;
case Taken:
seekg(address + 1, ios::beg);
read(stored_key, key_size);
if (memcmp(key, stored_key, key_size) == 0) {
loc_address = address;
return true;
}
break;
}
address += record_size;
if (address >= total_bytes)//ʵֲѭΪǹϣ洢
address = header_size;
} while (address != start_address);
loc_address = unocc_address;
return false;//ûҵ
}
bool frandom::add_record(char* record) {
//ʵʼ¼ѾKʱѾڸô
if (no_records >= slots || locate(record))
return false;
//λ
seekp(loc_address, ios::beg);
//дǷ T
write(&Taken, 1);
//д洢ַϢ
write(record, record_size - 1);
//¼һ
no_records++;
//ӳɹ
return true;
}
bool frandom::find_record(char* record) {
//λ
if (locate(record)) {
seekg(loc_address + 1, ios::beg);
//ȡ洢
read(record, record_size - 1);
return true;
}
else
return false;
}
bool frandom::remove_record(char* key) {
if (locate(key)) {
--no_records;
seekp(loc_address, ios::beg);
write(&Deleted, 1);//ɾ¼ʶΪ D
return true;
}
else
return false;
}
void frandom::close() {
if (is_open()) {
delete[] stored_key;//ջ
delete[] buffer;
char buff[header_size];
for (int i = 0; i < header_size; i++)
buff[i] = ' ';
sprintf(buff, "%ld %ld %ld %ld", slots, record_size, key_size, no_records);
seekp(0, ios::beg);
write(buff, header_size);
fstream::close();
}
}
int main()
{
char b[10], c;
frandom findout;
remove("data.dat");
cout << "New file(Y/N)?";
cin >> c;
if (toupper(c) == 'Y') {
findout.open("data.dat", 15, 5, 3);
if (!findout) {
cerr << "Couldn't open file" << endl;
return EXIT_FAILURE;
}
}
else {
findout.open("data.dat");
if (!findout) {
cerr << "Couldn't open file" << endl;
return EXIT_FAILURE;
}
}
do {
cout << "\n\n[A]dd\n[F]ind\n[R]emove\n[Q]uit?";
cin >> c;
switch (toupper(c))
{
case 'A':
cout << "Which record to add?";
cin >> b;
if (findout.add_record(b))
cout << "Record added" << endl;
else
cout << "Record not added" << endl;
break;
case 'F':
cout << "key?";
cin >> b;
if (findout.find_record(b)) {
b[5] = '\0';
cout << "Record found:" << b << endl;
}
else
cout << "Record not found" << endl;
break;
case 'R':
cout << "key?";
cin >> b;
if (findout.remove_record(b))
cout << "Record removed" << b << endl;
else
cout << "Record not removed" << endl;
break;
case 'Q':
break;
default:
cout << "Illegal choice" << endl;
break;
}
} while (toupper(c) != 'Q');
system("pause");
}
| true |
81d9ac2e606929428b232427443485651af0c074 | C++ | UBIC-repo/core | /NtpEsk/NtpEskSignatureRequestObject.h | UTF-8 | 2,048 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/bn.h>
#include <vector>
#ifndef NTPESK_NTPESKSIGNATUREREQUESTOBJECT_H
#define NTPESK_NTPESKSIGNATUREREQUESTOBJECT_H
class NtpEskSignatureRequestObject {
private:
const EC_POINT *pubKey;
const EC_GROUP *curveParams;
const BIGNUM *r;
const BIGNUM *s;
std::vector<unsigned char> messageHash;
std::vector<unsigned char> newMessageHash;
uint16_t mdAlg;
std::vector<unsigned char> signedPayload;
public:
const EC_POINT* getPubKey() const {
return pubKey;
}
void setPubKey(const EC_POINT *pubKey) {
this->pubKey = pubKey;
}
const EC_GROUP *getCurveParams() const {
return this->curveParams;
}
void setCurveParams(const EC_GROUP *curveParams) {
this->curveParams = curveParams;
}
const BIGNUM *getR() const {
return this->r;
}
void setR(const BIGNUM *r) {
this->r = r;
}
const BIGNUM *getS() const {
return this->s;
}
void setS(const BIGNUM *s) {
this->s = s;
}
const std::vector<unsigned char> &getMessageHash() const {
return this->messageHash;
}
void setMessageHash(const std::vector<unsigned char> &messageHash) {
this->messageHash = messageHash;
}
const std::vector<unsigned char> &getNewMessageHash() const {
return this->newMessageHash;
}
void setNewMessageHash(const std::vector<unsigned char> &newMessageHash) {
this->newMessageHash = newMessageHash;
}
uint16_t getMdAlg() const {
return mdAlg;
}
void setMdAlg(uint16_t mdAlg) {
NtpEskSignatureRequestObject::mdAlg = mdAlg;
}
const std::vector<unsigned char> &getSignedPayload() const {
return signedPayload;
}
void setSignedPayload(const std::vector<unsigned char> &signedPayload) {
NtpEskSignatureRequestObject::signedPayload = signedPayload;
}
};
#endif //NTPESK_NTPESKSIGNATUREREQUESTOBJECT_H
| true |
8b9958ff8e9a6af0317afa4a6fb3d135385d0cd2 | C++ | niuxu18/logTracker-old | /second/download/git/gumtree/git_repos_function_6813_git-2.11.4.cpp | UTF-8 | 345 | 2.53125 | 3 | [] | no_license | static struct entry *lookup_entry(unsigned char *sha1)
{
int low = 0, high = nr_convert;
while (low < high) {
int next = (low + high) / 2;
struct entry *n = convert[next];
int cmp = hashcmp(sha1, n->old_sha1);
if (!cmp)
return n;
if (cmp < 0) {
high = next;
continue;
}
low = next+1;
}
return insert_new(sha1, low);
} | true |
7ec01f4b5f74cfc0f24d73a6b66d511fa2042406 | C++ | JackeryShh/CPPlayGround | /XcodeCPPTest/DataAndStruction/BinaryTree.cpp | UTF-8 | 1,155 | 2.8125 | 3 | [] | no_license | //
// BinaryTree.cpp
// XcodeCPPTest
//
// Created by jackery on 2018/3/25.
// Copyright © 2018年 jackery. All rights reserved.
//
#include <stdio.h>
#include "iostream"
#include "BinaryTree.h"
#include <deque>
using namespace std;
CBinaryTree::CBinaryTree():pRoot(nullptr)
{
cout << "wow,great!" <<endl;
deque<int> test;
}
CBinaryTree::~CBinaryTree()
{
}
void CBinaryTree::CreateBinaryTree(int nodeNumber)
{
if (!pRoot) {
pRoot =new Node;
}
int value;
cin >>value;
pRoot->data=value;
pRoot->leftChild=nullptr;
pRoot->rightChild=nullptr;
nodeNumber--;
while(nodeNumber)
{
cin >>value;
_pNode left=new Node;
left->data=value;
left->rightChild=nullptr;
left->leftChild=nullptr;
pRoot->leftChild=left;
nodeNumber--;
if(nodeNumber!=0)
{
cin >>value;
_pNode right=new Node;
right->data=value;
right->leftChild=nullptr;
right->rightChild=nullptr;
pRoot->rightChild=right;
nodeNumber--;
}
}
}
| true |
200f027cc52be77d7d47f15a513ecf1b8c58cae4 | C++ | YoucefSklab/utymap | /core/src/index/GeoStore.hpp | UTF-8 | 2,979 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #ifndef INDEX_GEOSTORE_HPP_DEFINED
#define INDEX_GEOSTORE_HPP_DEFINED
#include "BoundingBox.hpp"
#include "CancellationToken.hpp"
#include "GeoCoordinate.hpp"
#include "LodRange.hpp"
#include "QuadKey.hpp"
#include "entities/Element.hpp"
#include "entities/ElementVisitor.hpp"
#include "index/ElementStore.hpp"
#include "index/StringTable.hpp"
#include "mapcss/StyleProvider.hpp"
#include <memory>
namespace utymap {
namespace index {
/// Provides API to store and access geo data using different underlying data stores.
class GeoStore final {
public:
explicit GeoStore(const utymap::index::StringTable &stringTable);
~GeoStore();
/// Adds underlying element store for usage.
void registerStore(const std::string &storeKey,
std::unique_ptr<ElementStore> store);
/// Adds element to selected store.
void add(const std::string &storeKey,
const utymap::entities::Element &element,
const utymap::LodRange &range,
const utymap::mapcss::StyleProvider &styleProvider,
const utymap::CancellationToken &cancelToken);
/// Adds all data from file to selected store in given level of detail range.
void add(const std::string &storeKey,
const std::string &path,
const utymap::LodRange &range,
const utymap::mapcss::StyleProvider &styleProvider,
const utymap::CancellationToken &cancelToken);
/// Adds all data from file to selected store in given quad key.
void add(const std::string &storeKey,
const std::string &path,
const utymap::QuadKey &quadKey,
const utymap::mapcss::StyleProvider &styleProvider,
const utymap::CancellationToken &cancelToken);
/// Adds all data from file to selected store in given boundging box.
void add(const std::string &storeKey,
const std::string &path,
const utymap::BoundingBox &bbox,
const utymap::LodRange &range,
const utymap::mapcss::StyleProvider &styleProvider,
const utymap::CancellationToken &cancelToken);
/// Searches for elements matches given query, bounding box and LOD range
void search(const std::string ¬Terms,
const std::string &andTerms,
const std::string &orTerms,
const utymap::BoundingBox &bbox,
const utymap::LodRange &range,
utymap::entities::ElementVisitor &visitor,
const utymap::CancellationToken &cancelToken);
/// Searches for elements inside quadkey.
void search(const QuadKey &quadKey,
const utymap::mapcss::StyleProvider &styleProvider,
utymap::entities::ElementVisitor &visitor,
const utymap::CancellationToken &cancelToken);
/// Checks whether there is data for given quadkey.
bool hasData(const QuadKey &quadKey) const;
private:
class GeoStoreImpl;
std::unique_ptr<GeoStoreImpl> pimpl_;
};
}
}
#endif // INDEX_GEOSTORE_HPP_DEFINED
| true |
b72031708099f03621870f3d275ec49e06806d33 | C++ | joaovitor73/ExeCplusplus | /vetorMatriz/exe 07.cpp | UTF-8 | 462 | 3.09375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int A[4] , B[4], R[4], l;
for (l = 0; l < 4; l++){
cout << "\nDigite o " << 1+l << "o. valor para o vetor A: ";
cin >> A[l];
cout << "\nDigite o " << 1+l << "o. valor para o vetor B: ";
cin >> B[l];
R[l] = A[l] * B[l];
}
cout << "\n\nRESULTADO";
for (l = 0; l < 4; l++){
cout <<" \n\n\n\n" << "(" << l << ")" << A[l] << " * " << B[l] << " = " << R[l];
}
}
| true |
3238ab14f5972d0fe41e0b97be7c3883b9b5ea3b | C++ | Xalanot/AcceleratorPractice | /Ex4/4.1/common_pinned_memory.h | UTF-8 | 2,419 | 2.734375 | 3 | [] | no_license | #pragma once
#include <thrust/random.h>
#include <thrust/device_vector.h>
#include <cuda.h>
#include <thrust/sort.h>
#include <thrust/memory.h>
#include <thrust/system/cuda/memory.h>
#define DEBUG 1
// Error handeling of cuda functions
#define checkCudaError(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
struct get_rand_number : public thrust::binary_function<void, void, size_t>
{
int seed;
size_t maxRange;
thrust::default_random_engine rng;
thrust::uniform_int_distribution<size_t> rng_index;
get_rand_number(int seed, size_t maxRange) {
seed = seed;
maxRange = maxRange;
rng = thrust::default_random_engine(seed);
rng_index = thrust::uniform_int_distribution<size_t>(0, maxRange);
}
__host__ __device__
size_t operator()(long x)
{
return rng_index(rng);
}
};
size_t bytesToMBytes(size_t bytes)
{
return bytes >> 20;
}
size_t bytesToGBytes(size_t bytes)
{
return bytes >> 30;
}
bool checkDevice(size_t memSize)
{
int device;
cudaGetDevice(&device);
cudaDeviceProp properties;
cudaGetDeviceProperties(&properties, device);
// check if the device supports unifiedAdressing and mapHostMemory
if(!properties.unifiedAddressing || !properties.canMapHostMemory)
{
if (DEBUG)
{
std::cout << "Device #" << device
<< " [" << properties.name << "] does not support memory mapping" << std::endl;
}
return false;
}
else
{
if (DEBUG)
{
std::cout << "Checking for " << bytesToGBytes(memSize) << " GB" << std::endl;
}
// check if there is enough memory size on the deive, we want to leave 5% left over
if (properties.totalGlobalMem * 0.95 < 2 * memSize)
{
if (DEBUG)
{
std::cout << "Device #" << device
<< " [" << properties.name << "] does not have enough memory" << std::endl;
std::cout << "There is " << bytesToMBytes(2 * memSize - properties.totalGlobalMem * 0.95) << "MB too few bytes of memory" << std::endl;
}
return false;
}
}
return true;
} | true |